diff --git a/.clang-tidy b/.clang-tidy index b23d7ccbff..33569be50a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -156,13 +156,7 @@ Checks: "-*, # readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names # readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable # --- - CheckOptions: - bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true - bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc - - misc-include-cleaner.IgnoreHeaders: ".*/(detail|impl)/.*;.*fwd\\.h(pp)?;time.h;stdlib.h;sqlite3.h;netinet/in\\.h;sys/resource\\.h;sys/sysinfo\\.h;linux/sysinfo\\.h;__chrono/.*;bits/.*;_abort\\.h;boost/uuid/uuid_hash.hpp;boost/beast/core/flat_buffer\\.hpp;boost/beast/http/field\\.hpp;boost/beast/http/dynamic_body\\.hpp;boost/beast/http/message\\.hpp;boost/beast/http/read\\.hpp;boost/beast/http/write\\.hpp;openssl/obj_mac\\.h" - readability-braces-around-statements.ShortStatementLines: 2 readability-identifier-naming.MacroDefinitionCase: UPPER_CASE readability-identifier-naming.ClassCase: CamelCase @@ -171,7 +165,7 @@ CheckOptions: readability-identifier-naming.EnumCase: CamelCase readability-identifier-naming.EnumConstantCase: CamelCase readability-identifier-naming.ScopedEnumConstantCase: CamelCase - readability-identifier-naming.GlobalConstantCase: CamelCase + readability-identifier-naming.GlobalConstantCase: UPPER_CASE readability-identifier-naming.GlobalConstantPrefix: "k" readability-identifier-naming.GlobalVariableCase: CamelCase readability-identifier-naming.GlobalVariablePrefix: "g" @@ -179,26 +173,27 @@ CheckOptions: readability-identifier-naming.ConstexprMethodCase: camelBack readability-identifier-naming.ClassMethodCase: camelBack readability-identifier-naming.ClassMemberCase: camelBack - readability-identifier-naming.ClassConstantCase: CamelCase + readability-identifier-naming.ClassConstantCase: UPPER_CASE readability-identifier-naming.ClassConstantPrefix: "k" - readability-identifier-naming.StaticConstantCase: CamelCase + readability-identifier-naming.StaticConstantCase: UPPER_CASE readability-identifier-naming.StaticConstantPrefix: "k" - readability-identifier-naming.StaticVariableCase: camelBack - readability-identifier-naming.ConstexprVariableCase: camelBack + readability-identifier-naming.StaticVariableCase: UPPER_CASE + readability-identifier-naming.StaticVariablePrefix: "k" + readability-identifier-naming.ConstexprVariableCase: UPPER_CASE + readability-identifier-naming.ConstexprVariablePrefix: "k" readability-identifier-naming.LocalConstantCase: camelBack readability-identifier-naming.LocalVariableCase: camelBack readability-identifier-naming.TemplateParameterCase: CamelCase readability-identifier-naming.ParameterCase: camelBack readability-identifier-naming.FunctionCase: camelBack readability-identifier-naming.MemberCase: camelBack - readability-identifier-naming.PrivateMemberCase: camelBack readability-identifier-naming.PrivateMemberSuffix: _ - readability-identifier-naming.ProtectedMemberCase: camelBack readability-identifier-naming.ProtectedMemberSuffix: _ - readability-identifier-naming.PublicMemberCase: camelBack readability-identifier-naming.PublicMemberSuffix: "" readability-identifier-naming.GlobalFunctionIgnoredRegexp: "^(to_string|hash_append|tuple_hash)$" - -HeaderFilterRegex: '^.*/(tests?|xrpl|xrpld)/.*\.(h|hpp|ipp)$' + bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true + bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc + misc-include-cleaner.IgnoreHeaders: ".*/(detail|impl)/.*;.*fwd\\.h(pp)?;time.h;stdlib.h;sqlite3.h;netinet/in\\.h;sys/resource\\.h;sys/sysinfo\\.h;linux/sysinfo\\.h;__chrono/.*;bits/.*;_abort\\.h;boost/uuid/uuid_hash.hpp;boost/beast/core/flat_buffer\\.hpp;boost/beast/http/field\\.hpp;boost/beast/http/dynamic_body\\.hpp;boost/beast/http/message\\.hpp;boost/beast/http/read\\.hpp;boost/beast/http/write\\.hpp;openssl/obj_mac\\.h" +HeaderFilterRegex: '^.*/(test|xrpl|xrpld)/.*\.(h|hpp|ipp)$' ExcludeHeaderFilterRegex: '^.*/protocol_autogen/.*\.(h|hpp)$' WarningsAsErrors: "*" diff --git a/.github/actions/build-deps/action.yml b/.github/actions/build-deps/action.yml index 0891d56dfa..9d52be1998 100644 --- a/.github/actions/build-deps/action.yml +++ b/.github/actions/build-deps/action.yml @@ -37,12 +37,12 @@ runs: run: | echo 'Installing dependencies.' conan install \ - --profile ci \ - --build="${BUILD_OPTION}" \ - --options:host='&:tests=True' \ - --options:host='&:xrpld=True' \ - --settings:all build_type="${BUILD_TYPE}" \ - --conf:all tools.build:jobs=${BUILD_NPROC} \ - --conf:all tools.build:verbosity="${LOG_VERBOSITY}" \ - --conf:all tools.compilation:verbosity="${LOG_VERBOSITY}" \ - . + --profile ci \ + --build="${BUILD_OPTION}" \ + --options:host='&:tests=True' \ + --options:host='&:xrpld=True' \ + --settings:all build_type="${BUILD_TYPE}" \ + --conf:all tools.build:jobs=${BUILD_NPROC} \ + --conf:all tools.build:verbosity="${LOG_VERBOSITY}" \ + --conf:all tools.compilation:verbosity="${LOG_VERBOSITY}" \ + . diff --git a/.github/actions/generate-version/action.yml b/.github/actions/generate-version/action.yml index 50b3166596..8edb7920c6 100644 --- a/.github/actions/generate-version/action.yml +++ b/.github/actions/generate-version/action.yml @@ -15,7 +15,7 @@ runs: shell: bash env: VERSION: ${{ github.ref_name }} - run: echo "VERSION=${VERSION}" >>"${GITHUB_ENV}" + 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. @@ -28,17 +28,17 @@ runs: 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 + 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}" + echo "VERSION=${VERSION}" >> "${GITHUB_ENV}" - name: Output version id: version shell: bash - run: echo "version=${VERSION}" >>"${GITHUB_OUTPUT}" + run: echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" diff --git a/.github/scripts/format-inline-bash.py b/.github/scripts/format-inline-bash.py deleted file mode 100755 index 423c78109c..0000000000 --- a/.github/scripts/format-inline-bash.py +++ /dev/null @@ -1,403 +0,0 @@ -#!/usr/bin/env python3 - -""" -Format embedded shell snippets using the shfmt hook configured in -.pre-commit-config.yaml. - -Two shapes are recognised: - -* YAML workflow/action files: literal block-scalar runs (`run: |`) and - single-line runs (`run: some command`). A single-line run is upgraded to - a `run: |` block scalar if shfmt's output spans multiple lines. - -* Markdown files: ``` ```bash ``` fenced code blocks. - -Any block that shfmt cannot parse is skipped with a warning on stderr, so -the file is left untouched and surrounding blocks still get formatted. - -For each occurrence the body is dedented, written to a temp .sh file, -formatted via `pre-commit run shfmt --files ` (falling back to -`prek`), then re-indented and written back in place. - -When invoked without arguments, every .yml/.yaml under .github/ plus every -.md file in the repo is scanned. When invoked with file arguments (the -pre-commit case), only those files are processed. -""" - -from __future__ import annotations - -import re -import shutil -import subprocess -import sys -import tempfile -from dataclasses import dataclass -from pathlib import Path -from typing import Union - -REPO = Path(__file__).resolve().parents[2] - -_HOOK_RUNNER = next((cmd for cmd in ("pre-commit", "prek") if shutil.which(cmd)), None) -if _HOOK_RUNNER is None: - sys.exit("error: neither `pre-commit` nor `prek` found on PATH") - -RUN_BLOCK_RE = re.compile(r"^(?P[ \t]*(?:- )?)run:[ \t]*\|[+-]?[ \t]*$") -RUN_INLINE_RE = re.compile( - r"^(?P[ \t]*(?:- )?)run:[ \t]+" r"(?P(?!\|[+-]?[ \t]*$)\S.*?)[ \t]*$" -) -MD_BASH_OPEN_RE = re.compile(r"^(?P[ ]{0,3})`{3}bash[ \t]*$") -MD_FENCE_CLOSE_RE = re.compile(r"^[ ]{0,3}`{3,}[ \t]*$") - - -@dataclass(frozen=True) -class BlockRun: - """A `run: |` block scalar; `body_start:body_end` slices into `lines`.""" - - body_start: int - body_end: int - body_indent: int - - -@dataclass(frozen=True) -class InlineRun: - """A single-line `run: value` at `line_idx`.""" - - line_idx: int - prefix: str - value: str - - -@dataclass(frozen=True) -class MdBashBlock: - """A markdown ``` ```bash ``` fenced code block. - - `body_start:body_end` slices into the file's lines; `open_line_idx` - points at the opening fence line. - """ - - open_line_idx: int - body_start: int - body_end: int - body_indent: int - - -RunItem = Union[BlockRun, InlineRun] - - -def _scan_block_body( - lines: list[str], body_start: int, run_col: int -) -> tuple[int | None, int]: - """Locate the body of a `run: |` block scalar starting at `body_start`. - - Returns `(body_indent, scan_end)`. `scan_end` is the line index where the - outer scanner should resume. `body_indent` is `None` when no body is - present (the scalar is empty, or the next non-blank line has indent - `<= run_col`). - """ - body_indent: int | None = None - scan_end = len(lines) - for idx in range(body_start, len(lines)): - line = lines[idx] - if line.strip() == "": - continue - indent = len(line) - len(line.lstrip(" ")) - if body_indent is None: - if indent > run_col: - body_indent = indent - else: - scan_end = idx - break - elif indent < body_indent: - scan_end = idx - break - if body_indent is not None: - while scan_end > body_start and lines[scan_end - 1].strip() == "": - scan_end -= 1 - if scan_end <= body_start: - body_indent = None - return body_indent, scan_end - - -def find_run_blocks(lines: list[str]) -> list[RunItem]: - """Return run items in document order.""" - items: list[RunItem] = [] - line_idx = 0 - while line_idx < len(lines): - line = lines[line_idx] - if block_match := RUN_BLOCK_RE.match(line): - run_col = len(block_match.group("prefix")) - body_start = line_idx + 1 - body_indent, scan_end = _scan_block_body(lines, body_start, run_col) - if body_indent is not None: - items.append( - BlockRun( - body_start=body_start, - body_end=scan_end, - body_indent=body_indent, - ) - ) - line_idx = scan_end - continue - if inline_match := RUN_INLINE_RE.match(line): - items.append( - InlineRun( - line_idx=line_idx, - prefix=inline_match.group("prefix"), - value=inline_match.group("value"), - ) - ) - line_idx += 1 - return items - - -def find_md_bash_blocks(lines: list[str]) -> list[MdBashBlock]: - """Return ``` ```bash ``` fenced code blocks in document order.""" - blocks: list[MdBashBlock] = [] - line_idx = 0 - while line_idx < len(lines): - open_match = MD_BASH_OPEN_RE.match(lines[line_idx]) - if not open_match: - line_idx += 1 - continue - body_start = line_idx + 1 - close_idx = next( - ( - j - for j in range(body_start, len(lines)) - if MD_FENCE_CLOSE_RE.match(lines[j]) - ), - None, - ) - if close_idx is None: - line_idx = body_start - continue - body = lines[body_start:close_idx] - non_blank = [b for b in body if b.strip()] - body_indent = ( - min(len(b) - len(b.lstrip(" ")) for b in non_blank) - if non_blank - else len(open_match.group("indent")) - ) - blocks.append( - MdBashBlock( - open_line_idx=line_idx, - body_start=body_start, - body_end=close_idx, - body_indent=body_indent, - ) - ) - line_idx = close_idx + 1 - return blocks - - -def dedent(lines: list[str], n: int) -> list[str]: - pad = " " * n - return [ - ( - "" - if line.strip() == "" - else (line[n:] if line.startswith(pad) else line.lstrip(" ")) - ) - for line in lines - ] - - -def reindent(lines: list[str], n: int) -> list[str]: - pad = " " * n - return [pad + line if line else "" for line in lines] - - -_SHFMT_ERR_RE = re.compile(r"\.sh:\d+:\d+:\s") -_GHA_EXPR_RE = re.compile(r"\$\{\{.*?\}\}", re.DOTALL) -_GHA_PLACEHOLDER_RE = re.compile(r"__GHA_EXPR_(\d+)__") - - -def _encode_gha_exprs(text: str) -> tuple[str, list[str]]: - """Replace `${{ ... }}` expressions with bash-safe placeholder identifiers.""" - exprs: list[str] = [] - - def repl(match: re.Match[str]) -> str: - exprs.append(match.group(0)) - return f"__GHA_EXPR_{len(exprs) - 1}__" - - return _GHA_EXPR_RE.sub(repl, text), exprs - - -def _decode_gha_exprs(text: str, exprs: list[str]) -> str: - """Restore `${{ ... }}` expressions from placeholder identifiers.""" - return _GHA_PLACEHOLDER_RE.sub(lambda m: exprs[int(m.group(1))], text) - - -def shfmt_via_hook(tmp_path: Path) -> tuple[bool, str]: - # `${{ ... }}` is not valid shell, so swap it for a placeholder identifier - # that shfmt can parse, then restore it after formatting. - encoded, exprs = _encode_gha_exprs(tmp_path.read_text()) - if exprs: - tmp_path.write_text(encoded) - res = subprocess.run( - [_HOOK_RUNNER, "run", "shfmt", "--files", str(tmp_path)], - cwd=REPO, - capture_output=True, - text=True, - ) - output = res.stdout + res.stderr - # shfmt emits parse errors as "::: ". - parse_err = bool(_SHFMT_ERR_RE.search(output)) - # A non-zero exit that is neither a parse error nor pre-commit's "I had - # to modify files" signal means the hook itself failed to run (missing - # binary, install failure, bad config, ...). Surface that loudly rather - # than silently treating it as a no-op. - if ( - res.returncode != 0 - and not parse_err - and "files were modified by this hook" not in output - ): - sys.exit( - f"error: `{_HOOK_RUNNER} run shfmt` failed with exit {res.returncode}:\n{output}" - ) - if exprs and not parse_err: - tmp_path.write_text(_decode_gha_exprs(tmp_path.read_text(), exprs)) - return not parse_err, output - - -def _skip(path: Path, where: int, kind: str, output: str) -> None: - print( - f" shfmt could not parse {kind} at {path}:{where + 1} — skipped", - file=sys.stderr, - ) - print(f" {output.strip()}", file=sys.stderr) - - -def process_yaml_file(path: Path, tmp_path: Path) -> int: - text = path.read_text() - had_nl = text.endswith("\n") - lines = text.split("\n") - if had_nl: - lines = lines[:-1] - items = find_run_blocks(lines) - if not items: - return 0 - changed = 0 - # Process in reverse so earlier indices remain valid as we splice. - for item in reversed(items): - if isinstance(item, BlockRun): - body = lines[item.body_start : item.body_end] - tmp_path.write_text("\n".join(dedent(body, item.body_indent)) + "\n") - ok, output = shfmt_via_hook(tmp_path) - if not ok: - _skip(path, item.body_start, "block", output) - continue - formatted = tmp_path.read_text().rstrip("\n") - new_body = reindent(formatted.split("\n"), item.body_indent) - if new_body != body: - lines[item.body_start : item.body_end] = new_body - changed += 1 - else: - tmp_path.write_text(item.value + "\n") - ok, output = shfmt_via_hook(tmp_path) - if not ok: - _skip(path, item.line_idx, "inline run", output) - continue - formatted = tmp_path.read_text().rstrip("\n") - if formatted == item.value: - continue - formatted_lines = formatted.split("\n") - if len(formatted_lines) == 1: - lines[item.line_idx] = f"{item.prefix}run: {formatted}" - else: - body_indent = len(item.prefix) + 2 - lines[item.line_idx : item.line_idx + 1] = [ - f"{item.prefix}run: |", - *reindent(formatted_lines, body_indent), - ] - changed += 1 - new_text = "\n".join(lines) + ("\n" if had_nl else "") - if new_text != text: - path.write_text(new_text) - return changed - - -def process_md_file(path: Path, tmp_path: Path) -> int: - text = path.read_text() - had_nl = text.endswith("\n") - lines = text.split("\n") - if had_nl: - lines = lines[:-1] - blocks = find_md_bash_blocks(lines) - if not blocks: - return 0 - changed = 0 - for block in reversed(blocks): - body = lines[block.body_start : block.body_end] - tmp_path.write_text("\n".join(dedent(body, block.body_indent)) + "\n") - ok, output = shfmt_via_hook(tmp_path) - if not ok: - _skip(path, block.open_line_idx, "```bash block", output) - continue - formatted = tmp_path.read_text().rstrip("\n") - formatted_lines = formatted.split("\n") if formatted else [] - new_body = reindent(formatted_lines, block.body_indent) - if new_body != body: - lines[block.body_start : block.body_end] = new_body - changed += 1 - new_text = "\n".join(lines) + ("\n" if had_nl else "") - if new_text != text: - path.write_text(new_text) - return changed - - -def process_file(path: Path, tmp_path: Path) -> int: - if path.suffix in (".yml", ".yaml"): - return process_yaml_file(path, tmp_path) - if path.suffix == ".md": - return process_md_file(path, tmp_path) - return 0 - - -def gather_files(argv: list[str]) -> list[Path]: - """Return YAML workflow/action files and markdown files that we should - process — either the paths in `argv` or, when `argv` is empty, every - such file in the repo (skipping `external/`).""" - if argv: - candidates: list[Path] = [ - (REPO / a).resolve() if not Path(a).is_absolute() else Path(a) for a in argv - ] - else: - gh = REPO / ".github" - candidates = [ - *gh.rglob("*.yml"), - *gh.rglob("*.yaml"), - *( - p - for p in REPO.rglob("*.md") - if "external" not in p.relative_to(REPO).parts - ), - ] - return sorted( - p - for p in candidates - if p.exists() - and ( - (p.suffix in (".yml", ".yaml") and ".github" in p.parts) - or p.suffix == ".md" - ) - ) - - -def main(argv: list[str]) -> int: - files = gather_files(argv) - if not files: - return 0 - with tempfile.TemporaryDirectory(prefix="format-inline-bash-") as tmpdir: - tmp_path = Path(tmpdir) / "shfmt.sh" - total = 0 - for f in files: - n = process_file(f, tmp_path) - if n: - print(f"{f.relative_to(REPO)}: reformatted {n} block(s)") - total += n - return 1 if total else 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) diff --git a/.github/scripts/levelization/generate.py b/.github/scripts/levelization/generate.py old mode 100755 new mode 100644 diff --git a/.github/scripts/rename/binary.sh b/.github/scripts/rename/binary.sh index 89d884538c..cdce6db4ba 100755 --- a/.github/scripts/rename/binary.sh +++ b/.github/scripts/rename/binary.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi diff --git a/.github/scripts/rename/cmake.sh b/.github/scripts/rename/cmake.sh index 28bf777fed..9c91e8f277 100755 --- a/.github/scripts/rename/cmake.sh +++ b/.github/scripts/rename/cmake.sh @@ -8,12 +8,12 @@ set -e SED_COMMAND=sed HEAD_COMMAND=head if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi SED_COMMAND=gsed - if ! command -v ghead &>/dev/null; then + if ! command -v ghead &> /dev/null; then echo "Error: ghead is not installed. Please install it using 'brew install coreutils'." exit 1 fi @@ -74,10 +74,10 @@ if grep -q '"xrpld"' cmake/XrplCore.cmake; then # The script has been rerun, so just restore the name of the binary. ${SED_COMMAND} -i 's/"xrpld"/"rippled"/' cmake/XrplCore.cmake elif ! grep -q '"rippled"' cmake/XrplCore.cmake; then - ${HEAD_COMMAND} -n -1 cmake/XrplCore.cmake >cmake.tmp - echo ' # For the time being, we will keep the name of the binary as it was.' >>cmake.tmp - echo ' set_target_properties(xrpld PROPERTIES OUTPUT_NAME "rippled")' >>cmake.tmp - tail -1 cmake/XrplCore.cmake >>cmake.tmp + ${HEAD_COMMAND} -n -1 cmake/XrplCore.cmake > cmake.tmp + echo ' # For the time being, we will keep the name of the binary as it was.' >> cmake.tmp + echo ' set_target_properties(xrpld PROPERTIES OUTPUT_NAME "rippled")' >> cmake.tmp + tail -1 cmake/XrplCore.cmake >> cmake.tmp mv cmake.tmp cmake/XrplCore.cmake fi diff --git a/.github/scripts/rename/config.sh b/.github/scripts/rename/config.sh index ac9debb154..a27d0823a9 100755 --- a/.github/scripts/rename/config.sh +++ b/.github/scripts/rename/config.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi @@ -62,7 +62,7 @@ ${SED_COMMAND} -i 's@ripple/@xrpld/@g' src/test/core/Config_test.cpp ${SED_COMMAND} -i 's/Rippled/File/g' src/test/core/Config_test.cpp # Restore the old config file name in the code that maintains support for now. -${SED_COMMAND} -i 's/kConfigLegacyName = "xrpld.cfg"/kConfigLegacyName = "rippled.cfg"/g' src/xrpld/core/detail/Config.cpp +${SED_COMMAND} -i 's/kCONFIG_LEGACY_NAME = "xrpld.cfg"/kCONFIG_LEGACY_NAME = "rippled.cfg"/g' src/xrpld/core/detail/Config.cpp # Restore an URL. ${SED_COMMAND} -i 's/connect-your-xrpld-to-the-xrp-test-net.html/connect-your-rippled-to-the-xrp-test-net.html/g' cfg/xrpld-example.cfg diff --git a/.github/scripts/rename/copyright.sh b/.github/scripts/rename/copyright.sh index 09bc5a8926..9ebdad1e89 100755 --- a/.github/scripts/rename/copyright.sh +++ b/.github/scripts/rename/copyright.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi @@ -62,37 +62,37 @@ done # restoring the verbiage that is already present in LICENSE.md. Ensure that if # the script is run multiple times, duplicate notices are not added. if ! grep -q 'Raw Material Software' include/xrpl/beast/core/CurrentThreadName.h; then - echo -e "// Portions of this file are from JUCE (http://www.juce.com).\n// Copyright (c) 2013 - Raw Material Software Ltd.\n// Please visit http://www.juce.com\n\n$(cat include/xrpl/beast/core/CurrentThreadName.h)" >include/xrpl/beast/core/CurrentThreadName.h + echo -e "// Portions of this file are from JUCE (http://www.juce.com).\n// Copyright (c) 2013 - Raw Material Software Ltd.\n// Please visit http://www.juce.com\n\n$(cat include/xrpl/beast/core/CurrentThreadName.h)" > include/xrpl/beast/core/CurrentThreadName.h fi if ! grep -q 'Dev Null' src/test/app/NetworkID_test.cpp; then - echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/app/NetworkID_test.cpp)" >src/test/app/NetworkID_test.cpp + echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/app/NetworkID_test.cpp)" > src/test/app/NetworkID_test.cpp fi if ! grep -q 'Dev Null' src/test/app/tx/apply_test.cpp; then - echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/app/tx/apply_test.cpp)" >src/test/app/tx/apply_test.cpp + echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/app/tx/apply_test.cpp)" > src/test/app/tx/apply_test.cpp fi if ! grep -q 'Dev Null' src/test/rpc/ManifestRPC_test.cpp; then - echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/rpc/ManifestRPC_test.cpp)" >src/test/rpc/ManifestRPC_test.cpp + echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/rpc/ManifestRPC_test.cpp)" > src/test/rpc/ManifestRPC_test.cpp fi if ! grep -q 'Dev Null' src/test/rpc/ValidatorInfo_test.cpp; then - echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/rpc/ValidatorInfo_test.cpp)" >src/test/rpc/ValidatorInfo_test.cpp + echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/rpc/ValidatorInfo_test.cpp)" > src/test/rpc/ValidatorInfo_test.cpp fi if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/server_info/Manifest.cpp; then - echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/server_info/Manifest.cpp)" >src/xrpld/rpc/handlers/server_info/Manifest.cpp + echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/server_info/Manifest.cpp)" > src/xrpld/rpc/handlers/server_info/Manifest.cpp fi if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp; then - echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp)" >src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp + echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp)" > src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp fi if ! grep -q 'Bougalis' include/xrpl/basics/SlabAllocator.h; then - echo -e "// Copyright (c) 2022, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/SlabAllocator.h)" >include/xrpl/basics/SlabAllocator.h # cspell: ignore Nikolaos Bougalis nikb + echo -e "// Copyright (c) 2022, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/SlabAllocator.h)" > include/xrpl/basics/SlabAllocator.h # cspell: ignore Nikolaos Bougalis nikb fi if ! grep -q 'Bougalis' include/xrpl/basics/spinlock.h; then - echo -e "// Copyright (c) 2022, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/spinlock.h)" >include/xrpl/basics/spinlock.h # cspell: ignore Nikolaos Bougalis nikb + echo -e "// Copyright (c) 2022, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/spinlock.h)" > include/xrpl/basics/spinlock.h # cspell: ignore Nikolaos Bougalis nikb fi if ! grep -q 'Bougalis' include/xrpl/basics/tagged_integer.h; then - echo -e "// Copyright (c) 2014, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/tagged_integer.h)" >include/xrpl/basics/tagged_integer.h # cspell: ignore Nikolaos Bougalis nikb + echo -e "// Copyright (c) 2014, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/tagged_integer.h)" > include/xrpl/basics/tagged_integer.h # cspell: ignore Nikolaos Bougalis nikb fi if ! grep -q 'Ritchford' include/xrpl/beast/utility/Zero.h; then - echo -e "// Copyright (c) 2014, Tom Ritchford \n\n$(cat include/xrpl/beast/utility/Zero.h)" >include/xrpl/beast/utility/Zero.h # cspell: ignore Ritchford + echo -e "// Copyright (c) 2014, Tom Ritchford \n\n$(cat include/xrpl/beast/utility/Zero.h)" > include/xrpl/beast/utility/Zero.h # cspell: ignore Ritchford fi # Restore newlines and tabs in string literals in the affected file. diff --git a/.github/scripts/rename/definitions.sh b/.github/scripts/rename/definitions.sh index daa5d01e80..5e004afe39 100755 --- a/.github/scripts/rename/definitions.sh +++ b/.github/scripts/rename/definitions.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi diff --git a/.github/scripts/rename/docs.sh b/.github/scripts/rename/docs.sh index 9f080b06e5..23ff76bc05 100755 --- a/.github/scripts/rename/docs.sh +++ b/.github/scripts/rename/docs.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi @@ -90,7 +90,7 @@ ${SED_COMMAND} -i 's/www.ripple.com/www.xrpl.org/g' src/test/protocol/Seed_test. # Restore specific changes. ${SED_COMMAND} -i 's@b5efcc/src/xrpld@b5efcc/src/ripple@' include/xrpl/protocol/README.md ${SED_COMMAND} -i 's/dbPrefix_ = "xrpldb"/dbPrefix_ = "rippledb"/' src/xrpld/app/misc/SHAMapStoreImp.h # cspell: disable-line -${SED_COMMAND} -i 's/kConfigLegacyName = "xrpld.cfg"/kConfigLegacyName = "rippled.cfg"/' src/xrpld/core/detail/Config.cpp +${SED_COMMAND} -i 's/kCONFIG_LEGACY_NAME = "xrpld.cfg"/kCONFIG_LEGACY_NAME = "rippled.cfg"/' src/xrpld/core/detail/Config.cpp popd echo "Renaming complete." diff --git a/.github/scripts/rename/namespace.sh b/.github/scripts/rename/namespace.sh index bb186bc8bc..aba193b0cf 100755 --- a/.github/scripts/rename/namespace.sh +++ b/.github/scripts/rename/namespace.sh @@ -6,7 +6,7 @@ set -e # On MacOS, ensure that GNU sed is installed and available as `gsed`. SED_COMMAND=sed if [[ "${OSTYPE}" == 'darwin'* ]]; then - if ! command -v gsed &>/dev/null; then + if ! command -v gsed &> /dev/null; then echo "Error: gsed is not installed. Please install it using 'brew install gnu-sed'." exit 1 fi diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 6eccfcc6be..dec41a2610 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -32,32 +32,7 @@ We will further set additional CMake arguments as follows: """ -def build_config_name(os_entry: dict[str, str], platform: str, build_type: str) -> str: - parts = [os_entry["distro_name"]] - for key in ("distro_version", "compiler_name", "compiler_version"): - if value := os_entry[key]: - parts.append(value) - parts.append("arm64" if "arm64" in platform else "amd64") - parts.append(build_type.lower()) - return "-".join(parts) - - -def generate_packaging_matrix(config: Config) -> list[dict]: - """Emit one entry per os entry with `package: true`. Architecture is - hardcoded to linux/amd64 here (and the runner is hardcoded at the - workflow level) until arm64 packaging is ready. - """ - return [ - { - "artifact_name": f"xrpld-{build_config_name(os, 'linux/amd64', 'Release')}", - "os": os, - } - for os in config.os - if os.get("package", False) - ] - - -def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: +def generate_strategy_matrix(all: bool, config: Config) -> list: configurations = [] for architecture, os, build_type, cmake_args in itertools.product( config.architecture, config.os, config.build_type, config.cmake_args @@ -97,7 +72,7 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: skip = False if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" - and build_type == "Release" + and build_type == "Debug" and architecture["platform"] == "linux/amd64" ): skip = False @@ -115,9 +90,8 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: ): cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=1000 {cmake_args}" skip = False - elif os["distro_version"] == "trixie": if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-22" + f"{os['compiler_name']}-{os['compiler_version']}" == "clang-20" and build_type == "Debug" and architecture["platform"] == "linux/amd64" ): @@ -126,15 +100,14 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: continue # RHEL: - # - 9 using GCC 12: Debug and Release on linux/amd64 - # (Release is required for RPM packaging). + # - 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 in ["Debug", "Release"] + and build_type == "Debug" and architecture["platform"] == "linux/amd64" ): skip = False @@ -149,8 +122,7 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: continue # Ubuntu: - # - Jammy using GCC 12: Debug on linux/arm64, Release on - # linux/amd64 (Release is required for DEB packaging). + # - 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. @@ -163,12 +135,6 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: and architecture["platform"] == "linux/arm64" ): skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - skip = False elif os["distro_version"] == "noble": if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-14" @@ -222,9 +188,8 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: # We skip all clang 20+ on arm64 due to Boost build error. if ( - os["compiler_name"] == "clang" - and os["compiler_version"].isdigit() - and int(os["compiler_version"]) >= 20 + f"{os['compiler_name']}-{os['compiler_version']}" + in ["clang-20", "clang-21"] and architecture["platform"] == "linux/arm64" ): continue @@ -251,7 +216,17 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: # Generate a unique name for the configuration, e.g. macos-arm64-debug # or debian-bookworm-gcc-12-amd64-release. - config_name = build_config_name(os, architecture["platform"], build_type) + config_name = os["distro_name"] + if (n := os["distro_version"]) != "": + config_name += f"-{n}" + if (n := os["compiler_name"]) != "": + config_name += f"-{n}" + if (n := os["compiler_version"]) != "": + config_name += f"-{n}" + config_name += ( + f"-{architecture['platform'][architecture['platform'].find('/')+1:]}" + ) + config_name += f"-{build_type.lower()}" if "-Dcoverage=ON" in cmake_args: config_name += "-coverage" if "-Dunity=ON" in cmake_args: @@ -263,14 +238,13 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: # Add Address and UB sanitizers as separate configurations for specific # bookworm distros. Thread sanitizer is currently disabled (see below). # GCC-Asan xrpld-embedded tests are failing because of https://github.com/google/sanitizers/issues/856 - if ( - os["distro_version"] == "bookworm" - and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" - ) or ( - os["distro_version"] == "trixie" - and f"{os['compiler_name']}-{os['compiler_version']}" == "clang-22" - ): - # Add ASAN and UBSAN configurations for both gcc-15 and clang-22 + if os[ + "distro_version" + ] == "bookworm" and f"{os['compiler_name']}-{os['compiler_version']}" in [ + "gcc-15", + "clang-20", + ]: + # Add ASAN configuration. configurations.append( { "config_name": config_name + "-asan", @@ -283,6 +257,7 @@ def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: "sanitizers": "address", } ) + # Add UBSAN configuration. configurations.append( { "config_name": config_name + "-ubsan", @@ -355,19 +330,10 @@ if __name__ == "__main__": required=False, type=Path, ) - parser.add_argument( - "-p", - "--packaging", - help="Emit the packaging matrix (derived from the 'package' field on os entries) instead of the build/test matrix.", - action="store_true", - ) args = parser.parse_args() matrix = [] - if args.packaging: - config_path = args.config if args.config else THIS_DIR / "linux.json" - matrix += generate_packaging_matrix(read_config(config_path)) - elif args.config is None or args.config == "": + if args.config is None or args.config == "": matrix += generate_strategy_matrix( args.all, read_config(THIS_DIR / "linux.json") ) diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 4f090a81a3..4943579be8 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -15,205 +15,196 @@ "distro_version": "bookworm", "compiler_name": "gcc", "compiler_version": "12", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "gcc", "compiler_version": "13", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "gcc", "compiler_version": "15", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "clang", "compiler_version": "16", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "clang", "compiler_version": "17", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "clang", "compiler_version": "18", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "clang", "compiler_version": "19", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "bookworm", "compiler_name": "clang", "compiler_version": "20", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "trixie", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "trixie", "compiler_name": "gcc", "compiler_version": "15", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "trixie", "compiler_name": "clang", "compiler_version": "20", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "debian", "distro_version": "trixie", "compiler_name": "clang", "compiler_version": "21", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "clang", - "compiler_version": "22", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "8", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "8", "compiler_name": "clang", "compiler_version": "any", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "9", "compiler_name": "gcc", "compiler_version": "12", - "image_sha": "4c086b9", - "package": true + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "9", "compiler_name": "gcc", "compiler_version": "13", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "9", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "9", "compiler_name": "clang", "compiler_version": "any", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "10", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "rhel", "distro_version": "10", "compiler_name": "clang", "compiler_version": "any", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "jammy", "compiler_name": "gcc", "compiler_version": "12", - "image_sha": "4c086b9", - "package": true + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "gcc", "compiler_version": "13", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "gcc", "compiler_version": "14", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "clang", "compiler_version": "16", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "clang", "compiler_version": "17", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "clang", "compiler_version": "18", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" }, { "distro_name": "ubuntu", "distro_version": "noble", "compiler_name": "clang", "compiler_version": "19", - "image_sha": "4c086b9" + "image_sha": "ab4d1f0" } ], "build_type": ["Debug", "Release"], diff --git a/.github/workflows/build-nix-image.yml b/.github/workflows/build-nix-image.yml deleted file mode 100644 index bae4cfd437..0000000000 --- a/.github/workflows/build-nix-image.yml +++ /dev/null @@ -1,109 +0,0 @@ -name: Build Nix Docker image - -on: - push: - branches: - - develop - paths: - - ".github/workflows/build-nix-image.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - "docker/**" - - "flake.nix" - - "flake.lock" - - "nix/**" - pull_request: - paths: - - ".github/workflows/build-nix-image.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - "docker/**" - - "flake.nix" - - "flake.lock" - - "nix/**" - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -defaults: - run: - shell: bash - -jobs: - build: - name: Build ${{ matrix.distro.name }} (${{ matrix.target.platform }}) - permissions: - contents: read - packages: write - strategy: - fail-fast: false - matrix: - # The base images are the oldest supported version of each distro - # that we want to build images for. - distro: - - name: nixos - base_image: nixos/nix:latest - - name: ubuntu - base_image: ubuntu:20.04 - - name: rhel - base_image: registry.access.redhat.com/ubi9/ubi:latest - - name: debian - base_image: debian:bookworm - target: - - platform: linux/amd64 - runner: ubuntu-latest - - platform: linux/arm64 - runner: ubuntu-24.04-arm - uses: ./.github/workflows/reusable-build-docker-image.yml - with: - image_name: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro.name }} - dockerfile: docker/nix.Dockerfile - base_image: ${{ matrix.distro.base_image }} - platform: ${{ matrix.target.platform }} - runner: ${{ matrix.target.runner }} - push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - - merge: - name: Merge ${{ matrix.distro }} manifest - needs: build - if: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - strategy: - fail-fast: false - matrix: - distro: [nixos, ubuntu, rhel, debian] - env: - IMAGE_NAME: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro }} - - steps: - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - - - name: Docker metadata - id: meta - uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 - with: - images: ${{ env.IMAGE_NAME }} - tags: | - type=sha,prefix=sha-,format=short - type=raw,value=latest - - - name: Login to GitHub Container Registry - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Create multi-arch manifests - run: | - for tag in $(jq -cr '.tags[]' <<<"$DOCKER_METADATA_OUTPUT_JSON"); do - docker buildx imagetools create -t "$tag" "${tag}-amd64" "${tag}-arm64" - done - - - name: Inspect image - run: | - docker buildx imagetools inspect "${IMAGE_NAME}:${{ steps.meta.outputs.version }}" diff --git a/.github/workflows/check-pr-description.yml b/.github/workflows/check-pr-description.yml index ff28220171..f6eee50291 100644 --- a/.github/workflows/check-pr-description.yml +++ b/.github/workflows/check-pr-description.yml @@ -5,17 +5,8 @@ on: types: - checks_requested pull_request: - types: - - opened - - edited - - reopened - - synchronize - - ready_for_review - branches: - - develop - - "release-*" - - "release/*" - - "staging/*" + types: [opened, edited, reopened, synchronize, ready_for_review] + branches: [develop] jobs: check_description: @@ -29,11 +20,11 @@ jobs: env: PR_BODY: ${{ github.event.pull_request.body }} if: ${{ github.event_name == 'pull_request' }} - run: printenv PR_BODY >pr_body.md + run: printenv PR_BODY > pr_body.md - name: Check PR description differs from template if: ${{ github.event_name == 'pull_request' }} - run: | - python .github/scripts/check-pr-description.py \ - --template-file .github/pull_request_template.md \ - --pr-body-file pr_body.md + run: > + python .github/scripts/check-pr-description.py + --template-file .github/pull_request_template.md + --pr-body-file pr_body.md diff --git a/.github/workflows/check-pr-title.yml b/.github/workflows/check-pr-title.yml index 4b5f679df1..6d7bdefa08 100644 --- a/.github/workflows/check-pr-title.yml +++ b/.github/workflows/check-pr-title.yml @@ -5,19 +5,10 @@ on: types: - checks_requested pull_request: - types: - - opened - - edited - - reopened - - synchronize - - ready_for_review - branches: - - develop - - "release-*" - - "release/*" - - "staging/*" + types: [opened, edited, reopened, synchronize, ready_for_review] + branches: [develop] jobs: check_title: if: ${{ github.event.pull_request.draft != true }} - uses: XRPLF/actions/.github/workflows/check-pr-title.yml@cba1f0891650baf1a9c88624dc2d72573be2eb81 + uses: XRPLF/actions/.github/workflows/check-pr-title.yml@a5d8dd35be543365e90a11358447130c8763871d diff --git a/.github/workflows/conflicting-pr.yml b/.github/workflows/conflicting-pr.yml index 772d46fd7d..6e667632a0 100644 --- a/.github/workflows/conflicting-pr.yml +++ b/.github/workflows/conflicting-pr.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check if PRs are dirty - uses: eps1lon/actions-label-merge-conflict@0273be72a0bbd58fcd71d0d6c02c209b50d1e5e1 # v3.1.0 + uses: eps1lon/actions-label-merge-conflict@1df065ebe6e3310545d4f4c4e862e43bdca146f0 # v3.0.3 with: dirtyLabel: "PR: has conflicts" repoToken: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index db3c8667e5..d95f3a6c00 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -64,13 +64,11 @@ jobs: .github/workflows/reusable-build-test-config.yml .github/workflows/reusable-build-test.yml .github/workflows/reusable-clang-tidy.yml - .github/workflows/reusable-package.yml .github/workflows/reusable-strategy-matrix.yml .github/workflows/reusable-test.yml .github/workflows/reusable-upload-recipe.yml .clang-tidy .codecov.yml - cfg/** cmake/** conan/** external/** @@ -80,10 +78,6 @@ jobs: CMakeLists.txt conanfile.py conan.lock - LICENSE.md - package/** - README.md - - name: Check whether to run # This step determines whether the rest of the workflow should # run. The rest of the workflow will run if this job runs AND at @@ -98,7 +92,7 @@ jobs: READY: ${{ contains(github.event.pull_request.labels.*.name, 'Ready to merge') }} MERGE: ${{ github.event_name == 'merge_group' }} run: | - echo "go=${{ (env.DRAFT != 'true' && env.READY == 'true') || env.FILES == 'true' || env.MERGE == 'true' }}" >>"${GITHUB_OUTPUT}" + echo "go=${{ (env.DRAFT != 'true' && env.READY == 'true') || env.FILES == 'true' || env.MERGE == 'true' }}" >> "${GITHUB_OUTPUT}" cat "${GITHUB_OUTPUT}" outputs: go: ${{ steps.go.outputs.go == 'true' }} @@ -140,11 +134,6 @@ jobs: secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - package: - needs: [should-run, build-test] - if: ${{ needs.should-run.outputs.go == 'true' }} - uses: ./.github/workflows/reusable-package.yml - upload-recipe: needs: - should-run @@ -168,9 +157,9 @@ jobs: 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}" + /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() @@ -179,7 +168,6 @@ jobs: - check-rename - clang-tidy - build-test - - package - upload-recipe - notify-clio runs-on: ubuntu-latest diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml index b7517ccf11..e570a0e119 100644 --- a/.github/workflows/on-tag.yml +++ b/.github/workflows/on-tag.yml @@ -1,5 +1,5 @@ -# This workflow uploads the libxrpl recipe to the Conan remote and builds -# release packages when a versioned tag is pushed. +# This workflow uploads the libxrpl recipe to the Conan remote when a versioned +# tag is pushed. name: Tag on: @@ -22,22 +22,3 @@ jobs: secrets: remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} - - build-test: - if: ${{ github.repository == 'XRPLF/rippled' }} - uses: ./.github/workflows/reusable-build-test.yml - strategy: - fail-fast: true - matrix: - os: [linux] - with: - ccache_enabled: false - os: ${{ matrix.os }} - strategy_matrix: minimal - secrets: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - package: - if: ${{ github.repository == 'XRPLF/rippled' }} - needs: build-test - uses: ./.github/workflows/reusable-package.yml diff --git a/.github/workflows/on-trigger.yml b/.github/workflows/on-trigger.yml index 803ba3c87b..11d98bffb7 100644 --- a/.github/workflows/on-trigger.yml +++ b/.github/workflows/on-trigger.yml @@ -21,13 +21,11 @@ on: - ".github/workflows/reusable-build-test-config.yml" - ".github/workflows/reusable-build-test.yml" - ".github/workflows/reusable-clang-tidy.yml" - - ".github/workflows/reusable-package.yml" - ".github/workflows/reusable-strategy-matrix.yml" - ".github/workflows/reusable-test.yml" - ".github/workflows/reusable-upload-recipe.yml" - ".clang-tidy" - ".codecov.yml" - - "cfg/**" - "cmake/**" - "conan/**" - "external/**" @@ -37,9 +35,6 @@ on: - "CMakeLists.txt" - "conanfile.py" - "conan.lock" - - "LICENSE.md" - - "package/**" - - "README.md" # Run at 06:32 UTC on every day of the week from Monday through Friday. This # will force all dependencies to be rebuilt, which is useful to verify that @@ -100,7 +95,3 @@ jobs: secrets: remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} - - package: - needs: build-test - uses: ./.github/workflows/reusable-package.yml diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index de6a4f40b4..2f15b82266 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -14,7 +14,7 @@ on: jobs: # Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks. run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@cba1f0891650baf1a9c88624dc2d72573be2eb81 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a with: runs_on: ubuntu-latest container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-41ec7c1" }' diff --git a/.github/workflows/reusable-build-docker-image.yml b/.github/workflows/reusable-build-docker-image.yml deleted file mode 100644 index c3795e56fa..0000000000 --- a/.github/workflows/reusable-build-docker-image.yml +++ /dev/null @@ -1,89 +0,0 @@ -# Build a single-platform Docker image. On push, the image is pushed to -# GHCR with arch-suffixed tags (e.g. `:latest-amd64`, `:sha-abc-amd64`) -# so the calling workflow can stitch per-arch builds into a multi-arch -# manifest without needing to pass digests around. -name: Reusable build Docker image (single platform) - -on: - workflow_call: - inputs: - image_name: - description: "Full image name without tag (e.g. 'ghcr.io/xrplf/xrpld/nix-ubuntu')" - required: true - type: string - dockerfile: - description: "Path to the Dockerfile, relative to the repository root" - required: true - type: string - base_image: - description: "Value passed to the Dockerfile as the BASE_IMAGE build arg" - required: true - type: string - platform: - description: "Docker platform string, e.g. linux/amd64" - required: true - type: string - runner: - description: "GitHub Actions runner label to build on" - required: true - type: string - push: - description: "Whether to push the image to GHCR" - required: true - type: boolean - -defaults: - run: - shell: bash - -jobs: - build: - name: Build (${{ inputs.platform }}) - runs-on: ${{ inputs.runner }} - permissions: - contents: read - packages: write - - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Determine arch - id: vars - env: - PLATFORM: ${{ inputs.platform }} - run: | - echo "arch=${PLATFORM##*/}" >>$GITHUB_OUTPUT - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - - - name: Login to GitHub Container Registry - if: inputs.push - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Docker metadata - id: meta - uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 - with: - images: ${{ inputs.image_name }} - tags: | - type=sha,prefix=sha-,format=short - type=raw,value=latest - flavor: | - suffix=-${{ steps.vars.outputs.arch }},onlatest=true - - - name: Build and push - uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 - with: - context: . - file: ${{ inputs.dockerfile }} - platforms: ${{ inputs.platform }} - push: ${{ inputs.push }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - build-args: BASE_IMAGE=${{ inputs.base_image }} diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 31457bb892..ae998faebd 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -113,7 +113,7 @@ jobs: - name: Set ccache log file if: ${{ inputs.ccache_enabled && runner.debug == '1' }} - run: echo "CCACHE_LOGFILE=${{ runner.temp }}/ccache.log" >>"${GITHUB_ENV}" + run: echo "CCACHE_LOGFILE=${{ runner.temp }}/ccache.log" >> "${GITHUB_ENV}" - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 @@ -143,14 +143,15 @@ jobs: working-directory: ${{ env.BUILD_DIR }} env: BUILD_TYPE: ${{ inputs.build_type }} + SANITIZERS: ${{ inputs.sanitizers }} CMAKE_ARGS: ${{ inputs.cmake_args }} run: | cmake \ - -G '${{ runner.os == 'Windows' && 'Visual Studio 17 2022' || 'Ninja' }}' \ - -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ - -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ - ${CMAKE_ARGS} \ - .. + -G '${{ runner.os == 'Windows' && 'Visual Studio 17 2022' || 'Ninja' }}' \ + -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + ${CMAKE_ARGS} \ + .. - name: Check protocol autogen files are up-to-date working-directory: ${{ env.BUILD_DIR }} @@ -172,10 +173,10 @@ jobs: cmake --build . --target code_gen DIFF=$(git -C .. status --porcelain -- include/xrpl/protocol_autogen src/tests/libxrpl/protocol_autogen) if [ -n "${DIFF}" ]; then - echo "::error::Generated protocol files are out of date" - git -C .. diff -- include/xrpl/protocol_autogen src/tests/libxrpl/protocol_autogen - echo "${MESSAGE}" - exit 1 + echo "::error::Generated protocol files are out of date" + git -C .. diff -- include/xrpl/protocol_autogen src/tests/libxrpl/protocol_autogen + echo "${MESSAGE}" + exit 1 fi - name: Build the binary @@ -186,18 +187,18 @@ jobs: CMAKE_TARGET: ${{ inputs.cmake_target }} run: | cmake \ - --build . \ - --config "${BUILD_TYPE}" \ - --parallel "${BUILD_NPROC}" \ - --target "${CMAKE_TARGET}" + --build . \ + --config "${BUILD_TYPE}" \ + --parallel "${BUILD_NPROC}" \ + --target "${CMAKE_TARGET}" - name: Show ccache statistics if: ${{ inputs.ccache_enabled }} run: | ccache --show-stats -vv if [ '${{ runner.debug }}' = '1' ]; then - cat "${CCACHE_LOGFILE}" - curl ${CCACHE_REMOTE_STORAGE%|*}/status || true + cat "${CCACHE_LOGFILE}" + curl ${CCACHE_REMOTE_STORAGE%|*}/status || true fi - name: Upload the binary (Linux) @@ -214,7 +215,7 @@ jobs: working-directory: ${{ env.BUILD_DIR }} run: | set -o pipefail - ./xrpld --definitions | python3 -m json.tool >server_definitions.json + ./xrpld --definitions | python3 -m json.tool > server_definitions.json - name: Upload server definitions if: ${{ github.event.repository.visibility == 'public' && inputs.config_name == 'debian-bookworm-gcc-13-amd64-release' }} @@ -231,10 +232,10 @@ jobs: run: | ldd ./xrpld if [ "$(ldd ./xrpld | grep -E '(libstdc\+\+|libgcc)' | wc -l)" -eq 0 ]; then - echo 'The binary is statically linked.' + echo 'The binary is statically linked.' else - echo 'The binary is dynamically linked.' - exit 1 + echo 'The binary is dynamically linked.' + exit 1 fi - name: Verify presence of instrumentation (Linux) @@ -250,12 +251,12 @@ jobs: run: | ASAN_OPTS="include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-asan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/asan.supp" if [[ "${CONFIG_NAME}" == *gcc* ]]; then - ASAN_OPTS="${ASAN_OPTS}:alloc_dealloc_mismatch=0" + ASAN_OPTS="${ASAN_OPTS}:alloc_dealloc_mismatch=0" fi - echo "ASAN_OPTIONS=${ASAN_OPTS}" >>${GITHUB_ENV} - echo "TSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-tsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/tsan.supp" >>${GITHUB_ENV} - echo "UBSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-ubsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/ubsan.supp" >>${GITHUB_ENV} - echo "LSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-lsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/lsan.supp" >>${GITHUB_ENV} + echo "ASAN_OPTIONS=${ASAN_OPTS}" >> ${GITHUB_ENV} + echo "TSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-tsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/tsan.supp" >> ${GITHUB_ENV} + echo "UBSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-ubsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/ubsan.supp" >> ${GITHUB_ENV} + echo "LSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-lsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/lsan.supp" >> ${GITHUB_ENV} - name: Run the separate tests if: ${{ !inputs.build_only }} @@ -266,9 +267,9 @@ jobs: PARALLELISM: ${{ runner.os == 'Windows' && '1' || steps.nproc.outputs.nproc }} run: | ctest \ - --output-on-failure \ - -C "${BUILD_TYPE}" \ - -j "${PARALLELISM}" + --output-on-failure \ + -C "${BUILD_TYPE}" \ + -j "${PARALLELISM}" - name: Run the embedded tests if: ${{ !inputs.build_only }} @@ -278,28 +279,20 @@ jobs: run: | set -o pipefail # Coverage builds are slower due to instrumentation; use fewer parallel jobs to avoid flakiness - [ "$COVERAGE_ENABLED" = "true" ] && BUILD_NPROC=$((BUILD_NPROC - 2)) + [ "$COVERAGE_ENABLED" = "true" ] && BUILD_NPROC=$(( BUILD_NPROC - 2 )) ./xrpld --unittest --unittest-jobs "${BUILD_NPROC}" 2>&1 | tee unittest.log - name: Show test failure summary if: ${{ failure() && !inputs.build_only }} - env: - WORKING_DIR: ${{ runner.os == 'Windows' && format('{0}\{1}', env.BUILD_DIR, inputs.build_type) || env.BUILD_DIR }} + working-directory: ${{ runner.os == 'Windows' && format('{0}/{1}', env.BUILD_DIR, inputs.build_type) || env.BUILD_DIR }} run: | - if [ ! -d "${WORKING_DIR}" ]; then - echo "Working directory '${WORKING_DIR}' does not exist." - exit 0 - fi - - cd "${WORKING_DIR}" - if [ ! -f unittest.log ]; then - echo "unittest.log not found; embedded tests may not have run." - exit 0 + echo "unittest.log not found; embedded tests may not have run." + exit 0 fi if ! grep -E "failed" unittest.log; then - echo "Log present but no failure lines found in unittest.log." + echo "Log present but no failure lines found in unittest.log." fi - name: Debug failure (Linux) if: ${{ failure() && runner.os == 'Linux' && !inputs.build_only }} @@ -317,14 +310,14 @@ jobs: BUILD_TYPE: ${{ inputs.build_type }} run: | cmake \ - --build . \ - --config "${BUILD_TYPE}" \ - --parallel "${BUILD_NPROC}" \ - --target coverage + --build . \ + --config "${BUILD_TYPE}" \ + --parallel "${BUILD_NPROC}" \ + --target coverage - name: Upload coverage report if: ${{ github.repository == 'XRPLF/rippled' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1 + uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 with: disable_search: true disable_telem: true diff --git a/.github/workflows/reusable-check-levelization.yml b/.github/workflows/reusable-check-levelization.yml index b5d57a177a..4efe3e1138 100644 --- a/.github/workflows/reusable-check-levelization.yml +++ b/.github/workflows/reusable-check-levelization.yml @@ -38,9 +38,9 @@ jobs: run: | DIFF=$(git status --porcelain) if [ -n "${DIFF}" ]; then - # Print the differences to give the contributor a hint about what to - # expect when running levelization on their own machine. - git diff - echo "${MESSAGE}" - exit 1 + # Print the differences to give the contributor a hint about what to + # expect when running levelization on their own machine. + git diff + echo "${MESSAGE}" + exit 1 fi diff --git a/.github/workflows/reusable-check-rename.yml b/.github/workflows/reusable-check-rename.yml index 7aa5b80594..56a1a3e637 100644 --- a/.github/workflows/reusable-check-rename.yml +++ b/.github/workflows/reusable-check-rename.yml @@ -48,9 +48,9 @@ jobs: run: | DIFF=$(git status --porcelain) if [ -n "${DIFF}" ]; then - # Print the differences to give the contributor a hint about what to - # expect when running the renaming scripts on their own machine. - git diff - echo "${MESSAGE}" - exit 1 + # Print the differences to give the contributor a hint about what to + # expect when running the renaming scripts on their own machine. + git diff + echo "${MESSAGE}" + exit 1 fi diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 8be1db5fb2..a678fe4c8e 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -29,7 +29,7 @@ jobs: if: ${{ inputs.check_only_changed }} permissions: contents: read - uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@224f3c48d3014d082a1129237b8291ff0b0a331f + uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@12f5dbc98a2260259a66970e57fa4d26fb7f285c run-clang-tidy: name: Run clang tidy @@ -39,7 +39,6 @@ jobs: container: "ghcr.io/xrplf/ci/debian-trixie:clang-21-sha-53033a2" permissions: contents: read - issues: write steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -70,13 +69,13 @@ jobs: working-directory: ${{ env.BUILD_DIR }} run: | cmake \ - -G 'Ninja' \ - -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ - -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ - -Dtests=ON \ - -Dwerr=ON \ - -Dxrpld=ON \ - .. + -G 'Ninja' \ + -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -Dtests=ON \ + -Dwerr=ON \ + -Dxrpld=ON \ + .. # clang-tidy needs headers generated from proto files - name: Build libxrpl.libpb @@ -93,11 +92,6 @@ jobs: set -o pipefail run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee "${OUTPUT_FILE}" - - name: Print errors - if: ${{ steps.run_clang_tidy.outcome != 'success' }} - run: | - sed '/error\||/!d' "${OUTPUT_FILE}" - - name: Upload clang-tidy output if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -106,24 +100,13 @@ jobs: archive: false retention-days: 30 - - name: Check for changes - id: files_changed - continue-on-error: true - run: | - git diff --exit-code - - - name: Fix style - if: ${{ steps.files_changed.outcome != 'success' }} - run: | - pre-commit run --all-files || true - - name: Generate git diff - if: ${{ steps.files_changed.outcome != 'success' }} + if: ${{ steps.run_clang_tidy.outcome != 'success' }} run: | git diff | tee "${DIFF_FILE}" - name: Upload clang-tidy diff output - if: ${{ github.event.repository.visibility == 'public' && steps.files_changed.outcome != 'success' }} + if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: path: ${{ env.DIFF_FILE }} @@ -133,58 +116,98 @@ jobs: - name: Write issue header if: ${{ steps.run_clang_tidy.outcome != 'success' }} run: | - cat >"${ISSUE_FILE}" < "${ISSUE_FILE}" <filtered-output.txt || true + # Extract lines containing 'error:', 'warning:', or 'note:' + grep -E '(error:|warning:|note:)' "${OUTPUT_FILE}" > filtered-output.txt || true - # If filtered output is empty, use original (might be a different error format) - if [ ! -s filtered-output.txt ]; then - cp "${OUTPUT_FILE}" filtered-output.txt - fi + # If filtered output is empty, use original (might be a different error format) + if [ ! -s filtered-output.txt ]; then + cp "${OUTPUT_FILE}" filtered-output.txt + fi - # Truncate if too large - head -c 60000 filtered-output.txt >>"${ISSUE_FILE}" - if [ "$(wc -c >"${ISSUE_FILE}" - echo "... (output truncated, see artifacts for full output)" >>"${ISSUE_FILE}" - fi + # Truncate if too large + head -c 60000 filtered-output.txt >> "${ISSUE_FILE}" + if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then + echo "" >> "${ISSUE_FILE}" + echo "... (output truncated, see artifacts for full output)" >> "${ISSUE_FILE}" + fi - rm filtered-output.txt + rm filtered-output.txt else - echo "No output file found" >>"${ISSUE_FILE}" + echo "No output file found" >> "${ISSUE_FILE}" fi - name: Append issue footer if: ${{ steps.run_clang_tidy.outcome != 'success' }} run: | - cat >>"${ISSUE_FILE}" <> "${ISSUE_FILE}" < create_issue.log + + - name: Output created issue number + run: | + created_issue="$(sed 's|.*/||' create_issue.log)" + echo "created_issue=$created_issue" >> $GITHUB_OUTPUT + echo "Created issue #$created_issue" diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml deleted file mode 100644 index 2a3ed8a33e..0000000000 --- a/.github/workflows/reusable-package.yml +++ /dev/null @@ -1,99 +0,0 @@ -# Build Linux packages (DEB and RPM) from pre-built binary artifacts. -# Discovers which configurations to package from linux.json (os entries -# with "package": true) and fans out one job per entry. Today only -# linux/amd64 is emitted; the architecture is hardcoded both here -# (runner) and in generate.py. -name: Package - -on: - workflow_call: - inputs: - pkg_release: - description: "Package release number. Increment when repackaging the same executable." - required: false - type: string - default: "1" - -defaults: - run: - shell: bash - -env: - BUILD_DIR: build - -jobs: - generate-matrix: - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.generate.outputs.matrix }} - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version: 3.13 - - - name: Generate packaging matrix - id: generate - working-directory: .github/scripts/strategy-matrix - run: | - ./generate.py --packaging --config=linux.json >>"${GITHUB_OUTPUT}" - - generate-version: - runs-on: ubuntu-latest - outputs: - version: ${{ steps.version.outputs.version }} - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - sparse-checkout: | - .github/actions/generate-version - src/libxrpl/protocol/BuildInfo.cpp - - name: Generate version - id: version - uses: ./.github/actions/generate-version - - package: - needs: [generate-matrix, generate-version] - if: ${{ github.event.repository.visibility == 'public' }} - strategy: - fail-fast: false - matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} - name: "${{ matrix.artifact_name }}" - permissions: - contents: read - runs-on: ["self-hosted", "Linux", "X64", "heavy"] - container: ${{ format('ghcr.io/xrplf/ci/{0}-{1}:{2}-{3}-sha-{4}', matrix.os.distro_name, matrix.os.distro_version, matrix.os.compiler_name, matrix.os.compiler_version, matrix.os.image_sha) }} - timeout-minutes: 30 - - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Download pre-built binary - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: ${{ matrix.artifact_name }} - path: ${{ env.BUILD_DIR }} - - - name: Make binary executable - run: chmod +x "${BUILD_DIR}/xrpld" - - - name: Build package - env: - PKG_VERSION: ${{ needs.generate-version.outputs.version }} - PKG_RELEASE: ${{ inputs.pkg_release }} - run: ./package/build_pkg.sh - - - name: Upload package artifact - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.artifact_name }}-pkg-${{ needs.generate-version.outputs.version }} - path: | - ${{ env.BUILD_DIR }}/debbuild/*.deb - ${{ env.BUILD_DIR }}/debbuild/*.ddeb - ${{ env.BUILD_DIR }}/rpmbuild/RPMS/**/*.rpm - if-no-files-found: error diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index 62d65ad3fa..b1232a138f 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -42,4 +42,4 @@ jobs: env: GENERATE_CONFIG: ${{ inputs.os != '' && format('--config={0}.json', inputs.os) || '' }} GENERATE_OPTION: ${{ inputs.strategy_matrix == 'all' && '--all' || '' }} - run: ./generate.py ${GENERATE_OPTION} ${GENERATE_CONFIG} >>"${GITHUB_OUTPUT}" + run: ./generate.py ${GENERATE_OPTION} ${GENERATE_CONFIG} >> "${GITHUB_OUTPUT}" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c9dec89435..1c0dc94550 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -37,57 +37,40 @@ repos: exclude: ^include/xrpl/protocol_autogen/(transactions|ledger_entries)/ - repo: https://github.com/pre-commit/mirrors-clang-format - rev: dd18dad857d6133e90bbe478f4f2f22ec0030269 # frozen: v22.1.5 + rev: cd481d7b0bfb5c7b3090c21846317f9a8262e891 # frozen: v22.1.0 hooks: - id: clang-format args: [--style=file] "types_or": [c++, c, proto] exclude: ^include/xrpl/protocol_autogen/(transactions|ledger_entries)/ - - repo: https://github.com/BlankSpruce/gersemi-pre-commit - rev: faadd6a9d852369ca94f4d15b2404c967ba8cb01 # frozen: 0.27.6 + - repo: https://github.com/BlankSpruce/gersemi + rev: 0.26.0 hooks: - id: gersemi - repo: https://github.com/rbubley/mirrors-prettier - rev: 515f543f5718ebfd6ce22e16708bb32c68ff96e1 # frozen: v3.8.3 + rev: c2bc67fe8f8f549cc489e00ba8b45aa18ee713b1 # frozen: v3.8.1 hooks: - id: prettier args: [--end-of-line=auto] - repo: https://github.com/psf/black-pre-commit-mirror - rev: 4160603246a6b365d4a2af661c6d71b0a0f50478 # frozen: 26.5.1 + rev: ea488cebbfd88a5f50b8bd95d5c829d0bb76feb8 # frozen: 26.1.0 hooks: - id: black - - repo: https://github.com/scop/pre-commit-shfmt - rev: 05c1426671b9237fb5e1444dd63aa5731bec0dfb # frozen: v3.13.1-1 + - repo: https://github.com/openstack/bashate + rev: 5798d24d571676fc407e81df574c1ef57b520f23 # frozen: 2.1.1 hooks: - - id: shfmt - args: [--write, --indent=4, --case-indent=true] - - - repo: local - hooks: - - id: format-inline-bash-workflows - name: "format `run:` blocks in workflows/actions" - entry: ./.github/scripts/format-inline-bash.py - language: python - files: ^\.github/(workflows|actions)/.*\.ya?ml$ - - id: format-inline-bash-markdown - name: "format ```bash blocks in markdown" - entry: ./.github/scripts/format-inline-bash.py - language: python - files: \.md$ + - id: bashate + args: ["--ignore=E006"] - repo: https://github.com/streetsidesoftware/cspell-cli - rev: 4643f154907327ee0a2c7038f0296e0dd77d9776 # frozen: v10.0.0 + rev: a42085ade523f591dca134379a595e7859986445 # frozen: v9.7.0 hooks: - id: cspell # Spell check changed files - exclude: | - (?x)^( - .config/cspell.config.yaml| - include/xrpl/protocol_autogen/(transactions|ledger_entries)/.* - )$ + exclude: (.config/cspell.config.yaml|^include/xrpl/protocol_autogen/(transactions|ledger_entries)/) - id: cspell # Spell check the commit message name: check commit message spelling args: diff --git a/BUILD.md b/BUILD.md index 1d3fc8f774..cf0a685abd 100644 --- a/BUILD.md +++ b/BUILD.md @@ -141,7 +141,7 @@ Alternatively, you can pull our recipes from the repository and export them loca ```bash # Define which recipes to export. -recipes=('abseil' 'ed25519' 'mpt-crypto' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') +recipes=('abseil' 'ed25519' 'grpc' 'm4' 'mpt-crypto' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') # Selectively check out the recipes from our CCI fork. cd external @@ -151,8 +151,8 @@ git init git remote add origin git@github.com:XRPLF/conan-center-index.git git sparse-checkout init for recipe in "${recipes[@]}"; do - echo "Checking out recipe '${recipe}'..." - git sparse-checkout add recipes/${recipe} + echo "Checking out recipe '${recipe}'..." + git sparse-checkout add recipes/${recipe} done git fetch origin master git checkout master @@ -180,7 +180,7 @@ the new recipe will be automatically pulled from the official Conan Center. If you see an error similar to the following after running `conan profile show`: -```text +```bash ERROR: Invalid setting '17' is not a valid 'settings.compiler.version' value. Possible values are ['5.0', '5.1', '6.0', '6.1', '7.0', '7.3', '8.0', '8.1', '9.0', '9.1', '10.0', '11.0', '12.0', '13', '13.0', '13.1', '14', '14.0', '15', @@ -427,19 +427,16 @@ install ccache --version 4.11.3 --allow-downgrade`. Single-config generators: ``` - cmake --build . --parallel N + cmake --build . ``` Multi-config generators: ``` - cmake --build . --config Release --parallel N - cmake --build . --config Debug --parallel N + cmake --build . --config Release + cmake --build . --config Debug ``` - Replace the `--parallel` parameter N with the desired number of parallel jobs. A common starting point is half of the number of available CPU - cores. - 5. Test xrpld. Single-config generators: @@ -533,15 +530,15 @@ stored inside the build directory, as either of: ## Sanitizers To build dependencies and xrpld with sanitizer instrumentation, set the -`SANITIZERS` environment variable when running `conan install` and use the `sanitizers` profile: +`SANITIZERS` environment variable (only once before running conan and cmake) and use the `sanitizers` profile in conan: ```bash export SANITIZERS=address,undefinedbehavior conan install .. --output-folder . --profile:all sanitizers --build missing --settings build_type=Debug -``` -You can then build and test as usual, with the generated `xrpld` binary containing the sanitizer instrumentation. When you run it, it will report any sanitizer errors it detects in the console output. +cmake -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Debug -Dxrpld=ON -Dtests=ON .. +``` See [Sanitizers docs](./docs/build/sanitizers.md) for more details. diff --git a/CMakeLists.txt b/CMakeLists.txt index b16e5dad9c..84a4b29108 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -136,7 +136,6 @@ endif() include(XrplCore) include(XrplProtocolAutogen) include(XrplInstall) -include(XrplPackaging) include(XrplValidatorKeys) if(tests) diff --git a/bin/git/setup-upstreams.sh b/bin/git/setup-upstreams.sh index 97c84f5507..57c3f935f9 100755 --- a/bin/git/setup-upstreams.sh +++ b/bin/git/setup-upstreams.sh @@ -1,8 +1,8 @@ #!/bin/bash if [[ $# -ne 1 || "$1" == "--help" || "$1" == "-h" ]]; then - name=$(basename $0) - cat <<-USAGE + name=$( basename $0 ) + cat <<- USAGE Usage: $name Where is the Github username of the upstream repo. e.g. XRPLF @@ -14,7 +14,7 @@ fi shift user="$1" # Get the origin URL. Expect it be an SSH-style URL -origin=$(git remote get-url origin) +origin=$( git remote get-url origin ) if [[ "${origin}" == "" ]]; then echo Invalid origin remote >&2 exit 1 @@ -22,11 +22,11 @@ fi # echo "Origin: ${origin}" # Parse the origin ifs_orig="${IFS}" -IFS=':' read remote originpath <<<"${origin}" +IFS=':' read remote originpath <<< "${origin}" # echo "Remote: ${remote}, Originpath: ${originpath}" -IFS='@' read sshuser server <<<"${remote}" +IFS='@' read sshuser server <<< "${remote}" # echo "SSHUser: ${sshuser}, Server: ${server}" -IFS='/' read originuser repo <<<"${originpath}" +IFS='/' read originuser repo <<< "${originpath}" # echo "Originuser: ${originuser}, Repo: ${repo}" if [[ "${sshuser}" == "" || "${server}" == "" || "${originuser}" == "" || "${repo}" == "" ]]; then echo "Can't parse origin URL: ${origin}" >&2 @@ -35,9 +35,9 @@ fi upstream="https://${server}/${user}/${repo}" upstreampush="${remote}:${user}/${repo}" upstreamgroup="upstream upstream-push" -current=$(git remote get-url upstream 2>/dev/null) -currentpush=$(git remote get-url upstream-push 2>/dev/null) -currentgroup=$(git config remotes.upstreams) +current=$( git remote get-url upstream 2>/dev/null ) +currentpush=$( git remote get-url upstream-push 2>/dev/null ) +currentgroup=$( git config remotes.upstreams ) if [[ "${current}" == "${upstream}" ]]; then echo "Upstream already set up correctly. Skip" elif [[ -n "${current}" && "${current}" != "${upstream}" && "${current}" != "${upstreampush}" ]]; then @@ -45,9 +45,9 @@ elif [[ -n "${current}" && "${current}" != "${upstream}" && "${current}" != "${u else if [[ "${current}" == "${upstreampush}" ]]; then echo "Upstream set to dangerous push URL. Update." - _run git remote rename upstream upstream-push || - _run git remote remove upstream - currentpush=$(git remote get-url upstream-push 2>/dev/null) + _run git remote rename upstream upstream-push || \ + _run git remote remove upstream + currentpush=$( git remote get-url upstream-push 2>/dev/null ) fi _run git remote add upstream "${upstream}" fi diff --git a/bin/git/squash-branches.sh b/bin/git/squash-branches.sh index ba63f9c148..eb4aefe23c 100755 --- a/bin/git/squash-branches.sh +++ b/bin/git/squash-branches.sh @@ -1,8 +1,8 @@ #!/bin/bash if [[ $# -lt 3 || "$1" == "--help" || "$1" = "-h" ]]; then - name=$(basename $0) - cat <<-USAGE + name=$( basename $0 ) + cat <<- USAGE Usage: $name workbranch base/branch user/branch [user/branch [...]] * workbranch will be created locally from base/branch @@ -16,7 +16,7 @@ fi work="$1" shift -branches=($(echo "${@}" | sed "s/:/\//")) +branches=( $( echo "${@}" | sed "s/:/\//" ) ) base="${branches[0]}" unset branches[0] @@ -24,10 +24,10 @@ set -e users=() for b in "${branches[@]}"; do - users+=($(echo $b | cut -d/ -f1)) + users+=( $( echo $b | cut -d/ -f1 ) ) done -users=($(printf '%s\n' "${users[@]}" | sort -u)) +users=( $( printf '%s\n' "${users[@]}" | sort -u ) ) git fetch --multiple upstreams "${users[@]}" git checkout -B "$work" --no-track "$base" @@ -40,7 +40,7 @@ done # Make sure the commits look right git log --show-signature "$base..HEAD" -parts=($(echo $base | sed "s/\// /")) +parts=( $( echo $base | sed "s/\// /" ) ) repo="${parts[0]}" b="${parts[1]}" push=$repo @@ -50,7 +50,7 @@ fi if [[ "$repo" == "upstream" ]]; then repo="upstreams" fi -cat </dev/null) || true +push=$( git rev-parse --abbrev-ref --symbolic-full-name '@{push}' \ + 2>/dev/null ) || true if [[ "${push}" != "" ]]; then echo "Warning: ${push} may already exist." fi -build=$(find -name BuildInfo.cpp) -sed 's/\(^.*versionString =\).*$/\1 "'${version}'"/' ${build} >version.cpp && - diff "${build}" version.cpp && exit 1 || - mv -vi version.cpp ${build} +build=$( find -name BuildInfo.cpp ) +sed 's/\(^.*versionString =\).*$/\1 "'${version}'"/' ${build} > version.cpp && \ +diff "${build}" version.cpp && exit 1 || \ +mv -vi version.cpp ${build} git diff @@ -47,7 +47,7 @@ git commit -S -m "Set version to ${version}" git log --oneline --first-parent ${base}^.. -cat < -# -# If set to 0, the server will skip validation of endpoint -# addresses received in TMEndpoints peer protocol messages, -# allowing addresses that are not publicly routable or have a -# port of 0. The default is 1 (verification enabled). -# -# WARNING: Disabling this option is a security risk and should -# only be used for local testing and debugging. Do not disable -# on mainnet. -# # # [transaction_queue] EXPERIMENTAL # @@ -953,21 +942,6 @@ # # Optional keys for NuDB and RocksDB: # -# 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 cache_size or cache_age is not specified, -# default values will be used for the unspecified -# parameter. -# -# Note: the cache will not be created if online_delete -# is specified, because the rotating NodeStore does -# not use this cache). -# # fast_load Boolean. If set, load the last persisted ledger # from disk upon process start before syncing to # the network. This is likely to improve performance @@ -1284,7 +1258,7 @@ # default. Don't change this without understanding the consequences. # # Example: -# account_reserve = 1000000 # 1 XRP +# account_reserve = 10000000 # 10 XRP # # owner_reserve = # @@ -1296,7 +1270,7 @@ # default. Don't change this without understanding the consequences. # # Example: -# owner_reserve = 200000 # 0.2 XRP +# owner_reserve = 2000000 # 2 XRP # #------------------------------------------------------------------------------- # @@ -1481,7 +1455,10 @@ admin = 127.0.0.1 protocol = http [port_peer] -port = 2459 +# Many servers still use the legacy port of 51235, so for backward-compatibility +# we maintain that port number here. However, for new servers we recommend +# changing this to the default port of 2459. +port = 51235 ip = 0.0.0.0 # alternatively, to accept connections on IPv4 + IPv6, use: #ip = :: diff --git a/cmake/XrplPackaging.cmake b/cmake/XrplPackaging.cmake deleted file mode 100644 index fe885c200c..0000000000 --- a/cmake/XrplPackaging.cmake +++ /dev/null @@ -1,44 +0,0 @@ -#[===================================================================[ - Linux packaging support: 'package' target. - - The packaging script (package/build_pkg.sh) installs to FHS-standard - paths (/usr/bin, /etc/xrpld, etc.) regardless of CMAKE_INSTALL_PREFIX, - so no prefix guard is needed here. -#]===================================================================] -if(NOT is_linux) - message(STATUS "Packaging not supported on non-Linux hosts") - return() -endif() - -if(NOT DEFINED pkg_release) - set(pkg_release 1) -endif() - -find_program(RPMBUILD_EXECUTABLE rpmbuild) -find_program(DPKG_BUILDPACKAGE_EXECUTABLE dpkg-buildpackage) - -if(NOT (RPMBUILD_EXECUTABLE OR DPKG_BUILDPACKAGE_EXECUTABLE)) - message( - STATUS - "Neither rpmbuild nor dpkg-buildpackage found; 'package' target not available" - ) - return() -endif() - -set(package_env - SRC_DIR=${CMAKE_SOURCE_DIR} - BUILD_DIR=${CMAKE_BINARY_DIR} - PKG_VERSION=${xrpld_version} - PKG_RELEASE=${pkg_release} -) - -add_custom_target( - package - COMMAND - ${CMAKE_COMMAND} -E env ${package_env} - ${CMAKE_SOURCE_DIR}/package/build_pkg.sh - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} - DEPENDS xrpld - COMMENT "Building Linux package (deb/rpm inferred from host tooling)" - VERBATIM -) diff --git a/cmake/XrplSanitizers.cmake b/cmake/XrplSanitizers.cmake index 64f1841bfb..2228381286 100644 --- a/cmake/XrplSanitizers.cmake +++ b/cmake/XrplSanitizers.cmake @@ -1,33 +1,140 @@ #[===================================================================[ - Apply sanitizer flags built by the Conan profile. + Configure sanitizers based on environment variables. - Parsing, validation, and flag construction are performed in conan/profiles/sanitizers. - This module reads the following CMake variables injected by the Conan toolchain via extra_variables: + This module reads the following environment variables: + - SANITIZERS: The sanitizers to enable. Possible values: + - "address" + - "address,undefinedbehavior" + - "thread" + - "thread,undefinedbehavior" + - "undefinedbehavior" - - SANITIZERS: The active sanitizers (e.g. "address,undefinedbehavior"). - - SANITIZERS_COMPILER_FLAGS: Space-separated compiler flags. - - SANITIZERS_LINKER_FLAGS: Space-separated linker flags. + The compiler type and platform are detected in CompilationEnv.cmake. + The sanitizer compile options are applied to the 'common' interface library + which is linked to all targets in the project. - The flags are applied to the 'common' interface library which is linked to all targets in the project. + Internal flag variables set by this module: + + - SANITIZER_TYPES: List of sanitizer types to enable (e.g., "address", + "thread", "undefined"). And two more flags for undefined behavior sanitizer (e.g., "float-divide-by-zero", "unsigned-integer-overflow"). + This list is joined with commas and passed to -fsanitize=. + + - SANITIZERS_COMPILE_FLAGS: Compiler flags for sanitizer instrumentation. + Includes: + * -fno-omit-frame-pointer: Preserves frame pointers for stack traces + * -O1: Minimum optimization for reasonable performance + * -fsanitize=: Enables sanitizer instrumentation + * -fsanitize-ignorelist=: (Clang only) Compile-time ignorelist + * -mcmodel=large/medium: (GCC only) Code model for large binaries + * -Wno-stringop-overflow: (GCC only) Suppresses false positive warnings + * -Wno-tsan: (For GCC TSAN combination only) Suppresses atomic_thread_fence warnings + + - SANITIZERS_LINK_FLAGS: Linker flags for sanitizer runtime libraries. + Includes: + * -fsanitize=: Links sanitizer runtime libraries + * -mcmodel=large/medium: (GCC only) Matches compile-time code model + + - SANITIZERS_RELOCATION_FLAGS: (GCC only, x86_64 only) Code model flags for linking. + Used to handle large instrumented binaries on x86_64: + * -mcmodel=large: For AddressSanitizer (prevents relocation errors) + * -mcmodel=medium: For ThreadSanitizer (large model is incompatible) + On ARM64, these flags are omitted since GCC does not support + -mcmodel=large with -fPIC, and -mcmodel=medium does not exist. #]===================================================================] -include_guard(GLOBAL) include(CompilationEnv) -if(NOT DEFINED SANITIZERS) +# Read environment variable +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") + set(SANITIZERS_ENABLED TRUE) +else() set(SANITIZERS_ENABLED FALSE) return() endif() -set(SANITIZERS_ENABLED TRUE) -message(STATUS "=== Configuring Sanitizers ===") -message(STATUS " SANITIZERS: ${SANITIZERS}") -message(STATUS " Compile flags: ${SANITIZERS_COMPILER_FLAGS}") -message(STATUS " Link flags: ${SANITIZERS_LINKER_FLAGS}") +# Sanitizers are not supported on Windows/MSVC +if(is_msvc) + message( + FATAL_ERROR + "Sanitizers are not supported on Windows/MSVC. " + "Please unset the SANITIZERS environment variable." + ) +endif() -# GCC with sanitizers is incompatible with mold, gold, and lld linkers. -# Namely, the instrumented binary exceeds size limits imposed by these linkers. +message(STATUS "Configuring sanitizers: ${SANITIZERS}") + +# Parse SANITIZERS value to determine which sanitizers to enable +set(enable_asan FALSE) +set(enable_tsan FALSE) +set(enable_ubsan FALSE) + +# Normalize SANITIZERS into a list +set(san_list "${SANITIZERS}") +string(REPLACE "," ";" san_list "${san_list}") +separate_arguments(san_list) + +foreach(san IN LISTS san_list) + if(san STREQUAL "address") + set(enable_asan TRUE) + elseif(san STREQUAL "thread") + set(enable_tsan TRUE) + elseif(san STREQUAL "undefinedbehavior") + set(enable_ubsan TRUE) + else() + message( + FATAL_ERROR + "Unsupported sanitizer type: ${san}" + "Supported: address, thread, undefinedbehavior and their combinations." + ) + endif() +endforeach() + +# Validate sanitizer compatibility +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() + +# 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") + +# Build the sanitizer flags list +set(SANITIZER_TYPES) + +if(enable_asan) + list(APPEND SANITIZER_TYPES "address") +elseif(enable_tsan) + list(APPEND SANITIZER_TYPES "thread") +endif() + +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 + list(APPEND SANITIZER_TYPES "unsigned-integer-overflow") + 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) +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 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) @@ -35,62 +142,82 @@ if(is_gcc) STATUS " Disabled mold, gold, and lld linkers for GCC with sanitizers" ) + + # Suppress false positive warnings in GCC with stringop-overflow + list(APPEND SANITIZERS_COMPILE_FLAGS "-Wno-stringop-overflow") + + 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) + # GCC doesn't support atomic_thread_fence with tsan. Suppress warnings. + list(APPEND SANITIZERS_COMPILE_FLAGS "-Wno-tsan") + if(is_amd64) + 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) + + # Add sanitizer to compile and link flags + 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 + set(IGNORELIST_PATH + "${CMAKE_SOURCE_DIR}/sanitizers/suppressions/sanitizer-ignorelist.txt" + ) + if(NOT EXISTS "${IGNORELIST_PATH}") + message( + FATAL_ERROR + "Sanitizer ignorelist not found: ${IGNORELIST_PATH}" + ) + endif() + + list( + APPEND SANITIZERS_COMPILE_FLAGS + "-fsanitize-ignorelist=${IGNORELIST_PATH}" + ) + message(STATUS " Using sanitizer ignorelist: ${IGNORELIST_PATH}") + + # Join sanitizer flags with commas for -fsanitize option + list(JOIN SANITIZER_TYPES "," SANITIZER_TYPES_STR) + + # 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() -# Flags arrive as space-separated strings; split into CMake lists before use -separate_arguments( - sanitizers_compiler_flags - UNIX_COMMAND - "${SANITIZERS_COMPILER_FLAGS}" -) -separate_arguments( - sanitizers_linker_flags - UNIX_COMMAND - "${SANITIZERS_LINKER_FLAGS}" -) +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_compiler_flags}> - $<$:${sanitizers_compiler_flags}> + $<$:${SANITIZERS_COMPILE_FLAGS}> + $<$:${SANITIZERS_COMPILE_FLAGS}> ) -target_link_options(common INTERFACE ${sanitizers_linker_flags}) -# This module appends -fsanitize-ignorelist= for Clang builds. -# The ignorelist path contains CMAKE_SOURCE_DIR, so it must be set here, rather than in the Conan profile. -# GCC does not support -fsanitize-ignorelist. -if(is_clang) - set(ignorelist_path - "${CMAKE_SOURCE_DIR}/sanitizers/suppressions/sanitizer-ignorelist.txt" - ) - if(NOT EXISTS "${ignorelist_path}") - message( - FATAL_ERROR - "Sanitizer ignorelist not found: ${ignorelist_path}" - ) - endif() - target_compile_options( - common - INTERFACE - $<$:-fsanitize-ignorelist=${ignorelist_path}> - $<$:-fsanitize-ignorelist=${ignorelist_path}> - ) - message(STATUS " Ignorelist: ${ignorelist_path}") -endif() +# Apply linker flags +target_link_options(common INTERFACE ${SANITIZERS_LINK_FLAGS}) # Define SANITIZERS macro for BuildInfo.cpp set(sanitizers_list) -if(SANITIZERS MATCHES "address") - set(enable_asan ON) +if(enable_asan) list(APPEND sanitizers_list "ASAN") endif() -if(SANITIZERS MATCHES "thread") - set(enable_tsan ON) +if(enable_tsan) list(APPEND sanitizers_list "TSAN") endif() -if(SANITIZERS MATCHES "undefinedbehavior") - set(enable_ubsan ON) +if(enable_ubsan) list(APPEND sanitizers_list "UBSAN") endif() diff --git a/cmake/scripts/codegen/requirements.in b/cmake/scripts/codegen/requirements.in deleted file mode 100644 index d799fd60fd..0000000000 --- a/cmake/scripts/codegen/requirements.in +++ /dev/null @@ -1,13 +0,0 @@ -# Python dependencies for XRP Ledger code generation scripts -# -# These packages are required to run the code generation scripts that -# parse macro files and generate C++ wrapper classes. - -# C preprocessor for Python - used to preprocess macro files -pcpp>=1.30 - -# Parser combinator library - used to parse the macro DSL -pyparsing>=3.0.0 - -# Template engine - used to generate C++ code from templates -Mako>=1.2.2 diff --git a/cmake/scripts/codegen/requirements.txt b/cmake/scripts/codegen/requirements.txt index ff37548c7b..40b472078d 100644 --- a/cmake/scripts/codegen/requirements.txt +++ b/cmake/scripts/codegen/requirements.txt @@ -1,105 +1,13 @@ -# This file was autogenerated by uv via the following command: -# uv pip compile requirements.in --generate-hashes --output-file requirements.txt -mako==1.3.12 \ - --hash=sha256:8f61569480282dbf557145ce441e4ba888be453c30989f879f0d652e39f53ea9 \ - --hash=sha256:9f778e93289bd410bb35daadeb4fc66d95a746f0b75777b942088b7fd7af550a - # via -r requirements.in -markupsafe==3.0.3 \ - --hash=sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f \ - --hash=sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a \ - --hash=sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf \ - --hash=sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19 \ - --hash=sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf \ - --hash=sha256:0f4b68347f8c5eab4a13419215bdfd7f8c9b19f2b25520968adfad23eb0ce60c \ - --hash=sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175 \ - --hash=sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219 \ - --hash=sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb \ - --hash=sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6 \ - --hash=sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab \ - --hash=sha256:15d939a21d546304880945ca1ecb8a039db6b4dc49b2c5a400387cdae6a62e26 \ - --hash=sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1 \ - --hash=sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce \ - --hash=sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218 \ - --hash=sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634 \ - --hash=sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695 \ - --hash=sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad \ - --hash=sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73 \ - --hash=sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c \ - --hash=sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe \ - --hash=sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa \ - --hash=sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559 \ - --hash=sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa \ - --hash=sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37 \ - --hash=sha256:3537e01efc9d4dccdf77221fb1cb3b8e1a38d5428920e0657ce299b20324d758 \ - --hash=sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f \ - --hash=sha256:38664109c14ffc9e7437e86b4dceb442b0096dfe3541d7864d9cbe1da4cf36c8 \ - --hash=sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d \ - --hash=sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c \ - --hash=sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97 \ - --hash=sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a \ - --hash=sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19 \ - --hash=sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9 \ - --hash=sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9 \ - --hash=sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc \ - --hash=sha256:591ae9f2a647529ca990bc681daebdd52c8791ff06c2bfa05b65163e28102ef2 \ - --hash=sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4 \ - --hash=sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354 \ - --hash=sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50 \ - --hash=sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698 \ - --hash=sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9 \ - --hash=sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b \ - --hash=sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc \ - --hash=sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115 \ - --hash=sha256:7c3fb7d25180895632e5d3148dbdc29ea38ccb7fd210aa27acbd1201a1902c6e \ - --hash=sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485 \ - --hash=sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f \ - --hash=sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12 \ - --hash=sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025 \ - --hash=sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009 \ - --hash=sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d \ - --hash=sha256:949b8d66bc381ee8b007cd945914c721d9aba8e27f71959d750a46f7c282b20b \ - --hash=sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a \ - --hash=sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5 \ - --hash=sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f \ - --hash=sha256:a320721ab5a1aba0a233739394eb907f8c8da5c98c9181d1161e77a0c8e36f2d \ - --hash=sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1 \ - --hash=sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287 \ - --hash=sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6 \ - --hash=sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f \ - --hash=sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581 \ - --hash=sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed \ - --hash=sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b \ - --hash=sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c \ - --hash=sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026 \ - --hash=sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8 \ - --hash=sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676 \ - --hash=sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6 \ - --hash=sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e \ - --hash=sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d \ - --hash=sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d \ - --hash=sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01 \ - --hash=sha256:df2449253ef108a379b8b5d6b43f4b1a8e81a061d6537becd5582fba5f9196d7 \ - --hash=sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419 \ - --hash=sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795 \ - --hash=sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1 \ - --hash=sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5 \ - --hash=sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d \ - --hash=sha256:e8fc20152abba6b83724d7ff268c249fa196d8259ff481f3b1476383f8f24e42 \ - --hash=sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe \ - --hash=sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda \ - --hash=sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e \ - --hash=sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737 \ - --hash=sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523 \ - --hash=sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591 \ - --hash=sha256:f71a396b3bf33ecaa1626c255855702aca4d3d9fea5e051b41ac59a9c1c41edc \ - --hash=sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a \ - --hash=sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50 - # via mako -pcpp==1.30 \ - --hash=sha256:05fe08292b6da57f385001c891a87f40d6aa7f46787b03e8ba326d20a3297c6e \ - --hash=sha256:5af9fbce55f136d7931ae915fae03c34030a3b36c496e72d9636cedc8e2543a1 - # via -r requirements.in -pyparsing==3.3.2 \ - --hash=sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d \ - --hash=sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc - # via -r requirements.in +# Python dependencies for XRP Ledger code generation scripts +# +# These packages are required to run the code generation scripts that +# parse macro files and generate C++ wrapper classes. + +# C preprocessor for Python - used to preprocess macro files +pcpp>=1.30 + +# Parser combinator library - used to parse the macro DSL +pyparsing>=3.0.0 + +# Template engine - used to generate C++ code from templates +Mako>=1.2.0 diff --git a/cmake/scripts/codegen/templates/LedgerEntry.h.mako b/cmake/scripts/codegen/templates/LedgerEntry.h.mako index 63f5f39ef9..31029cd311 100644 --- a/cmake/scripts/codegen/templates/LedgerEntry.h.mako +++ b/cmake/scripts/codegen/templates/LedgerEntry.h.mako @@ -33,7 +33,7 @@ public: * @brief Construct a ${name} ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit ${name}(SLE::const_pointer sle) + explicit ${name}(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -168,7 +168,7 @@ ${field['typeData']['setter_type']} ${field['paramName']}${',' if i < len(requir * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - ${name}Builder(SLE::const_pointer sle) + ${name}Builder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ${tag}) { diff --git a/conan.lock b/conan.lock index 95424ff6c4..073ff0ffc3 100644 --- a/conan.lock +++ b/conan.lock @@ -1,39 +1,39 @@ { "version": "0.5", "requires": [ - "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb%1777558780.503", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", - "sqlite3/3.53.0#324ada52333108388a9a6108bfa96734%1776096494.149", + "sqlite3/3.51.0#66aa11eabd0e34954c5c1c061ad44abe%1774467355.988", "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1774398111.888", "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12", - "openssl/3.6.2#4789bbf131b77d0515d15e094c8f697f%1778071755.506", - "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1775040983.408", + "openssl/3.6.1#e6399de266349245a4542fc5f6c71552%1774458290.139", + "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1774883011.384", "mpt-crypto/0.3.0-rc1#468344c6855d4aeaa8bd31fb2c403f89%1776358155.918", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", "libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1765842973.03", - "libarchive/3.8.7#c446109bd1f1d8ba7936c94189bc50e6%1776147552.838", - "jemalloc/5.3.1#1fc58d55316041f10fbc1e8a2eae632a%1776700028.228", + "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", + "jemalloc/5.3.0#e951da9cf599e956cebc117880d2d9f8%1729241615.244", "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", "grpc/1.78.1#b1a9e74b145cc471bed4dc64dc6eb2c1%1774467387.342", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", - "boost/1.91.0#ea540ca2133d831b560036aa24dece3c%1778050991.9", + "boost/1.90.0#d5e8defe7355494953be18524a7f135b%1769454080.269", "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" ], "build_requires": [ - "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb%1777558780.503", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1774447376.964", "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", - "m4/1.4.19#4523e4347b55cd26ae918bd5770cab9a%1778062762.471", + "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183", "cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479", "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447", @@ -50,22 +50,22 @@ "lz4/1.10.0" ], "boost/[>=1.83.0 <1.91.0]": [ - "boost/1.91.0" + "boost/1.90.0" ], "sqlite3/[>=3.44 <4]": [ - "sqlite3/3.53.0" + "sqlite3/3.51.0" ], "boost/1.83.0": [ - "boost/1.91.0" + "boost/1.90.0" ], "lz4/[>=1.9.4 <2]": [ "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504" ], "openssl/3.5.5": [ - "openssl/3.6.2" + "openssl/3.6.1" ], "openssl/[>=3 <4]": [ - "openssl/3.6.2" + "openssl/3.6.1" ] }, "config_requires": [] diff --git a/conan/global.conf b/conan/global.conf index cc803dc801..37b329a5c5 100644 --- a/conan/global.conf +++ b/conan/global.conf @@ -3,5 +3,3 @@ core:non_interactive=True core.download:parallel={{ os.cpu_count() }} core.upload:parallel={{ os.cpu_count() }} -tools.files.download:retry=5 -tools.files.download:retry_wait=10 diff --git a/conan/profiles/ci b/conan/profiles/ci index ae93187026..c4c0898ad5 100644 --- a/conan/profiles/ci +++ b/conan/profiles/ci @@ -1 +1 @@ -include(sanitizers) + include(sanitizers) diff --git a/conan/profiles/sanitizers b/conan/profiles/sanitizers index 4a05fda734..800e6eb48c 100644 --- a/conan/profiles/sanitizers +++ b/conan/profiles/sanitizers @@ -3,120 +3,96 @@ include(default) {% set arch = detect_api.detect_arch() %} {% set sanitizers = os.getenv("SANITIZERS") %} -{% if not sanitizers %} -{# Sanitizers not configured; no additional settings needed #} -{% else %} +[conf] +{% if sanitizers %} + {% if compiler == "gcc" %} + {% if "address" in sanitizers or "thread" in sanitizers or "undefinedbehavior" in sanitizers %} + {% set sanitizer_list = [] %} + {% set defines = [] %} + {% set model_code = "" %} + {% set extra_cxxflags = ["-fno-omit-frame-pointer", "-O1", "-Wno-stringop-overflow"] %} -{% if compiler == "msvc" %} - {{ "Sanitizers are not supported on Windows/MSVC. Please unset the SANITIZERS environment variable." }} -{% endif %} + {% if "address" in sanitizers %} + {% set _ = sanitizer_list.append("address") %} + {% if arch == "x86_64" %} + {% set model_code = "-mcmodel=large" %} + {% endif %} + {% set _ = defines.append("BOOST_USE_ASAN")%} + {% set _ = defines.append("BOOST_USE_UCONTEXT")%} + {% elif "thread" in sanitizers %} + {% set _ = sanitizer_list.append("thread") %} + {% if arch == "x86_64" %} + {% set model_code = "-mcmodel=medium" %} + {% endif %} + {% set _ = extra_cxxflags.append("-Wno-tsan") %} + {% set _ = defines.append("BOOST_USE_TSAN")%} + {% set _ = defines.append("BOOST_USE_UCONTEXT")%} + {% endif %} -{% set known_sanitizers = ["address", "thread", "undefinedbehavior"] %} -{% set provided_sanitizers = [] %} -{% for san in sanitizers.split(",") %} - {% set san = san.strip() %} - {% if san not in known_sanitizers %} - {{ "Unknown sanitizer in SANITIZERS: " ~ san }} - {% endif %} - {% set _ = provided_sanitizers.append(san) %} -{% endfor %} + {% if "undefinedbehavior" in sanitizers %} + {% set _ = sanitizer_list.append("undefined") %} + {% set _ = sanitizer_list.append("float-divide-by-zero") %} + {% endif %} -{% set enable_asan = "address" in provided_sanitizers %} -{% set enable_tsan = "thread" in provided_sanitizers %} -{% set enable_ubsan = "undefinedbehavior" in provided_sanitizers %} + {% set sanitizer_flags = "-fsanitize=" ~ ",".join(sanitizer_list) ~ " " ~ model_code %} -{% if enable_asan and enable_tsan %} - {{ "AddressSanitizer and ThreadSanitizer are incompatible and cannot be enabled simultaneously." }} -{% endif %} + tools.build:cxxflags+=['{{sanitizer_flags}} {{" ".join(extra_cxxflags)}}'] + tools.build:sharedlinkflags+=['{{sanitizer_flags}}'] + tools.build:exelinkflags+=['{{sanitizer_flags}}'] + tools.build:defines+={{defines}} + {% endif %} + {% elif compiler == "apple-clang" or compiler == "clang" %} + {% if "address" in sanitizers or "thread" in sanitizers or "undefinedbehavior" in sanitizers %} + {% set sanitizer_list = [] %} + {% set defines = [] %} + {% set extra_cxxflags = ["-fno-omit-frame-pointer", "-O1"] %} -{% set sanitizer_types = [] %} -{% set defines = [] %} + {% if "address" in sanitizers %} + {% set _ = sanitizer_list.append("address") %} + {% set _ = defines.append("BOOST_USE_ASAN")%} + {% set _ = defines.append("BOOST_USE_UCONTEXT")%} + {% elif "thread" in sanitizers %} + {% set _ = sanitizer_list.append("thread") %} + {% set _ = defines.append("BOOST_USE_TSAN")%} + {% set _ = defines.append("BOOST_USE_UCONTEXT")%} + {% endif %} -{% if enable_asan %} - {% set _ = sanitizer_types.append("address") %} - {% set _ = defines.append("BOOST_USE_ASAN") %} - {% set _ = defines.append("BOOST_USE_UCONTEXT") %} -{% elif enable_tsan %} - {% set _ = sanitizer_types.append("thread") %} - {% set _ = defines.append("BOOST_USE_TSAN") %} - {% set _ = defines.append("BOOST_USE_UCONTEXT") %} -{% endif %} + {% if "undefinedbehavior" in sanitizers %} + {% set _ = sanitizer_list.append("undefined") %} + {% set _ = sanitizer_list.append("float-divide-by-zero") %} + {% set _ = sanitizer_list.append("unsigned-integer-overflow") %} + {% endif %} -{% if enable_ubsan %} - {% set _ = sanitizer_types.append("undefined") %} - {% set _ = sanitizer_types.append("float-divide-by-zero") %} - {# Clang supports additional UB checks beyond the GCC baseline #} - {% if compiler == "clang" or compiler == "apple-clang" %} - {% set _ = sanitizer_types.append("unsigned-integer-overflow") %} - {% endif %} -{% endif %} + {% set sanitizer_flags = "-fsanitize=" ~ ",".join(sanitizer_list) %} -{# Frame pointer required for meaningful stack traces; -O1 for reasonable performance #} -{% set compile_flags = ["-fno-omit-frame-pointer", "-O1"] %} - -{% if compiler == "gcc" %} - {# Suppress false positive warnings with GCC #} - {% set _ = compile_flags.append("-Wno-stringop-overflow") %} - - {% set relocation_flags = [] %} - - {% if arch == "x86_64" and enable_asan %} - {# Large code model prevents relocation errors in instrumented ASAN binaries #} - {% set _ = compile_flags.append("-mcmodel=large") %} - {% set _ = relocation_flags.append("-mcmodel=large") %} - {% elif enable_tsan %} - {# GCC doesn't support atomic_thread_fence with TSAN; suppress warnings #} - {% set _ = compile_flags.append("-Wno-tsan") %} - {% if arch == "x86_64" %} - {# Medium code model for TSAN; large is incompatible #} - {% set _ = compile_flags.append("-mcmodel=medium") %} - {% set _ = relocation_flags.append("-mcmodel=medium") %} + tools.build:cxxflags+=['{{sanitizer_flags}} {{" ".join(extra_cxxflags)}}'] + tools.build:sharedlinkflags+=['{{sanitizer_flags}}'] + tools.build:exelinkflags+=['{{sanitizer_flags}}'] + tools.build:defines+={{defines}} {% endif %} {% endif %} - - {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} - {% set _ = compile_flags.append(fsanitize) %} - {% set _ = relocation_flags.append(fsanitize) %} - - {% set sanitizer_compiler_flags = " ".join(compile_flags) %} - {% set sanitizer_linker_flags = " ".join(relocation_flags) %} -{% elif compiler == "clang" or compiler == "apple-clang" %} - {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} - {% set _ = compile_flags.append(fsanitize) %} - - {% set sanitizer_compiler_flags = " ".join(compile_flags) %} - {% set sanitizer_linker_flags = fsanitize %} {% endif %} -[conf] -tools.build:defines+={{defines}} -tools.build:cxxflags+=['{{sanitizer_compiler_flags}}'] -tools.build:sharedlinkflags+=['{{sanitizer_linker_flags}}'] -tools.build:exelinkflags+=['{{sanitizer_linker_flags}}'] - tools.info.package_id:confs+=["tools.build:cxxflags", "tools.build:exelinkflags", "tools.build:sharedlinkflags", "tools.build:defines"] -# &: means "apply only to the consumer/root package" -&:tools.cmake.cmaketoolchain:extra_variables={"SANITIZERS": "{{sanitizers}}", "SANITIZERS_COMPILER_FLAGS": "{{sanitizer_compiler_flags}}", "SANITIZERS_LINKER_FLAGS": "{{sanitizer_linker_flags}}"} - [options] -{% if enable_asan %} - # Build Boost.Context with ucontext backend (not fcontext) so that - # ASAN fiber-switching annotations (__sanitizer_start/finish_switch_fiber) - # are compiled into the library. fcontext (assembly) has no ASAN support. - # define=BOOST_USE_ASAN=1 is critical: it must be defined when building - # Boost.Context itself so the ucontext backend compiles in the ASAN annotations. - boost/*:extra_b2_flags=context-impl=ucontext address-sanitizer=on define=BOOST_USE_ASAN=1 - boost/*:without_context=False - # Boost stacktrace fails to build with some sanitizers - boost/*:without_stacktrace=True -{% elif enable_tsan %} - # Build Boost.Context with ucontext backend for TSAN. fcontext (assembly) - # has no TSAN annotations, so without this the BOOST_USE_TSAN/BOOST_USE_UCONTEXT - # defines in [conf] would be ineffective. - boost/*:extra_b2_flags=context-impl=ucontext thread-sanitizer=on define=BOOST_USE_TSAN=1 - boost/*:without_context=False - boost/*:without_stacktrace=True -{% endif %} - +{% if sanitizers %} + {% if "address" in sanitizers %} + # Build Boost.Context with ucontext backend (not fcontext) so that + # ASAN fiber-switching annotations (__sanitizer_start/finish_switch_fiber) + # are compiled into the library. fcontext (assembly) has no ASAN support. + # define=BOOST_USE_ASAN=1 is critical: it must be defined when building + # Boost.Context itself so the ucontext backend compiles in the ASAN annotations. + boost/*:extra_b2_flags=context-impl=ucontext address-sanitizer=on define=BOOST_USE_ASAN=1 + boost/*:without_context=False + # Boost stacktrace fails to build with some sanitizers + boost/*:without_stacktrace=True + {% elif "thread" in sanitizers %} + # Build Boost.Context with ucontext backend for TSAN. fcontext (assembly) + # has no TSAN annotations, so without this the BOOST_USE_TSAN/BOOST_USE_UCONTEXT + # defines in [conf] would be ineffective. + boost/*:extra_b2_flags=context-impl=ucontext thread-sanitizer=on define=BOOST_USE_TSAN=1 + boost/*:without_context=False + boost/*:without_stacktrace=True + {% endif %} {% endif %} diff --git a/conanfile.py b/conanfile.py index 6a9299480b..042092bfdb 100644 --- a/conanfile.py +++ b/conanfile.py @@ -1,3 +1,4 @@ +import os import re from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout @@ -29,13 +30,13 @@ class Xrpl(ConanFile): requires = [ "ed25519/2015.03", "grpc/1.78.1", - "libarchive/3.8.7", + "libarchive/3.8.1", "mpt-crypto/0.3.0-rc1", "nudb/2.0.9", - "openssl/3.6.2", + "openssl/3.6.1", "secp256k1/0.7.1", "soci/4.0.3", - "zlib/1.3.2", + "zlib/1.3.1", ] test_requires = [ @@ -57,7 +58,6 @@ class Xrpl(ConanFile): "tests": False, "unity": False, "xrpld": False, - "boost/*:without_cobalt": True, "boost/*:without_context": False, "boost/*:without_coroutine": True, "boost/*:without_coroutine2": False, @@ -131,13 +131,13 @@ class Xrpl(ConanFile): self.options["boost"].without_cobalt = True def requirements(self): - self.requires("boost/1.91.0", force=True, transitive_headers=True) + self.requires("boost/1.90.0", force=True, transitive_headers=True) self.requires("date/3.0.4", transitive_headers=True) self.requires("lz4/1.10.0", force=True) self.requires("protobuf/6.33.5", force=True) - self.requires("sqlite3/3.53.0", force=True) + self.requires("sqlite3/3.51.0", force=True) if self.options.jemalloc: - self.requires("jemalloc/5.3.1") + self.requires("jemalloc/5.3.0") if self.options.rocksdb: self.requires("rocksdb/10.5.1") self.requires("xxhash/0.8.3", transitive_headers=True) diff --git a/cspell.config.yaml b/cspell.config.yaml index 2461f8e846..2f3c453319 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -64,7 +64,6 @@ words: - Bougalis - Britto - Btrfs - - Buildx - canonicality - changespq - checkme @@ -73,7 +72,6 @@ words: - citardauq - clawback - clawbacks - - cmaketoolchain - coeffs - coldwallet - compr @@ -95,23 +93,19 @@ words: - dcmake - dearmor - decryptor - - dedented - deleteme - demultiplexer - deserializaton - desync - desynced - determ - - disablerepo - distro - doxyfile - dxrpl - elgamal - enabled - - enablerepo - endmacro - exceptioned - - EXPECT_STREQ - Falco - fcontext - finalizers @@ -124,7 +118,6 @@ words: - gcovr - ghead - Gnutella - - godexsoft - gpgcheck - gpgkey - hotwallet @@ -170,7 +163,6 @@ words: - Merkle - Metafuncton - misprediction - - missingok - mptbalance - MPTDEX - mptflags @@ -202,15 +194,11 @@ words: - NOLINT - NOLINTNEXTLINE - nonxrp - - noreplace - noripple - - nostdinc - - notifempty - nudb - nullptr - nunl - Nyffenegger - - onlatest - ostr - pargs - partitioner @@ -227,7 +215,6 @@ words: - preauthorize - preauthorizes - preclaim - - preun - protobuf - protos - ptrs @@ -265,15 +252,12 @@ words: - sfields - shamap - shamapitem - - shfmt - - shlibs - sidechain - SIGGOOD - sle - sles - soci - socidb - - SRPMS - sslws - statsd - STATSDCOLLECTOR @@ -302,8 +286,8 @@ words: - txn - txns - txs - - ubsan - UBSAN + - ubsan - umant - unacquired - unambiguity @@ -311,7 +295,6 @@ words: - unauthorizing - unergonomic - unfetched - - unfindable - unflatten - unfund - unimpair @@ -341,6 +324,7 @@ words: - xbridge - xchain - ximinez + - EXPECT_STREQ - XMACRO - xrpkuwait - xrpl @@ -348,4 +332,3 @@ words: - xrplf - xxhash - xxhasher - - CGNAT diff --git a/docker/loader-path.sh b/docker/loader-path.sh deleted file mode 100755 index b8b9f0de51..0000000000 --- a/docker/loader-path.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -case "$(uname -m)" in - x86_64) LOADER=/lib64/ld-linux-x86-64.so.2 ;; - aarch64) LOADER=/lib/ld-linux-aarch64.so.1 ;; - *) - echo "Unsupported arch: $(uname -m)" >&2 - exit 1 - ;; -esac - -echo "${LOADER}" diff --git a/docker/nix.Dockerfile b/docker/nix.Dockerfile deleted file mode 100644 index 3c5dbcb734..0000000000 --- a/docker/nix.Dockerfile +++ /dev/null @@ -1,102 +0,0 @@ -ARG BASE_IMAGE=nixos/nix:latest - -# Nix builder -FROM nixos/nix:latest AS builder-source - -RUN mkdir -p ~/.config/nix && \ - echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf - -# Copy our source and setup our working dir. -COPY nix/ci-env.nix /tmp/build/nix/ci-env.nix -COPY nix/packages.nix /tmp/build/nix/packages.nix -COPY nix/utils.nix /tmp/build/nix/utils.nix -COPY flake.nix /tmp/build/ -COPY flake.lock /tmp/build/ -WORKDIR /tmp/build - -FROM builder-source AS builder - -# Build our Nix CI environment (all build tools in a single store path) -RUN nix \ - --option filter-syscalls false \ - build - -# Copy the Nix store closure into a directory. The Nix store closure is the -# entire set of Nix store values that we need for our build. -RUN mkdir /tmp/nix-store-closure && \ - cp -R $(nix-store -qR result/) /tmp/nix-store-closure - -# Final image -FROM ${BASE_IMAGE} AS final - -ARG BASE_IMAGE - -# bash is not located at /bin/bash in nixos/nix, so we need to create a symlink to it. -RUN if [ -d /nix ]; then \ - ln -s /root/.nix-profile/bin/bash /bin/bash; \ - fi - -# Use Bash as the default shell for RUN commands, using the options -# `set -o errexit -o pipefail`, and as the entrypoint. -SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] -ENTRYPOINT ["/bin/bash"] - -# Copy /nix/store and the env symlink tree -COPY --from=builder /tmp/nix-store-closure /nix/store -COPY --from=builder /tmp/build/result /nix/ci-env - -ENV PATH="/nix/ci-env/bin:${PATH}" - -# Externally-built dynamically-linked ELF binaries hard-code the loader path -# (e.g. /lib64/ld-linux-x86-64.so.2) in their PT_INTERP header. Install it -# from the Nix store when the base image doesn't already provide one. -COPY docker/loader-path.sh /tmp/loader-path.sh - -RUN <&2; exit 1; } - mkdir -p "$(dirname "${target}")" - cp "${src}" "${target}" -fi -EOF - -RUN < -#include -#include - -#if defined(__clang__) || defined(__GNUC__) -__attribute__((noinline)) -#elif defined(_MSC_VER) -__declspec(noinline) -#endif -int -read_after_free(volatile int* array, std::size_t index) -{ - std::atomic_signal_fence(std::memory_order_seq_cst); - int value = array[index]; - std::atomic_signal_fence(std::memory_order_seq_cst); - return value; -} - -int -main() -{ - int* array = new int[5]{10, 20, 30, 40, 50}; - delete[] array; - - std::cout << "Value at index 2: " << read_after_free(array, 2) << std::endl; - - return 0; -} diff --git a/docker/test_files/cpp_sources/regular.cpp b/docker/test_files/cpp_sources/regular.cpp deleted file mode 100644 index 637dafa1fd..0000000000 --- a/docker/test_files/cpp_sources/regular.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include -#include -#include - -static std::mutex gMutex; - -void -worker(int id) -{ - std::lock_guard lock(gMutex); - std::cout << "Hello from thread " << id << "\n"; -} - -int -main() -{ - constexpr int kNumThreads = 10; - std::vector threads; - threads.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) - threads.emplace_back(worker, i); - for (auto& t : threads) - t.join(); - - std::cout << "Hello from main thread\n"; - return 0; -} diff --git a/docker/test_files/cpp_sources/tsan.cpp b/docker/test_files/cpp_sources/tsan.cpp deleted file mode 100644 index 34b0990a6d..0000000000 --- a/docker/test_files/cpp_sources/tsan.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include - -static int kCounter = 0; - -void -increment() -{ - for (int i = 0; i < 100'000; ++i) - { - ++kCounter; - } -} - -int -main() -{ - std::thread t1(increment); - std::thread t2(increment); - - t1.join(); - t2.join(); - - std::cout << "Final counter value: " << kCounter << std::endl; - return 0; -} diff --git a/docker/test_files/cpp_sources/ubsan.cpp b/docker/test_files/cpp_sources/ubsan.cpp deleted file mode 100644 index db86119070..0000000000 --- a/docker/test_files/cpp_sources/ubsan.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include -#include - -int -main() -{ - int maxInt = std::numeric_limits::max(); - int volatile one = 1; - std::cout << "Current max: " << maxInt << std::endl; - int overflowed = maxInt + one; - std::cout << "Overflowed result: " << overflowed << std::endl; - return 0; -} diff --git a/docker/test_files/run-test-binaries.sh b/docker/test_files/run-test-binaries.sh deleted file mode 100755 index 6e8f0a931c..0000000000 --- a/docker/test_files/run-test-binaries.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash -# Run pre-compiled sanitizer binaries and confirm each emits its expected diagnostic. -# Binaries must already exist in with the layout: -# -g++ and -clang++ for name in {regular,asan,tsan,ubsan} - -set -eo pipefail - -bins_dir="${1:?usage: $0 }" - -# Run a binary and verify its exit code and output. -# Usage: run -function run() { - local binary="${1}" - local expected_output="${2}" - local expected_rc="${3}" - - local out_file - out_file="$(mktemp)" - - echo "=== Run ${binary} ===" - local rc=0 - "${binary}" >"${out_file}" 2>&1 || rc=$? - - cat "${out_file}" - - if [ "${expected_rc}" = "nonzero" ]; then - if [ "${rc}" -eq 0 ]; then - echo "ERROR: expected non-zero exit code from ${binary}, got ${rc}" >&2 - exit 1 - fi - elif [ "${rc}" -ne "${expected_rc}" ]; then - echo "ERROR: expected exit code ${expected_rc} from ${binary}, got ${rc}" >&2 - exit 1 - fi - - grep -q "${expected_output}" "${out_file}" || - { - echo "ERROR: expected '${expected_output}' from ${binary}" >&2 - exit 1 - } - echo "OK: '${expected_output}' detected" -} - -declare -A expect=( - [regular]="Hello from main thread" - - [asan]="heap-use-after-free" - [tsan]="data race" - [ubsan]="signed integer overflow" -) - -for compiler in g++ clang++; do - for name in regular asan tsan ubsan; do - binary="${bins_dir}/${name}-${compiler}" - if [ "${name}" = "regular" ]; then - expected_rc=0 - else - expected_rc=nonzero - fi - run "${binary}" "${expect[$name]}" "${expected_rc}" - done -done diff --git a/docs/build/sanitizers.md b/docs/build/sanitizers.md index 6e7284fd06..e4949bcf86 100644 --- a/docs/build/sanitizers.md +++ b/docs/build/sanitizers.md @@ -1,17 +1,15 @@ # Sanitizer Configuration for Xrpld -This document explains how to properly configure and run sanitizers (`AddressSanitizer`, `UndefinedBehaviorSanitizer`, `ThreadSanitizer`) with the xrpld project. +This document explains how to properly configure and run sanitizers (AddressSanitizer, undefinedbehaviorSanitizer, ThreadSanitizer) with the xrpld project. Corresponding suppression files are located in the `sanitizers/suppressions` directory. -> [!CAUTION] -> Do not mix Address and Thread sanitizers - they are incompatible. -> Also, we don't yet support MSVC sanitizers, so this is only for Clang/GCC builds. - - [Sanitizer Configuration for Xrpld](#sanitizer-configuration-for-xrpld) - [Building with Sanitizers](#building-with-sanitizers) - [Summary](#summary) - [Build steps:](#build-steps) - [Install dependencies](#install-dependencies) + - [Call CMake](#call-cmake) + - [Build](#build) - [Running Tests with Sanitizers](#running-tests-with-sanitizers) - [AddressSanitizer (ASAN)](#addresssanitizer-asan) - [ThreadSanitizer (TSan)](#threadsanitizer-tsan) @@ -35,13 +33,9 @@ Corresponding suppression files are located in the `sanitizers/suppressions` dir Follow the same instructions as mentioned in [BUILD.md](../../BUILD.md) but with the following changes: 1. Make sure you have a clean build directory. -2. Set the `SANITIZERS` environment variable before calling `conan install`. Only set it once. +2. Set the `SANITIZERS` environment variable before calling conan install and cmake. Only set it once. Make sure both conan and cmake read the same values. Example: `export SANITIZERS=address,undefinedbehavior` -3. Use `--profile:all sanitizers` with Conan to build dependencies with sanitizer instrumentation. - - > [!NOTE] - > Building with sanitizer-instrumented dependencies is slower but produces fewer false positives. - +3. Optionally use `--profile:all sanitizers` with Conan to build dependencies with sanitizer instrumentation. [!NOTE]Building with sanitizer-instrumented dependencies is slower but produces fewer false positives. 4. Set `ASAN_OPTIONS`, `LSAN_OPTIONS`, `UBSAN_OPTIONS` and `TSAN_OPTIONS` environment variables to configure sanitizer behavior when running executables. [More details below](#running-tests-with-sanitizers). --- @@ -57,13 +51,36 @@ cd .build #### Install dependencies -The `SANITIZERS` environment variable is used during `conan install` command. +The `SANITIZERS` environment variable is used by both Conan and CMake. ```bash -SANITIZERS=address,undefinedbehavior conan install .. --output-folder . --build missing --settings build_type=Debug --profile:all sanitizers +export SANITIZERS=address,undefinedbehavior +# Standard build (without instrumenting dependencies) +conan install .. --output-folder . --build missing --settings build_type=Debug + +# Or with sanitizer-instrumented dependencies (takes longer but fewer false positives) +conan install .. --output-folder . --profile:all sanitizers --build missing --settings build_type=Debug ``` -Proceed with the rest of the build instructions as mentioned in [BUILD.md](../../BUILD.md). +[!CAUTION] +Do not mix Address and Thread sanitizers - they are incompatible. + +Since you already set the `SANITIZERS` environment variable when running Conan, same values will be read for the next part. + +#### Call CMake + +```bash +cmake .. -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ + -DCMAKE_BUILD_TYPE=Debug \ + -Dtests=ON -Dxrpld=ON +``` + +#### Build + +```bash +cmake --build . --parallel 4 +``` ## Running Tests with Sanitizers diff --git a/flake.lock b/flake.lock index 3149f3feed..fd43f5b683 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1777954456, - "narHash": "sha256-hGdgeU2Nk87RAuZyYjyDjFL6LK7dAZN5RE9+hrDTkDU=", + "lastModified": 1769461804, + "narHash": "sha256-6h5sROT/3CTHvzPy9koKBmoCa2eJKh4fzQK8eYFEgl8=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "549bd84d6279f9852cae6225e372cc67fb91a4c1", + "rev": "b579d443b37c9c5373044201ea77604e37e748c8", "type": "github" }, "original": { @@ -15,27 +15,9 @@ "type": "indirect" } }, - "nixpkgs-custom-glibc": { - "flake": false, - "locked": { - "lastModified": 1593520194, - "narHash": "sha256-+TZW+2I7kLL9JglPNOagm1ywjf9ua0JYGoptq/dzVn0=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "9cd98386a38891d1074fc18036b842dc4416f562", - "type": "github" - }, - "original": { - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "9cd98386a38891d1074fc18036b842dc4416f562", - "type": "github" - } - }, "root": { "inputs": { - "nixpkgs": "nixpkgs", - "nixpkgs-custom-glibc": "nixpkgs-custom-glibc" + "nixpkgs": "nixpkgs" } } }, diff --git a/flake.nix b/flake.nix index 3b3ec7ea08..4c500f1933 100644 --- a/flake.nix +++ b/flake.nix @@ -2,24 +2,15 @@ description = "Nix related things for xrpld"; inputs = { nixpkgs.url = "nixpkgs/nixos-unstable"; - # nixpkgs snapshot (2020-06-30) that shipped glibc 2.31 as the primary - # version — matches the system libc on Ubuntu 20.04 LTS. Imported - # manually (flake = false) because this revision predates nixpkgs' - # own flake.nix. - nixpkgs-custom-glibc = { - url = "github:NixOS/nixpkgs/9cd98386a38891d1074fc18036b842dc4416f562"; - flake = false; - }; }; outputs = - { nixpkgs, nixpkgs-custom-glibc, ... }: + { nixpkgs, ... }: let - forEachSystem = import ./nix/utils.nix { inherit nixpkgs nixpkgs-custom-glibc; }; + forEachSystem = (import ./nix/utils.nix { inherit nixpkgs; }).forEachSystem; in { devShells = forEachSystem (import ./nix/devshell.nix); - packages = forEachSystem (import ./nix/ci-env.nix); formatter = forEachSystem ({ pkgs, ... }: pkgs.nixfmt); }; } diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h index 3796151777..74a0e76eef 100644 --- a/include/xrpl/basics/Expected.h +++ b/include/xrpl/basics/Expected.h @@ -148,23 +148,17 @@ public: } [[nodiscard]] constexpr E const& - error() const& + error() const { return Base::error(); } - [[nodiscard]] constexpr E& - error() & + constexpr E& + error() { return Base::error(); } - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - constexpr explicit operator bool() const { @@ -221,23 +215,17 @@ public: } [[nodiscard]] constexpr E const& - error() const& + error() const { return Base::error(); } - [[nodiscard]] constexpr E& - error() & + constexpr E& + error() { return Base::error(); } - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - constexpr explicit operator bool() const { diff --git a/include/xrpl/basics/IntrusivePointer.h b/include/xrpl/basics/IntrusivePointer.h index d66c340d3f..06ee3e5bb4 100644 --- a/include/xrpl/basics/IntrusivePointer.h +++ b/include/xrpl/basics/IntrusivePointer.h @@ -406,8 +406,8 @@ private: // 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. std::uintptr_t tp_{0}; - static constexpr std::uintptr_t kTagMask = 1; - static constexpr std::uintptr_t kPtrMask = ~kTagMask; + static constexpr std::uintptr_t kTAG_MASK = 1; + static constexpr std::uintptr_t kPTR_MASK = ~kTAG_MASK; private: /** Return the raw pointer held by this object. diff --git a/include/xrpl/basics/IntrusivePointer.ipp b/include/xrpl/basics/IntrusivePointer.ipp index 8344a3e613..f229df8b27 100644 --- a/include/xrpl/basics/IntrusivePointer.ipp +++ b/include/xrpl/basics/IntrusivePointer.ipp @@ -567,14 +567,14 @@ template bool SharedWeakUnion::isStrong() const { - return (tp_ & kTagMask) == 0u; + return (tp_ & kTAG_MASK) == 0u; } template bool SharedWeakUnion::isWeak() const { - return (tp_ & kTagMask) != 0u; + return (tp_ & kTAG_MASK) != 0u; } template @@ -641,7 +641,7 @@ template T* SharedWeakUnion::unsafeGetRawPtr() const { - return reinterpret_cast(tp_ & kPtrMask); + return reinterpret_cast(tp_ & kPTR_MASK); } template @@ -650,7 +650,7 @@ SharedWeakUnion::unsafeSetRawPtr(T* p, RefStrength rs) { tp_ = reinterpret_cast(p); if (tp_ && rs == RefStrength::Weak) - tp_ |= kTagMask; + tp_ |= kTAG_MASK; } template diff --git a/include/xrpl/basics/IntrusiveRefCounts.h b/include/xrpl/basics/IntrusiveRefCounts.h index 0b00f1d5b1..f0689197d7 100644 --- a/include/xrpl/basics/IntrusiveRefCounts.h +++ b/include/xrpl/basics/IntrusiveRefCounts.h @@ -98,11 +98,11 @@ private: // enough for strong pointers and 14 bit counts are enough for weak // pointers. Use type aliases to make it easy to switch types. using CountType = std::uint16_t; - static constexpr size_t kStrongCountNumBits = sizeof(CountType) * 8; - static constexpr size_t kWeakCountNumBits = kStrongCountNumBits - 2; + static constexpr size_t kSTRONG_COUNT_NUM_BITS = sizeof(CountType) * 8; + static constexpr size_t kWEAK_COUNT_NUM_BITS = kSTRONG_COUNT_NUM_BITS - 2; using FieldType = std::uint32_t; - static constexpr size_t kFieldTypeBits = sizeof(FieldType) * 8; - static constexpr FieldType kOne = 1; + static constexpr size_t kFIELD_TYPE_BITS = sizeof(FieldType) * 8; + static constexpr FieldType kONE = 1; /** `refCounts` consists of four fields that are treated atomically: @@ -137,21 +137,21 @@ private: */ - mutable std::atomic refCounts_{kStrongDelta}; + mutable std::atomic refCounts_{kSTRONG_DELTA}; /** Amount to change the strong count when adding or releasing a reference Note: The strong count is stored in the low `StrongCountNumBits` bits of refCounts */ - static constexpr FieldType kStrongDelta = 1; + static constexpr FieldType kSTRONG_DELTA = 1; /** Amount to change the weak count when adding or releasing a reference Note: The weak count is stored in the high `WeakCountNumBits` bits of refCounts */ - static constexpr FieldType kWeakDelta = (kOne << kStrongCountNumBits); + static constexpr FieldType kWEAK_DELTA = (kONE << kSTRONG_COUNT_NUM_BITS); /** Flag that is set when the partialDestroy function has started running (or is about to start running). @@ -159,33 +159,34 @@ private: See description of the `refCounts` field for a fuller description of this field. */ - static constexpr FieldType kPartialDestroyStartedMask = (kOne << (kFieldTypeBits - 1)); + static constexpr FieldType kPARTIAL_DESTROY_STARTED_MASK = (kONE << (kFIELD_TYPE_BITS - 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 kPartialDestroyFinishedMask = (kOne << (kFieldTypeBits - 2)); + static constexpr FieldType kPARTIAL_DESTROY_FINISHED_MASK = (kONE << (kFIELD_TYPE_BITS - 2)); /** Mask that will zero out all the `count` bits and leave the tag bits unchanged. */ - static constexpr FieldType kTagMask = kPartialDestroyStartedMask | kPartialDestroyFinishedMask; + static constexpr FieldType kTAG_MASK = + kPARTIAL_DESTROY_STARTED_MASK | kPARTIAL_DESTROY_FINISHED_MASK; /** Mask that will zero out the `tag` bits and leave the count bits unchanged. */ - static constexpr FieldType kValueMask = ~kTagMask; + static constexpr FieldType kVALUE_MASK = ~kTAG_MASK; /** Mask that will zero out everything except the strong count. */ - static constexpr FieldType kStrongMask = ((kOne << kStrongCountNumBits) - 1) & kValueMask; + static constexpr FieldType kSTRONG_MASK = ((kONE << kSTRONG_COUNT_NUM_BITS) - 1) & kVALUE_MASK; /** Mask that will zero out everything except the weak count. */ - static constexpr FieldType kWeakMask = - (((kOne << kWeakCountNumBits) - 1) << kStrongCountNumBits) & kValueMask; + static constexpr FieldType kWEAK_MASK = + (((kONE << kWEAK_COUNT_NUM_BITS) - 1) << kSTRONG_COUNT_NUM_BITS) & kVALUE_MASK; /** Unpack the count and tag fields from the packed atomic integer form. */ struct RefCountPair @@ -210,29 +211,29 @@ private: [[nodiscard]] FieldType combinedValue() const noexcept; - static constexpr CountType kMaxStrongValue = - static_cast((kOne << kStrongCountNumBits) - 1); - static constexpr CountType kMaxWeakValue = - static_cast((kOne << kWeakCountNumBits) - 1); + static constexpr CountType kMAX_STRONG_VALUE = + static_cast((kONE << kSTRONG_COUNT_NUM_BITS) - 1); + static constexpr CountType kMAX_WEAK_VALUE = + static_cast((kONE << kWEAK_COUNT_NUM_BITS) - 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). */ - static constexpr CountType kCheckStrongMaxValue = kMaxStrongValue - 32; - static constexpr CountType kCheckWeakMaxValue = kMaxWeakValue - 32; + static constexpr CountType kCHECK_STRONG_MAX_VALUE = kMAX_STRONG_VALUE - 32; + static constexpr CountType kCHECK_WEAK_MAX_VALUE = kMAX_WEAK_VALUE - 32; }; }; inline void IntrusiveRefCounts::addStrongRef() const noexcept { - refCounts_.fetch_add(kStrongDelta, std::memory_order_acq_rel); + refCounts_.fetch_add(kSTRONG_DELTA, std::memory_order_acq_rel); } inline void IntrusiveRefCounts::addWeakRef() const noexcept { - refCounts_.fetch_add(kWeakDelta, std::memory_order_acq_rel); + refCounts_.fetch_add(kWEAK_DELTA, std::memory_order_acq_rel); } inline ReleaseStrongRefAction @@ -251,10 +252,10 @@ IntrusiveRefCounts::releaseStrongRef() const { RefCountPair const prevVal{prevIntVal}; XRPL_ASSERT( - (prevVal.strong >= kStrongDelta), + (prevVal.strong >= kSTRONG_DELTA), "xrpl::IntrusiveRefCounts::releaseStrongRef : previous ref " "higher than new"); - auto nextIntVal = prevIntVal - kStrongDelta; + auto nextIntVal = prevIntVal - kSTRONG_DELTA; ReleaseStrongRefAction action = NoOp; if (prevVal.strong == 1) { @@ -264,7 +265,7 @@ IntrusiveRefCounts::releaseStrongRef() const } else { - nextIntVal |= kPartialDestroyStartedMask; + nextIntVal |= kPARTIAL_DESTROY_STARTED_MASK; action = PartialDestroy; } } @@ -275,7 +276,7 @@ IntrusiveRefCounts::releaseStrongRef() const // count to zero can start a partial destroy, and that can't happen // twice. XRPL_ASSERT( - (action == NoOp) || !(prevIntVal & kPartialDestroyStartedMask), + (action == NoOp) || !(prevIntVal & kPARTIAL_DESTROY_STARTED_MASK), "xrpl::IntrusiveRefCounts::releaseStrongRef : not in partial " "destroy"); return action; @@ -288,8 +289,8 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const { using enum ReleaseStrongRefAction; - static_assert(kWeakDelta > kStrongDelta); - static constexpr auto kDelta = kWeakDelta - kStrongDelta; + static_assert(kWEAK_DELTA > kSTRONG_DELTA); + auto constexpr kDELTA = kWEAK_DELTA - kSTRONG_DELTA; auto prevIntVal = refCounts_.load(std::memory_order_acquire); // This loop will almost always run once. The loop is needed to atomically // change the counts and flags (the count could be atomically changed, but @@ -311,7 +312,7 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const "xrpl::IntrusiveRefCounts::addWeakReleaseStrongRef : not in " "partial destroy"); - auto nextIntVal = prevIntVal + kDelta; + auto nextIntVal = prevIntVal + kDELTA; ReleaseStrongRefAction action = NoOp; if (prevVal.strong == 1) { @@ -321,14 +322,14 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const } else { - nextIntVal |= kPartialDestroyStartedMask; + nextIntVal |= kPARTIAL_DESTROY_STARTED_MASK; action = PartialDestroy; } } if (refCounts_.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel)) { XRPL_ASSERT( - (!(prevIntVal & kPartialDestroyStartedMask)), + (!(prevIntVal & kPARTIAL_DESTROY_STARTED_MASK)), "xrpl::IntrusiveRefCounts::addWeakReleaseStrongRef : not " "started partial destroy"); return action; @@ -339,7 +340,7 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const inline ReleaseWeakRefAction IntrusiveRefCounts::releaseWeakRef() const { - auto prevIntVal = refCounts_.fetch_sub(kWeakDelta, std::memory_order_acq_rel); + auto prevIntVal = refCounts_.fetch_sub(kWEAK_DELTA, std::memory_order_acq_rel); RefCountPair prev = prevIntVal; if (prev.weak == 1 && prev.strong == 0) { @@ -356,7 +357,7 @@ IntrusiveRefCounts::releaseWeakRef() const { // partial destroy MUST finish before running a full destroy (when // using weak pointers) - refCounts_.wait(prevIntVal - kWeakDelta, std::memory_order_acquire); + refCounts_.wait(prevIntVal - kWEAK_DELTA, std::memory_order_acquire); } return ReleaseWeakRefAction::Destroy; } @@ -375,7 +376,7 @@ IntrusiveRefCounts::checkoutStrongRefFromWeak() const noexcept if (prev.strong == 0u) return false; - desiredValue = curValue + kStrongDelta; + desiredValue = curValue + kSTRONG_DELTA; } return true; } @@ -399,22 +400,23 @@ inline IntrusiveRefCounts::~IntrusiveRefCounts() noexcept #ifndef NDEBUG auto v = refCounts_.load(std::memory_order_acquire); XRPL_ASSERT( - (!(v & kValueMask)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); - auto t = v & kTagMask; - XRPL_ASSERT((!t || t == kTagMask), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag"); + (!(v & kVALUE_MASK)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); + auto t = v & kTAG_MASK; + XRPL_ASSERT( + (!t || t == kTAG_MASK), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag"); #endif } //------------------------------------------------------------------------------ inline IntrusiveRefCounts::RefCountPair::RefCountPair(IntrusiveRefCounts::FieldType v) noexcept - : strong{static_cast(v & kStrongMask)} - , weak{static_cast((v & kWeakMask) >> kStrongCountNumBits)} - , partialDestroyStartedBit{v & kPartialDestroyStartedMask} - , partialDestroyFinishedBit{v & kPartialDestroyFinishedMask} + : strong{static_cast(v & kSTRONG_MASK)} + , weak{static_cast((v & kWEAK_MASK) >> kSTRONG_COUNT_NUM_BITS)} + , partialDestroyStartedBit{v & kPARTIAL_DESTROY_STARTED_MASK} + , partialDestroyFinishedBit{v & kPARTIAL_DESTROY_FINISHED_MASK} { XRPL_ASSERT( - (strong < kCheckStrongMaxValue && weak < kCheckWeakMaxValue), + (strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE), "xrpl::IntrusiveRefCounts::RefCountPair(FieldType) : inputs inside " "range"); } @@ -425,7 +427,7 @@ inline IntrusiveRefCounts::RefCountPair::RefCountPair( : strong{s}, weak{w} { XRPL_ASSERT( - (strong < kCheckStrongMaxValue && weak < kCheckWeakMaxValue), + (strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE), "xrpl::IntrusiveRefCounts::RefCountPair(CountType, CountType) : " "inputs inside range"); } @@ -434,11 +436,11 @@ inline IntrusiveRefCounts::FieldType IntrusiveRefCounts::RefCountPair::combinedValue() const noexcept { XRPL_ASSERT( - (strong < kCheckStrongMaxValue && weak < kCheckWeakMaxValue), + (strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE), "xrpl::IntrusiveRefCounts::RefCountPair::combinedValue : inputs " "inside range"); return (static_cast(weak) - << IntrusiveRefCounts::kStrongCountNumBits) | + << IntrusiveRefCounts::kSTRONG_COUNT_NUM_BITS) | static_cast(strong) | partialDestroyStartedBit | partialDestroyFinishedBit; } @@ -449,7 +451,7 @@ partialDestructorFinished(T** o) { T& self = **o; IntrusiveRefCounts::RefCountPair const p = - self.refCounts_.fetch_or(IntrusiveRefCounts::kPartialDestroyFinishedMask); + self.refCounts_.fetch_or(IntrusiveRefCounts::kPARTIAL_DESTROY_FINISHED_MASK); XRPL_ASSERT( (!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && !p.strong), "xrpl::partialDestructorFinished : not a weak ref"); diff --git a/include/xrpl/basics/LocalValue.h b/include/xrpl/basics/LocalValue.h index 1c2a657a18..f39df425a6 100644 --- a/include/xrpl/basics/LocalValue.h +++ b/include/xrpl/basics/LocalValue.h @@ -55,8 +55,8 @@ template boost::thread_specific_ptr& getLocalValues() { - static boost::thread_specific_ptr kTsp(&detail::LocalValues::cleanup); - return kTsp; + static boost::thread_specific_ptr kTSP(&detail::LocalValues::cleanup); + return kTSP; } } // namespace detail diff --git a/include/xrpl/basics/Log.h b/include/xrpl/basics/Log.h index 6bafbc7c54..8e6532f7c0 100644 --- a/include/xrpl/basics/Log.h +++ b/include/xrpl/basics/Log.h @@ -10,11 +10,24 @@ #include #include #include -#include #include namespace xrpl { +// DEPRECATED use beast::severities::Severity instead +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum LogSeverity { + LSInvalid = -1, // used to indicate an invalid severity + LSTrace = 0, // Very low-level progress information, details inside + // an operation + LSDebug = 1, // Function-level progress information, operations + LSInfo = 2, // Server-level progress information, major operations + LSWarning = 3, // Conditions that warrant human attention, may indicate + // a problem + LSError = 4, // A condition that indicates a problem + LSFatal = 5 // A severe condition that indicates a server problem +}; + /** Manages partitions for logging. */ class Logs { @@ -26,17 +39,17 @@ private: std::string partition_; public: - Sink(std::string partition, beast::Severity thresh, Logs& logs); + Sink(std::string partition, beast::severities::Severity thresh, Logs& logs); Sink(Sink const&) = delete; Sink& operator=(Sink const&) = delete; void - write(beast::Severity level, std::string const& text) override; + write(beast::severities::Severity level, std::string const& text) override; void - writeAlways(beast::Severity level, std::string const& text) override; + writeAlways(beast::severities::Severity level, std::string const& text) override; }; /** Manages a system file containing logged output. @@ -123,12 +136,12 @@ private: std::mutex mutable mutex_; std::map, boost::beast::iless> sinks_; - beast::Severity thresh_; + beast::severities::Severity thresh_; File file_; bool silent_ = false; public: - Logs(beast::Severity level); + Logs(beast::severities::Severity level); Logs(Logs const&) = delete; Logs& @@ -148,18 +161,18 @@ public: beast::Journal journal(std::string const& name); - beast::Severity + beast::severities::Severity threshold() const; void - threshold(beast::Severity thresh); + threshold(beast::severities::Severity thresh); std::vector> partitionSeverities() const; void write( - beast::Severity level, + beast::severities::Severity level, std::string const& partition, std::string const& text, bool console); @@ -179,25 +192,36 @@ public: } virtual std::unique_ptr - makeSink(std::string const& partition, beast::Severity startingLevel); + makeSink(std::string const& partition, beast::severities::Severity startingLevel); public: - static std::string - toString(beast::Severity s); + static LogSeverity + fromSeverity(beast::severities::Severity level); - static std::optional + static beast::severities::Severity + toSeverity(LogSeverity level); + + static std::string + toString(LogSeverity s); + + static LogSeverity fromString(std::string const& s); private: - // Maximum line length for log messages. - // If the message exceeds this length it will be truncated with ellipses. - static constexpr auto kMaximumMessageCharacters = 12 * 1024; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + // Maximum line length for log messages. + // If the message exceeds this length it will be truncated with + // ellipses. + MaximumMessageCharacters = 12 * 1024 + }; static void format( std::string& output, std::string const& message, - beast::Severity severity, + beast::severities::Severity severity, std::string const& partition); }; diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index 93bef82a8c..cdb9014a87 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -2,16 +2,12 @@ #include -#include #include #include #include #include #include -#include -#include #include -#include namespace xrpl { @@ -42,58 +38,17 @@ isPowerOfTen(T value) return logTen(value).has_value(); } -namespace detail { - -/** Builds a table of the powers of 10 - * - * This function is marked consteval, so it can only be run in - * a constexpr context. This assures that it is and can only be run at - * compile time. Doing it at runtime would be pretty wasteful and - * inefficient. - */ -constexpr std::size_t kInt64Digits = 20; -consteval std::array -buildPowersOfTen() -{ - std::array result{}; - - std::uint64_t power = 1; - std::size_t exponent = 0; - // end the loop early so it doesn't overflow; - for (; exponent < result.size() - 1; ++exponent, power *= 10) - { - result[exponent] = power; - if (power > std::numeric_limits::max() / 10) - throw std::logic_error("Power of 10 table is too big"); - } - result[exponent] = power; - if (power < std::numeric_limits::max() / 10) - throw std::logic_error("Power of 10 table is not big enough for the uint64_t type"); - - return result; -} - -} // namespace detail - -constexpr std::array kPowerOfTen = detail::buildPowersOfTen(); - -static_assert(kPowerOfTen[0] == 1); -static_assert(kPowerOfTen[1] == 10); -static_assert(kPowerOfTen[10] == 10'000'000'000); -static_assert( - isPowerOfTen(kPowerOfTen.back()) && *logTen(kPowerOfTen.back()) == detail::kInt64Digits - 1); - /** MantissaRange defines a range for the mantissa of a normalized Number. * * The mantissa is in the range [min, max], where * * min is a power of 10, and * * max = min * 10 - 1. * - * The MantissaScale enum indicates properties of the range: size, and some behavioral - * options. This intentionally restricts the number of unique MantissaRanges that can - * be instantiated: one for each scale. + * The mantissa_scale enum indicates whether the range is "small" or "large". + * This intentionally restricts the number of MantissaRanges that can be + * instantiated to two: one for each scale. * - * The "Small" scale is based on the behavior of STAmount for IOUs. It has a min + * The "small" scale is based on the behavior of STAmount for IOUs. It has a min * value of 10^15, and a max value of 10^16-1. This was sufficient for * uses before Lending Protocol was implemented, mostly related to AMM. * @@ -104,100 +59,46 @@ static_assert( * STNumber field type, and for internal calculations. That necessitated the * "large" scale. * - * The "Large" scales are intended to represent all values that can be represented + * The "large" scale is intended to represent all values that can be represented * by an STAmount - IOUs, XRP, and MPTs. It has a min value of 10^18, and a max - * value of 10^19-1. "LargeLegacy" is like "Large", but preserves - * a rounding error when a computation results in a mantissa of - * Number::kMaxRep that needs to be rounded up, but rounds down - * instead. It will maintain consistent behavior until the fixCleanup3_2_0 - * amendment is enabled. + * value of 10^19-1. * * Note that if the mentioned amendments are eventually retired, this class - * should be left in place, but the "Small" scale option should be removed. This + * should be left in place, but the "small" scale option should be removed. This * will allow for future expansion beyond 64-bits if it is ever needed. */ -struct MantissaRange final +struct MantissaRange { using rep = std::uint64_t; + enum class MantissaScale { Small, Large }; - enum class MantissaScale { - Small, - // LargeLegacy can be removed when fixCleanup3_2_0 is retired - LargeLegacy, - Large, - }; - - // This entire enum can be removed when fixCleanup3_2_0 is retired - enum class CuspRoundingFix : bool { - Disabled = false, - Enabled = true, - }; - - explicit constexpr MantissaRange(MantissaScale sc) : scale(sc) + explicit constexpr MantissaRange(MantissaScale scale) + : min(getMin(scale)), log(logTen(min).value_or(-1)), scale(scale) { } - MantissaScale const scale; - int const log{getExponent(scale)}; - rep const min{getMin(scale, log)}; - rep const max{(min * 10) - 1}; - CuspRoundingFix const cuspRoundingFixEnabled{isCuspFixEnabled(scale)}; - - static MantissaRange const& - getMantissaRange(MantissaScale scale); - - static std::set const& - getAllScales(); + rep min; + rep max{(min * 10) - 1}; + int log; + MantissaScale scale; private: - static constexpr int - getExponent(MantissaScale scale) + static constexpr rep + getMin(MantissaScale scale) { switch (scale) { case MantissaScale::Small: - return 15; - case MantissaScale::LargeLegacy: + return 1'000'000'000'000'000ULL; case MantissaScale::Large: - return 18; - // LCOV_EXCL_START + return 1'000'000'000'000'000'000ULL; default: - // If called in a constexpr context, this throw assures that the build fails if an + // Since this can never be called outside a non-constexpr + // context, this throw assures that the build fails if an // invalid scale is used. throw std::runtime_error("Unknown mantissa scale"); - // LCOV_EXCL_STOP } } - - // Keep this function for future use with different ways to compute - // the ranges. - static constexpr rep - getMin(MantissaScale scale, int exponent) - { - if (exponent < 0 || exponent >= kPowerOfTen.size()) - throw std::runtime_error("Invalid exponent"); // LCOV_EXCL_LINE - return kPowerOfTen[exponent]; - } - - static constexpr CuspRoundingFix - isCuspFixEnabled(MantissaScale scale) - { - switch (scale) - { - case MantissaScale::Small: - case MantissaScale::LargeLegacy: - return CuspRoundingFix::Disabled; - case MantissaScale::Large: - return CuspRoundingFix::Enabled; - default: - // If called in a constexpr context, this throw assures that the build fails if an - // invalid scale is used. - throw std::runtime_error("Unknown mantissa scale"); // LCOV_EXCL_LINE - } - } - - static std::unordered_map const& - getRanges(); }; // Like std::integral, but only 64-bit integral types. @@ -302,7 +203,7 @@ concept Integral64 = std::is_same_v || std::is_same_v::max(); - static_assert(kMaxRep == 9'223'372'036'854'775'807); - static_assert(-kMaxRep == std::numeric_limits::min() + 1); + constexpr static internalrep kMAX_REP = std::numeric_limits::max(); + static_assert(kMAX_REP == 9'223'372'036'854'775'807); + static_assert(-kMAX_REP == std::numeric_limits::min() + 1); // May need to make unchecked private struct Unchecked @@ -508,48 +409,69 @@ public: static internalrep minMantissa() { - return kRange.get().min; + return kRANGE.get().min; } static internalrep maxMantissa() { - return kRange.get().max; + return kRANGE.get().max; } static int mantissaLog() { - return kRange.get().log; + return kRANGE.get().log; } + /// oneSmall is needed because the ranges are private + constexpr static Number + oneSmall(); + /// oneLarge is needed because the ranges are private + constexpr static Number + oneLarge(); + + // And one is needed because it needs to choose between oneSmall and + // oneLarge based on the current range static Number one(); - template < - auto MinMantissa, - auto MaxMantissa, - Integral64 T = std::decay_t> + template [[nodiscard]] std::pair - normalizeToRange() const; + normalizeToRange(T minMantissa, T maxMantissa) const; private: static thread_local RoundingMode mode; // The available ranges for mantissa + constexpr static MantissaRange kSMALL_RANGE{MantissaRange::MantissaScale::Small}; + static_assert(isPowerOfTen(kSMALL_RANGE.min)); + static_assert(kSMALL_RANGE.min == 1'000'000'000'000'000LL); + static_assert(kSMALL_RANGE.max == 9'999'999'999'999'999LL); + static_assert(kSMALL_RANGE.log == 15); + static_assert(kSMALL_RANGE.min < kMAX_REP); + static_assert(kSMALL_RANGE.max < kMAX_REP); + constexpr static MantissaRange kLARGE_RANGE{MantissaRange::MantissaScale::Large}; + static_assert(isPowerOfTen(kLARGE_RANGE.min)); + static_assert(kLARGE_RANGE.min == 1'000'000'000'000'000'000ULL); + static_assert(kLARGE_RANGE.max == internalrep(9'999'999'999'999'999'999ULL)); + static_assert(kLARGE_RANGE.log == 18); + static_assert(kLARGE_RANGE.min < kMAX_REP); + static_assert(kLARGE_RANGE.max > kMAX_REP); + // The range for the mantissa when normalized. // Use reference_wrapper to avoid making copies, and prevent accidentally // changing the values inside the range. - static thread_local std::reference_wrapper kRange; + static thread_local std::reference_wrapper kRANGE; void - normalize(MantissaRange const& range); + normalize(); /** Normalize Number components to an arbitrary range. * * min/maxMantissa are parameters because this function is used by both - * normalize(), which reads from kRange, and by normalizeToRange, + * normalize(), which reads from kRANGE, and by normalizeToRange, * which is public and can accept an arbitrary range from the caller. */ template @@ -559,8 +481,7 @@ private: T& mantissa, int& exponent, internalrep const& minMantissa, - internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled); + internalrep const& maxMantissa); template friend void @@ -569,9 +490,7 @@ private: T& mantissa, int& exponent, MantissaRange::rep const& minMantissa, - MantissaRange::rep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled, - bool dropped); + MantissaRange::rep const& maxMantissa); [[nodiscard]] bool isnormal() const noexcept; @@ -602,12 +521,12 @@ constexpr Number::Number(internalrep mantissa, int exponent, Unchecked) noexcept { } -static constexpr Number kNumZero{}; +constexpr static Number kNUM_ZERO{}; inline Number::Number(bool negative, internalrep mantissa, int exponent, Normalized) : Number(negative, mantissa, exponent, Unchecked{}) { - normalize(kRange); + normalize(); } inline Number::Number(internalrep mantissa, int exponent, Normalized) @@ -633,10 +552,10 @@ constexpr Number::rep Number::mantissa() const noexcept { auto m = mantissa_; - if (m > kMaxRep) + if (m > kMAX_REP) { XRPL_ASSERT_PARTS( - !isnormal() || (m % 10 == 0 && m / 10 <= kMaxRep), + !isnormal() || (m % 10 == 0 && m / 10 <= kMAX_REP), "xrpl::Number::mantissa", "large normalized mantissa has no remainder"); m /= 10; @@ -654,10 +573,10 @@ constexpr int Number::exponent() const noexcept { auto e = exponent_; - if (mantissa_ > kMaxRep) + if (mantissa_ > kMAX_REP) { XRPL_ASSERT_PARTS( - !isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= kMaxRep), + !isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= kMAX_REP), "xrpl::Number::exponent", "large normalized mantissa has no remainder"); ++e; @@ -752,46 +671,35 @@ operator/(Number const& x, Number const& y) inline Number Number::min() noexcept { - return Number{false, kRange.get().min, kMinExponent, Unchecked{}}; + return Number{false, kRANGE.get().min, kMIN_EXPONENT, Unchecked{}}; } inline Number Number::max() noexcept { - return Number{false, std::min(kRange.get().max, kMaxRep), kMaxExponent, Unchecked{}}; + return Number{false, std::min(kRANGE.get().max, kMAX_REP), kMAX_EXPONENT, Unchecked{}}; } inline Number Number::lowest() noexcept { - return Number{true, std::min(kRange.get().max, kMaxRep), kMaxExponent, Unchecked{}}; + return Number{true, std::min(kRANGE.get().max, kMAX_REP), kMAX_EXPONENT, Unchecked{}}; } inline bool Number::isnormal() const noexcept { - MantissaRange const& range = kRange; + MantissaRange const& range = kRANGE; auto const absM = mantissa_; return *this == Number{} || - (range.min <= absM && absM <= range.max && (absM <= kMaxRep || absM % 10 == 0) && - kMinExponent <= exponent_ && exponent_ <= kMaxExponent); + (range.min <= absM && absM <= range.max && (absM <= kMAX_REP || absM % 10 == 0) && + kMIN_EXPONENT <= exponent_ && exponent_ <= kMAX_EXPONENT); } -template +template std::pair -Number::normalizeToRange() const +Number::normalizeToRange(T minMantissa, T maxMantissa) const { - static_assert(std::is_same_v || std::is_same_v); - static_assert(std::is_same_v>); - static_assert(std::is_same_v>); - auto constexpr kMIN = static_cast(MinMantissa); - auto constexpr kMAX = static_cast(MaxMantissa); - static_assert(kMIN > 0); - static_assert(kMIN % 10 == 0); - static_assert(isPowerOfTen(kMIN)); - static_assert(kMAX % 10 == 9); - static_assert((kMAX + 1) / 10 == kMIN); - bool negative = negative_; internalrep mantissa = mantissa_; int exponent = exponent_; @@ -803,10 +711,7 @@ Number::normalizeToRange() const "xrpl::Number::normalizeToRange", "Number is non-negative for unsigned range."); } - // Don't need to worry about the cuspRounding fix because rounding up will never take the - // mantissa over maxMantissa with a ones digit value other than 0. 0 can safely be truncated. - Number::normalize( - negative, mantissa, exponent, kMIN, kMAX, MantissaRange::CuspRoundingFix::Disabled); + Number::normalize(negative, mantissa, exponent, minMantissa, maxMantissa); auto const sign = negative ? -1 : 1; return std::make_pair(static_cast(sign * mantissa), exponent); @@ -858,8 +763,6 @@ to_string(MantissaRange::MantissaScale const& scale) { case MantissaRange::MantissaScale::Small: return "small"; - case MantissaRange::MantissaScale::LargeLegacy: - return "largeLegacy"; case MantissaRange::MantissaScale::Large: return "large"; default: diff --git a/include/xrpl/basics/SHAMapHash.h b/include/xrpl/basics/SHAMapHash.h index 76d9d4fa3d..3b93d1f151 100644 --- a/include/xrpl/basics/SHAMapHash.h +++ b/include/xrpl/basics/SHAMapHash.h @@ -21,12 +21,12 @@ public: } [[nodiscard]] uint256 const& - asUInt256() const + asUint256() const { return hash_; } uint256& - asUInt256() + asUint256() { return hash_; } @@ -93,7 +93,7 @@ template <> inline std::size_t extract(SHAMapHash const& key) { - return *reinterpret_cast(key.asUInt256().data()); + return *reinterpret_cast(key.asUint256().data()); } } // namespace xrpl diff --git a/include/xrpl/basics/SharedWeakCachePointer.ipp b/include/xrpl/basics/SharedWeakCachePointer.ipp index 6228d09b6f..2f8345e645 100644 --- a/include/xrpl/basics/SharedWeakCachePointer.ipp +++ b/include/xrpl/basics/SharedWeakCachePointer.ipp @@ -57,10 +57,10 @@ template std::shared_ptr const& SharedWeakCachePointer::getStrong() const { - static std::shared_ptr const kEmpty; + static std::shared_ptr const kEMPTY; if (auto p = std::get_if>(&combo_)) return *p; - return kEmpty; + return kEMPTY; } template diff --git a/include/xrpl/basics/StringUtilities.h b/include/xrpl/basics/StringUtilities.h index 28421626aa..c9f26026be 100644 --- a/include/xrpl/basics/StringUtilities.h +++ b/include/xrpl/basics/StringUtilities.h @@ -7,11 +7,9 @@ #include #include -#include #include #include #include -#include namespace xrpl { @@ -28,39 +26,28 @@ namespace xrpl { std::string sqlBlobLiteral(Blob const& blob); -namespace detail { - -template -concept SomeChar = std::same_as, int8_t> || - std::same_as, char> || std::same_as, uint8_t>; - -inline constexpr std::array, 256> const kDigitLookupTable = []() { - std::array, 256> t{}; - - for (int i = 0; i < 10; ++i) - t['0' + i] = i; - - for (int i = 0; i < 6; ++i) - { - t['A' + i] = 10 + i; - t['a' + i] = 10 + i; - } - - return t; -}(); - -inline std::optional -hexCharToInt(SomeChar auto hexChar) -{ - return kDigitLookupTable[static_cast(hexChar)]; -} - -} // namespace detail - template std::optional strUnHex(std::size_t strSize, Iterator begin, Iterator end) { + static constexpr std::array const kDIGIT_LOOKUP_TABLE = []() { + std::array t{}; + + for (auto& x : t) + x = -1; + + for (int i = 0; i < 10; ++i) + t['0' + i] = i; + + for (int i = 0; i < 6; ++i) + { + t['A' + i] = 10 + i; + t['a' + i] = 10 + i; + } + + return t; + }(); + Blob out; out.reserve((strSize + 1) / 2); @@ -69,26 +56,27 @@ strUnHex(std::size_t strSize, Iterator begin, Iterator end) if (strSize & 1) { - auto const c = detail::hexCharToInt(*iter++); - if (!c.has_value()) + int c = kDIGIT_LOOKUP_TABLE[*iter++]; + + if (c < 0) return {}; - out.push_back(static_cast(*c)); + out.push_back(c); } while (iter != end) { - auto const cHigh = detail::hexCharToInt(*iter++); + int const cHigh = kDIGIT_LOOKUP_TABLE[*iter++]; - if (!cHigh.has_value()) + if (cHigh < 0) return {}; - auto const cLow = detail::hexCharToInt(*iter++); + int const cLow = kDIGIT_LOOKUP_TABLE[*iter++]; - if (!cLow.has_value()) + if (cLow < 0) return {}; - out.push_back(static_cast((*cHigh << 4) | *cLow)); + out.push_back(static_cast((cHigh << 4) | cLow)); } return {std::move(out)}; @@ -132,7 +120,7 @@ std::string trimWhitespace(std::string str); std::optional -toUInt64(std::string const& s); +toUint64(std::string const& s); /** Determines if the given string looks like a TOML-file hosting domain. diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index 380b7c687f..52b866cdad 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -157,7 +157,7 @@ public: /** Fetch an item from the cache. If the digest was not found, Handler will be called with this signature: - SLE::const_pointer(void) + std::shared_ptr(void) */ template SharedPointerType @@ -181,14 +181,14 @@ private: beast::insight::Collector::ptr const& collector) : hook(collector->makeHook(handler)) , size(collector->makeGauge(prefix, "size")) - , hitRate(collector->makeGauge(prefix, "hit_rate")) + , hit_rate(collector->makeGauge(prefix, "hit_rate")) { } beast::insight::Hook hook; beast::insight::Gauge size; - beast::insight::Gauge hitRate; + beast::insight::Gauge hit_rate; std::size_t hits{0}; std::size_t misses{0}; @@ -197,16 +197,16 @@ private: class KeyOnlyEntry { public: - clock_type::time_point lastAccess; + clock_type::time_point last_access; - explicit KeyOnlyEntry(clock_type::time_point const& lastAccess) : lastAccess(lastAccess) + explicit KeyOnlyEntry(clock_type::time_point const& lastAccess) : last_access(lastAccess) { } void touch(clock_type::time_point const& now) { - lastAccess = now; + last_access = now; } }; @@ -214,10 +214,10 @@ private: { public: shared_weak_combo_pointer_type ptr; - clock_type::time_point lastAccess; + clock_type::time_point last_access; ValueEntry(clock_type::time_point const& lastAccess, shared_pointer_type const& ptr) - : ptr(ptr), lastAccess(lastAccess) + : ptr(ptr), last_access(lastAccess) { } @@ -246,7 +246,7 @@ private: void touch(clock_type::time_point const& now) { - lastAccess = now; + last_access = now; } }; @@ -286,13 +286,13 @@ private: std::string name_; // Desired number of cache entries (0 = ignore) - int const targetSize_; + int const target_size_; // Desired maximum cache age - clock_type::duration const targetAge_; + clock_type::duration const target_age_; // Number of items cached - int cacheCount_{0}; + int cache_count_{0}; cache_type cache_; // Hold strong reference to recent objects std::uint64_t hits_{0}; std::uint64_t misses_{0}; diff --git a/include/xrpl/basics/TaggedCache.ipp b/include/xrpl/basics/TaggedCache.ipp index cee02749c6..8ef9e16570 100644 --- a/include/xrpl/basics/TaggedCache.ipp +++ b/include/xrpl/basics/TaggedCache.ipp @@ -34,8 +34,8 @@ inline TaggedCache< , clock_(clock) , stats_(name, std::bind(&TaggedCache::collectMetrics, this), collector) , name_(name) - , targetSize_(size) - , targetAge_(expiration) + , target_size_(size) + , target_age_(expiration) { } @@ -86,7 +86,7 @@ TaggedCache(cache_.size()) <= targetSize_)) + if (target_size_ == 0 || (static_cast(cache_.size()) <= target_size_)) { - whenExpire = now - targetAge_; + whenExpire = now - target_age_; } else { - whenExpire = now - (targetAge_ * targetSize_ / cache_.size()); + whenExpire = now - (target_age_ * target_size_ / cache_.size()); clock_type::duration const minimumAge(std::chrono::seconds(1)); if (whenExpire > (now - minimumAge)) whenExpire = now - minimumAge; JLOG(journal_.trace()) - << name_ << " is growing fast " << cache_.size() << " of " << targetSize_ - << " aging at " << (now - whenExpire).count() << " of " << targetAge_.count(); + << name_ << " is growing fast " << cache_.size() << " of " << target_size_ + << " aging at " << (now - whenExpire).count() << " of " << target_age_.count(); } std::vector workers; @@ -242,7 +242,7 @@ TaggedCachesecond.lastAccess = now; + it->second.last_access = now; return inserted; } @@ -626,7 +626,7 @@ TaggedCachesecond.lastAccess <= whenExpire) + else if (cit->second.last_access <= whenExpire) { // strong, expired ++cacheRemovals; @@ -773,12 +773,12 @@ TaggedCachesecond.lastAccess > now) + if (cit->second.last_access > now) { - cit->second.lastAccess = now; + cit->second.last_access = now; ++cit; } - else if (cit->second.lastAccess <= whenExpire) + else if (cit->second.last_access <= whenExpire) { cit = partition.erase(cit); } diff --git a/include/xrpl/basics/UptimeClock.h b/include/xrpl/basics/UptimeClock.h index 502aae7c25..bb7d4fd77a 100644 --- a/include/xrpl/basics/UptimeClock.h +++ b/include/xrpl/basics/UptimeClock.h @@ -30,8 +30,8 @@ public: now(); // seconds since xrpld program start private: - static std::atomic kNow; - static std::atomic kStop; + static std::atomic kNOW; + static std::atomic kSTOP; struct UpdateThread : private std::thread { diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 93a9ced15e..15fc4f6966 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -46,11 +46,6 @@ struct IsContiguousContainer : std::true_type { }; -template -struct AlwaysFalseT : std::bool_constant -{ -}; - } // namespace detail /** Integers of any length that is a multiple of 32-bits @@ -67,18 +62,18 @@ struct AlwaysFalseT : std::bool_constant number of bits. */ template -class BaseUInt +class BaseUint { 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 constexpr std::size_t kWidth = Bits / 32; + static constexpr std::size_t kWIDTH = Bits / 32; // This is really big-endian in byte order. // We sometimes use std::uint32_t for speed. - std::array data_; + std::array data_; public: //-------------------------------------------------------------------------- @@ -86,8 +81,8 @@ public: // STL Container Interface // - static constexpr std::size_t kBytes = Bits / 8; - static_assert(sizeof(data_) == kBytes, ""); + static std::size_t constexpr kBYTES = Bits / 8; + static_assert(sizeof(data_) == kBYTES, ""); using size_type = std::size_t; using difference_type = std::ptrdiff_t; @@ -121,7 +116,7 @@ public: iterator end() { - return data() + kBytes; + return data() + kBYTES; } [[nodiscard]] const_iterator begin() const @@ -131,7 +126,7 @@ public: [[nodiscard]] const_iterator end() const { - return data() + kBytes; + return data() + kBYTES; } [[nodiscard]] const_iterator cbegin() const @@ -141,7 +136,7 @@ public: [[nodiscard]] const_iterator cend() const { - return data() + kBytes; + return data() + kBYTES; } /** Value hashing function. @@ -165,9 +160,9 @@ private: explicit VoidHelper() = default; }; - explicit BaseUInt(void const* data, VoidHelper) + explicit BaseUint(void const* data, VoidHelper) { - memcpy(data_.data(), data, kBytes); + memcpy(data_.data(), data, kBYTES); } // Helper function to initialize a base_uint from a std::string_view. @@ -249,15 +244,15 @@ private: } public: - constexpr BaseUInt() : data_{} + constexpr BaseUint() : data_{} { } - constexpr BaseUInt(beast::Zero) : data_{} + constexpr BaseUint(beast::Zero) : data_{} { } - explicit BaseUInt(std::uint64_t b) + explicit BaseUint(std::uint64_t b) { *this = b; } @@ -265,7 +260,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 BaseUInt(std::string_view sv) noexcept(false) + explicit constexpr BaseUint(std::string_view sv) noexcept(false) : data_(parseFromStringViewThrows(sv)) { } @@ -275,42 +270,24 @@ public: class = std::enable_if_t< detail::IsContiguousContainer::value && std::is_trivially_copyable_v>> - explicit BaseUInt(Container const& c) + explicit BaseUint(Container const& c) { - // Use AlwaysFalseT so the static_assert condition is dependent - // and only triggers when this constructor template is instantiated. - static_assert( - detail::AlwaysFalseT::value, - "This constructor is not intended to be used and will be soon removed. " - "Use base_uint::fromRaw instead."); - } - - template < - class Container, - class = std::enable_if_t< - detail::IsContiguousContainer::value && - std::is_trivially_copyable_v>> - static BaseUInt - fromRaw(Container const& c) - { - BaseUInt result; XRPL_ASSERT( c.size() * sizeof(typename Container::value_type) == size(), - "xrpl::BaseUInt::fromRaw(Container auto) : input size match"); - std::memcpy(result.data_.data(), c.data(), size()); - return result; + "xrpl::base_uint::base_uint(Container auto) : input size match"); + std::memcpy(data_.data(), c.data(), size()); } template std::enable_if_t< detail::IsContiguousContainer::value && std::is_trivially_copyable_v, - BaseUInt&> + BaseUint&> operator=(Container const& c) { XRPL_ASSERT( c.size() * sizeof(typename Container::value_type) == size(), - "xrpl::BaseUInt::operator=(Container auto) : input size match"); + "xrpl::base_uint::operator=(Container auto) : input size match"); std::memcpy(data_.data(), c.data(), size()); return *this; } @@ -318,14 +295,14 @@ public: /* Construct from a raw pointer. The buffer pointed to by `data` must be at least Bits/8 bytes. */ - static BaseUInt + static BaseUint fromVoid(void const* data) { - return BaseUInt(data, VoidHelper()); + return BaseUint(data, VoidHelper()); } template - static std::optional + static std::optional fromVoidChecked(T const& from) { if (from.size() != size()) @@ -336,7 +313,7 @@ public: [[nodiscard]] constexpr int signum() const { - for (int i = 0; i < kWidth; i++) + for (int i = 0; i < kWIDTH; i++) { if (data_[i] != 0) return 1; @@ -348,24 +325,24 @@ public: bool operator!() const { - return *this == beast::kZero; + return *this == beast::kZERO; } - constexpr BaseUInt + constexpr BaseUint operator~() const { - BaseUInt ret; + BaseUint ret; - for (int i = 0; i < kWidth; i++) + for (int i = 0; i < kWIDTH; i++) ret.data_[i] = ~data_[i]; return ret; } - BaseUInt& + BaseUint& operator=(std::uint64_t uHost) { - *this = beast::kZero; + *this = beast::kZERO; // NOLINTBEGIN(cppcoreguidelines-pro-type-member-init) union { @@ -375,43 +352,43 @@ public: // NOLINTEND(cppcoreguidelines-pro-type-member-init) // Put in least significant bits. ul = boost::endian::native_to_big(uHost); - data_[kWidth - 2] = u[0]; - data_[kWidth - 1] = u[1]; + data_[kWIDTH - 2] = u[0]; + data_[kWIDTH - 1] = u[1]; return *this; } - BaseUInt& - operator^=(BaseUInt const& b) + BaseUint& + operator^=(BaseUint const& b) { - for (int i = 0; i < kWidth; i++) + for (int i = 0; i < kWIDTH; i++) data_[i] ^= b.data_[i]; return *this; } - BaseUInt& - operator&=(BaseUInt const& b) + BaseUint& + operator&=(BaseUint const& b) { - for (int i = 0; i < kWidth; i++) + for (int i = 0; i < kWIDTH; i++) data_[i] &= b.data_[i]; return *this; } - BaseUInt& - operator|=(BaseUInt const& b) + BaseUint& + operator|=(BaseUint const& b) { - for (int i = 0; i < kWidth; i++) + for (int i = 0; i < kWIDTH; i++) data_[i] |= b.data_[i]; return *this; } - BaseUInt& + BaseUint& operator++() { // prefix operator - for (int i = kWidth - 1; i >= 0; --i) + for (int i = kWIDTH - 1; i >= 0; --i) { data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) + 1); if (data_[i] != 0) @@ -421,20 +398,20 @@ public: return *this; } - BaseUInt + BaseUint operator++(int) { // postfix operator - BaseUInt const ret = *this; + BaseUint const ret = *this; ++(*this); return ret; } - BaseUInt& + BaseUint& operator--() { - for (int i = kWidth - 1; i >= 0; --i) + for (int i = kWIDTH - 1; i >= 0; --i) { auto prev = data_[i]; data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) - 1); @@ -446,36 +423,36 @@ public: return *this; } - BaseUInt + BaseUint operator--(int) { // postfix operator - BaseUInt const ret = *this; + BaseUint const ret = *this; --(*this); return ret; } - [[nodiscard]] BaseUInt + [[nodiscard]] BaseUint next() const { auto ret = *this; return ++ret; } - [[nodiscard]] BaseUInt + [[nodiscard]] BaseUint prev() const { auto ret = *this; return --ret; } - BaseUInt& - operator+=(BaseUInt const& b) + BaseUint& + operator+=(BaseUint const& b) { std::uint64_t carry = 0; - for (int i = kWidth - 1; i >= 0; i--) + for (int i = kWIDTH - 1; i >= 0; i--) { std::uint64_t const n = carry + boost::endian::big_to_native(data_[i]) + boost::endian::big_to_native(b.data_[i]); @@ -489,7 +466,7 @@ public: template friend void - hash_append(Hasher& h, BaseUInt const& a) noexcept + hash_append(Hasher& h, BaseUint const& a) noexcept { // Do not allow any endian transformations on this memory h(a.data_.data(), sizeof(a.data_)); @@ -526,13 +503,13 @@ public: return parseHex(std::string_view{str}); } - static constexpr std::size_t + constexpr static std::size_t size() { - return kBytes; + return kBYTES; } - BaseUInt& + BaseUint& operator=(beast::Zero) { data_.fill(0); @@ -543,28 +520,28 @@ public: [[nodiscard]] bool isZero() const { - return *this == beast::kZero; + return *this == beast::kZERO; } [[nodiscard]] bool isNonZero() const { - return *this != beast::kZero; + return *this != beast::kZERO; } void zero() { - *this = beast::kZero; + *this = beast::kZERO; } }; -using uint128 = BaseUInt<128>; -using uint160 = BaseUInt<160>; -using uint256 = BaseUInt<256>; -using uint192 = BaseUInt<192>; +using uint128 = BaseUint<128>; +using uint160 = BaseUint<160>; +using uint256 = BaseUint<256>; +using uint192 = BaseUint<192>; template [[nodiscard]] constexpr std::strong_ordering -operator<=>(BaseUInt const& lhs, BaseUInt const& rhs) +operator<=>(BaseUint const& lhs, BaseUint const& rhs) { // This comparison might seem wrong on a casual inspection because it // compares data internally stored as std::uint32_t byte-by-byte. But @@ -585,7 +562,7 @@ operator<=>(BaseUInt const& lhs, BaseUInt const& rhs) template [[nodiscard]] constexpr bool -operator==(BaseUInt const& lhs, BaseUInt const& rhs) +operator==(BaseUint const& lhs, BaseUint const& rhs) { return (lhs <=> rhs) == 0; } @@ -593,59 +570,59 @@ operator==(BaseUInt const& lhs, BaseUInt const& rhs) //------------------------------------------------------------------------------ template constexpr bool -operator==(BaseUInt const& a, std::uint64_t b) +operator==(BaseUint const& a, std::uint64_t b) { - return a == BaseUInt(b); + return a == BaseUint(b); } //------------------------------------------------------------------------------ template -constexpr BaseUInt -operator^(BaseUInt const& a, BaseUInt const& b) +constexpr BaseUint +operator^(BaseUint const& a, BaseUint const& b) { - return BaseUInt(a) ^= b; + return BaseUint(a) ^= b; } template -constexpr BaseUInt -operator&(BaseUInt const& a, BaseUInt const& b) +constexpr BaseUint +operator&(BaseUint const& a, BaseUint const& b) { - return BaseUInt(a) &= b; + return BaseUint(a) &= b; } template -constexpr BaseUInt -operator|(BaseUInt const& a, BaseUInt const& b) +constexpr BaseUint +operator|(BaseUint const& a, BaseUint const& b) { - return BaseUInt(a) |= b; + return BaseUint(a) |= b; } template -constexpr BaseUInt -operator+(BaseUInt const& a, BaseUInt const& b) +constexpr BaseUint +operator+(BaseUint const& a, BaseUint const& b) { - return BaseUInt(a) += b; + return BaseUint(a) += b; } //------------------------------------------------------------------------------ template inline std::string -to_string(BaseUInt const& a) +to_string(BaseUint const& a) { return strHex(a.cbegin(), a.cend()); } template inline std::string -toShortString(BaseUInt const& a) +toShortString(BaseUint const& a) { - static_assert(BaseUInt::kBytes > 4, "For 4 bytes or less, use a native type"); + static_assert(BaseUint::kBYTES > 4, "For 4 bytes or less, use a native type"); return strHex(a.cbegin(), a.cbegin() + 4) + "..."; } template inline std::ostream& -operator<<(std::ostream& out, BaseUInt const& u) +operator<<(std::ostream& out, BaseUint const& u) { return out << to_string(u); } @@ -673,7 +650,7 @@ static_assert(sizeof(uint256) == 256 / 8, "There should be no padding bytes"); namespace beast { template -struct IsUniquelyRepresented> : public std::true_type +struct IsUniquelyRepresented> : public std::true_type { explicit IsUniquelyRepresented() = default; }; diff --git a/include/xrpl/basics/chrono.h b/include/xrpl/basics/chrono.h index 5d6de06248..8b71be04b4 100644 --- a/include/xrpl/basics/chrono.h +++ b/include/xrpl/basics/chrono.h @@ -30,10 +30,10 @@ using weeks = std::chrono::duration @@ -77,7 +77,7 @@ toStringIso(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 toStringIso(date::sys_time{tp.time_since_epoch() + kEpochOffset}); + return toStringIso(date::sys_time{tp.time_since_epoch() + kEPOCH_OFFSET}); } /** A clock for measuring elapsed time. diff --git a/include/xrpl/basics/hardened_hash.h b/include/xrpl/basics/hardened_hash.h index efc77e058b..07f5aded4c 100644 --- a/include/xrpl/basics/hardened_hash.h +++ b/include/xrpl/basics/hardened_hash.h @@ -31,9 +31,9 @@ makeSeedPair() noexcept // state_t(state_t const&) = delete; // state_t& operator=(state_t const&) = delete; }; - static StateT kState; - std::scoped_lock const lock(kState.mutex); - return {kState.dist(kState.gen), kState.dist(kState.gen)}; + static StateT kSTATE; + std::scoped_lock const lock(kSTATE.mutex); + return {kSTATE.dist(kSTATE.gen), kSTATE.dist(kSTATE.gen)}; } } // namespace detail diff --git a/include/xrpl/basics/mulDiv.h b/include/xrpl/basics/mulDiv.h index 9076da62f2..8a9bc4f5dc 100644 --- a/include/xrpl/basics/mulDiv.h +++ b/include/xrpl/basics/mulDiv.h @@ -5,7 +5,7 @@ #include namespace xrpl { -constexpr auto kMuldivMax = std::numeric_limits::max(); +auto constexpr kMULDIV_MAX = std::numeric_limits::max(); /** Return value*mul/div accurately. Computes the result of the multiplication and division in diff --git a/include/xrpl/basics/partitioned_unordered_map.h b/include/xrpl/basics/partitioned_unordered_map.h index 3bf64985e5..5f32cca8af 100644 --- a/include/xrpl/basics/partitioned_unordered_map.h +++ b/include/xrpl/basics/partitioned_unordered_map.h @@ -236,7 +236,7 @@ public: map_.resize(partitions_); XRPL_ASSERT( partitions_, - "xrpl::PartitionedUnorderedMap::PartitionedUnorderedMap : " + "xrpl::partitioned_unordered_map::partitioned_unordered_map : " "nonzero partitions"); } diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index 17f4a1c213..ca51ef9364 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -47,7 +47,7 @@ inline beast::xor_shift_engine& defaultPrng() { // This is used to seed the thread-specific PRNGs on demand - static beast::xor_shift_engine kSeeder = [] { + static beast::xor_shift_engine kSEEDER = [] { std::random_device rng; std::uniform_int_distribution distribution{1}; return beast::xor_shift_engine(distribution(rng)); @@ -57,17 +57,17 @@ defaultPrng() static std::mutex kM; // The thread-specific PRNGs: - thread_local beast::xor_shift_engine kEngine = [] { + thread_local beast::xor_shift_engine kENGINE = [] { std::uint64_t seed = 0; { std::scoped_lock const lk(kM); std::uniform_int_distribution distribution{1}; - seed = distribution(kSeeder); + seed = distribution(kSEEDER); } return beast::xor_shift_engine{seed}; }(); - return kEngine; + return kENGINE; } /** Return a uniformly distributed random integer. @@ -94,7 +94,7 @@ template std::enable_if_t && detail::is_engine::value, Integral> randInt(Engine& engine, Integral min, Integral max) { - XRPL_ASSERT(max > min, "xrpl::randInt : max over min inputs"); + XRPL_ASSERT(max > min, "xrpl::rand_int : max over min inputs"); // This should have no state and constructing it should // be very cheap. If that turns out not to be the case diff --git a/include/xrpl/basics/safe_cast.h b/include/xrpl/basics/safe_cast.h index f71edc47ad..b9a7aa1fa0 100644 --- a/include/xrpl/basics/safe_cast.h +++ b/include/xrpl/basics/safe_cast.h @@ -22,9 +22,9 @@ safeCast(Src s) noexcept { static_assert( std::is_signed_v || std::is_unsigned_v, "Cannot cast signed to unsigned"); - constexpr unsigned kNotSame = std::is_signed_v != std::is_signed_v; + constexpr unsigned kNOT_SAME = std::is_signed_v != std::is_signed_v; static_assert( - sizeof(Dest) >= sizeof(Src) + kNotSame, + sizeof(Dest) >= sizeof(Src) + kNOT_SAME, "Destination is too small to hold all values of source"); return static_cast(s); } @@ -81,7 +81,7 @@ safeDowncast(Src* s) noexcept return static_cast(s); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) #else auto* result = dynamic_cast(s); - XRPL_ASSERT(result != nullptr, "xrpl::safeDowncast : pointer downcast is valid"); + XRPL_ASSERT(result != nullptr, "xrpl::safe_downcast : pointer downcast is valid"); return result; #endif } @@ -94,7 +94,7 @@ safeDowncast(Src& s) noexcept #ifndef NDEBUG XRPL_ASSERT( dynamic_cast>>(&s) != nullptr, - "xrpl::safeDowncast : reference downcast is valid"); + "xrpl::safe_downcast : reference downcast is valid"); #endif return static_cast(s); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) } diff --git a/include/xrpl/basics/scope.h b/include/xrpl/basics/scope.h index cfd21e6e30..64f91727fa 100644 --- a/include/xrpl/basics/scope.h +++ b/include/xrpl/basics/scope.h @@ -24,20 +24,20 @@ namespace xrpl { template class ScopeExit { - EF exitFunction_; - bool executeOnDestruction_{true}; + EF exit_function_; + bool execute_on_destruction_{true}; public: ~ScopeExit() { - if (executeOnDestruction_) - exitFunction_(); + if (execute_on_destruction_) + exit_function_(); } ScopeExit(ScopeExit&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exitFunction_{std::forward(rhs.exitFunction_)} - , executeOnDestruction_{rhs.executeOnDestruction_} + : exit_function_{std::forward(rhs.exit_function_)} + , execute_on_destruction_{rhs.execute_on_destruction_} { rhs.release(); } @@ -51,7 +51,7 @@ public: std::enable_if_t< !std::is_same_v, ScopeExit> && std::is_constructible_v>* = 0) noexcept - : exitFunction_{std::forward(f)} + : exit_function_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); } @@ -59,7 +59,7 @@ public: void release() noexcept { - executeOnDestruction_ = false; + execute_on_destruction_ = false; } }; @@ -69,22 +69,22 @@ ScopeExit(EF) -> ScopeExit; template class ScopeFail { - EF exitFunction_; - bool executeOnDestruction_{true}; - int uncaughtOnCreation_{std::uncaught_exceptions()}; + EF exit_function_; + bool execute_on_destruction_{true}; + int uncaught_on_creation_{std::uncaught_exceptions()}; public: ~ScopeFail() { - if (executeOnDestruction_ && std::uncaught_exceptions() > uncaughtOnCreation_) - exitFunction_(); + if (execute_on_destruction_ && std::uncaught_exceptions() > uncaught_on_creation_) + exit_function_(); } ScopeFail(ScopeFail&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exitFunction_{std::forward(rhs.exitFunction_)} - , executeOnDestruction_{rhs.executeOnDestruction_} - , uncaughtOnCreation_{rhs.uncaughtOnCreation_} + : exit_function_{std::forward(rhs.exit_function_)} + , execute_on_destruction_{rhs.execute_on_destruction_} + , uncaught_on_creation_{rhs.uncaught_on_creation_} { rhs.release(); } @@ -98,7 +98,7 @@ public: std::enable_if_t< !std::is_same_v, ScopeFail> && std::is_constructible_v>* = 0) noexcept - : exitFunction_{std::forward(f)} + : exit_function_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); } @@ -106,7 +106,7 @@ public: void release() noexcept { - executeOnDestruction_ = false; + execute_on_destruction_ = false; } }; @@ -116,22 +116,22 @@ ScopeFail(EF) -> ScopeFail; template class ScopeSuccess { - EF exitFunction_; - bool executeOnDestruction_{true}; - int uncaughtOnCreation_{std::uncaught_exceptions()}; + EF exit_function_; + bool execute_on_destruction_{true}; + int uncaught_on_creation_{std::uncaught_exceptions()}; public: - ~ScopeSuccess() noexcept(noexcept(exitFunction_())) + ~ScopeSuccess() noexcept(noexcept(exit_function_())) { - if (executeOnDestruction_ && std::uncaught_exceptions() <= uncaughtOnCreation_) - exitFunction_(); + if (execute_on_destruction_ && std::uncaught_exceptions() <= uncaught_on_creation_) + exit_function_(); } ScopeSuccess(ScopeSuccess&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exitFunction_{std::forward(rhs.exitFunction_)} - , executeOnDestruction_{rhs.executeOnDestruction_} - , uncaughtOnCreation_{rhs.uncaughtOnCreation_} + : exit_function_{std::forward(rhs.exit_function_)} + , execute_on_destruction_{rhs.execute_on_destruction_} + , uncaught_on_creation_{rhs.uncaught_on_creation_} { rhs.release(); } @@ -146,14 +146,14 @@ public: !std::is_same_v, ScopeSuccess> && std::is_constructible_v>* = 0) noexcept(std::is_nothrow_constructible_v || std::is_nothrow_constructible_v) - : exitFunction_{std::forward(f)} + : exit_function_{std::forward(f)} { } void release() noexcept { - executeOnDestruction_ = false; + execute_on_destruction_ = false; } }; @@ -205,7 +205,7 @@ class ScopeUnlock public: explicit ScopeUnlock(std::unique_lock& lock) noexcept(true) : plock_(&lock) { - XRPL_ASSERT(plock_->owns_lock(), "xrpl::ScopeUnlock::ScopeUnlock : mutex must be locked"); + XRPL_ASSERT(plock_->owns_lock(), "xrpl::scope_unlock::scope_unlock : mutex must be locked"); plock_->unlock(); } diff --git a/include/xrpl/basics/spinlock.h b/include/xrpl/basics/spinlock.h index 2cc00efdef..3518b94680 100644 --- a/include/xrpl/basics/spinlock.h +++ b/include/xrpl/basics/spinlock.h @@ -103,7 +103,7 @@ public: { XRPL_ASSERT( index >= 0 && (mask_ != 0), - "xrpl::PackedSpinlock::PackedSpinlock : valid index and mask"); + "xrpl::packed_spinlock::packed_spinlock : valid index and mask"); } [[nodiscard]] bool diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index ce3929a394..4ba985e579 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -15,7 +15,7 @@ namespace beast { /** Measures handler latency on an io_context queue. */ template -class IOLatencyProbe +class IoLatencyProbe { private: using duration = typename Clock::duration; @@ -30,12 +30,12 @@ private: bool cancel_{false}; public: - IOLatencyProbe(duration const& period, boost::asio::io_context& ios) + IoLatencyProbe(duration const& period, boost::asio::io_context& ios) : period_(period), ios_(ios), timer_(ios_) { } - ~IOLatencyProbe() + ~IoLatencyProbe() { std::unique_lock lock(mutex_); cancel(lock, true); @@ -85,7 +85,7 @@ public: { std::scoped_lock const lock(mutex_); if (cancel_) - throw std::logic_error("IOLatencyProbe is canceled"); + throw std::logic_error("io_latency_probe is canceled"); boost::asio::post( ios_, SampleOp(std::forward(handler), Clock::now(), false, this)); } @@ -100,7 +100,7 @@ public: { std::scoped_lock const lock(mutex_); if (cancel_) - throw std::logic_error("IOLatencyProbe is canceled"); + throw std::logic_error("io_latency_probe is canceled"); boost::asio::post( ios_, SampleOp(std::forward(handler), Clock::now(), true, this)); } @@ -140,18 +140,18 @@ private: Handler handler; time_point start; bool repeat; - IOLatencyProbe* probe; + IoLatencyProbe* probe; SampleOp( Handler const& handler, time_point const& start, bool repeat, - IOLatencyProbe* probe) + IoLatencyProbe* probe) : handler(handler), start(start), repeat(repeat), probe(probe) { XRPL_ASSERT( probe, - "beast::IOLatencyProbe::SampleOp::SampleOp : non-null " + "beast::io_latency_probe::sample_op::sample_op : non-null " "probe input"); probe->addref(); } @@ -164,7 +164,7 @@ private: { XRPL_ASSERT( probe, - "beast::IOLatencyProbe::SampleOp::SampleOp(SampleOp&&) : " + "beast::io_latency_probe::sample_op::sample_op(sample_op&&) : " "non-null probe input"); from.probe = nullptr; } diff --git a/include/xrpl/beast/clock/abstract_clock.h b/include/xrpl/beast/clock/abstract_clock.h index 33d4096d0e..67320ceabc 100644 --- a/include/xrpl/beast/clock/abstract_clock.h +++ b/include/xrpl/beast/clock/abstract_clock.h @@ -83,8 +83,8 @@ template AbstractClock& getAbstractClock() { - static detail::AbstractClockWrapper kClock; - return kClock; + static detail::AbstractClockWrapper kCLOCK; + return kCLOCK; } } // namespace beast diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index 7162c237d6..78a2a5a32d 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -1370,7 +1370,7 @@ private: buck_.resize(size() + additional, cont_); XRPL_ASSERT( loadFactor() <= maxLoadFactor(), - "beast::detail::AgedUnorderedContainer::maybeRehash : maximum " + "beast::detail::AgedUnorderedContainer::maybe_rehash : maximum " "load factor"); } diff --git a/include/xrpl/beast/core/CurrentThreadName.h b/include/xrpl/beast/core/CurrentThreadName.h index 6175d99b16..9bf062a885 100644 --- a/include/xrpl/beast/core/CurrentThreadName.h +++ b/include/xrpl/beast/core/CurrentThreadName.h @@ -21,7 +21,7 @@ setCurrentThreadName(std::string_view newThreadName); // On Linux, thread names are limited to 16 bytes including the null terminator. // Maximum number of characters is therefore 15. -constexpr std::size_t kMaxThreadNameLength = 15; +constexpr std::size_t kMAX_THREAD_NAME_LENGTH = 15; /** Sets the name of the caller thread with compile-time size checking. @tparam N The size of the string literal including null terminator @@ -34,7 +34,7 @@ template void setCurrentThreadName(char const (&newThreadName)[N]) { - static_assert(N <= kMaxThreadNameLength + 1, "Thread name cannot exceed 15 characters"); + static_assert(N <= kMAX_THREAD_NAME_LENGTH + 1, "Thread name cannot exceed 15 characters"); setCurrentThreadName(std::string_view(newThreadName, N - 1)); } diff --git a/include/xrpl/beast/hash/hash_append.h b/include/xrpl/beast/hash/hash_append.h index 83cff4bdea..25ce668166 100644 --- a/include/xrpl/beast/hash/hash_append.h +++ b/include/xrpl/beast/hash/hash_append.h @@ -53,7 +53,7 @@ inline void maybeReverseBytes(T& t, Hasher&) { maybeReverseBytes( - t, std::integral_constant{}); + t, std::integral_constant{}); } } // namespace detail @@ -154,7 +154,7 @@ struct IsContiguouslyHashable : public std::integral_constant< bool, IsUniquelyRepresented::value && - (sizeof(T) == 1 || HashAlgorithm::kEndian == boost::endian::order::native)> + (sizeof(T) == 1 || HashAlgorithm::kENDIAN == boost::endian::order::native)> { explicit IsContiguouslyHashable() = default; }; diff --git a/include/xrpl/beast/hash/xxhasher.h b/include/xrpl/beast/hash/xxhasher.h index 95a67dede0..01485e1e85 100644 --- a/include/xrpl/beast/hash/xxhasher.h +++ b/include/xrpl/beast/hash/xxhasher.h @@ -21,9 +21,9 @@ private: static_assert(sizeof(std::size_t) == 8, "requires 64-bit std::size_t"); // Have an internal buffer to avoid the streaming API // A 64-byte buffer should to be big enough for us - static constexpr std::size_t kInternalBufferSize = 64; + static constexpr std::size_t kINTERNAL_BUFFER_SIZE = 64; - alignas(64) std::array buffer_{}; + alignas(64) std::array buffer_{}; std::span readBuffer_; std::span writeBuffer_; @@ -102,7 +102,7 @@ private: } public: - static constexpr auto kEndian = boost::endian::order::native; + static constexpr auto const kENDIAN = boost::endian::order::native; Xxhasher(Xxhasher const&) = delete; Xxhasher& diff --git a/include/xrpl/beast/unit_test/reporter.h b/include/xrpl/beast/unit_test/reporter.h index 1fdbb451a6..d2ba624f4a 100644 --- a/include/xrpl/beast/unit_test/reporter.h +++ b/include/xrpl/beast/unit_test/reporter.h @@ -62,7 +62,9 @@ private: { using run_time = std::pair; - static constexpr auto kMaxTop = 10; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { MaxTop = 10 }; std::size_t suites = 0; std::size_t cases = 0; @@ -77,8 +79,8 @@ private: std::ostream& os_; Results results_; - SuiteResults suiteResults_; - CaseResults caseResults_; + SuiteResults suite_results_; + CaseResults case_results_; public: Reporter(Reporter const&) = delete; @@ -146,11 +148,11 @@ Reporter::Results::add(SuiteResults const& r) }); if (iter != top.end()) { - if (top.size() == kMaxTop) + if (top.size() == MaxTop) top.resize(top.size() - 1); top.emplace(iter, r.name, elapsed); } - else if (top.size() < kMaxTop) + else if (top.size() < MaxTop) { top.emplace_back(r.name, elapsed); } @@ -196,22 +198,22 @@ template void Reporter::onSuiteBegin(SuiteInfo const& info) { - suiteResults_ = SuiteResults{info.fullName()}; + suite_results_ = SuiteResults{info.fullName()}; } template void Reporter::onSuiteEnd() { - results_.add(suiteResults_); + results_.add(suite_results_); } template void Reporter::onCaseBegin(std::string const& name) { - caseResults_ = CaseResults(name); - os_ << suiteResults_.name << (caseResults_.name.empty() ? "" : (" " + caseResults_.name)) + case_results_ = CaseResults(name); + os_ << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << std::endl; } @@ -219,23 +221,23 @@ template void Reporter::onCaseEnd() { - suiteResults_.add(caseResults_); + suite_results_.add(case_results_); } template void Reporter::onPass() { - ++caseResults_.total; + ++case_results_.total; } template void Reporter::onFail(std::string const& reason) { - ++caseResults_.failed; - ++caseResults_.total; - os_ << "#" << caseResults_.total << " failed" << (reason.empty() ? "" : ": ") << reason + ++case_results_.failed; + ++case_results_.total; + os_ << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << std::endl; } diff --git a/include/xrpl/beast/unit_test/suite.h b/include/xrpl/beast/unit_test/suite.h index fded866da0..999058b7f1 100644 --- a/include/xrpl/beast/unit_test/suite.h +++ b/include/xrpl/beast/unit_test/suite.h @@ -299,8 +299,8 @@ private: static Suite** pThisSuite() { - static Suite* kPTs = nullptr; // NOLINT TODO - return &kPTs; + static Suite* kP_TS = nullptr; // NOLINT TODO + return &kP_TS; } /** Runs the suite. */ diff --git a/include/xrpl/beast/utility/Journal.h b/include/xrpl/beast/utility/Journal.h index 1a0c148d1f..0fd0019235 100644 --- a/include/xrpl/beast/utility/Journal.h +++ b/include/xrpl/beast/utility/Journal.h @@ -2,25 +2,29 @@ #include -#include #include namespace beast { +/** A namespace for easy access to logging severity values. */ +namespace severities { /** Severity level / threshold of a Journal message. */ -enum class Severity : std::uint8_t { - All = 0, +// Hundreds of usages via logging macros +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum Severity { + KAll = 0, - Trace = All, - Debug = 1, - Info = 2, - Warning = 3, - Error = 4, - Fatal = 5, + KTrace = KAll, + KDebug = 1, + KInfo = 2, + KWarning = 3, + KError = 4, + KFatal = 5, - Disabled = 6, - None = Disabled + KDisabled = 6, + KNone = KDisabled }; +} // namespace severities /** A generic endpoint for log messages. @@ -40,6 +44,9 @@ public: class Sink; private: + // Severity level / threshold of a Journal message. + using Severity = severities::Severity; + // Invariant: sink_ always points to a valid Sink Sink* sink_; @@ -176,7 +183,7 @@ public: { public: /** Create a stream which produces no output. */ - explicit Stream() : sink_(getNullSink()), level_(Severity::Disabled) + explicit Stream() : sink_(getNullSink()), level_(severities::KDisabled) { } @@ -187,7 +194,7 @@ public: Stream(Sink& sink, Severity level) : sink_(sink), level_(level) { XRPL_ASSERT( - level_ < Severity::Disabled, "beast::Journal::Stream::Stream : maximum level"); + level_ < severities::KDisabled, "beast::Journal::Stream::Stream : maximum level"); } /** Construct or copy another Stream. */ @@ -290,37 +297,37 @@ public: [[nodiscard]] Stream trace() const { - return {*sink_, Severity::Trace}; + return {*sink_, severities::KTrace}; } [[nodiscard]] Stream debug() const { - return {*sink_, Severity::Debug}; + return {*sink_, severities::KDebug}; } [[nodiscard]] Stream info() const { - return {*sink_, Severity::Info}; + return {*sink_, severities::KInfo}; } [[nodiscard]] Stream warn() const { - return {*sink_, Severity::Warning}; + return {*sink_, severities::KWarning}; } [[nodiscard]] Stream error() const { - return {*sink_, Severity::Error}; + return {*sink_, severities::KError}; } [[nodiscard]] Stream fatal() const { - return {*sink_, Severity::Fatal}; + return {*sink_, severities::KFatal}; } /** @} */ }; diff --git a/include/xrpl/beast/utility/WrappedSink.h b/include/xrpl/beast/utility/WrappedSink.h index 22d75927fe..57f0a02413 100644 --- a/include/xrpl/beast/utility/WrappedSink.h +++ b/include/xrpl/beast/utility/WrappedSink.h @@ -36,7 +36,7 @@ public: } [[nodiscard]] bool - active(beast::Severity level) const override + active(beast::severities::Severity level) const override { return sink_.active(level); } @@ -53,27 +53,27 @@ public: sink_.console(output); } - [[nodiscard]] beast::Severity + [[nodiscard]] beast::severities::Severity threshold() const override { return sink_.threshold(); } void - threshold(beast::Severity thresh) override + threshold(beast::severities::Severity thresh) override { sink_.threshold(thresh); } void - write(beast::Severity level, std::string const& text) override + write(beast::severities::Severity level, std::string const& text) override { using beast::Journal; sink_.write(level, prefix_ + text); } void - writeAlways(Severity level, std::string const& text) override + writeAlways(severities::Severity level, std::string const& text) override { using beast::Journal; sink_.writeAlways(level, prefix_ + text); diff --git a/include/xrpl/beast/utility/Zero.h b/include/xrpl/beast/utility/Zero.h index f54345d437..7825bb96e0 100644 --- a/include/xrpl/beast/utility/Zero.h +++ b/include/xrpl/beast/utility/Zero.h @@ -27,7 +27,7 @@ struct Zero }; namespace { -constexpr Zero kZero{}; +constexpr Zero kZERO{}; } // namespace /** Default implementation of signum calls the method on the class. */ @@ -102,42 +102,42 @@ template bool operator==(Zero, T const& t) { - return t == kZero; + return t == kZERO; } template bool operator!=(Zero, T const& t) { - return t != kZero; + return t != kZERO; } template bool operator<(Zero, T const& t) { - return t > kZero; + return t > kZERO; } template bool operator>(Zero, T const& t) { - return t < kZero; + return t < kZERO; } template bool operator>=(Zero, T const& t) { - return t <= kZero; + return t <= kZERO; } template bool operator<=(Zero, T const& t) { - return t >= kZero; + return t >= kZERO; } } // namespace beast diff --git a/include/xrpl/beast/utility/rngfill.h b/include/xrpl/beast/utility/rngfill.h index 1614a594c5..1bc8350d4f 100644 --- a/include/xrpl/beast/utility/rngfill.h +++ b/include/xrpl/beast/utility/rngfill.h @@ -14,23 +14,23 @@ void rngfill(void* const buffer, std::size_t const bytes, Generator& g) { using result_type = typename Generator::result_type; - constexpr std::size_t kResultSize = sizeof(result_type); + constexpr std::size_t kRESULT_SIZE = sizeof(result_type); std::uint8_t* const bufferStart = static_cast(buffer); - std::size_t const completeIterations = bytes / kResultSize; - std::size_t const bytesRemaining = bytes % kResultSize; + std::size_t const completeIterations = bytes / kRESULT_SIZE; + std::size_t const bytesRemaining = bytes % kRESULT_SIZE; for (std::size_t count = 0; count < completeIterations; ++count) { result_type const v = g(); - std::size_t const offset = count * kResultSize; - std::memcpy(bufferStart + offset, &v, kResultSize); + std::size_t const offset = count * kRESULT_SIZE; + std::memcpy(bufferStart + offset, &v, kRESULT_SIZE); } if (bytesRemaining > 0) { result_type const v = g(); - std::size_t const offset = completeIterations * kResultSize; + std::size_t const offset = completeIterations * kRESULT_SIZE; std::memcpy(bufferStart + offset, &v, bytesRemaining); } } diff --git a/include/xrpl/beast/xor_shift_engine.h b/include/xrpl/beast/xor_shift_engine.h index 45baecf101..3a5345934e 100644 --- a/include/xrpl/beast/xor_shift_engine.h +++ b/include/xrpl/beast/xor_shift_engine.h @@ -26,14 +26,12 @@ public: result_type operator()(); - static constexpr result_type - min() + static result_type constexpr min() { return std::numeric_limits::min(); } - static constexpr result_type - max() + static result_type constexpr max() { return std::numeric_limits::max(); } diff --git a/include/xrpl/conditions/Condition.h b/include/xrpl/conditions/Condition.h index 66d1d24736..0d45245585 100644 --- a/include/xrpl/conditions/Condition.h +++ b/include/xrpl/conditions/Condition.h @@ -27,7 +27,7 @@ public: that were previously considered valid to no longer be allowed. */ - static constexpr std::size_t kMaxSerializedCondition = 128; + static constexpr std::size_t kMAX_SERIALIZED_CONDITION = 128; /** Load a condition from its binary form diff --git a/include/xrpl/conditions/Fulfillment.h b/include/xrpl/conditions/Fulfillment.h index fd8cd7d31e..8b315297d7 100644 --- a/include/xrpl/conditions/Fulfillment.h +++ b/include/xrpl/conditions/Fulfillment.h @@ -16,7 +16,7 @@ public: that were previously considered valid to no longer be allowed. */ - static constexpr std::size_t kMaxSerializedFulfillment = 256; + static constexpr std::size_t kMAX_SERIALIZED_FULFILLMENT = 256; /** Load a fulfillment from its binary form diff --git a/include/xrpl/conditions/detail/PreimageSha256.h b/include/xrpl/conditions/detail/PreimageSha256.h index c592ea37ee..e3018f754c 100644 --- a/include/xrpl/conditions/detail/PreimageSha256.h +++ b/include/xrpl/conditions/detail/PreimageSha256.h @@ -23,7 +23,7 @@ public: While future versions of this code will never lower this limit, they may opt to raise it. */ - static constexpr std::size_t kMaxPreimageLength = 128; + static constexpr std::size_t kMAX_PREIMAGE_LENGTH = 128; /** Parse the payload for a PreimageSha256 condition @@ -65,7 +65,7 @@ public: return {}; } - if (s.size() > kMaxPreimageLength) + if (s.size() > kMAX_PREIMAGE_LENGTH) { ec = Error::PreimageTooLong; return {}; diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index 133caf37a9..4b876dc68d 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -6,7 +6,7 @@ namespace xrpl { /// Coroutine stack size (1.5 MB). Increased from 1 MB because /// ASAN-instrumented deep call stacks exceeded the original limit. -constexpr std::size_t kCoroStackSize = 1536 * 1024; +constexpr std::size_t kCORO_STACK_SIZE = 1536 * 1024; template JobQueue::Coro::Coro(CoroCreateT, JobQueue& jq, JobType type, std::string name, F&& f) @@ -14,7 +14,7 @@ JobQueue::Coro::Coro(CoroCreateT, JobQueue& jq, JobType type, std::string name, , type_(type) , name_(std::move(name)) , coro_( - boost::context::protected_fixedsize_stack(kCoroStackSize), + boost::context::protected_fixedsize_stack(kCORO_STACK_SIZE), [this, fn = std::forward(f)](boost::coroutines2::coroutine::push_type& doYield) { yield_ = &doYield; yield(); @@ -47,7 +47,7 @@ inline bool JobQueue::Coro::post() { { - std::scoped_lock const lk(mutexRun_); + std::scoped_lock const lk(mutex_run_); running_ = true; } @@ -58,7 +58,7 @@ JobQueue::Coro::post() } // The coroutine will not run. Clean up running_. - std::scoped_lock const lk(mutexRun_); + std::scoped_lock const lk(mutex_run_); running_ = false; cv_.notify_all(); return false; @@ -68,7 +68,7 @@ inline void JobQueue::Coro::resume() { { - std::scoped_lock const lk(mutexRun_); + std::scoped_lock const lk(mutex_run_); running_ = true; } { @@ -92,7 +92,7 @@ JobQueue::Coro::resume() } detail::getLocalValues().release(); detail::getLocalValues().reset(saved); - std::scoped_lock const lk(mutexRun_); + std::scoped_lock const lk(mutex_run_); running_ = false; cv_.notify_all(); } @@ -127,7 +127,7 @@ JobQueue::Coro::expectEarlyExit() inline void JobQueue::Coro::join() { - std::unique_lock lk(mutexRun_); + std::unique_lock lk(mutex_run_); cv_.wait(lk, [this]() { return !running_; }); } diff --git a/include/xrpl/core/Job.h b/include/xrpl/core/Job.h index 6af32eb2d8..b62488dec6 100644 --- a/include/xrpl/core/Job.h +++ b/include/xrpl/core/Job.h @@ -127,7 +127,7 @@ private: std::function job_; std::shared_ptr loadEvent_; std::string name_; - clock_type::time_point queueTime_; + clock_type::time_point queue_time_; }; using JobCounter = ClosureCounter; diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index fc15e9a064..2a96ea45fa 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -52,7 +52,7 @@ public: std::string name_; bool running_{false}; std::mutex mutex_; - std::mutex mutexRun_; + std::mutex mutex_run_; std::condition_variable cv_; boost::coroutines2::coroutine::push_type* yield_{}; boost::coroutines2::coroutine::pull_type coro_; @@ -246,7 +246,7 @@ private: // Statistics tracking perf::PerfLog& perfLog_; beast::insight::Collector::ptr collector_; - beast::insight::Gauge jobCount_; + beast::insight::Gauge job_count_; beast::insight::Hook hook_; std::condition_variable cv_; diff --git a/include/xrpl/core/JobTypes.h b/include/xrpl/core/JobTypes.h index fb5c7988cb..32a793c9dc 100644 --- a/include/xrpl/core/JobTypes.h +++ b/include/xrpl/core/JobTypes.h @@ -101,8 +101,8 @@ public: static JobTypes const& instance() { - static JobTypes const kTypes; - return kTypes; + static JobTypes const kTYPES; + return kTYPES; } static std::string const& diff --git a/include/xrpl/json/JsonPropertyStream.h b/include/xrpl/json/JsonPropertyStream.h index 47317b9ddb..47d3c9fdfa 100644 --- a/include/xrpl/json/JsonPropertyStream.h +++ b/include/xrpl/json/JsonPropertyStream.h @@ -5,7 +5,7 @@ namespace xrpl { -/** A PropertyStream::Sink which produces a json::Value of type ValueType::Object. */ +/** A PropertyStream::Sink which produces a json::Value of type objectValue. */ class JsonPropertyStream : public beast::PropertyStream { public: diff --git a/include/xrpl/json/Writer.h b/include/xrpl/json/Writer.h index 87e3e99c7e..664a2a75c1 100644 --- a/include/xrpl/json/Writer.h +++ b/include/xrpl/json/Writer.h @@ -161,7 +161,7 @@ public: * While the JSON spec doesn't explicitly disallow this, you should avoid * calling this method twice with the same tag for the same object. * - * If CHECK_JSON_WRITER is defined, this function throws an exception if + * If CHECK_JSON_WRITER is defined, this function throws an exception if if * the tag you use has already been used in this object. */ template diff --git a/include/xrpl/json/json_reader.h b/include/xrpl/json/json_reader.h index 9251183281..8ce565dbbc 100644 --- a/include/xrpl/json/json_reader.h +++ b/include/xrpl/json/json_reader.h @@ -67,25 +67,27 @@ public: [[nodiscard]] std::string getFormattedErrorMessages() const; - static constexpr unsigned kNestLimit{25}; + static constexpr unsigned kNEST_LIMIT{25}; private: - enum class TokenType { - EndOfStream = 0, - ObjectBegin, - ObjectEnd, - ArrayBegin, - ArrayEnd, - String, - Integer, - Double, - True, - False, - Null, - ArraySeparator, - MemberSeparator, - Comment, - Error + // 53 files, protocol-wide + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum TokenType { + TokenEndOfStream = 0, + TokenObjectBegin, + TokenObjectEnd, + TokenArrayBegin, + TokenArrayEnd, + TokenString, + TokenInteger, + TokenDouble, + TokenTrue, + TokenFalse, + TokenNull, + TokenArraySeparator, + TokenMemberSeparator, + TokenComment, + TokenError }; class Token diff --git a/include/xrpl/json/json_value.h b/include/xrpl/json/json_value.h index e9dcb8bcbe..2344da3788 100644 --- a/include/xrpl/json/json_value.h +++ b/include/xrpl/json/json_value.h @@ -15,20 +15,22 @@ namespace json { /** \brief Type of the value held by a Value object. */ -enum class ValueType { - Null = 0, ///< 'null' value - Int, ///< signed integer value - UInt, ///< unsigned integer value - Real, ///< double value - String, ///< UTF-8 string value - Boolean, ///< bool value - Array, ///< array value (ordered list) - Object ///< object value (collection of name/value pairs). +// Used throughout JSON layer +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum ValueType { + NullValue = 0, ///< 'null' value + IntValue, ///< signed integer value + UintValue, ///< unsigned integer value + RealValue, ///< double value + StringValue, ///< UTF-8 string value + BooleanValue, ///< bool value + ArrayValue, ///< array value (ordered list) + ObjectValue ///< object value (collection of name/value pairs). }; /** \brief Lightweight wrapper to tag static string. * - * Value constructor and ValueType::Object member assignment takes advantage of the + * Value constructor and objectValue member assignment takes advantage of the * StaticString and avoid the cost of string duplication when storing the * string or the member name. * @@ -102,8 +104,8 @@ operator!=(StaticString x, std::string const& y) /** \brief Represents a JSON value. * * This class is a discriminated union wrapper that can represent a: - * - signed integer [range: Value::kMinInt - Value::kMaxInt] - * - unsigned integer (range: 0 - Value::kMaxUInt) + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) * - double * - UTF-8 string * - boolean @@ -114,16 +116,16 @@ operator!=(StaticString x, std::string const& y) * The type of the held value is represented by a #ValueType and * can be obtained using type(). * - * values of an ValueType::Object or ValueType::Array can be accessed using operator[]() - * methods. Non const methods will automatically create the a ValueType::Null element + * values of an #objectValue or #arrayValue can be accessed using operator[]() + * methods. Non const methods will automatically create the a #nullValue element * if it does not exist. - * The sequence of an ValueType::Array will be automatically resize and initialized - * with ValueType::Null. resize() can be used to enlarge or truncate an ValueType::Array. + * The sequence of an #arrayValue will be automatically resize and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. * * The get() methods can be used to obtain a default value in the case the * required element does not exist. * - * It is possible to iterate over the list of a ValueType::Object values using + * It is possible to iterate over the list of a #objectValue values using * the getMemberNames() method. */ class Value @@ -138,16 +140,18 @@ public: using Int = json::Int; using ArrayIndex = UInt; - static Value const kNull; - static constexpr Int kMinInt = std::numeric_limits::min(); - static constexpr Int kMaxInt = std::numeric_limits::max(); - static constexpr UInt kMaxUInt = std::numeric_limits::max(); + static Value const kNULL; + static constexpr Int kMIN_INT = std::numeric_limits::min(); + static constexpr Int kMAX_INT = std::numeric_limits::max(); + static constexpr UInt kMAX_U_INT = std::numeric_limits::max(); private: class CZString { public: - enum class DuplicationPolicy { NoDuplication = 0, Duplicate, DuplicateOnCopy }; + // Stored as int field, implicit conversion + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum DuplicationPolicy { NoDuplication = 0, Duplicate, DuplicateOnCopy }; CZString(int index); CZString(char const* cstr, DuplicationPolicy allocate); @@ -178,19 +182,19 @@ public: /** \brief Create a default Value of the given type. This is a very useful constructor. - To create an empty array, pass ValueType::Array. - To create an empty object, pass ValueType::Object. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. Another Value can then be set to this one by assignment. This is useful since clear() and resize() will not alter types. Examples: \code json::Value null_value; // null - json::Value arr_value(json::ValueType::Array); // [] - json::Value obj_value(json::ValueType::Object); // {} + json::Value arr_value(json::arrayValue); // [] + json::Value obj_value(json::objectValue); // {} \endcode */ - Value(ValueType type = ValueType::Null); + Value(ValueType type = NullValue); Value(Int value); Value(UInt value); Value(double value); @@ -286,7 +290,7 @@ public: operator bool() const; /// Remove all object members and array elements. - /// \pre type() is ValueType::Array, ValueType::Object, or ValueType::Null + /// \pre type() is arrayValue, objectValue, or nullValue /// \post type() is unchanged void clear(); @@ -363,7 +367,7 @@ public: /// /// Do nothing if it did not exist. /// \return the removed Value, or null. - /// \pre type() is ValueType::Object or ValueType::Null + /// \pre type() is objectValue or nullValue /// \post type() is unchanged Value removeMember(char const* key); @@ -384,8 +388,8 @@ public: /// \brief Return a list of the member names. /// /// If null, return an empty list. - /// \pre type() is ValueType::Object or ValueType::Null - /// \post if type() was ValueType::Null, it remains ValueType::Null + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue [[nodiscard]] Members getMemberNames() const; @@ -465,14 +469,16 @@ operator>=(Value const& x, Value const& y) * string value memory management done by Value. * * - makeMemberName() and releaseMemberName() are called to respectively - * duplicate and free an json::ValueType::Object member name. + * duplicate and free an json::objectValue member name. * - duplicateStringValue() and releaseStringValue() are called similarly to - * duplicate and free a json::ValueType::String value. + * duplicate and free a json::stringValue value. */ class ValueAllocator { public: - static constexpr auto kUnknown = (unsigned)-1; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { Unknown = (unsigned)-1 }; virtual ~ValueAllocator() = default; @@ -481,7 +487,7 @@ public: virtual void releaseMemberName(char* memberName) = 0; virtual char* - duplicateStringValue(char const* value, unsigned int length = kUnknown) = 0; + duplicateStringValue(char const* value, unsigned int length = Unknown) = 0; virtual void releaseStringValue(char* value) = 0; }; @@ -517,12 +523,12 @@ public: [[nodiscard]] Value key() const; - /// Return the index of the referenced Value. -1 if it is not an ValueType::Array. + /// Return the index of the referenced Value. -1 if it is not an arrayValue. [[nodiscard]] UInt index() const; /// Return the member name of the referenced Value. "" if it is not an - /// ValueType::Object. + /// objectValue. [[nodiscard]] char const* memberName() const; diff --git a/include/xrpl/json/json_writer.h b/include/xrpl/json/json_writer.h index afc99fe8c9..8e5e819b10 100644 --- a/include/xrpl/json/json_writer.h +++ b/include/xrpl/json/json_writer.h @@ -204,31 +204,31 @@ writeValue(Write const& write, Value const& value) { switch (value.type()) { - case ValueType::Null: + case NullValue: write("null", 4); break; - case ValueType::Int: + case IntValue: writeString(write, valueToString(value.asInt())); break; - case ValueType::UInt: + case UintValue: writeString(write, valueToString(value.asUInt())); break; - case ValueType::Real: + case RealValue: writeString(write, valueToString(value.asDouble())); break; - case ValueType::String: + case StringValue: writeString(write, valueToQuotedString(value.asCString())); break; - case ValueType::Boolean: + case BooleanValue: writeString(write, valueToString(value.asBool())); break; - case ValueType::Array: { + case ArrayValue: { write("[", 1); int const size = value.size(); for (int index = 0; index < size; ++index) @@ -241,7 +241,7 @@ writeValue(Write const& write, Value const& value) break; } - case ValueType::Object: { + case ObjectValue: { Value::Members const members = value.getMemberNames(); write("{", 1); for (auto it = members.begin(); it != members.end(); ++it) diff --git a/include/xrpl/ledger/AmendmentTable.h b/include/xrpl/ledger/AmendmentTable.h index 8ed3cb81ff..a15433813d 100644 --- a/include/xrpl/ledger/AmendmentTable.h +++ b/include/xrpl/ledger/AmendmentTable.h @@ -67,7 +67,7 @@ public: [[nodiscard]] virtual json::Value getJson(bool isAdmin) const = 0; - /** Returns a json::ValueType::Object. */ + /** Returns a json::objectValue. */ [[nodiscard]] virtual json::Value getJson(uint256 const& amendment, bool isAdmin) const = 0; diff --git a/include/xrpl/ledger/ApplyView.h b/include/xrpl/ledger/ApplyView.h index 362eae0f79..f825311e1d 100644 --- a/include/xrpl/ledger/ApplyView.h +++ b/include/xrpl/ledger/ApplyView.h @@ -123,7 +123,7 @@ private: bool preserveOrder, Keylet const& directory, uint256 const& key, - std::function const& describe); + std::function const&)> const& describe); public: ApplyView() = default; @@ -153,7 +153,7 @@ public: @return `nullptr` if the key is not present */ - virtual SLE::pointer + virtual std::shared_ptr peek(Keylet const& k) = 0; /** Remove a peeked SLE. @@ -168,7 +168,7 @@ public: The key is no longer associated with the SLE. */ virtual void - erase(SLE::ref sle) = 0; + erase(std::shared_ptr const& sle) = 0; /** Insert a new state SLE @@ -189,7 +189,7 @@ public: @note The key is taken from the SLE */ virtual void - insert(SLE::ref sle) = 0; + insert(std::shared_ptr const& sle) = 0; /** Indicate changes to a peeked SLE @@ -208,7 +208,7 @@ public: */ /** @{ */ virtual void - update(SLE::ref sle) = 0; + update(std::shared_ptr const& sle) = 0; //-------------------------------------------------------------------------- @@ -301,7 +301,7 @@ public: dirAppend( Keylet const& directory, Keylet const& key, - std::function const& describe) + std::function const&)> const& describe) { if (key.type != ltOFFER) { @@ -340,7 +340,7 @@ public: dirInsert( Keylet const& directory, uint256 const& key, - std::function const& describe) + std::function const&)> const& describe) { return dirAdd(false, directory, key, describe); } @@ -349,7 +349,7 @@ public: dirInsert( Keylet const& directory, Keylet const& key, - std::function const& describe) + std::function const&)> const& describe) { return dirAdd(false, directory, key.key, describe); } @@ -411,7 +411,7 @@ createRoot( ApplyView& view, Keylet const& directory, uint256 const& key, - std::function const& describe); + std::function const&)> const& describe); auto findPreviousPage(ApplyView& view, Keylet const& directory, SLE::ref start); @@ -434,7 +434,7 @@ insertPage( SLE::ref next, uint256 const& key, Keylet const& directory, - std::function const& describe); + std::function const&)> const& describe); } // namespace directory } // namespace xrpl diff --git a/include/xrpl/ledger/ApplyViewImpl.h b/include/xrpl/ledger/ApplyViewImpl.h index 1245568630..7f790f2be5 100644 --- a/include/xrpl/ledger/ApplyViewImpl.h +++ b/include/xrpl/ledger/ApplyViewImpl.h @@ -67,8 +67,8 @@ public: std::function const& func); + std::shared_ptr const& before, + std::shared_ptr const& after)> const& func); private: std::optional deliver_; diff --git a/include/xrpl/ledger/BookDirs.h b/include/xrpl/ledger/BookDirs.h index 36798934da..afde6ee7b3 100644 --- a/include/xrpl/ledger/BookDirs.h +++ b/include/xrpl/ledger/BookDirs.h @@ -9,15 +9,15 @@ class BookDirs private: ReadView const* view_ = nullptr; uint256 const root_; - uint256 const nextQuality_; + uint256 const next_quality_; uint256 const key_; - SLE::const_pointer sle_ = nullptr; + std::shared_ptr sle_ = nullptr; unsigned int entry_ = 0; uint256 index_; public: class const_iterator; // NOLINT(readability-identifier-naming) - using value_type = SLE::const_pointer; + using value_type = std::shared_ptr; BookDirs(ReadView const&, Book const&); @@ -67,16 +67,16 @@ private: friend class BookDirs; const_iterator(ReadView const& view, uint256 const& root, uint256 const& dirKey) - : view_(&view), root_(root), key_(dirKey), curKey_(dirKey) + : view_(&view), root_(root), key_(dirKey), cur_key_(dirKey) { } ReadView const* view_ = nullptr; uint256 root_; - uint256 nextQuality_; + uint256 next_quality_; uint256 key_; - uint256 curKey_; - SLE::const_pointer sle_; + uint256 cur_key_; + std::shared_ptr sle_; unsigned int entry_ = 0; uint256 index_; std::optional mutable cache_; diff --git a/include/xrpl/ledger/CachedView.h b/include/xrpl/ledger/CachedView.h index 462db48ee3..34a75e4c07 100644 --- a/include/xrpl/ledger/CachedView.h +++ b/include/xrpl/ledger/CachedView.h @@ -36,7 +36,7 @@ public: bool exists(Keylet const& k) const override; - SLE::const_pointer + std::shared_ptr read(Keylet const& k) const override; bool diff --git a/include/xrpl/ledger/Dir.h b/include/xrpl/ledger/Dir.h index d305e21938..cfbef357b1 100644 --- a/include/xrpl/ledger/Dir.h +++ b/include/xrpl/ledger/Dir.h @@ -22,12 +22,12 @@ class Dir private: ReadView const* view_ = nullptr; Keylet root_; - SLE::const_pointer sle_; + std::shared_ptr sle_; STVector256 const* indexes_ = nullptr; public: class ConstIterator; - using value_type = SLE::const_pointer; + using value_type = std::shared_ptr; Dir(ReadView const&, Keylet const&); @@ -102,7 +102,7 @@ private: Keylet page_; uint256 index_; std::optional mutable cache_; - SLE::const_pointer sle_; + std::shared_ptr sle_; STVector256 const* indexes_ = nullptr; std::vector::const_iterator it_; }; diff --git a/include/xrpl/ledger/Ledger.h b/include/xrpl/ledger/Ledger.h index 5f7d79c61d..2d6f48db2d 100644 --- a/include/xrpl/ledger/Ledger.h +++ b/include/xrpl/ledger/Ledger.h @@ -24,7 +24,7 @@ struct CreateGenesisT { explicit CreateGenesisT() = default; }; -extern CreateGenesisT const kCreateGenesis; +extern CreateGenesisT const kCREATE_GENESIS; /** Holds a ledger. @@ -166,7 +166,7 @@ public: std::optional succ(uint256 const& key, std::optional const& last = std::nullopt) const override; - SLE::const_pointer + std::shared_ptr read(Keylet const& k) const override; std::unique_ptr @@ -202,16 +202,16 @@ public: // void - rawErase(SLE::ref sle) override; + rawErase(std::shared_ptr const& sle) override; void - rawInsert(SLE::ref sle) override; + rawInsert(std::shared_ptr const& sle) override; void rawErase(uint256 const& key); void - rawReplace(SLE::ref sle) override; + rawReplace(std::shared_ptr const& sle) override; void rawDestroyXRP(XRPAmount const& fee) override @@ -361,7 +361,7 @@ public: bool isVotingLedger() const; - SLE::pointer + std::shared_ptr peek(Keylet const& k) const; private: diff --git a/include/xrpl/ledger/LedgerTiming.h b/include/xrpl/ledger/LedgerTiming.h index 508403d760..dce28bd44b 100644 --- a/include/xrpl/ledger/LedgerTiming.h +++ b/include/xrpl/ledger/LedgerTiming.h @@ -12,7 +12,7 @@ namespace xrpl { Values should not be duplicated. @see getNextLedgerTimeResolution */ -constexpr std::chrono::seconds kLedgerPossibleTimeResolutions[] = { +std::chrono::seconds constexpr kLEDGER_POSSIBLE_TIME_RESOLUTIONS[] = { std::chrono::seconds{10}, std::chrono::seconds{20}, std::chrono::seconds{30}, @@ -21,16 +21,16 @@ constexpr std::chrono::seconds kLedgerPossibleTimeResolutions[] = { std::chrono::seconds{120}}; //! Initial resolution of ledger close time. -constexpr auto kLedgerDefaultTimeResolution = kLedgerPossibleTimeResolutions[2]; +auto constexpr kLEDGER_DEFAULT_TIME_RESOLUTION = kLEDGER_POSSIBLE_TIME_RESOLUTIONS[2]; //! Close time resolution in genesis ledger -constexpr auto kLedgerGenesisTimeResolution = kLedgerPossibleTimeResolutions[0]; +auto constexpr kLEDGER_GENESIS_TIME_RESOLUTION = kLEDGER_POSSIBLE_TIME_RESOLUTIONS[0]; //! How often we increase the close time resolution (in numbers of ledgers) -constexpr auto kIncreaseLedgerTimeResolutionEvery = 8; +auto constexpr kINCREASE_LEDGER_TIME_RESOLUTION_EVERY = 8; //! How often we decrease the close time resolution (in numbers of ledgers) -constexpr auto kDecreaseLedgerTimeResolutionEvery = 1; +auto constexpr kDECREASE_LEDGER_TIME_RESOLUTION_EVERY = 1; /** Calculates the close time resolution for the specified ledger. @@ -46,7 +46,7 @@ constexpr auto kDecreaseLedgerTimeResolutionEvery = 1; @param ledgerSeq the sequence number of the new ledger @pre previousResolution must be a valid bin - from @ref kLedgerPossibleTimeResolutions + from @ref kLEDGER_POSSIBLE_TIME_RESOLUTIONS @tparam Rep Type representing number of ticks in std::chrono::duration @tparam Period An std::ratio representing tick period in @@ -67,30 +67,30 @@ getNextLedgerTimeResolution( using namespace std::chrono; // Find the current resolution: auto iter = std::find( - std::begin(kLedgerPossibleTimeResolutions), - std::end(kLedgerPossibleTimeResolutions), + std::begin(kLEDGER_POSSIBLE_TIME_RESOLUTIONS), + std::end(kLEDGER_POSSIBLE_TIME_RESOLUTIONS), previousResolution); XRPL_ASSERT( - iter != std::end(kLedgerPossibleTimeResolutions), + iter != std::end(kLEDGER_POSSIBLE_TIME_RESOLUTIONS), "xrpl::getNextLedgerTimeResolution : found time resolution"); // This should never happen, but just as a precaution - if (iter == std::end(kLedgerPossibleTimeResolutions)) + if (iter == std::end(kLEDGER_POSSIBLE_TIME_RESOLUTIONS)) return previousResolution; // If we did not previously agree, we try to decrease the resolution to // improve the chance that we will agree now. - if (!previousAgree && (ledgerSeq % Seq{kDecreaseLedgerTimeResolutionEvery} == Seq{0})) + if (!previousAgree && (ledgerSeq % Seq{kDECREASE_LEDGER_TIME_RESOLUTION_EVERY} == Seq{0})) { - if (++iter != std::end(kLedgerPossibleTimeResolutions)) + if (++iter != std::end(kLEDGER_POSSIBLE_TIME_RESOLUTIONS)) return *iter; } // If we previously agreed, we try to increase the resolution to determine // if we can continue to agree. - if (previousAgree && (ledgerSeq % Seq{kIncreaseLedgerTimeResolutionEvery} == Seq{0})) + if (previousAgree && (ledgerSeq % Seq{kINCREASE_LEDGER_TIME_RESOLUTION_EVERY} == Seq{0})) { - if (iter-- != std::begin(kLedgerPossibleTimeResolutions)) + if (iter-- != std::begin(kLEDGER_POSSIBLE_TIME_RESOLUTIONS)) return *iter; } diff --git a/include/xrpl/ledger/OpenView.h b/include/xrpl/ledger/OpenView.h index 4ba2a7759b..59ab733211 100644 --- a/include/xrpl/ledger/OpenView.h +++ b/include/xrpl/ledger/OpenView.h @@ -23,7 +23,7 @@ namespace xrpl { inline constexpr struct OpenLedgerT { explicit constexpr OpenLedgerT() = default; -} kOpenLedger{}; +} kOPEN_LEDGER{}; /** Batch view construction tag. @@ -33,7 +33,7 @@ inline constexpr struct OpenLedgerT inline constexpr struct BatchViewT { explicit constexpr BatchViewT() = default; -} kBatchView{}; +} kBATCH_VIEW{}; //------------------------------------------------------------------------------ @@ -47,7 +47,7 @@ private: // Initial size for the monotonic_buffer_resource used for allocations // The size was chosen from the old `qalloc` code (which this replaces). // It is unclear how the size initially chosen in qalloc. - static constexpr size_t kInitialBufferSize = kilobytes(256); + static constexpr size_t kINITIAL_BUFFER_SIZE = kilobytes(256); class TxsIterImpl; @@ -76,7 +76,7 @@ private: // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr monotonicResource_; + std::unique_ptr monotonic_resource_; txs_map txs_; Rules rules_; LedgerHeader header_; @@ -139,7 +139,7 @@ public: std::shared_ptr hold = nullptr); OpenView(OpenLedgerT, Rules const& rules, std::shared_ptr const& base) - : OpenView(kOpenLedger, &*base, rules, base) + : OpenView(kOPEN_LEDGER, &*base, rules, base) { } @@ -197,7 +197,7 @@ public: std::optional succ(key_type const& key, std::optional const& last = std::nullopt) const override; - SLE::const_pointer + std::shared_ptr read(Keylet const& k) const override; std::unique_ptr @@ -224,13 +224,13 @@ public: // RawView void - rawErase(SLE::ref sle) override; + rawErase(std::shared_ptr const& sle) override; void - rawInsert(SLE::ref sle) override; + rawInsert(std::shared_ptr const& sle) override; void - rawReplace(SLE::ref sle) override; + rawReplace(std::shared_ptr const& sle) override; void rawDestroyXRP(XRPAmount const& fee) override; diff --git a/include/xrpl/ledger/RawView.h b/include/xrpl/ledger/RawView.h index cf61c3e814..cfcf807e13 100644 --- a/include/xrpl/ledger/RawView.h +++ b/include/xrpl/ledger/RawView.h @@ -25,7 +25,7 @@ public: can calculate metadata. */ virtual void - rawErase(SLE::ref sle) = 0; + rawErase(std::shared_ptr const& sle) = 0; /** Unconditionally insert a state item. @@ -39,7 +39,7 @@ public: @note The key is taken from the SLE */ virtual void - rawInsert(SLE::ref sle) = 0; + rawInsert(std::shared_ptr const& sle) = 0; /** Unconditionally replace a state item. @@ -54,7 +54,7 @@ public: @note The key is taken from the SLE */ virtual void - rawReplace(SLE::ref sle) = 0; + rawReplace(std::shared_ptr const& sle) = 0; /** Destroy XRP. diff --git a/include/xrpl/ledger/ReadView.h b/include/xrpl/ledger/ReadView.h index f4ee7e6fd2..4f9bf9c31d 100644 --- a/include/xrpl/ledger/ReadView.h +++ b/include/xrpl/ledger/ReadView.h @@ -34,9 +34,9 @@ public: using key_type = uint256; - using mapped_type = SLE::const_pointer; + using mapped_type = std::shared_ptr; - struct SlesType : detail::ReadViewFwdRange + struct SlesType : detail::ReadViewFwdRange> { explicit SlesType(ReadView const& view); [[nodiscard]] Iterator @@ -143,7 +143,7 @@ public: @return `nullptr` if the key is not present or if the type does not match. */ - [[nodiscard]] virtual SLE::const_pointer + [[nodiscard]] virtual std::shared_ptr read(Keylet const& k) const = 0; // Accounts in a payment are not allowed to use assets acquired during that diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index 255413e459..4958a89d8c 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -56,7 +57,7 @@ isVaultPseudoAccountFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptShare, - std::uint8_t depth); + int depth); [[nodiscard]] bool isLPTokenFrozen( @@ -134,7 +135,7 @@ areCompatible( dirLink( ApplyView& view, AccountID const& owner, - SLE::pointer& object, + std::shared_ptr& object, SF_UINT64 const& node = sfOwnerNode); /** Checks that can withdraw funds from an object to itself or a destination. @@ -214,8 +215,8 @@ doWithdraw( * (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&, SLE::pointer&)>; +using EntryDeleter = std::function< + std::pair(LedgerEntryType, uint256 const&, std::shared_ptr&)>; /** Cleanup owner directory entries on account delete. * Used for a regular and AMM accounts deletion. The caller * has to provide the deleter function, which handles details of diff --git a/include/xrpl/ledger/detail/ApplyStateTable.h b/include/xrpl/ledger/detail/ApplyStateTable.h index f40e3d0d1c..7b18f742b4 100644 --- a/include/xrpl/ledger/detail/ApplyStateTable.h +++ b/include/xrpl/ledger/detail/ApplyStateTable.h @@ -8,6 +8,8 @@ #include #include +#include + namespace xrpl::detail { // Helper class that buffers modifications @@ -24,7 +26,7 @@ private: Modify, }; - using items_t = std::map>; + using items_t = std::map>>; items_t items_; XRPAmount dropsDestroyed_{0}; @@ -58,10 +60,10 @@ public: [[nodiscard]] std::optional succ(ReadView const& base, key_type const& key, std::optional const& last) const; - [[nodiscard]] SLE::const_pointer + [[nodiscard]] std::shared_ptr read(ReadView const& base, Keylet const& k) const; - SLE::pointer + std::shared_ptr peek(ReadView const& base, Keylet const& k); [[nodiscard]] std::size_t @@ -73,23 +75,23 @@ public: std::function const& func) const; + std::shared_ptr const& before, + std::shared_ptr const& after)> const& func) const; void - erase(ReadView const& base, SLE::ref sle); + erase(ReadView const& base, std::shared_ptr const& sle); void - rawErase(ReadView const& base, SLE::ref sle); + rawErase(ReadView const& base, std::shared_ptr const& sle); void - insert(ReadView const& base, SLE::ref sle); + insert(ReadView const& base, std::shared_ptr const& sle); void - update(ReadView const& base, SLE::ref sle); + update(ReadView const& base, std::shared_ptr const& sle); void - replace(ReadView const& base, SLE::ref sle); + replace(ReadView const& base, std::shared_ptr const& sle); void destroyXRP(XRPAmount const& fee); @@ -102,12 +104,12 @@ public: } private: - using Mods = hash_map; + using Mods = hash_map>; static void - threadItem(TxMeta& meta, SLE::ref to); + threadItem(TxMeta& meta, std::shared_ptr const& to); - SLE::pointer + std::shared_ptr getForMod(ReadView const& base, key_type const& key, Mods& mods, beast::Journal j); void @@ -117,7 +119,7 @@ private: threadOwners( ReadView const& base, TxMeta& meta, - SLE::const_ref sle, + std::shared_ptr const& sle, Mods& mods, beast::Journal j); }; diff --git a/include/xrpl/ledger/detail/ApplyViewBase.h b/include/xrpl/ledger/detail/ApplyViewBase.h index d6493c46a8..558c9e5d4d 100644 --- a/include/xrpl/ledger/detail/ApplyViewBase.h +++ b/include/xrpl/ledger/detail/ApplyViewBase.h @@ -40,7 +40,7 @@ public: [[nodiscard]] std::optional succ(key_type const& key, std::optional const& last = std::nullopt) const override; - [[nodiscard]] SLE::const_pointer + [[nodiscard]] std::shared_ptr read(Keylet const& k) const override; [[nodiscard]] std::unique_ptr @@ -69,28 +69,28 @@ public: [[nodiscard]] ApplyFlags flags() const override; - SLE::pointer + std::shared_ptr peek(Keylet const& k) override; void - erase(SLE::ref sle) override; + erase(std::shared_ptr const& sle) override; void - insert(SLE::ref sle) override; + insert(std::shared_ptr const& sle) override; void - update(SLE::ref sle) override; + update(std::shared_ptr const& sle) override; // RawView void - rawErase(SLE::ref sle) override; + rawErase(std::shared_ptr const& sle) override; void - rawInsert(SLE::ref sle) override; + rawInsert(std::shared_ptr const& sle) override; void - rawReplace(SLE::ref sle) override; + rawReplace(std::shared_ptr const& sle) override; void rawDestroyXRP(XRPAmount const& feeDrops) override; diff --git a/include/xrpl/ledger/detail/RawStateTable.h b/include/xrpl/ledger/detail/RawStateTable.h index d2567e34f1..169a7c505e 100644 --- a/include/xrpl/ledger/detail/RawStateTable.h +++ b/include/xrpl/ledger/detail/RawStateTable.h @@ -19,17 +19,17 @@ public: // Initial size for the monotonic_buffer_resource used for allocations // The size was chosen from the old `qalloc` code (which this replaces). // It is unclear how the size initially chosen in qalloc. - static constexpr size_t kInitialBufferSize = kilobytes(256); + static constexpr size_t kINITIAL_BUFFER_SIZE = kilobytes(256); RawStateTable() - : monotonicResource_{std::make_unique( - kInitialBufferSize)} - , items_{monotonicResource_.get()} {}; + : monotonic_resource_{std::make_unique( + kINITIAL_BUFFER_SIZE)} + , items_{monotonic_resource_.get()} {}; RawStateTable(RawStateTable const& rhs) - : monotonicResource_{std::make_unique( - kInitialBufferSize)} - , items_{rhs.items_, monotonicResource_.get()} + : monotonic_resource_{std::make_unique( + kINITIAL_BUFFER_SIZE)} + , items_{rhs.items_, monotonic_resource_.get()} , dropsDestroyed_{rhs.dropsDestroyed_} {}; RawStateTable(RawStateTable&&) = default; @@ -49,15 +49,15 @@ public: succ(ReadView const& base, key_type const& key, std::optional const& last) const; void - erase(SLE::ref sle); + erase(std::shared_ptr const& sle); void - insert(SLE::ref sle); + insert(std::shared_ptr const& sle); void - replace(SLE::ref sle); + replace(std::shared_ptr const& sle); - [[nodiscard]] SLE::const_pointer + [[nodiscard]] std::shared_ptr read(ReadView const& base, Keylet const& k) const; void @@ -84,10 +84,10 @@ private: struct SleAction { Action action; - SLE::pointer sle; + std::shared_ptr sle; // Constructor needed for emplacement in std::map - SleAction(Action action, SLE::pointer sle) : action(action), sle(std::move(sle)) + SleAction(Action action, std::shared_ptr const& sle) : action(action), sle(sle) { } }; @@ -101,7 +101,7 @@ private: boost::container::pmr::polymorphic_allocator>>; // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr monotonicResource_; + std::unique_ptr monotonic_resource_; items_t items_; XRPAmount dropsDestroyed_{0}; diff --git a/include/xrpl/ledger/helpers/AMMHelpers.h b/include/xrpl/ledger/helpers/AMMHelpers.h index 61d6e9d2fb..c62437bf75 100644 --- a/include/xrpl/ledger/helpers/AMMHelpers.h +++ b/include/xrpl/ledger/helpers/AMMHelpers.h @@ -25,11 +25,11 @@ namespace detail { Number reduceOffer(auto const& amount) { - static Number const kReducedOfferPct(9999, -4); + static Number const kREDUCED_OFFER_PCT(9999, -4); // Make sure the result is always less than amount or zero. NumberRoundModeGuard const mg(Number::RoundingMode::TowardsZero); - return amount * kReducedOfferPct; + return amount * kREDUCED_OFFER_PCT; } } // namespace detail @@ -177,7 +177,7 @@ getAMMOfferStartWithTakerGets( Quality const& targetQuality, std::uint16_t const& tfee) { - if (targetQuality.rate() == beast::kZero) + if (targetQuality.rate() == beast::kZERO) return std::nullopt; NumberRoundModeGuard const mg(Number::RoundingMode::ToNearest); @@ -244,7 +244,7 @@ getAMMOfferStartWithTakerPays( Quality const& targetQuality, std::uint16_t tfee) { - if (targetQuality.rate() == beast::kZero) + if (targetQuality.rate() == beast::kZERO) return std::nullopt; NumberRoundModeGuard const mg(Number::RoundingMode::ToNearest); @@ -792,7 +792,7 @@ deleteAMMAccount(Sandbox& view, Asset const& asset, Asset const& asset2, beast:: void initializeFeeAuctionVote( ApplyView& view, - SLE::pointer& ammSle, + std::shared_ptr& ammSle, AccountID const& account, Asset const& lptAsset, std::uint16_t tfee); @@ -812,7 +812,7 @@ Expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, - SLE::pointer& ammSle, + std::shared_ptr& ammSle, AccountID const& account); } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/AccountRootHelpers.h b/include/xrpl/ledger/helpers/AccountRootHelpers.h index c02cad98d8..353c27fe41 100644 --- a/include/xrpl/ledger/helpers/AccountRootHelpers.h +++ b/include/xrpl/ledger/helpers/AccountRootHelpers.h @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -35,7 +36,11 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, /** Adjust the owner count up or down. */ void -adjustOwnerCount(ApplyView& view, SLE::ref sle, std::int32_t amount, beast::Journal j); +adjustOwnerCount( + ApplyView& view, + std::shared_ptr const& sle, + std::int32_t amount, + beast::Journal j); /** Returns IOU issuer transfer fee as Rate. Rate specifies * the fee as fractions of 1 billion. For example, 1% transfer rate @@ -71,7 +76,9 @@ getPseudoAccountFields(); - null pointer */ [[nodiscard]] bool -isPseudoAccount(SLE::const_pointer sleAcct, std::set const& pseudoFieldFilter = {}); +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter = {}); /** Convenience overload that reads the account from the view. */ [[nodiscard]] inline bool @@ -91,7 +98,7 @@ isPseudoAccount( * before using a field. The amendment check is **not** performed in * createPseudoAccount. */ -[[nodiscard]] Expected +[[nodiscard]] Expected, TER> createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); /** Checks the destination and tag. diff --git a/include/xrpl/ledger/helpers/CredentialHelpers.h b/include/xrpl/ledger/helpers/CredentialHelpers.h index b70b28ec02..43d7f47518 100644 --- a/include/xrpl/ledger/helpers/CredentialHelpers.h +++ b/include/xrpl/ledger/helpers/CredentialHelpers.h @@ -19,11 +19,15 @@ namespace credentials { // Check if credential sfExpiration field has passed ledger's parentCloseTime bool -checkExpired(SLE 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 +removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j); // Actually remove a credentials object from the ledger -[[nodiscard]] TER -deleteSLE(ApplyView& view, SLE::ref sleCredential, beast::Journal j); +TER +deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Journal j); // Amendment and parameters checks for sfCredentialIDs field NotTEC @@ -84,7 +88,7 @@ verifyDepositPreauth( ApplyView& view, AccountID const& src, AccountID const& dst, - SLE::const_ref sleDst, + std::shared_ptr const& sleDst, beast::Journal j); } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/DelegateHelpers.h b/include/xrpl/ledger/helpers/DelegateHelpers.h index 9cdad7173d..78ccc46d0b 100644 --- a/include/xrpl/ledger/helpers/DelegateHelpers.h +++ b/include/xrpl/ledger/helpers/DelegateHelpers.h @@ -15,7 +15,7 @@ namespace xrpl { * if not. */ NotTEC -checkTxPermission(SLE::const_ref delegate, STTx const& tx); +checkTxPermission(std::shared_ptr const& delegate, STTx const& tx); /** * Load the granular permissions granted to the delegate account for the @@ -28,7 +28,7 @@ checkTxPermission(SLE::const_ref delegate, STTx const& tx); */ void loadGranularPermission( - SLE::const_ref delegate, + std::shared_ptr const& delegate, TxType const& type, std::unordered_set& granularPermissions); diff --git a/include/xrpl/ledger/helpers/DirectoryHelpers.h b/include/xrpl/ledger/helpers/DirectoryHelpers.h index a0be52df99..2ae188182d 100644 --- a/include/xrpl/ledger/helpers/DirectoryHelpers.h +++ b/include/xrpl/ledger/helpers/DirectoryHelpers.h @@ -115,7 +115,7 @@ bool cdirFirst( ReadView const& view, uint256 const& root, - SLE::const_pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry); @@ -123,7 +123,7 @@ bool dirFirst( ApplyView& view, uint256 const& root, - SLE::pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry); /** @} */ @@ -147,7 +147,7 @@ bool cdirNext( ReadView const& view, uint256 const& root, - SLE::const_pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry); @@ -155,14 +155,17 @@ bool dirNext( ApplyView& view, uint256 const& root, - SLE::pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry); /** @} */ /** Iterate all items in the given directory. */ void -forEachItem(ReadView const& view, Keylet const& root, std::function 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 @@ -177,11 +180,14 @@ forEachItemAfter( uint256 const& after, std::uint64_t const hint, unsigned int limit, - std::function const& f); + std::function const&)> const& f); /** Iterate all items in an account's owner directory. */ inline void -forEachItem(ReadView const& view, AccountID const& id, std::function const& f) +forEachItem( + ReadView const& view, + AccountID const& id, + std::function const&)> const& f) { forEachItem(view, keylet::ownerDir(id), f); } @@ -199,7 +205,7 @@ forEachItemAfter( uint256 const& after, std::uint64_t const hint, unsigned int limit, - std::function const& f) + std::function const&)> const& f) { return forEachItemAfter(view, keylet::ownerDir(id), after, hint, limit, f); } diff --git a/include/xrpl/ledger/helpers/EscrowHelpers.h b/include/xrpl/ledger/helpers/EscrowHelpers.h index bdb83230eb..5aa5214b1f 100644 --- a/include/xrpl/ledger/helpers/EscrowHelpers.h +++ b/include/xrpl/ledger/helpers/EscrowHelpers.h @@ -18,7 +18,7 @@ TER escrowUnlockApplyHelper( ApplyView& view, Rate lockedRate, - SLE::ref sleDest, + std::shared_ptr const& sleDest, STAmount const& xrpBalance, STAmount const& amount, AccountID const& issuer, @@ -32,7 +32,7 @@ inline TER escrowUnlockApplyHelper( ApplyView& view, Rate lockedRate, - SLE::ref sleDest, + std::shared_ptr const& sleDest, STAmount const& xrpBalance, STAmount const& amount, AccountID const& issuer, @@ -70,21 +70,21 @@ escrowUnlockApplyHelper( initialBalance.get().account = noAccount(); if (TER const ter = trustCreate( - view, // payment sandbox - recvLow, // is dest low? - issuer, // source - receiver, // destination - trustLineKey.key, // ledger index - sleDest, // Account to add to - false, // authorize account - !sleDest->isFlag(lsfDefaultRipple), // - false, // freeze trust line - false, // deep freeze trust line - initialBalance, // zero initial balance - Issue(currency, receiver), // limit of zero - 0, // quality in - 0, // quality out - journal); // journal + view, // payment sandbox + recvLow, // is dest low? + issuer, // source + receiver, // destination + trustLineKey.key, // ledger index + sleDest, // Account to add to + false, // authorize account + (sleDest->getFlags() & lsfDefaultRipple) == 0, // + false, // freeze trust line + false, // deep freeze trust line + initialBalance, // zero initial balance + Issue(currency, receiver), // limit of zero + 0, // quality in + 0, // quality out + journal); // journal !isTesSuccess(ter)) { return ter; // LCOV_EXCL_LINE @@ -111,7 +111,7 @@ escrowUnlockApplyHelper( // whereas in a normal payment, the transfer fee is taken on top of the // sending amount. auto finalAmt = amount; - if ((!senderIssuer && !receiverIssuer) && lockedRate != kParityRate) + if ((!senderIssuer && !receiverIssuer) && lockedRate != kPARITY_RATE) { // compute transfer fee, if any auto const xferFee = @@ -162,7 +162,7 @@ inline TER escrowUnlockApplyHelper( ApplyView& view, Rate lockedRate, - SLE::ref sleDest, + std::shared_ptr const& sleDest, STAmount const& xrpBalance, STAmount const& amount, AccountID const& issuer, @@ -211,7 +211,7 @@ escrowUnlockApplyHelper( // whereas in a normal payment, the transfer fee is taken on top of the // sending amount. auto finalAmt = amount; - if ((!senderIssuer && !receiverIssuer) && lockedRate != kParityRate) + if ((!senderIssuer && !receiverIssuer) && lockedRate != kPARITY_RATE) { // compute transfer fee, if any auto const xferFee = amount.value() - divideRound(amount, lockedRate, amount.asset(), true); diff --git a/include/xrpl/ledger/helpers/LendingHelpers.h b/include/xrpl/ledger/helpers/LendingHelpers.h index 32f94ee277..83ce8e5efa 100644 --- a/include/xrpl/ledger/helpers/LendingHelpers.h +++ b/include/xrpl/ledger/helpers/LendingHelpers.h @@ -4,43 +4,13 @@ #include #include -#include - namespace xrpl { -/** - * Broker cover preclaim precision guard (fixCleanup3_2_0). - * - * Prevents a "silent sub-ULP no-op" where a deposit, withdrawal, or clawback - * amount is so small that it rounds to zero at `sfCoverAvailable`'s scale. - * Without this guard, both the pseudo trust-line and `sfCoverAvailable` would - * identically absorb the rounded zero, resulting in a successful transaction - * (tesSUCCESS) where no funds actually moved. - * - * @param view Read view (rules used for amendment gating). - * @param sleBroker The loan broker SLE (read-only). - * @param vaultAsset The underlying vault asset (the broker's cover asset). - * @param amount The effective subtraction/addition amount. - * @param j Journal for logging. - * @param logPrefix Transactor name for log diagnostics. - * - * @return `tecPRECISION_LOSS` if the request rounds to zero at cover scale. - * `tesSUCCESS` if the amendment is disabled or the request is safely supra-ULP. - */ -[[nodiscard]] TER -canApplyToBrokerCover( - ReadView const& view, - SLE::const_ref sleBroker, - Asset const& vaultAsset, - STAmount const& amount, - beast::Journal j, - std::string_view logPrefix); - // Lending protocol has dependencies, so capture them here. bool checkLendingProtocolDependencies(Rules const& rules, STTx const& tx); -static constexpr std::uint32_t kSecondsInYear = 365 * 24 * 60 * 60; +static constexpr std::uint32_t kSECONDS_IN_YEAR = 365 * 24 * 60 * 60; Number loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval); @@ -72,14 +42,14 @@ struct LoanPaymentParts // The amount of principal paid that reduces the loan balance. // This amount is subtracted from sfPrincipalOutstanding in the Loan object // and paid to the Vault - Number principalPaid = kNumZero; + Number principalPaid = kNUM_ZERO; // The total amount of interest paid to the Vault. // This includes: // - Tracked interest from the amortization schedule // - Untracked interest (e.g., late payment penalty interest) // This value is always non-negative. - Number interestPaid = kNumZero; + Number interestPaid = kNUM_ZERO; // The change in the loan's total value outstanding. // - If valueChange < 0: Loan value decreased @@ -92,7 +62,7 @@ struct LoanPaymentParts // - Late payments add penalty interest to the loan value // - Early full payment may increase or decrease the loan value based on // terms - Number valueChange = kNumZero; + Number valueChange = kNUM_ZERO; /* The total amount of fees paid to the Broker. * This includes: @@ -100,7 +70,7 @@ struct LoanPaymentParts * - Untracked fees (e.g., late payment fees, service fees, origination * fees) This value is always non-negative. */ - Number feePaid = kNumZero; + Number feePaid = kNUM_ZERO; LoanPaymentParts& operator+=(LoanPaymentParts const& other); @@ -191,7 +161,7 @@ adjustImpreciseNumber( { value = roundToAsset(asset, value + adjustment, vaultScale); - if (*value < beast::kZero) + if (*value < beast::kZERO) value = 0; } @@ -199,25 +169,10 @@ inline int getAssetsTotalScale(SLE::const_ref vaultSle) { if (!vaultSle) - return Number::kMinExponent - 1; // LCOV_EXCL_LINE + return Number::kMIN_EXPONENT - 1; // LCOV_EXCL_LINE return scale(vaultSle->at(sfAssetsTotal), vaultSle->at(sfAsset)); } -// Compute the minimum required broker cover, rounded consistently. -// DebtTotal is a broker-level aggregate maintained at vault scale, so the -// rounding must also use vault scale — never an individual loan's scale. -inline Number -minimumBrokerCover(Number const& debtTotal, TenthBips32 coverRateMinimum, SLE::const_ref vaultSle) -{ - XRPL_ASSERT( - vaultSle && vaultSle->getType() == ltVAULT, "xrpl::minimumBrokerCover : valid Vault sle"); - NumberRoundModeGuard const mg(Number::RoundingMode::Upward); - return roundToAsset( - vaultSle->at(sfAsset), - tenthBipsOfValue(debtTotal, coverRateMinimum), - getAssetsTotalScale(vaultSle)); -} - TER checkLoanGuards( Asset const& vaultAsset, @@ -229,7 +184,6 @@ checkLoanGuards( LoanState computeTheoreticalLoanState( - Rules const& rules, Number const& periodicPayment, Number const& periodicRate, std::uint32_t const paymentRemaining, @@ -356,7 +310,7 @@ struct ExtendedPaymentComponents : public PaymentComponents // borrower is sufficient to cover all components of the payment. Number totalDue; - ExtendedPaymentComponents(PaymentComponents const& p, Number fee, Number interest = kNumZero) + ExtendedPaymentComponents(PaymentComponents const& p, Number fee, Number interest = kNUM_ZERO) : PaymentComponents(p) , untrackedManagementFee(fee) , untrackedInterest(interest) @@ -399,7 +353,6 @@ struct LoanStateDeltas Expected, TER> tryOverpayment( - Rules const& rules, Asset const& asset, std::int32_t loanScale, ExtendedPaymentComponents const& overpaymentComponents, @@ -410,17 +363,11 @@ tryOverpayment( TenthBips16 const managementFeeRate, beast::Journal j); -[[nodiscard]] Number -computePowerMinusOne(Number const& periodicRate, std::uint32_t paymentsRemaining); +Number +computeRaisedRate(Number const& periodicRate, std::uint32_t paymentsRemaining); -[[nodiscard]] Number -computePowerMinusOneHybrid(Number const& periodicRate, std::uint32_t paymentsRemaining); - -[[nodiscard]] Number -computePaymentFactor( - Rules const& rules, - Number const& periodicRate, - std::uint32_t paymentsRemaining); +Number +computePaymentFactor(Number const& periodicRate, std::uint32_t paymentsRemaining); std::pair computeInterestAndFeeParts( @@ -431,14 +378,12 @@ computeInterestAndFeeParts( Number loanPeriodicPayment( - Rules const& rules, Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining); Number loanPrincipalFromPeriodicPayment( - Rules const& rules, Number const& periodicPayment, Number const& periodicRate, std::uint32_t paymentsRemaining); @@ -461,7 +406,6 @@ loanAccruedInterest( ExtendedPaymentComponents computeOverpaymentComponents( - Rules const& rules, Asset const& asset, int32_t const loanScale, Number const& overpayment, @@ -471,7 +415,6 @@ computeOverpaymentComponents( PaymentComponents computePaymentComponents( - Rules const& rules, Asset const& asset, std::int32_t scale, Number const& totalValueOutstanding, @@ -495,7 +438,6 @@ operator+(LoanState const& lhs, detail::LoanStateDeltas const& rhs); LoanProperties computeLoanProperties( - Rules const& rules, Asset const& asset, Number const& principalOutstanding, TenthBips32 interestRate, @@ -506,7 +448,6 @@ computeLoanProperties( LoanProperties computeLoanProperties( - Rules const& rules, Asset const& asset, Number const& principalOutstanding, Number const& periodicRate, diff --git a/include/xrpl/ledger/helpers/MPTokenHelpers.h b/include/xrpl/ledger/helpers/MPTokenHelpers.h index c709badab8..6544b18dd1 100644 --- a/include/xrpl/ledger/helpers/MPTokenHelpers.h +++ b/include/xrpl/ledger/helpers/MPTokenHelpers.h @@ -27,18 +27,14 @@ isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue); isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); [[nodiscard]] bool -isFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - std::uint8_t depth = 0); +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0); [[nodiscard]] bool isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, - std::uint8_t depth = 0); + int depth = 0); //------------------------------------------------------------------------------ // @@ -92,7 +88,7 @@ requireAuth( MPTIssue const& mptIssue, AccountID const& account, AuthType authType = AuthType::Legacy, - std::uint8_t depth = 0); + int depth = 0); /** Enforce account has MPToken to match its authorization. * @@ -108,78 +104,23 @@ enforceMPTokenAuthorization( XRPAmount const& priorBalance, beast::Journal j); -/** Resolve the underlying asset of a vault share. - * - * Reads sfReferenceHolding from @p sleShareIssuance to determine which - * asset the vault wraps. @p sleHolding must be the SLE that - * sfReferenceHolding points to — either an ltMPTOKEN (returns its - * MPTIssue) or an ltRIPPLE_STATE (returns its low/high Issue). - * - * @pre Both SLEs must exist and @p sleHolding must be of type ltMPTOKEN - * or ltRIPPLE_STATE. Passing any other type is undefined behaviour. - * @param sleShareIssuance MPTokenIssuance SLE for the vault share token. - * @param sleHolding SLE referenced by sfReferenceHolding. - * @return The underlying Asset (MPTIssue or Issue). - */ -[[nodiscard]] Asset -assetOfHolding(SLE const& sleShareIssuance, SLE const& sleHolding); - -/** Check whether @p to may receive the given MPT from @p from. - * - * The check passes when any of the following is true: - * - @p waive is WaiveMPTCanTransfer::Yes (recovery-path exemption), or - * - @p from or @p to is the issuer, or - * - lsfMPTCanTransfer is set on the MPTokenIssuance. - * - * For vault shares (MPTokenIssuances that carry sfReferenceHolding) the - * check recurses into the underlying asset's transferability. This - * recursion is defensive; vault-of-vault-shares is rejected at vault - * creation, so in practice depth never exceeds 1. - * - * @param view Ledger state to read from. - * @param mptIssue The MPT issuance being transferred. - * @param from Sending account. - * @param to Receiving account. - * @param waive WaiveMPTCanTransfer::Yes skips the lsfMPTCanTransfer - * check. Use for recovery paths (e.g. unwinding SAV or - * Lending Protocol positions after an issuer revokes - * transferability). - * @param depth Recursion depth; bounded at kMaxAssetCheckDepth. - * @return tesSUCCESS if the transfer is allowed, tecNO_AUTH otherwise. +/** Check if the destination account is allowed + * to receive MPT. Return tecNO_AUTH if it doesn't + * and tesSUCCESS otherwise. */ [[nodiscard]] TER canTransfer( ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, - AccountID const& to, - WaiveMPTCanTransfer waive = WaiveMPTCanTransfer::No, - std::uint8_t depth = 0); - -/** Check whether @p asset may be traded on the DEX. - * - * For IOU assets the check delegates to the existing offer/AMM freeze - * logic. For MPT assets it checks lsfMPTCanTrade on the MPTokenIssuance. - * Vault shares recurse into the underlying asset's tradability via - * sfReferenceHolding; depth is bounded at kMaxAssetCheckDepth. - * - * @param view Ledger state to read from. - * @param asset The asset to check. - * @param depth Recursion depth; bounded at kMaxAssetCheckDepth. - * @return tesSUCCESS if trading is allowed, tecNO_PERMISSION otherwise. - */ -[[nodiscard]] TER -canTrade(ReadView const& view, Asset const& asset, std::uint8_t depth = 0); - -/** Convenience to combine canTrade/Transfer. Returns tesSUCCESS if Asset is Issue. - */ -[[nodiscard]] TER -canMPTTradeAndTransfer( - ReadView const& v, - Asset const& asset, - AccountID const& from, AccountID const& to); +/** Check if Asset can be traded on DEX. return tecNO_PERMISSION + * if it doesn't and tesSUCCESS otherwise. + */ +[[nodiscard]] TER +canTrade(ReadView const& view, Asset const& asset); + //------------------------------------------------------------------------------ // // Empty holding operations (MPT-specific) @@ -286,4 +227,17 @@ issuerFundsToSelfIssue(ReadView const& view, MPTIssue const& issue); void issuerSelfDebitHookMPT(ApplyView& view, MPTIssue const& issue, std::uint64_t amount); +//------------------------------------------------------------------------------ +// +// MPT DEX +// +//------------------------------------------------------------------------------ + +/* Return true if a transaction is allowed for the specified MPT/account. The + * function checks MPTokenIssuance and MPToken objects flags to determine if the + * transaction is allowed. + */ +TER +checkMPTTxAllowed(ReadView const& v, TxType tx, Asset const& asset, AccountID const& accountID); + } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/NFTokenHelpers.h b/include/xrpl/ledger/helpers/NFTokenHelpers.h index 362cfe5a8c..4294e1ca13 100644 --- a/include/xrpl/ledger/helpers/NFTokenHelpers.h +++ b/include/xrpl/ledger/helpers/NFTokenHelpers.h @@ -28,9 +28,10 @@ findToken(ReadView const& view, AccountID const& owner, uint256 const& nftokenID struct TokenAndPage { STObject token; - SLE::pointer page; + std::shared_ptr page; - TokenAndPage(STObject token, SLE::pointer page) : token(std::move(token)), page(std::move(page)) + TokenAndPage(STObject token, std::shared_ptr page) + : token(std::move(token)), page(std::move(page)) { } }; @@ -46,7 +47,11 @@ TER removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID); TER -removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, SLE::ref page); +removeToken( + ApplyView& view, + AccountID const& owner, + uint256 const& nftokenID, + std::shared_ptr const& page); /** Deletes the given token offer. @@ -58,7 +63,7 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, S The offer also consumes one incremental reserve. */ bool -deleteTokenOffer(ApplyView& view, SLE::ref offer); +deleteTokenOffer(ApplyView& view, std::shared_ptr const& offer); /** Repairs the links in an NFTokenPage directory. diff --git a/include/xrpl/ledger/helpers/OfferHelpers.h b/include/xrpl/ledger/helpers/OfferHelpers.h index fc863dff0a..9096071811 100644 --- a/include/xrpl/ledger/helpers/OfferHelpers.h +++ b/include/xrpl/ledger/helpers/OfferHelpers.h @@ -5,6 +5,8 @@ #include #include +#include + namespace xrpl { /** Delete an offer. @@ -21,6 +23,6 @@ namespace xrpl { */ // [[nodiscard]] // nodiscard commented out so Flow, BookTip and others compile. TER -offerDelete(ApplyView& view, SLE::ref sle, beast::Journal j); +offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j); } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/PaymentChannelHelpers.h b/include/xrpl/ledger/helpers/PaymentChannelHelpers.h index 810907b0af..24838f1331 100644 --- a/include/xrpl/ledger/helpers/PaymentChannelHelpers.h +++ b/include/xrpl/ledger/helpers/PaymentChannelHelpers.h @@ -8,6 +8,10 @@ namespace xrpl { TER -closeChannel(SLE::ref slep, ApplyView& view, uint256 const& key, beast::Journal j); +closeChannel( + std::shared_ptr const& slep, + ApplyView& view, + uint256 const& key, + beast::Journal j); } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/RippleStateHelpers.h b/include/xrpl/ledger/helpers/RippleStateHelpers.h index 3aaaa541fd..17b0f7673e 100644 --- a/include/xrpl/ledger/helpers/RippleStateHelpers.h +++ b/include/xrpl/ledger/helpers/RippleStateHelpers.h @@ -93,7 +93,7 @@ isFrozen(ReadView const& view, AccountID const& account, Issue const& issue) // Overload with depth parameter for uniformity with MPTIssue version. // The depth parameter is ignored for IOUs since they don't have vault recursion. [[nodiscard]] inline bool -isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, std::uint8_t /*depth*/) +isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int /*depth*/) { return isFrozen(view, account, issue); } @@ -110,7 +110,7 @@ isDeepFrozen( ReadView const& view, AccountID const& account, Issue const& issue, - std::uint8_t = 0 /*ignored*/) + int = 0 /*ignored*/) { return isDeepFrozen(view, account, issue.currency, issue.account); } @@ -154,7 +154,7 @@ trustCreate( [[nodiscard]] TER trustDelete( ApplyView& view, - SLE::ref sleRippleState, + std::shared_ptr const& sleRippleState, AccountID const& uLowAccountID, AccountID const& uHighAccountID, beast::Journal j); @@ -248,7 +248,7 @@ removeEmptyHolding( [[nodiscard]] TER deleteAMMTrustLine( ApplyView& view, - SLE::pointer sleState, + std::shared_ptr sleState, std::optional const& ammAccountID, beast::Journal j); @@ -258,7 +258,7 @@ deleteAMMTrustLine( [[nodiscard]] TER deleteAMMMPToken( ApplyView& view, - SLE::pointer sleMPT, + std::shared_ptr sleMPT, AccountID const& ammAccountID, beast::Journal j); diff --git a/include/xrpl/ledger/helpers/TokenHelpers.h b/include/xrpl/ledger/helpers/TokenHelpers.h index f736e51d28..3d41ac47cd 100644 --- a/include/xrpl/ledger/helpers/TokenHelpers.h +++ b/include/xrpl/ledger/helpers/TokenHelpers.h @@ -34,15 +34,6 @@ enum class WaiveTransferFee : bool { No = false, Yes }; /** Controls whether accountSend is allowed to overflow OutstandingAmount **/ enum class AllowMPTOverflow : bool { No = false, Yes }; -/** Controls whether canTransfer enforces lsfMPTCanTransfer on MPTs. - * - * Default is No (enforce). Use Yes at call sites that must remain available - * even when an MPT issuer has cleared lsfMPTCanTransfer - for example, - * unwinding existing positions in SAV or the Lending Protocol. Has no - * effect on the IOU branch of canTransfer. - */ -enum class WaiveMPTCanTransfer : bool { No = false, Yes }; - /* Check if MPToken (for MPT) or trust line (for IOU) exists: * - StrongAuth - before checking if authorization is required * - WeakAuth @@ -63,26 +54,16 @@ enum class AuthType { StrongAuth, WeakAuth, Legacy }; [[nodiscard]] bool isGlobalFrozen(ReadView const& view, Asset const& asset); -[[nodiscard]] TER -checkGlobalFrozen(ReadView const& view, Asset const& asset); - [[nodiscard]] bool isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset); -[[nodiscard]] TER -checkIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset); - /** * isFrozen check is recursive for MPT shares in a vault, descending to * assets in the vault, up to maxAssetCheckDepth recursion depth. This is * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] bool -isFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset, - std::uint8_t depth = 0); +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); [[nodiscard]] TER checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue); @@ -104,14 +85,14 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, Asset const& asset, - std::uint8_t depth = 0); + int depth = 0); [[nodiscard]] bool isDeepFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, - std::uint8_t depth = 0); + int depth = 0); /** * isFrozen check is recursive for MPT shares in a vault, descending to @@ -119,11 +100,7 @@ isDeepFrozen( * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset, - std::uint8_t depth = 0); +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); [[nodiscard]] TER checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); @@ -257,13 +234,7 @@ requireAuth( AuthType authType = AuthType::Legacy); [[nodiscard]] TER -canTransfer( - ReadView const& view, - Asset const& asset, - AccountID const& from, - AccountID const& to, - WaiveMPTCanTransfer waive = WaiveMPTCanTransfer::No, - std::uint8_t depth = 0); +canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to); //------------------------------------------------------------------------------ // diff --git a/include/xrpl/ledger/helpers/VaultHelpers.h b/include/xrpl/ledger/helpers/VaultHelpers.h index 2344b4de77..14b0c004cb 100644 --- a/include/xrpl/ledger/helpers/VaultHelpers.h +++ b/include/xrpl/ledger/helpers/VaultHelpers.h @@ -1,10 +1,9 @@ #pragma once -#include -#include #include #include +#include #include namespace xrpl { @@ -20,7 +19,10 @@ namespace xrpl { @return The number of shares, or nullopt on error. */ [[nodiscard]] std::optional -assetsToSharesDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const& assets); +assetsToSharesDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets); /** From the perspective of a vault, return the number of assets to take from depositor when they receive a fixed amount of shares. Note, since shares are @@ -33,19 +35,14 @@ assetsToSharesDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount co @return The number of assets, or nullopt on error. */ [[nodiscard]] std::optional -sharesToAssetsDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const& shares); +sharesToAssetsDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares); /** Controls whether to truncate shares instead of rounding. */ enum class TruncateShares : bool { No = false, Yes = true }; -/** Controls whether the withdraw conversion helpers - (assetsToSharesWithdraw and sharesToAssetsWithdraw) subtract - sfLossUnrealized from sfAssetsTotal before computing the exchange rate. - The default (No) applies the standard discounted rate; Yes is used when - the redeemer is the sole remaining shareholder. -*/ -enum class WaiveUnrealizedLoss : bool { No = false, Yes = true }; - /** From the perspective of a vault, return the number of shares to demand from the depositor when they ask to withdraw a fixed amount of assets. Since shares are MPT this number is integral, and it will be rounded to nearest @@ -55,18 +52,15 @@ enum class WaiveUnrealizedLoss : bool { No = false, Yes = true }; @param issuance The MPTokenIssuance SLE for the vault's shares. @param assets The amount of assets to convert. @param truncate Whether to truncate instead of rounding. - @param waive Whether to waive the unrealized-loss discount when computing - the exchange rate. @return The number of shares, or nullopt on error. */ [[nodiscard]] std::optional assetsToSharesWithdraw( - SLE::const_ref vault, - SLE::const_ref issuance, + std::shared_ptr const& vault, + std::shared_ptr const& issuance, STAmount const& assets, - TruncateShares truncate = TruncateShares::No, - WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No); + TruncateShares truncate = TruncateShares::No); /** From the perspective of a vault, return the number of assets to give the depositor when they redeem a fixed amount of shares. Note, since shares are @@ -75,28 +69,13 @@ assetsToSharesWithdraw( @param vault The vault SLE. @param issuance The MPTokenIssuance SLE for the vault's shares. @param shares The amount of shares to convert. - @param waive Whether to waive (i.e. not subtract) the vault's unrealized - loss when computing the exchange rate. @return The number of assets, or nullopt on error. */ [[nodiscard]] std::optional sharesToAssetsWithdraw( - SLE::const_ref vault, - SLE::const_ref issuance, - STAmount const& shares, - WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No); - -/** Returns true iff `account` holds all of the vault's outstanding shares — - i.e. is the sole remaining shareholder. Returns false if the account - holds no shares or fewer than the total outstanding. - - @param view The ledger view. - @param account The candidate sole shareholder. - @param issuance The MPTokenIssuance SLE for the vault's shares; provides - both the share MPTID and the outstanding-amount total. -*/ -[[nodiscard]] bool -isSoleShareholder(ReadView const& view, AccountID const& account, SLE::const_ref issuance); + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares); } // namespace xrpl diff --git a/include/xrpl/net/HTTPClient.h b/include/xrpl/net/HTTPClient.h index f059b19047..ea0c5d72cd 100644 --- a/include/xrpl/net/HTTPClient.h +++ b/include/xrpl/net/HTTPClient.h @@ -20,7 +20,7 @@ class HTTPClient public: explicit HTTPClient() = default; - static constexpr auto kMaxClientHeaderBytes = kilobytes(32); + static constexpr auto kMAX_CLIENT_HEADER_BYTES = kilobytes(32); static void initializeSSLContext( diff --git a/include/xrpl/net/HTTPClientSSLContext.h b/include/xrpl/net/HTTPClientSSLContext.h index ca1983f141..d1744bbce4 100644 --- a/include/xrpl/net/HTTPClientSSLContext.h +++ b/include/xrpl/net/HTTPClientSSLContext.h @@ -21,13 +21,13 @@ public: bool sslVerify, beast::Journal j, boost::asio::ssl::context_base::method method = boost::asio::ssl::context::sslv23) - : sslContext_{method}, j_(j), verify_{sslVerify} + : ssl_context_{method}, j_(j), verify_{sslVerify} { boost::system::error_code ec; if (sslVerifyFile.empty()) { - registerSSLCerts(sslContext_, ec, j_); + registerSSLCerts(ssl_context_, ec, j_); if (ec && sslVerifyDir.empty()) { @@ -37,12 +37,12 @@ public: } else { - sslContext_.load_verify_file(sslVerifyFile); + ssl_context_.load_verify_file(sslVerifyFile); } if (!sslVerifyDir.empty()) { - sslContext_.add_verify_path(sslVerifyDir, ec); + ssl_context_.add_verify_path(sslVerifyDir, ec); if (ec) { @@ -55,7 +55,7 @@ public: boost::asio::ssl::context& context() { - return sslContext_; + return ssl_context_; } [[nodiscard]] bool @@ -153,7 +153,7 @@ public: } private: - boost::asio::ssl::context sslContext_; + boost::asio::ssl::context ssl_context_; beast::Journal const j_; bool const verify_; }; diff --git a/include/xrpl/nodestore/Backend.h b/include/xrpl/nodestore/Backend.h index 0061890237..124cd99db5 100644 --- a/include/xrpl/nodestore/Backend.h +++ b/include/xrpl/nodestore/Backend.h @@ -83,6 +83,10 @@ public: virtual Status fetch(uint256 const& hash, std::shared_ptr* pObject) = 0; + /** Fetch a batch synchronously. */ + virtual std::pair>, Status> + fetchBatch(std::vector const& hashes) = 0; + /** Store a single object. Depending on the implementation this may happen immediately or deferred using a scheduled task. diff --git a/include/xrpl/nodestore/Database.h b/include/xrpl/nodestore/Database.h index 438a3cc7fc..ca2dde560c 100644 --- a/include/xrpl/nodestore/Database.h +++ b/include/xrpl/nodestore/Database.h @@ -131,10 +131,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. diff --git a/include/xrpl/nodestore/NodeObject.h b/include/xrpl/nodestore/NodeObject.h index 04ba391b2b..2a216606c4 100644 --- a/include/xrpl/nodestore/NodeObject.h +++ b/include/xrpl/nodestore/NodeObject.h @@ -29,7 +29,7 @@ enum class NodeObjectType : std::uint32_t { class NodeObject : public CountedObject { public: - static constexpr std::size_t kKeyBytes = 32; + static constexpr std::size_t kKEY_BYTES = 32; private: // This hack is used to make the constructor effectively private diff --git a/include/xrpl/nodestore/Types.h b/include/xrpl/nodestore/Types.h index 21c01e9111..2b5d9ac770 100644 --- a/include/xrpl/nodestore/Types.h +++ b/include/xrpl/nodestore/Types.h @@ -6,16 +6,20 @@ namespace xrpl::NodeStore { -// This is only used to pre-allocate the array for -// batch objects and does not affect the amount written. -// -static constexpr auto kBatchWritePreallocationSize = 256; +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + // This is only used to pre-allocate the array for + // batch objects and does not affect the amount written. + // + BatchWritePreallocationSize = 256, -// This sets a limit on the maximum number of writes -// in a batch. Actual usage can be twice this since -// we have a new batch growing as we write the old. -// -static constexpr auto kBatchWriteLimitSize = 65536; + // This sets a limit on the maximum number of writes + // in a batch. Actual usage can be twice this since + // we have a new batch growing as we write the old. + // + BatchWriteLimitSize = 65536 +}; /** Return codes from Backend operations. */ enum class Status { diff --git a/include/xrpl/nodestore/detail/DatabaseNodeImp.h b/include/xrpl/nodestore/detail/DatabaseNodeImp.h index 951c60c8c7..add66c51a7 100644 --- a/include/xrpl/nodestore/detail/DatabaseNodeImp.h +++ b/include/xrpl/nodestore/detail/DatabaseNodeImp.h @@ -22,32 +22,6 @@ public: beast::Journal j) : 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.has_value() || cacheAge.has_value()) - { - 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 " @@ -93,19 +67,16 @@ public: backend_->sync(); } + std::vector> + fetchBatch(std::vector const& hashes); + void asyncFetch( uint256 const& hash, std::uint32_t ledgerSeq, std::function const&)>&& callback) override; - void - sweep() 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_; diff --git a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h index 1ba9435a5f..39441ef4d8 100644 --- a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h +++ b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h @@ -55,9 +55,6 @@ public: void sync() override; - void - sweep() override; - private: std::shared_ptr writableBackend_; std::shared_ptr archiveBackend_; diff --git a/include/xrpl/nodestore/detail/codec.h b/include/xrpl/nodestore/detail/codec.h index 49238fa34a..4dedc54902 100644 --- a/include/xrpl/nodestore/detail/codec.h +++ b/include/xrpl/nodestore/detail/codec.h @@ -55,7 +55,7 @@ lz4Compress(void const* in, std::size_t inSize, BufferFactory&& bf) using std::runtime_error; using namespace nudb::detail; std::pair result; - std::array::kMax> vi{}; + std::array::kMAX> vi{}; auto const n = writeVarint(vi.data(), inSize); auto const outMax = LZ4_compressBound(inSize); std::uint8_t* out = reinterpret_cast(bf(n + outMax)); @@ -254,12 +254,12 @@ nodeobjectCompress(void const* in, std::size_t inSize, BufferFactory&& bf) } } - std::array::kMax> vi{}; + std::array::kMAX> vi{}; - static constexpr std::size_t kCodecType = 1; - auto const vn = writeVarint(vi.data(), kCodecType); + constexpr std::size_t kCODEC_TYPE = 1; + auto const vn = writeVarint(vi.data(), kCODEC_TYPE); std::pair result; - switch (kCodecType) + switch (kCODEC_TYPE) { // case 0 was uncompressed data; we always compress now. case 1: // lz4 @@ -275,7 +275,7 @@ nodeobjectCompress(void const* in, std::size_t inSize, BufferFactory&& bf) break; } default: - Throw("nodeobject codec: unknown=" + std::to_string(kCodecType)); + Throw("nodeobject codec: unknown=" + std::to_string(kCODEC_TYPE)); }; return result; } diff --git a/include/xrpl/nodestore/detail/varint.h b/include/xrpl/nodestore/detail/varint.h index e6b78fcf08..c98b36e322 100644 --- a/include/xrpl/nodestore/detail/varint.h +++ b/include/xrpl/nodestore/detail/varint.h @@ -25,7 +25,7 @@ struct varint_traits { explicit varint_traits() = default; - static constexpr std::size_t kMax = (8 * sizeof(T) + 6) / 7; + static std::size_t constexpr kMAX = (8 * sizeof(T) + 6) / 7; }; // Returns: Number of bytes consumed or 0 on error, diff --git a/include/xrpl/protocol/AMMCore.h b/include/xrpl/protocol/AMMCore.h index ced84c4c87..9d8f8c62b0 100644 --- a/include/xrpl/protocol/AMMCore.h +++ b/include/xrpl/protocol/AMMCore.h @@ -8,21 +8,21 @@ namespace xrpl { -constexpr std::uint16_t kTradingFeeThreshold = 1000; // 1% +std::uint16_t constexpr kTRADING_FEE_THRESHOLD = 1000; // 1% // Auction slot -constexpr std::uint32_t kTotalTimeSlotSecs = 24 * 3600; -constexpr std::uint16_t kAuctionSlotTimeIntervals = 20; -constexpr std::uint16_t kAuctionSlotMaxAuthAccounts = 4; -constexpr std::uint32_t kAuctionSlotFeeScaleFactor = 100000; -constexpr std::uint32_t kAuctionSlotDiscountedFeeFraction = 10; -constexpr std::uint32_t kAuctionSlotMinFeeFraction = 25; -constexpr std::uint32_t kAuctionSlotIntervalDuration = - kTotalTimeSlotSecs / kAuctionSlotTimeIntervals; +std::uint32_t constexpr kTOTAL_TIME_SLOT_SECS = 24 * 3600; +std::uint16_t constexpr kAUCTION_SLOT_TIME_INTERVALS = 20; +std::uint16_t constexpr kAUCTION_SLOT_MAX_AUTH_ACCOUNTS = 4; +std::uint32_t constexpr kAUCTION_SLOT_FEE_SCALE_FACTOR = 100000; +std::uint32_t constexpr kAUCTION_SLOT_DISCOUNTED_FEE_FRACTION = 10; +std::uint32_t constexpr kAUCTION_SLOT_MIN_FEE_FRACTION = 25; +std::uint32_t constexpr kAUCTION_SLOT_INTERVAL_DURATION = + kTOTAL_TIME_SLOT_SECS / kAUCTION_SLOT_TIME_INTERVALS; // Votes -constexpr std::uint16_t kVoteMaxSlots = 8; -constexpr std::uint32_t kVoteWeightScaleFactor = 100000; +std::uint16_t constexpr kVOTE_MAX_SLOTS = 8; +std::uint32_t constexpr kVOTE_WEIGHT_SCALE_FACTOR = 100000; class STObject; class STAmount; @@ -77,7 +77,7 @@ ammEnabled(Rules const&); inline Number getFee(std::uint16_t tfee) { - return Number{tfee} / kAuctionSlotFeeScaleFactor; + return Number{tfee} / kAUCTION_SLOT_FEE_SCALE_FACTOR; } /** Get fee multiplier (1 - tfee) diff --git a/include/xrpl/protocol/AccountID.h b/include/xrpl/protocol/AccountID.h index 4938812ffa..e22c3b8edd 100644 --- a/include/xrpl/protocol/AccountID.h +++ b/include/xrpl/protocol/AccountID.h @@ -25,7 +25,7 @@ public: } // namespace detail /** A 160-bit unsigned that uniquely identifies an account. */ -using AccountID = BaseUInt<160, detail::AccountIDTag>; +using AccountID = BaseUint<160, detail::AccountIDTag>; /** Convert AccountID to base58 checked string */ std::string @@ -69,7 +69,7 @@ toIssuer(AccountID&, std::string const&); inline bool isXRP(AccountID const& c) { - return c == beast::kZero; + return c == beast::kZERO; } // DEPRECATED diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index a5f7ec310f..53b7dace3c 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -96,9 +96,9 @@ inline MPTAmount toAmount(STAmount const& amt) { XRPL_ASSERT( - amt.holds() && amt.mantissa() <= kMaxMpTokenAmount && amt.exponent() == 0, + amt.holds() && amt.mantissa() <= kMAX_MP_TOKEN_AMOUNT && amt.exponent() == 0, "xrpl::toAmount : maximum mantissa"); - if (amt.mantissa() > kMaxMpTokenAmount || amt.exponent() != 0) + if (amt.mantissa() > kMAX_MP_TOKEN_AMOUNT || amt.exponent() != 0) Throw("toAmount: invalid mantissa or exponent"); bool const isNeg = amt.negative(); std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); @@ -167,8 +167,8 @@ toAmount(Asset const& asset, Number const& n, Number::RoundingMode mode = Number } else { - static constexpr bool kAlwaysFalse = !std::is_same_v; - static_assert(kAlwaysFalse, "Unsupported type for toAmount"); + constexpr bool kALWAYS_FALSE = !std::is_same_v; + static_assert(kALWAYS_FALSE, "Unsupported type for toAmount"); } } @@ -178,30 +178,30 @@ toMaxAmount(Asset const& asset) { if constexpr (std::is_same_v) { - return IOUAmount(STAmount::kMaxValue, STAmount::kMaxOffset); + return IOUAmount(STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); } else if constexpr (std::is_same_v) { - return XRPAmount(static_cast(STAmount::kMaxNativeN)); + return XRPAmount(static_cast(STAmount::kMAX_NATIVE_N)); } else if constexpr (std::is_same_v) { - return MPTAmount(kMaxMpTokenAmount); + return MPTAmount(kMAX_MP_TOKEN_AMOUNT); } else if constexpr (std::is_same_v) { return asset.visit( [](Issue const& issue) { if (isXRP(issue)) - return STAmount(issue, static_cast(STAmount::kMaxNativeN)); - return STAmount(issue, STAmount::kMaxValue, STAmount::kMaxOffset); + return STAmount(issue, static_cast(STAmount::kMAX_NATIVE_N)); + return STAmount(issue, STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); }, - [](MPTIssue const& issue) { return STAmount(issue, kMaxMpTokenAmount); }); + [](MPTIssue const& issue) { return STAmount(issue, kMAX_MP_TOKEN_AMOUNT); }); } else { - static constexpr bool kAlwaysFalse = !std::is_same_v; - static_assert(kAlwaysFalse, "Unsupported type for toMaxAmount"); + constexpr bool kALWAYS_FALSE = !std::is_same_v; + static_assert(kALWAYS_FALSE, "Unsupported type for toMaxAmount"); } } @@ -233,8 +233,8 @@ getAsset(T const& amt) } else { - static constexpr bool kAlwaysFalse = !std::is_same_v; - static_assert(kAlwaysFalse, "Unsupported type for getIssue"); + constexpr bool kALWAYS_FALSE = !std::is_same_v; + static_assert(kALWAYS_FALSE, "Unsupported type for getIssue"); } } @@ -260,8 +260,8 @@ get(STAmount const& a) } else { - constexpr bool kAlwaysFalse = !std::is_same_v; - static_assert(kAlwaysFalse, "Unsupported type for get"); + constexpr bool kALWAYS_FALSE = !std::is_same_v; + static_assert(kALWAYS_FALSE, "Unsupported type for get"); } } diff --git a/include/xrpl/protocol/ApiVersion.h b/include/xrpl/protocol/ApiVersion.h index 345049b377..3399152363 100644 --- a/include/xrpl/protocol/ApiVersion.h +++ b/include/xrpl/protocol/ApiVersion.h @@ -35,49 +35,49 @@ namespace xrpl { namespace RPC { template -static constexpr std::integral_constant kApiVersion = {}; +constexpr static std::integral_constant kAPI_VERSION = {}; -static constexpr auto kApiInvalidVersion = kApiVersion<0>; -static constexpr auto kApiMinimumSupportedVersion = kApiVersion<1>; -static constexpr auto kApiMaximumSupportedVersion = kApiVersion<2>; -static constexpr auto kApiVersionIfUnspecified = kApiVersion<1>; -static constexpr auto kApiCommandLineVersion = kApiVersion<1>; // TODO Bump to 2 later -static constexpr auto kApiBetaVersion = kApiVersion<3>; -static constexpr auto kApiMaximumValidVersion = kApiBetaVersion; +constexpr static auto kAPI_INVALID_VERSION = kAPI_VERSION<0>; +constexpr static auto kAPI_MINIMUM_SUPPORTED_VERSION = kAPI_VERSION<1>; +constexpr static auto kAPI_MAXIMUM_SUPPORTED_VERSION = kAPI_VERSION<2>; +constexpr static auto kAPI_VERSION_IF_UNSPECIFIED = kAPI_VERSION<1>; +constexpr static auto kAPI_COMMAND_LINE_VERSION = kAPI_VERSION<1>; // TODO Bump to 2 later +constexpr static auto kAPI_BETA_VERSION = kAPI_VERSION<3>; +constexpr static auto kAPI_MAXIMUM_VALID_VERSION = kAPI_BETA_VERSION; -static_assert(kApiInvalidVersion < kApiMinimumSupportedVersion); +static_assert(kAPI_INVALID_VERSION < kAPI_MINIMUM_SUPPORTED_VERSION); static_assert( - kApiVersionIfUnspecified >= kApiMinimumSupportedVersion && - kApiVersionIfUnspecified <= kApiMaximumSupportedVersion); + kAPI_VERSION_IF_UNSPECIFIED >= kAPI_MINIMUM_SUPPORTED_VERSION && + kAPI_VERSION_IF_UNSPECIFIED <= kAPI_MAXIMUM_SUPPORTED_VERSION); static_assert( - kApiCommandLineVersion >= kApiMinimumSupportedVersion && - kApiCommandLineVersion <= kApiMaximumSupportedVersion); -static_assert(kApiMaximumSupportedVersion >= kApiMinimumSupportedVersion); -static_assert(kApiBetaVersion >= kApiMaximumSupportedVersion); -static_assert(kApiMaximumValidVersion >= kApiMaximumSupportedVersion); + kAPI_COMMAND_LINE_VERSION >= kAPI_MINIMUM_SUPPORTED_VERSION && + kAPI_COMMAND_LINE_VERSION <= kAPI_MAXIMUM_SUPPORTED_VERSION); +static_assert(kAPI_MAXIMUM_SUPPORTED_VERSION >= kAPI_MINIMUM_SUPPORTED_VERSION); +static_assert(kAPI_BETA_VERSION >= kAPI_MAXIMUM_SUPPORTED_VERSION); +static_assert(kAPI_MAXIMUM_VALID_VERSION >= kAPI_MAXIMUM_SUPPORTED_VERSION); inline void setVersion(json::Value& parent, unsigned int apiVersion, bool betaEnabled) { - XRPL_ASSERT(apiVersion != kApiInvalidVersion, "xrpl::RPC::setVersion : input is valid"); + XRPL_ASSERT(apiVersion != kAPI_INVALID_VERSION, "xrpl::RPC::setVersion : input is valid"); - auto& retObj = parent[jss::version] = json::ValueType::Object; + auto& retObj = parent[jss::version] = json::ObjectValue; - if (apiVersion == kApiVersionIfUnspecified) + if (apiVersion == kAPI_VERSION_IF_UNSPECIFIED) { // API version numbers used in API version 1 - static beast::SemanticVersion const kFirstVersion{"1.0.0"}; - static beast::SemanticVersion const kGoodVersion{"1.0.0"}; - static beast::SemanticVersion const kLastVersion{"1.0.0"}; + static beast::SemanticVersion const kFIRST_VERSION{"1.0.0"}; + static beast::SemanticVersion const kGOOD_VERSION{"1.0.0"}; + static beast::SemanticVersion const kLAST_VERSION{"1.0.0"}; - retObj[jss::first] = kFirstVersion.print(); - retObj[jss::good] = kGoodVersion.print(); - retObj[jss::last] = kLastVersion.print(); + retObj[jss::first] = kFIRST_VERSION.print(); + retObj[jss::good] = kGOOD_VERSION.print(); + retObj[jss::last] = kLAST_VERSION.print(); } else { - retObj[jss::first] = kApiMinimumSupportedVersion.value; - retObj[jss::last] = betaEnabled ? kApiBetaVersion : kApiMaximumSupportedVersion; + retObj[jss::first] = kAPI_MINIMUM_SUPPORTED_VERSION.value; + retObj[jss::last] = betaEnabled ? kAPI_BETA_VERSION : kAPI_MAXIMUM_SUPPORTED_VERSION; } } @@ -98,9 +98,9 @@ setVersion(json::Value& parent, unsigned int apiVersion, bool betaEnabled) inline unsigned int getAPIVersionNumber(json::Value const& jv, bool betaEnabled) { - static json::Value const kMinVersion(RPC::kApiMinimumSupportedVersion); + static json::Value const kMIN_VERSION(RPC::kAPI_MINIMUM_SUPPORTED_VERSION); json::Value const maxVersion( - betaEnabled ? RPC::kApiBetaVersion : RPC::kApiMaximumSupportedVersion); + betaEnabled ? RPC::kAPI_BETA_VERSION : RPC::kAPI_MAXIMUM_SUPPORTED_VERSION); if (jv.isObject()) { @@ -109,18 +109,18 @@ getAPIVersionNumber(json::Value const& jv, bool betaEnabled) auto const specifiedVersion = jv[jss::api_version]; if (!specifiedVersion.isInt() && !specifiedVersion.isUInt()) { - return RPC::kApiInvalidVersion; + return RPC::kAPI_INVALID_VERSION; } auto const specifiedVersionInt = specifiedVersion.asInt(); - if (specifiedVersionInt < kMinVersion || specifiedVersionInt > maxVersion) + if (specifiedVersionInt < kMIN_VERSION || specifiedVersionInt > maxVersion) { - return RPC::kApiInvalidVersion; + return RPC::kAPI_INVALID_VERSION; } return specifiedVersionInt; } } - return RPC::kApiVersionIfUnspecified; + return RPC::kAPI_VERSION_IF_UNSPECIFIED; } } // namespace RPC @@ -128,33 +128,33 @@ getAPIVersionNumber(json::Value const& jv, bool betaEnabled) template void forApiVersions(Fn const& fn, Args&&... args) - requires // - (MaxVer >= MinVer) && // - (MinVer >= RPC::kApiMinimumSupportedVersion) && // - (RPC::kApiMaximumValidVersion >= MaxVer) && requires { + requires // + (MaxVer >= MinVer) && // + (MinVer >= RPC::kAPI_MINIMUM_SUPPORTED_VERSION) && // + (RPC::kAPI_MAXIMUM_VALID_VERSION >= MaxVer) && requires { fn(std::integral_constant{}, std::forward(args)...); fn(std::integral_constant{}, std::forward(args)...); } { - static constexpr auto kSize = MaxVer + 1 - MinVer; + constexpr auto kSIZE = MaxVer + 1 - MinVer; [&](std::index_sequence) { // NOLINTBEGIN(bugprone-use-after-move) (((void)fn( std::integral_constant{}, std::forward(args)...)), ...); // NOLINTEND(bugprone-use-after-move) - }(std::make_index_sequence{}); + }(std::make_index_sequence{}); } template void forAllApiVersions(Fn const& fn, Args&&... args) requires requires { - forApiVersions( + forApiVersions( fn, std::forward(args)...); } { - forApiVersions( + forApiVersions( fn, std::forward(args)...); } diff --git a/include/xrpl/protocol/Asset.h b/include/xrpl/protocol/Asset.h index ec9d8db02f..e0f4aa08a2 100644 --- a/include/xrpl/protocol/Asset.h +++ b/include/xrpl/protocol/Asset.h @@ -148,10 +148,10 @@ public: }; template -constexpr bool kIsIssueV = std::is_same_v; +constexpr bool kIS_ISSUE_V = std::is_same_v; template -constexpr bool kIsMptissueV = std::is_same_v; +constexpr bool kIS_MPTISSUE_V = std::is_same_v; inline json::Value toJson(Asset const& asset) @@ -242,7 +242,7 @@ operator<=>(Asset const& lhs, Asset const& rhs) { return std::weak_ordering(lhs <=> rhs); } - else if constexpr (kIsIssueV && kIsMptissueV) + else if constexpr (kIS_ISSUE_V && kIS_MPTISSUE_V) { return std::weak_ordering::greater; } diff --git a/include/xrpl/protocol/Book.h b/include/xrpl/protocol/Book.h index 01dc40075b..fc36abddc4 100644 --- a/include/xrpl/protocol/Book.h +++ b/include/xrpl/protocol/Book.h @@ -140,8 +140,8 @@ private: using issue_hasher = std::hash; using mptissue_hasher = std::hash; - issue_hasher mIssueHasher_; - mptissue_hasher mMptissueHasher_; + issue_hasher m_issue_hasher_; + mptissue_hasher m_mptissue_hasher_; public: explicit hash() = default; @@ -151,11 +151,11 @@ public: { return asset.visit( [&](xrpl::Issue const& issue) { - value_type const result(mIssueHasher_(issue)); + value_type const result(m_issue_hasher_(issue)); return result; }, [&](xrpl::MPTIssue const& issue) { - value_type const result(mMptissueHasher_(issue)); + value_type const result(m_mptissue_hasher_(issue)); return result; }); } @@ -170,8 +170,8 @@ private: using asset_hasher = std::hash; using uint256_hasher = xrpl::uint256::hasher; - asset_hasher issueHasher_; - uint256_hasher uint256Hasher_; + asset_hasher issue_hasher_; + uint256_hasher uint256_hasher_; public: hash() = default; @@ -182,11 +182,11 @@ public: value_type operator()(argument_type const& value) const { - value_type result(issueHasher_(value.in)); - boost::hash_combine(result, issueHasher_(value.out)); + value_type result(issue_hasher_(value.in)); + boost::hash_combine(result, issue_hasher_(value.out)); if (value.domain) - boost::hash_combine(result, uint256Hasher_(*value.domain)); + boost::hash_combine(result, uint256_hasher_(*value.domain)); return result; } diff --git a/include/xrpl/protocol/ErrorCodes.h b/include/xrpl/protocol/ErrorCodes.h index f5e67fd572..a91adfc55a 100644 --- a/include/xrpl/protocol/ErrorCodes.h +++ b/include/xrpl/protocol/ErrorCodes.h @@ -172,24 +172,24 @@ struct ErrorInfo { // Default ctor needed to produce an empty std::array during constexpr eval. constexpr ErrorInfo() - : code(RpcUnknown), token("unknown"), message("An unknown error code."), httpStatus(200) + : code(RpcUnknown), token("unknown"), message("An unknown error code."), http_status(200) { } constexpr ErrorInfo(ErrorCodeI code, char const* token, char const* message) - : code(code), token(token), message(message), httpStatus(200) + : code(code), token(token), message(message), http_status(200) { } constexpr ErrorInfo(ErrorCodeI code, char const* token, char const* message, int httpStatus) - : code(code), token(token), message(message), httpStatus(httpStatus) + : code(code), token(token), message(message), http_status(httpStatus) { } ErrorCodeI code; json::StaticString token; json::StaticString message; - int httpStatus; + int http_status; }; /** Returns an ErrorInfo that reflects the error code. */ diff --git a/include/xrpl/protocol/Feature.h b/include/xrpl/protocol/Feature.h index 5de8ca64a9..281e598bf7 100644 --- a/include/xrpl/protocol/Feature.h +++ b/include/xrpl/protocol/Feature.h @@ -65,11 +65,11 @@ namespace xrpl { // Feature names must not exceed this length (in characters, excluding the null terminator). -static constexpr std::size_t kMaxFeatureNameSize = 63; +static constexpr std::size_t kMAX_FEATURE_NAME_SIZE = 63; // Reserve this exact feature-name length (in characters/bytes, excluding the null terminator) // so that a 32-byte uint256 (for example, in WASM or other interop contexts) can be used // as a compact, fixed-size feature selector without conflicting with human-readable names. -static constexpr std::size_t kReservedFeatureNameSize = 32; +static constexpr std::size_t kRESERVED_FEATURE_NAME_SIZE = 32; // Both validFeatureNameSize and validFeatureName are consteval functions that can be used in // static_asserts to validate feature names at compile time. They are only used inside @@ -81,14 +81,14 @@ validFeatureNameSize(auto fn) -> bool { constexpr char const* kN = fn(); // Note, std::strlen is not constexpr, we need to implement our own here. - constexpr std::size_t kLen = [](auto n) { + constexpr std::size_t kLEN = [](auto n) { std::size_t ret = 0; for (auto ptr = n; *ptr != '\0'; ret++, ++ptr) ; return ret; }(kN); - return kLen != kReservedFeatureNameSize && // - kLen <= kMaxFeatureNameSize; + return kLEN != kRESERVED_FEATURE_NAME_SIZE && // + kLEN <= kMAX_FEATURE_NAME_SIZE; } consteval auto @@ -136,7 +136,7 @@ namespace detail { // Feature.cpp. Because it's only used to reserve storage, and determine how // large to make the FeatureBitset, it MAY be larger. It MUST NOT be less than // the actual number of amendments. A LogicError on startup will verify this. -static constexpr std::size_t kNumFeatures = +static constexpr std::size_t kNUM_FEATURES = (0 + #include ); @@ -184,9 +184,9 @@ bitsetIndexToFeature(size_t i); std::string featureToName(uint256 const& f); -class FeatureBitset : private std::bitset +class FeatureBitset : private std::bitset { - using base = std::bitset; + using base = std::bitset; template void diff --git a/include/xrpl/protocol/Fees.h b/include/xrpl/protocol/Fees.h index 14bcc068bf..c94ba31b8a 100644 --- a/include/xrpl/protocol/Fees.h +++ b/include/xrpl/protocol/Fees.h @@ -6,7 +6,7 @@ namespace xrpl { // Deprecated constant for backwards compatibility with pre-XRPFees amendment. // This was the reference fee units used in the old fee calculation. -inline constexpr std::uint32_t kFeeUnitsDeprecated = 10; +inline constexpr std::uint32_t kFEE_UNITS_DEPRECATED = 10; /** Reflects the fee settings for a particular ledger. diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 9e0fbe38eb..6ce773fabd 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -92,7 +92,7 @@ public: inline IOUAmount::IOUAmount(beast::Zero) { - *this = beast::kZero; + *this = beast::kZERO; } inline IOUAmount::IOUAmount(mantissa_type mantissa, exponent_type exponent) diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index 887a208ec6..14e7d95e23 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -82,7 +82,7 @@ struct BookT Keylet operator()(Book const& b) const; }; -static BookT const kBook{}; +static BookT const kBOOK{}; /** The index of a trust line for a given currency @@ -126,7 +126,7 @@ struct NextT Keylet operator()(Keylet const& k) const; }; -static NextT const kNext{}; +static NextT const kNEXT{}; /** A ticket belonging to an account */ struct TicketT @@ -145,7 +145,7 @@ struct TicketT return {ltTICKET, key}; } }; -static TicketT const kTicket{}; +static TicketT const kTICKET{}; /** A SignerList */ Keylet @@ -373,7 +373,7 @@ struct KeyletDesc // This list should include all of the keylet functions that take a single // AccountID parameter. -std::array, 6> const kDirectAccountKeylets{ +std::array, 6> const kDIRECT_ACCOUNT_KEYLETS{ {{.function = &keylet::account, .expectedLEName = jss::AccountRoot, .includeInTests = false}, {.function = &keylet::ownerDir, .expectedLEName = jss::DirectoryNode, .includeInTests = true}, {.function = &keylet::signers, .expectedLEName = jss::SignerList, .includeInTests = true}, diff --git a/include/xrpl/protocol/Issue.h b/include/xrpl/protocol/Issue.h index c8022698d3..3b74b9132a 100644 --- a/include/xrpl/protocol/Issue.h +++ b/include/xrpl/protocol/Issue.h @@ -96,16 +96,16 @@ operator<=>(Issue const& lhs, Issue const& rhs) inline Issue const& xrpIssue() { - static Issue const kIssue{xrpCurrency(), xrpAccount()}; - return kIssue; + static Issue const kISSUE{xrpCurrency(), xrpAccount()}; + return kISSUE; } /** Returns an asset specifier that represents no account and currency. */ inline Issue const& noIssue() { - static Issue const kIssue{noCurrency(), noAccount()}; - return kIssue; + static Issue const kISSUE{noCurrency(), noAccount()}; + return kISSUE; } inline bool diff --git a/include/xrpl/protocol/LedgerHeader.h b/include/xrpl/protocol/LedgerHeader.h index f05b11d1eb..68dd5e24b9 100644 --- a/include/xrpl/protocol/LedgerHeader.h +++ b/include/xrpl/protocol/LedgerHeader.h @@ -26,12 +26,12 @@ struct LedgerHeader // // Closed means "tx set already determined" - uint256 hash = beast::kZero; - uint256 txHash = beast::kZero; - uint256 accountHash = beast::kZero; - uint256 parentHash = beast::kZero; + uint256 hash = beast::kZERO; + uint256 txHash = beast::kZERO; + uint256 accountHash = beast::kZERO; + uint256 parentHash = beast::kZERO; - XRPAmount drops = beast::kZero; + XRPAmount drops = beast::kZERO; // If validated is false, it means "not yet validated." // Once validated is true, it will never be set false at a later time. @@ -53,12 +53,12 @@ struct LedgerHeader }; // ledger close flags -static std::uint32_t const kSLcfNoConsensusTime = 0x01; +static std::uint32_t const kS_LCF_NO_CONSENSUS_TIME = 0x01; inline bool getCloseAgree(LedgerHeader const& info) { - return (info.closeFlags & kSLcfNoConsensusTime) == 0; + return (info.closeFlags & kS_LCF_NO_CONSENSUS_TIME) == 0; } void diff --git a/include/xrpl/protocol/MPTAmount.h b/include/xrpl/protocol/MPTAmount.h index 6ea36fc294..b4907774d2 100644 --- a/include/xrpl/protocol/MPTAmount.h +++ b/include/xrpl/protocol/MPTAmount.h @@ -88,7 +88,7 @@ constexpr MPTAmount::MPTAmount(value_type value) : value_(value) constexpr MPTAmount::MPTAmount(beast::Zero) { - *this = beast::kZero; + *this = beast::kZERO; } constexpr MPTAmount& diff --git a/include/xrpl/protocol/MultiApiJson.h b/include/xrpl/protocol/MultiApiJson.h index 9a4882ec55..5a7dfcd731 100644 --- a/include/xrpl/protocol/MultiApiJson.h +++ b/include/xrpl/protocol/MultiApiJson.h @@ -15,14 +15,14 @@ namespace xrpl { namespace detail { template -constexpr bool kIsIntegralConstant = false; +constexpr bool kIS_INTEGRAL_CONSTANT = false; template -constexpr bool kIsIntegralConstant&> = true; +constexpr bool kIS_INTEGRAL_CONSTANT&> = true; template -constexpr bool kIsIntegralConstant const&> = true; +constexpr bool kIS_INTEGRAL_CONSTANT const&> = true; template -concept some_integral_constant = detail::kIsIntegralConstant; +concept some_integral_constant = detail::kIS_INTEGRAL_CONSTANT; // This class is designed to wrap a collection of _almost_ identical json::Value // objects, indexed by version (i.e. there is some mapping of version to object @@ -47,8 +47,8 @@ struct MultiApiJson return (v < MinVer) ? 0 : static_cast(v - MinVer); } - static constexpr std::size_t kSize = MaxVer + 1 - MinVer; - std::array val = {}; + constexpr static std::size_t kSIZE = MaxVer + 1 - MinVer; + std::array val = {}; explicit MultiApiJson(json::Value const& init = {}) { @@ -80,7 +80,7 @@ struct MultiApiJson if (count == 0) return IsMemberResult::None; - return count < kSize ? IsMemberResult::Some : IsMemberResult::All; + return count < kSIZE ? IsMemberResult::Some : IsMemberResult::All; } static constexpr struct VisitorT final @@ -100,7 +100,7 @@ struct MultiApiJson std::integral_constant, Args&&...> { - static_assert(valid(Version) && index(Version) >= 0 && index(Version) < kSize); + static_assert(valid(Version) && index(Version) >= 0 && index(Version) < kSIZE); return std::invoke(fn, json.val[index(Version)], version, std::forward(args)...); } @@ -111,7 +111,7 @@ struct MultiApiJson operator()(Json& json, std::integral_constant const, Fn fn) const -> std::invoke_result_t { - static_assert(valid(Version) && index(Version) >= 0 && index(Version) < kSize); + static_assert(valid(Version) && index(Version) >= 0 && index(Version) < kSIZE); return std::invoke(fn, json.val[index(Version)]); } @@ -124,7 +124,7 @@ struct MultiApiJson -> std::invoke_result_t { XRPL_ASSERT( - valid(version) && index(version) >= 0 && index(version) < kSize, + valid(version) && index(version) >= 0 && index(version) < kSIZE, "xrpl::detail::MultiApijson::operator() : valid " "version"); return std::invoke(fn, json.val[index(version)], version, std::forward(args)...); @@ -139,20 +139,20 @@ struct MultiApiJson -> std::invoke_result_t { XRPL_ASSERT( - valid(version) && index(version) >= 0 && index(version) < kSize, + valid(version) && index(version) >= 0 && index(version) < kSIZE, "xrpl::detail::MultiApijson::operator() : valid version"); return std::invoke(fn, json.val[index(version)]); } - } kVisitor = {}; + } kVISITOR = {}; auto visit() { return [self = this](auto... args) requires requires { - kVisitor(std::declval(), std::declval()...); + kVISITOR(std::declval(), std::declval()...); } - { return kVisitor(*self, std::forward(args)...); }; + { return kVISITOR(*self, std::forward(args)...); }; } [[nodiscard]] auto @@ -160,27 +160,27 @@ struct MultiApiJson { return [self = this](auto... args) requires requires { - kVisitor(std::declval(), std::declval()...); + kVISITOR(std::declval(), std::declval()...); } - { return kVisitor(*self, std::forward(args)...); }; + { return kVISITOR(*self, std::forward(args)...); }; } template auto visit(Args... args) -> std::invoke_result_t requires(sizeof...(args) > 0) && - requires { kVisitor(*this, std::forward(args)...); } + requires { kVISITOR(*this, std::forward(args)...); } { - return kVisitor(*this, std::forward(args)...); + return kVISITOR(*this, std::forward(args)...); } template [[nodiscard]] auto visit(Args... args) const -> std::invoke_result_t requires(sizeof...(args) > 0) && - requires { kVisitor(*this, std::forward(args)...); } + requires { kVISITOR(*this, std::forward(args)...); } { - return kVisitor(*this, std::forward(args)...); + return kVISITOR(*this, std::forward(args)...); } }; @@ -188,6 +188,6 @@ struct MultiApiJson // Wrapper for Json for all supported API versions. using MultiApiJson = - detail::MultiApiJson; + detail::MultiApiJson; } // namespace xrpl diff --git a/include/xrpl/protocol/PathAsset.h b/include/xrpl/protocol/PathAsset.h index b51dc52b47..4c4a3f7af4 100644 --- a/include/xrpl/protocol/PathAsset.h +++ b/include/xrpl/protocol/PathAsset.h @@ -52,10 +52,10 @@ public: }; template -constexpr bool kIsCurrencyV = std::is_same_v; +constexpr bool kIS_CURRENCY_V = std::is_same_v; template -constexpr bool kIsMptidV = std::is_same_v; +constexpr bool kIS_MPTID_V = std::is_same_v; inline PathAsset::PathAsset(Asset const& asset) { diff --git a/include/xrpl/protocol/Protocol.h b/include/xrpl/protocol/Protocol.h index c96c6c3dfe..05463dae82 100644 --- a/include/xrpl/protocol/Protocol.h +++ b/include/xrpl/protocol/Protocol.h @@ -19,40 +19,40 @@ namespace xrpl { @ingroup protocol */ /** Smallest legal byte size of a transaction. */ -constexpr std::size_t kTxMinSizeBytes = 32; +std::size_t constexpr kTX_MIN_SIZE_BYTES = 32; /** Largest legal byte size of a transaction. */ -constexpr std::size_t kTxMaxSizeBytes = megabytes(1); +std::size_t constexpr kTX_MAX_SIZE_BYTES = megabytes(1); /** The maximum number of unfunded offers to delete at once */ -constexpr std::size_t kUnfundedOfferRemoveLimit = 1000; +std::size_t constexpr kUNFUNDED_OFFER_REMOVE_LIMIT = 1000; /** The maximum number of expired offers to delete at once */ -constexpr std::size_t kExpiredOfferRemoveLimit = 256; +std::size_t constexpr kEXPIRED_OFFER_REMOVE_LIMIT = 256; /** The maximum number of metadata entries allowed in one transaction */ -constexpr std::size_t kOversizeMetaDataCap = 5200; +std::size_t constexpr kOVERSIZE_META_DATA_CAP = 5200; /** The maximum number of entries per directory page */ -constexpr std::size_t kDirNodeMaxEntries = 32; +std::size_t constexpr kDIR_NODE_MAX_ENTRIES = 32; /** The maximum number of pages allowed in a directory Made obsolete by fixDirectoryLimit amendment. */ -constexpr std::uint64_t kDirNodeMaxPages = 262144; +std::uint64_t constexpr kDIR_NODE_MAX_PAGES = 262144; /** The maximum number of items in an NFT page */ -constexpr std::size_t kDirMaxTokensPerPage = 32; +std::size_t constexpr kDIR_MAX_TOKENS_PER_PAGE = 32; /** The maximum number of owner directory entries for account to be deletable */ -constexpr std::size_t kMaxDeletableDirEntries = 1000; +std::size_t constexpr kMAX_DELETABLE_DIR_ENTRIES = 1000; /** The maximum number of token offers that can be canceled at once */ -constexpr std::size_t kMaxTokenOfferCancelCount = 500; +std::size_t constexpr kMAX_TOKEN_OFFER_CANCEL_COUNT = 500; /** The maximum number of offers in an offer directory for NFT to be burnable */ -constexpr std::size_t kMaxDeletableTokenOfferEntries = 500; +std::size_t constexpr kMAX_DELETABLE_TOKEN_OFFER_ENTRIES = 500; /** The maximum token transfer fee allowed. @@ -63,7 +63,7 @@ constexpr std::size_t kMaxDeletableTokenOfferEntries = 500; Note that for extremely low transfer fees values, it is possible that the calculated fee will be 0. */ -constexpr std::uint16_t kMaxTransferFee = 50000; +std::uint16_t constexpr kMAX_TRANSFER_FEE = 50000; /** There are 10,000 basis points (bips) in 100%. * @@ -81,32 +81,32 @@ constexpr std::uint16_t kMaxTransferFee = 50000; * * Example: 50% is 0.50 * bipsPerUnity = 5,000 bps. */ -constexpr Bips32 kBipsPerUnity(100 * 100); -static_assert(kBipsPerUnity == Bips32{10'000}); -constexpr TenthBips32 kTenthBipsPerUnity(kBipsPerUnity.value() * 10); -static_assert(kTenthBipsPerUnity == TenthBips32(100'000)); +Bips32 constexpr kBIPS_PER_UNITY(100 * 100); +static_assert(kBIPS_PER_UNITY == Bips32{10'000}); +TenthBips32 constexpr kTENTH_BIPS_PER_UNITY(kBIPS_PER_UNITY.value() * 10); +static_assert(kTENTH_BIPS_PER_UNITY == TenthBips32(100'000)); constexpr Bips32 percentageToBips(std::uint32_t percentage) { - return Bips32(percentage * kBipsPerUnity.value() / 100); + return Bips32(percentage * kBIPS_PER_UNITY.value() / 100); } constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage) { - return TenthBips32(percentage * kTenthBipsPerUnity.value() / 100); + return TenthBips32(percentage * kTENTH_BIPS_PER_UNITY.value() / 100); } template constexpr T bipsOfValue(T value, Bips bips) { - return value * bips.value() / kBipsPerUnity.value(); + return value * bips.value() / kBIPS_PER_UNITY.value(); } template constexpr T tenthBipsOfValue(T value, TenthBips bips) { - return value * bips.value() / kTenthBipsPerUnity.value(); + return value * bips.value() / kTENTH_BIPS_PER_UNITY.value(); } namespace Lending { @@ -114,54 +114,54 @@ namespace Lending { Valid values are between 0 and 10% inclusive. */ -constexpr TenthBips16 kMaxManagementFeeRate( +TenthBips16 constexpr kMAX_MANAGEMENT_FEE_RATE( unsafeCast(percentageToTenthBips(10).value())); -static_assert(kMaxManagementFeeRate == TenthBips16(std::uint16_t(10'000u))); +static_assert(kMAX_MANAGEMENT_FEE_RATE == TenthBips16(std::uint16_t(10'000u))); /** The maximum coverage rate required of a loan broker in 1/10 bips. Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxCoverRate = percentageToTenthBips(100); -static_assert(kMaxCoverRate == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_COVER_RATE = percentageToTenthBips(100); +static_assert(kMAX_COVER_RATE == TenthBips32(100'000u)); /** The maximum overpayment fee on a loan in 1/10 bips. * Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxOverpaymentFee = percentageToTenthBips(100); -static_assert(kMaxOverpaymentFee == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_OVERPAYMENT_FEE = percentageToTenthBips(100); +static_assert(kMAX_OVERPAYMENT_FEE == TenthBips32(100'000u)); /** Annualized interest rate of the Loan in 1/10 bips. * * Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxInterestRate = percentageToTenthBips(100); -static_assert(kMaxInterestRate == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_INTEREST_RATE = percentageToTenthBips(100); +static_assert(kMAX_INTEREST_RATE == TenthBips32(100'000u)); /** The maximum premium added to the interest rate for late payments on a loan * in 1/10 bips. * * Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxLateInterestRate = percentageToTenthBips(100); -static_assert(kMaxLateInterestRate == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_LATE_INTEREST_RATE = percentageToTenthBips(100); +static_assert(kMAX_LATE_INTEREST_RATE == TenthBips32(100'000u)); /** The maximum close interest rate charged for repaying a loan early in 1/10 * bips. * * Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxCloseInterestRate = percentageToTenthBips(100); -static_assert(kMaxCloseInterestRate == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_CLOSE_INTEREST_RATE = percentageToTenthBips(100); +static_assert(kMAX_CLOSE_INTEREST_RATE == TenthBips32(100'000u)); /** The maximum overpayment interest rate charged on loan overpayments in 1/10 * bips. * * Valid values are between 0 and 100% inclusive. */ -constexpr TenthBips32 kMaxOverpaymentInterestRate = percentageToTenthBips(100); -static_assert(kMaxOverpaymentInterestRate == TenthBips32(100'000u)); +TenthBips32 constexpr kMAX_OVERPAYMENT_INTEREST_RATE = percentageToTenthBips(100); +static_assert(kMAX_OVERPAYMENT_INTEREST_RATE == TenthBips32(100'000u)); /** LoanPay transaction cost will be one base fee per X combined payments * @@ -172,7 +172,7 @@ static_assert(kMaxOverpaymentInterestRate == TenthBips32(100'000u)); * This number was chosen arbitrarily, but should not be changed once released * without an amendment */ -static constexpr int kLoanPaymentsPerFeeIncrement = 5; +static constexpr int kLOAN_PAYMENTS_PER_FEE_INCREMENT = 5; /** Maximum number of combined payments that a LoanPay transaction will process * @@ -196,65 +196,65 @@ static constexpr int kLoanPaymentsPerFeeIncrement = 5; * This number was chosen arbitrarily, but should not be changed once released * without an amendment */ -static constexpr int kLoanMaximumPaymentsPerTransaction = 100; +static constexpr int kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION = 100; } // namespace Lending /** The maximum length of a URI inside an NFT */ -constexpr std::size_t kMaxTokenUriLength = 256; +std::size_t constexpr kMAX_TOKEN_URI_LENGTH = 256; /** The maximum length of a Data element inside a DID */ -constexpr std::size_t kMaxDidDocumentLength = 256; +std::size_t constexpr kMAX_DID_DOCUMENT_LENGTH = 256; /** The maximum length of a URI inside a DID */ -constexpr std::size_t kMaxDidUriLength = 256; +std::size_t constexpr kMAX_DIDURI_LENGTH = 256; /** The maximum length of an Attestation inside a DID */ -constexpr std::size_t kMaxDidDataLength = 256; +std::size_t constexpr kMAX_DID_DATA_LENGTH = 256; /** The maximum length of a domain */ -constexpr std::size_t kMaxDomainLength = 256; +std::size_t constexpr kMAX_DOMAIN_LENGTH = 256; /** The maximum length of a URI inside a Credential */ -constexpr std::size_t kMaxCredentialUriLength = 256; +std::size_t constexpr kMAX_CREDENTIAL_URI_LENGTH = 256; /** The maximum length of a CredentialType inside a Credential */ -constexpr std::size_t kMaxCredentialTypeLength = 64; +std::size_t constexpr kMAX_CREDENTIAL_TYPE_LENGTH = 64; /** The maximum number of credentials can be passed in array */ -constexpr std::size_t kMaxCredentialsArraySize = 8; +std::size_t constexpr kMAX_CREDENTIALS_ARRAY_SIZE = 8; /** The maximum number of credentials can be passed in array for permissioned * domain */ -constexpr std::size_t kMaxPermissionedDomainCredentialsArraySize = 10; +std::size_t constexpr kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE = 10; /** The maximum length of MPTokenMetadata */ -constexpr std::size_t kMaxMpTokenMetadataLength = 1024; +std::size_t constexpr kMAX_MP_TOKEN_METADATA_LENGTH = 1024; /** The maximum amount of MPTokenIssuance */ -constexpr std::uint64_t kMaxMpTokenAmount = 0x7FFF'FFFF'FFFF'FFFFull; -static_assert(Number::kMaxRep >= kMaxMpTokenAmount); +std::uint64_t constexpr kMAX_MP_TOKEN_AMOUNT = 0x7FFF'FFFF'FFFF'FFFFull; +static_assert(Number::kMAX_REP >= kMAX_MP_TOKEN_AMOUNT); /** The maximum length of Data payload */ -constexpr std::size_t kMaxDataPayloadLength = 256; +std::size_t constexpr kMAX_DATA_PAYLOAD_LENGTH = 256; /** Vault withdrawal policies */ -constexpr std::uint8_t kVaultStrategyFirstComeFirstServe = 1; +std::uint8_t constexpr kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE = 1; /** Default IOU scale factor for a Vault */ -constexpr std::uint8_t kVaultDefaultIouScale = 6; +std::uint8_t constexpr kVAULT_DEFAULT_IOU_SCALE = 6; /** Maximum scale factor for a Vault. The number is chosen to ensure that 1 IOU can be always converted to shares. 10^19 > maxMPTokenAmount (2^64-1) > 10^18 */ -constexpr std::uint8_t kVaultMaximumIouScale = 18; +std::uint8_t constexpr kVAULT_MAXIMUM_IOU_SCALE = 18; /** Maximum recursion depth for vault shares being put as an asset inside * another vault; counted from 0 */ -constexpr std::uint8_t kMaxAssetCheckDepth = 5; +std::uint8_t constexpr kMAX_ASSET_CHECK_DEPTH = 5; /** A ledger index. */ using LedgerIndex = std::uint32_t; -constexpr std::uint32_t kFlagLedgerInterval = 256; +std::uint32_t constexpr kFLAG_LEDGER_INTERVAL = 256; /** Returns true if the given ledgerIndex is a voting ledgerIndex */ bool @@ -273,88 +273,88 @@ using TxID = uint256; /** The maximum number of trustlines to delete as part of AMM account * deletion cleanup. */ -constexpr std::uint16_t kMaxDeletableAmmTrustLines = 512; +std::uint16_t constexpr kMAX_DELETABLE_AMM_TRUST_LINES = 512; /** The maximum length of a URI inside an Oracle */ -constexpr std::size_t kMaxOracleUri = 256; +std::size_t constexpr kMAX_ORACLE_URI = 256; /** The maximum length of a Provider inside an Oracle */ -constexpr std::size_t kMaxOracleProvider = 256; +std::size_t constexpr kMAX_ORACLE_PROVIDER = 256; /** The maximum size of a data series array inside an Oracle */ -constexpr std::size_t kMaxOracleDataSeries = 10; +std::size_t constexpr kMAX_ORACLE_DATA_SERIES = 10; /** The maximum length of a SymbolClass inside an Oracle */ -constexpr std::size_t kMaxOracleSymbolClass = 16; +std::size_t constexpr kMAX_ORACLE_SYMBOL_CLASS = 16; /** The maximum allowed time difference between lastUpdateTime and the time of the last closed ledger */ -constexpr std::size_t kMaxLastUpdateTimeDelta = 300; +std::size_t constexpr kMAX_LAST_UPDATE_TIME_DELTA = 300; /** The maximum price scaling factor */ -constexpr std::size_t kMaxPriceScale = 20; +std::size_t constexpr kMAX_PRICE_SCALE = 20; /** The maximum percentage of outliers to trim */ -constexpr std::size_t kMaxTrim = 25; +std::size_t constexpr kMAX_TRIM = 25; /** The maximum number of delegate permissions an account can grant */ -constexpr std::size_t kPermissionMaxSize = 10; +std::size_t constexpr kPERMISSION_MAX_SIZE = 10; /** The maximum number of transactions that can be in a batch. */ -constexpr std::size_t kMaxBatchTxCount = 8; +std::size_t constexpr kMAX_BATCH_TX_COUNT = 8; /** Length of one component of EC ElGamal ciphertext */ -std::size_t constexpr kEcGamalEncryptedLength = 33; +std::size_t constexpr kEC_GAMAL_ENCRYPTED_LENGTH = 33; /** EC ElGamal ciphertext length: two 33-byte components concatenated */ -std::size_t constexpr kEcGamalEncryptedTotalLength = kEcGamalEncryptedLength * 2; +std::size_t constexpr kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH = kEC_GAMAL_ENCRYPTED_LENGTH * 2; /** Length of EC point (compressed) */ -std::size_t constexpr kCompressedEcPointLength = 33; +std::size_t constexpr kCOMPRESSED_EC_POINT_LENGTH = 33; /** Length of EC public key (compressed) */ -std::size_t constexpr kEcPubKeyLength = kCompressedEcPointLength; +std::size_t constexpr kEC_PUB_KEY_LENGTH = kCOMPRESSED_EC_POINT_LENGTH; /** Length of EC private key in bytes */ -std::size_t constexpr kEcPrivKeyLength = 32; +std::size_t constexpr kEC_PRIV_KEY_LENGTH = 32; /** Length of the EC blinding factor in bytes */ -std::size_t constexpr kEcBlindingFactorLength = 32; +std::size_t constexpr kEC_BLINDING_FACTOR_LENGTH = 32; /** Length of Schnorr ZKProof for public key registration (compact form) in bytes */ -std::size_t constexpr kEcSchnorrProofLength = 64; +std::size_t constexpr kEC_SCHNORR_PROOF_LENGTH = 64; /** Length of Pedersen Commitment (compressed) */ -std::size_t constexpr kEcPedersenCommitmentLength = kCompressedEcPointLength; +std::size_t constexpr kEC_PEDERSEN_COMMITMENT_LENGTH = kCOMPRESSED_EC_POINT_LENGTH; /** Length of single bulletproof (range proof for 1 commitment) in bytes */ -std::size_t constexpr kEcSingleBulletproofLength = 688; +std::size_t constexpr kEC_SINGLE_BULLETPROOF_LENGTH = 688; /** Length of double bulletproof (range proof for 2 commitments) in bytes */ -std::size_t constexpr kEcDoubleBulletproofLength = 754; +std::size_t constexpr kEC_DOUBLE_BULLETPROOF_LENGTH = 754; /** Length of the ZKProof for ConfidentialMPTSend. * 192 bytes compact sigma proof + 754 bytes double bulletproof. */ -std::size_t constexpr kEcSendProofLength = 946; +std::size_t constexpr kEC_SEND_PROOF_LENGTH = 946; /** Length of the ZKProof for ConfidentialMPTConvertBack. * 128 bytes compact sigma proof + 688 bytes single bulletproof. */ -std::size_t constexpr kEcConvertBackProofLength = 816; +std::size_t constexpr kEC_CONVERT_BACK_PROOF_LENGTH = 816; /** Length of the ZKProof for ConfidentialMPTClawback. */ -std::size_t constexpr kEcClawbackProofLength = 64; +std::size_t constexpr kEC_CLAWBACK_PROOF_LENGTH = 64; /** Extra base fee multiplier charged to confidential MPT transactions. */ -std::uint32_t constexpr kConfidentialFeeMultiplier = 9; +std::uint32_t constexpr kCONFIDENTIAL_FEE_MULTIPLIER = 9; /** Compressed EC point prefix for even y-coordinate */ -std::uint8_t constexpr kEcCompressedPrefixEvenY = 0x02; +std::uint8_t constexpr kEC_COMPRESSED_PREFIX_EVEN_Y = 0x02; /** Compressed EC point prefix for odd y-coordinate */ -std::uint8_t constexpr kEcCompressedPrefixOddY = 0x03; +std::uint8_t constexpr kEC_COMPRESSED_PREFIX_ODD_Y = 0x03; } // namespace xrpl diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index 20693160d3..75b898a71c 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -43,8 +43,8 @@ class PublicKey protected: // All the constructed public keys are valid, non-empty and contain 33 // bytes of data. - static constexpr std::size_t kSize = 33; - std::uint8_t buf_[kSize]{}; // should be large enough + static constexpr std::size_t kSIZE = 33; + std::uint8_t buf_[kSIZE]{}; // should be large enough public: using const_iterator = std::uint8_t const*; @@ -72,7 +72,7 @@ public: static std::size_t size() noexcept { - return kSize; + return kSIZE; } [[nodiscard]] const_iterator @@ -90,19 +90,19 @@ public: [[nodiscard]] const_iterator end() const noexcept { - return buf_ + kSize; + return buf_ + kSIZE; } [[nodiscard]] const_iterator cend() const noexcept { - return buf_ + kSize; + return buf_ + kSIZE; } [[nodiscard]] Slice slice() const noexcept { - return {buf_, kSize}; + return {buf_, kSIZE}; } operator Slice() const noexcept @@ -267,10 +267,10 @@ getOrThrow(json::Value const& v, xrpl::SField const& field) { using namespace xrpl; std::string const b58 = getOrThrow(v, field); - if (auto pubKeyBlob = strUnHex(b58); - pubKeyBlob.has_value() && publicKeyType(makeSlice(*pubKeyBlob))) + if (auto pubKeyBlob = strUnHex(b58); pubKeyBlob && publicKeyType(makeSlice(*pubKeyBlob))) { - return PublicKey{makeSlice(*pubKeyBlob)}; + return PublicKey{makeSlice( + *pubKeyBlob)}; // NOLINT(bugprone-unchecked-optional-access) checked in condition above } for (auto const tokenType : {TokenType::NodePublic, TokenType::AccountPublic}) { diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index e261025cb8..115e4498df 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -26,7 +26,7 @@ struct TAmounts { TAmounts() = default; - TAmounts(beast::Zero, beast::Zero) : in(beast::kZero), out(beast::kZero) + TAmounts(beast::Zero, beast::Zero) : in(beast::kZERO), out(beast::kZERO) { } @@ -38,7 +38,7 @@ struct TAmounts [[nodiscard]] bool empty() const noexcept { - return in <= beast::kZero || out <= beast::kZero; + return in <= beast::kZERO || out <= beast::kZERO; } TAmounts& @@ -94,8 +94,8 @@ public: // have lower unsigned integer representations. using value_type = std::uint64_t; - static int const kMinTickSize = 3; - static int const kMaxTickSize = 16; + static int const kMIN_TICK_SIZE = 3; + static int const kMAX_TICK_SIZE = 16; private: // This has the same representation as STAmount, see the comment on the @@ -316,10 +316,10 @@ TAmounts Quality::ceilIn(TAmounts const& amount, In const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*kCeilInFnPtr)(Amounts const&, STAmount const&) const = + static constexpr Amounts (Quality::*kCEIL_IN_FN_PTR)(Amounts const&, STAmount const&) const = &Quality::ceilIn; - return ceilTAmountsHelper(amount, limit, amount.in, kCeilInFnPtr); + return ceilTAmountsHelper(amount, limit, amount.in, kCEIL_IN_FN_PTR); } template @@ -327,10 +327,10 @@ TAmounts Quality::ceilInStrict(TAmounts const& amount, In const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*kCeilInFnPtr)(Amounts const&, STAmount const&, bool) const = - &Quality::ceilInStrict; + static constexpr Amounts (Quality::*kCEIL_IN_FN_PTR)(Amounts const&, STAmount const&, bool) + const = &Quality::ceilInStrict; - return ceilTAmountsHelper(amount, limit, amount.in, kCeilInFnPtr, roundUp); + return ceilTAmountsHelper(amount, limit, amount.in, kCEIL_IN_FN_PTR, roundUp); } template @@ -338,10 +338,10 @@ TAmounts Quality::ceilOut(TAmounts const& amount, Out const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*kCeilOutFnPtr)(Amounts const&, STAmount const&) const = + static constexpr Amounts (Quality::*kCEIL_OUT_FN_PTR)(Amounts const&, STAmount const&) const = &Quality::ceilOut; - return ceil_TAmounts_helper(amount, limit, amount.out, kCeilOutFnPtr); + return ceil_TAmounts_helper(amount, limit, amount.out, kCEIL_OUT_FN_PTR); } template @@ -349,10 +349,10 @@ TAmounts Quality::ceilOutStrict(TAmounts const& amount, Out const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*kCeilOutFnPtr)(Amounts const&, STAmount const&, bool) + static constexpr Amounts (Quality::*kCEIL_OUT_FN_PTR)(Amounts const&, STAmount const&, bool) const = &Quality::ceilOutStrict; - return ceilTAmountsHelper(amount, limit, amount.out, kCeilOutFnPtr, roundUp); + return ceilTAmountsHelper(amount, limit, amount.out, kCEIL_OUT_FN_PTR, roundUp); } /** Calculate the quality of a two-hop path given the two hops. diff --git a/include/xrpl/protocol/QualityFunction.h b/include/xrpl/protocol/QualityFunction.h index 96d30735b8..f7f92e50da 100644 --- a/include/xrpl/protocol/QualityFunction.h +++ b/include/xrpl/protocol/QualityFunction.h @@ -72,7 +72,7 @@ QualityFunction::QualityFunction( std::uint32_t tfee, QualityFunction::AMMTag) { - if (amounts.in <= beast::kZero || amounts.out <= beast::kZero) + if (amounts.in <= beast::kZERO || amounts.out <= beast::kZERO) Throw("QualityFunction amounts are 0."); Number const cfee = feeMult(tfee); m_ = -cfee / amounts.in; diff --git a/include/xrpl/protocol/Rate.h b/include/xrpl/protocol/Rate.h index 504b17ed80..5dcd62a295 100644 --- a/include/xrpl/protocol/Rate.h +++ b/include/xrpl/protocol/Rate.h @@ -72,6 +72,6 @@ transferFeeAsRate(std::uint16_t fee); } // namespace nft /** A transfer rate signifying a 1:1 exchange */ -extern Rate const kParityRate; +extern Rate const kPARITY_RATE; } // namespace xrpl diff --git a/include/xrpl/protocol/Rules.h b/include/xrpl/protocol/Rules.h index 9c17ff2391..fbbd3d8805 100644 --- a/include/xrpl/protocol/Rules.h +++ b/include/xrpl/protocol/Rules.h @@ -122,17 +122,4 @@ private: std::optional saved_; }; -class NumberSO; -class NumberMantissaScaleGuard; - -bool -useRulesGuards(Rules const& rules); - -void -createGuards( - Rules const& rules, - std::optional& stNumberSO, - std::optional& rulesGuard, - std::optional& mantissaScaleGuard); - } // namespace xrpl diff --git a/include/xrpl/protocol/SField.h b/include/xrpl/protocol/SField.h index 34fb66ce00..45e4d8932e 100644 --- a/include/xrpl/protocol/SField.h +++ b/include/xrpl/protocol/SField.h @@ -92,7 +92,7 @@ class STCurrency; // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum SerializedTypeID { XMACRO(TO_ENUM) }; -static std::map const kSTypeMap = {XMACRO(TO_MAP)}; +static std::map const kS_TYPE_MAP = {XMACRO(TO_MAP)}; #undef XMACRO #undef TO_ENUM @@ -129,23 +129,26 @@ fieldCode(int id, int index) class SField { public: - static constexpr auto kSmdNever = 0x00; - static constexpr auto kSmdChangeOrig = 0x01; // original value when it changes - static constexpr auto kSmdChangeNew = 0x02; // new value when it changes - static constexpr auto kSmdDeleteFinal = 0x04; // final value when it is deleted - static constexpr auto kSmdCreate = 0x08; // value when it's created - static constexpr auto kSmdAlways = 0x10; // value when node containing it is affected at all - static constexpr auto kSmdBaseTen = 0x20; // value is treated as base 10, overriding behavior - static constexpr auto kSmdPseudoAccount = 0x40; // if this field is set in an ACCOUNT_ROOT - // _only_, then it is a pseudo-account - static constexpr auto kSmdNeedsAsset = 0x80; // This field needs to be associated with an - // asset before it is serialized as a ledger - // object. Intended for STNumber. - static constexpr auto kSmdDefault = - kSmdChangeOrig | kSmdChangeNew | kSmdDeleteFinal | kSmdCreate; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + SMdNever = 0x00, + SMdChangeOrig = 0x01, // original value when it changes + SMdChangeNew = 0x02, // new value when it changes + SMdDeleteFinal = 0x04, // final value when it is deleted + SMdCreate = 0x08, // value when it's created + SMdAlways = 0x10, // value when node containing it is affected at all + SMdBaseTen = 0x20, // value is treated as base 10, overriding behavior + SMdPseudoAccount = 0x40, // if this field is set in an ACCOUNT_ROOT + // _only_, then it is a pseudo-account + SMdNeedsAsset = 0x80, // This field needs to be associated with an + // asset before it is serialized as a ledger + // object. Intended for STNumber. + SMdDefault = SMdChangeOrig | SMdChangeNew | SMdDeleteFinal | SMdCreate + }; enum class IsSigning : unsigned char { No, Yes }; - static IsSigning const kNotSigning = IsSigning::No; + static IsSigning const kNOT_SIGNING = IsSigning::No; int const fieldCodeMem; // (type<<16)|index // TODO: rename, clashes with function SerializedTypeID const fieldType; // STI_* @@ -172,7 +175,7 @@ public: SerializedTypeID tid, int fv, char const* fn, - int meta = kSmdDefault, + int meta = SMdDefault, IsSigning signing = IsSigning::Yes); explicit SField(PrivateAccessTagT, int fc, char const* fn); @@ -365,8 +368,8 @@ using SF_XCHAIN_BRIDGE = TypedField; #define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SField const sfName; #define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SF_##stiSuffix const sfName; -extern SField const sfInvalid; // NOLINT(readability-identifier-naming) -extern SField const sfGeneric; // NOLINT(readability-identifier-naming) +extern SField const kSF_INVALID; +extern SField const kSF_GENERIC; #include diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index 1a5b442d8b..7fa6ef88ae 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -3,13 +3,11 @@ #include #include #include -#include #include #include #include #include #include -#include #include #include #include @@ -44,24 +42,24 @@ private: public: using value_type = STAmount; - static constexpr int kMinOffset = -96; - static constexpr int kMaxOffset = 80; + constexpr static int kMIN_OFFSET = -96; + constexpr static int kMAX_OFFSET = 80; // Maximum native value supported by the code - static constexpr std::uint64_t kMinValue = 1'000'000'000'000'000ull; - static_assert(isPowerOfTen(kMinValue)); - static constexpr std::uint64_t kMaxValue = (kMinValue * 10) - 1; - static_assert(kMaxValue == 9'999'999'999'999'999ull); - static constexpr std::uint64_t kMaxNative = 9'000'000'000'000'000'000ull; + constexpr static std::uint64_t kMIN_VALUE = 1'000'000'000'000'000ull; + static_assert(isPowerOfTen(kMIN_VALUE)); + constexpr static std::uint64_t kMAX_VALUE = (kMIN_VALUE * 10) - 1; + static_assert(kMAX_VALUE == 9'999'999'999'999'999ull); + constexpr static std::uint64_t kMAX_NATIVE = 9'000'000'000'000'000'000ull; // Max native value on network. - static constexpr std::uint64_t kMaxNativeN = 100'000'000'000'000'000ull; - static constexpr std::uint64_t kIssuedCurrency = 0x8'000'000'000'000'000ull; - static constexpr std::uint64_t kPositive = 0x4'000'000'000'000'000ull; - static constexpr std::uint64_t kMpToken = 0x2'000'000'000'000'000ull; - static constexpr std::uint64_t kValueMask = ~(kPositive | kMpToken); + constexpr static std::uint64_t kMAX_NATIVE_N = 100'000'000'000'000'000ull; + constexpr static std::uint64_t kISSUED_CURRENCY = 0x8'000'000'000'000'000ull; + constexpr static std::uint64_t kPOSITIVE = 0x4'000'000'000'000'000ull; + constexpr static std::uint64_t kMP_TOKEN = 0x2'000'000'000'000'000ull; + constexpr static std::uint64_t kVALUE_MASK = ~(kPOSITIVE | kMP_TOKEN); - static std::uint64_t const kURateOne; + static std::uint64_t const kU_RATE_ONE; //-------------------------------------------------------------------------- STAmount(SerialIter& sit, SField const& name); @@ -186,23 +184,6 @@ public: [[nodiscard]] STAmount const& value() const noexcept; - /** - * Checks if this amount evaluates to zero when constrained to a specific - * accounting scale. - * For XRP and MPT `roundToScale` is a no-op, returns true only when the amount itself is zero. - * The `scale` argument is ignored in that case. - * For IOU, the amount is rounded to the given scale using Number::RoundingMode::ToNearest mode - * and the result is checked for zero; if `scale <= exponent()`, `roundToScale` short-circuits - * and returns the value unchanged, so this returns false for any non-zero amount. - * - * @param scale The target accounting scale to evaluate against. - * @return `true` if this amount rounds to zero at the given scale, `false` otherwise. - * - * @see roundToScale - */ - [[nodiscard]] bool - isZeroAtScale(int scale) const; - //-------------------------------------------------------------------------- // // Operators @@ -260,7 +241,7 @@ public: [[nodiscard]] std::string getText() const override; - [[nodiscard]] json::Value getJson(JsonOptions = JsonOptions::Values::None) const override; + [[nodiscard]] json::Value getJson(JsonOptions = JsonOptions::KNone) const override; void add(Serializer& s) const override; @@ -375,7 +356,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) - : asset_(issue), offset_(amount.exponent()), isNegative_(amount < beast::kZero) + : asset_(issue), offset_(amount.exponent()), isNegative_(amount < beast::kZERO) { if (isNegative_) { @@ -390,7 +371,7 @@ inline STAmount::STAmount(IOUAmount const& amount, Issue const& issue) } inline STAmount::STAmount(MPTAmount const& amount, MPTIssue const& mptIssue) - : asset_(mptIssue), offset_(0), isNegative_(amount < beast::kZero) + : asset_(mptIssue), offset_(0), isNegative_(amount < beast::kZERO) { if (isNegative_) { @@ -517,7 +498,7 @@ STAmount::zeroed() const inline STAmount:: operator bool() const noexcept { - return *this != beast::kZero; + return *this != beast::kZERO; } inline STAmount:: @@ -559,7 +540,7 @@ STAmount::fromNumber(A const& a, Number const& number) return STAmount{asset, intValue, 0, negative}; } - auto const [mantissa, exponent] = working.normalizeToRange(); + auto const [mantissa, exponent] = working.normalizeToRange(kMIN_VALUE, kMAX_VALUE); return STAmount{asset, mantissa, exponent, negative}; } @@ -567,7 +548,7 @@ STAmount::fromNumber(A const& a, Number const& number) inline void STAmount::negate() { - if (*this != beast::kZero) + if (*this != beast::kZERO) isNegative_ = !isNegative_; } @@ -594,25 +575,12 @@ STAmount::value() const noexcept return *this; } -[[nodiscard]] inline bool +inline bool isLegalNet(STAmount const& value) { - return !value.native() || (value.mantissa() <= STAmount::kMaxNativeN); + return !value.native() || (value.mantissa() <= STAmount::kMAX_NATIVE_N); } -[[nodiscard]] inline bool -isLegalMPT(STAmount const& value) -{ - return !value.holds() || - (!value.negative() && value.exponent() == 0 && value.mantissa() <= kMaxMpTokenAmount); -} - -/* Check recursively if an object has invalid MPTAmount or XRPAmount in STAmount field. - * Calls isLegalNet() and isLegalMPT(). - */ -[[nodiscard]] bool -hasInvalidAmount(STBase const& field, beast::Journal j); - //------------------------------------------------------------------------------ // // Operators diff --git a/include/xrpl/protocol/STBase.h b/include/xrpl/protocol/STBase.h index 6633253d3b..cba0bfbe74 100644 --- a/include/xrpl/protocol/STBase.h +++ b/include/xrpl/protocol/STBase.h @@ -18,23 +18,23 @@ struct JsonOptions using underlying_t = unsigned int; underlying_t value; - enum class Values : underlying_t { - None = 0b0000'0000, - IncludeDate = 0b0000'0001, - DisableApiPriorV2 = 0b0000'0010, + // Bitwise flags with operator~ + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum Values : underlying_t { + // clang-format off + KNone = 0b0000'0000, + KIncludeDate = 0b0000'0001, + KDisableApiPriorV2 = 0b0000'0010, - // IMPORTANT `All` must be union of all of the above; see also operator~ - All = IncludeDate | DisableApiPriorV2 // 0b0000'0011 + // IMPORTANT `kALL` must be union of all of the above; see also operator~ + KAll = 0b0000'0011 + // clang-format on }; constexpr JsonOptions(underlying_t v) noexcept : value(v) { } - constexpr JsonOptions(Values v) noexcept : value(static_cast(v)) - { - } - [[nodiscard]] constexpr explicit operator underlying_t() const noexcept { @@ -65,22 +65,22 @@ struct JsonOptions } /// Returns JsonOptions binary negation, can be used with & (above) for set - /// difference e.g. `(options & ~JsonOptions::kIncludeDate)` + /// difference e.g. `(options & ~JsonOptions::kINCLUDE_DATE)` [[nodiscard]] constexpr JsonOptions friend operator~(JsonOptions v) noexcept { - return {~v.value & static_cast(Values::All)}; + return {~v.value & static_cast(KAll)}; } }; template requires requires(T const& t) { - { t.getJson(JsonOptions::Values::None) } -> std::convertible_to; + { t.getJson(JsonOptions::KNone) } -> std::convertible_to; } json::Value toJson(T const& t) { - return t.getJson(JsonOptions::Values::None); + return t.getJson(JsonOptions::KNone); } namespace detail { @@ -148,7 +148,7 @@ public: [[nodiscard]] virtual std::string getText() const; - [[nodiscard]] virtual json::Value getJson(JsonOptions = JsonOptions::Values::None) const; + [[nodiscard]] virtual json::Value getJson(JsonOptions = JsonOptions::KNone) const; virtual void add(Serializer& s) const; diff --git a/include/xrpl/protocol/STBitString.h b/include/xrpl/protocol/STBitString.h index 87c8cd4f45..efb98cfe27 100644 --- a/include/xrpl/protocol/STBitString.h +++ b/include/xrpl/protocol/STBitString.h @@ -16,7 +16,7 @@ class STBitString final : public STBase, public CountedObject> static_assert(Bits > 0, "Number of bits must be positive"); public: - using value_type = BaseUInt; + using value_type = BaseUint; private: value_type value_{}; @@ -46,7 +46,7 @@ public: template void - setValue(BaseUInt const& v); + setValue(BaseUint const& v); [[nodiscard]] value_type const& value() const; @@ -157,7 +157,7 @@ STBitString::add(Serializer& s) const template template void -STBitString::setValue(BaseUInt const& v) +STBitString::setValue(BaseUint const& v) { value_ = v; } @@ -180,7 +180,7 @@ template bool STBitString::isDefault() const { - return value_ == beast::kZero; + return value_ == beast::kZERO; } } // namespace xrpl diff --git a/include/xrpl/protocol/STBlob.h b/include/xrpl/protocol/STBlob.h index 0667c54e30..84f44f1b78 100644 --- a/include/xrpl/protocol/STBlob.h +++ b/include/xrpl/protocol/STBlob.h @@ -24,7 +24,7 @@ public: STBlob(SField const& f, void const* data, std::size_t size); STBlob(SField const& f, Buffer&& b); STBlob(SField const& n); - STBlob(SerialIter&, SField const& name = sfGeneric); + STBlob(SerialIter&, SField const& name = kSF_GENERIC); [[nodiscard]] std::size_t size() const; diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index aa87411ae6..e37b132806 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -38,7 +38,7 @@ public: getText() const override; [[nodiscard]] json::Value - getJson(JsonOptions options = JsonOptions::Values::None) const override; + getJson(JsonOptions options = JsonOptions::KNone) const override; /** Returns the 'key' (or 'index') of this item. The key identifies this entry's position in diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index c635e8ce22..a9e46e8717 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -132,7 +132,7 @@ public: getText() const override; // TODO(tom): options should be an enum. - [[nodiscard]] json::Value getJson(JsonOptions = JsonOptions::Values::None) const override; + [[nodiscard]] json::Value getJson(JsonOptions = JsonOptions::KNone) const override; void addWithoutSigningFields(Serializer& s) const; @@ -381,7 +381,7 @@ public: template void - setFieldH160(SField const& field, BaseUInt<160, Tag> const& v); + setFieldH160(SField const& field, BaseUint<160, Tag> const& v); STObject& peekFieldObject(SField const& field); @@ -1143,7 +1143,7 @@ STObject::at(OptionaledField const& of) -> OptionalProxy template void -STObject::setFieldH160(SField const& field, BaseUInt<160, Tag> const& v) +STObject::setFieldH160(SField const& field, BaseUint<160, Tag> const& v) { STBase* rf = getPField(field, true); diff --git a/include/xrpl/protocol/STParsedJSON.h b/include/xrpl/protocol/STParsedJSON.h index 2557ab055b..d5b4f33be7 100644 --- a/include/xrpl/protocol/STParsedJSON.h +++ b/include/xrpl/protocol/STParsedJSON.h @@ -6,13 +6,6 @@ namespace xrpl { -/** Maximum JSON object nesting depth permitted during parsing. */ -inline constexpr std::size_t kMaxParsedJsonDepth = 64; - -/** Maximum number of elements permitted in any JSON array field during parsing. - Requests exceeding this limit are rejected with an invalidParams error. */ -inline constexpr std::size_t kMaxParsedJsonArraySize = 512; - /** Holds the serialized result of parsing an input JSON object. This does validation and checking on the provided JSON. */ diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index 1508dcb727..a1891164f6 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -21,8 +21,8 @@ class STPathElement final : public CountedObject PathAsset assetID_; AccountID issuerID_; - bool isOffer_; - std::size_t hashValue_; + bool is_offer_; + std::size_t hash_value_; public: // Bitwise values (typeCurrency | typeMPT) @@ -235,9 +235,9 @@ private: // ------------ STPathElement ------------ -inline STPathElement::STPathElement() : type_(TypeNone), isOffer_(true) +inline STPathElement::STPathElement() : type_(TypeNone), is_offer_(true) { - hashValue_ = getHash(*this); + hash_value_ = getHash(*this); } inline STPathElement::STPathElement( @@ -248,11 +248,11 @@ inline STPathElement::STPathElement( { if (!account) { - isOffer_ = true; + is_offer_ = true; } else { - isOffer_ = false; + is_offer_ = false; accountID_ = *account; type_ |= TypeAccount; XRPL_ASSERT( @@ -272,7 +272,7 @@ inline STPathElement::STPathElement( XRPL_ASSERT(issuerID_ != noAccount(), "xrpl::STPathElement::STPathElement : issuer is set"); } - hashValue_ = getHash(*this); + hash_value_ = getHash(*this); } inline STPathElement::STPathElement( @@ -284,9 +284,9 @@ inline STPathElement::STPathElement( , accountID_(account) , assetID_(asset) , issuerID_(issuer) - , isOffer_(isXRP(accountID_)) + , is_offer_(isXRP(accountID_)) { - if (!isOffer_) + if (!is_offer_) type_ |= TypeAccount; if (forceAsset || !isXRP(assetID_)) @@ -295,7 +295,7 @@ inline STPathElement::STPathElement( if (!isXRP(issuer)) type_ |= TypeIssuer; - hashValue_ = getHash(*this); + hash_value_ = getHash(*this); } inline STPathElement::STPathElement( @@ -307,12 +307,12 @@ inline STPathElement::STPathElement( , accountID_(account) , assetID_(asset) , issuerID_(issuer) - , isOffer_(isXRP(accountID_)) + , is_offer_(isXRP(accountID_)) { assetID_.visit( [&](Currency const&) { type_ = type_ & (~Type::TypeMpt); }, [&](MPTID const&) { type_ = type_ & (~Type::TypeCurrency); }); - hashValue_ = getHash(*this); + hash_value_ = getHash(*this); } inline auto @@ -324,7 +324,7 @@ STPathElement::getNodeType() const inline bool STPathElement::isOffer() const { - return isOffer_; + return is_offer_; } inline bool @@ -404,7 +404,7 @@ STPathElement::getIssuerID() const inline bool STPathElement::operator==(STPathElement const& t) const { - return (type_ & TypeAccount) == (t.type_ & TypeAccount) && hashValue_ == t.hashValue_ && + return (type_ & TypeAccount) == (t.type_ & TypeAccount) && hash_value_ == t.hash_value_ && accountID_ == t.accountID_ && assetID_ == t.assetID_ && issuerID_ == t.issuerID_; } diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index 4deedfafb7..d1bd32848f 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -27,11 +27,11 @@ enum class TxnSql : char { class STTx final : public STObject, public CountedObject { uint256 tid_; - TxType txType_; + TxType tx_type_; public: - static constexpr std::size_t kMinMultiSigners = 1; - static constexpr std::size_t kMaxMultiSigners = 32; + static constexpr std::size_t kMIN_MULTI_SIGNERS = 1; + static constexpr std::size_t kMAX_MULTI_SIGNERS = 32; STTx() = delete; STTx(STTx const& other) = default; @@ -187,7 +187,7 @@ inline STTx::STTx(SerialIter&& sit) // NOLINT(cppcoreguidelines-rvalue-referenc inline TxType STTx::getTxnType() const { - return txType_; + return tx_type_; } inline Blob diff --git a/include/xrpl/protocol/STValidation.h b/include/xrpl/protocol/STValidation.h index 91ce88b441..27d5ef1051 100644 --- a/include/xrpl/protocol/STValidation.h +++ b/include/xrpl/protocol/STValidation.h @@ -16,10 +16,10 @@ namespace xrpl { // Validation flags // This is a full (as opposed to a partial) validation -constexpr std::uint32_t kVfFullValidation = 0x00000001; +constexpr std::uint32_t kVF_FULL_VALIDATION = 0x00000001; // The signature is fully canonical -constexpr std::uint32_t kVfFullyCanonicalSig = 0x80000000; +constexpr std::uint32_t kVF_FULLY_CANONICAL_SIG = 0x80000000; class STValidation final : public STObject, public CountedObject { @@ -161,7 +161,7 @@ STValidation::STValidation(SerialIter& sit, LookupNodeID&& lookupNodeID, bool ch if (checkSignature && !isValid()) { JLOG(debugLog().error()) << "Invalid signature in validation: " - << getJson(JsonOptions::Values::None); + << getJson(JsonOptions::KNone); Throw("Invalid signature in validation"); } @@ -204,7 +204,7 @@ STValidation::STValidation( f(*this); // Finally, sign the validation and mark it as trusted: - setFlag(kVfFullyCanonicalSig); + setFlag(kVF_FULLY_CANONICAL_SIG); setFieldVL(sfSignature, signDigest(pk, sk, getSigningHash())); setTrusted(); diff --git a/include/xrpl/protocol/SecretKey.h b/include/xrpl/protocol/SecretKey.h index 712b095f81..9af27e9709 100644 --- a/include/xrpl/protocol/SecretKey.h +++ b/include/xrpl/protocol/SecretKey.h @@ -17,10 +17,10 @@ namespace xrpl { class SecretKey { public: - static constexpr std::size_t kSize = 32; + static constexpr std::size_t kSIZE = 32; private: - std::uint8_t buf_[kSize]{}; + std::uint8_t buf_[kSIZE]{}; public: using const_iterator = std::uint8_t const*; @@ -37,7 +37,7 @@ public: ~SecretKey(); - SecretKey(std::array const& data); + SecretKey(std::array const& data); SecretKey(Slice const& slice); [[nodiscard]] std::uint8_t const* diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index ffe9afabe8..385c09009a 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -102,7 +102,7 @@ public: template int - addBitString(BaseUInt const& v) + addBitString(BaseUint const& v) { return addRaw(v.data(), v.size()); } @@ -134,13 +134,13 @@ public: bool getInteger(Integer& number, int offset) { - static auto const kBytes = sizeof(Integer); - if ((offset + kBytes) > data_.size()) + static auto const kBYTES = sizeof(Integer); + if ((offset + kBYTES) > data_.size()) return false; number = 0; auto ptr = &data_[offset]; - for (auto i = 0; i < kBytes; ++i) + for (auto i = 0; i < kBYTES; ++i) { if (i) number <<= 8; @@ -151,7 +151,7 @@ public: template bool - getBitString(BaseUInt& data, int offset) const + getBitString(BaseUint& data, int offset) const { auto success = (offset + (Bits / 8)) <= data_.size(); if (success) @@ -369,7 +369,7 @@ public: geti64(); template - BaseUInt + BaseUint getBitString(); uint128 @@ -428,7 +428,7 @@ public: }; template -BaseUInt +BaseUint SerialIter::getBitString() { auto const n = Bits / 8; @@ -442,7 +442,7 @@ SerialIter::getBitString() used_ += n; remain_ -= n; - return BaseUInt::fromVoid(x); + return BaseUint::fromVoid(x); } } // namespace xrpl diff --git a/include/xrpl/protocol/SystemParameters.h b/include/xrpl/protocol/SystemParameters.h index 1cc35a0f31..029c0418b5 100644 --- a/include/xrpl/protocol/SystemParameters.h +++ b/include/xrpl/protocol/SystemParameters.h @@ -14,22 +14,22 @@ namespace xrpl { static inline std::string const& systemName() { - static std::string const kName = "xrpld"; - return kName; + static std::string const kNAME = "xrpld"; + return kNAME; } /** Configure the native currency. */ /** Number of drops in the genesis account. */ -constexpr XRPAmount kInitialXrp{100'000'000'000 * kDropsPerXrp}; -static_assert(kInitialXrp.drops() == 100'000'000'000'000'000); -static_assert(Number::kMaxRep >= kInitialXrp.drops()); +constexpr XRPAmount kINITIAL_XRP{100'000'000'000 * kDROPS_PER_XRP}; +static_assert(kINITIAL_XRP.drops() == 100'000'000'000'000'000); +static_assert(Number::kMAX_REP >= kINITIAL_XRP.drops()); /** Returns true if the amount does not exceed the initial XRP in existence. */ inline bool isLegalAmount(XRPAmount const& amount) { - return amount <= kInitialXrp; + return amount <= kINITIAL_XRP; } /** Returns true if the absolute value of the amount does not exceed the initial @@ -37,31 +37,31 @@ isLegalAmount(XRPAmount const& amount) inline bool isLegalAmountSigned(XRPAmount const& amount) { - return amount >= -kInitialXrp && amount <= kInitialXrp; + return amount >= -kINITIAL_XRP && amount <= kINITIAL_XRP; } /* The currency code for the native currency. */ static inline std::string const& systemCurrencyCode() { - static std::string const kCode = "XRP"; - return kCode; + static std::string const kCODE = "XRP"; + return kCODE; } /** The XRP ledger network's earliest allowed sequence */ -static constexpr std::uint32_t kXrpLedgerEarliestSeq{32570u}; +static constexpr std::uint32_t kXRP_LEDGER_EARLIEST_SEQ{32570u}; /** The XRP Ledger mainnet's earliest ledger with a FeeSettings object. Only * used in asserts and tests. */ -static constexpr std::uint32_t kXrpLedgerEarliestFees{562177u}; +static constexpr std::uint32_t kXRP_LEDGER_EARLIEST_FEES{562177u}; /** The minimum amount of support an amendment should have. */ -constexpr std::ratio<80, 100> kAmendmentMajorityCalcThreshold; +constexpr std::ratio<80, 100> kAMENDMENT_MAJORITY_CALC_THRESHOLD; /** The minimum amount of time an amendment must hold a majority */ -constexpr std::chrono::seconds const kDefaultAmendmentMajorityTime = weeks{2}; +constexpr std::chrono::seconds const kDEFAULT_AMENDMENT_MAJORITY_TIME = weeks{2}; } // namespace xrpl /** Default peer port (IANA registered) */ -inline constexpr std::uint16_t kDefaultPeerPort{2459}; +inline std::uint16_t constexpr kDEFAULT_PEER_PORT{2459}; diff --git a/include/xrpl/protocol/UintTypes.h b/include/xrpl/protocol/UintTypes.h index b38c544096..6fb0648b5f 100644 --- a/include/xrpl/protocol/UintTypes.h +++ b/include/xrpl/protocol/UintTypes.h @@ -30,21 +30,21 @@ public: /** Directory is an index into the directory of offer books. The last 64 bits of this are the quality. */ -using Directory = BaseUInt<256, detail::DirectoryTag>; +using Directory = BaseUint<256, detail::DirectoryTag>; /** Currency is a hash representing a specific currency. */ -using Currency = BaseUInt<160, detail::CurrencyTag>; +using Currency = BaseUint<160, detail::CurrencyTag>; /** NodeID is a 160-bit hash representing one node. */ -using NodeID = BaseUInt<160, detail::NodeIDTag>; +using NodeID = BaseUint<160, detail::NodeIDTag>; /** MPTID is a 192-bit value representing MPT Issuance ID, * which is a concatenation of a 32-bit sequence (big endian) * and a 160-bit account */ -using MPTID = BaseUInt<192>; +using MPTID = BaseUint<192>; /** Domain is a 256-bit hash representing a specific domain. */ -using Domain = BaseUInt<256>; +using Domain = BaseUint<256>; /** XRP currency. */ Currency const& @@ -62,7 +62,7 @@ badCurrency(); inline bool isXRP(Currency const& c) { - return c == beast::kZero; + return c == beast::kZERO; } /** Returns "", "XRP", or three letter ISO code. */ diff --git a/include/xrpl/protocol/Units.h b/include/xrpl/protocol/Units.h index 7fedc05a0d..dd5cfdeffd 100644 --- a/include/xrpl/protocol/Units.h +++ b/include/xrpl/protocol/Units.h @@ -300,13 +300,13 @@ public: using jsontype = std::conditional_t, json::Int, json::UInt>; - constexpr auto kMin = std::numeric_limits::min(); - constexpr auto kMax = std::numeric_limits::max(); + constexpr auto kMIN = std::numeric_limits::min(); + constexpr auto kMAX = std::numeric_limits::max(); - if (value_ < kMin) - return kMin; - if (value_ > kMax) - return kMax; + if (value_ < kMIN) + return kMIN; + if (value_ > kMAX) + return kMAX; return static_cast(value_); } else @@ -392,14 +392,14 @@ mulDivU(Source1 value, Dest mul, Source2 div) } using desttype = typename Dest::value_type; - constexpr auto kMax = std::numeric_limits::max(); + constexpr auto kMAX = std::numeric_limits::max(); // Shortcuts, since these happen a lot in the real world if (value == div) return mul; if (mul.value() == div.value()) { - if (value.value() > kMax) + if (value.value() > kMAX) return std::nullopt; return Dest{static_cast(value.value())}; } @@ -414,7 +414,7 @@ mulDivU(Source1 value, Dest mul, Source2 div) auto quotient = product / div.value(); - if (quotient > kMax) + if (quotient > kMAX) return std::nullopt; return Dest{static_cast(quotient)}; diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index 993f478b5e..d8a35a29e3 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -357,7 +357,7 @@ private: // Set a max number of allowed attestations to limit the amount of memory // allocated and processing time. This number is much larger than the actual // number of attestation a server would ever expect. - static constexpr std::uint32_t kMaxAttestations = 256; + static constexpr std::uint32_t kMAX_ATTESTATIONS = 256; AttCollection attestations_; protected: diff --git a/include/xrpl/protocol/XRPAmount.h b/include/xrpl/protocol/XRPAmount.h index f09ddc337a..067ea511da 100644 --- a/include/xrpl/protocol/XRPAmount.h +++ b/include/xrpl/protocol/XRPAmount.h @@ -202,13 +202,13 @@ public: std::is_signed_v && std::is_integral_v, "Expected XRPAmount to be a signed integral type"); - constexpr auto kMin = std::numeric_limits::min(); - constexpr auto kMax = std::numeric_limits::max(); + constexpr auto kMIN = std::numeric_limits::min(); + constexpr auto kMAX = std::numeric_limits::max(); - if (drops_ < kMin) - return kMin; - if (drops_ > kMax) - return kMax; + if (drops_ < kMIN) + return kMIN; + if (drops_ > kMAX) + return kMAX; return static_cast(drops_); } @@ -237,12 +237,12 @@ public: }; /** Number of drops per 1 XRP */ -constexpr XRPAmount kDropsPerXrp{1'000'000}; +constexpr XRPAmount kDROPS_PER_XRP{1'000'000}; constexpr double XRPAmount::decimalXRP() const { - return static_cast(drops_) / kDropsPerXrp.drops(); + return static_cast(drops_) / kDROPS_PER_XRP.drops(); } // Output XRPAmount as just the drops value. diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index 98a0b8dcd2..52045965fd 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -35,9 +35,9 @@ class STVar { private: // The largest "small object" we can accommodate - static constexpr std::size_t kMaxSize = 72; + static std::size_t constexpr kMAX_SIZE = 72; - std::aligned_storage::type d_ = {}; + std::aligned_storage::type d_ = {}; STBase* p_ = nullptr; public: @@ -51,12 +51,12 @@ public: STVar(STBase&& t) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) { - p_ = t.move(kMaxSize, &d_); + p_ = t.move(kMAX_SIZE, &d_); } STVar(STBase const& t) { - p_ = t.copy(kMaxSize, &d_); + p_ = t.copy(kMAX_SIZE, &d_); } STVar(DefaultObjectT, SField const& name); @@ -110,7 +110,7 @@ private: void construct(Args&&... args) { - if constexpr (sizeof(T) > kMaxSize) + if constexpr (sizeof(T) > kMAX_SIZE) { p_ = new T(std::forward(args)...); } diff --git a/include/xrpl/protocol/detail/b58_utils.h b/include/xrpl/protocol/detail/b58_utils.h index e800dbda06..f860dc40c4 100644 --- a/include/xrpl/protocol/detail/b58_utils.h +++ b/include/xrpl/protocol/detail/b58_utils.h @@ -155,16 +155,16 @@ inplaceBigintDivRem(std::span numerator, std::uint64_t divisor) [[nodiscard]] inline std::array b5810ToB58Be(std::uint64_t input) { - [[maybe_unused]] static constexpr std::uint64_t kB5810 = 430804206899405824; // 58^10; - XRPL_ASSERT(input < kB5810, "xrpl::b58_fast::detail::b5810ToB58Be : valid input"); - static constexpr std::size_t kResultSize = 10; - std::array result{}; + [[maybe_unused]] static constexpr std::uint64_t kB_58_10 = 430804206899405824; // 58^10; + XRPL_ASSERT(input < kB_58_10, "xrpl::b58_fast::detail::b5810ToB58Be : valid input"); + constexpr std::size_t kRESULT_SIZE = 10; + std::array result{}; int i = 0; while (input > 0) { std::uint64_t rem = 0; std::tie(input, rem) = divRem(input, 58); - result[kResultSize - 1 - i] = rem; + result[kRESULT_SIZE - 1 - i] = rem; i += 1; } diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index 43e0f2a2b8..2419cebea8 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -16,10 +16,11 @@ // Keep it sorted in reverse chronological order. XRPL_FEATURE(ConfidentialTransfer, Supported::No, VoteBehavior::DefaultNo) -XRPL_FIX (Cleanup3_2_0, Supported::Yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(MPTokensV2, Supported::No, VoteBehavior::DefaultNo) -XRPL_FIX (Cleanup3_1_3, Supported::Yes, VoteBehavior::DefaultYes) -XRPL_FIX (BatchInnerSigs, Supported::No, VoteBehavior::DefaultNo) +XRPL_FIX (Cleanup3_2_0, Supported::No, VoteBehavior::DefaultNo) +XRPL_FEATURE(MPTokensV2, Supported::No, VoteBehavior::DefaultNo) +XRPL_FIX (Security3_1_3, Supported::No, VoteBehavior::DefaultNo) +XRPL_FIX (PermissionedDomainInvariant, Supported::Yes, VoteBehavior::DefaultNo) +XRPL_FIX (BatchInnerSigs, Supported::No, VoteBehavior::DefaultNo) XRPL_FEATURE(LendingProtocol, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(PermissionDelegationV1_1, Supported::No, VoteBehavior::DefaultNo) XRPL_FIX (DirectoryLimit, Supported::Yes, VoteBehavior::DefaultNo) @@ -34,7 +35,7 @@ XRPL_FIX (EnforceNFTokenTrustlineV2, Supported::Yes, VoteBehavior::DefaultN XRPL_FIX (AMMv1_3, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(PermissionedDEX, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(Batch, Supported::No, VoteBehavior::DefaultNo) -XRPL_FEATURE(SingleAssetVault, Supported::Yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(SingleAssetVault, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (PayChanCancelAfter, Supported::Yes, VoteBehavior::DefaultNo) // Check flags in Credential transactions XRPL_FIX (InvalidTxFlags, Supported::Yes, VoteBehavior::DefaultNo) @@ -46,6 +47,9 @@ XRPL_FEATURE(Credentials, Supported::Yes, VoteBehavior::DefaultNo XRPL_FEATURE(AMMClawback, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (AMMv1_2, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(MPTokensV1, Supported::Yes, VoteBehavior::DefaultNo) +// InvariantsV1_1 will be changes to Supported::yes when all the +// invariants expected to be included under it are complete. +XRPL_FEATURE(InvariantsV1_1, Supported::No, VoteBehavior::DefaultNo) XRPL_FIX (NFTokenPageLinks, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (InnerObjTemplate2, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (EnforceNFTokenTrustline, Supported::Yes, VoteBehavior::DefaultNo) diff --git a/include/xrpl/protocol/detail/ledger_entries.macro b/include/xrpl/protocol/detail/ledger_entries.macro index 1e767461bf..e673411e32 100644 --- a/include/xrpl/protocol/detail/ledger_entries.macro +++ b/include/xrpl/protocol/detail/ledger_entries.macro @@ -84,7 +84,7 @@ LEDGER_ENTRY(ltNEGATIVE_UNL, 0x004e, NegativeUNL, nunl, ({ /** A ledger object which contains a list of NFTs - \sa keylet::nftpageMin, keylet::nftpageMax, keylet::nftpage + \sa keylet::nftpage_min, keylet::nftpage_max, keylet::nftpage */ LEDGER_ENTRY(ltNFTOKEN_PAGE, 0x0050, NFTokenPage, nft_page, ({ {sfPreviousPageMin, SoeOptional}, @@ -112,7 +112,7 @@ LEDGER_ENTRY(ltSIGNER_LIST, 0x0053, SignerList, signer_list, ({ /** A ledger object which describes a ticket. - \sa keylet::kTicket + \sa keylet::ticket */ LEDGER_ENTRY(ltTICKET, 0x0054, Ticket, ticket, ({ {sfAccount, SoeRequired}, @@ -405,11 +405,10 @@ LEDGER_ENTRY( {sfPreviousTxnLgrSeq, SoeRequired}, {sfDomainID, SoeOptional}, {sfMutableFlags, SoeDefault}, - {sfReferenceHolding, SoeOptional}, {sfIssuerEncryptionKey, SoeOptional}, {sfAuditorEncryptionKey, SoeOptional}, {sfConfidentialOutstandingAmount, SoeDefault}, - })) +})) /** A ledger object which tracks MPToken \sa keylet::mptoken @@ -606,7 +605,7 @@ LEDGER_ENTRY(ltLOAN, 0x0089, Loan, loan, ({ // LoanBroker.ManagementFeeRate // The unrounded true total fee still owed to the broker. // - // Note the "True" values may differ significantly from the tracked + // Note the the "True" values may differ significantly from the tracked // rounded values. {sfPaymentRemaining, SoeDefault}, {sfPeriodicPayment, SoeRequired}, diff --git a/include/xrpl/protocol/detail/sfields.macro b/include/xrpl/protocol/detail/sfields.macro index 146a5a09e6..fbb1d4ba67 100644 --- a/include/xrpl/protocol/detail/sfields.macro +++ b/include/xrpl/protocol/detail/sfields.macro @@ -27,7 +27,7 @@ TYPED_SFIELD(sfWasLockingChainSend, UINT8, 19) TYPED_SFIELD(sfWithdrawalPolicy, UINT8, 20) // 16-bit integers (common) -TYPED_SFIELD(sfLedgerEntryType, UINT16, 1, SField::kSmdNever) +TYPED_SFIELD(sfLedgerEntryType, UINT16, 1, SField::SMdNever) TYPED_SFIELD(sfTransactionType, UINT16, 2) TYPED_SFIELD(sfSignerWeight, UINT16, 3) TYPED_SFIELD(sfTransferFee, UINT16, 4) @@ -48,7 +48,7 @@ TYPED_SFIELD(sfNetworkID, UINT32, 1) TYPED_SFIELD(sfFlags, UINT32, 2) TYPED_SFIELD(sfSourceTag, UINT32, 3) TYPED_SFIELD(sfSequence, UINT32, 4) -TYPED_SFIELD(sfPreviousTxnLgrSeq, UINT32, 5, SField::kSmdDeleteFinal) +TYPED_SFIELD(sfPreviousTxnLgrSeq, UINT32, 5, SField::SMdDeleteFinal) TYPED_SFIELD(sfLedgerSequence, UINT32, 6) TYPED_SFIELD(sfCloseTime, UINT32, 7) TYPED_SFIELD(sfParentCloseTime, UINT32, 8) @@ -139,15 +139,15 @@ TYPED_SFIELD(sfXChainClaimID, UINT64, 20) TYPED_SFIELD(sfXChainAccountCreateCount, UINT64, 21) TYPED_SFIELD(sfXChainAccountClaimCount, UINT64, 22) TYPED_SFIELD(sfAssetPrice, UINT64, 23) -TYPED_SFIELD(sfMaximumAmount, UINT64, 24, SField::kSmdBaseTen|SField::kSmdDefault) -TYPED_SFIELD(sfOutstandingAmount, UINT64, 25, SField::kSmdBaseTen|SField::kSmdDefault) -TYPED_SFIELD(sfMPTAmount, UINT64, 26, SField::kSmdBaseTen|SField::kSmdDefault) +TYPED_SFIELD(sfMaximumAmount, UINT64, 24, SField::SMdBaseTen|SField::SMdDefault) +TYPED_SFIELD(sfOutstandingAmount, UINT64, 25, SField::SMdBaseTen|SField::SMdDefault) +TYPED_SFIELD(sfMPTAmount, UINT64, 26, SField::SMdBaseTen|SField::SMdDefault) TYPED_SFIELD(sfIssuerNode, UINT64, 27) TYPED_SFIELD(sfSubjectNode, UINT64, 28) -TYPED_SFIELD(sfLockedAmount, UINT64, 29, SField::kSmdBaseTen|SField::kSmdDefault) +TYPED_SFIELD(sfLockedAmount, UINT64, 29, SField::SMdBaseTen|SField::SMdDefault) TYPED_SFIELD(sfVaultNode, UINT64, 30) TYPED_SFIELD(sfLoanBrokerNode, UINT64, 31) -TYPED_SFIELD(sfConfidentialOutstandingAmount, UINT64, 32, SField::kSmdBaseTen|SField::kSmdDefault) +TYPED_SFIELD(sfConfidentialOutstandingAmount, UINT64, 32, SField::SMdBaseTen|SField::SMdDefault) // 128-bit TYPED_SFIELD(sfEmailHash, UINT128, 1) @@ -169,17 +169,17 @@ TYPED_SFIELD(sfLedgerHash, UINT256, 1) TYPED_SFIELD(sfParentHash, UINT256, 2) TYPED_SFIELD(sfTransactionHash, UINT256, 3) TYPED_SFIELD(sfAccountHash, UINT256, 4) -TYPED_SFIELD(sfPreviousTxnID, UINT256, 5, SField::kSmdDeleteFinal) +TYPED_SFIELD(sfPreviousTxnID, UINT256, 5, SField::SMdDeleteFinal) TYPED_SFIELD(sfLedgerIndex, UINT256, 6) TYPED_SFIELD(sfWalletLocator, UINT256, 7) -TYPED_SFIELD(sfRootIndex, UINT256, 8, SField::kSmdAlways) +TYPED_SFIELD(sfRootIndex, UINT256, 8, SField::SMdAlways) TYPED_SFIELD(sfAccountTxnID, UINT256, 9) TYPED_SFIELD(sfNFTokenID, UINT256, 10) TYPED_SFIELD(sfEmitParentTxnID, UINT256, 11) TYPED_SFIELD(sfEmitNonce, UINT256, 12) TYPED_SFIELD(sfEmitHookHash, UINT256, 13) TYPED_SFIELD(sfAMMID, UINT256, 14, - SField::kSmdPseudoAccount | SField::kSmdDefault) + SField::SMdPseudoAccount | SField::SMdDefault) // 256-bit (uncommon) TYPED_SFIELD(sfBookDirectory, UINT256, 16) @@ -202,32 +202,31 @@ TYPED_SFIELD(sfHookNamespace, UINT256, 32) TYPED_SFIELD(sfHookSetTxnID, UINT256, 33) TYPED_SFIELD(sfDomainID, UINT256, 34) TYPED_SFIELD(sfVaultID, UINT256, 35, - SField::kSmdPseudoAccount | SField::kSmdDefault) + SField::SMdPseudoAccount | SField::SMdDefault) TYPED_SFIELD(sfParentBatchID, UINT256, 36) TYPED_SFIELD(sfLoanBrokerID, UINT256, 37, - SField::kSmdPseudoAccount | SField::kSmdDefault) + SField::SMdPseudoAccount | SField::SMdDefault) TYPED_SFIELD(sfLoanID, UINT256, 38) -TYPED_SFIELD(sfReferenceHolding, UINT256, 39) -TYPED_SFIELD(sfBlindingFactor, UINT256, 40) +TYPED_SFIELD(sfBlindingFactor, UINT256, 39) // number (common) TYPED_SFIELD(sfNumber, NUMBER, 1) -TYPED_SFIELD(sfAssetsAvailable, NUMBER, 2, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfAssetsMaximum, NUMBER, 3, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfAssetsTotal, NUMBER, 4, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfLossUnrealized, NUMBER, 5, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfDebtTotal, NUMBER, 6, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfDebtMaximum, NUMBER, 7, SField::kSmdNeedsAsset | SField::kSmdDefault) -TYPED_SFIELD(sfCoverAvailable, NUMBER, 8, SField::kSmdNeedsAsset | SField::kSmdDefault) +TYPED_SFIELD(sfAssetsAvailable, NUMBER, 2, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfAssetsMaximum, NUMBER, 3, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfAssetsTotal, NUMBER, 4, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfLossUnrealized, NUMBER, 5, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfDebtTotal, NUMBER, 6, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfDebtMaximum, NUMBER, 7, SField::SMdNeedsAsset | SField::SMdDefault) +TYPED_SFIELD(sfCoverAvailable, NUMBER, 8, SField::SMdNeedsAsset | SField::SMdDefault) TYPED_SFIELD(sfLoanOriginationFee, NUMBER, 9) TYPED_SFIELD(sfLoanServiceFee, NUMBER, 10) TYPED_SFIELD(sfLatePaymentFee, NUMBER, 11) TYPED_SFIELD(sfClosePaymentFee, NUMBER, 12) -TYPED_SFIELD(sfPrincipalOutstanding, NUMBER, 13, SField::kSmdNeedsAsset | SField::kSmdDefault) +TYPED_SFIELD(sfPrincipalOutstanding, NUMBER, 13, SField::SMdNeedsAsset | SField::SMdDefault) TYPED_SFIELD(sfPrincipalRequested, NUMBER, 14) -TYPED_SFIELD(sfTotalValueOutstanding, NUMBER, 15, SField::kSmdNeedsAsset | SField::kSmdDefault) +TYPED_SFIELD(sfTotalValueOutstanding, NUMBER, 15, SField::SMdNeedsAsset | SField::SMdDefault) TYPED_SFIELD(sfPeriodicPayment, NUMBER, 16) -TYPED_SFIELD(sfManagementFeeOutstanding, NUMBER, 17, SField::kSmdNeedsAsset | SField::kSmdDefault) +TYPED_SFIELD(sfManagementFeeOutstanding, NUMBER, 17, SField::SMdNeedsAsset | SField::SMdDefault) // int32 TYPED_SFIELD(sfLoanScale, INT32, 1) @@ -273,9 +272,9 @@ TYPED_SFIELD(sfLPTokenBalance, AMOUNT, 31) TYPED_SFIELD(sfPublicKey, VL, 1) TYPED_SFIELD(sfMessageKey, VL, 2) TYPED_SFIELD(sfSigningPubKey, VL, 3) -TYPED_SFIELD(sfTxnSignature, VL, 4, SField::kSmdDefault, SField::kNotSigning) +TYPED_SFIELD(sfTxnSignature, VL, 4, SField::SMdDefault, SField::kNOT_SIGNING) TYPED_SFIELD(sfURI, VL, 5) -TYPED_SFIELD(sfSignature, VL, 6, SField::kSmdDefault, SField::kNotSigning) +TYPED_SFIELD(sfSignature, VL, 6, SField::SMdDefault, SField::kNOT_SIGNING) TYPED_SFIELD(sfDomain, VL, 7) TYPED_SFIELD(sfFundCode, VL, 8) TYPED_SFIELD(sfRemoveCode, VL, 9) @@ -288,7 +287,7 @@ TYPED_SFIELD(sfMemoFormat, VL, 14) // variable length (uncommon) TYPED_SFIELD(sfFulfillment, VL, 16) TYPED_SFIELD(sfCondition, VL, 17) -TYPED_SFIELD(sfMasterSignature, VL, 18, SField::kSmdDefault, SField::kNotSigning) +TYPED_SFIELD(sfMasterSignature, VL, 18, SField::SMdDefault, SField::kNOT_SIGNING) TYPED_SFIELD(sfUNLModifyValidator, VL, 19) TYPED_SFIELD(sfValidatorToDisable, VL, 20) TYPED_SFIELD(sfValidatorToReEnable, VL, 21) @@ -345,7 +344,7 @@ TYPED_SFIELD(sfBorrower, ACCOUNT, 25) TYPED_SFIELD(sfCounterparty, ACCOUNT, 26) // vector of 256-bit -TYPED_SFIELD(sfIndexes, VECTOR256, 1, SField::kSmdNever) +TYPED_SFIELD(sfIndexes, VECTOR256, 1, SField::SMdNever) TYPED_SFIELD(sfHashes, VECTOR256, 2) TYPED_SFIELD(sfAmendments, VECTOR256, 3) TYPED_SFIELD(sfNFTokenOffers, VECTOR256, 4) @@ -406,13 +405,13 @@ UNTYPED_SFIELD(sfCredential, OBJECT, 33) UNTYPED_SFIELD(sfRawTransaction, OBJECT, 34) UNTYPED_SFIELD(sfBatchSigner, OBJECT, 35) UNTYPED_SFIELD(sfBook, OBJECT, 36) -UNTYPED_SFIELD(sfCounterpartySignature, OBJECT, 37, SField::kSmdDefault, SField::kNotSigning) +UNTYPED_SFIELD(sfCounterpartySignature, OBJECT, 37, SField::SMdDefault, SField::kNOT_SIGNING) // array of objects (common) // ARRAY/1 is reserved for end of array // sfSigningAccounts has never been used. //UNTYPED_SFIELD(sfSigningAccounts, ARRAY, 2) -UNTYPED_SFIELD(sfSigners, ARRAY, 3, SField::kSmdDefault, SField::kNotSigning) +UNTYPED_SFIELD(sfSigners, ARRAY, 3, SField::SMdDefault, SField::kNOT_SIGNING) UNTYPED_SFIELD(sfSignerEntries, ARRAY, 4) UNTYPED_SFIELD(sfTemplate, ARRAY, 5) UNTYPED_SFIELD(sfNecessary, ARRAY, 6) @@ -440,4 +439,4 @@ UNTYPED_SFIELD(sfUnauthorizeCredentials, ARRAY, 27) UNTYPED_SFIELD(sfAcceptedCredentials, ARRAY, 28) UNTYPED_SFIELD(sfPermissions, ARRAY, 29) UNTYPED_SFIELD(sfRawTransactions, ARRAY, 30) -UNTYPED_SFIELD(sfBatchSigners, ARRAY, 31, SField::kSmdDefault, SField::kNotSigning) +UNTYPED_SFIELD(sfBatchSigners, ARRAY, 31, SField::SMdDefault, SField::kNOT_SIGNING) diff --git a/include/xrpl/protocol/detail/transactions.macro b/include/xrpl/protocol/detail/transactions.macro index 143bc91fdd..39be1057e5 100644 --- a/include/xrpl/protocol/detail/transactions.macro +++ b/include/xrpl/protocol/detail/transactions.macro @@ -688,7 +688,6 @@ TRANSACTION(ttLEDGER_STATE_FIX, 53, LedgerStateFix, ({ {sfLedgerFixType, SoeRequired}, {sfOwner, SoeOptional}, - {sfBookDirectory, SoeOptional}, })) /** This transaction type creates a MPTokensIssuance instance */ diff --git a/include/xrpl/protocol/digest.h b/include/xrpl/protocol/digest.h index 50bf2735fb..6564237771 100644 --- a/include/xrpl/protocol/digest.h +++ b/include/xrpl/protocol/digest.h @@ -27,7 +27,7 @@ namespace xrpl { struct OpensslRipemd160Hasher { public: - static constexpr auto kEndian = boost::endian::order::native; + static constexpr auto const kENDIAN = boost::endian::order::native; using result_type = std::array; @@ -50,7 +50,7 @@ private: struct OpensslSha512Hasher { public: - static constexpr auto kEndian = boost::endian::order::native; + static constexpr auto const kENDIAN = boost::endian::order::native; using result_type = std::array; @@ -73,7 +73,7 @@ private: struct OpensslSha256Hasher { public: - static constexpr auto kEndian = boost::endian::order::native; + static constexpr auto const kENDIAN = boost::endian::order::native; using result_type = std::array; @@ -118,7 +118,7 @@ private: sha256_hasher h_; public: - static constexpr auto kEndian = boost::endian::order::native; + static constexpr auto const kENDIAN = boost::endian::order::native; using result_type = std::array; @@ -154,7 +154,7 @@ private: sha512_hasher h_; public: - static constexpr auto kEndian = boost::endian::order::big; + static constexpr auto const kENDIAN = boost::endian::order::big; using result_type = uint256; diff --git a/include/xrpl/protocol/nft.h b/include/xrpl/protocol/nft.h index 1e79b3f285..ce73e244c1 100644 --- a/include/xrpl/protocol/nft.h +++ b/include/xrpl/protocol/nft.h @@ -29,11 +29,11 @@ toUInt32(Taxon t) return static_cast(t); } -constexpr std::uint16_t const kFlagBurnable = 0x0001; -constexpr std::uint16_t const kFlagOnlyXrp = 0x0002; -constexpr std::uint16_t const kFlagCreateTrustLines = 0x0004; -constexpr std::uint16_t const kFlagTransferable = 0x0008; -constexpr std::uint16_t const kFlagMutable = 0x0010; +constexpr std::uint16_t const kFLAG_BURNABLE = 0x0001; +constexpr std::uint16_t const kFLAG_ONLY_XRP = 0x0002; +constexpr std::uint16_t const kFLAG_CREATE_TRUST_LINES = 0x0004; +constexpr std::uint16_t const kFLAG_TRANSFERABLE = 0x0008; +constexpr std::uint16_t const kFLAG_MUTABLE = 0x0010; inline std::uint16_t getFlags(uint256 const& id) diff --git a/include/xrpl/protocol/nftPageMask.h b/include/xrpl/protocol/nftPageMask.h index 827df34cf3..d679c319fa 100644 --- a/include/xrpl/protocol/nftPageMask.h +++ b/include/xrpl/protocol/nftPageMask.h @@ -8,7 +8,7 @@ namespace xrpl::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. -constexpr uint256 kPageMask( +uint256 constexpr kPAGE_MASK( std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff")); } // namespace xrpl::nft diff --git a/include/xrpl/protocol_autogen/LedgerEntryBase.h b/include/xrpl/protocol_autogen/LedgerEntryBase.h index 5758adbb24..ad513992c7 100644 --- a/include/xrpl/protocol_autogen/LedgerEntryBase.h +++ b/include/xrpl/protocol_autogen/LedgerEntryBase.h @@ -27,7 +27,7 @@ public: * @brief Construct a ledger entry wrapper from an existing SLE object. * @param sle The underlying serialized ledger entry to wrap */ - explicit LedgerEntryBase(SLE::const_pointer sle) : sle_(std::move(sle)) + explicit LedgerEntryBase(std::shared_ptr sle) : sle_(std::move(sle)) { } @@ -151,7 +151,7 @@ public: * @return A constant reference to the underlying SLE object */ [[nodiscard]] - SLE::const_pointer + std::shared_ptr getSle() const { return sle_; @@ -159,7 +159,7 @@ public: protected: /** @brief The underlying serialized ledger entry being wrapped. */ - SLE::const_pointer sle_; + std::shared_ptr sle_; }; } // namespace xrpl::ledger_entries diff --git a/include/xrpl/protocol_autogen/README.md b/include/xrpl/protocol_autogen/README.md index 608ffed085..860ed1a242 100644 --- a/include/xrpl/protocol_autogen/README.md +++ b/include/xrpl/protocol_autogen/README.md @@ -15,8 +15,8 @@ Generation requires a one-time setup step to create a virtual environment and install Python dependencies, followed by running the generation target: ```bash -cmake --build . --target setup_code_gen # create venv and install dependencies (once) -cmake --build . --target code_gen # generate code +cmake --build . --target setup_code_gen # create venv and install dependencies (once) +cmake --build . --target code_gen # generate code ``` By default, `CODEGEN_VENV_DIR` points to `.venv` in the project root. The diff --git a/include/xrpl/protocol_autogen/ledger_entries/AMM.h b/include/xrpl/protocol_autogen/ledger_entries/AMM.h index 11fd3738c9..529e3f4df7 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/AMM.h +++ b/include/xrpl/protocol_autogen/ledger_entries/AMM.h @@ -33,7 +33,7 @@ public: * @brief Construct a AMM ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit AMM(SLE::const_pointer sle) + explicit AMM(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -256,7 +256,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - AMMBuilder(SLE::const_pointer sle) + AMMBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltAMM) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/AccountRoot.h b/include/xrpl/protocol_autogen/ledger_entries/AccountRoot.h index f9a12a027f..e20259330d 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/AccountRoot.h +++ b/include/xrpl/protocol_autogen/ledger_entries/AccountRoot.h @@ -33,7 +33,7 @@ public: * @brief Construct a AccountRoot ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit AccountRoot(SLE::const_pointer sle) + explicit AccountRoot(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -555,7 +555,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - AccountRootBuilder(SLE::const_pointer sle) + AccountRootBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltACCOUNT_ROOT) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Amendments.h b/include/xrpl/protocol_autogen/ledger_entries/Amendments.h index 6a801308ca..4f1b316b99 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Amendments.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Amendments.h @@ -33,7 +33,7 @@ public: * @brief Construct a Amendments ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Amendments(SLE::const_pointer sle) + explicit Amendments(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -166,7 +166,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - AmendmentsBuilder(SLE::const_pointer sle) + AmendmentsBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltAMENDMENTS) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Bridge.h b/include/xrpl/protocol_autogen/ledger_entries/Bridge.h index 2c7479b243..fd7df1977f 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Bridge.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Bridge.h @@ -33,7 +33,7 @@ public: * @brief Construct a Bridge ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Bridge(SLE::const_pointer sle) + explicit Bridge(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -210,7 +210,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - BridgeBuilder(SLE::const_pointer sle) + BridgeBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltBRIDGE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Check.h b/include/xrpl/protocol_autogen/ledger_entries/Check.h index 5b3fd10b92..750270cad9 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Check.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Check.h @@ -33,7 +33,7 @@ public: * @brief Construct a Check ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Check(SLE::const_pointer sle) + explicit Check(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -269,7 +269,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - CheckBuilder(SLE::const_pointer sle) + CheckBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltCHECK) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Credential.h b/include/xrpl/protocol_autogen/ledger_entries/Credential.h index dfce76e45c..5433f00b33 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Credential.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Credential.h @@ -33,7 +33,7 @@ public: * @brief Construct a Credential ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Credential(SLE::const_pointer sle) + explicit Credential(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -219,7 +219,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - CredentialBuilder(SLE::const_pointer sle) + CredentialBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltCREDENTIAL) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/DID.h b/include/xrpl/protocol_autogen/ledger_entries/DID.h index ad423377e7..2f57961be4 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/DID.h +++ b/include/xrpl/protocol_autogen/ledger_entries/DID.h @@ -33,7 +33,7 @@ public: * @brief Construct a DID ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit DID(SLE::const_pointer sle) + explicit DID(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -193,7 +193,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - DIDBuilder(SLE::const_pointer sle) + DIDBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltDID) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Delegate.h b/include/xrpl/protocol_autogen/ledger_entries/Delegate.h index bfe5f5587a..7458b8103a 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Delegate.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Delegate.h @@ -33,7 +33,7 @@ public: * @brief Construct a Delegate ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Delegate(SLE::const_pointer sle) + explicit Delegate(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -172,7 +172,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - DelegateBuilder(SLE::const_pointer sle) + DelegateBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltDELEGATE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/DepositPreauth.h b/include/xrpl/protocol_autogen/ledger_entries/DepositPreauth.h index 069bed6b77..42b430a665 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/DepositPreauth.h +++ b/include/xrpl/protocol_autogen/ledger_entries/DepositPreauth.h @@ -33,7 +33,7 @@ public: * @brief Construct a DepositPreauth ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit DepositPreauth(SLE::const_pointer sle) + explicit DepositPreauth(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -170,7 +170,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - DepositPreauthBuilder(SLE::const_pointer sle) + DepositPreauthBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltDEPOSIT_PREAUTH) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h b/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h index 50659c33f6..e47cb98a26 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h +++ b/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h @@ -33,7 +33,7 @@ public: * @brief Construct a DirectoryNode ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit DirectoryNode(SLE::const_pointer sle) + explicit DirectoryNode(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -431,7 +431,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - DirectoryNodeBuilder(SLE::const_pointer sle) + DirectoryNodeBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltDIR_NODE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Escrow.h b/include/xrpl/protocol_autogen/ledger_entries/Escrow.h index f3c033d26d..ae8219a4f0 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Escrow.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Escrow.h @@ -33,7 +33,7 @@ public: * @brief Construct a Escrow ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Escrow(SLE::const_pointer sle) + explicit Escrow(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -363,7 +363,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - EscrowBuilder(SLE::const_pointer sle) + EscrowBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltESCROW) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/FeeSettings.h b/include/xrpl/protocol_autogen/ledger_entries/FeeSettings.h index 8f43d3b782..cfd7a591e8 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/FeeSettings.h +++ b/include/xrpl/protocol_autogen/ledger_entries/FeeSettings.h @@ -33,7 +33,7 @@ public: * @brief Construct a FeeSettings ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit FeeSettings(SLE::const_pointer sle) + explicit FeeSettings(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -285,7 +285,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - FeeSettingsBuilder(SLE::const_pointer sle) + FeeSettingsBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltFEE_SETTINGS) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/LedgerHashes.h b/include/xrpl/protocol_autogen/ledger_entries/LedgerHashes.h index f1d3684b55..8c082be685 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/LedgerHashes.h +++ b/include/xrpl/protocol_autogen/ledger_entries/LedgerHashes.h @@ -33,7 +33,7 @@ public: * @brief Construct a LedgerHashes ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit LedgerHashes(SLE::const_pointer sle) + explicit LedgerHashes(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -130,7 +130,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - LedgerHashesBuilder(SLE::const_pointer sle) + LedgerHashesBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltLEDGER_HASHES) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Loan.h b/include/xrpl/protocol_autogen/ledger_entries/Loan.h index 5d837736ec..4408c278db 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Loan.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Loan.h @@ -33,7 +33,7 @@ public: * @brief Construct a Loan ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Loan(SLE::const_pointer sle) + explicit Loan(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -607,7 +607,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - LoanBuilder(SLE::const_pointer sle) + LoanBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltLOAN) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/LoanBroker.h b/include/xrpl/protocol_autogen/ledger_entries/LoanBroker.h index 88f05e3433..b1c6dd8a54 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/LoanBroker.h +++ b/include/xrpl/protocol_autogen/ledger_entries/LoanBroker.h @@ -33,7 +33,7 @@ public: * @brief Construct a LoanBroker ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit LoanBroker(SLE::const_pointer sle) + explicit LoanBroker(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -378,7 +378,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - LoanBrokerBuilder(SLE::const_pointer sle) + LoanBrokerBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltLOAN_BROKER) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/MPToken.h b/include/xrpl/protocol_autogen/ledger_entries/MPToken.h index 379cfe53f5..03db1cd6e9 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/MPToken.h +++ b/include/xrpl/protocol_autogen/ledger_entries/MPToken.h @@ -33,7 +33,7 @@ public: * @brief Construct a MPToken ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit MPToken(SLE::const_pointer sle) + explicit MPToken(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -326,7 +326,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - MPTokenBuilder(SLE::const_pointer sle) + MPTokenBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltMPTOKEN) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h b/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h index b6c77093ac..5b26d13a83 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h +++ b/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h @@ -33,7 +33,7 @@ public: * @brief Construct a MPTokenIssuance ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit MPTokenIssuance(SLE::const_pointer sle) + explicit MPTokenIssuance(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -279,30 +279,6 @@ public: return this->sle_->isFieldPresent(sfMutableFlags); } - /** - * @brief Get sfReferenceHolding (SoeOptional) - * @return The field value, or std::nullopt if not present. - */ - [[nodiscard]] - protocol_autogen::Optional - getReferenceHolding() const - { - if (hasReferenceHolding()) - return this->sle_->at(sfReferenceHolding); - return std::nullopt; - } - - /** - * @brief Check if sfReferenceHolding is present. - * @return True if the field is present, false otherwise. - */ - [[nodiscard]] - bool - hasReferenceHolding() const - { - return this->sle_->isFieldPresent(sfReferenceHolding); - } - /** * @brief Get sfIssuerEncryptionKey (SoeOptional) * @return The field value, or std::nullopt if not present. @@ -411,7 +387,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - MPTokenIssuanceBuilder(SLE::const_pointer sle) + MPTokenIssuanceBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltMPTOKEN_ISSUANCE) { @@ -565,17 +541,6 @@ public: return *this; } - /** - * @brief Set sfReferenceHolding (SoeOptional) - * @return Reference to this builder for method chaining. - */ - MPTokenIssuanceBuilder& - setReferenceHolding(std::decay_t const& value) - { - object_[sfReferenceHolding] = value; - return *this; - } - /** * @brief Set sfIssuerEncryptionKey (SoeOptional) * @return Reference to this builder for method chaining. diff --git a/include/xrpl/protocol_autogen/ledger_entries/NFTokenOffer.h b/include/xrpl/protocol_autogen/ledger_entries/NFTokenOffer.h index 072d3721f9..c0a6ee6cbc 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/NFTokenOffer.h +++ b/include/xrpl/protocol_autogen/ledger_entries/NFTokenOffer.h @@ -33,7 +33,7 @@ public: * @brief Construct a NFTokenOffer ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit NFTokenOffer(SLE::const_pointer sle) + explicit NFTokenOffer(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -208,7 +208,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - NFTokenOfferBuilder(SLE::const_pointer sle) + NFTokenOfferBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltNFTOKEN_OFFER) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/NFTokenPage.h b/include/xrpl/protocol_autogen/ledger_entries/NFTokenPage.h index 5e00cb1120..c4190f9068 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/NFTokenPage.h +++ b/include/xrpl/protocol_autogen/ledger_entries/NFTokenPage.h @@ -33,7 +33,7 @@ public: * @brief Construct a NFTokenPage ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit NFTokenPage(SLE::const_pointer sle) + explicit NFTokenPage(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -157,7 +157,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - NFTokenPageBuilder(SLE::const_pointer sle) + NFTokenPageBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltNFTOKEN_PAGE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/NegativeUNL.h b/include/xrpl/protocol_autogen/ledger_entries/NegativeUNL.h index 7ca9729082..b09135e5f8 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/NegativeUNL.h +++ b/include/xrpl/protocol_autogen/ledger_entries/NegativeUNL.h @@ -33,7 +33,7 @@ public: * @brief Construct a NegativeUNL ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit NegativeUNL(SLE::const_pointer sle) + explicit NegativeUNL(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -190,7 +190,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - NegativeUNLBuilder(SLE::const_pointer sle) + NegativeUNLBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltNEGATIVE_UNL) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Offer.h b/include/xrpl/protocol_autogen/ledger_entries/Offer.h index f51b54cfd2..a6d427cbbd 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Offer.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Offer.h @@ -33,7 +33,7 @@ public: * @brief Construct a Offer ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Offer(SLE::const_pointer sle) + explicit Offer(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -259,7 +259,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - OfferBuilder(SLE::const_pointer sle) + OfferBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltOFFER) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Oracle.h b/include/xrpl/protocol_autogen/ledger_entries/Oracle.h index 902032f94f..31735a713c 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Oracle.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Oracle.h @@ -33,7 +33,7 @@ public: * @brief Construct a Oracle ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Oracle(SLE::const_pointer sle) + explicit Oracle(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -222,7 +222,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - OracleBuilder(SLE::const_pointer sle) + OracleBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltORACLE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/PayChannel.h b/include/xrpl/protocol_autogen/ledger_entries/PayChannel.h index 61a4e2d044..097f287425 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/PayChannel.h +++ b/include/xrpl/protocol_autogen/ledger_entries/PayChannel.h @@ -33,7 +33,7 @@ public: * @brief Construct a PayChannel ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit PayChannel(SLE::const_pointer sle) + explicit PayChannel(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -330,7 +330,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - PayChannelBuilder(SLE::const_pointer sle) + PayChannelBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltPAYCHAN) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/PermissionedDomain.h b/include/xrpl/protocol_autogen/ledger_entries/PermissionedDomain.h index 638dda2420..cc5a1649ef 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/PermissionedDomain.h +++ b/include/xrpl/protocol_autogen/ledger_entries/PermissionedDomain.h @@ -33,7 +33,7 @@ public: * @brief Construct a PermissionedDomain ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit PermissionedDomain(SLE::const_pointer sle) + explicit PermissionedDomain(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -148,7 +148,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - PermissionedDomainBuilder(SLE::const_pointer sle) + PermissionedDomainBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltPERMISSIONED_DOMAIN) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/RippleState.h b/include/xrpl/protocol_autogen/ledger_entries/RippleState.h index e8debfe792..cb221bb2ad 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/RippleState.h +++ b/include/xrpl/protocol_autogen/ledger_entries/RippleState.h @@ -33,7 +33,7 @@ public: * @brief Construct a RippleState ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit RippleState(SLE::const_pointer sle) + explicit RippleState(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -278,7 +278,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - RippleStateBuilder(SLE::const_pointer sle) + RippleStateBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltRIPPLE_STATE) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/SignerList.h b/include/xrpl/protocol_autogen/ledger_entries/SignerList.h index 443e5588f9..dfc7eb4506 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/SignerList.h +++ b/include/xrpl/protocol_autogen/ledger_entries/SignerList.h @@ -33,7 +33,7 @@ public: * @brief Construct a SignerList ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit SignerList(SLE::const_pointer sle) + explicit SignerList(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -172,7 +172,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - SignerListBuilder(SLE::const_pointer sle) + SignerListBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltSIGNER_LIST) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Ticket.h b/include/xrpl/protocol_autogen/ledger_entries/Ticket.h index 6fa5b57f6c..ceadd70765 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Ticket.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Ticket.h @@ -33,7 +33,7 @@ public: * @brief Construct a Ticket ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Ticket(SLE::const_pointer sle) + explicit Ticket(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -134,7 +134,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - TicketBuilder(SLE::const_pointer sle) + TicketBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltTICKET) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/Vault.h b/include/xrpl/protocol_autogen/ledger_entries/Vault.h index d1aaeb4ed8..168894d8d2 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/Vault.h +++ b/include/xrpl/protocol_autogen/ledger_entries/Vault.h @@ -33,7 +33,7 @@ public: * @brief Construct a Vault ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit Vault(SLE::const_pointer sle) + explicit Vault(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -330,7 +330,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - VaultBuilder(SLE::const_pointer sle) + VaultBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltVAULT) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedClaimID.h b/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedClaimID.h index 3f8058a4a1..4a3e9c9103 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedClaimID.h +++ b/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedClaimID.h @@ -33,7 +33,7 @@ public: * @brief Construct a XChainOwnedClaimID ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit XChainOwnedClaimID(SLE::const_pointer sle) + explicit XChainOwnedClaimID(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -187,7 +187,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - XChainOwnedClaimIDBuilder(SLE::const_pointer sle) + XChainOwnedClaimIDBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltXCHAIN_OWNED_CLAIM_ID) { diff --git a/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedCreateAccountClaimID.h b/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedCreateAccountClaimID.h index e24009a4b7..542de104ea 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedCreateAccountClaimID.h +++ b/include/xrpl/protocol_autogen/ledger_entries/XChainOwnedCreateAccountClaimID.h @@ -33,7 +33,7 @@ public: * @brief Construct a XChainOwnedCreateAccountClaimID ledger entry wrapper from an existing SLE object. * @throws std::runtime_error if the ledger entry type doesn't match. */ - explicit XChainOwnedCreateAccountClaimID(SLE::const_pointer sle) + explicit XChainOwnedCreateAccountClaimID(std::shared_ptr sle) : LedgerEntryBase(std::move(sle)) { // Verify ledger entry type @@ -161,7 +161,7 @@ public: * @param sle The existing ledger entry to copy from. * @throws std::runtime_error if the ledger entry type doesn't match. */ - XChainOwnedCreateAccountClaimIDBuilder(SLE::const_pointer sle) + XChainOwnedCreateAccountClaimIDBuilder(std::shared_ptr sle) { if (sle->at(sfLedgerEntryType) != ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID) { diff --git a/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h b/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h index 52723ad5eb..3c58815a02 100644 --- a/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h +++ b/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h @@ -83,32 +83,6 @@ public: { return this->tx_->isFieldPresent(sfOwner); } - - /** - * @brief Get sfBookDirectory (SoeOptional) - * @return The field value, or std::nullopt if not present. - */ - [[nodiscard]] - protocol_autogen::Optional - getBookDirectory() const - { - if (hasBookDirectory()) - { - return this->tx_->at(sfBookDirectory); - } - return std::nullopt; - } - - /** - * @brief Check if sfBookDirectory is present. - * @return True if the field is present, false otherwise. - */ - [[nodiscard]] - bool - hasBookDirectory() const - { - return this->tx_->isFieldPresent(sfBookDirectory); - } }; /** @@ -175,17 +149,6 @@ public: return *this; } - /** - * @brief Set sfBookDirectory (SoeOptional) - * @return Reference to this builder for method chaining. - */ - LedgerStateFixBuilder& - setBookDirectory(std::decay_t const& value) - { - object_[sfBookDirectory] = value; - return *this; - } - /** * @brief Build and return the LedgerStateFix wrapper. * @param publicKey The public key for signing. diff --git a/include/xrpl/rdb/DBInit.h b/include/xrpl/rdb/DBInit.h index 10b04905f2..59806b2e85 100644 --- a/include/xrpl/rdb/DBInit.h +++ b/include/xrpl/rdb/DBInit.h @@ -9,20 +9,20 @@ namespace xrpl { // These pragmas are built at startup and applied to all database // connections, unless otherwise noted. -inline constexpr char const* kCommonDbPragmaJournal{"PRAGMA journal_mode=%s;"}; -inline constexpr char const* kCommonDbPragmaSync{"PRAGMA synchronous=%s;"}; -inline constexpr char const* kCommonDbPragmaTemp{"PRAGMA temp_store=%s;"}; +inline constexpr char const* kCOMMON_DB_PRAGMA_JOURNAL{"PRAGMA journal_mode=%s;"}; +inline constexpr char const* kCOMMON_DB_PRAGMA_SYNC{"PRAGMA synchronous=%s;"}; +inline constexpr char const* kCOMMON_DB_PRAGMA_TEMP{"PRAGMA temp_store=%s;"}; // A warning will be logged if any lower-safety sqlite tuning settings // are used and at least this much ledger history is configured. This // includes full history nodes. This is because such a large amount of // data will be more difficult to recover if a rare failure occurs, // which are more likely with some of the other available tuning settings. -inline constexpr std::uint32_t kSqliteTuningCutoff = 10'000'000; +inline constexpr std::uint32_t kSQLITE_TUNING_CUTOFF = 10'000'000; // Ledger database holds ledgers and ledger confirmations -inline constexpr auto kLgrDbName{"ledger.db"}; +inline constexpr auto kLGR_DB_NAME{"ledger.db"}; -inline constexpr std::array kLgrDbInit{ +inline constexpr std::array kLGR_DB_INIT{ {"BEGIN TRANSACTION;", "CREATE TABLE IF NOT EXISTS Ledgers ( \ @@ -47,9 +47,9 @@ inline constexpr std::array kLgrDbInit{ //////////////////////////////////////////////////////////////////////////////// // Transaction database holds transactions and public keys -inline constexpr auto kTxDbName{"transaction.db"}; +inline constexpr auto kTX_DB_NAME{"transaction.db"}; -inline constexpr std::array kTxDbInit{ +inline constexpr std::array kTX_DB_INIT{ {"BEGIN TRANSACTION;", "CREATE TABLE IF NOT EXISTS Transactions ( \ @@ -82,9 +82,9 @@ inline constexpr std::array kTxDbInit{ //////////////////////////////////////////////////////////////////////////////// -inline constexpr auto kWalletDbName{"wallet.db"}; +inline constexpr auto kWALLET_DB_NAME{"wallet.db"}; -inline constexpr std::array kWalletDbInit{ +inline constexpr std::array kWALLET_DB_INIT{ {"BEGIN TRANSACTION;", // A node's identity must be persisted, including diff --git a/include/xrpl/resource/Fees.h b/include/xrpl/resource/Fees.h index 55d539ac6a..dc14e3bd4d 100644 --- a/include/xrpl/resource/Fees.h +++ b/include/xrpl/resource/Fees.h @@ -6,27 +6,28 @@ namespace xrpl::Resource { /** Schedule of fees charged for imposing load on the server. */ /** @{ */ -extern Charge const kFeeMalformedRequest; // A request that we can immediately tell is invalid. -extern Charge const kFeeRequestNoReply; // A request that we cannot satisfy. -extern Charge const kFeeInvalidSignature; // An object whose signature we had to check that failed. -extern Charge const kFeeUselessData; // Data we have no use for. -extern Charge const kFeeInvalidData; // Data we have to verify before rejecting. +extern Charge const kFEE_MALFORMED_REQUEST; // A request that we can immediately tell is invalid. +extern Charge const kFEE_REQUEST_NO_REPLY; // A request that we cannot satisfy. +extern Charge const + kFEE_INVALID_SIGNATURE; // An object whose signature we had to check that failed. +extern Charge const kFEE_USELESS_DATA; // Data we have no use for. +extern Charge const kFEE_INVALID_DATA; // Data we have to verify before rejecting. // RPC loads -extern Charge const kFeeMalformedRpc; // An RPC request that we can immediately tell is invalid. -extern Charge const kFeeReferenceRpc; // A default "reference" unspecified load. -extern Charge const kFeeExceptionRpc; // RPC load that causes an exception. -extern Charge const kFeeMediumBurdenRpc; // A somewhat burdensome RPC load. -extern Charge const kFeeHeavyBurdenRpc; // A very burdensome RPC load. +extern Charge const kFEE_MALFORMED_RPC; // An RPC request that we can immediately tell is invalid. +extern Charge const kFEE_REFERENCE_RPC; // A default "reference" unspecified load. +extern Charge const kFEE_EXCEPTION_RPC; // RPC load that causes an exception. +extern Charge const kFEE_MEDIUM_BURDEN_RPC; // A somewhat burdensome RPC load. +extern Charge const kFEE_HEAVY_BURDEN_RPC; // A very burdensome RPC load. // Peer loads -extern Charge const kFeeTrivialPeer; // Requires no reply. -extern Charge const kFeeModerateBurdenPeer; // Requires some work. -extern Charge const kFeeHeavyBurdenPeer; // Extensive work. +extern Charge const kFEE_TRIVIAL_PEER; // Requires no reply. +extern Charge const kFEE_MODERATE_BURDEN_PEER; // Requires some work. +extern Charge const kFEE_HEAVY_BURDEN_PEER; // Extensive work. // Administrative -extern Charge const kFeeWarning; // The cost of receiving a warning. -extern Charge const kFeeDrop; // The cost of being dropped for excess load. +extern Charge const kFEE_WARNING; // The cost of receiving a warning. +extern Charge const kFEE_DROP; // The cost of being dropped for excess load. /** @} */ } // namespace xrpl::Resource diff --git a/include/xrpl/resource/detail/Entry.h b/include/xrpl/resource/detail/Entry.h index 361c8409c8..a821461e2e 100644 --- a/include/xrpl/resource/detail/Entry.h +++ b/include/xrpl/resource/detail/Entry.h @@ -21,7 +21,7 @@ struct Entry : public beast::List::Node @param now Construction time of Entry. */ explicit Entry(clock_type::time_point const now) - : refcount(0), localBalance(now), remoteBalance(0) + : refcount(0), local_balance(now), remote_balance(0) { } @@ -46,7 +46,7 @@ struct Entry : public beast::List::Node int balance(clock_type::time_point const now) { - return localBalance.value(now) + remoteBalance; + return local_balance.value(now) + remote_balance; } // Add a charge and return normalized balance @@ -54,7 +54,7 @@ struct Entry : public beast::List::Node int add(int charge, clock_type::time_point const now) { - return localBalance.add(charge, now) + remoteBalance; + return local_balance.add(charge, now) + remote_balance; } // The public key of the peer @@ -67,10 +67,10 @@ struct Entry : public beast::List::Node int refcount; // Exponentially decaying balance of resource consumption - DecayingSample localBalance; + DecayingSample local_balance; // Normalized balance contribution from imports - int remoteBalance; + int remote_balance; // Time of the last warning clock_type::time_point lastWarningTime; diff --git a/include/xrpl/resource/detail/Key.h b/include/xrpl/resource/detail/Key.h index 7d24b33955..935d44425e 100644 --- a/include/xrpl/resource/detail/Key.h +++ b/include/xrpl/resource/detail/Key.h @@ -25,11 +25,11 @@ struct Key std::size_t operator()(Key const& v) const { - return addrHash_(v.address); + return addr_hash_(v.address); } private: - beast::Uhash<> addrHash_; + beast::Uhash<> addr_hash_; }; struct KeyEqual diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index b11ac100f5..3bbe08724d 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -180,48 +180,48 @@ public: json::Value getJson() { - return getJson(kWarningThreshold); + return getJson(WarningThreshold); } - /** Returns a json::ValueType::Object. */ + /** Returns a json::objectValue. */ json::Value getJson(int threshold) { clock_type::time_point const now(clock_.now()); - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); std::scoped_lock const _(lock_); for (auto& inboundEntry : inbound_) { - int const localBalance = inboundEntry.localBalance.value(now); - if ((localBalance + inboundEntry.remoteBalance) >= threshold) + int const localBalance = inboundEntry.local_balance.value(now); + if ((localBalance + inboundEntry.remote_balance) >= threshold) { - json::Value& entry = (ret[inboundEntry.toString()] = json::ValueType::Object); + json::Value& entry = (ret[inboundEntry.toString()] = json::ObjectValue); entry[jss::local] = localBalance; - entry[jss::remote] = inboundEntry.remoteBalance; + entry[jss::remote] = inboundEntry.remote_balance; entry[jss::type] = "inbound"; } } for (auto& outboundEntry : outbound_) { - int const localBalance = outboundEntry.localBalance.value(now); - if ((localBalance + outboundEntry.remoteBalance) >= threshold) + int const localBalance = outboundEntry.local_balance.value(now); + if ((localBalance + outboundEntry.remote_balance) >= threshold) { - json::Value& entry = (ret[outboundEntry.toString()] = json::ValueType::Object); + json::Value& entry = (ret[outboundEntry.toString()] = json::ObjectValue); entry[jss::local] = localBalance; - entry[jss::remote] = outboundEntry.remoteBalance; + entry[jss::remote] = outboundEntry.remote_balance; entry[jss::type] = "outbound"; } } for (auto& adminEntry : admin_) { - int const localBalance = adminEntry.localBalance.value(now); - if ((localBalance + adminEntry.remoteBalance) >= threshold) + int const localBalance = adminEntry.local_balance.value(now); + if ((localBalance + adminEntry.remote_balance) >= threshold) { - json::Value& entry = (ret[adminEntry.toString()] = json::ValueType::Object); + json::Value& entry = (ret[adminEntry.toString()] = json::ObjectValue); entry[jss::local] = localBalance; - entry[jss::remote] = adminEntry.remoteBalance; + entry[jss::remote] = adminEntry.remote_balance; entry[jss::type] = "admin"; } } @@ -242,8 +242,8 @@ public: for (auto& inboundEntry : inbound_) { Gossip::Item item; - item.balance = inboundEntry.localBalance.value(now); - if (item.balance >= kMinimumGossipBalance) + item.balance = inboundEntry.local_balance.value(now); + if (item.balance >= MinimumGossipBalance) { item.address = inboundEntry.key->address; gossip.items.push_back(item); @@ -270,7 +270,7 @@ public: { // This is a new import Import& next(resultIt->second); - next.whenExpires = elapsed + kGossipExpirationSeconds; + next.whenExpires = elapsed + kGOSSIP_EXPIRATION_SECONDS; next.items.reserve(gossip.items.size()); for (auto const& gossipItem : gossip.items) @@ -278,7 +278,7 @@ public: Import::Item item; item.balance = gossipItem.balance; item.consumer = newInboundEndpoint(gossipItem.address); - item.consumer.entry().remoteBalance += item.balance; + item.consumer.entry().remote_balance += item.balance; next.items.push_back(item); } } @@ -288,21 +288,21 @@ public: // balances and then deduct the old remote balances. Import next; - next.whenExpires = elapsed + kGossipExpirationSeconds; + next.whenExpires = elapsed + kGOSSIP_EXPIRATION_SECONDS; next.items.reserve(gossip.items.size()); for (auto const& gossipItem : gossip.items) { Import::Item item; item.balance = gossipItem.balance; item.consumer = newInboundEndpoint(gossipItem.address); - item.consumer.entry().remoteBalance += item.balance; + item.consumer.entry().remote_balance += item.balance; next.items.push_back(item); } Import& prev(resultIt->second); for (auto& item : prev.items) { - item.consumer.entry().remoteBalance -= item.balance; + item.consumer.entry().remote_balance -= item.balance; } std::swap(next, prev); @@ -345,7 +345,7 @@ public: for (auto itemIter(import.items.begin()); itemIter != import.items.end(); ++itemIter) { - itemIter->consumer.entry().remoteBalance -= itemIter->balance; + itemIter->consumer.entry().remote_balance -= itemIter->balance; } iter = importTable_.erase(iter); @@ -363,10 +363,10 @@ public: static Disposition disposition(int balance) { - if (balance >= kDropThreshold) + if (balance >= DropThreshold) return Disposition::Drop; - if (balance >= kWarningThreshold) + if (balance >= WarningThreshold) return Disposition::Warn; return Disposition::Ok; @@ -417,25 +417,26 @@ public: // LCOV_EXCL_STOP } inactive_.pushBack(entry); - entry.whenExpires = clock_.now() + kSecondsUntilExpiration; + entry.whenExpires = clock_.now() + kSECONDS_UNTIL_EXPIRATION; } } Disposition charge(Entry& entry, Charge const& fee, std::string context = {}) { - static constexpr Charge::value_type kFeeLogAsWarn = 3000; - static constexpr Charge::value_type kFeeLogAsInfo = 1000; - static constexpr Charge::value_type kFeeLogAsDebug = 100; + static constexpr Charge::value_type kFEE_LOG_AS_WARN = 3000; + static constexpr Charge::value_type kFEE_LOG_AS_INFO = 1000; + static constexpr Charge::value_type kFEE_LOG_AS_DEBUG = 100; static_assert( - kFeeLogAsWarn > kFeeLogAsInfo && kFeeLogAsInfo > kFeeLogAsDebug && kFeeLogAsDebug > 10); + kFEE_LOG_AS_WARN > kFEE_LOG_AS_INFO && kFEE_LOG_AS_INFO > kFEE_LOG_AS_DEBUG && + kFEE_LOG_AS_DEBUG > 10); - static auto kGetStream = [](Resource::Charge::value_type cost, beast::Journal& journal) { - if (cost >= kFeeLogAsWarn) + static auto kGET_STREAM = [](Resource::Charge::value_type cost, beast::Journal& journal) { + if (cost >= kFEE_LOG_AS_WARN) return journal.warn(); - if (cost >= kFeeLogAsInfo) + if (cost >= kFEE_LOG_AS_INFO) return journal.info(); - if (cost >= kFeeLogAsDebug) + if (cost >= kFEE_LOG_AS_DEBUG) return journal.debug(); return journal.trace(); }; @@ -446,7 +447,8 @@ public: std::scoped_lock const _(lock_); clock_type::time_point const now(clock_.now()); int const balance(entry.add(fee.cost(), now)); - JLOG(kGetStream(fee.cost(), journal_)) << "Charging " << entry << " for " << fee << context; + JLOG(kGET_STREAM(fee.cost(), journal_)) + << "Charging " << entry << " for " << fee << context; return disposition(balance); } @@ -459,9 +461,9 @@ public: std::scoped_lock const _(lock_); bool notify(false); auto const elapsed = clock_.now(); - if (entry.balance(clock_.now()) >= kWarningThreshold && elapsed != entry.lastWarningTime) + if (entry.balance(clock_.now()) >= WarningThreshold && elapsed != entry.lastWarningTime) { - charge(entry, kFeeWarning); + charge(entry, kFEE_WARNING); notify = true; entry.lastWarningTime = elapsed; } @@ -483,15 +485,15 @@ public: bool drop(false); clock_type::time_point const now(clock_.now()); int const balance(entry.balance(now)); - if (balance >= kDropThreshold) + if (balance >= DropThreshold) { JLOG(journal_.warn()) << "Consumer entry " << entry << " dropped with balance " - << balance << " at or above drop threshold " << kDropThreshold; + << 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 // dropped. - charge(entry, kFeeDrop); + charge(entry, kFEE_DROP); ++stats_.drop; drop = true; } @@ -520,8 +522,8 @@ public: item["count"] = entry.refcount; item["name"] = entry.toString(); item["balance"] = entry.balance(now); - if (entry.remoteBalance != 0) - item["remote_balance"] = entry.remoteBalance; + if (entry.remote_balance != 0) + item["remote_balance"] = entry.remote_balance; } } diff --git a/include/xrpl/resource/detail/Tuning.h b/include/xrpl/resource/detail/Tuning.h index 7b2046f45c..3452005c35 100644 --- a/include/xrpl/resource/detail/Tuning.h +++ b/include/xrpl/resource/detail/Tuning.h @@ -5,23 +5,30 @@ namespace xrpl::Resource { /** Tunable constants. */ +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + // Balance at which a warning is issued + WarningThreshold = 5000 -// balance at which a warning is issued -static constexpr auto kWarningThreshold = 5000; + // Balance at which the consumer is disconnected + , + DropThreshold = 25000 -// balance at which the consumer is disconnected -static constexpr auto kDropThreshold = 25000; + // The number of seconds in the exponential decay window + // (This should be a power of two) + , + DecayWindowSeconds = 32 -// seconds in exponential decay window (power of two) -static constexpr auto kDecayWindowSeconds = 32; - -// minimum balance to include a load source in gossip -static constexpr auto kMinimumGossipBalance = 1000; + // The minimum balance required in order to include a load source in gossip + , + MinimumGossipBalance = 1000 +}; // The number of seconds until an inactive table item is removed -static constexpr std::chrono::seconds kSecondsUntilExpiration{300}; +std::chrono::seconds constexpr kSECONDS_UNTIL_EXPIRATION{300}; // Number of seconds until imported gossip expires -static constexpr std::chrono::seconds kGossipExpirationSeconds{30}; +std::chrono::seconds constexpr kGOSSIP_EXPIRATION_SECONDS{30}; } // namespace xrpl::Resource diff --git a/include/xrpl/server/Handoff.h b/include/xrpl/server/Handoff.h index b80a9c5745..eba8c6c4de 100644 --- a/include/xrpl/server/Handoff.h +++ b/include/xrpl/server/Handoff.h @@ -21,7 +21,7 @@ struct Handoff bool moved = false; // If response is set, this determines the keep alive - bool keepAlive = false; + bool keep_alive = false; // When set, this will be sent back std::shared_ptr response; diff --git a/include/xrpl/server/LoadFeeTrack.h b/include/xrpl/server/LoadFeeTrack.h index aa32e70ac8..5ad3972836 100644 --- a/include/xrpl/server/LoadFeeTrack.h +++ b/include/xrpl/server/LoadFeeTrack.h @@ -63,7 +63,7 @@ public: static std::uint32_t getLoadBase() { - return kLftNormalFee; + return kLFT_NORMAL_FEE; } std::uint32_t @@ -100,29 +100,29 @@ public: isLoadedLocal() const { std::scoped_lock const sl(lock_); - return (raiseCount_ != 0) || (localTxnLoadFee_ != kLftNormalFee); + return (raiseCount_ != 0) || (localTxnLoadFee_ != kLFT_NORMAL_FEE); } bool isLoadedCluster() const { std::scoped_lock const sl(lock_); - return (raiseCount_ != 0) || (localTxnLoadFee_ != kLftNormalFee) || - (clusterTxnLoadFee_ != kLftNormalFee); + return (raiseCount_ != 0) || (localTxnLoadFee_ != kLFT_NORMAL_FEE) || + (clusterTxnLoadFee_ != kLFT_NORMAL_FEE); } private: - static constexpr std::uint32_t kLftNormalFee = 256; // 256 is the minimum/normal load factor - static constexpr std::uint32_t kLftFeeIncFraction = 4; // increase fee by 1/4 - static constexpr std::uint32_t kLftFeeDecFraction = 4; // decrease fee by 1/4 - static constexpr std::uint32_t kLftFeeMax = kLftNormalFee * 1000000; + static std::uint32_t constexpr kLFT_NORMAL_FEE = 256; // 256 is the minimum/normal load factor + static std::uint32_t constexpr kLFT_FEE_INC_FRACTION = 4; // increase fee by 1/4 + static std::uint32_t constexpr kLFT_FEE_DEC_FRACTION = 4; // decrease fee by 1/4 + static std::uint32_t constexpr kLFT_FEE_MAX = kLFT_NORMAL_FEE * 1000000; beast::Journal const j_; std::mutex mutable lock_; - std::uint32_t localTxnLoadFee_{kLftNormalFee}; // Scale factor, lftNormalFee = normal fee - std::uint32_t remoteTxnLoadFee_{kLftNormalFee}; // Scale factor, lftNormalFee = normal fee - std::uint32_t clusterTxnLoadFee_{kLftNormalFee}; // Scale factor, lftNormalFee = normal fee + std::uint32_t localTxnLoadFee_{kLFT_NORMAL_FEE}; // Scale factor, lftNormalFee = normal fee + std::uint32_t remoteTxnLoadFee_{kLFT_NORMAL_FEE}; // Scale factor, lftNormalFee = normal fee + std::uint32_t clusterTxnLoadFee_{kLFT_NORMAL_FEE}; // Scale factor, lftNormalFee = normal fee std::uint32_t raiseCount_{0}; }; diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index ac9b855cf0..9207e0552b 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -30,19 +30,19 @@ struct Port boost::asio::ip::address ip; std::uint16_t port = 0; std::set protocol; - std::vector adminNetsV4; - std::vector adminNetsV6; - std::vector secureGatewayNetsV4; - std::vector secureGatewayNetsV6; + std::vector admin_nets_v4; + std::vector admin_nets_v6; + std::vector secure_gateway_nets_v4; + std::vector secure_gateway_nets_v6; std::string user; std::string password; - std::string adminUser; - std::string adminPassword; - std::string sslKey; - std::string sslCert; - std::string sslChain; - std::string sslCiphers; - boost::beast::websocket::permessage_deflate pmdOptions; + std::string admin_user; + std::string admin_password; + std::string ssl_key; + std::string ssl_cert; + std::string ssl_chain; + std::string ssl_ciphers; + boost::beast::websocket::permessage_deflate pmd_options; std::shared_ptr context; // How many incoming connections are allowed on this @@ -50,7 +50,7 @@ struct Port int limit = 0; // Websocket disconnects if send queue exceeds this limit - std::uint16_t wsQueueLimit{}; + std::uint16_t ws_queue_limit{}; // Returns `true` if any websocket protocols are specified [[nodiscard]] bool @@ -78,22 +78,22 @@ struct ParsedPort std::set protocol; std::string user; std::string password; - std::string adminUser; - std::string adminPassword; - std::string sslKey; - std::string sslCert; - std::string sslChain; - std::string sslCiphers; - boost::beast::websocket::permessage_deflate pmdOptions; + std::string admin_user; + std::string admin_password; + std::string ssl_key; + std::string ssl_cert; + std::string ssl_chain; + std::string ssl_ciphers; + boost::beast::websocket::permessage_deflate pmd_options; int limit = 0; - std::uint16_t wsQueueLimit{}; + std::uint16_t ws_queue_limit{}; std::optional ip; std::optional port; - std::vector adminNetsV4; - std::vector adminNetsV6; - std::vector secureGatewayNetsV4; - std::vector secureGatewayNetsV6; + std::vector admin_nets_v4; + std::vector admin_nets_v6; + std::vector secure_gateway_nets_v4; + std::vector secure_gateway_nets_v6; }; void diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index d26817bc45..0260cd6b84 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -30,7 +30,7 @@ namespace xrpl { /** Represents an active connection. */ template -class BaseHTTPPeer : public IOList::Work, public Session +class BaseHTTPPeer : public IoList::Work, public Session { protected: using clock_type = std::chrono::system_clock; @@ -38,9 +38,16 @@ protected: using endpoint_type = boost::asio::ip::tcp::endpoint; using yield_context = boost::asio::yield_context; - static constexpr auto kBufferSize = 4 * 1024; // size of read/write buffer - static constexpr auto kTimeoutSeconds = 30; // max seconds without completing a message - static constexpr auto kTimeoutSecondsLocal = 3; // used for localhost clients + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + // Size of our read/write buffer + BufferSize = 4 * 1024, + + // Max seconds without completing a message + TimeoutSeconds = 30, + TimeoutSecondsLocal = 3 // used for localhost clients + }; struct Buffer { @@ -58,13 +65,13 @@ protected: Handler& handler_; boost::asio::executor_work_guard work_; boost::asio::strand strand_; - endpoint_type remoteAddress_; + endpoint_type remote_address_; beast::Journal const journal_; std::string id_; std::size_t nid_; - boost::asio::streambuf readBuf_; + boost::asio::streambuf read_buf_; http_request_type message_; std::vector wq_; std::vector wq2_; @@ -73,9 +80,9 @@ protected: bool complete_ = false; boost::system::error_code ec_; - int requestCount_ = 0; - std::size_t bytesIn_ = 0; - std::size_t bytesOut_ = 0; + int request_count_ = 0; + std::size_t bytes_in_ = 0; + std::size_t bytes_out_ = 0; //-------------------------------------------------------------------------- @@ -151,7 +158,7 @@ protected: beast::IP::Endpoint remoteAddress() override { - return beast::IPAddressConversion::fromAsio(remoteAddress_); + return beast::IPAddressConversion::fromAsio(remote_address_); } http_request_type& @@ -191,23 +198,23 @@ BaseHTTPPeer::BaseHTTPPeer( , handler_(handler) , work_(boost::asio::make_work_guard(executor)) , strand_(boost::asio::make_strand(executor)) - , remoteAddress_(std::move(remoteAddress)) + , remote_address_(std::move(remoteAddress)) , journal_(journal) { - readBuf_.commit( - boost::asio::buffer_copy(readBuf_.prepare(boost::asio::buffer_size(buffers)), buffers)); - static std::atomic kSid; - nid_ = ++kSid; + read_buf_.commit( + boost::asio::buffer_copy(read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); + static std::atomic kSID; + nid_ = ++kSID; id_ = std::string("#") + std::to_string(nid_) + " "; - JLOG(journal_.trace()) << id_ << "accept: " << remoteAddress_.address(); + JLOG(journal_.trace()) << id_ << "accept: " << remote_address_.address(); } template BaseHTTPPeer::~BaseHTTPPeer() { handler_.onClose(session(), ec_); - JLOG(journal_.trace()) << id_ << "destroyed: " << requestCount_ - << ((requestCount_ == 1) ? " request" : " requests"); + JLOG(journal_.trace()) << id_ << "destroyed: " << request_count_ + << ((request_count_ == 1) ? " request" : " requests"); } template @@ -245,7 +252,7 @@ BaseHTTPPeer::startTimer() boost::beast::get_lowest_layer(impl().stream_) .expires_after( std::chrono::seconds( - remoteAddress_.address().is_loopback() ? kTimeoutSecondsLocal : kTimeoutSeconds)); + remote_address_.address().is_loopback() ? TimeoutSecondsLocal : TimeoutSeconds)); } // Convenience for discarding the error code @@ -274,7 +281,7 @@ BaseHTTPPeer::doRead(yield_context doYield) complete_ = false; error_code ec; startTimer(); - boost::beast::http::async_read(impl().stream_, readBuf_, message_, doYield[ec]); + boost::beast::http::async_read(impl().stream_, read_buf_, message_, doYield[ec]); cancelTimer(); if (ec == boost::beast::http::error::end_of_stream) return doClose(); @@ -296,7 +303,7 @@ BaseHTTPPeer::onWrite(error_code const& ec, std::size_t bytesTran return onTimer(); if (ec) return fail(ec, "write"); - bytesOut_ += bytesTransferred; + bytes_out_ += bytesTransferred; { std::scoped_lock const lock(mutex_); wq2_.clear(); @@ -357,7 +364,7 @@ BaseHTTPPeer::doWriter( for (;;) { - if (!writer->prepare(kBufferSize, resume)) + if (!writer->prepare(BufferSize, resume)) return; error_code ec; auto const bytesTransferred = boost::asio::async_write( diff --git a/include/xrpl/server/detail/BasePeer.h b/include/xrpl/server/detail/BasePeer.h index edde28981c..4aec164fe2 100644 --- a/include/xrpl/server/detail/BasePeer.h +++ b/include/xrpl/server/detail/BasePeer.h @@ -17,7 +17,7 @@ namespace xrpl { // Common part of all peers template -class BasePeer : public IOList::Work +class BasePeer : public IoList::Work { protected: using clock_type = std::chrono::system_clock; @@ -27,7 +27,7 @@ protected: Port const& port_; Handler& handler_; - endpoint_type remoteAddress_; + endpoint_type remote_address_; beast::WrappedSink sink_; beast::Journal const j_; @@ -65,7 +65,7 @@ BasePeer::BasePeer( beast::Journal journal) : port_(port) , handler_(handler) - , remoteAddress_(std::move(remoteAddress)) + , remote_address_(std::move(remoteAddress)) , sink_( journal.sink(), [] { diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index 13225dcba1..0d592ff09f 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -42,15 +42,15 @@ private: /// The socket has been closed, or will close after the next write /// finishes. Do not do any more writes, and don't try to close /// again. - bool doClose_ = false; + bool do_close_ = false; boost::beast::websocket::close_reason cr_; waitable_timer timer_; - bool closeOnTimer_ = false; - bool pingActive_ = false; + bool close_on_timer_ = false; + bool ping_active_ = false; boost::beast::websocket::ping_data payload_; error_code ec_; std::function - controlCallback_; + control_callback_; public: template @@ -85,7 +85,7 @@ public: [[nodiscard]] boost::asio::ip::tcp::endpoint const& remoteEndpoint() const override { - return this->remoteAddress_; + return this->remote_address_; } void @@ -173,14 +173,14 @@ BaseWSPeer::run() { if (!strand_.running_in_this_thread()) return post(strand_, std::bind(&BaseWSPeer::run, impl().shared_from_this())); - impl().ws_.set_option(port().pmdOptions); + impl().ws_.set_option(port().pmd_options); // Must manage the control callback memory outside of the `control_callback` // function - controlCallback_ = + control_callback_ = std::bind(&BaseWSPeer::onPingPong, this, std::placeholders::_1, std::placeholders::_2); - impl().ws_.control_callback(controlCallback_); + impl().ws_.control_callback(control_callback_); startTimer(); - closeOnTimer_ = true; + 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()); })); @@ -198,9 +198,9 @@ BaseWSPeer::send(std::shared_ptr w) { if (!strand_.running_in_this_thread()) return post(strand_, std::bind(&BaseWSPeer::send, impl().shared_from_this(), std::move(w))); - if (doClose_) + if (do_close_) return; - if (wq_.size() > port().wsQueueLimit) + if (wq_.size() > port().ws_queue_limit) { cr_.code = safeCast(boost::beast::websocket::close_code::policy_error); cr_.reason = "Policy error: client is too slow."; @@ -227,9 +227,9 @@ BaseWSPeer::close(boost::beast::websocket::close_reason const& re { if (!strand_.running_in_this_thread()) return post(strand_, [self = impl().shared_from_this(), reason] { self->close(reason); }); - if (doClose_) + if (do_close_) return; - doClose_ = true; + do_close_ = true; if (wq_.empty()) { impl().ws_.async_close( @@ -260,7 +260,7 @@ BaseWSPeer::onWsHandshake(error_code const& ec) { if (ec) return fail(ec, "on_ws_handshake"); - closeOnTimer_ = false; + close_on_timer_ = false; doRead(); } @@ -313,7 +313,7 @@ BaseWSPeer::onWriteFin(error_code const& ec) if (ec) return fail(ec, "write_fin"); wq_.pop_front(); - if (doClose_) + if (do_close_) { impl().ws_.async_close( cr_, @@ -368,12 +368,12 @@ void BaseWSPeer::startTimer() { // Max seconds without completing a message - static constexpr std::chrono::seconds kTimeout{30}; - static constexpr std::chrono::seconds kTimeoutLocal{3}; + static constexpr std::chrono::seconds kTIMEOUT{30}; + static constexpr std::chrono::seconds kTIMEOUT_LOCAL{3}; try { - timer_.expires_after(remoteEndpoint().address().is_loopback() ? kTimeoutLocal : kTimeout); + timer_.expires_after(remoteEndpoint().address().is_loopback() ? kTIMEOUT_LOCAL : kTIMEOUT); } catch (boost::system::system_error const& e) { @@ -409,7 +409,7 @@ BaseWSPeer::onPing(error_code const& ec) { if (ec == boost::asio::error::operation_aborted) return; - pingActive_ = false; + ping_active_ = false; if (!ec) return; fail(ec, "on_ping"); @@ -426,7 +426,7 @@ BaseWSPeer::onPingPong( boost::beast::string_view const p(payload_.begin()); if (payload == p) { - closeOnTimer_ = false; + close_on_timer_ = false; JLOG(this->j_.trace()) << "got matching pong"; } else @@ -444,11 +444,11 @@ BaseWSPeer::onTimer(error_code ec) return; if (!ec) { - if (!closeOnTimer_ || !pingActive_) + if (!close_on_timer_ || !ping_active_) { startTimer(); - closeOnTimer_ = true; - pingActive_ = true; + close_on_timer_ = true; + ping_active_ = true; // cryptographic is probably overkill.. beast::rngfill(payload_.begin(), payload_.size(), cryptoPrng()); impl().ws_.async_ping( diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index 79d36cae0c..811bf68a74 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -23,6 +23,7 @@ #include #include +#include #endif #include @@ -38,7 +39,7 @@ namespace xrpl { /** A listening socket. */ template -class Door : public IOList::Work, public std::enable_shared_from_this> +class Door : public IoList::Work, public std::enable_shared_from_this> { private: using clock_type = std::chrono::steady_clock; @@ -52,7 +53,7 @@ private: using stream_type = boost::beast::tcp_stream; // Detects SSL on a socket - class Detector : public IOList::Work, public std::enable_shared_from_this + class Detector : public IoList::Work, public std::enable_shared_from_this { private: Port const& port_; @@ -60,7 +61,7 @@ private: boost::asio::io_context& ioc_; stream_type stream_; socket_type& socket_; - endpoint_type remoteAddress_; + endpoint_type remote_address_; boost::asio::strand strand_; beast::Journal const j_; @@ -89,19 +90,16 @@ private: acceptor_type acceptor_; boost::asio::strand strand_; bool ssl_{ - port_.protocol.contains("https") || port_.protocol.contains("wss") || - port_.protocol.contains("wss2") || port_.protocol.contains("peer")}; + port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || + port_.protocol.count("wss2") > 0 || port_.protocol.count("peer") > 0}; bool plain_{ - port_.protocol.contains("http") || port_.protocol.contains("ws") || - (port_.protocol.contains("ws2"))}; - static constexpr std::chrono::milliseconds kInitialAcceptDelay{50}; - static constexpr std::chrono::milliseconds kMaxAcceptDelay{2000}; - std::chrono::milliseconds acceptDelay_{kInitialAcceptDelay}; - boost::asio::steady_timer backoffTimer_; - static constexpr std::uint64_t kMaxUsedFdPercent = 70; - static constexpr std::chrono::milliseconds kFdSampleInterval{250}; - clock_type::time_point fdSampleAt_; - bool cachedThrottle_{false}; + port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || + (port_.protocol.count("ws2") != 0u)}; + static constexpr std::chrono::milliseconds kINITIAL_ACCEPT_DELAY{50}; + static constexpr std::chrono::milliseconds kMAX_ACCEPT_DELAY{2000}; + std::chrono::milliseconds accept_delay_{kINITIAL_ACCEPT_DELAY}; + boost::asio::steady_timer backoff_timer_; + static constexpr double kFREE_FD_THRESHOLD = 0.70; struct FDStats { @@ -166,7 +164,7 @@ Door::Detector::Detector( , ioc_(ioc) , stream_(std::move(stream)) , socket_(stream_.socket()) - , remoteAddress_(std::move(remoteAddress)) + , remote_address_(std::move(remoteAddress)) , strand_(boost::asio::make_strand(ioc_)) , j_(j) { @@ -201,18 +199,18 @@ Door::Detector::doDetect(boost::asio::yield_context doYield) if (ssl) { if (auto sp = ios().template emplace>( - port_, handler_, ioc_, j_, remoteAddress_, 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_, remoteAddress_, 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 " << remoteAddress_; + JLOG(j_.trace()) << "Error detecting ssl: " << ec.message() << " from " << remote_address_; } } @@ -281,8 +279,7 @@ Door::Door( , ioc_(ioContext) , acceptor_(ioContext) , strand_(boost::asio::make_strand(ioContext)) - , backoffTimer_(ioContext) - , fdSampleAt_(clock_type::now() - kFdSampleInterval) + , backoff_timer_(ioContext) { reOpen(); } @@ -305,7 +302,7 @@ Door::close() return boost::asio::post( strand_, std::bind(&Door::close, this->shared_from_this())); } - backoffTimer_.cancel(); + backoff_timer_.cancel(); error_code ec; acceptor_.close(ec); } @@ -341,11 +338,11 @@ Door::doAccept(boost::asio::yield_context doYield) { if (shouldThrottleForFds()) { - JLOG(j_.warn()) << "Throttling do_accept for " << acceptDelay_.count() << "ms."; - backoffTimer_.expires_after(acceptDelay_); + backoff_timer_.expires_after(accept_delay_); boost::system::error_code tec; - backoffTimer_.async_wait(doYield[tec]); - acceptDelay_ = std::min(acceptDelay_ * 2, kMaxAcceptDelay); + backoff_timer_.async_wait(doYield[tec]); + accept_delay_ = std::min(accept_delay_ * 2, kMAX_ACCEPT_DELAY); + JLOG(j_.warn()) << "Throttling do_accept for " << accept_delay_.count() << "ms."; continue; } @@ -362,17 +359,14 @@ Door::doAccept(boost::asio::yield_context doYield) if (ec == boost::asio::error::no_descriptors || ec == boost::asio::error::no_buffer_space) { - char const* const cause = (ec == boost::asio::error::no_descriptors) - ? "too many open files" - : "kernel buffer space exhausted"; - JLOG(j_.warn()) << "accept: " << cause << ". Pausing for " << acceptDelay_.count() - << "ms."; + JLOG(j_.warn()) << "accept: Too many open files. Pausing for " + << accept_delay_.count() << "ms."; - backoffTimer_.expires_after(acceptDelay_); + backoff_timer_.expires_after(accept_delay_); boost::system::error_code tec; - backoffTimer_.async_wait(doYield[tec]); + backoff_timer_.async_wait(doYield[tec]); - acceptDelay_ = std::min(acceptDelay_ * 2, kMaxAcceptDelay); + accept_delay_ = std::min(accept_delay_ * 2, kMAX_ACCEPT_DELAY); } else { @@ -381,7 +375,7 @@ Door::doAccept(boost::asio::yield_context doYield) continue; } - acceptDelay_ = kInitialAcceptDelay; + accept_delay_ = kINITIAL_ACCEPT_DELAY; if (ssl_ && plain_) { @@ -409,11 +403,11 @@ Door::queryFdStats() const return std::nullopt; s.limit = static_cast(rl.rlim_cur); #if BOOST_OS_LINUX - static constexpr char const* kFdDir = "/proc/self/fd"; + constexpr char const* kFD_DIR = "/proc/self/fd"; #else - static constexpr char const* kFdDir = "/dev/fd"; + constexpr char const* kFD_DIR = "/dev/fd"; #endif - if (DIR* d = ::opendir(kFdDir)) + if (DIR* d = ::opendir(kFD_DIR)) { std::uint64_t cnt = 0; while (::readdir(d) != nullptr) @@ -434,15 +428,14 @@ Door::shouldThrottleForFds() #if BOOST_OS_WINDOWS return false; #else - auto const now = clock_type::now(); - if (now - fdSampleAt_ < kFdSampleInterval) - return cachedThrottle_; - - fdSampleAt_ = now; auto const stats = queryFdStats(); - cachedThrottle_ = - stats && stats->limit > 0 && stats->used * 100 > stats->limit * kMaxUsedFdPercent; - return cachedThrottle_; + if (!stats || stats->limit == 0) + return false; + + auto const& s = *stats; + auto const free = (s.limit > s.used) ? (s.limit - s.used) : 0ull; + double const freeRatio = static_cast(free) / static_cast(s.limit); + return freeRatio < kFREE_FD_THRESHOLD; #endif } diff --git a/include/xrpl/server/detail/PlainHTTPPeer.h b/include/xrpl/server/detail/PlainHTTPPeer.h index 791ab91acf..40f7fe2571 100644 --- a/include/xrpl/server/detail/PlainHTTPPeer.h +++ b/include/xrpl/server/detail/PlainHTTPPeer.h @@ -82,7 +82,7 @@ template void PlainHTTPPeer::run() { - if (!this->handler_.onAccept(this->session(), this->remoteAddress_)) + if (!this->handler_.onAccept(this->session(), this->remote_address_)) { util::spawn(this->strand_, std::bind(&PlainHTTPPeer::doClose, this->shared_from_this())); return; @@ -103,7 +103,7 @@ PlainHTTPPeer::websocketUpgrade() auto ws = this->ios().template emplace>( this->port_, this->handler_, - this->remoteAddress_, + this->remote_address_, std::move(this->message_), std::move(stream_), this->journal_); @@ -114,20 +114,20 @@ template void PlainHTTPPeer::doRequest() { - ++this->requestCount_; + ++this->request_count_; auto const what = - this->handler_.onHandoff(this->session(), std::move(this->message_), this->remoteAddress_); + this->handler_.onHandoff(this->session(), std::move(this->message_), this->remote_address_); if (what.moved) return; boost::system::error_code ec; if (what.response) { // half-close on Connection: close - if (!what.keepAlive) + if (!what.keep_alive) socket_.shutdown(socket_type::shutdown_receive, ec); if (ec) return this->fail(ec, "request"); - return this->write(what.response, what.keepAlive); + return this->write(what.response, what.keep_alive); } // Perform half-close when Connection: close and not SSL diff --git a/include/xrpl/server/detail/SSLHTTPPeer.h b/include/xrpl/server/detail/SSLHTTPPeer.h index f3b047150f..2eec8ed60f 100644 --- a/include/xrpl/server/detail/SSLHTTPPeer.h +++ b/include/xrpl/server/detail/SSLHTTPPeer.h @@ -26,7 +26,7 @@ private: using yield_context = boost::asio::yield_context; using error_code = boost::system::error_code; - std::unique_ptr streamPtr_; + std::unique_ptr stream_ptr_; stream_type& stream_; socket_type& socket_; @@ -80,8 +80,8 @@ SSLHTTPPeer::SSLHTTPPeer( journal, remoteAddress, buffers) - , streamPtr_(std::make_unique(middle_type(std::move(stream)), *port.context)) - , stream_(*streamPtr_) + , stream_ptr_(std::make_unique(middle_type(std::move(stream)), *port.context)) + , stream_(*stream_ptr_) , socket_(stream_.next_layer().socket()) { } @@ -91,7 +91,7 @@ template void SSLHTTPPeer::run() { - if (!this->handler_.onAccept(this->session(), this->remoteAddress_)) + if (!this->handler_.onAccept(this->session(), this->remote_address_)) { util::spawn(this->strand_, std::bind(&SSLHTTPPeer::doClose, this->shared_from_this())); return; @@ -110,9 +110,9 @@ SSLHTTPPeer::websocketUpgrade() auto ws = this->ios().template emplace>( this->port_, this->handler_, - this->remoteAddress_, + this->remote_address_, std::move(this->message_), - std::move(this->streamPtr_), + std::move(this->stream_ptr_), this->journal_); return ws; } @@ -124,8 +124,8 @@ SSLHTTPPeer::doHandshake(yield_context doYield) boost::system::error_code ec; stream_.set_verify_mode(boost::asio::ssl::verify_none); this->startTimer(); - this->readBuf_.consume( - stream_.async_handshake(stream_type::server, this->readBuf_.data(), doYield[ec])); + this->read_buf_.consume( + stream_.async_handshake(stream_type::server, this->read_buf_.data(), doYield[ec])); this->cancelTimer(); if (ec == boost::beast::error::timeout) return this->onTimer(); @@ -148,13 +148,13 @@ template void SSLHTTPPeer::doRequest() { - ++this->requestCount_; + ++this->request_count_; auto const what = this->handler_.onHandoff( - this->session(), std::move(streamPtr_), std::move(this->message_), this->remoteAddress_); + this->session(), std::move(stream_ptr_), std::move(this->message_), this->remote_address_); if (what.moved) return; if (what.response) - return this->write(what.response, what.keepAlive); + return this->write(what.response, what.keep_alive); // legacy this->handler_.onRequest(this->session()); } diff --git a/include/xrpl/server/detail/SSLWSPeer.h b/include/xrpl/server/detail/SSLWSPeer.h index cb03d5a796..19b77ea932 100644 --- a/include/xrpl/server/detail/SSLWSPeer.h +++ b/include/xrpl/server/detail/SSLWSPeer.h @@ -28,7 +28,7 @@ class SSLWSPeer : public BaseWSPeer>, using stream_type = boost::beast::ssl_stream; using waitable_timer = boost::asio::basic_waitable_timer; - std::unique_ptr streamPtr_; + std::unique_ptr stream_ptr_; boost::beast::websocket::stream ws_; public: @@ -61,8 +61,8 @@ SSLWSPeer::SSLWSPeer( remoteEndpoint, std::move(request), journal) - , streamPtr_(std::move(streamPtr)) - , ws_(*streamPtr_) + , stream_ptr_(std::move(streamPtr)) + , ws_(*stream_ptr_) { } diff --git a/include/xrpl/server/detail/ServerImpl.h b/include/xrpl/server/detail/ServerImpl.h index 48ffa26cfe..ce3a1c19c7 100644 --- a/include/xrpl/server/detail/ServerImpl.h +++ b/include/xrpl/server/detail/ServerImpl.h @@ -62,11 +62,13 @@ class ServerImpl : public Server private: using clock_type = std::chrono::system_clock; - static constexpr auto kHistorySize = 100; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { HistorySize = 100 }; Handler& handler_; beast::Journal const j_; - boost::asio::io_context& ioContext_; + boost::asio::io_context& io_context_; boost::asio::strand strand_; std::optional> work_; @@ -76,7 +78,7 @@ private: int high_ = 0; std::array hist_{}; - IOList ios_; + IoList ios_; public: ServerImpl(Handler& handler, boost::asio::io_context& ioContext, beast::Journal journal); @@ -95,7 +97,7 @@ public: void close() override; - IOList& + IoList& ios() { return ios_; @@ -104,7 +106,7 @@ public: boost::asio::io_context& getIoContext() { - return ioContext_; + return io_context_; } bool @@ -122,9 +124,9 @@ ServerImpl::ServerImpl( beast::Journal journal) : handler_(handler) , j_(journal) - , ioContext_(ioContext) - , strand_(boost::asio::make_strand(ioContext_)) - , work_(std::in_place, boost::asio::make_work_guard(ioContext_)) + , io_context_(ioContext) + , strand_(boost::asio::make_strand(io_context_)) + , work_(std::in_place, boost::asio::make_work_guard(io_context_)) { } @@ -150,7 +152,7 @@ ServerImpl::ports(std::vector const& ports) { ports_.push_back(port); auto& internalPort = ports_.back(); - if (auto sp = ios_.emplace>(handler_, ioContext_, internalPort, j_)) + if (auto sp = ios_.emplace>(handler_, io_context_, internalPort, j_)) { list_.push_back(sp); diff --git a/include/xrpl/server/detail/Spawn.h b/include/xrpl/server/detail/Spawn.h index 2560a2718b..50760be761 100644 --- a/include/xrpl/server/detail/Spawn.h +++ b/include/xrpl/server/detail/Spawn.h @@ -25,7 +25,7 @@ concept IsStrand = std:: * * @param ePtr The exception that was caught on the coroutine */ -inline constexpr auto kPropagateExceptions = [](std::exception_ptr ePtr) { +inline constexpr auto kPROPAGATE_EXCEPTIONS = [](std::exception_ptr ePtr) { if (ePtr) { try @@ -50,7 +50,7 @@ inline constexpr auto kPropagateExceptions = [](std::exception_ptr ePtr) { /** * @brief Spawns a coroutine using `boost::asio::spawn` * - * @note This uses kPropagateExceptions to force asio to propagate exceptions + * @note This uses kPROPAGATE_EXCEPTIONS to force asio to propagate exceptions * through `io_context` * @note Since implicit strand was removed from boost::asio::spawn this helper * function adds the strand back @@ -68,14 +68,14 @@ spawn(Ctx&& ctx, F&& func) if constexpr (impl::IsStrand) { boost::asio::spawn( - std::forward(ctx), std::forward(func), impl::kPropagateExceptions); + 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))), std::forward(func), - impl::kPropagateExceptions); + impl::kPROPAGATE_EXCEPTIONS); } } diff --git a/include/xrpl/server/detail/io_list.h b/include/xrpl/server/detail/io_list.h index 4daa23fb7e..a7037b683c 100644 --- a/include/xrpl/server/detail/io_list.h +++ b/include/xrpl/server/detail/io_list.h @@ -12,7 +12,7 @@ namespace xrpl { /** Manages a set of objects performing asynchronous I/O. */ -class IOList final +class IoList final { public: class Work @@ -21,8 +21,8 @@ public: void destroy(); - friend class IOList; - IOList* ios_ = nullptr; + friend class IoList; + IoList* ios_ = nullptr; public: virtual ~Work() @@ -30,13 +30,13 @@ public: destroy(); } - /** Return the IOList associated with the work. + /** Return the IoList associated with the work. Requirements: - The call to IOList::emplace to + The call to IoList::emplace to create the work has already returned. */ - IOList& + IoList& ios() { return *ios_; @@ -59,17 +59,17 @@ private: std::function f_; public: - IOList() = default; + IoList() = default; /** Destroy the list. Effects: - Closes the IOList if it was not previously + Closes the IoList if it was not previously closed. No finisher is invoked in this case. Blocks until all work is destroyed. */ - ~IOList() + ~IoList() { destroy(); } @@ -159,7 +159,7 @@ public: template void -IOList::Work::destroy() +IoList::Work::destroy() { if (!ios_) return; @@ -179,7 +179,7 @@ IOList::Work::destroy() template void -IOList::destroy() +IoList::destroy() { close(); join(); @@ -187,9 +187,9 @@ IOList::destroy() template std::shared_ptr -IOList::emplace(Args&&... args) +IoList::emplace(Args&&... args) { - static_assert(std::is_base_of_v, "T must derive from IOList::Work"); + static_assert(std::is_base_of_v, "T must derive from IoList::Work"); if (closed_) return nullptr; auto sp = std::make_shared(std::forward(args)...); @@ -211,7 +211,7 @@ IOList::emplace(Args&&... args) template void -IOList::close(Finisher&& f) +IoList::close(Finisher&& f) { std::unique_lock lock(m_); if (closed_) @@ -237,7 +237,7 @@ IOList::close(Finisher&& f) template void -IOList::join() +IoList::join() { std::unique_lock lock(m_); cv_.wait(lock, [&] { return closed_ && n_ == 0; }); diff --git a/include/xrpl/shamap/FullBelowCache.h b/include/xrpl/shamap/FullBelowCache.h index 07290dfbd1..0812f97c7b 100644 --- a/include/xrpl/shamap/FullBelowCache.h +++ b/include/xrpl/shamap/FullBelowCache.h @@ -22,7 +22,9 @@ private: using CacheType = KeyCache; public: - static constexpr auto kDefaultCacheTargetSize = 0; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { DefaultCacheTargetSize = 0 }; using key_type = uint256; using clock_type = typename CacheType::clock_type; @@ -39,7 +41,7 @@ public: clock_type& clock, beast::Journal j, beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::make(), - std::size_t targetSize = kDefaultCacheTargetSize, + std::size_t targetSize = DefaultCacheTargetSize, std::chrono::seconds expiration = std::chrono::minutes{2}) : cache_(name, targetSize, expiration, clock, j, collector), gen_(1) { diff --git a/include/xrpl/shamap/README.md b/include/xrpl/shamap/README.md index 8931a1b50c..ae37d23ac3 100644 --- a/include/xrpl/shamap/README.md +++ b/include/xrpl/shamap/README.md @@ -231,7 +231,7 @@ The `fetchNodeNT()` method goes through three phases: will be 0. 2. If the node is not in the TreeNodeCache, we attempt to locate the node - in the historic data stored by the data base. The call to + in the historic data stored by the data base. The call to to `fetchNodeFromDB(hash)` does that work for us. 3. Finally if a filter exists, we check if it can supply the node. This is diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index f63fc95b27..ba48e1927b 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -94,10 +94,10 @@ private: public: /** Number of children each non-leaf node has (the 'radix tree' part of the * map) */ - static constexpr unsigned int kBranchFactor = SHAMapInnerNode::kBranchFactor; + static constexpr unsigned int kBRANCH_FACTOR = SHAMapInnerNode::kBRANCH_FACTOR; /** The depth of the hash map: data is only present in the leaves */ - static constexpr unsigned int kLeafDepth = 64; + static constexpr unsigned int kLEAF_DEPTH = 64; using DeltaItem = std::pair, boost::intrusive_ptr>; @@ -390,7 +390,7 @@ private: lastBelow( intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, - int branch = kBranchFactor) const; + int branch = kBRANCH_FACTOR) const; // helper function for firstBelow and lastBelow SHAMapLeafNode* @@ -624,7 +624,7 @@ private: inline SHAMap::ConstIterator::ConstIterator(SHAMap const* map) : map_(map) { - XRPL_ASSERT(map_, "xrpl::SHAMap::ConstIterator::ConstIterator : 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(); diff --git a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h index c67b32d4e7..c006b2de37 100644 --- a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h +++ b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h @@ -50,7 +50,7 @@ public: { s.addRaw(item_->slice()); s.addBitString(item_->key()); - s.add8(kWireTypeAccountState); + s.add8(kWIRE_TYPE_ACCOUNT_STATE); } void diff --git a/include/xrpl/shamap/SHAMapInnerNode.h b/include/xrpl/shamap/SHAMapInnerNode.h index 48416a93e6..ee2a18bf03 100644 --- a/include/xrpl/shamap/SHAMapInnerNode.h +++ b/include/xrpl/shamap/SHAMapInnerNode.h @@ -15,7 +15,7 @@ class SHAMapInnerNode final : public SHAMapTreeNode, public CountedObject makeShamapitem(uint256 const& tag, Slice data) { XRPL_ASSERT( - data.size() <= megabytes(16), "xrpl::makeShamapitem : maximum input size"); + data.size() <= megabytes(16), "xrpl::make_shamapitem : maximum input size"); // NOLINTNEXTLINE(misc-const-correctness) std::uint8_t* raw = detail::gSlabber.allocate(data.size()); diff --git a/include/xrpl/shamap/SHAMapTreeNode.h b/include/xrpl/shamap/SHAMapTreeNode.h index ee74155ac4..d50fc65ccb 100644 --- a/include/xrpl/shamap/SHAMapTreeNode.h +++ b/include/xrpl/shamap/SHAMapTreeNode.h @@ -7,7 +7,6 @@ #include #include -#include #include #include @@ -15,14 +14,11 @@ namespace xrpl { // These are wire-protocol identifiers used during serialization to encode the // type of a node. They should not be arbitrarily be changed. -static constexpr unsigned char const kWireTypeTransaction = 0; -static constexpr unsigned char const kWireTypeAccountState = 1; -static constexpr unsigned char const kWireTypeInner = 2; -static constexpr unsigned char const kWireTypeCompressedInner = 3; -static constexpr unsigned char const kWireTypeTransactionWithMeta = 4; - -// Lower bound on SHAMap leaf item payload size, in bytes. -inline constexpr std::size_t kMinShaMapItemBytes = 12; +static constexpr unsigned char const kWIRE_TYPE_TRANSACTION = 0; +static constexpr unsigned char const kWIRE_TYPE_ACCOUNT_STATE = 1; +static constexpr unsigned char const kWIRE_TYPE_INNER = 2; +static constexpr unsigned char const kWIRE_TYPE_COMPRESSED_INNER = 3; +static constexpr unsigned char const kWIRE_TYPE_TRANSACTION_WITH_META = 4; enum class SHAMapNodeType { TnInner = 1, diff --git a/include/xrpl/shamap/SHAMapTxLeafNode.h b/include/xrpl/shamap/SHAMapTxLeafNode.h index 72be5b1962..eaac104c7e 100644 --- a/include/xrpl/shamap/SHAMapTxLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxLeafNode.h @@ -48,7 +48,7 @@ public: serializeForWire(Serializer& s) const final { s.addRaw(item_->slice()); - s.add8(kWireTypeTransaction); + s.add8(kWIRE_TYPE_TRANSACTION); } void diff --git a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h index 44562aeaba..5cf5b723b0 100644 --- a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h @@ -50,7 +50,7 @@ public: { s.addRaw(item_->slice()); s.addBitString(item_->key()); - s.add8(kWireTypeTransactionWithMeta); + s.add8(kWIRE_TYPE_TRANSACTION_WITH_META); } void diff --git a/include/xrpl/shamap/detail/TaggedPointer.h b/include/xrpl/shamap/detail/TaggedPointer.h index 94dbe95284..d3c0a6542f 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.h +++ b/include/xrpl/shamap/detail/TaggedPointer.h @@ -47,9 +47,9 @@ private: */ std::uintptr_t tp_ = 0; /** bit-and with this mask to get the tag bits (lowest two bits) */ - static constexpr std::uintptr_t kTagMask = 3; + static constexpr std::uintptr_t kTAG_MASK = 3; /** bit-and with this mask to get the pointer bits (mask out the tag) */ - static constexpr std::uintptr_t kPtrMask = ~kTagMask; + static constexpr std::uintptr_t kPTR_MASK = ~kTAG_MASK; /** Deallocate memory and run destructors */ void @@ -205,7 +205,7 @@ popcnt16(std::uint16_t a) return __builtin_popcount(a); #else // fallback to table lookup - static constexpr auto tbl = []() { + static auto constexpr const tbl = []() { std::array ret{}; for (int i = 0; i != 256; ++i) { diff --git a/include/xrpl/shamap/detail/TaggedPointer.ipp b/include/xrpl/shamap/detail/TaggedPointer.ipp index 2e6e31fed8..d4b5ca3365 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.ipp +++ b/include/xrpl/shamap/detail/TaggedPointer.ipp @@ -14,130 +14,130 @@ 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 kBoundaries{2, 4, 6, SHAMapInnerNode::kBranchFactor}; +constexpr std::array kBOUNDARIES{2, 4, 6, SHAMapInnerNode::kBRANCH_FACTOR}; static_assert( - kBoundaries.size() <= 4, + kBOUNDARIES.size() <= 4, "The hashesAndChildren member uses a tagged array format with two bits " "reserved for the tag. This supports at most 4 values."); static_assert( - kBoundaries.back() == SHAMapInnerNode::kBranchFactor, + kBOUNDARIES.back() == SHAMapInnerNode::kBRANCH_FACTOR, "Last element of boundaries must be number of children in a dense array"); // Terminology: A chunk is the memory being allocated from a block. A block // contains multiple chunks. This is the terminology the boost documentation // uses. Pools use "Simple Segregated Storage" as their storage format. -constexpr size_t kElementSizeBytes = +constexpr size_t kELEMENT_SIZE_BYTES = (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); -constexpr size_t kBlockSizeBytes = kilobytes(512); +constexpr size_t kBLOCK_SIZE_BYTES = kilobytes(512); template -constexpr std::array +constexpr std::array initArrayChunkSizeBytes(std::index_sequence) { - return std::array{ - kBoundaries[I] * kElementSizeBytes..., + return std::array{ + kBOUNDARIES[I] * kELEMENT_SIZE_BYTES..., }; } -constexpr auto kArrayChunkSizeBytes = - initArrayChunkSizeBytes(std::make_index_sequence{}); +constexpr auto kARRAY_CHUNK_SIZE_BYTES = + initArrayChunkSizeBytes(std::make_index_sequence{}); template -constexpr std::array +constexpr std::array initArrayChunksPerBlock(std::index_sequence) { - return std::array{ - kBlockSizeBytes / kArrayChunkSizeBytes[I]..., + return std::array{ + kBLOCK_SIZE_BYTES / kARRAY_CHUNK_SIZE_BYTES[I]..., }; } -constexpr auto kChunksPerBlock = - initArrayChunksPerBlock(std::make_index_sequence{}); +constexpr auto kCHUNKS_PER_BLOCK = + initArrayChunksPerBlock(std::make_index_sequence{}); [[nodiscard]] inline std::uint8_t numAllocatedChildren(std::uint8_t n) { - XRPL_ASSERT(n <= SHAMapInnerNode::kBranchFactor, "xrpl::numAllocatedChildren : valid input"); - return *std::ranges::lower_bound(kBoundaries, n); + XRPL_ASSERT(n <= SHAMapInnerNode::kBRANCH_FACTOR, "xrpl::numAllocatedChildren : valid input"); + return *std::ranges::lower_bound(kBOUNDARIES, n); } [[nodiscard]] inline std::size_t boundariesIndex(std::uint8_t numChildren) { XRPL_ASSERT( - numChildren <= SHAMapInnerNode::kBranchFactor, "xrpl::boundariesIndex : valid input"); - return std::distance(kBoundaries.begin(), std::ranges::lower_bound(kBoundaries, numChildren)); + numChildren <= SHAMapInnerNode::kBRANCH_FACTOR, "xrpl::boundariesIndex : valid input"); + return std::distance(kBOUNDARIES.begin(), std::ranges::lower_bound(kBOUNDARIES, numChildren)); } template -std::array, kBoundaries.size()> +std::array, kBOUNDARIES.size()> initAllocateArrayFuns(std::index_sequence) { - return std::array, kBoundaries.size()>{ + return std::array, kBOUNDARIES.size()>{ boost::singleton_pool< boost::fast_pool_allocator_tag, - kArrayChunkSizeBytes[I], + kARRAY_CHUNK_SIZE_BYTES[I], boost::default_user_allocator_new_delete, std::mutex, - kChunksPerBlock[I], - kChunksPerBlock[I]>::malloc..., + kCHUNKS_PER_BLOCK[I], + kCHUNKS_PER_BLOCK[I]>::malloc..., }; } -std::array, kBoundaries.size()> const kAllocateArrayFuns = - initAllocateArrayFuns(std::make_index_sequence{}); +std::array, kBOUNDARIES.size()> const kALLOCATE_ARRAY_FUNS = + initAllocateArrayFuns(std::make_index_sequence{}); template -std::array, kBoundaries.size()> +std::array, kBOUNDARIES.size()> initFreeArrayFuns(std::index_sequence) { - return std::array, kBoundaries.size()>{ + return std::array, kBOUNDARIES.size()>{ static_cast(boost::singleton_pool< boost::fast_pool_allocator_tag, - kArrayChunkSizeBytes[I], + kARRAY_CHUNK_SIZE_BYTES[I], boost::default_user_allocator_new_delete, std::mutex, - kChunksPerBlock[I], - kChunksPerBlock[I]>::free)..., + kCHUNKS_PER_BLOCK[I], + kCHUNKS_PER_BLOCK[I]>::free)..., }; } -std::array, kBoundaries.size()> const kFreeArrayFuns = - initFreeArrayFuns(std::make_index_sequence{}); +std::array, kBOUNDARIES.size()> const kFREE_ARRAY_FUNS = + initFreeArrayFuns(std::make_index_sequence{}); template -std::array, kBoundaries.size()> +std::array, kBOUNDARIES.size()> initIsFromArrayFuns(std::index_sequence) { - return std::array, kBoundaries.size()>{ + return std::array, kBOUNDARIES.size()>{ boost::singleton_pool< boost::fast_pool_allocator_tag, - kArrayChunkSizeBytes[I], + kARRAY_CHUNK_SIZE_BYTES[I], boost::default_user_allocator_new_delete, std::mutex, - kChunksPerBlock[I], - kChunksPerBlock[I]>::is_from..., + kCHUNKS_PER_BLOCK[I], + kCHUNKS_PER_BLOCK[I]>::is_from..., }; } -std::array, kBoundaries.size()> const kIsFromArrayFuns = - initIsFromArrayFuns(std::make_index_sequence{}); +std::array, kBOUNDARIES.size()> const kIS_FROM_ARRAY_FUNS = + initIsFromArrayFuns(std::make_index_sequence{}); // This function returns an untagged pointer [[nodiscard]] inline std::pair allocateArrays(std::uint8_t numChildren) { auto const i = boundariesIndex(numChildren); - return {i, kAllocateArrayFuns[i]()}; + return {i, kALLOCATE_ARRAY_FUNS[i]()}; } // This function takes an untagged pointer inline void deallocateArrays(std::uint8_t boundaryIndex, void* p) { - XRPL_ASSERT(kIsFromArrayFuns[boundaryIndex](p), "xrpl::deallocateArrays : valid inputs"); - kFreeArrayFuns[boundaryIndex](p); + XRPL_ASSERT(kIS_FROM_ARRAY_FUNS[boundaryIndex](p), "xrpl::deallocateArrays : valid inputs"); + kFREE_ARRAY_FUNS[boundaryIndex](p); } // Used in `iterChildren` and elsewhere as the hash value for sparse arrays when // the hash isn't actually stored in the array. -SHAMapHash const kZeroShaMapHash; +SHAMapHash const kZERO_SHA_MAP_HASH; } // namespace @@ -146,17 +146,17 @@ void TaggedPointer::iterChildren(std::uint16_t isBranch, F&& f) const { auto [numAllocated, hashes, _] = getHashesAndChildren(); - if (numAllocated == SHAMapInnerNode::kBranchFactor) + if (numAllocated == SHAMapInnerNode::kBRANCH_FACTOR) { // dense case - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) f(hashes[i]); } else { // sparse case int curHashI = 0; - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { if ((1 << i) & isBranch) { @@ -164,7 +164,7 @@ TaggedPointer::iterChildren(std::uint16_t isBranch, F&& f) const } else { - f(kZeroShaMapHash); + f(kZERO_SHA_MAP_HASH); } } } @@ -174,10 +174,10 @@ template void TaggedPointer::iterNonEmptyChildIndexes(std::uint16_t isBranch, F&& f) const { - if (capacity() == SHAMapInnerNode::kBranchFactor) + if (capacity() == SHAMapInnerNode::kBRANCH_FACTOR) { // dense case - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { if ((1 << i) & isBranch) { @@ -189,7 +189,7 @@ TaggedPointer::iterNonEmptyChildIndexes(std::uint16_t isBranch, F&& f) const { // sparse case int curHashI = 0; - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { if ((1 << i) & isBranch) { @@ -247,11 +247,11 @@ inline TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t numChildren) { auto [tag, p] = allocateArrays(numChildren); XRPL_ASSERT( - tag < kBoundaries.size(), + tag < kBOUNDARIES.size(), "xrpl::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " "maximum tag"); XRPL_ASSERT( - (reinterpret_cast(p) & kPtrMask) == reinterpret_cast(p), + (reinterpret_cast(p) & kPTR_MASK) == reinterpret_cast(p), "xrpl::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " "valid pointer"); tp_ = reinterpret_cast(p) + tag; @@ -275,7 +275,7 @@ inline TaggedPointer::TaggedPointer( auto [srcDstNumAllocated, srcDstHashes, srcDstChildren] = getHashesAndChildren(); bool const srcDstIsDense = isDense(); int srcDstIndex = 0; - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { auto const mask = (1 << i); bool const inSrc = (srcBranches & mask) != 0; @@ -354,7 +354,7 @@ inline TaggedPointer::TaggedPointer( bool const srcIsDense = src.isDense(); bool const dstIsDense = dst.isDense(); int srcIndex = 0, dstIndex = 0; - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { auto const mask = (1 << i); bool const inSrc = (srcBranches & mask) != 0; @@ -440,7 +440,7 @@ inline TaggedPointer::TaggedPointer( std::tie(newNumAllocated, newHashes, newChildren) = newHashesAndChildren.getHashesAndChildren(); std::tie(std::ignore, oldHashes, oldChildren) = getHashesAndChildren(); - if (newNumAllocated == SHAMapInnerNode::kBranchFactor) + if (newNumAllocated == SHAMapInnerNode::kBRANCH_FACTOR) { // new arrays are dense, old arrays are sparse iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { @@ -449,7 +449,7 @@ inline TaggedPointer::TaggedPointer( intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; }); // Run the constructors for the remaining elements - for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) + for (int i = 0; i < SHAMapInnerNode::kBRANCH_FACTOR; ++i) { if (((1 << i) & isBranch) != 0) continue; @@ -508,19 +508,19 @@ TaggedPointer::operator=(TaggedPointer&& other) [[nodiscard]] inline std::pair TaggedPointer::decode() const { - return {tp_ & kTagMask, reinterpret_cast(tp_ & kPtrMask)}; + return {tp_ & kTAG_MASK, reinterpret_cast(tp_ & kPTR_MASK)}; } [[nodiscard]] inline std::uint8_t TaggedPointer::capacity() const { - return kBoundaries[tp_ & kTagMask]; + return kBOUNDARIES[tp_ & kTAG_MASK]; } [[nodiscard]] inline bool TaggedPointer::isDense() const { - return (tp_ & kTagMask) == kBoundaries.size() - 1; + return (tp_ & kTAG_MASK) == kBOUNDARIES.size() - 1; } [[nodiscard]] inline std::tuple*> @@ -528,7 +528,7 @@ TaggedPointer::getHashesAndChildren() const { auto const [tag, ptr] = decode(); auto const hashes = reinterpret_cast(ptr); - std::uint8_t const numAllocated = kBoundaries[tag]; + std::uint8_t const numAllocated = kBOUNDARIES[tag]; auto const children = reinterpret_cast*>(hashes + numAllocated); return {numAllocated, hashes, children}; @@ -537,7 +537,7 @@ TaggedPointer::getHashesAndChildren() const [[nodiscard]] inline SHAMapHash* TaggedPointer::getHashes() const { - return reinterpret_cast(tp_ & kPtrMask); + return reinterpret_cast(tp_ & kPTR_MASK); }; [[nodiscard]] inline intr_ptr::SharedPtr* diff --git a/include/xrpl/tx/ApplyContext.h b/include/xrpl/tx/ApplyContext.h index 8540037601..910ec6be42 100644 --- a/include/xrpl/tx/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -93,8 +93,8 @@ public: std::function const& func); + std::shared_ptr const& before, + std::shared_ptr const& after)> const& func); void destroyXRP(XRPAmount const& fee) diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index 86b1e856b3..cf8030b275 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -115,7 +115,7 @@ protected: beast::WrappedSink sink_; beast::Journal const j_; - AccountID const accountID_; + AccountID const account_; XRPAmount preFeeBalance_{}; // Balance before fees. public: @@ -123,8 +123,9 @@ public: Transactor(Transactor const&) = delete; Transactor& operator=(Transactor const&) = delete; - - enum class ConsequencesFactoryType { Normal, Blocker, Custom }; + // 68 transactor subclass files + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum ConsequencesFactoryType { Normal, Blocker, Custom }; /** Process the transaction. */ ApplyResult @@ -263,7 +264,10 @@ protected: * to detect deletions. */ virtual void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) = 0; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) = 0; /** Check transaction-specific post-conditions after all entries have * been visited. @@ -365,7 +369,7 @@ private: ReadView const& view, AccountID const& idSigner, AccountID const& idAccount, - SLE::const_pointer sleAccount, + std::shared_ptr sleAccount, beast::Journal const j); static NotTEC checkMultiSign( @@ -395,15 +399,6 @@ private: static NotTEC preflight2(PreflightContext const& ctx); - /** Universal validations - - Valid MPTAmount and XRPAmount - - Do not try to call preflightUniversal from preflight() in derived classes. See - the description of invokePreflight for details. - */ - static NotTEC - preflightUniversal(PreflightContext const& ctx); - /** Check transaction-specific invariants only. * * Walks every modified ledger entry via visitInvariantEntry, then @@ -469,9 +464,6 @@ Transactor::invokePreflight(PreflightContext const& ctx) if (auto const ret = preflight1(ctx, T::getFlagsMask(ctx))) return ret; - if (auto const ret = preflightUniversal(ctx)) - return ret; - if (auto const ret = T::preflight(ctx)) return ret; diff --git a/include/xrpl/tx/invariants/AMMInvariant.h b/include/xrpl/tx/invariants/AMMInvariant.h index ee2fb66a1c..43d9c5ad0a 100644 --- a/include/xrpl/tx/invariants/AMMInvariant.h +++ b/include/xrpl/tx/invariants/AMMInvariant.h @@ -22,7 +22,7 @@ public: ValidAMM() = default; void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); diff --git a/include/xrpl/tx/invariants/DirectoryInvariant.h b/include/xrpl/tx/invariants/DirectoryInvariant.h deleted file mode 100644 index 96643ea465..0000000000 --- a/include/xrpl/tx/invariants/DirectoryInvariant.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -namespace xrpl { - -class ValidBookDirectory -{ - bool badBookDirectory_ = false; - hash_set rootIndexes_; - -public: - void - visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - - bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); -}; - -} // namespace xrpl diff --git a/include/xrpl/tx/invariants/FreezeInvariant.h b/include/xrpl/tx/invariants/FreezeInvariant.h index a76eb66497..645f444462 100644 --- a/include/xrpl/tx/invariants/FreezeInvariant.h +++ b/include/xrpl/tx/invariants/FreezeInvariant.h @@ -22,7 +22,7 @@ class TransfersNotFrozen { struct BalanceChange { - SLE::const_pointer const line; + std::shared_ptr const line; int const balanceChangeSign; }; @@ -35,34 +35,37 @@ class TransfersNotFrozen using ByIssuer = std::map; ByIssuer balanceChanges_; - std::map possibleIssuers_; + std::map const> possibleIssuers_; public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); private: bool - isValidEntry(SLE::const_ref before, SLE::const_ref after); + isValidEntry(std::shared_ptr const& before, std::shared_ptr const& after); static STAmount - calculateBalanceChange(SLE::const_ref before, SLE::const_ref after, bool isDelete); + calculateBalanceChange( + std::shared_ptr const& before, + std::shared_ptr const& after, + bool isDelete); void recordBalance(Issue const& issue, BalanceChange change); void - recordBalanceChanges(SLE::const_ref after, STAmount const& balanceChange); + recordBalanceChanges(std::shared_ptr const& after, STAmount const& balanceChange); - SLE::const_pointer + std::shared_ptr findIssuer(AccountID const& issuerID, ReadView const& view); static bool validateIssuerChanges( - SLE::const_ref issuer, + std::shared_ptr const& issuer, IssuerChanges const& changes, STTx const& tx, beast::Journal const& j, diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index 8931d189fd..9b4335c215 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -70,7 +69,10 @@ public: * @param after ledger entry after modification by the transaction */ void - visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after); + visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after); /** * @brief called after all ledger entries have been visited to determine @@ -108,7 +110,7 @@ class TransactionFeeCheck { public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); static bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); @@ -128,7 +130,7 @@ class XRPNotCreated public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -148,7 +150,7 @@ class AccountRootsNotDeleted public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -171,11 +173,11 @@ class AccountRootsDeletedClean // deleted, it can still be found. After is used specifically for any checks // that are expected as part of the deletion, such as zeroing out the // balance. - std::vector> accountsDeleted_; + std::vector, std::shared_ptr>> accountsDeleted_; public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); @@ -194,7 +196,7 @@ class XRPBalanceChecks public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -211,7 +213,7 @@ class LedgerEntryTypesMatch public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -229,7 +231,7 @@ class NoXRPTrustLines public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -248,7 +250,7 @@ class NoDeepFreezeTrustLinesWithoutFreeze public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -267,7 +269,7 @@ class NoBadOffers public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -283,7 +285,7 @@ class NoZeroEscrow public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -303,7 +305,7 @@ class ValidNewAccountRoot public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -324,7 +326,7 @@ class ValidClawback public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -344,7 +346,7 @@ class ValidPseudoAccounts public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); @@ -364,27 +366,12 @@ class NoModifiedUnmodifiableFields public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); }; -/** Verify that MPT/XRP STAmounts are canonical in any ledger entries left after the - * transaction applies. - */ -class ValidAmounts -{ - std::vector> afterEntries_; - -public: - void - visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - - [[nodiscard]] bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; -}; - // additional invariant checks can be declared above and then added to this // tuple using InvariantChecks = std::tuple< @@ -406,7 +393,6 @@ using InvariantChecks = std::tuple< ValidMPTIssuance, ValidPermissionedDomain, ValidPermissionedDEX, - ValidBookDirectory, ValidAMM, NoModifiedUnmodifiableFields, ValidPseudoAccounts, @@ -414,9 +400,7 @@ using InvariantChecks = std::tuple< ValidLoan, ValidVault, ValidConfidentialMPToken, - ValidMPTPayment, - ValidAmounts, - ValidMPTTransfer>; + ValidMPTPayment>; /** * @brief get a tuple of all invariant checks diff --git a/include/xrpl/tx/invariants/InvariantCheckPrivilege.h b/include/xrpl/tx/invariants/InvariantCheckPrivilege.h index e55419dfc1..5f76a43759 100644 --- a/include/xrpl/tx/invariants/InvariantCheckPrivilege.h +++ b/include/xrpl/tx/invariants/InvariantCheckPrivilege.h @@ -25,7 +25,7 @@ not have the relevant amendments enabled_. It's intentionally a pain in the neck so that bad code gets caught and fixed as early as possible. */ -// Bitwise flags, 86 files, used in macros files +// Bitwise flags, 86 files // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum Privilege { NoPriv = 0x0000, // The transaction can not do any of the enumerated operations diff --git a/include/xrpl/tx/invariants/LoanBrokerInvariant.h b/include/xrpl/tx/invariants/LoanBrokerInvariant.h index 684bbff423..e7d14a638b 100644 --- a/include/xrpl/tx/invariants/LoanBrokerInvariant.h +++ b/include/xrpl/tx/invariants/LoanBrokerInvariant.h @@ -46,7 +46,7 @@ class ValidLoanBroker public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); diff --git a/include/xrpl/tx/invariants/LoanInvariant.h b/include/xrpl/tx/invariants/LoanInvariant.h index 3f408d169a..bda9c51653 100644 --- a/include/xrpl/tx/invariants/LoanInvariant.h +++ b/include/xrpl/tx/invariants/LoanInvariant.h @@ -23,7 +23,7 @@ class ValidLoan public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); diff --git a/include/xrpl/tx/invariants/MPTInvariant.h b/include/xrpl/tx/invariants/MPTInvariant.h index 01d91f6ae9..5607bb72a0 100644 --- a/include/xrpl/tx/invariants/MPTInvariant.h +++ b/include/xrpl/tx/invariants/MPTInvariant.h @@ -2,13 +2,10 @@ #include #include -#include #include #include #include -#include -#include namespace xrpl { @@ -23,21 +20,9 @@ class ValidMPTIssuance // MPToken by an issuer bool mptCreatedByIssuer_ = false; - /// sfReferenceHolding is intended to be set exactly once at vault - /// creation and immutable thereafter; true when that rule was violated. - bool referenceHoldingSetOnCreate_ = false; - - /// True when sfReferenceHolding was mutated on an existing MPTokenIssuance. - bool referenceHoldingMutated_ = false; - - /// MPTokens and RippleStates deleted during apply. finalize() checks each - /// holder's AccountRoot to detect vault pseudo-account holdings deleted - /// outside VaultDelete. All these checks are gated on fixCleanup3_2_0. - std::vector> deletedHoldings_; - public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -65,7 +50,7 @@ class ValidMPTPayment public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); @@ -114,42 +99,4 @@ public: finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); }; -class ValidMPTTransfer -{ - struct Value - { - std::optional amtBefore; - std::optional amtAfter; - }; - // MPTID: {holder: Value} - hash_map> amount_; - // Deleted MPToken - // MPToken key: true if MPTAuthorized is set - hash_map deletedAuthorized_; - -public: - void - visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - - bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); - -private: - /** - * @brief Check whether a holder is authorized to send or receive an MPToken. - * - * Deleted MPToken SLEs are no longer present in the view by the time - * finalize() runs, so their authorization state is captured during - * visitEntry() and stored in deletedAuthorized_. For deleted MPTokens, - * returns true if reqAuth is false or lsfMPTAuthorized was set at deletion. - * For existing MPTokens, returns the result of requireAuth() - */ - [[nodiscard]] bool - isAuthorized( - ReadView const& view, - MPTID const& mptid, - AccountID const& holder, - bool requireAuth) const; -}; - } // namespace xrpl diff --git a/include/xrpl/tx/invariants/NFTInvariant.h b/include/xrpl/tx/invariants/NFTInvariant.h index 698df05247..fa056ecbb0 100644 --- a/include/xrpl/tx/invariants/NFTInvariant.h +++ b/include/xrpl/tx/invariants/NFTInvariant.h @@ -33,7 +33,7 @@ class ValidNFTokenPage public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; @@ -61,7 +61,7 @@ class NFTokenCountTracking public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; diff --git a/include/xrpl/tx/invariants/PermissionedDEXInvariant.h b/include/xrpl/tx/invariants/PermissionedDEXInvariant.h index 2ec22ded88..da187779b2 100644 --- a/include/xrpl/tx/invariants/PermissionedDEXInvariant.h +++ b/include/xrpl/tx/invariants/PermissionedDEXInvariant.h @@ -10,15 +10,14 @@ namespace xrpl { class ValidPermissionedDEX { - bool regularOffersOld_ = false; // pre-fixCleanup3_2_0: also flags deleted offers - bool regularOffers_ = false; // post-fixCleanup3_2_0: excludes deleted offers - bool badHybridsOld_ = false; // pre-fixCleanup3_1_3: missing field/domain or size > 1 - bool badHybrids_ = false; // post-fixCleanup3_1_3: also catches size == 0 (size != 1) + bool regularOffers_ = false; + bool badHybridsOld_ = false; // pre-fixSecurity3_1_3: missing field/domain or size > 1 + bool badHybrids_ = false; // post-fixSecurity3_1_3: also catches size == 0 (size != 1) hash_set domains_; public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); diff --git a/include/xrpl/tx/invariants/PermissionedDomainInvariant.h b/include/xrpl/tx/invariants/PermissionedDomainInvariant.h index 19edcc0b39..2475ed8f6b 100644 --- a/include/xrpl/tx/invariants/PermissionedDomainInvariant.h +++ b/include/xrpl/tx/invariants/PermissionedDomainInvariant.h @@ -32,7 +32,7 @@ class ValidPermissionedDomain public: void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); diff --git a/include/xrpl/tx/invariants/VaultInvariant.h b/include/xrpl/tx/invariants/VaultInvariant.h index 2a9ffc8282..7ca67f546d 100644 --- a/include/xrpl/tx/invariants/VaultInvariant.h +++ b/include/xrpl/tx/invariants/VaultInvariant.h @@ -4,11 +4,9 @@ #include #include #include -#include #include #include #include -#include #include #include @@ -37,15 +35,15 @@ namespace xrpl { */ class ValidVault { - static constexpr Number kZero{}; + Number static constexpr kZERO{}; struct Vault final { - uint256 key = beast::kZero; + uint256 key = beast::kZERO; Asset asset; AccountID pseudoId; AccountID owner; - uint192 shareMPTID = beast::kZero; + uint192 shareMPTID = beast::kZERO; Number assetsTotal = 0; Number assetsAvailable = 0; Number assetsMaximum = 0; @@ -66,7 +64,7 @@ class ValidVault public: struct DeltaInfo final { - Number delta = kNumZero; + Number delta = kNUM_ZERO; std::optional scale; // Compute the delta between two Numbers, taking the coarsest scale @@ -81,83 +79,16 @@ private: std::vector beforeMPTs_; std::unordered_map deltas_; - /** - * @brief Compute the minimum STAmount scale for rounding invariant - * calculations. - * - * Post-amendment (@c fixCleanup3_2_0) this is simply the posterior - * @c assetsTotal scale. Pre-amendment it is the coarsest scale across - * @p vaultDelta and both asset-field deltas. - * - * @param vaultDelta Delta of the vault's asset balance for this transaction. - * @param rules Active ledger rules (used to check the amendment). - * @returns The minimum scale to apply when rounding vault-related amounts. - */ - [[nodiscard]] std::int32_t - computeVaultMinScale(DeltaInfo const& vaultDelta, Rules const& rules) const; - - /** - * @brief Return the vault-asset balance-change delta for an account. - * - * Looks up the ledger-entry delta recorded during @c visitEntry for the - * account entry (XRP), trust line (IOU), or MPToken (MPT) that corresponds - * to the vault asset held by @p id. - * - * @param id Account whose asset delta is requested. - * @returns The delta, or @c std::nullopt if the entry was not touched. - */ - [[nodiscard]] std::optional - deltaAssets(AccountID const& id) const; - - /** - * @brief Return the vault-asset delta for the transaction's sending - * account, adjusted for the fee. - * - * Calls @c deltaAssets for @c tx[sfAccount] and, for non-delegated XRP - * transactions, adds the consumed fee back so the invariant sees the net - * asset movement rather than the fee-reduced balance change. - * - * @param tx The transaction being applied. - * @param fee Fee charged by this transaction. - * @returns The fee-adjusted delta, or @c std::nullopt if the net delta is - * zero or the account entry was not touched. - */ - [[nodiscard]] std::optional - deltaAssetsTxAccount(STTx const& tx, XRPAmount fee) const; - - /** - * @brief Return the vault-share balance-change delta for an account. - * - * For the vault's pseudo-account the @c MPTokenIssuance outstanding-amount - * delta is returned; for all other accounts the @c MPToken delta is - * returned. - * - * @param id Account whose share delta is requested. - * @returns The delta, or @c std::nullopt if the entry was not touched. - */ - [[nodiscard]] std::optional - deltaShares(AccountID const& id) const; - - /** - * @brief Check whether a vault holds no assets. - * - * @param vault Snapshot of the vault to test. - * @returns @c true when both @c assetsAvailable and @c assetsTotal are - * zero. - */ - [[nodiscard]] static bool - isVaultEmpty(Vault const& vault); - public: - // Compute the coarsest scale required to represent all numbers - [[nodiscard]] static std::int32_t - computeCoarsestScale(std::vector const& numbers); - void - visitEntry(bool, SLE::const_ref, SLE::const_ref); + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + + // Compute the coarsest scale required to represent all numbers + [[nodiscard]] static std::int32_t + computeCoarsestScale(std::vector const& numbers); }; } // namespace xrpl diff --git a/include/xrpl/tx/paths/AMMLiquidity.h b/include/xrpl/tx/paths/AMMLiquidity.h index 9abe37f868..3211d0caa7 100644 --- a/include/xrpl/tx/paths/AMMLiquidity.h +++ b/include/xrpl/tx/paths/AMMLiquidity.h @@ -31,7 +31,7 @@ template class AMMLiquidity { private: - inline static Number const kInitialFibSeqPct = Number(5) / 20000; + inline static Number const kINITIAL_FIB_SEQ_PCT = Number(5) / 20000; AMMContext& ammContext_; AccountID const ammAccountID_; std::uint32_t const tradingFee_; diff --git a/include/xrpl/tx/paths/BookTip.h b/include/xrpl/tx/paths/BookTip.h index c4bdb0415c..e06a2da86c 100644 --- a/include/xrpl/tx/paths/BookTip.h +++ b/include/xrpl/tx/paths/BookTip.h @@ -21,7 +21,7 @@ private: uint256 end_; uint256 dir_; uint256 index_; - SLE::pointer entry_; + std::shared_ptr entry_; Quality quality_{}; public: diff --git a/include/xrpl/tx/paths/Offer.h b/include/xrpl/tx/paths/Offer.h index 2dab5bcebf..0a551f4c2d 100644 --- a/include/xrpl/tx/paths/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -21,7 +21,7 @@ class TOffer private: SLE::pointer entry_; Quality quality_{}; - AccountID accountID_; + AccountID account_; Asset assetIn_; Asset assetOut_; @@ -53,7 +53,7 @@ public: [[nodiscard]] AccountID const& owner() const { - return accountID_; + return account_; } /** Returns the in and out amounts. @@ -69,9 +69,9 @@ public: [[nodiscard]] bool fullyConsumed() const { - if (amounts_.in <= beast::kZero) + if (amounts_.in <= beast::kZERO) return true; - if (amounts_.out <= beast::kZero) + if (amounts_.out <= beast::kZERO) return true; return false; } @@ -122,7 +122,7 @@ public: isFunded() const { // Offer owner is issuer; they have unlimited funds if IOU - return accountID_ == assetOut_.getIssuer() && assetOut_.holds(); + return account_ == assetOut_.getIssuer() && assetOut_.holds(); } static std::pair @@ -159,7 +159,7 @@ public: template TOffer::TOffer(SLE::pointer entry, Quality quality) - : entry_(std::move(entry)), quality_(quality), accountID_(entry_->getAccountID(sfAccount)) + : entry_(std::move(entry)), quality_(quality), account_(entry_->getAccountID(sfAccount)) { auto const tp = entry_->getFieldAmount(sfTakerPays); auto const tg = entry_->getFieldAmount(sfTakerGets); diff --git a/include/xrpl/tx/paths/detail/StepChecks.h b/include/xrpl/tx/paths/detail/StepChecks.h index fea9f90a31..a1e6490781 100644 --- a/include/xrpl/tx/paths/detail/StepChecks.h +++ b/include/xrpl/tx/paths/detail/StepChecks.h @@ -77,8 +77,8 @@ checkNoRipple( if (!sleIn || !sleOut) return terNO_LINE; - if (sleIn->isFlag((cur > prev) ? lsfHighNoRipple : lsfLowNoRipple) && - sleOut->isFlag((cur > next) ? lsfHighNoRipple : lsfLowNoRipple)) + if ((((*sleIn)[sfFlags] & ((cur > prev) ? lsfHighNoRipple : lsfLowNoRipple)) != 0u) && + (((*sleOut)[sfFlags] & ((cur > next) ? lsfHighNoRipple : lsfLowNoRipple)) != 0u)) { JLOG(j.info()) << "Path violates noRipple constraint between " << prev << ", " << cur << " and " << next; diff --git a/include/xrpl/tx/paths/detail/Steps.h b/include/xrpl/tx/paths/detail/Steps.h index 9909c4bdcd..db9d3a6f3a 100644 --- a/include/xrpl/tx/paths/detail/Steps.h +++ b/include/xrpl/tx/paths/detail/Steps.h @@ -460,7 +460,7 @@ public: [[nodiscard]] bool isZero(EitherAmount const& out) const override { - return get(out) == beast::kZero; + return get(out) == beast::kZERO; } [[nodiscard]] bool diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 31f0182258..f69e10e99a 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -28,8 +28,8 @@ template struct StrandResult { bool success = false; ///< Strand succeeded - TInAmt in = beast::kZero; ///< Currency amount in - TOutAmt out = beast::kZero; ///< Currency amount out + TInAmt in = beast::kZERO; ///< Currency amount in + TOutAmt out = beast::kZERO; ///< Currency amount out std::optional sandbox; ///< Resulting Sandbox state boost::container::flat_set ofrsToRm; ///< Offers to remove // Num offers consumed or partially consumed (includes expired and unfunded @@ -284,8 +284,8 @@ flow( template struct FlowResult { - TInAmt in = beast::kZero; - TOutAmt out = beast::kZero; + TInAmt in = beast::kZERO; + TOutAmt out = beast::kZERO; std::optional sandbox; boost::container::flat_set removableOffers; TER ter = temUNKNOWN; @@ -325,7 +325,7 @@ struct FlowResult inline std::optional qualityUpperBound(ReadView const& v, Strand const& strand) { - Quality q{STAmount::kURateOne}; + Quality q{STAmount::kU_RATE_ONE}; std::optional stepQ; DebtDirection dir = DebtDirection::Issues; for (auto const& step : strand) @@ -595,9 +595,9 @@ flow( // values if `remainingIn` is initialized through a copy constructor. We can // get similar warnings for `sendMax` if it is initialized in the most // natural way. Using `make_optional`, allows us to work around this bug. - TInAmt const sendMaxInit = sendMaxST ? toAmount(*sendMaxST) : TInAmt{beast::kZero}; + TInAmt const sendMaxInit = sendMaxST ? toAmount(*sendMaxST) : TInAmt{beast::kZERO}; std::optional const sendMax = - (sendMaxST && sendMaxInit >= beast::kZero) ? std::make_optional(sendMaxInit) : std::nullopt; + (sendMaxST && sendMaxInit >= beast::kZERO) ? std::make_optional(sendMaxInit) : std::nullopt; std::optional remainingIn = !!sendMax ? std::make_optional(sendMaxInit) : std::nullopt; // std::optional remainingIn{sendMax}; @@ -619,7 +619,7 @@ flow( auto sum = [](auto const& col) { using TResult = std::decay_t; if (col.empty()) - return TResult{beast::kZero}; + return TResult{beast::kZERO}; return std::accumulate(col.begin() + 1, col.end(), *col.begin()); }; @@ -627,7 +627,7 @@ flow( // successful boost::container::flat_set ofrsToRmOnFail; - while (remainingOut > beast::kZero && (!remainingIn || *remainingIn > beast::kZero)) + while (remainingOut > beast::kZERO && (!remainingIn || *remainingIn > beast::kZERO)) { ++curTry; if (curTry >= maxTries) @@ -679,7 +679,7 @@ flow( offersConsidered += f.ofrsUsed; - if (!f.success || f.out == beast::kZero) + if (!f.success || f.out == beast::kZERO) continue; if (flowDebugInfo) @@ -800,7 +800,7 @@ flow( return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)}; } } - else if (actualOut == beast::kZero) + else if (actualOut == beast::kZERO) { return {tecPATH_DRY, std::move(ofrsToRmOnFail)}; } @@ -816,7 +816,7 @@ flow( // fixFillOrKill amendment: // Handles 2. 1. is handled above and falls through for tfSell. XRPL_ASSERT(remainingIn, "xrpl::flow : nonzero remainingIn"); - if (remainingIn && *remainingIn != beast::kZero) + if (remainingIn && *remainingIn != beast::kZERO) return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)}; } diff --git a/include/xrpl/tx/transactors/account/AccountDelete.h b/include/xrpl/tx/transactors/account/AccountDelete.h index 16661a4b7c..1491ae09d9 100644 --- a/include/xrpl/tx/transactors/account/AccountDelete.h +++ b/include/xrpl/tx/transactors/account/AccountDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class AccountDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit AccountDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -29,7 +29,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/account/AccountSet.h b/include/xrpl/tx/transactors/account/AccountSet.h index a40a9ec963..780ad846da 100644 --- a/include/xrpl/tx/transactors/account/AccountSet.h +++ b/include/xrpl/tx/transactors/account/AccountSet.h @@ -8,7 +8,7 @@ namespace xrpl { class AccountSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; explicit AccountSet(ApplyContext& ctx) : Transactor(ctx) { @@ -33,7 +33,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/account/SetRegularKey.h b/include/xrpl/tx/transactors/account/SetRegularKey.h index 6ff9c5aa52..22a40714db 100644 --- a/include/xrpl/tx/transactors/account/SetRegularKey.h +++ b/include/xrpl/tx/transactors/account/SetRegularKey.h @@ -7,7 +7,7 @@ namespace xrpl { class SetRegularKey : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit SetRegularKey(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/account/SignerListSet.h b/include/xrpl/tx/transactors/account/SignerListSet.h index 46e3191323..16e7bf3a06 100644 --- a/include/xrpl/tx/transactors/account/SignerListSet.h +++ b/include/xrpl/tx/transactors/account/SignerListSet.h @@ -24,7 +24,7 @@ private: std::vector signers_; public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit SignerListSet(ApplyContext& ctx) : Transactor(ctx) { @@ -42,7 +42,10 @@ public: preCompute() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/bridge/XChainBridge.h b/include/xrpl/tx/transactors/bridge/XChainBridge.h index 58a546de2f..79755c0c2f 100644 --- a/include/xrpl/tx/transactors/bridge/XChainBridge.h +++ b/include/xrpl/tx/transactors/bridge/XChainBridge.h @@ -5,14 +5,14 @@ namespace xrpl { -constexpr size_t kXbridgeMaxAccountCreateClaims = 128; +constexpr size_t kXBRIDGE_MAX_ACCOUNT_CREATE_CLAIMS = 128; // Attach a new bridge to a door account. Once this is done, the cross-chain // transfer transactions may be used to transfer funds from this account. class XChainCreateBridge : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit XChainCreateBridge(ApplyContext& ctx) : Transactor(ctx) { @@ -28,7 +28,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -42,7 +45,7 @@ public: class BridgeModify : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit BridgeModify(ApplyContext& ctx) : Transactor(ctx) { @@ -61,7 +64,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -89,7 +95,7 @@ class XChainClaim : public Transactor { public: // Blocker since we cannot accurately calculate the consequences - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit XChainClaim(ApplyContext& ctx) : Transactor(ctx) { @@ -105,7 +111,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -124,7 +133,7 @@ public: class XChainCommit : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; static TxConsequences makeTxConsequences(PreflightContext const& ctx); @@ -143,7 +152,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -167,7 +179,7 @@ public: class XChainCreateClaimID : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit XChainCreateClaimID(ApplyContext& ctx) : Transactor(ctx) { @@ -183,7 +195,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -207,7 +222,7 @@ class XChainAddClaimAttestation : public Transactor { public: // Blocker since we cannot accurately calculate the consequences - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit XChainAddClaimAttestation(ApplyContext& ctx) : Transactor(ctx) { @@ -223,7 +238,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -238,7 +256,7 @@ class XChainAddAccountCreateAttestation : public Transactor { public: // Blocker since we cannot accurately calculate the consequences - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Blocker; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Blocker}; explicit XChainAddAccountCreateAttestation(ApplyContext& ctx) : Transactor(ctx) { @@ -254,7 +272,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -293,7 +314,7 @@ public: class XChainCreateAccountCommit : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit XChainCreateAccountCommit(ApplyContext& ctx) : Transactor(ctx) { @@ -309,7 +330,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/check/CheckCancel.h b/include/xrpl/tx/transactors/check/CheckCancel.h index b8e8b6c52d..4861a05a02 100644 --- a/include/xrpl/tx/transactors/check/CheckCancel.h +++ b/include/xrpl/tx/transactors/check/CheckCancel.h @@ -7,7 +7,7 @@ namespace xrpl { class CheckCancel : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CheckCancel(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/check/CheckCash.h b/include/xrpl/tx/transactors/check/CheckCash.h index 7d4e615cfd..c831cc279e 100644 --- a/include/xrpl/tx/transactors/check/CheckCash.h +++ b/include/xrpl/tx/transactors/check/CheckCash.h @@ -7,7 +7,7 @@ namespace xrpl { class CheckCash : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CheckCash(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/check/CheckCreate.h b/include/xrpl/tx/transactors/check/CheckCreate.h index 178fe4707c..494870cb1c 100644 --- a/include/xrpl/tx/transactors/check/CheckCreate.h +++ b/include/xrpl/tx/transactors/check/CheckCreate.h @@ -7,7 +7,7 @@ namespace xrpl { class CheckCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CheckCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/credentials/CredentialAccept.h b/include/xrpl/tx/transactors/credentials/CredentialAccept.h index 8630ac3f7f..0da5dd6131 100644 --- a/include/xrpl/tx/transactors/credentials/CredentialAccept.h +++ b/include/xrpl/tx/transactors/credentials/CredentialAccept.h @@ -7,7 +7,7 @@ namespace xrpl { class CredentialAccept : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CredentialAccept(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/credentials/CredentialCreate.h b/include/xrpl/tx/transactors/credentials/CredentialCreate.h index 91b5e829d3..d7a1a245df 100644 --- a/include/xrpl/tx/transactors/credentials/CredentialCreate.h +++ b/include/xrpl/tx/transactors/credentials/CredentialCreate.h @@ -7,7 +7,7 @@ namespace xrpl { class CredentialCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CredentialCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/credentials/CredentialDelete.h b/include/xrpl/tx/transactors/credentials/CredentialDelete.h index 70fe5cb3d0..60de0957ca 100644 --- a/include/xrpl/tx/transactors/credentials/CredentialDelete.h +++ b/include/xrpl/tx/transactors/credentials/CredentialDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class CredentialDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit CredentialDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/delegate/DelegateSet.h b/include/xrpl/tx/transactors/delegate/DelegateSet.h index a55524ecff..ee4bfeaaef 100644 --- a/include/xrpl/tx/transactors/delegate/DelegateSet.h +++ b/include/xrpl/tx/transactors/delegate/DelegateSet.h @@ -7,7 +7,7 @@ namespace xrpl { class DelegateSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit DelegateSet(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -35,7 +38,7 @@ public: // Interface used by AccountDelete static TER - deleteDelegate(ApplyView& view, SLE::ref sle, beast::Journal j); + deleteDelegate(ApplyView& view, std::shared_ptr const& sle, beast::Journal j); }; } // namespace xrpl diff --git a/include/xrpl/tx/transactors/dex/AMMBid.h b/include/xrpl/tx/transactors/dex/AMMBid.h index dfa50d06ba..979ca0250d 100644 --- a/include/xrpl/tx/transactors/dex/AMMBid.h +++ b/include/xrpl/tx/transactors/dex/AMMBid.h @@ -45,7 +45,7 @@ namespace xrpl { class AMMBid : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMBid(ApplyContext& ctx) : Transactor(ctx) { @@ -64,7 +64,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMClawback.h b/include/xrpl/tx/transactors/dex/AMMClawback.h index 6f31480490..3cf6288ccf 100644 --- a/include/xrpl/tx/transactors/dex/AMMClawback.h +++ b/include/xrpl/tx/transactors/dex/AMMClawback.h @@ -7,7 +7,7 @@ class Sandbox; class AMMClawback : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMClawback(ApplyContext& ctx) : Transactor(ctx) { @@ -29,7 +29,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMContext.h b/include/xrpl/tx/transactors/dex/AMMContext.h index 65954044be..3d13547b52 100644 --- a/include/xrpl/tx/transactors/dex/AMMContext.h +++ b/include/xrpl/tx/transactors/dex/AMMContext.h @@ -18,11 +18,11 @@ public: // Restrict number of AMM offers. If this restriction is removed // then need to restrict in some other way because AMM offers are // not counted in the BookStep offer counter. - static constexpr std::uint8_t kMaxIterations = 30; + constexpr static std::uint8_t kMAX_ITERATIONS = 30; private: // Tx account owner is required to get the AMM trading fee in BookStep - AccountID accountID_; + AccountID account_; // true if payment has multiple paths bool multiPath_{false}; // Is true if AMM offer is consumed during a payment engine iteration. @@ -31,8 +31,7 @@ private: std::uint16_t ammIters_{0}; public: - AMMContext(AccountID const& account, bool multiPath) - : accountID_(account), multiPath_(multiPath) + AMMContext(AccountID const& account, bool multiPath) : account_(account), multiPath_(multiPath) { } ~AMMContext() = default; @@ -69,7 +68,7 @@ public: [[nodiscard]] bool maxItersReached() const { - return ammIters_ >= kMaxIterations; + return ammIters_ >= kMAX_ITERATIONS; } [[nodiscard]] std::uint16_t @@ -81,7 +80,7 @@ public: [[nodiscard]] AccountID account() const { - return accountID_; + return account_; } /** Strand execution may fail. Reset the flag at the start diff --git a/include/xrpl/tx/transactors/dex/AMMCreate.h b/include/xrpl/tx/transactors/dex/AMMCreate.h index 64d2a1e3b1..485273ca17 100644 --- a/include/xrpl/tx/transactors/dex/AMMCreate.h +++ b/include/xrpl/tx/transactors/dex/AMMCreate.h @@ -37,7 +37,7 @@ namespace xrpl { class AMMCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -60,7 +60,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMDelete.h b/include/xrpl/tx/transactors/dex/AMMDelete.h index d3e8cfeeb4..1fbb4ec9e8 100644 --- a/include/xrpl/tx/transactors/dex/AMMDelete.h +++ b/include/xrpl/tx/transactors/dex/AMMDelete.h @@ -13,7 +13,7 @@ namespace xrpl { class AMMDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMDeposit.h b/include/xrpl/tx/transactors/dex/AMMDeposit.h index 453046ddad..3847a2a529 100644 --- a/include/xrpl/tx/transactors/dex/AMMDeposit.h +++ b/include/xrpl/tx/transactors/dex/AMMDeposit.h @@ -42,7 +42,7 @@ class Sandbox; class AMMDeposit : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMDeposit(ApplyContext& ctx) : Transactor(ctx) { @@ -64,7 +64,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMVote.h b/include/xrpl/tx/transactors/dex/AMMVote.h index 8defc1369e..c1fa059bd6 100644 --- a/include/xrpl/tx/transactors/dex/AMMVote.h +++ b/include/xrpl/tx/transactors/dex/AMMVote.h @@ -30,7 +30,7 @@ namespace xrpl { class AMMVote : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMVote(ApplyContext& ctx) : Transactor(ctx) { @@ -49,7 +49,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/AMMWithdraw.h b/include/xrpl/tx/transactors/dex/AMMWithdraw.h index 6e88320eae..cbaae78433 100644 --- a/include/xrpl/tx/transactors/dex/AMMWithdraw.h +++ b/include/xrpl/tx/transactors/dex/AMMWithdraw.h @@ -50,7 +50,7 @@ enum class WithdrawAll : bool { No = false, Yes }; class AMMWithdraw : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit AMMWithdraw(ApplyContext& ctx) : Transactor(ctx) { @@ -72,7 +72,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -152,7 +155,7 @@ public: static std::pair deleteAMMAccountIfEmpty( Sandbox& sb, - SLE::pointer const ammSle, + std::shared_ptr const ammSle, STAmount const& lpTokenBalance, Asset const& asset1, Asset const& asset2, diff --git a/include/xrpl/tx/transactors/dex/OfferCancel.h b/include/xrpl/tx/transactors/dex/OfferCancel.h index 2806b6942f..a8e408492e 100644 --- a/include/xrpl/tx/transactors/dex/OfferCancel.h +++ b/include/xrpl/tx/transactors/dex/OfferCancel.h @@ -8,7 +8,7 @@ namespace xrpl { class OfferCancel : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit OfferCancel(ApplyContext& ctx) : Transactor(ctx) { @@ -24,7 +24,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/dex/OfferCreate.h b/include/xrpl/tx/transactors/dex/OfferCreate.h index 7faf613d3a..2c5e63705a 100644 --- a/include/xrpl/tx/transactors/dex/OfferCreate.h +++ b/include/xrpl/tx/transactors/dex/OfferCreate.h @@ -12,7 +12,7 @@ class Sandbox; class OfferCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; /** Construct a Transactor subclass that creates an offer in the ledger. */ explicit OfferCreate(ApplyContext& ctx) : Transactor(ctx) @@ -41,7 +41,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -78,11 +81,10 @@ private: TER applyHybrid( Sandbox& sb, - STLedgerEntry::pointer sleOffer, + std::shared_ptr sleOffer, Keylet const& offerIndex, STAmount const& saTakerPays, STAmount const& saTakerGets, - std::uint64_t openRate, std::function)> const& setDir); }; diff --git a/include/xrpl/tx/transactors/did/DIDDelete.h b/include/xrpl/tx/transactors/did/DIDDelete.h index 94615f51b6..2699307b39 100644 --- a/include/xrpl/tx/transactors/did/DIDDelete.h +++ b/include/xrpl/tx/transactors/did/DIDDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class DIDDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit DIDDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -20,13 +20,16 @@ public: deleteSLE(ApplyContext& ctx, Keylet sleKeylet, AccountID const owner); static TER - deleteSLE(ApplyView& view, SLE::pointer sle, AccountID const owner, beast::Journal j); + deleteSLE(ApplyView& view, std::shared_ptr sle, AccountID const owner, beast::Journal j); TER doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/did/DIDSet.h b/include/xrpl/tx/transactors/did/DIDSet.h index 8c84ea6c9b..fa07cfc295 100644 --- a/include/xrpl/tx/transactors/did/DIDSet.h +++ b/include/xrpl/tx/transactors/did/DIDSet.h @@ -7,7 +7,7 @@ namespace xrpl { class DIDSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit DIDSet(ApplyContext& ctx) : Transactor(ctx) { @@ -20,7 +20,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/escrow/EscrowCancel.h b/include/xrpl/tx/transactors/escrow/EscrowCancel.h index af09f70202..13270b6741 100644 --- a/include/xrpl/tx/transactors/escrow/EscrowCancel.h +++ b/include/xrpl/tx/transactors/escrow/EscrowCancel.h @@ -7,7 +7,7 @@ namespace xrpl { class EscrowCancel : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit EscrowCancel(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/escrow/EscrowCreate.h b/include/xrpl/tx/transactors/escrow/EscrowCreate.h index 8800e97b80..4e809e3bf5 100644 --- a/include/xrpl/tx/transactors/escrow/EscrowCreate.h +++ b/include/xrpl/tx/transactors/escrow/EscrowCreate.h @@ -7,7 +7,7 @@ namespace xrpl { class EscrowCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; explicit EscrowCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -16,9 +16,6 @@ public: static TxConsequences makeTxConsequences(PreflightContext const& ctx); - static bool - checkExtraFeatures(PreflightContext const& ctx); - static NotTEC preflight(PreflightContext const& ctx); @@ -29,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/escrow/EscrowFinish.h b/include/xrpl/tx/transactors/escrow/EscrowFinish.h index 061fa0527c..0fc6b46311 100644 --- a/include/xrpl/tx/transactors/escrow/EscrowFinish.h +++ b/include/xrpl/tx/transactors/escrow/EscrowFinish.h @@ -7,7 +7,7 @@ namespace xrpl { class EscrowFinish : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit EscrowFinish(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanBrokerCoverClawback.h b/include/xrpl/tx/transactors/lending/LoanBrokerCoverClawback.h index 81ea97ce7e..a774e23717 100644 --- a/include/xrpl/tx/transactors/lending/LoanBrokerCoverClawback.h +++ b/include/xrpl/tx/transactors/lending/LoanBrokerCoverClawback.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanBrokerCoverClawback : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanBrokerCoverClawback(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanBrokerCoverDeposit.h b/include/xrpl/tx/transactors/lending/LoanBrokerCoverDeposit.h index 43b932726b..f69c47afbc 100644 --- a/include/xrpl/tx/transactors/lending/LoanBrokerCoverDeposit.h +++ b/include/xrpl/tx/transactors/lending/LoanBrokerCoverDeposit.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanBrokerCoverDeposit : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanBrokerCoverDeposit(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.h b/include/xrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.h index a757ac51bf..b70b0a758a 100644 --- a/include/xrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.h +++ b/include/xrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanBrokerCoverWithdraw : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanBrokerCoverWithdraw(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanBrokerDelete.h b/include/xrpl/tx/transactors/lending/LoanBrokerDelete.h index 0ce5f29387..ca58fc75bd 100644 --- a/include/xrpl/tx/transactors/lending/LoanBrokerDelete.h +++ b/include/xrpl/tx/transactors/lending/LoanBrokerDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanBrokerDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanBrokerDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanBrokerSet.h b/include/xrpl/tx/transactors/lending/LoanBrokerSet.h index 75175e2dd6..6c07740f9a 100644 --- a/include/xrpl/tx/transactors/lending/LoanBrokerSet.h +++ b/include/xrpl/tx/transactors/lending/LoanBrokerSet.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanBrokerSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanBrokerSet(ApplyContext& ctx) : Transactor(ctx) { @@ -29,7 +29,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanDelete.h b/include/xrpl/tx/transactors/lending/LoanDelete.h index 9e8c3c172a..6f9d3ed5f0 100644 --- a/include/xrpl/tx/transactors/lending/LoanDelete.h +++ b/include/xrpl/tx/transactors/lending/LoanDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanManage.h b/include/xrpl/tx/transactors/lending/LoanManage.h index d2344c0ec0..c01d25e428 100644 --- a/include/xrpl/tx/transactors/lending/LoanManage.h +++ b/include/xrpl/tx/transactors/lending/LoanManage.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanManage : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanManage(ApplyContext& ctx) : Transactor(ctx) { @@ -60,7 +60,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanPay.h b/include/xrpl/tx/transactors/lending/LoanPay.h index 9be9695c64..6c2aa0ec47 100644 --- a/include/xrpl/tx/transactors/lending/LoanPay.h +++ b/include/xrpl/tx/transactors/lending/LoanPay.h @@ -7,7 +7,7 @@ namespace xrpl { class LoanPay : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanPay(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/lending/LoanSet.h b/include/xrpl/tx/transactors/lending/LoanSet.h index d277629e44..e926c927fb 100644 --- a/include/xrpl/tx/transactors/lending/LoanSet.h +++ b/include/xrpl/tx/transactors/lending/LoanSet.h @@ -8,7 +8,7 @@ namespace xrpl { class LoanSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LoanSet(ApplyContext& ctx) : Transactor(ctx) { @@ -39,7 +39,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -50,16 +53,16 @@ public: beast::Journal const& j) override; public: - static constexpr std::uint32_t kMinPaymentTotal = 1; - static constexpr std::uint32_t kDefaultPaymentTotal = 1; - static_assert(kDefaultPaymentTotal >= kMinPaymentTotal); + static std::uint32_t constexpr kMIN_PAYMENT_TOTAL = 1; + static std::uint32_t constexpr kDEFAULT_PAYMENT_TOTAL = 1; + static_assert(kDEFAULT_PAYMENT_TOTAL >= kMIN_PAYMENT_TOTAL); - static constexpr std::uint32_t kMinPaymentInterval = 60; - static constexpr std::uint32_t kDefaultPaymentInterval = 60; - static_assert(kDefaultPaymentInterval >= kMinPaymentInterval); + static std::uint32_t constexpr kMIN_PAYMENT_INTERVAL = 60; + static std::uint32_t constexpr kDEFAULT_PAYMENT_INTERVAL = 60; + static_assert(kDEFAULT_PAYMENT_INTERVAL >= kMIN_PAYMENT_INTERVAL); - static constexpr std::uint32_t kDefaultGracePeriod = 60; - static_assert(kDefaultGracePeriod >= kMinPaymentInterval); + static std::uint32_t constexpr kDEFAULT_GRACE_PERIOD = 60; + static_assert(kDEFAULT_GRACE_PERIOD >= kMIN_PAYMENT_INTERVAL); }; //------------------------------------------------------------------------------ diff --git a/include/xrpl/tx/transactors/nft/NFTokenAcceptOffer.h b/include/xrpl/tx/transactors/nft/NFTokenAcceptOffer.h index c5cd10fa6a..7c77b02277 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenAcceptOffer.h +++ b/include/xrpl/tx/transactors/nft/NFTokenAcceptOffer.h @@ -11,16 +11,16 @@ private: pay(AccountID const& from, AccountID const& to, STAmount const& amount); TER - acceptOffer(SLE::ref offer); + acceptOffer(std::shared_ptr const& offer); TER - bridgeOffers(SLE::ref buy, SLE::ref sell); + bridgeOffers(std::shared_ptr const& buy, std::shared_ptr const& sell); TER transferNFToken(AccountID const& buyer, AccountID const& seller, uint256 const& nfTokenID); public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenAcceptOffer(ApplyContext& ctx) : Transactor(ctx) { @@ -36,7 +36,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/nft/NFTokenBurn.h b/include/xrpl/tx/transactors/nft/NFTokenBurn.h index 849d09cb7e..075bcc59ce 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenBurn.h +++ b/include/xrpl/tx/transactors/nft/NFTokenBurn.h @@ -7,7 +7,7 @@ namespace xrpl { class NFTokenBurn : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenBurn(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/nft/NFTokenCancelOffer.h b/include/xrpl/tx/transactors/nft/NFTokenCancelOffer.h index a74a1c3e59..f78c29dfe5 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenCancelOffer.h +++ b/include/xrpl/tx/transactors/nft/NFTokenCancelOffer.h @@ -7,7 +7,7 @@ namespace xrpl { class NFTokenCancelOffer : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenCancelOffer(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/nft/NFTokenCreateOffer.h b/include/xrpl/tx/transactors/nft/NFTokenCreateOffer.h index c874381dd0..bdb76e1c44 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenCreateOffer.h +++ b/include/xrpl/tx/transactors/nft/NFTokenCreateOffer.h @@ -7,7 +7,7 @@ namespace xrpl { class NFTokenCreateOffer : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenCreateOffer(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/nft/NFTokenMint.h b/include/xrpl/tx/transactors/nft/NFTokenMint.h index 9267e8e801..5274e1b4b8 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenMint.h +++ b/include/xrpl/tx/transactors/nft/NFTokenMint.h @@ -9,7 +9,7 @@ namespace xrpl { class NFTokenMint : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenMint(ApplyContext& ctx) : Transactor(ctx) { @@ -31,7 +31,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/nft/NFTokenModify.h b/include/xrpl/tx/transactors/nft/NFTokenModify.h index 0d18e4a6d4..6d3bac49f5 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenModify.h +++ b/include/xrpl/tx/transactors/nft/NFTokenModify.h @@ -7,7 +7,7 @@ namespace xrpl { class NFTokenModify : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit NFTokenModify(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/oracle/OracleDelete.h b/include/xrpl/tx/transactors/oracle/OracleDelete.h index c16d5fb2a9..85ca9a2a88 100644 --- a/include/xrpl/tx/transactors/oracle/OracleDelete.h +++ b/include/xrpl/tx/transactors/oracle/OracleDelete.h @@ -16,7 +16,7 @@ namespace xrpl { class OracleDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit OracleDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -43,7 +46,11 @@ public: beast::Journal const& j) override; static TER - deleteOracle(ApplyView& view, SLE::ref sle, AccountID const& account, beast::Journal j); + deleteOracle( + ApplyView& view, + std::shared_ptr const& sle, + AccountID const& account, + beast::Journal j); }; } // namespace xrpl diff --git a/include/xrpl/tx/transactors/oracle/OracleSet.h b/include/xrpl/tx/transactors/oracle/OracleSet.h index 831c11b8c4..7bedf9c837 100644 --- a/include/xrpl/tx/transactors/oracle/OracleSet.h +++ b/include/xrpl/tx/transactors/oracle/OracleSet.h @@ -16,7 +16,7 @@ namespace xrpl { class OracleSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit OracleSet(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/payment/DepositPreauth.h b/include/xrpl/tx/transactors/payment/DepositPreauth.h index 742b1ef3f7..365ba157a5 100644 --- a/include/xrpl/tx/transactors/payment/DepositPreauth.h +++ b/include/xrpl/tx/transactors/payment/DepositPreauth.h @@ -7,7 +7,7 @@ namespace xrpl { class DepositPreauth : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit DepositPreauth(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/payment/Payment.h b/include/xrpl/tx/transactors/payment/Payment.h index 14897b4efe..4ad870ce3f 100644 --- a/include/xrpl/tx/transactors/payment/Payment.h +++ b/include/xrpl/tx/transactors/payment/Payment.h @@ -7,13 +7,13 @@ namespace xrpl { class Payment : public Transactor { /* The largest number of paths we allow */ - static std::size_t const kMaxPathSize = 6; + static std::size_t const kMAX_PATH_SIZE = 6; /* The longest path we allow */ - static std::size_t const kMaxPathLength = 8; + static std::size_t const kMAX_PATH_LENGTH = 8; public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; explicit Payment(ApplyContext& ctx) : Transactor(ctx) { @@ -41,7 +41,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/payment_channel/PaymentChannelClaim.h b/include/xrpl/tx/transactors/payment_channel/PaymentChannelClaim.h index e13fea6d6c..d5e8235d31 100644 --- a/include/xrpl/tx/transactors/payment_channel/PaymentChannelClaim.h +++ b/include/xrpl/tx/transactors/payment_channel/PaymentChannelClaim.h @@ -7,7 +7,7 @@ namespace xrpl { class PaymentChannelClaim : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit PaymentChannelClaim(ApplyContext& ctx) : Transactor(ctx) { @@ -29,7 +29,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/payment_channel/PaymentChannelCreate.h b/include/xrpl/tx/transactors/payment_channel/PaymentChannelCreate.h index 56e984cd57..94a43ea165 100644 --- a/include/xrpl/tx/transactors/payment_channel/PaymentChannelCreate.h +++ b/include/xrpl/tx/transactors/payment_channel/PaymentChannelCreate.h @@ -7,7 +7,7 @@ namespace xrpl { class PaymentChannelCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; explicit PaymentChannelCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/payment_channel/PaymentChannelFund.h b/include/xrpl/tx/transactors/payment_channel/PaymentChannelFund.h index 272076ff20..3f16cf1ec1 100644 --- a/include/xrpl/tx/transactors/payment_channel/PaymentChannelFund.h +++ b/include/xrpl/tx/transactors/payment_channel/PaymentChannelFund.h @@ -7,7 +7,7 @@ namespace xrpl { class PaymentChannelFund : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; explicit PaymentChannelFund(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.h b/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.h index 88883fb86f..4aaff83a7a 100644 --- a/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.h +++ b/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class PermissionedDomainDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit PermissionedDomainDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -24,7 +24,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.h b/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.h index 4afa8cef5a..820b36688c 100644 --- a/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.h +++ b/include/xrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.h @@ -7,7 +7,7 @@ namespace xrpl { class PermissionedDomainSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit PermissionedDomainSet(ApplyContext& ctx) : Transactor(ctx) { @@ -27,7 +27,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/system/Batch.h b/include/xrpl/tx/transactors/system/Batch.h index 43f0103319..b1af9a2f86 100644 --- a/include/xrpl/tx/transactors/system/Batch.h +++ b/include/xrpl/tx/transactors/system/Batch.h @@ -9,7 +9,7 @@ namespace xrpl { class Batch : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit Batch(ApplyContext& ctx) : Transactor(ctx) { @@ -34,7 +34,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -44,7 +47,7 @@ public: ReadView const& view, beast::Journal const& j) override; - static constexpr auto kDisabledTxTypes = std::to_array({ + static constexpr auto kDISABLED_TX_TYPES = std::to_array({ ttVAULT_CREATE, ttVAULT_SET, ttVAULT_DELETE, diff --git a/include/xrpl/tx/transactors/system/Change.h b/include/xrpl/tx/transactors/system/Change.h index 339723ae8e..fc68fd55c2 100644 --- a/include/xrpl/tx/transactors/system/Change.h +++ b/include/xrpl/tx/transactors/system/Change.h @@ -7,7 +7,7 @@ namespace xrpl { class Change : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit Change(ApplyContext& ctx) : Transactor(ctx) { @@ -19,7 +19,10 @@ public: preCompute() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/system/LedgerStateFix.h b/include/xrpl/tx/transactors/system/LedgerStateFix.h index 973f89faa9..72ad8196c1 100644 --- a/include/xrpl/tx/transactors/system/LedgerStateFix.h +++ b/include/xrpl/tx/transactors/system/LedgerStateFix.h @@ -9,10 +9,9 @@ class LedgerStateFix : public Transactor public: enum class FixType : std::uint16_t { NfTokenPageLink = 1, - BookExchangeRate = 2, }; - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit LedgerStateFix(ApplyContext& ctx) : Transactor(ctx) { @@ -31,7 +30,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/system/TicketCreate.h b/include/xrpl/tx/transactors/system/TicketCreate.h index 5783faa6d1..fc1743236f 100644 --- a/include/xrpl/tx/transactors/system/TicketCreate.h +++ b/include/xrpl/tx/transactors/system/TicketCreate.h @@ -7,9 +7,9 @@ namespace xrpl { class TicketCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Custom; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Custom}; - static constexpr std::uint32_t kMinValidCount = 1; + constexpr static std::uint32_t kMIN_VALID_COUNT = 1; // A note on how the maxValidCount was determined. The goal is for // a single TicketCreate transaction to not use more compute power than @@ -31,7 +31,7 @@ public: // about the same compute time as a single compute-intensive payment. // // October 2018. - static constexpr std::uint32_t kMaxValidCount = 250; + constexpr static std::uint32_t kMAX_VALID_COUNT = 250; // The maximum number of Tickets an account may hold. If a // TicketCreate would cause an account to own more than this many @@ -39,7 +39,7 @@ public: // // The number was chosen arbitrarily and is an effort toward avoiding // ledger-stuffing with Tickets. - static constexpr std::uint32_t kMaxTicketThreshold = 250; + constexpr static std::uint32_t kMAX_TICKET_THRESHOLD = 250; explicit TicketCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -61,7 +61,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/Clawback.h b/include/xrpl/tx/transactors/token/Clawback.h index ed90776e59..e21f98bd7a 100644 --- a/include/xrpl/tx/transactors/token/Clawback.h +++ b/include/xrpl/tx/transactors/token/Clawback.h @@ -7,7 +7,7 @@ namespace xrpl { class Clawback : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit Clawback(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/ConfidentialMPTClawback.h b/include/xrpl/tx/transactors/token/ConfidentialMPTClawback.h index ff6f76e8ea..4724b4c77b 100644 --- a/include/xrpl/tx/transactors/token/ConfidentialMPTClawback.h +++ b/include/xrpl/tx/transactors/token/ConfidentialMPTClawback.h @@ -23,7 +23,7 @@ namespace xrpl { class ConfidentialMPTClawback : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit ConfidentialMPTClawback(ApplyContext& ctx) : Transactor(ctx) { diff --git a/include/xrpl/tx/transactors/token/ConfidentialMPTConvert.h b/include/xrpl/tx/transactors/token/ConfidentialMPTConvert.h index 2e2591844f..af0da27d81 100644 --- a/include/xrpl/tx/transactors/token/ConfidentialMPTConvert.h +++ b/include/xrpl/tx/transactors/token/ConfidentialMPTConvert.h @@ -25,7 +25,7 @@ namespace xrpl { class ConfidentialMPTConvert : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit ConfidentialMPTConvert(ApplyContext& ctx) : Transactor(ctx) { diff --git a/include/xrpl/tx/transactors/token/ConfidentialMPTConvertBack.h b/include/xrpl/tx/transactors/token/ConfidentialMPTConvertBack.h index cb4b6295a0..10a7a2a55f 100644 --- a/include/xrpl/tx/transactors/token/ConfidentialMPTConvertBack.h +++ b/include/xrpl/tx/transactors/token/ConfidentialMPTConvertBack.h @@ -26,7 +26,7 @@ namespace xrpl { class ConfidentialMPTConvertBack : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit ConfidentialMPTConvertBack(ApplyContext& ctx) : Transactor(ctx) { diff --git a/include/xrpl/tx/transactors/token/ConfidentialMPTMergeInbox.h b/include/xrpl/tx/transactors/token/ConfidentialMPTMergeInbox.h index 585c273e12..c371a811b9 100644 --- a/include/xrpl/tx/transactors/token/ConfidentialMPTMergeInbox.h +++ b/include/xrpl/tx/transactors/token/ConfidentialMPTMergeInbox.h @@ -27,7 +27,7 @@ namespace xrpl { class ConfidentialMPTMergeInbox : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit ConfidentialMPTMergeInbox(ApplyContext& ctx) : Transactor(ctx) { diff --git a/include/xrpl/tx/transactors/token/ConfidentialMPTSend.h b/include/xrpl/tx/transactors/token/ConfidentialMPTSend.h index 72599ab987..b3d959e535 100644 --- a/include/xrpl/tx/transactors/token/ConfidentialMPTSend.h +++ b/include/xrpl/tx/transactors/token/ConfidentialMPTSend.h @@ -33,7 +33,7 @@ namespace xrpl { class ConfidentialMPTSend : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit ConfidentialMPTSend(ApplyContext& ctx) : Transactor(ctx) { diff --git a/include/xrpl/tx/transactors/token/MPTokenAuthorize.h b/include/xrpl/tx/transactors/token/MPTokenAuthorize.h index e30d123e52..29cdda275a 100644 --- a/include/xrpl/tx/transactors/token/MPTokenAuthorize.h +++ b/include/xrpl/tx/transactors/token/MPTokenAuthorize.h @@ -16,7 +16,7 @@ struct MPTAuthorizeArgs class MPTokenAuthorize : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit MPTokenAuthorize(ApplyContext& ctx) : Transactor(ctx) { @@ -35,7 +35,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h index a706c71e18..0107c11598 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h @@ -6,33 +6,28 @@ namespace xrpl { -// NOLINTBEGIN(readability-redundant-member-init) struct MPTCreateArgs { std::optional priorBalance; AccountID const& account; std::uint32_t sequence = 0; std::uint32_t flags = 0; - std::optional maxAmount = std::nullopt; - std::optional assetScale = std::nullopt; - std::optional transferFee = std::nullopt; + std::optional maxAmount = + std::nullopt; // NOLINT(readability-redundant-member-init) + std::optional assetScale = + std::nullopt; // NOLINT(readability-redundant-member-init) + std::optional transferFee = + std::nullopt; // NOLINT(readability-redundant-member-init) std::optional const& metadata{}; - std::optional domainId = std::nullopt; - std::optional mutableFlags = std::nullopt; - // Set only by callers that issue an MPT representing a wrapped asset - // (e.g. VaultCreate's share token). The keylet must point to an - // existing MPToken or RippleState owned by `account`. Surfaces on - // the resulting MPTokenIssuance via the optional sfReferenceHolding - // field. Used by readers (canTransfer, canTrade, freezing) to - // inherit the underlying asset's transferability. - std::optional referenceHolding = std::nullopt; + std::optional domainId = std::nullopt; // NOLINT(readability-redundant-member-init) + std::optional mutableFlags = + std::nullopt; // NOLINT(readability-redundant-member-init) }; -// NOLINTEND(readability-redundant-member-init) class MPTokenIssuanceCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit MPTokenIssuanceCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -51,7 +46,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceDestroy.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceDestroy.h index 21032e7337..8e2a4c3dcd 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceDestroy.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceDestroy.h @@ -7,7 +7,7 @@ namespace xrpl { class MPTokenIssuanceDestroy : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit MPTokenIssuanceDestroy(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h index 6a6d1fc445..e15027ab5e 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h @@ -7,7 +7,7 @@ namespace xrpl { class MPTokenIssuanceSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit MPTokenIssuanceSet(ApplyContext& ctx) : Transactor(ctx) { @@ -32,7 +32,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/token/TrustSet.h b/include/xrpl/tx/transactors/token/TrustSet.h index dcf454bea1..e99d599fe4 100644 --- a/include/xrpl/tx/transactors/token/TrustSet.h +++ b/include/xrpl/tx/transactors/token/TrustSet.h @@ -8,7 +8,7 @@ namespace xrpl { class TrustSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit TrustSet(ApplyContext& ctx) : Transactor(ctx) { @@ -30,7 +30,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/vault/VaultClawback.h b/include/xrpl/tx/transactors/vault/VaultClawback.h index b8032809ee..4f0328aa4f 100644 --- a/include/xrpl/tx/transactors/vault/VaultClawback.h +++ b/include/xrpl/tx/transactors/vault/VaultClawback.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultClawback : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultClawback(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( @@ -36,8 +39,8 @@ public: private: Expected, TER> assetsToClawback( - SLE::ref vault, - SLE::const_ref sleShareIssuance, + std::shared_ptr const& vault, + std::shared_ptr const& sleShareIssuance, AccountID const& holder, STAmount const& clawbackAmount); }; diff --git a/include/xrpl/tx/transactors/vault/VaultCreate.h b/include/xrpl/tx/transactors/vault/VaultCreate.h index 9b11f97957..61b3e552cc 100644 --- a/include/xrpl/tx/transactors/vault/VaultCreate.h +++ b/include/xrpl/tx/transactors/vault/VaultCreate.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultCreate : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultCreate(ApplyContext& ctx) : Transactor(ctx) { @@ -29,7 +29,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/vault/VaultDelete.h b/include/xrpl/tx/transactors/vault/VaultDelete.h index b8bb3c4096..9a75fcebac 100644 --- a/include/xrpl/tx/transactors/vault/VaultDelete.h +++ b/include/xrpl/tx/transactors/vault/VaultDelete.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultDelete : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultDelete(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/vault/VaultDeposit.h b/include/xrpl/tx/transactors/vault/VaultDeposit.h index 523b3f2e53..21dc1749e2 100644 --- a/include/xrpl/tx/transactors/vault/VaultDeposit.h +++ b/include/xrpl/tx/transactors/vault/VaultDeposit.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultDeposit : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultDeposit(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/vault/VaultSet.h b/include/xrpl/tx/transactors/vault/VaultSet.h index 5c362d5db4..59a9639126 100644 --- a/include/xrpl/tx/transactors/vault/VaultSet.h +++ b/include/xrpl/tx/transactors/vault/VaultSet.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultSet : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultSet(ApplyContext& ctx) : Transactor(ctx) { @@ -26,7 +26,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/include/xrpl/tx/transactors/vault/VaultWithdraw.h b/include/xrpl/tx/transactors/vault/VaultWithdraw.h index 7bbe06187d..f9b7665fd6 100644 --- a/include/xrpl/tx/transactors/vault/VaultWithdraw.h +++ b/include/xrpl/tx/transactors/vault/VaultWithdraw.h @@ -7,7 +7,7 @@ namespace xrpl { class VaultWithdraw : public Transactor { public: - static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; + static constexpr ConsequencesFactoryType kCONSEQUENCES_FACTORY{Normal}; explicit VaultWithdraw(ApplyContext& ctx) : Transactor(ctx) { @@ -23,7 +23,10 @@ public: doApply() override; void - visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override; + visitInvariantEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) override; [[nodiscard]] bool finalizeInvariants( diff --git a/nix/ci-env.nix b/nix/ci-env.nix deleted file mode 100644 index 0d617913d9..0000000000 --- a/nix/ci-env.nix +++ /dev/null @@ -1,118 +0,0 @@ -{ - pkgs, - customGlibc, - ... -}: -let - inherit (import ./packages.nix { inherit pkgs; }) commonPackages; - inherit (pkgs) lib; - - # Underlying compiler toolchains to wrap. Bump these in one place to - # roll the whole environment forward. - customGccPackage = pkgs.gcc15; - customLlvmPackages = pkgs.llvmPackages_22; - customClangMajor = lib.versions.major (lib.getVersion customLlvmPackages.clang-unwrapped); - - # binutils wrapped to emit binaries that reference the custom glibc - # (dynamic linker path, library search path, RPATH). - customBinutils = pkgs.wrapBintoolsWith { - bintools = pkgs.binutils-unwrapped; - libc = customGlibc; - }; - - # Rebuild gcc (specifically libstdc++ / libgcc_s) against the custom - # glibc. The override swaps gcc.cc's bootstrap stdenv for one that uses - # the existing gcc binary but links against the custom glibc, so the - # resulting compiler ships runtime libraries that only reference symbols - # available in that glibc. - customGccCc = customGccPackage.cc.override { - stdenv = pkgs.stdenvAdapters.overrideCC pkgs.stdenv ( - pkgs.wrapCCWith { - cc = customGccPackage.cc; - libc = customGlibc; - bintools = customBinutils; - } - ); - }; - - # cc-wrapper around the rebuilt compiler, pointing at the custom glibc - # headers and libraries. This is what we actually expose to users. - customGcc = pkgs.wrapCCWith { - cc = customGccCc; - libc = customGlibc; - bintools = customBinutils; - }; - - # stdenv built around the rebuilt gcc / custom glibc. Used to rebuild - # compiler-rt below so its sanitizer runtimes see the custom glibc - # headers. - customStdenv = pkgs.stdenvAdapters.overrideCC pkgs.stdenv customGcc; - - # Rebuild compiler-rt against the custom glibc so the sanitizer runtimes - # don't use glibc symbols (or sysconf constants like _SC_SIGSTKSZ) that - # only exist in newer glibc versions. scudo is dropped because its CMake - # includes CheckAtomic with -nostdinc++ in CMAKE_REQUIRED_FLAGS, which - # makes std::atomic unfindable in our stdenv; we don't use scudo (only - # asan/ubsan/tsan etc.). - customCompilerRt = - (customLlvmPackages.compiler-rt.override { - stdenv = customStdenv; - }).overrideAttrs - (old: { - postPatch = (old.postPatch or "") + '' - substituteInPlace lib/CMakeLists.txt \ - --replace-quiet 'add_subdirectory(scudo/standalone)' \ - '# scudo/standalone disabled in xrpld ci-env' - ''; - }); - - # cc-wrapper around clang, pointing at the custom glibc headers and - # libraries. Reuses the rebuilt gcc for libstdc++ / libgcc_s so that - # C++ binaries produced by clang also only reference symbols available - # in the custom glibc. compiler-rt is wired into a resource-root so - # sanitizer runtimes (libclang_rt.*.a) are found at link time; this - # mirrors what nixpkgs does internally when building llvmPackages.clang. - customClang = pkgs.wrapCCWith { - cc = customLlvmPackages.clang-unwrapped; - libc = customGlibc; - bintools = customBinutils; - gccForLibs = customGccCc; - extraPackages = [ customCompilerRt ]; - extraBuildCommands = '' - rsrc="$out/resource-root" - mkdir "$rsrc" - ln -s "${customLlvmPackages.clang-unwrapped.lib}/lib/clang/${customClangMajor}/include" "$rsrc/include" - ln -s "${customCompilerRt.out}/lib" "$rsrc/lib" - ln -s "${customCompilerRt.out}/share" "$rsrc/share" || true - echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags - ''; - }; - - # Strip the generic cc/c++/cpp symlinks from the clang wrapper so it can - # coexist with the gcc wrapper in buildEnv. gcc remains the default - # compiler (cc/c++/cpp); clang is invoked explicitly as clang/clang++. - customClangForCiEnv = pkgs.symlinkJoin { - name = "clang-wrapper-custom-for-ci-env"; - paths = [ customClang ]; - postBuild = '' - rm -f $out/bin/cc $out/bin/c++ $out/bin/cpp - ''; - }; - -in -{ - default = pkgs.buildEnv { - name = "xrpld-ci-env"; - paths = commonPackages ++ [ - customGcc - customClangForCiEnv - customBinutils - ]; - pathsToLink = [ - "/bin" - "/lib" - "/include" - "/share" - ]; - }; -} diff --git a/nix/devshell.nix b/nix/devshell.nix index 1bd7ea4c0c..1d907f4d87 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -1,6 +1,19 @@ { pkgs, ... }: let - inherit (import ./packages.nix { inherit pkgs; }) commonPackages; + commonPackages = with pkgs; [ + ccache + cmake + conan + gcovr + git + gnumake + llvmPackages_21.clang-tools + ninja + perl # needed for openssl + pkg-config + pre-commit + python314 + ]; # Supported compiler versions gccVersion = pkgs.lib.range 13 15; diff --git a/nix/packages.nix b/nix/packages.nix deleted file mode 100644 index d209620a68..0000000000 --- a/nix/packages.nix +++ /dev/null @@ -1,28 +0,0 @@ -{ pkgs }: -let - # In LLVM 22, run-clang-tidy.py moved from share/clang/ to bin/, so nixpkgs - # clang-tools no longer links it. Wrap it manually. - runClangTidy = pkgs.writeShellScriptBin "run-clang-tidy" '' - exec ${pkgs.python3}/bin/python3 ${pkgs.llvmPackages_22.clang-unwrapped}/bin/run-clang-tidy "$@" - ''; -in -{ - commonPackages = with pkgs; [ - ccache - cmake - conan - gcovr - git - gnumake - llvmPackages_22.clang-tools - mold - ninja - patchelf - perl # needed for openssl - pkg-config - pre-commit - python3 - runClangTidy - vim - ]; -} diff --git a/nix/utils.nix b/nix/utils.nix index d83e612c16..821d60a6f6 100644 --- a/nix/utils.nix +++ b/nix/utils.nix @@ -1,21 +1,19 @@ -{ nixpkgs, nixpkgs-custom-glibc }: -function: -nixpkgs.lib.genAttrs - [ - "x86_64-linux" - "aarch64-linux" - "x86_64-darwin" - "aarch64-darwin" - ] - ( - system: - function { - pkgs = import nixpkgs { inherit system; }; - # glibc 2.31 — matches the system libc on Ubuntu 20.04 LTS. Sourced - # from the nixpkgs snapshot pinned via the `nixpkgs-custom-glibc` - # flake input, so the build uses the compiler from that snapshot - # (gcc 9.3.0) along with the matching patches, configure flags, and - # hardening defaults. - customGlibc = (import nixpkgs-custom-glibc { inherit system; }).glibc; - } - ) +{ nixpkgs }: +{ + forEachSystem = + function: + nixpkgs.lib.genAttrs + [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ] + ( + system: + function { + inherit system; + pkgs = import nixpkgs { inherit system; }; + } + ); +} diff --git a/package/README.md b/package/README.md deleted file mode 100644 index 867ca273b4..0000000000 --- a/package/README.md +++ /dev/null @@ -1,175 +0,0 @@ -# Linux Packaging - -This directory contains all files needed to build RPM and Debian packages for `xrpld`. - -## Directory layout - -``` -package/ - build_pkg.sh Staging and build script (called by CMake targets and CI) - rpm/ - xrpld.spec RPM spec (xrpld_version/pkg_release passed via rpmbuild --define) - debian/ Debian control files (control, rules, install, links, conffiles, ...) - shared/ - xrpld.service systemd unit file (used by both RPM and DEB) - xrpld.sysusers sysusers.d config (used by both RPM and DEB) - xrpld.tmpfiles tmpfiles.d config (used by both RPM and DEB) - xrpld.logrotate logrotate config (installed to /etc/logrotate.d/xrpld) - update-xrpld auto-update script (installed to /usr/libexec/xrpld/, run by update-xrpld.timer) -``` - -## Prerequisites - -Packaging targets and their container images are declared in -[`.github/scripts/strategy-matrix/linux.json`](../.github/scripts/strategy-matrix/linux.json) -via a `"package": true` field on specific os entries. Today only -`linux/amd64` is emitted; the architecture is hardcoded in `generate.py` -and the workflow runner. The package format -(deb or rpm) is inferred at build time from the container's package manager -(`apt-get` -> deb, `dnf`/`yum` -> rpm). The image tag is composed as -`ghcr.io/xrplf/ci/{distro}-{version}:{compiler}-{cver}-sha-{image_sha}` — -the same scheme used by `reusable-build-test.yml`. Bump `image_sha` in -`linux.json` and both CI and local builds pick up the new image with no -workflow edits. - -| Package type | Image (derived from `linux.json`) | Tool required | -| ------------ | ---------------------------------------------------- | --------------------------------------------------------------- | -| RPM | `ghcr.io/xrplf/ci/rhel-9:gcc-12-sha-` | `rpmbuild` | -| DEB | `ghcr.io/xrplf/ci/ubuntu-jammy:gcc-12-sha-` | `dpkg-buildpackage`, `debhelper (>= 13)`, `dh-sequence-systemd` | - -To print the exact image tags for the current `linux.json`: - -```bash -./.github/scripts/strategy-matrix/generate.py --packaging --config=.github/scripts/strategy-matrix/linux.json -``` - -## Building packages - -### Via CI - -Caller workflows (`on-pr.yml`, `on-tag.yml`, `on-trigger.yml`) call -`reusable-strategy-matrix.yml` with `mode: packaging` to generate the matrix of -`{artifact_name, os}` entries, then fan out to -`reusable-package.yml` per entry. That workflow downloads the pre-built `xrpld` -binary artifact, detects the package format from the container, and calls -`build_pkg.sh` directly — no CMake configure or build step is needed inside -the packaging job. - -### Locally (mirrors CI) - -With an `xrpld` binary already built at `build/xrpld`, run the packaging step -inside the same container CI uses. The image tag is derived from `linux.json` -so you don't need to hardcode a SHA. - -```bash -# From the repo root. Pick any image flagged with `"package": true` in -# linux.json; the package format is inferred from the container's package -# manager. Example for the rpm-producing image: -IMAGE=$(jq -r ' - .os | map(select(.package == true))[0] | - "ghcr.io/xrplf/ci/\(.distro_name)-\(.distro_version):\(.compiler_name)-\(.compiler_version)-sha-\(.image_sha)" -' .github/scripts/strategy-matrix/linux.json) - -VERSION=2.4.0-local -PKG_RELEASE=1 - -docker run --rm \ - -v "$(pwd):/src" \ - -w /src \ - "$IMAGE" \ - ./package/build_pkg.sh --pkg-version "$VERSION" --pkg-release "$PKG_RELEASE" - -# Output: -# build/debbuild/*.deb (DEB + dbgsym .ddeb) -# build/rpmbuild/RPMS/x86_64/*.rpm -``` - -### Via CMake (host-side target) - -If you run CMake configure on a host that has `rpmbuild` or `dpkg-buildpackage` -installed natively, you can use the CMake target directly — no container -needed, but the host toolchain replaces the pinned CI image: - -```bash -cmake \ - -Dxrpld=ON \ - -Dxrpld_version=2.4.0-local \ - -Dtests=OFF \ - .. - -cmake --build . --target package # deb on Debian/Ubuntu, rpm on RHEL -``` - -The `cmake/XrplPackaging.cmake` module defines the target only if at least one -of `rpmbuild` / `dpkg-buildpackage` is present; `build_pkg.sh` then infers the -package format from the host's package manager. The packaging script installs -to FHS-standard paths (`/usr/bin`, `/etc/xrpld`, etc.) regardless of -`CMAKE_INSTALL_PREFIX`. - -## How `build_pkg.sh` works - -`build_pkg.sh` accepts long-form flags, each of which can also be set via an -environment variable. Flags override env vars; env vars override the built-in -defaults. Run `./package/build_pkg.sh --help` for the same table: - -| Flag | Env var | Default | Purpose | -| -------------------------- | ------------------- | ----------------------------- | ----------------------------------- | -| `--src-dir DIR` | `SRC_DIR` | `$PWD` | repo root | -| `--build-dir DIR` | `BUILD_DIR` | `$PWD/build` | directory holding pre-built `xrpld` | -| `--pkg-version STR` | `PKG_VERSION` | parsed from `xrpld --version` | version string, e.g. `3.2.0-b1` | -| `--pkg-release N` | `PKG_RELEASE` | `1` | package release number | -| `--source-date-epoch SECS` | `SOURCE_DATE_EPOCH` | latest git commit ctime | reproducibility timestamp | - -The package format (`deb` or `rpm`) is inferred from the host's package -manager (`apt-get` -> deb, `dnf`/`yum` -> rpm). Hosts without one of those -fail early. - -Flags are for explicit invocation; environment variables are intended for -CMake/systemd/CI integration. The CI workflow and the CMake `package` target -both invoke `build_pkg.sh` with no flags, configuring it entirely via env -(see `cmake/XrplPackaging.cmake`). - -It resolves `SRC_DIR` and `BUILD_DIR` to absolute paths, then calls -`stage_common()` to copy the binary, config files, and shared support files -into the staging area, and invokes the platform build tool. - -### RPM - -1. Creates the standard `rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}` tree inside the build directory. -2. Copies `xrpld.spec` and all source files (binary, configs, service files) into `SOURCES/`. -3. Runs `rpmbuild -bb --define "xrpld_version ..." --define "pkg_release ..."`. The spec uses manual `install` commands to place files. -4. Output: `rpmbuild/RPMS/x86_64/xrpld-*.rpm` - -### DEB - -1. Creates a staging source tree at `debbuild/source/` inside the build directory. -2. Stages the binary, configs, `README.md`, and `LICENSE.md`. -3. Copies `package/debian/` control files into `debbuild/source/debian/`. -4. Copies shared service/sysusers/tmpfiles into `debian/` where `dh_installsystemd`, `dh_installsysusers`, and `dh_installtmpfiles` pick them up automatically. -5. Generates a minimal `debian/changelog` (pre-release versions use `~` instead of `-`). -6. Runs `dpkg-buildpackage -b --no-sign`. `debian/rules` uses manual `install` commands. -7. Output: `debbuild/*.deb` and `debbuild/*.ddeb` (dbgsym package) - -## Post-build verification - -```bash -# DEB -dpkg-deb -c debbuild/*.deb | grep -E 'systemd|sysusers|tmpfiles' -lintian -I debbuild/*.deb - -# RPM -rpm -qlp rpmbuild/RPMS/x86_64/*.rpm -``` - -## Reproducibility - -The following environment variables improve build reproducibility. They are not -set automatically by `build_pkg.sh`; set them manually if needed: - -```bash -export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) -export TZ=UTC -export LC_ALL=C.UTF-8 -export GZIP=-n -export DEB_BUILD_OPTIONS="noautodbgsym reproducible=+fixfilepath" -``` diff --git a/package/build_pkg.sh b/package/build_pkg.sh deleted file mode 100755 index f2c2c63c12..0000000000 --- a/package/build_pkg.sh +++ /dev/null @@ -1,219 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Build an RPM or Debian package from a pre-built xrpld binary. -# -# Flags override env vars; env vars override defaults. Env vars are intended -# for CMake/systemd/CI integration; flags are for explicit invocation. - -usage() { - cat <<'EOF' -Usage: build_pkg.sh [options] - -Options (each can also be set via the env var shown): - --src-dir DIR repo root [SRC_DIR; default: $PWD] - --build-dir DIR directory holding xrpld [BUILD_DIR; default: $PWD/build] - --pkg-version STR version, e.g. 3.2.0-b1 [PKG_VERSION; default: parsed from xrpld --version] - --pkg-release N package release number [PKG_RELEASE; default: 1] - --source-date-epoch SECS reproducibility timestamp [SOURCE_DATE_EPOCH; default: latest git commit ctime] - -h, --help show this help and exit -EOF -} - -need_arg() { - if [[ $# -lt 2 || "$2" == --* ]]; then - echo "Missing value for $1" >&2 - exit 2 - fi -} - -# Seed from env. CLI parsing below overrides these directly. -SRC_DIR="${SRC_DIR:-}" -BUILD_DIR="${BUILD_DIR:-}" -PKG_VERSION="${PKG_VERSION:-}" -PKG_RELEASE="${PKG_RELEASE:-}" -SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-}" - -while [[ $# -gt 0 ]]; do - case "$1" in - --src-dir) - need_arg "$@" - SRC_DIR="$2" - shift 2 - ;; - --build-dir) - need_arg "$@" - BUILD_DIR="$2" - shift 2 - ;; - --pkg-version) - need_arg "$@" - PKG_VERSION="$2" - shift 2 - ;; - --pkg-release) - need_arg "$@" - PKG_RELEASE="$2" - shift 2 - ;; - --source-date-epoch) - need_arg "$@" - SOURCE_DATE_EPOCH="$2" - shift 2 - ;; - -h | --help) - usage - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - usage >&2 - exit 2 - ;; - esac -done - -SRC_DIR="$(cd "${SRC_DIR:-${PWD}}" && pwd)" -BUILD_DIR="$(cd "${BUILD_DIR:-${PWD}/build}" && pwd)" -PKG_RELEASE="${PKG_RELEASE:-1}" - -if [[ -z "${PKG_VERSION}" ]]; then - PKG_VERSION="$("${BUILD_DIR}/xrpld" --version | awk 'NR==1 {print $3; exit}')" -fi - -if [[ -z "${PKG_VERSION}" ]]; then - echo "PKG_VERSION is empty (not provided and could not be derived)." >&2 - exit 1 -fi - -VERSION="${PKG_VERSION}" - -if command -v apt-get >/dev/null 2>&1; then - pkg_type=deb -elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then - pkg_type=rpm -else - echo "Cannot infer pkg_type: no apt-get, dnf, or yum on PATH." >&2 - exit 1 -fi - -if [[ -z "${SOURCE_DATE_EPOCH}" ]]; then - if git -C "$SRC_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then - SOURCE_DATE_EPOCH="$(git -C "$SRC_DIR" log -1 --format=%ct)" - else - SOURCE_DATE_EPOCH="$(date +%s)" - fi -fi - -export SOURCE_DATE_EPOCH -CHANGELOG_DATE="$(date -u -R -d "@$SOURCE_DATE_EPOCH")" - -# Split VERSION at the first '-' into base and optional pre-release suffix. -# Examples: "3.2.0" -> ("3.2.0", ""); "3.2.0-b1" -> ("3.2.0", "b1"). -VER_BASE="${VERSION%%-*}" -VER_SUFFIX="${VERSION#*-}" -[[ "${VER_SUFFIX}" == "${VERSION}" ]] && VER_SUFFIX="" - -# Reject multi-segment suffixes (e.g. "beta-1", "rc1-15-gabc123"). The RPM -# Release field forbids '-', and the convention here is single-token suffixes -# like b1 or rc2. Fail early with a clear message rather than letting either -# rpmbuild blow up or silently mangling dashes into dots. -if [[ "${VER_SUFFIX}" == *-* ]]; then - echo "build_pkg.sh: multi-segment pre-release in VERSION='${VERSION}' (suffix '${VER_SUFFIX}')." >&2 - echo "Use single-token suffixes like 3.2.0-b1 or 3.2.0-rc2." >&2 - exit 1 -fi - -SHARED="${SRC_DIR}/package/shared" -DEBIAN_DIR="${SRC_DIR}/package/debian" - -# Stage files that both packaging systems consume using the same filenames. -stage_common() { - local dest="$1" - mkdir -p "${dest}" - - cp "${BUILD_DIR}/xrpld" "${dest}/xrpld" - cp "${SRC_DIR}/cfg/xrpld-example.cfg" "${dest}/xrpld.cfg" - cp "${SRC_DIR}/cfg/validators-example.txt" "${dest}/validators.txt" - cp "${SRC_DIR}/LICENSE.md" "${dest}/LICENSE.md" - cp "${SRC_DIR}/README.md" "${dest}/README.md" - - cp "${SHARED}/xrpld.service" "${dest}/xrpld.service" - cp "${SHARED}/xrpld.sysusers" "${dest}/xrpld.sysusers" - cp "${SHARED}/xrpld.tmpfiles" "${dest}/xrpld.tmpfiles" - cp "${SHARED}/xrpld.logrotate" "${dest}/xrpld.logrotate" - cp "${SHARED}/update-xrpld" "${dest}/update-xrpld" - cp "${SHARED}/update-xrpld.service" "${dest}/update-xrpld.service" - cp "${SHARED}/update-xrpld.timer" "${dest}/update-xrpld.timer" - cp "${SHARED}/50-xrpld.preset" "${dest}/50-xrpld.preset" -} - -build_rpm() { - local topdir="${BUILD_DIR}/rpmbuild" - rm -rf "${topdir}" - mkdir -p "${topdir}"/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} - - cp "${SRC_DIR}/package/rpm/xrpld.spec" "${topdir}/SPECS/xrpld.spec" - stage_common "${topdir}/SOURCES" - - # RPM Version can't contain '-'. A pre-release goes in Release with a - # leading "0." so 3.2.0-b1 sorts before the final 3.2.0-. - # The order is "0.." (e.g. 0.1.b6) — the Fedora/EPEL - # convention. Reversing to "0.." (e.g. 0.b6.1) breaks - # rpmvercmp against the former because numeric segments outrank alphabetic - # ones, so "0.1.b5" would sort newer than "0.b6.1". - local rpm_release="${PKG_RELEASE}" - [[ -n "${VER_SUFFIX}" ]] && rpm_release="0.${PKG_RELEASE}.${VER_SUFFIX}" - - set -x - rpmbuild -bb \ - --define "_topdir ${topdir}" \ - --define "xrpld_version ${VER_BASE}" \ - --define "xrpld_release ${rpm_release}" \ - "${topdir}/SPECS/xrpld.spec" -} - -build_deb() { - local staging="${BUILD_DIR}/debbuild/source" - rm -rf "${staging}" - mkdir -p "${staging}" - - stage_common "${staging}" - cp -r "${DEBIAN_DIR}" "${staging}/debian" - - # Debhelper auto-discovers these only from debian/. - cp "${staging}/xrpld.service" "${staging}/debian/xrpld.service" - cp "${staging}/xrpld.sysusers" "${staging}/debian/xrpld.sysusers" - cp "${staging}/xrpld.tmpfiles" "${staging}/debian/xrpld.tmpfiles" - cp "${staging}/xrpld.logrotate" "${staging}/debian/xrpld.logrotate" - cp "${staging}/update-xrpld.service" "${staging}/debian/xrpld.update-xrpld.service" - cp "${staging}/update-xrpld.timer" "${staging}/debian/xrpld.update-xrpld.timer" - - # Debian '~' marks a pre-release; 3.2.0~b1 sorts before 3.2.0. - local deb_full_version="${VER_BASE}${VER_SUFFIX:+~${VER_SUFFIX}}-${PKG_RELEASE}" - - # Derive release channel from the version suffix: - # (none) -> stable (tagged release) - # b0 -> develop (develop-branch build) - # b, rc -> unstable (pre-release) - local deb_distribution - case "${VER_SUFFIX}" in - "") deb_distribution="stable" ;; - b0) deb_distribution="develop" ;; - *) deb_distribution="unstable" ;; - esac - - cat >"${staging}/debian/changelog" < ${CHANGELOG_DATE} -EOF - - chmod +x "${staging}/debian/rules" - - set -x - (cd "${staging}" && dpkg-buildpackage -b --no-sign -d) -} - -"build_${pkg_type}" diff --git a/package/debian/control b/package/debian/control deleted file mode 100644 index 45d2acbbea..0000000000 --- a/package/debian/control +++ /dev/null @@ -1,23 +0,0 @@ -Source: xrpld -Section: net -Priority: optional -Maintainer: XRPL Foundation -Rules-Requires-Root: no -Build-Depends: - debhelper-compat (= 13) -Standards-Version: 4.7.0 -Homepage: https://github.com/XRPLF/rippled -Vcs-Git: https://github.com/XRPLF/rippled.git -Vcs-Browser: https://github.com/XRPLF/rippled - -Package: xrpld -Section: net -Priority: optional -Architecture: any -Depends: - ${shlibs:Depends}, - ${misc:Depends} -Description: XRP Ledger daemon - Reference implementation of the XRP Ledger protocol. - Participates in the peer-to-peer network, processes transactions, - and maintains a local ledger copy. diff --git a/package/debian/copyright b/package/debian/copyright deleted file mode 100644 index ddaa719e3a..0000000000 --- a/package/debian/copyright +++ /dev/null @@ -1,18 +0,0 @@ -Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: rippled -Source: https://github.com/XRPLF/rippled - -Files: * -Copyright: 2011-present, the XRP Ledger developers -License: ISC - Permission to use, copy, modify, and distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - . - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/package/debian/rules b/package/debian/rules deleted file mode 100644 index 612fe1b1a9..0000000000 --- a/package/debian/rules +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/make -f - -export DH_VERBOSE = 1 - -%: - dh $@ - -override_dh_auto_configure override_dh_auto_build override_dh_auto_test: - @: - -override_dh_installsystemd: - dh_installsystemd --no-stop-on-upgrade xrpld.service - dh_installsystemd --name=update-xrpld --no-enable --no-start update-xrpld.service update-xrpld.timer - -execute_before_dh_installtmpfiles: - dh_installsysusers - -override_dh_installsysusers: - -override_dh_install: - install -D -m 0755 xrpld debian/xrpld/usr/bin/xrpld - install -D -m 0644 xrpld.cfg debian/xrpld/etc/xrpld/xrpld.cfg - install -D -m 0644 validators.txt debian/xrpld/etc/xrpld/validators.txt - install -D -m 0755 update-xrpld debian/xrpld/usr/libexec/xrpld/update-xrpld - -override_dh_dwz: - @: diff --git a/package/debian/source/format b/package/debian/source/format deleted file mode 100644 index 163aaf8d82..0000000000 --- a/package/debian/source/format +++ /dev/null @@ -1 +0,0 @@ -3.0 (quilt) diff --git a/package/debian/xrpld.docs b/package/debian/xrpld.docs deleted file mode 100644 index 1217b6db43..0000000000 --- a/package/debian/xrpld.docs +++ /dev/null @@ -1,2 +0,0 @@ -README.md -LICENSE.md diff --git a/package/debian/xrpld.links b/package/debian/xrpld.links deleted file mode 100644 index 10d34f5b8c..0000000000 --- a/package/debian/xrpld.links +++ /dev/null @@ -1,2 +0,0 @@ -# Legacy compat symlinks (remove next major release) -usr/bin/xrpld usr/local/bin/rippled diff --git a/package/rpm/xrpld.spec b/package/rpm/xrpld.spec deleted file mode 100644 index 4933c724f7..0000000000 --- a/package/rpm/xrpld.spec +++ /dev/null @@ -1,100 +0,0 @@ -Name: xrpld -Version: %{xrpld_version} -Release: %{xrpld_release}%{?dist} -Summary: XRP Ledger daemon - -License: ISC -URL: https://github.com/XRPLF/rippled - -ExclusiveArch: x86_64 aarch64 -BuildRequires: systemd-rpm-macros - -%undefine _debugsource_packages -%debug_package - -%build_mtime_policy clamp_to_source_date_epoch - -%{?systemd_requires} -%{?sysusers_requires_compat} - -%description -xrpld is the reference implementation of the XRP Ledger protocol. It -participates in the peer-to-peer XRP Ledger network, processes -transactions, and maintains the ledger database. - -%prep -: - -%build -: - -%install -install -Dm0755 %{_sourcedir}/xrpld %{buildroot}%{_bindir}/%{name} -install -Dm0644 %{_sourcedir}/xrpld.cfg %{buildroot}%{_sysconfdir}/%{name}/xrpld.cfg -install -Dm0644 %{_sourcedir}/validators.txt %{buildroot}%{_sysconfdir}/%{name}/validators.txt - -# systemd units, sysusers, tmpfiles, preset -install -Dm0644 %{_sourcedir}/xrpld.service %{buildroot}%{_unitdir}/xrpld.service -install -Dm0644 %{_sourcedir}/update-xrpld.service %{buildroot}%{_unitdir}/update-xrpld.service -install -Dm0644 %{_sourcedir}/update-xrpld.timer %{buildroot}%{_unitdir}/update-xrpld.timer -install -Dm0644 %{_sourcedir}/xrpld.sysusers %{buildroot}%{_sysusersdir}/xrpld.conf -install -Dm0644 %{_sourcedir}/xrpld.tmpfiles %{buildroot}%{_tmpfilesdir}/xrpld.conf -install -Dm0644 %{_sourcedir}/50-xrpld.preset %{buildroot}%{_presetdir}/50-xrpld.preset - -# Logrotate config -install -Dm0644 %{_sourcedir}/xrpld.logrotate %{buildroot}%{_sysconfdir}/logrotate.d/%{name} - -# Update helper -install -Dm0755 %{_sourcedir}/update-xrpld %{buildroot}%{_libexecdir}/%{name}/update-xrpld - -# Docs -install -Dm0644 %{_sourcedir}/LICENSE.md %{buildroot}%{_docdir}/%{name}/LICENSE.md -install -Dm0644 %{_sourcedir}/README.md %{buildroot}%{_docdir}/%{name}/README.md - -# Legacy compatibility for pre-FHS package layouts. -# TODO: remove after rippled fully deprecated. -install -d %{buildroot}/usr/local/bin -ln -s %{_bindir}/%{name} %{buildroot}/usr/local/bin/rippled - -%pre -%sysusers_create_package %{name} %{_sourcedir}/xrpld.sysusers - -%post -systemd-tmpfiles --create %{_tmpfilesdir}/xrpld.conf || : -%systemd_post xrpld.service update-xrpld.timer - -%preun -%systemd_preun xrpld.service update-xrpld.timer - -%postun -%systemd_postun_with_restart xrpld.service - -%files -%license %{_docdir}/%{name}/LICENSE.md -%doc %{_docdir}/%{name}/README.md - -%dir %{_sysconfdir}/%{name} -%dir %{_libexecdir}/%{name} - -%{_bindir}/%{name} - -%config(noreplace) %{_sysconfdir}/%{name}/xrpld.cfg -%config(noreplace) %{_sysconfdir}/%{name}/validators.txt -%config(noreplace) %{_sysconfdir}/logrotate.d/%{name} - -%{_libexecdir}/%{name}/update-xrpld - -%{_unitdir}/xrpld.service -%{_unitdir}/update-xrpld.service -%{_unitdir}/update-xrpld.timer -%{_presetdir}/50-xrpld.preset -%{_sysusersdir}/xrpld.conf -%{_tmpfilesdir}/xrpld.conf - -%ghost %dir /var/lib/%{name} -%ghost %dir /var/log/%{name} - - -# Legacy compatibility for pre-FHS package layouts. -# TODO: remove after rippled fully deprecated. -/usr/local/bin/rippled diff --git a/package/shared/50-xrpld.preset b/package/shared/50-xrpld.preset deleted file mode 100644 index 6264e00131..0000000000 --- a/package/shared/50-xrpld.preset +++ /dev/null @@ -1,4 +0,0 @@ -# /usr/lib/systemd/system-preset/50-xrpld.preset -enable xrpld.service -# Don't enable automatic updates -disable update-xrpld.timer diff --git a/package/shared/update-xrpld b/package/shared/update-xrpld deleted file mode 100755 index 4bd4db2538..0000000000 --- a/package/shared/update-xrpld +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Optional: also write logs to a legacy file in addition to journald. -# By default, this script logs to systemd/journald, viewable via: -# journalctl -t update-xrpld -# -# Uncomment the line below if you need a flat file for compatibility with -# external tooling, manual inspection, or environments where journald logs -# are not persisted or easily accessible. -# -# Note: This duplicates all output (stdout/stderr) to both journald and the file. -# It is generally not needed on modern systems and may cause log file growth -# if left enabled long-term. -# -# Requires /var/log/xrpld/ to exist and be writable by the service (root). -# -# exec > >(tee -a /var/log/xrpld/update.log) 2>&1 - -PATH=/usr/sbin:/usr/bin:/sbin:/bin - -PKG_NAME=${PKG_NAME:-xrpld} - -log() { - # If running under systemd/journald, let it handle timestamps. - if [[ -n "${JOURNAL_STREAM:-}" ]]; then - printf '%s\n' "$*" - else - printf '%s %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*" - fi -} - -require_root() { - if [[ ${EUID:-$(id -u)} -ne 0 ]]; then - log "RESULT: failed reason=not-root" - exit 1 - fi -} - -get_installed_version() { - if command -v dpkg-query >/dev/null 2>&1; then - dpkg-query -W -f='${Version}' "$PKG_NAME" 2>/dev/null || printf 'unknown' - elif command -v rpm >/dev/null 2>&1; then - rpm -q --qf '%{VERSION}-%{RELEASE}' "$PKG_NAME" 2>/dev/null || printf 'unknown' - else - printf 'unknown' - fi -} - -trap 'log "RESULT: failed reason=script-error exit_code=$?"' ERR - -apt_can_update() { - apt-get update -qq - apt-get -s --only-upgrade install "$PKG_NAME" 2>/dev/null | grep -q "^Inst ${PKG_NAME}\b" -} - -apt_apply_update() { - DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \ - -o Dpkg::Options::="--force-confdef" \ - -o Dpkg::Options::="--force-confold" \ - "$PKG_NAME" -} - -get_rpm_pm() { - if command -v dnf >/dev/null 2>&1; then - printf 'dnf\n' - elif command -v yum >/dev/null 2>&1; then - printf 'yum\n' - else - return 1 - fi -} - -rpm_refresh_metadata() { - local pm=$1 - if [[ "$pm" == "dnf" ]]; then - dnf makecache --refresh -q >/dev/null - else - yum clean expire-cache -q >/dev/null - fi -} - -rpm_can_update() { - local pm=$1 - - rpm_refresh_metadata "$pm" - local rc=0 - set +e - "$pm" check-update -q "$PKG_NAME" >/dev/null 2>&1 - rc=$? - set -e - - if [[ $rc -eq 100 ]]; then - return 0 - elif [[ $rc -eq 0 ]]; then - return 1 - else - log "$pm check-update failed with exit code ${rc}." - exit 1 - fi -} - -rpm_apply_update() { - local pm=$1 - "$pm" update -y "$PKG_NAME" -} - -restart_service() { - # Preserve the operator's prior service state: if xrpld was intentionally - # stopped before the update, don't bring it back up just because the - # auto-update timer fired. - if systemctl is-active --quiet "${PKG_NAME}.service"; then - systemctl restart "${PKG_NAME}.service" - log "${PKG_NAME} service restarted successfully." - else - log "${PKG_NAME} service was not running; skipping restart to preserve prior state." - fi -} - -main() { - require_root - if command -v apt-get >/dev/null 2>&1; then - log "Checking for ${PKG_NAME} updates via apt" - if apt_can_update; then - log "Update available; installing." - apt_apply_update - restart_service - log "RESULT: updated ${PKG_NAME}=$(get_installed_version)" - else - log "RESULT: no-update ${PKG_NAME}=$(get_installed_version)" - fi - return - fi - - local rpm_pm="" - if rpm_pm="$(get_rpm_pm)"; then - log "Checking for ${PKG_NAME} updates via ${rpm_pm}" - if rpm_can_update "$rpm_pm"; then - log "Update available; installing" - rpm_apply_update "$rpm_pm" - restart_service - log "RESULT: updated ${PKG_NAME}=$(get_installed_version)" - else - log "RESULT: no-update ${PKG_NAME}=$(get_installed_version)" - fi - return - fi - log "RESULT: failed reason=no-package-manager" - exit 1 -} - -main "$@" diff --git a/package/shared/update-xrpld.service b/package/shared/update-xrpld.service deleted file mode 100644 index a964ca5482..0000000000 --- a/package/shared/update-xrpld.service +++ /dev/null @@ -1,16 +0,0 @@ -[Unit] -Description=Check for and install xrpld package updates -Documentation=man:systemd.service(5) -Wants=network-online.target -After=network-online.target -ConditionPathExists=/usr/libexec/xrpld/update-xrpld -ConditionPathExists=/usr/bin/xrpld - -[Service] -Type=oneshot -ExecStart=/usr/bin/flock -n /run/lock/xrpld-update.lock /usr/libexec/xrpld/update-xrpld -StandardOutput=journal -StandardError=journal -SyslogIdentifier=update-xrpld -TimeoutStartSec=30min -PrivateTmp=true diff --git a/package/shared/update-xrpld.timer b/package/shared/update-xrpld.timer deleted file mode 100644 index 9fba09d30a..0000000000 --- a/package/shared/update-xrpld.timer +++ /dev/null @@ -1,10 +0,0 @@ -[Unit] -Description=Daily xrpld update check - -[Timer] -OnCalendar=*-*-* 00:00:00 -RandomizedDelaySec=4h -Persistent=true - -[Install] -WantedBy=timers.target diff --git a/package/shared/xrpld.logrotate b/package/shared/xrpld.logrotate deleted file mode 100644 index 0ae2b7783b..0000000000 --- a/package/shared/xrpld.logrotate +++ /dev/null @@ -1,19 +0,0 @@ -/var/log/xrpld/*.log { - daily - minsize 200M - rotate 7 - nocreate - missingok - notifempty - compress - compresscmd /usr/bin/gzip - compressext .gz - postrotate - # Only signal the daemon if it's actually running; otherwise the RPC - # call returns a transport error and logrotate marks the rotation as - # failed, generating recurring errors on stopped nodes. - if systemctl is-active --quiet xrpld; then - /usr/bin/xrpld --conf /etc/xrpld/xrpld.cfg logrotate - fi - endscript -} diff --git a/package/shared/xrpld.service b/package/shared/xrpld.service deleted file mode 100644 index 8e10ed2eee..0000000000 --- a/package/shared/xrpld.service +++ /dev/null @@ -1,23 +0,0 @@ -[Unit] -Description=XRP Ledger Daemon -After=network-online.target -Wants=network-online.target -StartLimitIntervalSec=5min -StartLimitBurst=5 - -[Service] -Type=simple -ExecStart=/usr/bin/xrpld --net --silent --conf /etc/xrpld/xrpld.cfg -Restart=on-failure -RestartSec=5s -TimeoutStopSec=5min -NoNewPrivileges=true -ProtectSystem=full -ProtectHome=true -PrivateTmp=true -User=xrpld -Group=xrpld -LimitNOFILE=65536 - -[Install] -WantedBy=multi-user.target diff --git a/package/shared/xrpld.sysusers b/package/shared/xrpld.sysusers deleted file mode 100644 index 4547ac6f3d..0000000000 --- a/package/shared/xrpld.sysusers +++ /dev/null @@ -1 +0,0 @@ -u xrpld - "XRP Ledger daemon" /var/lib/xrpld /sbin/nologin diff --git a/package/shared/xrpld.tmpfiles b/package/shared/xrpld.tmpfiles deleted file mode 100644 index ff9b4d95c2..0000000000 --- a/package/shared/xrpld.tmpfiles +++ /dev/null @@ -1,2 +0,0 @@ -d /var/lib/xrpld 0750 xrpld xrpld - -d /var/log/xrpld 0750 xrpld xrpld - diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/basics/BasicConfig.cpp index 9fe79bdf4e..c1997eb713 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/basics/BasicConfig.cpp @@ -28,7 +28,7 @@ void Section::append(std::vector const& lines) { // '=' - static boost::regex const kRe1( + static boost::regex const kRE1( "^" // start of line "(?:\\s*)" // whitespace (optional) "([a-zA-Z][_a-zA-Z0-9]*)" // @@ -82,7 +82,7 @@ Section::append(std::vector const& lines) continue; boost::smatch match; - if (boost::regex_match(line, match, kRe1)) + if (boost::regex_match(line, match, kRE1)) { set(match[1], match[2]); } @@ -126,10 +126,10 @@ BasicConfig::section(std::string const& name) Section const& BasicConfig::section(std::string const& name) const { - static Section const kNone(""); + static Section const kNONE(""); auto const iter = map_.find(name); if (iter == map_.end()) - return kNone; + return kNONE; return iter->second; } diff --git a/src/libxrpl/basics/CountedObject.cpp b/src/libxrpl/basics/CountedObject.cpp index f5b98354dc..1bf88687f8 100644 --- a/src/libxrpl/basics/CountedObject.cpp +++ b/src/libxrpl/basics/CountedObject.cpp @@ -7,9 +7,9 @@ namespace xrpl { CountedObjects& CountedObjects::getInstance() noexcept { - static CountedObjects kInstance; + static CountedObjects kINSTANCE; - return kInstance; + return kINSTANCE; } CountedObjects::CountedObjects() noexcept : count_(0), head_(nullptr) diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index d1e54a515f..c74bd36e47 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -14,20 +14,19 @@ #include #include #include -#include #include #include #include namespace xrpl { -Logs::Sink::Sink(std::string partition, beast::Severity thresh, Logs& logs) +Logs::Sink::Sink(std::string partition, beast::severities::Severity thresh, Logs& logs) : beast::Journal::Sink(thresh, false), logs_(logs), partition_(std::move(partition)) { } void -Logs::Sink::write(beast::Severity level, std::string const& text) +Logs::Sink::write(beast::severities::Severity level, std::string const& text) { if (level < threshold()) return; @@ -36,7 +35,7 @@ Logs::Sink::write(beast::Severity level, std::string const& text) } void -Logs::Sink::writeAlways(beast::Severity level, std::string const& text) +Logs::Sink::writeAlways(beast::severities::Severity level, std::string const& text) { logs_.write(level, partition_, text, console()); } @@ -109,7 +108,7 @@ Logs::File::writeln(char const* text) //------------------------------------------------------------------------------ -Logs::Logs(beast::Severity thresh) : thresh_(thresh) // default severity +Logs::Logs(beast::severities::Severity thresh) : thresh_(thresh) // default severity { } @@ -139,14 +138,14 @@ Logs::journal(std::string const& name) return beast::Journal(get(name)); } -beast::Severity +beast::severities::Severity Logs::threshold() const { return thresh_; } void -Logs::threshold(beast::Severity thresh) +Logs::threshold(beast::severities::Severity thresh) { std::scoped_lock const lock(mutex_); thresh_ = thresh; @@ -161,13 +160,13 @@ Logs::partitionSeverities() const std::scoped_lock const lock(mutex_); list.reserve(sinks_.size()); for (auto const& [name, sink] : sinks_) - list.emplace_back(name, toString(sink->threshold())); + list.emplace_back(name, toString(fromSeverity(sink->threshold()))); return list; } void Logs::write( - beast::Severity level, + beast::severities::Severity level, std::string const& partition, std::string const& text, bool console) @@ -194,65 +193,122 @@ Logs::rotate() } std::unique_ptr -Logs::makeSink(std::string const& name, beast::Severity threshold) +Logs::makeSink(std::string const& name, beast::severities::Severity threshold) { return std::make_unique(name, threshold, *this); } +LogSeverity +Logs::fromSeverity(beast::severities::Severity level) +{ + using namespace beast::severities; + switch (level) + { + case KTrace: + return LSTrace; + case KDebug: + return LSDebug; + case KInfo: + return LSInfo; + case KWarning: + return LSWarning; + case KError: + return LSError; + + // LCOV_EXCL_START + default: + UNREACHABLE("xrpl::Logs::fromSeverity : invalid severity"); + [[fallthrough]]; + // LCOV_EXCL_STOP + case KFatal: + break; + } + + return LSFatal; +} + +beast::severities::Severity +Logs::toSeverity(LogSeverity level) +{ + using namespace beast::severities; + switch (level) + { + case LSTrace: + return KTrace; + case LSDebug: + return KDebug; + case LSInfo: + return KInfo; + case LSWarning: + return KWarning; + case LSError: + return KError; + // LCOV_EXCL_START + default: + UNREACHABLE("xrpl::Logs::toSeverity : invalid severity"); + [[fallthrough]]; + // LCOV_EXCL_STOP + case LSFatal: + break; + } + + return KFatal; +} + std::string -Logs::toString(beast::Severity s) +Logs::toString(LogSeverity s) { switch (s) { - case beast::Severity::Trace: + case LSTrace: return "Trace"; - case beast::Severity::Debug: + case LSDebug: return "Debug"; - case beast::Severity::Info: + case LSInfo: return "Info"; - case beast::Severity::Warning: + case LSWarning: return "Warning"; - case beast::Severity::Error: + case LSError: return "Error"; - case beast::Severity::Fatal: + case LSFatal: return "Fatal"; // LCOV_EXCL_START default: - UNREACHABLE("xrpl::Logs::toString : invalid severity"); + UNREACHABLE("xrpl::Logs::to_string : invalid severity"); return "Unknown"; // LCOV_EXCL_STOP } } -std::optional +LogSeverity Logs::fromString(std::string const& s) { if (boost::iequals(s, "trace")) - return beast::Severity::Trace; + return LSTrace; if (boost::iequals(s, "debug")) - return beast::Severity::Debug; + return LSDebug; if (boost::iequals(s, "info") || boost::iequals(s, "information")) - return beast::Severity::Info; + return LSInfo; if (boost::iequals(s, "warn") || boost::iequals(s, "warning") || boost::iequals(s, "warnings")) - return beast::Severity::Warning; + return LSWarning; if (boost::iequals(s, "error") || boost::iequals(s, "errors")) - return beast::Severity::Error; + return LSError; if (boost::iequals(s, "fatal") || boost::iequals(s, "fatals")) - return beast::Severity::Fatal; + return LSFatal; - return std::nullopt; + return LSInvalid; } void Logs::format( std::string& output, std::string const& message, - beast::Severity severity, + beast::severities::Severity severity, std::string const& partition) { output.reserve(message.size() + partition.size() + 100); @@ -263,22 +319,22 @@ Logs::format( if (!partition.empty()) output += partition + ":"; - using beast::Severity; + using namespace beast::severities; switch (severity) { - case Severity::Trace: + case KTrace: output += "TRC "; break; - case Severity::Debug: + case KDebug: output += "DBG "; break; - case Severity::Info: + case KInfo: output += "NFO "; break; - case Severity::Warning: + case KWarning: output += "WRN "; break; - case Severity::Error: + case KError: output += "ERR "; break; // LCOV_EXCL_START @@ -286,7 +342,7 @@ Logs::format( UNREACHABLE("xrpl::Logs::format : invalid severity"); [[fallthrough]]; // LCOV_EXCL_STOP - case Severity::Fatal: + case KFatal: output += "FTL "; break; } @@ -294,9 +350,9 @@ Logs::format( output += message; // Limit the maximum length of the output - if (output.size() > kMaximumMessageCharacters) + if (output.size() > MaximumMessageCharacters) { - output.resize(kMaximumMessageCharacters - 3); + output.resize(MaximumMessageCharacters - 3); output += "..."; } @@ -385,8 +441,8 @@ public: static DebugSink& debugSink() { - static DebugSink kInst; - return kInst; + static DebugSink kINST; + return kINST; } std::unique_ptr diff --git a/src/libxrpl/basics/MallocTrim.cpp b/src/libxrpl/basics/MallocTrim.cpp index 3831c8adae..6fb9ab611b 100644 --- a/src/libxrpl/basics/MallocTrim.cpp +++ b/src/libxrpl/basics/MallocTrim.cpp @@ -86,7 +86,7 @@ mallocTrim(std::string_view tag, beast::Journal journal) // Keep glibc malloc_trim padding at 0 (default): 12h Mainnet tests across 0/256KB/1MB/16MB // showed no clear, consistent benefit from custom padding—0 provided the best overall balance // of RSS reduction and trim-latency stability without adding a tuning surface. - static constexpr std::size_t kTrimPad = 0; + constexpr static std::size_t kTRIM_PAD = 0; report.supported = true; @@ -114,7 +114,7 @@ mallocTrim(std::string_view tag, beast::Journal journal) auto const t0 = std::chrono::steady_clock::now(); - report.trimResult = detail::mallocTrimWithPad(kTrimPad); + report.trimResult = detail::mallocTrimWithPad(kTRIM_PAD); auto const t1 = std::chrono::steady_clock::now(); @@ -140,7 +140,7 @@ mallocTrim(std::string_view tag, beast::Journal journal) : (static_cast(rssAfterKB) - static_cast(rssBeforeKB)); JLOG(journal.debug()) << "malloc_trim tag=" << tagStr << " result=" << report.trimResult - << " pad=" << kTrimPad << " bytes" + << " pad=" << kTRIM_PAD << " bytes" << " rss_before=" << rssBeforeKB << "kB" << " rss_after=" << rssAfterKB << "kB" << " delta=" << deltaKB << "kB" @@ -150,7 +150,7 @@ mallocTrim(std::string_view tag, beast::Journal journal) } else { - report.trimResult = detail::mallocTrimWithPad(kTrimPad); + report.trimResult = detail::mallocTrimWithPad(kTRIM_PAD); } #endif diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 275d82d8c9..08ead182bf 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -10,11 +10,9 @@ #include #include #include -#include #include #include #include -#include #include #ifdef _MSC_VER @@ -30,76 +28,7 @@ using int128_t = __int128_t; namespace xrpl { thread_local Number::RoundingMode Number::mode = Number::RoundingMode::ToNearest; -thread_local std::reference_wrapper Number::kRange = - MantissaRange::getMantissaRange(MantissaRange::MantissaScale::Large); - -std::set const& -MantissaRange::getAllScales() -{ - static std::set const kScales = { - MantissaRange::MantissaScale::Small, - MantissaRange::MantissaScale::LargeLegacy, - MantissaRange::MantissaScale::Large, - }; - return kScales; -} - -std::unordered_map const& -MantissaRange::getRanges() -{ - static auto const kMap = []() { - std::unordered_map map; - for (auto const scale : getAllScales()) - { - map.emplace(scale, scale); - } - - // Use these constexpr declarations to do static_asserts to verify the MantissaRanges are - // created correctly, but nothing else. - { - [[maybe_unused]] - constexpr static MantissaRange kRange{MantissaRange::MantissaScale::Small}; - static_assert(isPowerOfTen(kRange.min)); - static_assert(kRange.min == 1'000'000'000'000'000LL); - static_assert(kRange.max == 9'999'999'999'999'999LL); - static_assert(kRange.log == 15); - static_assert(kRange.min < Number::kMaxRep); - static_assert(kRange.max < Number::kMaxRep); - static_assert(kRange.cuspRoundingFixEnabled == CuspRoundingFix::Disabled); - } - { - [[maybe_unused]] - constexpr static MantissaRange kRange{MantissaRange::MantissaScale::LargeLegacy}; - static_assert(isPowerOfTen(kRange.min)); - static_assert(kRange.min == 1'000'000'000'000'000'000ULL); - static_assert(kRange.max == rep(9'999'999'999'999'999'999ULL)); - static_assert(kRange.log == 18); - static_assert(kRange.min < Number::kMaxRep); - static_assert(kRange.max > Number::kMaxRep); - static_assert(kRange.cuspRoundingFixEnabled == CuspRoundingFix::Disabled); - } - { - [[maybe_unused]] - constexpr static MantissaRange kRange{MantissaRange::MantissaScale::Large}; - static_assert(isPowerOfTen(kRange.min)); - static_assert(kRange.min == 1'000'000'000'000'000'000ULL); - static_assert(kRange.max == rep(9'999'999'999'999'999'999ULL)); - static_assert(kRange.log == 18); - static_assert(kRange.min < Number::kMaxRep); - static_assert(kRange.max > Number::kMaxRep); - static_assert(kRange.cuspRoundingFixEnabled == CuspRoundingFix::Enabled); - } - return map; - }(); - - return kMap; -} - -MantissaRange const& -MantissaRange::getMantissaRange(MantissaScale scale) -{ - return getRanges().at(scale); -} +thread_local std::reference_wrapper Number::kRANGE = kLARGE_RANGE; Number::RoundingMode Number::getround() @@ -116,43 +45,16 @@ Number::setround(RoundingMode inMode) MantissaRange::MantissaScale Number::getMantissaScale() { - return kRange.get().scale; + return kRANGE.get().scale; } void Number::setMantissaScale(MantissaRange::MantissaScale scale) { - if (!MantissaRange::getAllScales().contains(scale)) + if (scale != MantissaRange::MantissaScale::Small && + scale != MantissaRange::MantissaScale::Large) logicError("Unknown mantissa scale"); - kRange = MantissaRange::getMantissaRange(scale); -} - -// Optimization equivalent to: -// auto r = static_cast(u % 10); -// u /= 10; -// return r; -// Derived from Hacker's Delight Second Edition Chapter 10 -// by Henry S. Warren, Jr. -static inline unsigned -divu10(uint128_t& u) -{ - // q = u * 0.75 - auto q = (u >> 1) + (u >> 2); - // iterate towards q = u * 0.8 - q += q >> 4; - q += q >> 8; - q += q >> 16; - q += q >> 32; - q += q >> 64; - // q /= 8 approximately == u / 10 - q >>= 3; - // r = u - q * 10 approximately == u % 10 - auto r = static_cast(u - ((q << 3) + (q << 1))); - // correction c is 1 if r >= 10 else 0 - auto c = (r + 6) >> 4; - u = q + c; - r -= c * 10; - return r; + kRANGE = scale == MantissaRange::MantissaScale::Small ? kSMALL_RANGE : kLARGE_RANGE; } // Guard @@ -178,10 +80,6 @@ public: setPositive() noexcept; void setNegative() noexcept; - // Should only be called by doNormalize, and then only for division - // operations with remainders. - void - setDropped() noexcept; [[nodiscard]] bool isNegative() const noexcept; @@ -194,18 +92,6 @@ public: unsigned pop() noexcept; - /** Drop a digit from the mantissa, and increment the exponent, storing the dropped digit in - * this Guard. - * - * Substitute for: - push(mantissa % 10); - mantissa /= 10; - ++exponent; - */ - template - void - doDropDigit(T& mantissa, int& exponent) noexcept; - // Indicate round direction: 1 is up, -1 is down, 0 is even // This enables the client to round towards nearest, and on // tie, round towards even. @@ -221,7 +107,6 @@ public: int& exponent, internalrep const& minMantissa, internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled, std::string location); // Modify the result to the correctly rounded value @@ -254,12 +139,6 @@ Number::Guard::setNegative() noexcept sbit_ = 1; } -inline void -Number::Guard::setDropped() noexcept -{ - xbit_ = 1; -} - inline bool Number::Guard::isNegative() const noexcept { @@ -289,27 +168,6 @@ Number::Guard::pop() noexcept return d; } -template -void -Number::Guard::doDropDigit(T& mantissa, int& exponent) noexcept -{ - push(mantissa % 10); - mantissa /= 10; - ++exponent; -} - -// Use the divu10 optimization for uint128s -template <> -void -Number::Guard::doDropDigit(uint128_t& mantissa, int& exponent) noexcept -{ - // The following is optimization for: - // push(static_cast(mantissa % 10)); - // mantissa /= 10; - push(divu10(mantissa)); - ++exponent; -} - // Returns: // -1 if Guard is less than half // 0 if Guard is exactly half @@ -366,13 +224,13 @@ Number::Guard::bringIntoRange( mantissa *= 10; --exponent; } - if (exponent < kMinExponent) + if (exponent < kMIN_EXPONENT) { - static constexpr Number kZero = Number{}; + constexpr Number kZERO = Number{}; - negative = kZero.negative_; - mantissa = kZero.mantissa_; - exponent = kZero.exponent_; + negative = kZERO.negative_; + mantissa = kZERO.mantissa_; + exponent = kZERO.exponent_; } } @@ -384,64 +242,22 @@ Number::Guard::doRoundUp( int& exponent, internalrep const& minMantissa, internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled, std::string location) { auto r = round(); if (r == 1 || (r == 0 && (mantissa & 1) == 1)) { - auto const safeToIncrement = [&maxMantissa](auto const& mantissa) { - return mantissa < maxMantissa && mantissa < kMaxRep; - }; - if (cuspRoundingFixEnabled == MantissaRange::CuspRoundingFix::Enabled) + ++mantissa; + // Ensure mantissa after incrementing fits within both the + // min/maxMantissa range and is a valid "rep". + if (mantissa > maxMantissa || mantissa > kMAX_REP) { - // Ensure mantissa after incrementing fits within both the - // min/maxMantissa range and is a valid "rep". - if (safeToIncrement(mantissa)) - { - // Nothing unusual here, just increment the mantissa - ++mantissa; - } - else - { - // Incrementing the mantissa will require dividing, which will require rounding. So - // _don't_ increment the mantissa. Instead, divide and round recursively. It should - // be impossible to recurse more than once, because once the mantissa is divided by - // 10, it will be _well_ under maxMantissa and kMaxRep, so adding 1 will have no - // chance of bringing it back over. - doDropDigit(mantissa, exponent); - XRPL_ASSERT_PARTS( - safeToIncrement(mantissa), - "xrpl::Number::Guard::doRoundUp", - "can't recurse more than once"); - doRoundUp( - negative, - mantissa, - exponent, - minMantissa, - maxMantissa, - cuspRoundingFixEnabled, - location); - return; - } - } - else - { - // Need to preserve the incorrect behavior until the fix amendment can be retired, - // because otherwise would risk an unplanned ledger fork. - ++mantissa; - // Ensure mantissa after incrementing fits within both the - // min/maxMantissa range and is a valid "rep". - if (mantissa > maxMantissa || mantissa > kMaxRep) - { - // Don't use doDropDigit here - mantissa /= 10; - ++exponent; - } + mantissa /= 10; + ++exponent; } } bringIntoRange(negative, mantissa, exponent, minMantissa); - if (exponent > kMaxExponent) + if (exponent > kMAX_EXPONENT) Throw(std::string(location)); } @@ -473,13 +289,13 @@ Number::Guard::doRound(rep& drops, std::string location) const auto r = round(); if (r == 1 || (r == 0 && (drops & 1) == 1)) { - if (drops >= kMaxRep) + if (drops >= kMAX_REP) { static_assert(sizeof(internalrep) == sizeof(rep)); // This should be impossible, because it's impossible to represent - // "kMaxRep + 0.6" in Number, regardless of the scale. There aren't - // enough digits available. You'd either get a mantissa of "kMaxRep" - // or "(kMaxRep + 1) / 10", neither of which will round up when + // "maxRep + 0.6" in Number, regardless of the scale. There aren't + // enough digits available. You'd either get a mantissa of "maxRep" + // or "(maxRep + 1) / 10", neither of which will round up when // converting to rep, though the latter might overflow _before_ // rounding. Throw(std::string(location)); // LCOV_EXCL_LINE @@ -515,13 +331,33 @@ Number::externalToInternal(rep mantissa) return static_cast(-temp); } +constexpr Number +Number::oneSmall() +{ + return Number{false, Number::kSMALL_RANGE.min, -Number::kSMALL_RANGE.log, Number::Unchecked{}}; +}; + +constexpr Number kONE_SML = Number::oneSmall(); + +constexpr Number +Number::oneLarge() +{ + return Number{false, Number::kLARGE_RANGE.min, -Number::kLARGE_RANGE.log, Number::Unchecked{}}; +}; + +constexpr Number kONE_LRG = Number::oneLarge(); + Number Number::one() { - auto const& range = kRange.get(); - return Number{false, range.min, -range.log, Number::Unchecked{}}; + if (&kRANGE.get() == &kSMALL_RANGE) + return kONE_SML; + XRPL_ASSERT(&kRANGE.get() == &kLARGE_RANGE, "Number::one() : valid range"); + return kONE_LRG; } +// Use the member names in this static function for now so the diff is cleaner +// TODO: Rename the function parameters to get rid of the "_" suffix template void doNormalize( @@ -529,26 +365,24 @@ doNormalize( T& mantissa, int& exponent, MantissaRange::rep const& minMantissa, - MantissaRange::rep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled, - bool dropped) + MantissaRange::rep const& maxMantissa) { - static constexpr auto kMinExponent = Number::kMinExponent; - static constexpr auto kMaxExponent = Number::kMaxExponent; - static constexpr auto kMaxRep = Number::kMaxRep; + auto constexpr kMIN_EXPONENT = Number::kMIN_EXPONENT; + auto constexpr kMAX_EXPONENT = Number::kMAX_EXPONENT; + auto constexpr kMAX_REP = Number::kMAX_REP; using Guard = Number::Guard; - static constexpr Number kZero = Number{}; + constexpr Number kZERO = Number{}; if (mantissa == 0) { - mantissa = kZero.mantissa_; - exponent = kZero.exponent_; - negative = kZero.negative_; + mantissa = kZERO.mantissa_; + exponent = kZERO.exponent_; + negative = kZERO.negative_; return; } auto m = mantissa; - while ((m < minMantissa) && (exponent > kMinExponent)) + while ((m < minMantissa) && (exponent > kMIN_EXPONENT)) { m *= 10; --exponent; @@ -556,24 +390,24 @@ doNormalize( Guard g; if (negative) g.setNegative(); - if (dropped) - g.setDropped(); while (m > maxMantissa) { - if (exponent >= kMaxExponent) + if (exponent >= kMAX_EXPONENT) throw std::overflow_error("Number::normalize 1"); - g.doDropDigit(m, exponent); + g.push(m % 10); + m /= 10; + ++exponent; } - if ((exponent < kMinExponent) || (m < minMantissa)) + if ((exponent < kMIN_EXPONENT) || (m < minMantissa)) { - mantissa = kZero.mantissa_; - exponent = kZero.exponent_; - negative = kZero.negative_; + mantissa = kZERO.mantissa_; + exponent = kZERO.exponent_; + negative = kZERO.negative_; return; } // When using the largeRange, "m" needs fit within an int64, even if - // the final mantissa is going to end up larger to fit within the + // the final mantissa_ is going to end up larger to fit within the // MantissaRange. Cut it down here so that the rounding will be done while // it's smaller. // @@ -581,31 +415,26 @@ doNormalize( // so "m" will be modified to 990,000,000,000,012,345. Then that value // will be rounded to 990,000,000,000,012,345 or // 990,000,000,000,012,346, depending on the rounding mode. Finally, - // mantissa will be "m*10" so it fits within the range, and end up as + // mantissa_ will be "m*10" so it fits within the range, and end up as // 9,900,000,000,000,123,450 or 9,900,000,000,000,123,460. - // mantissa() will return mantissa / 10, and exponent() will return - // exponent + 1. - if (m > kMaxRep) + // mantissa() will return mantissa_ / 10, and exponent() will return + // exponent_ + 1. + if (m > kMAX_REP) { - if (exponent >= kMaxExponent) + if (exponent >= kMAX_EXPONENT) throw std::overflow_error("Number::normalize 1.5"); - g.doDropDigit(m, exponent); + g.push(m % 10); + m /= 10; + ++exponent; } // Before modification, m should be within the min/max range. After - // modification, it must be less than kMaxRep. In other words, the original - // value should have been no more than kMaxRep * 10. - // (kMaxRep * 10 > maxMantissa) - XRPL_ASSERT_PARTS(m <= kMaxRep, "xrpl::doNormalize", "intermediate mantissa fits in int64"); + // 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 <= kMAX_REP, "xrpl::doNormalize", "intermediate mantissa fits in int64"); mantissa = m; - g.doRoundUp( - negative, - mantissa, - exponent, - minMantissa, - maxMantissa, - cuspRoundingFixEnabled, - "Number::normalize 2"); + g.doRoundUp(negative, mantissa, exponent, minMantissa, maxMantissa, "Number::normalize 2"); XRPL_ASSERT_PARTS( mantissa >= minMantissa && mantissa <= maxMantissa, "xrpl::doNormalize", @@ -619,15 +448,9 @@ Number::normalize( uint128_t& mantissa, int& exponent, internalrep const& minMantissa, - internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled) + internalrep const& maxMantissa) { - // Not used by every compiler version, and thus not necessarily - // counted by coverage build - // LCOV_EXCL_START - doNormalize( - negative, mantissa, exponent, minMantissa, maxMantissa, cuspRoundingFixEnabled, false); - // LCOV_EXCL_STOP + doNormalize(negative, mantissa, exponent, minMantissa, maxMantissa); } template <> @@ -637,15 +460,9 @@ Number::normalize( unsigned long long& mantissa, int& exponent, internalrep const& minMantissa, - internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled) + internalrep const& maxMantissa) { - // Not used by every compiler version, and thus not necessarily - // counted by coverage build - // LCOV_EXCL_START - doNormalize( - negative, mantissa, exponent, minMantissa, maxMantissa, cuspRoundingFixEnabled, false); - // LCOV_EXCL_STOP + doNormalize(negative, mantissa, exponent, minMantissa, maxMantissa); } template <> @@ -655,17 +472,16 @@ Number::normalize( unsigned long& mantissa, int& exponent, internalrep const& minMantissa, - internalrep const& maxMantissa, - MantissaRange::CuspRoundingFix cuspRoundingFixEnabled) + internalrep const& maxMantissa) { - doNormalize( - negative, mantissa, exponent, minMantissa, maxMantissa, cuspRoundingFixEnabled, false); + doNormalize(negative, mantissa, exponent, minMantissa, maxMantissa); } void -Number::normalize(MantissaRange const& range) +Number::normalize() { - normalize(negative_, mantissa_, exponent_, range.min, range.max, range.cuspRoundingFixEnabled); + auto const& range = kRANGE.get(); + normalize(negative_, mantissa_, exponent_, range.min, range.max); } // Copy the number, but set a new exponent. Because the mantissa doesn't change, @@ -676,9 +492,9 @@ Number::shiftExponent(int exponentDelta) const { XRPL_ASSERT_PARTS(isnormal(), "xrpl::Number::shiftExponent", "normalized"); auto const newExponent = exponent_ + exponentDelta; - if (newExponent >= kMaxExponent) + if (newExponent >= kMAX_EXPONENT) throw std::overflow_error("Number::shiftExponent"); - if (newExponent < kMinExponent) + if (newExponent < kMIN_EXPONENT) { return Number{}; } @@ -690,17 +506,17 @@ Number::shiftExponent(int exponentDelta) const Number& Number::operator+=(Number const& y) { - static constexpr Number kZero = Number{}; - if (y == kZero) + constexpr Number kZERO = Number{}; + if (y == kZERO) return *this; - if (*this == kZero) + if (*this == kZERO) { *this = y; return *this; } if (*this == -y) { - *this = kZero; + *this = kZERO; return *this; } @@ -726,7 +542,9 @@ Number::operator+=(Number const& y) g.setNegative(); do { - g.doDropDigit(xm, xe); + g.push(xm % 10); + xm /= 10; + ++xe; } while (xe < ye); } else if (xe > ye) @@ -735,30 +553,26 @@ Number::operator+=(Number const& y) g.setNegative(); do { - g.doDropDigit(ym, ye); + g.push(ym % 10); + ym /= 10; + ++ye; } while (xe > ye); } - auto const& range = kRange.get(); + auto const& range = kRANGE.get(); auto const& minMantissa = range.min; auto const& maxMantissa = range.max; - auto const cuspRoundingFixEnabled = range.cuspRoundingFixEnabled; if (xn == yn) { xm += ym; - if (xm > maxMantissa || xm > kMaxRep) + if (xm > maxMantissa || xm > kMAX_REP) { - g.doDropDigit(xm, xe); + g.push(xm % 10); + xm /= 10; + ++xe; } - g.doRoundUp( - xn, - xm, - xe, - minMantissa, - maxMantissa, - cuspRoundingFixEnabled, - "Number::addition overflow"); + g.doRoundUp(xn, xm, xe, minMantissa, maxMantissa, "Number::addition overflow"); } else { @@ -772,7 +586,7 @@ Number::operator+=(Number const& y) xe = ye; xn = yn; } - while (xm < minMantissa && xm * 10 <= kMaxRep) + while (xm < minMantissa && xm * 10 <= kMAX_REP) { xm *= 10; xm -= g.pop(); @@ -784,17 +598,45 @@ Number::operator+=(Number const& y) negative_ = xn; mantissa_ = static_cast(xm); exponent_ = xe; - normalize(range); + normalize(); return *this; } +// Optimization equivalent to: +// auto r = static_cast(u % 10); +// u /= 10; +// return r; +// Derived from Hacker's Delight Second Edition Chapter 10 +// by Henry S. Warren, Jr. +static inline unsigned +divu10(uint128_t& u) +{ + // q = u * 0.75 + auto q = (u >> 1) + (u >> 2); + // iterate towards q = u * 0.8 + q += q >> 4; + q += q >> 8; + q += q >> 16; + q += q >> 32; + q += q >> 64; + // q /= 8 approximately == u / 10 + q >>= 3; + // r = u - q * 10 approximately == u % 10 + auto r = static_cast(u - ((q << 3) + (q << 1))); + // correction c is 1 if r >= 10 else 0 + auto c = (r + 6) >> 4; + u = q + c; + r -= c * 10; + return r; +} + Number& Number::operator*=(Number const& y) { - static constexpr Number kZero = Number{}; - if (*this == kZero) + constexpr Number kZERO = Number{}; + if (*this == kZERO) return *this; - if (y == kZero) + if (y == kZERO) { *this = y; return *this; @@ -822,16 +664,18 @@ Number::operator*=(Number const& y) if (zn) g.setNegative(); - auto const& range = kRange.get(); + auto const& range = kRANGE.get(); auto const& minMantissa = range.min; auto const& maxMantissa = range.max; - auto const cuspRoundingFixEnabled = range.cuspRoundingFixEnabled; - while (zm > maxMantissa || zm > kMaxRep) + while (zm > maxMantissa || zm > kMAX_REP) { - g.doDropDigit(zm, ze); + // The following is optimization for: + // g.push(static_cast(zm % 10)); + // zm /= 10; + g.push(divu10(zm)); + ++ze; } - xm = static_cast(zm); xe = ze; g.doRoundUp( @@ -840,29 +684,26 @@ Number::operator*=(Number const& y) xe, minMantissa, maxMantissa, - cuspRoundingFixEnabled, "Number::multiplication overflow : exponent is " + std::to_string(xe)); negative_ = zn; mantissa_ = xm; exponent_ = xe; - normalize(range); + normalize(); return *this; } Number& Number::operator/=(Number const& y) { - static constexpr Number kZero = Number{}; - if (y == kZero) + constexpr Number kZERO = Number{}; + if (y == kZERO) throw std::overflow_error("Number: divide by 0"); - if (*this == kZero) + if (*this == kZERO) return *this; // n* = numerator // d* = denominator - // z* = result (quotient) - // *p = negative (p for positive, even though the value means not - // positive?) + // *p = negative (positive?) // *s = sign // *m = mantissa // *e = exponent @@ -874,155 +715,72 @@ Number::operator/=(Number const& y) bool const dp = y.negative_; int const ds = (dp ? -1 : 1); - // Create the denominator as 128-bit unsigned, since that's what we - // need to work with. - uint128_t const dm = static_cast(y.mantissa_); - auto const de = y.exponent_; + auto dm = y.mantissa_; + auto de = y.exponent_; - auto const& range = kRange.get(); + auto const& range = kRANGE.get(); auto const& minMantissa = range.min; auto const& maxMantissa = range.max; - auto const cuspRoundingFixEnabled = range.cuspRoundingFixEnabled; - // Division operates on two large integers (16-digit for small - // mantissas, 19-digit for large) using integer math. If the values - // were just divided directly, the result would be only ever be one - // digit or zero - not very useful. - // e.g. 9'876'543'210'987'654 / 1'234'567'890'123'456 = 8 - // 1'234'567'890'123'456 / 9'876'543'210'987'654 = 0 - // Introduce a power-of-ten multiplication factor for the numerator - // which will ensure the result has a meaningful number of digits. - // - // Consider numbers with a 2-digit mantissa: - // * Assume both numbers have an exponent of 0, using "ToNearest" rounding - // * 23 / 67 = 0 - // * Use a factor of 10^4 - // * 230'000 / 67 = 3432 with an exponent of -4 - // * The normalized result will be 34, exponent -2, or 0.34 - // - // The most extreme results are 10/99 and 99/10 - // * 100'000 / 99 = 1'010e-4 = 10e-2 or 0.10 - // * 990'000 / 10 = 99'000e-4 = 99e-1 or 9.9 - // - // Note that the computations give 2 or 3 digits after the - // decimal point to determine which way to round for most scenarios. - // - // For small mantissas (where the MantissaRange.log == 15), shifting by 10^17 gives sufficient - // precision while not overflowing uint128_t or the cast back to int64_t. (This is legacy - // behavior, which must not be changed.) - // - // For large mantissas (where the MantissaRange.log == 18), a shift by 10^20 would be optimal - // for most scenarios. However, larger mantissa values would overflow 2^128. - // - // * log(2^128,10) ~ 38.5 - // * largeRange.log = 18, fits in 10^19 - // * The expanded numerator must fit in 10^38 - // * f not be more than 10^(38-19) = 10^19 safely - // - // So, we do the division into stages: - // - // Stage 1: Use the same factor of 10^17, for the initial division. This - // will frequently not result in a whole number quotient. - // - // Stage 2: If there is a remainder from the first step, repeat the - // process with a "correction" factor of 10^5. Shift the - // result of Stage 1 over by 5 places, and add the second result to it. - // This is equivalent to if we had used an initial factor of 10^22, - // a couple digits more than we actually need. - // - // Stage 3: If there is still a remainder, and the CuspRoundingFix - // is enabled, pass a flag indicating such to doNormalize. The Guard - // in doNormalize will treat that flag as if non-zero digits had - // been dropped from the mantissa when shrinking it into range. - // This is only relevant when rounding away from zero (Upward for - // positive numbers, Downward for negative), or if the "regular" - // remainder is exactly 0.5 for "ToNearest". This will give the - // rounding the most accurate result possible, as if infinite - // precision was used in the initial calculation. + // Shift by 10^17 gives greatest precision while not overflowing + // uint128_t or the cast back to int64_t + // TODO: Can/should this be made bigger for largeRange? + // log(2^128,10) ~ 38.5 + // largeRange.log = 18, fits in 10^19 + // f can be up to 10^(38-19) = 10^19 safely + static_assert(kSMALL_RANGE.log == 15); + static_assert(kLARGE_RANGE.log == 18); + bool const small = Number::getMantissaScale() == MantissaRange::MantissaScale::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"); - // Stage 1: Do the initial division with a factor of 10^17. - auto constexpr factorExponent = 17; - - uint128_t constexpr f = kPowerOfTen[factorExponent]; + // unsigned denominator + auto const dmu = static_cast(dm); + // correctionFactor can be anything between 10 and f, depending on how much + // extra precision we want to only use for rounding with the + // largeRange. Three digits seems like plenty, and is more than + // the smallRange uses. + uint128_t const correctionFactor = 1'000; auto const numerator = uint128_t(nm) * f; - auto zm = numerator / dm; - auto ze = ne - de - factorExponent; - bool zp = (ns * ds) < 0; - // dropped is used in the same way as Guard::xbit_. In the case of - // division, it indicates if there's any remainder left over after - // we have been as precise as reasonable. If there is, it would be as - // if we were using infinite precision math, and a non-zero digit - // had been shifted off the end of the result when normalizing. - bool dropped = false; - - if (range.scale != MantissaRange::MantissaScale::Small) + auto zm = numerator / dmu; + auto ze = ne - de - (small ? 17 : 19); + bool zn = (ns * ds) < 0; + if (!small) { - // Stage 2 - // - // If there is a remainder, treat it as a secondary numerator. - // Multiply by correctionFactor separately from stage 1. + // Virtually multiply numerator by correctionFactor. Since that would + // overflow in the existing uint128_t, we'll do that part separately. // The math for this would work for small mantissas, but we need to - // preserve legacy behavior. + // preserve existing behavior. // // Consider: - // ((numerator * correctionFactor) / dm) / correctionFactor - // = ((numerator / dm) * correctionFactor) / correctionFactor) + // ((numerator * correctionFactor) / dmu) / correctionFactor + // = ((numerator / dmu) * correctionFactor) / correctionFactor) // // But that assumes infinite precision. With integer math, this is // equivalent to // - // = ((numerator / dm * correctionFactor) - // + ((numerator % dm) * correctionFactor) / dm) / correctionFactor - // = ((zm * correctionFactor) - // + (remainder * correctionFactor) / dm) / correctionFactor + // = ((numerator / dmu * correctionFactor) + // + ((numerator % dmu) * correctionFactor) / dmu) / correctionFactor // - // The trick is that multiplication by correctionFactor is done on the mantissa, but - // division by correctionFactor is done by modifying the exponent, so no precision is lost - // until we normalize. - // - // If remainder is zero, we can skip this stage entirely because - // the first stage gave an exact answer. - auto constexpr correctionExponent = 5; - uint128_t constexpr correctionFactor = kPowerOfTen[correctionExponent]; - static_assert(factorExponent + correctionExponent == 22); - - auto const remainder = (numerator % dm); + // We have already set `mantissa_ = numerator / dmu`. Now we + // compute `remainder = numerator % dmu`, and if it is + // nonzero, we do the rest of the arithmetic. If it's zero, we can skip + // it. + auto const remainder = (numerator % dmu); if (remainder != 0) { - auto const partialNumerator = remainder * correctionFactor; - auto const correction = partialNumerator / dm; - - // If the correction is zero, we do not have to make any - // modifications to z*, because it will not have any - // effect on the final result. (We'd be adding a bunch of - // zeros to the end of zm that would just be removed in - // normalize.) However, if that is the case, then Stage 3 is - // even more important for accuracy. - if (correction != 0) - { - zm *= correctionFactor; - // divide by the correctionFactor by moving the exponent, so we don't lose the - // integer value we just computed - ze -= correctionExponent; - - zm += correction; - } - - // Stage 3: If there's still anything left, and the cusp - // rounding fix is enabled, flag if there is still - // a remainder from stage 2. - bool const useTrailingRemainder = - cuspRoundingFixEnabled == MantissaRange::CuspRoundingFix::Enabled; - if (useTrailingRemainder) - { - dropped = partialNumerator % dm != 0; - } + zm *= correctionFactor; + auto const correction = remainder * correctionFactor / dmu; + zm += correction; + // divide by 1000 by moving the exponent, so we don't lose the + // integer value we just computed + ze -= 3; } } - doNormalize(zp, zm, ze, minMantissa, maxMantissa, cuspRoundingFixEnabled, dropped); - negative_ = zp; + normalize(zn, zm, ze, minMantissa, maxMantissa); + negative_ = zn; mantissa_ = static_cast(zm); exponent_ = ze; XRPL_ASSERT_PARTS(isnormal(), "xrpl::Number::operator/=", "result is normalized"); @@ -1043,13 +801,14 @@ operator rep() const g.setNegative(); drops = -drops; } - while (offset < 0) + for (; offset < 0; ++offset) { - g.doDropDigit(drops, offset); + g.push(drops % 10); + drops /= 10; } for (; offset > 0; --offset) { - if (drops > kMaxRep / 10) + if (drops > kMAX_REP / 10) throw std::overflow_error("Number::operator rep() overflow"); drops *= 10; } @@ -1072,7 +831,7 @@ Number::truncate() const noexcept } // We are guaranteed that normalize() will never throw an exception // because exponent is either negative or zero at this point. - ret.normalize(kRange); + ret.normalize(); return ret; } @@ -1080,8 +839,8 @@ std::string to_string(Number const& amount) { // keep full internal accuracy, but make more human friendly if possible - static constexpr Number kZero = Number{}; - if (amount == kZero) + constexpr Number kZERO = Number{}; + if (amount == kZERO) return "0"; auto exponent = amount.exponent_; @@ -1092,7 +851,7 @@ to_string(Number const& amount) auto const rangeLog = Number::mantissaLog(); if (((exponent != 0) && ((exponent < -(rangeLog + 10)) || (exponent > -(rangeLog - 10))))) { - while (mantissa != 0 && mantissa % 10 == 0 && exponent < Number::kMaxExponent) + while (mantissa != 0 && mantissa % 10 == 0 && exponent < Number::kMAX_EXPONENT) { mantissa /= 10; ++exponent; @@ -1200,7 +959,7 @@ power(Number const& f, unsigned n) Number root(Number f, unsigned d) { - static constexpr Number kZero = Number{}; + constexpr Number kZERO = Number{}; auto const one = Number::one(); if (f == one || d == 1) @@ -1210,12 +969,12 @@ root(Number f, unsigned d) if (f == -one) return one; if (abs(f) < one) - return kZero; + return kZERO; throw std::overflow_error("Number::root infinity"); } - if (f < kZero && d % 2 == 0) + if (f < kZERO && d % 2 == 0) throw std::overflow_error("Number::root nan"); - if (f == kZero) + if (f == kZERO) return f; // Scale f into the range (0, 1) such that f's exponent is a multiple of d @@ -1234,7 +993,7 @@ root(Number f, unsigned d) XRPL_ASSERT_PARTS(f.isnormal(), "xrpl::root(Number, unsigned)", "f is normalized"); bool neg = false; - if (f < kZero) + if (f < kZERO) { neg = true; f = -f; @@ -1272,14 +1031,14 @@ root(Number f, unsigned d) Number root2(Number f) { - static constexpr Number kZero = Number{}; + constexpr Number kZERO = Number{}; auto const one = Number::one(); if (f == one) return f; - if (f < kZero) + if (f < kZERO) throw std::overflow_error("Number::root nan"); - if (f == kZero) + if (f == kZERO) return f; // Scale f into the range (0, 1) such that f's exponent is a multiple of d @@ -1319,7 +1078,7 @@ root2(Number f) Number power(Number const& f, unsigned n, unsigned d) { - static constexpr Number kZero = Number{}; + constexpr Number kZERO = Number{}; auto const one = Number::one(); if (f == one) @@ -1332,7 +1091,7 @@ power(Number const& f, unsigned n, unsigned d) if (f == -one) return one; if (abs(f) < one) - return kZero; + return kZERO; // abs(f) > one throw std::overflow_error("Number::power infinity"); } @@ -1340,7 +1099,7 @@ power(Number const& f, unsigned n, unsigned d) return one; n /= g; d /= g; - if ((n % 2) == 1 && (d % 2) == 0 && f < kZero) + if ((n % 2) == 1 && (d % 2) == 0 && f < kZERO) throw std::overflow_error("Number::power nan"); return root(power(f, n), d); } diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index ddf006b681..4e64c280c7 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -108,7 +108,7 @@ public: beast::Journal journal; - boost::asio::io_context& ioContext; + boost::asio::io_context& io_context; boost::asio::strand strand; boost::asio::ip::tcp::resolver resolver; @@ -116,7 +116,7 @@ public: std::mutex mut; bool asyncHandlersCompleted{true}; - std::atomic stopCalled; + std::atomic stop_called; std::atomic stopped; // Represents a unit of work for the resolver to do @@ -138,10 +138,10 @@ public: ResolverAsioImpl(boost::asio::io_context& ioContext, beast::Journal journal) : journal(journal) - , ioContext(ioContext) + , io_context(ioContext) , strand(boost::asio::make_strand(ioContext)) , resolver(ioContext) - , stopCalled(false) + , stop_called(false) , stopped(true) { } @@ -172,7 +172,7 @@ public: start() override { XRPL_ASSERT(stopped == true, "xrpl::ResolverAsioImpl::start : stopped"); - XRPL_ASSERT(stopCalled == false, "xrpl::ResolverAsioImpl::start : not stopping"); + XRPL_ASSERT(stop_called == false, "xrpl::ResolverAsioImpl::start : not stopping"); if (stopped.exchange(false)) { @@ -187,10 +187,10 @@ public: void stopAsync() override { - if (!stopCalled.exchange(true)) + if (!stop_called.exchange(true)) { boost::asio::dispatch( - ioContext, + io_context, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doStop, this, CompletionCounter(this)))); @@ -213,13 +213,13 @@ public: void resolve(std::vector const& names, HandlerType const& handler) override { - XRPL_ASSERT(stopCalled == false, "xrpl::ResolverAsioImpl::resolve : not stopping"); + XRPL_ASSERT(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( - ioContext, + io_context, boost::asio::bind_executor( strand, std::bind( @@ -231,7 +231,7 @@ public: void doStop(CompletionCounter) { - XRPL_ASSERT(stopCalled == true, "xrpl::ResolverAsioImpl::doStop : stopping"); + XRPL_ASSERT(stop_called == true, "xrpl::ResolverAsioImpl::do_stop : stopping"); if (!stopped.exchange(true)) { @@ -270,7 +270,7 @@ public: handler(name, addresses); boost::asio::post( - ioContext, + io_context, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); } @@ -324,7 +324,7 @@ public: void doWork(CompletionCounter) { - if (stopCalled) + if (stop_called) return; // We don't have any work to do at this time @@ -346,7 +346,7 @@ public: JLOG(journal.error()) << "Unable to parse '" << name << "'"; boost::asio::post( - ioContext, + io_context, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); @@ -369,9 +369,9 @@ public: void doResolve(std::vector const& names, HandlerType const& handler, CompletionCounter) { - XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::doResolve : names non-empty"); + XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::do_resolve : names non-empty"); - if (!stopCalled) + if (!stop_called) { work.emplace_back(names, handler); @@ -381,7 +381,7 @@ public: if (!work.empty()) { boost::asio::post( - ioContext, + io_context, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); diff --git a/src/libxrpl/basics/StringUtilities.cpp b/src/libxrpl/basics/StringUtilities.cpp index f4edaf5aca..f1f8515ae1 100644 --- a/src/libxrpl/basics/StringUtilities.cpp +++ b/src/libxrpl/basics/StringUtilities.cpp @@ -37,7 +37,7 @@ bool parseUrl(ParsedUrl& pUrl, std::string const& strUrl) { // scheme://username:password@hostname:port/rest - static boost::regex const kReUrl( + static boost::regex const kRE_URL( "(?i)\\`\\s*" // required scheme "([[:alpha:]][-+.[:alpha:][:digit:]]*?):" @@ -58,7 +58,7 @@ parseUrl(ParsedUrl& pUrl, std::string const& strUrl) // Bail if there is no match. try { - if (!boost::regex_match(strUrl, smMatch, kReUrl)) + if (!boost::regex_match(strUrl, smMatch, kRE_URL)) return false; } catch (...) @@ -101,7 +101,7 @@ trimWhitespace(std::string str) } std::optional -toUInt64(std::string const& s) +toUint64(std::string const& s) { std::uint64_t result = 0; if (beast::lexicalCastChecked(result, s)) diff --git a/src/libxrpl/basics/UptimeClock.cpp b/src/libxrpl/basics/UptimeClock.cpp index 0ae5f6bfe9..5b92617098 100644 --- a/src/libxrpl/basics/UptimeClock.cpp +++ b/src/libxrpl/basics/UptimeClock.cpp @@ -7,15 +7,15 @@ namespace xrpl { -std::atomic UptimeClock::kNow{0}; // seconds since start -std::atomic UptimeClock::kStop{false}; // stop update thread +std::atomic UptimeClock::kNOW{0}; // seconds since start +std::atomic UptimeClock::kSTOP{false}; // stop update thread // On xrpld shutdown, cancel and wait for the update thread UptimeClock::UpdateThread::~UpdateThread() { if (joinable()) { - kStop = true; + kSTOP = true; // This join() may take up to a 1s, but happens only // once at xrpld shutdown. join(); @@ -30,13 +30,13 @@ UptimeClock::startClock() using namespace std; using namespace std::chrono; - // Wake up every second and update kNow + // Wake up every second and update kNOW auto next = system_clock::now() + 1s; - while (!kStop) + while (!kSTOP) { this_thread::sleep_until(next); next += 1s; - ++kNow; + ++kNOW; } }}; } @@ -49,10 +49,10 @@ UptimeClock::time_point UptimeClock::now() { // start the update thread on first use - static auto const kInit = startClock(); + static auto const kINIT = startClock(); // Return the number of seconds since xrpld start - return time_point{duration{kNow}}; + return time_point{duration{kNOW}}; } } // namespace xrpl diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index 541ddd0839..7a649a8c3a 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -47,15 +47,15 @@ namespace base64 { inline char const* getAlphabet() { - static constexpr char kTab[] = { + static char constexpr kTAB[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; - return &kTab[0]; + return &kTAB[0]; } inline signed char const* getInverse() { - static constexpr signed char kTab[] = { + static signed char constexpr kTAB[] = { -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 @@ -73,19 +73,17 @@ getInverse() -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 &kTab[0]; + return &kTAB[0]; } /// Returns max chars needed to encode a base64 string -constexpr std::size_t -encodedSize(std::size_t n) +std::size_t constexpr encodedSize(std::size_t n) { return 4 * ((n + 2) / 3); } /// Returns max bytes needed to decode a base64 string -constexpr std::size_t -decodedSize(std::size_t n) +std::size_t constexpr decodedSize(std::size_t n) { return ((n / 4) * 3) + 2; } diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index 165d36076b..89da14333a 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -60,7 +60,7 @@ int gDefaultRsaKeyBits = 2048; @note If you increase the number of bits you need to update defaultRSAKeyBits accordingly. */ -static constexpr char kDefaultDh[] = +static constexpr char const kDEFAULT_DH[] = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEApKSWfR7LKy0VoZ/SDCObCvJ5HKX2J93RJ+QN8kJwHh+uuA8G+t8Q\n" "MDRjL5HanlV/sKN9HXqBc7eqHmmbqYwIXKUt9MUZTLNheguddxVlc2IjdP5i9Ps8\n" @@ -84,14 +84,14 @@ static constexpr char kDefaultDh[] = global or per-port basis, using the `ssl_ciphers` directive in the config file. */ -std::string const kDefaultCipherList = "TLSv1.2:!CBC:!DSS:!PSK:!eNULL:!aNULL"; +std::string const kDEFAULT_CIPHER_LIST = "TLSv1.2:!CBC:!DSS:!PSK:!eNULL:!aNULL"; static void initAnonymous(boost::asio::ssl::context& context) { using namespace openssl; - static auto kDefaultRsa = []() { + static auto kDEFAULT_RSA = []() { BIGNUM* bn = BN_new(); BN_set_word(bn, RSA_F4); @@ -108,7 +108,7 @@ initAnonymous(boost::asio::ssl::context& context) return rsa; }(); - static auto kDefaultEphemeralPrivateKey = []() { + static auto kDEFAULT_EPHEMERAL_PRIVATE_KEY = []() { auto pkey = EVP_PKEY_new(); if (!pkey) @@ -116,16 +116,16 @@ 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(kDefaultRsa) != 1) + if (RSA_up_ref(kDEFAULT_RSA) != 1) logicError("EVP_PKEY_assign_RSA: incrementing reference count failed"); - if (!EVP_PKEY_assign_RSA(pkey, kDefaultRsa)) + if (!EVP_PKEY_assign_RSA(pkey, kDEFAULT_RSA)) logicError("EVP_PKEY_assign_RSA failed"); return pkey; }(); - static auto kDefaultCert = []() { + static auto kDEFAULT_CERT = []() { auto x509 = X509_new(); if (x509 == nullptr) @@ -205,9 +205,9 @@ initAnonymous(boost::asio::ssl::context& context) } // And a private key - X509_set_pubkey(x509, kDefaultEphemeralPrivateKey); + X509_set_pubkey(x509, kDEFAULT_EPHEMERAL_PRIVATE_KEY); - if (!X509_sign(x509, kDefaultEphemeralPrivateKey, EVP_sha256())) + if (!X509_sign(x509, kDEFAULT_EPHEMERAL_PRIVATE_KEY, EVP_sha256())) logicError("X509_sign failed"); return x509; @@ -215,10 +215,10 @@ initAnonymous(boost::asio::ssl::context& context) SSL_CTX* const ctx = context.native_handle(); - if (SSL_CTX_use_certificate(ctx, kDefaultCert) <= 0) + if (SSL_CTX_use_certificate(ctx, kDEFAULT_CERT) <= 0) logicError("SSL_CTX_use_certificate failed"); - if (SSL_CTX_use_PrivateKey(ctx, kDefaultEphemeralPrivateKey) <= 0) + if (SSL_CTX_use_PrivateKey(ctx, kDEFAULT_EPHEMERAL_PRIVATE_KEY) <= 0) logicError("SSL_CTX_use_PrivateKey failed"); } @@ -330,12 +330,12 @@ getContext(std::string cipherList) boost::asio::ssl::context::no_compression); if (cipherList.empty()) - cipherList = kDefaultCipherList; + cipherList = kDEFAULT_CIPHER_LIST; 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::kDefaultDh), sizeof(kDefaultDh)}); + c->use_tmp_dh({std::addressof(detail::kDEFAULT_DH), sizeof(kDEFAULT_DH)}); // Disable all renegotiation support in TLS v1.2. This can help prevent // exploitation of the bug described in CVE-2021-3499 (for details see diff --git a/src/libxrpl/basics/mulDiv.cpp b/src/libxrpl/basics/mulDiv.cpp index b5e6304738..64d37a35c3 100644 --- a/src/libxrpl/basics/mulDiv.cpp +++ b/src/libxrpl/basics/mulDiv.cpp @@ -15,7 +15,7 @@ mulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div) result /= div; - if (result > xrpl::kMuldivMax) + if (result > xrpl::kMULDIV_MAX) return std::nullopt; return static_cast(result); diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index ec003ffb1f..2c8ac34b6a 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -40,7 +40,7 @@ static_assert(std::atomic::is_always_lock_free); SecondsClockThread::~SecondsClockThread() { XRPL_ASSERT( - thread_.joinable(), "beast::SecondsClockThread::~SecondsClockThread : thread joinable"); + thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); { std::scoped_lock const lock(mut_); stop_ = true; @@ -81,8 +81,8 @@ SecondsClockThread::run() BasicSecondsClock::time_point BasicSecondsClock::now() { - static SecondsClockThread kClk; - return kClk.now(); + static SecondsClockThread kCLK; + return kCLK.now(); } } // namespace beast diff --git a/src/libxrpl/beast/core/CurrentThreadName.cpp b/src/libxrpl/beast/core/CurrentThreadName.cpp index 52d9063179..39daa286c6 100644 --- a/src/libxrpl/beast/core/CurrentThreadName.cpp +++ b/src/libxrpl/beast/core/CurrentThreadName.cpp @@ -80,19 +80,20 @@ inline void setCurrentThreadNameImpl(std::string_view name) { // truncate and set the thread name. - char boundedName[kMaxThreadNameLength + 1]; + char boundedName[kMAX_THREAD_NAME_LENGTH + 1]; auto const boundedSize = - name.size() < kMaxThreadNameLength ? name.size() : kMaxThreadNameLength; + name.size() < kMAX_THREAD_NAME_LENGTH ? name.size() : kMAX_THREAD_NAME_LENGTH; name.copy(boundedName, boundedSize); boundedName[boundedSize] = '\0'; pthread_setname_np(pthread_self(), boundedName); #ifdef TRUNCATED_THREAD_NAME_LOGS - if (name.size() > kMaxThreadNameLength) + if (name.size() > kMAX_THREAD_NAME_LENGTH) { std::cerr << "WARNING: Thread name \"" << name << "\" (length " << name.size() - << ") exceeds maximum of " << kMaxThreadNameLength << " characters on Linux.\n"; + << ") exceeds maximum of " << kMAX_THREAD_NAME_LENGTH + << " characters on Linux.\n"; } #endif } diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 88f52c26de..90d06ddf28 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -164,7 +164,7 @@ public: private: std::shared_ptr impl_; std::string name_; - GaugeImpl::value_type lastValue_{0}; + GaugeImpl::value_type last_value_{0}; GaugeImpl::value_type value_{0}; bool dirty_{false}; }; @@ -204,12 +204,17 @@ class StatsDCollectorImp : public StatsDCollector, public std::enable_shared_from_this { private: - static constexpr auto kMaxPacketSize = 1472; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + // MaxPacketSize = 484 + MaxPacketSize = 1472 + }; Journal journal_; IP::Endpoint address_; std::string prefix_; - boost::asio::io_context ioContext_; + boost::asio::io_context io_context_; std::optional> work_; boost::asio::strand strand_; boost::asio::basic_waitable_timer timer_; @@ -232,10 +237,10 @@ public: : journal_(journal) , address_(std::move(address)) , prefix_(std::move(prefix)) - , work_(boost::asio::make_work_guard(ioContext_)) - , strand_(boost::asio::make_strand(ioContext_)) - , timer_(ioContext_) - , socket_(ioContext_) + , work_(boost::asio::make_work_guard(io_context_)) + , strand_(boost::asio::make_strand(io_context_)) + , timer_(io_context_) + , socket_(io_context_) , thread_(&StatsDCollectorImp::run, this) { } @@ -306,7 +311,7 @@ public: boost::asio::io_context& getIoContext() { - return ioContext_; + return io_context_; } std::string const& @@ -325,7 +330,7 @@ public: postBuffer(std::string&& buffer) { boost::asio::dispatch( - ioContext_, + io_context_, boost::asio::bind_executor( strand_, std::bind(&StatsDCollectorImp::doPostBuffer, this, std::move(buffer)))); } @@ -387,7 +392,7 @@ public: !s.empty(), "beast::insight::detail::StatsDCollectorImp::sendBuffers : " "non-empty payload"); - if (!buffers.empty() && (size + length) > kMaxPacketSize) + if (!buffers.empty() && (size + length) > MaxPacketSize) { log(buffers); socket_.async_send( @@ -465,14 +470,14 @@ public: setTimer(); - ioContext_.run(); + io_context_.run(); // NOLINTNEXTLINE(bugprone-unused-return-value) socket_.shutdown(boost::asio::ip::udp::socket::shutdown_send, ec); socket_.close(); - ioContext_.poll(); + io_context_.poll(); } }; @@ -628,9 +633,9 @@ StatsDGaugeImpl::doSet(GaugeImpl::value_type value) { value_ = value; - if (value_ != lastValue_) + if (value_ != last_value_) { - lastValue_ = value_; + last_value_ = value_; dirty_ = true; } } diff --git a/src/libxrpl/beast/net/IPAddressV4.cpp b/src/libxrpl/beast/net/IPAddressV4.cpp index f9b0c96022..48554d0ec3 100644 --- a/src/libxrpl/beast/net/IPAddressV4.cpp +++ b/src/libxrpl/beast/net/IPAddressV4.cpp @@ -14,52 +14,14 @@ isPrivate(AddressV4 const& addr) bool isPublic(AddressV4 const& addr) { - if (isPrivate(addr)) - return false; - if (addr.is_multicast()) - return false; - - auto const ip = addr.to_uint(); - - // 0.0.0.0/8 "This network" - if ((ip & 0xff000000) == 0x00000000) - return false; - // 100.64.0.0/10 Shared Address Space (CGNAT) - RFC 6598 - if ((ip & 0xffc00000) == 0x64400000) - return false; - // 169.254.0.0/16 Link-local - if ((ip & 0xffff0000) == 0xa9fe0000) - return false; - // 192.0.0.0/24 IETF Protocol Assignments - RFC 6890 - if ((ip & 0xffffff00) == 0xc0000000) - return false; - // 192.0.2.0/24 TEST-NET-1 (documentation) - RFC 5737 - if ((ip & 0xffffff00) == 0xc0000200) - return false; - // 192.88.99.0/24 6to4 Relay Anycast (deprecated) - RFC 7526 - if ((ip & 0xffffff00) == 0xc0586300) - return false; - // 198.18.0.0/15 Benchmarking - RFC 2544 - if ((ip & 0xfffe0000) == 0xc6120000) - return false; - // 198.51.100.0/24 TEST-NET-2 (documentation) - RFC 5737 - if ((ip & 0xffffff00) == 0xc6336400) - return false; - // 203.0.113.0/24 TEST-NET-3 (documentation) - RFC 5737 - if ((ip & 0xffffff00) == 0xcb007100) - return false; - // 240.0.0.0/4 Reserved for future use - RFC 1112 - if ((ip & 0xf0000000) == 0xf0000000) - return false; - - return true; + return !isPrivate(addr) && !addr.is_multicast(); } char getClass(AddressV4 const& addr) { - static char const* kTable = "AAAABBCD"; // cspell:disable-line - return kTable[(addr.to_uint() & 0xE0000000) >> 29]; + static char const* kTABLE = "AAAABBCD"; // cspell:disable-line + return kTABLE[(addr.to_uint() & 0xE0000000) >> 29]; } } // namespace beast::IP diff --git a/src/libxrpl/beast/net/IPAddressV6.cpp b/src/libxrpl/beast/net/IPAddressV6.cpp index c75ccaf1cc..fad11dddc0 100644 --- a/src/libxrpl/beast/net/IPAddressV6.cpp +++ b/src/libxrpl/beast/net/IPAddressV6.cpp @@ -9,53 +9,17 @@ namespace beast::IP { bool isPrivate(AddressV6 const& addr) { - // fc00::/7 - Unique Local Address (ULA), covers fc00:: and fd00:: - if ((addr.to_bytes()[0] & 0xfe) == 0xfc) - return true; - if (addr.is_v4_mapped()) - return isPrivate(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)); - return false; + return ( + ((addr.to_bytes()[0] & 0xfd) != 0) || // TODO fc00::/8 too ? + (addr.is_v4_mapped() && + isPrivate(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)))); } bool isPublic(AddressV6 const& addr) { - if (addr.is_loopback()) - return false; - if (addr.is_v4_mapped()) - return isPublic(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)); - if (isPrivate(addr)) - return false; - if (addr.is_multicast()) - return false; - if (addr.is_unspecified()) - return false; - - auto const b = addr.to_bytes(); - - // fe80::/10 - Link-local - if (b[0] == 0xfe && (b[1] & 0xc0) == 0x80) - return false; - // 100::/64 - Discard prefix (RFC 6666) - if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0 && b[3] == 0 && b[4] == 0 && b[5] == 0 && - b[6] == 0 && b[7] == 0) - return false; - // 2001:db8::/32 - Documentation (RFC 3849) - if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0d && b[3] == 0xb8) - return false; - // 2001::/32 - IETF Protocol Assignments / Teredo (RFC 4380) - if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00) - return false; - // 2001:20::/28 - ORCHIDv2 (RFC 7343) - // 28-bit prefix: 0x2001002 => b[0]=0x20, b[1]=0x01, b[2]=0x00, - // top nibble of b[3]=0x2 - if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && (b[3] & 0xf0) == 0x20) - return false; - // 2002::/16 - 6to4 (RFC 3056, deprecated by RFC 7526) - if (b[0] == 0x20 && b[1] == 0x02) - return false; - - return true; + // TODO is this correct? + return !isPrivate(addr) && !addr.is_multicast(); } } // namespace beast::IP diff --git a/src/libxrpl/beast/utility/beast_Journal.cpp b/src/libxrpl/beast/utility/beast_Journal.cpp index 0837dd2392..abe5072461 100644 --- a/src/libxrpl/beast/utility/beast_Journal.cpp +++ b/src/libxrpl/beast/utility/beast_Journal.cpp @@ -12,14 +12,14 @@ namespace beast { class NullJournalSink : public Journal::Sink { public: - NullJournalSink() : Sink(Severity::Disabled, false) + NullJournalSink() : Sink(severities::KDisabled, false) { } ~NullJournalSink() override = default; [[nodiscard]] bool - active(Severity) const override + active(severities::Severity) const override { return false; } @@ -35,24 +35,24 @@ public: { } - [[nodiscard]] Severity + [[nodiscard]] severities::Severity threshold() const override { - return Severity::Disabled; + return severities::KDisabled; } void - threshold(Severity) override + threshold(severities::Severity) override { } void - write(Severity, std::string const&) override + write(severities::Severity, std::string const&) override { } void - writeAlways(Severity, std::string const&) override + writeAlways(severities::Severity, std::string const&) override { } }; @@ -62,8 +62,8 @@ public: Journal::Sink& Journal::getNullSink() { - static NullJournalSink kSink; - return kSink; + static NullJournalSink kSINK; + return kSINK; } //------------------------------------------------------------------------------ @@ -92,7 +92,7 @@ Journal::Sink::console(bool output) console_ = output; } -Severity +severities::Severity Journal::Sink::threshold() const { return thresh_; diff --git a/src/libxrpl/conditions/Condition.cpp b/src/libxrpl/conditions/Condition.cpp index cb950c9e24..004778bc4e 100644 --- a/src/libxrpl/conditions/Condition.cpp +++ b/src/libxrpl/conditions/Condition.cpp @@ -52,7 +52,7 @@ namespace detail { // ed25519Sha256 (4) // } -constexpr std::size_t kFingerprintSize = 32; +constexpr std::size_t kFINGERPRINT_SIZE = 32; std::unique_ptr loadSimpleSha256(Type type, Slice s, std::error_code& ec) @@ -76,7 +76,7 @@ loadSimpleSha256(Type type, Slice s, std::error_code& ec) return {}; } - if (p.length != kFingerprintSize) + if (p.length != kFINGERPRINT_SIZE) { ec = Error::FingerprintSize; return {}; @@ -118,7 +118,7 @@ loadSimpleSha256(Type type, Slice s, std::error_code& ec) switch (type) { case Type::PreimageSha256: - if (cost > PreimageSha256::kMaxPreimageLength) + if (cost > PreimageSha256::kMAX_PREIMAGE_LENGTH) { ec = Error::PreimageTooLong; return {}; @@ -173,7 +173,7 @@ Condition::deserialize(Slice s, std::error_code& ec) return {}; } - if (s.size() > kMaxSerializedCondition) + if (s.size() > kMAX_SERIALIZED_CONDITION) { ec = Error::LargeSize; return {}; diff --git a/src/libxrpl/conditions/Fulfillment.cpp b/src/libxrpl/conditions/Fulfillment.cpp index eaad6b8cdb..52f89a6150 100644 --- a/src/libxrpl/conditions/Fulfillment.cpp +++ b/src/libxrpl/conditions/Fulfillment.cpp @@ -82,7 +82,7 @@ Fulfillment::deserialize(Slice s, std::error_code& ec) return {}; } - if (p.length > kMaxSerializedFulfillment) + if (p.length > kMAX_SERIALIZED_FULFILLMENT) { ec = Error::LargeSize; return {}; diff --git a/src/libxrpl/conditions/error.cpp b/src/libxrpl/conditions/error.cpp index 48e8ece94f..a26a153975 100644 --- a/src/libxrpl/conditions/error.cpp +++ b/src/libxrpl/conditions/error.cpp @@ -101,8 +101,8 @@ public: inline std::error_category const& getCryptoconditionsErrorCategory() { - static CryptoconditionsErrorCategory const kCat{}; - return kCat; + static CryptoconditionsErrorCategory const kCAT{}; + return kCAT; } } // namespace detail diff --git a/src/libxrpl/core/detail/Job.cpp b/src/libxrpl/core/detail/Job.cpp index 89fe42db05..a1b88864d7 100644 --- a/src/libxrpl/core/detail/Job.cpp +++ b/src/libxrpl/core/detail/Job.cpp @@ -25,7 +25,7 @@ Job::Job( std::uint64_t index, LoadMonitor& lm, std::function const& job) - : type_(type), jobIndex_(index), job_(job), name_(name), queueTime_(clock_type::now()) + : type_(type), jobIndex_(index), job_(job), name_(name), queue_time_(clock_type::now()) { loadEvent_ = std::make_shared(std::ref(lm), name, false); } @@ -39,7 +39,7 @@ Job::getType() const Job::clock_type::time_point const& Job::queueTime() const { - return queueTime_; + return queue_time_; } void diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 5c07bf68cc..06a2d226e1 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -36,7 +36,7 @@ JobQueue::JobQueue( JLOG(journal_.info()) << "Using " << threadCount << " threads"; hook_ = collector_->makeHook(std::bind(&JobQueue::collect, this)); - jobCount_ = collector_->makeGauge("job_count"); + job_count_ = collector_->makeGauge("job_count"); { std::scoped_lock const lock(mutex_); @@ -66,7 +66,7 @@ void JobQueue::collect() { std::scoped_lock const lock(mutex_); - jobCount_ = jobSet_.size(); + job_count_ = jobSet_.size(); } bool @@ -186,11 +186,11 @@ json::Value JobQueue::getJson(int c) { using namespace std::chrono_literals; - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret["threads"] = workers_.getNumberOfThreads(); - json::Value priorities = json::ValueType::Array; + json::Value priorities = json::ArrayValue; std::scoped_lock const lock(mutex_); @@ -210,7 +210,7 @@ JobQueue::getJson(int c) if ((stats.count != 0) || (waiting != 0) || (stats.latencyPeak != 0ms) || (running != 0)) { - json::Value& pri = priorities.append(json::ValueType::Object); + json::Value& pri = priorities.append(json::ObjectValue); pri["job_type"] = data.name(); diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index 0d9c1afd26..991c51b77a 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -46,7 +46,7 @@ Workers::getNumberOfThreads() const noexcept void Workers::setNumberOfThreads(int numberOfThreads) { - static int kInstance{0}; + static int kINSTANCE{0}; if (numberOfThreads_ == numberOfThreads) return; @@ -72,7 +72,7 @@ Workers::setNumberOfThreads(int numberOfThreads) } else { - worker = new Worker(*this, threadNames_, kInstance++); + worker = new Worker(*this, threadNames_, kINSTANCE++); everyone_.pushFront(worker); } } diff --git a/src/libxrpl/crypto/csprng.cpp b/src/libxrpl/crypto/csprng.cpp index e000786c4a..897432fcf1 100644 --- a/src/libxrpl/crypto/csprng.cpp +++ b/src/libxrpl/crypto/csprng.cpp @@ -80,8 +80,8 @@ CsprngEngine::operator()() CsprngEngine& cryptoPrng() { - static CsprngEngine kEngine; - return kEngine; + static CsprngEngine kENGINE; + return kENGINE; } } // namespace xrpl diff --git a/src/libxrpl/git/Git.cpp b/src/libxrpl/git/Git.cpp index d5f3a24b3a..e13b2ef693 100644 --- a/src/libxrpl/git/Git.cpp +++ b/src/libxrpl/git/Git.cpp @@ -11,21 +11,21 @@ namespace xrpl::git { -static constexpr char kGitCommitHash[] = GIT_COMMIT_HASH; -static constexpr char kGitBuildBranch[] = GIT_BUILD_BRANCH; +static constexpr char kGIT_COMMIT_HASH[] = GIT_COMMIT_HASH; +static constexpr char kGIT_BUILD_BRANCH[] = GIT_BUILD_BRANCH; std::string const& getCommitHash() { - static std::string const kValue = kGitCommitHash; - return kValue; + static std::string const kVALUE = kGIT_COMMIT_HASH; + return kVALUE; } std::string const& getBuildBranch() { - static std::string const kValue = kGitBuildBranch; - return kValue; + static std::string const kVALUE = kGIT_BUILD_BRANCH; + return kVALUE; } } // namespace xrpl::git diff --git a/src/libxrpl/json/JsonPropertyStream.cpp b/src/libxrpl/json/JsonPropertyStream.cpp index d4d343e186..b6a151d702 100644 --- a/src/libxrpl/json/JsonPropertyStream.cpp +++ b/src/libxrpl/json/JsonPropertyStream.cpp @@ -6,7 +6,7 @@ namespace xrpl { -JsonPropertyStream::JsonPropertyStream() : topValue(json::ValueType::Object) +JsonPropertyStream::JsonPropertyStream() : topValue(json::ObjectValue) { stack.reserve(64); stack.push_back(&topValue); @@ -23,7 +23,7 @@ JsonPropertyStream::mapBegin() { // top is array json::Value& top(*stack.back()); - json::Value& map(top.append(json::ValueType::Object)); + json::Value& map(top.append(json::ObjectValue)); stack.push_back(&map); } @@ -32,7 +32,7 @@ JsonPropertyStream::mapBegin(std::string const& key) { // top is a map json::Value& top(*stack.back()); - json::Value& map(top[key] = json::ValueType::Object); + json::Value& map(top[key] = json::ObjectValue); stack.push_back(&map); } @@ -95,7 +95,7 @@ JsonPropertyStream::arrayBegin() { // top is array json::Value& top(*stack.back()); - json::Value& vec(top.append(json::ValueType::Array)); + json::Value& vec(top.append(json::ArrayValue)); stack.push_back(&vec); } @@ -104,7 +104,7 @@ JsonPropertyStream::arrayBegin(std::string const& key) { // top is a map json::Value& top(*stack.back()); - json::Value& vec(top[key] = json::ValueType::Array); + json::Value& vec(top[key] = json::ArrayValue); stack.push_back(&vec); } diff --git a/src/libxrpl/json/Output.cpp b/src/libxrpl/json/Output.cpp index dc411f92b2..14b6617b2f 100644 --- a/src/libxrpl/json/Output.cpp +++ b/src/libxrpl/json/Output.cpp @@ -10,41 +10,41 @@ namespace json { namespace { void -outputJson(Value const& value, Writer& writer) +outputJson(json::Value const& value, Writer& writer) { switch (value.type()) { - case ValueType::Null: { + case json::NullValue: { writer.output(nullptr); break; } - case ValueType::Int: { + case json::IntValue: { writer.output(value.asInt()); break; } - case ValueType::UInt: { + case json::UintValue: { writer.output(value.asUInt()); break; } - case ValueType::Real: { + case json::RealValue: { writer.output(value.asDouble()); break; } - case ValueType::String: { + case json::StringValue: { writer.output(value.asString()); break; } - case ValueType::Boolean: { + case json::BooleanValue: { writer.output(value.asBool()); break; } - case ValueType::Array: { + case json::ArrayValue: { writer.startRoot(Writer::CollectionType::Array); for (auto const& i : value) { @@ -55,7 +55,7 @@ outputJson(Value const& value, Writer& writer) break; } - case ValueType::Object: { + case json::ObjectValue: { writer.startRoot(Writer::CollectionType::Object); auto members = value.getMemberNames(); for (auto const& tag : members) @@ -72,14 +72,14 @@ outputJson(Value const& value, Writer& writer) } // namespace void -outputJson(Value const& value, Output const& out) +outputJson(json::Value const& value, Output const& out) { Writer writer(out); outputJson(value, writer); } std::string -jsonAsString(Value const& value) +jsonAsString(json::Value const& value) { std::string s; Writer writer(stringOutput(s)); diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index c5c4b3cd31..518573ded4 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -26,18 +26,18 @@ std::map gJsonSpecialCharacterEscape = { {'\r', "\\r"}, {'\t', "\\t"}}; -size_t const kJsonEscapeLength = 2; +size_t const kJSON_ESCAPE_LENGTH = 2; // All other JSON punctuation. -char const kCloseBrace = '}'; -char const kCloseBracket = ']'; -char const kColon = ':'; -char const kComma = ','; -char const kOpenBrace = '{'; -char const kOpenBracket = '['; -char const kQuote = '"'; +char const kCLOSE_BRACE = '}'; +char const kCLOSE_BRACKET = ']'; +char const kCOLON = ':'; +char const kCOMMA = ','; +char const kOPEN_BRACE = '{'; +char const kOPEN_BRACKET = '['; +char const kQUOTE = '"'; -auto const kIntegralFloatsBecomeInts = false; +auto const kINTEGRAL_FLOATS_BECOME_INTS = false; size_t lengthWithoutTrailingZeros(std::string const& s) @@ -52,7 +52,7 @@ lengthWithoutTrailingZeros(std::string const& s) if (hasDecimals) return lastNonZero + 1; - if (kIntegralFloatsBecomeInts || lastNonZero + 2 > s.size()) + if (kINTEGRAL_FLOATS_BECOME_INTS || lastNonZero + 2 > s.size()) return lastNonZero; return lastNonZero + 2; @@ -81,7 +81,7 @@ public: void start(CollectionType ct) { - char const ch = (ct == CollectionType::Array) ? kOpenBracket : kOpenBrace; + char const ch = (ct == CollectionType::Array) ? kOPEN_BRACKET : kOPEN_BRACE; output({&ch, 1}); stack_.emplace(Collection{.type = ct}); } @@ -99,7 +99,7 @@ public: markStarted(); std::size_t position = 0, writtenUntil = 0; - output_({&kQuote, 1}); + output_({&kQUOTE, 1}); auto data = bytes.data(); for (; position < bytes.size(); ++position) { @@ -110,13 +110,13 @@ public: { output_({data + writtenUntil, position - writtenUntil}); } - output_({i->second, kJsonEscapeLength}); + output_({i->second, kJSON_ESCAPE_LENGTH}); writtenUntil = position + 1; }; } if (writtenUntil < position) output_({data + writtenUntil, position - writtenUntil}); - output_({&kQuote, 1}); + output_({&kQUOTE, 1}); } void @@ -144,7 +144,7 @@ public: } else { - output_({&kComma, 1}); + output_({&kCOMMA, 1}); } } @@ -159,7 +159,7 @@ public: #endif stringOutput(tag); - output_({&kColon, 1}); + output_({&kCOLON, 1}); } [[nodiscard]] bool @@ -174,7 +174,7 @@ public: check(!empty(), "Empty stack in finish()"); auto isArray = stack_.top().type == CollectionType::Array; - auto ch = isArray ? kCloseBracket : kCloseBrace; + auto ch = isArray ? kCLOSE_BRACKET : kCLOSE_BRACE; output_({&ch, 1}); stack_.pop(); } diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 3786f51fdd..6574789e7b 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -102,7 +102,7 @@ Reader::parse(char const* beginDoc, char const* endDoc, Value& root) { // Set error location to start of doc, ideally should be first token // found in doc - token.type = TokenType::Error; + token.type = TokenError; token.start = beginDoc; token.end = endDoc; addError("A valid JSON document must be either an array or an object value.", token); @@ -117,41 +117,41 @@ Reader::readValue(unsigned depth) { Token token{}; skipCommentTokens(token); - if (depth > kNestLimit) + if (depth > kNEST_LIMIT) return addError("Syntax error: maximum nesting depth exceeded", token); bool successful = true; switch (token.type) { - case TokenType::ObjectBegin: + case TokenObjectBegin: successful = readObject(token, depth); break; - case TokenType::ArrayBegin: + case TokenArrayBegin: successful = readArray(token, depth); break; - case TokenType::Integer: + case TokenInteger: successful = decodeNumber(token); break; - case TokenType::Double: + case TokenDouble: successful = decodeDouble(token); break; - case TokenType::String: + case TokenString: successful = decodeString(token); break; - case TokenType::True: + case TokenTrue: currentValue() = true; break; - case TokenType::False: + case TokenFalse: currentValue() = false; break; - case TokenType::Null: + case TokenNull: currentValue() = Value(); break; @@ -168,7 +168,7 @@ Reader::skipCommentTokens(Token& token) do { readToken(token); - } while (token.type == TokenType::Comment); + } while (token.type == TokenComment); } bool @@ -193,28 +193,28 @@ Reader::readToken(Token& token) switch (c) { case '{': - token.type = TokenType::ObjectBegin; + token.type = TokenObjectBegin; break; case '}': - token.type = TokenType::ObjectEnd; + token.type = TokenObjectEnd; break; case '[': - token.type = TokenType::ArrayBegin; + token.type = TokenArrayBegin; break; case ']': - token.type = TokenType::ArrayEnd; + token.type = TokenArrayEnd; break; case '"': - token.type = TokenType::String; + token.type = TokenString; ok = readString(); break; case '/': - token.type = TokenType::Comment; + token.type = TokenComment; ok = readComment(); break; @@ -233,30 +233,30 @@ Reader::readToken(Token& token) break; case 't': - token.type = TokenType::True; + token.type = TokenTrue; ok = match("rue", 3); break; case 'f': - token.type = TokenType::False; + token.type = TokenFalse; ok = match("alse", 4); // cspell:disable-line break; case 'n': - token.type = TokenType::Null; + token.type = TokenNull; ok = match("ull", 3); break; case ',': - token.type = TokenType::ArraySeparator; + token.type = TokenArraySeparator; break; case ':': - token.type = TokenType::MemberSeparator; + token.type = TokenMemberSeparator; break; case 0: - token.type = TokenType::EndOfStream; + token.type = TokenEndOfStream; break; default: @@ -265,7 +265,7 @@ Reader::readToken(Token& token) } if (!ok) - token.type = TokenType::Error; + token.type = TokenError; token.end = current_; return true; @@ -352,9 +352,9 @@ Reader::readCppStyleComment() Reader::TokenType Reader::readNumber() { - static char const kExtendedTokens[] = {'.', 'e', 'E', '+', '-'}; + static char const kEXTENDED_TOKENS[] = {'.', 'e', 'E', '+', '-'}; - TokenType type = TokenType::Integer; + TokenType type = TokenInteger; if (current_ != end_) { @@ -365,12 +365,12 @@ Reader::readNumber() { if (std::isdigit(static_cast(*current_)) == 0) { - auto ret = std::ranges::find(kExtendedTokens, *current_); + auto ret = std::ranges::find(kEXTENDED_TOKENS, *current_); - if (ret == std::end(kExtendedTokens)) + if (ret == std::end(kEXTENDED_TOKENS)) break; - type = TokenType::Double; + type = TokenDouble; } ++current_; @@ -407,35 +407,35 @@ Reader::readObject(Token& tokenStart, unsigned depth) { Token tokenName{}; std::string name; - currentValue() = Value(ValueType::Object); + currentValue() = Value(ObjectValue); while (readToken(tokenName)) { bool initialTokenOk = true; - while (tokenName.type == TokenType::Comment && initialTokenOk) + while (tokenName.type == TokenComment && initialTokenOk) initialTokenOk = readToken(tokenName); if (!initialTokenOk) break; - if (tokenName.type == TokenType::ObjectEnd && name.empty()) // empty object + if (tokenName.type == TokenObjectEnd && name.empty()) // empty object return true; - if (tokenName.type != TokenType::String) + if (tokenName.type != TokenString) break; name = ""; if (!decodeString(tokenName, name)) - return recoverFromError(TokenType::ObjectEnd); + return recoverFromError(TokenObjectEnd); Token colon{}; - if (!readToken(colon) || colon.type != TokenType::MemberSeparator) + if (!readToken(colon) || colon.type != TokenMemberSeparator) { return addErrorAndRecover( - "Missing ':' after object member name", colon, TokenType::ObjectEnd); + "Missing ':' after object member name", colon, TokenObjectEnd); } // Reject duplicate names @@ -448,34 +448,34 @@ Reader::readObject(Token& tokenStart, unsigned depth) nodes_.pop(); if (!ok) // error already set - return recoverFromError(TokenType::ObjectEnd); + return recoverFromError(TokenObjectEnd); Token comma{}; if (!readToken(comma) || - (comma.type != TokenType::ObjectEnd && comma.type != TokenType::ArraySeparator && - comma.type != TokenType::Comment)) + (comma.type != TokenObjectEnd && comma.type != TokenArraySeparator && + comma.type != TokenComment)) { return addErrorAndRecover( - "Missing ',' or '}' in object declaration", comma, TokenType::ObjectEnd); + "Missing ',' or '}' in object declaration", comma, TokenObjectEnd); } bool finalizeTokenOk = true; - while (comma.type == TokenType::Comment && finalizeTokenOk) + while (comma.type == TokenComment && finalizeTokenOk) finalizeTokenOk = readToken(comma); - if (comma.type == TokenType::ObjectEnd) + if (comma.type == TokenObjectEnd) return true; } - return addErrorAndRecover("Missing '}' or object member name", tokenName, TokenType::ObjectEnd); + return addErrorAndRecover("Missing '}' or object member name", tokenName, TokenObjectEnd); } bool Reader::readArray(Token& tokenStart, unsigned depth) { - currentValue() = Value(ValueType::Array); + currentValue() = Value(ArrayValue); skipSpaces(); if (*current_ == ']') // empty array @@ -495,27 +495,27 @@ Reader::readArray(Token& tokenStart, unsigned depth) nodes_.pop(); if (!ok) // error already set - return recoverFromError(TokenType::ArrayEnd); + return recoverFromError(TokenArrayEnd); Token token{}; // Accept Comment after last item in the array. ok = readToken(token); - while (token.type == TokenType::Comment && ok) + while (token.type == TokenComment && ok) { ok = readToken(token); } bool const badTokenType = - (token.type != TokenType::ArraySeparator && token.type != TokenType::ArrayEnd); + (token.type != TokenArraySeparator && token.type != TokenArrayEnd); if (!ok || badTokenType) { return addErrorAndRecover( - "Missing ',' or ']' in array declaration", token, TokenType::ArrayEnd); + "Missing ',' or ']' in array declaration", token, TokenArrayEnd); } - if (token.type == TokenType::ArrayEnd) + if (token.type == TokenArrayEnd) break; } @@ -542,10 +542,10 @@ Reader::decodeNumber(Token& token) std::int64_t value = 0; static_assert( - sizeof(value) > sizeof(Value::kMaxUInt), + sizeof(value) > sizeof(Value::kMAX_U_INT), "The JSON integer overflow logic will need to be reworked."); - while (current < token.end && (value <= Value::kMaxUInt)) + while (current < token.end && (value <= Value::kMAX_U_INT)) { Char const c = *current++; @@ -569,7 +569,7 @@ Reader::decodeNumber(Token& token) { value = -value; - if (value < Value::kMinInt || value > Value::kMaxInt) + if (value < Value::kMIN_INT || value > Value::kMAX_INT) { return addError( "'" + std::string(token.start, token.end) + "' exceeds the allowable range.", @@ -580,7 +580,7 @@ Reader::decodeNumber(Token& token) } else { - if (value > Value::kMaxUInt) + if (value > Value::kMAX_U_INT) { return addError( "'" + std::string(token.start, token.end) + "' exceeds the allowable range.", @@ -588,7 +588,7 @@ Reader::decodeNumber(Token& token) } // If it's representable as a signed integer, construct it as one. - if (value <= Value::kMaxInt) + if (value <= Value::kMAX_INT) { currentValue() = static_cast(value); } @@ -834,7 +834,7 @@ Reader::recoverFromError(TokenType skipUntilToken) if (!readToken(skip)) errors_.resize(errorCount); // discard errors caused by recovery - if (skip.type == skipUntilToken || skip.type == TokenType::EndOfStream) + if (skip.type == skipUntilToken || skip.type == TokenEndOfStream) break; } diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index 93875f497a..e7dc4b067b 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -17,7 +17,7 @@ namespace json { -Value const Value::kNull; +Value const Value::kNULL; class DefaultValueAllocator : public ValueAllocator { @@ -37,13 +37,13 @@ public: } char* - duplicateStringValue(char const* value, unsigned int length = kUnknown) override + duplicateStringValue(char const* value, unsigned int length = Unknown) override { //@todo investigate this old optimization // if ( !value || value[0] == 0 ) // return 0; - if (length == kUnknown) + if (length == Unknown) length = (value != nullptr) ? (unsigned int)strlen(value) : 0; char* newString = static_cast(malloc(length + 1)); @@ -64,8 +64,8 @@ public: static ValueAllocator*& valueAllocator() { - static ValueAllocator* kValueAllocator = new DefaultValueAllocator; // NOLINT TODO - return kValueAllocator; + static ValueAllocator* kVALUE_ALLOCATOR = new DefaultValueAllocator; // NOLINT TODO + return kVALUE_ALLOCATOR; } static struct DummyValueAllocatorInitializer @@ -93,30 +93,26 @@ Value::CZString::CZString(int index) : cstr_(0), index_(index) } Value::CZString::CZString(char const* cstr, DuplicationPolicy allocate) - : cstr_( - allocate == DuplicationPolicy::Duplicate ? valueAllocator()->makeMemberName(cstr) : cstr) - , index_(static_cast(allocate)) + : cstr_(allocate == Duplicate ? valueAllocator()->makeMemberName(cstr) : cstr), index_(allocate) { } Value::CZString::CZString(CZString const& other) : cstr_( - other.index_ != static_cast(DuplicationPolicy::NoDuplication) && other.cstr_ != 0 + other.index_ != NoDuplication && other.cstr_ != 0 ? valueAllocator()->makeMemberName(other.cstr_) : other.cstr_) , index_([&]() -> int { if (!other.cstr_) return other.index_; - return other.index_ == static_cast(DuplicationPolicy::NoDuplication) - ? static_cast(DuplicationPolicy::NoDuplication) - : static_cast(DuplicationPolicy::Duplicate); + return other.index_ == NoDuplication ? NoDuplication : Duplicate; }()) { } Value::CZString::~CZString() { - if ((cstr_ != nullptr) && index_ == static_cast(DuplicationPolicy::Duplicate)) + if ((cstr_ != nullptr) && index_ == Duplicate) valueAllocator()->releaseMemberName(const_cast(cstr_)); } @@ -153,7 +149,7 @@ Value::CZString::cStr() const bool Value::CZString::isStaticString() const { - return index_ == static_cast(DuplicationPolicy::NoDuplication); + return index_ == NoDuplication; } // ////////////////////////////////////////////////////////////////// @@ -172,28 +168,28 @@ Value::Value(ValueType type) : type_(type) { switch (type) { - case ValueType::Null: + case NullValue: break; - case ValueType::Int: - case ValueType::UInt: + case IntValue: + case UintValue: value_.intVal = 0; break; - case ValueType::Real: + case RealValue: value_.realVal = 0.0; break; - case ValueType::String: + case StringValue: value_.stringVal = 0; break; - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: value_.mapVal = new ObjectValues(); break; - case ValueType::Boolean: + case BooleanValue: value_.boolVal = false; break; @@ -204,44 +200,44 @@ Value::Value(ValueType type) : type_(type) } } -Value::Value(Int value) : type_(ValueType::Int) +Value::Value(Int value) : type_(IntValue) { value_.intVal = value; } -Value::Value(UInt value) : type_(ValueType::UInt) +Value::Value(UInt value) : type_(UintValue) { value_.uintVal = value; } -Value::Value(double value) : type_(ValueType::Real) +Value::Value(double value) : type_(RealValue) { value_.realVal = value; } -Value::Value(char const* value) : type_(ValueType::String), allocated_(true) +Value::Value(char const* value) : type_(StringValue), allocated_(true) { value_.stringVal = valueAllocator()->duplicateStringValue(value); } -Value::Value(xrpl::Number const& value) : type_(ValueType::String), allocated_(true) +Value::Value(xrpl::Number const& value) : type_(StringValue), allocated_(true) { auto const tmp = to_string(value); value_.stringVal = valueAllocator()->duplicateStringValue(tmp.c_str(), tmp.length()); } -Value::Value(std::string const& value) : type_(ValueType::String), allocated_(true) +Value::Value(std::string const& value) : type_(StringValue), allocated_(true) { value_.stringVal = valueAllocator()->duplicateStringValue(value.c_str(), (unsigned int)value.length()); } -Value::Value(StaticString const& value) : type_(ValueType::String) +Value::Value(StaticString const& value) : type_(StringValue) { value_.stringVal = const_cast(value.cStr()); } -Value::Value(bool value) : type_(ValueType::Boolean) +Value::Value(bool value) : type_(BooleanValue) { value_.boolVal = value; } @@ -250,15 +246,15 @@ Value::Value(Value const& other) : type_(other.type_) { switch (type_) { - case ValueType::Null: - case ValueType::Int: - case ValueType::UInt: - case ValueType::Real: - case ValueType::Boolean: + case NullValue: + case IntValue: + case UintValue: + case RealValue: + case BooleanValue: value_ = other.value_; break; - case ValueType::String: + case StringValue: if (other.value_.stringVal != nullptr) { value_.stringVal = valueAllocator()->duplicateStringValue(other.value_.stringVal); @@ -271,8 +267,8 @@ Value::Value(Value const& other) : type_(other.type_) break; - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: value_.mapVal = new ObjectValues(*other.value_.mapVal); break; @@ -287,21 +283,21 @@ Value::~Value() { switch (type_) { - case ValueType::Null: - case ValueType::Int: - case ValueType::UInt: - case ValueType::Real: - case ValueType::Boolean: + case NullValue: + case IntValue: + case UintValue: + case RealValue: + case BooleanValue: break; - case ValueType::String: + case StringValue: if (allocated_) valueAllocator()->releaseStringValue(value_.stringVal); break; - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: if (value_.mapVal != nullptr) delete value_.mapVal; break; @@ -324,7 +320,7 @@ Value::operator=(Value const& other) Value::Value(Value&& other) noexcept : value_(other.value_), type_(other.type_), allocated_(other.allocated_) { - other.type_ = ValueType::Null; + other.type_ = NullValue; other.allocated_ = 0; } @@ -372,13 +368,13 @@ integerCmp(Int i, UInt ui) bool operator<(Value const& x, Value const& y) { - if (auto signum = static_cast(x.type_) - static_cast(y.type_)) + if (auto signum = x.type_ - y.type_) { - if (x.type_ == ValueType::Int && y.type_ == ValueType::UInt) + if (x.type_ == IntValue && y.type_ == UintValue) { signum = integerCmp(x.value_.intVal, y.value_.uintVal); } - else if (x.type_ == ValueType::UInt && y.type_ == ValueType::Int) + else if (x.type_ == UintValue && y.type_ == IntValue) { signum = -integerCmp(y.value_.intVal, x.value_.uintVal); } @@ -387,28 +383,28 @@ operator<(Value const& x, Value const& y) switch (x.type_) { - case ValueType::Null: + case NullValue: return false; - case ValueType::Int: + case IntValue: return x.value_.intVal < y.value_.intVal; - case ValueType::UInt: + case UintValue: return x.value_.uintVal < y.value_.uintVal; - case ValueType::Real: + case RealValue: return x.value_.realVal < y.value_.realVal; - case ValueType::Boolean: + case BooleanValue: return static_cast(x.value_.boolVal) < static_cast(y.value_.boolVal); - case ValueType::String: + case StringValue: return (x.value_.stringVal == 0 && (y.value_.stringVal != nullptr)) || ((y.value_.stringVal != nullptr) && (x.value_.stringVal != nullptr) && strcmp(x.value_.stringVal, y.value_.stringVal) < 0); - case ValueType::Array: - case ValueType::Object: { + case ArrayValue: + case ObjectValue: { if (int const signum = int(x.value_.mapVal->size()) - y.value_.mapVal->size()) return signum < 0; @@ -429,37 +425,37 @@ operator==(Value const& x, Value const& y) { if (x.type_ != y.type_) { - if (x.type_ == ValueType::Int && y.type_ == ValueType::UInt) + if (x.type_ == IntValue && y.type_ == UintValue) return integerCmp(x.value_.intVal, y.value_.uintVal) == 0; - if (x.type_ == ValueType::UInt && y.type_ == ValueType::Int) + if (x.type_ == UintValue && y.type_ == IntValue) return integerCmp(y.value_.intVal, x.value_.uintVal) == 0; return false; } switch (x.type_) { - case ValueType::Null: + case NullValue: return true; - case ValueType::Int: + case IntValue: return x.value_.intVal == y.value_.intVal; - case ValueType::UInt: + case UintValue: return x.value_.uintVal == y.value_.uintVal; - case ValueType::Real: + case RealValue: return x.value_.realVal == y.value_.realVal; - case ValueType::Boolean: + case BooleanValue: return x.value_.boolVal == y.value_.boolVal; - case ValueType::String: + case StringValue: return x.value_.stringVal == y.value_.stringVal || ((y.value_.stringVal != nullptr) && (x.value_.stringVal != nullptr) && (strcmp(x.value_.stringVal, y.value_.stringVal) == 0)); - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: return x.value_.mapVal->size() == y.value_.mapVal->size() && *x.value_.mapVal == *y.value_.mapVal; @@ -475,7 +471,7 @@ operator==(Value const& x, Value const& y) char const* Value::asCString() const { - XRPL_ASSERT(type_ == ValueType::String, "json::Value::asCString : valid type"); + XRPL_ASSERT(type_ == StringValue, "json::Value::asCString : valid type"); return value_.stringVal; } @@ -484,26 +480,26 @@ Value::asString() const { switch (type_) { - case ValueType::Null: + case NullValue: return ""; - case ValueType::String: + case StringValue: return (value_.stringVal != nullptr) ? value_.stringVal : ""; - case ValueType::Boolean: + case BooleanValue: return value_.boolVal ? "true" : "false"; - case ValueType::Int: + case IntValue: return std::to_string(value_.intVal); - case ValueType::UInt: + case UintValue: return std::to_string(value_.uintVal); - case ValueType::Real: + case RealValue: return std::to_string(value_.realVal); - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: JSON_ASSERT_MESSAGE(false, "Type is not convertible to string"); // LCOV_EXCL_START @@ -520,33 +516,33 @@ Value::asInt() const { switch (type_) { - case ValueType::Null: + case NullValue: return 0; - case ValueType::Int: + case IntValue: return value_.intVal; - case ValueType::UInt: + case UintValue: JSON_ASSERT_MESSAGE( - value_.uintVal < (unsigned)kMaxInt, "integer out of signed integer range"); + value_.uintVal < (unsigned)kMAX_INT, "integer out of signed integer range"); return value_.uintVal; - case ValueType::Real: + case RealValue: JSON_ASSERT_MESSAGE( - (value_.realVal >= kMinInt && value_.realVal <= kMaxInt), + (value_.realVal >= kMIN_INT && value_.realVal <= kMAX_INT), "Real out of signed integer range"); return Int(value_.realVal); - case ValueType::Boolean: + case BooleanValue: return value_.boolVal ? 1 : 0; - case ValueType::String: { + case StringValue: { char const* const str{(value_.stringVal != nullptr) ? value_.stringVal : ""}; return beast::lexicalCastThrow(str); } - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: JSON_ASSERT_MESSAGE(false, "Type is not convertible to int"); // LCOV_EXCL_START @@ -563,10 +559,10 @@ Value::asAbsUInt() const { switch (type_) { - case ValueType::Null: + case NullValue: return 0; - case ValueType::Int: { + case IntValue: { // Doing this conversion through int64 avoids overflow error for // value_.intVal = -1 * 2^31 i.e. numeric_limits::min(). if (value_.intVal < 0) @@ -574,37 +570,38 @@ Value::asAbsUInt() const return value_.intVal; } - case ValueType::UInt: + case UintValue: return value_.uintVal; - case ValueType::Real: { + case RealValue: { if (value_.realVal < 0) { JSON_ASSERT_MESSAGE( - -1 * value_.realVal <= kMaxUInt, "Real out of unsigned integer range"); + -1 * value_.realVal <= kMAX_U_INT, "Real out of unsigned integer range"); return UInt(-1 * value_.realVal); } - JSON_ASSERT_MESSAGE(value_.realVal <= kMaxUInt, "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE(value_.realVal <= kMAX_U_INT, "Real out of unsigned integer range"); return UInt(value_.realVal); } - case ValueType::Boolean: + case BooleanValue: return value_.boolVal ? 1 : 0; - case ValueType::String: { + case StringValue: { char const* const str{(value_.stringVal != nullptr) ? value_.stringVal : ""}; auto const temp = beast::lexicalCastThrow(str); if (temp < 0) { - JSON_ASSERT_MESSAGE(-1 * temp <= kMaxUInt, "String out of unsigned integer range"); + JSON_ASSERT_MESSAGE( + -1 * temp <= kMAX_U_INT, "String out of unsigned integer range"); return -1 * temp; } - JSON_ASSERT_MESSAGE(temp <= kMaxUInt, "String out of unsigned integer range"); + JSON_ASSERT_MESSAGE(temp <= kMAX_U_INT, "String out of unsigned integer range"); return temp; } - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: JSON_ASSERT_MESSAGE(false, "Type is not convertible to int"); // LCOV_EXCL_START @@ -621,33 +618,33 @@ Value::asUInt() const { switch (type_) { - case ValueType::Null: + case NullValue: return 0; - case ValueType::Int: + case IntValue: JSON_ASSERT_MESSAGE( value_.intVal >= 0, "Negative integer can not be converted to unsigned integer"); return value_.intVal; - case ValueType::UInt: + case UintValue: return value_.uintVal; - case ValueType::Real: + case RealValue: JSON_ASSERT_MESSAGE( - (value_.realVal >= 0 && value_.realVal <= kMaxUInt), + (value_.realVal >= 0 && value_.realVal <= kMAX_U_INT), "Real out of unsigned integer range"); return UInt(value_.realVal); - case ValueType::Boolean: + case BooleanValue: return value_.boolVal ? 1 : 0; - case ValueType::String: { + case StringValue: { char const* const str{(value_.stringVal != nullptr) ? value_.stringVal : ""}; return beast::lexicalCastThrow(str); } - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: JSON_ASSERT_MESSAGE(false, "Type is not convertible to uint"); // LCOV_EXCL_START @@ -664,24 +661,24 @@ Value::asDouble() const { switch (type_) { - case ValueType::Null: + case NullValue: return 0.0; - case ValueType::Int: + case IntValue: return value_.intVal; - case ValueType::UInt: + case UintValue: return value_.uintVal; - case ValueType::Real: + case RealValue: return value_.realVal; - case ValueType::Boolean: + case BooleanValue: return value_.boolVal ? 1.0 : 0.0; - case ValueType::String: - case ValueType::Array: - case ValueType::Object: + case StringValue: + case ArrayValue: + case ObjectValue: JSON_ASSERT_MESSAGE(false, "Type is not convertible to double"); // LCOV_EXCL_START @@ -698,24 +695,24 @@ Value::asBool() const { switch (type_) { - case ValueType::Null: + case NullValue: return false; - case ValueType::Int: - case ValueType::UInt: + case IntValue: + case UintValue: return value_.intVal != 0; - case ValueType::Real: + case RealValue: return value_.realVal != 0.0; - case ValueType::Boolean: + case BooleanValue: return value_.boolVal; - case ValueType::String: + case StringValue: return (value_.stringVal != nullptr) && value_.stringVal[0] != 0; - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: return !value_.mapVal->empty(); // LCOV_EXCL_START @@ -732,47 +729,41 @@ Value::isConvertibleTo(ValueType other) const { switch (type_) { - case ValueType::Null: + case NullValue: return true; - case ValueType::Int: - return (other == ValueType::Null && value_.intVal == 0) || other == ValueType::Int || - (other == ValueType::UInt && value_.intVal >= 0) || other == ValueType::Real || - other == ValueType::String || other == ValueType::Boolean; + case IntValue: + return (other == NullValue && value_.intVal == 0) || other == IntValue || + (other == UintValue && value_.intVal >= 0) || other == RealValue || + other == StringValue || other == BooleanValue; - case ValueType::UInt: - return (other == ValueType::Null && value_.uintVal == 0) || - (other == ValueType::Int && value_.uintVal <= (unsigned)kMaxInt) || - other == ValueType::UInt || other == ValueType::Real || - other == ValueType::String || other == ValueType::Boolean; + case UintValue: + return (other == NullValue && value_.uintVal == 0) || + (other == IntValue && value_.uintVal <= (unsigned)kMAX_INT) || other == UintValue || + other == RealValue || other == StringValue || other == BooleanValue; - case ValueType::Real: - return (other == ValueType::Null && value_.realVal == 0.0) || - (other == ValueType::Int && value_.realVal >= kMinInt && - value_.realVal <= kMaxInt) || - (other == ValueType::UInt && value_.realVal >= 0 && value_.realVal <= kMaxUInt && + case RealValue: + return (other == NullValue && value_.realVal == 0.0) || + (other == IntValue && value_.realVal >= kMIN_INT && value_.realVal <= kMAX_INT) || + (other == UintValue && value_.realVal >= 0 && value_.realVal <= kMAX_U_INT && std::fabs(round(value_.realVal) - value_.realVal) < std::numeric_limits::epsilon()) || - other == ValueType::Real || other == ValueType::String || - other == ValueType::Boolean; + other == RealValue || other == StringValue || other == BooleanValue; - case ValueType::Boolean: - return (other == ValueType::Null && !value_.boolVal) || other == ValueType::Int || - other == ValueType::UInt || other == ValueType::Real || - other == ValueType::String || other == ValueType::Boolean; + case BooleanValue: + return (other == NullValue && !value_.boolVal) || other == IntValue || + other == UintValue || other == RealValue || other == StringValue || + other == BooleanValue; - case ValueType::String: - return other == ValueType::String || - (other == ValueType::Null && - ((value_.stringVal == nullptr) || value_.stringVal[0] == 0)); + case StringValue: + return other == StringValue || + (other == NullValue && ((value_.stringVal == nullptr) || value_.stringVal[0] == 0)); - case ValueType::Array: - return other == ValueType::Array || - (other == ValueType::Null && value_.mapVal->empty()); + case ArrayValue: + return other == ArrayValue || (other == NullValue && value_.mapVal->empty()); - case ValueType::Object: - return other == ValueType::Object || - (other == ValueType::Null && value_.mapVal->empty()); + case ObjectValue: + return other == ObjectValue || (other == NullValue && value_.mapVal->empty()); // LCOV_EXCL_START default: @@ -789,15 +780,15 @@ Value::size() const { switch (type_) { - case ValueType::Null: - case ValueType::Int: - case ValueType::UInt: - case ValueType::Real: - case ValueType::Boolean: - case ValueType::String: + case NullValue: + case IntValue: + case UintValue: + case RealValue: + case BooleanValue: + case StringValue: return 0; - case ValueType::Array: // size of the array is highest index + 1 + case ArrayValue: // size of the array is highest index + 1 if (!value_.mapVal->empty()) { ObjectValues::const_iterator itLast = value_.mapVal->end(); @@ -807,7 +798,7 @@ Value::size() const return 0; - case ValueType::Object: + case ObjectValue: return Int(value_.mapVal->size()); // LCOV_EXCL_START @@ -838,13 +829,13 @@ void Value::clear() { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Array || type_ == ValueType::Object, + type_ == NullValue || type_ == ArrayValue || type_ == ObjectValue, "json::Value::clear : valid type"); switch (type_) { - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: value_.mapVal->clear(); break; @@ -857,11 +848,10 @@ Value& Value::operator[](UInt index) { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Array, - "json::Value::operator[](UInt) : valid type"); + type_ == NullValue || type_ == ArrayValue, "json::Value::operator[](UInt) : valid type"); - if (type_ == ValueType::Null) - *this = Value(ValueType::Array); + if (type_ == NullValue) + *this = Value(ArrayValue); CZString const key(index); ObjectValues::iterator it = value_.mapVal->lower_bound(key); @@ -869,7 +859,7 @@ Value::operator[](UInt index) if (it != value_.mapVal->end() && (*it).first == key) return (*it).second; - ObjectValues::value_type const defaultValue(key, kNull); + ObjectValues::value_type const defaultValue(key, kNULL); it = value_.mapVal->insert(it, defaultValue); return (*it).second; } @@ -878,17 +868,17 @@ Value const& Value::operator[](UInt index) const { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Array, + type_ == NullValue || type_ == ArrayValue, "json::Value::operator[](UInt) const : valid type"); - if (type_ == ValueType::Null) - return kNull; + if (type_ == NullValue) + return kNULL; CZString const key(index); ObjectValues::const_iterator const it = value_.mapVal->find(key); if (it == value_.mapVal->end()) - return kNull; + return kNULL; return (*it).second; } @@ -903,22 +893,18 @@ Value& Value::resolveReference(char const* key, bool isStatic) { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Object, - "json::Value::resolveReference : valid type"); + type_ == NullValue || type_ == ObjectValue, "json::Value::resolveReference : valid type"); - if (type_ == ValueType::Null) - *this = Value(ValueType::Object); + if (type_ == NullValue) + *this = Value(ObjectValue); - CZString const actualKey( - key, - isStatic ? CZString::DuplicationPolicy::NoDuplication - : CZString::DuplicationPolicy::DuplicateOnCopy); + CZString const actualKey(key, isStatic ? CZString::NoDuplication : CZString::DuplicateOnCopy); ObjectValues::iterator it = value_.mapVal->lower_bound(actualKey); if (it != value_.mapVal->end() && (*it).first == actualKey) return (*it).second; - ObjectValues::value_type const defaultValue(actualKey, kNull); + ObjectValues::value_type const defaultValue(actualKey, kNULL); it = value_.mapVal->insert(it, defaultValue); Value& value = (*it).second; return value; @@ -928,7 +914,7 @@ Value Value::get(UInt index, Value const& defaultValue) const { Value const* value = &((*this)[index]); - return value == &kNull ? defaultValue : *value; + return value == &kNULL ? defaultValue : *value; } bool @@ -941,17 +927,17 @@ Value const& Value::operator[](char const* key) const { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Object, + type_ == NullValue || type_ == ObjectValue, "json::Value::operator[](const char*) const : valid type"); - if (type_ == ValueType::Null) - return kNull; + if (type_ == NullValue) + return kNULL; - CZString const actualKey(key, CZString::DuplicationPolicy::NoDuplication); + CZString const actualKey(key, CZString::NoDuplication); ObjectValues::const_iterator const it = value_.mapVal->find(actualKey); if (it == value_.mapVal->end()) - return kNull; + return kNULL; return (*it).second; } @@ -996,7 +982,7 @@ Value Value::get(char const* key, Value const& defaultValue) const { Value const* value = &((*this)[key]); - return value == &kNull ? defaultValue : *value; + return value == &kNULL ? defaultValue : *value; } Value @@ -1009,17 +995,16 @@ Value Value::removeMember(char const* key) { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Object, - "json::Value::removeMember : valid type"); + type_ == NullValue || type_ == ObjectValue, "json::Value::removeMember : valid type"); - if (type_ == ValueType::Null) - return kNull; + if (type_ == NullValue) + return kNULL; - CZString const actualKey(key, CZString::DuplicationPolicy::NoDuplication); + CZString const actualKey(key, CZString::NoDuplication); ObjectValues::iterator const it = value_.mapVal->find(actualKey); if (it == value_.mapVal->end()) - return kNull; + return kNULL; Value old(it->second); value_.mapVal->erase(it); @@ -1035,11 +1020,11 @@ Value::removeMember(std::string const& key) bool Value::isMember(char const* key) const { - if (type_ != ValueType::Object) + if (type_ != ObjectValue) return false; Value const* value = &((*this)[key]); - return value != &kNull; + return value != &kNULL; } bool @@ -1058,10 +1043,9 @@ Value::Members Value::getMemberNames() const { XRPL_ASSERT( - type_ == ValueType::Null || type_ == ValueType::Object, - "json::Value::getMemberNames : valid type"); + type_ == NullValue || type_ == ObjectValue, "json::Value::getMemberNames : valid type"); - if (type_ == ValueType::Null) + if (type_ == NullValue) return Value::Members(); Members members; @@ -1078,37 +1062,37 @@ Value::getMemberNames() const bool Value::isNull() const { - return type_ == ValueType::Null; + return type_ == NullValue; } bool Value::isBool() const { - return type_ == ValueType::Boolean; + return type_ == BooleanValue; } bool Value::isInt() const { - return type_ == ValueType::Int; + return type_ == IntValue; } bool Value::isUInt() const { - return type_ == ValueType::UInt; + return type_ == UintValue; } bool Value::isIntegral() const { - return type_ == ValueType::Int || type_ == ValueType::UInt || type_ == ValueType::Boolean; + return type_ == IntValue || type_ == UintValue || type_ == BooleanValue; } bool Value::isDouble() const { - return type_ == ValueType::Real; + return type_ == RealValue; } bool @@ -1120,31 +1104,31 @@ Value::isNumeric() const bool Value::isString() const { - return type_ == ValueType::String; + return type_ == StringValue; } bool Value::isArray() const { - return type_ == ValueType::Array; + return type_ == ArrayValue; } bool Value::isArrayOrNull() const { - return type_ == ValueType::Null || type_ == ValueType::Array; + return type_ == NullValue || type_ == ArrayValue; } bool Value::isObject() const { - return type_ == ValueType::Object; + return type_ == ObjectValue; } bool Value::isObjectOrNull() const { - return type_ == ValueType::Null || type_ == ValueType::Object; + return type_ == NullValue || type_ == ObjectValue; } std::string @@ -1159,8 +1143,8 @@ Value::begin() const { switch (type_) { - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: if (value_.mapVal != nullptr) return const_iterator(value_.mapVal->begin()); @@ -1177,8 +1161,8 @@ Value::end() const { switch (type_) { - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: if (value_.mapVal != nullptr) return const_iterator(value_.mapVal->end()); @@ -1195,8 +1179,8 @@ Value::begin() { switch (type_) { - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: if (value_.mapVal != nullptr) return iterator(value_.mapVal->begin()); break; @@ -1212,8 +1196,8 @@ Value::end() { switch (type_) { - case ValueType::Array: - case ValueType::Object: + case ArrayValue: + case ObjectValue: if (value_.mapVal != nullptr) return iterator(value_.mapVal->end()); break; diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 4c38bdcf92..6c138e1fb1 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -188,31 +188,31 @@ FastWriter::writeValue(Value const& value) { switch (value.type()) { - case ValueType::Null: + case NullValue: document_ += "null"; break; - case ValueType::Int: + case IntValue: document_ += valueToString(value.asInt()); break; - case ValueType::UInt: + case UintValue: document_ += valueToString(value.asUInt()); break; - case ValueType::Real: + case RealValue: document_ += valueToString(value.asDouble()); break; - case ValueType::String: + case StringValue: document_ += valueToQuotedString(value.asCString()); break; - case ValueType::Boolean: + case BooleanValue: document_ += valueToString(value.asBool()); break; - case ValueType::Array: { + case ArrayValue: { document_ += "["; int const size = value.size(); @@ -228,7 +228,7 @@ FastWriter::writeValue(Value const& value) } break; - case ValueType::Object: { + case ObjectValue: { Value::Members members(value.getMemberNames()); document_ += "{"; @@ -271,35 +271,35 @@ StyledWriter::writeValue(Value const& value) { switch (value.type()) { - case ValueType::Null: + case NullValue: pushValue("null"); break; - case ValueType::Int: + case IntValue: pushValue(valueToString(value.asInt())); break; - case ValueType::UInt: + case UintValue: pushValue(valueToString(value.asUInt())); break; - case ValueType::Real: + case RealValue: pushValue(valueToString(value.asDouble())); break; - case ValueType::String: + case StringValue: pushValue(valueToQuotedString(value.asCString())); break; - case ValueType::Boolean: + case BooleanValue: pushValue(valueToString(value.asBool())); break; - case ValueType::Array: + case ArrayValue: writeArrayValue(value); break; - case ValueType::Object: { + case ObjectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) @@ -506,35 +506,35 @@ StyledStreamWriter::writeValue(Value const& value) { switch (value.type()) { - case ValueType::Null: + case NullValue: pushValue("null"); break; - case ValueType::Int: + case IntValue: pushValue(valueToString(value.asInt())); break; - case ValueType::UInt: + case UintValue: pushValue(valueToString(value.asUInt())); break; - case ValueType::Real: + case RealValue: pushValue(valueToString(value.asDouble())); break; - case ValueType::String: + case StringValue: pushValue(valueToQuotedString(value.asCString())); break; - case ValueType::Boolean: + case BooleanValue: pushValue(valueToString(value.asBool())); break; - case ValueType::Array: + case ArrayValue: writeArrayValue(value); break; - case ValueType::Object: { + case ObjectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) diff --git a/src/libxrpl/ledger/AcceptedLedgerTx.cpp b/src/libxrpl/ledger/AcceptedLedgerTx.cpp index 2275c3552f..304c99ffcb 100644 --- a/src/libxrpl/ledger/AcceptedLedgerTx.cpp +++ b/src/libxrpl/ledger/AcceptedLedgerTx.cpp @@ -35,17 +35,17 @@ AcceptedLedgerTx::AcceptedLedgerTx( met->add(s); rawMeta_ = std::move(s.modData()); - json_ = json::ValueType::Object; - json_[jss::transaction] = txn_->getJson(JsonOptions::Values::None); + json_ = json::ObjectValue; + json_[jss::transaction] = txn_->getJson(JsonOptions::KNone); - json_[jss::meta] = meta_.getJson(JsonOptions::Values::None); + json_[jss::meta] = meta_.getJson(JsonOptions::KNone); json_[jss::raw_meta] = strHex(rawMeta_); json_[jss::result] = transHuman(meta_.getResultTER()); if (!affected_.empty()) { - json::Value& affected = (json_[jss::affected] = json::ValueType::Array); + json::Value& affected = (json_[jss::affected] = json::ArrayValue); for (auto const& account : affected_) affected.append(toBase58(account)); } diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index abcbaac0aa..f49b1d0122 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -80,9 +80,11 @@ ApplyStateTable::size() const void ApplyStateTable::visit( ReadView const& to, - std::function< - void(uint256 const& key, bool isDelete, SLE::const_ref before, SLE::const_ref after)> const& - func) const + std::function const& before, + std::shared_ptr const& after)> const& func) const { for (auto& item : items_) { @@ -167,7 +169,7 @@ ApplyStateTable::apply( { // go through the original node for // modified fields saved on modification - if (obj.getFName().shouldMeta(SField::kSmdChangeOrig) && + if (obj.getFName().shouldMeta(SField::SMdChangeOrig) && !curNode->hasMatchingEntry(obj)) prevs.emplaceBack(obj); } @@ -179,7 +181,7 @@ ApplyStateTable::apply( for (auto const& obj : *curNode) { // go through the final node for final fields - if (obj.getFName().shouldMeta(SField::kSmdAlways | SField::kSmdDeleteFinal)) + if (obj.getFName().shouldMeta(SField::SMdAlways | SField::SMdDeleteFinal)) finals.emplaceBack(obj); } @@ -203,7 +205,7 @@ ApplyStateTable::apply( for (auto const& obj : *origNode) { // search the original node for values saved on modify - if (obj.getFName().shouldMeta(SField::kSmdChangeOrig) && + if (obj.getFName().shouldMeta(SField::SMdChangeOrig) && !curNode->hasMatchingEntry(obj)) prevs.emplaceBack(obj); } @@ -215,7 +217,7 @@ ApplyStateTable::apply( for (auto const& obj : *curNode) { // search the final node for values saved always - if (obj.getFName().shouldMeta(SField::kSmdAlways | SField::kSmdChangeNew)) + if (obj.getFName().shouldMeta(SField::SMdAlways | SField::SMdChangeNew)) finals.emplaceBack(obj); } @@ -238,7 +240,7 @@ ApplyStateTable::apply( { // save non-default values if (!obj.isDefault() && - obj.getFName().shouldMeta(SField::kSmdCreate | SField::kSmdAlways)) + obj.getFName().shouldMeta(SField::SMdCreate | SField::SMdAlways)) news.emplaceBack(obj); } @@ -267,7 +269,7 @@ ApplyStateTable::apply( // VFALCO For diagnostics do we want to show // metadata even when the base view is open? - JLOG(j.trace()) << "metadata " << meta.getJson(JsonOptions::Values::None); + JLOG(j.trace()) << "metadata " << meta.getJson(JsonOptions::KNone); metadata = meta; } @@ -337,7 +339,7 @@ ApplyStateTable::succ( return next; } -SLE::const_pointer +std::shared_ptr ApplyStateTable::read(ReadView const& base, Keylet const& k) const { auto const iter = items_.find(k.key); @@ -359,7 +361,7 @@ ApplyStateTable::read(ReadView const& base, Keylet const& k) const return sle; } -SLE::pointer +std::shared_ptr ApplyStateTable::peek(ReadView const& base, Keylet const& k) { auto iter = items_.lower_bound(k.key); @@ -394,7 +396,7 @@ ApplyStateTable::peek(ReadView const& base, Keylet const& k) } void -ApplyStateTable::erase(ReadView const& base, SLE::ref sle) +ApplyStateTable::erase(ReadView const& base, std::shared_ptr const& sle) { auto const iter = items_.find(sle->key()); if (iter == items_.end()) @@ -418,7 +420,7 @@ ApplyStateTable::erase(ReadView const& base, SLE::ref sle) } void -ApplyStateTable::rawErase(ReadView const& base, SLE::ref sle) +ApplyStateTable::rawErase(ReadView const& base, std::shared_ptr const& sle) { using namespace std; auto const result = items_.emplace( @@ -443,7 +445,7 @@ ApplyStateTable::rawErase(ReadView const& base, SLE::ref sle) } void -ApplyStateTable::insert(ReadView const& base, SLE::ref sle) +ApplyStateTable::insert(ReadView const& base, std::shared_ptr const& sle) { auto const iter = items_.lower_bound(sle->key()); if (iter == items_.end() || iter->first != sle->key()) @@ -473,7 +475,7 @@ ApplyStateTable::insert(ReadView const& base, SLE::ref sle) } void -ApplyStateTable::replace(ReadView const& base, SLE::ref sle) +ApplyStateTable::replace(ReadView const& base, std::shared_ptr const& sle) { auto const iter = items_.lower_bound(sle->key()); if (iter == items_.end() || iter->first != sle->key()) @@ -502,7 +504,7 @@ ApplyStateTable::replace(ReadView const& base, SLE::ref sle) } void -ApplyStateTable::update(ReadView const& base, SLE::ref sle) +ApplyStateTable::update(ReadView const& base, std::shared_ptr const& sle) { auto const iter = items_.find(sle->key()); if (iter == items_.end()) @@ -534,7 +536,7 @@ ApplyStateTable::destroyXRP(XRPAmount const& fee) // Insert this transaction to the SLE's threading list void -ApplyStateTable::threadItem(TxMeta& meta, SLE::ref sle) +ApplyStateTable::threadItem(TxMeta& meta, std::shared_ptr const& sle) { key_type prevTxID; LedgerIndex prevLgrID = 0; @@ -566,7 +568,7 @@ ApplyStateTable::threadItem(TxMeta& meta, SLE::ref sle) } } -SLE::pointer +std::shared_ptr ApplyStateTable::getForMod(ReadView const& base, key_type const& key, Mods& mods, beast::Journal j) { { @@ -638,7 +640,7 @@ void ApplyStateTable::threadOwners( ReadView const& base, TxMeta& meta, - SLE::const_ref sle, + std::shared_ptr const& sle, Mods& mods, beast::Journal j) { diff --git a/src/libxrpl/ledger/ApplyView.cpp b/src/libxrpl/ledger/ApplyView.cpp index 8575bc2f52..3343748a75 100644 --- a/src/libxrpl/ledger/ApplyView.cpp +++ b/src/libxrpl/ledger/ApplyView.cpp @@ -31,7 +31,7 @@ createRoot( ApplyView& view, Keylet const& directory, uint256 const& key, - std::function const& describe) + std::function const&)> const& describe) { auto newRoot = std::make_shared(directory); newRoot->setFieldH256(sfRootIndex, directory.key); @@ -110,7 +110,7 @@ insertPage( SLE::ref next, uint256 const& key, Keylet const& directory, - std::function const& describe) + std::function const&)> const& describe) { // We rely on modulo arithmetic of unsigned integers (guaranteed in // [basic.fundamental] paragraph 2) to detect page representation overflow. @@ -125,7 +125,7 @@ insertPage( // Check whether we're out of pages. if (page == 0) return std::nullopt; - if (!view.rules().enabled(fixDirectoryLimit) && page >= kDirNodeMaxPages) // Old pages limit + if (!view.rules().enabled(fixDirectoryLimit) && page >= kDIR_NODE_MAX_PAGES) // Old pages limit return std::nullopt; // We are about to create a new node; we'll link it to @@ -166,7 +166,7 @@ ApplyView::dirAdd( bool preserveOrder, Keylet const& directory, uint256 const& key, - std::function const& describe) + std::function const&)> const& describe) { auto root = peek(directory); @@ -179,7 +179,7 @@ ApplyView::dirAdd( auto [page, node, indexes] = directory::findPreviousPage(*this, directory, root); // If there's space, we use it: - if (indexes.size() < kDirNodeMaxEntries) + if (indexes.size() < kDIR_NODE_MAX_ENTRIES) { return directory::insertKey(*this, node, page, preserveOrder, indexes, key); } @@ -208,19 +208,19 @@ ApplyView::emptyDirDelete(Keylet const& directory) if (!node->getFieldV256(sfIndexes).empty()) return false; - static constexpr std::uint64_t kRootPage = 0; + std::uint64_t constexpr kROOT_PAGE = 0; auto prevPage = node->getFieldU64(sfIndexPrevious); auto nextPage = node->getFieldU64(sfIndexNext); - if (nextPage == kRootPage && prevPage != kRootPage) + if (nextPage == kROOT_PAGE && prevPage != kROOT_PAGE) Throw("Directory chain: fwd link broken"); // LCOV_EXCL_LINE - if (prevPage == kRootPage && nextPage != kRootPage) + if (prevPage == kROOT_PAGE && nextPage != kROOT_PAGE) Throw("Directory chain: rev link broken"); // LCOV_EXCL_LINE // Older versions of the code would, in some cases, allow the last // page to be empty. Remove such pages: - if (nextPage == prevPage && nextPage != kRootPage) + if (nextPage == prevPage && nextPage != kROOT_PAGE) { auto last = peek(keylet::page(directory, nextPage)); @@ -232,8 +232,8 @@ ApplyView::emptyDirDelete(Keylet const& directory) // Update the first page's linked list and // mark it as updated. - node->setFieldU64(sfIndexNext, kRootPage); - node->setFieldU64(sfIndexPrevious, kRootPage); + node->setFieldU64(sfIndexNext, kROOT_PAGE); + node->setFieldU64(sfIndexPrevious, kROOT_PAGE); update(node); // And erase the empty last page: @@ -241,12 +241,12 @@ ApplyView::emptyDirDelete(Keylet const& directory) // Make sure our local values reflect the // updated information: - nextPage = kRootPage; - prevPage = kRootPage; + nextPage = kROOT_PAGE; + prevPage = kROOT_PAGE; } // If there are no other pages, erase the root: - if (nextPage == kRootPage && prevPage == kRootPage) + if (nextPage == kROOT_PAGE && prevPage == kROOT_PAGE) erase(node); return true; @@ -260,7 +260,7 @@ ApplyView::dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& if (!node) return false; - static constexpr std::uint64_t kRootPage = 0; + std::uint64_t constexpr kROOT_PAGE = 0; { auto entries = node->getFieldV256(sfIndexes); @@ -289,7 +289,7 @@ ApplyView::dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& // treated specially: it can never be deleted even if // it is empty, unless we plan on removing the entire // directory. - if (page == kRootPage) + if (page == kROOT_PAGE) { if (nextPage == page && prevPage != page) Throw("Directory chain: fwd link broken"); // LCOV_EXCL_LINE @@ -360,30 +360,30 @@ ApplyView::dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& // Check whether the next page is the last page and, if // so, whether it's empty. If it is, delete it. - if (nextPage != kRootPage && next->getFieldU64(sfIndexNext) == kRootPage && + if (nextPage != kROOT_PAGE && next->getFieldU64(sfIndexNext) == kROOT_PAGE && next->getFieldV256(sfIndexes).empty()) { // Since next doesn't point to the root, it can't be pointing to prev. erase(next); // The previous page is now the last page: - prev->setFieldU64(sfIndexNext, kRootPage); + prev->setFieldU64(sfIndexNext, kROOT_PAGE); update(prev); // And the root points to the last page: - auto root = peek(keylet::page(directory, kRootPage)); + auto root = peek(keylet::page(directory, kROOT_PAGE)); if (!root) Throw("Directory chain: root link broken."); // LCOV_EXCL_LINE root->setFieldU64(sfIndexPrevious, prevPage); update(root); - nextPage = kRootPage; + nextPage = kROOT_PAGE; } // If we're not keeping the root, then check to see if // it's left empty. If so, delete it as well. - if (!keepRoot && nextPage == kRootPage && prevPage == kRootPage) + if (!keepRoot && nextPage == kROOT_PAGE && prevPage == kROOT_PAGE) { if (prev->getFieldV256(sfIndexes).empty()) erase(prev); diff --git a/src/libxrpl/ledger/ApplyViewBase.cpp b/src/libxrpl/ledger/ApplyViewBase.cpp index 1b6ba78046..e5a8e11b4c 100644 --- a/src/libxrpl/ledger/ApplyViewBase.cpp +++ b/src/libxrpl/ledger/ApplyViewBase.cpp @@ -58,7 +58,7 @@ ApplyViewBase::succ(key_type const& key, std::optional const& last) co return items_.succ(*base_, key, last); } -SLE::const_pointer +std::shared_ptr ApplyViewBase::read(Keylet const& k) const { return items_.read(*base_, k); @@ -114,26 +114,26 @@ ApplyViewBase::flags() const return flags_; } -SLE::pointer +std::shared_ptr ApplyViewBase::peek(Keylet const& k) { return items_.peek(*base_, k); } void -ApplyViewBase::erase(SLE::ref sle) +ApplyViewBase::erase(std::shared_ptr const& sle) { items_.erase(*base_, sle); } void -ApplyViewBase::insert(SLE::ref sle) +ApplyViewBase::insert(std::shared_ptr const& sle) { items_.insert(*base_, sle); } void -ApplyViewBase::update(SLE::ref sle) +ApplyViewBase::update(std::shared_ptr const& sle) { items_.update(*base_, sle); } @@ -141,19 +141,19 @@ ApplyViewBase::update(SLE::ref sle) //--- void -ApplyViewBase::rawErase(SLE::ref sle) +ApplyViewBase::rawErase(std::shared_ptr const& sle) { items_.rawErase(*base_, sle); } void -ApplyViewBase::rawInsert(SLE::ref sle) +ApplyViewBase::rawInsert(std::shared_ptr const& sle) { items_.insert(*base_, sle); } void -ApplyViewBase::rawReplace(SLE::ref sle) +ApplyViewBase::rawReplace(std::shared_ptr const& sle) { items_.replace(*base_, sle); } diff --git a/src/libxrpl/ledger/ApplyViewImpl.cpp b/src/libxrpl/ledger/ApplyViewImpl.cpp index 66c009cd88..9650190a3e 100644 --- a/src/libxrpl/ledger/ApplyViewImpl.cpp +++ b/src/libxrpl/ledger/ApplyViewImpl.cpp @@ -13,6 +13,7 @@ #include #include +#include #include namespace xrpl { @@ -42,9 +43,11 @@ ApplyViewImpl::size() void ApplyViewImpl::visit( OpenView& to, - std::function< - void(uint256 const& key, bool isDelete, SLE::const_ref before, SLE::const_ref after)> const& - func) + std::function const& before, + std::shared_ptr const& after)> const& func) { items_.visit(to, func); } diff --git a/src/libxrpl/ledger/BookDirs.cpp b/src/libxrpl/ledger/BookDirs.cpp index 099fec99e1..fbe876669e 100644 --- a/src/libxrpl/ledger/BookDirs.cpp +++ b/src/libxrpl/ledger/BookDirs.cpp @@ -14,11 +14,11 @@ namespace xrpl { BookDirs::BookDirs(ReadView const& view, Book const& book) : view_(&view) , root_(keylet::page(getBookBase(book)).key) - , nextQuality_(getQualityNext(root_)) - , key_(view_->succ(root_, nextQuality_).value_or(beast::kZero)) + , next_quality_(getQualityNext(root_)) + , key_(view_->succ(root_, next_quality_).value_or(beast::kZERO)) { - XRPL_ASSERT(root_ != beast::kZero, "xrpl::BookDirs::BookDirs : nonzero root"); - if (key_ != beast::kZero) + XRPL_ASSERT(root_ != beast::kZERO, "xrpl::BookDirs::BookDirs : nonzero root"); + if (key_ != beast::kZERO) { if (!cdirFirst(*view_, key_, sle_, entry_, index_)) { @@ -33,9 +33,9 @@ auto BookDirs::begin() const -> BookDirs::const_iterator { auto it = BookDirs::const_iterator(*view_, root_, key_); - if (key_ != beast::kZero) + if (key_ != beast::kZERO) { - it.nextQuality_ = nextQuality_; + it.next_quality_ = next_quality_; it.sle_ = sle_; it.entry_ = entry_; it.index_ = index_; @@ -59,14 +59,14 @@ BookDirs::const_iterator::operator==(BookDirs::const_iterator const& other) cons view_ == other.view_ && root_ == other.root_, "xrpl::BookDirs::const_iterator::operator== : views and roots are " "matching"); - return entry_ == other.entry_ && curKey_ == other.curKey_ && 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::kZero, "xrpl::BookDirs::const_iterator::operator* : nonzero index"); + index_ != beast::kZERO, "xrpl::BookDirs::const_iterator::operator* : nonzero index"); if (!cache_) cache_ = view_->read(keylet::offer(index_)); return *cache_; @@ -75,21 +75,21 @@ BookDirs::const_iterator::operator*() const BookDirs::const_iterator& BookDirs::const_iterator::operator++() { - using beast::kZero; + using beast::kZERO; - XRPL_ASSERT(index_ != kZero, "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); - if (!cdirNext(*view_, curKey_, sle_, entry_, index_)) + XRPL_ASSERT(index_ != kZERO, "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); + if (!cdirNext(*view_, cur_key_, sle_, entry_, index_)) { if (index_ == 0) - curKey_ = view_->succ(++curKey_, nextQuality_).value_or(kZero); + cur_key_ = view_->succ(++cur_key_, next_quality_).value_or(kZERO); - if (index_ != 0 || curKey_ == kZero) + if (index_ != 0 || cur_key_ == kZERO) { - curKey_ = key_; + cur_key_ = key_; entry_ = 0; - index_ = kZero; + index_ = kZERO; } - else if (!cdirFirst(*view_, curKey_, sle_, entry_, index_)) + else if (!cdirFirst(*view_, cur_key_, sle_, entry_, index_)) { // LCOV_EXCL_START UNREACHABLE("xrpl::BookDirs::const_iterator::operator++ : directory is empty"); @@ -105,7 +105,7 @@ BookDirs::const_iterator BookDirs::const_iterator::operator++(int) { XRPL_ASSERT( - index_ != beast::kZero, "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); + index_ != beast::kZERO, "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); ++(*this); return tmp; diff --git a/src/libxrpl/ledger/CachedView.cpp b/src/libxrpl/ledger/CachedView.cpp index 1853cc0ac8..2dc28d67e0 100644 --- a/src/libxrpl/ledger/CachedView.cpp +++ b/src/libxrpl/ledger/CachedView.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -18,12 +19,12 @@ CachedViewImpl::exists(Keylet const& k) const return read(k) != nullptr; } -SLE::const_pointer +std::shared_ptr CachedViewImpl::read(Keylet const& k) const { - static CountedObjects::Counter kHits{"CachedView::hit"}; - static CountedObjects::Counter kHitsExpired{"CachedView::hitExpired"}; - static CountedObjects::Counter kMisses{"CachedView::miss"}; + static CountedObjects::Counter kHITS{"CachedView::hit"}; + static CountedObjects::Counter kHITSEXPIRED{"CachedView::hitExpired"}; + static CountedObjects::Counter kMISSES{"CachedView::miss"}; bool cacheHit = false; bool baseRead = false; @@ -49,15 +50,15 @@ CachedViewImpl::read(Keylet const& k) const XRPL_ASSERT(sle || baseRead, "xrpl::CachedView::read : null SLE result from base"); if (cacheHit && baseRead) { - kHitsExpired.increment(); + kHITSEXPIRED.increment(); } else if (cacheHit) { - kHits.increment(); + kHITS.increment(); } else { - kMisses.increment(); + kMISSES.increment(); } if (!cacheHit) diff --git a/src/libxrpl/ledger/CanonicalTXSet.cpp b/src/libxrpl/ledger/CanonicalTXSet.cpp index a06576342a..bfa3d811e6 100644 --- a/src/libxrpl/ledger/CanonicalTXSet.cpp +++ b/src/libxrpl/ledger/CanonicalTXSet.cpp @@ -33,7 +33,7 @@ operator<(CanonicalTXSet::Key const& lhs, CanonicalTXSet::Key const& rhs) uint256 CanonicalTXSet::accountKey(AccountID const& account) { - uint256 ret = beast::kZero; + uint256 ret = beast::kZERO; memcpy(ret.begin(), account.begin(), account.size()); ret ^= salt_; return ret; @@ -68,7 +68,7 @@ CanonicalTXSet::popAcctTransaction(std::shared_ptr const& tx) uint256 const effectiveAccount{accountKey(tx->getAccountID(sfAccount))}; auto const seqProxy = tx->getSeqProxy(); - Key const after(effectiveAccount, seqProxy, beast::kZero); + Key const after(effectiveAccount, seqProxy, beast::kZERO); auto const itrNext{map_.lower_bound(after)}; if (itrNext != map_.end() && itrNext->first.getAccount() == effectiveAccount && (!itrNext->second->getSeqProxy().isSeq() || diff --git a/src/libxrpl/ledger/Dir.cpp b/src/libxrpl/ledger/Dir.cpp index 63f41762a4..a633257b27 100644 --- a/src/libxrpl/ledger/Dir.cpp +++ b/src/libxrpl/ledger/Dir.cpp @@ -54,14 +54,14 @@ const_iterator::operator==(ConstIterator const& other) const XRPL_ASSERT( view_ == other.view_ && root_.key == other.root_.key, - "xrpl::Dir::ConstIterator::operator== : views and roots are matching"); + "xrpl::const_iterator::operator== : views and roots are matching"); return page_.key == other.page_.key && index_ == other.index_; } const_iterator::reference const_iterator::operator*() const { - XRPL_ASSERT(index_ != beast::kZero, "xrpl::Dir::ConstIterator::operator* : nonzero index"); + XRPL_ASSERT(index_ != beast::kZERO, "xrpl::const_iterator::operator* : nonzero index"); if (!cache_) cache_ = view_->read(keylet::child(index_)); return *cache_; @@ -70,7 +70,7 @@ const_iterator::operator*() const const_iterator& const_iterator::operator++() { - XRPL_ASSERT(index_ != beast::kZero, "xrpl::Dir::ConstIterator::operator++ : nonzero index"); + XRPL_ASSERT(index_ != beast::kZERO, "xrpl::const_iterator::operator++ : nonzero index"); if (++it_ != std::end(*indexes_)) { index_ = *it_; @@ -84,8 +84,7 @@ const_iterator::operator++() const_iterator const_iterator::operator++(int) { - XRPL_ASSERT( - index_ != beast::kZero, "xrpl::Dir::ConstIterator::operator++(int) : nonzero index"); + XRPL_ASSERT(index_ != beast::kZERO, "xrpl::const_iterator::operator++(int) : nonzero index"); ConstIterator tmp(*this); ++(*this); return tmp; @@ -98,17 +97,17 @@ const_iterator::nextPage() if (next == 0) { page_.key = root_.key; - index_ = beast::kZero; + index_ = beast::kZERO; } else { page_ = keylet::page(root_, next); sle_ = view_->read(page_); - XRPL_ASSERT(sle_, "xrpl::Dir::ConstIterator::nextPage : non-null SLE"); + XRPL_ASSERT(sle_, "xrpl::const_iterator::next_page : non-null SLE"); indexes_ = &sle_->getFieldV256(sfIndexes); if (indexes_->empty()) { - index_ = beast::kZero; + index_ = beast::kZERO; } else { diff --git a/src/libxrpl/ledger/Ledger.cpp b/src/libxrpl/ledger/Ledger.cpp index 82956650e2..9857b49b65 100644 --- a/src/libxrpl/ledger/Ledger.cpp +++ b/src/libxrpl/ledger/Ledger.cpp @@ -46,7 +46,7 @@ namespace xrpl { -CreateGenesisT const kCreateGenesis{}; +CreateGenesisT const kCREATE_GENESIS{}; //------------------------------------------------------------------------------ @@ -159,8 +159,8 @@ Ledger::Ledger( , j_(beast::Journal(beast::Journal::getNullSink())) { header_.seq = 1; - header_.drops = kInitialXrp; - header_.closeTimeResolution = kLedgerGenesisTimeResolution; + header_.drops = kINITIAL_XRP; + header_.closeTimeResolution = kLEDGER_GENESIS_TIME_RESOLUTION; static auto const kID = calcAccountID(generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")).first); @@ -196,7 +196,7 @@ Ledger::Ledger( sle->at(sfReserveBase) = *f; if (auto const f = fees.increment.dropsAs()) sle->at(sfReserveIncrement) = *f; - sle->at(sfReferenceFeeUnits) = kFeeUnitsDeprecated; + sle->at(sfReferenceFeeUnits) = kFEE_UNITS_DEPRECATED; } rawInsert(sle); } @@ -304,7 +304,7 @@ Ledger::Ledger( { header_.seq = ledgerSeq; header_.closeTime = closeTime; - header_.closeTimeResolution = kLedgerDefaultTimeResolution; + header_.closeTimeResolution = kLEDGER_DEFAULT_TIME_RESOLUTION; setup(); } @@ -315,8 +315,8 @@ Ledger::setImmutable(bool rehash) // place the hash transitions to valid if (!immutable_ && rehash) { - header_.txHash = txMap_.getHash().asUInt256(); - header_.accountHash = stateMap_.getHash().asUInt256(); + header_.txHash = txMap_.getHash().asUint256(); + header_.accountHash = stateMap_.getHash().asUint256(); } if (rehash) @@ -339,7 +339,7 @@ Ledger::setAccepted( header_.closeTime = closeTime; header_.closeTimeResolution = closeResolution; - header_.closeFlags = correctCloseTime ? 0 : kSLcfNoConsensusTime; + header_.closeFlags = correctCloseTime ? 0 : kS_LCF_NO_CONSENSUS_TIME; setImmutable(); } @@ -401,10 +401,10 @@ Ledger::succ(uint256 const& key, std::optional const& last) const return item->key(); } -SLE::const_pointer +std::shared_ptr Ledger::read(Keylet const& k) const { - if (k.key == beast::kZero) + if (k.key == beast::kZERO) { // LCOV_EXCL_START UNREACHABLE("xrpl::Ledger::read : zero key"); @@ -480,13 +480,13 @@ Ledger::digest(key_type const& key) const -> std::optional // from the NodeStore needlessly. if (!stateMap_.peekItem(key, digest)) return std::nullopt; - return digest.asUInt256(); + return digest.asUint256(); } //------------------------------------------------------------------------------ void -Ledger::rawErase(SLE::ref sle) +Ledger::rawErase(std::shared_ptr const& sle) { if (!stateMap_.delItem(sle->key())) logicError("Ledger::rawErase: key not found"); @@ -500,7 +500,7 @@ Ledger::rawErase(uint256 const& key) } void -Ledger::rawInsert(SLE::ref sle) +Ledger::rawInsert(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); @@ -512,7 +512,7 @@ Ledger::rawInsert(SLE::ref sle) } void -Ledger::rawReplace(SLE::ref sle) +Ledger::rawReplace(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); @@ -623,7 +623,7 @@ Ledger::setup() return ret; } -SLE::pointer +std::shared_ptr Ledger::peek(Keylet const& k) const { auto const& value = stateMap_.peekItem(k.key); @@ -795,9 +795,9 @@ Ledger::isSensible() const return false; if (header_.accountHash.isZero()) return false; - if (header_.accountHash != stateMap_.getHash().asUInt256()) + if (header_.accountHash != stateMap_.getHash().asUint256()) return false; - if (header_.txHash != txMap_.getHash().asUInt256()) + if (header_.txHash != txMap_.getHash().asUint256()) return false; return true; } diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index 26cb109f85..afe826d78d 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -78,9 +78,9 @@ public: OpenView::OpenView(OpenView const& rhs) : ReadView(rhs) , TxsRawView(rhs) - , monotonicResource_{std::make_unique( - kInitialBufferSize)} - , txs_{rhs.txs_, monotonicResource_.get()} + , monotonic_resource_{std::make_unique( + kINITIAL_BUFFER_SIZE)} + , txs_{rhs.txs_, monotonic_resource_.get()} , rules_{rhs.rules_} , header_{rhs.header_} , base_{rhs.base_} @@ -89,9 +89,9 @@ OpenView::OpenView(OpenView const& rhs) , open_{rhs.open_} {}; OpenView::OpenView(OpenLedgerT, ReadView const* base, Rules rules, std::shared_ptr hold) - : monotonicResource_{ - std::make_unique(kInitialBufferSize)} - , txs_{monotonicResource_.get()} + : monotonic_resource_{ + std::make_unique(kINITIAL_BUFFER_SIZE)} + , txs_{monotonic_resource_.get()} , rules_(std::move(rules)) , header_(base->header()) , base_(base) @@ -105,9 +105,9 @@ OpenView::OpenView(OpenLedgerT, ReadView const* base, Rules rules, std::shared_p } OpenView::OpenView(ReadView const* base, std::shared_ptr hold) - : monotonicResource_{ - std::make_unique(kInitialBufferSize)} - , txs_{monotonicResource_.get()} + : monotonic_resource_{ + std::make_unique(kINITIAL_BUFFER_SIZE)} + , txs_{monotonic_resource_.get()} , rules_(base->rules()) , header_(base->header()) , base_(base) @@ -163,7 +163,7 @@ OpenView::succ(key_type const& key, std::optional const& last) const return items_.succ(*base_, key, last); } -SLE::const_pointer +std::shared_ptr OpenView::read(Keylet const& k) const { return items_.read(*base_, k); @@ -228,19 +228,19 @@ OpenView::txRead(key_type const& key) const -> tx_type //--- void -OpenView::rawErase(SLE::ref sle) +OpenView::rawErase(std::shared_ptr const& sle) { items_.erase(sle); } void -OpenView::rawInsert(SLE::ref sle) +OpenView::rawInsert(std::shared_ptr const& sle) { items_.insert(sle); } void -OpenView::rawReplace(SLE::ref sle) +OpenView::rawReplace(std::shared_ptr const& sle) { items_.replace(sle); } diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index 97e3e53cbf..a730b247ba 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -321,7 +321,7 @@ PaymentSandbox::balanceHookIOU( auto adjustedAmt = std::min({amount, lastBal - delta, minBal}); adjustedAmt.get().account = amount.getIssuer(); - if (isXRP(issuer) && adjustedAmt < beast::kZero) + if (isXRP(issuer) && adjustedAmt < beast::kZERO) { // A calculated negative XRP balance is not an error case. Consider a // payment snippet that credits a large XRP amount and then debits the diff --git a/src/libxrpl/ledger/RawStateTable.cpp b/src/libxrpl/ledger/RawStateTable.cpp index fbe7bf1d82..69e2f5c0fe 100644 --- a/src/libxrpl/ledger/RawStateTable.cpp +++ b/src/libxrpl/ledger/RawStateTable.cpp @@ -20,10 +20,10 @@ namespace xrpl::detail { class RawStateTable::SlesIterImpl : public ReadView::SlesType::iter_base { private: - SLE::const_pointer sle0_; + std::shared_ptr sle0_; ReadView::SlesType::Iterator iter0_; ReadView::SlesType::Iterator end0_; - SLE::const_pointer sle1_; + std::shared_ptr sle1_; items_t::const_iterator iter1_; items_t::const_iterator end1_; @@ -241,7 +241,7 @@ RawStateTable::succ(ReadView const& base, key_type const& key, std::optional const& sle) { // The base invariant is checked during apply auto const result = items_.emplace( @@ -267,7 +267,7 @@ RawStateTable::erase(SLE::ref sle) } void -RawStateTable::insert(SLE::ref sle) +RawStateTable::insert(std::shared_ptr const& sle) { auto const result = items_.emplace( std::piecewise_construct, @@ -292,7 +292,7 @@ RawStateTable::insert(SLE::ref sle) } void -RawStateTable::replace(SLE::ref sle) +RawStateTable::replace(std::shared_ptr const& sle) { auto const result = items_.emplace( std::piecewise_construct, @@ -313,7 +313,7 @@ RawStateTable::replace(SLE::ref sle) } } -SLE::const_pointer +std::shared_ptr RawStateTable::read(ReadView const& base, Keylet const& k) const { auto const iter = items_.find(k.key); @@ -323,7 +323,7 @@ RawStateTable::read(ReadView const& base, Keylet const& k) const if (item.action == Action::Erase) return nullptr; // Convert to SLE const - SLE::const_pointer sle = item.sle; + std::shared_ptr sle = item.sle; if (!k.check(*sle)) return nullptr; return sle; diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index fdd7998609..9fb03a230c 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -32,6 +31,7 @@ #include #include +#include #include #include @@ -57,45 +57,19 @@ isVaultPseudoAccountFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptShare, - std::uint8_t depth) + int depth) { if (!view.rules().enabled(featureSingleAssetVault)) return false; - if (depth >= kMaxAssetCheckDepth) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::View::isVaultPseudoAccountFrozen : reached asset check depth"); - return true; - // LCOV_EXCL_STOP - } + if (depth >= kMAX_ASSET_CHECK_DEPTH) + return true; // LCOV_EXCL_LINE auto const mptIssuance = view.read(keylet::mptIssuance(mptShare.getMptID())); if (mptIssuance == nullptr) return false; // zero MPToken won't block deletion of MPTokenIssuance auto const issuer = mptIssuance->getAccountID(sfIssuer); - - // Post-fixCleanup3_2_0: vault shares carry sfReferenceHolding pointing - // to the vault pseudo's MPToken or RippleState for the underlying. - // Read it to derive the underlying asset and recurse, skipping the - // issuer-account-then-vault chain. Pre-amendment shares (no field) - // fall back to the chain lookup below. - if (mptIssuance->isFieldPresent(sfReferenceHolding)) - { - auto const sleHolding = - view.read(keylet::unchecked(mptIssuance->getFieldH256(sfReferenceHolding))); - if (!sleHolding) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::isVaultPseudoAccountFrozen : dangling sfReferenceHolding"); - return false; - // LCOV_EXCL_STOP - } - return isAnyFrozen( - view, {issuer, account}, assetOfHolding(*mptIssuance, *sleHolding), depth + 1); - } - auto const mptIssuer = view.read(keylet::account(issuer)); if (mptIssuer == nullptr) { @@ -331,7 +305,11 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) //------------------------------------------------------------------------------ TER -dirLink(ApplyView& view, AccountID const& owner, SLE::pointer& 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)); @@ -372,7 +350,7 @@ withdrawToDestExceedsLimit( [&](Issue const& issue) -> TER { auto const& currency = issue.currency; auto const owed = creditBalance(view, to, issuer, currency); - if (owed <= beast::kZero) + if (owed <= beast::kZERO) { auto const limit = creditLimit(view, to, issuer, currency); if (-owed >= limit || amount > (limit + owed)) @@ -483,9 +461,9 @@ cleanupOnAccountDelete( std::optional maxNodesToDelete) { // Delete all the entries in the account directory. - SLE::pointer sleDirNode{}; + std::shared_ptr sleDirNode{}; unsigned int uDirEntry{0}; - uint256 dirEntry{beast::kZero}; + uint256 dirEntry{beast::kZERO}; std::uint32_t deleted = 0; if (view.exists(ownerDirKeylet) && diff --git a/src/libxrpl/ledger/helpers/AMMHelpers.cpp b/src/libxrpl/ledger/helpers/AMMHelpers.cpp index fe6d022490..4cef02e056 100644 --- a/src/libxrpl/ledger/helpers/AMMHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AMMHelpers.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -204,7 +205,7 @@ adjustAmountsByLPTokens( auto const lpTokensActual = adjustLPTokens(lptAMMBalance, lpTokens, isDeposit); - if (lpTokensActual == beast::kZero) + if (lpTokensActual == beast::kZERO) { auto const amount2Opt = amount2 ? std::make_optional(STAmount{}) : std::nullopt; return std::make_tuple(STAmount{}, amount2Opt, lpTokensActual); @@ -635,7 +636,7 @@ deleteAMMTrustLines( keylet::ownerDir(ammAccountID), [&](LedgerEntryType nodeType, uint256 const&, - SLE::pointer& sleItem) -> std::pair { + std::shared_ptr& sleItem) -> std::pair { // Skip AMM and MPToken if (nodeType == ltAMM || nodeType == ltMPTOKEN) return {tesSUCCESS, SkipEntry::Yes}; @@ -643,7 +644,7 @@ deleteAMMTrustLines( if (nodeType == ltRIPPLE_STATE) { // Trustlines must have zero balance - if (sleItem->getFieldAmount(sfBalance) != beast::kZero) + if (sleItem->getFieldAmount(sfBalance) != beast::kZERO) { // LCOV_EXCL_START JLOG(j.error()) << "deleteAMMObjects: deleting trustline with " @@ -671,7 +672,7 @@ deleteAMMMPTokens(Sandbox& sb, AccountID const& ammAccountID, beast::Journal j) keylet::ownerDir(ammAccountID), [&](LedgerEntryType nodeType, uint256 const&, - SLE::pointer& sleItem) -> std::pair { + std::shared_ptr& sleItem) -> std::pair { // Skip AMM if (nodeType == ltAMM) return {tesSUCCESS, SkipEntry::Yes}; @@ -731,7 +732,7 @@ deleteAMMAccount(Sandbox& sb, Asset const& asset, Asset const& asset2, beast::Jo // LCOV_EXCL_STOP } - if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, kMaxDeletableAmmTrustLines, j); + if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, kMAX_DELETABLE_AMM_TRUST_LINES, j); !isTesSuccess(ter)) return ter; @@ -767,7 +768,7 @@ deleteAMMAccount(Sandbox& sb, Asset const& asset, Asset const& asset2, beast::Jo void initializeFeeAuctionVote( ApplyView& view, - SLE::pointer& ammSle, + std::shared_ptr& ammSle, AccountID const& account, Asset const& lptAsset, std::uint16_t tfee) @@ -778,7 +779,7 @@ initializeFeeAuctionVote( STObject voteEntry = STObject::makeInnerObject(sfVoteEntry); if (tfee != 0) voteEntry.setFieldU16(sfTradingFee, tfee); - voteEntry.setFieldU32(sfVoteWeight, kVoteWeightScaleFactor); + voteEntry.setFieldU32(sfVoteWeight, kVOTE_WEIGHT_SCALE_FACTOR); voteEntry.setAccountID(sfAccount, account); voteSlots.pushBack(voteEntry); ammSle->setFieldArray(sfVoteSlots, voteSlots); @@ -796,7 +797,7 @@ initializeFeeAuctionVote( auto const expiration = std::chrono::duration_cast( view.header().parentCloseTime.time_since_epoch()) .count() + - kTotalTimeSlotSecs; + kTOTAL_TIME_SLOT_SECS; auctionSlot.setFieldU32(sfExpiration, expiration); auctionSlot.setFieldAmount(sfPrice, STAmount{lptAsset, 0}); // Set the fee @@ -808,7 +809,7 @@ initializeFeeAuctionVote( { ammSle->makeFieldAbsent(sfTradingFee); // LCOV_EXCL_LINE } - if (auto const dfee = tfee / kAuctionSlotDiscountedFeeFraction) + if (auto const dfee = tfee / kAUCTION_SLOT_DISCOUNTED_FEE_FRACTION) { auctionSlot.setFieldU16(sfDiscountedFee, dfee); } @@ -816,9 +817,6 @@ initializeFeeAuctionVote( { auctionSlot.makeFieldAbsent(sfDiscountedFee); // LCOV_EXCL_LINE } - // Clear stale auth accounts from any previous auction slot holder. - if (rules.enabled(fixCleanup3_2_0) && auctionSlot.isFieldPresent(sfAuthAccounts)) - auctionSlot.makeFieldAbsent(sfAuthAccounts); } Expected @@ -925,7 +923,7 @@ Expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, - SLE::pointer& ammSle, + std::shared_ptr& ammSle, AccountID const& account) { auto const res = isOnlyLiquidityProvider(sb, lpTokens.get(), account); diff --git a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp index 1634de93c9..052c93739c 100644 --- a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp @@ -88,7 +88,7 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, { auto const sle = view.read(keylet::account(id)); if (sle == nullptr) - return beast::kZero; + return beast::kZERO; // Return balance minus reserve std::uint32_t const ownerCount = @@ -121,11 +121,15 @@ transferRate(ReadView const& view, AccountID const& issuer) if (sle && sle->isFieldPresent(sfTransferRate)) return Rate{sle->getFieldU32(sfTransferRate)}; - return kParityRate; + return kPARITY_RATE; } void -adjustOwnerCount(ApplyView& view, SLE::ref 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; @@ -142,17 +146,17 @@ AccountID pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey) { // This number must not be changed without an amendment - static constexpr std::uint16_t kMaxAccountAttempts = 256; - for (std::uint16_t i = 0; i < kMaxAccountAttempts; ++i) + constexpr std::uint16_t kMAX_ACCOUNT_ATTEMPTS = 256; + for (std::uint16_t i = 0; i < kMAX_ACCOUNT_ATTEMPTS; ++i) { RipeshaHasher rsh; auto const hash = sha512Half(i, view.header().parentHash, pseudoOwnerKey); rsh(hash.data(), hash.size()); - AccountID const ret = AccountID::fromRaw(static_cast(rsh)); + AccountID const ret{static_cast(rsh)}; if (!view.read(keylet::account(ret))) return ret; } - return beast::kZero; + return beast::kZERO; } // Pseudo-account designator fields MUST be maintained by including the @@ -164,7 +168,7 @@ pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey) [[nodiscard]] std::vector const& getPseudoAccountFields() { - static std::vector const kPseudoFields = []() { + static std::vector const kPSEUDO_FIELDS = []() { auto const ar = LedgerFormats::getInstance().findByType(ltACCOUNT_ROOT); if (!ar) { @@ -179,16 +183,18 @@ getPseudoAccountFields() std::vector pseudoFields; for (auto const& field : soTemplate) { - if (field.sField().shouldMeta(SField::kSmdPseudoAccount)) + if (field.sField().shouldMeta(SField::SMdPseudoAccount)) pseudoFields.emplace_back(&field.sField()); } return pseudoFields; }(); - return kPseudoFields; + return kPSEUDO_FIELDS; } [[nodiscard]] bool -isPseudoAccount(SLE::const_pointer sleAcct, std::set const& pseudoFieldFilter) +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter) { auto const& fields = getPseudoAccountFields(); @@ -202,7 +208,7 @@ isPseudoAccount(SLE::const_pointer sleAcct, std::set const& pseud }) > 0; } -Expected +Expected, TER> createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) { [[maybe_unused]] @@ -215,7 +221,7 @@ createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const "xrpl::createPseudoAccount : valid owner field"); auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); - if (accountId == beast::kZero) + if (accountId == beast::kZERO) return Unexpected(tecDUPLICATE); // Create pseudo-account. diff --git a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp index 7cfbc773d7..9a9e3d47d3 100644 --- a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -10,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -25,6 +23,7 @@ #include #include +#include #include #include #include @@ -34,16 +33,15 @@ namespace xrpl { namespace credentials { bool -checkExpired(SLE 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()); + (*sleCredential)[~sfExpiration].value_or(std::numeric_limits::max()); std::uint32_t const now = closed.time_since_epoch().count(); return now > exp; } -[[nodiscard]] -static Expected +bool removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) { auto const closeTime = view.header().parentCloseTime; @@ -55,13 +53,11 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) auto const k = keylet::credential(h); auto const sleCred = view.peek(k); - if (sleCred && checkExpired(*sleCred, closeTime)) + if (sleCred && checkExpired(sleCred, closeTime)) { JLOG(j.trace()) << "Credentials are expired. Cred: " << sleCred->getText(); // delete expired credentials even if the transaction failed - auto const err = deleteSLE(view, sleCred, j); - if (view.rules().enabled(fixCleanup3_1_3) && !isTesSuccess(err)) - return Unexpected(err); + deleteSLE(view, sleCred, j); foundExpired = true; } } @@ -70,7 +66,7 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) } TER -deleteSLE(ApplyView& view, SLE::ref sleCredential, beast::Journal j) +deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Journal j) { if (!sleCredential) return tecNO_ENTRY; @@ -104,7 +100,7 @@ deleteSLE(ApplyView& view, SLE::ref sleCredential, beast::Journal j) auto const issuer = sleCredential->getAccountID(sfIssuer); auto const subject = sleCredential->getAccountID(sfSubject); - bool const accepted = sleCredential->isFlag(lsfAccepted); + bool const accepted = (sleCredential->getFlags() & lsfAccepted) != 0u; auto err = delSLE(issuer, sfIssuerNode, !accepted || (subject == issuer)); if (!isTesSuccess(err)) @@ -130,7 +126,7 @@ checkFields(STTx const& tx, beast::Journal j) return tesSUCCESS; auto const& credentials = tx.getFieldV256(sfCredentialIDs); - if (credentials.empty() || (credentials.size() > kMaxCredentialsArraySize)) + if (credentials.empty() || (credentials.size() > kMAX_CREDENTIALS_ARRAY_SIZE)) { JLOG(j.trace()) << "Malformed transaction: Credentials array size is invalid: " << credentials.size(); @@ -173,7 +169,7 @@ valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal return tecBAD_CREDENTIALS; } - if (!sleCred->isFlag(lsfAccepted)) + if ((sleCred->getFlags() & lsfAccepted) == 0u) { JLOG(j.trace()) << "Credential isn't accepted. Cred: " << h; return tecBAD_CREDENTIALS; @@ -209,12 +205,12 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject) // allows expired credentials to be deleted by any transaction. if (sleCredential) { - if (checkExpired(*sleCredential, closeTime)) + if (checkExpired(sleCredential, closeTime)) { foundExpired = true; continue; } - if (sleCredential->isFlag(lsfAccepted)) + if ((sleCredential->getFlags() & lsfAccepted) != 0u) { return tesSUCCESS; } @@ -230,7 +226,7 @@ TER authorizedDepositPreauth(ReadView const& view, STVector256 const& credIDs, AccountID const& dst) { std::set> sorted; - std::vector lifeExtender; + std::vector> lifeExtender; lifeExtender.reserve(credIDs.size()); for (auto const& h : credIDs) { @@ -287,7 +283,7 @@ checkArray(STArray const& credentials, unsigned maxSize, beast::Journal j) } auto const ct = credential[sfCredentialType]; - if (ct.empty() || (ct.size() > kMaxCredentialTypeLength)) + if (ct.empty() || (ct.size() > kMAX_CREDENTIAL_TYPE_LENGTH)) { JLOG(j.trace()) << "Malformed transaction: " "Invalid credentialType size: " @@ -328,21 +324,18 @@ verifyValidDomain(ApplyView& view, AccountID const& account, uint256 domainID, b credentials.pushBack(keyletCredential.key); } - auto const foundExpired = credentials::removeExpired(view, credentials, j); - if (!foundExpired.has_value()) - return foundExpired.error(); - + bool const foundExpired = credentials::removeExpired(view, credentials, j); for (auto const& h : credentials) { auto sleCredential = view.read(keylet::credential(h)); if (!sleCredential) continue; // expired, i.e. deleted in credentials::removeExpired - if (sleCredential->isFlag(lsfAccepted)) + if ((sleCredential->getFlags() & lsfAccepted) != 0u) return tesSUCCESS; } - return *foundExpired ? tecEXPIRED : tecNO_PERMISSION; + return foundExpired ? tecEXPIRED : tecNO_PERMISSION; } TER @@ -351,7 +344,7 @@ checkDepositPreauth( ReadView const& view, AccountID const& src, AccountID const& dst, - SLE::const_ref sleDst, + std::shared_ptr const& sleDst, beast::Journal j) { // If depositPreauth is enabled, then an account that requires @@ -360,17 +353,16 @@ checkDepositPreauth( // 2. If src is deposit preauthorized by dst (either by account or by // credentials). - bool const credentialsPresent = tx.isFieldPresent(sfCredentialIDs); - - if (sleDst && sleDst->isFlag(lsfDepositAuth)) + if (sleDst && ((sleDst->getFlags() & lsfDepositAuth) != 0u)) { if (src != dst) { if (!view.exists(keylet::depositPreauth(dst, src))) { - return !credentialsPresent ? tecNO_PERMISSION - : credentials::authorizedDepositPreauth( - view, tx.getFieldV256(sfCredentialIDs), dst); + return !tx.isFieldPresent(sfCredentialIDs) + ? tecNO_PERMISSION + : credentials::authorizedDepositPreauth( + view, tx.getFieldV256(sfCredentialIDs), dst); } } } @@ -381,14 +373,8 @@ checkDepositPreauth( TER cleanupExpiredCredentials(STTx const& tx, ApplyView& view, beast::Journal j) { - if (!tx.isFieldPresent(sfCredentialIDs)) - return tesSUCCESS; - - auto const foundExpired = credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j); - if (!foundExpired.has_value()) - return foundExpired.error(); - - if (*foundExpired) + if (tx.isFieldPresent(sfCredentialIDs) && + credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j)) return tecEXPIRED; return tesSUCCESS; @@ -400,7 +386,7 @@ verifyDepositPreauth( ApplyView& view, AccountID const& src, AccountID const& dst, - SLE::const_ref sleDst, + std::shared_ptr const& sleDst, beast::Journal j) { if (auto const err = cleanupExpiredCredentials(tx, view, j); !isTesSuccess(err)) diff --git a/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp index 43f8219b6a..8b4eeae7b7 100644 --- a/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp +++ b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp @@ -13,13 +13,15 @@ #include #include +#include + namespace xrpl { bool dirFirst( ApplyView& view, uint256 const& root, - SLE::pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry) { @@ -30,7 +32,7 @@ bool dirNext( ApplyView& view, uint256 const& root, - SLE::pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry) { @@ -41,7 +43,7 @@ bool cdirFirst( ReadView const& view, uint256 const& root, - SLE::const_pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry) { @@ -52,7 +54,7 @@ bool cdirNext( ReadView const& view, uint256 const& root, - SLE::const_pointer& page, + std::shared_ptr& page, unsigned int& index, uint256& entry) { @@ -60,7 +62,10 @@ cdirNext( } void -forEachItem(ReadView const& view, Keylet const& root, std::function 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"); @@ -90,7 +95,7 @@ forEachItemAfter( uint256 const& after, std::uint64_t const hint, unsigned int limit, - std::function const& f) + std::function const&)> const& f) { XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItemAfter : valid root type"); @@ -179,7 +184,7 @@ dirIsEmpty(ReadView const& view, Keylet const& k) std::function describeOwnerDir(AccountID const& account) { - return [account](SLE::ref sle) { (*sle)[sfOwner] = account; }; + return [account](std::shared_ptr const& sle) { (*sle)[sfOwner] = account; }; } } // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp index 15ebf33e46..28b0c8976d 100644 --- a/src/libxrpl/ledger/helpers/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -25,42 +24,10 @@ #include #include #include -#include #include namespace xrpl { -[[nodiscard]] TER -canApplyToBrokerCover( - ReadView const& view, - SLE::const_ref sleBroker, - Asset const& vaultAsset, - STAmount const& amount, - beast::Journal j, - std::string_view logPrefix) -{ - XRPL_ASSERT( - sleBroker && sleBroker->getType() == ltLOAN_BROKER, - "xrpl::canApplyToBrokerCover : valid LoanBroker sle"); - XRPL_ASSERT(vaultAsset == amount.asset(), "xrpl::canApplyToBrokerCover : valid asset"); - - if (!view.rules().enabled(fixCleanup3_2_0)) - return tesSUCCESS; - - if (amount == beast::kZero) - return tecPRECISION_LOSS; - - int const coverScale = scale(sleBroker->at(sfCoverAvailable), vaultAsset); - if (amount.isZeroAtScale(coverScale)) - { - JLOG(j.warn()) << logPrefix << ": amount " << amount.getFullText() - << " rounds to zero at cover scale " << coverScale; - return tecPRECISION_LOSS; - } - - return tesSUCCESS; -} - bool checkLendingProtocolDependencies(Rules const& rules, STTx const& tx) { @@ -81,15 +48,15 @@ LoanPaymentParts::operator+=(LoanPaymentParts const& other) { XRPL_ASSERT( - other.principalPaid >= beast::kZero, + other.principalPaid >= beast::kZERO, "xrpl::LoanPaymentParts::operator+= : other principal " "non-negative"); XRPL_ASSERT( - other.interestPaid >= beast::kZero, + other.interestPaid >= beast::kZERO, "xrpl::LoanPaymentParts::operator+= : other interest paid " "non-negative"); XRPL_ASSERT( - other.feePaid >= beast::kZero, + other.feePaid >= beast::kZERO, "xrpl::LoanPaymentParts::operator+= : other fee paid " "non-negative"); @@ -116,7 +83,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) / kSecondsInYear; + return tenthBipsOfValue(Number(paymentInterval), interestRate) / kSECONDS_IN_YEAR; } /* Checks if a value is already rounded to the specified scale. @@ -135,86 +102,22 @@ namespace detail { void LoanStateDeltas::nonNegative() { - if (principal < beast::kZero) - principal = kNumZero; - if (interest < beast::kZero) - interest = kNumZero; - if (managementFee < beast::kZero) - managementFee = kNumZero; + if (principal < beast::kZERO) + principal = kNUM_ZERO; + if (interest < beast::kZERO) + interest = kNUM_ZERO; + if (managementFee < beast::kZERO) + managementFee = kNUM_ZERO; } -/* Computes (1 + r)^n - 1 accurately even for near-zero r, where direct - * subtraction of `power(1 + r, n) - 1` suffers catastrophic cancellation. +/* Computes (1 + periodicRate)^paymentsRemaining for amortization calculations. * - * The binomial expansion gives - * (1 + r)^n - 1 = sum_{k=1}^{n} C(n,k) r^k - * = nr + C(n,2) r^2 + ... + r^n - * which is a sum of positive terms when r >= 0, avoiding cancellation. - * Each term is computed from the previous via - * term_{k+1} = term_k * r * (n - k) / (k + 1) - * - * The loop terminates early once the next term is below Number precision. + * Equation (5) from XLS-66 spec, Section A-2 Equation Glossary */ Number -computePowerMinusOne(Number const& periodicRate, std::uint32_t paymentsRemaining) +computeRaisedRate(Number const& periodicRate, std::uint32_t paymentsRemaining) { - XRPL_ASSERT_PARTS( - periodicRate >= beast::kZero, - "xrpl::detail::computePowerMinusOne", - "periodicRate is non-negative"); - - if (paymentsRemaining == 0 || periodicRate == beast::kZero) - return kNumZero; - - // k = 1 term: C(n, 1) * r = n * r - Number term = paymentsRemaining * periodicRate; - Number sum = term; - for (std::uint32_t k = 1; k < paymentsRemaining; ++k) - { - // term_{k+1} from term_k: multiply by r * (n - k) / (k + 1) - term = term * periodicRate * (paymentsRemaining - k) / (k + 1); - Number const next = sum + term; - // adding this term fell below Number's precision - if (next == sum) - break; - sum = next; - } - return sum; -} - -/* Hybrid evaluator of (1 + r)^n - 1. - * - * The closed-form `power(1 + r, n) - 1` loses sig digits to cancellation - * when `r * n` is small: the result `~r*n` sits well below the `1` that - * dominates `(1+r)^n`, so most of Number's stored precision is consumed - * by the leading `1`. - * - * A threshold of `1e-9` preserves the closed-form path for any rate the - * lending code actually sees in practice (fixtures at moderate rates are bit-exact), - * while routing the pathological near-zero regime through the binomial - * expansion where cancellation is severe. - */ -Number -computePowerMinusOneHybrid(Number const& periodicRate, std::uint32_t paymentsRemaining) -{ - XRPL_ASSERT_PARTS( - periodicRate >= beast::kZero, - "xrpl::detail::computePowerMinusOneHybrid", - "periodicRate is non-negative"); - - if (paymentsRemaining == 0 || periodicRate == beast::kZero) - return kNumZero; - - // Threshold 1e-9 retains ~10 sig digits of (1+r)^n - 1 against - // Number's 19-digit mantissa: the leading "1" of (1+r)^n consumes - // ~log10(1/(r*n)) digits before the subtraction. Above this point - // closed form is accurate and ~30-500x faster than the binomial - // expansion. - Number const cancellationThreshold{1, -9}; - if (paymentsRemaining * periodicRate >= cancellationThreshold) - return power(1 + periodicRate, paymentsRemaining) - 1; - - return computePowerMinusOne(periodicRate, paymentsRemaining); + return power(1 + periodicRate, paymentsRemaining); } /* Computes the payment factor used in standard amortization formulas. @@ -223,31 +126,16 @@ computePowerMinusOneHybrid(Number const& periodicRate, std::uint32_t paymentsRem * Equation (6) from XLS-66 spec, Section A-2 Equation Glossary */ Number -computePaymentFactor( - Rules const& rules, - Number const& periodicRate, - std::uint32_t paymentsRemaining) +computePaymentFactor(Number const& periodicRate, std::uint32_t paymentsRemaining) { if (paymentsRemaining == 0) - return kNumZero; + return kNUM_ZERO; // For zero interest, payment factor is simply 1/paymentsRemaining - if (periodicRate == beast::kZero) + if (periodicRate == beast::kZERO) return Number{1} / paymentsRemaining; - if (rules.enabled(fixCleanup3_2_0)) - { - Number const raisedRateMinusOne = - computePowerMinusOneHybrid(periodicRate, paymentsRemaining); - Number const raisedRate = 1 + raisedRateMinusOne; - - return (periodicRate * raisedRate) / raisedRateMinusOne; - } - - // Pre-fixCleanup3_2_0: direct subtraction `(1+r)^n - 1` suffers - // catastrophic cancellation at near-zero rates. Retained for - // amendment-gated bit-exact pre-fix behavior. - Number const raisedRate = power(1 + periodicRate, paymentsRemaining); + Number const raisedRate = computeRaisedRate(periodicRate, paymentsRemaining); return (periodicRate * raisedRate) / (raisedRate - 1); } @@ -259,7 +147,6 @@ computePaymentFactor( */ Number loanPeriodicPayment( - Rules const& rules, Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining) @@ -268,10 +155,10 @@ loanPeriodicPayment( return 0; // Interest-free loans: equal principal payments - if (periodicRate == beast::kZero) + if (periodicRate == beast::kZERO) return principalOutstanding / paymentsRemaining; - return principalOutstanding * computePaymentFactor(rules, periodicRate, paymentsRemaining); + return principalOutstanding * computePaymentFactor(periodicRate, paymentsRemaining); } /* Reverse-calculates principal from periodic payment amount. @@ -281,18 +168,17 @@ loanPeriodicPayment( */ Number loanPrincipalFromPeriodicPayment( - Rules const& rules, Number const& periodicPayment, Number const& periodicRate, std::uint32_t paymentsRemaining) { if (paymentsRemaining == 0) - return kNumZero; + return kNUM_ZERO; if (periodicRate == 0) return periodicPayment * paymentsRemaining; - return periodicPayment / computePaymentFactor(rules, periodicRate, paymentsRemaining); + return periodicPayment / computePaymentFactor(periodicRate, paymentsRemaining); } /* @@ -324,11 +210,11 @@ loanLatePaymentInterest( NetClock::time_point parentCloseTime, std::uint32_t nextPaymentDueDate) { - if (principalOutstanding == beast::kZero) - return kNumZero; + if (principalOutstanding == beast::kZERO) + return kNUM_ZERO; if (lateInterestRate == TenthBips32{0}) - return kNumZero; + return kNUM_ZERO; auto const now = parentCloseTime.time_since_epoch().count(); @@ -359,11 +245,11 @@ loanAccruedInterest( std::uint32_t prevPaymentDate, std::uint32_t paymentInterval) { - if (periodicRate == beast::kZero) - return kNumZero; + if (periodicRate == beast::kZERO) + return kNUM_ZERO; if (paymentInterval == 0) - return kNumZero; + return kNUM_ZERO; auto const lastPaymentDate = std::max(prevPaymentDate, startDate); auto const now = parentCloseTime.time_since_epoch().count(); @@ -371,7 +257,7 @@ loanAccruedInterest( // If the loan has been paid ahead, then "lastPaymentDate" is in the future, // and no interest has accrued. if (now <= lastPaymentDate) - return kNumZero; + return kNUM_ZERO; // Equation (4) from XLS-66 spec, Section A-2 Equation Glossary auto const secondsSinceLastPayment = now - lastPaymentDate; @@ -480,7 +366,7 @@ doPayment( XRPL_ASSERT_PARTS( // Use an explicit cast because the template parameter can be // ValueProxy or Number - static_cast(managementFeeOutstandingProxy) >= beast::kZero, + static_cast(managementFeeOutstandingProxy) >= beast::kZERO, "xrpl::detail::doPayment", "fee outstanding stays valid"); @@ -516,7 +402,6 @@ doPayment( */ Expected, TER> tryOverpayment( - Rules const& rules, Asset const& asset, std::int32_t loanScale, ExtendedPaymentComponents const& overpaymentComponents, @@ -529,7 +414,7 @@ tryOverpayment( { // Calculate what the loan state SHOULD be theoretically (at full precision) auto const theoreticalState = computeTheoreticalLoanState( - rules, periodicPayment, periodicRate, paymentRemaining, managementFeeRate); + 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 @@ -547,7 +432,6 @@ tryOverpayment( // recalculates the periodic payment, total value, and management fees // for the remaining payment schedule. auto newLoanProperties = computeLoanProperties( - rules, asset, newTheoreticalPrincipal, periodicRate, @@ -559,34 +443,12 @@ tryOverpayment( << ", 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 the preserved rounding errors. - - auto const newTheoreticalState = [&]() { - auto const state = computeTheoreticalLoanState( - rules, - newLoanProperties.periodicPayment, - periodicRate, - paymentRemaining, - managementFeeRate) + - errors; - - if (!rules.enabled(fixCleanup3_2_0)) - return state; - - // The new principal is known exactly: it is reduced by the overpayment's - // principal portion. computeTheoreticalLoanState instead derives the - // principal -- and, from it, the management fee and interest -- via a - // lossy (P * factor) / factor round-trip. Pin the principal to the exact - // value and re-derive the management fee from the exact interest gross - // (value - principal), so the intermediate state is fully consistent with - // the exact principal rather than the one-scale-unit-high round-trip. - Number const principal = - roundedOldState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta; - Number const managementFee = - tenthBipsOfValue(state.valueOutstanding - principal, managementFeeRate); - return constructLoanState(state.valueOutstanding, principal, managementFee); - }(); + // 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) + + errors; JLOG(j.debug()) << "new theoretical value: " << newTheoreticalState.valueOutstanding << ", principal: " << newTheoreticalState.principalOutstanding @@ -601,7 +463,7 @@ tryOverpayment( newTheoreticalState.principalOutstanding, loanScale, Number::RoundingMode::Upward), - kNumZero, + kNUM_ZERO, roundedOldState.principalOutstanding); auto const totalValueOutstanding = std::clamp( roundToAsset( @@ -609,11 +471,11 @@ tryOverpayment( principalOutstanding + newTheoreticalState.interestOutstanding(), loanScale, Number::RoundingMode::Upward), - kNumZero, + kNUM_ZERO, roundedOldState.valueOutstanding); auto const managementFeeOutstanding = std::clamp( roundToAsset(asset, newTheoreticalState.managementFeeDue, loanScale), - kNumZero, + kNUM_ZERO, roundedOldState.managementFeeDue); auto const roundedNewState = @@ -635,7 +497,7 @@ tryOverpayment( // small interest amounts, that may have already been paid // off. Check what's still outstanding. This should // guarantee that the interest checks pass. - roundedNewState.interestOutstanding() != beast::kZero, + roundedNewState.interestOutstanding() != beast::kZERO, paymentRemaining, newLoanProperties, j)) @@ -720,7 +582,6 @@ tryOverpayment( template Expected doOverpayment( - Rules const& rules, Asset const& asset, std::int32_t loanScale, ExtendedPaymentComponents const& overpaymentComponents, @@ -749,7 +610,6 @@ doOverpayment( // Attempt to re-amortize the loan with the overpayment applied. // This modifies the temporary copies, leaving the proxies unchanged. auto const ret = tryOverpayment( - rules, asset, loanScale, overpaymentComponents, @@ -781,6 +641,16 @@ doOverpayment( // The proxies still hold the original (pre-overpayment) values, which // allows us to compute deltas and verify they match what we expect // from the overpaymentComponents and loanPaymentParts. + + XRPL_ASSERT_PARTS( + overpaymentComponents.trackedPrincipalDelta == + 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 @@ -792,50 +662,18 @@ doOverpayment( << overpaymentComponents.trackedPrincipalDelta - (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding); - // The three assertions below are invariants that only hold once - // fixCleanup3_2_0 pins the new principal to the exact reduction - // (oldPrincipal - trackedPrincipalDelta). Before the amendment, the lossy - // (P * factor) / factor round-trip can leave the new principal one - // scale-unit high, so these equalities do not hold on the pre-amendment - // code path and must be gated to match the fix they verify. - if (rules.enabled(fixCleanup3_2_0)) - { - // The valueChange returned by tryOverpayment satisfies - // valueChange = (newInterestDue - oldInterestDue) + untrackedInterest. - // Using the loan-state identity v = p + i + m and the adjacent - // `principal change agrees` assertion (dp = oldP - newP), this - // rearranges into three independently-computable terms: - // - // 1. TVO change beyond what principal repayment alone explains: - // newTVO - (oldTVO - dp) - // 2. Management fee released by re-amortization (positive when - // mfee decreased; zero when managementFeeRate == 0): - // oldMfee - newMfee - // 3. The overpayment's penalty interest part (= untrackedInterest - // for the overpayment path; see computeOverpaymentComponents): - // trackedInterestPart() - [[maybe_unused]] Number const tvoChange = newRoundedLoanState.valueOutstanding - - (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta); - [[maybe_unused]] Number const managementFeeReleased = - managementFeeOutstandingProxy - newRoundedLoanState.managementFeeDue; - [[maybe_unused]] Number const interestPart = overpaymentComponents.trackedInterestPart(); + XRPL_ASSERT_PARTS( + loanPaymentParts.valueChange == + newRoundedLoanState.valueOutstanding - + (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta) + + overpaymentComponents.trackedInterestPart(), + "xrpl::detail::doOverpayment", + "interest paid agrees"); - XRPL_ASSERT_PARTS( - overpaymentComponents.trackedPrincipalDelta == - principalOutstandingProxy - newRoundedLoanState.principalOutstanding, - "xrpl::detail::doOverpayment", - "principal change agrees"); - - XRPL_ASSERT_PARTS( - loanPaymentParts.valueChange == tvoChange + managementFeeReleased + interestPart, - "xrpl::detail::doOverpayment", - "interest paid agrees"); - - XRPL_ASSERT_PARTS( - overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid, - "xrpl::detail::doOverpayment", - "principal payment matches"); - } + XRPL_ASSERT_PARTS( + overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid, + "xrpl::detail::doOverpayment", + "principal payment matches"); // All validations passed, so update the proxy objects (which will // modify the actual Loan ledger object) @@ -985,8 +823,8 @@ computeFullPayment( // Calculate the theoretical principal based on the payment schedule. // This theoretical (unrounded) value is used to compute interest and // penalties accurately. - Number const theoreticalPrincipalOutstanding = loanPrincipalFromPeriodicPayment( - view.rules(), periodicPayment, periodicRate, paymentRemaining); + Number const theoreticalPrincipalOutstanding = + loanPrincipalFromPeriodicPayment(periodicPayment, periodicRate, paymentRemaining); // Full payment interest includes both accrued interest (time since last // payment) and prepayment penalty (for closing early). @@ -1091,7 +929,6 @@ PaymentComponents::trackedInterestPart() const */ PaymentComponents computePaymentComponents( - Rules const& rules, Asset const& asset, std::int32_t scale, Number const& totalValueOutstanding, @@ -1129,25 +966,14 @@ 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( - rules, periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); + periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); // Round the target to the loan's scale to match how actual loan values - // are stored. With fixCleanup3_2_0 enabled, principal is rounded upward - // and interest downward so that at coarse scale principal sticks at the - // floor (until the final payment clears it) while interest absorbs each - // periodic payment. Without the amendment the pre-existing round-to- - // nearest behavior is preserved (which can hit the "Partial principal - // payment" assertion on degenerate integer-scale loans). - bool const fixCleanup320Enabled = rules.enabled(fixCleanup3_2_0); - Number::RoundingMode const principalRounding = - fixCleanup320Enabled ? Number::RoundingMode::Upward : Number::getround(); - Number::RoundingMode const interestRounding = - fixCleanup320Enabled ? Number::RoundingMode::Downward : Number::getround(); + // are stored. LoanState const roundedTarget = LoanState{ .valueOutstanding = roundToAsset(asset, trueTarget.valueOutstanding, scale), - .principalOutstanding = - roundToAsset(asset, trueTarget.principalOutstanding, scale, principalRounding), - .interestDue = roundToAsset(asset, trueTarget.interestDue, scale, interestRounding), + .principalOutstanding = roundToAsset(asset, trueTarget.principalOutstanding, scale), + .interestDue = roundToAsset(asset, trueTarget.interestDue, scale), .managementFeeDue = roundToAsset(asset, trueTarget.managementFeeDue, scale)}; // Get the current actual loan state from the ledger values @@ -1171,18 +997,16 @@ computePaymentComponents( // Cap each component to never exceed what's actually outstanding deltas.principal = std::min(deltas.principal, currentLedgerState.principalOutstanding); - if (fixCleanup320Enabled) - { - XRPL_ASSERT_PARTS( - deltas.interest <= currentLedgerState.interestDue, - "xrpl::detail::computePaymentComponents", - "interest due delta not greater than outstanding"); - } + XRPL_ASSERT_PARTS( + deltas.interest <= currentLedgerState.interestDue, + "xrpl::detail::computePaymentComponents", + "interest due delta not greater than outstanding"); + // Cap interest to both the outstanding amount AND what's left of the // periodic payment after principal is paid deltas.interest = std::min( {deltas.interest, - std::max(kNumZero, roundedPeriodicPayment - deltas.principal), + std::max(kNUM_ZERO, roundedPeriodicPayment - deltas.principal), currentLedgerState.interestDue}); XRPL_ASSERT_PARTS( @@ -1202,14 +1026,14 @@ computePaymentComponents( // which indicates that we're not going to take the whole payment amount, // but if so, it must be small. auto takeFrom = [](Number& component, Number& excess) { - if (excess > beast::kZero) + if (excess > beast::kZERO) { auto part = std::min(component, excess); component -= part; excess -= part; } XRPL_ASSERT_PARTS( - excess >= beast::kZero, + excess >= beast::kZERO, "xrpl::detail::computePaymentComponents", "excess non-negative"); }; @@ -1227,7 +1051,7 @@ computePaymentComponents( // happen due to earlier caps, but handle it defensively. Number totalOverpayment = deltas.total() - currentLedgerState.valueOutstanding; - if (totalOverpayment > beast::kZero) + if (totalOverpayment > beast::kZERO) { // LCOV_EXCL_START UNREACHABLE( @@ -1245,7 +1069,7 @@ computePaymentComponents( "xrpl::detail::computePaymentComponents", "shortage is rounded"); - if (shortage < beast::kZero) + if (shortage < beast::kZERO) { // Deltas exceed payment amount - reduce them proportionally Number excess = -shortage; @@ -1257,7 +1081,7 @@ computePaymentComponents( // 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::kZero, + shortage >= beast::kZERO, "xrpl::detail::computePaymentComponents", "no shortage or excess"); @@ -1268,33 +1092,33 @@ computePaymentComponents( "total value adds up"); XRPL_ASSERT_PARTS( - deltas.principal >= beast::kZero && + deltas.principal >= beast::kZERO && deltas.principal <= currentLedgerState.principalOutstanding, "xrpl::detail::computePaymentComponents", "valid principal result"); XRPL_ASSERT_PARTS( - deltas.interest >= beast::kZero && deltas.interest <= currentLedgerState.interestDue, + deltas.interest >= beast::kZERO && deltas.interest <= currentLedgerState.interestDue, "xrpl::detail::computePaymentComponents", "valid interest result"); XRPL_ASSERT_PARTS( - deltas.managementFee >= beast::kZero && + deltas.managementFee >= beast::kZERO && deltas.managementFee <= currentLedgerState.managementFeeDue, "xrpl::detail::computePaymentComponents", "valid fee result"); XRPL_ASSERT_PARTS( - deltas.principal + deltas.interest + deltas.managementFee > beast::kZero, + deltas.principal + deltas.interest + deltas.managementFee > beast::kZERO, "xrpl::detail::computePaymentComponents", "payment parts add to payment"); // Final safety clamp to ensure no value exceeds its outstanding balance return PaymentComponents{ .trackedValueDelta = - std::clamp(deltas.total(), kNumZero, currentLedgerState.valueOutstanding), + std::clamp(deltas.total(), kNUM_ZERO, currentLedgerState.valueOutstanding), .trackedPrincipalDelta = - std::clamp(deltas.principal, kNumZero, currentLedgerState.principalOutstanding), + std::clamp(deltas.principal, kNUM_ZERO, currentLedgerState.principalOutstanding), .trackedManagementFeeDelta = - std::clamp(deltas.managementFee, kNumZero, currentLedgerState.managementFeeDue), + std::clamp(deltas.managementFee, kNUM_ZERO, currentLedgerState.managementFeeDue), }; } @@ -1318,7 +1142,6 @@ computePaymentComponents( */ ExtendedPaymentComponents computeOverpaymentComponents( - Rules const& rules, Asset const& asset, int32_t const loanScale, Number const& overpayment, @@ -1326,13 +1149,10 @@ computeOverpaymentComponents( TenthBips32 const overpaymentFeeRate, TenthBips16 const managementFeeRate) { - if (rules.enabled(fixCleanup3_2_0)) - { - XRPL_ASSERT( - overpayment > 0 && isRounded(asset, overpayment, loanScale), - "xrpl::detail::computeOverpaymentComponents : valid overpayment " - "amount"); - } + XRPL_ASSERT( + overpayment > 0 && isRounded(asset, overpayment, loanScale), + "xrpl::detail::computeOverpaymentComponents : valid overpayment " + "amount"); // First, deduct the fixed overpayment fee from the total amount. // This reduces the effective payment that will be applied to the loan. @@ -1464,7 +1284,7 @@ checkLoanGuards( // avoids dividing by 0. auto const roundedPayment = roundPeriodicPayment(vaultAsset, properties.periodicPayment, properties.loanScale); - if (roundedPayment == beast::kZero) + if (roundedPayment == beast::kZERO) { JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment << ") rounds to 0. "; @@ -1522,7 +1342,7 @@ computeFullPaymentInterest( "interest"); // Equation (28) from XLS-66 spec, Section A-2 Equation Glossary - auto const prepaymentPenalty = closeInterestRate == beast::kZero + auto const prepaymentPenalty = closeInterestRate == beast::kZERO ? Number{} : tenthBipsOfValue(theoreticalPrincipalOutstanding, closeInterestRate); @@ -1559,7 +1379,6 @@ computeFullPaymentInterest( */ LoanState computeTheoreticalLoanState( - Rules const& rules, Number const& periodicPayment, Number const& periodicRate, std::uint32_t const paymentRemaining, @@ -1577,8 +1396,8 @@ computeTheoreticalLoanState( // Equation (30) from XLS-66 spec, Section A-2 Equation Glossary Number const totalValueOutstanding = periodicPayment * paymentRemaining; - Number const principalOutstanding = detail::loanPrincipalFromPeriodicPayment( - rules, periodicPayment, periodicRate, paymentRemaining); + Number const principalOutstanding = + detail::loanPrincipalFromPeriodicPayment(periodicPayment, periodicRate, paymentRemaining); // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary Number const interestOutstandingGross = totalValueOutstanding - principalOutstanding; @@ -1669,7 +1488,6 @@ computeManagementFee( */ LoanProperties computeLoanProperties( - Rules const& rules, Asset const& asset, Number const& principalOutstanding, TenthBips32 interestRate, @@ -1681,7 +1499,6 @@ computeLoanProperties( auto const periodicRate = loanPeriodicRate(interestRate, paymentInterval); XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::computeLoanProperties : valid rate"); return computeLoanProperties( - rules, asset, principalOutstanding, periodicRate, @@ -1700,7 +1517,6 @@ computeLoanProperties( */ LoanProperties computeLoanProperties( - Rules const& rules, Asset const& asset, Number const& principalOutstanding, Number const& periodicRate, @@ -1709,7 +1525,7 @@ computeLoanProperties( std::int32_t minimumScale) { auto const periodicPayment = - detail::loanPeriodicPayment(rules, principalOutstanding, periodicRate, paymentsRemaining); + detail::loanPeriodicPayment(principalOutstanding, periodicRate, paymentsRemaining); auto const [totalValueOutstanding, loanScale] = [&]() { // only round up if there should be interest @@ -1757,10 +1573,10 @@ computeLoanProperties( // Compute the parts for the first payment. Ensure that the // principal payment will actually change the principal. auto const startingState = computeTheoreticalLoanState( - rules, periodicPayment, periodicRate, paymentsRemaining, managementFeeRate); + periodicPayment, periodicRate, paymentsRemaining, managementFeeRate); auto const firstPaymentState = computeTheoreticalLoanState( - rules, periodicPayment, periodicRate, paymentsRemaining - 1, managementFeeRate); + 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 @@ -1917,7 +1733,6 @@ loanMakePayment( // payment is late or regular detail::ExtendedPaymentComponents periodic{ detail::computePaymentComponents( - view.rules(), asset, loanScale, totalValueOutstandingProxy, @@ -1994,7 +1809,7 @@ loanMakePayment( std::size_t numPayments = 0; while ((amount >= (totalPaid + periodic.totalDue)) && paymentRemainingProxy > 0 && - numPayments < kLoanMaximumPaymentsPerTransaction) + numPayments < kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION) { // Try to make more payments XRPL_ASSERT_PARTS( @@ -2026,7 +1841,6 @@ loanMakePayment( periodic = detail::ExtendedPaymentComponents{ detail::computePaymentComponents( - view.rules(), asset, loanScale, totalValueOutstandingProxy, @@ -2054,19 +1868,9 @@ loanMakePayment( // ------------------------------------------------------------- // overpayment handling - // - // If the "fixCleanup3_1_3" amendment is enabled, truncate "amount", - // at the loan scale. If the raw value is used, the overpayment - // amount could be meaningless dust. Trying to process such a small - // amount will, at best, waste time when all the result values round - // to zero. At worst, it can cause logical errors with tiny amounts - // of interest that don't add up correctly. - auto const roundedAmount = view.rules().enabled(fixCleanup3_1_3) - ? roundToAsset(asset, amount, loanScale, Number::RoundingMode::TowardsZero) - : amount; if (paymentType == LoanPaymentType::Overpayment && loan->isFlag(lsfLoanOverpayment) && - paymentRemainingProxy > 0 && totalPaid < roundedAmount && - numPayments < kLoanMaximumPaymentsPerTransaction) + paymentRemainingProxy > 0 && totalPaid < amount && + numPayments < kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION) { TenthBips32 const overpaymentInterestRate{loan->at(sfOverpaymentInterestRate)}; TenthBips32 const overpaymentFeeRate{loan->at(sfOverpaymentFee)}; @@ -2074,63 +1878,50 @@ loanMakePayment( // 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 overpaymentRaw = - std::min(roundedAmount - totalPaid, *totalValueOutstandingProxy); + Number const overpayment = std::min(amount - totalPaid, *totalValueOutstandingProxy); - bool const fixEnabled = view.rules().enabled(fixCleanup3_2_0); - Number const overpayment = fixEnabled - ? roundToAsset(asset, overpaymentRaw, loanScale, Number::RoundingMode::Downward) - : overpaymentRaw; + detail::ExtendedPaymentComponents const overpaymentComponents = + detail::computeOverpaymentComponents( + asset, + loanScale, + overpayment, + overpaymentInterestRate, + overpaymentFeeRate, + managementFeeRate); - // Post-amendment, the rounded overpayment can be zero; pre-amendment - // it's always positive given the surrounding guards. - if (!fixEnabled || overpayment > 0) + // Don't process an overpayment if the whole amount (or more!) + // gets eaten by fees and interest. + if (overpaymentComponents.trackedPrincipalDelta > 0) { - detail::ExtendedPaymentComponents const overpaymentComponents = - detail::computeOverpaymentComponents( - view.rules(), + XRPL_ASSERT_PARTS( + overpaymentComponents.untrackedInterest >= beast::kZERO, + "xrpl::loanMakePayment", + "overpayment penalty did not reduce value of loan"); + // Can't just use `periodicPayment` here, because it might + // change + auto periodicPaymentProxy = loan->at(sfPeriodicPayment); + if (auto const overResult = detail::doOverpayment( asset, loanScale, - overpayment, - overpaymentInterestRate, - overpaymentFeeRate, - managementFeeRate); - - // Don't process an overpayment if the whole amount (or more!) - // gets eaten by fees and interest. - if (overpaymentComponents.trackedPrincipalDelta > 0) + overpaymentComponents, + totalValueOutstandingProxy, + principalOutstandingProxy, + managementFeeOutstandingProxy, + periodicPaymentProxy, + periodicRate, + paymentRemainingProxy, + managementFeeRate, + j)) { - XRPL_ASSERT_PARTS( - overpaymentComponents.untrackedInterest >= beast::kZero, - "xrpl::loanMakePayment", - "overpayment penalty did not reduce value of loan"); - // Can't just use `periodicPayment` here, because it might - // change - auto periodicPaymentProxy = loan->at(sfPeriodicPayment); - if (auto const overResult = detail::doOverpayment( - view.rules(), - asset, - loanScale, - overpaymentComponents, - totalValueOutstandingProxy, - principalOutstandingProxy, - managementFeeOutstandingProxy, - periodicPaymentProxy, - periodicRate, - paymentRemainingProxy, - managementFeeRate, - j)) - { - totalParts += *overResult; - } - else if (overResult.error()) - { - // error() will be the TER returned if a payment is not - // made. It will only evaluate to true if it's unsuccessful. - // Otherwise, tesSUCCESS means nothing was done, so - // continue. - return Unexpected(overResult.error()); - } + totalParts += *overResult; + } + else if (overResult.error()) + { + // error() will be the TER returned if a payment is not + // made. It will only evaluate to true if it's unsuccessful. + // Otherwise, tesSUCCESS means nothing was done, so + // continue. + return Unexpected(overResult.error()); } } } @@ -2139,17 +1930,17 @@ loanMakePayment( // intermediate steps were rounded. XRPL_ASSERT( isRounded(asset, totalParts.principalPaid, loanScale) && - totalParts.principalPaid >= beast::kZero, + totalParts.principalPaid >= beast::kZERO, "xrpl::loanMakePayment : total principal paid is valid"); XRPL_ASSERT( isRounded(asset, totalParts.interestPaid, loanScale) && - totalParts.interestPaid >= beast::kZero, + totalParts.interestPaid >= beast::kZERO, "xrpl::loanMakePayment : total interest paid is valid"); XRPL_ASSERT( isRounded(asset, totalParts.valueChange, loanScale), "xrpl::loanMakePayment : loan value change is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.feePaid, loanScale) && totalParts.feePaid >= beast::kZero, + isRounded(asset, totalParts.feePaid, loanScale) && totalParts.feePaid >= beast::kZERO, "xrpl::loanMakePayment : fee paid is valid"); return totalParts; } diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index 5c6863fbe6..7c6b01ce06 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -54,11 +55,7 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue cons } bool -isFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - std::uint8_t depth) +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) { return isGlobalFrozen(view, mptIssue) || isIndividualFrozen(view, account, mptIssue) || isVaultPseudoAccountFrozen(view, account, mptIssue, depth); @@ -69,7 +66,7 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, - std::uint8_t depth) + int depth) { if (isGlobalFrozen(view, mptIssue)) return true; @@ -99,11 +96,11 @@ transferRate(ReadView const& view, MPTID const& issuanceID) sle && sle->isFieldPresent(sfTransferFee)) { auto const fee = sle->getFieldU16(sfTransferFee); - XRPL_ASSERT(fee <= kMaxTransferFee, "xrpl::transferRate : fee is too large"); + XRPL_ASSERT(fee <= kMAX_TRANSFER_FEE, "xrpl::transferRate : fee is too large"); return Rate{1'000'000'000u + (10'000 * fee)}; } - return kParityRate; + return kPARITY_RATE; } [[nodiscard]] TER @@ -172,7 +169,7 @@ authorizeMPToken( auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); auto const sleMpt = view.peek(mptokenKey); if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0 || - (view.rules().enabled(fixCleanup3_1_3) && + (view.rules().enabled(fixSecurity3_1_3) && (*sleMpt)[~sfLockedAmount].valueOr(0) != 0)) return tecINTERNAL; // LCOV_EXCL_LINE @@ -197,7 +194,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::kZero) + (uOwnerCount < 2) ? XRPAmount(beast::kZERO) : view.fees().accountReserve(uOwnerCount + 1)); if (priorBalance < reserveCreate) @@ -287,7 +284,7 @@ removeEmptyHolding( // accounting out of balance, so fail. Since this should be impossible // anyway, I'm not going to put any effort into it. if (mptoken->at(sfMPTAmount) != 0 || - (view.rules().enabled(fixCleanup3_1_3) && (*mptoken)[~sfLockedAmount].valueOr(0) != 0)) + (view.rules().enabled(fixSecurity3_1_3) && (*mptoken)[~sfLockedAmount].valueOr(0) != 0)) return tecHAS_OBLIGATIONS; // Don't delete if the token still has confidential balances @@ -313,7 +310,7 @@ requireAuth( MPTIssue const& mptIssue, AccountID const& account, AuthType authType, - std::uint8_t depth) + int depth) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -330,13 +327,8 @@ requireAuth( if (featureSAVEnabled) { - if (depth >= kMaxAssetCheckDepth) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::MPTokenHelpers::requireAuth : reached asset check depth"); - return tecINTERNAL; - // LCOV_EXCL_STOP - } + if (depth >= kMAX_ASSET_CHECK_DEPTH) + return tecINTERNAL; // LCOV_EXCL_LINE // requireAuth is recursive if the issuer is a vault pseudo-account auto const sleIssuer = view.read(keylet::account(mptIssuer)); @@ -373,7 +365,7 @@ requireAuth( if (maybeDomainID) { XRPL_ASSERT( - sleIssuance->isFlag(lsfMPTRequireAuth), + sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, "xrpl::requireAuth : issuance requires authorization"); // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED auto const ter = credentials::validDomain(view, *maybeDomainID, account); @@ -389,11 +381,10 @@ requireAuth( // belong to someone who is explicitly authorized e.g. a vault owner. } - bool const featureMPTV2Enabled = view.rules().enabled(featureMPTokensV2); - if (featureSAVEnabled || featureMPTV2Enabled) + if (featureSAVEnabled) { - // Implicitly authorize Vault, LoanBroker, and AMM pseudo-accounts - if (isPseudoAccount(view, account, {&sfVaultID, &sfLoanBrokerID, &sfAMMID})) + // Implicitly authorize Vault and LoanBroker pseudo-accounts + if (isPseudoAccount(view, account, {&sfVaultID, &sfLoanBrokerID})) return tesSUCCESS; } @@ -505,88 +496,28 @@ enforceMPTokenAuthorization( // LCOV_EXCL_STOP } -[[nodiscard]] Asset -assetOfHolding(SLE const& sleShareIssuance, SLE const& sleHolding) -{ - XRPL_ASSERT_PARTS( - sleHolding.getType() == ltRIPPLE_STATE || sleHolding.getType() == ltMPTOKEN, - "xrpl::assetOfHolding", - "unexpected holding type"); - XRPL_ASSERT_PARTS( - sleShareIssuance.getType() == ltMPTOKEN_ISSUANCE, - "xrpl::assetOfHolding", - "not SLE MPTokenIssuance"); - - if (sleHolding.getType() == ltMPTOKEN) - return MPTIssue{sleHolding.getFieldH192(sfMPTokenIssuanceID)}; - - auto const vaultPseudo = sleShareIssuance.at(sfIssuer); - auto const lowLimit = sleHolding.getFieldAmount(sfLowLimit); - auto const highLimit = sleHolding.getFieldAmount(sfHighLimit); - auto const& iouIssuer = - (lowLimit.getIssuer() != vaultPseudo) ? lowLimit.getIssuer() : highLimit.getIssuer(); - return Issue{lowLimit.get().currency, iouIssuer}; -} - TER canTransfer( ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, - AccountID const& to, - WaiveMPTCanTransfer waive, - std::uint8_t depth) + AccountID const& to) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); if (!sleIssuance) return tecOBJECT_NOT_FOUND; - auto const issuer = (*sleIssuance)[sfIssuer]; - if (waive == WaiveMPTCanTransfer::Yes || from == issuer || to == issuer) - return tesSUCCESS; - if (!sleIssuance->isFlag(lsfMPTCanTransfer)) - return TER{tecNO_AUTH}; - - // Post-fixCleanup3_2_0: vault shares carry sfReferenceHolding pointing - // to the vault pseudo's MPToken or RippleState for the underlying asset. - // Third-party transfers inherit the underlying's transferability. - // Issuer-involving transfers and waived callers returned tesSUCCESS above. - // - // The recursive call always passes WaiveMPTCanTransfer::No so that - // a waived outer caller does not transitively unlock the underlying. - if (view.rules().enabled(fixCleanup3_2_0) && sleIssuance->isFieldPresent(sfReferenceHolding)) { - // Defensive depth bound on the inheritance recursion. Unreachable - // in practice (vault-of-vault-shares is forbidden at VaultCreate). - if (depth >= kMaxAssetCheckDepth) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::MPTokenHelpers::canTransfer : reached asset check depth"); - return tecINTERNAL; - // LCOV_EXCL_STOP - } - - auto const sleHolding = - view.read(keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); - if (!sleHolding) - return tefINTERNAL; // LCOV_EXCL_LINE - - return canTransfer( - view, - assetOfHolding(*sleIssuance, *sleHolding), - from, - to, - WaiveMPTCanTransfer::No, - depth + 1); + if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer]) + return TER{tecNO_AUTH}; } - return tesSUCCESS; } TER -canTrade(ReadView const& view, Asset const& asset, std::uint8_t depth) +canTrade(ReadView const& view, Asset const& asset) { return asset.visit( [&](Issue const&) -> TER { return tesSUCCESS; }, @@ -596,51 +527,10 @@ canTrade(ReadView const& view, Asset const& asset, std::uint8_t depth) return tecOBJECT_NOT_FOUND; if (!sleIssuance->isFlag(lsfMPTCanTrade)) return tecNO_PERMISSION; - - // Post-fixCleanup3_2_0: vault shares inherit the underlying - // asset's tradability. A share whose underlying has been - // removed from trading cannot itself be placed on the DEX. - if (view.rules().enabled(fixCleanup3_2_0) && - sleIssuance->isFieldPresent(sfReferenceHolding)) - { - // Defensive depth bound on the inheritance recursion. - // Unreachable in practice (vault-of-vault-shares - // forbidden at VaultCreate). - if (depth >= kMaxAssetCheckDepth) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::MPTokenHelpers::canTrade : reached asset check depth"); - return tecINTERNAL; - // LCOV_EXCL_STOP - } - auto const sleHolding = - view.read(keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); - if (!sleHolding) - return tefINTERNAL; // LCOV_EXCL_LINE - - return canTrade(view, assetOfHolding(*sleIssuance, *sleHolding), depth + 1); - } - return tesSUCCESS; }); } -TER -canMPTTradeAndTransfer( - ReadView const& view, - Asset const& asset, - AccountID const& from, - AccountID const& to) -{ - if (!asset.holds()) - return tesSUCCESS; - - if (auto const ter = canTrade(view, asset); !isTesSuccess(ter)) - return ter; - - return canTransfer(view, asset, from, to); -} - TER lockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& amount, beast::Journal j) { @@ -956,7 +846,7 @@ checkCreateMPT( std::int64_t maxMPTAmount(SLE const& sleIssuance) { - return sleIssuance[~sfMaximumAmount].value_or(kMaxMpTokenAmount); + return sleIssuance[~sfMaximumAmount].value_or(kMAX_MP_TOKEN_AMOUNT); } std::int64_t @@ -1008,4 +898,65 @@ issuerSelfDebitHookMPT(ApplyView& view, MPTIssue const& issue, std::uint64_t amo view.issuerSelfDebitHookMPT(issue, amount, available); } +static TER +checkMPTAllowed(ReadView const& view, TxType txType, Asset const& asset, AccountID const& accountID) +{ + if (!asset.holds()) + return tesSUCCESS; + + auto const& issuanceID = asset.get().getMptID(); + auto const validTx = txType == ttAMM_CREATE || txType == ttAMM_DEPOSIT || + txType == ttAMM_WITHDRAW || txType == ttOFFER_CREATE || txType == ttCHECK_CREATE || + txType == ttCHECK_CASH || txType == ttPAYMENT; + XRPL_ASSERT(validTx, "xrpl::checkMPTAllowed : all MPT tx or DEX"); + if (!validTx) + return tefINTERNAL; // LCOV_EXCL_LINE + + auto const& issuer = asset.getIssuer(); + if (!view.exists(keylet::account(issuer))) + return tecNO_ISSUER; // LCOV_EXCL_LINE + + auto const issuanceKey = keylet::mptIssuance(issuanceID); + auto const issuanceSle = view.read(issuanceKey); + if (!issuanceSle) + return tecOBJECT_NOT_FOUND; // LCOV_EXCL_LINE + + auto const flags = issuanceSle->getFlags(); + + if ((flags & lsfMPTLocked) != 0u) + return tecLOCKED; // LCOV_EXCL_LINE + // Offer crossing and Payment + if ((flags & lsfMPTCanTrade) == 0) + return tecNO_PERMISSION; + + if (accountID != issuer) + { + if ((flags & lsfMPTCanTransfer) == 0) + return tecNO_PERMISSION; + + auto const mptSle = view.read(keylet::mptoken(issuanceKey.key, accountID)); + // Allow to succeed since some tx create MPToken if it doesn't exist. + // Tx's have their own check for missing MPToken. + if (!mptSle) + return tesSUCCESS; + + if (mptSle->isFlag(lsfMPTLocked)) + return tecLOCKED; + } + + return tesSUCCESS; +} + +TER +checkMPTTxAllowed( + ReadView const& view, + TxType txType, + Asset const& asset, + AccountID const& accountID) +{ + // use isDEXAllowed for payment/offer crossing + XRPL_ASSERT(txType != ttPAYMENT, "xrpl::checkMPTTxAllowed : not payment"); + return checkMPTAllowed(view, txType, asset, accountID); +} + } // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp b/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp index 5b467db796..eb69ec93d0 100644 --- a/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp @@ -41,7 +41,7 @@ namespace xrpl::nft { -static SLE::const_pointer +static std::shared_ptr locatePage(ReadView const& view, AccountID const& owner, uint256 const& id) { auto const first = keylet::nftpage(keylet::nftpageMin(owner), id); @@ -54,7 +54,7 @@ locatePage(ReadView const& view, AccountID const& owner, uint256 const& id) Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); } -static SLE::pointer +static std::shared_ptr locatePage(ApplyView& view, AccountID const& owner, uint256 const& id) { auto const first = keylet::nftpage(keylet::nftpageMin(owner), id); @@ -67,7 +67,7 @@ locatePage(ApplyView& view, AccountID const& owner, uint256 const& id) Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); } -static SLE::pointer +static std::shared_ptr getPageForToken( ApplyView& view, AccountID const& owner, @@ -98,7 +98,7 @@ getPageForToken( STArray narr = cp->getFieldArray(sfNFTokens); // The right page still has space: we're good. - if (narr.size() != kDirMaxTokensPerPage) + if (narr.size() != kDIR_MAX_TOKENS_PER_PAGE) return cp; // We need to split the page in two: the first half of the items in this @@ -115,13 +115,13 @@ getPageForToken( // any additional equivalent NFTs maximum room for expansion. // Round up the boundary until there's a non-equivalent entry. uint256 const cmp = - narr[(kDirMaxTokensPerPage / 2) - 1].getFieldH256(sfNFTokenID) & nft::kPageMask; + narr[(kDIR_MAX_TOKENS_PER_PAGE / 2) - 1].getFieldH256(sfNFTokenID) & nft::kPAGE_MASK; // Note that the calls to find_if_not() and (later) find_if() // rely on the fact that narr is kept in sorted order. auto splitIter = std::find_if_not( - narr.begin() + (kDirMaxTokensPerPage / 2), narr.end(), [&cmp](STObject const& obj) { - return (obj.getFieldH256(sfNFTokenID) & nft::kPageMask) == cmp; + narr.begin() + (kDIR_MAX_TOKENS_PER_PAGE / 2), narr.end(), [&cmp](STObject const& obj) { + return (obj.getFieldH256(sfNFTokenID) & nft::kPAGE_MASK) == cmp; }); // If we get all the way from the middle to the end with only @@ -130,7 +130,7 @@ getPageForToken( if (splitIter == narr.end()) { splitIter = std::ranges::find_if(narr, [&cmp](STObject const& obj) { - return (obj.getFieldH256(sfNFTokenID) & nft::kPageMask) == cmp; + return (obj.getFieldH256(sfNFTokenID) & nft::kPAGE_MASK) == cmp; }); } @@ -143,7 +143,7 @@ getPageForToken( // equivalent tokens. This requires special handling. if (splitIter == narr.begin()) { - auto const relation{(id & nft::kPageMask) <=> cmp}; + auto const relation{(id & nft::kPAGE_MASK) <=> cmp}; if (relation == 0) { // If the passed in id belongs exactly on this (full) page @@ -178,8 +178,8 @@ getPageForToken( // less than the low 96-bits of the enclosing page's index. In order to // accommodate that requirement we use an index one higher than the // largest NFT in the page. - uint256 const tokenIDForNewPage = narr.size() == kDirMaxTokensPerPage - ? narr[kDirMaxTokensPerPage - 1].getFieldH256(sfNFTokenID).next() + uint256 const tokenIDForNewPage = narr.size() == kDIR_MAX_TOKENS_PER_PAGE + ? narr[kDIR_MAX_TOKENS_PER_PAGE - 1].getFieldH256(sfNFTokenID).next() : carr[0].getFieldH256(sfNFTokenID); auto np = std::make_shared(keylet::nftpage(base, tokenIDForNewPage)); @@ -217,7 +217,7 @@ compareTokens(uint256 const& a, uint256 const& b) // 96-bits are identical we still need a fully deterministic sort. // So we sort on the low 96-bits first. If those are equal we sort on // the whole thing. - if (auto const lowBitsCmp{(a & nft::kPageMask) <=> (b & nft::kPageMask)}; lowBitsCmp != 0) + if (auto const lowBitsCmp{(a & nft::kPAGE_MASK) <=> (b & nft::kPAGE_MASK)}; lowBitsCmp != 0) return lowBitsCmp < 0; return a < b; @@ -230,7 +230,7 @@ changeTokenURI( uint256 const& nftokenID, std::optional const& uri) { - SLE::pointer const page = locatePage(view, owner, nftokenID); + std::shared_ptr const page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -267,7 +267,7 @@ insertToken(ApplyView& view, AccountID owner, STObject&& nft) // First, we need to locate the page the NFT belongs to, creating it // if necessary. This operation may fail if it is impossible to insert // the NFT. - SLE::pointer const page = + std::shared_ptr const page = getPageForToken(view, owner, nft[sfNFTokenID], [](ApplyView& view, AccountID const& owner) { adjustOwnerCount( view, @@ -296,7 +296,7 @@ insertToken(ApplyView& view, AccountID owner, STObject&& nft) } static bool -mergePages(ApplyView& view, SLE::ref p1, SLE::ref p2) +mergePages(ApplyView& view, std::shared_ptr const& p1, std::shared_ptr const& p2) { if (p1->key() >= p2->key()) Throw("mergePages: pages passed in out of order!"); @@ -314,7 +314,7 @@ mergePages(ApplyView& view, SLE::ref p1, SLE::ref p2) // this it would mean that one of them can be deleted as a result of // the merge. - if (p1arr.size() + p2arr.size() > kDirMaxTokensPerPage) + if (p1arr.size() + p2arr.size() > kDIR_MAX_TOKENS_PER_PAGE) return false; STArray x(p1arr.size() + p2arr.size()); @@ -355,7 +355,7 @@ mergePages(ApplyView& view, SLE::ref p1, SLE::ref p2) TER removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) { - SLE::pointer const page = locatePage(view, owner, nftokenID); + std::shared_ptr const page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -366,7 +366,11 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) /** Remove the token from the owner's token directory. */ TER -removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, SLE::ref curr) +removeToken( + ApplyView& view, + AccountID const& owner, + uint256 const& nftokenID, + std::shared_ptr const& curr) { // We found a page, but the given NFT may not be in it. auto arr = curr->getFieldArray(sfNFTokens); @@ -382,8 +386,8 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, S } // Page management: - auto const loadPage = [&view](SLE::ref page1, SF_UINT256 const& field) { - SLE::pointer page2; + auto const loadPage = [&view](std::shared_ptr const& page1, SF_UINT256 const& field) { + std::shared_ptr page2; if (auto const id = (*page1)[~field]) { @@ -441,7 +445,7 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, S // 3. Fix up the owner count. // 4. Erase the previous page. if (view.rules().enabled(fixNFTokenPageLinks) && - ((curr->key() & nft::kPageMask) == kPageMask)) + ((curr->key() & nft::kPAGE_MASK) == kPAGE_MASK)) { // Copy all relevant information from prev to curr. curr->peekFieldArray(sfNFTokens) = prev->peekFieldArray(sfNFTokens); @@ -531,7 +535,7 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, S std::optional findToken(ReadView const& view, AccountID const& owner, uint256 const& nftokenID) { - SLE::const_pointer const page = locatePage(view, owner, nftokenID); + std::shared_ptr const page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -550,7 +554,7 @@ findToken(ReadView const& view, AccountID const& owner, uint256 const& nftokenID std::optional findTokenAndPage(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) { - SLE::pointer page = locatePage(view, owner, nftokenID); + std::shared_ptr page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -619,7 +623,7 @@ removeTokenOffersWithLimit(ApplyView& view, Keylet const& directory, std::size_t } bool -deleteTokenOffer(ApplyView& view, SLE::ref offer) +deleteTokenOffer(ApplyView& view, std::shared_ptr const& offer) { if (offer->getType() != ltNFTOKEN_OFFER) return false; @@ -632,8 +636,8 @@ deleteTokenOffer(ApplyView& view, SLE::ref offer) auto const nftokenID = (*offer)[sfNFTokenID]; if (!view.dirRemove( - offer->isFlag(lsfSellNFToken) ? keylet::nftSells(nftokenID) - : keylet::nftBuys(nftokenID), + (((*offer)[sfFlags] & lsfSellNFToken) != 0u) ? keylet::nftSells(nftokenID) + : keylet::nftBuys(nftokenID), (*offer)[sfNFTokenOfferNode], offer->key(), false)) @@ -653,7 +657,7 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) auto const last = keylet::nftpageMax(owner); - SLE::pointer page = view.peek(Keylet( + std::shared_ptr page = view.peek(Keylet( ltNFTOKEN_PAGE, view.succ(keylet::nftpageMin(owner).key, last.key.next()).value_or(last.key))); @@ -687,7 +691,7 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) view.update(page); } - SLE::pointer nextPage; + std::shared_ptr nextPage; while ( (nextPage = view.peek(Keylet( ltNFTOKEN_PAGE, view.succ(page->key().next(), last.key.next()).value_or(last.key))))) @@ -784,7 +788,7 @@ tokenOfferCreatePreflight( if (!isXRP(amount)) { - if ((nftFlags & nft::kFlagOnlyXrp) != 0) + if ((nftFlags & nft::kFLAG_ONLY_XRP) != 0) return temBAD_AMOUNT; if (!amount) @@ -829,7 +833,7 @@ tokenOfferCreatePreclaim( std::optional const& owner, std::uint32_t txFlags) { - if (((nftFlags & nft::kFlagCreateTrustLines) == 0) && !amount.native() && (xferFee != 0u)) + if (((nftFlags & nft::kFLAG_CREATE_TRUST_LINES) == 0) && !amount.native() && (xferFee != 0u)) { if (!view.exists(keylet::account(nftIssuer))) return tecNO_ISSUER; @@ -851,7 +855,7 @@ tokenOfferCreatePreclaim( return tecFROZEN; } - if (nftIssuer != acctID && ((nftFlags & nft::kFlagTransferable) == 0)) + if (nftIssuer != acctID && ((nftFlags & nft::kFLAG_TRANSFERABLE) == 0)) { auto const root = view.read(keylet::account(nftIssuer)); XRPL_ASSERT(root, "xrpl::nft::tokenOfferCreatePreclaim : non-null account"); @@ -884,7 +888,7 @@ tokenOfferCreatePreclaim( return tecNO_DST; // check if the destination has disallowed incoming offers - if (sleDst->isFlag(lsfDisallowIncomingNFTokenOffer)) + if ((sleDst->getFlags() & lsfDisallowIncomingNFTokenOffer) != 0u) return tecNO_PERMISSION; } @@ -897,7 +901,7 @@ tokenOfferCreatePreclaim( if (!sleOwner) return tecNO_TARGET; - if (sleOwner->isFlag(lsfDisallowIncomingNFTokenOffer)) + if ((sleOwner->getFlags() & lsfDisallowIncomingNFTokenOffer) != 0u) return tecNO_PERMISSION; } @@ -952,7 +956,7 @@ tokenOfferCreateApply( auto const offerNode = view.dirInsert( isSellOffer ? keylet::nftSells(nftokenID) : keylet::nftBuys(nftokenID), offerID, - [&nftokenID, isSellOffer](SLE::ref sle) { + [&nftokenID, isSellOffer](std::shared_ptr const& sle) { (*sle)[sfFlags] = isSellOffer ? lsfNFTokenSellOffers : lsfNFTokenBuyOffers; (*sle)[sfNFTokenID] = nftokenID; }); diff --git a/src/libxrpl/ledger/helpers/OfferHelpers.cpp b/src/libxrpl/ledger/helpers/OfferHelpers.cpp index 5249870143..03a1170aad 100644 --- a/src/libxrpl/ledger/helpers/OfferHelpers.cpp +++ b/src/libxrpl/ledger/helpers/OfferHelpers.cpp @@ -12,10 +12,12 @@ #include #include +#include + namespace xrpl { TER -offerDelete(ApplyView& view, SLE::ref sle, beast::Journal j) +offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) { if (!sle) return tesSUCCESS; diff --git a/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp b/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp index e755dbaca3..31c206d85b 100644 --- a/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp +++ b/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp @@ -12,10 +12,16 @@ #include #include +#include + namespace xrpl { TER -closeChannel(SLE::ref slep, ApplyView& view, uint256 const& key, beast::Journal j) +closeChannel( + std::shared_ptr const& slep, + ApplyView& view, + uint256 const& key, + beast::Journal j) { AccountID const src = (*slep)[sfAccount]; // Remove PayChan from owner directory diff --git a/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp b/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp index f8653f7111..456c4e95d6 100644 --- a/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp +++ b/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp @@ -3,8 +3,6 @@ #include #include #include -#include -#include #include #include #include @@ -21,16 +19,6 @@ namespace xrpl::permissioned_dex { bool accountInDomain(ReadView const& view, AccountID const& account, Domain const& domainID) { - // Avoid constructing a zero-key PermissionedDomain keylet. - // keylet::permissionedDomain(uint256) uses the DomainID as the ledger key. - if (view.rules().enabled(fixCleanup3_2_0) && domainID == beast::kZero) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::permissioned_dex::accountInDomain : domainID is zero"); - return false; - // LCOV_EXCL_STOP - } - auto const sleDomain = view.read(keylet::permissionedDomain(domainID)); if (!sleDomain) return false; @@ -47,7 +35,7 @@ accountInDomain(ReadView const& view, AccountID const& account, Domain const& do if (!sleCred || !sleCred->isFlag(lsfAccepted)) return false; - return !credentials::checkExpired(*sleCred, view.header().parentCloseTime); + return !credentials::checkExpired(sleCred, view.header().parentCloseTime); }); return inDomain; @@ -72,9 +60,9 @@ offerInDomain( if (sleOffer->getFieldH256(sfDomainID) != domainID) return false; // LCOV_EXCL_LINE - if (view.rules().enabled(fixCleanup3_1_3)) + if (view.rules().enabled(fixSecurity3_1_3)) { - // post-fixCleanup3_1_3: a valid hybrid offer must have + // post-fixSecurity3_1_3: a valid hybrid offer must have // sfAdditionalBooks present with exactly 1 entry if (sleOffer->isFlag(lsfHybrid) && (!sleOffer->isFieldPresent(sfAdditionalBooks) || @@ -87,7 +75,7 @@ offerInDomain( } else { - // pre-fixCleanup3_1_3: a valid hybrid offer must have + // pre-fixSecurity3_1_3: a valid hybrid offer must have // sfAdditionalBooks present (size is not checked) if (sleOffer->isFlag(lsfHybrid) && !sleOffer->isFieldPresent(sfAdditionalBooks)) { diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp index 7ed7ab8fc4..58f44534cf 100644 --- a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -183,15 +183,15 @@ trustCreate( bool const bSrcHigh, AccountID const& uSrcAccountID, AccountID const& uDstAccountID, - uint256 const& uIndex, // ripple state entry - SLE::ref sleAccount, // the account being set. - bool const bAuth, // authorize account. - bool const bNoRipple, // others cannot ripple through - bool const bFreeze, // funds cannot leave - bool bDeepFreeze, // can neither receive nor send funds - STAmount const& saBalance, // balance of account being set. + uint256 const& uIndex, // --> ripple state entry + SLE::ref sleAccount, // --> the account being set. + bool const bAuth, // --> authorize account. + bool const bNoRipple, // --> others cannot ripple through + bool const bFreeze, // --> funds cannot leave + bool bDeepFreeze, // --> can neither receive nor send funds + STAmount const& saBalance, // --> balance of account being set. // Issuer should be noAccount() - STAmount const& saLimit, // limit for account being set. + STAmount const& saLimit, // --> limit for account being set. // Issuer should be the account being set. std::uint32_t uQualityIn, std::uint32_t uQualityOut, @@ -274,7 +274,7 @@ trustCreate( uFlags |= (bSetHigh ? lsfHighDeepFreeze : lsfLowDeepFreeze); } - if (!slePeer->isFlag(lsfDefaultRipple)) + if ((slePeer->getFlags() & lsfDefaultRipple) == 0) { // The other side's default is no rippling uFlags |= (bSetHigh ? lsfLowNoRipple : lsfHighNoRipple); @@ -294,7 +294,7 @@ trustCreate( TER trustDelete( ApplyView& view, - SLE::ref sleRippleState, + std::shared_ptr const& sleRippleState, AccountID const& uLowAccountID, AccountID const& uHighAccountID, beast::Journal j) @@ -341,25 +341,22 @@ updateTrustLine( { if (!state) return false; + std::uint32_t const flags(state->getFieldU32(sfFlags)); auto sle = view.peek(keylet::account(sender)); if (!sle) return false; - auto const senderReserveFlag = bSenderHigh ? lsfHighReserve : lsfLowReserve; - auto const senderNoRippleFlag = bSenderHigh ? lsfHighNoRipple : lsfLowNoRipple; - auto const senderFreezeFlag = bSenderHigh ? lsfHighFreeze : lsfLowFreeze; - auto const receiverReserveFlag = bSenderHigh ? lsfLowReserve : lsfHighReserve; - // YYY Could skip this if rippling in reverse. - if (before > beast::kZero + if (before > beast::kZERO // Sender balance was positive. - && after <= beast::kZero + && after <= beast::kZERO // Sender is zero or negative. - && state->isFlag(senderReserveFlag) + && ((flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) != 0u) // Sender reserve is set. - && state->isFlag(senderNoRippleFlag) != sle->isFlag(lsfDefaultRipple) && - !state->isFlag(senderFreezeFlag) && + && static_cast(flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + static_cast(sle->getFlags() & lsfDefaultRipple) && + ((flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) == 0u) && !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. && (state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) == 0u) @@ -372,10 +369,11 @@ updateTrustLine( adjustOwnerCount(view, sle, -1, j); // Clear reserve flag. - state->clearFlag(senderReserveFlag); + state->setFieldU32(sfFlags, flags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); // Balance is zero, receiver reserve is clear. - if (!after && !state->isFlag(receiverReserveFlag)) + if (!after // Balance is zero. + && ((flags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)) == 0u)) return true; } return false; @@ -455,7 +453,7 @@ issueIOU( if (!receiverAccount) return tefINTERNAL; // LCOV_EXCL_LINE - bool const noRipple = !receiverAccount->isFlag(lsfDefaultRipple); + bool const noRipple = (receiverAccount->getFlags() & lsfDefaultRipple) == 0; return trustCreate( view, @@ -566,11 +564,12 @@ requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, // If this is a weak or legacy check, or if the account has a line, fail if // auth is required and not set on the line if (auto const issuerAccount = view.read(keylet::account(issue.account)); - issuerAccount && issuerAccount->isFlag(lsfRequireAuth)) + issuerAccount && (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u)) { if (trustLine) { - return trustLine->isFlag((account > issue.account) ? lsfLowAuth : lsfHighAuth) + return (((*trustLine)[sfFlags] & + ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) != 0u) ? tesSUCCESS : TER{tecNO_AUTH}; } @@ -699,7 +698,7 @@ removeEmptyHolding( auto const line = view.peek(keylet::line(accountID, issue)); if (!line) return accountIsIssuer ? (TER)tesSUCCESS : (TER)tecOBJECT_NOT_FOUND; - if (!accountIsIssuer && line->at(sfBalance)->iou() != beast::kZero) + if (!accountIsIssuer && line->at(sfBalance)->iou() != beast::kZERO) return tecHAS_OBLIGATIONS; // Adjust the owner count(s) @@ -738,7 +737,7 @@ removeEmptyHolding( TER deleteAMMTrustLine( ApplyView& view, - SLE::pointer sleState, + std::shared_ptr sleState, std::optional const& ammAccountID, beast::Journal j) { @@ -775,7 +774,7 @@ deleteAMMTrustLine( } auto const uFlags = !ammLow ? lsfLowReserve : lsfHighReserve; - if (!sleState->isFlag(uFlags)) + if ((sleState->getFlags() & uFlags) == 0u) return tecINTERNAL; // LCOV_EXCL_LINE adjustOwnerCount(view, !ammLow ? sleLow : sleHigh, -1, j); @@ -786,7 +785,7 @@ deleteAMMTrustLine( TER deleteAMMMPToken( ApplyView& view, - SLE::pointer sleMpt, + std::shared_ptr sleMpt, AccountID const& ammAccountID, beast::Journal j) { diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 6139498b69..4c11eceb54 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -28,7 +28,6 @@ #include #include -#include #include #include @@ -56,14 +55,6 @@ isGlobalFrozen(ReadView const& view, Asset const& asset) [&](MPTIssue const& issue) { return isGlobalFrozen(view, issue); }); } -TER -checkGlobalFrozen(ReadView const& view, Asset const& asset) -{ - if (isGlobalFrozen(view, asset)) - return asset.holds() ? tecLOCKED : tecFROZEN; - return tesSUCCESS; -} - bool isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { @@ -71,16 +62,8 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& [&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); } -TER -checkIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) -{ - if (isIndividualFrozen(view, account, asset)) - return asset.holds() ? tecLOCKED : tecFROZEN; - return tesSUCCESS; -} - bool -isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, std::uint8_t depth) +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) { return std::visit( [&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); @@ -124,7 +107,7 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, Asset const& asset, - std::uint8_t depth) + int depth) { return asset.visit( [&](Issue const& issue) { return isAnyFrozen(view, accounts, issue); }, @@ -132,11 +115,7 @@ isAnyFrozen( } bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - std::uint8_t depth) +isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) { // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive // funds, so checking "deep frozen" is the same as checking "frozen". @@ -144,7 +123,7 @@ isDeepFrozen( } bool -isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, std::uint8_t depth) +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) { return std::visit( [&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, @@ -278,7 +257,7 @@ accountHolds( { // If the account is the issuer, then their limit is effectively // infinite - return STAmount{Issue{currency, issuer}, STAmount::kMaxValue, STAmount::kMaxOffset}; + return STAmount{Issue{currency, issuer}, STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET}; } // IOU: Return balance on trust line modulo freeze @@ -522,19 +501,13 @@ requireAuth(ReadView const& view, Asset const& asset, AccountID const& account, } TER -canTransfer( - ReadView const& view, - Asset const& asset, - AccountID const& from, - AccountID const& to, - WaiveMPTCanTransfer waive, - std::uint8_t depth) +canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to) { - return asset.visit( - [&](MPTIssue const& issue) -> TER { - return canTransfer(view, issue, from, to, waive, depth); + return std::visit( + [&](TIss const& issue) -> TER { + return canTransfer(view, issue, from, to); }, - [&](Issue const& issue) -> TER { return canTransfer(view, issue, from, to); }); + asset.value()); } //------------------------------------------------------------------------------ @@ -597,41 +570,39 @@ directSendNoFeeIOU( << " amount=" << saAmount.getFullText() << " after=" << saBalance.getFullText(); + std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags)); bool bDelete = false; - auto const senderReserveFlag = bSenderHigh ? lsfHighReserve : lsfLowReserve; - auto const senderNoRippleFlag = bSenderHigh ? lsfHighNoRipple : lsfLowNoRipple; - auto const senderFreezeFlag = bSenderHigh ? lsfHighFreeze : lsfLowFreeze; - auto const receiverReserveFlag = bSenderHigh ? lsfLowReserve : lsfHighReserve; - // FIXME This NEEDS to be cleaned up and simplified. It's impossible // for anyone to understand. - if (saBefore > beast::kZero + if (saBefore > beast::kZERO // Sender balance was positive. - && saBalance <= beast::kZero + && saBalance <= beast::kZERO // Sender is zero or negative. - && sleRippleState->isFlag(senderReserveFlag) + && ((uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) != 0u) // Sender reserve is set. - && sleRippleState->isFlag(senderNoRippleFlag) != - view.read(keylet::account(uSenderID))->isFlag(lsfDefaultRipple) && - !sleRippleState->isFlag(senderFreezeFlag) && - !sleRippleState->getFieldAmount(bSenderHigh ? sfHighLimit : sfLowLimit) + && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + static_cast( + view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && + ((uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) == 0u) && + !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. - && (sleRippleState->getFieldU32(bSenderHigh ? sfHighQualityIn : sfLowQualityIn) == 0u) + && (sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) == 0u) // Sender quality in is 0. && - (sleRippleState->getFieldU32(bSenderHigh ? sfHighQualityOut : sfLowQualityOut) == 0u)) + (sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut) == 0u)) // Sender quality out is 0. { // Clear the reserve of the sender, possibly delete the line! adjustOwnerCount(view, view.peek(keylet::account(uSenderID)), -1, j); // Clear reserve flag. - sleRippleState->clearFlag(senderReserveFlag); + sleRippleState->setFieldU32( + sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); // Balance is zero, receiver reserve is clear. bDelete = !saBalance // Balance is zero. - && !sleRippleState->isFlag(receiverReserveFlag); + && ((uFlags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)) == 0u); // Receiver reserve is clear. } @@ -648,7 +619,7 @@ directSendNoFeeIOU( view, sleRippleState, bSenderHigh ? uReceiverID : uSenderID, - bSenderHigh ? uSenderID : uReceiverID, + !bSenderHigh ? uReceiverID : uSenderID, j); } @@ -670,7 +641,7 @@ directSendNoFeeIOU( if (!sleAccount) return tefINTERNAL; // LCOV_EXCL_LINE - bool const noRipple = !sleAccount->isFlag(lsfDefaultRipple); + bool const noRipple = (sleAccount->getFlags() & lsfDefaultRipple) == 0; return trustCreate( view, @@ -825,7 +796,7 @@ accountSendIOU( { if (view.rules().enabled(fixAMMv1_1)) { - if (saAmount < beast::kZero || saAmount.holds()) + if (saAmount < beast::kZERO || saAmount.holds()) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -834,7 +805,7 @@ accountSendIOU( { // LCOV_EXCL_START XRPL_ASSERT( - saAmount >= beast::kZero && !saAmount.holds(), + saAmount >= beast::kZERO && !saAmount.holds(), "xrpl::accountSendIOU : minimum amount and not MPT"); // LCOV_EXCL_STOP } @@ -863,9 +834,9 @@ accountSendIOU( TER terResult(tesSUCCESS); SLE::pointer const sender = - uSenderID != beast::kZero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); + uSenderID != beast::kZERO ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); SLE::pointer const receiver = - uReceiverID != beast::kZero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); + uReceiverID != beast::kZERO ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -959,7 +930,7 @@ accountSendMultiIOU( */ SLE::pointer const sender = - senderID != beast::kZero ? view.peek(keylet::account(senderID)) : SLE::pointer(); + senderID != beast::kZERO ? view.peek(keylet::account(senderID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -979,7 +950,7 @@ accountSendMultiIOU( auto const& receiverID = r.first; STAmount const amount{issue, r.second}; - if (amount < beast::kZero) + if (amount < beast::kZERO) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -991,7 +962,7 @@ accountSendMultiIOU( continue; SLE::pointer const receiver = - receiverID != beast::kZero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); + receiverID != beast::kZERO ? view.peek(keylet::account(receiverID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -1123,13 +1094,6 @@ directSendNoFeeMPT( auto const mptokenID = keylet::mptoken(mptID.key, uReceiverID); if (auto sle = view.peek(mptokenID)) { - if (view.rules().enabled(featureMPTokensV2)) - { - if ((*sle)[sfMPTAmount] > (std::numeric_limits::max() - amt)) - { - return tecINTERNAL; // LCOV_EXCL_LINE - } - } view.creditHookMPT(uSenderID, uReceiverID, saAmount, (*sle)[sfMPTAmount], available); (*sle)[sfMPTAmount] += amt; view.update(sle); @@ -1226,9 +1190,9 @@ directSendNoLimitMultiMPT( // Use uint64_t, not STAmount, to keep MaximumAmount comparisons in exact // integer arithmetic. STAmount implicitly converts to Number, whose // small-scale mantissa (~16 digits) can lose precision for values near - // kMaxMpTokenAmount (19 digits). + // maxMPTokenAmount (19 digits). std::uint64_t totalSendAmount{0}; - std::uint64_t const maximumAmount = sle->at(~sfMaximumAmount).value_or(kMaxMpTokenAmount); + std::uint64_t const maximumAmount = sle->at(~sfMaximumAmount).value_or(kMAX_MP_TOKEN_AMOUNT); std::uint64_t const outstandingAmount = sle->getFieldU64(sfOutstandingAmount); // actual accumulates the total cost to the sender (includes transfer @@ -1242,7 +1206,7 @@ directSendNoLimitMultiMPT( { STAmount const amount{mptIssue, amt}; - if (amount < beast::kZero) + if (amount < beast::kZERO) return tecINTERNAL; // LCOV_EXCL_LINE if (!amount || senderID == receiverID) @@ -1253,15 +1217,15 @@ directSendNoLimitMultiMPT( if (senderID == issuer) { XRPL_ASSERT_PARTS( - takeFromSender == beast::kZero, + takeFromSender == beast::kZERO, "xrpl::directSendNoLimitMultiMPT", "sender == issuer, takeFromSender == zero"); std::uint64_t const sendAmount = amount.mpt().value(); - if (view.rules().enabled(fixCleanup3_1_3)) + if (view.rules().enabled(fixSecurity3_1_3)) { - // Post-fixCleanup3_1_3: aggregate MaximumAmount + // Post-fixSecurity3_1_3: aggregate MaximumAmount // check. WARNING: the order of conditions is // critical — each guards the subtraction in the // next against unsigned underflow. Do not reorder. @@ -1279,7 +1243,7 @@ directSendNoLimitMultiMPT( } else { - // Pre-fixCleanup3_1_3: per-iteration MaximumAmount + // Pre-fixSecurity3_1_3: per-iteration MaximumAmount // check. Reads sfOutstandingAmount from a stale // view.read() snapshot — incorrect for multi-destination // sends but retained for ledger replay compatibility. @@ -1335,7 +1299,7 @@ accountSendMPT( AllowMPTOverflow allowOverflow) { XRPL_ASSERT( - saAmount >= beast::kZero && saAmount.holds(), + saAmount >= beast::kZERO && saAmount.holds(), "xrpl::accountSendMPT : minimum amount and MPT"); /* If we aren't sending anything or if the sender is the same as the @@ -1437,8 +1401,8 @@ transferXRP( STAmount const& amount, beast::Journal j) { - XRPL_ASSERT(from != beast::kZero, "xrpl::transferXRP : nonzero from account"); - XRPL_ASSERT(to != beast::kZero, "xrpl::transferXRP : nonzero to account"); + XRPL_ASSERT(from != beast::kZERO, "xrpl::transferXRP : nonzero from account"); + XRPL_ASSERT(to != beast::kZERO, "xrpl::transferXRP : nonzero to account"); XRPL_ASSERT(from != to, "xrpl::transferXRP : sender is not receiver"); XRPL_ASSERT(amount.native(), "xrpl::transferXRP : amount is XRP"); diff --git a/src/libxrpl/ledger/helpers/VaultHelpers.cpp b/src/libxrpl/ledger/helpers/VaultHelpers.cpp index 3a3a756499..8832e0078f 100644 --- a/src/libxrpl/ledger/helpers/VaultHelpers.cpp +++ b/src/libxrpl/ledger/helpers/VaultHelpers.cpp @@ -2,22 +2,21 @@ #include #include -#include -#include -#include -#include #include #include #include #include // IWYU pragma: keep -#include +#include #include namespace xrpl { [[nodiscard]] std::optional -assetsToSharesDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const& assets) +assetsToSharesDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets) { XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); XRPL_ASSERT( @@ -41,7 +40,10 @@ assetsToSharesDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount co } [[nodiscard]] std::optional -sharesToAssetsDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const& shares) +sharesToAssetsDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares) { XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); XRPL_ASSERT( @@ -65,11 +67,10 @@ sharesToAssetsDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount co [[nodiscard]] std::optional assetsToSharesWithdraw( - SLE::const_ref vault, - SLE::const_ref issuance, + std::shared_ptr const& vault, + std::shared_ptr const& issuance, STAmount const& assets, - TruncateShares truncate, - WaiveUnrealizedLoss waive) + TruncateShares truncate) { XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesWithdraw : non-negative assets"); XRPL_ASSERT( @@ -79,8 +80,7 @@ assetsToSharesWithdraw( return std::nullopt; // LCOV_EXCL_LINE Number assetTotal = vault->at(sfAssetsTotal); - if (waive == WaiveUnrealizedLoss::No) - assetTotal -= vault->at(sfLossUnrealized); + assetTotal -= vault->at(sfLossUnrealized); STAmount shares{vault->at(sfShareMPTID)}; if (assetTotal == 0) return shares; @@ -94,10 +94,9 @@ assetsToSharesWithdraw( [[nodiscard]] std::optional sharesToAssetsWithdraw( - SLE::const_ref vault, - SLE::const_ref issuance, - STAmount const& shares, - WaiveUnrealizedLoss waive) + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares) { XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsWithdraw : non-negative shares"); XRPL_ASSERT( @@ -107,8 +106,7 @@ sharesToAssetsWithdraw( return std::nullopt; // LCOV_EXCL_LINE Number assetTotal = vault->at(sfAssetsTotal); - if (waive == WaiveUnrealizedLoss::No) - assetTotal -= vault->at(sfLossUnrealized); + assetTotal -= vault->at(sfLossUnrealized); STAmount assets{vault->at(sfAsset)}; if (assetTotal == 0) return assets; @@ -117,24 +115,4 @@ sharesToAssetsWithdraw( return assets; } -[[nodiscard]] bool -isSoleShareholder(ReadView const& view, AccountID const& account, SLE::const_ref issuance) -{ - XRPL_ASSERT( - issuance && issuance->getType() == ltMPTOKEN_ISSUANCE, - "xrpl::isSoleShareholder : valid issuance SLE"); - - std::uint64_t const outstanding = issuance->at(sfOutstandingAmount); - if (outstanding == 0) - return false; - - auto const shareMPTID = - makeMptID(issuance->getFieldU32(sfSequence), issuance->getAccountID(sfIssuer)); - auto const sleToken = view.read(keylet::mptoken(shareMPTID, account)); - if (!sleToken) - return false; // LCOV_EXCL_LINE - - return sleToken->getFieldU64(sfMPTAmount) == outstanding; -} - } // namespace xrpl diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index 78ee5eb577..afdb264916 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -69,7 +69,7 @@ public: ioContext, gHttpClientSslContext->context()) // NOLINT(bugprone-unchecked-optional-access) , resolver_(ioContext) - , header_(kMaxClientHeaderBytes) + , header_(kMAX_CLIENT_HEADER_BYTES) , port_(port) , maxResponseSize_(maxResponseSize) , deadline_(ioContext) @@ -372,14 +372,14 @@ public: {std::istreambuf_iterator(&header_)}, std::istreambuf_iterator()}; JLOG(j_.trace()) << "Header: \"" << strHeader << "\""; - static boost::regex const kReStatus{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK - static boost::regex const kReSize{ + static boost::regex const kRE_STATUS{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK + static boost::regex const kRE_SIZE{ "\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; - static boost::regex const kReBody{"\\`.*\\r\\n\\r\\n(.*)\\'"}; + static boost::regex const kRE_BODY{"\\`.*\\r\\n\\r\\n(.*)\\'"}; boost::smatch smMatch; // Match status code. - if (!boost::regex_match(strHeader, smMatch, kReStatus)) + if (!boost::regex_match(strHeader, smMatch, kRE_STATUS)) { // XXX Use our own error code. JLOG(j_.trace()) << "No status code"; @@ -391,11 +391,11 @@ public: status_ = beast::lexicalCastThrow(std::string(smMatch[1])); - if (boost::regex_match(strHeader, smMatch, kReBody)) // we got some body + if (boost::regex_match(strHeader, smMatch, kRE_BODY)) // we got some body body_ = smMatch[1]; std::size_t const responseSize = [&] { - if (boost::regex_match(strHeader, smMatch, kReSize)) + if (boost::regex_match(strHeader, smMatch, kRE_SIZE)) return beast::lexicalCast(std::string(smMatch[1]), maxResponseSize_); return maxResponseSize_; }(); diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index e0a1fbf20c..28184bf174 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -16,7 +16,7 @@ namespace xrpl::NodeStore { BatchWriter::BatchWriter(Callback& callback, Scheduler& scheduler) : callback_(callback), scheduler_(scheduler) { - writeSet_.reserve(kBatchWritePreallocationSize); + writeSet_.reserve(BatchWritePreallocationSize); } BatchWriter::~BatchWriter() @@ -31,7 +31,7 @@ BatchWriter::store(std::shared_ptr const& object) // If the batch has reached its limit, we wait // until the batch writer is finished - while (writeSet_.size() >= kBatchWritePreallocationSize) + while (writeSet_.size() >= BatchWriteLimitSize) writeCondition_.wait(sl); writeSet_.push_back(object); @@ -65,7 +65,7 @@ BatchWriter::writeBatch() { std::vector> set; - set.reserve(kBatchWritePreallocationSize); + set.reserve(BatchWritePreallocationSize); { std::scoped_lock const sl(writeMutex_); diff --git a/src/libxrpl/nodestore/Database.cpp b/src/libxrpl/nodestore/Database.cpp index b584aca268..84941d98aa 100644 --- a/src/libxrpl/nodestore/Database.cpp +++ b/src/libxrpl/nodestore/Database.cpp @@ -38,7 +38,7 @@ Database::Database( beast::Journal journal) : j_(journal) , scheduler_(scheduler) - , earliestLedgerSeq_(get(config, "earliest_seq", kXrpLedgerEarliestSeq)) + , earliestLedgerSeq_(get(config, "earliest_seq", kXRP_LEDGER_EARLIEST_SEQ)) , requestBundle_(get(config, "rq_bundle", 4)) , readThreads_(std::max(1, readThreads)) { @@ -192,7 +192,7 @@ void Database::importInternal(Backend& dstBackend, Database& srcDB) { Batch batch; - batch.reserve(kBatchWritePreallocationSize); + batch.reserve(BatchWritePreallocationSize); auto storeBatch = [&, fname = __func__]() { try { @@ -217,7 +217,7 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) return; batch.emplace_back(std::move(nodeObject)); - if (batch.size() >= kBatchWritePreallocationSize) + if (batch.size() >= BatchWritePreallocationSize) storeBatch(); }); diff --git a/src/libxrpl/nodestore/DatabaseNodeImp.cpp b/src/libxrpl/nodestore/DatabaseNodeImp.cpp index 9323d69131..ef84862de6 100644 --- a/src/libxrpl/nodestore/DatabaseNodeImp.cpp +++ b/src/libxrpl/nodestore/DatabaseNodeImp.cpp @@ -4,16 +4,21 @@ #include #include #include +#include +#include #include #include #include #include +#include +#include #include #include #include #include #include +#include namespace xrpl::NodeStore { @@ -24,13 +29,6 @@ DatabaseNodeImp::store(NodeObjectType type, Blob&& data, uint256 const& hash, st 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() == NodeObjectType::Dummy; - }); - } } void @@ -39,25 +37,9 @@ DatabaseNodeImp::asyncFetch( std::uint32_t ledgerSeq, std::function const&)>&& callback) { - if (cache_) - { - std::shared_ptr const obj = cache_->fetch(hash); - if (obj) - { - callback(obj->getType() == NodeObjectType::Dummy ? 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, @@ -65,58 +47,32 @@ DatabaseNodeImp::fetchNodeObject( FetchReport& fetchReport, bool duplicate) { - std::shared_ptr nodeObject = cache_ ? cache_->fetch(hash) : nullptr; - if (!nodeObject) + std::shared_ptr nodeObject = nullptr; + Status status = Status::Ok; + + try { - JLOG(j_.trace()) << "fetchNodeObject " << hash << ": record not " - << (cache_ ? "cached" : "found"); - - Status status = Status::Ok; - try - { - status = backend_->fetch(hash, &nodeObject); - } - catch (std::exception const& e) - { - JLOG(j_.fatal()) << "fetchNodeObject " << hash - << ": Exception fetching from backend: " << e.what(); - rethrow(); - } - - switch (status) - { - case Status::Ok: - if (cache_) - { - if (nodeObject) - { - cache_->canonicalizeReplaceClient(hash, nodeObject); - } - else - { - auto notFound = NodeObject::createObject(NodeObjectType::Dummy, {}, hash); - cache_->canonicalizeReplaceClient(hash, notFound); - if (notFound->getType() != NodeObjectType::Dummy) - nodeObject = notFound; - } - } - break; - case Status::NotFound: - break; - case Status::DataCorrupt: - JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted"; - break; - default: - JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " - << static_cast(status); - break; - } + status = backend_->fetch(hash, &nodeObject); } - else + catch (std::exception const& e) { - JLOG(j_.trace()) << "fetchNodeObject " << hash << ": record found in cache"; - if (nodeObject->getType() == NodeObjectType::Dummy) - nodeObject.reset(); + JLOG(j_.fatal()) << "fetchNodeObject " << hash + << ": Exception fetching from backend: " << e.what(); + rethrow(); + } + + switch (status) + { + case Status::Ok: + case Status::NotFound: + break; + case Status::DataCorrupt: + JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted"; + break; + default: + JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " + << static_cast(status); + break; } if (nodeObject) @@ -125,4 +81,33 @@ DatabaseNodeImp::fetchNodeObject( return nodeObject; } +std::vector> +DatabaseNodeImp::fetchBatch(std::vector const& hashes) +{ + using namespace std::chrono; + auto const before = steady_clock::now(); + + // 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(hashes).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) + { + if (!results[i]) + { + JLOG(j_.error()) << "fetchBatch - " + << "record not found in db. hash = " << strHex(hashes[i]); + } + } + + auto fetchDurationUs = + std::chrono::duration_cast(steady_clock::now() - before).count(); + updateFetchMetrics(hashes.size(), 0, fetchDurationUs); + return results; +} + } // namespace xrpl::NodeStore diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index 1de6a83b4c..24b0e2de2e 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -113,12 +113,6 @@ DatabaseRotatingImp::store(NodeObjectType type, Blob&& data, uint256 const& hash storeStats(1, nObj->getData().size()); } -void -DatabaseRotatingImp::sweep() -{ - // Nothing to do. -} - std::shared_ptr DatabaseRotatingImp::fetchNodeObject( uint256 const& hash, diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index 5cefbfd357..0cfda7d86a 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -26,8 +26,8 @@ namespace xrpl::NodeStore { ManagerImp& ManagerImp::instance() { - static ManagerImp kInst; - return kInst; + static ManagerImp k_; + return k_; } void @@ -77,7 +77,7 @@ ManagerImp::makeBackend( } return factory->createInstance( - NodeObject::kKeyBytes, parameters, burstSize, scheduler, journal); + NodeObject::kKEY_BYTES, parameters, burstSize, scheduler, journal); } std::unique_ptr diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 5bdf8e65b5..13c82696cb 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -22,6 +22,7 @@ #include #include #include +#include namespace xrpl::NodeStore { @@ -73,8 +74,8 @@ MemoryFactory* gMemoryFactory = nullptr; void registerMemoryFactory(Manager& manager) { - static MemoryFactory kInstance{manager}; - gMemoryFactory = &kInstance; + static MemoryFactory kINSTANCE{manager}; + gMemoryFactory = &kINSTANCE; } //------------------------------------------------------------------------------ @@ -145,6 +146,28 @@ public: return Status::Ok; } + std::pair>, Status> + fetchBatch(std::vector const& hashes) override + { + std::vector> results; + results.reserve(hashes.size()); + for (auto const& h : hashes) + { + std::shared_ptr nObj; + Status const status = fetch(h, &nObj); + if (status != Status::Ok) + { + results.push_back({}); + } + else + { + results.push_back(nObj); + } + } + + return {results, Status::Ok}; + } + void store(std::shared_ptr const& object) override { diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index abf09e871d..db9dbcbec1 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -42,6 +42,7 @@ #include #include #include +#include namespace xrpl::NodeStore { @@ -52,7 +53,7 @@ public: // NuDB database. We used it to identify shard databases before that code // was removed. For now, its only use is a sanity check that the database // was created by xrpld. - static constexpr std::uint64_t kAppNum = 1; + static constexpr std::uint64_t kAPPNUM = 1; beast::Journal const j; size_t const keyBytes; @@ -160,7 +161,7 @@ public: if (ec) Throw(ec); - if (db.appnum() != kAppNum) + if (db.appnum() != kAPPNUM) Throw("nodestore: unknown appnum"); db.set_burst(burstSize); } @@ -174,7 +175,7 @@ public: void open(bool createIfMissing) override { - open(createIfMissing, kAppNum, nudb::make_uid(), nudb::make_salt()); + open(createIfMissing, kAPPNUM, nudb::make_uid(), nudb::make_salt()); } void @@ -231,6 +232,28 @@ public: return status; } + std::pair>, Status> + fetchBatch(std::vector const& hashes) override + { + std::vector> results; + results.reserve(hashes.size()); + for (auto const& h : hashes) + { + std::shared_ptr nObj; + Status const status = fetch(h, &nObj); + if (status != Status::Ok) + { + results.push_back({}); + } + else + { + results.push_back(nObj); + } + } + + return {results, Status::Ok}; + } + void doInsert(std::shared_ptr const& no) { @@ -437,7 +460,7 @@ public: void registerNuDBFactory(Manager& manager) { - static NuDBFactory const kInstance{manager}; + static NuDBFactory const kINSTANCE{manager}; } } // namespace xrpl::NodeStore diff --git a/src/libxrpl/nodestore/backend/NullFactory.cpp b/src/libxrpl/nodestore/backend/NullFactory.cpp index 36b8139984..38f35e91ff 100644 --- a/src/libxrpl/nodestore/backend/NullFactory.cpp +++ b/src/libxrpl/nodestore/backend/NullFactory.cpp @@ -12,6 +12,8 @@ #include #include #include +#include +#include namespace xrpl::NodeStore { @@ -50,6 +52,12 @@ public: return Status::NotFound; } + std::pair>, Status> + fetchBatch(std::vector const& hashes) override + { + return {}; + } + void store(std::shared_ptr const& object) override { @@ -120,7 +128,7 @@ public: void registerNullFactory(Manager& manager) { - static NullFactory const kInstance{manager}; + static NullFactory const kINSTANCE{manager}; } } // namespace xrpl::NodeStore diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index d2c193888c..7f5ac6b14e 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -29,6 +29,8 @@ #include #include #include +#include +#include #if XRPL_ROCKSDB_AVAILABLE #include @@ -328,6 +330,28 @@ public: return status; } + std::pair>, Status> + fetchBatch(std::vector const& hashes) override + { + std::vector> results; + results.reserve(hashes.size()); + for (auto const& h : hashes) + { + std::shared_ptr nObj; + Status const status = fetch(h, &nObj); + if (status != Status::Ok) + { + results.push_back({}); + } + else + { + results.push_back(nObj); + } + } + + return {results, Status::Ok}; + } + void store(std::shared_ptr const& object) override { @@ -462,7 +486,7 @@ public: void registerRocksDBFactory(Manager& manager) { - static RocksDBFactory const kInstance{manager}; + static RocksDBFactory const kINSTANCE{manager}; } } // namespace xrpl::NodeStore diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index eccb581c6d..b4c44f0f36 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -29,7 +29,7 @@ Currency ammLPTCurrency(Asset const& asset1, Asset const& asset2) { // AMM LPToken is 0x03 plus 19 bytes of the hash - static constexpr std::int32_t kAmmCurrencyCode = 0x03; + std::int32_t constexpr kAMM_CURRENCY_CODE = 0x03; auto const& [minA, maxA] = std::minmax(asset1, asset2); uint256 const hash = std::visit( [](auto&& issue1, auto&& issue2) { @@ -44,7 +44,7 @@ ammLPTCurrency(Asset const& asset1, Asset const& asset2) minA.value(), maxA.value()); Currency currency; - *currency.begin() = kAmmCurrencyCode; + *currency.begin() = kAMM_CURRENCY_CODE; std::copy(hash.begin(), hash.begin() + currency.size() - 1, currency.begin() + 1); return currency; } @@ -60,7 +60,7 @@ invalidAMMAsset(Asset const& asset, std::optional> const { auto const err = asset.visit( [](MPTIssue const& issue) -> std::optional { - if (issue.getIssuer() == beast::kZero) + if (issue.getIssuer() == beast::kZERO) return temBAD_MPT; return std::nullopt; }, @@ -101,7 +101,7 @@ invalidAMMAmount( { if (auto const res = invalidAMMAsset(amount.asset(), pair)) return res; - if (amount < beast::kZero || (!validZero && amount == beast::kZero)) + if (amount < beast::kZERO || (!validZero && amount == beast::kZERO)) return temBAD_AMOUNT; return tesSUCCESS; } @@ -112,13 +112,14 @@ 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 >= kTotalTimeSlotSecs, "xrpl::ammAuctionTimeSlot : minimum expiration"); - if (expiration >= kTotalTimeSlotSecs) + XRPL_ASSERT( + expiration >= kTOTAL_TIME_SLOT_SECS, "xrpl::ammAuctionTimeSlot : minimum expiration"); + if (expiration >= kTOTAL_TIME_SLOT_SECS) { - if (auto const start = expiration - kTotalTimeSlotSecs; current >= start) + if (auto const start = expiration - kTOTAL_TIME_SLOT_SECS; current >= start) { - if (auto const diff = current - start; diff < kTotalTimeSlotSecs) - return diff / kAuctionSlotIntervalDuration; + if (auto const diff = current - start; diff < kTOTAL_TIME_SLOT_SECS) + return diff / kAUCTION_SLOT_INTERVAL_DURATION; } } return std::nullopt; diff --git a/src/libxrpl/protocol/AccountID.cpp b/src/libxrpl/protocol/AccountID.cpp index 6050144a8e..6639835b41 100644 --- a/src/libxrpl/protocol/AccountID.cpp +++ b/src/libxrpl/protocol/AccountID.cpp @@ -103,9 +103,9 @@ std::optional parseBase58(std::string const& s) { auto const result = decodeBase58Token(s, TokenType::AccountID); - if (result.size() != AccountID::kBytes) + if (result.size() != AccountID::kBYTES) return std::nullopt; - return AccountID::fromRaw(result); + return AccountID{result}; } //------------------------------------------------------------------------------ @@ -146,25 +146,25 @@ parseBase58(std::string const& s) AccountID calcAccountID(PublicKey const& pk) { - static_assert(AccountID::kBytes == sizeof(RipeshaHasher::result_type)); + static_assert(AccountID::kBYTES == sizeof(RipeshaHasher::result_type)); RipeshaHasher rsh; rsh(pk.data(), pk.size()); - return AccountID::fromRaw(static_cast(rsh)); + return AccountID{static_cast(rsh)}; } AccountID const& xrpAccount() { - static AccountID const kAccount(beast::kZero); - return kAccount; + static AccountID const kACCOUNT(beast::kZERO); + return kACCOUNT; } AccountID const& noAccount() { - static AccountID const kAccount(1); - return kAccount; + static AccountID const kACCOUNT(1); + return kACCOUNT; } bool diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index 7de1862dfc..7ea934fe3a 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0-rc3" +char const* const versionString = "3.2.0-b0" // clang-format on ; @@ -67,7 +67,7 @@ buildVersionString() std::string const& getVersionString() { - static std::string const kValue = [] { + static std::string const kVALUE = [] { std::string const s = buildVersionString(); beast::SemanticVersion v; @@ -75,23 +75,23 @@ getVersionString() logicError(s + ": Bad server version string"); return s; }(); - return kValue; + return kVALUE; } std::string const& getFullVersionString() { - static std::string const kValue = systemName() + "-" + getVersionString(); - return kValue; + static std::string const kVALUE = systemName() + "-" + getVersionString(); + return kVALUE; } -static constexpr std::uint64_t kImplementationVersionIdentifier = 0x183B'0000'0000'0000LLU; -static constexpr std::uint64_t kImplementationVersionIdentifierMask = 0xFFFF'0000'0000'0000LLU; +static constexpr std::uint64_t kIMPLEMENTATION_VERSION_IDENTIFIER = 0x183B'0000'0000'0000LLU; +static constexpr std::uint64_t kIMPLEMENTATION_VERSION_IDENTIFIER_MASK = 0xFFFF'0000'0000'0000LLU; std::uint64_t encodeSoftwareVersion(std::string_view versionStr) { - std::uint64_t c = kImplementationVersionIdentifier; + std::uint64_t c = kIMPLEMENTATION_VERSION_IDENTIFIER; beast::SemanticVersion v; @@ -155,14 +155,15 @@ encodeSoftwareVersion(std::string_view versionStr) std::uint64_t getEncodedVersion() { - static std::uint64_t const kCookie = {encodeSoftwareVersion(getVersionString())}; - return kCookie; + static std::uint64_t const kCOOKIE = {encodeSoftwareVersion(getVersionString())}; + return kCOOKIE; } bool isXrpldVersion(std::uint64_t version) { - return (version & kImplementationVersionIdentifierMask) == kImplementationVersionIdentifier; + return (version & kIMPLEMENTATION_VERSION_IDENTIFIER_MASK) == + kIMPLEMENTATION_VERSION_IDENTIFIER; } bool diff --git a/src/libxrpl/protocol/ConfidentialTransfer.cpp b/src/libxrpl/protocol/ConfidentialTransfer.cpp index e37aa67d64..dc49d4a934 100644 --- a/src/libxrpl/protocol/ConfidentialTransfer.cpp +++ b/src/libxrpl/protocol/ConfidentialTransfer.cpp @@ -115,15 +115,15 @@ getConvertBackContextHash( std::optional makeEcPair(Slice const& buffer) { - if (buffer.length() != 2 * kEcGamalEncryptedLength) + if (buffer.length() != 2 * kEC_GAMAL_ENCRYPTED_LENGTH) return std::nullopt; // LCOV_EXCL_LINE auto parsePubKey = [](Slice const& slice, secp256k1_pubkey& out) { return secp256k1_ec_pubkey_parse(secp256k1Context(), &out, slice.data(), slice.length()); }; - Slice const s1{buffer.data(), kEcGamalEncryptedLength}; - Slice const s2{buffer.data() + kEcGamalEncryptedLength, kEcGamalEncryptedLength}; + Slice const s1{buffer.data(), kEC_GAMAL_ENCRYPTED_LENGTH}; + Slice const s2{buffer.data() + kEC_GAMAL_ENCRYPTED_LENGTH, kEC_GAMAL_ENCRYPTED_LENGTH}; EcPair pair{}; if (parsePubKey(s1, pair.c1) != 1 || parsePubKey(s2, pair.c2) != 1) @@ -136,16 +136,16 @@ std::optional serializeEcPair(EcPair const& pair) { auto serializePubKey = [](secp256k1_pubkey const& pub, unsigned char* out) { - size_t outLen = kEcGamalEncryptedLength; // 33 bytes + size_t outLen = kEC_GAMAL_ENCRYPTED_LENGTH; // 33 bytes auto const ret = secp256k1_ec_pubkey_serialize( secp256k1Context(), out, &outLen, &pub, SECP256K1_EC_COMPRESSED); - return ret == 1 && outLen == kEcGamalEncryptedLength; + return ret == 1 && outLen == kEC_GAMAL_ENCRYPTED_LENGTH; }; - Buffer buffer(kEcGamalEncryptedTotalLength); + Buffer buffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); auto const ptr = buffer.data(); bool const res1 = serializePubKey(pair.c1, ptr); - bool const res2 = serializePubKey(pair.c2, ptr + kEcGamalEncryptedLength); + bool const res2 = serializePubKey(pair.c2, ptr + kEC_GAMAL_ENCRYPTED_LENGTH); if (!res1 || !res2) return std::nullopt; @@ -162,11 +162,11 @@ isValidCiphertext(Slice const& buffer) bool isValidCompressedECPoint(Slice const& buffer) { - if (buffer.size() != kCompressedEcPointLength) + if (buffer.size() != kCOMPRESSED_EC_POINT_LENGTH) return false; // Compressed EC points must start with 0x02 or 0x03 - if (buffer[0] != kEcCompressedPrefixEvenY && buffer[0] != kEcCompressedPrefixOddY) + if (buffer[0] != kEC_COMPRESSED_PREFIX_EVEN_Y && buffer[0] != kEC_COMPRESSED_PREFIX_ODD_Y) return false; secp256k1_pubkey point; @@ -176,7 +176,8 @@ isValidCompressedECPoint(Slice const& buffer) std::optional homomorphicAdd(Slice const& a, Slice const& b) { - if (a.length() != kEcGamalEncryptedTotalLength || b.length() != kEcGamalEncryptedTotalLength) + if (a.length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + b.length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return std::nullopt; auto const pairA = makeEcPair(a); @@ -199,7 +200,8 @@ homomorphicAdd(Slice const& a, Slice const& b) std::optional homomorphicSubtract(Slice const& a, Slice const& b) { - if (a.length() != kEcGamalEncryptedTotalLength || b.length() != kEcGamalEncryptedTotalLength) + if (a.length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + b.length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return std::nullopt; auto const pairA = makeEcPair(a); @@ -222,22 +224,23 @@ homomorphicSubtract(Slice const& a, Slice const& b) Buffer generateBlindingFactor() { - unsigned char blindingFactor[kEcBlindingFactorLength]; + unsigned char blindingFactor[kEC_BLINDING_FACTOR_LENGTH]; // todo: might need to be updated using another RNG - if (RAND_bytes(blindingFactor, kEcBlindingFactorLength) != 1) + if (RAND_bytes(blindingFactor, kEC_BLINDING_FACTOR_LENGTH) != 1) Throw("Failed to generate random number"); - return Buffer(blindingFactor, kEcBlindingFactorLength); + return Buffer(blindingFactor, kEC_BLINDING_FACTOR_LENGTH); } std::optional encryptAmount(uint64_t const amt, Slice const& pubKeySlice, Slice const& blindingFactor) { - if (blindingFactor.size() != kEcBlindingFactorLength || pubKeySlice.size() != kEcPubKeyLength) + if (blindingFactor.size() != kEC_BLINDING_FACTOR_LENGTH || + pubKeySlice.size() != kEC_PUB_KEY_LENGTH) return std::nullopt; - Buffer out(kEcGamalEncryptedTotalLength); + Buffer out(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); if (mpt_encrypt_amount(amt, pubKeySlice.data(), blindingFactor.data(), out.data()) != 0) return std::nullopt; @@ -247,13 +250,13 @@ encryptAmount(uint64_t const amt, Slice const& pubKeySlice, Slice const& blindin std::optional encryptCanonicalZeroAmount(Slice const& pubKeySlice, AccountID const& account, MPTID const& mptId) { - if (pubKeySlice.size() != kEcPubKeyLength) + if (pubKeySlice.size() != kEC_PUB_KEY_LENGTH) return std::nullopt; // LCOV_EXCL_LINE EcPair pair{}; secp256k1_pubkey pubKey; if (auto res = secp256k1_ec_pubkey_parse( - secp256k1Context(), &pubKey, pubKeySlice.data(), kEcPubKeyLength); + secp256k1Context(), &pubKey, pubKeySlice.data(), kEC_PUB_KEY_LENGTH); res != 1) { return std::nullopt; // LCOV_EXCL_LINE @@ -277,11 +280,11 @@ verifyRevealedAmount( ConfidentialRecipient const& issuer, std::optional const& auditor) { - if (blindingFactor.size() != kEcBlindingFactorLength || - holder.publicKey.size() != kEcPubKeyLength || - holder.encryptedAmount.size() != kEcGamalEncryptedTotalLength || - issuer.publicKey.size() != kEcPubKeyLength || - issuer.encryptedAmount.size() != kEcGamalEncryptedTotalLength) + if (blindingFactor.size() != kEC_BLINDING_FACTOR_LENGTH || + holder.publicKey.size() != kEC_PUB_KEY_LENGTH || + holder.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + issuer.publicKey.size() != kEC_PUB_KEY_LENGTH || + issuer.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -299,8 +302,8 @@ verifyRevealedAmount( mpt_confidential_participant const* auditorPtr = nullptr; if (auditor) { - if (auditor->publicKey.size() != kEcPubKeyLength || - auditor->encryptedAmount.size() != kEcGamalEncryptedTotalLength) + if (auditor->publicKey.size() != kEC_PUB_KEY_LENGTH || + auditor->encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -329,14 +332,14 @@ checkEncryptedAmountFormat(STObject const& object) return temMALFORMED; // LCOV_EXCL_LINE } - if (object[sfHolderEncryptedAmount].length() != kEcGamalEncryptedTotalLength || - object[sfIssuerEncryptedAmount].length() != kEcGamalEncryptedTotalLength) + if (object[sfHolderEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + object[sfIssuerEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) { return temBAD_CIPHERTEXT; } bool const hasAuditor = object.isFieldPresent(sfAuditorEncryptedAmount); - if (hasAuditor && object[sfAuditorEncryptedAmount].length() != kEcGamalEncryptedTotalLength) + if (hasAuditor && object[sfAuditorEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return temBAD_CIPHERTEXT; if (!isValidCiphertext(object[sfHolderEncryptedAmount]) || @@ -354,7 +357,7 @@ checkEncryptedAmountFormat(STObject const& object) TER verifySchnorrProof(Slice const& pubKeySlice, Slice const& proofSlice, uint256 const& contextHash) { - if (proofSlice.size() != kEcSchnorrProofLength || pubKeySlice.size() != kEcPubKeyLength) + if (proofSlice.size() != kEC_SCHNORR_PROOF_LENGTH || pubKeySlice.size() != kEC_PUB_KEY_LENGTH) return tecINTERNAL; // LCOV_EXCL_LINE if (mpt_verify_convert_proof(proofSlice.data(), pubKeySlice.data(), contextHash.data()) != 0) @@ -371,8 +374,8 @@ verifyClawbackProof( Slice const& ciphertext, uint256 const& contextHash) { - if (ciphertext.size() != kEcGamalEncryptedTotalLength || - pubKeySlice.size() != kEcPubKeyLength || proof.size() != kEcClawbackProofLength) + if (ciphertext.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + pubKeySlice.size() != kEC_PUB_KEY_LENGTH || proof.size() != kEC_CLAWBACK_PROOF_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -399,15 +402,15 @@ verifySendProof( uint256 const& contextHash) { auto const recipientCount = getConfidentialRecipientCount(auditor.has_value()); - if (proof.size() != kEcSendProofLength || sender.publicKey.size() != kEcPubKeyLength || - sender.encryptedAmount.size() != kEcGamalEncryptedTotalLength || - destination.publicKey.size() != kEcPubKeyLength || - destination.encryptedAmount.size() != kEcGamalEncryptedTotalLength || - issuer.publicKey.size() != kEcPubKeyLength || - issuer.encryptedAmount.size() != kEcGamalEncryptedTotalLength || - spendingBalance.size() != kEcGamalEncryptedTotalLength || - amountCommitment.size() != kEcPedersenCommitmentLength || - balanceCommitment.size() != kEcPedersenCommitmentLength) + if (proof.size() != kEC_SEND_PROOF_LENGTH || sender.publicKey.size() != kEC_PUB_KEY_LENGTH || + sender.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + destination.publicKey.size() != kEC_PUB_KEY_LENGTH || + destination.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + issuer.publicKey.size() != kEC_PUB_KEY_LENGTH || + issuer.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + spendingBalance.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + amountCommitment.size() != kEC_PEDERSEN_COMMITMENT_LENGTH || + balanceCommitment.size() != kEC_PEDERSEN_COMMITMENT_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -425,8 +428,8 @@ verifySendProof( participants[2] = makeParticipant(issuer); if (auditor) { - if (auditor->publicKey.size() != kEcPubKeyLength || - auditor->encryptedAmount.size() != kEcGamalEncryptedTotalLength) + if (auditor->publicKey.size() != kEC_PUB_KEY_LENGTH || + auditor->encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } @@ -457,9 +460,9 @@ verifyConvertBackProof( uint64_t amount, uint256 const& contextHash) { - if (proof.size() != kEcConvertBackProofLength || pubKeySlice.size() != kEcPubKeyLength || - spendingBalance.size() != kEcGamalEncryptedTotalLength || - balanceCommitment.size() != kEcPedersenCommitmentLength) + if (proof.size() != kEC_CONVERT_BACK_PROOF_LENGTH || pubKeySlice.size() != kEC_PUB_KEY_LENGTH || + spendingBalance.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + balanceCommitment.size() != kEC_PEDERSEN_COMMITMENT_LENGTH) { return tecINTERNAL; // LCOV_EXCL_LINE } diff --git a/src/libxrpl/protocol/ErrorCodes.cpp b/src/libxrpl/protocol/ErrorCodes.cpp index 87761ce13e..a51bb9b56d 100644 --- a/src/libxrpl/protocol/ErrorCodes.cpp +++ b/src/libxrpl/protocol/ErrorCodes.cpp @@ -30,7 +30,7 @@ namespace detail { // status code. // clang-format off -static constexpr ErrorInfo kUnorderedErrorInfos[]{ +constexpr static ErrorInfo kUNORDERED_ERROR_INFOS[]{ {RpcActMalformed, "actMalformed", "Account malformed."}, {RpcActNotFound, "actNotFound", "Account not found."}, {RpcAlreadyMultisig, "alreadyMultisig", "Already multisigned."}, @@ -153,9 +153,9 @@ sortErrorInfos(ErrorInfo const (&unordered)[N]) -> std::array return ret; } -constexpr auto kSortedErrorInfos{sortErrorInfos(kUnorderedErrorInfos)}; +constexpr auto kSORTED_ERROR_INFOS{sortErrorInfos(kUNORDERED_ERROR_INFOS)}; -constexpr ErrorInfo kUnknownError; +constexpr ErrorInfo kUNKNOWN_ERROR; } // namespace detail @@ -183,8 +183,8 @@ ErrorInfo const& getErrorInfo(ErrorCodeI code) { if (code <= RpcSuccess || code > RpcLast) - return detail::kUnknownError; - return detail::kSortedErrorInfos[code - 1]; + return detail::kUNKNOWN_ERROR; + return detail::kSORTED_ERROR_INFOS[code - 1]; } json::Value @@ -212,7 +212,7 @@ containsError(json::Value const& json) int errorCodeHttpStatus(ErrorCodeI code) { - return getErrorInfo(code).httpStatus; + return getErrorInfo(code).http_status; } } // namespace RPC diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index 059abe2996..3862b52e27 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -202,7 +202,7 @@ public: FeatureCollections::FeatureCollections() { - features_.reserve(xrpl::detail::kNumFeatures); + features_.reserve(xrpl::detail::kNUM_FEATURES); } std::optional @@ -233,7 +233,7 @@ FeatureCollections::registerFeature(std::string const& name, Supported support, Feature const* i = getByName(name); if (i == nullptr) { - check(features_.size() < detail::kNumFeatures, "More features defined than allocated."); + check(features_.size() < detail::kNUM_FEATURES, "More features defined than allocated."); auto const f = sha512Half(Slice(name.data(), name.size())); @@ -446,6 +446,6 @@ enforceValidFeatureName(auto fn) -> char const* // are initialized from top to bottom. // // Use initialization of one final static variable to set featureCollections::readOnly_. -[[maybe_unused]] static bool const kReadOnlySet = gFeatureCollections.registrationIsDone(); +[[maybe_unused]] static bool const kREAD_ONLY_SET = gFeatureCollections.registrationIsDone(); } // namespace xrpl diff --git a/src/libxrpl/protocol/IOUAmount.cpp b/src/libxrpl/protocol/IOUAmount.cpp index d214995809..e4326d611e 100644 --- a/src/libxrpl/protocol/IOUAmount.cpp +++ b/src/libxrpl/protocol/IOUAmount.cpp @@ -43,11 +43,11 @@ setSTNumberSwitchover(bool v) /* The range for the mantissa when normalized */ // log(2^63,10) ~ 18.96 // -static constexpr std::int64_t kMinMantissa = STAmount::kMinValue; -static constexpr std::int64_t kMaxMantissa = STAmount::kMaxValue; +static std::int64_t constexpr kMIN_MANTISSA = STAmount::kMIN_VALUE; +static std::int64_t constexpr kMAX_MANTISSA = STAmount::kMAX_VALUE; /* The range for the exponent when normalized */ -static constexpr int kMinExponent = STAmount::kMinOffset; -static constexpr int kMaxExponent = STAmount::kMaxOffset; +static int constexpr kMIN_EXPONENT = STAmount::kMIN_OFFSET; +static int constexpr kMAX_EXPONENT = STAmount::kMAX_OFFSET; IOUAmount IOUAmount::fromNumber(Number const& number) @@ -56,14 +56,14 @@ IOUAmount::fromNumber(Number const& number) // to normalize, which calls fromNumber IOUAmount result{}; std::tie(result.mantissa_, result.exponent_) = - number.normalizeToRange(); + number.normalizeToRange(kMIN_MANTISSA, kMAX_MANTISSA); return result; } IOUAmount IOUAmount::minPositiveAmount() { - return IOUAmount(kMinMantissa, kMinExponent); + return IOUAmount(kMIN_MANTISSA, kMIN_EXPONENT); } void @@ -71,7 +71,7 @@ IOUAmount::normalize() { if (mantissa_ == 0) { - *this = beast::kZero; + *this = beast::kZERO; return; } @@ -79,10 +79,10 @@ IOUAmount::normalize() { Number const v{mantissa_, exponent_}; *this = fromNumber(v); - if (exponent_ > kMaxExponent) + if (exponent_ > kMAX_EXPONENT) Throw("value overflow"); - if (exponent_ < kMinExponent) - *this = beast::kZero; + if (exponent_ < kMIN_EXPONENT) + *this = beast::kZERO; return; } @@ -91,28 +91,28 @@ IOUAmount::normalize() if (negative) mantissa_ = -mantissa_; - while ((mantissa_ < kMinMantissa) && (exponent_ > kMinExponent)) + while ((mantissa_ < kMIN_MANTISSA) && (exponent_ > kMIN_EXPONENT)) { mantissa_ *= 10; --exponent_; } - while (mantissa_ > kMaxMantissa) + while (mantissa_ > kMAX_MANTISSA) { - if (exponent_ >= kMaxExponent) + if (exponent_ >= kMAX_EXPONENT) Throw("IOUAmount::normalize"); mantissa_ /= 10; ++exponent_; } - if ((exponent_ < kMinExponent) || (mantissa_ < kMinMantissa)) + if ((exponent_ < kMIN_EXPONENT) || (mantissa_ < kMIN_MANTISSA)) { - *this = beast::kZero; + *this = beast::kZERO; return; } - if (exponent_ > kMaxExponent) + if (exponent_ > kMAX_EXPONENT) Throw("value overflow"); if (negative) @@ -121,19 +121,19 @@ IOUAmount::normalize() IOUAmount::IOUAmount(Number const& other) : IOUAmount(fromNumber(other)) { - if (exponent_ > kMaxExponent) + if (exponent_ > kMAX_EXPONENT) Throw("value overflow"); - if (exponent_ < kMinExponent) - *this = beast::kZero; + if (exponent_ < kMIN_EXPONENT) + *this = beast::kZERO; } IOUAmount& IOUAmount::operator+=(IOUAmount const& other) { - if (other == beast::kZero) + if (other == beast::kZERO) return *this; - if (*this == beast::kZero) + if (*this == beast::kZERO) { *this = other; return *this; @@ -165,7 +165,7 @@ IOUAmount::operator+=(IOUAmount const& other) if (mantissa_ >= -10 && mantissa_ <= 10) { - *this = beast::kZero; + *this = beast::kZERO; return *this; } @@ -190,7 +190,7 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU // A vector with the value 10^index for indexes from 0 to 29 // The largest intermediate value we expect is 2^96, which // is less than 10^29 - static auto const kPowerTable = [] { + static auto const kPOWER_TABLE = [] { std::vector result; result.reserve(30); // 2^96 is largest intermediate result size uint128_t cur(1); @@ -204,11 +204,11 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU // Return floor(log10(v)) // Note: Returns -1 for v == 0 - static auto kLoG10Floor = [](uint128_t const& v) { + static auto kLOG10_FLOOR = [](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::ranges::lower_bound(kPowerTable, v); - int index = std::distance(kPowerTable.begin(), l); + auto const l = std::ranges::lower_bound(kPOWER_TABLE, v); + int index = std::distance(kPOWER_TABLE.begin(), l); // If we're not equal, subtract to get the floor if (*l != v) --index; @@ -216,14 +216,14 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU }; // Return ceil(log10(v)) - static auto kLoG10Ceil = [](uint128_t const& v) { + static auto kLOG10_CEIL = [](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::ranges::lower_bound(kPowerTable, v); - return int(std::distance(kPowerTable.begin(), l)); + auto const l = std::ranges::lower_bound(kPOWER_TABLE, v); + return int(std::distance(kPOWER_TABLE.begin(), l)); }; - static auto const kFl64 = kLoG10Floor(std::numeric_limits::max()); + static auto const kFL64 = kLOG10_FLOOR(std::numeric_limits::max()); bool const neg = amt.mantissa() < 0; uint128_t const den128(den); @@ -244,12 +244,12 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU // and (rem/den128) is as large as possible. Scale by multiplying low // and rem by 10 and subtracting one from the exponent. We could do this // with a loop, but it's more efficient to use logarithms. - auto const roomToGrow = kFl64 - kLoG10Ceil(low); + auto const roomToGrow = kFL64 - kLOG10_CEIL(low); if (roomToGrow > 0) { exponent -= roomToGrow; - low *= kPowerTable[roomToGrow]; - rem *= kPowerTable[roomToGrow]; + low *= kPOWER_TABLE[roomToGrow]; + rem *= kPOWER_TABLE[roomToGrow]; } auto const addRem = rem / den128; low += addRem; @@ -261,14 +261,14 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU // and adding one to the exponent until the low will fit in the 64-bit // mantissa. Use logarithms to avoid looping. bool hasRem = bool(rem); - auto const mustShrink = kLoG10Ceil(low) - kFl64; + auto const mustShrink = kLOG10_CEIL(low) - kFL64; if (mustShrink > 0) { uint128_t const sav(low); exponent += mustShrink; - low /= kPowerTable[mustShrink]; + low /= kPOWER_TABLE[mustShrink]; if (!hasRem) - hasRem = bool(sav - low * kPowerTable[mustShrink]); + hasRem = bool(sav - low * kPOWER_TABLE[mustShrink]); } std::int64_t mantissa = low.convert_to(); @@ -297,7 +297,7 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU { if (!result) { - return IOUAmount(-kMinMantissa, kMinExponent); + return IOUAmount(-kMIN_MANTISSA, kMIN_EXPONENT); } // This subtraction cannot underflow because `result` is not zero return IOUAmount(result.mantissa() - 1, result.exponent()); diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index ae29bd3297..b37428a6bf 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -143,9 +143,9 @@ getBookBase(Book const& book) uint256 getQualityNext(uint256 const& uBase) { - static constexpr uint256 kNextQuality( + static constexpr uint256 kNEXT_QUALITY( "0000000000000000000000000000000000000000000000010000000000000000"); - return uBase + kNextQuality; + return uBase + kNEXT_QUALITY; } std::uint64_t @@ -197,8 +197,8 @@ child(uint256 const& key) noexcept Keylet const& skip() noexcept { - static Keylet const kRet{ltLEDGER_HASHES, indexHash(LedgerNameSpace::SkipList)}; - return kRet; + static Keylet const kRET{ltLEDGER_HASHES, indexHash(LedgerNameSpace::SkipList)}; + return kRET; } Keylet @@ -213,22 +213,22 @@ skip(LedgerIndex ledger) noexcept Keylet const& amendments() noexcept { - static Keylet const kRet{ltAMENDMENTS, indexHash(LedgerNameSpace::Amendments)}; - return kRet; + static Keylet const kRET{ltAMENDMENTS, indexHash(LedgerNameSpace::Amendments)}; + return kRET; } Keylet const& fees() noexcept { - static Keylet const kRet{ltFEE_SETTINGS, indexHash(LedgerNameSpace::FeeSettings)}; - return kRet; + static Keylet const kRET{ltFEE_SETTINGS, indexHash(LedgerNameSpace::FeeSettings)}; + return kRET; } Keylet const& negativeUNL() noexcept { - static Keylet const kRet{ltNEGATIVE_UNL, indexHash(LedgerNameSpace::NegativeUnl)}; - return kRet; + static Keylet const kRET{ltNEGATIVE_UNL, indexHash(LedgerNameSpace::NegativeUnl)}; + return kRET; } Keylet @@ -287,7 +287,7 @@ quality(Keylet const& k, std::uint64_t q) noexcept Keylet NextT::operator()(Keylet const& k) const { - XRPL_ASSERT(k.type == ltDIR_NODE, "xrpl::keylet::NextT::operator() : valid input type"); + XRPL_ASSERT(k.type == ltDIR_NODE, "xrpl::keylet::next_t::operator() : valid input type"); return {ltDIR_NODE, getQualityNext(k.key)}; } @@ -385,13 +385,13 @@ nftpageMin(AccountID const& owner) { std::array buf{}; std::memcpy(buf.data(), owner.data(), owner.size()); - return {ltNFTOKEN_PAGE, uint256::fromRaw(buf)}; + return {ltNFTOKEN_PAGE, uint256{buf}}; } Keylet nftpageMax(AccountID const& owner) { - uint256 id = nft::kPageMask; + uint256 id = nft::kPAGE_MASK; std::memcpy(id.data(), owner.data(), owner.size()); return {ltNFTOKEN_PAGE, id}; } @@ -400,7 +400,7 @@ Keylet nftpage(Keylet const& k, uint256 const& token) { XRPL_ASSERT(k.type == ltNFTOKEN_PAGE, "xrpl::keylet::nftpage : valid input type"); - return {ltNFTOKEN_PAGE, (k.key & ~nft::kPageMask) + (token & nft::kPageMask)}; + return {ltNFTOKEN_PAGE, (k.key & ~nft::kPAGE_MASK) + (token & nft::kPAGE_MASK)}; } Keylet diff --git a/src/libxrpl/protocol/InnerObjectFormats.cpp b/src/libxrpl/protocol/InnerObjectFormats.cpp index 66b2822a42..5c691159d7 100644 --- a/src/libxrpl/protocol/InnerObjectFormats.cpp +++ b/src/libxrpl/protocol/InnerObjectFormats.cpp @@ -165,8 +165,8 @@ InnerObjectFormats::InnerObjectFormats() InnerObjectFormats const& InnerObjectFormats::getInstance() { - static InnerObjectFormats const kInstance; - return kInstance; + static InnerObjectFormats const kINSTANCE; + return kINSTANCE; } SOTemplate const* diff --git a/src/libxrpl/protocol/Issue.cpp b/src/libxrpl/protocol/Issue.cpp index 8de457a5cf..33ad3a0835 100644 --- a/src/libxrpl/protocol/Issue.cpp +++ b/src/libxrpl/protocol/Issue.cpp @@ -128,7 +128,7 @@ issueFromJson(json::Value const& v) } auto const issuer = parseBase58(issStr.asString()); - if (!issuer || *issuer == noAccount() || *issuer == xrpAccount()) + if (!issuer) { Throw("issueFromJson issuer must be a valid account"); } diff --git a/src/libxrpl/protocol/LedgerFormats.cpp b/src/libxrpl/protocol/LedgerFormats.cpp index 8b91bb7930..99c636fbdc 100644 --- a/src/libxrpl/protocol/LedgerFormats.cpp +++ b/src/libxrpl/protocol/LedgerFormats.cpp @@ -11,12 +11,12 @@ namespace xrpl { std::vector const& LedgerFormats::getCommonFields() { - static auto const kCommonFields = std::vector{ + static auto const kCOMMON_FIELDS = std::vector{ {sfLedgerIndex, SoeOptional}, {sfLedgerEntryType, SoeRequired}, {sfFlags, SoeRequired}, }; - return kCommonFields; + return kCOMMON_FIELDS; } LedgerFormats::LedgerFormats() @@ -41,8 +41,8 @@ LedgerFormats::LedgerFormats() LedgerFormats const& LedgerFormats::getInstance() { - static LedgerFormats const kInstance; - return kInstance; + static LedgerFormats const kINSTANCE; + return kINSTANCE; } } // namespace xrpl diff --git a/src/libxrpl/protocol/NFTokenID.cpp b/src/libxrpl/protocol/NFTokenID.cpp index cd2c46b66b..b7822caf01 100644 --- a/src/libxrpl/protocol/NFTokenID.cpp +++ b/src/libxrpl/protocol/NFTokenID.cpp @@ -159,7 +159,7 @@ insertNFTokenID( { std::vector const result = getNFTokenIDFromDeletedOffer(transactionMeta); - response[jss::nftoken_ids] = json::Value(json::ValueType::Array); + response[jss::nftoken_ids] = json::Value(json::ArrayValue); for (auto const& nftID : result) response[jss::nftoken_ids].append(to_string(nftID)); } diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index ce3baeb35e..4222c63fea 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -92,8 +92,8 @@ Permission::Permission() Permission const& Permission::getInstance() { - static Permission const kInstance; - return kInstance; + static Permission const kINSTANCE; + return kINSTANCE; } std::optional diff --git a/src/libxrpl/protocol/Protocol.cpp b/src/libxrpl/protocol/Protocol.cpp index fc45a2d4b3..14230e78bd 100644 --- a/src/libxrpl/protocol/Protocol.cpp +++ b/src/libxrpl/protocol/Protocol.cpp @@ -4,12 +4,12 @@ namespace xrpl { bool isVotingLedger(LedgerIndex seq) { - return seq % kFlagLedgerInterval == 0; + return seq % kFLAG_LEDGER_INTERVAL == 0; } bool isFlagLedger(LedgerIndex seq) { - return seq % kFlagLedgerInterval == 0; + return seq % kFLAG_LEDGER_INTERVAL == 0; } } // namespace xrpl diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index c6e6c1d324..17831957e0 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -89,9 +89,9 @@ sliceToHex(Slice const& slice) } for (int i = 0; i < slice.size(); ++i) { - static constexpr char kHex[] = "0123456789ABCDEF"; - s += kHex[((slice[i] & 0xf0) >> 4)]; - s += kHex[((slice[i] & 0x0f) >> 0)]; + constexpr char kHEX[] = "0123456789ABCDEF"; + s += kHEX[((slice[i] & 0xf0) >> 4)]; + s += kHEX[((slice[i] & 0x0f) >> 0)]; } return s; } @@ -174,7 +174,7 @@ ed25519Canonical(Slice const& sig) PublicKey::PublicKey(Slice const& slice) { - if (slice.size() < kSize) + if (slice.size() < kSIZE) { logicError( "PublicKey::PublicKey - Input slice cannot be an undersized " @@ -183,12 +183,12 @@ PublicKey::PublicKey(Slice const& slice) if (!publicKeyType(slice)) logicError("PublicKey::PublicKey invalid type"); - std::memcpy(buf_, slice.data(), kSize); + std::memcpy(buf_, slice.data(), kSIZE); } PublicKey::PublicKey(PublicKey const& other) { - std::memcpy(buf_, other.buf_, kSize); + std::memcpy(buf_, other.buf_, kSIZE); } PublicKey& @@ -196,7 +196,7 @@ PublicKey::operator=(PublicKey const& other) { if (this != &other) { - std::memcpy(buf_, other.buf_, kSize); + std::memcpy(buf_, other.buf_, kSIZE); } return *this; @@ -212,7 +212,7 @@ publicKeyType(Slice const& slice) if (slice[0] == 0xED) return KeyType::Ed25519; - if (slice[0] == kEcCompressedPrefixEvenY || slice[0] == kEcCompressedPrefixOddY) + if (slice[0] == kEC_COMPRESSED_PREFIX_EVEN_Y || slice[0] == kEC_COMPRESSED_PREFIX_ODD_Y) return KeyType::Secp256k1; } @@ -294,11 +294,11 @@ verify(PublicKey const& publicKey, Slice const& m, Slice const& sig) noexcept NodeID calcNodeID(PublicKey const& pk) { - static_assert(NodeID::kBytes == sizeof(RipeshaHasher::result_type)); + static_assert(NodeID::kBYTES == sizeof(RipeshaHasher::result_type)); RipeshaHasher h; h(pk.data(), pk.size()); - return NodeID::fromRaw(static_cast(h)); + return NodeID{static_cast(h)}; } } // namespace xrpl diff --git a/src/libxrpl/protocol/Quality.cpp b/src/libxrpl/protocol/Quality.cpp index 7ad426bef7..d3997cf2db 100644 --- a/src/libxrpl/protocol/Quality.cpp +++ b/src/libxrpl/protocol/Quality.cpp @@ -62,10 +62,10 @@ ceilInImpl(Amounts const& amount, STAmount const& limit, bool roundUp, Quality c // Clamp out if (result.out > amount.out) result.out = amount.out; - XRPL_ASSERT(result.in == limit, "xrpl::ceilInImpl : result matches limit"); + XRPL_ASSERT(result.in == limit, "xrpl::ceil_in_impl : result matches limit"); return result; } - XRPL_ASSERT(amount.in <= limit, "xrpl::ceilInImpl : result inside limit"); + XRPL_ASSERT(amount.in <= limit, "xrpl::ceil_in_impl : result inside limit"); return amount; } @@ -91,10 +91,10 @@ ceilOutImpl(Amounts const& amount, STAmount const& limit, bool roundUp, Quality // Clamp in if (result.in > amount.in) result.in = amount.in; - XRPL_ASSERT(result.out == limit, "xrpl::ceilOutImpl : result matches limit"); + XRPL_ASSERT(result.out == limit, "xrpl::ceil_out_impl : result matches limit"); return result; } - XRPL_ASSERT(amount.out <= limit, "xrpl::ceilOutImpl : result inside limit"); + XRPL_ASSERT(amount.out <= limit, "xrpl::ceil_out_impl : result inside limit"); return amount; } @@ -114,10 +114,10 @@ Quality composedQuality(Quality const& lhs, Quality const& rhs) { STAmount const lhsRate(lhs.rate()); - XRPL_ASSERT(lhsRate != beast::kZero, "xrpl::composedQuality : nonzero left input"); + XRPL_ASSERT(lhsRate != beast::kZERO, "xrpl::composed_quality : nonzero left input"); STAmount const rhsRate(rhs.rate()); - XRPL_ASSERT(rhsRate != beast::kZero, "xrpl::composedQuality : nonzero right input"); + XRPL_ASSERT(rhsRate != beast::kZERO, "xrpl::composed_quality : nonzero right input"); STAmount const rate(mulRound(lhsRate, rhsRate, lhsRate.asset(), true)); @@ -125,7 +125,7 @@ composedQuality(Quality const& lhs, Quality const& rhs) std::uint64_t const storedMantissa(rate.mantissa()); XRPL_ASSERT( - (storedExponent > 0) && (storedExponent <= 255), "xrpl::composedQuality : valid exponent"); + (storedExponent > 0) && (storedExponent <= 255), "xrpl::composed_quality : valid exponent"); return Quality((storedExponent << (64 - 8)) | storedMantissa); } @@ -134,7 +134,7 @@ Quality Quality::round(int digits) const { // Modulus for mantissa - static std::uint64_t const kMod[17] = { + static std::uint64_t const kMOD[17] = { /* 0 */ 10000000000000000, /* 1 */ 1000000000000000, /* 2 */ 100000000000000, @@ -156,8 +156,8 @@ Quality::round(int digits) const auto exponent = value_ >> (64 - 8); auto mantissa = value_ & 0x00ffffffffffffffULL; - mantissa += kMod[digits] - 1; - mantissa -= (mantissa % kMod[digits]); + mantissa += kMOD[digits] - 1; + mantissa -= (mantissa % kMOD[digits]); return Quality{(exponent << (64 - 8)) | mantissa}; } diff --git a/src/libxrpl/protocol/QualityFunction.cpp b/src/libxrpl/protocol/QualityFunction.cpp index e862770406..2e9eb5745a 100644 --- a/src/libxrpl/protocol/QualityFunction.cpp +++ b/src/libxrpl/protocol/QualityFunction.cpp @@ -13,7 +13,7 @@ namespace xrpl { QualityFunction::QualityFunction(Quality const& quality, QualityFunction::CLOBLikeTag) : m_(0), b_(0), quality_(quality) { - if (quality.rate() <= beast::kZero) + if (quality.rate() <= beast::kZERO) Throw("QualityFunction quality rate is 0."); b_ = 1 / quality.rate(); } @@ -30,7 +30,7 @@ QualityFunction::combine(QualityFunction const& qf) std::optional QualityFunction::outFromAvgQ(Quality const& quality) { - if (m_ != 0 && quality.rate() != beast::kZero) + if (m_ != 0 && quality.rate() != beast::kZERO) { SaveNumberRoundMode const rm(Number::setround(Number::RoundingMode::Upward)); auto const out = (1 / quality.rate() - b_) / m_; diff --git a/src/libxrpl/protocol/RPCErr.cpp b/src/libxrpl/protocol/RPCErr.cpp index ec9a3dee9d..66aef1470c 100644 --- a/src/libxrpl/protocol/RPCErr.cpp +++ b/src/libxrpl/protocol/RPCErr.cpp @@ -12,7 +12,7 @@ struct RPCErr; json::Value rpcError(ErrorCodeI iError) { - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); RPC::injectError(iError, jvResult); return jvResult; } diff --git a/src/libxrpl/protocol/Rate2.cpp b/src/libxrpl/protocol/Rate2.cpp index fd56f83bf5..27b17068e3 100644 --- a/src/libxrpl/protocol/Rate2.cpp +++ b/src/libxrpl/protocol/Rate2.cpp @@ -9,7 +9,7 @@ namespace xrpl { -Rate const kParityRate(QUALITY_ONE); +Rate const kPARITY_RATE(QUALITY_ONE); namespace detail { @@ -35,7 +35,7 @@ multiply(STAmount const& amount, Rate const& rate) { XRPL_ASSERT(rate.value, "xrpl::nft::multiply : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) return amount; return multiply(amount, detail::asAmount(rate), amount.asset()); @@ -46,7 +46,7 @@ multiplyRound(STAmount const& amount, Rate const& rate, bool roundUp) { XRPL_ASSERT(rate.value, "xrpl::nft::multiplyRound : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) return amount; return mulRound(amount, detail::asAmount(rate), amount.asset(), roundUp); @@ -57,7 +57,7 @@ multiplyRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool { XRPL_ASSERT(rate.value, "xrpl::nft::multiplyRound(Issue) : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) { return amount; } @@ -70,7 +70,7 @@ divide(STAmount const& amount, Rate const& rate) { XRPL_ASSERT(rate.value, "xrpl::nft::divide : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) return amount; return divide(amount, detail::asAmount(rate), amount.asset()); @@ -81,7 +81,7 @@ divideRound(STAmount const& amount, Rate const& rate, bool roundUp) { XRPL_ASSERT(rate.value, "xrpl::nft::divideRound : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) return amount; return divRound(amount, detail::asAmount(rate), amount.asset(), roundUp); @@ -92,7 +92,7 @@ divideRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool r { XRPL_ASSERT(rate.value, "xrpl::nft::divideRound(Issue) : nonzero rate input"); - if (rate == kParityRate) + if (rate == kPARITY_RATE) return amount; return divRound(amount, detail::asAmount(rate), asset, roundUp); diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 08a95145eb..2c971749b6 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -39,68 +38,15 @@ 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. - - // If any new conditions with new amendments are added, those amendments must also be added to - // useRulesGuards. - bool const enableVaultNumbers = + bool const enableLargeNumbers = !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); - bool const enableCuspRoundingFix = !r || r->enabled(fixCleanup3_2_0); - XRPL_ASSERT( - !r || useRulesGuards(*r) == (enableCuspRoundingFix || enableVaultNumbers), - "setCurrentTransactionRules : rule decisions match"); - - // Declare the range this way to keep clang-tidy from complaining - auto const range = [enableCuspRoundingFix, enableVaultNumbers]() { - if (enableVaultNumbers) - { - if (enableCuspRoundingFix) - { - return MantissaRange::MantissaScale::Large; - } - return MantissaRange::MantissaScale::LargeLegacy; - } - return MantissaRange::MantissaScale::Small; - }(); - Number::setMantissaScale(range); + Number::setMantissaScale( + enableLargeNumbers ? MantissaRange::MantissaScale::Large + : MantissaRange::MantissaScale::Small); *getCurrentTransactionRulesRef() = std::move(r); } -bool -useRulesGuards(Rules const& rules) -{ - // The list of amendments used here - to decide whether to create a RulesGuard - must be a - // superset of the list used to figure out which mantissa scale to use in - // setCurrentTransactionRules. Additional amendments can be added if desired. - // - // As soon as any one of these amendments is retired, this whole function can be removed, along - // with createGuards, and any other callers, and the first set of guards can be created directly - // at the call site, without using optional. - return rules.enabled(fixCleanup3_2_0) || rules.enabled(featureSingleAssetVault) || - rules.enabled(featureLendingProtocol); -} - -void -createGuards( - Rules const& rules, - std::optional& stNumberSO, - std::optional& rulesGuard, - std::optional& mantissaScaleGuard) -{ - if (useRulesGuards(rules)) - { - // raii classes for the current ledger rules. - // fixUniversalNumber predates the rulesGuard and should be replaced. - stNumberSO.emplace(rules.enabled(fixUniversalNumber)); - rulesGuard.emplace(rules); - } - else - { - // Without those features enabled, always use the old number rules. - mantissaScaleGuard.emplace(MantissaRange::MantissaScale::Small); - } -} - class Rules::Impl { private: diff --git a/src/libxrpl/protocol/SField.cpp b/src/libxrpl/protocol/SField.cpp index a2d4903c6a..4193bb3e27 100644 --- a/src/libxrpl/protocol/SField.cpp +++ b/src/libxrpl/protocol/SField.cpp @@ -8,7 +8,7 @@ namespace xrpl { // Storage for static const members. -SField::IsSigning const SField::kNotSigning; +SField::IsSigning const SField::kNOT_SIGNING; int SField::num = 0; std::unordered_map SField::knownCodeToField; std::unordered_map SField::knownNameToField; @@ -53,12 +53,12 @@ TypedField::TypedField(PrivateAccessTagT pat, Args&&... args) ##__VA_ARGS__); // SFields which, for historical reasons, do not follow naming conventions. -SField const sfInvalid(access, -1, ""); -SField const sfGeneric(access, 0, "Generic"); +SField const kSF_INVALID(access, -1, ""); +SField const kSF_GENERIC(access, 0, "Generic"); // The following two fields aren't used anywhere, but they break tests/have // downstream effects. -SField const kSfHash(access, STI_UINT256, 257, "hash"); -SField const kSfIndex(access, STI_UINT256, 258, "index"); +SField const kSF_HASH(access, STI_UINT256, 257, "hash"); +SField const kSF_INDEX(access, STI_UINT256, 258, "index"); #include @@ -98,7 +98,7 @@ SField::SField(PrivateAccessTagT, int fc, char const* fn) , fieldType(STI_UNKNOWN) , fieldValue(0) , fieldName(fn) - , fieldMeta(kSmdNever) + , fieldMeta(SMdNever) , fieldNum(++num) , signingField(IsSigning::Yes) , jsonName(fieldName.c_str()) @@ -121,7 +121,7 @@ SField::getField(int code) { return *(it->second); } - return sfInvalid; + return kSF_INVALID; } int @@ -149,7 +149,7 @@ SField::getField(std::string const& fieldName) { return *(it->second); } - return sfInvalid; + return kSF_INVALID; } } // namespace xrpl diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index da8b233c61..f561c9f930 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -17,11 +17,11 @@ namespace xrpl { -STAccount::STAccount() : value_(beast::kZero), default_(true) +STAccount::STAccount() : value_(beast::kZERO), default_(true) { } -STAccount::STAccount(SField const& n) : STBase(n), value_(beast::kZero), default_(true) +STAccount::STAccount(SField const& n) : STBase(n), value_(beast::kZERO), default_(true) { } @@ -35,11 +35,11 @@ STAccount::STAccount(SField const& n, Buffer const& v) : STAccount(n) // STVar::STVar (SerialIter&, SField const&) // which throws. If STVar can throw in its constructor, then so can // STAccount. - if (v.size() != uint160::kBytes) + if (v.size() != uint160::kBYTES) Throw("Invalid STAccount size"); default_ = false; - memcpy(value_.begin(), v.data(), uint160::kBytes); + memcpy(value_.begin(), v.data(), uint160::kBYTES); } STAccount::STAccount(SerialIter& sit, SField const& name) : STAccount(name, sit.getVLBuffer()) @@ -77,7 +77,7 @@ STAccount::add(Serializer& s) const // Preserve the serialization behavior of an STBlob: // o If we are default (all zeros) serialize as an empty blob. // o Otherwise serialize 160 bits. - int const size = isDefault() ? 0 : uint160::kBytes; + int const size = isDefault() ? 0 : uint160::kBYTES; s.addVL(value_.data(), size); } diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 1ba9cd042f..25857d387e 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -19,10 +19,8 @@ #include #include #include -#include #include #include -#include #include #include #include @@ -49,9 +47,9 @@ namespace xrpl { -static std::uint64_t const kTenTO14 = 100000000000000ull; -static std::uint64_t const kTenTO14M1 = kTenTO14 - 1; -static std::uint64_t const kTenTO17 = kTenTO14 * 1000; +static std::uint64_t const kTEN_TO14 = 100000000000000ull; +static std::uint64_t const kTEN_TO14M1 = kTEN_TO14 - 1; +static std::uint64_t const kTEN_TO17 = kTEN_TO14 * 1000; //------------------------------------------------------------------------------ static std::int64_t @@ -90,11 +88,11 @@ areComparable(STAmount const& v1, STAmount const& v2) { return std::visit( [&](TIss1 const& issue1, TIss2 const& issue2) { - if constexpr (kIsIssueV && kIsIssueV) + if constexpr (kIS_ISSUE_V && kIS_ISSUE_V) { return v1.native() == v2.native() && issue1.currency == issue2.currency; } - else if constexpr (kIsMptissueV && kIsMptissueV) + else if constexpr (kIS_MPTISSUE_V && kIS_MPTISSUE_V) { return issue1 == issue2; } @@ -107,20 +105,20 @@ areComparable(STAmount const& v1, STAmount const& v2) v2.asset().value()); } -static_assert(kInitialXrp.drops() == STAmount::kMaxNativeN); +static_assert(kINITIAL_XRP.drops() == STAmount::kMAX_NATIVE_N); STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) { std::uint64_t value = sit.get64(); // native or MPT - if ((value & kIssuedCurrency) == 0) + if ((value & kISSUED_CURRENCY) == 0) { - if ((value & kMpToken) != 0) + if ((value & kMP_TOKEN) != 0) { // is MPT offset_ = 0; - isNegative_ = (value & kPositive) == 0; + isNegative_ = (value & kPOSITIVE) == 0; value_ = (value << 8) | sit.get8(); asset_ = sit.get192(); return; @@ -128,9 +126,9 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) // else is XRP asset_ = xrpIssue(); // positive - if ((value & kPositive) != 0) + if ((value & kPOSITIVE) != 0) { - value_ = value & kValueMask; + value_ = value & kVALUE_MASK; offset_ = 0; isNegative_ = false; return; @@ -140,7 +138,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) if (value == 0) Throw("negative zero is not canonical"); - value_ = value & kValueMask; + value_ = value & kVALUE_MASK; offset_ = 0; isNegative_ = true; return; @@ -167,7 +165,8 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) bool const isNegative = (offset & 256) == 0; offset = (offset & 255) - 97; // center the range - if (value < kMinValue || value > kMaxValue || offset < kMinOffset || offset > kMaxOffset) + if (value < kMIN_VALUE || value > kMAX_VALUE || offset < kMIN_OFFSET || + offset > kMAX_OFFSET) { Throw("invalid currency value"); } @@ -230,7 +229,7 @@ STAmount::STAmount(std::uint64_t mantissa, bool negative) } STAmount::STAmount(XRPAmount const& amount) - : asset_(xrpIssue()), offset_(0), isNegative_(amount < beast::kZero) + : asset_(xrpIssue()), offset_(0), isNegative_(amount < beast::kZERO) { if (isNegative_) { @@ -317,7 +316,7 @@ STAmount::operator=(IOUAmount const& iou) { XRPL_ASSERT(integral() == false, "xrpl::STAmount::operator=(IOUAmount) : is not integral"); offset_ = iou.exponent(); - isNegative_ = iou < beast::kZero; + isNegative_ = iou < beast::kZERO; if (isNegative_) { value_ = static_cast(-iou.mantissa()); @@ -374,10 +373,10 @@ operator+(STAmount const& v1, STAmount const& v2) if (!areComparable(v1, v2)) Throw("Can't add amounts that are't comparable!"); - if (v2 == beast::kZero) + if (v2 == beast::kZERO) return v1; - if (v1 == beast::kZero) + if (v1 == beast::kZERO) { // Result must be in terms of v1 currency and issuer. return {v1.getFName(), v1.asset(), v2.mantissa(), v2.exponent(), v2.negative()}; @@ -439,7 +438,7 @@ operator-(STAmount const& v1, STAmount const& v2) //------------------------------------------------------------------------------ -std::uint64_t const STAmount::kURateOne = getRate(STAmount(1), STAmount(1)); +std::uint64_t const STAmount::kU_RATE_ONE = getRate(STAmount(1), STAmount(1)); void STAmount::setIssue(Asset const& asset) @@ -459,13 +458,13 @@ STAmount::setIssue(Asset const& asset) std::uint64_t getRate(STAmount const& offerOut, STAmount const& offerIn) { - if (offerOut == beast::kZero) + if (offerOut == beast::kZERO) return 0; try { STAmount const r = divide(offerIn, offerOut, noIssue()); - if (r == beast::kZero) // offer is too good + if (r == beast::kZERO) // offer is too good return 0; XRPL_ASSERT( (r.exponent() >= -100) && (r.exponent() <= 155), @@ -506,7 +505,7 @@ canAdd(STAmount const& a, STAmount const& b) return false; // special case: adding anything to zero is always fine - if (a == beast::kZero || b == beast::kZero) + if (a == beast::kZERO || b == beast::kZERO) return true; // XRP case (overflow & underflow check) @@ -526,17 +525,17 @@ canAdd(STAmount const& a, STAmount const& b) auto const ret = std::visit( [&]( TIss1 const&, TIss2 const&) -> std::optional { - if constexpr (kIsIssueV && kIsIssueV) + if constexpr (kIS_ISSUE_V && kIS_ISSUE_V) { - static STAmount const kOne{IOUAmount{1, 0}, noIssue()}; - static STAmount const kMaxLoss{IOUAmount{1, -4}, noIssue()}; - STAmount const lhs = divide((a - b) + b, a, noIssue()) - kOne; - STAmount const rhs = divide((b - a) + a, b, noIssue()) - kOne; - return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= kMaxLoss; + static STAmount const kONE{IOUAmount{1, 0}, noIssue()}; + static STAmount const kMAX_LOSS{IOUAmount{1, -4}, noIssue()}; + STAmount const lhs = divide((a - b) + b, a, noIssue()) - kONE; + STAmount const rhs = divide((b - a) + a, b, noIssue()) - kONE; + return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= kMAX_LOSS; } // MPT (overflow & underflow check) - if constexpr (kIsMptissueV && kIsMptissueV) + if constexpr (kIS_MPTISSUE_V && kIS_MPTISSUE_V) { MPTAmount const aVal = a.mpt(); MPTAmount const bVal = b.mpt(); @@ -583,7 +582,7 @@ canSubtract(STAmount const& a, STAmount const& b) return false; // Special case: subtracting zero is always fine - if (b == beast::kZero) + if (b == beast::kZERO) return true; // XRP case (underflow & overflow check) @@ -607,13 +606,13 @@ canSubtract(STAmount const& a, STAmount const& b) auto const ret = std::visit( [&]( TIss1 const&, TIss2 const&) -> std::optional { - if constexpr (kIsIssueV && kIsIssueV) + if constexpr (kIS_ISSUE_V && kIS_ISSUE_V) { return true; } // MPT case (underflow & overflow check) - if constexpr (kIsMptissueV && kIsMptissueV) + if constexpr (kIS_MPTISSUE_V && kIS_MPTISSUE_V) { MPTAmount const aVal = a.mpt(); MPTAmount const bVal = b.mpt(); @@ -643,7 +642,7 @@ canSubtract(STAmount const& a, STAmount const& b) void STAmount::setJson(json::Value& elem) const { - elem = json::ValueType::Object; + elem = json::ObjectValue; if (!native()) { @@ -684,7 +683,7 @@ std::string STAmount::getText() const { // keep full internal accuracy, but make more human friendly if possible - if (*this == beast::kZero) + if (*this == beast::kZERO) return "0"; std::string const rawValue(std::to_string(value_)); @@ -781,9 +780,9 @@ STAmount::add(Serializer& s) const { asset_.visit( [&](MPTIssue const& issue) { - auto u8 = static_cast(kMpToken >> 56); + auto u8 = static_cast(kMP_TOKEN >> 56); if (!isNegative_) - u8 |= static_cast(kPositive >> 56); + u8 |= static_cast(kPOSITIVE >> 56); s.add8(u8); s.add64(value_); s.addBitString(issue.getMptID()); @@ -795,7 +794,7 @@ STAmount::add(Serializer& s) const if (!isNegative_) { - s.add64(value_ | kPositive); + s.add64(value_ | kPOSITIVE); } else { @@ -804,9 +803,9 @@ STAmount::add(Serializer& s) const } else { - if (*this == beast::kZero) + if (*this == beast::kZERO) { - s.add64(kIssuedCurrency); + s.add64(kISSUED_CURRENCY); } else if (isNegative_) // 512 = not native { @@ -911,11 +910,11 @@ STAmount::canonicalize() { // N.B. do not move the overflow check to after the // multiplication - if (native() && value_ > kMaxNativeN) + if (native() && value_ > kMAX_NATIVE_N) { Throw("Native currency amount out of range"); } - else if (!native() && value_ > kMaxMpTokenAmount) + else if (!native() && value_ > kMAX_MP_TOKEN_AMOUNT) { Throw("MPT amount out of range"); } @@ -925,11 +924,11 @@ STAmount::canonicalize() } } - if (native() && value_ > kMaxNativeN) + if (native() && value_ > kMAX_NATIVE_N) { Throw("Native currency amount out of range"); } - else if (!native() && value_ > kMaxMpTokenAmount) + else if (!native() && value_ > kMAX_MP_TOKEN_AMOUNT) { Throw("MPT amount out of range"); } @@ -950,22 +949,22 @@ STAmount::canonicalize() return; } - while ((value_ < kMinValue) && (offset_ > kMinOffset)) + while ((value_ < kMIN_VALUE) && (offset_ > kMIN_OFFSET)) { value_ *= 10; --offset_; } - while (value_ > kMaxValue) + while (value_ > kMAX_VALUE) { - if (offset_ >= kMaxOffset) + if (offset_ >= kMAX_OFFSET) Throw("value overflow"); value_ /= 10; ++offset_; } - if ((offset_ < kMinOffset) || (value_ < kMinValue)) + if ((offset_ < kMIN_OFFSET) || (value_ < kMIN_VALUE)) { value_ = 0; isNegative_ = false; @@ -973,14 +972,14 @@ STAmount::canonicalize() return; } - if (offset_ > kMaxOffset) + if (offset_ > kMAX_OFFSET) Throw("value overflow"); XRPL_ASSERT( - (value_ == 0) || ((value_ >= kMinValue) && (value_ <= kMaxValue)), + (value_ == 0) || ((value_ >= kMIN_VALUE) && (value_ <= kMAX_VALUE)), "xrpl::STAmount::canonicalize : value inside range"); XRPL_ASSERT( - (value_ == 0) || ((offset_ >= kMinOffset) && (offset_ <= kMaxOffset)), + (value_ == 0) || ((offset_ >= kMIN_OFFSET) && (offset_ <= kMAX_OFFSET)), "xrpl::STAmount::canonicalize : offset inside range"); XRPL_ASSERT( (value_ != 0) || (offset_ != -100), "xrpl::STAmount::canonicalize : value or offset set"); @@ -1058,8 +1057,8 @@ amountFromJson(SField const& name, json::Value const& v) else if (v.isArray()) { value = v.get(json::UInt(0), 0); - currencyOrMPTID = v.get(json::UInt(1), json::ValueType::Null); - issuer = v.get(json::UInt(2), json::ValueType::Null); + currencyOrMPTID = v.get(json::UInt(1), json::NullValue); + issuer = v.get(json::UInt(2), json::NullValue); } else if (v.isString()) { @@ -1153,7 +1152,7 @@ amountFromJsonNoThrow(STAmount& result, json::Value const& jvSource) { try { - result = amountFromJson(sfGeneric, jvSource); + result = amountFromJson(kSF_GENERIC, jvSource); return true; } catch (std::exception const& e) @@ -1224,50 +1223,6 @@ operator-(STAmount const& value) STAmount::Unchecked{}); } -static bool -hasInvalidAmount(STBase const& field, int depth, beast::Journal j); - -static bool -hasInvalidAmount(STObject const& object, int depth, beast::Journal j) -{ - return std::ranges::any_of( - object, [&](STBase const& field) { return hasInvalidAmount(field, depth, j); }); -} - -static bool -hasInvalidAmount(STArray const& array, int depth, beast::Journal j) -{ - return std::ranges::any_of( - array, [&](STObject const& object) { return hasInvalidAmount(object, depth, j); }); -} - -static bool -hasInvalidAmount(STBase const& field, int depth, beast::Journal j) -{ - if (depth > 10) - { - JLOG(j.error()) << "hasInvalidAmount: depth exceeds 10"; - return true; - } - - if (auto const amount = dynamic_cast(&field)) - return !isLegalMPT(*amount) || !isLegalNet(*amount); - - if (auto const object = dynamic_cast(&field)) - return hasInvalidAmount(*object, depth + 1, j); - - if (auto const array = dynamic_cast(&field)) - return hasInvalidAmount(*array, depth + 1, j); - - return false; -} - -bool -hasInvalidAmount(STBase const& field, beast::Journal j) -{ - return hasInvalidAmount(field, 0, j); -} - //------------------------------------------------------------------------------ // // Arithmetic @@ -1320,10 +1275,10 @@ muldivRound( STAmount divide(STAmount const& num, STAmount const& den, Asset const& asset) { - if (den == beast::kZero) + if (den == beast::kZERO) Throw("division by zero"); - if (num == beast::kZero) + if (num == beast::kZERO) return {asset}; std::uint64_t numVal = num.mantissa(); @@ -1333,7 +1288,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) if (num.integral()) { - while (numVal < STAmount::kMinValue) + while (numVal < STAmount::kMIN_VALUE) { // Need to bring into range numVal *= 10; @@ -1343,7 +1298,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) if (den.integral()) { - while (denVal < STAmount::kMinValue) + while (denVal < STAmount::kMIN_VALUE) { denVal *= 10; --denOffset; @@ -1357,7 +1312,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) // is in the range of 10^16 to 10^15. return STAmount( asset, - muldiv(numVal, kTenTO17, denVal) + 5, + muldiv(numVal, kTEN_TO17, denVal) + 5, numOffset - denOffset - 17, num.negative() != den.negative()); } @@ -1365,7 +1320,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) STAmount multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) { - if (v1 == beast::kZero || v2 == beast::kZero) + if (v1 == beast::kZERO || v2 == beast::kZERO) return STAmount(asset); if (v1.native() && v2.native() && asset.native()) @@ -1408,7 +1363,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) if (v1.integral()) { - while (value1 < STAmount::kMinValue) + while (value1 < STAmount::kMIN_VALUE) { value1 *= 10; --offset1; @@ -1417,7 +1372,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) if (v2.integral()) { - while (value2 < STAmount::kMinValue) + while (value2 < STAmount::kMIN_VALUE) { value2 *= 10; --offset2; @@ -1430,7 +1385,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) // precision, by scaling the result to 10^16 to 10^18. return STAmount( asset, - muldiv(value1, value2, kTenTO14) + 7, + muldiv(value1, value2, kTEN_TO14) + 7, offset1 + offset2 + 14, v1.negative() != v2.negative()); } @@ -1476,9 +1431,9 @@ canonicalizeRound(bool integral, std::uint64_t& value, int& offset, bool) ++offset; } } - else if (value > STAmount::kMaxValue) + else if (value > STAmount::kMAX_VALUE) { - while (value > (10 * STAmount::kMaxValue)) + while (value > (10 * STAmount::kMAX_VALUE)) { value /= 10; ++offset; @@ -1518,9 +1473,9 @@ canonicalizeRoundStrict(bool integral, std::uint64_t& value, int& offset, bool r ++offset; } } - else if (value > STAmount::kMaxValue) + else if (value > STAmount::kMAX_VALUE) { - while (value > (10 * STAmount::kMaxValue)) + while (value > (10 * STAmount::kMAX_VALUE)) { value /= 10; ++offset; @@ -1539,7 +1494,7 @@ roundToScale(STAmount const& value, std::int32_t scale, Number::RoundingMode rou return value; // Nothing to do for zero. - if (value == beast::kZero) + if (value == beast::kZERO) return value; // If the value's exponent is greater than or equal to the scale, then @@ -1548,10 +1503,10 @@ roundToScale(STAmount const& value, std::int32_t scale, Number::RoundingMode rou if (value.exponent() >= scale) return value; - STAmount const referenceValue{value.asset(), STAmount::kMinValue, scale, value.negative()}; + STAmount const referenceValue{value.asset(), STAmount::kMIN_VALUE, scale, value.negative()}; NumberRoundModeGuard const mg(rounding); - // With an IOU, the result of addition will be truncated to the + // With an IOU, the the result of addition will be truncated to the // precision of the larger value, which in this case is referenceValue. Then // remove the reference value via subtraction, and we're left with the // rounded value. @@ -1585,7 +1540,7 @@ template static STAmount divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp) { - if (den == beast::kZero) + if (den == beast::kZERO) Throw("division by zero"); - if (num == beast::kZero) + if (num == beast::kZERO) return {asset}; std::uint64_t numVal = num.mantissa(), denVal = den.mantissa(); @@ -1710,7 +1665,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool if (num.integral()) { - while (numVal < STAmount::kMinValue) + while (numVal < STAmount::kMIN_VALUE) { numVal *= 10; --numOffset; @@ -1719,7 +1674,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool if (den.integral()) { - while (denVal < STAmount::kMinValue) + while (denVal < STAmount::kMIN_VALUE) { denVal *= 10; --denOffset; @@ -1737,7 +1692,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool // We round away from zero if we're rounding up or // truncate if we're rounding down. std::uint64_t amount = - muldivRound(numVal, kTenTO17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); + muldivRound(numVal, kTEN_TO17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); int offset = numOffset - denOffset - 17; @@ -1764,8 +1719,8 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool else { // return the smallest value above zero - amount = STAmount::kMinValue; - offset = STAmount::kMinOffset; + amount = STAmount::kMIN_VALUE; + offset = STAmount::kMIN_OFFSET; } return STAmount(asset, amount, offset, resultNegative); } @@ -1784,9 +1739,4 @@ divRoundStrict(STAmount const& num, STAmount const& den, Asset const& asset, boo return divRoundImpl(num, den, asset, roundUp); } -[[nodiscard]] bool -STAmount::isZeroAtScale(int scale) const -{ - return roundToScale(*this, scale, Number::RoundingMode::ToNearest).signum() == 0; -} } // namespace xrpl diff --git a/src/libxrpl/protocol/STArray.cpp b/src/libxrpl/protocol/STArray.cpp index 6bfe9fe88e..537cb36630 100644 --- a/src/libxrpl/protocol/STArray.cpp +++ b/src/libxrpl/protocol/STArray.cpp @@ -130,12 +130,12 @@ STArray::getText() const json::Value STArray::getJson(JsonOptions p) const { - json::Value v = json::ValueType::Array; + json::Value v = json::ArrayValue; for (auto const& object : v_) { if (object.getSType() != STI_NOTPRESENT) { - json::Value& inner = v.append(json::ValueType::Object); + json::Value& inner = v.append(json::ObjectValue); inner[object.getFName().getJsonName()] = object.getJson(p); } } diff --git a/src/libxrpl/protocol/STBase.cpp b/src/libxrpl/protocol/STBase.cpp index f029f10e75..ec6131482f 100644 --- a/src/libxrpl/protocol/STBase.cpp +++ b/src/libxrpl/protocol/STBase.cpp @@ -12,7 +12,7 @@ namespace xrpl { -STBase::STBase() : fName_(&sfGeneric) +STBase::STBase() : fName_(&kSF_GENERIC) { } diff --git a/src/libxrpl/protocol/STInteger.cpp b/src/libxrpl/protocol/STInteger.cpp index 5f3fb6ffa4..d17dd49fe5 100644 --- a/src/libxrpl/protocol/STInteger.cpp +++ b/src/libxrpl/protocol/STInteger.cpp @@ -209,7 +209,7 @@ STUInt64::getJson(JsonOptions) const return str; }; - if (auto const& fName = getFName(); fName.shouldMeta(SField::kSmdBaseTen)) + if (auto const& fName = getFName(); fName.shouldMeta(SField::SMdBaseTen)) { return convertToString(value_, 10); // Convert to base 10 } diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index c9b8109e32..c0019c334f 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -28,7 +28,7 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} { auto const currencyOrAccount = sit.get160(); - if (isXRP(Currency::fromRaw(currencyOrAccount))) + if (isXRP(static_cast(currencyOrAccount))) { asset_ = xrpIssue(); } @@ -39,7 +39,7 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} // - 160 bits MPT issuer account // - 160 bits black hole account // - 32 bits sequence - AccountID const account = AccountID::fromRaw(sit.get160()); + AccountID const account = static_cast(sit.get160()); // MPT if (noAccount() == account) { diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index 8c5c5b5eae..8bec23d319 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -133,12 +133,13 @@ STLedgerEntry::getJson(JsonOptions options) const bool STLedgerEntry::isThreadedType(Rules const& rules) const { - static constexpr std::array kNewPreviousTxnIdTypes = { + static constexpr std::array kNEW_PREVIOUS_TXN_ID_TYPES = { ltDIR_NODE, ltAMENDMENTS, ltFEE_SETTINGS, ltNEGATIVE_UNL, ltAMM}; // 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(kNewPreviousTxnIdTypes.cbegin(), kNewPreviousTxnIdTypes.cend(), type_) != 0); + (std::count( + kNEW_PREVIOUS_TXN_ID_TYPES.cbegin(), kNEW_PREVIOUS_TXN_ID_TYPES.cend(), type_) != 0); return !excludePrevTxnID && getFieldIndex(sfPreviousTxnID) != -1; } diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index 8ef7b9760f..f6481a4d5d 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -58,7 +58,7 @@ STNumber::associateAsset(Asset const& a) STTakesAsset::associateAsset(a); XRPL_ASSERT_PARTS( - getFName().shouldMeta(SField::kSmdNeedsAsset), + getFName().shouldMeta(SField::SMdNeedsAsset), "STNumber::associateAsset", "field needs asset"); @@ -76,7 +76,7 @@ STNumber::add(Serializer& s) const auto const exponent = value.exponent(); SField const& field = getFName(); - if (field.shouldMeta(SField::kSmdNeedsAsset)) + if (field.shouldMeta(SField::SMdNeedsAsset)) { // asset is defined in the STTakesAsset base class if (asset_) @@ -96,8 +96,7 @@ STNumber::add(Serializer& s) const // Json. Regardless, the only time we should be serializing an // STNumber is when the scale is large. XRPL_ASSERT_PARTS( - Number::getMantissaScale() == MantissaRange::MantissaScale::LargeLegacy || - Number::getMantissaScale() == MantissaRange::MantissaScale::Large, + Number::getMantissaScale() == MantissaRange::MantissaScale::Large, "xrpl::STNumber::add", "STNumber only used with large mantissa scale"); #endif @@ -161,7 +160,7 @@ operator<<(std::ostream& out, STNumber const& rhs) NumberParts partsFromString(std::string const& number) { - static boost::regex const kReNumber( + static boost::regex const kRE_NUMBER( "^" // the beginning of the string "([-+]?)" // (optional) + or - character "(0|[1-9][0-9]*)" // a number (no leading zeroes, unless 0) @@ -172,7 +171,7 @@ partsFromString(std::string const& number) boost::smatch match; - if (!boost::regex_match(number, match, kReNumber)) + if (!boost::regex_match(number, match, kRE_NUMBER)) Throw("'" + number + "' is not a number"); // Match fields: diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index e16cbc871f..6bce2f0ab2 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -646,22 +646,22 @@ STObject::getFieldVL(SField const& field) const STAmount const& STObject::getFieldAmount(SField const& field) const { - static STAmount const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STAmount const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } STPathSet const& STObject::getFieldPathSet(SField const& field) const { - static STPathSet const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STPathSet const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } STVector256 const& STObject::getFieldV256(SField const& field) const { - static STVector256 const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STVector256 const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } STObject @@ -677,22 +677,22 @@ STObject::getFieldObject(SField const& field) const STArray const& STObject::getFieldArray(SField const& field) const { - static STArray const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STArray const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } STCurrency const& STObject::getFieldCurrency(SField const& field) const { - static STCurrency const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STCurrency const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } STNumber const& STObject::getFieldNumber(SField const& field) const { - static STNumber const kEmpty{}; - return getFieldByConstRef(field, kEmpty); + static STNumber const kEMPTY{}; + return getFieldByConstRef(field, kEMPTY); } void @@ -834,7 +834,7 @@ STObject::setFieldObject(SField const& field, STObject const& v) json::Value STObject::getJson(JsonOptions options) const { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); for (auto const& elem : v_) { diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 64c4dfd1be..f6ebde4e52 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -136,15 +136,6 @@ arrayExpected(std::string const& object, std::string const& field) RpcInvalidParams, "Field '" + makeName(object, field) + "' must be a JSON array."); } -static inline json::Value -arrayTooBig(std::string const& object, std::string const& field) -{ - return RPC::makeError( - RpcInvalidParams, - "Field '" + makeName(object, field) + "' exceeds allowed JSON array size of " + - std::to_string(kMaxParsedJsonArraySize) + " elements per field."); -} - static inline json::Value stringExpected(std::string const& object, std::string const& field) { @@ -233,7 +224,7 @@ parseUnsigned( template static std::optional -parseUInt16( +parseUint16( SField const& field, std::string const& jsonName, std::string const& fieldName, @@ -258,7 +249,7 @@ parseUInt16( safeCast(static_cast( TxFormats::getInstance().findTypeByName(strValue)))); - if (*name == sfGeneric) + if (*name == kSF_GENERIC) name = &sfTransaction; } else if (field == sfLedgerEntryType) @@ -268,7 +259,7 @@ parseUInt16( safeCast(static_cast( LedgerFormats::getInstance().findTypeByName(strValue)))); - if (*name == sfGeneric) + if (*name == kSF_GENERIC) name = &sfLedgerEntry; } else @@ -294,7 +285,7 @@ parseUInt16( template static std::optional -parseUInt32( +parseUint32( SField const& field, std::string const& jsonName, std::string const& fieldName, @@ -361,7 +352,7 @@ parseLeaf( auto const& field = SField::getField(fieldName); // checked in parseObject - if (field == sfInvalid) + if (field == kSF_INVALID) { // LCOV_EXCL_START error = unknownField(jsonName, fieldName); @@ -374,8 +365,8 @@ parseLeaf( case STI_UINT8: try { - constexpr auto kMinValue = std::numeric_limits::min(); - constexpr auto kMaxValue = std::numeric_limits::max(); + constexpr auto kMIN_VALUE = std::numeric_limits::min(); + constexpr auto kMAX_VALUE = std::numeric_limits::max(); if (value.isString()) { std::string const strValue = value.asString(); @@ -386,7 +377,7 @@ parseLeaf( { auto ter = transCode(strValue); - if (!ter || TERtoInt(*ter) < kMinValue || TERtoInt(*ter) > kMaxValue) + if (!ter || TERtoInt(*ter) < kMIN_VALUE || TERtoInt(*ter) > kMAX_VALUE) { error = outOfRange(jsonName, fieldName); return ret; @@ -409,7 +400,7 @@ parseLeaf( } else if (value.isInt()) { - if (value.asInt() < kMinValue || value.asInt() > kMaxValue) + if (value.asInt() < kMIN_VALUE || value.asInt() > kMAX_VALUE) { error = outOfRange(jsonName, fieldName); return ret; @@ -420,7 +411,7 @@ parseLeaf( } else if (value.isUInt()) { - if (value.asUInt() > kMaxValue) + if (value.asUInt() > kMAX_VALUE) { error = outOfRange(jsonName, fieldName); return ret; @@ -443,14 +434,14 @@ parseLeaf( break; case STI_UINT16: - ret = parseUInt16(field, jsonName, fieldName, name, value, error); + ret = parseUint16(field, jsonName, fieldName, name, value, error); if (!ret) return ret; break; case STI_UINT32: - ret = parseUInt32(field, jsonName, fieldName, name, value, error); + ret = parseUint32(field, jsonName, fieldName, name, value, error); if (!ret) return ret; @@ -465,7 +456,7 @@ parseLeaf( std::uint64_t val = 0; - bool const useBase10 = field.shouldMeta(SField::kSmdBaseTen); + bool const useBase10 = field.shouldMeta(SField::SMdBaseTen); // if the field is amount, serialize as base 10 auto [p, ec] = std::from_chars( @@ -690,18 +681,12 @@ parseLeaf( break; case STI_VECTOR256: - if (not value.isArrayOrNull()) + if (!value.isArrayOrNull()) { error = arrayExpected(jsonName, fieldName); return ret; } - if (not value.isNull() and value.size() > kMaxParsedJsonArraySize) - { - error = arrayTooBig(jsonName, fieldName); - return ret; - } - try { STVector256 tail(field); @@ -723,18 +708,12 @@ parseLeaf( break; case STI_PATHSET: - if (not value.isArrayOrNull()) + if (!value.isArrayOrNull()) { error = arrayExpected(jsonName, fieldName); return ret; } - if (not value.isNull() and value.size() > kMaxParsedJsonArraySize) - { - error = arrayTooBig(jsonName, fieldName); - return ret; - } - try { STPathSet tail(field); @@ -743,7 +722,7 @@ parseLeaf( { STPath p; - if (not value[i].isArrayOrNull()) + if (!value[i].isArrayOrNull()) { std::stringstream ss; ss << fieldName << "[" << i << "]"; @@ -751,14 +730,6 @@ parseLeaf( return ret; } - if (not value[i].isNull() and value[i].size() > kMaxParsedJsonArraySize) - { - std::stringstream ss; - ss << fieldName << "[" << i << "]"; - error = arrayTooBig(jsonName, ss.str()); - return ret; - } - for (json::UInt j = 0; value[i].isValidIndex(j); ++j) { std::stringstream ss; @@ -839,7 +810,7 @@ parseLeaf( error = invalidData(elementName, assetName.cStr()); return ret; } - if (getMPTIssuer(u) == beast::kZero) + if (getMPTIssuer(u) == beast::kZERO) { error = invalidData(elementName, jss::account.cStr()); return ret; @@ -975,6 +946,8 @@ parseLeaf( return ret; } +static int const kMAX_DEPTH = 64; + // Forward declaration since parseObject() and parseArray() call each other. static std::optional parseArray( @@ -992,13 +965,13 @@ parseObject( int depth, json::Value& error) { - if (not json.isObjectOrNull()) + if (!json.isObjectOrNull()) { error = notAnObject(jsonName); return std::nullopt; } - if (depth > kMaxParsedJsonDepth) + if (depth > kMAX_DEPTH) { error = tooDeep(jsonName); return std::nullopt; @@ -1011,9 +984,10 @@ parseObject( for (auto const& fieldName : json.getMemberNames()) { json::Value const& value = json[fieldName]; + auto const& field = SField::getField(fieldName); - if (field == sfInvalid) + if (field == kSF_INVALID) { error = unknownField(jsonName, fieldName); return std::nullopt; @@ -1105,24 +1079,18 @@ parseArray( int depth, json::Value& error) { - if (not json.isArrayOrNull()) + if (!json.isArrayOrNull()) { error = notAnArray(jsonName); return std::nullopt; } - if (depth > kMaxParsedJsonDepth) + if (depth > kMAX_DEPTH) { error = tooDeep(jsonName); return std::nullopt; } - if (not json.isNull() and json.size() > kMaxParsedJsonArraySize) - { - error = arrayTooBig(jsonName, ""); - return std::nullopt; - } - try { STArray tail(inName); @@ -1140,11 +1108,13 @@ parseArray( } // TODO: There doesn't seem to be a nice way to get just the - // first/only key in an object without copying all keys into a vector + // first/only key in an object without copying all keys into + // a vector std::string const memberName(json[i].getMemberNames()[0]); + ; auto const& nameField(SField::getField(memberName)); - if (nameField == sfInvalid) + if (nameField == kSF_INVALID) { error = unknownField(jsonName, memberName); return std::nullopt; @@ -1189,7 +1159,7 @@ parseArray( STParsedJSONObject::STParsedJSONObject(std::string const& name, json::Value const& json) { using namespace STParsedJSONDetail; - object = parseObject(name, json, sfGeneric, 0, error); + object = parseObject(name, json, kSF_GENERIC, 0, error); } } // namespace xrpl diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index cb70ac36fe..8c4b139792 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -90,14 +90,10 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) if (hasAccount) account = sit.get160(); - if (hasCurrency && hasMPT) - { - JLOG(debugLog().error()) << "Bad path element MPT and Currency in pathset"; - Throw("bad path element: MPT and Currency"); - } - + XRPL_ASSERT( + !(hasCurrency && hasMPT), "xrpl::STPathSet::STPathSet : not has Currency and MPT"); if (hasCurrency) - asset = Currency::fromRaw(sit.get160()); + asset = static_cast(sit.get160()); if (hasMPT) asset = sit.get192(); @@ -105,7 +101,7 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) if (hasIssuer) issuer = sit.get160(); - path.emplace_back(account, asset, issuer, hasCurrency || hasMPT); + path.emplace_back(account, asset, issuer, hasCurrency); } } } @@ -171,11 +167,11 @@ STPath::hasSeen(AccountID const& account, PathAsset const& asset, AccountID cons json::Value STPath::getJson(JsonOptions) const { - json::Value ret(json::ValueType::Array); + json::Value ret(json::ArrayValue); for (auto const& it : path_) { - json::Value elem(json::ValueType::Object); + json::Value elem(json::ObjectValue); auto const iType = it.getNodeType(); elem[jss::type] = iType; @@ -205,7 +201,7 @@ STPath::getJson(JsonOptions) const json::Value STPathSet::getJson(JsonOptions options) const { - json::Value ret(json::ValueType::Array); + json::Value ret(json::ArrayValue); for (auto const& it : value_) ret.append(it.getJson(options)); diff --git a/src/libxrpl/protocol/STTakesAsset.cpp b/src/libxrpl/protocol/STTakesAsset.cpp index 806861e6b6..de7de002b0 100644 --- a/src/libxrpl/protocol/STTakesAsset.cpp +++ b/src/libxrpl/protocol/STTakesAsset.cpp @@ -17,7 +17,7 @@ associateAsset(SLE& sle, Asset const& asset) { STBase& entry = sle.getIndex(i); SField const& field = entry.getFName(); - if (field.shouldMeta(SField::kSmdNeedsAsset)) + if (field.shouldMeta(SField::SMdNeedsAsset)) { auto const type = entry.getSType(); // If the field is not set or present, skip it. diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 2777981fd7..d335988ac3 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -69,8 +69,8 @@ getTxFormat(TxType type) STTx::STTx(STObject&& object) : STObject(std::move(object)) { - txType_ = safeCast(getFieldU16(sfTransactionType)); - applyTemplate(getTxFormat(txType_)->getSOTemplate()); // may throw + tx_type_ = safeCast(getFieldU16(sfTransactionType)); + applyTemplate(getTxFormat(tx_type_)->getSOTemplate()); // may throw tid_ = getHash(HashPrefix::TransactionId); } @@ -78,15 +78,15 @@ STTx::STTx(SerialIter& sit) : STObject(sfTransaction) { int const length = sit.getBytesLeft(); - if ((length < kTxMinSizeBytes) || (length > kTxMaxSizeBytes)) + if ((length < kTX_MIN_SIZE_BYTES) || (length > kTX_MAX_SIZE_BYTES)) Throw("Transaction length invalid"); if (set(sit)) Throw("Transaction contains an object terminator"); - txType_ = safeCast(getFieldU16(sfTransactionType)); + tx_type_ = safeCast(getFieldU16(sfTransactionType)); - applyTemplate(getTxFormat(txType_)->getSOTemplate()); // May throw + applyTemplate(getTxFormat(tx_type_)->getSOTemplate()); // May throw tid_ = getHash(HashPrefix::TransactionId); } @@ -99,9 +99,9 @@ STTx::STTx(TxType type, std::function assembler) : STObject(sfT assembler(*this); - txType_ = safeCast(getFieldU16(sfTransactionType)); + tx_type_ = safeCast(getFieldU16(sfTransactionType)); - if (txType_ != type) + if (tx_type_ != type) logicError("Transaction type was mutated during assembly"); tid_ = getHash(HashPrefix::TransactionId); @@ -315,8 +315,8 @@ STTx::checkBatchSign(Rules const& rules) const json::Value STTx::getJson(JsonOptions options) const { - json::Value ret = STObject::getJson(JsonOptions::Values::None); - if (!(options & JsonOptions::Values::DisableApiPriorV2)) + json::Value ret = STObject::getJson(JsonOptions::KNone); + if (!(options & JsonOptions::KDisableApiPriorV2)) ret[jss::hash] = to_string(getTransactionID()); return ret; } @@ -324,7 +324,7 @@ STTx::getJson(JsonOptions options) const json::Value STTx::getJson(JsonOptions options, bool binary) const { - bool const v1 = !(options & JsonOptions::Values::DisableApiPriorV2); + bool const v1 = !(options & JsonOptions::KDisableApiPriorV2); if (binary) { @@ -333,7 +333,7 @@ STTx::getJson(JsonOptions options, bool binary) const if (v1) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::tx] = dataBin; ret[jss::hash] = to_string(getTransactionID()); return ret; @@ -342,7 +342,7 @@ STTx::getJson(JsonOptions options, bool binary) const return json::Value{dataBin}; } - json::Value ret = STObject::getJson(JsonOptions::Values::None); + json::Value ret = STObject::getJson(JsonOptions::KNone); if (v1) ret[jss::hash] = to_string(getTransactionID()); @@ -352,13 +352,13 @@ STTx::getJson(JsonOptions options, bool binary) const std::string const& STTx::getMetaSQLInsertReplaceHeader() { - static std::string const kSql = + static std::string const kSQL = "INSERT OR REPLACE INTO Transactions " "(TransID, TransType, FromAcct, FromSeq, LedgerSeq, Status, RawTxn, " "TxnMeta)" " VALUES "; - return kSql; + return kSQL; } std::string @@ -377,14 +377,14 @@ STTx::getMetaSQL( TxnSql status, std::string const& escapedMetaData) const { - static boost::format const kBfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); + static boost::format const kBF_TRANS("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); - auto format = TxFormats::getInstance().findByType(txType_); + auto format = TxFormats::getInstance().findByType(tx_type_); XRPL_ASSERT(format, "xrpl::STTx::getMetaSQL : non-null type format"); return str( - boost::format(kBfTrans) % to_string(getTransactionID()) % format->getName() % + boost::format(kBF_TRANS) % to_string(getTransactionID()) % format->getName() % toBase58(getAccountID(sfAccount)) % getFieldU32(sfSequence) % inLedger % safeCast(status) % rTxn % escapedMetaData); } @@ -454,11 +454,11 @@ multiSignHelper( STArray const& signers{sigObject.getFieldArray(sfSigners)}; // There are well known bounds that the number of signers must be within. - if (signers.size() < STTx::kMinMultiSigners || signers.size() > STTx::kMaxMultiSigners) + if (signers.size() < STTx::kMIN_MULTI_SIGNERS || signers.size() > STTx::kMAX_MULTI_SIGNERS) return Unexpected("Invalid Signers array size."); // Signers must be in sorted order by AccountID. - AccountID lastAccountID(beast::kZero); + AccountID lastAccountID(beast::kZERO); for (auto const& signer : signers) { @@ -535,10 +535,8 @@ STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const { // Used inside the loop in multiSignHelper to enforce that // the account owner may not multisign for themselves. - // For delegated transactions sfDelegate is the account whose signer list is checked, - // the delegate account itself can not be among the signers. auto const txnAccountID = - &sigObject != this ? std::nullopt : std::optional(getFeePayer()); + &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 @@ -654,7 +652,7 @@ isMemoOkay(STObject const& st, std::string& reason) // The only allowed characters for MemoType and MemoFormat are the // characters allowed in URLs per RFC 3986: alphanumerics and the // following symbols: -._~:/?#[]@!$&'()*+,;=% - static constexpr std::array const kAllowedSymbols = []() { + static constexpr std::array const kALLOWED_SYMBOLS = []() { std::array a{}; std::string_view const symbols( @@ -670,7 +668,7 @@ isMemoOkay(STObject const& st, std::string& reason) for (unsigned char const c : *optData) { - if (kAllowedSymbols[c] == 0) + if (kALLOWED_SYMBOLS[c] == 0) { reason = "The MemoType and MemoFormat fields may only " @@ -733,14 +731,14 @@ isRawTransactionOkay(STObject const& st, std::string& reason) return true; if (st.isFieldPresent(sfBatchSigners) && - st.getFieldArray(sfBatchSigners).size() > kMaxBatchTxCount) + st.getFieldArray(sfBatchSigners).size() > kMAX_BATCH_TX_COUNT) { reason = "Batch Signers array exceeds max entries."; return false; } auto const& rawTxns = st.getFieldArray(sfRawTransactions); - if (rawTxns.size() > kMaxBatchTxCount) + if (rawTxns.size() > kMAX_BATCH_TX_COUNT) { reason = "Raw Transactions array exceeds max entries."; return false; diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index 5eafb407ec..dd4b8a0fee 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -38,7 +38,7 @@ STValidation::validationFormat() // it relies on the SField's below being initialized, and we can't // guarantee the initialization order. // clang-format off - static SOTemplate const kFormat{ + static SOTemplate const kFORMAT{ {sfFlags, SoeRequired}, {sfLedgerHash, SoeRequired}, {sfLedgerSequence, SoeRequired}, @@ -62,7 +62,7 @@ STValidation::validationFormat() }; // clang-format on - return kFormat; + return kFORMAT; }; uint256 @@ -108,7 +108,7 @@ STValidation::isValid() const noexcept getSignerPublic(), getSigningHash(), makeSlice(getFieldVL(sfSignature)), - (getFlags() & kVfFullyCanonicalSig) != 0u); + (getFlags() & kVF_FULLY_CANONICAL_SIG) != 0u); } return valid_.value(); @@ -117,7 +117,7 @@ STValidation::isValid() const noexcept bool STValidation::isFull() const noexcept { - return (getFlags() & kVfFullValidation) != 0; + return (getFlags() & kVF_FULL_VALIDATION) != 0; } Blob diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index 3d123e6a0e..8e45d3c75b 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -38,7 +38,7 @@ STVar::~STVar() STVar::STVar(STVar const& other) { if (other.p_ != nullptr) - p_ = other.p_->copy(kMaxSize, &d_); + p_ = other.p_->copy(kMAX_SIZE, &d_); } STVar::STVar(STVar&& other) @@ -50,7 +50,7 @@ STVar::STVar(STVar&& other) } else { - p_ = other.p_->move(kMaxSize, &d_); + p_ = other.p_->move(kMAX_SIZE, &d_); } } @@ -62,7 +62,7 @@ STVar::operator=(STVar const& rhs) destroy(); if (rhs.p_ != nullptr) { - p_ = rhs.p_->copy(kMaxSize, &d_); + p_ = rhs.p_->copy(kMAX_SIZE, &d_); } else { @@ -86,7 +86,7 @@ STVar::operator=(STVar&& rhs) } else { - p_ = rhs.p_->move(kMaxSize, &d_); + p_ = rhs.p_->move(kMAX_SIZE, &d_); } } @@ -149,9 +149,9 @@ STVar::constructST(SerializedTypeID id, int depth, Args&&... args) } else { - static constexpr bool kAlwaysFalse = + constexpr bool kALWAYS_FALSE = !std::is_same_v, std::tuple>; - static_assert(kAlwaysFalse, "Invalid STVar constructor arguments"); + static_assert(kALWAYS_FALSE, "Invalid STVar constructor arguments"); } }; diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index 7aca309667..d720067508 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -30,7 +30,7 @@ STVector256::STVector256(SerialIter& sit, SField const& name) : STBase(name) value_.reserve(cnt); for (std::size_t i = 0; i != cnt; ++i) - value_.push_back(uint256::fromRaw(slice.substr(i * uint256::size(), uint256::size()))); + value_.emplace_back(slice.substr(i * uint256::size(), uint256::size())); } STBase* @@ -75,7 +75,7 @@ STVector256::isEquivalent(STBase const& t) const json::Value STVector256::getJson(JsonOptions) const { - json::Value ret(json::ValueType::Array); + json::Value ret(json::ArrayValue); for (auto const& vEntry : value_) ret.append(to_string(vEntry)); diff --git a/src/libxrpl/protocol/STXChainBridge.cpp b/src/libxrpl/protocol/STXChainBridge.cpp index ce6ad2368a..35f47f891e 100644 --- a/src/libxrpl/protocol/STXChainBridge.cpp +++ b/src/libxrpl/protocol/STXChainBridge.cpp @@ -64,12 +64,11 @@ STXChainBridge::STXChainBridge(SField const& name, json::Value const& v) : STBas } auto checkExtra = [](json::Value const& v) { - static auto const kBridgeJson = - xrpl::STXChainBridge().getJson(xrpl::JsonOptions::Values::None); + static auto const kBRIDGE_JSON = xrpl::STXChainBridge().getJson(xrpl::JsonOptions::KNone); for (auto it = v.begin(); it != v.end(); ++it) { std::string const name = it.memberName(); - if (!kBridgeJson.isMember(name)) + if (!kBRIDGE_JSON.isMember(name)) { Throw("STXChainBridge extra field detected: " + name); } diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index f33b1871e1..d5fe54867a 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -56,7 +56,7 @@ SecretKey::toString() const namespace detail { void -copyUInt32(std::uint8_t* out, std::uint32_t v) +copyUint32(std::uint8_t* out, std::uint32_t v) { *out++ = v >> 24; *out++ = (v >> 16) & 0xff; @@ -84,7 +84,7 @@ deriveDeterministicRootKey(Seed const& seed) // more iterations loop a few times. for (std::uint32_t seq = 0; seq != 128; ++seq) { - copyUInt32(buf.data() + 16, seq); + copyUint32(buf.data() + 16, seq); auto const ret = sha512Half(buf); @@ -137,13 +137,13 @@ private: std::array buf{}; std::ranges::copy(generator_, buf.begin()); - copyUInt32(buf.data() + 33, seq); + copyUint32(buf.data() + 33, seq); // The odds that this loop executes more than once are negligible // but we impose a maximum limit just in case. for (std::uint32_t subseq = 0; subseq != 128; ++subseq) { - copyUInt32(buf.data() + 37, subseq); + copyUint32(buf.data() + 37, subseq); auto const ret = sha512HalfS(buf); diff --git a/src/libxrpl/protocol/Seed.cpp b/src/libxrpl/protocol/Seed.cpp index 42b2e85498..f15d4dcff0 100644 --- a/src/libxrpl/protocol/Seed.cpp +++ b/src/libxrpl/protocol/Seed.cpp @@ -105,7 +105,7 @@ parseGenericSeed(std::string const& str, bool rfc1751) if (RFC1751::getKeyFromEnglish(key, str) == 1) { Blob const blob(key.rbegin(), key.rend()); - return Seed{uint128::fromRaw(blob)}; + return Seed{uint128{blob}}; } } diff --git a/src/libxrpl/protocol/TER.cpp b/src/libxrpl/protocol/TER.cpp index e5c1d17b1a..d70314ea9f 100644 --- a/src/libxrpl/protocol/TER.cpp +++ b/src/libxrpl/protocol/TER.cpp @@ -22,7 +22,7 @@ transResults() static std::unordered_map< TERUnderlyingType, - std::pair> const kResults + std::pair> const kRESULTS { MAKE_ERROR(tecAMM_BALANCE, "AMM has invalid balance."), MAKE_ERROR(tecAMM_INVALID_TOKENS, "AMM invalid LP tokens."), @@ -225,7 +225,7 @@ transResults() #undef MAKE_ERROR - return kResults; + return kRESULTS; } bool @@ -264,7 +264,7 @@ transHuman(TER code) std::optional transCode(std::string const& token) { - static auto const kResults = [] { + static auto const kRESULTS = [] { auto& byTer = transResults(); auto range = boost::make_iterator_range(byTer.begin(), byTer.end()); auto tRange = boost::adaptors::transform( @@ -274,9 +274,9 @@ transCode(std::string const& token) return byToken; }(); - auto const r = kResults.find(token); + auto const r = kRESULTS.find(token); - if (r == kResults.end()) + if (r == kRESULTS.end()) return std::nullopt; return TER::fromInt(r->second); diff --git a/src/libxrpl/protocol/TxFormats.cpp b/src/libxrpl/protocol/TxFormats.cpp index b926bdf0e5..083889622c 100644 --- a/src/libxrpl/protocol/TxFormats.cpp +++ b/src/libxrpl/protocol/TxFormats.cpp @@ -12,7 +12,7 @@ namespace xrpl { std::vector const& TxFormats::getCommonFields() { - static auto const kCommonFields = std::vector{ + static auto const kCOMMON_FIELDS = std::vector{ {sfTransactionType, SoeRequired}, {sfFlags, SoeOptional}, {sfSourceTag, SoeOptional}, @@ -31,7 +31,7 @@ TxFormats::getCommonFields() {sfNetworkID, SoeOptional}, {sfDelegate, SoeOptional}, }; - return kCommonFields; + return kCOMMON_FIELDS; } TxFormats::TxFormats() @@ -56,8 +56,8 @@ TxFormats::TxFormats() TxFormats const& TxFormats::getInstance() { - static TxFormats const kInstance; - return kInstance; + static TxFormats const kINSTANCE; + return kINSTANCE; } } // namespace xrpl diff --git a/src/libxrpl/protocol/UintTypes.cpp b/src/libxrpl/protocol/UintTypes.cpp index 486c11ba45..adef5e2c14 100644 --- a/src/libxrpl/protocol/UintTypes.cpp +++ b/src/libxrpl/protocol/UintTypes.cpp @@ -18,41 +18,41 @@ namespace detail { // Characters we are willing to allow in the ASCII representation of a // three-letter currency code. -constexpr std::string_view kIsoCharSet = +constexpr std::string_view kISO_CHAR_SET = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "<>(){}[]|?!@#$%^&*"; // The location (in bytes) of the 3 digit currency inside a 160-bit value -constexpr std::size_t kIsoCodeOffset = 12; +constexpr std::size_t kISO_CODE_OFFSET = 12; // The length of an ISO-4217 like code -constexpr std::size_t kIsoCodeLength = 3; +constexpr std::size_t kISO_CODE_LENGTH = 3; } // namespace detail std::string to_string(Currency const& currency) { - if (currency == beast::kZero) + if (currency == beast::kZERO) return systemCurrencyCode(); if (currency == noCurrency()) return "1"; - static constexpr Currency kSIsoBits("FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); + static constexpr Currency kS_ISO_BITS("FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); - if ((currency & kSIsoBits).isZero()) + if ((currency & kS_ISO_BITS).isZero()) { std::string const iso( - currency.data() + detail::kIsoCodeOffset, - currency.data() + detail::kIsoCodeOffset + detail::kIsoCodeLength); + currency.data() + detail::kISO_CODE_OFFSET, + currency.data() + detail::kISO_CODE_OFFSET + detail::kISO_CODE_LENGTH); // Specifying the system currency code using ISO-style representation // is not allowed. if ((iso != systemCurrencyCode()) && - (iso.find_first_not_of(detail::kIsoCharSet) == std::string::npos)) + (iso.find_first_not_of(detail::kISO_CHAR_SET) == std::string::npos)) { return iso; } @@ -66,19 +66,19 @@ toCurrency(Currency& currency, std::string const& code) { if (code.empty() || (code.compare(systemCurrencyCode()) == 0)) { - currency = beast::kZero; + currency = beast::kZERO; return true; } // Handle ISO-4217-like 3-digit character codes. - if (code.size() == detail::kIsoCodeLength) + if (code.size() == detail::kISO_CODE_LENGTH) { - if (code.find_first_not_of(detail::kIsoCharSet) != std::string::npos) + if (code.find_first_not_of(detail::kISO_CHAR_SET) != std::string::npos) return false; - currency = beast::kZero; + currency = beast::kZERO; - std::ranges::copy(code, currency.begin() + detail::kIsoCodeOffset); + std::ranges::copy(code, currency.begin() + detail::kISO_CODE_OFFSET); return true; } @@ -98,22 +98,22 @@ toCurrency(std::string const& code) Currency const& xrpCurrency() { - static Currency const kCurrency(beast::kZero); - return kCurrency; + static Currency const kCURRENCY(beast::kZERO); + return kCURRENCY; } Currency const& noCurrency() { - static Currency const kCurrency(1); - return kCurrency; + static Currency const kCURRENCY(1); + return kCURRENCY; } Currency const& badCurrency() { - static Currency const kCurrency(0x5852500000000000); - return kCurrency; + static Currency const kCURRENCY(0x5852500000000000); + return kCURRENCY; } } // namespace xrpl diff --git a/src/libxrpl/protocol/XChainAttestations.cpp b/src/libxrpl/protocol/XChainAttestations.cpp index 805d08c097..f89ad6a52c 100644 --- a/src/libxrpl/protocol/XChainAttestations.cpp +++ b/src/libxrpl/protocol/XChainAttestations.cpp @@ -195,7 +195,7 @@ AttestationClaim::message( std::uint64_t claimID, std::optional const& dst) { - STObject o{sfGeneric}; + STObject o{kSF_GENERIC}; // Serialize in SField order to make python serializers easier to write o[sfXChainClaimID] = claimID; o[sfAmount] = sendingAmount; @@ -332,7 +332,7 @@ AttestationCreateAccount::message( std::uint64_t createCount, AccountID const& dst) { - STObject o{sfGeneric}; + STObject o{kSF_GENERIC}; // Serialize in SField order to make python serializers easier to write o[sfXChainAccountCreateCount] = createCount; o[sfAmount] = sendingAmount; @@ -668,7 +668,7 @@ XChainAttestationsBase::XChainAttestationsBase(json::Value const& attestations_ = [&] { auto const jAtts = v[jss::attestations]; - if (jAtts.size() > kMaxAttestations) + if (jAtts.size() > kMAX_ATTESTATIONS) Throw("XChainAttestationsBase exceeded max number of attestations"); std::vector r; @@ -682,7 +682,7 @@ XChainAttestationsBase::XChainAttestationsBase(json::Value const& template XChainAttestationsBase::XChainAttestationsBase(STArray const& arr) { - if (arr.size() > kMaxAttestations) + if (arr.size() > kMAX_ATTESTATIONS) Throw("XChainAttestationsBase exceeded max number of attestations"); attestations_.reserve(arr.size()); diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index a43cbd9c85..91063d3fa6 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -122,15 +122,15 @@ coefficients sizes greatly speeds up the multi-precision computations. namespace xrpl { -static constexpr char const* kAlphabetForward = +static constexpr char const* kALPHABET_FORWARD = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; -static constexpr std::array const kAlphabetReverse = []() { +static constexpr std::array const kALPHABET_REVERSE = []() { std::array map{}; for (auto& m : map) m = -1; - for (int i = 0, j = 0; kAlphabetForward[i] != 0; ++i) - map[static_cast(kAlphabetForward[i])] = j++; + for (int i = 0, j = 0; kALPHABET_FORWARD[i] != 0; ++i) + map[static_cast(kALPHABET_FORWARD[i])] = j++; return map; }(); @@ -239,9 +239,9 @@ encodeBase58(void const* message, std::size_t size, void* temp, std::size_t temp // Translate the result into a string. std::string str; str.reserve(zeroes + (b58end - iter)); - str.assign(zeroes, kAlphabetForward[0]); + str.assign(zeroes, kALPHABET_FORWARD[0]); while (iter != b58end) - str += kAlphabetForward[*(iter++)]; + str += kALPHABET_FORWARD[*(iter++)]; return str; } @@ -252,7 +252,7 @@ decodeBase58(std::string const& s) auto remain = s.size(); // Skip and count leading zeroes int zeroes = 0; - while (remain > 0 && kAlphabetReverse[*psz] == 0) + while (remain > 0 && kALPHABET_REVERSE[*psz] == 0) { ++zeroes; ++psz; @@ -267,7 +267,7 @@ decodeBase58(std::string const& s) std::vector b256((remain * 733 / 1000) + 1); while (remain > 0) { - auto carry = kAlphabetReverse[*psz]; + auto carry = kALPHABET_REVERSE[*psz]; if (carry == -1) return {}; // Apply "b256 = b256 * 58 + carry". @@ -425,7 +425,7 @@ b256ToB58Be(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() + inputZeros, ::xrpl::kAlphabetForward[0]); + std::fill(out.begin(), out.begin() + inputZeros, ::xrpl::kALPHABET_FORWARD[0]); // iterate through the base 58^10 coeff // convert to base 58 big endian then @@ -458,7 +458,7 @@ b256ToB58Be(std::span input, std::span out) } for (auto b58Coeff : b58BeS.subspan(toSkip)) { - out[outIndex] = ::xrpl::kAlphabetForward[b58Coeff]; + out[outIndex] = ::xrpl::kALPHABET_FORWARD[b58Coeff]; outIndex += 1; } } @@ -487,7 +487,7 @@ b58ToB256Be(std::string_view input, std::span out) std::size_t count = 0; for (auto const& c : col) { - if (c != ::xrpl::kAlphabetForward[0]) + if (c != ::xrpl::kALPHABET_FORWARD[0]) { return count; } @@ -510,7 +510,7 @@ b58ToB256Be(std::string_view input, std::span out) "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); for (unsigned char const c : input.substr(0, partial_coeff_len)) { - auto curVal = ::xrpl::kAlphabetReverse[c]; + auto curVal = ::xrpl::kALPHABET_REVERSE[c]; if (curVal < 0) { return Unexpected(TokenCodecErrc::InvalidEncodingChar); @@ -523,7 +523,7 @@ b58ToB256Be(std::string_view input, std::span out) for (int j = 0; j < num_full_coeffs; ++j) { unsigned char const c = input[partial_coeff_len + (j * 10) + i]; - auto curVal = ::xrpl::kAlphabetReverse[c]; + auto curVal = ::xrpl::kALPHABET_REVERSE[c]; if (curVal < 0) { return Unexpected(TokenCodecErrc::InvalidEncodingChar); @@ -610,9 +610,9 @@ encodeBase58Token( std::span input, std::span out) { - static constexpr std::size_t kTmpBufSize = 128; - std::array buf{}; - if (input.size() > kTmpBufSize - 5) + constexpr std::size_t kTMP_BUF_SIZE = 128; + std::array buf{}; + if (input.size() > kTMP_BUF_SIZE - 5) { return Unexpected(TokenCodecErrc::InputTooLarge); } diff --git a/src/libxrpl/resource/Fees.cpp b/src/libxrpl/resource/Fees.cpp index bb825fa3c7..8c9b72987f 100644 --- a/src/libxrpl/resource/Fees.cpp +++ b/src/libxrpl/resource/Fees.cpp @@ -4,24 +4,24 @@ namespace xrpl::Resource { -Charge const kFeeMalformedRequest(200, "malformed request"); -Charge const kFeeRequestNoReply(10, "unsatisfiable request"); -Charge const kFeeInvalidSignature(2000, "invalid signature"); -Charge const kFeeUselessData(150, "useless data"); -Charge const kFeeInvalidData(400, "invalid data"); +Charge const kFEE_MALFORMED_REQUEST(200, "malformed request"); +Charge const kFEE_REQUEST_NO_REPLY(10, "unsatisfiable request"); +Charge const kFEE_INVALID_SIGNATURE(2000, "invalid signature"); +Charge const kFEE_USELESS_DATA(150, "useless data"); +Charge const kFEE_INVALID_DATA(400, "invalid data"); -Charge const kFeeMalformedRpc(100, "malformed RPC"); -Charge const kFeeReferenceRpc(20, "reference RPC"); -Charge const kFeeExceptionRpc(100, "exceptioned RPC"); -Charge const kFeeMediumBurdenRpc(400, "medium RPC"); -Charge const kFeeHeavyBurdenRpc(3000, "heavy RPC"); +Charge const kFEE_MALFORMED_RPC(100, "malformed RPC"); +Charge const kFEE_REFERENCE_RPC(20, "reference RPC"); +Charge const kFEE_EXCEPTION_RPC(100, "exceptioned RPC"); +Charge const kFEE_MEDIUM_BURDEN_RPC(400, "medium RPC"); +Charge const kFEE_HEAVY_BURDEN_RPC(3000, "heavy RPC"); -Charge const kFeeTrivialPeer(1, "trivial peer request"); -Charge const kFeeModerateBurdenPeer(250, "moderate peer request"); -Charge const kFeeHeavyBurdenPeer(2000, "heavy peer request"); +Charge const kFEE_TRIVIAL_PEER(1, "trivial peer request"); +Charge const kFEE_MODERATE_BURDEN_PEER(250, "moderate peer request"); +Charge const kFEE_HEAVY_BURDEN_PEER(2000, "heavy peer request"); -Charge const kFeeWarning(4000, "received warning"); -Charge const kFeeDrop(6000, "dropped"); +Charge const kFEE_WARNING(4000, "received warning"); +Charge const kFEE_DROP(6000, "dropped"); // See also Resource::Logic::charge for log level cutoff values diff --git a/src/libxrpl/server/LoadFeeTrack.cpp b/src/libxrpl/server/LoadFeeTrack.cpp index 31b2fa2558..085e846145 100644 --- a/src/libxrpl/server/LoadFeeTrack.cpp +++ b/src/libxrpl/server/LoadFeeTrack.cpp @@ -27,9 +27,9 @@ LoadFeeTrack::raiseLocalFee() localTxnLoadFee_ = std::max(localTxnLoadFee_, remoteTxnLoadFee_); // Increase slowly - localTxnLoadFee_ += (localTxnLoadFee_ / kLftFeeIncFraction); + localTxnLoadFee_ += (localTxnLoadFee_ / kLFT_FEE_INC_FRACTION); - localTxnLoadFee_ = std::min(localTxnLoadFee_, kLftFeeMax); + localTxnLoadFee_ = std::min(localTxnLoadFee_, kLFT_FEE_MAX); if (origFee == localTxnLoadFee_) return false; @@ -46,9 +46,9 @@ LoadFeeTrack::lowerLocalFee() raiseCount_ = 0; // Reduce slowly - localTxnLoadFee_ -= (localTxnLoadFee_ / kLftFeeDecFraction); + localTxnLoadFee_ -= (localTxnLoadFee_ / kLFT_FEE_DEC_FRACTION); - localTxnLoadFee_ = std::max(localTxnLoadFee_, kLftNormalFee); + localTxnLoadFee_ = std::max(localTxnLoadFee_, kLFT_NORMAL_FEE); if (origFee == localTxnLoadFee_) return false; diff --git a/src/libxrpl/server/Manifest.cpp b/src/libxrpl/server/Manifest.cpp index b26c67e531..fd38d02d6b 100644 --- a/src/libxrpl/server/Manifest.cpp +++ b/src/libxrpl/server/Manifest.cpp @@ -62,7 +62,7 @@ deserializeManifest(Slice s, beast::Journal journal) if (s.empty()) return std::nullopt; - static SOTemplate const kManifestFormat{ + static SOTemplate const kMANIFEST_FORMAT{ // A manifest must include: // - the master public key {sfPublicKey, SoeRequired}, @@ -90,9 +90,9 @@ deserializeManifest(Slice s, beast::Journal journal) try { SerialIter sit{s}; - STObject st{sit, sfGeneric}; + STObject st{sit, kSF_GENERIC}; - st.applyTemplate(kManifestFormat); + st.applyTemplate(kMANIFEST_FORMAT); // We only understand "version 0" manifests at this time: if (st.isFieldPresent(sfVersion) && st.getFieldU16(sfVersion) != 0) @@ -193,7 +193,7 @@ logMftAct( bool Manifest::verify() const { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); @@ -213,7 +213,7 @@ Manifest::verify() const uint256 Manifest::hash() const { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); return st.getHash(HashPrefix::Manifest); @@ -240,7 +240,7 @@ Manifest::revoked(std::uint32_t sequence) std::optional Manifest::getSignature() const { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); if (!get(st, sfSignature)) @@ -251,7 +251,7 @@ Manifest::getSignature() const Blob Manifest::getMasterSignature() const { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); return st.getFieldVL(sfMasterSignature); diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 00c10b2b55..228b65df43 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -44,30 +44,30 @@ operator<<(std::ostream& os, Port const& p) { os << "'" << p.name << "' (ip=" << p.ip << ":" << p.port << ", "; - if (!p.adminNetsV4.empty() || !p.adminNetsV6.empty()) + if (!p.admin_nets_v4.empty() || !p.admin_nets_v6.empty()) { os << "admin nets:"; - for (auto const& net : p.adminNetsV4) + for (auto const& net : p.admin_nets_v4) { os << net.to_string(); os << ", "; } - for (auto const& net : p.adminNetsV6) + for (auto const& net : p.admin_nets_v6) { os << net.to_string(); os << ", "; } } - if (!p.secureGatewayNetsV4.empty() || !p.secureGatewayNetsV6.empty()) + if (!p.secure_gateway_nets_v4.empty() || !p.secure_gateway_nets_v6.empty()) { - os << "secure_gateway nets:"; - for (auto const& net : p.secureGatewayNetsV4) + os << "secureGateway nets:"; + for (auto const& net : p.secure_gateway_nets_v4) { os << net.to_string(); os << ", "; } - for (auto const& net : p.secureGatewayNetsV6) + for (auto const& net : p.secure_gateway_nets_v6) { os << net.to_string(); os << ", "; @@ -265,10 +265,10 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) { try { - port.wsQueueLimit = beast::lexicalCastThrow(*optResult); + port.ws_queue_limit = beast::lexicalCastThrow(*optResult); // Queue must be greater than 0 - if (port.wsQueueLimit == 0) + if (port.ws_queue_limit == 0) Throw(); } catch (std::exception const&) @@ -281,31 +281,32 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) else { // Default Websocket send queue size limit - port.wsQueueLimit = 100; + port.ws_queue_limit = 100; } } - populate(section, "admin", log, port.adminNetsV4, port.adminNetsV6); - populate(section, "secure_gateway", log, port.secureGatewayNetsV4, port.secureGatewayNetsV6); + populate(section, "admin", log, port.admin_nets_v4, port.admin_nets_v6); + populate( + section, "secureGateway", log, port.secure_gateway_nets_v4, port.secure_gateway_nets_v6); set(port.user, "user", section); set(port.password, "password", section); - set(port.adminUser, "admin_user", section); - set(port.adminPassword, "admin_password", section); - set(port.sslKey, "ssl_key", section); - set(port.sslCert, "ssl_cert", section); - set(port.sslChain, "ssl_chain", section); - set(port.sslCiphers, "ssl_ciphers", section); + set(port.admin_user, "admin_user", section); + set(port.admin_password, "admin_password", section); + set(port.ssl_key, "ssl_key", section); + set(port.ssl_cert, "ssl_cert", section); + set(port.ssl_chain, "ssl_chain", section); + set(port.ssl_ciphers, "ssl_ciphers", section); - port.pmdOptions.server_enable = section.valueOr("permessage_deflate", true); - port.pmdOptions.client_max_window_bits = section.valueOr("client_max_window_bits", 15); - port.pmdOptions.server_max_window_bits = section.valueOr("server_max_window_bits", 15); - port.pmdOptions.client_no_context_takeover = + port.pmd_options.server_enable = section.valueOr("permessage_deflate", true); + port.pmd_options.client_max_window_bits = section.valueOr("client_max_window_bits", 15); + port.pmd_options.server_max_window_bits = section.valueOr("server_max_window_bits", 15); + port.pmd_options.client_no_context_takeover = section.valueOr("client_no_context_takeover", false); - port.pmdOptions.server_no_context_takeover = + port.pmd_options.server_no_context_takeover = section.valueOr("server_no_context_takeover", false); - port.pmdOptions.compLevel = section.valueOr("compress_level", 8); - port.pmdOptions.memLevel = section.valueOr("memory_level", 4); + port.pmd_options.compLevel = section.valueOr("compress_level", 8); + port.pmd_options.memLevel = section.valueOr("memory_level", 4); } } // namespace xrpl diff --git a/src/libxrpl/server/State.cpp b/src/libxrpl/server/State.cpp index b9cb7c6ff2..3d2ed37e98 100644 --- a/src/libxrpl/server/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -5,7 +5,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include diff --git a/src/libxrpl/server/Vacuum.cpp b/src/libxrpl/server/Vacuum.cpp index 63d40af156..140ef04def 100644 --- a/src/libxrpl/server/Vacuum.cpp +++ b/src/libxrpl/server/Vacuum.cpp @@ -20,7 +20,7 @@ namespace xrpl { bool doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) { - boost::filesystem::path const dbPath = setup.dataDir / kTxDbName; + boost::filesystem::path const dbPath = setup.dataDir / kTX_DB_NAME; uintmax_t const dbSize = file_size(dbPath); XRPL_ASSERT(dbSize != static_cast(-1), "xrpl::doVacuumDB : file_size succeeded"); @@ -34,14 +34,14 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) return false; } - auto txnDB = std::make_unique(setup, kTxDbName, setup.txPragma, kTxDbInit, j); + auto txnDB = std::make_unique(setup, kTX_DB_NAME, setup.txPragma, kTX_DB_INIT, j); auto& session = txnDB->getSession(); std::uint32_t pageSize = 0; // Only the most trivial databases will fit in memory on typical // (recommended) hardware. Force temp files to be written to disk // regardless of the config settings. - session << boost::format(kCommonDbPragmaTemp) % "file"; + session << boost::format(kCOMMON_DB_PRAGMA_TEMP) % "file"; session << "PRAGMA page_size;", soci::into(pageSize); std::cout << "VACUUM beginning. page_size: " << pageSize << std::endl; diff --git a/src/libxrpl/server/Wallet.cpp b/src/libxrpl/server/Wallet.cpp index f3ae9dc925..ee579c7b9f 100644 --- a/src/libxrpl/server/Wallet.cpp +++ b/src/libxrpl/server/Wallet.cpp @@ -17,7 +17,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include @@ -40,7 +40,7 @@ makeWalletDB(DatabaseCon::Setup const& setup, beast::Journal j) { // wallet database return std::make_unique( - setup, kWalletDbName, std::array(), kWalletDbInit, j); + setup, kWALLET_DB_NAME, std::array(), kWALLET_DB_INIT, j); } std::unique_ptr @@ -48,7 +48,7 @@ makeTestWalletDB(DatabaseCon::Setup const& setup, std::string const& dbname, bea { // wallet database return std::make_unique( - setup, dbname.data(), std::array(), kWalletDbInit, j); + setup, dbname.data(), std::array(), kWALLET_DB_INIT, j); } void diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index d3a7d49da6..795c097118 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -169,7 +169,7 @@ intr_ptr::SharedPtr SHAMap::fetchNodeFromDB(SHAMapHash const& hash) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::fetchNodeFromDB : is backed"); - auto obj = f_.db().fetchNodeObject(hash.asUInt256(), ledgerSeq_); + auto obj = f_.db().fetchNodeObject(hash.asUint256(), ledgerSeq_); return finishFetch(hash, obj); } @@ -185,7 +185,7 @@ SHAMap::finishFetch(SHAMapHash const& hash, std::shared_ptr const& o if (full_) { full_ = false; - f_.missingNodeAcquireBySeq(ledgerSeq_, hash.asUInt256()); + f_.missingNodeAcquireBySeq(ledgerSeq_, hash.asUint256()); } return {}; } @@ -352,7 +352,7 @@ SHAMap::descend( { XRPL_ASSERT(parent->isInner(), "xrpl::SHAMap::descend : valid parent input"); XRPL_ASSERT( - (branch >= 0) && (branch < kBranchFactor), "xrpl::SHAMap::descend : valid branch input"); + (branch >= 0) && (branch < kBRANCH_FACTOR), "xrpl::SHAMap::descend : valid branch input"); XRPL_ASSERT( !parent->isEmptyBranch(branch), "xrpl::SHAMap::descend : parent branch is non-empty"); @@ -398,7 +398,7 @@ SHAMap::descendAsync( if (!ptr && backed_) { f_.db().asyncFetch( - hash.asUInt256(), + hash.asUint256(), ledgerSeq_, [this, hash, cb{std::move(callback)}](std::shared_ptr const& object) { auto node = finishFetch(hash, object); @@ -443,7 +443,7 @@ SHAMap::belowHelper( if (node->isLeaf()) { auto n = intr_ptr::staticPointerCast(node); - stack.push({node, {kLeafDepth, n->peekItem()->key()}}); + stack.push({node, {kLEAF_DEPTH, n->peekItem()->key()}}); return n.get(); } auto inner = intr_ptr::staticPointerCast(node); @@ -464,7 +464,7 @@ SHAMap::belowHelper( if (node->isLeaf()) { auto n = intr_ptr::staticPointerCast(node); - stack.push({n, {kLeafDepth, n->peekItem()->key()}}); + stack.push({n, {kLEAF_DEPTH, n->peekItem()->key()}}); return n.get(); } inner = intr_ptr::staticPointerCast(node); @@ -482,7 +482,7 @@ SHAMapLeafNode* SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) const { - auto init = kBranchFactor - 1; + auto init = kBRANCH_FACTOR - 1; auto cmp = [](int i) { return i >= 0; }; auto incr = [](int& i) { --i; }; @@ -493,12 +493,12 @@ SHAMap::firstBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& const { auto init = 0; - auto cmp = [](int i) { return i <= kBranchFactor; }; + auto cmp = [](int i) { return i <= kBRANCH_FACTOR; }; auto incr = [](int& i) { ++i; }; return belowHelper(node, stack, branch, {init, cmp, incr}); } -static boost::intrusive_ptr const kNoItem; +static boost::intrusive_ptr const kNO_ITEM; boost::intrusive_ptr const& SHAMap::onlyBelow(SHAMapTreeNode* node) const @@ -509,12 +509,12 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const { SHAMapTreeNode* nextNode = nullptr; auto inner = safeDowncast(node); - for (int i = 0; i < kBranchFactor; ++i) + for (int i = 0; i < kBRANCH_FACTOR; ++i) { if (!inner->isEmptyBranch(i)) { if (nextNode != nullptr) - return kNoItem; + return kNO_ITEM; nextNode = descendThrow(inner, i); } @@ -524,7 +524,7 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const { // LCOV_EXCL_START UNREACHABLE("xrpl::SHAMap::onlyBelow : no next node"); - return kNoItem; + return kNO_ITEM; // LCOV_EXCL_STOP } @@ -564,7 +564,7 @@ SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const auto [node, nodeID] = stack.top(); XRPL_ASSERT(!node->isLeaf(), "xrpl::SHAMap::peekNextItem : another node is not leaf"); auto inner = intr_ptr::staticPointerCast(node); - for (auto i = selectBranch(nodeID, id) + 1; i < kBranchFactor; ++i) + for (auto i = selectBranch(nodeID, id) + 1; i < kBRANCH_FACTOR; ++i) { if (!inner->isEmptyBranch(i)) { @@ -588,7 +588,7 @@ SHAMap::peekItem(uint256 const& id) const SHAMapLeafNode const* leaf = findKey(id); if (leaf == nullptr) - return kNoItem; + return kNO_ITEM; return leaf->peekItem(); } @@ -599,7 +599,7 @@ SHAMap::peekItem(uint256 const& id, SHAMapHash& hash) const SHAMapLeafNode const* leaf = findKey(id); if (leaf == nullptr) - return kNoItem; + return kNO_ITEM; hash = leaf->getHash(); return leaf->peekItem(); @@ -622,7 +622,7 @@ SHAMap::upperBound(uint256 const& id) const else { auto inner = intr_ptr::staticPointerCast(node); - for (auto branch = selectBranch(nodeID, id) + 1; branch < kBranchFactor; ++branch) + for (auto branch = selectBranch(nodeID, id) + 1; branch < kBRANCH_FACTOR; ++branch) { if (!inner->isEmptyBranch(branch)) { @@ -737,7 +737,7 @@ SHAMap::delItem(uint256 const& id) if (item) { - for (int i = 0; i < kBranchFactor; ++i) + for (int i = 0; i < kBRANCH_FACTOR; ++i) { if (!node->isEmptyBranch(i)) { @@ -947,7 +947,7 @@ SHAMap::writeNode(NodeObjectType t, intr_ptr::SharedPtr node) co Serializer s; node->serializeWithPrefix(s); - f_.db().store(t, std::move(s.modData()), node->getHash().asUInt256(), ledgerSeq_); + f_.db().store(t, std::move(s.modData()), node->getHash().asUint256(), ledgerSeq_); return node; } @@ -1027,7 +1027,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) // We can't flush an inner node until we flush its children while (true) { - while (pos < kBranchFactor) + while (pos < kBRANCH_FACTOR) { if (node->isEmptyBranch(pos)) { @@ -1131,7 +1131,7 @@ SHAMap::dump(bool hash) const if (node->isInner()) { auto inner = safeDowncast(node); - for (int i = 0; i < kBranchFactor; ++i) + for (int i = 0; i < kBRANCH_FACTOR; ++i) { if (!inner->isEmptyBranch(i)) { @@ -1158,7 +1158,7 @@ SHAMap::dump(bool hash) const intr_ptr::SharedPtr SHAMap::cacheLookup(SHAMapHash const& hash) const { - auto ret = f_.getTreeNodeCache()->fetch(hash.asUInt256()); + auto ret = f_.getTreeNodeCache()->fetch(hash.asUint256()); XRPL_ASSERT(!ret || !ret->cowid(), "xrpl::SHAMap::cacheLookup : not found or zero cowid"); return ret; } @@ -1170,7 +1170,7 @@ SHAMap::canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr 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()->canonicalizeReplaceClient(hash.asUInt256(), node); + f_.getTreeNodeCache()->canonicalizeReplaceClient(hash.asUint256(), node); } void diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index f31b75ad39..a0adc10a61 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -122,18 +122,18 @@ intr_ptr::SharedPtr 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() != kBranchFactor * uint256::kBytes) + if (data.size() != kBRANCH_FACTOR * uint256::kBYTES) Throw("Invalid FI node"); - auto ret = intr_ptr::makeShared(0, kBranchFactor); + auto ret = intr_ptr::makeShared(0, kBRANCH_FACTOR); SerialIter si(data); auto hashes = ret->hashesAndChildren_.getHashes(); - for (int i = 0; i < kBranchFactor; ++i) + for (int i = 0; i < kBRANCH_FACTOR; ++i) { - hashes[i].asUInt256() = si.getBitString<256>(); + hashes[i].asUint256() = si.getBitString<256>(); if (hashes[i].isNonZero()) ret->isBranch_ |= (1 << i); @@ -158,14 +158,14 @@ SHAMapInnerNode::makeCompressedInner(Slice data) { // A compressed inner node is serialized as a series of 33 byte chunks, // representing a one byte "position" and a 256-bit hash: - static constexpr std::size_t kChunkSize = uint256::kBytes + 1; + constexpr std::size_t kCHUNK_SIZE = uint256::kBYTES + 1; - if (auto const s = data.size(); (s % kChunkSize != 0) || (s > kChunkSize * kBranchFactor)) + if (auto const s = data.size(); (s % kCHUNK_SIZE != 0) || (s > kCHUNK_SIZE * kBRANCH_FACTOR)) Throw("Invalid CI node"); SerialIter si(data); - auto ret = intr_ptr::makeShared(0, kBranchFactor); + auto ret = intr_ptr::makeShared(0, kBRANCH_FACTOR); auto hashes = ret->hashesAndChildren_.getHashes(); @@ -174,10 +174,10 @@ SHAMapInnerNode::makeCompressedInner(Slice data) auto const hash = si.getBitString<256>(); auto const pos = si.get8(); - if (pos >= kBranchFactor) + if (pos >= kBRANCH_FACTOR) Throw("invalid CI node"); - hashes[pos].asUInt256() = hash; + hashes[pos].asUint256() = hash; if (hashes[pos].isNonZero()) ret->isBranch_ |= (1 << pos); @@ -228,15 +228,15 @@ SHAMapInnerNode::serializeForWire(Serializer& s) const // compressed node auto hashes = hashesAndChildren_.getHashes(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { - s.addBitString(hashes[indexNum].asUInt256()); + s.addBitString(hashes[indexNum].asUint256()); s.add8(branchNum); }); - s.add8(kWireTypeCompressedInner); + s.add8(kWIRE_TYPE_COMPRESSED_INNER); } else { - iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.asUInt256()); }); - s.add8(kWireTypeInner); + iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.asUint256()); }); + s.add8(kWIRE_TYPE_INNER); } } @@ -246,7 +246,7 @@ SHAMapInnerNode::serializeWithPrefix(Serializer& s) const XRPL_ASSERT(!isEmpty(), "xrpl::SHAMapInnerNode::serializeWithPrefix : is non-empty"); s.add32(HashPrefix::InnerNode); - iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.asUInt256()); }); + iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.asUint256()); }); } std::string @@ -268,7 +268,7 @@ void SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) { XRPL_ASSERT( - (m >= 0) && (m < kBranchFactor), "xrpl::SHAMapInnerNode::setChild : valid branch input"); + (m >= 0) && (m < kBRANCH_FACTOR), "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"); @@ -310,7 +310,7 @@ void SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& child) { XRPL_ASSERT( - (m >= 0) && (m < kBranchFactor), "xrpl::SHAMapInnerNode::shareChild : valid branch input"); + (m >= 0) && (m < kBRANCH_FACTOR), "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"); @@ -324,7 +324,7 @@ SHAMapTreeNode* SHAMapInnerNode::getChildPointer(int branch) { XRPL_ASSERT( - branch >= 0 && branch < kBranchFactor, + branch >= 0 && branch < kBRANCH_FACTOR, "xrpl::SHAMapInnerNode::getChildPointer : valid branch input"); XRPL_ASSERT( !isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); @@ -341,7 +341,7 @@ intr_ptr::SharedPtr SHAMapInnerNode::getChild(int branch) { XRPL_ASSERT( - branch >= 0 && branch < kBranchFactor, + branch >= 0 && branch < kBRANCH_FACTOR, "xrpl::SHAMapInnerNode::getChild : valid branch input"); XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChild : non-empty branch input"); @@ -357,19 +357,19 @@ SHAMapHash const& SHAMapInnerNode::getChildHash(int m) const { XRPL_ASSERT( - (m >= 0) && (m < kBranchFactor), + (m >= 0) && (m < kBRANCH_FACTOR), "xrpl::SHAMapInnerNode::getChildHash : valid branch input"); if (auto const i = getChildIndex(m)) return hashesAndChildren_.getHashes()[*i]; - return kZeroShaMapHash; + return kZERO_SHA_MAP_HASH; } intr_ptr::SharedPtr SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtr node) { XRPL_ASSERT( - branch >= 0 && branch < kBranchFactor, + branch >= 0 && branch < kBRANCH_FACTOR, "xrpl::SHAMapInnerNode::canonicalizeChild : valid branch input"); XRPL_ASSERT(node != nullptr, "xrpl::SHAMapInnerNode::canonicalizeChild : valid node input"); XRPL_ASSERT( @@ -405,7 +405,7 @@ SHAMapInnerNode::invariants(bool isRoot) const [[maybe_unused]] unsigned count = 0; auto [numAllocated, hashes, children] = hashesAndChildren_.getHashesAndChildren(); - if (numAllocated != kBranchFactor) + if (numAllocated != kBRANCH_FACTOR) { auto const branchCount = getBranchCount(); for (int i = 0; i < branchCount; ++i) @@ -420,7 +420,7 @@ SHAMapInnerNode::invariants(bool isRoot) const } else { - for (int i = 0; i < kBranchFactor; ++i) + for (int i = 0; i < kBRANCH_FACTOR; ++i) { if (hashes[i].isNonZero()) { diff --git a/src/libxrpl/shamap/SHAMapLeafNode.cpp b/src/libxrpl/shamap/SHAMapLeafNode.cpp index 2fc23d6bb3..ce41a64e56 100644 --- a/src/libxrpl/shamap/SHAMapLeafNode.cpp +++ b/src/libxrpl/shamap/SHAMapLeafNode.cpp @@ -19,7 +19,7 @@ SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr item, std: : SHAMapTreeNode(cowid), item_(std::move(item)) { XRPL_ASSERT( - item_->size() >= kMinShaMapItemBytes, + item_->size() >= 12, "xrpl::SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr<" "SHAMapItem const>, std::uint32_t) : minimum input size"); } @@ -31,7 +31,7 @@ SHAMapLeafNode::SHAMapLeafNode( : SHAMapTreeNode(cowid, hash), item_(std::move(item)) { XRPL_ASSERT( - item_->size() >= kMinShaMapItemBytes, + item_->size() >= 12, "xrpl::SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr<" "SHAMapItem const>, std::uint32_t, SHAMapHash const&) : minimum input " "size"); diff --git a/src/libxrpl/shamap/SHAMapNodeID.cpp b/src/libxrpl/shamap/SHAMapNodeID.cpp index 16aaafe709..f7caf8ae02 100644 --- a/src/libxrpl/shamap/SHAMapNodeID.cpp +++ b/src/libxrpl/shamap/SHAMapNodeID.cpp @@ -16,35 +16,37 @@ namespace xrpl { static uint256 const& depthMask(unsigned int depth) { - static constexpr auto kMaskSize = 65; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { MaskSize = 65 }; struct MasksT { - uint256 entry[kMaskSize]; + uint256 entry[MaskSize]; MasksT() { uint256 selector; - for (int i = 0; i < kMaskSize - 1; i += 2) + for (int i = 0; i < MaskSize - 1; i += 2) { entry[i] = selector; *(selector.begin() + (i / 2)) = 0xF0; entry[i + 1] = selector; *(selector.begin() + (i / 2)) = 0xFF; } - entry[kMaskSize - 1] = selector; + entry[MaskSize - 1] = selector; } }; - static MasksT const kMasks; - return kMasks.entry[depth]; + static MasksT const kMASKS; + return kMASKS.entry[depth]; } // canonicalize the hash to a node ID for this depth SHAMapNodeID::SHAMapNodeID(unsigned int depth, uint256 const& hash) : id_(hash), depth_(depth) { XRPL_ASSERT( - depth <= SHAMap::kLeafDepth, "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); + depth <= SHAMap::kLEAF_DEPTH, "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); XRPL_ASSERT( id_ == (id_ & depthMask(depth)), "xrpl::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); @@ -63,7 +65,7 @@ SHAMapNodeID SHAMapNodeID::getChildNodeID(unsigned int m) const { XRPL_ASSERT( - m < SHAMap::kBranchFactor, "xrpl::SHAMapNodeID::getChildNodeID : valid branch input"); + m < SHAMap::kBRANCH_FACTOR, "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 @@ -74,9 +76,9 @@ SHAMapNodeID::getChildNodeID(unsigned int m) const // 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::kLeafDepth, "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); + depth_ <= SHAMap::kLEAF_DEPTH, "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); - if (depth_ >= SHAMap::kLeafDepth) + if (depth_ >= SHAMap::kLEAF_DEPTH) Throw("Request for child node ID of " + to_string(*this)); if (id_ != (id_ & depthMask(depth_))) @@ -95,7 +97,7 @@ deserializeSHAMapNodeID(void const* data, std::size_t size) if (size == 33) { unsigned int const depth = *(static_cast(data) + 32); - if (depth <= SHAMap::kLeafDepth) + if (depth <= SHAMap::kLEAF_DEPTH) { auto const id = uint256::fromVoid(data); @@ -122,7 +124,7 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) branch >>= 4; } - XRPL_ASSERT(branch < SHAMap::kBranchFactor, "xrpl::selectBranch : maximum result"); + XRPL_ASSERT(branch < SHAMap::kBRANCH_FACTOR, "xrpl::selectBranch : maximum result"); return branch; } diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index cd2654c603..348928f863 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -196,7 +196,7 @@ SHAMap::gmnProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) // we already know this child node is missing fullBelow = false; } - else if (!backed_ || !f_.getFullBelowCache()->touchIfExists(childHash.asUInt256())) + else if (!backed_ || !f_.getFullBelowCache()->touchIfExists(childHash.asUint256())) { bool pending = false; auto d = descendAsync( @@ -223,7 +223,7 @@ SHAMap::gmnProcessNodes(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.asUInt256()); + mn.missingNodes.emplace_back(nodeID.getChildNodeID(branch), childHash.asUint256()); if (--mn.max <= 0) return; @@ -250,7 +250,7 @@ SHAMap::gmnProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) node->setFullBelowGen(mn.generation); if (backed_) { - f_.getFullBelowCache()->insert(node->getHash().asUInt256()); + f_.getFullBelowCache()->insert(node->getHash().asUint256()); } } @@ -292,7 +292,7 @@ SHAMap::gmnProcessDeferredReads(MissingNodes& mn) } else if ((mn.max > 0) && (mn.missingHashes.insert(nodeHash).second)) { - mn.missingNodes.emplace_back(parentID.getChildNodeID(branch), nodeHash.asUInt256()); + mn.missingNodes.emplace_back(parentID.getChildNodeID(branch), nodeHash.asUint256()); --mn.max; } } @@ -572,7 +572,7 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF } auto childHash = inner->getChildHash(branch); - if (f_.getFullBelowCache()->touchIfExists(childHash.asUInt256())) + if (f_.getFullBelowCache()->touchIfExists(childHash.asUint256())) { return SHAMapAddNode::duplicate(); } @@ -615,8 +615,8 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF // Inner nodes must be at a level strictly less than 64 // but leaf nodes (while notionally at level 64) can be // at any depth up to and including 64: - if ((currNodeID.getDepth() > kLeafDepth) || - (newNode->isInner() && currNodeID.getDepth() == kLeafDepth)) + if ((currNodeID.getDepth() > kLEAF_DEPTH) || + (newNode->isInner() && currNodeID.getDepth() == kLEAF_DEPTH)) { // Map is provably invalid state_ = SHAMapState::Invalid; diff --git a/src/libxrpl/shamap/SHAMapTreeNode.cpp b/src/libxrpl/shamap/SHAMapTreeNode.cpp index 3b8d976c69..ac405f3286 100644 --- a/src/libxrpl/shamap/SHAMapTreeNode.cpp +++ b/src/libxrpl/shamap/SHAMapTreeNode.cpp @@ -28,13 +28,6 @@ namespace xrpl { intr_ptr::SharedPtr SHAMapTreeNode::makeTransaction(Slice data, SHAMapHash const& hash, bool hashValid) { - if (data.size() < kMinShaMapItemBytes) - { - Throw( - "Short TXN node: " + std::to_string(data.size()) + " bytes (minimum " + - std::to_string(kMinShaMapItemBytes) + " required)"); - } - auto item = makeShamapitem(sha512Half(HashPrefix::TransactionId, data), data); if (hashValid) @@ -50,30 +43,14 @@ SHAMapTreeNode::makeTransactionWithMeta(Slice data, SHAMapHash const& hash, bool uint256 tag; - if (s.size() < tag.kBytes) - { - Throw( - "Short TXN+MD node: " + std::to_string(s.size()) + " bytes (minimum " + - std::to_string(tag.kBytes) + " required for tag)"); - } + if (s.size() < tag.kBYTES) + Throw("Short TXN+MD node"); // FIXME: improve this interface so that the above check isn't needed - if (!s.getBitString(tag, s.size() - tag.kBytes)) - { - Throw( - "Short TXN+MD node: failed to read tag at offset " + - std::to_string(s.size() - tag.kBytes)); - } + if (!s.getBitString(tag, s.size() - tag.kBYTES)) + Throw("Short TXN+MD node (" + std::to_string(s.size()) + ")"); - s.chop(tag.kBytes); - - if (s.size() < kMinShaMapItemBytes) - { - Throw( - "Short TXN+MD node: " + std::to_string(s.size()) + - " bytes after tag removal (minimum " + std::to_string(kMinShaMapItemBytes) + - " required)"); - } + s.chop(tag.kBYTES); auto item = makeShamapitem(tag, s.slice()); @@ -90,32 +67,18 @@ SHAMapTreeNode::makeAccountState(Slice data, SHAMapHash const& hash, bool hashVa uint256 tag; - if (s.size() < tag.kBytes) - { - Throw( - "Short AS node: " + std::to_string(s.size()) + " bytes (minimum " + - std::to_string(tag.kBytes) + " required for tag)"); - } + if (s.size() < tag.kBYTES) + Throw("short AS node"); // FIXME: improve this interface so that the above check isn't needed - if (!s.getBitString(tag, s.size() - tag.kBytes)) - { - Throw( - "Short AS node: failed to read tag at offset " + std::to_string(s.size() - tag.kBytes)); - } + if (!s.getBitString(tag, s.size() - tag.kBYTES)) + Throw("Short AS node (" + std::to_string(s.size()) + ")"); - s.chop(tag.kBytes); + s.chop(tag.kBYTES); if (tag.isZero()) Throw("Invalid AS node"); - if (s.size() < kMinShaMapItemBytes) - { - Throw( - "Short AS node: " + std::to_string(s.size()) + " bytes after tag removal (minimum " + - std::to_string(kMinShaMapItemBytes) + " required)"); - } - auto item = makeShamapitem(tag, s.slice()); if (hashValid) @@ -137,19 +100,19 @@ SHAMapTreeNode::makeFromWire(Slice rawNode) bool const hashValid = false; SHAMapHash const hash; - if (type == kWireTypeTransaction) + if (type == kWIRE_TYPE_TRANSACTION) return makeTransaction(rawNode, hash, hashValid); - if (type == kWireTypeAccountState) + if (type == kWIRE_TYPE_ACCOUNT_STATE) return makeAccountState(rawNode, hash, hashValid); - if (type == kWireTypeInner) + if (type == kWIRE_TYPE_INNER) return SHAMapInnerNode::makeFullInner(rawNode, hash, hashValid); - if (type == kWireTypeCompressedInner) + if (type == kWIRE_TYPE_COMPRESSED_INNER) return SHAMapInnerNode::makeCompressedInner(rawNode); - if (type == kWireTypeTransactionWithMeta) + if (type == kWIRE_TYPE_TRANSACTION_WITH_META) return makeTransactionWithMeta(rawNode, hash, hashValid); Throw("wire: Unknown type (" + std::to_string(type) + ")"); diff --git a/src/libxrpl/tx/ApplyContext.cpp b/src/libxrpl/tx/ApplyContext.cpp index 93b0d101af..94d35cf5d9 100644 --- a/src/libxrpl/tx/ApplyContext.cpp +++ b/src/libxrpl/tx/ApplyContext.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -69,7 +70,11 @@ ApplyContext::size() void ApplyContext::visit( - std::function const& func) + std::function const&, + std::shared_ptr const&)> const& func) { view_->visit(base_, func); // NOLINT(bugprone-unchecked-optional-access) } @@ -99,11 +104,13 @@ ApplyContext::checkInvariantsHelper( auto checkers = getInvariantChecks(); // call each check's per-entry method - visit( - [&checkers]( - uint256 const& index, bool isDelete, SLE::const_ref before, SLE::const_ref after) { - (..., std::get(checkers).visitEntry(isDelete, before, after)); - }); + visit([&checkers]( + uint256 const& index, + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { + (..., std::get(checkers).visitEntry(isDelete, before, after)); + }); // Note: do not replace this logic with a `...&&` fold expression. // The fold expression will only run until the first check fails (it @@ -117,7 +124,7 @@ ApplyContext::checkInvariantsHelper( if (!std::all_of(finalizers.cbegin(), finalizers.cend(), [](auto const& b) { return b; })) { JLOG(journal.fatal()) << "Transaction has failed one or more global invariants: " - << to_string(tx.getJson(JsonOptions::Values::None)); + << to_string(tx.getJson(JsonOptions::KNone)); return failInvariantCheck(result); } @@ -126,7 +133,7 @@ ApplyContext::checkInvariantsHelper( { JLOG(journal.fatal()) << "Transaction caused an exception in a global invariant" << ", ex: " << ex.what() - << ", tx: " << to_string(tx.getJson(JsonOptions::Values::None)); + << ", tx: " << to_string(tx.getJson(JsonOptions::KNone)); return failInvariantCheck(result); } diff --git a/src/libxrpl/tx/SignerEntries.cpp b/src/libxrpl/tx/SignerEntries.cpp index 7251b8260f..d425c86ca6 100644 --- a/src/libxrpl/tx/SignerEntries.cpp +++ b/src/libxrpl/tx/SignerEntries.cpp @@ -28,7 +28,7 @@ SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::str } std::vector accountVec; - accountVec.reserve(STTx::kMaxMultiSigners); + accountVec.reserve(STTx::kMAX_MULTI_SIGNERS); STArray const& sEntries(obj.getFieldArray(sfSignerEntries)); for (STObject const& sEntry : sEntries) diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 51541cc2e3..79dec33c66 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include // IWYU pragma: keep @@ -45,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -89,7 +89,7 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) auto const txID = ctx.tx.getTransactionID(); - if (txID == beast::kZero) + if (txID == beast::kZERO) { JLOG(ctx.j.warn()) << "applyTransaction: transaction id may not be zero"; return temINVALID; @@ -182,7 +182,7 @@ Transactor::preflight1(PreflightContext const& ctx, std::uint32_t flagMask) return ret; auto const id = ctx.tx.getAccountID(sfAccount); - if (id == beast::kZero) + if (id == beast::kZERO) { JLOG(ctx.j.warn()) << "preflight1: bad account id"; return temBAD_SRC_ACCOUNT; @@ -256,22 +256,13 @@ Transactor::preflight2(PreflightContext const& ctx) return tesSUCCESS; } -NotTEC -Transactor::preflightUniversal(PreflightContext const& ctx) -{ - if (ctx.rules.enabled(fixCleanup3_2_0) && hasInvalidAmount(ctx.tx, ctx.j)) - return temBAD_AMOUNT; - - return tesSUCCESS; -} - //------------------------------------------------------------------------------ Transactor::Transactor(ApplyContext& ctx) : ctx_(ctx) , sink_(ctx.journal, toShortString(ctx.tx.getTransactionID()) + " ") , j_(sink_) - , accountID_(ctx.tx.getAccountID(sfAccount)) + , account_(ctx.tx.getAccountID(sfAccount)) { } @@ -370,14 +361,14 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) if ((ctx.flags & TapBatch) != 0u) { - if (feePaid == beast::kZero) + if (feePaid == beast::kZERO) return tesSUCCESS; JLOG(ctx.j.trace()) << "Batch: Fee must be zero."; return temBAD_FEE; // LCOV_EXCL_LINE } - if (!isLegalAmount(feePaid) || feePaid < beast::kZero) + if (!isLegalAmount(feePaid) || feePaid < beast::kZERO) return temBAD_FEE; // Only check fee is sufficient when the ledger is open. @@ -393,7 +384,7 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) } } - if (feePaid == beast::kZero) + if (feePaid == beast::kZERO) return tesSUCCESS; auto const id = ctx.tx.getFeePayer(); @@ -415,7 +406,7 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) JLOG(ctx.j.trace()) << "Insufficient balance:" << " balance=" << to_string(balance) << " paid=" << to_string(feePaid); - if ((balance > beast::kZero) && !ctx.view.open()) + if ((balance > beast::kZERO) && !ctx.view.open()) { // Closed ledger, non-zero balance, less than fee return tecINSUFF_FEE; @@ -440,7 +431,7 @@ Transactor::payFee() // Deduct the fee, so it's not available during the transaction. // Will only write the account back if the transaction succeeds. sle->setFieldAmount(sfBalance, sle->getFieldAmount(sfBalance) - feePaid); - if (feePayer != accountID_) + if (feePayer != account_) view().update(sle); // done in `apply()` for the account // VFALCO Should we call view().rawDestroyXRP() here as well? @@ -501,7 +492,7 @@ Transactor::checkSeqProxy(ReadView const& view, STTx const& tx, beast::Journal j } // Transaction can never succeed if the Ticket is not in the ledger. - if (!view.exists(keylet::kTicket(id, tSeqProx))) + if (!view.exists(keylet::kTICKET(id, tSeqProx))) { JLOG(j.trace()) << "applyTransaction: ticket already used or never created " << "a_seq=" << aSeq << " t_seq=" << tSeqProx; @@ -553,7 +544,7 @@ Transactor::consumeSeqProxy(SLE::pointer const& sleAccount) sleAccount->setFieldU32(sfSequence, seqProx.value() + 1); return tesSUCCESS; } - return ticketDelete(view(), accountID_, getTicketIndex(accountID_, seqProx), j_); + return ticketDelete(view(), account_, getTicketIndex(account_, seqProx), j_); } // Remove a single Ticket from the ledger. @@ -566,7 +557,7 @@ Transactor::ticketDelete( { // Delete the Ticket, adjust the account root ticket count, and // reduce the owner count. - SLE::pointer const sleTicket = view.peek(keylet::kTicket(ticketIndex)); + SLE::pointer const sleTicket = view.peek(keylet::kTICKET(ticketIndex)); if (!sleTicket) { // LCOV_EXCL_START @@ -626,7 +617,7 @@ Transactor::ticketDelete( void Transactor::preCompute() { - XRPL_ASSERT(accountID_ != beast::kZero, "xrpl::Transactor::preCompute : nonzero account"); + XRPL_ASSERT(account_ != beast::kZERO, "xrpl::Transactor::preCompute : nonzero account"); } TER @@ -636,12 +627,12 @@ Transactor::apply() // If the transactor requires a valid account and the transaction doesn't // list one, preflight will have already a flagged a failure. - auto const sle = view().peek(keylet::account(accountID_)); + auto const sle = view().peek(keylet::account(account_)); // sle must exist except for transactions // that allow zero account. XRPL_ASSERT( - sle != nullptr || accountID_ == beast::kZero, + sle != nullptr || account_ == beast::kZERO, "xrpl::Transactor::apply : non-null SLE or zero account"); if (sle) @@ -788,7 +779,7 @@ Transactor::checkSingleSign( ReadView const& view, AccountID const& idSigner, AccountID const& idAccount, - SLE::const_pointer sleAccount, + std::shared_ptr sleAccount, beast::Journal const j) { bool const isMasterDisabled = sleAccount->isFlag(lsfDisableMaster); @@ -824,7 +815,7 @@ Transactor::checkMultiSign( beast::Journal const j) { // Get id's SignerList and Quorum. - STLedgerEntry::const_pointer const sleAccountSigners = view.read(keylet::signers(id)); + std::shared_ptr const sleAccountSigners = view.read(keylet::signers(id)); // If the signer list doesn't exist the account is not multi-signing. if (!sleAccountSigners) { @@ -988,7 +979,7 @@ removeUnfundedOffers(ApplyView& view, std::vector const& offers, beast: { // offer is unfunded offerDelete(view, sleOffer, viewJ); - if (++removed == kUnfundedOfferRemoveLimit) + if (++removed == kUNFUNDED_OFFER_REMOVE_LIMIT) return; } } @@ -1007,7 +998,7 @@ removeExpiredNFTokenOffers( if (auto const offer = view.peek(keylet::nftoffer(index))) { nft::deleteTokenOffer(view, offer); - if (++removed == kExpiredOfferRemoveLimit) + if (++removed == kEXPIRED_OFFER_REMOVE_LIMIT) return; } } @@ -1019,14 +1010,7 @@ removeExpiredCredentials(ApplyView& view, std::vector const& creds, bea for (auto const& index : creds) { if (auto const sle = view.peek(keylet::credential(index))) - { - if (auto const ter = credentials::deleteSLE(view, sle, viewJ); !isTesSuccess(ter)) - { - JLOG(viewJ.error()) - << "removeExpiredCredentials: failed to delete expired credential. Err: " - << transToken(ter); - } - } + credentials::deleteSLE(view, sle, viewJ); } } @@ -1036,7 +1020,7 @@ removeDeletedTrustLines( std::vector const& trustLines, beast::Journal viewJ) { - if (trustLines.size() > kMaxDeletableAmmTrustLines) + if (trustLines.size() > kMAX_DELETABLE_AMM_TRUST_LINES) { JLOG(viewJ.error()) << "removeDeletedTrustLines: deleted trustlines exceed max " << trustLines.size(); @@ -1088,17 +1072,17 @@ Transactor::reset(XRPAmount fee) // The account should never be missing from the ledger. But if it // is missing then we can't very well charge it a fee, can we? if (!txnAcct) - return {tefINTERNAL, beast::kZero}; + return {tefINTERNAL, beast::kZERO}; auto const payerSle = view().peek(keylet::account(ctx_.tx.getFeePayer())); if (!payerSle) - return {tefINTERNAL, beast::kZero}; // LCOV_EXCL_LINE + return {tefINTERNAL, beast::kZERO}; // LCOV_EXCL_LINE auto const balance = payerSle->getFieldAmount(sfBalance).xrp(); // balance should have already been checked in checkFee / preFlight. XRPL_ASSERT( - balance != beast::kZero && (!view().open() || balance >= fee), + balance != beast::kZERO && (!view().open() || balance >= fee), "xrpl::Transactor::reset : valid balance"); // We retry/reject the transaction if the account balance is zero or @@ -1151,7 +1135,7 @@ Transactor::checkTransactionInvariants(TER result, XRPAmount fee) { JLOG(ctx_.journal.fatal()) << // "Transaction has failed one or more transaction invariants, tx: " << // - to_string(ctx_.tx.getJson(JsonOptions::Values::None)); + to_string(ctx_.tx.getJson(JsonOptions::KNone)); return tecINVARIANT_FAILED; } } @@ -1161,7 +1145,7 @@ Transactor::checkTransactionInvariants(TER result, XRPAmount fee) "Exception while checking transaction invariants: " << // ex.what() << // ", tx: " << // - to_string(ctx_.tx.getJson(JsonOptions::Values::None)); + to_string(ctx_.tx.getJson(JsonOptions::KNone)); return tecINVARIANT_FAILED; } @@ -1214,8 +1198,8 @@ Transactor::operator()() { // LCOV_EXCL_START JLOG(j_.fatal()) << "Transaction serdes mismatch"; - JLOG(j_.fatal()) << ctx_.tx.getJson(JsonOptions::Values::None); - JLOG(j_.fatal()) << s2.getJson(JsonOptions::Values::None); + JLOG(j_.fatal()) << ctx_.tx.getJson(JsonOptions::KNone); + JLOG(j_.fatal()) << s2.getJson(JsonOptions::KNone); UNREACHABLE("xrpl::Transactor::operator() : transaction serdes mismatch"); // LCOV_EXCL_STOP } @@ -1242,12 +1226,12 @@ Transactor::operator()() bool applied = isTesSuccess(result); auto fee = ctx_.tx.getFieldAmount(sfFee).xrp(); - if (ctx_.size() > kOversizeMetaDataCap) + if (ctx_.size() > kOVERSIZE_META_DATA_CAP) result = tecOVERSIZE; if (isTecClaim(result) && ((view().flags() & TapFailHard) != 0u)) { - // If the TapFailHard flag is set, a tec result + // If the tapFAIL_HARD flag is set, a tec result // must not do anything ctx_.discard(); applied = false; @@ -1285,8 +1269,8 @@ Transactor::operator()() &expiredCredentials]( uint256 const& index, bool isDelete, - SLE::const_ref before, - SLE::const_ref after) { + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete) { XRPL_ASSERT( @@ -1397,14 +1381,14 @@ Transactor::operator()() // The transactor and invariant checkers guarantee that this will // *never* trigger but if it, somehow, happens, don't allow a tx // that charges a negative fee. - if (fee < beast::kZero) + if (fee < beast::kZERO) Throw("fee charged is negative!"); // Charge whatever fee they specified. The fee has already been // deducted from the balance of the account that issued the // transaction. We just need to account for it in the ledger // header. - if (!view().open() && fee != beast::kZero) + if (!view().open() && fee != beast::kZERO) ctx_.destroyXRP(fee); // Once we call apply, we will no longer be able to look at view() diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index 0fc0275eb0..228d15778f 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -27,10 +27,10 @@ namespace xrpl { // These are the same flags defined as HashRouterFlags::PRIVATE1-4 in // HashRouter.h -constexpr HashRouterFlags kSfSigbad = HashRouterFlags::PRIVATE1; // Signature is bad -constexpr HashRouterFlags kSfSiggood = HashRouterFlags::PRIVATE2; // Signature is good -constexpr HashRouterFlags kSfLocalbad = HashRouterFlags::PRIVATE3; // Local checks failed -constexpr HashRouterFlags kSfLocalgood = HashRouterFlags::PRIVATE4; // Local checks passed +constexpr HashRouterFlags kSF_SIGBAD = HashRouterFlags::PRIVATE1; // Signature is bad +constexpr HashRouterFlags kSF_SIGGOOD = HashRouterFlags::PRIVATE2; // Signature is good +constexpr HashRouterFlags kSF_LOCALBAD = HashRouterFlags::PRIVATE3; // Local checks failed +constexpr HashRouterFlags kSF_LOCALGOOD = HashRouterFlags::PRIVATE4; // Local checks passed //------------------------------------------------------------------------------ @@ -57,41 +57,41 @@ checkValidity(HashRouter& router, STTx const& tx, Rules const& rules) std::string reason; if (!passesLocalChecks(tx, reason)) { - router.setFlags(id, kSfLocalbad); + router.setFlags(id, kSF_LOCALBAD); return {Validity::SigGoodOnly, reason}; } - router.setFlags(id, kSfSiggood); + router.setFlags(id, kSF_SIGGOOD); return {Validity::Valid, ""}; } } - if (any(flags & kSfSigbad)) + if (any(flags & kSF_SIGBAD)) { // Signature is known bad return {Validity::SigBad, "Transaction has bad signature."}; } - if (!any(flags & kSfSiggood)) + if (!any(flags & kSF_SIGGOOD)) { auto const sigVerify = tx.checkSign(rules); if (!sigVerify) { - router.setFlags(id, kSfSigbad); + router.setFlags(id, kSF_SIGBAD); return {Validity::SigBad, sigVerify.error()}; } - router.setFlags(id, kSfSiggood); + router.setFlags(id, kSF_SIGGOOD); } // Signature is now known good - if (any(flags & kSfLocalbad)) + if (any(flags & kSF_LOCALBAD)) { // ...but the local checks // are known bad. return {Validity::SigGoodOnly, "Local checks failed."}; } - if (any(flags & kSfLocalgood)) + if (any(flags & kSF_LOCALGOOD)) { // ...and the local checks // are known good. @@ -102,10 +102,10 @@ checkValidity(HashRouter& router, STTx const& tx, Rules const& rules) std::string reason; if (!passesLocalChecks(tx, reason)) { - router.setFlags(id, kSfLocalbad); + router.setFlags(id, kSF_LOCALBAD); return {Validity::SigGoodOnly, reason}; } - router.setFlags(id, kSfLocalgood); + router.setFlags(id, kSF_LOCALGOOD); return {Validity::Valid, ""}; } @@ -116,10 +116,10 @@ forceValidity(HashRouter& router, uint256 const& txid, Validity validity) switch (validity) { case Validity::Valid: - flags |= kSfLocalgood; + flags |= kSF_LOCALGOOD; [[fallthrough]]; case Validity::SigGoodOnly: - flags |= kSfSiggood; + flags |= kSF_SIGGOOD; [[fallthrough]]; case Validity::SigBad: // would be silly to call directly @@ -173,7 +173,7 @@ applyBatchTransactions( auto const mode = batchTxn.getFlags(); auto applyOneTransaction = [®istry, &j, &parentBatchId, &batchView](STTx const& tx) { - OpenView perTxBatchView(kBatchView, batchView); + OpenView perTxBatchView(kBATCH_VIEW, batchView); auto const ret = apply(registry, perTxBatchView, parentBatchId, tx, TapBatch, j); XRPL_ASSERT( @@ -247,7 +247,7 @@ applyTransaction( // its inner transactions as necessary. if (isTesSuccess(result.ter) && txn.getTxnType() == ttBATCH) { - OpenView wholeBatchView(kBatchView, view); + OpenView wholeBatchView(kBATCH_VIEW, view); if (applyBatchTransactions(registry, wholeBatchView, txn, j)) wholeBatchView.apply(view); diff --git a/src/libxrpl/tx/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp index 217fdd717f..7833341808 100644 --- a/src/libxrpl/tx/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -65,15 +66,26 @@ withTxnType(Rules const& rules, TxType txnType, F&& f) // so these need to be more global. // // To prevent unintentional side effects on existing checks, they will be - // set for every operation only once at least one of the relevant amendments - // are enabled. + // set for every operation only once SingleAssetVault (or later + // LendingProtocol) are enabled. // // See also Transactor::operator(). // std::optional stNumberSO; std::optional rulesGuard; std::optional mantissaScaleGuard; - createGuards(rules, stNumberSO, rulesGuard, mantissaScaleGuard); + if (rules.enabled(featureSingleAssetVault) || rules.enabled(featureLendingProtocol)) + { + // raii classes for the current ledger rules. + // fixUniversalNumber predates the rulesGuard and should be replaced. + stNumberSO.emplace(rules.enabled(fixUniversalNumber)); + rulesGuard.emplace(rules); + } + else + { + // Without those features enabled, always use the old number rules. + mantissaScaleGuard.emplace(MantissaRange::MantissaScale::Small); + } switch (txnType) { @@ -94,36 +106,36 @@ withTxnType(Rules const& rules, TxType txnType, F&& f) } } // namespace -// Templates so preflight does the right thing with T::kConsequencesFactory. +// Templates so preflight does the right thing with T::kCONSEQUENCES_FACTORY. // // This could be done more easily using if constexpr, but Visual Studio // 2017 doesn't handle if constexpr correctly. So once we're no longer // building with Visual Studio 2017 we can consider replacing the four // templates with a single template function that uses if constexpr. // -// For ConsequencesFactoryType::Normal +// For Transactor::Normal // template - requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Normal) + requires(T::kCONSEQUENCES_FACTORY == Transactor::Normal) TxConsequences consequencesHelper(PreflightContext const& ctx) { return TxConsequences(ctx.tx); }; -// For ConsequencesFactoryType::Blocker +// For Transactor::Blocker template - requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Blocker) + requires(T::kCONSEQUENCES_FACTORY == Transactor::Blocker) TxConsequences consequencesHelper(PreflightContext const& ctx) { return TxConsequences(ctx.tx, TxConsequences::Category::Blocker); }; -// For ConsequencesFactoryType::Custom +// For Transactor::Custom template - requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Custom) + requires(T::kCONSEQUENCES_FACTORY == Transactor::Custom) TxConsequences consequencesHelper(PreflightContext const& ctx) { @@ -146,7 +158,7 @@ invokePreflight(PreflightContext const& ctx) // Should never happen // LCOV_EXCL_START JLOG(ctx.j.fatal()) << "Unknown transaction type in preflight: " << e.txnType; - UNREACHABLE("xrpl::invokePreflight : unknown transaction type"); + UNREACHABLE("xrpl::invoke_preflight : unknown transaction type"); return {temUNKNOWN, TxConsequences{temUNKNOWN}}; // LCOV_EXCL_STOP } @@ -174,7 +186,7 @@ invokePreclaim(PreclaimContext const& ctx) // a flagged a failure. auto const id = ctx.tx.getAccountID(sfAccount); - if (id != beast::kZero) + if (id != beast::kZERO) { if (NotTEC const preSigResult = [&]() -> NotTEC { if (NotTEC const result = T::checkSeqProxy(ctx.view, ctx.tx, ctx.j)) @@ -205,7 +217,7 @@ invokePreclaim(PreclaimContext const& ctx) // Should never happen // LCOV_EXCL_START JLOG(ctx.j.fatal()) << "Unknown transaction type in preclaim: " << e.txnType; - UNREACHABLE("xrpl::invokePreclaim : unknown transaction type"); + UNREACHABLE("xrpl::invoke_preclaim : unknown transaction type"); return temUNKNOWN; // LCOV_EXCL_STOP } @@ -247,8 +259,8 @@ invokeCalculateBaseFee(ReadView const& view, STTx const& tx) TxConsequences::TxConsequences(NotTEC pfResult) : isBlocker_(false) - , fee_(beast::kZero) - , potentialSpend_(beast::kZero) + , fee_(beast::kZERO) + , potentialSpend_(beast::kZERO) , seqProx_(SeqProxy::sequence(0)) , sequencesConsumed_(0) { @@ -258,8 +270,8 @@ TxConsequences::TxConsequences(NotTEC pfResult) TxConsequences::TxConsequences(STTx const& tx) : isBlocker_(false) - , fee_(tx[sfFee].native() && !tx[sfFee].negative() ? tx[sfFee].xrp() : beast::kZero) - , potentialSpend_(beast::kZero) + , fee_(tx[sfFee].native() && !tx[sfFee].negative() ? tx[sfFee].xrp() : beast::kZERO) + , potentialSpend_(beast::kZERO) , seqProx_(tx.getSeqProxy()) , sequencesConsumed_(tx.getSeqProxy().isSeq() ? 1 : 0) { @@ -295,7 +307,7 @@ invokeApply(ApplyContext& ctx) // Should never happen // LCOV_EXCL_START JLOG(ctx.journal.fatal()) << "Unknown transaction type in apply: " << e.txnType; - UNREACHABLE("xrpl::invokeApply : unknown transaction type"); + UNREACHABLE("xrpl::invoke_apply : unknown transaction type"); return {temUNKNOWN, false}; // LCOV_EXCL_STOP } diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index ecd7bedf89..6469799eb6 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -19,12 +19,16 @@ #include #include +#include #include namespace xrpl { void -ValidAMM::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidAMM::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete) return; @@ -40,9 +44,8 @@ ValidAMM::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) } // AMM pool changed else if ( - (type == ltRIPPLE_STATE && after->isFlag(lsfAMMNode)) || - (type == ltACCOUNT_ROOT && after->isFieldPresent(sfAMMID)) || - (type == ltMPTOKEN && after->isFlag(lsfMPTAMM))) + (type == ltRIPPLE_STATE && ((after->getFlags() & lsfAMMNode) != 0u)) || + (type == ltACCOUNT_ROOT && after->isFieldPresent(sfAMMID))) { ammPoolChanged_ = true; } @@ -66,11 +69,11 @@ validBalances( ValidAMM::ZeroAllowed zeroAllowed) { bool const positive = - amount > beast::kZero && amount2 > beast::kZero && lptAMMBalance > beast::kZero; + amount > beast::kZERO && amount2 > beast::kZERO && lptAMMBalance > beast::kZERO; if (zeroAllowed == ValidAMM::ZeroAllowed::Yes) { return positive || - (amount == beast::kZero && amount2 == beast::kZero && lptAMMBalance == beast::kZero); + (amount == beast::kZERO && amount2 == beast::kZERO && lptAMMBalance == beast::kZERO); } return positive; } @@ -82,9 +85,9 @@ ValidAMM::finalizeVote(bool enforce, beast::Journal const& j) const { // LPTokens and the pool can not change on vote // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMMVote failed, " - << lptAMMBalanceBefore_.value_or(STAmount{}) << " " - << lptAMMBalanceAfter_.value_or(STAmount{}) << " " << ammPoolChanged_; + JLOG(j.error()) << "AMMVote invariant failed: " << lptAMMBalanceBefore_.value_or(STAmount{}) + << " " << lptAMMBalanceAfter_.value_or(STAmount{}) << " " + << ammPoolChanged_; if (enforce) return false; // LCOV_EXCL_STOP @@ -100,7 +103,7 @@ ValidAMM::finalizeBid(bool enforce, beast::Journal const& j) const { // The pool can not change on bid // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMMBid failed, pool changed"; + JLOG(j.error()) << "AMMBid invariant failed: pool changed"; if (enforce) return false; // LCOV_EXCL_STOP @@ -108,10 +111,10 @@ ValidAMM::finalizeBid(bool enforce, beast::Journal const& j) const // LPTokens are burnt, therefore there should be fewer LPTokens else if ( lptAMMBalanceBefore_ && lptAMMBalanceAfter_ && - (*lptAMMBalanceAfter_ > *lptAMMBalanceBefore_ || *lptAMMBalanceAfter_ <= beast::kZero)) + (*lptAMMBalanceAfter_ > *lptAMMBalanceBefore_ || *lptAMMBalanceAfter_ <= beast::kZERO)) { // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMMBid failed, " << *lptAMMBalanceBefore_ << " " + JLOG(j.error()) << "AMMBid invariant failed: " << *lptAMMBalanceBefore_ << " " << *lptAMMBalanceAfter_; if (enforce) return false; @@ -131,7 +134,7 @@ ValidAMM::finalizeCreate( if (!ammAccount_) { // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMMCreate failed, AMM object is not created"; + JLOG(j.error()) << "AMMCreate invariant failed: AMM object is not created"; if (enforce) return false; // LCOV_EXCL_STOP @@ -154,8 +157,8 @@ ValidAMM::finalizeCreate( if (!validBalances(amount, amount2, *lptAMMBalanceAfter_, ZeroAllowed::No) || ammLPTokens(amount, amount2, lptAMMBalanceAfter_->get()) != *lptAMMBalanceAfter_) { - JLOG(j.error()) << "Invariant failed: AMMCreate failed, " << amount << " " << amount2 - << " " << *lptAMMBalanceAfter_; + JLOG(j.error()) << "AMMCreate invariant failed: " << amount << " " << amount2 << " " + << *lptAMMBalanceAfter_; if (enforce) return false; } @@ -173,7 +176,7 @@ ValidAMM::finalizeDelete(bool enforce, TER res, beast::Journal const& j) const // LCOV_EXCL_START std::string const msg = (isTesSuccess(res)) ? "AMM object is not deleted on tesSUCCESS" : "AMM object is changed on tecINCOMPLETE"; - JLOG(j.error()) << "Invariant failed: AMMDelete failed, " << msg; + JLOG(j.error()) << "AMMDelete invariant failed: " << msg; if (enforce) return false; // LCOV_EXCL_STOP @@ -188,7 +191,7 @@ ValidAMM::finalizeDEX(bool enforce, beast::Journal const& j) const if (ammAccount_) { // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMM swap failed, AMM object changed"; + JLOG(j.error()) << "AMM swap invariant failed: AMM object changed"; if (enforce) return false; // LCOV_EXCL_STOP @@ -224,16 +227,16 @@ ValidAMM::generalInvariant( bool const strongInvariantCheck = poolProductMean >= *lptAMMBalanceAfter_; // Allow for a small relative error if strongInvariantCheck fails auto weakInvariantCheck = [&]() { - return *lptAMMBalanceAfter_ != beast::kZero && + return *lptAMMBalanceAfter_ != beast::kZERO && withinRelativeDistance(poolProductMean, Number{*lptAMMBalanceAfter_}, Number{1, -11}); }; if (!nonNegativeBalances || (!strongInvariantCheck && !weakInvariantCheck())) { - JLOG(j.error()) << "Invariant failed: AMM " << tx.getTxnType() << " " - << tx.getHash(HashPrefix::TransactionId) << " " << ammPoolChanged_ << " " - << amount << " " << amount2 << " " << poolProductMean << " " - << lptAMMBalanceAfter_->getText() << " " - << ((*lptAMMBalanceAfter_ == beast::kZero) + JLOG(j.error()) << "AMM " << tx.getTxnType() + << " invariant failed: " << tx.getHash(HashPrefix::TransactionId) << " " + << ammPoolChanged_ << " " << amount << " " << amount2 << " " + << poolProductMean << " " << lptAMMBalanceAfter_->getText() << " " + << ((*lptAMMBalanceAfter_ == beast::kZERO) ? Number{1} : ((*lptAMMBalanceAfter_ - poolProductMean) / poolProductMean)); return false; @@ -253,7 +256,7 @@ ValidAMM::finalizeDeposit( if (!ammAccount_) { // LCOV_EXCL_START - JLOG(j.error()) << "Invariant failed: AMMDeposit failed, AMM object is deleted"; + JLOG(j.error()) << "AMMDeposit invariant failed: AMM object is deleted"; if (enforce) return false; // LCOV_EXCL_STOP diff --git a/src/libxrpl/tx/invariants/DirectoryInvariant.cpp b/src/libxrpl/tx/invariants/DirectoryInvariant.cpp deleted file mode 100644 index 1624a19830..0000000000 --- a/src/libxrpl/tx/invariants/DirectoryInvariant.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace xrpl { - -namespace { - -[[nodiscard]] bool -isRootBookDirectory(SLE const& dir) -{ - // Child page keys do not encode book quality. - return dir.isFieldPresent(sfExchangeRate) || dir.isFieldPresent(sfTakerPaysCurrency) || - dir.isFieldPresent(sfTakerPaysIssuer) || dir.isFieldPresent(sfTakerPaysMPT) || - dir.isFieldPresent(sfTakerGetsCurrency) || dir.isFieldPresent(sfTakerGetsIssuer) || - dir.isFieldPresent(sfTakerGetsMPT) || dir.isFieldPresent(sfDomainID); -} - -[[nodiscard]] bool -badExchangeRate(SLE const& dir) -{ - return isRootBookDirectory(dir) && - (!dir.isFieldPresent(sfExchangeRate) || - dir.getFieldU64(sfExchangeRate) != getQuality(dir.key())); -} - -} // namespace - -void -ValidBookDirectory::visitEntry( - bool isDelete, - std::shared_ptr const& before, - std::shared_ptr const& after) -{ - // New root directories must have matching exchange-rate metadata. New - // child directories, and modified directories that change sfRootIndex, must - // point to an existing root. - - // Only validate newly-created directories and sfRootIndex changes; - // LedgerStateFix handles legacy bad exchange-rate metadata. Skip deletions - // because `after` is not guaranteed to be null. - if (badBookDirectory_ || isDelete || !after || after->getType() != ltDIR_NODE) - return; - - auto const rootIndex = after->getFieldH256(sfRootIndex); - // Ignore ordinary modifications that do not change which root this - // directory belongs to. That tolerates legacy bad exchange-rate metadata - // during normal operation while still checking sfRootIndex changes. - if (before && before->getFieldH256(sfRootIndex) == rootIndex) - return; - - if (after->key() == rootIndex && !badBookDirectory_) - { - badBookDirectory_ = badBookDirectory_ || badExchangeRate(*after); - return; - } - - rootIndexes_.insert(rootIndex); -} - -bool -ValidBookDirectory::finalize( - STTx const&, - TER const, - XRPAmount const, - ReadView const& view, - beast::Journal const& j) -{ - if (!view.rules().enabled(fixCleanup3_2_0)) - return true; - - if (badBookDirectory_) - { - JLOG(j.fatal()) << "Invariant failed: book directory exchange rate " - "does not match directory quality"; - return false; - } - - for (auto const& rootIndex : rootIndexes_) - { - auto const root = view.read(Keylet(ltDIR_NODE, rootIndex)); - if (!root) - { - JLOG(j.fatal()) << "Invariant failed: book directory root missing"; - return false; - } - } - - return true; -} - -} // namespace xrpl diff --git a/src/libxrpl/tx/invariants/FreezeInvariant.cpp b/src/libxrpl/tx/invariants/FreezeInvariant.cpp index 0293d42e97..eaaeb7fc6f 100644 --- a/src/libxrpl/tx/invariants/FreezeInvariant.cpp +++ b/src/libxrpl/tx/invariants/FreezeInvariant.cpp @@ -16,12 +16,16 @@ #include #include +#include #include namespace xrpl { void -TransfersNotFrozen::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +TransfersNotFrozen::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { /* * A trust line freeze state alone doesn't determine if a transfer is @@ -103,7 +107,9 @@ TransfersNotFrozen::finalize( } bool -TransfersNotFrozen::isValidEntry(SLE::const_ref before, SLE::const_ref after) +TransfersNotFrozen::isValidEntry( + std::shared_ptr const& before, + std::shared_ptr const& after) { // `after` can never be null, even if the trust line is deleted. XRPL_ASSERT(after, "xrpl::TransfersNotFrozen::isValidEntry : valid after."); @@ -129,8 +135,8 @@ TransfersNotFrozen::isValidEntry(SLE::const_ref before, SLE::const_ref after) STAmount TransfersNotFrozen::calculateBalanceChange( - SLE::const_ref before, - SLE::const_ref after, + std::shared_ptr const& before, + std::shared_ptr const& after, bool isDelete) { auto const getBalance = [](auto const& line, auto const& other, bool zero) { @@ -174,7 +180,9 @@ TransfersNotFrozen::recordBalance(Issue const& issue, BalanceChange change) } void -TransfersNotFrozen::recordBalanceChanges(SLE::const_ref after, STAmount const& balanceChange) +TransfersNotFrozen::recordBalanceChanges( + std::shared_ptr const& after, + STAmount const& balanceChange) { auto const balanceChangeSign = balanceChange.signum(); auto const currency = after->at(sfBalance).get().currency; @@ -190,7 +198,7 @@ TransfersNotFrozen::recordBalanceChanges(SLE::const_ref after, STAmount const& b {.line = after, .balanceChangeSign = -balanceChangeSign}); } -SLE::const_pointer +std::shared_ptr TransfersNotFrozen::findIssuer(AccountID const& issuerID, ReadView const& view) { if (auto it = possibleIssuers_.find(issuerID); it != possibleIssuers_.end()) @@ -203,7 +211,7 @@ TransfersNotFrozen::findIssuer(AccountID const& issuerID, ReadView const& view) bool TransfersNotFrozen::validateIssuerChanges( - SLE::const_ref issuer, + std::shared_ptr const& issuer, IssuerChanges const& changes, STTx const& tx, beast::Journal const& j, diff --git a/src/libxrpl/tx/invariants/InvariantCheck.cpp b/src/libxrpl/tx/invariants/InvariantCheck.cpp index b4a533905c..4f25a91bdf 100644 --- a/src/libxrpl/tx/invariants/InvariantCheck.cpp +++ b/src/libxrpl/tx/invariants/InvariantCheck.cpp @@ -64,7 +64,10 @@ hasPrivilege(STTx const& tx, Privilege priv) #pragma pop_macro("TRANSACTION") void -TransactionFeeCheck::visitEntry(bool, SLE::const_ref, SLE::const_ref) +TransactionFeeCheck::visitEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { // nothing to do } @@ -86,7 +89,7 @@ TransactionFeeCheck::finalize( // We should never charge a fee that's greater than or equal to the // entire XRP supply. - if (fee >= kInitialXrp) + if (fee >= kINITIAL_XRP) { JLOG(j.fatal()) << "Invariant failed: fee paid exceeds system limit: " << fee.drops(); return false; @@ -107,7 +110,10 @@ TransactionFeeCheck::finalize( //------------------------------------------------------------------------------ void -XRPNotCreated::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +XRPNotCreated::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { /* We go through all modified ledger entries, looking only at account roots, * escrow payments, and payment channels. We remove from the total any @@ -186,7 +192,10 @@ XRPNotCreated::finalize( //------------------------------------------------------------------------------ void -XRPBalanceChecks::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) +XRPBalanceChecks::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { auto isBad = [](STAmount const& balance) { if (!balance.native()) @@ -196,7 +205,7 @@ XRPBalanceChecks::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) // Can't have more than the number of drops instantiated // in the genesis ledger. - if (drops > kInitialXrp) + if (drops > kINITIAL_XRP) return true; // Can't have a negative balance (0 is OK) @@ -233,14 +242,17 @@ XRPBalanceChecks::finalize( //------------------------------------------------------------------------------ void -NoBadOffers::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +NoBadOffers::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { auto isBad = [](STAmount const& pays, STAmount const& gets) { // An offer should never be negative - if (pays < beast::kZero) + if (pays < beast::kZERO) return true; - if (gets < beast::kZero) + if (gets < beast::kZERO) return true; // Can't have an XRP to XRP offer: @@ -274,7 +286,10 @@ NoBadOffers::finalize( //------------------------------------------------------------------------------ void -NoZeroEscrow::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +NoZeroEscrow::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { auto isBad = [](STAmount const& amount) { // XRP case @@ -283,7 +298,7 @@ NoZeroEscrow::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref af if (amount.xrp() <= XRPAmount{0}) return true; - if (amount.xrp() >= kInitialXrp) + if (amount.xrp() >= kINITIAL_XRP) return true; } else @@ -291,7 +306,7 @@ NoZeroEscrow::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref af return amount.asset().visit( [&](Issue const& issue) { // IOU case - if (amount <= beast::kZero) + if (amount <= beast::kZERO) return true; if (badCurrency() == issue.currency) @@ -303,10 +318,10 @@ NoZeroEscrow::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref af // MPT case , [&](MPTIssue const&) { - if (amount <= beast::kZero) + if (amount <= beast::kZERO) return true; - if (amount.mpt() > MPTAmount{kMaxMpTokenAmount}) + if (amount.mpt() > MPTAmount{kMAX_MP_TOKEN_AMOUNT}) return true; // LCOV_EXCL_LINE return false; @@ -322,11 +337,11 @@ NoZeroEscrow::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref af bad_ |= isBad((*after)[sfAmount]); auto checkAmount = [this](std::int64_t amount) { - if (amount > kMaxMpTokenAmount || amount < 0) + if (amount > kMAX_MP_TOKEN_AMOUNT || amount < 0) bad_ |= true; }; - bool const overwriteFixEnabled = isFeatureEnabled(fixCleanup3_1_3, true); + bool const overwriteFixEnabled = isFeatureEnabled(fixSecurity3_1_3, true); if (after && after->getType() == ltMPTOKEN_ISSUANCE) { @@ -378,7 +393,10 @@ NoZeroEscrow::finalize( //------------------------------------------------------------------------------ void -AccountRootsNotDeleted::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref) +AccountRootsNotDeleted::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const&) { if (isDelete && before && before->getType() == ltACCOUNT_ROOT) accountsDeleted_++; @@ -428,7 +446,10 @@ AccountRootsNotDeleted::finalize( //------------------------------------------------------------------------------ void -AccountRootsDeletedClean::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +AccountRootsDeletedClean::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete && before && before->getType() == ltACCOUNT_ROOT) accountsDeleted_.emplace_back(before, after); @@ -446,7 +467,7 @@ AccountRootsDeletedClean::finalize( // transaction processing results, however unlikely, only fail if the // feature is enabled. Enabled, or not, though, a fatal-level message will // be logged - [[maybe_unused]] bool const enforce = view.rules().enabled(fixCleanup3_2_0) || + [[maybe_unused]] bool const enforce = view.rules().enabled(featureInvariantsV1_1) || view.rules().enabled(featureSingleAssetVault) || view.rules().enabled(featureLendingProtocol); @@ -480,7 +501,7 @@ AccountRootsDeletedClean::finalize( { auto const accountID = before->getAccountID(sfAccount); // An account should not be deleted with a balance - if (after->at(sfBalance) != beast::kZero) + if (after->at(sfBalance) != beast::kZERO) { JLOG(j.fatal()) << "Invariant failed: account deletion left " "behind a non-zero balance"; @@ -504,7 +525,7 @@ AccountRootsDeletedClean::finalize( return false; } // Simple types - for (auto const& [keyletfunc, _1, _2] : kDirectAccountKeylets) + for (auto const& [keyletfunc, _1, _2] : kDIRECT_ACCOUNT_KEYLETS) { // TODO: use '_' for both unused variables above once we are in C++26 if (objectExists(std::invoke(keyletfunc, accountID)) && enforce) @@ -545,7 +566,10 @@ AccountRootsDeletedClean::finalize( //------------------------------------------------------------------------------ void -LedgerEntryTypesMatch::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) +LedgerEntryTypesMatch::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (before && after && before->getType() != after->getType()) typeMismatch_ = true; @@ -599,9 +623,12 @@ LedgerEntryTypesMatch::finalize( //------------------------------------------------------------------------------ void -NoXRPTrustLines::visitEntry(bool, SLE::const_ref, SLE::const_ref after) +NoXRPTrustLines::visitEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const& after) { - bool const overwriteFixEnabled = isFeatureEnabled(fixCleanup3_1_3, true); + bool const overwriteFixEnabled = isFeatureEnabled(fixSecurity3_1_3, true); if (after && after->getType() == ltRIPPLE_STATE) { @@ -639,17 +666,21 @@ NoXRPTrustLines::finalize( //------------------------------------------------------------------------------ void -NoDeepFreezeTrustLinesWithoutFreeze::visitEntry(bool, SLE::const_ref, SLE::const_ref after) +NoDeepFreezeTrustLinesWithoutFreeze::visitEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const& after) { if (after && after->getType() == ltRIPPLE_STATE) { - bool const overwriteFixEnabled = isFeatureEnabled(fixCleanup3_1_3, true); + bool const overwriteFixEnabled = isFeatureEnabled(fixSecurity3_1_3, true); - bool const lowFreeze = after->isFlag(lsfLowFreeze); - bool const lowDeepFreeze = after->isFlag(lsfLowDeepFreeze); + std::uint32_t const uFlags = after->getFieldU32(sfFlags); + bool const lowFreeze = (uFlags & lsfLowFreeze) != 0u; + bool const lowDeepFreeze = (uFlags & lsfLowDeepFreeze) != 0u; - bool const highFreeze = after->isFlag(lsfHighFreeze); - bool const highDeepFreeze = after->isFlag(lsfHighDeepFreeze); + bool const highFreeze = (uFlags & lsfHighFreeze) != 0u; + bool const highDeepFreeze = (uFlags & lsfHighDeepFreeze) != 0u; bool const bad = (lowDeepFreeze && !lowFreeze) || (highDeepFreeze && !highFreeze); if (overwriteFixEnabled) @@ -682,7 +713,10 @@ NoDeepFreezeTrustLinesWithoutFreeze::finalize( //------------------------------------------------------------------------------ void -ValidNewAccountRoot::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) +ValidNewAccountRoot::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (!before && after->getType() == ltACCOUNT_ROOT) { @@ -756,7 +790,10 @@ ValidNewAccountRoot::finalize( //------------------------------------------------------------------------------ void -ValidClawback::visitEntry(bool, SLE::const_ref before, SLE::const_ref) +ValidClawback::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const&) { if (before && before->getType() == ltRIPPLE_STATE) trustlinesChanged_++; @@ -804,7 +841,7 @@ ValidClawback::finalize( [&](MPTIssue const& issue) { return accountHolds( view, - holder, + issuer, issue, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, @@ -841,7 +878,10 @@ ValidClawback::finalize( //------------------------------------------------------------------------------ void -ValidPseudoAccounts::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidPseudoAccounts::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete) { @@ -929,7 +969,10 @@ ValidPseudoAccounts::finalize( //------------------------------------------------------------------------------ void -NoModifiedUnmodifiableFields::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +NoModifiedUnmodifiableFields::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete || !before) { @@ -948,7 +991,9 @@ NoModifiedUnmodifiableFields::finalize( ReadView const& view, beast::Journal const& j) { - static auto const kFieldChanged = [](auto const& before, auto const& after, auto const& field) { + static auto const kFIELD_CHANGED = [](auto const& before, + auto const& after, + auto const& field) { bool const beforeField = before->isFieldPresent(field); bool const afterField = after->isFieldPresent(field); return beforeField != afterField || (afterField && before->at(field) != after->at(field)); @@ -969,17 +1014,17 @@ NoModifiedUnmodifiableFields::finalize( * potential issues even when the amendment is disabled. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = kFieldChanged(before, after, sfLedgerEntryType) || - kFieldChanged(before, after, sfLedgerIndex) || - kFieldChanged(before, after, sfSequence) || - kFieldChanged(before, after, sfOwnerNode) || - kFieldChanged(before, after, sfVaultNode) || - kFieldChanged(before, after, sfVaultID) || - kFieldChanged(before, after, sfAccount) || - kFieldChanged(before, after, sfOwner) || - kFieldChanged(before, after, sfManagementFeeRate) || - kFieldChanged(before, after, sfCoverRateMinimum) || - kFieldChanged(before, after, sfCoverRateLiquidation); + bad = kFIELD_CHANGED(before, after, sfLedgerEntryType) || + kFIELD_CHANGED(before, after, sfLedgerIndex) || + kFIELD_CHANGED(before, after, sfSequence) || + kFIELD_CHANGED(before, after, sfOwnerNode) || + kFIELD_CHANGED(before, after, sfVaultNode) || + kFIELD_CHANGED(before, after, sfVaultID) || + kFIELD_CHANGED(before, after, sfAccount) || + kFIELD_CHANGED(before, after, sfOwner) || + kFIELD_CHANGED(before, after, sfManagementFeeRate) || + kFIELD_CHANGED(before, after, sfCoverRateMinimum) || + kFIELD_CHANGED(before, after, sfCoverRateLiquidation); break; case ltLOAN: /* @@ -988,26 +1033,26 @@ NoModifiedUnmodifiableFields::finalize( * potential issues even when the amendment is disabled. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = kFieldChanged(before, after, sfLedgerEntryType) || - kFieldChanged(before, after, sfLedgerIndex) || - kFieldChanged(before, after, sfSequence) || - kFieldChanged(before, after, sfOwnerNode) || - kFieldChanged(before, after, sfLoanBrokerNode) || - kFieldChanged(before, after, sfLoanBrokerID) || - kFieldChanged(before, after, sfBorrower) || - kFieldChanged(before, after, sfLoanOriginationFee) || - kFieldChanged(before, after, sfLoanServiceFee) || - kFieldChanged(before, after, sfLatePaymentFee) || - kFieldChanged(before, after, sfClosePaymentFee) || - kFieldChanged(before, after, sfOverpaymentFee) || - kFieldChanged(before, after, sfInterestRate) || - kFieldChanged(before, after, sfLateInterestRate) || - kFieldChanged(before, after, sfCloseInterestRate) || - kFieldChanged(before, after, sfOverpaymentInterestRate) || - kFieldChanged(before, after, sfStartDate) || - kFieldChanged(before, after, sfPaymentInterval) || - kFieldChanged(before, after, sfGracePeriod) || - kFieldChanged(before, after, sfLoanScale); + bad = kFIELD_CHANGED(before, after, sfLedgerEntryType) || + kFIELD_CHANGED(before, after, sfLedgerIndex) || + kFIELD_CHANGED(before, after, sfSequence) || + kFIELD_CHANGED(before, after, sfOwnerNode) || + kFIELD_CHANGED(before, after, sfLoanBrokerNode) || + kFIELD_CHANGED(before, after, sfLoanBrokerID) || + kFIELD_CHANGED(before, after, sfBorrower) || + kFIELD_CHANGED(before, after, sfLoanOriginationFee) || + kFIELD_CHANGED(before, after, sfLoanServiceFee) || + kFIELD_CHANGED(before, after, sfLatePaymentFee) || + kFIELD_CHANGED(before, after, sfClosePaymentFee) || + kFIELD_CHANGED(before, after, sfOverpaymentFee) || + kFIELD_CHANGED(before, after, sfInterestRate) || + kFIELD_CHANGED(before, after, sfLateInterestRate) || + kFIELD_CHANGED(before, after, sfCloseInterestRate) || + kFIELD_CHANGED(before, after, sfOverpaymentInterestRate) || + kFIELD_CHANGED(before, after, sfStartDate) || + kFIELD_CHANGED(before, after, sfPaymentInterval) || + kFIELD_CHANGED(before, after, sfGracePeriod) || + kFIELD_CHANGED(before, after, sfLoanScale); break; default: /* @@ -1020,8 +1065,8 @@ NoModifiedUnmodifiableFields::finalize( * was added. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = kFieldChanged(before, after, sfLedgerEntryType) || - kFieldChanged(before, after, sfLedgerIndex); + bad = kFIELD_CHANGED(before, after, sfLedgerEntryType) || + kFIELD_CHANGED(before, after, sfLedgerIndex); } XRPL_ASSERT( !bad || enforce, @@ -1038,35 +1083,4 @@ NoModifiedUnmodifiableFields::finalize( return true; } -void -ValidAmounts::visitEntry( - bool isDelete, - std::shared_ptr const&, - std::shared_ptr const& after) -{ - if (!isDelete && after) - afterEntries_.push_back(after); -} - -bool -ValidAmounts::finalize( - STTx const&, - TER const, - XRPAmount const, - ReadView const& view, - beast::Journal const& j) const -{ - bool const badLedgerEntry = std::ranges::any_of( - afterEntries_, [&](auto const& sle) { return hasInvalidAmount(*sle, j); }); - - if (badLedgerEntry) - { - JLOG(j.fatal()) - << "Invariant failed: ledger entry contains non-canonical MPT or XRP amount"; - return !view.rules().enabled(fixCleanup3_2_0); - } - - return true; -} - } // namespace xrpl diff --git a/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp index 8586a27be3..b98d769393 100644 --- a/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp @@ -15,10 +15,15 @@ #include #include +#include + namespace xrpl { void -ValidLoanBroker::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidLoanBroker::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (after) { @@ -192,7 +197,7 @@ ValidLoanBroker::finalize( return false; } - if (view.rules().enabled(fixCleanup3_1_3)) + if (view.rules().enabled(fixSecurity3_1_3)) { // Don't check the balance when LoanBroker is deleted, // sfCoverAvailable is not zeroed diff --git a/src/libxrpl/tx/invariants/LoanInvariant.cpp b/src/libxrpl/tx/invariants/LoanInvariant.cpp index ce9a7c6e03..e3dff3dde9 100644 --- a/src/libxrpl/tx/invariants/LoanInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanInvariant.cpp @@ -12,10 +12,15 @@ #include #include +#include + namespace xrpl { void -ValidLoan::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidLoan::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (after && after->getType() == ltLOAN) { @@ -39,9 +44,9 @@ ValidLoan::finalize( // https://github.com/Tapanito/XRPL-Standards/blob/xls-66-lending-protocol/XLS-0066d-lending-protocol/README.md#3223-invariants // If `Loan.PaymentRemaining = 0` then the loan MUST be fully paid off if (after->at(sfPaymentRemaining) == 0 && - (after->at(sfTotalValueOutstanding) != beast::kZero || - after->at(sfPrincipalOutstanding) != beast::kZero || - after->at(sfManagementFeeOutstanding) != beast::kZero)) + (after->at(sfTotalValueOutstanding) != beast::kZERO || + after->at(sfPrincipalOutstanding) != beast::kZERO || + after->at(sfManagementFeeOutstanding) != beast::kZERO)) { JLOG(j.fatal()) << "Invariant failed: Loan with zero payments " "remaining has not been paid off"; @@ -50,9 +55,9 @@ ValidLoan::finalize( // If `Loan.PaymentRemaining != 0` then the loan MUST NOT be fully paid // off if (after->at(sfPaymentRemaining) != 0 && - after->at(sfTotalValueOutstanding) == beast::kZero && - after->at(sfPrincipalOutstanding) == beast::kZero && - after->at(sfManagementFeeOutstanding) == beast::kZero) + after->at(sfTotalValueOutstanding) == beast::kZERO && + after->at(sfPrincipalOutstanding) == beast::kZERO && + after->at(sfManagementFeeOutstanding) == beast::kZERO) { JLOG(j.fatal()) << "Invariant failed: Fully paid off Loan still has payments remaining"; return false; diff --git a/src/libxrpl/tx/invariants/MPTInvariant.cpp b/src/libxrpl/tx/invariants/MPTInvariant.cpp index 4474aeba0e..1754a30120 100644 --- a/src/libxrpl/tx/invariants/MPTInvariant.cpp +++ b/src/libxrpl/tx/invariants/MPTInvariant.cpp @@ -7,19 +7,16 @@ #include #include #include -#include #include #include #include #include #include -#include #include #include #include #include #include -#include #include #include @@ -28,9 +25,10 @@ #include #include #include + namespace xrpl { -static constexpr auto kConfidentialMptTxTypes = std::to_array({ +static constexpr auto kCONFIDENTIAL_MPT_TX_TYPES = std::to_array({ ttCONFIDENTIAL_MPT_SEND, ttCONFIDENTIAL_MPT_CONVERT, ttCONFIDENTIAL_MPT_CONVERT_BACK, @@ -39,15 +37,11 @@ static constexpr auto kConfidentialMptTxTypes = std::to_array({ }); void -ValidMPTIssuance::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidMPTIssuance::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { - // The sfReferenceHolding tracking and the deleted-holding capture are - // only meaningful post-fixCleanup3_2_0 (the field is never set - // pre-amendment, and the holding-deletion rule does not apply). - // Skip both blocks when the amendment is off so we avoid wasted work - // on the hot path. - bool const fix320Enabled = isFeatureEnabled(fixCleanup3_2_0); - if (after && after->getType() == ltMPTOKEN_ISSUANCE) { if (isDelete) @@ -57,21 +51,6 @@ ValidMPTIssuance::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re else if (!before) { mptIssuancesCreated_++; - if (fix320Enabled && after->isFieldPresent(sfReferenceHolding)) - referenceHoldingSetOnCreate_ = true; - } - else if (fix320Enabled) - { - // Modified issuance: detect any change to sfReferenceHolding. - bool const beforePresent = before->isFieldPresent(sfReferenceHolding); - bool const afterPresent = after->isFieldPresent(sfReferenceHolding); - if (beforePresent != afterPresent || - (afterPresent && - before->getFieldH256(sfReferenceHolding) != - after->getFieldH256(sfReferenceHolding))) - { - referenceHoldingMutated_ = true; - } } } @@ -80,8 +59,6 @@ ValidMPTIssuance::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re if (isDelete) { mptokensDeleted_++; - if (fix320Enabled) - deletedHoldings_.push_back(after); } else if (!before) { @@ -91,11 +68,6 @@ ValidMPTIssuance::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re mptCreatedByIssuer_ = true; } } - - // Capture deleted RippleState SLEs so finalize() can verify none of - // them were owned by a vault pseudo-account outside VaultDelete. - if (fix320Enabled && isDelete && after && after->getType() == ltRIPPLE_STATE) - deletedHoldings_.push_back(after); } bool @@ -108,63 +80,6 @@ ValidMPTIssuance::finalize( { auto const& rules = view.rules(); bool const mptV2Enabled = rules.enabled(featureMPTokensV2); - - // Post-fixCleanup3_2_0: - // - sfReferenceHolding is set only by VaultCreate at share-issuance - // creation, and is immutable thereafter. - // - A vault pseudo-account's MPToken or RippleState may only be - // deleted by VaultDelete; the share's sfReferenceHolding pointer - // must not dangle outside that controlled lifecycle. - if (rules.enabled(fixCleanup3_2_0)) - { - bool invariantPasses = true; - if (referenceHoldingMutated_) - { - JLOG(j.fatal()) << "Invariant failed: sfReferenceHolding was modified " - "on an existing MPTokenIssuance"; - invariantPasses = false; - } - if (referenceHoldingSetOnCreate_ && tx.getTxnType() != ttVAULT_CREATE) - { - JLOG(j.fatal()) << "Invariant failed: sfReferenceHolding set on a new " - "MPTokenIssuance by a non-VaultCreate transaction"; - invariantPasses = false; - } - if (!deletedHoldings_.empty() && tx.getTxnType() != ttVAULT_DELETE) - { - auto const isVaultPseudo = [&](AccountID const& acct) { - auto const sle = view.read(keylet::account(acct)); - return sle && sle->isFieldPresent(sfVaultID); - }; - for (auto const& sleHolding : deletedHoldings_) - { - bool offending = false; - if (sleHolding->getType() == ltMPTOKEN) - { - offending = isVaultPseudo(sleHolding->at(sfAccount)); - } - else // ltRIPPLE_STATE - { - auto const lowLimit = sleHolding->getFieldAmount(sfLowLimit); - auto const highLimit = sleHolding->getFieldAmount(sfHighLimit); - // Each limit's STAmount.issuer is the COUNTERPARTY of - // that side's owner: lowLimit's issuer is the high - // account, highLimit's issuer is the low account. - offending = - isVaultPseudo(lowLimit.getIssuer()) || isVaultPseudo(highLimit.getIssuer()); - } - if (offending) - { - JLOG(j.fatal()) << "Invariant failed: vault pseudo-account holding " - "deleted by a non-VaultDelete transaction"; - invariantPasses = false; - } - } - } - if (!invariantPasses) - return false; - } - if (isTesSuccess(result) || (mptV2Enabled && result == tecINCOMPLETE)) { [[maybe_unused]] @@ -377,7 +292,10 @@ ValidMPTIssuance::finalize( } void -ValidMPTPayment::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) +ValidMPTPayment::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (overflow_) return; @@ -393,7 +311,7 @@ ValidMPTPayment::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) if (type == ltMPTOKEN_ISSUANCE) { auto const outstanding = sle[sfOutstandingAmount]; - if (outstanding > kMaxMpTokenAmount) + if (outstanding > kMAX_MP_TOKEN_AMOUNT) { overflow_ = true; return false; @@ -404,8 +322,8 @@ ValidMPTPayment::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) { auto const mptAmt = sle[sfMPTAmount]; auto const lockedAmt = sle[~sfLockedAmount].value_or(0); - if (mptAmt > kMaxMpTokenAmount || lockedAmt > kMaxMpTokenAmount || - lockedAmt > (kMaxMpTokenAmount - mptAmt)) + if (mptAmt > kMAX_MP_TOKEN_AMOUNT || lockedAmt > kMAX_MP_TOKEN_AMOUNT || + lockedAmt > (kMAX_MP_TOKEN_AMOUNT - mptAmt)) { overflow_ = true; return false; @@ -452,33 +370,34 @@ ValidMPTPayment::finalize( // They modify encrypted fields and sfConfidentialOutstandingAmount // rather than sfMPTAmount/sfOutstandingAmount in the standard way, // so ValidMPTPayment's accounting does not apply to them. - if (std::ranges::find(kConfidentialMptTxTypes, tx.getTxnType()) != - kConfidentialMptTxTypes.end()) + if (std::ranges::find(kCONFIDENTIAL_MPT_TX_TYPES, tx.getTxnType()) != + kCONFIDENTIAL_MPT_TX_TYPES.end()) return true; - bool const invariantPasses = !view.rules().enabled(featureMPTokensV2); + bool const enforce = view.rules().enabled(featureMPTokensV2); if (overflow_) { JLOG(j.fatal()) << "Invariant failed: OutstandingAmount overflow"; - return invariantPasses; + return !enforce; } - auto const signedMax = static_cast(kMaxMpTokenAmount); + auto const signedMax = static_cast(kMAX_MP_TOKEN_AMOUNT); for (auto const& [id, data] : data_) { (void)id; - static constexpr auto kIBefore = static_cast(Order::Before); - static constexpr auto kIAfter = static_cast(Order::After); + constexpr auto kI_BEFORE = static_cast(Order::Before); + constexpr auto kI_AFTER = static_cast(Order::After); bool const addOverflows = - (data.mptAmount > 0 && data.outstanding[kIBefore] > (signedMax - data.mptAmount)) || - (data.mptAmount < 0 && data.outstanding[kIBefore] < (-signedMax - data.mptAmount)); + (data.mptAmount > 0 && + data.outstanding[kI_BEFORE] > (signedMax - data.mptAmount)) || + (data.mptAmount < 0 && data.outstanding[kI_BEFORE] < (-signedMax - data.mptAmount)); if (addOverflows || - data.outstanding[kIAfter] != (data.outstanding[kIBefore] + data.mptAmount)) + data.outstanding[kI_AFTER] != (data.outstanding[kI_BEFORE] + data.mptAmount)) { JLOG(j.fatal()) << "Invariant failed: invalid OutstandingAmount balance " - << data.outstanding[kIBefore] << " " << data.outstanding[kIAfter] + << data.outstanding[kI_BEFORE] << " " << data.outstanding[kI_AFTER] << " " << data.mptAmount; - return invariantPasses; + return !enforce; } } } @@ -486,149 +405,6 @@ ValidMPTPayment::finalize( return true; } -void -ValidMPTTransfer::visitEntry( - bool isDelete, - std::shared_ptr const& before, - std::shared_ptr const& after) -{ - // Record the before/after MPTAmount for each (issuanceID, account) pair - // so finalize() can determine whether a transfer actually occurred. - auto update = [&](SLE const& sle, bool isBefore) { - if (sle.getType() == ltMPTOKEN) - { - auto const issuanceID = sle[sfMPTokenIssuanceID]; - auto const account = sle[sfAccount]; - auto const amount = sle[sfMPTAmount]; - if (isBefore) - { - amount_[issuanceID][account].amtBefore = amount; - } - else - { - amount_[issuanceID][account].amtAfter = amount; - } - if (isDelete && isBefore) - { - deletedAuthorized_[sle.key()] = sle.isFlag(lsfMPTAuthorized); - } - } - }; - - if (before) - update(*before, true); - - if (after) - update(*after, false); -} - -bool -ValidMPTTransfer::isAuthorized( - ReadView const& view, - MPTID const& mptid, - AccountID const& holder, - bool reqAuth) const -{ - auto const key = keylet::mptoken(mptid, holder); - auto const it = deletedAuthorized_.find(key.key); - if (it != deletedAuthorized_.end()) - return !reqAuth || it->second; - return isTesSuccess(requireAuth(view, MPTIssue{mptid}, holder)); -} - -bool -ValidMPTTransfer::finalize( - STTx const& tx, - TER const, - XRPAmount const, - ReadView const& view, - beast::Journal const& j) -{ - if (hasPrivilege(tx, OverrideFreeze)) - return true; - - // DEX transactions (AMM[Create,Deposit], cross-currency payments, offer creates) are - // subject to the MPTCanTrade flag in addition to the standard transfer rules. - // A payment is only DEX if it is a cross-currency payment. - auto const txnType = tx.getTxnType(); - auto const isDEX = [&] { - if (txnType == ttPAYMENT) - { - // A payment is cross-currency (and thus DEX) only if SendMax is present - // and its asset differs from the destination asset. - auto const amount = tx[sfAmount]; - return tx[~sfSendMax].value_or(amount).asset() != amount.asset(); - } - return txnType == ttAMM_CREATE || txnType == ttAMM_DEPOSIT || txnType == ttOFFER_CREATE; - }(); - - // Only enforce once MPTokensV2 is enabled to preserve consensus with non-V2 nodes. - // Log invariant failure error even if MPTokensV2 is disabled. - auto const invariantPasses = !view.rules().enabled(featureMPTokensV2); - - for (auto const& [mptID, values] : amount_) - { - std::uint16_t senders = 0; - std::uint16_t receivers = 0; - bool invalidTransfer = false; - auto const sleIssuance = view.read(keylet::mptIssuance(mptID)); - if (!sleIssuance) - { - continue; - } - - // These transactions are recovery/settlement paths. They may move an - // existing MPT position even after the issuer clears CanTransfer, so - // holders are not trapped in AMM, vault, or loan protocol accounts. - auto const waivesCanTransfer = txnType == ttAMM_WITHDRAW || - (view.rules().enabled(fixCleanup3_2_0) && - (txnType == ttVAULT_WITHDRAW || txnType == ttLOAN_BROKER_COVER_WITHDRAW || - txnType == ttLOAN_PAY)); - auto const canTransfer = sleIssuance->isFlag(lsfMPTCanTransfer) || waivesCanTransfer; - auto const canTrade = sleIssuance->isFlag(lsfMPTCanTrade); - auto const reqAuth = sleIssuance->isFlag(lsfMPTRequireAuth); - - for (auto const& [account, value] : values) - { - // Classify each account as a sender or receiver based on whether their MPTAmount - // decreased or increased. Count new MPToken holders (no amtBefore) as receivers. - // Skip deleted MPToken holders (amtAfter is nullopt); deletion requires zero balance. - if (value.amtAfter.has_value() && value.amtBefore.value_or(0) != *value.amtAfter) - { - if (!value.amtBefore.has_value() || *value.amtAfter > *value.amtBefore) - { - ++receivers; - } - else - { - ++senders; - } - - // Check once: if any involved account is frozen, the whole - // issuance transfer is considered frozen. Only need to check for - // frozen if there is a transfer of funds. - if (!invalidTransfer && - (isFrozen(view, account, MPTIssue{mptID}) || - !isAuthorized(view, mptID, account, reqAuth))) - { - invalidTransfer = true; - } - } - } - // A transfer between holders has occurred (senders > 0 && receivers > 0). - // Fail if the issuance is frozen, does not permit transfers, or — for - // DEX transactions — does not permit trading. - if ((invalidTransfer || !canTransfer || (isDEX && !canTrade)) && senders > 0 && - receivers > 0) - { - JLOG(j.fatal()) << "Invariant failed: invalid MPToken transfer between holders"; - return invariantPasses; - } - } - - return true; -} - void ValidConfidentialMPToken::visitEntry( bool isDelete, @@ -638,12 +414,12 @@ ValidConfidentialMPToken::visitEntry( // Helper to get MPToken Issuance ID safely auto const getMptID = [](std::shared_ptr const& sle) -> uint192 { if (!sle) - return beast::kZero; + return beast::kZERO; if (sle->getType() == ltMPTOKEN) return sle->getFieldH192(sfMPTokenIssuanceID); if (sle->getType() == ltMPTOKEN_ISSUANCE) return makeMptID(sle->getFieldU32(sfSequence), sle->getAccountID(sfIssuer)); - return beast::kZero; + return beast::kZERO; }; if (before && before->getType() == ltMPTOKEN) @@ -835,8 +611,8 @@ ValidConfidentialMPToken::finalize( } } else if ( - std::ranges::find(kConfidentialMptTxTypes, tx.getTxnType()) != - kConfidentialMptTxTypes.end()) + std::ranges::find(kCONFIDENTIAL_MPT_TX_TYPES, tx.getTxnType()) != + kCONFIDENTIAL_MPT_TX_TYPES.end()) { // Confidential Txns should not modify public MPTAmount balance // if Confidential Amount Delta is 0 diff --git a/src/libxrpl/tx/invariants/NFTInvariant.cpp b/src/libxrpl/tx/invariants/NFTInvariant.cpp index 52ecbcd9d1..da415d2ad8 100644 --- a/src/libxrpl/tx/invariants/NFTInvariant.cpp +++ b/src/libxrpl/tx/invariants/NFTInvariant.cpp @@ -20,23 +20,27 @@ #include #include +#include #include namespace xrpl { void -ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidNFTokenPage::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { - static constexpr uint256 const& kPageBits = nft::kPageMask; - static constexpr uint256 kAccountBits = ~kPageBits; + static constexpr uint256 const& kPAGE_BITS = nft::kPAGE_MASK; + static constexpr uint256 const kACCOUNT_BITS = ~kPAGE_BITS; if ((before && before->getType() != ltNFTOKEN_PAGE) || (after && after->getType() != ltNFTOKEN_PAGE)) return; - auto check = [this, isDelete](SLE::const_ref sle) { - uint256 const account = sle->key() & kAccountBits; - uint256 const hiLimit = sle->key() & kPageBits; + auto check = [this, isDelete](std::shared_ptr const& sle) { + uint256 const account = sle->key() & kACCOUNT_BITS; + uint256 const hiLimit = sle->key() & kPAGE_BITS; std::optional const prev = (*sle)[~sfPreviousPageMin]; // Make sure that any page links... @@ -44,19 +48,19 @@ ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re // 2. The page is correctly ordered between links. if (prev) { - if (account != (*prev & kAccountBits)) + if (account != (*prev & kACCOUNT_BITS)) badLink_ = true; - if (hiLimit <= (*prev & kPageBits)) + if (hiLimit <= (*prev & kPAGE_BITS)) badLink_ = true; } if (auto const next = (*sle)[~sfNextPageMin]) { - if (account != (*next & kAccountBits)) + if (account != (*next & kACCOUNT_BITS)) badLink_ = true; - if (hiLimit >= (*next & kPageBits)) + if (hiLimit >= (*next & kPAGE_BITS)) badLink_ = true; } @@ -65,12 +69,12 @@ ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re // An NFTokenPage should never contain too many tokens or be empty. if (std::size_t const nftokenCount = nftokens.size(); - (!isDelete && nftokenCount == 0) || nftokenCount > kDirMaxTokensPerPage) + (!isDelete && nftokenCount == 0) || nftokenCount > kDIR_MAX_TOKENS_PER_PAGE) invalidSize_ = true; // If prev is valid, use it to establish a lower bound for // page entries. If prev is not valid the lower bound is zero. - uint256 const loLimit = prev ? *prev & kPageBits : uint256(beast::kZero); + uint256 const loLimit = prev ? *prev & kPAGE_BITS : uint256(beast::kZERO); // Also verify that all NFTokenIDs in the page are sorted. uint256 loCmp = loLimit; @@ -83,7 +87,7 @@ ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re // None of the NFTs on this page should belong on lower or // higher pages. - if (uint256 const tokenPageBits = tokenID & kPageBits; + if (uint256 const tokenPageBits = tokenID & kPAGE_BITS; tokenPageBits < loLimit || tokenPageBits >= hiLimit) badEntry_ = true; @@ -100,7 +104,7 @@ ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re // While an account's NFToken directory contains any NFTokens, the last // NFTokenPage (with 96 bits of 1 in the low part of the index) should // never be deleted. - if (isDelete && (before->key() & nft::kPageMask) == nft::kPageMask && + if (isDelete && (before->key() & nft::kPAGE_MASK) == nft::kPAGE_MASK && before->isFieldPresent(sfPreviousPageMin)) { deletedFinalPage_ = true; @@ -117,7 +121,7 @@ ValidNFTokenPage::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_re // 2. This is not the last page in the directory // Then we have identified a corruption in the links between the // NFToken pages in the NFToken directory. - if ((before->key() & nft::kPageMask) != nft::kPageMask && + if ((before->key() & nft::kPAGE_MASK) != nft::kPAGE_MASK && before->isFieldPresent(sfNextPageMin) && !after->isFieldPresent(sfNextPageMin)) { deletedLink_ = true; @@ -183,7 +187,10 @@ ValidNFTokenPage::finalize( //------------------------------------------------------------------------------ void -NFTokenCountTracking::visitEntry(bool, SLE::const_ref before, SLE::const_ref after) +NFTokenCountTracking::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (before && before->getType() == ltACCOUNT_ROOT) { diff --git a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp index 1014642b36..6466812743 100644 --- a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp @@ -14,10 +14,15 @@ #include #include +#include + namespace xrpl { void -ValidPermissionedDEX::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidPermissionedDEX::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (after && after->getType() == ltDIR_NODE) { @@ -33,19 +38,17 @@ ValidPermissionedDEX::visitEntry(bool isDelete, SLE::const_ref before, SLE::cons } else { - regularOffersOld_ = true; - if (!isDelete) - regularOffers_ = true; + regularOffers_ = true; } - // pre-fixCleanup3_1_3: hybrid offer missing domain, missing + // pre-fixSecurity3_1_3: hybrid offer missing domain, missing // sfAdditionalBooks, or sfAdditionalBooks has more than one entry if (after->isFlag(lsfHybrid) && (!after->isFieldPresent(sfDomainID) || !after->isFieldPresent(sfAdditionalBooks) || after->getFieldArray(sfAdditionalBooks).size() > 1)) badHybridsOld_ = true; - // post-fixCleanup3_1_3: same as above but also catches size == 0 + // post-fixSecurity3_1_3: same as above but also catches size == 0 if (after->isFlag(lsfHybrid) && (!after->isFieldPresent(sfDomainID) || !after->isFieldPresent(sfAdditionalBooks) || after->getFieldArray(sfAdditionalBooks).size() != 1)) @@ -67,7 +70,7 @@ ValidPermissionedDEX::finalize( // For each offercreate transaction, check if // permissioned offers are valid - bool const isMalformed = view.rules().enabled(fixCleanup3_1_3) ? badHybrids_ : badHybridsOld_; + bool const isMalformed = view.rules().enabled(fixSecurity3_1_3) ? badHybrids_ : badHybridsOld_; if (txType == ttOFFER_CREATE && isMalformed) { JLOG(j.fatal()) << "Invariant failed: hybrid offer is malformed"; @@ -97,9 +100,7 @@ ValidPermissionedDEX::finalize( } } - bool const hasRegularOffers = - view.rules().enabled(fixCleanup3_2_0) ? regularOffers_ : regularOffersOld_; - if (hasRegularOffers) + if (regularOffers_) { JLOG(j.fatal()) << "Invariant failed: domain transaction" " affected regular offers"; diff --git a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp index 544a3af2dc..784a2503ca 100644 --- a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp @@ -15,19 +15,23 @@ #include #include +#include #include namespace xrpl { void -ValidPermissionedDomain::visitEntry(bool isDel, SLE::const_ref before, SLE::const_ref after) +ValidPermissionedDomain::visitEntry( + bool isDel, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (before && before->getType() != ltPERMISSIONED_DOMAIN) return; if (after && after->getType() != ltPERMISSIONED_DOMAIN) return; - auto check = [isDel](std::vector& sleStatus, SLE::const_ref sle) { + auto check = [isDel](std::vector& sleStatus, std::shared_ptr const& sle) { auto const& credentials = sle->getFieldArray(sfAcceptedCredentials); auto const sorted = credentials::makeSorted(credentials); @@ -73,7 +77,7 @@ ValidPermissionedDomain::finalize( return false; } - if (sleStatus.credentialsSize > kMaxPermissionedDomainCredentialsArraySize) + if (sleStatus.credentialsSize > kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE) { JLOG(j.fatal()) << "Invariant failed: permissioned domain bad " "credentials size " @@ -98,7 +102,7 @@ ValidPermissionedDomain::finalize( return true; }; - if (view.rules().enabled(fixCleanup3_1_3)) + if (view.rules().enabled(fixPermissionedDomainInvariant)) { // No permissioned domains should be affected if the transaction failed if (!isTesSuccess(result)) diff --git a/src/libxrpl/tx/invariants/VaultInvariant.cpp b/src/libxrpl/tx/invariants/VaultInvariant.cpp index 80b8f36bd9..0dad8c18a0 100644 --- a/src/libxrpl/tx/invariants/VaultInvariant.cpp +++ b/src/libxrpl/tx/invariants/VaultInvariant.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -57,12 +58,15 @@ ValidVault::Shares::make(SLE const& from) ValidVault::Shares self; self.share = MPTIssue(makeMptID(from.getFieldU32(sfSequence), from.getAccountID(sfIssuer))); self.sharesTotal = from.at(sfOutstandingAmount); - self.sharesMaximum = from[~sfMaximumAmount].value_or(kMaxMpTokenAmount); + self.sharesMaximum = from[~sfMaximumAmount].value_or(kMAX_MP_TOKEN_AMOUNT); return self; } void -ValidVault::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) +ValidVault::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { // If `before` is empty, this means an object is being created, in which // case `isDelete` must be false. Otherwise `before` and `after` are set and @@ -77,7 +81,7 @@ ValidVault::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref afte // validation. It is used to validate that the change in account // balances matches the change in vault balances, stored to deltas_ at the // end of this function. - DeltaInfo balanceDelta{.delta = kNumZero, .scale = std::nullopt}; + DeltaInfo balanceDelta{.delta = kNUM_ZERO, .scale = std::nullopt}; std::int8_t sign = 0; if (before) @@ -182,101 +186,6 @@ ValidVault::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref afte } } -std::optional -ValidVault::deltaAssets(AccountID const& id) const -{ - auto const& vaultAsset = afterVault_[0].asset; - auto const lookup = [&](uint256 const& key) -> std::optional { - auto const it = deltas_.find(key); - if (it == deltas_.end()) - return std::nullopt; - return it->second; - }; - - return std::visit( - [&](TIss const& issue) -> std::optional { - if constexpr (std::is_same_v) - { - if (isXRP(issue)) - return lookup(keylet::account(id).key); - auto result = lookup(keylet::line(id, issue).key); - // Trust-line balance is stored from the low-account's perspective; - // negate if id is the high account so the delta is in id's terms. - if (result && id > issue.getIssuer()) - result->delta = -result->delta; - return result; - } - else if constexpr (std::is_same_v) - { - return lookup(keylet::mptoken(issue.getMptID(), id).key); - } - }, - vaultAsset.value()); -} - -std::optional -ValidVault::deltaAssetsTxAccount(STTx const& tx, XRPAmount fee) const -{ - auto const& vaultAsset = afterVault_[0].asset; - auto ret = deltaAssets(tx[sfAccount]); - if (!ret.has_value() || !vaultAsset.native()) - return ret; - - if (auto const delegate = tx[~sfDelegate]; delegate.has_value() && *delegate != tx[sfAccount]) - return ret; - - ret->delta += fee.drops(); - if (ret->delta == kZero) - return std::nullopt; - - return ret; -} - -std::optional -ValidVault::deltaShares(AccountID const& id) const -{ - auto const& afterVault = afterVault_[0]; - auto const it = [&]() { - if (id == afterVault.pseudoId) - return deltas_.find(keylet::mptIssuance(afterVault.shareMPTID).key); - return deltas_.find(keylet::mptoken(afterVault.shareMPTID, id).key); - }(); - - return it != deltas_.end() ? std::optional(it->second) : std::nullopt; -} - -bool -ValidVault::isVaultEmpty(Vault const& vault) -{ - return vault.assetsAvailable == 0 && vault.assetsTotal == 0; -} - -std::int32_t -ValidVault::computeVaultMinScale(DeltaInfo const& vaultDelta, Rules const& rules) const -{ - // Returns the posterior `assetsTotal` scale. - // - // 1. Because STAmounts are normalized, `assetsTotal` (being >= `assetsAvailable`) - // safely represents the coarsest exponent needed for both fields. - // - // 2. The scale may decrease (withdraw/clawback) or increase (deposit). In both cases - // we ensure the vault is in a legitimate state in the post-transaction scale. - auto const& afterVault = afterVault_[0]; - auto const& vaultAsset = afterVault.asset; - if (rules.enabled(fixCleanup3_2_0)) - { - NumberRoundModeGuard const roundGuard(Number::RoundingMode::ToNearest); - return scale(afterVault.assetsTotal, vaultAsset); - } - - auto const& beforeVault = beforeVault_[0]; - auto const totalDelta = - DeltaInfo::makeDelta(beforeVault.assetsTotal, afterVault.assetsTotal, vaultAsset); - auto const availableDelta = - DeltaInfo::makeDelta(beforeVault.assetsAvailable, afterVault.assetsAvailable, vaultAsset); - return computeCoarsestScale({vaultDelta, totalDelta, availableDelta}); -} - bool ValidVault::finalize( STTx const& tx, @@ -370,13 +279,13 @@ ValidVault::finalize( "shares outstanding"; result = false; } - if (beforeVault.assetsTotal != kZero) + if (beforeVault.assetsTotal != kZERO) { JLOG(j.fatal()) << "Invariant failed: deleted vault must have no " "assets outstanding"; result = false; } - if (beforeVault.assetsAvailable != kZero) + if (beforeVault.assetsAvailable != kZERO) { JLOG(j.fatal()) << "Invariant failed: deleted vault must have no " "assets available"; @@ -439,13 +348,13 @@ ValidVault::finalize( if (updatedShares->sharesTotal == 0) { - if (afterVault.assetsTotal != kZero) + if (afterVault.assetsTotal != kZERO) { JLOG(j.fatal()) << "Invariant failed: updated zero sized " "vault must have no assets outstanding"; result = false; } - if (afterVault.assetsAvailable != kZero) + if (afterVault.assetsAvailable != kZERO) { JLOG(j.fatal()) << "Invariant failed: updated zero sized " "vault must have no assets available"; @@ -460,7 +369,7 @@ ValidVault::finalize( result = false; } - if (afterVault.assetsAvailable < kZero) + if (afterVault.assetsAvailable < kZERO) { JLOG(j.fatal()) << "Invariant failed: assets available must be positive"; result = false; @@ -480,13 +389,13 @@ ValidVault::finalize( result = false; } - if (afterVault.assetsTotal < kZero) + if (afterVault.assetsTotal < kZERO) { JLOG(j.fatal()) << "Invariant failed: assets outstanding must be positive"; result = false; } - if (afterVault.assetsMaximum < kZero) + if (afterVault.assetsMaximum < kZERO) { JLOG(j.fatal()) << "Invariant failed: assets maximum must be positive"; result = false; @@ -536,6 +445,61 @@ ValidVault::finalize( } auto const& vaultAsset = afterVault.asset; + auto const deltaAssets = [&](AccountID const& id) -> std::optional { + auto const get = // + [&](auto const& it, std::int8_t sign = 1) -> std::optional { + if (it == deltas_.end()) + return std::nullopt; + + return DeltaInfo{it->second.delta * sign, it->second.scale}; + }; + + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + if (isXRP(issue)) + return get(deltas_.find(keylet::account(id).key)); + return get( + deltas_.find(keylet::line(id, issue).key), id > issue.getIssuer() ? -1 : 1); + } + else if constexpr (std::is_same_v) + { + return get(deltas_.find(keylet::mptoken(issue.getMptID(), id).key)); + } + }, + vaultAsset.value()); + }; + auto const deltaAssetsTxAccount = [&]() -> std::optional { + auto ret = deltaAssets(tx[sfAccount]); + // Nothing returned or not XRP transaction + if (!ret.has_value() || !vaultAsset.native()) + return ret; + + // Delegated transaction; no need to compensate for fees + if (auto const delegate = tx[~sfDelegate]; + delegate.has_value() && *delegate != tx[sfAccount]) + return ret; + + ret->delta += fee.drops(); + if (ret->delta == kZERO) + return std::nullopt; + + return ret; + }; + auto const deltaShares = [&](AccountID const& id) -> std::optional { + auto const it = [&]() { + if (id == afterVault.pseudoId) + return deltas_.find(keylet::mptIssuance(afterVault.shareMPTID).key); + return deltas_.find(keylet::mptoken(afterVault.shareMPTID, id).key); + }(); + + return it != deltas_.end() ? std::optional(it->second) : std::nullopt; + }; + + auto const vaultHoldsNoAssets = [&](Vault const& vault) { + return vault.assetsAvailable == 0 && vault.assetsTotal == 0; + }; // Technically this does not need to be a lambda, but it's more // convenient thanks to early "return false"; the not-so-nice @@ -555,8 +519,8 @@ ValidVault::finalize( result = false; } - if (afterVault.assetsAvailable != kZero || afterVault.assetsTotal != kZero || - afterVault.lossUnrealized != kZero || updatedShares->sharesTotal != 0) + if (afterVault.assetsAvailable != kZERO || afterVault.assetsTotal != kZERO || + afterVault.lossUnrealized != kZERO || updatedShares->sharesTotal != 0) { JLOG(j.fatal()) // << "Invariant failed: created vault must be empty"; @@ -622,7 +586,7 @@ ValidVault::finalize( result = false; } - if (afterVault.assetsMaximum > kZero && + if (afterVault.assetsMaximum > kZERO && afterVault.assetsTotal > afterVault.assetsMaximum) { JLOG(j.fatal()) << // @@ -665,8 +629,16 @@ ValidVault::finalize( return false; // That's all we can do } - // Get the posterior scale to round calculations to - auto const minScale = computeVaultMinScale(*maybeVaultDeltaAssets, view.rules()); + // Get the coarsest scale to round calculations to + auto const totalDelta = DeltaInfo::makeDelta( + beforeVault.assetsTotal, afterVault.assetsTotal, vaultAsset); + auto const availableDelta = DeltaInfo::makeDelta( + beforeVault.assetsAvailable, afterVault.assetsAvailable, vaultAsset); + auto const minScale = computeCoarsestScale({ + *maybeVaultDeltaAssets, + totalDelta, + availableDelta, + }); auto const vaultDeltaAssets = roundToAsset(vaultAsset, maybeVaultDeltaAssets->delta, minScale); @@ -680,7 +652,7 @@ ValidVault::finalize( result = false; } - if (vaultDeltaAssets <= kZero) + if (vaultDeltaAssets <= kZERO) { JLOG(j.fatal()) << // "Invariant failed: deposit must increase vault balance"; @@ -697,11 +669,12 @@ ValidVault::finalize( if (!issuerDeposit) { - auto const maybeAccDeltaAssets = deltaAssetsTxAccount(tx, fee); + auto const maybeAccDeltaAssets = deltaAssetsTxAccount(); if (!maybeAccDeltaAssets) { - JLOG(j.fatal()) - << "Invariant failed: deposit must change depositor balance"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must change depositor " + "balance"; return false; } auto const localMinScale = @@ -712,59 +685,65 @@ ValidVault::finalize( auto const localVaultDeltaAssets = roundToAsset(vaultAsset, vaultDeltaAssets, localMinScale); - // For IOUs, if the deposit amount is not-representable at depositor trustline - // scale deposit amount could round to zero, giving depositor shares for no - // assets. Unlike withdrawal, we do not allow that. - if (accountDeltaAssets >= kZero) + if (accountDeltaAssets >= kZERO) { - JLOG(j.fatal()) - << "Invariant failed: deposit must decrease depositor balance"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must decrease depositor " + "balance"; result = false; } if (localVaultDeltaAssets * -1 != accountDeltaAssets) { - JLOG(j.fatal()) << "Invariant failed: " << // - "deposit must change vault and depositor balance by equal amount"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must change vault and " + "depositor balance by equal amount"; result = false; } } - if (afterVault.assetsMaximum > kZero && + if (afterVault.assetsMaximum > kZERO && afterVault.assetsTotal > afterVault.assetsMaximum) { - JLOG(j.fatal()) << "Invariant failed: " << // - "deposit assets outstanding must not exceed assets maximum"; + JLOG(j.fatal()) << // + "Invariant failed: deposit assets outstanding must not " + "exceed assets maximum"; result = false; } auto const maybeAccDeltaShares = deltaShares(tx[sfAccount]); if (!maybeAccDeltaShares) { - JLOG(j.fatal()) << "Invariant failed: deposit must change depositor shares"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must change depositor " + "shares"; return false; // That's all we can do } - // We don't round shares, they are integral MPT + // We don't need to round shares, they are integral MPT auto const& accountDeltaShares = *maybeAccDeltaShares; - if (accountDeltaShares.delta <= kZero) + if (accountDeltaShares.delta <= kZERO) { - JLOG(j.fatal()) << "Invariant failed: deposit must increase depositor shares"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must increase depositor " + "shares"; result = false; } auto const maybeVaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!maybeVaultDeltaShares || maybeVaultDeltaShares->delta == kZero) + if (!maybeVaultDeltaShares || maybeVaultDeltaShares->delta == kZERO) { - JLOG(j.fatal()) << "Invariant failed: deposit must change vault shares"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must change vault shares"; return false; // That's all we can do } - // We don't round shares, they are integral MPT + // We don't need to round shares, they are integral MPT auto const& vaultDeltaShares = *maybeVaultDeltaShares; if (vaultDeltaShares.delta * -1 != accountDeltaShares.delta) { - JLOG(j.fatal()) << "Invariant failed: " << // - "deposit must change depositor and vault shares by equal amount"; + JLOG(j.fatal()) << // + "Invariant failed: deposit must change depositor and " + "vault shares by equal amount"; result = false; } @@ -772,8 +751,8 @@ ValidVault::finalize( vaultAsset, afterVault.assetsTotal - beforeVault.assetsTotal, minScale); if (assetTotalDelta != vaultDeltaAssets) { - JLOG(j.fatal()) - << "Invariant failed: deposit and assets outstanding must add up"; + JLOG(j.fatal()) << "Invariant failed: deposit and assets " + "outstanding must add up"; result = false; } @@ -781,7 +760,8 @@ ValidVault::finalize( vaultAsset, afterVault.assetsAvailable - beforeVault.assetsAvailable, minScale); if (assetAvailableDelta != vaultDeltaAssets) { - JLOG(j.fatal()) << "Invariant failed: deposit and assets available must add up"; + JLOG(j.fatal()) << "Invariant failed: deposit and assets " + "available must add up"; result = false; } @@ -792,25 +772,34 @@ ValidVault::finalize( XRPL_ASSERT( !beforeVault_.empty(), - "xrpl::ValidVault::finalize : withdrawal updated a vault"); + "xrpl::ValidVault::finalize : withdrawal updated a " + "vault"); auto const& beforeVault = beforeVault_[0]; auto const maybeVaultDeltaAssets = deltaAssets(afterVault.pseudoId); + if (!maybeVaultDeltaAssets) { - JLOG(j.fatal()) << "Invariant failed: withdrawal must change vault balance"; + JLOG(j.fatal()) << "Invariant failed: withdrawal must " + "change vault balance"; return false; // That's all we can do } - // Get the posterior scale to round calculations to - auto const minScale = computeVaultMinScale(*maybeVaultDeltaAssets, view.rules()); + // Get the most coarse scale to round calculations to + auto const totalDelta = DeltaInfo::makeDelta( + beforeVault.assetsTotal, afterVault.assetsTotal, vaultAsset); + auto const availableDelta = DeltaInfo::makeDelta( + beforeVault.assetsAvailable, afterVault.assetsAvailable, vaultAsset); + auto const minScale = + computeCoarsestScale({*maybeVaultDeltaAssets, totalDelta, availableDelta}); auto const vaultPseudoDeltaAssets = roundToAsset(vaultAsset, maybeVaultDeltaAssets->delta, minScale); - if (vaultPseudoDeltaAssets >= kZero) + if (vaultPseudoDeltaAssets >= kZERO) { - JLOG(j.fatal()) << "Invariant failed: withdrawal must decrease vault balance"; + JLOG(j.fatal()) << "Invariant failed: withdrawal must " + "decrease vault balance"; result = false; } @@ -825,7 +814,7 @@ ValidVault::finalize( if (!issuerWithdrawal) { - auto const maybeAccDelta = deltaAssetsTxAccount(tx, fee); + auto const maybeAccDelta = deltaAssetsTxAccount(); auto const maybeOtherAccDelta = [&]() -> std::optional { if (auto const destination = tx[~sfDestination]; destination && *destination != tx[sfAccount]) @@ -836,7 +825,8 @@ ValidVault::finalize( if (maybeAccDelta.has_value() == maybeOtherAccDelta.has_value()) { JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change one destination balance"; + "Invariant failed: withdrawal must change one " + "destination balance"; return false; } @@ -845,83 +835,63 @@ ValidVault::finalize( // the scale of destinationDelta can be coarser than // minScale, so we take that into account when rounding - auto const destinationScale = computeCoarsestScale({destinationDelta}); - auto const localMinScale = std::max(minScale, destinationScale); + auto const localMinScale = + std::max(minScale, computeCoarsestScale({destinationDelta})); auto const roundedDestinationDelta = roundToAsset(vaultAsset, destinationDelta.delta, localMinScale); - // Post-fixCleanup3_2_0: Tolerate zero-rounded destination deltas for IOUs only. - // If the receiver's trust line sits at a coarser scale, the inflow may - // safely round down to zero. - // - // XRP and MPT remain strict. Because they are integer-exact, a zero - // destination delta indicates a true accounting bug, not a rounding artifact. - bool const tolerateZeroDelta = - view.rules().enabled(fixCleanup3_2_0) && !vaultAsset.integral(); - auto const invalidBalanceChange = tolerateZeroDelta - ? roundedDestinationDelta < kZero - : roundedDestinationDelta <= kZero; - if (invalidBalanceChange) + if (roundedDestinationDelta <= kZERO) { JLOG(j.fatal()) << // - "Invariant failed: withdrawal must increase destination balance"; + "Invariant failed: withdrawal must increase " + "destination balance"; result = false; } auto const localPseudoDeltaAssets = roundToAsset(vaultAsset, vaultPseudoDeltaAssets, localMinScale); - // For IOU assets near a precision boundary the destination's STAmount - // exponent can shift, making part of the sent value unrepresentable at the - // receiver's new scale — that portion is irreversibly absorbed by the IOU - // rail. Tolerate the mismatch only when the destroyed amount (vault outflow - // minus destination inflow, in Number space) is itself sub-ULP at the - // destination's scale. Floor rounding is used so that values exactly at the - // step boundary are not mistakenly dismissed. Any representable discrepancy - // indicates a real accounting bug and must be caught. - auto const destroyedIsSubUlp = tolerateZeroDelta && - roundToAsset( - vaultAsset, - maybeVaultDeltaAssets->delta * -1 - destinationDelta.delta, - destinationScale, - Number::RoundingMode::Downward) == kZero; - if (!destroyedIsSubUlp && - localPseudoDeltaAssets * -1 != roundedDestinationDelta) + if (localPseudoDeltaAssets * -1 != roundedDestinationDelta) { - JLOG(j.fatal()) << "Invariant failed: " << // - "withdrawal must change vault and destination balance by equal " - "amount"; + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change vault " + "and destination balance by equal amount"; result = false; } } - // We don't round shares, they are integral MPT + // We don't need to round shares, they are integral MPT auto const accountDeltaShares = deltaShares(tx[sfAccount]); if (!accountDeltaShares) { - JLOG(j.fatal()) << "Invariant failed: withdrawal must change depositor shares"; + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change depositor " + "shares"; return false; } - if (accountDeltaShares->delta >= kZero) + if (accountDeltaShares->delta >= kZERO) { - JLOG(j.fatal()) - << "Invariant failed: withdrawal must decrease depositor shares"; + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must decrease depositor " + "shares"; result = false; } - // We don't round shares, they are integral MPT + // We don't need to round shares, they are integral MPT auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!vaultDeltaShares || vaultDeltaShares->delta == kZero) + if (!vaultDeltaShares || vaultDeltaShares->delta == kZERO) { - JLOG(j.fatal()) << "Invariant failed: withdrawal must change vault shares"; + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change vault shares"; return false; // That's all we can do } if (vaultDeltaShares->delta * -1 != accountDeltaShares->delta) { - JLOG(j.fatal()) << "Invariant failed: " << // - "withdrawal must change depositor and vault shares by equal amount"; + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change depositor " + "and vault shares by equal amount"; result = false; } @@ -930,8 +900,8 @@ ValidVault::finalize( // Note, vaultBalance is negative (see check above) if (assetTotalDelta != vaultPseudoDeltaAssets) { - JLOG(j.fatal()) - << "Invariant failed: withdrawal and assets outstanding must add up"; + JLOG(j.fatal()) << "Invariant failed: withdrawal and " + "assets outstanding must add up"; result = false; } @@ -940,8 +910,8 @@ ValidVault::finalize( if (assetAvailableDelta != vaultPseudoDeltaAssets) { - JLOG(j.fatal()) - << "Invariant failed: withdrawal and assets available must add up"; + JLOG(j.fatal()) << "Invariant failed: withdrawal and " + "assets available must add up"; result = false; } @@ -959,11 +929,12 @@ ValidVault::finalize( // The owner can use clawback to force-burn shares when the // vault is empty but there are outstanding shares if (!(beforeShares && beforeShares->sharesTotal > 0 && - isVaultEmpty(beforeVault) && beforeVault.owner == tx[sfAccount])) + vaultHoldsNoAssets(beforeVault) && beforeVault.owner == tx[sfAccount])) { - JLOG(j.fatal()) << "Invariant failed: " << // - "clawback may only be performed by the asset issuer, or by the vault " - "owner of an empty vault"; + JLOG(j.fatal()) << // + "Invariant failed: clawback may only be performed " + "by the asset issuer, or by the vault owner of an " + "empty vault"; return false; // That's all we can do } } @@ -971,13 +942,19 @@ ValidVault::finalize( auto const maybeVaultDeltaAssets = deltaAssets(afterVault.pseudoId); if (maybeVaultDeltaAssets) { + auto const totalDelta = DeltaInfo::makeDelta( + beforeVault.assetsTotal, afterVault.assetsTotal, vaultAsset); + auto const availableDelta = DeltaInfo::makeDelta( + beforeVault.assetsAvailable, afterVault.assetsAvailable, vaultAsset); auto const minScale = - computeVaultMinScale(*maybeVaultDeltaAssets, view.rules()); + computeCoarsestScale({*maybeVaultDeltaAssets, totalDelta, availableDelta}); auto const vaultDeltaAssets = roundToAsset(vaultAsset, maybeVaultDeltaAssets->delta, minScale); - if (vaultDeltaAssets >= kZero) + if (vaultDeltaAssets >= kZERO) { - JLOG(j.fatal()) << "Invariant failed: clawback must decrease vault balance"; + JLOG(j.fatal()) << // + "Invariant failed: clawback must decrease vault " + "balance"; result = false; } @@ -986,7 +963,8 @@ ValidVault::finalize( if (assetsTotalDelta != vaultDeltaAssets) { JLOG(j.fatal()) << // - "Invariant failed: clawback and assets outstanding must add up"; + "Invariant failed: clawback and assets outstanding " + "must add up"; result = false; } @@ -997,11 +975,12 @@ ValidVault::finalize( if (assetAvailableDelta != vaultDeltaAssets) { JLOG(j.fatal()) << // - "Invariant failed: clawback and assets available must add up"; + "Invariant failed: clawback and assets available " + "must add up"; result = false; } } - else if (!isVaultEmpty(beforeVault)) + else if (!vaultHoldsNoAssets(beforeVault)) { JLOG(j.fatal()) << // "Invariant failed: clawback must change vault balance"; @@ -1016,16 +995,17 @@ ValidVault::finalize( "Invariant failed: clawback must change holder shares"; return false; // That's all we can do } - if (maybeAccountDeltaShares->delta >= kZero) + if (maybeAccountDeltaShares->delta >= kZERO) { JLOG(j.fatal()) << // - "Invariant failed: clawback must decrease holder shares"; + "Invariant failed: clawback must decrease holder " + "shares"; result = false; } // We don't need to round shares, they are integral MPT auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!vaultDeltaShares || vaultDeltaShares->delta == kZero) + if (!vaultDeltaShares || vaultDeltaShares->delta == kZERO) { JLOG(j.fatal()) << // "Invariant failed: clawback must change vault shares"; @@ -1034,8 +1014,9 @@ ValidVault::finalize( if (vaultDeltaShares->delta * -1 != maybeAccountDeltaShares->delta) { - JLOG(j.fatal()) << "Invariant failed: " << // - "clawback must change holder and vault shares by equal amount"; + JLOG(j.fatal()) << // + "Invariant failed: clawback must change holder and " + "vault shares by equal amount"; result = false; } @@ -1086,7 +1067,7 @@ ValidVault::computeCoarsestScale(std::vector const& numbers) numbers, [](auto const& a, auto const& b) -> bool { return a.scale < b.scale; }); XRPL_ASSERT_PARTS( max->scale, "xrpl::ValidVault::computeCoarsestScale", "scale set for destinationDelta"); - return max->scale.value_or(STAmount::kMaxOffset); + return max->scale.value_or(STAmount::kMAX_OFFSET); } } // namespace xrpl diff --git a/src/libxrpl/tx/paths/AMMLiquidity.cpp b/src/libxrpl/tx/paths/AMMLiquidity.cpp index 0d1c66ead8..87eb29f104 100644 --- a/src/libxrpl/tx/paths/AMMLiquidity.cpp +++ b/src/libxrpl/tx/paths/AMMLiquidity.cpp @@ -54,7 +54,7 @@ AMMLiquidity::fetchBalances(ReadView const& view) const auto const amountIn = ammAccountHolds(view, ammAccountID_, assetIn_); auto const amountOut = ammAccountHolds(view, ammAccountID_, assetOut_); // This should not happen. - if (amountIn < beast::kZero || amountOut < beast::kZero) + if (amountIn < beast::kZERO || amountOut < beast::kZERO) Throw("AMMLiquidity: invalid balances"); return TAmounts{get(amountIn), get(amountOut)}; @@ -68,7 +68,7 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances cur.in = toAmount( getAsset(balances.in), - kInitialFibSeqPct * initialBalances_.in, + kINITIAL_FIB_SEQ_PCT * initialBalances_.in, Number::RoundingMode::Upward); cur.out = swapAssetIn(initialBalances_, cur.in, tradingFee_); @@ -76,7 +76,7 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances return cur; // clang-format off - static constexpr std::uint32_t kFib[AMMContext::kMaxIterations] = { + constexpr std::uint32_t kFIB[AMMContext::kMAX_ITERATIONS] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269}; @@ -88,7 +88,7 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances cur.out = toAmount( getAsset(balances.out), - cur.out * kFib[ammContext_.curIters() - 1], + cur.out * kFIB[ammContext_.curIters() - 1], Number::RoundingMode::Downward); // swapAssetOut() returns negative in this case if (cur.out >= balances.out) @@ -106,19 +106,19 @@ maxAmount() { if constexpr (std::is_same_v) { - return XRPAmount(STAmount::kMaxNative); + return XRPAmount(STAmount::kMAX_NATIVE); } else if constexpr (std::is_same_v) { - return IOUAmount(STAmount::kMaxValue / 2, STAmount::kMaxOffset); + return IOUAmount(STAmount::kMAX_VALUE / 2, STAmount::kMAX_OFFSET); } else if constexpr (std::is_same_v) { - return STAmount(STAmount::kMaxValue / 2, STAmount::kMaxOffset); + return STAmount(STAmount::kMAX_VALUE / 2, STAmount::kMAX_OFFSET); } else if constexpr (std::is_same_v) { - return MPTAmount(kMaxMpTokenAmount); + return MPTAmount(kMAX_MP_TOKEN_AMOUNT); } } @@ -163,7 +163,7 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c auto const balances = fetchBalances(view); // Frozen accounts - if (balances.in == beast::kZero || balances.out == beast::kZero) + if (balances.in == beast::kZERO || balances.out == beast::kZERO) { JLOG(j_.debug()) << "AMMLiquidity::getOffer, frozen accounts"; return std::nullopt; @@ -239,7 +239,7 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c if (offer) { - if (offer->amount().in > beast::kZero && offer->amount().out > beast::kZero) + if (offer->amount().in > beast::kZERO && offer->amount().out > beast::kZERO) { JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in) << "/" << assetIn_ << " " << to_string(offer->amount().out) << "/" diff --git a/src/libxrpl/tx/paths/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp index 5cc2a987b8..113155e530 100644 --- a/src/libxrpl/tx/paths/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -57,7 +57,7 @@ class BookStep : public StepImp> protected: enum class OfferType { Amm, Clob }; - static constexpr uint32_t kMaxOffersToConsume{1000}; + static constexpr uint32_t kMAX_OFFERS_TO_CONSUME{1000}; Book book_; AccountID strandSrc_; AccountID strandDst_; @@ -104,7 +104,7 @@ private: , strandDeliver_(ctx.strandDeliver) { if (auto const ammSle = ctx.view.read(keylet::amm(in, out)); - ammSle && ammSle->getFieldAmount(sfLPTokenBalance) != beast::kZero) + ammSle && ammSle->getFieldAmount(sfLPTokenBalance) != beast::kZERO) { ammLiquidity_.emplace( ctx.view, @@ -350,12 +350,12 @@ public: // Calculate amount that goes to the taker and the amount charged the // offer owner auto const trIn = - redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kParityRate; + redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kPARITY_RATE; // Always charge the transfer fee, even if the owner is the issuer, // unless the fee is waived auto const trOut = (this->ownerPaysTransferFee_ && waiveFee == WaiveTransferFee::No) ? this->rate(v, this->book_.out, this->strandDst_) - : kParityRate; + : kPARITY_RATE; Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))}; return composedQuality(q1, ofrQ); @@ -537,9 +537,9 @@ public: } auto const trIn = - redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kParityRate; + redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kPARITY_RATE; // AMM doesn't pay the transfer fee on the out amount - auto const trOut = kParityRate; + auto const trOut = kPARITY_RATE; Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))}; return composedQuality(q1, ofrQ); @@ -598,10 +598,10 @@ BookStep::getQualityFunc(ReadView const& v, DebtDirection p // AMM if (!res->isConst()) { - auto static const kQOne = Quality{STAmount::kURateOne}; + auto static const kQ_ONE = Quality{STAmount::kU_RATE_ONE}; auto const q = static_cast(this)->adjustQualityWithFees( - v, kQOne, prevStepDir, WaiveTransferFee::Yes, OfferType::Amm, v.rules()); - if (q == kQOne) + v, kQ_ONE, prevStepDir, WaiveTransferFee::Yes, OfferType::Amm, v.rules()); + if (q == kQ_ONE) return {res, dir}; QualityFunction qf{q, QualityFunction::CLOBLikeTag{}}; qf.combine(*res); @@ -700,7 +700,7 @@ BookStep::forEachOffer( std::uint32_t const trOut = ownerPaysTransferFee_ ? rate(sb, book_.out, this->strandDst_).value : QUALITY_ONE; - typename FlowOfferStream::StepCounter counter(kMaxOffersToConsume, j_); + typename FlowOfferStream::StepCounter counter(kMAX_OFFERS_TO_CONSUME, j_); FlowOfferStream offers(sb, afView, book_, sb.parentCloseTime(), counter, j_); @@ -989,7 +989,7 @@ sum(TCollection const& col) { using TResult = std::decay_t; if (col.empty()) - return TResult{beast::kZero}; + return TResult{beast::kZERO}; return std::accumulate(col.begin() + 1, col.end(), *col.begin()); }; @@ -1003,7 +1003,7 @@ BookStep::revImp( { cache_.reset(); - TAmounts result(beast::kZero, beast::kZero); + TAmounts result(beast::kZERO, beast::kZERO); auto remainingOut = out; @@ -1022,7 +1022,7 @@ BookStep::revImp( TOut const& ownerGives, std::uint32_t transferRateIn, std::uint32_t transferRateOut) mutable -> bool { - if (remainingOut <= beast::kZero) + if (remainingOut <= beast::kZERO) return false; if (stpAmt.out <= remainingOut) @@ -1048,7 +1048,7 @@ BookStep::revImp( transferRateIn, transferRateOut, remainingOut); - remainingOut = beast::kZero; + remainingOut = beast::kZERO; savedIns.insert(stpAdjAmt.in); savedOuts.insert(remainingOut); result.in = sum(savedIns); @@ -1076,7 +1076,7 @@ BookStep::revImp( setUnion(ofrsToRm, toRm); // Too many iterations, mark this strand as inactive - if (offersConsumed >= kMaxOffersToConsume) + if (offersConsumed >= kMAX_OFFERS_TO_CONSUME) { inactive_ = true; } @@ -1089,8 +1089,8 @@ BookStep::revImp( // LCOV_EXCL_START JLOG(j_.error()) << "BookStep remainingOut < 0 " << to_string(remainingOut); UNREACHABLE("xrpl::BookStep::revImp : remaining less than zero"); - cache_.emplace(beast::kZero, beast::kZero); - return {beast::kZero, beast::kZero}; + cache_.emplace(beast::kZERO, beast::kZERO); + return {beast::kZERO, beast::kZERO}; // LCOV_EXCL_STOP } case 0: { @@ -1114,7 +1114,7 @@ BookStep::fwdImp( { XRPL_ASSERT(cache_, "xrpl::BookStep::fwdImp : cache is set"); - TAmounts result(beast::kZero, beast::kZero); + TAmounts result(beast::kZERO, beast::kZERO); auto remainingIn = in; @@ -1133,7 +1133,7 @@ BookStep::fwdImp( std::uint32_t transferRateOut) mutable -> bool { XRPL_ASSERT(cache_, "xrpl::BookStep::fwdImp::eachOffer : cache is set"); - if (remainingIn <= beast::kZero) + if (remainingIn <= beast::kZERO) return false; bool processMore = true; @@ -1238,7 +1238,7 @@ BookStep::fwdImp( setUnion(ofrsToRm, toRm); // Too many iterations, mark this strand as inactive (dry) - if (offersConsumed >= kMaxOffersToConsume) + if (offersConsumed >= kMAX_OFFERS_TO_CONSUME) { inactive_ = true; } @@ -1251,8 +1251,8 @@ BookStep::fwdImp( // something went very wrong JLOG(j_.error()) << "BookStep remainingIn < 0 " << to_string(remainingIn); UNREACHABLE("xrpl::BookStep::fwdImp : remaining less than zero"); - cache_.emplace(beast::kZero, beast::kZero); - return {beast::kZero, beast::kZero}; + cache_.emplace(beast::kZERO, beast::kZERO); + return {beast::kZERO, beast::kZERO}; // LCOV_EXCL_STOP } case 0: { @@ -1276,7 +1276,7 @@ BookStep::validFwd( if (!cache_) { JLOG(j_.trace()) << "Expected valid cache in validFwd"; - return {false, EitherAmount(TOut(beast::kZero))}; + return {false, EitherAmount(TOut(beast::kZERO))}; } auto const savCache = *cache_; @@ -1288,7 +1288,7 @@ BookStep::validFwd( } catch (FlowException const&) { - return {false, EitherAmount(TOut(beast::kZero))}; + return {false, EitherAmount(TOut(beast::kZERO))}; } // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success @@ -1357,22 +1357,24 @@ BookStep::check(StrandContext const& ctx) const auto sle = view.read(keylet::line(*prev, cur, issue.currency)); if (!sle) return terNO_LINE; - if (sle->isFlag((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) + if (((*sle)[sfFlags] & ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) != + 0u) return terNO_RIPPLE; return std::nullopt; }, - [&](MPTIssue const& issue) -> std::optional { return std::nullopt; }); + [&](MPTIssue const& issue) -> std::optional { + // Check if can trade on DEX. + if (auto const ter = canTrade(view, book_.in); !isTesSuccess(ter)) + return ter; + if (auto const ter = canTrade(view, book_.out); !isTesSuccess(ter)) + return ter; + return std::nullopt; + }); if (err) return *err; } } - // Check if the offer can be traded on DEX. - if (auto const ter = canTrade(ctx.view, book_.in); !isTesSuccess(ter)) - return ter; - if (auto const ter = canTrade(ctx.view, book_.out); !isTesSuccess(ter)) - return ter; - return tesSUCCESS; } @@ -1383,22 +1385,12 @@ BookStep::rate( Asset const& asset, AccountID const& dstAccount) const { + auto const& issuer = asset.getIssuer(); + if (isXRP(issuer) || issuer == dstAccount) + return kPARITY_RATE; return asset.visit( - [&](Issue const& issue) -> Rate { - if (isXRP(issue.account) || issue.account == dstAccount) - return kParityRate; - return transferRate(view, issue.account); - }, - [&](MPTIssue const& mptIssue) -> Rate { - // For MPT, parity applies only when this asset is the final strand - // delivery AND the destination is the MPT issuer (holder → issuer, - // which is fee-free). Using strandDst_ alone is wrong because it - // incorrectly suppresses the fee when MPT is an intermediate or - // the in-side of a book that precedes the issuer's XRP receipt. - if (asset == strandDeliver_ && mptIssue.getIssuer() == dstAccount) - return kParityRate; - return transferRate(view, mptIssue.getMptID()); - }); + [&](Issue const&) { return transferRate(view, issuer); }, + [&](MPTIssue const& issue) { return transferRate(view, issue.getMptID()); }); }; template diff --git a/src/libxrpl/tx/paths/BookTip.cpp b/src/libxrpl/tx/paths/BookTip.cpp index eda11e5d72..5be512aa84 100644 --- a/src/libxrpl/tx/paths/BookTip.cpp +++ b/src/libxrpl/tx/paths/BookTip.cpp @@ -8,6 +8,8 @@ #include #include +#include + namespace xrpl { BookTip::BookTip(ApplyView& view, Book const& book) @@ -38,7 +40,7 @@ BookTip::step(beast::Journal j) return false; unsigned int di = 0; - SLE::pointer dir; + std::shared_ptr dir; if (dirFirst(view_, *firstPage, dir, di, index_)) { diff --git a/src/libxrpl/tx/paths/DirectStep.cpp b/src/libxrpl/tx/paths/DirectStep.cpp index cc6e75ea3d..7373f8a341 100644 --- a/src/libxrpl/tx/paths/DirectStep.cpp +++ b/src/libxrpl/tx/paths/DirectStep.cpp @@ -269,7 +269,7 @@ public: // Verify the consistency of the step. These checks are specific to // payments and assume that general checks were already performed. [[nodiscard]] TER - check(StrandContext const& ctx, SLE::const_ref sleSrc) const; + check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; [[nodiscard]] std::string logString() const override @@ -327,7 +327,7 @@ public: // Verify the consistency of the step. These checks are specific to // offer crossing and assume that general checks were already performed. static TER - check(StrandContext const& ctx, SLE::const_ref sleSrc); + check(StrandContext const& ctx, std::shared_ptr const& sleSrc); [[nodiscard]] std::string logString() const override @@ -415,7 +415,7 @@ DirectIOfferCrossingStep::maxFlow(ReadView const& sb, IOUAmount const& desired) } TER -DirectIPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const +DirectIPaymentStep::check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const { // Since this is a payment a trust line must be present. Perform all // trust line related checks. @@ -429,8 +429,8 @@ DirectIPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const auto const authField = (src_ > dst_) ? lsfHighAuth : lsfLowAuth; - if (sleSrc->isFlag(lsfRequireAuth) && !sleLine->isFlag(authField) && - (*sleLine)[sfBalance] == beast::kZero) + if ((((*sleSrc)[sfFlags] & lsfRequireAuth) != 0u) && + (((*sleLine)[sfFlags] & authField) == 0u) && (*sleLine)[sfBalance] == beast::kZERO) { JLOG(j_.debug()) << "DirectStepI: can't receive IOUs from issuer without auth." << " src: " << src_; @@ -441,7 +441,9 @@ DirectIPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const { if (ctx.prevStep->bookStepBook()) { - if (sleLine->isFlag((src_ > dst_) ? lsfHighNoRipple : lsfLowNoRipple)) + auto const noRippleSrcToDst = + ((*sleLine)[sfFlags] & ((src_ > dst_) ? lsfHighNoRipple : lsfLowNoRipple)); + if (noRippleSrcToDst != 0u) return terNO_RIPPLE; } } @@ -449,7 +451,7 @@ DirectIPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const { auto const owed = creditBalance(ctx.view, dst_, src_, currency_); - if (owed <= beast::kZero) + if (owed <= beast::kZERO) { auto const limit = creditLimit(ctx.view, dst_, src_, currency_); if (-owed >= limit) @@ -463,7 +465,7 @@ DirectIPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const } TER -DirectIOfferCrossingStep::check(StrandContext const&, SLE::const_ref) +DirectIOfferCrossingStep::check(StrandContext const&, std::shared_ptr const&) { // The standard checks are all we can do because any remaining checks // require the existence of a trust line. Offer crossing does not @@ -526,8 +528,8 @@ DirectStepI::revImp( { JLOG(j_.trace()) << "DirectStepI::rev: dry"; cache_.emplace( - IOUAmount(beast::kZero), IOUAmount(beast::kZero), IOUAmount(beast::kZero), srcDebtDir); - return {beast::kZero, beast::kZero}; + IOUAmount(beast::kZERO), IOUAmount(beast::kZERO), IOUAmount(beast::kZERO), srcDebtDir); + return {beast::kZERO, beast::kZERO}; } IOUAmount const srcToDst = mulRatio(out, QUALITY_ONE, dstQIn, /*roundUp*/ true); @@ -639,8 +641,8 @@ DirectStepI::fwdImp( { JLOG(j_.trace()) << "DirectStepI::fwd: dry"; cache_.emplace( - IOUAmount(beast::kZero), IOUAmount(beast::kZero), IOUAmount(beast::kZero), srcDebtDir); - return {beast::kZero, beast::kZero}; + IOUAmount(beast::kZERO), IOUAmount(beast::kZERO), IOUAmount(beast::kZERO), srcDebtDir); + return {beast::kZERO, beast::kZERO}; } IOUAmount const srcToDst = mulRatio(in, QUALITY_ONE, srcQOut, /*roundUp*/ false); @@ -688,7 +690,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo if (!cache_) { JLOG(j_.trace()) << "Expected valid cache in validFwd"; - return {false, EitherAmount(IOUAmount(beast::kZero))}; + return {false, EitherAmount(IOUAmount(beast::kZERO))}; } auto const savCache = *cache_; @@ -706,7 +708,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo } catch (FlowException const&) { - return {false, EitherAmount(IOUAmount(beast::kZero))}; + return {false, EitherAmount(IOUAmount(beast::kZERO))}; } // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success diff --git a/src/libxrpl/tx/paths/MPTEndpointStep.cpp b/src/libxrpl/tx/paths/MPTEndpointStep.cpp index 7dcd6d9241..25c9062e47 100644 --- a/src/libxrpl/tx/paths/MPTEndpointStep.cpp +++ b/src/libxrpl/tx/paths/MPTEndpointStep.cpp @@ -264,7 +264,7 @@ public: // Verify the consistency of the step. These checks are specific to // payments and assume that general checks were already performed. [[nodiscard]] TER - check(StrandContext const& ctx, SLE::const_ref sleSrc) const; + check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; [[nodiscard]] std::string logString() const override @@ -312,7 +312,7 @@ public: // Verify the consistency of the step. These checks are specific to // offer crossing and assume that general checks were already performed. static TER - check(StrandContext const& ctx, SLE::const_ref sleSrc); + check(StrandContext const& ctx, std::shared_ptr const& sleSrc); [[nodiscard]] std::string logString() const override @@ -328,7 +328,8 @@ public: //------------------------------------------------------------------------------ TER -MPTEndpointPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) const +MPTEndpointPaymentStep::check(StrandContext const& ctx, std::shared_ptr const& sleSrc) + const { // Since this is a payment, MPToken must be present. Perform all // MPToken related checks. @@ -384,7 +385,7 @@ MPTEndpointPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) c auto const owed = accountFunds( ctx.view, src_, mptIssue_, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); // Already at MaximumAmount - if (owed <= beast::kZero) + if (owed <= beast::kZERO) return tecPATH_DRY; } @@ -392,11 +393,8 @@ MPTEndpointPaymentStep::check(StrandContext const& ctx, SLE::const_ref sleSrc) c } TER -MPTEndpointOfferCrossingStep::check(StrandContext const& ctx, SLE::const_ref) +MPTEndpointOfferCrossingStep::check(StrandContext const& ctx, std::shared_ptr const&) { - // The standard checks are all we can do because any remaining checks - // require the existence of a MPToken. Offer crossing does not - // require a pre-existing MPToken. return tesSUCCESS; } @@ -489,12 +487,12 @@ MPTEndpointStep::revImp( { JLOG(j_.trace()) << "MPTEndpointStep::rev: dry"; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } if (auto const err = static_cast(this)->checkCreateMPT(sb, srcDebtDir); !isTesSuccess(err)) - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; // Don't have to factor in dstQIn since it is always QUALITY_ONE MPTAmount const srcToDst = out; @@ -514,7 +512,7 @@ MPTEndpointStep::revImp( { JLOG(j_.trace()) << "MPTEndpointStep::rev: error " << ter; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } JLOG(j_.trace()) << "MPTEndpointStep::rev: Non-limiting" << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) @@ -539,7 +537,7 @@ MPTEndpointStep::revImp( { JLOG(j_.trace()) << "MPTEndpointStep::rev: error " << ter; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } JLOG(j_.trace()) << "MPTEndpointStep::rev: Limiting" << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) @@ -620,12 +618,12 @@ MPTEndpointStep::fwdImp( { JLOG(j_.trace()) << "MPTEndpointStep::fwd: dry"; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } if (auto const err = static_cast(this)->checkCreateMPT(sb, srcDebtDir); !isTesSuccess(err)) - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; MPTAmount const srcToDst = mulRatio(in, QUALITY_ONE, srcQOut, /*roundUp*/ false); @@ -645,7 +643,7 @@ MPTEndpointStep::fwdImp( { JLOG(j_.trace()) << "MPTEndpointStep::fwd: error " << ter; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } JLOG(j_.trace()) << "MPTEndpointStep::fwd: Non-limiting" << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) @@ -669,7 +667,7 @@ MPTEndpointStep::fwdImp( { JLOG(j_.trace()) << "MPTEndpointStep::fwd: error " << ter; resetCache(srcDebtDir); - return {beast::kZero, beast::kZero}; + return {beast::kZERO, beast::kZERO}; } JLOG(j_.trace()) << "MPTEndpointStep::fwd: Limiting" << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(actualIn) @@ -686,7 +684,7 @@ MPTEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe if (!cache_) { JLOG(j_.trace()) << "Expected valid cache in validFwd"; - return {false, EitherAmount(MPTAmount(beast::kZero))}; + return {false, EitherAmount(MPTAmount(beast::kZERO))}; } auto const savCache = *cache_; @@ -703,7 +701,7 @@ MPTEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe } catch (FlowException const&) { - return {false, EitherAmount(MPTAmount(beast::kZero))}; + return {false, EitherAmount(MPTAmount(beast::kZERO))}; } // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success @@ -840,17 +838,10 @@ MPTEndpointStep::check(StrandContext const& ctx) const } // pure issue/redeem can't be frozen (issuer/holder) - // For the first step: check global freeze of the step's own asset. - // For the last step: check only the per-holder MPToken lock. - // Global freeze of the deliver asset is not checked here - // because MPT semantics allow issuer<->holder transfers even when globally - // locked — only holder-to-holder DEX paths are restricted. if (!(ctx.isLast && ctx.isFirst)) { auto const& account = ctx.isFirst ? src_ : dst_; - bool const frozen = (ctx.isFirst && isGlobalFrozen(ctx.view, mptIssue_)) || - isIndividualFrozen(ctx.view, account, mptIssue_); - if (frozen) + if (isFrozen(ctx.view, account, mptIssue_)) return terLOCKED; } @@ -902,7 +893,7 @@ template void MPTEndpointStep::resetCache(xrpl::DebtDirection dir) { - cache_.emplace(MPTAmount(beast::kZero), MPTAmount(beast::kZero), MPTAmount(beast::kZero), dir); + cache_.emplace(MPTAmount(beast::kZERO), MPTAmount(beast::kZERO), MPTAmount(beast::kZERO), dir); } //------------------------------------------------------------------------------ diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index b7defb4df8..b5ac45503a 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -27,6 +27,7 @@ #include #include +#include #include namespace xrpl { @@ -137,10 +138,10 @@ TOfferStreamBase::shouldRmSmallIncreasedQOffer() const // Consider removing the offer if: // o `TakerPays` is XRP (because of XRP drops granularity) or // o `TakerPays` and `TakerGets` are both IOU and `TakerPays`<`TakerGets` - static constexpr bool kInIsXrp = std::is_same_v; - static constexpr bool kOutIsXrp = std::is_same_v; + constexpr bool const kIN_IS_XRP = std::is_same_v; + constexpr bool const kOUT_IS_XRP = std::is_same_v; - if constexpr (kOutIsXrp) + if constexpr (kOUT_IS_XRP) { // If `TakerGets` is XRP, the worst this offer's quality can change is // to about 10^-81 `TakerPays` and 1 drop `TakerGets`. This will be @@ -155,7 +156,7 @@ TOfferStreamBase::shouldRmSmallIncreasedQOffer() const TAmounts const ofrAmts{ toAmount(offer_.amount().in), toAmount(offer_.amount().out)}; - if constexpr (!kInIsXrp && !kOutIsXrp) + if constexpr (!kIN_IS_XRP && !kOUT_IS_XRP) { if (Number(ofrAmts.in) >= Number(ofrAmts.out)) return false; @@ -204,7 +205,7 @@ TOfferStreamBase::step() if (!tip_.step(j_)) return false; - SLE::pointer const entry = tip_.entry(); + std::shared_ptr const entry = tip_.entry(); // If we exceed the maximum number of allowed steps, we're done. if (!counter_.step()) @@ -270,7 +271,7 @@ TOfferStreamBase::step() j_); // Check for unfunded offer - if (*ownerFunds_ <= beast::kZero) + if (*ownerFunds_ <= beast::kZERO) { // If the owner's balance in the pristine view is the same, // we haven't modified the balance and therefore the diff --git a/src/libxrpl/tx/paths/PaySteps.cpp b/src/libxrpl/tx/paths/PaySteps.cpp index 0a5adeb77f..68bd501d87 100644 --- a/src/libxrpl/tx/paths/PaySteps.cpp +++ b/src/libxrpl/tx/paths/PaySteps.cpp @@ -189,9 +189,9 @@ toStrand( (dst == noAccount()) || (deliver.getIssuer() == noAccount())) return {temBAD_PATH, Strand{}}; - if ((deliver.holds() && deliver.getIssuer() == beast::kZero) || + if ((deliver.holds() && deliver.getIssuer() == beast::kZERO) || (sendMaxAsset && sendMaxAsset->holds() && - sendMaxAsset->getIssuer() == beast::kZero)) + sendMaxAsset->getIssuer() == beast::kZERO)) return {temBAD_PATH, Strand{}}; for (std::size_t i = 0; i < path.size(); ++i) @@ -662,7 +662,7 @@ toStrands( { lastFailTer = ter; JLOG(j.trace()) << "failed to add path: ter: " << ter - << "path: " << p.getJson(JsonOptions::Values::None); + << "path: " << p.getJson(JsonOptions::KNone); if (isTemMalformed(ter)) return {ter, std::vector{}}; } diff --git a/src/libxrpl/tx/paths/RippleCalc.cpp b/src/libxrpl/tx/paths/RippleCalc.cpp index cc497b7935..06e386344d 100644 --- a/src/libxrpl/tx/paths/RippleCalc.cpp +++ b/src/libxrpl/tx/paths/RippleCalc.cpp @@ -59,13 +59,13 @@ RippleCalc::rippleCalculate( bool const partialPayment = (pInputs == nullptr) ? false : pInputs->partialPaymentAllowed; auto const limitQuality = [&]() -> std::optional { - if (pInputs && pInputs->limitQuality && saMaxAmountReq > beast::kZero) + if (pInputs && pInputs->limitQuality && saMaxAmountReq > beast::kZERO) return Quality{Amounts(saMaxAmountReq, saDstAmountReq)}; return std::nullopt; }(); auto const sendMax = [&]() -> std::optional { - if (saMaxAmountReq >= beast::kZero || + if (saMaxAmountReq >= beast::kZERO || !equalTokens(saMaxAmountReq.asset(), saDstAmountReq.asset()) || saMaxAmountReq.getIssuer() != uSrcAccountID) { diff --git a/src/libxrpl/tx/paths/XRPEndpointStep.cpp b/src/libxrpl/tx/paths/XRPEndpointStep.cpp index 314780c3a7..244e1cffea 100644 --- a/src/libxrpl/tx/paths/XRPEndpointStep.cpp +++ b/src/libxrpl/tx/paths/XRPEndpointStep.cpp @@ -253,7 +253,7 @@ template std::pair, DebtDirection> XRPEndpointStep::qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const { - return {Quality{STAmount::kURateOne}, this->debtDirection(v, StrandDirection::Forward)}; + return {Quality{STAmount::kU_RATE_ONE}, this->debtDirection(v, StrandDirection::Forward)}; } template @@ -272,7 +272,7 @@ XRPEndpointStep::revImp( auto& receiver = isLast_ ? acc_ : xrpAccount(); auto ter = accountSend(sb, sender, receiver, toSTAmount(result), j_); if (!isTesSuccess(ter)) - return {XRPAmount{beast::kZero}, XRPAmount{beast::kZero}}; + return {XRPAmount{beast::kZERO}, XRPAmount{beast::kZERO}}; cache_.emplace(result); return {result, result}; @@ -295,7 +295,7 @@ XRPEndpointStep::fwdImp( auto& receiver = isLast_ ? acc_ : xrpAccount(); auto ter = accountSend(sb, sender, receiver, toSTAmount(result), j_); if (!isTesSuccess(ter)) - return {XRPAmount{beast::kZero}, XRPAmount{beast::kZero}}; + return {XRPAmount{beast::kZERO}, XRPAmount{beast::kZERO}}; cache_.emplace(result); return {result, result}; @@ -308,7 +308,7 @@ XRPEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe if (!cache_) { JLOG(j_.error()) << "Expected valid cache in validFwd"; - return {false, EitherAmount(XRPAmount(beast::kZero))}; + return {false, EitherAmount(XRPAmount(beast::kZERO))}; } XRPL_ASSERT(in.holds(), "xrpl::XRPEndpointStep::validFwd : input is XRP"); diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index 833f1c8b25..f9d1913dff 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -32,6 +32,7 @@ #include #include +#include #include namespace xrpl { @@ -71,7 +72,7 @@ using DeleterFuncPtr = TER (*)( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j); // Local function definitions that provides signature compatibility. @@ -81,7 +82,7 @@ offerDelete( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return offerDelete(view, sleDel, j); @@ -93,7 +94,7 @@ removeSignersFromLedger( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return SignerListSet::removeFromLedger(registry, view, account, j); @@ -105,7 +106,7 @@ removeTicketFromLedger( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref, + std::shared_ptr const&, beast::Journal j) { return Transactor::ticketDelete(view, account, delIndex, j); @@ -117,7 +118,7 @@ removeDepositPreauthFromLedger( ApplyView& view, AccountID const&, uint256 const& delIndex, - SLE::ref, + std::shared_ptr const&, beast::Journal j) { return DepositPreauth::removeFromLedger(view, delIndex, j); @@ -129,7 +130,7 @@ removeNFTokenOfferFromLedger( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal) { if (!nft::deleteTokenOffer(view, sleDel)) @@ -144,7 +145,7 @@ removeDIDFromLedger( ApplyView& view, AccountID const& account, uint256 const& delIndex, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return DIDDelete::deleteSLE(view, sleDel, account, j); @@ -156,7 +157,7 @@ removeOracleFromLedger( ApplyView& view, AccountID const& account, uint256 const&, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return OracleDelete::deleteOracle(view, sleDel, account, j); @@ -168,7 +169,7 @@ removeCredentialFromLedger( ApplyView& view, AccountID const&, uint256 const&, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return credentials::deleteSLE(view, sleDel, j); @@ -180,7 +181,7 @@ removeDelegateFromLedger( ApplyView& view, AccountID const&, uint256 const&, - SLE::ref sleDel, + std::shared_ptr const& sleDel, beast::Journal j) { return DelegateSet::deleteDelegate(view, sleDel, j); @@ -230,7 +231,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (!sleDst) return tecNO_DST; - if (sleDst->isFlag(lsfRequireDestTag) && !ctx.tx[~sfDestinationTag]) + if ((((*sleDst)[sfFlags] & lsfRequireDestTag) != 0u) && !ctx.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; // If credentials are provided - check them anyway @@ -242,7 +243,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (!ctx.tx.isFieldPresent(sfCredentialIDs)) { // Check whether the destination account requires deposit authorization. - if (sleDst->isFlag(lsfDepositAuth)) + if ((sleDst->getFlags() & lsfDepositAuth) != 0u) { if (!ctx.view.exists(keylet::depositPreauth(dst, account))) return tecNO_PERMISSION; @@ -274,8 +275,8 @@ AccountDelete::preclaim(PreclaimContext const& ctx) // // We look at the account's Sequence rather than the transaction's // Sequence in preparation for Tickets. - static constexpr std::uint32_t kSeqDelta{255}; - if ((*sleAccount)[sfSequence] + kSeqDelta > ctx.view.seq()) + constexpr std::uint32_t kSEQ_DELTA{255}; + if ((*sleAccount)[sfSequence] + kSEQ_DELTA > ctx.view.seq()) return tecTOO_SOON; // We don't allow an account to be deleted if @@ -290,7 +291,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) // NFTokenSequence of this NFToken is the same as the one that the // authorized minter minted in a previous ledger. if ((*sleAccount)[~sfFirstNFTokenSequence].value_or(0) + - (*sleAccount)[~sfMintedNFTokens].value_or(0) + kSeqDelta > + (*sleAccount)[~sfMintedNFTokens].value_or(0) + kSEQ_DELTA > ctx.view.seq()) return tecTOO_SOON; @@ -300,9 +301,9 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (dirIsEmpty(ctx.view, ownerDirKeylet)) return tesSUCCESS; - SLE::const_pointer sleDirNode{}; + std::shared_ptr sleDirNode{}; unsigned int uDirEntry{0}; - uint256 dirEntry{beast::kZero}; + uint256 dirEntry{beast::kZERO}; // Account has no directory at all. This _should_ have been caught // by the dirIsEmpty() check earlier, but it's okay to catch it here. @@ -332,7 +333,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) // We found a deletable directory entry. Count it. If we find too // many deletable directory entries then bail out. - if (++deletableDirEntryCount > kMaxDeletableDirEntries) + if (++deletableDirEntryCount > kMAX_DELETABLE_DIR_ENTRIES) return tefTOO_BIG; } while (cdirNext(ctx.view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)); @@ -343,7 +344,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) TER AccountDelete::doApply() { - auto src = view().peek(keylet::account(accountID_)); + auto src = view().peek(keylet::account(account_)); XRPL_ASSERT(src, "xrpl::AccountDelete::doApply : non-null source account"); auto const dstID = ctx_.tx[sfDestination]; @@ -356,21 +357,21 @@ AccountDelete::doApply() if (ctx_.tx.isFieldPresent(sfCredentialIDs)) { if (auto err = - verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, dstID, dst, ctx_.journal); + verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstID, dst, ctx_.journal); !isTesSuccess(err)) return err; } - Keylet const ownerDirKeylet{keylet::ownerDir(accountID_)}; + Keylet const ownerDirKeylet{keylet::ownerDir(account_)}; auto const ter = cleanupOnAccountDelete( view(), ownerDirKeylet, [&](LedgerEntryType nodeType, uint256 const& dirEntry, - SLE::pointer& sleItem) -> std::pair { + std::shared_ptr& sleItem) -> std::pair { if (auto deleter = nonObligationDeleter(nodeType)) { - TER const result{deleter(ctx_.registry, view(), accountID_, dirEntry, sleItem, j_)}; + TER const result{deleter(ctx_.registry, view(), account_, dirEntry, sleItem, j_)}; return {result, SkipEntry::No}; } @@ -401,7 +402,7 @@ AccountDelete::doApply() // delete it. if (view().exists(ownerDirKeylet) && !view().emptyDirDelete(ownerDirKeylet)) { - JLOG(j_.error()) << "AccountDelete cannot delete root dir node of " << toBase58(accountID_); + JLOG(j_.error()) << "AccountDelete cannot delete root dir node of " << toBase58(account_); return tecHAS_OBLIGATIONS; } @@ -416,9 +417,11 @@ AccountDelete::doApply() } void -AccountDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AccountDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -429,7 +432,6 @@ AccountDelete::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index bc207b39dc..da24640bfa 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -26,6 +26,7 @@ #include #include +#include #include namespace xrpl { @@ -68,6 +69,8 @@ AccountSet::preflight(PreflightContext const& ctx) auto& tx = ctx.tx; auto& j = ctx.j; + std::uint32_t const uTxFlags = tx.getFlags(); + std::uint32_t const uSetFlag = tx.getFieldU32(sfSetFlag); std::uint32_t const uClearFlag = tx.getFieldU32(sfClearFlag); @@ -80,8 +83,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireAuth // - bool const bSetRequireAuth = tx.isFlag(tfRequireAuth) || (uSetFlag == asfRequireAuth); - bool const bClearRequireAuth = tx.isFlag(tfOptionalAuth) || (uClearFlag == asfRequireAuth); + bool const bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); + bool const bClearRequireAuth = + ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth); if (bSetRequireAuth && bClearRequireAuth) { @@ -92,8 +96,10 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireDestTag // - bool const bSetRequireDest = tx.isFlag(tfRequireDestTag) || (uSetFlag == asfRequireDest); - bool const bClearRequireDest = tx.isFlag(tfOptionalDestTag) || (uClearFlag == asfRequireDest); + bool const bSetRequireDest = + ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest); + bool const bClearRequireDest = + ((uTxFlags & tfOptionalDestTag) != 0u) || (uClearFlag == asfRequireDest); if (bSetRequireDest && bClearRequireDest) { @@ -104,8 +110,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // DisallowXRP // - bool const bSetDisallowXRP = tx.isFlag(tfDisallowXRP) || (uSetFlag == asfDisallowXRP); - bool const bClearDisallowXRP = tx.isFlag(tfAllowXRP) || (uClearFlag == asfDisallowXRP); + bool const bSetDisallowXRP = ((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP); + bool const bClearDisallowXRP = + ((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP); if (bSetDisallowXRP && bClearDisallowXRP) { @@ -136,7 +143,7 @@ AccountSet::preflight(PreflightContext const& ctx) { auto uTickSize = tx[sfTickSize]; if ((uTickSize != 0u) && - ((uTickSize < Quality::kMinTickSize) || (uTickSize > Quality::kMaxTickSize))) + ((uTickSize < Quality::kMIN_TICK_SIZE) || (uTickSize > Quality::kMAX_TICK_SIZE))) { JLOG(j.trace()) << "Malformed transaction: Bad tick size."; return temBAD_TICK_SIZE; @@ -152,7 +159,7 @@ AccountSet::preflight(PreflightContext const& ctx) } } - if (auto const domain = tx[~sfDomain]; domain && domain->size() > kMaxDomainLength) + if (auto const domain = tx[~sfDomain]; domain && domain->size() > kMAX_DOMAIN_LENGTH) { JLOG(j.trace()) << "domain too long"; return telBAD_DOMAIN; @@ -188,11 +195,12 @@ AccountSet::checkPermission(ReadView const& view, STTx const& tx) auto const uSetFlag = tx.getFieldU32(sfSetFlag); auto const uClearFlag = tx.getFieldU32(sfClearFlag); + auto const uTxFlags = tx.getFlags(); // We don't support any flag based granular permission under // AccountSet transaction. If any delegated account is trying to // update the flag on behalf of another account, it is not // authorized. - if (uSetFlag != 0 || uClearFlag != 0 || ((tx.getFlags() & tfUniversalMask) != 0u)) + if (uSetFlag != 0 || uClearFlag != 0 || ((uTxFlags & tfUniversalMask) != 0u)) return terNO_DELEGATE_PERMISSION; if (tx.isFieldPresent(sfEmailHash) && !granularPermissions.contains(AccountEmailHashSet)) @@ -221,19 +229,23 @@ AccountSet::preclaim(PreclaimContext const& ctx) { auto const id = ctx.tx[sfAccount]; + std::uint32_t const uTxFlags = ctx.tx.getFlags(); + auto const sle = ctx.view.read(keylet::account(id)); if (!sle) return terNO_ACCOUNT; + std::uint32_t const uFlagsIn = sle->getFieldU32(sfFlags); + std::uint32_t const uSetFlag = ctx.tx.getFieldU32(sfSetFlag); // legacy AccountSet flags - bool const bSetRequireAuth = ctx.tx.isFlag(tfRequireAuth) || (uSetFlag == asfRequireAuth); + bool const bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); // // RequireAuth // - if (bSetRequireAuth && !sle->isFlag(lsfRequireAuth)) + if (bSetRequireAuth && ((uFlagsIn & lsfRequireAuth) == 0u)) { if (!dirIsEmpty(ctx.view, keylet::ownerDir(id))) { @@ -249,7 +261,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) { if (uSetFlag == asfAllowTrustLineClawback) { - if (sle->isFlag(lsfNoFreeze)) + if ((uFlagsIn & lsfNoFreeze) != 0u) { JLOG(ctx.j.trace()) << "Can't set Clawback if NoFreeze is set"; return tecNO_PERMISSION; @@ -264,7 +276,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) else if (uSetFlag == asfNoFreeze) { // Cannot set NoFreeze if clawback is enabled - if (sle->isFlag(lsfAllowTrustLineClawback)) + if ((uFlagsIn & lsfAllowTrustLineClawback) != 0u) { JLOG(ctx.j.trace()) << "Can't set NoFreeze if clawback is enabled"; return tecNO_PERMISSION; @@ -278,7 +290,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) TER AccountSet::doApply() { - auto const sle = view().peek(keylet::account(accountID_)); + auto const sle = view().peek(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -290,14 +302,18 @@ AccountSet::doApply() std::uint32_t const uClearFlag{tx.getFieldU32(sfClearFlag)}; // legacy AccountSet flags - bool const bSetRequireDest{tx.isFlag(tfRequireDestTag) || (uSetFlag == asfRequireDest)}; - bool const bClearRequireDest{tx.isFlag(tfOptionalDestTag) || (uClearFlag == asfRequireDest)}; - bool const bSetRequireAuth{tx.isFlag(tfRequireAuth) || (uSetFlag == asfRequireAuth)}; - bool const bClearRequireAuth{tx.isFlag(tfOptionalAuth) || (uClearFlag == asfRequireAuth)}; - bool const bSetDisallowXRP{tx.isFlag(tfDisallowXRP) || (uSetFlag == asfDisallowXRP)}; - bool const bClearDisallowXRP{tx.isFlag(tfAllowXRP) || (uClearFlag == asfDisallowXRP)}; + std::uint32_t const uTxFlags{tx.getFlags()}; + bool const bSetRequireDest{ + ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest)}; + bool const bClearRequireDest{ + ((uTxFlags & tfOptionalDestTag) != 0u) || (uClearFlag == asfRequireDest)}; + bool const bSetRequireAuth{((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth)}; + bool const bClearRequireAuth{ + ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth)}; + bool const bSetDisallowXRP{((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP)}; + bool const bClearDisallowXRP{((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP)}; - bool const sigWithMaster{[&tx, &acct = accountID_]() { + bool const sigWithMaster{[&tx, &acct = account_]() { auto const spk = tx.getSigningPubKey(); if (publicKeyType(makeSlice(spk))) @@ -313,13 +329,13 @@ AccountSet::doApply() // // RequireAuth // - if (bSetRequireAuth && !sle->isFlag(lsfRequireAuth)) + if (bSetRequireAuth && ((uFlagsIn & lsfRequireAuth) == 0u)) { JLOG(j_.trace()) << "Set RequireAuth."; uFlagsOut |= lsfRequireAuth; } - if (bClearRequireAuth && sle->isFlag(lsfRequireAuth)) + if (bClearRequireAuth && ((uFlagsIn & lsfRequireAuth) != 0u)) { JLOG(j_.trace()) << "Clear RequireAuth."; uFlagsOut &= ~lsfRequireAuth; @@ -328,13 +344,13 @@ AccountSet::doApply() // // RequireDestTag // - if (bSetRequireDest && !sle->isFlag(lsfRequireDestTag)) + if (bSetRequireDest && ((uFlagsIn & lsfRequireDestTag) == 0u)) { JLOG(j_.trace()) << "Set lsfRequireDestTag."; uFlagsOut |= lsfRequireDestTag; } - if (bClearRequireDest && sle->isFlag(lsfRequireDestTag)) + if (bClearRequireDest && ((uFlagsIn & lsfRequireDestTag) != 0u)) { JLOG(j_.trace()) << "Clear lsfRequireDestTag."; uFlagsOut &= ~lsfRequireDestTag; @@ -343,13 +359,13 @@ AccountSet::doApply() // // DisallowXRP // - if (bSetDisallowXRP && !sle->isFlag(lsfDisallowXRP)) + if (bSetDisallowXRP && ((uFlagsIn & lsfDisallowXRP) == 0u)) { JLOG(j_.trace()) << "Set lsfDisallowXRP."; uFlagsOut |= lsfDisallowXRP; } - if (bClearDisallowXRP && sle->isFlag(lsfDisallowXRP)) + if (bClearDisallowXRP && ((uFlagsIn & lsfDisallowXRP) != 0u)) { JLOG(j_.trace()) << "Clear lsfDisallowXRP."; uFlagsOut &= ~lsfDisallowXRP; @@ -358,7 +374,7 @@ AccountSet::doApply() // // DisableMaster // - if ((uSetFlag == asfDisableMaster) && !sle->isFlag(lsfDisableMaster)) + if ((uSetFlag == asfDisableMaster) && ((uFlagsIn & lsfDisableMaster) == 0u)) { if (!sigWithMaster) { @@ -366,7 +382,7 @@ AccountSet::doApply() return tecNEED_MASTER_KEY; } - if ((!sle->isFieldPresent(sfRegularKey)) && (!view().peek(keylet::signers(accountID_)))) + if ((!sle->isFieldPresent(sfRegularKey)) && (!view().peek(keylet::signers(account_)))) { // Account has no regular key or multi-signer signer list. return tecNO_ALTERNATIVE_KEY; @@ -376,7 +392,7 @@ AccountSet::doApply() uFlagsOut |= lsfDisableMaster; } - if ((uClearFlag == asfDisableMaster) && sle->isFlag(lsfDisableMaster)) + if ((uClearFlag == asfDisableMaster) && ((uFlagsIn & lsfDisableMaster) != 0u)) { JLOG(j_.trace()) << "Clear lsfDisableMaster."; uFlagsOut &= ~lsfDisableMaster; @@ -401,7 +417,7 @@ AccountSet::doApply() // if (uSetFlag == asfNoFreeze) { - if (!sigWithMaster && !sle->isFlag(lsfDisableMaster)) + if (!sigWithMaster && ((uFlagsIn & lsfDisableMaster) == 0u)) { JLOG(j_.trace()) << "Must use master key to set NoFreeze."; return tecNEED_MASTER_KEY; @@ -558,7 +574,7 @@ AccountSet::doApply() if (tx.isFieldPresent(sfTickSize)) { auto uTickSize = tx[sfTickSize]; - if ((uTickSize == 0) || (uTickSize == Quality::kMaxTickSize)) + if ((uTickSize == 0) || (uTickSize == Quality::kMAX_TICK_SIZE)) { JLOG(j_.trace()) << "unset tick size"; sle->makeFieldAbsent(sfTickSize); @@ -642,15 +658,16 @@ AccountSet::doApply() } void -AccountSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AccountSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AccountSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp index 08ccf5e7ab..bc59ed4fc1 100644 --- a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp +++ b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp @@ -13,6 +13,8 @@ #include #include +#include + namespace xrpl { XRPAmount @@ -27,7 +29,7 @@ SetRegularKey::calculateBaseFee(ReadView const& view, STTx const& tx) { auto const sle = view.read(keylet::account(id)); - if (sle && !sle->isFlag(lsfPasswordSpent)) + if (sle && ((sle->getFlags() & lsfPasswordSpent) == 0u)) { // flag is armed and they signed with the right account return XRPAmount{0}; @@ -53,7 +55,7 @@ SetRegularKey::preflight(PreflightContext const& ctx) TER SetRegularKey::doApply() { - auto const sle = view().peek(keylet::account(accountID_)); + auto const sle = view().peek(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -67,7 +69,7 @@ SetRegularKey::doApply() else { // Account has disabled master key and no multi-signer signer list. - if (sle->isFlag(lsfDisableMaster) && !view().peek(keylet::signers(accountID_))) + if (sle->isFlag(lsfDisableMaster) && !view().peek(keylet::signers(account_))) return tecNO_ALTERNATIVE_KEY; sle->makeFieldAbsent(sfRegularKey); @@ -79,9 +81,11 @@ SetRegularKey::doApply() } void -SetRegularKey::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +SetRegularKey::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -92,7 +96,6 @@ SetRegularKey::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index cedb9ace78..3060abe6df 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -37,7 +37,7 @@ namespace xrpl { // We're prepared for there to be multiple signer lists in the future, // but we don't need them yet. So for the time being we're manually // setting the sfSignerListID to zero in all cases. -static std::uint32_t const kDefaultSignerListId = 0; +static std::uint32_t const kDEFAULT_SIGNER_LIST_ID = 0; std::tuple, SignerListSet::Operation> SignerListSet::determineOperation(STTx const& tx, ApplyFlags flags, beast::Journal j) @@ -168,10 +168,10 @@ signerCountBasedOwnerCountDelta(std::size_t entryCount, Rules const& rules) // be in the range from 1 to 32. // We've got a lot of room to grow. XRPL_ASSERT( - entryCount >= STTx::kMinMultiSigners, + entryCount >= STTx::kMIN_MULTI_SIGNERS, "xrpl::signerCountBasedOwnerCountDelta : minimum signers"); XRPL_ASSERT( - entryCount <= STTx::kMaxMultiSigners, + entryCount <= STTx::kMAX_MULTI_SIGNERS, "xrpl::signerCountBasedOwnerCountDelta : maximum signers"); return 2 + static_cast(entryCount); } @@ -197,7 +197,7 @@ removeSignersFromLedger( // If the lsfOneOwnerCount bit is set then remove just one owner count. // Otherwise use the pre-MultiSignReserve amendment calculation. int removeFromOwnerCount = -1; - if (!signers->isFlag(lsfOneOwnerCount)) + if ((signers->getFlags() & lsfOneOwnerCount) == 0) { STArray const& actualList = signers->getFieldArray(sfSignerEntries); removeFromOwnerCount = @@ -249,7 +249,7 @@ SignerListSet::validateQuorumAndSignerEntries( // Reject if there are too many or too few entries in the list. { std::size_t const signerCount = signers.size(); - if (signerCount < STTx::kMinMultiSigners || signerCount > STTx::kMaxMultiSigners) + if (signerCount < STTx::kMIN_MULTI_SIGNERS || signerCount > STTx::kMAX_MULTI_SIGNERS) { JLOG(j.trace()) << "Too many or too few signers in signer list."; return temMALFORMED; @@ -300,9 +300,9 @@ SignerListSet::validateQuorumAndSignerEntries( TER SignerListSet::replaceSignerList() { - auto const accountKeylet = keylet::account(accountID_); - auto const ownerDirKeylet = keylet::ownerDir(accountID_); - auto const signerListKeylet = keylet::signers(accountID_); + auto const accountKeylet = keylet::account(account_); + auto const ownerDirKeylet = keylet::ownerDir(account_); + auto const signerListKeylet = keylet::signers(account_); // This may be either a create or a replace. Preemptively remove any // old signer list. May reduce the reserve, so this is done before @@ -318,10 +318,10 @@ SignerListSet::replaceSignerList() // Compute new reserve. Verify the account has funds to meet the reserve. std::uint32_t const oldOwnerCount{(*sle)[sfOwnerCount]}; - static constexpr int kAddedOwnerCount = 1; + constexpr int kADDED_OWNER_COUNT = 1; std::uint32_t const flags{lsfOneOwnerCount}; - XRPAmount const newReserve{view().fees().accountReserve(oldOwnerCount + kAddedOwnerCount)}; + XRPAmount const newReserve{view().fees().accountReserve(oldOwnerCount + kADDED_OWNER_COUNT)}; // We check the reserve against the starting balance because we want to // allow dipping into the reserve to pay fees. This behavior is consistent @@ -337,9 +337,9 @@ SignerListSet::replaceSignerList() auto viewJ = ctx_.registry.get().getJournal("View"); // Add the signer list to the account's directory. auto const page = - ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(accountID_)); + ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); - JLOG(j_.trace()) << "Create signer list for account " << toBase58(accountID_) << ": " + JLOG(j_.trace()) << "Create signer list for account " << toBase58(account_) << ": " << (page ? "success" : "failure"); if (!page) @@ -349,14 +349,14 @@ SignerListSet::replaceSignerList() // If we succeeded, the new entry counts against the // creator's reserve. - adjustOwnerCount(view(), sle, kAddedOwnerCount, viewJ); + adjustOwnerCount(view(), sle, kADDED_OWNER_COUNT, viewJ); return tesSUCCESS; } TER SignerListSet::destroySignerList() { - auto const accountKeylet = keylet::account(accountID_); + auto const accountKeylet = keylet::account(account_); // Destroying the signer list is only allowed if either the master key // is enabled or there is a regular key. SLE::pointer const ledgerEntry = view().peek(accountKeylet); @@ -366,8 +366,8 @@ SignerListSet::destroySignerList() if ((ledgerEntry->isFlag(lsfDisableMaster)) && (!ledgerEntry->isFieldPresent(sfRegularKey))) return tecNO_ALTERNATIVE_KEY; - auto const ownerDirKeylet = keylet::ownerDir(accountID_); - auto const signerListKeylet = keylet::signers(accountID_); + auto const ownerDirKeylet = keylet::ownerDir(account_); + auto const signerListKeylet = keylet::signers(account_); return removeSignersFromLedger( ctx_.registry, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_); } @@ -378,10 +378,10 @@ SignerListSet::writeSignersToSLE(SLE::pointer const& ledgerEntry, std::uint32_t // Assign the quorum, default SignerListID, and flags. if (ctx_.view().rules().enabled(fixIncludeKeyletFields)) { - ledgerEntry->setAccountID(sfOwner, accountID_); + ledgerEntry->setAccountID(sfOwner, account_); } ledgerEntry->setFieldU32(sfSignerQuorum, quorum_); - ledgerEntry->setFieldU32(sfSignerListID, kDefaultSignerListId); + ledgerEntry->setFieldU32(sfSignerListID, kDEFAULT_SIGNER_LIST_ID); if (flags != 0u) // Only set flags if they are non-default (default is zero). ledgerEntry->setFieldU32(sfFlags, flags); @@ -406,9 +406,11 @@ SignerListSet::writeSignersToSLE(SLE::pointer const& ledgerEntry, std::uint32_t } void -SignerListSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +SignerListSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -419,7 +421,6 @@ SignerListSet::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 7c9c9d95dc..09e5a7284a 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -130,7 +130,7 @@ checkAttestationPublicKey( if (accountFromPK == attestationSignerAccount) { // master key - if (sleAttestationSigningAccount->isFlag(lsfDisableMaster)) + if ((sleAttestationSigningAccount->getFieldU32(sfFlags) & lsfDisableMaster) != 0u) { JLOG(j.trace()) << "Attempt to add an attestation with " "disabled master key."; @@ -408,7 +408,7 @@ transferHelper( { // Check dst tag and deposit auth - if (sleDst->isFlag(lsfRequireDestTag) && !dstTag) + if (((sleDst->getFlags() & lsfRequireDestTag) != 0u) && !dstTag) return tecDST_TAG_NEEDED; // If the destination is the claim owner, and this is a claim @@ -417,7 +417,7 @@ transferHelper( bool const canBypassDepositAuth = dst == claimOwner && depositAuthPolicy == DepositAuthPolicy::DstCanBypass; - if (!canBypassDepositAuth && sleDst->isFlag(lsfDepositAuth) && + if (!canBypassDepositAuth && ((sleDst->getFlags() & lsfDepositAuth) != 0u) && !psb.exists(keylet::depositPreauth(dst, src))) { return tecNO_PERMISSION; @@ -798,21 +798,21 @@ readOrpeekBridge(F&& getter, STXChainBridge const& bridgeSpec) return tryGet(STXChainBridge::ChainType::Issuing); } -SLE::pointer +std::shared_ptr peekBridge(ApplyView& v, STXChainBridge const& bridgeSpec) { return readOrpeekBridge( - [&v](STXChainBridge const& b, STXChainBridge::ChainType ct) -> SLE::pointer { + [&v](STXChainBridge const& b, STXChainBridge::ChainType ct) -> std::shared_ptr { return v.peek(keylet::bridge(b, ct)); }, bridgeSpec); } -SLE::const_pointer +std::shared_ptr readBridge(ReadView const& v, STXChainBridge const& bridgeSpec) { return readOrpeekBridge( - [&v](STXChainBridge const& b, STXChainBridge::ChainType ct) -> SLE::const_pointer { + [&v](STXChainBridge const& b, STXChainBridge::ChainType ct) -> std::shared_ptr { return v.read(keylet::bridge(b, ct)); }, bridgeSpec); @@ -981,7 +981,7 @@ applyCreateAccountAttestations( { return tecXCHAIN_ACCOUNT_CREATE_PAST; } - if (attBegin->createCount >= claimCount + kXbridgeMaxAccountCreateClaims) + if (attBegin->createCount >= claimCount + kXBRIDGE_MAX_ACCOUNT_CREATE_CLAIMS) { // Limit the number of claims on the account return tecXCHAIN_ACCOUNT_CREATE_TOO_MANY; @@ -1369,9 +1369,9 @@ XChainCreateBridge::preflight(PreflightContext const& ctx) // Issuing account must be the root account for XRP (which presumably // owns all the XRP). This is done so the issuing account can't "run // out" of wrapped tokens. - static auto const kRootAccount = calcAccountID( + static auto const kROOT_ACCOUNT = calcAccountID( generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")).first); - if (bridgeSpec.issuingChainDoor() != kRootAccount) + if (bridgeSpec.issuingChainDoor() != kROOT_ACCOUNT) { return temXCHAIN_BRIDGE_BAD_ISSUES; } @@ -1425,7 +1425,7 @@ XChainCreateBridge::preclaim(PreclaimContext const& ctx) // Allowing clawing back funds would break the bridge's invariant that // wrapped funds are always backed by locked funds - if (sleIssuer->isFlag(lsfAllowTrustLineClawback)) + if ((sleIssuer->getFlags() & lsfAllowTrustLineClawback) != 0u) return tecNO_PERMISSION; } @@ -1504,7 +1504,7 @@ BridgeModify::preflight(PreflightContext const& ctx) auto const reward = ctx.tx[~sfSignatureReward]; auto const minAccountCreate = ctx.tx[~sfMinAccountCreateAmount]; auto const bridgeSpec = ctx.tx[sfXChainBridge]; - bool const clearAccountCreate = ctx.tx.isFlag(tfClearAccountCreateAmount); + bool const clearAccountCreate = (ctx.tx.getFlags() & tfClearAccountCreateAmount) != 0u; if (!reward && !minAccountCreate && !clearAccountCreate) { @@ -1562,7 +1562,7 @@ BridgeModify::doApply() auto const bridgeSpec = ctx_.tx[sfXChainBridge]; auto const reward = ctx_.tx[~sfSignatureReward]; auto const minAccountCreate = ctx_.tx[~sfMinAccountCreateAmount]; - bool const clearAccountCreate = ctx_.tx.isFlag(tfClearAccountCreateAmount); + bool const clearAccountCreate = (ctx_.tx.getFlags() & tfClearAccountCreateAmount) != 0u; auto const sleAcct = ctx_.view().peek(keylet::account(account)); if (!sleAcct) @@ -1826,7 +1826,7 @@ XChainCommit::makeTxConsequences(PreflightContext const& ctx) auto const amount = ctx.tx[sfAmount]; if (amount.native() && amount.signum() > 0) return amount.xrp(); - return XRPAmount{beast::kZero}; + return XRPAmount{beast::kZERO}; }(); return TxConsequences{ctx.tx, maxSpend}; @@ -1920,7 +1920,7 @@ XChainCommit::doApply() // Support dipping into reserves to pay the fee TransferHelperSubmittingAccountInfo submittingAccountInfo{ - .account = accountID_, + .account = account_, .preFeeBalance = preFeeBalance_, .postFeeBalance = (*sleAccount)[sfBalance]}; @@ -2197,9 +2197,7 @@ XChainCreateAccountCommit::doApply() // Support dipping into reserves to pay the fee TransferHelperSubmittingAccountInfo submittingAccountInfo{ - .account = accountID_, - .preFeeBalance = preFeeBalance_, - .postFeeBalance = (*sle)[sfBalance]}; + .account = account_, .preFeeBalance = preFeeBalance_, .postFeeBalance = (*sle)[sfBalance]}; STAmount const toTransfer = amount + reward; auto const thTer = transferHelper( psb, @@ -2225,9 +2223,11 @@ XChainCreateAccountCommit::doApply() } void -XChainCreateBridge::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainCreateBridge::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2238,14 +2238,15 @@ XChainCreateBridge::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -BridgeModify::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +BridgeModify::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2256,27 +2257,29 @@ BridgeModify::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainClaim::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainClaim::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool XChainClaim::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainCommit::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainCommit::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2287,14 +2290,15 @@ XChainCommit::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainCreateClaimID::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainCreateClaimID::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2305,14 +2309,15 @@ XChainCreateClaimID::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainAddClaimAttestation::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainAddClaimAttestation::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2323,14 +2328,15 @@ XChainAddClaimAttestation::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainAddAccountCreateAttestation::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainAddAccountCreateAttestation::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2341,14 +2347,15 @@ XChainAddAccountCreateAttestation::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } void -XChainCreateAccountCommit::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +XChainCreateAccountCommit::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -2359,7 +2366,6 @@ XChainCreateAccountCommit::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/check/CheckCancel.cpp b/src/libxrpl/tx/transactors/check/CheckCancel.cpp index d966772191..c30c116e58 100644 --- a/src/libxrpl/tx/transactors/check/CheckCancel.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCancel.cpp @@ -14,6 +14,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -100,15 +102,16 @@ CheckCancel::doApply() } void -CheckCancel::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CheckCancel::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool CheckCancel::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index c5813ae42d..34288425a5 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -31,6 +31,7 @@ #include #include +#include #include namespace xrpl { @@ -114,7 +115,8 @@ CheckCash::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; } - if (sleDst->isFlag(lsfRequireDestTag) && !sleCheck->isFieldPresent(sfDestinationTag)) + if (((sleDst->getFlags() & lsfRequireDestTag) != 0u) && + !sleCheck->isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. @@ -138,11 +140,6 @@ CheckCash::preclaim(PreclaimContext const& ctx) }(ctx.tx)}; STAmount const sendMax = sleCheck->at(sfSendMax); - // A legacy Check may contain a non-canonical MPT sfSendMax. Universal - // preflight only validates the CheckCash transaction, not the stored Check. - if (ctx.view.rules().enabled(fixCleanup3_2_0) && !isLegalMPT(sendMax)) - return tefBAD_LEDGER; - if (!equalTokens(value.asset(), sendMax.asset())) { JLOG(ctx.j.warn()) << "Check cash does not match check currency."; @@ -203,7 +200,7 @@ CheckCash::preclaim(PreclaimContext const& ctx) return tecNO_ISSUER; } - if (sleIssuer->isFlag(lsfRequireAuth)) + if ((sleIssuer->at(sfFlags) & lsfRequireAuth) != 0u) { if (!sleTrustLine) { @@ -268,10 +265,9 @@ CheckCash::preclaim(PreclaimContext const& ctx) return tecLOCKED; } - if (auto const err = canTransfer(ctx.view, issue, srcId, dstId); - !isTesSuccess(err)) + if (auto const err = canTrade(ctx.view, value.asset()); !isTesSuccess(err)) { - JLOG(ctx.j.warn()) << "MPT transfer is disabled."; + JLOG(ctx.j.warn()) << "MPT DEX is not allowed."; return err; } @@ -299,7 +295,7 @@ CheckCash::doApply() } AccountID const srcId{sleCheck->getAccountID(sfAccount)}; - if (!psb.exists(keylet::account(srcId)) || !psb.exists(keylet::account(accountID_))) + if (!psb.exists(keylet::account(srcId)) || !psb.exists(keylet::account(account_))) { // LCOV_EXCL_START JLOG(ctx_.journal.fatal()) << "Precheck did not verify source or destination's existence."; @@ -320,7 +316,7 @@ CheckCash::doApply() auto viewJ = ctx_.registry.get().getJournal("View"); auto const optDeliverMin = ctx_.tx[~sfDeliverMin]; - if (srcId != accountID_) + if (srcId != account_) { STAmount const sendMax = sleCheck->at(sfSendMax); @@ -358,7 +354,7 @@ CheckCash::doApply() } // The source account has enough XRP so make the ledger change. - if (TER const ter{transferXRP(psb, srcId, accountID_, xrpDeliver, viewJ)}; + if (TER const ter{transferXRP(psb, srcId, account_, xrpDeliver, viewJ)}; !isTesSuccess(ter)) { // The transfer failed. Return the error code. @@ -376,10 +372,12 @@ CheckCash::doApply() return optDeliverMin->asset().visit( [&](Issue const&) { return STAmount( - optDeliverMin->asset(), STAmount::kMaxValue / 2, STAmount::kMaxOffset); + optDeliverMin->asset(), + STAmount::kMAX_VALUE / 2, + STAmount::kMAX_OFFSET); }, [&](MPTIssue const&) { - return STAmount(optDeliverMin->asset(), kMaxMpTokenAmount / 2); + return STAmount(optDeliverMin->asset(), kMAX_MP_TOKEN_AMOUNT / 2); }); }; STAmount const flowDeliver{ @@ -387,8 +385,8 @@ CheckCash::doApply() // Check reserve. Return destination account SLE if enough reserve, // otherwise return nullptr. - auto checkReserve = [&]() -> SLE::pointer { - auto sleDst = psb.peek(keylet::account(accountID_)); + auto checkReserve = [&]() -> std::shared_ptr { + auto sleDst = psb.peek(keylet::account(account_)); // Can the account cover the trust line's or MPT reserve? if (std::uint32_t const ownerCount = {sleDst->at(sfOwnerCount)}; @@ -410,9 +408,9 @@ CheckCash::doApply() [&](Issue const& issue) -> std::optional { // If a trust line does not exist yet create one. Issue const& trustLineIssue = issue; - AccountID const truster = deliverIssuer == accountID_ ? srcId : accountID_; + AccountID const truster = deliverIssuer == account_ ? srcId : account_; trustLineKey = keylet::line(truster, trustLineIssue); - destLow = deliverIssuer > accountID_; + destLow = deliverIssuer > account_; if (!psb.exists(*trustLineKey)) { @@ -435,21 +433,21 @@ CheckCash::doApply() initialBalance.get().account = noAccount(); if (TER const ter = trustCreate( - psb, // payment sandbox - destLow, // is dest low? - deliverIssuer, // source - accountID_, // destination - trustLineKey->key, // ledger index - sleDst, // Account to add to - false, // authorize account - !sleDst->isFlag(lsfDefaultRipple), // - false, // freeze trust line - false, // deep freeze trust line - initialBalance, // zero initial balance - Issue(currency, accountID_), // limit of zero - 0, // quality in - 0, // quality out - viewJ); // journal + psb, // payment sandbox + destLow, // is dest low? + deliverIssuer, // source + account_, // destination + trustLineKey->key, // ledger index + sleDst, // Account to add to + false, // authorize account + (sleDst->getFlags() & lsfDefaultRipple) == 0, // + false, // freeze trust line + false, // deep freeze trust line + initialBalance, // zero initial balance + Issue(currency, account_), // limit of zero + 0, // quality in + 0, // quality out + viewJ); // journal !isTesSuccess(ter)) { return ter; @@ -478,24 +476,24 @@ CheckCash::doApply() // Set the trust line limit to the highest possible // value while flow runs. STAmount const bigAmount( - trustLineIssue, STAmount::kMaxValue, STAmount::kMaxOffset); + trustLineIssue, STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); sleTrustLine->at(tweakedLimit) = bigAmount; return std::nullopt; }, [&](MPTIssue const& issue) -> std::optional { - if (accountID_ != deliverIssuer) + if (account_ != deliverIssuer) { auto const& mptID = issue.getMptID(); // Create MPT if it doesn't exist - auto const mptokenKey = keylet::mptoken(mptID, accountID_); + auto const mptokenKey = keylet::mptoken(mptID, account_); if (!psb.exists(mptokenKey)) { auto sleDst = checkReserve(); if (sleDst == nullptr) return tecINSUFFICIENT_RESERVE; - if (auto const err = checkCreateMPT(psb, mptID, accountID_, j_); + if (auto const err = checkCreateMPT(psb, mptID, account_, j_); !isTesSuccess(err)) { return err; @@ -523,7 +521,7 @@ CheckCash::doApply() psb, flowDeliver, srcId, - accountID_, + account_, STPathSet{}, true, // default path static_cast(optDeliverMin), // partial payment @@ -561,9 +559,9 @@ CheckCash::doApply() // Check was cashed. If not a self send (and it shouldn't be), remove // check link from destination directory. - if (srcId != accountID_ && + if (srcId != account_ && !psb.dirRemove( - keylet::ownerDir(accountID_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) + keylet::ownerDir(account_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Unable to delete check from destination."; @@ -591,15 +589,16 @@ CheckCash::doApply() } void -CheckCash::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CheckCash::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool CheckCash::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index ff82912a1f..6a13819615 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -86,8 +86,10 @@ CheckCreate::preclaim(PreclaimContext const& ctx) return tecNO_DST; } + auto const flags = sleDst->getFlags(); + // Check if the destination has disallowed incoming checks - if (sleDst->isFlag(lsfDisallowIncomingCheck)) + if ((flags & lsfDisallowIncomingCheck) != 0u) return tecNO_PERMISSION; // Pseudo-accounts cannot cash checks. Note, this is not amendment-gated @@ -97,7 +99,7 @@ CheckCreate::preclaim(PreclaimContext const& ctx) if (isPseudoAccount(sleDst)) return tecNO_PERMISSION; - if (sleDst->isFlag(lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag)) + if (((flags & lsfRequireDestTag) != 0u) && !ctx.tx.isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. @@ -111,10 +113,10 @@ CheckCreate::preclaim(PreclaimContext const& ctx) { // The currency may not be globally frozen AccountID const& issuerId{sendMax.getIssuer()}; - if (auto const ter = checkGlobalFrozen(ctx.view, sendMax.asset()); !isTesSuccess(ter)) + if (isGlobalFrozen(ctx.view, sendMax.asset())) { - JLOG(ctx.j.warn()) << "Creating a check for frozen or locked asset"; - return ter; + JLOG(ctx.j.warn()) << "Creating a check for frozen asset"; + return sendMax.asset().holds() ? tecLOCKED : tecFROZEN; } auto const err = sendMax.asset().visit( [&](Issue const& issue) -> std::optional { @@ -153,21 +155,9 @@ CheckCreate::preclaim(PreclaimContext const& ctx) }, [&](MPTIssue const& issue) -> std::optional { if (srcId != issuerId && isFrozen(ctx.view, srcId, issue)) - { - JLOG(ctx.j.warn()) << "Creating a check for locked MPT."; return tecLOCKED; - } if (dstId != issuerId && isFrozen(ctx.view, dstId, issue)) - { - JLOG(ctx.j.warn()) << "Creating a check for locked MPT."; return tecLOCKED; - } - if (auto const ter = canTransfer(ctx.view, issue, srcId, dstId); - !isTesSuccess(ter)) - { - JLOG(ctx.j.warn()) << "MPT transfer is disabled."; - return ter; - } return std::nullopt; }); @@ -181,13 +171,13 @@ CheckCreate::preclaim(PreclaimContext const& ctx) return tecEXPIRED; } - return tesSUCCESS; + return canTrade(ctx.view, ctx.tx[sfSendMax].asset()); } TER CheckCreate::doApply() { - auto const sle = view().peek(keylet::account(accountID_)); + auto const sle = view().peek(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -204,10 +194,10 @@ CheckCreate::doApply() // Note that we use the value from the sequence or ticket as the // Check sequence. For more explanation see comments in SeqProxy.h. std::uint32_t const seq = ctx_.tx.getSeqValue(); - Keylet const checkKeylet = keylet::check(accountID_, seq); + Keylet const checkKeylet = keylet::check(account_, seq); auto sleCheck = std::make_shared(checkKeylet); - sleCheck->setAccountID(sfAccount, accountID_); + sleCheck->setAccountID(sfAccount, account_); AccountID const dstAccountId = ctx_.tx[sfDestination]; sleCheck->setAccountID(sfDestination, dstAccountId); sleCheck->setFieldU32(sfSequence, seq); @@ -226,7 +216,7 @@ CheckCreate::doApply() auto viewJ = ctx_.registry.get().getJournal("View"); // If it's not a self-send (and it shouldn't be), add Check to the // destination's owner directory. - if (dstAccountId != accountID_) + if (dstAccountId != account_) { auto const page = view().dirInsert( keylet::ownerDir(dstAccountId), checkKeylet, describeOwnerDir(dstAccountId)); @@ -241,8 +231,8 @@ CheckCreate::doApply() } { - auto const page = view().dirInsert( - keylet::ownerDir(accountID_), checkKeylet, describeOwnerDir(accountID_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), checkKeylet, describeOwnerDir(account_)); JLOG(j_.trace()) << "Adding Check to owner directory " << to_string(checkKeylet.key) << ": " << (page ? "success" : "failure"); @@ -258,15 +248,16 @@ CheckCreate::doApply() } void -CheckCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CheckCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool CheckCreate::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp index e0ebdd893a..0dd21d3bd5 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace xrpl { using namespace credentials; @@ -41,7 +43,7 @@ CredentialAccept::preflight(PreflightContext const& ctx) } auto const credType = ctx.tx[sfCredentialType]; - if (credType.empty() || (credType.size() > kMaxCredentialTypeLength)) + if (credType.empty() || (credType.size() > kMAX_CREDENTIAL_TYPE_LENGTH)) { JLOG(ctx.j.trace()) << "Malformed transaction: invalid size of CredentialType."; return temMALFORMED; @@ -71,7 +73,7 @@ CredentialAccept::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; } - if (sleCred->isFlag(lsfAccepted)) + if ((sleCred->getFieldU32(sfFlags) & lsfAccepted) != 0u) { JLOG(ctx.j.warn()) << "Credential already accepted: " << to_string(subject) << ", " << to_string(issuer) << ", " << credType; @@ -87,7 +89,7 @@ CredentialAccept::doApply() AccountID const issuer{ctx_.tx[sfIssuer]}; // Both exist as credential object exist itself (checked in preclaim) - auto const sleSubject = view().peek(keylet::account(accountID_)); + auto const sleSubject = view().peek(keylet::account(account_)); auto const sleIssuer = view().peek(keylet::account(issuer)); if (!sleSubject || !sleIssuer) @@ -101,12 +103,10 @@ CredentialAccept::doApply() } auto const credType(ctx_.tx[sfCredentialType]); - Keylet const credentialKey = keylet::credential(accountID_, issuer, credType); + Keylet const credentialKey = keylet::credential(account_, issuer, credType); auto const sleCred = view().peek(credentialKey); // Checked in preclaim() - if (!sleCred) - return tefINTERNAL; // LCOV_EXCL_LINE - if (checkExpired(*sleCred, view().header().parentCloseTime)) + if (checkExpired(sleCred, view().header().parentCloseTime)) { JLOG(j_.trace()) << "Credential is expired: " << sleCred->getText(); // delete expired credentials even if the transaction failed @@ -124,9 +124,11 @@ CredentialAccept::doApply() } void -CredentialAccept::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CredentialAccept::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -137,7 +139,6 @@ CredentialAccept::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp index acca408a95..e54c48287f 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp @@ -62,14 +62,14 @@ CredentialCreate::preflight(PreflightContext const& ctx) } auto const uri = tx[~sfURI]; - if (uri && (uri->empty() || (uri->size() > kMaxCredentialUriLength))) + if (uri && (uri->empty() || (uri->size() > kMAX_CREDENTIAL_URI_LENGTH))) { JLOG(j.trace()) << "Malformed transaction: invalid size of URI."; return temMALFORMED; } auto const credType = tx[sfCredentialType]; - if (credType.empty() || (credType.size() > kMaxCredentialTypeLength)) + if (credType.empty() || (credType.size() > kMAX_CREDENTIAL_TYPE_LENGTH)) { JLOG(j.trace()) << "Malformed transaction: invalid size of CredentialType."; return temMALFORMED; @@ -104,7 +104,7 @@ CredentialCreate::doApply() { auto const subject = ctx_.tx[sfSubject]; auto const credType(ctx_.tx[sfCredentialType]); - Keylet const credentialKey = keylet::credential(subject, accountID_, credType); + Keylet const credentialKey = keylet::credential(subject, account_, credType); auto const sleCred = std::make_shared(credentialKey); if (!sleCred) @@ -126,7 +126,7 @@ CredentialCreate::doApply() sleCred->setFieldU32(sfExpiration, *optExp); } - auto const sleIssuer = view().peek(keylet::account(accountID_)); + auto const sleIssuer = view().peek(keylet::account(account_)); if (!sleIssuer) return tefINTERNAL; // LCOV_EXCL_LINE @@ -138,15 +138,15 @@ CredentialCreate::doApply() } sleCred->setAccountID(sfSubject, subject); - sleCred->setAccountID(sfIssuer, accountID_); + sleCred->setAccountID(sfIssuer, account_); sleCred->setFieldVL(sfCredentialType, credType); if (ctx_.tx.isFieldPresent(sfURI)) sleCred->setFieldVL(sfURI, ctx_.tx.getFieldVL(sfURI)); { - auto const page = view().dirInsert( - keylet::ownerDir(accountID_), credentialKey, describeOwnerDir(accountID_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), credentialKey, describeOwnerDir(account_)); JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) << ": " << (page ? "success" : "failure"); if (!page) @@ -156,7 +156,7 @@ CredentialCreate::doApply() adjustOwnerCount(view(), sleIssuer, 1, j_); } - if (subject == accountID_) + if (subject == account_) { sleCred->setFieldU32(sfFlags, lsfAccepted); } @@ -179,9 +179,11 @@ CredentialCreate::doApply() } void -CredentialCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CredentialCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -192,7 +194,6 @@ CredentialCreate::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp index 6bd4ad54c5..42880bfdf8 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp @@ -16,6 +16,8 @@ #include #include +#include + namespace xrpl { using namespace credentials; @@ -50,7 +52,7 @@ CredentialDelete::preflight(PreflightContext const& ctx) } auto const credType = ctx.tx[sfCredentialType]; - if (credType.empty() || (credType.size() > kMaxCredentialTypeLength)) + if (credType.empty() || (credType.size() > kMAX_CREDENTIAL_TYPE_LENGTH)) { JLOG(ctx.j.trace()) << "Malformed transaction: invalid size of CredentialType."; return temMALFORMED; @@ -76,16 +78,16 @@ CredentialDelete::preclaim(PreclaimContext const& ctx) TER CredentialDelete::doApply() { - auto const subject = ctx_.tx[~sfSubject].value_or(accountID_); - auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); + auto const subject = ctx_.tx[~sfSubject].value_or(account_); + auto const issuer = ctx_.tx[~sfIssuer].value_or(account_); auto const credType(ctx_.tx[sfCredentialType]); auto const sleCred = view().peek(keylet::credential(subject, issuer, credType)); if (!sleCred) return tefINTERNAL; // LCOV_EXCL_LINE - if ((subject != accountID_) && (issuer != accountID_) && - !checkExpired(*sleCred, ctx_.view().header().parentCloseTime)) + if ((subject != account_) && (issuer != account_) && + !checkExpired(sleCred, ctx_.view().header().parentCloseTime)) { JLOG(j_.trace()) << "Can't delete non-expired credential."; return tecNO_PERMISSION; @@ -95,9 +97,11 @@ CredentialDelete::doApply() } void -CredentialDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +CredentialDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -108,7 +112,6 @@ CredentialDelete::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp index 82fe88aa9f..baf208a305 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp @@ -25,7 +25,7 @@ NotTEC DelegateSet::preflight(PreflightContext const& ctx) { auto const& permissions = ctx.tx.getFieldArray(sfPermissions); - if (permissions.size() > kPermissionMaxSize) + if (permissions.size() > kPERMISSION_MAX_SIZE) return temARRAY_TOO_LARGE; // can not authorize self @@ -68,12 +68,12 @@ DelegateSet::preclaim(PreclaimContext const& ctx) TER DelegateSet::doApply() { - auto const sleOwner = ctx_.view().peek(keylet::account(accountID_)); + auto const sleOwner = ctx_.view().peek(keylet::account(account_)); if (!sleOwner) return tefINTERNAL; // LCOV_EXCL_LINE auto const& authAccount = ctx_.tx[sfAuthorize]; - auto const delegateKey = keylet::delegate(accountID_, authAccount); + auto const delegateKey = keylet::delegate(account_, authAccount); auto sle = ctx_.view().peek(delegateKey); if (sle) @@ -101,22 +101,22 @@ DelegateSet::doApply() return tecINSUFFICIENT_RESERVE; sle = std::make_shared(delegateKey); - sle->setAccountID(sfAccount, accountID_); + sle->setAccountID(sfAccount, account_); sle->setAccountID(sfAuthorize, authAccount); sle->setFieldArray(sfPermissions, permissions); // Add to delegating account's owner directory - auto const page = ctx_.view().dirInsert( - keylet::ownerDir(accountID_), delegateKey, describeOwnerDir(accountID_)); + auto const page = + ctx_.view().dirInsert(keylet::ownerDir(account_), delegateKey, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*sle)[sfOwnerNode] = *page; - // Add to authorized account's owner directory so AccountDelete can find - // and clean up inbound delegations when the authorized account is deleted. + // Add to authorized account's owner directory so the object can be found + // and cleaned up when the authorized account is deleted. auto const destPage = ctx_.view().dirInsert( keylet::ownerDir(authAccount), delegateKey, describeOwnerDir(authAccount)); @@ -132,7 +132,7 @@ DelegateSet::doApply() } TER -DelegateSet::deleteDelegate(ApplyView& view, SLE::ref sle, beast::Journal j) +DelegateSet::deleteDelegate(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) { if (!sle) return tecINTERNAL; // LCOV_EXCL_LINE @@ -174,15 +174,16 @@ DelegateSet::deleteDelegate(ApplyView& view, SLE::ref sle, beast::Journal j) } void -DelegateSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +DelegateSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool DelegateSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp b/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp index dc6c98f95e..4d3d97e443 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp @@ -7,11 +7,12 @@ #include #include +#include #include namespace xrpl { NotTEC -checkTxPermission(SLE::const_ref delegate, STTx const& tx) +checkTxPermission(std::shared_ptr const& delegate, STTx const& tx) { if (!delegate) return terNO_DELEGATE_PERMISSION; @@ -31,7 +32,7 @@ checkTxPermission(SLE::const_ref delegate, STTx const& tx) void loadGranularPermission( - SLE::const_ref delegate, + std::shared_ptr const& delegate, TxType const& txType, std::unordered_set& granularPermissions) { diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index a98f439d0a..d4783c783b 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -76,7 +77,7 @@ AMMBid::preflight(PreflightContext const& ctx) if (ctx.tx.isFieldPresent(sfAuthAccounts)) { auto const authAccounts = ctx.tx.getFieldArray(sfAuthAccounts); - if (authAccounts.size() > kAuctionSlotMaxAuthAccounts) + if (authAccounts.size() > kAUCTION_SLOT_MAX_AUTH_ACCOUNTS) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid number of AuthAccounts."; return temMALFORMED; @@ -112,7 +113,7 @@ AMMBid::preclaim(PreclaimContext const& ctx) } auto const lpTokensBalance = (*ammSle)[sfLPTokenBalance]; - if (lpTokensBalance == beast::kZero) + if (lpTokensBalance == beast::kZERO) return tecAMM_EMPTY; if (ctx.tx.isFieldPresent(sfAuthAccounts)) @@ -129,7 +130,7 @@ AMMBid::preclaim(PreclaimContext const& ctx) auto const lpTokens = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j); // Not LP - if (lpTokens == beast::kZero) + if (lpTokens == beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Bid: account is not LP."; return tecAMM_INVALID_TOKENS; @@ -200,12 +201,12 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa auto const current = duration_cast(ctx.view().header().parentCloseTime.time_since_epoch()).count(); // Auction slot discounted fee - auto const discountedFee = (*ammSle)[sfTradingFee] / kAuctionSlotDiscountedFeeFraction; + auto const discountedFee = (*ammSle)[sfTradingFee] / kAUCTION_SLOT_DISCOUNTED_FEE_FRACTION; auto const tradingFee = getFee((*ammSle)[sfTradingFee]); // Min price - auto const minSlotPrice = lptAMMBalance * tradingFee / kAuctionSlotMinFeeFraction; + auto const minSlotPrice = lptAMMBalance * tradingFee / kAUCTION_SLOT_MIN_FEE_FRACTION; - static constexpr std::uint32_t kTailingSlot = kAuctionSlotTimeIntervals - 1; + std::uint32_t constexpr kTAILING_SLOT = kAUCTION_SLOT_TIME_INTERVALS - 1; // If seated then it is the current slot-holder time slot, otherwise // the auction slot is not owned. Slot range is in {0-19} @@ -215,12 +216,12 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa auto validOwner = [&](AccountID const& account) { // Valid range is 0-19 but the tailing slot pays MinSlotPrice // and doesn't refund so the check is < instead of <= to optimize. - return timeSlot && *timeSlot < kTailingSlot && sb.read(keylet::account(account)); + return timeSlot && *timeSlot < kTAILING_SLOT && sb.read(keylet::account(account)); }; auto updateSlot = [&](std::uint32_t fee, Number const& minPrice, Number const& burn) -> TER { auctionSlot.setAccountID(sfAccount, account); - auctionSlot.setFieldU32(sfExpiration, current + kTotalTimeSlotSecs); + auctionSlot.setFieldU32(sfExpiration, current + kTOTAL_TIME_SLOT_SECS); if (fee != 0) { auctionSlot.setFieldU16(sfDiscountedFee, fee); @@ -321,7 +322,7 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa STAmount const pricePurchased = auctionSlot[sfPrice]; XRPL_ASSERT(timeSlot, "xrpl::applyBid : timeSlot is set"); // NOLINTBEGIN(bugprone-unchecked-optional-access) - auto const fractionUsed = (Number(*timeSlot) + 1) / kAuctionSlotTimeIntervals; + auto const fractionUsed = (Number(*timeSlot) + 1) / kAUCTION_SLOT_TIME_INTERVALS; auto const fractionRemaining = Number(1) - fractionUsed; auto const computedPrice = [&]() -> Number { auto const p105 = Number(105, -2); @@ -370,7 +371,7 @@ AMMBid::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyBid(ctx_, sb, accountID_, j_); + auto const result = applyBid(ctx_, sb, account_, j_); if (result.second) sb.apply(ctx_.rawView()); @@ -378,15 +379,16 @@ AMMBid::doApply() } void -AMMBid::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMBid::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMBid::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp index b94e97e931..112d290e72 100644 --- a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp @@ -27,6 +27,7 @@ #include #include +#include #include #include @@ -70,7 +71,9 @@ AMMClawback::preflight(PreflightContext const& ctx) if (isXRP(asset)) return temMALFORMED; - if (ctx.tx.isFlag(tfClawTwoAssets) && asset.getIssuer() != asset2.getIssuer()) + auto const flags = ctx.tx.getFlags(); + + if (((flags & tfClawTwoAssets) != 0u) && asset.getIssuer() != asset2.getIssuer()) { JLOG(ctx.j.trace()) << "AMMClawback: tfClawTwoAssets can only be enabled when two " "assets in the AMM pool are both issued by the issuer"; @@ -91,7 +94,7 @@ AMMClawback::preflight(PreflightContext const& ctx) return temBAD_AMOUNT; } - if (clawAmount && *clawAmount <= beast::kZero) + if (clawAmount && *clawAmount <= beast::kZERO) return temBAD_AMOUNT; return tesSUCCESS; @@ -116,11 +119,13 @@ AMMClawback::preclaim(PreclaimContext const& ctx) return terNO_AMM; } + std::uint32_t const issuerFlagsIn = sleIssuer->getFieldU32(sfFlags); if (!ctx.view.rules().enabled(featureMPTokensV2)) { // If AllowTrustLineClawback is not set or NoFreeze is set, return no // permission - if (!sleIssuer->isFlag(lsfAllowTrustLineClawback) || sleIssuer->isFlag(lsfNoFreeze)) + if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlagsIn & lsfNoFreeze) != 0u)) { return tecNO_PERMISSION; } @@ -132,8 +137,8 @@ AMMClawback::preclaim(PreclaimContext const& ctx) if (issue.native()) return false; // LCOV_EXCL_LINE - return sleIssuer->isFlag(lsfAllowTrustLineClawback) && - !sleIssuer->isFlag(lsfNoFreeze); + return ((issuerFlagsIn & lsfAllowTrustLineClawback) != 0u) && + ((issuerFlagsIn & lsfNoFreeze) == 0u); }, [&](MPTIssue const& issue) { auto const sleIssuance = ctx.view.read(keylet::mptIssuance(issue.getMptID())); @@ -186,7 +191,7 @@ AMMClawback::applyGuts(Sandbox& sb) { // retrieve LP token balance inside the amendment gate to avoid inconsistent error behavior auto const lpTokenBalance = ammLPHolds(sb, *ammSle, holder, j_); - if (lpTokenBalance == beast::kZero) + if (lpTokenBalance == beast::kZERO) return tecAMM_BALANCE; if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokenBalance, ammSle, holder); @@ -215,7 +220,7 @@ AMMClawback::applyGuts(Sandbox& sb) // calling a second time on purpose since `verifyAndAdjustLPTokenBalance` rounds and may adjust // the balance auto const holdLPtokens = ammLPHolds(sb, *ammSle, holder, j_); - if (holdLPtokens == beast::kZero) + if (holdLPtokens == beast::kZERO) return tecAMM_BALANCE; if (!clawAmount) @@ -283,7 +288,8 @@ AMMClawback::applyGuts(Sandbox& sb) if (!amount2Withdraw) return tecINTERNAL; // LCOV_EXCL_LINE - if (ctx_.tx.isFlag(tfClawTwoAssets)) + auto const flags = ctx_.tx.getFlags(); + if ((flags & tfClawTwoAssets) != 0u) return sendAmount(*amount2Withdraw); return tesSUCCESS; @@ -334,7 +340,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( auto tokensAdj = getRoundedLPTokens(rules, lptAMMBalance, frac, IsDeposit::No); // LCOV_EXCL_START - if (tokensAdj == beast::kZero) + if (tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}, STAmount{}, std::nullopt}; // LCOV_EXCL_STOP @@ -382,15 +388,16 @@ AMMClawback::equalWithdrawMatchingOneAmount( } void -AMMClawback::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMClawback::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMClawback::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 9c1a5cfacb..c90ea0a6ab 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -75,7 +76,7 @@ AMMCreate::preflight(PreflightContext const& ctx) return err; } - if (ctx.tx[sfTradingFee] > kTradingFeeThreshold) + if (ctx.tx[sfTradingFee] > kTRADING_FEE_THRESHOLD) { JLOG(ctx.j.debug()) << "AMM Instance: invalid trading fee."; return temBAD_FEE; @@ -119,16 +120,11 @@ AMMCreate::preclaim(PreclaimContext const& ctx) } // Globally or individually frozen - if (auto const ter = checkFrozen(ctx.view, accountID, amount.asset()); !isTesSuccess(ter)) - + if (isFrozen(ctx.view, accountID, amount.asset()) || + isFrozen(ctx.view, accountID, amount2.asset())) { - JLOG(ctx.j.debug()) << "AMM Instance: involves frozen or locked asset."; - return ter; - } - if (auto const ter = checkFrozen(ctx.view, accountID, amount2.asset()); !isTesSuccess(ter)) - { - JLOG(ctx.j.debug()) << "AMM Instance: involves frozen or locked asset."; - return ter; + JLOG(ctx.j.debug()) << "AMM Instance: involves frozen asset."; + return tecFROZEN; } auto noDefaultRipple = [](ReadView const& view, Asset const& asset) { @@ -136,7 +132,7 @@ AMMCreate::preclaim(PreclaimContext const& ctx) return false; if (auto const issuerAccount = view.read(keylet::account(asset.getIssuer()))) - return !issuerAccount->isFlag(lsfDefaultRipple); + return (issuerAccount->getFlags() & lsfDefaultRipple) == 0; return false; }; @@ -150,7 +146,7 @@ AMMCreate::preclaim(PreclaimContext const& ctx) // Check the reserve for LPToken trustline STAmount const xrpBalance = xrpLiquid(ctx.view, accountID, 1, ctx.j); // Insufficient reserve - if (xrpBalance <= beast::kZero) + if (xrpBalance <= beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Instance: insufficient reserves"; return tecINSUF_RESERVE_LINE; @@ -191,14 +187,14 @@ AMMCreate::preclaim(PreclaimContext const& ctx) { if (auto const accountId = pseudoAccountAddress(ctx.view, keylet::amm(amount.asset(), amount2.asset()).key); - accountId == beast::kZero) + accountId == beast::kZERO) return terADDRESS_COLLISION; } - if (auto const ter = canMPTTradeAndTransfer(ctx.view, amount.asset(), accountID, accountID); + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_CREATE, amount.asset(), accountID); !isTesSuccess(ter)) return ter; - if (auto const ter = canMPTTradeAndTransfer(ctx.view, amount2.asset(), accountID, accountID); + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_CREATE, amount2.asset(), accountID); !isTesSuccess(ter)) return ter; @@ -305,14 +301,22 @@ applyCreate(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Jou // Authorize MPT return amount.asset().visit( [&](MPTIssue const& issue) -> TER { + // Authorize MPT auto const& mptIssue = issue; auto const& mptID = mptIssue.getMptID(); - // Implicitly authorize MPT asset for AMM pseudo-account. - std::uint32_t const flags = lsfMPTAMM | lsfMPTAuthorized; - if (auto const err = requireAuth(sb, mptIssue, accountId, AuthType::WeakAuth); + std::uint32_t flags = lsfMPTAMM; + if (auto const err = + requireAuth(ctx.view(), mptIssue, accountId, AuthType::WeakAuth); !isTesSuccess(err)) { - return err; + if (err == tecNO_AUTH) + { + flags |= lsfMPTAuthorized; + } + else + { + return err; + } } if (auto const err = createMPToken(sb, mptID, accountId, flags); !isTesSuccess(err)) @@ -364,7 +368,7 @@ applyCreate(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Jou << lpTokens << " " << amount << " " << amount2; auto addOrderBook = [&](Asset const& assetIn, Asset const& assetOut, std::uint64_t uRate) { Book const book{assetIn, assetOut, std::nullopt}; - auto const dir = keylet::quality(keylet::kBook(book), uRate); + auto const dir = keylet::quality(keylet::kBOOK(book), uRate); if (auto const bookExisted = static_cast(sb.read(dir)); !bookExisted) ctx.registry.get().getOrderBookDB().addOrderBook(book); }; @@ -381,7 +385,7 @@ AMMCreate::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyCreate(ctx_, sb, accountID_, j_); + auto const result = applyCreate(ctx_, sb, account_, j_); if (result.second) sb.apply(ctx_.rawView()); @@ -389,15 +393,16 @@ AMMCreate::doApply() } void -AMMCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMCreate::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMDelete.cpp b/src/libxrpl/tx/transactors/dex/AMMDelete.cpp index e2ecec8242..0ca7fd7c34 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDelete.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDelete.cpp @@ -15,6 +15,8 @@ #include #include +#include + namespace xrpl { bool @@ -44,7 +46,7 @@ AMMDelete::preclaim(PreclaimContext const& ctx) } auto const lpTokensBalance = (*ammSle)[sfLPTokenBalance]; - if (lpTokensBalance != beast::kZero) + if (lpTokensBalance != beast::kZERO) return tecAMM_NOT_EMPTY; return tesSUCCESS; @@ -65,15 +67,16 @@ AMMDelete::doApply() } void -AMMDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMDelete::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index 91858e3cd7..d2995c309f 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -21,12 +21,14 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -73,35 +75,35 @@ AMMDeposit::preflight(PreflightContext const& ctx) JLOG(ctx.j.debug()) << "AMM Deposit: invalid flags."; return temMALFORMED; } - if (ctx.tx.isFlag(tfLPToken)) + if ((flags & tfLPToken) != 0u) { // if included then both amount and amount2 are deposit min if (!lpTokens || ePrice || (amount && !amount2) || (!amount && amount2) || tradingFee) return temMALFORMED; } - else if (ctx.tx.isFlag(tfSingleAsset)) + else if ((flags & tfSingleAsset) != 0u) { // if included then lpTokens is deposit min if (!amount || amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (ctx.tx.isFlag(tfTwoAsset)) + else if ((flags & tfTwoAsset) != 0u) { // if included then lpTokens is deposit min if (!amount || !amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (ctx.tx.isFlag(tfOneAssetLPToken)) + else if ((flags & tfOneAssetLPToken) != 0u) { if (!amount || !lpTokens || amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (ctx.tx.isFlag(tfLimitLPToken)) + else if ((flags & tfLimitLPToken) != 0u) { if (!amount || !ePrice || lpTokens || amount2 || tradingFee) return temMALFORMED; } - else if (ctx.tx.isFlag(tfTwoAssetIfEmpty)) + else if ((flags & tfTwoAssetIfEmpty) != 0u) { if (!amount || !amount2 || ePrice || lpTokens) return temMALFORMED; @@ -122,7 +124,7 @@ AMMDeposit::preflight(PreflightContext const& ctx) return temBAD_AMM_TOKENS; } - if (lpTokens && *lpTokens <= beast::kZero) + if (lpTokens && *lpTokens <= beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid LPTokens"; return temBAD_AMM_TOKENS; @@ -164,7 +166,7 @@ AMMDeposit::preflight(PreflightContext const& ctx) } } - if (tradingFee > kTradingFeeThreshold) + if (tradingFee > kTRADING_FEE_THRESHOLD) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid trading fee."; return temBAD_FEE; @@ -196,11 +198,11 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) if (!expected) return expected.error(); // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; - if (ctx.tx.isFlag(tfTwoAssetIfEmpty)) + if ((ctx.tx.getFlags() & tfTwoAssetIfEmpty) != 0u) { - if (lptAMMBalance != beast::kZero) + if (lptAMMBalance != beast::kZERO) return tecAMM_NOT_EMPTY; - if (amountBalance != beast::kZero || amount2Balance != beast::kZero) + if (amountBalance != beast::kZERO || amount2Balance != beast::kZERO) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "AMM Deposit: tokens balance is not zero."; @@ -210,10 +212,10 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) } else { - if (lptAMMBalance == beast::kZero) + if (lptAMMBalance == beast::kZERO) return tecAMM_EMPTY; - if (amountBalance <= beast::kZero || amount2Balance <= beast::kZero || - lptAMMBalance < beast::kZero) + if (amountBalance <= beast::kZERO || amount2Balance <= beast::kZERO || + lptAMMBalance < beast::kZERO) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "AMM Deposit: reserves or tokens balance is zero."; @@ -265,12 +267,12 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return ter; } - if (auto const ter = checkFrozen(ctx.view, accountID, asset); !isTesSuccess(ter)) + if (isFrozen(ctx.view, accountID, asset)) { - JLOG(ctx.j.debug()) << "AMM Deposit: account or currency is frozen or locked, " + JLOG(ctx.j.debug()) << "AMM Deposit: account or currency is frozen, " << to_string(accountID) << " " << to_string(asset); - return ter; + return tecFROZEN; } return tesSUCCESS; @@ -302,20 +304,18 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) // LCOV_EXCL_STOP } // AMM account or currency frozen - if (auto const ter = checkFrozen(ctx.view, ammAccountID, amount->asset()); - !isTesSuccess(ter)) + if (isFrozen(ctx.view, ammAccountID, amount->asset())) { - JLOG(ctx.j.debug()) << "AMM Deposit: AMM account or currency is frozen or locked, " - << to_string(accountID); - return ter; + JLOG(ctx.j.debug()) + << "AMM Deposit: AMM account or currency is frozen, " << to_string(accountID); + return tecFROZEN; } // Account frozen - if (auto const ter = checkIndividualFrozen(ctx.view, accountID, amount->asset()); - !isTesSuccess(ter)) + if (isIndividualFrozen(ctx.view, accountID, amount->asset())) { - JLOG(ctx.j.debug()) << "AMM Deposit: account is frozen or locked, " - << to_string(accountID) << " " << to_string(amount->asset()); - return ter; + JLOG(ctx.j.debug()) << "AMM Deposit: account is frozen, " << to_string(accountID) + << " " << to_string(amount->asset()); + return tecFROZEN; } if (checkBalance) { @@ -331,7 +331,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) }; // amount and amount2 are deposit min in case of tfLPToken - if (!ctx.tx.isFlag(tfLPToken)) + if ((ctx.tx.getFlags() & tfLPToken) == 0u) { if (auto const ter = checkAmount(amount, true)) return ter; @@ -357,21 +357,21 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) // Check the reserve for LPToken trustline if not LP. // We checked above but need to check again if depositing IOU only. - if (ammLPHolds(ctx.view, *ammSle, accountID, ctx.j) == beast::kZero) + if (ammLPHolds(ctx.view, *ammSle, accountID, ctx.j) == beast::kZERO) { STAmount const xrpBalance = xrpLiquid(ctx.view, accountID, 1, ctx.j); // Insufficient reserve - if (xrpBalance <= beast::kZero) + if (xrpBalance <= beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Instance: insufficient reserves"; return tecINSUF_RESERVE_LINE; } } - if (auto const ter = canMPTTradeAndTransfer(ctx.view, ctx.tx[sfAsset], accountID, accountID); + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_DEPOSIT, ctx.tx[sfAsset], accountID); !isTesSuccess(ter)) return ter; - if (auto const ter = canMPTTradeAndTransfer(ctx.view, ctx.tx[sfAsset2], accountID, accountID); + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_DEPOSIT, ctx.tx[sfAsset2], accountID); !isTesSuccess(ter)) return ter; @@ -401,9 +401,9 @@ AMMDeposit::applyGuts(Sandbox& sb) if (!expected) return {expected.error(), false}; // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; - auto const tfee = (lptAMMBalance == beast::kZero) + auto const tfee = (lptAMMBalance == beast::kZERO) ? ctx_.tx[~sfTradingFee].value_or(0) - : getTradingFee(ctx_.view(), *ammSle, accountID_); + : getTradingFee(ctx_.view(), *ammSle, account_); auto const subTxType = ctx_.tx.getFlags() & tfDepositSubTx; @@ -468,13 +468,13 @@ AMMDeposit::applyGuts(Sandbox& sb) if (isTesSuccess(result)) { XRPL_ASSERT( - newLPTokenBalance > beast::kZero, + newLPTokenBalance > beast::kZERO, "xrpl::AMMDeposit::applyGuts : valid new LP token balance"); ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance); // LP depositing into AMM empty state gets the auction slot // and the voting - if (lptAMMBalance == beast::kZero) - initializeFeeAuctionVote(sb, ammSle, accountID_, lptAMMBalance.asset(), tfee); + if (lptAMMBalance == beast::kZERO) + initializeFeeAuctionVote(sb, ammSle, account_, lptAMMBalance.asset(), tfee); sb.update(ammSle); } @@ -513,20 +513,20 @@ AMMDeposit::deposit( // Check account has sufficient funds. // Return true if it does, false otherwise. auto checkBalance = [&](auto const& depositAmount) -> TER { - if (depositAmount <= beast::kZero) + if (depositAmount <= beast::kZERO) return temBAD_AMOUNT; if (isXRP(depositAmount)) { auto const& lpIssue = lpTokensDeposit.get(); // Adjust the reserve if LP doesn't have LPToken trustline - auto const sle = view.read(keylet::line(accountID_, lpIssue.account, lpIssue.currency)); - if (xrpLiquid(view, accountID_, !sle, j_) >= depositAmount) + auto const sle = view.read(keylet::line(account_, lpIssue.account, lpIssue.currency)); + if (xrpLiquid(view, account_, !sle, j_) >= depositAmount) return tesSUCCESS; } else if ( accountFunds( view, - accountID_, + account_, depositAmount, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, @@ -547,7 +547,7 @@ AMMDeposit::deposit( tfee, IsDeposit::Yes); - if (lpTokensDepositActual <= beast::kZero) + if (lpTokensDepositActual <= beast::kZERO) { JLOG(ctx_.journal.debug()) << "AMM Deposit: adjusted tokens zero"; return {tecAMM_INVALID_TOKENS, STAmount{}}; @@ -574,7 +574,7 @@ AMMDeposit::deposit( } auto res = accountSend( - view, accountID_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); + view, account_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit " << amountDepositActual; @@ -593,12 +593,7 @@ AMMDeposit::deposit( } res = accountSend( - view, - accountID_, - ammAccount, - *amount2DepositActual, - ctx_.journal, - WaiveTransferFee::Yes); + view, account_, ammAccount, *amount2DepositActual, ctx_.journal, WaiveTransferFee::Yes); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) @@ -608,7 +603,7 @@ AMMDeposit::deposit( } // Deposit LP tokens - res = accountSend(view, ammAccount, accountID_, lpTokensDepositActual, ctx_.journal); + res = accountSend(view, ammAccount, account_, lpTokensDepositActual, ctx_.journal); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit LPTokens"; @@ -647,7 +642,7 @@ AMMDeposit::equalDepositTokens( try { auto const tokensAdj = adjustLPTokensOut(view.rules(), lptAMMBalance, lpTokensDeposit); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; auto const frac = divide(tokensAdj, lptAMMBalance, lptAMMBalance.asset()); // amounts factor in the adjusted tokens @@ -719,7 +714,7 @@ AMMDeposit::equalDepositLimit( { auto frac = Number{amount} / amountBalance; auto tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::Yes); - if (tokensAdj == beast::kZero) + if (tokensAdj == beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -748,7 +743,7 @@ AMMDeposit::equalDepositLimit( } frac = Number{amount2} / amount2Balance; tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::Yes); - if (tokensAdj == beast::kZero) + if (tokensAdj == beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -798,7 +793,7 @@ AMMDeposit::singleDeposit( { auto const tokens = adjustLPTokensOut( view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); - if (tokens == beast::kZero) + if (tokens == beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -810,7 +805,7 @@ AMMDeposit::singleDeposit( // factor in the adjusted tokens auto const [tokensAdj, amountDepositAdj] = adjustAssetInByTokens(view.rules(), amountBalance, amount, lptAMMBalance, tokens, tfee); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE return deposit( view, @@ -844,7 +839,7 @@ AMMDeposit::singleDepositTokens( std::uint16_t tfee) { auto const tokensAdj = adjustLPTokensOut(view.rules(), lptAMMBalance, lpTokensDeposit); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // the adjusted tokens are factored in auto const amountDeposit = ammAssetIn(amountBalance, lptAMMBalance, tokensAdj, tfee); @@ -899,11 +894,11 @@ AMMDeposit::singleDepositEPrice( STAmount const& ePrice, std::uint16_t tfee) { - if (amount != beast::kZero) + if (amount != beast::kZERO) { auto const tokens = adjustLPTokensOut( view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); - if (tokens <= beast::kZero) + if (tokens <= beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -915,7 +910,7 @@ AMMDeposit::singleDepositEPrice( // factor in the adjusted tokens auto const [tokensAdj, amountDepositAdj] = adjustAssetInByTokens(view.rules(), amountBalance, amount, lptAMMBalance, tokens, tfee); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE auto const ep = Number{amountDepositAdj} / tokensAdj; if (ep <= ePrice) @@ -963,7 +958,7 @@ AMMDeposit::singleDepositEPrice( auto amtProdCb = [&] { return f1 * solveQuadraticEq(a1, b1, c1); }; auto const amountDeposit = getRoundedAsset(view.rules(), amtNoRoundCb, amountBalance, amtProdCb, IsDeposit::Yes); - if (amountDeposit <= beast::kZero) + if (amountDeposit <= beast::kZERO) return {tecAMM_FAILED, STAmount{}}; auto tokNoRoundCb = [&] { return amountDeposit / ePrice; }; auto tokProdCb = [&] { return amountDeposit / ePrice; }; @@ -972,7 +967,7 @@ AMMDeposit::singleDepositEPrice( // factor in the adjusted tokens auto const [tokensAdj, amountDepositAdj] = adjustAssetInByTokens( view.rules(), amountBalance, amountDeposit, lptAMMBalance, tokens, tfee); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE return deposit( @@ -1013,15 +1008,16 @@ AMMDeposit::equalDepositInEmptyState( } void -AMMDeposit::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMDeposit::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMDeposit::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index 23604d46cc..4ab3653792 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -46,7 +47,7 @@ AMMVote::preflight(PreflightContext const& ctx) return res; } - if (ctx.tx[sfTradingFee] > kTradingFeeThreshold) + if (ctx.tx[sfTradingFee] > kTRADING_FEE_THRESHOLD) { JLOG(ctx.j.debug()) << "AMM Vote: invalid trading fee."; return temBAD_FEE; @@ -64,12 +65,12 @@ AMMVote::preclaim(PreclaimContext const& ctx) JLOG(ctx.j.debug()) << "AMM Vote: Invalid asset pair."; return terNO_AMM; } - if (ammSle->getFieldAmount(sfLPTokenBalance) == beast::kZero) + if (ammSle->getFieldAmount(sfLPTokenBalance) == beast::kZERO) { return tecAMM_EMPTY; } if (auto const lpTokensNew = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j); - lpTokensNew == beast::kZero) + lpTokensNew == beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Vote: account is not LP."; return tecAMM_INVALID_TOKENS; @@ -79,14 +80,14 @@ AMMVote::preclaim(PreclaimContext const& ctx) } static std::pair -applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Journal j) +applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journal j) { auto const feeNew = ctx.tx[sfTradingFee]; auto ammSle = sb.peek(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2])); if (!ammSle) return {tecINTERNAL, false}; STAmount const lptAMMBalance = (*ammSle)[sfLPTokenBalance]; - auto const lpTokensNew = ammLPHolds(sb, *ammSle, accountID, ctx.journal); + auto const lpTokensNew = ammLPHolds(sb, *ammSle, account, ctx.journal); std::optional minTokens; std::size_t minPos{0}; AccountID minAccount{0}; @@ -105,15 +106,15 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Jou { auto const entryAccount = entry[sfAccount]; auto lpTokens = ammLPHolds(sb, *ammSle, entryAccount, ctx.journal); - if (lpTokens == beast::kZero) + if (lpTokens == beast::kZERO) { - JLOG(j.debug()) << "AMMVote::applyVote, accountID " << entryAccount << " is not LP"; + JLOG(j.debug()) << "AMMVote::applyVote, account " << entryAccount << " is not LP"; continue; } auto feeVal = entry[sfTradingFee]; STObject newEntry = STObject::makeInnerObject(sfVoteEntry); // The account already has the vote entry. - if (entryAccount == accountID) + if (entryAccount == account) { lpTokens = lpTokensNew; feeVal = feeNew; @@ -127,7 +128,8 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Jou newEntry.setFieldU16(sfTradingFee, feeVal); newEntry.setFieldU32( sfVoteWeight, - static_cast(Number(lpTokens) * kVoteWeightScaleFactor / lptAMMBalance)); + static_cast( + Number(lpTokens) * kVOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); // Find an entry with the least tokens/fee. Make the order deterministic // if the tokens/fees are equal. @@ -154,8 +156,8 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Jou newEntry.setFieldU32( sfVoteWeight, static_cast( - Number(lpTokensNew) * kVoteWeightScaleFactor / lptAMMBalance)); - newEntry.setAccountID(sfAccount, accountID); + Number(lpTokensNew) * kVOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); + newEntry.setAccountID(sfAccount, account); num += feeNew * lpTokensNew; den += lpTokensNew; if (minPos) @@ -169,7 +171,7 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Jou }; // Add new entry if the number of the vote entries // is less than Max. - if (updatedVoteSlots.size() < kVoteMaxSlots) + if (updatedVoteSlots.size() < kVOTE_MAX_SLOTS) { update(); // Add the entry if the account has more tokens than @@ -207,7 +209,7 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Jou if (ammSle->isFieldPresent(sfAuctionSlot)) { auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot); - if (auto const discountedFee = fee / kAuctionSlotDiscountedFeeFraction) + if (auto const discountedFee = fee / kAUCTION_SLOT_DISCOUNTED_FEE_FRACTION) { auctionSlot.setFieldU16(sfDiscountedFee, discountedFee); } @@ -240,7 +242,7 @@ AMMVote::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyVote(ctx_, sb, accountID_, j_); + auto const result = applyVote(ctx_, sb, account_, j_); if (result.second) sb.apply(ctx_.rawView()); @@ -248,15 +250,16 @@ AMMVote::doApply() } void -AMMVote::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMVote::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMVote::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index e57f8558ff..bae9d098a3 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include #include #include @@ -32,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -80,37 +83,37 @@ AMMWithdraw::preflight(PreflightContext const& ctx) JLOG(ctx.j.debug()) << "AMM Withdraw: invalid flags."; return temMALFORMED; } - if (ctx.tx.isFlag(tfLPToken)) + if ((flags & tfLPToken) != 0u) { if (!lpTokens || amount || amount2 || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfWithdrawAll)) + else if ((flags & tfWithdrawAll) != 0u) { if (lpTokens || amount || amount2 || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfOneAssetWithdrawAll)) + else if ((flags & tfOneAssetWithdrawAll) != 0u) { if (!amount || lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfSingleAsset)) + else if ((flags & tfSingleAsset) != 0u) { if (!amount || lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfTwoAsset)) + else if ((flags & tfTwoAsset) != 0u) { if (!amount || !amount2 || lpTokens || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfOneAssetLPToken)) + else if ((flags & tfOneAssetLPToken) != 0u) { if (!amount || !lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (ctx.tx.isFlag(tfLimitLPToken)) + else if ((flags & tfLimitLPToken) != 0u) { if (!amount || !ePrice || lpTokens || amount2) return temMALFORMED; @@ -131,7 +134,7 @@ AMMWithdraw::preflight(PreflightContext const& ctx) return temBAD_AMM_TOKENS; } - if (lpTokens && *lpTokens <= beast::kZero) + if (lpTokens && *lpTokens <= beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens."; return temBAD_AMM_TOKENS; @@ -208,10 +211,10 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) if (!expected) return expected.error(); auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; - if (lptAMMBalance == beast::kZero) + if (lptAMMBalance == beast::kZERO) return tecAMM_EMPTY; - if (amountBalance <= beast::kZero || amount2Balance <= beast::kZero || - lptAMMBalance < beast::kZero) + if (amountBalance <= beast::kZERO || amount2Balance <= beast::kZERO || + lptAMMBalance < beast::kZERO) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "AMM Withdraw: reserves or tokens balance is zero."; @@ -239,21 +242,24 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) return ter; } // AMM account or currency frozen - if (auto const ter = checkFrozen(ctx.view, ammAccountID, amount->asset()); - !isTesSuccess(ter)) + if (isFrozen(ctx.view, ammAccountID, amount->asset())) { - JLOG(ctx.j.debug()) << "AMM Withdraw: AMM account or currency is frozen or locked, " - << to_string(accountID); - return ter; + JLOG(ctx.j.debug()) + << "AMM Withdraw: AMM account or currency is frozen, " << to_string(accountID); + return tecFROZEN; } // Account frozen - if (auto const ter = checkIndividualFrozen(ctx.view, accountID, amount->asset()); - !isTesSuccess(ter)) + if (isIndividualFrozen(ctx.view, accountID, amount->asset())) { - JLOG(ctx.j.debug()) << "AMM Withdraw: account is frozen or locked, " - << to_string(accountID) << " " << to_string(amount->asset()); - return ter; + JLOG(ctx.j.debug()) << "AMM Withdraw: account is frozen, " << to_string(accountID) + << " " << to_string(amount->asset()); + return tecFROZEN; } + + if (auto const ter = + checkMPTTxAllowed(ctx.view, ttAMM_WITHDRAW, amount->asset(), accountID); + !isTesSuccess(ter)) + return ter; } return tesSUCCESS; }; @@ -267,7 +273,7 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) auto const lpTokens = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j); auto const lpTokensWithdraw = tokensWithdraw(lpTokens, ctx.tx[~sfLPTokenIn], ctx.tx.getFlags()); - if (lpTokens <= beast::kZero) + if (lpTokens <= beast::kZERO) { JLOG(ctx.j.debug()) << "AMM Withdraw: tokens balance is zero."; return tecAMM_BALANCE; @@ -323,11 +329,11 @@ AMMWithdraw::applyGuts(Sandbox& sb) // might not match the LP's trustline balance if (sb.rules().enabled(fixAMMv1_1)) { - if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokens, ammSle, accountID_); !res) + if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokens, ammSle, account_); !res) return {res.error(), false}; } - auto const tfee = getTradingFee(ctx_.view(), *ammSle, accountID_); + auto const tfee = getTradingFee(ctx_.view(), *ammSle, account_); auto const expected = ammHolds( sb, @@ -452,7 +458,7 @@ AMMWithdraw::withdraw( view, ammSle, ammAccount, - accountID_, + account_, amountBalance, amountWithdraw, amount2Withdraw, @@ -511,7 +517,7 @@ AMMWithdraw::withdraw( return std::make_tuple(amountWithdraw, amount2Withdraw, lpTokensWithdraw); }(); - if (lpTokensWithdrawActual <= beast::kZero || lpTokensWithdrawActual > lpTokens) + if (lpTokensWithdrawActual <= beast::kZERO || lpTokensWithdrawActual > lpTokens) { JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, invalid LP tokens: " << lpTokensWithdrawActual << " " << lpTokens << " " @@ -570,10 +576,10 @@ AMMWithdraw::withdraw( // or all balances are non-zero. if (view.rules().enabled(featureMPTokensV2)) { - bool const newBalanceZero = (curBalance - amountWithdrawActual) == beast::kZero; + bool const newBalanceZero = (curBalance - amountWithdrawActual) == beast::kZERO; bool const newBalance2Zero = - (curBalance2 - amount2WithdrawActual.value_or(curBalance2.asset())) == beast::kZero; - bool const newLPTokensZero = (lpTokensAMMBalance - lpTokensWithdrawActual) == beast::kZero; + (curBalance2 - amount2WithdrawActual.value_or(curBalance2.asset())) == beast::kZERO; + bool const newLPTokensZero = (lpTokensAMMBalance - lpTokensWithdrawActual) == beast::kZERO; // newBalance2Zero can be zero if that side of the pool is frozen. // ignore newBalance2Zero if one-sided withdrawal. bool const valid = [&]() { @@ -623,12 +629,16 @@ AMMWithdraw::withdraw( // See also TrustSet::doApply() and MPTokenAuthorize::authorize() XRPAmount const reserve( - (ownerCount < 2) ? XRPAmount(beast::kZero) + (ownerCount < 2) ? XRPAmount(beast::kZERO) : view.fees().accountReserve(ownerCount + 1)); auto const balanceAdj = isIssue ? std::max(priorBalance, balance.xrp()) : priorBalance; if (balanceAdj < reserve) return tecINSUFFICIENT_RESERVE; + + // Update owner count. + if (!isIssue) + adjustOwnerCount(view, sleAccount, 1, journal); } return tesSUCCESS; }; @@ -738,7 +748,7 @@ AMMWithdraw::equalWithdrawTokens( std::tie(ter, newLPTokenBalance, std::ignore, std::ignore) = equalWithdrawTokens( view, ammSle, - accountID_, + account_, ammAccount, amountBalance, amount2Balance, @@ -757,7 +767,7 @@ AMMWithdraw::equalWithdrawTokens( std::pair AMMWithdraw::deleteAMMAccountIfEmpty( Sandbox& sb, - SLE::pointer const ammSle, + std::shared_ptr const ammSle, STAmount const& lpTokenBalance, Asset const& asset1, Asset const& asset2, @@ -765,7 +775,7 @@ AMMWithdraw::deleteAMMAccountIfEmpty( { TER ter; bool updateBalance = true; - if (lpTokenBalance == beast::kZero) + if (lpTokenBalance == beast::kZERO) { ter = deleteAMMAccount(sb, asset1, asset2, journal); if (!isTesSuccess(ter) && ter != tecINCOMPLETE) @@ -828,7 +838,7 @@ AMMWithdraw::equalWithdrawTokens( auto const tokensAdj = adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, withdrawAll); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}, STAmount{}, std::nullopt}; // the adjusted tokens are factored in auto const frac = divide(tokensAdj, lptAMMBalance, noIssue()); @@ -840,7 +850,7 @@ AMMWithdraw::equalWithdrawTokens( // of LP tokens is likely too small and results in one-sided pool // withdrawal due to round off. Fail so the user withdraws // more tokens. - if (amountWithdraw == beast::kZero || amount2Withdraw == beast::kZero) + if (amountWithdraw == beast::kZERO || amount2Withdraw == beast::kZERO) return {tecAMM_FAILED, STAmount{}, STAmount{}, STAmount{}}; return withdraw( @@ -908,7 +918,7 @@ AMMWithdraw::equalWithdrawLimit( { auto frac = Number{amount} / amountBalance; auto tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::No); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // factor in the adjusted tokens frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac); @@ -930,7 +940,7 @@ AMMWithdraw::equalWithdrawLimit( frac = Number{amount2} / amount2Balance; auto amountWithdraw = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No); tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::No); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE // factor in the adjusted tokens frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac); @@ -979,7 +989,7 @@ AMMWithdraw::singleWithdraw( lptAMMBalance, lpTokensIn(amountBalance, amount, lptAMMBalance, tfee), isWithdrawAll(ctx_.tx)); - if (tokens == beast::kZero) + if (tokens == beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -991,7 +1001,7 @@ AMMWithdraw::singleWithdraw( // factor in the adjusted tokens auto const [tokensAdj, amountWithdrawAdj] = adjustAssetOutByTokens(view.rules(), amountBalance, amount, lptAMMBalance, tokens, tfee); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE return withdraw( view, @@ -1028,11 +1038,11 @@ AMMWithdraw::singleWithdrawTokens( { auto const tokensAdj = adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, isWithdrawAll(ctx_.tx)); - if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero) + if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZERO) return {tecAMM_INVALID_TOKENS, STAmount{}}; // the adjusted tokens are factored in auto const amountWithdraw = ammAssetOut(amountBalance, lptAMMBalance, tokensAdj, tfee); - if (amount == beast::kZero || amountWithdraw >= amount) + if (amount == beast::kZERO || amountWithdraw >= amount) { return withdraw( view, @@ -1097,7 +1107,7 @@ AMMWithdraw::singleWithdrawEPrice( auto tokProdCb = [&] { return (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); }; auto const tokensAdj = getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::No); - if (tokensAdj <= beast::kZero) + if (tokensAdj <= beast::kZERO) { if (!view.rules().enabled(fixAMMv1_3)) { @@ -1111,7 +1121,7 @@ AMMWithdraw::singleWithdrawEPrice( // the adjusted tokens are factored in auto const amountWithdraw = getRoundedAsset(view.rules(), amtNoRoundCb, amount, amtProdCb, IsDeposit::No); - if (amount == beast::kZero || amountWithdraw >= amount) + if (amount == beast::kZERO || amountWithdraw >= amount) { return withdraw( view, @@ -1136,15 +1146,16 @@ AMMWithdraw::isWithdrawAll(STTx const& tx) return WithdrawAll::No; } void -AMMWithdraw::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +AMMWithdraw::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool AMMWithdraw::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index 0dea5fa967..72682149a3 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -10,6 +10,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -53,11 +55,11 @@ OfferCancel::doApply() { auto const offerSequence = ctx_.tx[sfOfferSequence]; - auto const sle = view().read(keylet::account(accountID_)); + auto const sle = view().read(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE - if (auto sleOffer = view().peek(keylet::offer(accountID_, offerSequence))) + if (auto sleOffer = view().peek(keylet::offer(account_, offerSequence))) { JLOG(j_.debug()) << "Trying to cancel offer #" << offerSequence; return offerDelete(view(), sleOffer, ctx_.registry.get().getJournal("View")); @@ -68,15 +70,16 @@ OfferCancel::doApply() } void -OfferCancel::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +OfferCancel::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool OfferCancel::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 547d40e7b8..b69ed766c5 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -57,7 +57,7 @@ OfferCreate::makeTxConsequences(PreflightContext const& ctx) { auto calculateMaxXRPSpend = [](STTx const& tx) -> XRPAmount { auto const& amount{tx[sfTakerGets]}; - return amount.native() ? amount.xrp() : beast::kZero; + return amount.native() ? amount.xrp() : beast::kZERO; }; return TxConsequences{ctx.tx, calculateMaxXRPSpend(ctx.tx)}; @@ -91,17 +91,13 @@ OfferCreate::preflight(PreflightContext const& ctx) auto& tx = ctx.tx; auto& j = ctx.j; + std::uint32_t const uTxFlags = tx.getFlags(); + if (tx.isFlag(tfHybrid) && !tx.isFieldPresent(sfDomainID)) return temINVALID_FLAG; - // A zero DomainID is invalid for a PermissionedDomain ledger entry because - // keylet::permissionedDomain(uint256) uses the DomainID as the ledger key. - if (auto const domainID = tx[~sfDomainID]; - ctx.rules.enabled(fixCleanup3_2_0) && domainID && *domainID == beast::kZero) - return temMALFORMED; - - bool const bImmediateOrCancel(tx.isFlag(tfImmediateOrCancel)); - bool const bFillOrKill(tx.isFlag(tfFillOrKill)); + bool const bImmediateOrCancel((uTxFlags & tfImmediateOrCancel) != 0u); + bool const bFillOrKill((uTxFlags & tfFillOrKill) != 0u); if (bImmediateOrCancel && bFillOrKill) { @@ -134,7 +130,7 @@ OfferCreate::preflight(PreflightContext const& ctx) JLOG(j.debug()) << "Malformed offer: redundant (XRP for XRP)"; return temBAD_OFFER; } - if (saTakerPays <= beast::kZero || saTakerGets <= beast::kZero) + if (saTakerPays <= beast::kZERO || saTakerGets <= beast::kZERO) { JLOG(j.debug()) << "Malformed offer: bad amount"; return temBAD_OFFER; @@ -187,15 +183,11 @@ OfferCreate::preclaim(PreclaimContext const& ctx) auto viewJ = ctx.registry.get().getJournal("View"); - if (auto const ter = checkGlobalFrozen(ctx.view, saTakerPays.asset()); !isTesSuccess(ter)) + if (isGlobalFrozen(ctx.view, saTakerPays.asset()) || + isGlobalFrozen(ctx.view, saTakerGets.asset())) { - JLOG(ctx.j.debug()) << "Offer involves frozen or locked asset"; - return ter; - } - if (auto const ter = checkGlobalFrozen(ctx.view, saTakerGets.asset()); !isTesSuccess(ter)) - { - JLOG(ctx.j.debug()) << "Offer involves frozen or locked asset"; - return ter; + JLOG(ctx.j.debug()) << "Offer involves frozen asset"; + return tecFROZEN; } // Allow unfunded MPT for issuer (OutstandingAmount >= MaximumAmount) @@ -206,7 +198,7 @@ OfferCreate::preclaim(PreclaimContext const& ctx) saTakerGets, FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, - viewJ) <= beast::kZero) + viewJ) <= beast::kZERO) { JLOG(ctx.j.debug()) << "delay: Offers must be at least partially funded."; return tecUNFUNDED_OFFER; @@ -282,7 +274,7 @@ OfferCreate::checkAcceptAsset( return asset.visit( [&](Issue const& issue) -> TER { auto const& issuer = issue.getIssuer(); - if (issuerAccount->isFlag(lsfRequireAuth)) + if (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u) { auto const trustLine = view.read(keylet::line(id, issuer, issue.currency)); @@ -297,7 +289,8 @@ OfferCreate::checkAcceptAsset( // access. bool const canonicalGt(id > issuer); - bool const isAuthorized(trustLine->isFlag(canonicalGt ? lsfLowAuth : lsfHighAuth)); + bool const isAuthorized( + ((*trustLine)[sfFlags] & (canonicalGt ? lsfLowAuth : lsfHighAuth)) != 0u); if (!isAuthorized) { @@ -330,13 +323,7 @@ OfferCreate::checkAcceptAsset( [&](MPTIssue const& issue) -> TER { // WeakAuth - don't check if MPToken exists since it's created // if needed. - if (auto const ter = requireAuth(view, issue, id, AuthType::WeakAuth); - !isTesSuccess(ter)) - { - return ter; - } - - return checkFrozen(view, id, issue); + return requireAuth(view, issue, id, AuthType::WeakAuth); }); } @@ -357,15 +344,15 @@ OfferCreate::flowCross( // below the reserve) so we check this case again. STAmount const inStartBalance = accountFunds( psb, - accountID_, + account_, takerAmount.in, FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, j_); // Allow unfunded MPT issuer auto const disallowUnfunded = - !inStartBalance.holds() || inStartBalance.getIssuer() != accountID_; - if (disallowUnfunded && inStartBalance <= beast::kZero) + !inStartBalance.holds() || inStartBalance.getIssuer() != account_; + if (disallowUnfunded && inStartBalance <= beast::kZERO) { // The account balance can't cover even part of the offer. JLOG(j_.debug()) << "Not crossing: taker is unfunded."; @@ -377,7 +364,7 @@ OfferCreate::flowCross( // offer taker. Set sendMax to allow for the gateway's cut. Rate gatewayXferRate{QUALITY_ONE}; STAmount sendMax = takerAmount.in; - if (!sendMax.native() && (accountID_ != sendMax.getIssuer())) + if (!sendMax.native() && (account_ != sendMax.getIssuer())) { gatewayXferRate = transferRate(psb, sendMax); if (gatewayXferRate.value != QUALITY_ONE) @@ -393,7 +380,8 @@ OfferCreate::flowCross( // If we're creating a passive offer adjust the threshold so we only // cross offers that have a better quality than this one. - if (ctx_.tx.isFlag(tfPassive)) + std::uint32_t const txFlags = ctx_.tx.getFlags(); + if ((txFlags & tfPassive) != 0u) ++threshold; // Don't send more than our balance. @@ -415,7 +403,7 @@ OfferCreate::flowCross( STAmount deliver = takerAmount.out; auto const& deliverAsset = deliver.asset(); OfferCrossing offerCrossing = OfferCrossing::Yes; - if (ctx_.tx.isFlag(tfSell)) + if ((txFlags & tfSell) != 0u) { offerCrossing = OfferCrossing::Sell; // We are selling, so we will accept *more* than the offer @@ -425,7 +413,7 @@ OfferCreate::flowCross( [&](Issue const& issue) { if (issue.native()) { - deliver = STAmount{STAmount::kMaxNative}; + deliver = STAmount{STAmount::kMAX_NATIVE}; } // We can't use the maximum possible currency here because // there might be a gateway transfer rate to account for. @@ -434,22 +422,24 @@ OfferCreate::flowCross( else { deliver = - STAmount{deliverAsset, STAmount::kMaxValue / 2, STAmount::kMaxOffset}; + STAmount{deliverAsset, STAmount::kMAX_VALUE / 2, STAmount::kMAX_OFFSET}; } }, - [&](MPTIssue const&) { deliver = STAmount{deliverAsset, kMaxMpTokenAmount / 2}; }); + [&](MPTIssue const&) { + deliver = STAmount{deliverAsset, kMAX_MP_TOKEN_AMOUNT / 2}; + }); } // Call the payment engine's flow() to do the actual work. auto const result = flow( psb, deliver, - accountID_, - accountID_, + account_, + account_, paths, - true, // default path - !ctx_.tx.isFlag(tfFillOrKill), // partial payment - true, // owner pays transfer fee + true, // default path + (txFlags & tfFillOrKill) == 0u, // partial payment + true, // owner pays transfer fee offerCrossing, threshold, sendMax, @@ -471,13 +461,13 @@ OfferCreate::flowCross( { STAmount const takerInBalance = accountFunds( psb, - accountID_, + account_, takerAmount.in, FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, j_); - if (disallowUnfunded && takerInBalance <= beast::kZero) + if (disallowUnfunded && takerInBalance <= beast::kZERO) { // If offer crossing exhausted the account's funds don't // create the offer. @@ -488,7 +478,7 @@ OfferCreate::flowCross( { STAmount const rate{Quality{takerAmount.out, takerAmount.in}.rate()}; - if (ctx_.tx.isFlag(tfSell)) + if ((txFlags & tfSell) != 0u) { // If selling then scale the new out amount based on how // much we sold during crossing. This preserves the offer @@ -508,8 +498,8 @@ OfferCreate::flowCross( afterCross.in -= nonGatewayAmountIn; // It's possible that the divRound will cause our subtract - // to go slightly negative. So limit afterCross.in to beast::kZero. - if (afterCross.in < beast::kZero) + // to go slightly negative. So limit afterCross.in to beast::kZERO. + if (afterCross.in < beast::kZERO) { // We should verify that the difference *is* small, but // what is a good threshold to check? @@ -526,9 +516,9 @@ OfferCreate::flowCross( // Quality. afterCross.out -= result.actualAmountOut; XRPL_ASSERT( - afterCross.out >= beast::kZero, + afterCross.out >= beast::kZERO, "xrpl::OfferCreate::flowCross : minimum offer"); - if (afterCross.out < beast::kZero) + if (afterCross.out < beast::kZERO) afterCross.out.clear(); afterCross.in = mulRound(afterCross.out, rate, takerAmount.in.asset(), true); } @@ -559,11 +549,10 @@ OfferCreate::formatAmount(STAmount const& amount) TER OfferCreate::applyHybrid( Sandbox& sb, - STLedgerEntry::pointer sleOffer, + std::shared_ptr sleOffer, Keylet const& offerKey, STAmount const& saTakerPays, STAmount const& saTakerGets, - std::uint64_t openRate, std::function)> const& setDir) { if (!sleOffer->isFieldPresent(sfDomainID)) @@ -575,7 +564,7 @@ OfferCreate::applyHybrid( // if offer is hybrid, need to also place into open offer dir Book const book{saTakerPays.asset(), saTakerGets.asset(), std::nullopt}; - auto dir = keylet::quality(keylet::kBook(book), openRate); + auto dir = keylet::quality(keylet::kBOOK(book), getRate(saTakerGets, saTakerPays)); bool const bookExists = sb.exists(dir); auto const bookNode = sb.dirAppend(dir, offerKey, [&](SLE::ref sle) { @@ -606,13 +595,15 @@ OfferCreate::applyHybrid( std::pair OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) { - using beast::kZero; + using beast::kZERO; - bool const bPassive(ctx_.tx.isFlag(tfPassive)); - bool const bImmediateOrCancel(ctx_.tx.isFlag(tfImmediateOrCancel)); - bool const bFillOrKill(ctx_.tx.isFlag(tfFillOrKill)); - bool const bSell(ctx_.tx.isFlag(tfSell)); - bool const bHybrid(ctx_.tx.isFlag(tfHybrid)); + std::uint32_t const uTxFlags = ctx_.tx.getFlags(); + + bool const bPassive((uTxFlags & tfPassive) != 0u); + bool const bImmediateOrCancel((uTxFlags & tfImmediateOrCancel) != 0u); + bool const bFillOrKill((uTxFlags & tfFillOrKill) != 0u); + bool const bSell((uTxFlags & tfSell) != 0u); + bool const bHybrid((uTxFlags & tfHybrid) != 0u); auto saTakerPays = ctx_.tx[sfTakerPays]; auto saTakerGets = ctx_.tx[sfTakerGets]; @@ -636,7 +627,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // Process a cancellation request that's passed along with an offer. if (cancelSequence) { - auto const sleCancel = sb.peek(keylet::offer(accountID_, *cancelSequence)); + auto const sleCancel = sb.peek(keylet::offer(account_, *cancelSequence)); // It's not an error to not find the offer to cancel: it might have // been consumed or removed. If it is found, however, it's an error @@ -665,7 +656,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) auto const& uPaysIssuerID = saTakerPays.getIssuer(); auto const& uGetsIssuerID = saTakerGets.getIssuer(); - std::uint8_t uTickSize = Quality::kMaxTickSize; + std::uint8_t uTickSize = Quality::kMAX_TICK_SIZE; // Not XRP or MPT if (!saTakerPays.integral()) { @@ -680,7 +671,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) if (sle && sle->isFieldPresent(sfTickSize)) uTickSize = std::min(uTickSize, (*sle)[sfTickSize]); } - if (uTickSize < Quality::kMaxTickSize) + if (uTickSize < Quality::kMAX_TICK_SIZE) { auto const rate = Quality{saTakerGets, saTakerPays}.round(uTickSize).rate(); @@ -766,7 +757,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // The offer that we need to place after offer crossing should // never be negative. If it is, something went very very wrong. - if (placeOffer.in < kZero || placeOffer.out < kZero) + if (placeOffer.in < kZERO || placeOffer.out < kZERO) { JLOG(j_.fatal()) << "Cross left offer negative!" << " in: " << formatAmount(placeOffer.in) @@ -774,7 +765,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {tefINTERNAL, true}; } - if (placeOffer.in == kZero || placeOffer.out == kZero) + if (placeOffer.in == kZERO || placeOffer.out == kZERO) { JLOG(j_.debug()) << "Offer fully crossed!"; return {result, true}; @@ -788,7 +779,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } XRPL_ASSERT( - saTakerPays > beast::kZero && saTakerGets > beast::kZero, + saTakerPays > beast::kZERO && saTakerGets > beast::kZERO, "xrpl::OfferCreate::applyGuts : taker pays and gets positive"); if (!isTesSuccess(result)) @@ -827,7 +818,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {tesSUCCESS, true}; } - auto const sleCreator = sb.peek(keylet::account(accountID_)); + auto const sleCreator = sb.peek(keylet::account(account_)); if (!sleCreator) return {tefINTERNAL, false}; @@ -853,11 +844,11 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } // We need to place the remainder of the offer into its order book. - auto const offerIndex = keylet::offer(accountID_, offerSequence); + auto const offerIndex = keylet::offer(account_, offerSequence); // Add offer to owner's directory. auto const ownerNode = - sb.dirInsert(keylet::ownerDir(accountID_), offerIndex, describeOwnerDir(accountID_)); + sb.dirInsert(keylet::ownerDir(account_), offerIndex, describeOwnerDir(account_)); if (!ownerNode) { @@ -887,7 +878,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // Hybrid domain offer - BookDirectory points to domain directory, // and AdditionalBooks field stores one entry that points to the open // directory - auto dir = keylet::quality(keylet::kBook(book), uRate); + auto dir = keylet::quality(keylet::kBOOK(book), uRate); bool const bookExisted = static_cast(sb.peek(dir)); auto setBookDir = [&](SLE::ref sle, std::optional const& maybeDomain) { @@ -922,7 +913,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } auto sleOffer = std::make_shared(offerIndex); - sleOffer->setAccountID(sfAccount, accountID_); + sleOffer->setAccountID(sfAccount, account_); sleOffer->setFieldU32(sfSequence, offerSequence); sleOffer->setFieldH256(sfBookDirectory, dir.key); sleOffer->setFieldAmount(sfTakerPays, saTakerPays); @@ -941,16 +932,8 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // if it's a hybrid offer, set hybrid flag, and create an open dir if (bHybrid) { - // Pre-fixCleanup3_2_0: the open-book directory quality was computed - // from post-crossing amounts, which may differ from the original rate - // due to rounding in rate preservation. Post-fixCleanup3_2_0: use the - // original placement rate so the open-book directory quality matches - // the domain-book directory. - auto const openRate = ctx_.view().rules().enabled(fixCleanup3_2_0) - ? uRate - : getRate(saTakerGets, saTakerPays); auto const res = - applyHybrid(sb, sleOffer, offerIndex, saTakerPays, saTakerGets, openRate, setBookDir); + applyHybrid(sb, sleOffer, offerIndex, saTakerPays, saTakerGets, setBookDir); if (!isTesSuccess(res)) return {res, true}; // LCOV_EXCL_LINE } @@ -990,15 +973,16 @@ OfferCreate::doApply() } void -OfferCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +OfferCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool OfferCreate::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/did/DIDDelete.cpp b/src/libxrpl/tx/transactors/did/DIDDelete.cpp index 90aa21d8a1..a323822b9c 100644 --- a/src/libxrpl/tx/transactors/did/DIDDelete.cpp +++ b/src/libxrpl/tx/transactors/did/DIDDelete.cpp @@ -16,6 +16,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -35,7 +37,11 @@ DIDDelete::deleteSLE(ApplyContext& ctx, Keylet sleKeylet, AccountID const owner) } TER -DIDDelete::deleteSLE(ApplyView& view, SLE::pointer sle, AccountID const owner, beast::Journal j) +DIDDelete::deleteSLE( + ApplyView& view, + std::shared_ptr sle, + AccountID const owner, + beast::Journal j) { // Remove object from owner directory if (!view.dirRemove(keylet::ownerDir(owner), (*sle)[sfOwnerNode], sle->key(), true)) @@ -61,19 +67,20 @@ DIDDelete::deleteSLE(ApplyView& view, SLE::pointer sle, AccountID const owner, b TER DIDDelete::doApply() { - return deleteSLE(ctx_, keylet::did(accountID_), accountID_); + return deleteSLE(ctx_, keylet::did(account_), account_); } void -DIDDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +DIDDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool DIDDelete::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/did/DIDSet.cpp b/src/libxrpl/tx/transactors/did/DIDSet.cpp index 1392581bb0..69bb9dd839 100644 --- a/src/libxrpl/tx/transactors/did/DIDSet.cpp +++ b/src/libxrpl/tx/transactors/did/DIDSet.cpp @@ -55,15 +55,16 @@ DIDSet::preflight(PreflightContext const& ctx) return false; }; - if (isTooLong(sfURI, kMaxDidUriLength) || isTooLong(sfDIDDocument, kMaxDidDocumentLength) || - isTooLong(sfData, kMaxDidDataLength)) + if (isTooLong(sfURI, kMAX_DIDURI_LENGTH) || + isTooLong(sfDIDDocument, kMAX_DID_DOCUMENT_LENGTH) || + isTooLong(sfData, kMAX_DID_DATA_LENGTH)) return temMALFORMED; return tesSUCCESS; } static TER -addSLE(ApplyContext& ctx, SLE::ref sle, AccountID const& owner) +addSLE(ApplyContext& ctx, std::shared_ptr const& sle, AccountID const& owner) { auto const sleAccount = ctx.view().peek(keylet::account(owner)); if (!sleAccount) @@ -99,7 +100,7 @@ TER DIDSet::doApply() { // Edit ledger object if it already exists - Keylet const didKeylet = keylet::did(accountID_); + Keylet const didKeylet = keylet::did(account_); if (auto const sleDID = ctx_.view().peek(didKeylet)) { auto update = [&](auto const& sField) { @@ -130,7 +131,7 @@ DIDSet::doApply() // Create new ledger object otherwise auto const sleDID = std::make_shared(didKeylet); - (*sleDID)[sfAccount] = accountID_; + (*sleDID)[sfAccount] = account_; auto set = [&](auto const& sField) { if (auto const field = ctx_.tx[~sField]; field && !field->empty()) @@ -146,19 +147,20 @@ DIDSet::doApply() return tecEMPTY_DID; } - return addSLE(ctx_, sleDID, accountID_); + return addSLE(ctx_, sleDID, account_); } void -DIDSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +DIDSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool DIDSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index b8f4604d73..9a48123201 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -23,6 +23,7 @@ #include #include +#include #include namespace xrpl { @@ -177,13 +178,13 @@ EscrowCancel::doApply() return temDISABLED; // LCOV_EXCL_LINE auto const issuer = amount.getIssuer(); - bool const createAsset = account == accountID_; + bool const createAsset = account == account_; if (auto const ret = std::visit( [&](T const&) { return escrowUnlockApplyHelper( ctx_.view(), - kParityRate, - ctx_.view().rules().enabled(fixCleanup3_2_0) ? sle : slep, + kPARITY_RATE, + slep, preFeeBalance_, amount, issuer, @@ -219,9 +220,11 @@ EscrowCancel::doApply() } void -EscrowCancel::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +EscrowCancel::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -232,7 +235,6 @@ EscrowCancel::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index 0a12e2d1bc..d5bbe17325 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -78,17 +78,7 @@ TxConsequences EscrowCreate::makeTxConsequences(PreflightContext const& ctx) { auto const amount = ctx.tx[sfAmount]; - return TxConsequences{ctx.tx, isXRP(amount) ? amount.xrp() : beast::kZero}; -} - -bool -EscrowCreate::checkExtraFeatures(PreflightContext const& ctx) -{ - // Only require featureMPTokensV1 when the escrow amount is an MPT and - // fixCleanup3_2_0 is active; XRP/IOU escrows are unaffected by this gate. - if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx[sfAmount].holds()) - return ctx.rules.enabled(featureMPTokensV1); - return true; + return TxConsequences{ctx.tx, isXRP(amount) ? amount.xrp() : beast::kZERO}; } template @@ -100,7 +90,7 @@ NotTEC escrowCreatePreflightHelper(PreflightContext const& ctx) { STAmount const amount = ctx.tx[sfAmount]; - if (amount.native() || amount <= beast::kZero) + if (amount.native() || amount <= beast::kZERO) return temBAD_AMOUNT; if (badCurrency() == amount.get().currency) @@ -113,11 +103,11 @@ template <> NotTEC escrowCreatePreflightHelper(PreflightContext const& ctx) { - if (!ctx.rules.enabled(fixCleanup3_2_0) && !ctx.rules.enabled(featureMPTokensV1)) + if (!ctx.rules.enabled(featureMPTokensV1)) return temDISABLED; auto const amount = ctx.tx[sfAmount]; - if (amount.native() || amount.mpt() > MPTAmount{kMaxMpTokenAmount} || amount <= beast::kZero) + if (amount.native() || amount.mpt() > MPTAmount{kMAX_MP_TOKEN_AMOUNT} || amount <= beast::kZERO) return temBAD_AMOUNT; return tesSUCCESS; @@ -140,7 +130,7 @@ EscrowCreate::preflight(PreflightContext const& ctx) } else { - if (amount <= beast::kZero) + if (amount <= beast::kZERO) return temBAD_AMOUNT; } @@ -215,11 +205,11 @@ escrowCreatePreclaimHelper( STAmount const balance = (*sleRippleState)[sfBalance]; // If balance is positive, issuer must have higher address than account - if (balance > beast::kZero && issuer < account) + if (balance > beast::kZERO && issuer < account) return tecNO_PERMISSION; // LCOV_EXCL_LINE // If balance is negative, issuer must have lower address than account - if (balance < beast::kZero && issuer > account) + if (balance < beast::kZERO && issuer > account) return tecNO_PERMISSION; // LCOV_EXCL_LINE // If the issuer has requireAuth set, check if the account is authorized @@ -242,7 +232,7 @@ escrowCreatePreclaimHelper( ctx.view, account, issue.currency, issuer, FreezeHandling::IgnoreFreeze, ctx.j); // If the balance is less than or equal to 0, return tecINSUFFICIENT_FUNDS - if (spendableAmount <= beast::kZero) + if (spendableAmount <= beast::kZERO) return tecINSUFFICIENT_FUNDS; // If the spendable amount is less than the amount, return @@ -323,7 +313,7 @@ escrowCreatePreclaimHelper( ctx.j); // If the balance is less than or equal to 0, return tecINSUFFICIENT_FUNDS - if (spendableAmount <= beast::kZero) + if (spendableAmount <= beast::kZERO) return tecINSUFFICIENT_FUNDS; // If the spendable amount is less than the amount, return @@ -427,7 +417,7 @@ EscrowCreate::doApply() if (ctx_.tx[~sfFinishAfter] && after(closeTime, ctx_.tx[sfFinishAfter])) return tecNO_PERMISSION; - auto const sle = ctx_.view().peek(keylet::account(accountID_)); + auto const sle = ctx_.view().peek(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -452,16 +442,16 @@ EscrowCreate::doApply() auto const sled = ctx_.view().read(keylet::account(ctx_.tx[sfDestination])); if (!sled) return tecNO_DST; // LCOV_EXCL_LINE - if (sled->isFlag(lsfRequireDestTag) && !ctx_.tx[~sfDestinationTag]) + if ((((*sled)[sfFlags] & lsfRequireDestTag) != 0u) && !ctx_.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; } // Create escrow in ledger. Note that we use the value from the // sequence or ticket. For more explanation see comments in SeqProxy.h. - Keylet const escrowKeylet = keylet::escrow(accountID_, ctx_.tx.getSeqValue()); + Keylet const escrowKeylet = keylet::escrow(account_, ctx_.tx.getSeqValue()); auto const slep = std::make_shared(escrowKeylet); (*slep)[sfAmount] = amount; - (*slep)[sfAccount] = accountID_; + (*slep)[sfAccount] = account_; (*slep)[~sfCondition] = ctx_.tx[~sfCondition]; (*slep)[~sfSourceTag] = ctx_.tx[~sfSourceTag]; (*slep)[sfDestination] = ctx_.tx[sfDestination]; @@ -477,7 +467,7 @@ EscrowCreate::doApply() if (ctx_.view().rules().enabled(featureTokenEscrow) && !isXRP(amount)) { auto const xferRate = transferRate(ctx_.view(), amount); - if (xferRate != kParityRate) + if (xferRate != kPARITY_RATE) (*slep)[sfTransferRate] = xferRate.value; } @@ -486,7 +476,7 @@ EscrowCreate::doApply() // Add escrow to sender's owner directory { auto page = ctx_.view().dirInsert( - keylet::ownerDir(accountID_), escrowKeylet, describeOwnerDir(accountID_)); + keylet::ownerDir(account_), escrowKeylet, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfOwnerNode] = *page; @@ -494,7 +484,7 @@ EscrowCreate::doApply() // If it's not a self-send, add escrow to recipient's owner directory. AccountID const dest = ctx_.tx[sfDestination]; - if (dest != accountID_) + if (dest != account_) { auto page = ctx_.view().dirInsert(keylet::ownerDir(dest), escrowKeylet, describeOwnerDir(dest)); @@ -507,7 +497,7 @@ EscrowCreate::doApply() // track the total locked balance. For MPT, this isn't necessary because the // locked balance is already stored directly in the MPTokenIssuance object. AccountID const issuer = amount.getIssuer(); - if (!isXRP(amount) && issuer != accountID_ && issuer != dest && !amount.holds()) + if (!isXRP(amount) && issuer != account_ && issuer != dest && !amount.holds()) { auto page = ctx_.view().dirInsert(keylet::ownerDir(issuer), escrowKeylet, describeOwnerDir(issuer)); @@ -525,7 +515,7 @@ EscrowCreate::doApply() { if (auto const ret = std::visit( [&](T const&) { - return escrowLockApplyHelper(ctx_.view(), issuer, accountID_, amount, j_); + return escrowLockApplyHelper(ctx_.view(), issuer, account_, amount, j_); }, amount.asset().value()); !isTesSuccess(ret)) @@ -541,9 +531,11 @@ EscrowCreate::doApply() } void -EscrowCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +EscrowCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -554,7 +546,6 @@ EscrowCreate::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index 4cda867b48..116466a1a3 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -30,6 +30,7 @@ #include #include +#include #include #include @@ -38,8 +39,8 @@ namespace xrpl { // During an EscrowFinish, the transaction must specify both // a condition and a fulfillment. We track whether that // fulfillment matches and validates the condition. -constexpr HashRouterFlags kSfCfInvalid = HashRouterFlags::PRIVATE5; -constexpr HashRouterFlags kSfCfValid = HashRouterFlags::PRIVATE6; +constexpr HashRouterFlags kSF_CF_INVALID = HashRouterFlags::PRIVATE5; +constexpr HashRouterFlags kSF_CF_VALID = HashRouterFlags::PRIVATE6; //------------------------------------------------------------------------------ @@ -97,15 +98,15 @@ EscrowFinish::preflightSigValidated(PreflightContext const& ctx) // If we haven't checked the condition, check it // now. Whether it passes or not isn't important // in preflight. - if (!any(flags & (kSfCfInvalid | kSfCfValid))) + if (!any(flags & (kSF_CF_INVALID | kSF_CF_VALID))) { if (checkCondition(*fb, *cb)) { - router.setFlags(id, kSfCfValid); + router.setFlags(id, kSF_CF_VALID); } else { - router.setFlags(id, kSfCfInvalid); + router.setFlags(id, kSF_CF_INVALID); } } } @@ -260,7 +261,7 @@ EscrowFinish::doApply() // It's unlikely that the results of the check will // expire from the hash router, but if it happens, // simply re-run the check. - if (cb && !any(flags & (kSfCfInvalid | kSfCfValid))) + if (cb && !any(flags & (kSF_CF_INVALID | kSF_CF_VALID))) { // LCOV_EXCL_START auto const fb = ctx_.tx[~sfFulfillment]; @@ -270,11 +271,11 @@ EscrowFinish::doApply() if (checkCondition(*fb, *cb)) { - flags = kSfCfValid; + flags = kSF_CF_VALID; } else { - flags = kSfCfInvalid; + flags = kSF_CF_INVALID; } ctx_.registry.get().getHashRouter().setFlags(id, flags); @@ -283,7 +284,7 @@ EscrowFinish::doApply() // If the check failed, then simply return an error // and don't look at anything else. - if (any(flags & kSfCfInvalid)) + if (any(flags & kSF_CF_INVALID)) return tecCRYPTOCONDITION_ERROR; // Check against condition in the ledger entry: @@ -309,8 +310,7 @@ EscrowFinish::doApply() if (!sled) return tecNO_DST; - if (auto err = - verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, destID, sled, ctx_.journal); + if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, destID, sled, ctx_.journal); !isTesSuccess(err)) return err; @@ -353,9 +353,9 @@ EscrowFinish::doApply() Rate lockedRate = slep->isFieldPresent(sfTransferRate) ? xrpl::Rate(slep->getFieldU32(sfTransferRate)) - : kParityRate; + : kPARITY_RATE; auto const issuer = amount.getIssuer(); - bool const createAsset = destID == accountID_; + bool const createAsset = destID == account_; if (auto const ret = std::visit( [&](T const&) { return escrowUnlockApplyHelper( @@ -400,9 +400,11 @@ EscrowFinish::doApply() } void -EscrowFinish::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +EscrowFinish::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -413,7 +415,6 @@ EscrowFinish::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 0e1a4b3a3d..14bc5f7a51 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include +#include #include #include @@ -48,7 +48,7 @@ LoanBrokerCoverClawback::preflight(PreflightContext const& ctx) if (!brokerID && !amount) return temINVALID; - if (brokerID && *brokerID == beast::kZero) + if (brokerID && *brokerID == beast::kZERO) return temINVALID; if (amount) @@ -58,7 +58,7 @@ LoanBrokerCoverClawback::preflight(PreflightContext const& ctx) return temBAD_AMOUNT; // Zero is OK, and indicates "take it all" (down to the minimum cover) - if (*amount < beast::kZero) + if (*amount < beast::kZERO) return temBAD_AMOUNT; // This should be redundant @@ -75,7 +75,7 @@ LoanBrokerCoverClawback::preflight(PreflightContext const& ctx) // broker's pseudo-account, but we don't know yet whether it is, so // use a generic placeholder name. auto const holder = amount->getIssuer(); - if (holder == account || holder == beast::kZero) + if (holder == account || holder == beast::kZERO) return temINVALID; } } @@ -160,34 +160,24 @@ Expected determineClawAmount( SLE const& sleBroker, Asset const& vaultAsset, - std::optional const& amount, - SLE::const_ref vaultSle, - Rules const& rules) + std::optional const& amount) { auto const maxClawAmount = [&]() { - auto const minRequiredCover = [&]() { - if (rules.enabled(fixCleanup3_2_0)) - { - return minimumBrokerCover( - sleBroker[sfDebtTotal], TenthBips32(sleBroker[sfCoverRateMinimum]), vaultSle); - } - - // Always round the minimum required up - NumberRoundModeGuard const mg(Number::RoundingMode::Upward); - return tenthBipsOfValue( - sleBroker[sfDebtTotal], TenthBips32(sleBroker[sfCoverRateMinimum])); - }(); + // Always round the minimum required up + NumberRoundModeGuard const mg1(Number::RoundingMode::Upward); + auto const minRequiredCover = + tenthBipsOfValue(sleBroker[sfDebtTotal], TenthBips32(sleBroker[sfCoverRateMinimum])); // The subtraction probably won't round, but round down if it does. - NumberRoundModeGuard const mg(Number::RoundingMode::Downward); + NumberRoundModeGuard const mg2(Number::RoundingMode::Downward); return sleBroker[sfCoverAvailable] - minRequiredCover; }(); - if (maxClawAmount <= beast::kZero) + if (maxClawAmount <= beast::kZERO) return Unexpected(tecINSUFFICIENT_FUNDS); // Use the vaultAsset here, because it will be the right type in all // circumstances. The amount may be an IOU indicating the pseudo-account's // asset, which is correct, but not what is needed here. - if (!amount || *amount == beast::kZero) + if (!amount || *amount == beast::kZERO) return STAmount{vaultAsset, maxClawAmount}; Number const magnitude{*amount}; if (magnitude > maxClawAmount) @@ -293,8 +283,7 @@ LoanBrokerCoverClawback::preclaim(PreclaimContext const& ctx) } } - auto const findClawAmount = - determineClawAmount(*sleBroker, vaultAsset, amount, vault, ctx.view.rules()); + auto const findClawAmount = determineClawAmount(*sleBroker, vaultAsset, amount); if (!findClawAmount) { JLOG(ctx.j.warn()) << "LoanBroker cover is already at minimum."; @@ -302,10 +291,6 @@ LoanBrokerCoverClawback::preclaim(PreclaimContext const& ctx) } STAmount const& clawAmount = *findClawAmount; - if (auto const ret = canApplyToBrokerCover( - ctx.view, sleBroker, vaultAsset, clawAmount, ctx.j, "LoanBrokerCoverClawback")) - return ret; - // Explicitly check the balance of the trust line / MPT to make sure the // balance is actually there. It should always match `sfCoverAvailable`, so // if there isn't, this is an internal error. @@ -356,8 +341,7 @@ LoanBrokerCoverClawback::doApply() auto const vaultAsset = vault->at(sfAsset); - auto const findClawAmount = - determineClawAmount(*sleBroker, vaultAsset, amount, vault, view().rules()); + auto const findClawAmount = determineClawAmount(*sleBroker, vaultAsset, amount); if (!findClawAmount) return tecINTERNAL; // LCOV_EXCL_LINE STAmount const& clawAmount = *findClawAmount; @@ -376,9 +360,11 @@ LoanBrokerCoverClawback::doApply() } void -LoanBrokerCoverClawback::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanBrokerCoverClawback::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -389,7 +375,6 @@ LoanBrokerCoverClawback::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp index 537996ba57..a8fa91b648 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp @@ -1,11 +1,9 @@ #include #include -#include #include #include #include -#include #include #include #include @@ -16,6 +14,8 @@ #include #include +#include + namespace xrpl { bool @@ -27,11 +27,11 @@ LoanBrokerCoverDeposit::checkExtraFeatures(PreflightContext const& ctx) NotTEC LoanBrokerCoverDeposit::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanBrokerID] == beast::kZero) + if (ctx.tx[sfLoanBrokerID] == beast::kZERO) return temINVALID; auto const dstAmount = ctx.tx[sfAmount]; - if (dstAmount <= beast::kZero) + if (dstAmount <= beast::kZERO) return temBAD_AMOUNT; if (!isLegalNet(dstAmount)) @@ -87,29 +87,6 @@ LoanBrokerCoverDeposit::preclaim(PreclaimContext const& ctx) if (auto const ret = requireAuth(ctx.view, vaultAsset, account, AuthType::StrongAuth)) return ret; - // Deposit must round the amount Downward to cover scale and then reuse that rounded - // value for the actual transfer in doApply — otherwise implicit round-to-nearest during - // `sfCoverAvailable +=` could credit the broker more than the depositor paid Computing it - // here in preclaim lets us reject sub-cover-scale dust early with tecPRECISION_LOSS instead of - // failing only in doApply. - bool const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0); - auto const roundedAmount = [&]() -> STAmount { - if (!fix320Enabled) - return tx[sfAmount]; - - return roundToScale( - tx[sfAmount], - scale(sleBroker->at(sfCoverAvailable), vaultAsset), - Number::RoundingMode::Downward); - }(); - - if (fix320Enabled && roundedAmount == beast::kZero) - { - JLOG(ctx.j.warn()) << "LoanBrokerCoverDeposit: deposit amount: " << tx[sfAmount] - << " is zero at loan broker scale"; - return tecPRECISION_LOSS; - } - if (accountHolds( ctx.view, account, @@ -117,7 +94,7 @@ LoanBrokerCoverDeposit::preclaim(PreclaimContext const& ctx) FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, ctx.j, - SpendableHandling::FullBalance) < roundedAmount) + SpendableHandling::FullBalance) < amount) return tecINSUFFICIENT_FUNDS; return tesSUCCESS; @@ -129,6 +106,8 @@ LoanBrokerCoverDeposit::doApply() auto const& tx = ctx_.tx; auto const brokerID = tx[sfLoanBrokerID]; + auto const amount = tx[sfAmount]; + auto broker = view().peek(keylet::loanbroker(brokerID)); if (!broker) return tecINTERNAL; // LCOV_EXCL_LINE @@ -138,35 +117,11 @@ LoanBrokerCoverDeposit::doApply() return tecINTERNAL; // LCOV_EXCL_LINE auto const vaultAsset = vault->at(sfAsset); + auto const brokerPseudoID = broker->at(sfAccount); - // Re-round here (matches preclaim) so the same cover-scale-quantized - // value drives both the trustline transfer and the cover increment; - // see the rationale comment in preclaim. - bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0); - auto const amount = [&]() -> STAmount { - if (!fix320Enabled) - return tx[sfAmount]; - - return roundToScale( - tx[sfAmount], - scale(broker->at(sfCoverAvailable), vaultAsset), - Number::RoundingMode::Downward); - }(); - - // We validated zero-amount in preclaim, if we ended up with zero now, fail hard. - if (amount == beast::kZero) - { - // LCOV_EXCL_START - JLOG(j_.error()) << "LoanBrokerCoverDeposit: deposit amount: " << tx[sfAmount] - << " is zero"; - return tecINTERNAL; - // LCOV_EXCL_STOP - } - // Transfer assets from depositor to pseudo-account. - if (auto ter = - accountSend(view(), accountID_, brokerPseudoID, amount, j_, WaiveTransferFee::Yes)) + if (auto ter = accountSend(view(), account_, brokerPseudoID, amount, j_, WaiveTransferFee::Yes)) return ter; // Increase the LoanBroker's CoverAvailable by Amount @@ -179,9 +134,11 @@ LoanBrokerCoverDeposit::doApply() } void -LoanBrokerCoverDeposit::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanBrokerCoverDeposit::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -192,7 +149,6 @@ LoanBrokerCoverDeposit::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index fea6f3b9cb..ca4136be0a 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -20,6 +19,8 @@ #include #include +#include + namespace xrpl { bool @@ -31,11 +32,11 @@ LoanBrokerCoverWithdraw::checkExtraFeatures(PreflightContext const& ctx) NotTEC LoanBrokerCoverWithdraw::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanBrokerID] == beast::kZero) + if (ctx.tx[sfLoanBrokerID] == beast::kZERO) return temINVALID; auto const dstAmount = ctx.tx[sfAmount]; - if (dstAmount <= beast::kZero) + if (dstAmount <= beast::kZERO) return temBAD_AMOUNT; if (!isLegalNet(dstAmount)) @@ -43,7 +44,7 @@ LoanBrokerCoverWithdraw::preflight(PreflightContext const& ctx) if (auto const destination = ctx.tx[~sfDestination]) { - if (*destination == beast::kZero) + if (*destination == beast::kZERO) { return temMALFORMED; } @@ -92,20 +93,10 @@ LoanBrokerCoverWithdraw::preclaim(PreclaimContext const& ctx) if (amount.asset() != vaultAsset) return tecWRONG_ASSET; - // Helper handles both IOU and MPT correctly without explicit branching. - if (auto const ret = canApplyToBrokerCover( - ctx.view, sleBroker, vaultAsset, amount, ctx.j, "LoanBrokerCoverWithdraw")) - return ret; - // The broker's pseudo-account is the source of funds. auto const pseudoAccountID = sleBroker->at(sfAccount); - // Post-fixCleanup3_2_0: cover withdraw is a recovery path that bypasses - // the lsfMPTCanTransfer flag check, so an issuer cannot trap a broker's - // first-loss capital. Other transferability checks (IOU NoRipple, freeze, - // requireAuth) still apply. - auto const waive = ctx.view.rules().enabled(fixCleanup3_2_0) ? WaiveMPTCanTransfer::Yes - : WaiveMPTCanTransfer::No; - if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct, waive)) + // Cannot transfer a non-transferable Asset + if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct)) return ret; // Withdrawal to a 3rd party destination account is essentially a transfer. @@ -140,12 +131,6 @@ LoanBrokerCoverWithdraw::preclaim(PreclaimContext const& ctx) // Cover Rate is in 1/10 bips units auto const currentDebtTotal = sleBroker->at(sfDebtTotal); auto const minimumCover = [&]() { - if (ctx.view.rules().enabled(fixCleanup3_2_0)) - { - return minimumBrokerCover( - currentDebtTotal, TenthBips32{sleBroker->at(sfCoverRateMinimum)}, vault); - } - // Always round the minimum required up. // Applies to `tenthBipsOfValue` as well as `roundToAsset`. NumberRoundModeGuard const mg(Number::RoundingMode::Upward); @@ -178,7 +163,7 @@ LoanBrokerCoverWithdraw::doApply() auto const brokerID = tx[sfLoanBrokerID]; auto const amount = tx[sfAmount]; - auto const dstAcct = tx[~sfDestination].value_or(accountID_); + auto const dstAcct = tx[~sfDestination].value_or(account_); auto broker = view().peek(keylet::loanbroker(brokerID)); if (!broker) @@ -198,13 +183,15 @@ LoanBrokerCoverWithdraw::doApply() associateAsset(*broker, vaultAsset); - return doWithdraw(view(), tx, accountID_, dstAcct, brokerPseudoID, preFeeBalance_, amount, j_); + return doWithdraw(view(), tx, account_, dstAcct, brokerPseudoID, preFeeBalance_, amount, j_); } void -LoanBrokerCoverWithdraw::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanBrokerCoverWithdraw::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -215,7 +202,6 @@ LoanBrokerCoverWithdraw::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp index f3c000bf0b..0d6d6e6cd6 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -18,6 +17,8 @@ #include #include +#include + namespace xrpl { bool @@ -29,7 +30,7 @@ LoanBrokerDelete::checkExtraFeatures(PreflightContext const& ctx) NotTEC LoanBrokerDelete::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanBrokerID] == beast::kZero) + if (ctx.tx[sfLoanBrokerID] == beast::kZERO) return temINVALID; return tesSUCCESS; @@ -74,7 +75,7 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx) Asset const asset = vault->at(sfAsset); - if (auto const debtTotal = sleBroker->at(sfDebtTotal); debtTotal != beast::kZero) + if (auto const debtTotal = sleBroker->at(sfDebtTotal); debtTotal != beast::kZERO) { // Any remaining debt should have been wiped out by the last Loan // Delete. This check is purely defensive. @@ -83,7 +84,7 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx) auto const rounded = roundToAsset(asset, debtTotal, scale, Number::RoundingMode::TowardsZero); - if (rounded != beast::kZero) + if (rounded != beast::kZERO) { // LCOV_EXCL_START JLOG(ctx.j.warn()) << "LoanBrokerDelete: Debt total is " << debtTotal @@ -96,7 +97,7 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx) auto const coverAvailable = STAmount{asset, sleBroker->at(sfCoverAvailable)}; // If there are assets in the cover, broker will receive them on deletion. // So we need to check if the broker owner is deep frozen for that asset. - if (coverAvailable > beast::kZero) + if (coverAvailable > beast::kZERO) { if (auto const ret = checkDeepFrozen(ctx.view, brokerOwner, asset)) { @@ -105,19 +106,6 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx) } } - if (ctx.view.rules().enabled(fixCleanup3_2_0)) - { - if (coverAvailable > beast::kZero) - { - auto const brokerPseudo = sleBroker->at(sfAccount); - if (auto const ret = checkFrozen(ctx.view, brokerPseudo, asset)) - { - JLOG(ctx.j.warn()) << "Broker pseudo-account is frozen/locked."; - return ret; - } - } - } - return tesSUCCESS; } @@ -142,7 +130,7 @@ LoanBrokerDelete::doApply() auto const brokerPseudoID = broker->at(sfAccount); if (!view().dirRemove( - keylet::ownerDir(accountID_), broker->at(sfOwnerNode), broker->key(), false)) + keylet::ownerDir(account_), broker->at(sfOwnerNode), broker->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } @@ -155,7 +143,7 @@ LoanBrokerDelete::doApply() { auto const coverAvailable = STAmount{vaultAsset, broker->at(sfCoverAvailable)}; if (auto const ter = accountSend( - view(), brokerPseudoID, accountID_, coverAvailable, j_, WaiveTransferFee::Yes)) + view(), brokerPseudoID, account_, coverAvailable, j_, WaiveTransferFee::Yes)) return ter; } @@ -189,7 +177,7 @@ LoanBrokerDelete::doApply() view().erase(broker); { - auto owner = view().peek(keylet::account(accountID_)); + auto owner = view().peek(keylet::account(account_)); if (!owner) return tefBAD_LEDGER; // LCOV_EXCL_LINE @@ -204,9 +192,11 @@ LoanBrokerDelete::doApply() } void -LoanBrokerDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanBrokerDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -217,7 +207,6 @@ LoanBrokerDelete::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp index 2dc003eb7f..bf00a344a7 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp @@ -38,15 +38,15 @@ LoanBrokerSet::preflight(PreflightContext const& ctx) auto const& tx = ctx.tx; if (auto const data = tx[~sfData]; - data && !data->empty() && !validDataLength(tx[~sfData], kMaxDataPayloadLength)) + data && !data->empty() && !validDataLength(tx[~sfData], kMAX_DATA_PAYLOAD_LENGTH)) return temINVALID; - if (!validNumericRange(tx[~sfManagementFeeRate], kMaxManagementFeeRate)) + if (!validNumericRange(tx[~sfManagementFeeRate], kMAX_MANAGEMENT_FEE_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfCoverRateMinimum], kMaxCoverRate)) + if (!validNumericRange(tx[~sfCoverRateMinimum], kMAX_COVER_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfCoverRateLiquidation], kMaxCoverRate)) + if (!validNumericRange(tx[~sfCoverRateLiquidation], kMAX_COVER_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfDebtMaximum], Number(kMaxMpTokenAmount), Number(0))) + if (!validNumericRange(tx[~sfDebtMaximum], Number(kMAX_MP_TOKEN_AMOUNT), Number(0))) return temINVALID; if (tx.isFieldPresent(sfLoanBrokerID)) @@ -57,13 +57,13 @@ LoanBrokerSet::preflight(PreflightContext const& ctx) tx.isFieldPresent(sfCoverRateLiquidation)) return temINVALID; - if (tx[sfLoanBrokerID] == beast::kZero) + if (tx[sfLoanBrokerID] == beast::kZERO) return temINVALID; } if (auto const vaultID = tx.at(~sfVaultID)) { - if (*vaultID == beast::kZero) + if (*vaultID == beast::kZERO) return temINVALID; } @@ -83,9 +83,9 @@ LoanBrokerSet::preflight(PreflightContext const& ctx) std::vector> const& LoanBrokerSet::getValueFields() { - static std::vector> const kValueFields{~sfDebtMaximum}; + static std::vector> const kVALUE_FIELDS{~sfDebtMaximum}; - return kValueFields; + return kVALUE_FIELDS; } TER @@ -220,7 +220,7 @@ LoanBrokerSet::doApply() auto const vaultAsset = sleVault->at(sfAsset); auto const sequence = tx.getSeqValue(); - auto owner = view.peek(keylet::account(accountID_)); + auto owner = view.peek(keylet::account(account_)); if (!owner) { // This should be impossible @@ -229,9 +229,9 @@ LoanBrokerSet::doApply() return tefBAD_LEDGER; // LCOV_EXCL_STOP } - auto broker = std::make_shared(keylet::loanbroker(accountID_, sequence)); + auto broker = std::make_shared(keylet::loanbroker(account_, sequence)); - if (auto const ter = dirLink(view, accountID_, broker)) + if (auto const ter = dirLink(view, account_, broker)) return ter; // LCOV_EXCL_LINE if (auto const ter = dirLink(view, vaultPseudoID, broker, sfVaultNode)) return ter; // LCOV_EXCL_LINE @@ -255,7 +255,7 @@ LoanBrokerSet::doApply() // Initialize data fields: broker->at(sfSequence) = sequence; broker->at(sfVaultID) = vaultID; - broker->at(sfOwner) = accountID_; + broker->at(sfOwner) = account_; broker->at(sfAccount) = pseudoId; // The LoanSequence indexes loans created by this broker, starting at 1 broker->at(sfLoanSequence) = 1; @@ -279,9 +279,11 @@ LoanBrokerSet::doApply() } void -LoanBrokerSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanBrokerSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -292,7 +294,6 @@ LoanBrokerSet::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp index d4ec92a9fb..ff33bfb9fb 100644 --- a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp @@ -16,6 +16,8 @@ #include #include +#include + namespace xrpl { bool @@ -27,7 +29,7 @@ LoanDelete::checkExtraFeatures(PreflightContext const& ctx) NotTEC LoanDelete::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanID] == beast::kZero) + if (ctx.tx[sfLoanID] == beast::kZERO) return temINVALID; return tesSUCCESS; @@ -115,14 +117,14 @@ LoanDelete::doApply() if (brokerSle->at(sfOwnerCount) == 0) { auto debtTotalProxy = brokerSle->at(sfDebtTotal); - if (*debtTotalProxy != beast::kZero) + if (*debtTotalProxy != beast::kZERO) { XRPL_ASSERT_PARTS( roundToAsset( vaultSle->at(sfAsset), debtTotalProxy, getAssetsTotalScale(vaultSle), - Number::RoundingMode::TowardsZero) == beast::kZero, + Number::RoundingMode::TowardsZero) == beast::kZERO, "xrpl::LoanDelete::doApply", "last loan, remaining debt rounds to zero"); debtTotalProxy = 0; @@ -140,15 +142,16 @@ LoanDelete::doApply() } void -LoanDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool LoanDelete::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index 2b5c9d25f6..d1cd5de505 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -26,6 +26,8 @@ #include #include +#include + namespace xrpl { bool @@ -43,7 +45,7 @@ LoanManage::getFlagsMask(PreflightContext const& ctx) NotTEC LoanManage::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanID] == beast::kZero) + if (ctx.tx[sfLoanID] == beast::kZERO) return temINVALID; // Flags are mutually exclusive @@ -422,7 +424,7 @@ LoanManage::doApply() // Pre-amendment, associateAsset was only called on the noop (no flags) // path. Post-amendment, we call associateAsset on all successful paths. - if (view.rules().enabled(fixCleanup3_1_3) && isTesSuccess(result)) + if (view.rules().enabled(fixSecurity3_1_3) && isTesSuccess(result)) { associateAsset(*loanSle, vaultAsset); associateAsset(*brokerSle, vaultAsset); @@ -433,15 +435,16 @@ LoanManage::doApply() } void -LoanManage::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanManage::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool LoanManage::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index a0a1479bdb..b8d73bfd65 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include namespace xrpl { @@ -48,10 +48,10 @@ LoanPay::getFlagsMask(PreflightContext const& ctx) NotTEC LoanPay::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfLoanID] == beast::kZero) + if (ctx.tx[sfLoanID] == beast::kZERO) return temINVALID; - if (ctx.tx[sfAmount] <= beast::kZero) + if (ctx.tx[sfAmount] <= beast::kZERO) return temBAD_AMOUNT; // The loan payment flags are all mutually exclusive. If more than one is @@ -96,9 +96,9 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) return normalCost; } - if (loanSle->at(sfPaymentRemaining) <= kLoanPaymentsPerFeeIncrement) + if (loanSle->at(sfPaymentRemaining) <= kLOAN_PAYMENTS_PER_FEE_INCREMENT) { - // If there are fewer than kLoanPaymentsPerFeeIncrement payments left to + // If there are fewer than loanPaymentsPerFeeIncrement payments left to // pay, we can skip the computations. return normalCost; } @@ -141,36 +141,14 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) NumberRoundModeGuard const mg( tx.isFlag(tfLoanOverpayment) ? Number::RoundingMode::Upward : Number::RoundingMode::Downward); - - static_assert(kLoanMaximumPaymentsPerTransaction % kLoanPaymentsPerFeeIncrement == 0); - static constexpr std::int64_t kMaxFeeIncrements = - kLoanMaximumPaymentsPerTransaction / kLoanPaymentsPerFeeIncrement; - - if (view.rules().enabled(fixCleanup3_1_3) && - amount >= regularPayment * kLoanMaximumPaymentsPerTransaction) - { - // The payment handler will never process more than - // loanMaximumPaymentsPerTransaction payments (including overpayments), - // and one fee increment is charged for every - // loanPaymentsPerFeeIncrement, so don't charge more than - // loanMaximumPaymentsPerTransaction / loanPaymentsPerFeeIncrement fee - // increments. - return kMaxFeeIncrements * normalCost; - } - // Estimate how many payments will be made Number const numPaymentEstimate = static_cast(amount / regularPayment); // Charge one base fee per paymentsPerFeeIncrement payments, rounding up. - // This set round is safe because there's a mode guard just above Number::setround(Number::RoundingMode::Upward); auto const feeIncrements = std::max( std::int64_t(1), - static_cast(numPaymentEstimate / kLoanPaymentsPerFeeIncrement)); - XRPL_ASSERT( - !view.rules().enabled(fixCleanup3_1_3) || feeIncrements <= kMaxFeeIncrements, - "xrpl::LoanPay::calculateBaseFee : number of fee increments is in " - "range"); + static_cast(numPaymentEstimate / kLOAN_PAYMENTS_PER_FEE_INCREMENT)); return feeIncrements * normalCost; } @@ -200,7 +178,7 @@ LoanPay::preclaim(PreclaimContext const& ctx) if (tx.isFlag(tfLoanOverpayment) && !loanSle->isFlag(lsfLoanOverpayment)) { JLOG(ctx.j.warn()) << "Requested overpayment on a loan that doesn't allow it"; - return ctx.view.rules().enabled(fixCleanup3_1_3) ? TER{tecNO_PERMISSION} : temINVALID_FLAG; + return ctx.view.rules().enabled(fixSecurity3_1_3) ? TER{tecNO_PERMISSION} : temINVALID_FLAG; } auto const principalOutstanding = loanSle->at(sfPrincipalOutstanding); @@ -310,8 +288,6 @@ LoanPay::doApply() TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)}; auto debtTotalProxy = brokerSle->at(sfDebtTotal); - auto const vaultScale = getAssetsTotalScale(vaultSle); - // Send the broker fee to the owner if they have sufficient cover available, // _and_ if the owner can receive funds // _and_ if the broker is authorized to hold funds. If not, so as not to @@ -321,22 +297,14 @@ LoanPay::doApply() // Normally freeze status is checked in preclaim, but we do it here to // avoid duplicating the check. It'll claim a fee either way. bool const sendBrokerFeeToOwner = [&]() { - // In the fixCleanup3_2_0 path, vault-related values (for example, - // DebtTotal) use vaultScale. The legacy path below intentionally retains - // its pre-amendment loanScale behavior. - auto const minCover = [&]() { - if (view.rules().enabled(fixCleanup3_2_0)) - { - return minimumBrokerCover(debtTotalProxy.value(), coverRateMinimum, vaultSle); - } - // Round the minimum required cover up to be conservative. This ensures - // CoverAvailable never drops below the theoretical minimum, protecting - // the broker's solvency. - NumberRoundModeGuard const mg(Number::RoundingMode::Upward); - return roundToAsset( - asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale); - }(); - return coverAvailableProxy >= minCover && !isDeepFrozen(view, brokerOwner, asset) && + // Round the minimum required cover up to be conservative. This ensures + // CoverAvailable never drops below the theoretical minimum, protecting + // the broker's solvency. + NumberRoundModeGuard const mg(Number::RoundingMode::Upward); + return coverAvailableProxy >= + roundToAsset( + asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale) && + !isDeepFrozen(view, brokerOwner, asset) && !requireAuth(view, asset, brokerOwner, AuthType::StrongAuth); }(); @@ -432,6 +400,10 @@ LoanPay::doApply() auto assetsAvailableProxy = vaultSle->at(sfAssetsAvailable); auto assetsTotalProxy = vaultSle->at(sfAssetsTotal); + // The vault may be at a different scale than the loan. Reduce rounding + // errors during the payment by rounding some of the values to that scale. + auto const vaultScale = getAssetsTotalScale(vaultSle); + auto const totalPaidToVaultRaw = paymentParts->principalPaid + paymentParts->interestPaid; auto const totalPaidToVaultRounded = roundToAsset(asset, totalPaidToVaultRaw, vaultScale, Number::RoundingMode::Downward); @@ -470,10 +442,9 @@ LoanPay::doApply() // Vault object state changes view.update(vaultSle); - Number const assetsAvailableBefore = *assetsAvailableProxy; - Number const assetsTotalBefore = *assetsTotalProxy; #if !NDEBUG { + Number const assetsAvailableBefore = *assetsAvailableProxy; Number const pseudoAccountBalanceBefore = accountHolds( view, vaultPseudoAccount, @@ -497,6 +468,16 @@ LoanPay::doApply() "xrpl::LoanPay::doApply", "assets available must not be greater than assets outstanding"); + if (*assetsAvailableProxy > *assetsTotalProxy) + { + // LCOV_EXCL_START + JLOG(j_.fatal()) << "Vault assets available must not be greater " + "than assets outstanding. Available: " + << *assetsAvailableProxy << ", Total: " << *assetsTotalProxy; + return tecINTERNAL; + // LCOV_EXCL_STOP + } + JLOG(j_.debug()) << "total paid to vault raw: " << totalPaidToVaultRaw << ", total paid to vault rounded: " << totalPaidToVaultRounded << ", total paid to broker: " << totalPaidToBroker @@ -522,77 +503,21 @@ LoanPay::doApply() associateAsset(*vaultSle, asset); // Duplicate some checks after rounding - Number const assetsAvailableAfter = *assetsAvailableProxy; - Number const assetsTotalAfter = *assetsTotalProxy; - XRPL_ASSERT_PARTS( - assetsAvailableAfter <= assetsTotalAfter, + *assetsAvailableProxy <= *assetsTotalProxy, "xrpl::LoanPay::doApply", "assets available must not be greater than assets outstanding"); - if (assetsAvailableAfter == assetsAvailableBefore) - { - // An unchanged assetsAvailable indicates that the amount paid to the - // vault was zero, or rounded to zero. That should be impossible, but I - // can't rule it out for extreme edge cases, so fail gracefully if it - // happens. - // - // LCOV_EXCL_START - JLOG(j_.warn()) << "LoanPay: Vault assets available unchanged after rounding: " // - << "Before: " << assetsAvailableBefore // - << ", After: " << assetsAvailableAfter; - return tecPRECISION_LOSS; - // LCOV_EXCL_STOP - } - if (paymentParts->valueChange != beast::kZero && assetsTotalAfter == assetsTotalBefore) - { - // Non-zero valueChange with an unchanged assetsTotal indicates that the - // actual value change rounded to zero. That should be impossible, but I - // can't rule it out for extreme edge cases, so fail gracefully if it - // happens. - // - // LCOV_EXCL_START - JLOG(j_.warn()) - << "LoanPay: Vault assets expected change, but unchanged after rounding: " // - << "Before: " << assetsTotalBefore // - << ", After: " << assetsTotalAfter // - << ", ValueChange: " << paymentParts->valueChange; - return tecPRECISION_LOSS; - // LCOV_EXCL_STOP - } - if (paymentParts->valueChange == beast::kZero && assetsTotalAfter != assetsTotalBefore) - { - // A change in assetsTotal when there was no valueChange indicates that - // something really weird happened. That should be flat out impossible. - // - // LCOV_EXCL_START - JLOG(j_.fatal()) << "LoanPay: Vault assets changed unexpectedly after rounding: " // - << "Before: " << assetsTotalBefore // - << ", After: " << assetsTotalAfter // - << ", ValueChange: " << paymentParts->valueChange; - return tecINTERNAL; - // LCOV_EXCL_STOP - } - if (assetsAvailableAfter > assetsTotalAfter) - { - // Assets available are not allowed to be larger than assets total. - // LCOV_EXCL_START - JLOG(j_.fatal()) << "LoanPay: Vault assets available must not be greater " - "than assets outstanding. Available: " - << assetsAvailableAfter << ", Total: " << assetsTotalAfter; - return tecINTERNAL; - // LCOV_EXCL_STOP - } - // These three values are used to check that funds are conserved after the transfers +#if !NDEBUG auto const accountBalanceBefore = accountHolds( view, - accountID_, + account_, asset, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const vaultBalanceBefore = accountID_ == vaultPseudoAccount + auto const vaultBalanceBefore = account_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( view, @@ -602,26 +527,26 @@ LoanPay::doApply() AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const brokerBalanceBefore = accountID_ == brokerPayee - ? STAmount{asset, 0} - : accountHolds( - view, - brokerPayee, - asset, - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_, - SpendableHandling::FullBalance); + auto const brokerBalanceBefore = account_ == brokerPayee ? STAmount{asset, 0} + : accountHolds( + view, + brokerPayee, + asset, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_, + SpendableHandling::FullBalance); +#endif - if (totalPaidToVaultRounded != beast::kZero) + if (totalPaidToVaultRounded != beast::kZERO) { if (auto const ter = requireAuth(view, asset, vaultPseudoAccount, AuthType::StrongAuth)) return ter; } - if (totalPaidToBroker != beast::kZero) + if (totalPaidToBroker != beast::kZERO) { - if (brokerPayee == accountID_) + if (brokerPayee == account_) { // The broker may have deleted their holding. Recreate it if needed if (auto const ter = addEmptyHolding( @@ -639,7 +564,7 @@ LoanPay::doApply() if (auto const ter = accountSendMulti( view, - accountID_, + account_, asset, {{vaultPseudoAccount, totalPaidToVaultRounded}, {brokerPayee, totalPaidToBroker}}, j_, @@ -647,31 +572,28 @@ LoanPay::doApply() return ter; #if !NDEBUG - { - Number const pseudoAccountBalanceAfter = accountHolds( - view, - vaultPseudoAccount, - asset, - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_); - XRPL_ASSERT_PARTS( - assetsAvailableAfter == pseudoAccountBalanceAfter, - "xrpl::LoanPay::doApply", - "vault pseudo balance agrees after"); - } -#endif + Number const assetsAvailableAfter = *assetsAvailableProxy; + Number const pseudoAccountBalanceAfter = accountHolds( + view, + vaultPseudoAccount, + asset, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_); + XRPL_ASSERT_PARTS( + assetsAvailableAfter == pseudoAccountBalanceAfter, + "xrpl::LoanPay::doApply", + "vault pseudo balance agrees after"); - // Check that funds are conserved auto const accountBalanceAfter = accountHolds( view, - accountID_, + account_, asset, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const vaultBalanceAfter = accountID_ == vaultPseudoAccount + auto const vaultBalanceAfter = account_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( view, @@ -681,136 +603,29 @@ LoanPay::doApply() AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const brokerBalanceAfter = accountID_ == brokerPayee ? STAmount{asset, 0} - : accountHolds( - view, - brokerPayee, - asset, - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_, - SpendableHandling::FullBalance); - auto const balanceScale = [&]() { - // Find a reasonable scale to use for the balance comparisons. - // - // First find the minimum and maximum exponent of all the non-zero balances, before and - // after. If min and max are equal, use that value. If they are not, use "max + 1" to reduce - // rounding discrepancies without making the result meaningless. Cap the scale at - // STAmount::kMaxOffset, just in case the numbers are all very large. - std::vector exponents; - exponents.reserve(6); + auto const brokerBalanceAfter = account_ == brokerPayee ? STAmount{asset, 0} + : accountHolds( + view, + brokerPayee, + asset, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_, + SpendableHandling::FullBalance); - for (auto const& a : { - accountBalanceBefore, - vaultBalanceBefore, - brokerBalanceBefore, - accountBalanceAfter, - vaultBalanceAfter, - brokerBalanceAfter, - }) - { - // Exclude zeroes - if (a != beast::kZero) - exponents.push_back(a.exponent()); - } - if (exponents.empty()) - { - UNREACHABLE("xrpl::LoanPay::doApply : all zeroes"); - return 0; - } - auto const [minItr, maxItr] = std::ranges::minmax_element(exponents); - auto const min = *minItr; - auto const max = *maxItr; - JLOG(j_.trace()) << "Min scale: " << min << ", max scale: " << max; - // IOU rounding can be interesting. We want all the balance checks to agree, but don't want - // to round to such an extreme that it becomes meaningless. e.g. Everything rounds to one - // digit. So add 1 to the max (reducing the number of digits after the decimal point by 1) - // if the scales are not already all the same. - return std::min(min == max ? max : max + 1, STAmount::kMaxOffset); - }(); - - // No object changes are made below this point XRPL_ASSERT_PARTS( - Number::getround() == Number::RoundingMode::ToNearest, + accountBalanceBefore + vaultBalanceBefore + brokerBalanceBefore == + accountBalanceAfter + vaultBalanceAfter + brokerBalanceAfter, "xrpl::LoanPay::doApply", - "Number rounding ToNearest"); - NumberRoundModeGuard const mg(Number::RoundingMode::ToNearest); - - auto const accountBalanceBeforeRounded = roundToScale(accountBalanceBefore, balanceScale); - auto const vaultBalanceBeforeRounded = roundToScale(vaultBalanceBefore, balanceScale); - auto const brokerBalanceBeforeRounded = roundToScale(brokerBalanceBefore, balanceScale); - - auto const totalBalanceBefore = accountBalanceBefore + vaultBalanceBefore + brokerBalanceBefore; - auto const totalBalanceBeforeRounded = roundToScale(totalBalanceBefore, balanceScale); - - JLOG(j_.trace()) << "Before: " // - << "account " << Number(accountBalanceBeforeRounded) << " (" - << Number(accountBalanceBefore) << ")" - << ", vault " << Number(vaultBalanceBeforeRounded) << " (" - << Number(vaultBalanceBefore) << ")" - << ", broker " << Number(brokerBalanceBeforeRounded) << " (" - << Number(brokerBalanceBefore) << ")" - << ", total " << Number(totalBalanceBeforeRounded) << " (" - << Number(totalBalanceBefore) << ")"; - - auto const accountBalanceAfterRounded = roundToScale(accountBalanceAfter, balanceScale); - auto const vaultBalanceAfterRounded = roundToScale(vaultBalanceAfter, balanceScale); - auto const brokerBalanceAfterRounded = roundToScale(brokerBalanceAfter, balanceScale); - - auto const totalBalanceAfter = accountBalanceAfter + vaultBalanceAfter + brokerBalanceAfter; - auto const totalBalanceAfterRounded = roundToScale(totalBalanceAfter, balanceScale); - - JLOG(j_.trace()) << "After: " // - << "account " << Number(accountBalanceAfterRounded) << " (" - << Number(accountBalanceAfter) << ")" - << ", vault " << Number(vaultBalanceAfterRounded) << " (" - << Number(vaultBalanceAfter) << ")" - << ", broker " << Number(brokerBalanceAfterRounded) << " (" - << Number(brokerBalanceAfter) << ")" - << ", total " << Number(totalBalanceAfterRounded) << " (" - << Number(totalBalanceAfter) << ")"; - - auto const accountBalanceChange = accountBalanceAfter - accountBalanceBefore; - auto const vaultBalanceChange = vaultBalanceAfter - vaultBalanceBefore; - auto const brokerBalanceChange = brokerBalanceAfter - brokerBalanceBefore; - - auto const totalBalanceChange = accountBalanceChange + vaultBalanceChange + brokerBalanceChange; - auto const totalBalanceChangeRounded = roundToScale(totalBalanceChange, balanceScale); - - JLOG(j_.trace()) << "Changes: " // - << "account " << to_string(accountBalanceChange) // - << ", vault " << to_string(vaultBalanceChange) // - << ", broker " << to_string(brokerBalanceChange) // - << ", total " << to_string(totalBalanceChangeRounded) << " (" - << Number(totalBalanceChange) << ")"; - - bool const goodRounding = totalBalanceBeforeRounded == totalBalanceAfterRounded || - totalBalanceChangeRounded == beast::kZero; - if (totalBalanceBeforeRounded != totalBalanceAfterRounded) - { - JLOG((goodRounding ? j_.debug() : j_.warn())) - << "Total rounded balances don't match" - << (totalBalanceChangeRounded == beast::kZero ? ", but total changes do" : ""); - } - if (totalBalanceChangeRounded != beast::kZero) - { - JLOG((goodRounding ? j_.debug() : j_.warn())) - << "Total balance changes don't match" - << (totalBalanceBeforeRounded == totalBalanceAfterRounded ? ", but total balances do" - : ""); - } - - // Rounding for IOUs can be weird, so check a few different ways to show - // that funds are conserved. + "funds are conserved (with rounding)"); XRPL_ASSERT_PARTS( - goodRounding, "xrpl::LoanPay::doApply", "funds are conserved (with rounding)"); - + accountBalanceAfter >= beast::kZERO, "xrpl::LoanPay::doApply", "positive account balance"); XRPL_ASSERT_PARTS( - accountBalanceAfter < accountBalanceBefore || accountID_ == asset.getIssuer(), + accountBalanceAfter < accountBalanceBefore || account_ == asset.getIssuer(), "xrpl::LoanPay::doApply", "account balance decreased"); XRPL_ASSERT_PARTS( - vaultBalanceAfter >= beast::kZero && brokerBalanceAfter >= beast::kZero, + vaultBalanceAfter >= beast::kZERO && brokerBalanceAfter >= beast::kZERO, "xrpl::LoanPay::doApply", "positive vault and broker balances"); XRPL_ASSERT_PARTS( @@ -825,20 +640,22 @@ LoanPay::doApply() vaultBalanceAfter > vaultBalanceBefore || brokerBalanceAfter > brokerBalanceBefore, "xrpl::LoanPay::doApply", "vault and/or broker balance increased"); +#endif return tesSUCCESS; } void -LoanPay::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanPay::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool LoanPay::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index 573f700f51..9503eeef03 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -85,7 +85,7 @@ LoanSet::preflight(PreflightContext const& ctx) } if (auto const data = tx[~sfData]; - data && !data->empty() && !validDataLength(tx[~sfData], kMaxDataPayloadLength)) + data && !data->empty() && !validDataLength(tx[~sfData], kMAX_DATA_PAYLOAD_LENGTH)) return temINVALID; for (auto const& field : {&sfLoanServiceFee, &sfLatePaymentFee, &sfClosePaymentFee}) { @@ -98,27 +98,27 @@ LoanSet::preflight(PreflightContext const& ctx) return temINVALID; if (!validNumericRange(tx[~sfLoanOriginationFee], p)) return temINVALID; - if (!validNumericRange(tx[~sfInterestRate], kMaxInterestRate)) + if (!validNumericRange(tx[~sfInterestRate], kMAX_INTEREST_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfOverpaymentFee], kMaxOverpaymentFee)) + if (!validNumericRange(tx[~sfOverpaymentFee], kMAX_OVERPAYMENT_FEE)) return temINVALID; - if (!validNumericRange(tx[~sfLateInterestRate], kMaxLateInterestRate)) + if (!validNumericRange(tx[~sfLateInterestRate], kMAX_LATE_INTEREST_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfCloseInterestRate], kMaxCloseInterestRate)) + if (!validNumericRange(tx[~sfCloseInterestRate], kMAX_CLOSE_INTEREST_RATE)) return temINVALID; - if (!validNumericRange(tx[~sfOverpaymentInterestRate], kMaxOverpaymentInterestRate)) + if (!validNumericRange(tx[~sfOverpaymentInterestRate], kMAX_OVERPAYMENT_INTEREST_RATE)) return temINVALID; if (auto const paymentTotal = tx[~sfPaymentTotal]; paymentTotal && *paymentTotal <= 0) return temINVALID; auto const paymentInterval = tx[~sfPaymentInterval]; - if (!validNumericMinimum(paymentInterval, LoanSet::kMinPaymentInterval)) + if (!validNumericMinimum(paymentInterval, LoanSet::kMIN_PAYMENT_INTERVAL)) return temINVALID; // Grace period is between min default value and payment interval if (auto const gracePeriod = tx[~sfGracePeriod]; !validNumericRange( gracePeriod, - paymentInterval.value_or(LoanSet::kDefaultPaymentInterval), - kDefaultGracePeriod)) + paymentInterval.value_or(LoanSet::kDEFAULT_PAYMENT_INTERVAL), + kDEFAULT_GRACE_PERIOD)) { return temINVALID; } @@ -131,7 +131,7 @@ LoanSet::preflight(PreflightContext const& ctx) return *ret; } - if (auto const brokerID = ctx.tx[~sfLoanBrokerID]; brokerID && *brokerID == beast::kZero) + if (auto const brokerID = ctx.tx[~sfLoanBrokerID]; brokerID && *brokerID == beast::kZERO) return temINVALID; return tesSUCCESS; @@ -195,7 +195,7 @@ LoanSet::calculateBaseFee(ReadView const& view, STTx const& tx) std::vector> const& LoanSet::getValueFields() { - static std::vector> const kValueFields{ + static std::vector> const kVALUE_FIELDS{ ~sfPrincipalRequested, ~sfLoanOriginationFee, ~sfLoanServiceFee, @@ -204,7 +204,7 @@ LoanSet::getValueFields() // Overpayment fee is really a rate. Don't check it here. }; - return kValueFields; + return kVALUE_FIELDS; } static std::uint32_t @@ -226,14 +226,14 @@ LoanSet::preclaim(PreclaimContext const& ctx) // overflows, and we kill the transaction. using timeType = decltype(sfNextPaymentDueDate)::type::value_type; static_assert(std::is_same_v); - constexpr timeType kMaxTime = std::numeric_limits::max(); - static_assert(kMaxTime == 4'294'967'295); + timeType constexpr kMAX_TIME = std::numeric_limits::max(); + static_assert(kMAX_TIME == 4'294'967'295); - auto const timeAvailable = kMaxTime - getStartDate(ctx.view); + auto const timeAvailable = kMAX_TIME - getStartDate(ctx.view); - auto const interval = ctx.tx.at(~sfPaymentInterval).value_or(kDefaultPaymentInterval); - auto const total = ctx.tx.at(~sfPaymentTotal).value_or(kDefaultPaymentTotal); - auto const grace = ctx.tx.at(~sfGracePeriod).value_or(kDefaultGracePeriod); + auto const interval = ctx.tx.at(~sfPaymentInterval).value_or(kDEFAULT_PAYMENT_INTERVAL); + auto const total = ctx.tx.at(~sfPaymentTotal).value_or(kDEFAULT_PAYMENT_TOTAL); + auto const grace = ctx.tx.at(~sfGracePeriod).value_or(kDEFAULT_GRACE_PERIOD); // The grace period can't be larger than the interval. Check it first, // mostly so that unit tests can test that specific case. @@ -388,7 +388,7 @@ LoanSet::doApply() Asset const vaultAsset = vaultSle->at(sfAsset); auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner); - auto const borrower = counterparty == brokerOwner ? accountID_ : counterparty; + auto const borrower = counterparty == brokerOwner ? account_ : counterparty; auto const borrowerSle = view.peek(keylet::account(borrower)); if (!borrowerSle) { @@ -414,11 +414,10 @@ LoanSet::doApply() TenthBips32 const interestRate{tx[~sfInterestRate].value_or(0)}; - auto const paymentInterval = tx[~sfPaymentInterval].value_or(kDefaultPaymentInterval); - auto const paymentTotal = tx[~sfPaymentTotal].value_or(kDefaultPaymentTotal); + auto const paymentInterval = tx[~sfPaymentInterval].value_or(kDEFAULT_PAYMENT_INTERVAL); + auto const paymentTotal = tx[~sfPaymentTotal].value_or(kDEFAULT_PAYMENT_TOTAL); auto const properties = computeLoanProperties( - view.rules(), vaultAsset, principalRequested, interestRate, @@ -460,7 +459,7 @@ LoanSet::doApply() if (auto const ret = checkLoanGuards( vaultAsset, principalRequested, - interestRate != beast::kZero, + interestRate != beast::kZERO, paymentTotal, properties, j_)) @@ -493,19 +492,11 @@ LoanSet::doApply() } TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)}; { - auto const minCover = [&]() { - if (ctx_.view().rules().enabled(fixCleanup3_2_0)) - { - return minimumBrokerCover(newDebtTotal, coverRateMinimum, vaultSle); - } - - // Round the minimum required cover up to be conservative. This ensures - // CoverAvailable never drops below the theoretical minimum, protecting - // the broker's solvency. - NumberRoundModeGuard const mg(Number::RoundingMode::Upward); - return tenthBipsOfValue(newDebtTotal, coverRateMinimum); - }(); - if (brokerSle->at(sfCoverAvailable) < minCover) + // Round the minimum required cover up to be conservative. This ensures + // CoverAvailable never drops below the theoretical minimum, protecting + // the broker's solvency. + NumberRoundModeGuard const mg(Number::RoundingMode::Upward); + if (brokerSle->at(sfCoverAvailable) < tenthBipsOfValue(newDebtTotal, coverRateMinimum)) { JLOG(j_.warn()) << "Insufficient first-loss capital to cover the loan."; return tecINSUFFICIENT_FUNDS; @@ -516,7 +507,7 @@ LoanSet::doApply() { auto const ownerCount = borrowerSle->at(sfOwnerCount); auto const balance = - accountID_ == borrower ? preFeeBalance_ : borrowerSle->at(sfBalance).value().xrp(); + account_ == borrower ? preFeeBalance_ : borrowerSle->at(sfBalance).value().xrp(); if (balance < view.fees().accountReserve(ownerCount)) return tecINSUFFICIENT_RESERVE; } @@ -528,7 +519,7 @@ LoanSet::doApply() // Create a holding for the borrower if one does not already exist. XRPL_ASSERT_PARTS( - borrower == accountID_ || borrower == counterparty, + borrower == account_ || borrower == counterparty, "xrpl::LoanSet::doApply", "borrower signed transaction"); if (auto const ter = addEmptyHolding( @@ -545,12 +536,12 @@ LoanSet::doApply() // 2. Transfer originationFee, if any, from vault pseudo-account to // LoanBroker owner. - if (originationFee != beast::kZero) + if (originationFee != beast::kZERO) { // Create the holding if it doesn't already exist (necessary for MPTs). // The owner may have deleted their MPT / line at some point. XRPL_ASSERT_PARTS( - brokerOwner == accountID_ || brokerOwner == counterparty, + brokerOwner == account_ || brokerOwner == counterparty, "xrpl::LoanSet::doApply", "broker owner signed transaction"); @@ -609,7 +600,7 @@ LoanSet::doApply() setLoanField(~sfLateInterestRate); setLoanField(~sfCloseInterestRate); setLoanField(~sfOverpaymentInterestRate); - setLoanField(~sfGracePeriod, kDefaultGracePeriod); + setLoanField(~sfGracePeriod, kDEFAULT_GRACE_PERIOD); // Set dynamic / computed fields to their initial values loan->at(sfPrincipalOutstanding) = principalRequested; loan->at(sfPeriodicPayment) = properties.periodicPayment; @@ -656,15 +647,16 @@ LoanSet::doApply() } void -LoanSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LoanSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool LoanSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index 6a82a15044..06bd1301cb 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include @@ -43,7 +44,7 @@ NFTokenAcceptOffer::preflight(PreflightContext const& ctx) if (!bo || !so) return temMALFORMED; - if (*bf <= beast::kZero) + if (*bf <= beast::kZERO) return temMALFORMED; } @@ -54,7 +55,7 @@ TER NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) { auto const checkOffer = - [&ctx](std::optional id) -> std::pair { + [&ctx](std::optional id) -> std::pair, TER> { if (id) { if (id->isZero()) @@ -67,10 +68,10 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) if (hasExpired(ctx.view, (*offerSLE)[~sfExpiration])) { - // Before fixCleanup3_1_3 amendment, expired offers caused tecEXPIRED in preclaim, + // Before fixSecurity3_1_3 amendment, expired offers caused tecEXPIRED in preclaim, // leaving them on ledger forever. After the amendment, we allow expired offers to // reach doApply() where they get deleted and tecEXPIRED is returned. - if (!ctx.view.rules().enabled(fixCleanup3_1_3)) + if (!ctx.view.rules().enabled(fixSecurity3_1_3)) return {nullptr, tecEXPIRED}; // Amendment enabled: return the expired offer to be handled in doApply. } @@ -158,7 +159,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) if (bo) { - if (bo->isFlag(lsfSellNFToken)) + if (((*bo)[sfFlags] & lsfSellNFToken) == lsfSellNFToken) return tecNFTOKEN_OFFER_TYPE_MISMATCH; // An account can't accept an offer it placed: @@ -217,7 +218,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) if (so) { - if (!so->isFlag(lsfSellNFToken)) + if (((*so)[sfFlags] & lsfSellNFToken) != lsfSellNFToken) return tecNFTOKEN_OFFER_TYPE_MISMATCH; // An account can't accept an offer it placed: @@ -305,7 +306,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // give the NFToken issuer an undesired trust line. // Issuer doesn't need a trust line to accept their own currency. if (ctx.view.rules().enabled(fixEnforceNFTokenTrustline) && - (nft::getFlags(tokenID) & nft::kFlagCreateTrustLines) == 0 && + (nft::getFlags(tokenID) & nft::kFLAG_CREATE_TRUST_LINES) == 0 && nftMinter != amount.getIssuer() && !ctx.view.read(keylet::line(nftMinter, amount.get()))) return tecNO_LINE; @@ -332,7 +333,7 @@ TER NFTokenAcceptOffer::pay(AccountID const& from, AccountID const& to, STAmount const& amount) { // This should never happen, but it's easy and quick to check. - if (amount < beast::kZero) + if (amount < beast::kZERO) return tecINTERNAL; // LCOV_EXCL_LINE auto const result = accountSend(view(), from, to, amount, j_); @@ -402,16 +403,16 @@ NFTokenAcceptOffer::transferNFToken( } TER -NFTokenAcceptOffer::acceptOffer(SLE::ref offer) +NFTokenAcceptOffer::acceptOffer(std::shared_ptr const& offer) { bool const isSell = offer->isFlag(lsfSellNFToken); AccountID const owner = (*offer)[sfOwner]; - AccountID const& seller = isSell ? owner : accountID_; - AccountID const& buyer = isSell ? accountID_ : owner; + AccountID const& seller = isSell ? owner : account_; + AccountID const& buyer = isSell ? account_ : owner; auto const nftokenID = (*offer)[sfNFTokenID]; - if (auto amount = offer->getFieldAmount(sfAmount); amount != beast::kZero) + if (auto amount = offer->getFieldAmount(sfAmount); amount != beast::kZERO) { // Calculate the issuer's cut from this sale, if any: if (auto const fee = nft::getTransferFee(nftokenID); fee != 0) @@ -419,7 +420,7 @@ NFTokenAcceptOffer::acceptOffer(SLE::ref offer) auto const cut = multiply(amount, nft::transferFeeAsRate(fee)); if (auto const issuer = nft::getIssuer(nftokenID); - cut != beast::kZero && seller != issuer && buyer != issuer) + cut != beast::kZERO && seller != issuer && buyer != issuer) { if (auto const r = pay(buyer, issuer, cut); !isTesSuccess(r)) return r; @@ -440,7 +441,7 @@ TER NFTokenAcceptOffer::doApply() { auto const loadToken = [this](std::optional const& id) { - SLE::pointer sle; + std::shared_ptr sle; if (id) sle = view().peek(keylet::nftoffer(*id)); return sle; @@ -449,13 +450,14 @@ NFTokenAcceptOffer::doApply() auto bo = loadToken(ctx_.tx[~sfNFTokenBuyOffer]); auto so = loadToken(ctx_.tx[~sfNFTokenSellOffer]); - // With fixCleanup3_1_3 amendment, check for expired offers and delete them, returning + // With fixSecurity3_1_3 amendment, check for expired offers and delete them, returning // tecEXPIRED. This ensures expired offers are properly cleaned up from the ledger. - if (view().rules().enabled(fixCleanup3_1_3)) + if (view().rules().enabled(fixSecurity3_1_3)) { bool foundExpired = false; - auto const deleteOfferIfExpired = [this, &foundExpired](SLE::ref offer) -> TER { + auto const deleteOfferIfExpired = + [this, &foundExpired](std::shared_ptr const& offer) -> TER { if (offer && hasExpired(view(), (*offer)[~sfExpiration])) { JLOG(j_.trace()) << "Offer is expired, deleting: " << offer->key(); @@ -524,16 +526,16 @@ NFTokenAcceptOffer::doApply() // being paid out than the seller authorized. That would be bad! // Send the broker the amount they requested. - if (auto const cut = ctx_.tx[~sfNFTokenBrokerFee]; cut && cut.value() != beast::kZero) + if (auto const cut = ctx_.tx[~sfNFTokenBrokerFee]; cut && cut.value() != beast::kZERO) { - if (auto const r = pay(buyer, accountID_, cut.value()); !isTesSuccess(r)) + if (auto const r = pay(buyer, account_, cut.value()); !isTesSuccess(r)) return r; amount -= cut.value(); } // Calculate the issuer's cut, if any. - if (auto const fee = nft::getTransferFee(nftokenID); amount != beast::kZero && fee != 0) + if (auto const fee = nft::getTransferFee(nftokenID); amount != beast::kZERO && fee != 0) { auto cut = multiply(amount, nft::transferFeeAsRate(fee)); @@ -547,7 +549,7 @@ NFTokenAcceptOffer::doApply() } // And send whatever remains to the seller. - if (amount > beast::kZero) + if (amount > beast::kZERO) { if (auto const r = pay(buyer, seller, amount); !isTesSuccess(r)) return r; @@ -567,9 +569,11 @@ NFTokenAcceptOffer::doApply() } void -NFTokenAcceptOffer::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenAcceptOffer::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -580,7 +584,6 @@ NFTokenAcceptOffer::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp b/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp index d33b1af8c2..fb57b14c15 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp @@ -13,6 +13,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -38,7 +40,7 @@ NFTokenBurn::preclaim(PreclaimContext const& ctx) // do so if the token is marked as burnable. if (auto const account = ctx.tx[sfAccount]; owner != account) { - if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::kFlagBurnable) == 0) + if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::kFLAG_BURNABLE) == 0) return tecNO_PERMISSION; if (auto const issuer = nft::getIssuer(ctx.tx[sfNFTokenID]); issuer != account) @@ -79,29 +81,30 @@ NFTokenBurn::doApply() // the number of buy offers, we prioritize the deletion of sell // offers in order to clean up sell offer directory std::size_t const deletedSellOffers = nft::removeTokenOffersWithLimit( - view(), keylet::nftSells(ctx_.tx[sfNFTokenID]), kMaxDeletableTokenOfferEntries); + view(), keylet::nftSells(ctx_.tx[sfNFTokenID]), kMAX_DELETABLE_TOKEN_OFFER_ENTRIES); - if (kMaxDeletableTokenOfferEntries > deletedSellOffers) + if (kMAX_DELETABLE_TOKEN_OFFER_ENTRIES > deletedSellOffers) { nft::removeTokenOffersWithLimit( view(), keylet::nftBuys(ctx_.tx[sfNFTokenID]), - kMaxDeletableTokenOfferEntries - deletedSellOffers); + kMAX_DELETABLE_TOKEN_OFFER_ENTRIES - deletedSellOffers); } return tesSUCCESS; } void -NFTokenBurn::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenBurn::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool NFTokenBurn::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp index 1614f90202..e76d7677aa 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp @@ -16,13 +16,15 @@ #include #include +#include + namespace xrpl { NotTEC NFTokenCancelOffer::preflight(PreflightContext const& ctx) { if (auto const& ids = ctx.tx[sfNFTokenOffers]; - ids.empty() || (ids.size() > kMaxTokenOfferCancelCount)) + ids.empty() || (ids.size() > kMAX_TOKEN_OFFER_CANCEL_COUNT)) return temMALFORMED; // In order to prevent unnecessarily overlarge transactions, we @@ -96,9 +98,11 @@ NFTokenCancelOffer::doApply() } void -NFTokenCancelOffer::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenCancelOffer::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -109,7 +113,6 @@ NFTokenCancelOffer::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp index 1948f3803d..9ca5220a8c 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp @@ -14,6 +14,8 @@ #include #include +#include + namespace xrpl { std::uint32_t @@ -53,8 +55,9 @@ NFTokenCreateOffer::preclaim(PreclaimContext const& ctx) uint256 const nftokenID = ctx.tx[sfNFTokenID]; std::uint32_t const txFlags = ctx.tx.getFlags(); + if (!nft::findToken( - ctx.view, ctx.tx[ctx.tx.isFlag(tfSellNFToken) ? sfAccount : sfOwner], nftokenID)) + ctx.view, ctx.tx[((txFlags & tfSellNFToken) != 0u) ? sfAccount : sfOwner], nftokenID)) return tecNO_ENTRY; // Use implementation shared with NFTokenMint @@ -89,9 +92,11 @@ NFTokenCreateOffer::doApply() } void -NFTokenCreateOffer::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenCreateOffer::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -102,7 +107,6 @@ NFTokenCreateOffer::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp index bd7413d50b..c7cb37ad94 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp @@ -27,6 +27,7 @@ #include #include #include // IWYU pragma: keep +#include #include namespace xrpl { @@ -85,7 +86,7 @@ NFTokenMint::preflight(PreflightContext const& ctx) { if (auto const f = ctx.tx[~sfTransferFee]) { - if (f > kMaxTransferFee) + if (f > kMAX_TRANSFER_FEE) return temBAD_NFTOKEN_TRANSFER_FEE; // If a non-zero TransferFee is set then the tfTransferable flag @@ -100,7 +101,7 @@ NFTokenMint::preflight(PreflightContext const& ctx) if (auto uri = ctx.tx[~sfURI]) { - if (uri->empty() || uri->length() > kMaxTokenUriLength) + if (uri->empty() || uri->length() > kMAX_TOKEN_URI_LENGTH) return temMALFORMED; } @@ -221,7 +222,7 @@ NFTokenMint::preclaim(PreclaimContext const& ctx) TER NFTokenMint::doApply() { - auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); + auto const issuer = ctx_.tx[~sfIssuer].value_or(account_); auto const tokenSeq = [this, &issuer]() -> Expected { auto const root = view().peek(keylet::account(issuer)); @@ -278,7 +279,7 @@ NFTokenMint::doApply() return (tokenSeq.error()); std::uint32_t const ownerCountBefore = - view().read(keylet::account(accountID_))->getFieldU32(sfOwnerCount); + view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); // Assemble the new NFToken. SOTemplate const* nfTokenTemplate = @@ -304,7 +305,7 @@ NFTokenMint::doApply() object.setFieldVL(sfURI, *uri); }); - if (TER const ret = nft::insertToken(ctx_.view(), accountID_, std::move(newToken)); + if (TER const ret = nft::insertToken(ctx_.view(), account_, std::move(newToken)); !isTesSuccess(ret)) return ret; @@ -332,7 +333,7 @@ NFTokenMint::doApply() // requiring the reserve to be met each time. The reserve is // only managed when a new NFT page or sell offer is added. if (auto const ownerCountAfter = - view().read(keylet::account(accountID_))->getFieldU32(sfOwnerCount); + view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); ownerCountAfter > ownerCountBefore) { if (auto const reserve = view().fees().accountReserve(ownerCountAfter); @@ -343,15 +344,16 @@ NFTokenMint::doApply() } void -NFTokenMint::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenMint::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool NFTokenMint::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp index 32ba362ded..b56ee9b061 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp @@ -14,6 +14,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -24,7 +26,7 @@ NFTokenModify::preflight(PreflightContext const& ctx) if (auto uri = ctx.tx[~sfURI]) { - if (uri->empty() || uri->length() > kMaxTokenUriLength) + if (uri->empty() || uri->length() > kMAX_TOKEN_URI_LENGTH) return temMALFORMED; } @@ -41,7 +43,7 @@ NFTokenModify::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; // Check if the NFT is mutable - if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::kFlagMutable) == 0) + if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::kFLAG_MUTABLE) == 0) return tecNO_PERMISSION; // Verify permissions for the issuer @@ -67,9 +69,11 @@ NFTokenModify::doApply() } void -NFTokenModify::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +NFTokenModify::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -80,7 +84,6 @@ NFTokenModify::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp index 9a26816155..c6896b78d4 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp @@ -13,6 +13,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -49,7 +51,7 @@ OracleDelete::preclaim(PreclaimContext const& ctx) TER OracleDelete::deleteOracle( ApplyView& view, - SLE::ref sle, + std::shared_ptr const& sle, AccountID const& account, beast::Journal j) { @@ -80,16 +82,18 @@ OracleDelete::deleteOracle( TER OracleDelete::doApply() { - if (auto sle = ctx_.view().peek(keylet::oracle(accountID_, ctx_.tx[sfOracleDocumentID]))) - return deleteOracle(ctx_.view(), sle, accountID_, j_); + if (auto sle = ctx_.view().peek(keylet::oracle(account_, ctx_.tx[sfOracleDocumentID]))) + return deleteOracle(ctx_.view(), sle, account_, j_); return tecINTERNAL; // LCOV_EXCL_LINE } void -OracleDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +OracleDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -100,7 +104,6 @@ OracleDelete::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp index 12d826e54d..7c2a817ed1 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp @@ -43,7 +43,7 @@ OracleSet::preflight(PreflightContext const& ctx) auto const& dataSeries = ctx.tx.getFieldArray(sfPriceDataSeries); if (dataSeries.empty()) return temARRAY_EMPTY; - if (dataSeries.size() > kMaxOracleDataSeries) + if (dataSeries.size() > kMAX_ORACLE_DATA_SERIES) return temARRAY_TOO_LARGE; auto isInvalidLength = [&](auto const& sField, std::size_t length) { @@ -51,8 +51,9 @@ OracleSet::preflight(PreflightContext const& ctx) (ctx.tx[sField].length() == 0 || ctx.tx[sField].length() > length); }; - if (isInvalidLength(sfProvider, kMaxOracleProvider) || isInvalidLength(sfURI, kMaxOracleUri) || - isInvalidLength(sfAssetClass, kMaxOracleSymbolClass)) + if (isInvalidLength(sfProvider, kMAX_ORACLE_PROVIDER) || + isInvalidLength(sfURI, kMAX_ORACLE_URI) || + isInvalidLength(sfAssetClass, kMAX_ORACLE_SYMBOL_CLASS)) return temMALFORMED; return tesSUCCESS; @@ -71,13 +72,13 @@ OracleSet::preclaim(PreclaimContext const& ctx) std::size_t const closeTime = duration_cast(ctx.view.header().closeTime.time_since_epoch()).count(); std::size_t const lastUpdateTime = ctx.tx[sfLastUpdateTime]; - if (lastUpdateTime < kEpochOffset.count()) + if (lastUpdateTime < kEPOCH_OFFSET.count()) return tecINVALID_UPDATE_TIME; - std::size_t const lastUpdateTimeEpoch = lastUpdateTime - kEpochOffset.count(); - if (closeTime < kMaxLastUpdateTimeDelta) + std::size_t const lastUpdateTimeEpoch = lastUpdateTime - kEPOCH_OFFSET.count(); + if (closeTime < kMAX_LAST_UPDATE_TIME_DELTA) return tecINTERNAL; // LCOV_EXCL_LINE - if (lastUpdateTimeEpoch < (closeTime - kMaxLastUpdateTimeDelta) || - lastUpdateTimeEpoch > (closeTime + kMaxLastUpdateTimeDelta)) + if (lastUpdateTimeEpoch < (closeTime - kMAX_LAST_UPDATE_TIME_DELTA) || + lastUpdateTimeEpoch > (closeTime + kMAX_LAST_UPDATE_TIME_DELTA)) return tecINVALID_UPDATE_TIME; auto const sle = @@ -95,7 +96,7 @@ OracleSet::preclaim(PreclaimContext const& ctx) auto const key = tokenPairKey(entry); if (pairs.contains(key) || pairsDel.contains(key)) return temMALFORMED; - if (entry[~sfScale] > kMaxPriceScale) + if (entry[~sfScale] > kMAX_PRICE_SCALE) return temMALFORMED; if (entry.isFieldPresent(sfAssetPrice)) { @@ -165,7 +166,7 @@ OracleSet::preclaim(PreclaimContext const& ctx) if (pairs.empty()) return tecARRAY_EMPTY; - if (pairs.size() > kMaxOracleDataSeries) + if (pairs.size() > kMAX_ORACLE_DATA_SERIES) return tecARRAY_TOO_LARGE; auto const reserve = @@ -201,7 +202,7 @@ setPriceDataInnerObjTemplate(STObject& obj) TER OracleSet::doApply() { - auto const oracleID = keylet::oracle(accountID_, ctx_.tx[sfOracleDocumentID]); + auto const oracleID = keylet::oracle(account_, ctx_.tx[sfOracleDocumentID]); auto populatePriceData = [](STObject& priceData, STObject const& entry) { setPriceDataInnerObjTemplate(priceData); @@ -311,7 +312,7 @@ OracleSet::doApply() sle->setFieldU32(sfLastUpdateTime, ctx_.tx[sfLastUpdateTime]); auto page = ctx_.view().dirInsert( - keylet::ownerDir(accountID_), sle->key(), describeOwnerDir(accountID_)); + keylet::ownerDir(account_), sle->key(), describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -328,15 +329,16 @@ OracleSet::doApply() } void -OracleSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +OracleSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool OracleSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index 7e950dc743..e4a060ea31 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -84,7 +84,7 @@ DepositPreauth::preflight(PreflightContext const& ctx) if (auto err = credentials::checkArray( ctx.tx.getFieldArray( authArrPresent ? sfAuthorizeCredentials : sfUnauthorizeCredentials), - kMaxCredentialsArraySize, + kMAX_CREDENTIALS_ARRAY_SIZE, ctx.j); !isTesSuccess(err)) return err; @@ -153,7 +153,7 @@ DepositPreauth::doApply() { if (ctx_.tx.isFieldPresent(sfAuthorize)) { - auto const sleOwner = view().peek(keylet::account(accountID_)); + auto const sleOwner = view().peek(keylet::account(account_)); if (!sleOwner) return {tefINTERNAL}; @@ -171,15 +171,15 @@ DepositPreauth::doApply() // Preclaim already verified that the Preauth entry does not yet exist. // Create and populate the Preauth entry. AccountID const auth{ctx_.tx[sfAuthorize]}; - Keylet const preauthKeylet = keylet::depositPreauth(accountID_, auth); + Keylet const preauthKeylet = keylet::depositPreauth(account_, auth); auto slePreauth = std::make_shared(preauthKeylet); - slePreauth->setAccountID(sfAccount, accountID_); + slePreauth->setAccountID(sfAccount, account_); slePreauth->setAccountID(sfAuthorize, auth); view().insert(slePreauth); - auto const page = view().dirInsert( - keylet::ownerDir(accountID_), preauthKeylet, describeOwnerDir(accountID_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), preauthKeylet, describeOwnerDir(account_)); JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKeylet.key) << ": " << (page ? "success" : "failure"); @@ -194,13 +194,13 @@ DepositPreauth::doApply() } else if (ctx_.tx.isFieldPresent(sfUnauthorize)) { - auto const preauth = keylet::depositPreauth(accountID_, ctx_.tx[sfUnauthorize]); + auto const preauth = keylet::depositPreauth(account_, ctx_.tx[sfUnauthorize]); return DepositPreauth::removeFromLedger(view(), preauth.key, j_); } else if (ctx_.tx.isFieldPresent(sfAuthorizeCredentials)) { - auto const sleOwner = view().peek(keylet::account(accountID_)); + auto const sleOwner = view().peek(keylet::account(account_)); if (!sleOwner) return tefINTERNAL; // LCOV_EXCL_LINE @@ -229,18 +229,18 @@ DepositPreauth::doApply() sortedLE.pushBack(std::move(cred)); } - Keylet const preauthKey = keylet::depositPreauth(accountID_, sortedTX); + Keylet const preauthKey = keylet::depositPreauth(account_, sortedTX); auto slePreauth = std::make_shared(preauthKey); if (!slePreauth) return tefINTERNAL; // LCOV_EXCL_LINE - slePreauth->setAccountID(sfAccount, accountID_); + slePreauth->setAccountID(sfAccount, account_); slePreauth->peekFieldArray(sfAuthorizeCredentials) = std::move(sortedLE); view().insert(slePreauth); - auto const page = view().dirInsert( - keylet::ownerDir(accountID_), preauthKey, describeOwnerDir(accountID_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), preauthKey, describeOwnerDir(account_)); JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKey.key) << ": " << (page ? "success" : "failure"); @@ -256,7 +256,7 @@ DepositPreauth::doApply() else if (ctx_.tx.isFieldPresent(sfUnauthorizeCredentials)) { auto const preauthKey = keylet::depositPreauth( - accountID_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); + account_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); return DepositPreauth::removeFromLedger(view(), preauthKey.key, j_); } @@ -298,9 +298,11 @@ DepositPreauth::removeFromLedger(ApplyView& view, uint256 const& preauthIndex, b } void -DepositPreauth::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +DepositPreauth::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -311,7 +313,6 @@ DepositPreauth::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 805ebe3684..d283874296 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -53,7 +53,7 @@ Payment::makeTxConsequences(PreflightContext const& ctx) // If there's no sfSendMax in XRP, and the sfAmount isn't // in XRP, then the transaction does not spend XRP. - return maxAmount.native() ? maxAmount.xrp() : beast::kZero; + return maxAmount.native() ? maxAmount.xrp() : beast::kZERO; }; return TxConsequences{ctx.tx, calculateMaxXRPSpend(ctx.tx)}; @@ -78,7 +78,7 @@ getMaxSourceAmount( Issue{issue.currency, account}, dstAmount.mantissa(), dstAmount.exponent(), - dstAmount < beast::kZero); + dstAmount < beast::kZERO); }); } @@ -102,9 +102,9 @@ Payment::getFlagsMask(PreflightContext const& ctx) bool const isDstMPT = dstAmount.holds(); bool const mpTokensV2 = ctx.rules.enabled(featureMPTokensV2); - static constexpr std::uint32_t kTfMptPaymentMaskV1 = ~(tfUniversal | tfPartialPayment); + constexpr std::uint32_t kTF_MPT_PAYMENT_MASK_V1 = ~(tfUniversal | tfPartialPayment); std::uint32_t const paymentMask = - (isDstMPT && !mpTokensV2) ? kTfMptPaymentMaskV1 : tfPaymentMask; + (isDstMPT && !mpTokensV2) ? kTF_MPT_PAYMENT_MASK_V1 : tfPaymentMask; return paymentMask; } @@ -122,18 +122,14 @@ Payment::preflight(PreflightContext const& ctx) if (!ctx.rules.enabled(featureMPTokensV1) && isDstMPT) return temDISABLED; + std::uint32_t const txFlags = tx.getFlags(); + if (!mpTokensV2 && isDstMPT && ctx.tx.isFieldPresent(sfPaths)) return temMALFORMED; - // A zero DomainID is invalid for a PermissionedDomain ledger entry because - // keylet::permissionedDomain(uint256) uses the DomainID as the ledger key. - if (auto const domainID = tx[~sfDomainID]; - ctx.rules.enabled(fixCleanup3_2_0) && domainID && *domainID == beast::kZero) - return temMALFORMED; - - bool const partialPaymentAllowed = tx.isFlag(tfPartialPayment); - bool const limitQuality = tx.isFlag(tfLimitQuality); - bool const defaultPathsAllowed = !tx.isFlag(tfNoRippleDirect); + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; + bool const limitQuality = (txFlags & tfLimitQuality) != 0u; + bool const defaultPathsAllowed = (txFlags & tfNoRippleDirect) == 0u; bool const hasPaths = tx.isFieldPresent(sfPaths); bool const hasMax = tx.isFieldPresent(sfSendMax); @@ -168,13 +164,13 @@ Payment::preflight(PreflightContext const& ctx) << "Payment destination account not specified."; return temDST_NEEDED; } - if (hasMax && maxSourceAmount <= beast::kZero) + if (hasMax && maxSourceAmount <= beast::kZERO) { JLOG(j.trace()) << "Malformed transaction: bad max amount: " << maxSourceAmount.getFullText(); return temBAD_AMOUNT; } - if (dstAmount <= beast::kZero) + if (dstAmount <= beast::kZERO) { JLOG(j.trace()) << "Malformed transaction: bad dst amount: " << dstAmount.getFullText(); return temBAD_AMOUNT; @@ -245,7 +241,7 @@ Payment::preflight(PreflightContext const& ctx) } auto const dMin = *deliverMin; - if (!isLegalNet(dMin) || dMin <= beast::kZero) + if (!isLegalNet(dMin) || dMin <= beast::kZERO) { JLOG(j.trace()) << "Malformed transaction: Invalid " << jss::DeliverMin.cStr() << " amount. " << dMin.getFullText(); @@ -315,7 +311,8 @@ TER Payment::preclaim(PreclaimContext const& ctx) { // Ripple if source or destination is non-native or if there are paths. - bool const partialPaymentAllowed = ctx.tx.isFlag(tfPartialPayment); + std::uint32_t const txFlags = ctx.tx.getFlags(); + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; auto const hasPaths = ctx.tx.isFieldPresent(sfPaths); auto const sendMax = ctx.tx[~sfSendMax]; @@ -360,7 +357,9 @@ Payment::preclaim(PreclaimContext const& ctx) return tecNO_DST_INSUF_XRP; } } - else if (sleDst->isFlag(lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag)) + else if ( + ((sleDst->getFlags() & lsfRequireDestTag) != 0u) && + !ctx.tx.isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. @@ -377,8 +376,8 @@ Payment::preclaim(PreclaimContext const& ctx) { STPathSet const& paths = ctx.tx.getFieldPathSet(sfPaths); - if (paths.size() > kMaxPathSize || std::ranges::any_of(paths, [](STPath const& path) { - return path.size() > kMaxPathLength; + if (paths.size() > kMAX_PATH_SIZE || std::ranges::any_of(paths, [](STPath const& path) { + return path.size() > kMAX_PATH_LENGTH; })) { return telBAD_PATH_COUNT; @@ -407,16 +406,17 @@ Payment::doApply() auto const deliverMin = ctx_.tx[~sfDeliverMin]; // Ripple if source or destination is non-native or if there are paths. - bool const partialPaymentAllowed = ctx_.tx.isFlag(tfPartialPayment); - bool const limitQuality = ctx_.tx.isFlag(tfLimitQuality); - bool const defaultPathsAllowed = !ctx_.tx.isFlag(tfNoRippleDirect); + std::uint32_t const txFlags = ctx_.tx.getFlags(); + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; + bool const limitQuality = (txFlags & tfLimitQuality) != 0u; + bool const defaultPathsAllowed = (txFlags & tfNoRippleDirect) == 0u; auto const hasPaths = ctx_.tx.isFieldPresent(sfPaths); auto const sendMax = ctx_.tx[~sfSendMax]; AccountID const dstAccountID(ctx_.tx.getAccountID(sfDestination)); STAmount const dstAmount(ctx_.tx.getFieldAmount(sfAmount)); bool const isDstMPT = dstAmount.holds(); - STAmount const maxSourceAmount = getMaxSourceAmount(accountID_, dstAmount, sendMax); + STAmount const maxSourceAmount = getMaxSourceAmount(account_, dstAmount, sendMax); JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText() << " dstAmount=" << dstAmount.getFullText(); @@ -431,7 +431,7 @@ Payment::doApply() sleDst = std::make_shared(k); sleDst->setAccountID(sfAccount, dstAccountID); sleDst->setFieldU32(sfSequence, view().seq()); - sleDst->setFieldAmount(sfBalance, XRPAmount(beast::kZero)); + sleDst->setFieldAmount(sfBalance, XRPAmount(beast::kZERO)); view().insert(sleDst); } @@ -459,7 +459,7 @@ Payment::doApply() // 2. If Account is deposit preauthorized by destination. if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -478,7 +478,7 @@ Payment::doApply() maxSourceAmount, dstAmount, dstAccountID, - accountID_, + account_, ctx_.tx.getFieldPathSet(sfPaths), ctx_.tx[~sfDomainID], ctx_.registry, @@ -518,18 +518,18 @@ Payment::doApply() JLOG(j_.trace()) << " dstAmount=" << dstAmount.getFullText(); auto const& mptIssue = dstAmount.get(); - if (auto const ter = requireAuth(view(), mptIssue, accountID_); !isTesSuccess(ter)) + if (auto const ter = requireAuth(view(), mptIssue, account_); !isTesSuccess(ter)) return ter; if (auto const ter = requireAuth(view(), mptIssue, dstAccountID); !isTesSuccess(ter)) return ter; - if (auto const ter = canTransfer(view(), mptIssue, accountID_, dstAccountID); + if (auto const ter = canTransfer(view(), mptIssue, account_, dstAccountID); !isTesSuccess(ter)) return ter; if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -538,13 +538,13 @@ Payment::doApply() // Transfer rate Rate rate{QUALITY_ONE}; // Payment between the holders - if (accountID_ != issuer && dstAccountID != issuer) + if (account_ != issuer && dstAccountID != issuer) { // If globally/individually locked then // - can't send between holders // - holder can send back to issuer // - issuer can send to holder - if (isAnyFrozen(view(), {accountID_, dstAccountID}, mptIssue)) + if (isAnyFrozen(view(), {account_, dstAccountID}, mptIssue)) return tecLOCKED; // Get the rate for a payment between the holders. @@ -572,7 +572,7 @@ Payment::doApply() return tecPATH_PARTIAL; PaymentSandbox pv(&view()); - auto res = accountSend(pv, accountID_, dstAccountID, amountDeliver, ctx_.journal); + auto res = accountSend(pv, account_, dstAccountID, amountDeliver, ctx_.journal); if (isTesSuccess(res)) { pv.apply(ctx_.rawView()); @@ -595,7 +595,7 @@ Payment::doApply() // Direct XRP payment. - auto const sleSrc = view().peek(keylet::account(accountID_)); + auto const sleSrc = view().peek(keylet::account(account_)); if (!sleSrc) return tefINTERNAL; // LCOV_EXCL_LINE @@ -607,10 +607,10 @@ Payment::doApply() auto const reserve = view().fees().accountReserve(ownerCount); // In a delegated payment, the fee payer is the delegated account, - // not the source account (accountID_). - bool const accountIsPayer = (ctx_.tx.getFeePayer() == accountID_); + // not the source account (account_). + bool const accountIsPayer = (ctx_.tx.getFeePayer() == account_); - // preFeeBalance_ is the balance on the source account (accountID_) BEFORE the fees + // preFeeBalance_ is the balance on the source account (account_) BEFORE the fees // were charged. If source account is the fee payer, it must also cover the fee. // The final spend may use the reserve to cover fees. auto const minRequiredFunds = @@ -662,7 +662,7 @@ Payment::doApply() if (dstAmount > dstReserve || sleDst->getFieldAmount(sfBalance) > dstReserve) { if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; } @@ -672,22 +672,23 @@ Payment::doApply() sleDst->setFieldAmount(sfBalance, sleDst->getFieldAmount(sfBalance) + dstAmount); // Re-arm the password change fee if we can and need to. - if (sleDst->isFlag(lsfPasswordSpent)) + if ((sleDst->getFlags() & lsfPasswordSpent) != 0u) sleDst->clearFlag(lsfPasswordSpent); return tesSUCCESS; } void -Payment::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +Payment::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool Payment::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index b1fe5e24bc..ec2d4dd70d 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -23,6 +23,7 @@ #include #include +#include #include namespace xrpl { @@ -43,18 +44,20 @@ NotTEC PaymentChannelClaim::preflight(PreflightContext const& ctx) { auto const bal = ctx.tx[~sfBalance]; - if (bal && (!isXRP(*bal) || *bal <= beast::kZero)) + if (bal && (!isXRP(*bal) || *bal <= beast::kZERO)) return temBAD_AMOUNT; auto const amt = ctx.tx[~sfAmount]; - if (amt && (!isXRP(*amt) || *amt <= beast::kZero)) + if (amt && (!isXRP(*amt) || *amt <= beast::kZERO)) return temBAD_AMOUNT; if (bal && amt && *bal > *amt) return temBAD_AMOUNT; { - if (ctx.tx.isFlag(tfClose) && ctx.tx.isFlag(tfRenew)) + auto const flags = ctx.tx.getFlags(); + + if (((flags & tfClose) != 0u) && ((flags & tfRenew) != 0u)) return temMALFORMED; } @@ -164,13 +167,13 @@ PaymentChannelClaim::doApply() (*slep)[sfBalance] = ctx_.tx[sfBalance]; XRPAmount const reqDelta = reqBalance - chanBalance; XRPL_ASSERT( - reqDelta >= beast::kZero, "xrpl::PaymentChannelClaim::doApply : minimum balance delta"); + reqDelta >= beast::kZERO, "xrpl::PaymentChannelClaim::doApply : minimum balance delta"); (*sled)[sfBalance] = (*sled)[sfBalance] + reqDelta; ctx_.view().update(sled); ctx_.view().update(slep); } - if (ctx_.tx.isFlag(tfRenew)) + if ((ctx_.tx.getFlags() & tfRenew) != 0u) { if (src != txAccount) return tecNO_PERMISSION; @@ -178,7 +181,7 @@ PaymentChannelClaim::doApply() ctx_.view().update(slep); } - if (ctx_.tx.isFlag(tfClose)) + if ((ctx_.tx.getFlags() & tfClose) != 0u) { // Channel will close immediately if dry or the receiver closes if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) @@ -199,9 +202,11 @@ PaymentChannelClaim::doApply() } void -PaymentChannelClaim::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +PaymentChannelClaim::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -212,7 +217,6 @@ PaymentChannelClaim::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp index 63dbe01944..c86590aa98 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp @@ -56,7 +56,7 @@ PaymentChannelCreate::makeTxConsequences(PreflightContext const& ctx) NotTEC PaymentChannelCreate::preflight(PreflightContext const& ctx) { - if (!isXRP(ctx.tx[sfAmount]) || (ctx.tx[sfAmount] <= beast::kZero)) + if (!isXRP(ctx.tx[sfAmount]) || (ctx.tx[sfAmount] <= beast::kZERO)) return temBAD_AMOUNT; if (ctx.tx[sfAccount] == ctx.tx[sfDestination]) @@ -96,11 +96,13 @@ PaymentChannelCreate::preclaim(PreclaimContext const& ctx) if (!sled) return tecNO_DST; + auto const flags = sled->getFlags(); + // Check if they have disallowed incoming payment channels - if (sled->isFlag(lsfDisallowIncomingPayChan)) + if ((flags & lsfDisallowIncomingPayChan) != 0u) return tecNO_PERMISSION; - if (sled->isFlag(lsfRequireDestTag) && !ctx.tx[~sfDestinationTag]) + if (((flags & lsfRequireDestTag) != 0u) && !ctx.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; // Pseudo-accounts cannot receive payment channels, other than native @@ -185,9 +187,11 @@ PaymentChannelCreate::doApply() } void -PaymentChannelCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +PaymentChannelCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -198,7 +202,6 @@ PaymentChannelCreate::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp index bcb8a91c96..4d2590c382 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp @@ -18,6 +18,8 @@ #include #include +#include + namespace xrpl { TxConsequences @@ -29,7 +31,7 @@ PaymentChannelFund::makeTxConsequences(PreflightContext const& ctx) NotTEC PaymentChannelFund::preflight(PreflightContext const& ctx) { - if (!isXRP(ctx.tx[sfAmount]) || (ctx.tx[sfAmount] <= beast::kZero)) + if (!isXRP(ctx.tx[sfAmount]) || (ctx.tx[sfAmount] <= beast::kZERO)) return temBAD_AMOUNT; return tesSUCCESS; @@ -105,9 +107,11 @@ PaymentChannelFund::doApply() } void -PaymentChannelFund::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +PaymentChannelFund::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -118,7 +122,6 @@ PaymentChannelFund::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp index 7eb3f282b9..befae454b7 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp @@ -12,13 +12,15 @@ #include #include +#include + namespace xrpl { NotTEC PermissionedDomainDelete::preflight(PreflightContext const& ctx) { auto const domain = ctx.tx.getFieldH256(sfDomainID); - if (domain == beast::kZero) + if (domain == beast::kZERO) return temMALFORMED; return tesSUCCESS; @@ -53,7 +55,7 @@ PermissionedDomainDelete::doApply() auto const slePd = view().peek(keylet::permissionedDomain(ctx_.tx.at(sfDomainID))); auto const page = (*slePd)[sfOwnerNode]; - if (!view().dirRemove(keylet::ownerDir(accountID_), page, slePd->key(), true)) + if (!view().dirRemove(keylet::ownerDir(account_), page, slePd->key(), true)) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Unable to delete permissioned domain directory entry."; @@ -61,7 +63,7 @@ PermissionedDomainDelete::doApply() // LCOV_EXCL_STOP } - auto const ownerSle = view().peek(keylet::account(accountID_)); + auto const ownerSle = view().peek(keylet::account(account_)); XRPL_ASSERT( ownerSle && ownerSle->getFieldU32(sfOwnerCount) > 0, "xrpl::PermissionedDomainDelete::doApply : nonzero owner count"); @@ -72,9 +74,11 @@ PermissionedDomainDelete::doApply() } void -PermissionedDomainDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +PermissionedDomainDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -85,7 +89,6 @@ PermissionedDomainDelete::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp index 0e71ceada1..92f260db4e 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp @@ -33,13 +33,13 @@ PermissionedDomainSet::preflight(PreflightContext const& ctx) { if (auto err = credentials::checkArray( ctx.tx.getFieldArray(sfAcceptedCredentials), - kMaxPermissionedDomainCredentialsArraySize, + kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE, ctx.j); !isTesSuccess(err)) return err; auto const domain = ctx.tx.at(~sfDomainID); - if (domain && *domain == beast::kZero) + if (domain && *domain == beast::kZERO) return temMALFORMED; return tesSUCCESS; @@ -77,7 +77,7 @@ PermissionedDomainSet::preclaim(PreclaimContext const& ctx) TER PermissionedDomainSet::doApply() { - auto const ownerSle = view().peek(keylet::account(accountID_)); + auto const ownerSle = view().peek(keylet::account(account_)); if (!ownerSle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -110,16 +110,15 @@ PermissionedDomainSet::doApply() if (balance < reserve) return tecINSUFFICIENT_RESERVE; - bool const fixEnabled = view().rules().enabled(fixCleanup3_1_3); - auto const seq = fixEnabled ? ctx_.tx.getSeqValue() : ctx_.tx.getFieldU32(sfSequence); - Keylet const pdKeylet = keylet::permissionedDomain(accountID_, seq); + Keylet const pdKeylet = + keylet::permissionedDomain(account_, ctx_.tx.getFieldU32(sfSequence)); auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, accountID_); - slePd->setFieldU32(sfSequence, seq); + slePd->setAccountID(sfOwner, account_); + slePd->setFieldU32(sfSequence, ctx_.tx.getFieldU32(sfSequence)); slePd->peekFieldArray(sfAcceptedCredentials) = std::move(sortedLE); auto const page = - view().dirInsert(keylet::ownerDir(accountID_), pdKeylet, describeOwnerDir(accountID_)); + view().dirInsert(keylet::ownerDir(account_), pdKeylet, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -133,9 +132,11 @@ PermissionedDomainSet::doApply() } void -PermissionedDomainSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +PermissionedDomainSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -146,7 +147,6 @@ PermissionedDomainSet::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/system/Batch.cpp b/src/libxrpl/tx/transactors/system/Batch.cpp index 64a62ac273..f9ae9dc912 100644 --- a/src/libxrpl/tx/transactors/system/Batch.cpp +++ b/src/libxrpl/tx/transactors/system/Batch.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -61,7 +62,7 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) if (baseFee > maxAmount - view.fees().base) { JLOG(debugLog().error()) << "BatchTrace: Base fee overflow detected."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -74,10 +75,10 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) auto const& txns = tx.getFieldArray(sfRawTransactions); // LCOV_EXCL_START - if (txns.size() > kMaxBatchTxCount) + if (txns.size() > kMAX_BATCH_TX_COUNT) { JLOG(debugLog().error()) << "BatchTrace: Raw Transactions array exceeds max entries."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -89,7 +90,7 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) if (stx.getTxnType() == ttBATCH) { JLOG(debugLog().error()) << "BatchTrace: Inner Batch transaction found."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -99,7 +100,7 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) { JLOG(debugLog().error()) << "BatchTrace: XRPAmount overflow in txnFees calculation."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP txnFees += fee; @@ -113,10 +114,10 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) auto const& signers = tx.getFieldArray(sfBatchSigners); // LCOV_EXCL_START - if (signers.size() > kMaxBatchTxCount) + if (signers.size() > kMAX_BATCH_TX_COUNT) { JLOG(debugLog().error()) << "BatchTrace: Batch Signers array exceeds max entries."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -137,7 +138,7 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) if (signerCount > 0 && view.fees().base > maxAmount / signerCount) { JLOG(debugLog().error()) << "BatchTrace: XRPAmount overflow in signerCount calculation."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -147,12 +148,12 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) if (signerFees > maxAmount - txnFees) { JLOG(debugLog().error()) << "BatchTrace: XRPAmount overflow in signerFees calculation."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } if (txnFees + signerFees > maxAmount - batchBase) { JLOG(debugLog().error()) << "BatchTrace: XRPAmount overflow in total fee calculation."; - return XRPAmount{kInitialXrp}; + return XRPAmount{kINITIAL_XRP}; } // LCOV_EXCL_STOP @@ -220,7 +221,7 @@ Batch::preflight(PreflightContext const& ctx) return temARRAY_EMPTY; } - if (rawTxns.size() > kMaxBatchTxCount) + if (rawTxns.size() > kMAX_BATCH_TX_COUNT) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]:" << "txns array exceeds 8 entries."; @@ -281,12 +282,12 @@ Batch::preflight(PreflightContext const& ctx) } if (std::ranges::any_of( - kDisabledTxTypes, [txType](auto const& disabled) { return txType == disabled; })) + kDISABLED_TX_TYPES, [txType](auto const& disabled) { return txType == disabled; })) { return temINVALID_INNER_BATCH; } - if (!stx.isFlag(tfInnerBatchTxn)) + if ((stx.getFlags() & tfInnerBatchTxn) == 0u) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " << "inner txn must have the tfInnerBatchTxn flag. " @@ -310,7 +311,7 @@ Batch::preflight(PreflightContext const& ctx) } // Check that the Fee is native asset (XRP) and zero - if (auto const fee = stx.getFieldAmount(sfFee); !fee.native() || fee.xrp() != beast::kZero) + if (auto const fee = stx.getFieldAmount(sfFee); !fee.native() || fee.xrp() != beast::kZERO) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " << "inner txn must have a fee of 0. " @@ -412,7 +413,7 @@ Batch::preflightSigValidated(PreflightContext const& ctx) STArray const& signers = ctx.tx.getFieldArray(sfBatchSigners); // Check that the batch signers array is not too large. - if (signers.size() > kMaxBatchTxCount) + if (signers.size() > kMAX_BATCH_TX_COUNT) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " << "signers array exceeds 8 entries."; @@ -517,15 +518,16 @@ Batch::doApply() } void -Batch::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +Batch::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool Batch::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index 38fee5bf92..5f51f935f3 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -42,7 +42,7 @@ Transactor::invokePreflight(PreflightContext const& ctx) return ret; auto account = ctx.tx.getAccountID(sfAccount); - if (account != beast::kZero) + if (account != beast::kZERO) { JLOG(ctx.j.warn()) << "Change: Bad source id"; return temBAD_SRC_ACCOUNT; @@ -50,7 +50,7 @@ Transactor::invokePreflight(PreflightContext const& ctx) // No point in going any further if the transaction fee is malformed. auto const fee = ctx.tx.getFieldAmount(sfFee); - if (!fee.native() || fee != beast::kZero) + if (!fee.native() || fee != beast::kZERO) { JLOG(ctx.j.warn()) << "Change: invalid fee"; return temBAD_FEE; @@ -154,7 +154,7 @@ Change::doApply() void Change::preCompute() { - XRPL_ASSERT(accountID_ == beast::kZero, "xrpl::Change::preCompute : zero account"); + XRPL_ASSERT(account_ == beast::kZERO, "xrpl::Change::preCompute : zero account"); } TER @@ -177,8 +177,10 @@ Change::applyAmendment() if (std::ranges::find(amendments, amendment) != amendments.end()) return tefALREADY; - bool const gotMajority = ctx_.tx.isFlag(tfGotMajority); - bool const lostMajority = ctx_.tx.isFlag(tfLostMajority); + auto flags = ctx_.tx.getFlags(); + + bool const gotMajority = (flags & tfGotMajority) != 0; + bool const lostMajority = (flags & tfLostMajority) != 0; if (gotMajority && lostMajority) return temINVALID_FLAG; @@ -409,15 +411,16 @@ Change::applyUNLModify() } void -Change::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +Change::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool Change::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp b/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp index 65c32b788c..2bc71f8c86 100644 --- a/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp +++ b/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp @@ -4,9 +4,7 @@ #include #include #include -#include #include -#include #include #include #include @@ -14,71 +12,24 @@ #include #include -#include -#include -#include +#include namespace xrpl { -namespace { - -using FixType = LedgerStateFix::FixType; - -std::array, 2> const kLedgerFixFields = {{ - {FixType::NfTokenPageLink, &sfOwner}, - {FixType::BookExchangeRate, &sfBookDirectory}, -}}; - -[[nodiscard]] SField const* -fixField(FixType const fixType) -{ - auto const iter = std::ranges::find_if( - kLedgerFixFields, [fixType](auto const& entry) { return entry.first == fixType; }); - - if (iter == kLedgerFixFields.end()) - return nullptr; // LCOV_EXCL_LINE - - return iter->second; -} - -[[nodiscard]] bool -hasUnexpectedFixField(STTx const& tx, SField const& expected) -{ - return std::ranges::any_of(kLedgerFixFields, [&tx, &expected](auto const& entry) { - auto const field = entry.second; - return field != &expected && tx.isFieldPresent(*field); - }); -} - -} // namespace - NotTEC LedgerStateFix::preflight(PreflightContext const& ctx) { - auto const fixType = static_cast(ctx.tx[sfLedgerFixType]); - - switch (fixType) + switch (static_cast(ctx.tx[sfLedgerFixType])) { case FixType::NfTokenPageLink: - break; - - case FixType::BookExchangeRate: - if (!ctx.rules.enabled(fixCleanup3_2_0)) - return temDISABLED; + if (!ctx.tx.isFieldPresent(sfOwner)) + return temINVALID; break; default: return tefINVALID_LEDGER_FIX_TYPE; } - auto const expectedField = fixField(fixType); - if (expectedField == nullptr) - return tefINVALID_LEDGER_FIX_TYPE; // LCOV_EXCL_LINE - - // Each fix type allows exactly one fix-specific field. - if (!ctx.tx.isFieldPresent(*expectedField) || hasUnexpectedFixField(ctx.tx, *expectedField)) - return temINVALID; - return tesSUCCESS; } @@ -102,24 +53,6 @@ LedgerStateFix::preclaim(PreclaimContext const& ctx) return tesSUCCESS; } - if (static_cast(ctx.tx[sfLedgerFixType]) == FixType::BookExchangeRate) - { - auto const dirKey = ctx.tx.getFieldH256(sfBookDirectory); - auto const sle = ctx.view.read(Keylet(ltDIR_NODE, dirKey)); - if (!sle) - return tecOBJECT_NOT_FOUND; - - // Must be the first page of a book directory (has sfExchangeRate). - if (!sle->isFieldPresent(sfExchangeRate)) - return tecNO_PERMISSION; - - // ExchangeRate is already correct, nothing to fix. - if (getQuality(sle->key()) == sle->getFieldU64(sfExchangeRate)) - return tecNO_PERMISSION; - - return tesSUCCESS; - } - // preflight is supposed to verify that only valid FixTypes get to preclaim. return tecINTERNAL; // LCOV_EXCL_LINE } @@ -135,26 +68,16 @@ LedgerStateFix::doApply() return tesSUCCESS; } - if (static_cast(ctx_.tx[sfLedgerFixType]) == FixType::BookExchangeRate) - { - auto const dirKey = ctx_.tx.getFieldH256(sfBookDirectory); - auto sle = view().peek(Keylet(ltDIR_NODE, dirKey)); - if (!sle) - return tecINTERNAL; // LCOV_EXCL_LINE - - sle->setFieldU64(sfExchangeRate, getQuality(sle->key())); - view().update(sle); - return tesSUCCESS; - } - // preflight is supposed to verify that only valid FixTypes get to doApply. return tecINTERNAL; // LCOV_EXCL_LINE } void -LedgerStateFix::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +LedgerStateFix::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -165,7 +88,6 @@ LedgerStateFix::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index 5be00fe76c..75095772dd 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -32,7 +32,7 @@ NotTEC TicketCreate::preflight(PreflightContext const& ctx) { if (std::uint32_t const count = ctx.tx[sfTicketCount]; - count < kMinValidCount || count > kMaxValidCount) + count < kMIN_VALID_COUNT || count > kMAX_VALID_COUNT) return temINVALID_COUNT; return tesSUCCESS; @@ -58,7 +58,7 @@ TicketCreate::preclaim(PreclaimContext const& ctx) // o consumedTickets <= 1 // So in the worst case addedTickets == consumedTickets and the // computation yields curTicketCount. - if (curTicketCount + addedTickets - consumedTickets > kMaxTicketThreshold) + if (curTicketCount + addedTickets - consumedTickets > kMAX_TICKET_THRESHOLD) return tecDIR_FULL; return tesSUCCESS; @@ -67,7 +67,7 @@ TicketCreate::preclaim(PreclaimContext const& ctx) TER TicketCreate::doApply() { - SLE::pointer const sleAccountRoot = view().peek(keylet::account(accountID_)); + SLE::pointer const sleAccountRoot = view().peek(keylet::account(account_)); if (!sleAccountRoot) return tefINTERNAL; // LCOV_EXCL_LINE @@ -100,15 +100,15 @@ TicketCreate::doApply() for (std::uint32_t i = 0; i < ticketCount; ++i) { std::uint32_t const curTicketSeq = firstTicketSeq + i; - Keylet const ticketKeylet = keylet::kTicket(accountID_, curTicketSeq); + Keylet const ticketKeylet = keylet::kTICKET(account_, curTicketSeq); SLE::pointer const sleTicket = std::make_shared(ticketKeylet); - sleTicket->setAccountID(sfAccount, accountID_); + sleTicket->setAccountID(sfAccount, account_); sleTicket->setFieldU32(sfTicketSequence, curTicketSeq); view().insert(sleTicket); - auto const page = view().dirInsert( - keylet::ownerDir(accountID_), ticketKeylet, describeOwnerDir(accountID_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), ticketKeylet, describeOwnerDir(account_)); JLOG(j_.trace()) << "Creating ticket " << to_string(ticketKeylet.key) << ": " << (page ? "success" : "failure"); @@ -135,9 +135,11 @@ TicketCreate::doApply() } void -TicketCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +TicketCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -148,7 +150,6 @@ TicketCreate::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/Clawback.cpp b/src/libxrpl/tx/transactors/token/Clawback.cpp index 06132c1c97..8c99ce9b08 100644 --- a/src/libxrpl/tx/transactors/token/Clawback.cpp +++ b/src/libxrpl/tx/transactors/token/Clawback.cpp @@ -23,6 +23,8 @@ #include #include +#include +#include #include namespace xrpl { @@ -44,7 +46,7 @@ preflightHelper(PreflightContext const& ctx) // The issuer field is used for the token holder instead AccountID const& holder = clawAmount.getIssuer(); - if (issuer == holder || isXRP(clawAmount) || clawAmount <= beast::kZero) + if (issuer == holder || isXRP(clawAmount) || clawAmount <= beast::kZERO) return temBAD_AMOUNT; return tesSUCCESS; @@ -67,7 +69,7 @@ preflightHelper(PreflightContext const& ctx) if (ctx.tx[sfAccount] == *mptHolder) return temMALFORMED; - if (clawAmount.mpt() > MPTAmount{kMaxMpTokenAmount} || clawAmount <= beast::kZero) + if (clawAmount.mpt() > MPTAmount{kMAX_MP_TOKEN_AMOUNT} || clawAmount <= beast::kZERO) return temBAD_AMOUNT; return tesSUCCESS; @@ -103,9 +105,12 @@ preclaimHelper( AccountID const& holder, STAmount const& clawAmount) { + std::uint32_t const issuerFlagsIn = sleIssuer.getFieldU32(sfFlags); + // If AllowTrustLineClawback is not set or NoFreeze is set, return no // permission - if (!sleIssuer.isFlag(lsfAllowTrustLineClawback) || sleIssuer.isFlag(lsfNoFreeze)) + if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlagsIn & lsfNoFreeze) != 0u)) return tecNO_PERMISSION; auto const sleRippleState = @@ -116,11 +121,11 @@ preclaimHelper( STAmount const balance = (*sleRippleState)[sfBalance]; // If balance is positive, issuer must have higher address than holder - if (balance > beast::kZero && issuer < holder) + if (balance > beast::kZERO && issuer < holder) return tecNO_PERMISSION; // If balance is negative, issuer must have lower address than holder - if (balance < beast::kZero && issuer > holder) + if (balance < beast::kZERO && issuer > holder) return tecNO_PERMISSION; // At this point, we know that issuer and holder accounts @@ -138,7 +143,7 @@ preclaimHelper( clawAmount.get().currency, issuer, FreezeHandling::IgnoreFreeze, - ctx.j) <= beast::kZero) + ctx.j) <= beast::kZERO) return tecINSUFFICIENT_FUNDS; return tesSUCCESS; @@ -158,7 +163,7 @@ preclaimHelper( if (!sleIssuance) return tecOBJECT_NOT_FOUND; - if (!sleIssuance->isFlag(lsfMPTCanClawback)) + if (((*sleIssuance)[sfFlags] & lsfMPTCanClawback) == 0u) return tecNO_PERMISSION; if (sleIssuance->getAccountID(sfIssuer) != issuer) @@ -173,7 +178,7 @@ preclaimHelper( clawAmount.get(), FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, - ctx.j) <= beast::kZero) + ctx.j) <= beast::kZERO) return tecINSUFFICIENT_FUNDS; return tesSUCCESS; @@ -274,15 +279,16 @@ Clawback::doApply() } void -Clawback::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +Clawback::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool Clawback::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/ConfidentialMPTClawback.cpp b/src/libxrpl/tx/transactors/token/ConfidentialMPTClawback.cpp index 88f59bf2f2..da5b463089 100644 --- a/src/libxrpl/tx/transactors/token/ConfidentialMPTClawback.cpp +++ b/src/libxrpl/tx/transactors/token/ConfidentialMPTClawback.cpp @@ -37,11 +37,11 @@ ConfidentialMPTClawback::preflight(PreflightContext const& ctx) // Check invalid claw amount auto const clawAmount = ctx.tx[sfMPTAmount]; - if (clawAmount == 0 || clawAmount > kMaxMpTokenAmount) + if (clawAmount == 0 || clawAmount > kMAX_MP_TOKEN_AMOUNT) return temBAD_AMOUNT; // Verify proof length - if (ctx.tx[sfZKProof].length() != kEcClawbackProofLength) + if (ctx.tx[sfZKProof].length() != kEC_CLAWBACK_PROOF_LENGTH) return temMALFORMED; return tesSUCCESS; @@ -51,9 +51,9 @@ XRPAmount ConfidentialMPTClawback::calculateBaseFee(ReadView const& view, STTx const& tx) { // Transactor::calculateBaseFee = baseFee + (signerCount * baseFee). - // We charge kConfidentialFeeMultiplier extra base fees so the total is + // We charge kCONFIDENTIAL_FEE_MULTIPLIER extra base fees so the total is // 10 * baseFee + (signerCount * baseFee). - return Transactor::calculateBaseFee(view, tx) + view.fees().base * kConfidentialFeeMultiplier; + return Transactor::calculateBaseFee(view, tx) + view.fees().base * kCONFIDENTIAL_FEE_MULTIPLIER; } TER diff --git a/src/libxrpl/tx/transactors/token/ConfidentialMPTConvert.cpp b/src/libxrpl/tx/transactors/token/ConfidentialMPTConvert.cpp index 5f5dc51773..ab69b6ac42 100644 --- a/src/libxrpl/tx/transactors/token/ConfidentialMPTConvert.cpp +++ b/src/libxrpl/tx/transactors/token/ConfidentialMPTConvert.cpp @@ -32,7 +32,7 @@ ConfidentialMPTConvert::preflight(PreflightContext const& ctx) if (MPTIssue(ctx.tx[sfMPTokenIssuanceID]).getIssuer() == ctx.tx[sfAccount]) return temMALFORMED; - if (ctx.tx[sfMPTAmount] > kMaxMpTokenAmount) + if (ctx.tx[sfMPTAmount] > kMAX_MP_TOKEN_AMOUNT) return temBAD_AMOUNT; if (ctx.tx.isFieldPresent(sfHolderEncryptionKey)) @@ -46,7 +46,7 @@ ConfidentialMPTConvert::preflight(PreflightContext const& ctx) return temMALFORMED; // verify schnorr proof length when registering holder ec public key - if (ctx.tx[sfZKProof].size() != kEcSchnorrProofLength) + if (ctx.tx[sfZKProof].size() != kEC_SCHNORR_PROOF_LENGTH) return temMALFORMED; } else @@ -69,9 +69,9 @@ XRPAmount ConfidentialMPTConvert::calculateBaseFee(ReadView const& view, STTx const& tx) { // Transactor::calculateBaseFee = baseFee + (signerCount * baseFee). - // We charge kConfidentialFeeMultiplier extra base fees so the total is + // We charge kCONFIDENTIAL_FEE_MULTIPLIER extra base fees so the total is // 10 * baseFee + (signerCount * baseFee). - return Transactor::calculateBaseFee(view, tx) + view.fees().base * kConfidentialFeeMultiplier; + return Transactor::calculateBaseFee(view, tx) + view.fees().base * kCONFIDENTIAL_FEE_MULTIPLIER; } TER @@ -205,7 +205,7 @@ ConfidentialMPTConvert::doApply() { auto const mptIssuanceID = ctx_.tx[sfMPTokenIssuanceID]; - auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, accountID_)); + auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, account_)); if (!sleMptoken) return tecINTERNAL; // LCOV_EXCL_LINE @@ -222,7 +222,7 @@ ConfidentialMPTConvert::doApply() // Converting decreases regular balance and increases confidential outstanding. // The confidential outstanding tracks total tokens in confidential form globally. auto const currentCOA = (*sleIssuance)[~sfConfidentialOutstandingAmount].valueOr(0); - if (amtToConvert > kMaxMpTokenAmount - currentCOA) + if (amtToConvert > kMAX_MP_TOKEN_AMOUNT - currentCOA) return tecINTERNAL; // LCOV_EXCL_LINE (*sleMptoken)[sfMPTAmount] = amt - amtToConvert; @@ -287,7 +287,7 @@ ConfidentialMPTConvert::doApply() // Spending balance starts at zero. Must use canonical zero encryption // (deterministic ciphertext) so the ledger state is reproducible. auto zeroBalance = encryptCanonicalZeroAmount( - (*sleMptoken)[sfHolderEncryptionKey], accountID_, mptIssuanceID); + (*sleMptoken)[sfHolderEncryptionKey], account_, mptIssuanceID); if (!zeroBalance) return tecINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/token/ConfidentialMPTConvertBack.cpp b/src/libxrpl/tx/transactors/token/ConfidentialMPTConvertBack.cpp index 9af793b018..8a3f1aedbb 100644 --- a/src/libxrpl/tx/transactors/token/ConfidentialMPTConvertBack.cpp +++ b/src/libxrpl/tx/transactors/token/ConfidentialMPTConvertBack.cpp @@ -31,7 +31,7 @@ ConfidentialMPTConvertBack::preflight(PreflightContext const& ctx) if (MPTIssue(ctx.tx[sfMPTokenIssuanceID]).getIssuer() == ctx.tx[sfAccount]) return temMALFORMED; - if (ctx.tx[sfMPTAmount] == 0 || ctx.tx[sfMPTAmount] > kMaxMpTokenAmount) + if (ctx.tx[sfMPTAmount] == 0 || ctx.tx[sfMPTAmount] > kMAX_MP_TOKEN_AMOUNT) return temBAD_AMOUNT; if (!isValidCompressedECPoint(ctx.tx[sfBalanceCommitment])) @@ -43,7 +43,7 @@ ConfidentialMPTConvertBack::preflight(PreflightContext const& ctx) return res; // ConvertBack proof = compact sigma proof (128 bytes) + single bulletproof (688 bytes) - if (ctx.tx[sfZKProof].size() != kEcConvertBackProofLength) + if (ctx.tx[sfZKProof].size() != kEC_CONVERT_BACK_PROOF_LENGTH) return temMALFORMED; return tesSUCCESS; @@ -53,9 +53,9 @@ XRPAmount ConfidentialMPTConvertBack::calculateBaseFee(ReadView const& view, STTx const& tx) { // Transactor::calculateBaseFee = baseFee + (signerCount * baseFee). - // We charge kConfidentialFeeMultiplier extra base fees so the total is + // We charge kCONFIDENTIAL_FEE_MULTIPLIER extra base fees so the total is // 10 * baseFee + (signerCount * baseFee). - return Transactor::calculateBaseFee(view, tx) + view.fees().base * kConfidentialFeeMultiplier; + return Transactor::calculateBaseFee(view, tx) + view.fees().base * kCONFIDENTIAL_FEE_MULTIPLIER; } /** @@ -213,7 +213,7 @@ ConfidentialMPTConvertBack::doApply() { auto const mptIssuanceID = ctx_.tx[sfMPTokenIssuanceID]; - auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, accountID_)); + auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, account_)); if (!sleMptoken) return tecINTERNAL; // LCOV_EXCL_LINE @@ -226,7 +226,7 @@ ConfidentialMPTConvertBack::doApply() // Converting back increases regular balance and decreases confidential // outstanding. This is the inverse of Convert. - if (amt > kMaxMpTokenAmount - amtToConvertBack) + if (amt > kMAX_MP_TOKEN_AMOUNT - amtToConvertBack) return tecINTERNAL; // LCOV_EXCL_LINE (*sleMptoken)[sfMPTAmount] = amt + amtToConvertBack; diff --git a/src/libxrpl/tx/transactors/token/ConfidentialMPTMergeInbox.cpp b/src/libxrpl/tx/transactors/token/ConfidentialMPTMergeInbox.cpp index 33c305dfb1..d2537cb70f 100644 --- a/src/libxrpl/tx/transactors/token/ConfidentialMPTMergeInbox.cpp +++ b/src/libxrpl/tx/transactors/token/ConfidentialMPTMergeInbox.cpp @@ -37,9 +37,9 @@ XRPAmount ConfidentialMPTMergeInbox::calculateBaseFee(ReadView const& view, STTx const& tx) { // Transactor::calculateBaseFee = baseFee + (signerCount * baseFee). - // We charge kConfidentialFeeMultiplier extra base fees so the total is + // We charge kCONFIDENTIAL_FEE_MULTIPLIER extra base fees so the total is // 10 * baseFee + (signerCount * baseFee). - return Transactor::calculateBaseFee(view, tx) + view.fees().base * kConfidentialFeeMultiplier; + return Transactor::calculateBaseFee(view, tx) + view.fees().base * kCONFIDENTIAL_FEE_MULTIPLIER; } TER @@ -86,7 +86,7 @@ TER ConfidentialMPTMergeInbox::doApply() { auto const mptIssuanceID = ctx_.tx[sfMPTokenIssuanceID]; - auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, accountID_)); + auto sleMptoken = view().peek(keylet::mptoken(mptIssuanceID, account_)); if (!sleMptoken) return tecINTERNAL; // LCOV_EXCL_LINE @@ -111,7 +111,7 @@ ConfidentialMPTMergeInbox::doApply() // Reset inbox to encrypted zero. Must use canonical zero encryption // (deterministic ciphertext) so the ledger state is reproducible. auto zeroEncryption = - encryptCanonicalZeroAmount((*sleMptoken)[sfHolderEncryptionKey], accountID_, mptIssuanceID); + encryptCanonicalZeroAmount((*sleMptoken)[sfHolderEncryptionKey], account_, mptIssuanceID); if (!zeroEncryption) return tecINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/token/ConfidentialMPTSend.cpp b/src/libxrpl/tx/transactors/token/ConfidentialMPTSend.cpp index b89a64e291..a2a48649f7 100644 --- a/src/libxrpl/tx/transactors/token/ConfidentialMPTSend.cpp +++ b/src/libxrpl/tx/transactors/token/ConfidentialMPTSend.cpp @@ -49,19 +49,19 @@ ConfidentialMPTSend::preflight(PreflightContext const& ctx) return temMALFORMED; // Check the length of the encrypted amounts - if (ctx.tx[sfSenderEncryptedAmount].length() != kEcGamalEncryptedTotalLength || - ctx.tx[sfDestinationEncryptedAmount].length() != kEcGamalEncryptedTotalLength || - ctx.tx[sfIssuerEncryptedAmount].length() != kEcGamalEncryptedTotalLength) + if (ctx.tx[sfSenderEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + ctx.tx[sfDestinationEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + ctx.tx[sfIssuerEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) { return temBAD_CIPHERTEXT; } bool const hasAuditor = ctx.tx.isFieldPresent(sfAuditorEncryptedAmount); - if (hasAuditor && ctx.tx[sfAuditorEncryptedAmount].length() != kEcGamalEncryptedTotalLength) + if (hasAuditor && ctx.tx[sfAuditorEncryptedAmount].length() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return temBAD_CIPHERTEXT; // Check the length of the ZKProof (fixed size regardless of recipient count) - if (ctx.tx[sfZKProof].length() != kEcSendProofLength) + if (ctx.tx[sfZKProof].length() != kEC_SEND_PROOF_LENGTH) return temMALFORMED; // Check the Pedersen commitments are valid @@ -93,9 +93,9 @@ XRPAmount ConfidentialMPTSend::calculateBaseFee(ReadView const& view, STTx const& tx) { // Transactor::calculateBaseFee = baseFee + (signerCount * baseFee). - // We charge kConfidentialFeeMultiplier extra base fees so the total is + // We charge kCONFIDENTIAL_FEE_MULTIPLIER extra base fees so the total is // 10 * baseFee + (signerCount * baseFee). - return Transactor::calculateBaseFee(view, tx) + view.fees().base * kConfidentialFeeMultiplier; + return Transactor::calculateBaseFee(view, tx) + view.fees().base * kCONFIDENTIAL_FEE_MULTIPLIER; } TER @@ -268,7 +268,7 @@ ConfidentialMPTSend::doApply() auto const mptIssuanceID = ctx_.tx[sfMPTokenIssuanceID]; auto const destination = ctx_.tx[sfDestination]; - auto sleSenderMPToken = view().peek(keylet::mptoken(mptIssuanceID, accountID_)); + auto sleSenderMPToken = view().peek(keylet::mptoken(mptIssuanceID, account_)); auto sleDestinationMPToken = view().peek(keylet::mptoken(mptIssuanceID, destination)); auto const sleDestAcct = view().read(keylet::account(destination)); diff --git a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp index 9453db8aae..fe521d2886 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp @@ -15,6 +15,8 @@ #include #include +#include + namespace xrpl { std::uint32_t @@ -46,7 +48,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // `holderID` is NOT used if (!holderID) { - SLE::const_pointer const sleMpt = + std::shared_ptr const sleMpt = ctx.view.read(keylet::mptoken(ctx.tx[sfMPTokenIssuanceID], accountID)); // There is an edge case where all holders have zero balance, issuance @@ -56,7 +58,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // before fetching the MPTIssuance object. // if holder wants to delete/unauthorize a mpt - if (ctx.tx.isFlag(tfMPTUnauthorize)) + if ((ctx.tx.getFlags() & tfMPTUnauthorize) != 0u) { if (!sleMpt) return tecOBJECT_NOT_FOUND; @@ -129,6 +131,8 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) if (!sleMptIssuance) return tecOBJECT_NOT_FOUND; + std::uint32_t const mptIssuanceFlags = sleMptIssuance->getFieldU32(sfFlags); + // If tx is submitted by issuer, they would either try to do the following // for allowlisting: // 1. authorize an account @@ -141,7 +145,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // If tx is submitted by issuer, it only applies for MPT with // lsfMPTRequireAuth set - if (!sleMptIssuance->isFlag(lsfMPTRequireAuth)) + if ((mptIssuanceFlags & lsfMPTRequireAuth) == 0u) return tecNO_AUTH; // The holder must create the MPT before the issuer can authorize it. @@ -150,9 +154,8 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // Can't unauthorize the pseudo-accounts because they are implicitly // always authorized. No need to amendment gate since Vault and LoanBroker - // can only be created if the Vault amendment is enabled; AMM with MPToken asset - // can only be created if MPTokensV2 is enabled. - if (isPseudoAccount(ctx.view, *holderID, {&sfVaultID, &sfLoanBrokerID, &sfAMMID})) + // can only be created if the Vault amendment is enabled. + if (isPseudoAccount(ctx.view, *holderID, {&sfVaultID, &sfLoanBrokerID})) return tecNO_PERMISSION; return tesSUCCESS; @@ -166,16 +169,18 @@ MPTokenAuthorize::doApply() ctx_.view(), preFeeBalance_, tx[sfMPTokenIssuanceID], - accountID_, + account_, ctx_.journal, tx.getFlags(), tx[~sfHolder]); } void -MPTokenAuthorize::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +MPTokenAuthorize::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -186,7 +191,6 @@ MPTokenAuthorize::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 80c5046b96..69d7c1ef95 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -57,11 +56,6 @@ MPTokenIssuanceCreate::getFlagsMask(PreflightContext const& ctx) NotTEC MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) { - // sfReferenceHolding is set only internally by VaultCreate. Reject - // any user-submitted MPTokenIssuanceCreate that attempts to carry it. - if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx.isFieldPresent(sfReferenceHolding)) - return temMALFORMED; - // If the mutable flags field is included, at least one flag must be // specified. if (auto const mutableFlags = ctx.tx[~sfMutableFlags]; mutableFlags && @@ -70,7 +64,7 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) if (auto const fee = ctx.tx[~sfTransferFee]) { - if (fee > kMaxTransferFee) + if (fee > kMAX_TRANSFER_FEE) return temBAD_TRANSFER_FEE; // If a non-zero TransferFee is set then the tfTransferable flag @@ -85,17 +79,17 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) if (auto const domain = ctx.tx[~sfDomainID]) { - if (*domain == beast::kZero) + if (*domain == beast::kZERO) return temMALFORMED; // Domain present implies that MPTokenIssuance is not public - if (!ctx.tx.isFlag(tfMPTRequireAuth)) + if ((ctx.tx.getFlags() & tfMPTRequireAuth) == 0) return temMALFORMED; } if (auto const metadata = ctx.tx[~sfMPTokenMetadata]) { - if (metadata->empty() || metadata->length() > kMaxMpTokenMetadataLength) + if (metadata->empty() || metadata->length() > kMAX_MP_TOKEN_METADATA_LENGTH) return temMALFORMED; } @@ -105,7 +99,7 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) if (maxAmt == 0) return temMALFORMED; - if (maxAmt > kMaxMpTokenAmount) + if (maxAmt > kMAX_MP_TOKEN_AMOUNT) return temMALFORMED; } return tesSUCCESS; @@ -158,22 +152,6 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate if (args.mutableFlags) (*mptIssuance)[sfMutableFlags] = *args.mutableFlags; - if (args.referenceHolding) - { - // Defensive: the holding must already exist and be of an - // expected type. Callers (currently only VaultCreate) - // populate this after the pseudo-account's MPToken / - // RippleState has been installed. A missing holding here - // would dangle the pointer and is a programmer error. - auto const sleHolding = view.read(keylet::unchecked(*args.referenceHolding)); - if (!sleHolding) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE - auto const type = sleHolding->getType(); - if (type != ltMPTOKEN && type != ltRIPPLE_STATE) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE - (*mptIssuance)[sfReferenceHolding] = *args.referenceHolding; - } - view.insert(mptIssuance); } @@ -192,7 +170,7 @@ MPTokenIssuanceCreate::doApply() j_, { .priorBalance = preFeeBalance_, - .account = accountID_, + .account = account_, .sequence = tx.getSeqValue(), .flags = tx.getFlags(), .maxAmount = tx[~sfMaximumAmount], @@ -206,9 +184,11 @@ MPTokenIssuanceCreate::doApply() } void -MPTokenIssuanceCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +MPTokenIssuanceCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -219,7 +199,6 @@ MPTokenIssuanceCreate::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp index 1029c25813..80b185641a 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp @@ -9,6 +9,8 @@ #include #include +#include + namespace xrpl { NotTEC @@ -43,23 +45,25 @@ TER MPTokenIssuanceDestroy::doApply() { auto const mpt = view().peek(keylet::mptIssuance(ctx_.tx[sfMPTokenIssuanceID])); - if (accountID_ != mpt->getAccountID(sfIssuer)) + if (account_ != mpt->getAccountID(sfIssuer)) return tecINTERNAL; // LCOV_EXCL_LINE - if (!view().dirRemove(keylet::ownerDir(accountID_), (*mpt)[sfOwnerNode], mpt->key(), false)) + if (!view().dirRemove(keylet::ownerDir(account_), (*mpt)[sfOwnerNode], mpt->key(), false)) return tefBAD_LEDGER; // LCOV_EXCL_LINE view().erase(mpt); - adjustOwnerCount(view(), view().peek(keylet::account(accountID_)), -1, j_); + adjustOwnerCount(view(), view().peek(keylet::account(account_)), -1, j_); return tesSUCCESS; } void -MPTokenIssuanceDestroy::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +MPTokenIssuanceDestroy::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -70,7 +74,6 @@ MPTokenIssuanceDestroy::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp index 3190fcaf01..0a4bf80e27 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include namespace xrpl { @@ -54,7 +55,7 @@ struct MPTMutabilityFlags bool isCannotMutate = false; // if true, cannot mutate by default. }; -static constexpr std::array kMptMutabilityFlags = { +static constexpr std::array kMPT_MUTABILITY_FLAGS = { {{.setFlag = tmfMPTSetCanLock, .clearFlag = tmfMPTClearCanLock, .mutabilityFlag = lsmfMPTCanMutateCanLock, @@ -117,7 +118,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return temMALFORMED; // fails if both flags are set - if (ctx.tx.isFlag(tfMPTLock) && ctx.tx.isFlag(tfMPTUnlock)) + if (((txFlags & tfMPTLock) != 0u) && ((txFlags & tfMPTUnlock) != 0u)) return temINVALID_FLAG; auto const accountID = ctx.tx[sfAccount]; @@ -141,13 +142,13 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return temMALFORMED; // Can not set flags when mutating MPTokenIssuance - if (isMutate && ((ctx.tx.getFlags() & tfUniversalMask) != 0u)) + if (isMutate && ((txFlags & tfUniversalMask) != 0u)) return temMALFORMED; - if (transferFee && *transferFee > kMaxTransferFee) + if (transferFee && *transferFee > kMAX_TRANSFER_FEE) return temBAD_TRANSFER_FEE; - if (metadata && metadata->length() > kMaxMpTokenMetadataLength) + if (metadata && metadata->length() > kMAX_MP_TOKEN_METADATA_LENGTH) return temMALFORMED; if (mutableFlags) @@ -156,7 +157,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return temINVALID_FLAG; // Can not set and clear the same flag - if (std::ranges::any_of(kMptMutabilityFlags, [mutableFlags](auto const& f) { + if (std::ranges::any_of(kMPT_MUTABILITY_FLAGS, [mutableFlags](auto const& f) { return (*mutableFlags & f.setFlag) && (*mutableFlags & f.clearFlag); })) return temINVALID_FLAG; @@ -210,18 +211,20 @@ MPTokenIssuanceSet::checkPermission(ReadView const& view, STTx const& tx) if (isTesSuccess(checkTxPermission(sle, tx))) return tesSUCCESS; + auto const txFlags = tx.getFlags(); + // this is added in case more flags will be added for MPTokenIssuanceSet // in the future. Currently unreachable. - if ((tx.getFlags() & tfMPTokenIssuanceSetMask) != 0u) + if ((txFlags & tfMPTokenIssuanceSetMask) != 0u) return terNO_DELEGATE_PERMISSION; // LCOV_EXCL_LINE std::unordered_set granularPermissions; loadGranularPermission(sle, ttMPTOKEN_ISSUANCE_SET, granularPermissions); - if (tx.isFlag(tfMPTLock) && !granularPermissions.contains(MPTokenIssuanceLock)) + if (((txFlags & tfMPTLock) != 0u) && !granularPermissions.contains(MPTokenIssuanceLock)) return terNO_DELEGATE_PERMISSION; - if (tx.isFlag(tfMPTUnlock) && !granularPermissions.contains(MPTokenIssuanceUnlock)) + if (((txFlags & tfMPTUnlock) != 0u) && !granularPermissions.contains(MPTokenIssuanceUnlock)) return terNO_DELEGATE_PERMISSION; return tesSUCCESS; @@ -269,7 +272,7 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) if (not sleMptIssuance->isFlag(lsfMPTRequireAuth)) return tecNO_PERMISSION; - if (*domain != beast::kZero) + if (*domain != beast::kZERO) { auto const sleDomain = ctx.view.read(keylet::permissionedDomain(*domain)); if (!sleDomain) @@ -288,11 +291,12 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) auto const mutableFlags = ctx.tx[~sfMutableFlags]; if (mutableFlags) { - if (std::ranges::any_of(kMptMutabilityFlags, [mutableFlags, &isMutableFlag](auto const& f) { - bool const cannotMutate = f.isCannotMutate ? isMutableFlag(f.mutabilityFlag) - : !isMutableFlag(f.mutabilityFlag); - return cannotMutate && (*mutableFlags & (f.setFlag | f.clearFlag)); - })) + if (std::ranges::any_of( + kMPT_MUTABILITY_FLAGS, [mutableFlags, &isMutableFlag](auto const& f) { + bool const canMutate = f.isCannotMutate ? isMutableFlag(f.mutabilityFlag) + : !isMutableFlag(f.mutabilityFlag); + return canMutate && (*mutableFlags & (f.setFlag | f.clearFlag)); + })) return tecNO_PERMISSION; // Clearing lsfMPTRequireAuth is invalid when the issuance already has @@ -388,9 +392,10 @@ TER MPTokenIssuanceSet::doApply() { auto const mptIssuanceID = ctx_.tx[sfMPTokenIssuanceID]; + auto const txFlags = ctx_.tx.getFlags(); auto const holderID = ctx_.tx[~sfHolder]; auto const domainID = ctx_.tx[~sfDomainID]; - SLE::pointer sle; + std::shared_ptr sle; if (holderID) { @@ -407,18 +412,18 @@ MPTokenIssuanceSet::doApply() std::uint32_t const flagsIn = sle->getFieldU32(sfFlags); std::uint32_t flagsOut = flagsIn; - if (ctx_.tx.isFlag(tfMPTLock)) + if ((txFlags & tfMPTLock) != 0u) { flagsOut |= lsfMPTLocked; } - else if (ctx_.tx.isFlag(tfMPTUnlock)) + else if ((txFlags & tfMPTUnlock) != 0u) { flagsOut &= ~lsfMPTLocked; } if (auto const mutableFlags = ctx_.tx[~sfMutableFlags].value_or(0)) { - for (auto const& f : kMptMutabilityFlags) + for (auto const& f : kMPT_MUTABILITY_FLAGS) { if ((mutableFlags & f.setFlag) != 0u) { @@ -476,7 +481,7 @@ MPTokenIssuanceSet::doApply() sle->getType() == ltMPTOKEN_ISSUANCE, "MPTokenIssuanceSet::doApply : modifying MPTokenIssuance"); - if (*domainID != beast::kZero) + if (*domainID != beast::kZERO) { sle->setFieldH256(sfDomainID, *domainID); } @@ -513,9 +518,11 @@ MPTokenIssuanceSet::doApply() } void -MPTokenIssuanceSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +MPTokenIssuanceSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -526,7 +533,6 @@ MPTokenIssuanceSet::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 1d2bc96693..27252aef46 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -27,6 +27,7 @@ #include #include +#include #include namespace { @@ -77,11 +78,13 @@ TrustSet::preflight(PreflightContext const& ctx) auto& tx = ctx.tx; auto& j = ctx.j; + std::uint32_t const uTxFlags = tx.getFlags(); + if (!ctx.rules.enabled(featureDeepFreeze)) { // Even though the deep freeze flags are included in the // `tfTrustSetMask`, they are not valid if the amendment is not enabled. - if ((tx.getFlags() & (tfSetDeepFreeze | tfClearDeepFreeze)) != 0u) + if ((uTxFlags & (tfSetDeepFreeze | tfClearDeepFreeze)) != 0u) { return temINVALID_FLAG; } @@ -105,7 +108,7 @@ TrustSet::preflight(PreflightContext const& ctx) return temBAD_CURRENCY; } - if (saLimitAmount < beast::kZero) + if (saLimitAmount < beast::kZERO) { JLOG(j.trace()) << "Malformed transaction: Negative credit limit."; return temBAD_LIMIT; @@ -139,10 +142,12 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) if (isTesSuccess(checkTxPermission(sle, tx))) return tesSUCCESS; + std::uint32_t const txFlags = tx.getFlags(); + // Currently we only support TrustlineAuthorize, TrustlineFreeze and // TrustlineUnfreeze granular permission. Setting other flags returns // error. - if ((tx.getFlags() & tfTrustSetPermissionMask) != 0u) + if ((txFlags & tfTrustSetPermissionMask) != 0u) return terNO_DELEGATE_PERMISSION; if (tx.isFieldPresent(sfQualityIn) || tx.isFieldPresent(sfQualityOut)) @@ -161,11 +166,11 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) std::unordered_set granularPermissions; loadGranularPermission(sle, ttTRUST_SET, granularPermissions); - if (tx.isFlag(tfSetfAuth) && !granularPermissions.contains(TrustlineAuthorize)) + if (((txFlags & tfSetfAuth) != 0u) && !granularPermissions.contains(TrustlineAuthorize)) return terNO_DELEGATE_PERMISSION; - if (tx.isFlag(tfSetFreeze) && !granularPermissions.contains(TrustlineFreeze)) + if (((txFlags & tfSetFreeze) != 0u) && !granularPermissions.contains(TrustlineFreeze)) return terNO_DELEGATE_PERMISSION; - if (tx.isFlag(tfClearFreeze) && !granularPermissions.contains(TrustlineUnfreeze)) + if (((txFlags & tfClearFreeze) != 0u) && !granularPermissions.contains(TrustlineUnfreeze)) return terNO_DELEGATE_PERMISSION; // updating LimitAmount is not allowed only with granular permissions, @@ -192,9 +197,11 @@ TrustSet::preclaim(PreclaimContext const& ctx) if (!sle) return terNO_ACCOUNT; - bool const bSetAuth = ctx.tx.isFlag(tfSetfAuth); + std::uint32_t const uTxFlags = ctx.tx.getFlags(); - if (bSetAuth && !sle->isFlag(lsfRequireAuth)) + bool const bSetAuth = (uTxFlags & tfSetfAuth) != 0u; + + if (bSetAuth && ((sle->getFieldU32(sfFlags) & lsfRequireAuth) == 0u)) { JLOG(ctx.j.trace()) << "Retry: Auth not required."; return tefNO_AUTH_REQUIRED; @@ -216,7 +223,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) // If the destination has opted to disallow incoming trustlines // then honour that flag - if (sleDst->isFlag(lsfDisallowIncomingTrustline)) + if ((sleDst->getFlags() & lsfDisallowIncomingTrustline) != 0u) { // The original implementation of featureDisallowIncoming was // too restrictive. If @@ -251,7 +258,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) else if (auto const ammSle = ctx.view.read({ltAMM, sleDst->getFieldH256(sfAMMID)})) { auto const lpTokens = ammSle->getFieldAmount(sfLPTokenBalance); - if (lpTokens == beast::kZero) + if (lpTokens == beast::kZERO) { return tecAMM_EMPTY; } @@ -281,8 +288,8 @@ TrustSet::preclaim(PreclaimContext const& ctx) if (ctx.view.rules().enabled(featureDeepFreeze)) { bool const bNoFreeze = sle->isFlag(lsfNoFreeze); - bool const bSetFreeze = ctx.tx.isFlag(tfSetFreeze); - bool const bSetDeepFreeze = ctx.tx.isFlag(tfSetDeepFreeze); + bool const bSetFreeze = (uTxFlags & tfSetFreeze) != 0u; + bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; if (bNoFreeze && (bSetFreeze || bSetDeepFreeze)) { @@ -290,8 +297,8 @@ TrustSet::preclaim(PreclaimContext const& ctx) return tecNO_PERMISSION; } - bool const bClearFreeze = ctx.tx.isFlag(tfClearFreeze); - bool const bClearDeepFreeze = ctx.tx.isFlag(tfClearDeepFreeze); + bool const bClearFreeze = (uTxFlags & tfClearFreeze) != 0u; + bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; if ((bSetFreeze || bSetDeepFreeze) && (bClearFreeze || bClearDeepFreeze)) { // Freezing and unfreezing in the same transaction should be @@ -335,9 +342,9 @@ TrustSet::doApply() AccountID const uDstAccountID(saLimitAmount.getIssuer()); // true, if current is high account. - bool const bHigh = accountID_ > uDstAccountID; + bool const bHigh = account_ > uDstAccountID; - auto const sle = view().peek(keylet::account(accountID_)); + auto const sle = view().peek(keylet::account(account_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -362,7 +369,7 @@ TrustSet::doApply() // could use the extra XRP for their own purposes. XRPAmount const reserveCreate( - (uOwnerCount < 2) ? XRPAmount(beast::kZero) + (uOwnerCount < 2) ? XRPAmount(beast::kZERO) : view().fees().accountReserve(uOwnerCount + 1)); std::uint32_t const uQualityIn(bQualityIn ? ctx_.tx.getFieldU32(sfQualityIn) : 0); @@ -371,13 +378,15 @@ TrustSet::doApply() if (bQualityOut && QUALITY_ONE == uQualityOut) uQualityOut = 0; - bool const bSetAuth = ctx_.tx.isFlag(tfSetfAuth); - bool const bSetNoRipple = ctx_.tx.isFlag(tfSetNoRipple); - bool const bClearNoRipple = ctx_.tx.isFlag(tfClearNoRipple); - bool const bSetFreeze = ctx_.tx.isFlag(tfSetFreeze); - bool const bClearFreeze = ctx_.tx.isFlag(tfClearFreeze); - bool const bSetDeepFreeze = ctx_.tx.isFlag(tfSetDeepFreeze); - bool const bClearDeepFreeze = ctx_.tx.isFlag(tfClearDeepFreeze); + std::uint32_t const uTxFlags = ctx_.tx.getFlags(); + + bool const bSetAuth = (uTxFlags & tfSetfAuth) != 0u; + bool const bSetNoRipple = (uTxFlags & tfSetNoRipple) != 0u; + bool const bClearNoRipple = (uTxFlags & tfClearNoRipple) != 0u; + bool const bSetFreeze = (uTxFlags & tfSetFreeze) != 0u; + bool const bClearFreeze = (uTxFlags & tfClearFreeze) != 0u; + bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; + bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; auto viewJ = ctx_.registry.get().getJournal("View"); @@ -390,10 +399,10 @@ TrustSet::doApply() } STAmount saLimitAllow = saLimitAmount; - saLimitAllow.get().account = accountID_; + saLimitAllow.get().account = account_; SLE::pointer const sleRippleState = - view().peek(keylet::line(accountID_, uDstAccountID, currency)); + view().peek(keylet::line(account_, uDstAccountID, currency)); if (sleRippleState) { @@ -405,8 +414,8 @@ TrustSet::doApply() std::uint32_t uLowQualityOut = 0; std::uint32_t uHighQualityIn = 0; std::uint32_t uHighQualityOut = 0; - auto const& uLowAccountID = !bHigh ? accountID_ : uDstAccountID; - auto const& uHighAccountID = bHigh ? accountID_ : uDstAccountID; + auto const& uLowAccountID = !bHigh ? account_ : uDstAccountID; + auto const& uHighAccountID = bHigh ? account_ : uDstAccountID; SLE::ref sleLowAccount = !bHigh ? sle : sleDst; SLE::ref sleHighAccount = bHigh ? sle : sleDst; @@ -497,7 +506,7 @@ TrustSet::doApply() if (bSetNoRipple && !bClearNoRipple) { - if ((bHigh ? saHighBalance : saLowBalance) >= beast::kZero) + if ((bHigh ? saHighBalance : saLowBalance) >= beast::kZERO) { uFlagsOut |= (bHigh ? lsfHighNoRipple : lsfLowNoRipple); } @@ -529,23 +538,23 @@ TrustSet::doApply() if (QUALITY_ONE == uHighQualityOut) uHighQualityOut = 0; - bool const bLowDefRipple = sleLowAccount->isFlag(lsfDefaultRipple); - bool const bHighDefRipple = sleHighAccount->isFlag(lsfDefaultRipple); + bool const bLowDefRipple = (sleLowAccount->getFlags() & lsfDefaultRipple) != 0u; + bool const bHighDefRipple = (sleHighAccount->getFlags() & lsfDefaultRipple) != 0u; bool const bLowReserveSet = (uLowQualityIn != 0u) || (uLowQualityOut != 0u) || ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || - ((uFlagsOut & lsfLowFreeze) != 0u) || saLowLimit || saLowBalance > beast::kZero; + ((uFlagsOut & lsfLowFreeze) != 0u) || saLowLimit || saLowBalance > beast::kZERO; bool const bLowReserveClear = !bLowReserveSet; bool const bHighReserveSet = (uHighQualityIn != 0u) || (uHighQualityOut != 0u) || ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || - ((uFlagsOut & lsfHighFreeze) != 0u) || saHighLimit || saHighBalance > beast::kZero; + ((uFlagsOut & lsfHighFreeze) != 0u) || saHighLimit || saHighBalance > beast::kZERO; bool const bHighReserveClear = !bHighReserveSet; bool const bDefault = bLowReserveClear && bHighReserveClear; - bool const bLowReserved = sleRippleState->isFlag(lsfLowReserve); - bool const bHighReserved = sleRippleState->isFlag(lsfHighReserve); + bool const bLowReserved = (uFlagsIn & lsfLowReserve) != 0u; + bool const bHighReserved = (uFlagsIn & lsfHighReserve) != 0u; bool bReserveIncrease = false; @@ -641,7 +650,7 @@ TrustSet::doApply() // Zero balance in currency. STAmount const saBalance(Issue{currency, noAccount()}); - auto const k = keylet::line(accountID_, uDstAccountID, currency); + auto const k = keylet::line(account_, uDstAccountID, currency); JLOG(j_.trace()) << "doTrustSet: Creating ripple line: " << to_string(k.key); @@ -649,7 +658,7 @@ TrustSet::doApply() terResult = trustCreate( view(), bHigh, - accountID_, + account_, uDstAccountID, k.key, sle, @@ -668,15 +677,16 @@ TrustSet::doApply() } void -TrustSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +TrustSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool TrustSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index eb12905467..8743227e5c 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -26,6 +26,8 @@ #include #include +#include +#include #include #include #include @@ -34,7 +36,7 @@ namespace xrpl { NotTEC VaultClawback::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfVaultID] == beast::kZero) + if (ctx.tx[sfVaultID] == beast::kZERO) { JLOG(ctx.j.debug()) << "VaultClawback: zero/empty vault ID."; return temMALFORMED; @@ -44,7 +46,7 @@ VaultClawback::preflight(PreflightContext const& ctx) if (amount) { // Note, zero amount is valid, it means "all". It is also the default. - if (*amount < beast::kZero) + if (*amount < beast::kZERO) { return temBAD_AMOUNT; } @@ -60,7 +62,7 @@ VaultClawback::preflight(PreflightContext const& ctx) [[nodiscard]] STAmount clawbackAmount( - SLE::const_ref vault, + std::shared_ptr const& vault, std::optional const& maybeAmount, AccountID const& account) { @@ -132,7 +134,7 @@ VaultClawback::preclaim(PreclaimContext const& ctx) } // If amount is non-zero, the VaultOwner must burn all shares - if (amount != beast::kZero) + if (amount != beast::kZERO) { Number const& sharesHeld = accountHolds( ctx.view, @@ -184,7 +186,8 @@ VaultClawback::preclaim(PreclaimContext const& ctx) if (mptIssue == nullptr) return tecOBJECT_NOT_FOUND; - if (!mptIssue->isFlag(lsfMPTCanClawback)) + std::uint32_t const issueFlags = mptIssue->getFieldU32(sfFlags); + if ((issueFlags & lsfMPTCanClawback) == 0u) { JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " "MPT vault asset."; @@ -203,7 +206,9 @@ VaultClawback::preclaim(PreclaimContext const& ctx) // LCOV_EXCL_STOP } - if (!issuerSle->isFlag(lsfAllowTrustLineClawback) || issuerSle->isFlag(lsfNoFreeze)) + std::uint32_t const issuerFlags = issuerSle->getFieldU32(sfFlags); + if (((issuerFlags & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlags & lsfNoFreeze) != 0u)) { JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " "IOU vault asset."; @@ -220,8 +225,8 @@ VaultClawback::preclaim(PreclaimContext const& ctx) Expected, TER> VaultClawback::assetsToClawback( - SLE::ref vault, - SLE::const_ref sleShareIssuance, + std::shared_ptr const& vault, + std::shared_ptr const& sleShareIssuance, AccountID const& holder, STAmount const& clawbackAmount) { @@ -238,11 +243,11 @@ VaultClawback::assetsToClawback( auto const mptIssuanceID = *vault->at(sfShareMPTID); MPTIssue const share{mptIssuanceID}; - // Pre-fixCleanup3_1_3: zero-amount clawback returned early without + // Pre-fixSecurity3_1_3: zero-amount clawback returned early without // clamping to assetsAvailable, allowing more assets to be recovered // than available when there was an outstanding loan. Retained for // ledger replay compatibility. - if (!ctx_.view().rules().enabled(fixCleanup3_1_3) && clawbackAmount == beast::kZero) + if (!ctx_.view().rules().enabled(fixSecurity3_1_3) && clawbackAmount == beast::kZERO) { auto const sharesDestroyed = accountHolds( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); @@ -258,7 +263,7 @@ VaultClawback::assetsToClawback( try { - if (clawbackAmount == beast::kZero) + if (clawbackAmount == beast::kZERO) { sharesDestroyed = accountHolds( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); @@ -348,7 +353,7 @@ VaultClawback::doApply() MPTIssue const share{mptIssuanceID}; Asset const vaultAsset = vault->at(sfAsset); - STAmount const amount = clawbackAmount(vault, tx[~sfAmount], accountID_); + STAmount const amount = clawbackAmount(vault, tx[~sfAmount], account_); auto assetsAvailable = vault->at(sfAssetsAvailable); auto assetsTotal = vault->at(sfAssetsTotal); @@ -363,7 +368,7 @@ VaultClawback::doApply() STAmount assetsRecovered = {vault->at(sfAsset)}; // The Owner is burning shares - if (accountID_ == vault->at(sfOwner) && amount.asset() == share) + if (account_ == vault->at(sfOwner) && amount.asset() == share) { sharesDestroyed = accountHolds( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); @@ -380,7 +385,7 @@ VaultClawback::doApply() sharesDestroyed = clawbackParts->second; } - if (sharesDestroyed == beast::kZero) + if (sharesDestroyed == beast::kZERO) return tecPRECISION_LOSS; assetsTotal -= assetsRecovered; @@ -421,11 +426,11 @@ VaultClawback::doApply() // else quietly ignore, holder balance is not zero } - if (assetsRecovered > beast::kZero) + if (assetsRecovered > beast::kZERO) { // Transfer assets from vault to issuer. if (auto const ter = accountSend( - view(), vaultAccount, accountID_, assetsRecovered, j_, WaiveTransferFee::Yes); + view(), vaultAccount, account_, assetsRecovered, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; @@ -436,7 +441,7 @@ VaultClawback::doApply() assetsRecovered.asset(), FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, - j_) < beast::kZero) + j_) < beast::kZERO) { // LCOV_EXCL_START JLOG(j_.error()) << "VaultClawback: negative balance of vault assets."; @@ -451,9 +456,11 @@ VaultClawback::doApply() } void -VaultClawback::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultClawback::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -464,7 +471,6 @@ VaultClawback::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index 4163753014..0346503ae7 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -1,14 +1,12 @@ #include #include -#include #include #include #include #include #include #include -#include #include #include #include @@ -54,23 +52,23 @@ VaultCreate::getFlagsMask(PreflightContext const& ctx) NotTEC VaultCreate::preflight(PreflightContext const& ctx) { - if (!validDataLength(ctx.tx[~sfData], kMaxDataPayloadLength)) + if (!validDataLength(ctx.tx[~sfData], kMAX_DATA_PAYLOAD_LENGTH)) return temMALFORMED; if (auto const withdrawalPolicy = ctx.tx[~sfWithdrawalPolicy]) { // Enforce valid withdrawal policy - if (*withdrawalPolicy != kVaultStrategyFirstComeFirstServe) + if (*withdrawalPolicy != kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE) return temMALFORMED; } if (auto const domain = ctx.tx[~sfDomainID]) { - if (*domain == beast::kZero) + if (*domain == beast::kZERO) { return temMALFORMED; } - if (!ctx.tx.isFlag(tfVaultPrivate)) + if ((ctx.tx.getFlags() & tfVaultPrivate) == 0) { return temMALFORMED; // DomainID only allowed on private vaults } @@ -78,13 +76,13 @@ VaultCreate::preflight(PreflightContext const& ctx) if (auto const assetMax = ctx.tx[~sfAssetsMaximum]) { - if (*assetMax < beast::kZero) + if (*assetMax < beast::kZERO) return temMALFORMED; } if (auto const metadata = ctx.tx[~sfMPTokenMetadata]) { - if (metadata->empty() || metadata->length() > kMaxMpTokenMetadataLength) + if (metadata->empty() || metadata->length() > kMAX_MP_TOKEN_METADATA_LENGTH) return temMALFORMED; } @@ -94,7 +92,7 @@ VaultCreate::preflight(PreflightContext const& ctx) if (vaultAsset.holds() || vaultAsset.native()) return temMALFORMED; - if (scale > kVaultMaximumIouScale) + if (scale > kVAULT_MAXIMUM_IOU_SCALE) return temMALFORMED; } @@ -132,7 +130,7 @@ VaultCreate::preclaim(PreclaimContext const& ctx) auto const sequence = ctx.tx.getSeqValue(); if (auto const accountId = pseudoAccountAddress(ctx.view, keylet::vault(account, sequence).key); - accountId == beast::kZero) + accountId == beast::kZERO) return terADDRESS_COLLISION; return tesSUCCESS; @@ -147,13 +145,13 @@ VaultCreate::doApply() auto const& tx = ctx_.tx; auto const sequence = tx.getSeqValue(); - auto const owner = view().peek(keylet::account(accountID_)); + auto const owner = view().peek(keylet::account(account_)); if (owner == nullptr) return tefINTERNAL; // LCOV_EXCL_LINE - auto vault = std::make_shared(keylet::vault(accountID_, sequence)); + auto vault = std::make_shared(keylet::vault(account_, sequence)); - if (auto ter = dirLink(view(), accountID_, vault)) + if (auto ter = dirLink(view(), account_, vault)) return ter; // We will create Vault and PseudoAccount, hence increase OwnerCount by 2 adjustOwnerCount(view(), owner, 2, j_); @@ -164,44 +162,34 @@ VaultCreate::doApply() auto maybePseudo = createPseudoAccount(view(), vault->key(), sfVaultID); if (!maybePseudo) return maybePseudo.error(); // LCOV_EXCL_LINE - auto const& pseudo = *maybePseudo; - AccountID const pseudoId = pseudo->at(sfAccount); - auto const asset = tx[sfAsset]; + auto& pseudo = *maybePseudo; + auto pseudoId = pseudo->at(sfAccount); + auto asset = tx[sfAsset]; if (auto ter = addEmptyHolding(view(), pseudoId, preFeeBalance_, asset, j_); !isTesSuccess(ter)) return ter; std::uint8_t const scale = (asset.holds() || asset.native()) ? 0 - : ctx_.tx[~sfScale].value_or(kVaultDefaultIouScale); + : ctx_.tx[~sfScale].value_or(kVAULT_DEFAULT_IOU_SCALE); + auto txFlags = tx.getFlags(); std::uint32_t mptFlags = 0; - if (!tx.isFlag(tfVaultShareNonTransferable)) + if ((txFlags & tfVaultShareNonTransferable) == 0) mptFlags |= (lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer); - if (tx.isFlag(tfVaultPrivate)) + if ((txFlags & tfVaultPrivate) != 0u) mptFlags |= lsfMPTRequireAuth; // Note, here we are **not** creating an MPToken for the assets held in // the vault. That MPToken or TrustLine/RippleState is created above, in // addEmptyHolding. Here we are creating MPTokenIssuance for the shares - // in the vault. - // - // Post-fixCleanup3_2_0: surface the vault pseudo's holding (MPToken - // for MPT, RippleState for IOU) on the share via sfReferenceHolding. - // XRP underlyings leave it unset. - auto const referenceHolding = [&]() -> std::optional { - if (!view().rules().enabled(fixCleanup3_2_0) || asset.native()) - return std::nullopt; - return asset.holds() - ? keylet::mptoken(asset.get().getMptID(), pseudoId).key - : keylet::line(pseudoId, asset.get()).key; - }(); - auto const maybeShare = MPTokenIssuanceCreate::create( + // in the vault + auto maybeShare = MPTokenIssuanceCreate::create( view(), j_, { .priorBalance = std::nullopt, - .account = pseudoId, + .account = pseudoId->value(), .sequence = 1, .flags = mptFlags, .assetScale = scale, @@ -209,16 +197,15 @@ VaultCreate::doApply() .metadata = tx[~sfMPTokenMetadata], .domainId = tx[~sfDomainID], .mutableFlags = std::nullopt, - .referenceHolding = referenceHolding, }); if (!maybeShare) return maybeShare.error(); // LCOV_EXCL_LINE auto const& mptIssuanceID = *maybeShare; vault->setFieldIssue(sfAsset, STIssue{sfAsset, asset}); - vault->at(sfFlags) = tx.getFlags() & tfVaultPrivate; + vault->at(sfFlags) = txFlags & tfVaultPrivate; vault->at(sfSequence) = sequence; - vault->at(sfOwner) = accountID_; + vault->at(sfOwner) = account_; vault->at(sfAccount) = pseudoId; vault->at(sfAssetsTotal) = Number(0); vault->at(sfAssetsAvailable) = Number(0); @@ -236,7 +223,7 @@ VaultCreate::doApply() } else { - vault->at(sfWithdrawalPolicy) = kVaultStrategyFirstComeFirstServe; + vault->at(sfWithdrawalPolicy) = kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE; } if (scale != 0u) vault->at(sfScale) = scale; @@ -244,15 +231,15 @@ VaultCreate::doApply() // Explicitly create MPToken for the vault owner if (auto const err = - authorizeMPToken(view(), preFeeBalance_, mptIssuanceID, accountID_, ctx_.journal); + authorizeMPToken(view(), preFeeBalance_, mptIssuanceID, account_, ctx_.journal); !isTesSuccess(err)) return err; // If the vault is private, set the authorized flag for the vault owner - if (tx.isFlag(tfVaultPrivate)) + if ((txFlags & tfVaultPrivate) != 0u) { if (auto const err = authorizeMPToken( - view(), preFeeBalance_, mptIssuanceID, pseudoId, ctx_.journal, {}, accountID_); + view(), preFeeBalance_, mptIssuanceID, pseudoId, ctx_.journal, {}, account_); !isTesSuccess(err)) return err; } @@ -263,15 +250,16 @@ VaultCreate::doApply() } void -VaultCreate::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultCreate::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool VaultCreate::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp index 030a7e971c..58b0fdee82 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp @@ -17,12 +17,14 @@ #include #include +#include + namespace xrpl { NotTEC VaultDelete::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfVaultID] == beast::kZero) + if (ctx.tx[sfVaultID] == beast::kZERO) { JLOG(ctx.j.debug()) << "VaultDelete: zero/empty vault ID."; return temMALFORMED; @@ -120,16 +122,16 @@ VaultDelete::doApply() } // Try to remove MPToken for vault shares for the vault owner if it exists. - if (auto const mptoken = view().peek(keylet::mptoken(shareMPTID, accountID_))) + if (auto const mptoken = view().peek(keylet::mptoken(shareMPTID, account_))) { - if (auto const ter = removeEmptyHolding(view(), accountID_, MPTIssue(shareMPTID), j_); + if (auto const ter = removeEmptyHolding(view(), account_, MPTIssue(shareMPTID), j_); !isTesSuccess(ter)) { // LCOV_EXCL_START JLOG(j_.error()) // << "VaultDelete: failed to remove vault owner's MPToken" - << " MPTID=" << to_string(shareMPTID) // - << " account=" << toBase58(accountID_) // + << " MPTID=" << to_string(shareMPTID) // + << " account=" << toBase58(account_) // << " with result: " << transToken(ter); return ter; // LCOV_EXCL_STOP @@ -211,15 +213,16 @@ VaultDelete::doApply() } void -VaultDelete::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultDelete::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool VaultDelete::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index c08d1e957c..501ba58ca5 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -1,20 +1,17 @@ #include #include -#include #include #include #include #include #include #include -#include #include #include #include #include #include -#include #include #include // IWYU pragma: keep #include @@ -23,38 +20,21 @@ #include #include +#include #include namespace xrpl { -[[nodiscard]] -static STAmount -roundToVaultScale(STAmount const& amount, SLE::const_ref vault) -{ - XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::roundToVaultScale : valid vault sle"); - XRPL_ASSERT( - amount.asset() == vault->at(sfAsset), "xrpl::roundToVaultScale : valid vault asset"); - - if (amount.integral()) - return amount; - - int const postScale = [&]() { - NumberRoundModeGuard const rg(Number::RoundingMode::ToNearest); - return scale(vault->at(sfAssetsTotal) + amount, vault->at(sfAsset)); - }(); - return roundToScale(amount, postScale, Number::RoundingMode::Downward); -} - NotTEC VaultDeposit::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfVaultID] == beast::kZero) + if (ctx.tx[sfVaultID] == beast::kZERO) { JLOG(ctx.j.debug()) << "VaultDeposit: zero/empty vault ID."; return temMALFORMED; } - if (ctx.tx[sfAmount] <= beast::kZero) + if (ctx.tx[sfAmount] <= beast::kZERO) return temBAD_AMOUNT; return tesSUCCESS; @@ -68,9 +48,9 @@ VaultDeposit::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; auto const& account = ctx.tx[sfAccount]; - auto const amount = ctx.tx[sfAmount]; + auto const assets = ctx.tx[sfAmount]; auto const vaultAsset = vault->at(sfAsset); - if (amount.asset() != vaultAsset) + if (assets.asset() != vaultAsset) return tecWRONG_ASSET; auto const& vaultAccount = vault->at(sfAccount); @@ -82,7 +62,7 @@ VaultDeposit::preclaim(PreclaimContext const& ctx) auto const mptIssuanceID = vault->at(sfShareMPTID); auto const vaultShare = MPTIssue(mptIssuanceID); - if (vaultShare == amount.asset()) + if (vaultShare == assets.asset()) { // LCOV_EXCL_START JLOG(ctx.j.error()) << "VaultDeposit: vault shares and assets cannot be same."; @@ -141,69 +121,28 @@ VaultDeposit::preclaim(PreclaimContext const& ctx) if (auto const ter = requireAuth(ctx.view, vaultAsset, account); !isTesSuccess(ter)) return ter; - bool const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0); - auto const roundedAmount = fix320Enabled ? roundToVaultScale(amount, vault) : amount; - - if (fix320Enabled && roundedAmount == beast::kZero) - { - JLOG(ctx.j.warn()) << "VaultDeposit: deposit amount: " << ctx.tx[sfAmount] - << " is zero at vault scale"; - return tecPRECISION_LOSS; - } - - auto const accountBalance = accountHolds( - ctx.view, - account, - vaultAsset, - FreezeHandling::ZeroIfFrozen, - AuthHandling::ZeroIfUnauthorized, - ctx.j, - SpendableHandling::FullBalance); - - if (accountBalance < roundedAmount) + if (accountHolds( + ctx.view, + account, + vaultAsset, + FreezeHandling::ZeroIfFrozen, + AuthHandling::ZeroIfUnauthorized, + ctx.j, + SpendableHandling::FullBalance) < assets) return tecINSUFFICIENT_FUNDS; - // IOU precision checks - if (fix320Enabled && !roundedAmount.integral()) - { - // reject deposits that would canonicalize to a no-op at the depositor's trustline scale. - // Skipped for issuer-as-depositor: accountHolds returns (kMaxValue @ kMaxOffset) which - // would always trip the predicate. - if (account != amount.getIssuer() && - amount.isZeroAtScale(scale(accountBalance, vaultAsset))) - { - JLOG(ctx.j.warn()) << "VaultDeposit: amount " << amount.getFullText() - << " rounds to zero at counterparty trust-line scale"; - return tecPRECISION_LOSS; - } - } - return tesSUCCESS; } TER VaultDeposit::doApply() { - bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0); auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID])); if (!vault) return tefINTERNAL; // LCOV_EXCL_LINE auto const vaultAsset = vault->at(sfAsset); - // Post-amendment IOU only: round Downward to the AssetsTotal precision so - // a sub-ULP tail can't be silently absorbed by one rail and not the other. - auto const amount = - fix320Enabled ? roundToVaultScale(ctx_.tx[sfAmount], vault) : ctx_.tx[sfAmount]; - - // We validated zero-amount in preclaim, if we ended up with zero now, fail hard. - if (amount == beast::kZero) - { - // LCOV_EXCL_START - JLOG(j_.error()) << "VaultDeposit: deposit amount: " << ctx_.tx[sfAmount] << " is zero"; - return tecINTERNAL; - // LCOV_EXCL_STOP - } - + auto const amount = ctx_.tx[sfAmount]; // Make sure the depositor can hold shares. auto const mptIssuanceID = (*vault)[sfShareMPTID]; auto const sleIssuance = view().read(keylet::mptIssuance(mptIssuanceID)); @@ -217,20 +156,20 @@ VaultDeposit::doApply() auto const& vaultAccount = vault->at(sfAccount); // Note, vault owner is always authorized - if (vault->isFlag(lsfVaultPrivate) && accountID_ != vault->at(sfOwner)) + if (vault->isFlag(lsfVaultPrivate) && account_ != vault->at(sfOwner)) { if (auto const err = enforceMPTokenAuthorization( - ctx_.view(), mptIssuanceID, accountID_, preFeeBalance_, j_); + ctx_.view(), mptIssuanceID, account_, preFeeBalance_, j_); !isTesSuccess(err)) return err; } - else // !vault->isFlag(lsfVaultPrivate) || accountID_ == vault->at(sfOwner) + else // !vault->isFlag(lsfVaultPrivate) || account_ == vault->at(sfOwner) { // No authorization needed, but must ensure there is MPToken - if (!view().exists(keylet::mptoken(mptIssuanceID, accountID_))) + if (!view().exists(keylet::mptoken(mptIssuanceID, account_))) { if (auto const err = authorizeMPToken( - view(), preFeeBalance_, mptIssuanceID->value(), accountID_, ctx_.journal); + view(), preFeeBalance_, mptIssuanceID->value(), account_, ctx_.journal); !isTesSuccess(err)) return err; } @@ -240,15 +179,15 @@ VaultDeposit::doApply() { // This follows from the reverse of the outer enclosing if condition XRPL_ASSERT( - accountID_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); + account_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); if (auto const err = authorizeMPToken( view(), preFeeBalance_, // priorBalance mptIssuanceID->value(), // mptIssuanceID sleIssuance->at(sfIssuer), // account ctx_.journal, - {}, // flags - accountID_ // holderID + {}, // flags + account_ // holderID ); !isTesSuccess(err)) return err; @@ -265,7 +204,7 @@ VaultDeposit::doApply() return tecINTERNAL; // LCOV_EXCL_LINE sharesCreated = *maybeShares; } - if (sharesCreated == beast::kZero) + if (sharesCreated == beast::kZERO) return tecPRECISION_LOSS; auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated); @@ -308,36 +247,29 @@ VaultDeposit::doApply() return tecLIMIT_EXCEEDED; // Transfer assets from depositor to vault. - if (auto const ter = accountSend( - view(), accountID_, vaultAccount, assetsDeposited, j_, WaiveTransferFee::Yes); + if (auto const ter = + accountSend(view(), account_, vaultAccount, assetsDeposited, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; - // This check is wrong. Disable it with fixCleanup3_2_0. - // For XRP and MPT the predicate is structurally unsatisfiable: xrpLiquid clamps at zero, and - // MPT balances are unsigned. For IOUs it only fires when the deposit drove the depositor's - // trust line into debt the exact case preclaim authorizes via SpendableHandling::FullBalance. - // The check thus converts a preclaim- authorized deposit into tefINTERNAL after the asset - // transfer. - if (!fix320Enabled) + // Sanity check + if (accountHolds( + view(), + account_, + assetsDeposited.asset(), + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_) < beast::kZERO) { - // Sanity check - if (accountHolds( - view(), - accountID_, - assetsDeposited.asset(), - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_) < beast::kZero) - { - JLOG(j_.error()) << "VaultDeposit: negative balance of account assets."; - return tefINTERNAL; - } + // LCOV_EXCL_START + JLOG(j_.error()) << "VaultDeposit: negative balance of account assets."; + return tefINTERNAL; + // LCOV_EXCL_STOP } // Transfer shares from vault to depositor. if (auto const ter = - accountSend(view(), vaultAccount, accountID_, sharesCreated, j_, WaiveTransferFee::Yes); + accountSend(view(), vaultAccount, account_, sharesCreated, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; @@ -347,9 +279,11 @@ VaultDeposit::doApply() } void -VaultDeposit::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultDeposit::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -360,7 +294,6 @@ VaultDeposit::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultSet.cpp b/src/libxrpl/tx/transactors/vault/VaultSet.cpp index 6d0ade6e52..92dbb198f3 100644 --- a/src/libxrpl/tx/transactors/vault/VaultSet.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultSet.cpp @@ -15,6 +15,8 @@ #include #include +#include + namespace xrpl { bool @@ -26,7 +28,7 @@ VaultSet::checkExtraFeatures(PreflightContext const& ctx) NotTEC VaultSet::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfVaultID] == beast::kZero) + if (ctx.tx[sfVaultID] == beast::kZERO) { JLOG(ctx.j.debug()) << "VaultSet: zero/empty vault ID."; return temMALFORMED; @@ -34,7 +36,7 @@ VaultSet::preflight(PreflightContext const& ctx) if (auto const data = ctx.tx[~sfData]) { - if (data->empty() || data->length() > kMaxDataPayloadLength) + if (data->empty() || data->length() > kMAX_DATA_PAYLOAD_LENGTH) { JLOG(ctx.j.debug()) << "VaultSet: invalid data payload size."; return temMALFORMED; @@ -43,7 +45,7 @@ VaultSet::preflight(PreflightContext const& ctx) if (auto const assetMax = ctx.tx[~sfAssetsMaximum]) { - if (*assetMax < beast::kZero) + if (*assetMax < beast::kZERO) { JLOG(ctx.j.debug()) << "VaultSet: invalid max assets."; return temMALFORMED; @@ -93,7 +95,7 @@ VaultSet::preclaim(PreclaimContext const& ctx) return tecNO_PERMISSION; } - if (*domain != beast::kZero) + if (*domain != beast::kZERO) { auto const sleDomain = ctx.view.read(keylet::permissionedDomain(*domain)); if (!sleDomain) @@ -101,7 +103,7 @@ VaultSet::preclaim(PreclaimContext const& ctx) } // Sanity check only, this should be enforced by VaultCreate - if (!sleIssuance->isFlag(lsfMPTRequireAuth)) + if ((sleIssuance->getFlags() & lsfMPTRequireAuth) == 0) { // LCOV_EXCL_START JLOG(ctx.j.error()) << "VaultSet: issuance of vault shares is not private."; @@ -151,7 +153,7 @@ VaultSet::doApply() if (auto const domainId = tx[~sfDomainID]; domainId) { - if (*domainId != beast::kZero) + if (*domainId != beast::kZERO) { // In VaultSet::preclaim we enforce that lsfVaultPrivate must have // been set in the vault. We currently do not support making such a @@ -178,15 +180,16 @@ VaultSet::doApply() } void -VaultSet::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultSet::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool VaultSet::finalizeInvariants(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index cfcf79fdba..6932dc21f2 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -4,14 +4,12 @@ #include #include #include -#include #include #include #include #include #include #include -#include #include #include #include @@ -23,37 +21,26 @@ #include #include +#include #include namespace xrpl { -static WaiveUnrealizedLoss -shouldWaiveWithdrawal(ReadView const& view, AccountID const& account, SLE::const_ref issuance) -{ - XRPL_ASSERT( - issuance && issuance->getType() == ltMPTOKEN_ISSUANCE, - "xrpl::shouldWaiveWithdrawal : valid issuance sle"); - - return view.rules().enabled(fixCleanup3_2_0) && isSoleShareholder(view, account, issuance) - ? WaiveUnrealizedLoss::Yes - : WaiveUnrealizedLoss::No; -} - NotTEC VaultWithdraw::preflight(PreflightContext const& ctx) { - if (ctx.tx[sfVaultID] == beast::kZero) + if (ctx.tx[sfVaultID] == beast::kZERO) { JLOG(ctx.j.debug()) << "VaultWithdraw: zero/empty vault ID."; return temMALFORMED; } - if (ctx.tx[sfAmount] <= beast::kZero) + if (ctx.tx[sfAmount] <= beast::kZERO) return temBAD_AMOUNT; if (auto const destination = ctx.tx[~sfDestination]) { - if (*destination == beast::kZero) + if (*destination == beast::kZERO) { return temMALFORMED; } @@ -78,21 +65,14 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) auto const& vaultAccount = vault->at(sfAccount); auto const& account = ctx.tx[sfAccount]; auto const& dstAcct = ctx.tx[~sfDestination].value_or(account); - // Post-fixCleanup3_2_0: withdraw is a recovery path that bypasses the - // lsfMPTCanTransfer flag check, so an issuer cannot trap depositor funds. - // Other transferability checks (IOU NoRipple, freeze, requireAuth) still - // apply. - auto const waive = ctx.view.rules().enabled(fixCleanup3_2_0) ? WaiveMPTCanTransfer::Yes - : WaiveMPTCanTransfer::No; - if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct, waive); - !isTesSuccess(ter)) + if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct); !isTesSuccess(ter)) { JLOG(ctx.j.debug()) << "VaultWithdraw: vault assets are non-transferable."; return ter; } // Enforce valid withdrawal policy - if (vault->at(sfWithdrawalPolicy) != kVaultStrategyFirstComeFirstServe) + if (vault->at(sfWithdrawalPolicy) != kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE) { // LCOV_EXCL_START JLOG(ctx.j.error()) << "VaultWithdraw: invalid withdrawal policy."; @@ -100,9 +80,9 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) // LCOV_EXCL_STOP } - if (ctx.view.rules().enabled(fixCleanup3_1_3) && amount.asset() == vaultShare) + if (ctx.view.rules().enabled(fixSecurity3_1_3) && amount.asset() == vaultShare) { - // Post-fixCleanup3_1_3: if the user specified shares, convert + // Post-fixSecurity3_1_3: if the user specified shares, convert // to the equivalent asset amount before checking withdrawal // limits. Pre-amendment the limit check was skipped for // share-denominated withdrawals. @@ -115,14 +95,9 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) // LCOV_EXCL_STOP } - // When the user is the sole shareholder they own both the available and future value. - // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of - // their shares but keeping future value in the vault. - auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(ctx.view, account, sleIssuance); try { - auto const maybeAssets = - sharesToAssetsWithdraw(vault, sleIssuance, amount, waiveUnrealizedLoss); + auto const maybeAssets = sharesToAssetsWithdraw(vault, sleIssuance, amount); if (!maybeAssets) return tefINTERNAL; // LCOV_EXCL_LINE @@ -200,28 +175,21 @@ VaultWithdraw::doApply() MPTIssue const share{mptIssuanceID}; STAmount sharesRedeemed = {share}; STAmount assetsWithdrawn; - - // When the user is the sole shareholder they own both the available and future value. - // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of their - // shares but keeping future value in the vault. - auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(view(), accountID_, sleIssuance); try { if (amount.asset() == vaultAsset) { // Fixed assets, variable shares. { - auto const maybeShares = assetsToSharesWithdraw( - vault, sleIssuance, amount, TruncateShares::No, waiveUnrealizedLoss); + auto const maybeShares = assetsToSharesWithdraw(vault, sleIssuance, amount); if (!maybeShares) return tecINTERNAL; // LCOV_EXCL_LINE sharesRedeemed = *maybeShares; } - if (sharesRedeemed == beast::kZero) + if (sharesRedeemed == beast::kZERO) return tecPRECISION_LOSS; - auto const maybeAssets = - sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss); + auto const maybeAssets = sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed); if (!maybeAssets) return tecINTERNAL; // LCOV_EXCL_LINE assetsWithdrawn = *maybeAssets; @@ -230,8 +198,7 @@ VaultWithdraw::doApply() { // Fixed shares, variable assets. sharesRedeemed = amount; - auto const maybeAssets = - sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss); + auto const maybeAssets = sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed); if (!maybeAssets) return tecINTERNAL; // LCOV_EXCL_LINE assetsWithdrawn = *maybeAssets; @@ -255,7 +222,7 @@ VaultWithdraw::doApply() } if (accountHolds( - view(), accountID_, share, FreezeHandling::ZeroIfFrozen, AuthHandling::IgnoreAuth, j_) < + view(), account_, share, FreezeHandling::ZeroIfFrozen, AuthHandling::IgnoreAuth, j_) < sharesRedeemed) { JLOG(j_.debug()) << "VaultWithdraw: account doesn't hold enough shares"; @@ -264,85 +231,43 @@ VaultWithdraw::doApply() auto assetsAvailable = vault->at(sfAssetsAvailable); auto assetsTotal = vault->at(sfAssetsTotal); - auto const lossUnrealized = vault->at(sfLossUnrealized); + [[maybe_unused]] auto const lossUnrealized = vault->at(sfLossUnrealized); XRPL_ASSERT( lossUnrealized <= (assetsTotal - assetsAvailable), "xrpl::VaultWithdraw::doApply : loss and assets do balance"); - // The vault must have enough assets on hand. + // The vault must have enough assets on hand. The vault may hold assets + // that it has already pledged. That is why we look at AssetAvailable + // instead of the pseudo-account balance. if (*assetsAvailable < assetsWithdrawn) { JLOG(j_.debug()) << "VaultWithdraw: vault doesn't hold enough assets"; return tecINSUFFICIENT_FUNDS; } - // Post-fixCleanup3_2_0 "final withdrawal" rule: - // a transaction that would burn every outstanding share is only permitted when the vault is in - // a clean state — no outstanding receivables and no unrealized loss. Otherwise the resulting - // (shares == 0, assetsTotal > 0) state would violate the zero-sized-vault invariant. - // - // When the rule applies, the payout is the remaining sfAssetsAvailable; in a clean vault - // the helper result should already equal that value, and any mismatch is a rounding artifact - // worth logging. - bool const isFinalWithdrawal = - sharesRedeemed == STAmount{share, sleIssuance->at(sfOutstandingAmount)}; - if (view().rules().enabled(fixCleanup3_2_0) && isFinalWithdrawal) - { - // Unreachable: a final withdrawal with lossUnrealized > 0 has - // assetsWithdrawn == assetsTotal > assetsAvailable, which the - // insufficient-funds guard above already rejected. - if (*lossUnrealized != beast::kZero) - { - // LCOV_EXCL_START - UNREACHABLE( - "xrpl::VaultWithdraw::doApply : final withdrawal with non-zero unrealized loss"); - JLOG(j_.fatal()) - << "VaultWithdraw: " // - "Cannot burn all outstanding shares while unrealized loss is non-zero"; - return tefINTERNAL; - // LCOV_EXCL_END - } - - STAmount const allAvailable{vaultAsset, *assetsAvailable}; - if (assetsWithdrawn != allAvailable) - { - JLOG(j_.error()) // - << "VaultWithdraw: final withdrawal share-value mismatch;" - << " computed=" << assetsWithdrawn.getText() - << " assetsAvailable=" << allAvailable.getText(); - } - assetsWithdrawn = allAvailable; - - // Do not let dust accumulate in the Vault. - assetsTotal = 0; - assetsAvailable = 0; - } - else - { - assetsTotal -= assetsWithdrawn; - assetsAvailable -= assetsWithdrawn; - } + assetsTotal -= assetsWithdrawn; + assetsAvailable -= assetsWithdrawn; view().update(vault); auto const& vaultAccount = vault->at(sfAccount); // Transfer shares from depositor to vault. - if (auto const ter = accountSend( - view(), accountID_, vaultAccount, sharesRedeemed, j_, WaiveTransferFee::Yes); + if (auto const ter = + accountSend(view(), account_, vaultAccount, sharesRedeemed, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; // Try to remove MPToken for shares, if the account balance is zero. Vault // pseudo-account will never set lsfMPTAuthorized, so we ignore flags. // Keep MPToken if holder is the vault owner. - if (accountID_ != vault->at(sfOwner)) + if (account_ != vault->at(sfOwner)) { - if (auto const ter = removeEmptyHolding(view(), accountID_, sharesRedeemed.asset(), j_); + if (auto const ter = removeEmptyHolding(view(), account_, sharesRedeemed.asset(), j_); isTesSuccess(ter)) { JLOG(j_.debug()) // << "VaultWithdraw: removed empty MPToken for vault shares" << " MPTID=" << to_string(mptIssuanceID) // - << " account=" << toBase58(accountID_); + << " account=" << toBase58(account_); } else if (ter != tecHAS_OBLIGATIONS) { @@ -350,7 +275,7 @@ VaultWithdraw::doApply() JLOG(j_.error()) // << "VaultWithdraw: failed to remove MPToken for vault shares" << " MPTID=" << to_string(mptIssuanceID) // - << " account=" << toBase58(accountID_) // + << " account=" << toBase58(account_) // << " with result: " << transToken(ter); return ter; // LCOV_EXCL_STOP @@ -358,18 +283,20 @@ VaultWithdraw::doApply() // else quietly ignore, account balance is not zero } - auto const dstAcct = ctx_.tx[~sfDestination].value_or(accountID_); + auto const dstAcct = ctx_.tx[~sfDestination].value_or(account_); associateAsset(*vault, vaultAsset); return doWithdraw( - view(), ctx_.tx, accountID_, dstAcct, vaultAccount, preFeeBalance_, assetsWithdrawn, j_); + view(), ctx_.tx, account_, dstAcct, vaultAccount, preFeeBalance_, assetsWithdrawn, j_); } void -VaultWithdraw::visitInvariantEntry(bool, SLE::const_ref, SLE::const_ref) +VaultWithdraw::visitInvariantEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { - // No transaction-specific invariants yet (future work). } bool @@ -380,7 +307,6 @@ VaultWithdraw::finalizeInvariants( ReadView const&, beast::Journal const&) { - // No transaction-specific invariants yet (future work). return true; } diff --git a/src/test/app/AMMClawbackMPT_test.cpp b/src/test/app/AMMClawbackMPT_test.cpp index 6facafde4a..6f0fff0282 100644 --- a/src/test/app/AMMClawbackMPT_test.cpp +++ b/src/test/app/AMMClawbackMPT_test.cpp @@ -52,7 +52,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); auto const usd = gw["USD"]; env.trust(usd(10000), alice); @@ -167,7 +167,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw2, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM const amm(env, alice, btc(100), usd(100)); env.close(); @@ -197,7 +197,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM const amm(env, alice, btc(100), XRP(100)); env.close(); @@ -225,7 +225,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 10'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM const amm(env, alice, XRP(1'000), btc(1'000)); @@ -272,7 +272,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw2, .holders = {alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM const amm(env, alice, btc(1000000000), usd(2000)); env.close(); @@ -334,7 +334,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(1000000000), XRP(2000)); env.close(); @@ -431,14 +431,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eth = MPTTester( {.env = env, .issuer = gw2, .holders = {alice, bob}, .pay = 30'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(2'000'000000), eth(3'000'000000)); env.close(); @@ -535,7 +535,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw2, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(2000000000), usd(2000)); env.close(); @@ -589,7 +589,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(5000), XRP(10'000)); env.close(); @@ -646,14 +646,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eth = MPTTester( {.env = env, .issuer = gw2, .holders = {alice, bob}, .pay = 30'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(20'000), eth(50'000)); env.close(); @@ -722,7 +722,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(1'000'000000), usd(2000)); env.close(); @@ -811,14 +811,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eth = MPTTester( {.env = env, .issuer = gw, .holders = {alice, bob}, .pay = 30'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(2'000'000000), eth(3'000'000000)); env.close(); @@ -914,7 +914,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(2'000'000000), usd(8'000)); env.close(); @@ -969,14 +969,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eth = MPTTester( {.env = env, .issuer = gw, .holders = {alice, bob}, .pay = 30'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(20'000), eth(10'000)); env.close(); @@ -1048,7 +1048,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw2, .holders = {alice, gw}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, gw, usd(1000), btc(2000)); env.close(); @@ -1134,14 +1134,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {gw2, alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eth = MPTTester( {.env = env, .issuer = gw2, .holders = {gw, alice}, .pay = 30'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, gw, btc(10'000), eth(50'000)); env.close(); @@ -1217,7 +1217,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 30'000, - .flags = tfMPTCanClawback | tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanClawback | tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice, usd(10'000), btc(10'000)); BEAST_EXPECT(ammAlice.expectBalances(usd(10'000), btc(10'000), IOUAmount(10'000))); env.close(); @@ -1288,7 +1288,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 30'000, - .flags = tfMPTCanClawback | tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanClawback | tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice, usd(10'000), btc(10'000)); BEAST_EXPECT(ammAlice.expectBalances(usd(10'000), btc(10'000), IOUAmount(10'000))); env.close(); @@ -1354,7 +1354,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); // gw creates AMM pool of BTC/XRP. AMM amm(env, gw, XRP(100), btc(400), Ter(tesSUCCESS)); @@ -1400,7 +1400,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); // gw creates AMM pool of BTC/USD. AMM amm(env, gw, usd(100), btc(400), Ter(tesSUCCESS)); @@ -1448,14 +1448,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const btc = MPTTester( {.env = env, .issuer = gw, .holders = {alice}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); // gw creates AMM pool of BTC/USD. AMM amm(env, gw, usd(100), btc(400), Ter(tesSUCCESS)); @@ -1517,7 +1517,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, usd(2), eur(1)); amm.deposit(alice, IOUAmount{1'576123487565916, -15}); @@ -1580,14 +1580,14 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); MPT const eur = MPTTester( {.env = env, .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, alice, usd(2), eur(1)); amm.deposit(alice, IOUAmount{1'576123487565916, -15}); @@ -1697,7 +1697,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); // Asset USD is not clawable without asfAllowTrustLineClawback. AMM const amm(env, alice, usd(200), btc(100)); @@ -1737,7 +1737,7 @@ class AMMClawbackMPT_test : public beast::unit_test::Suite .issuer = gw2, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM const amm(env, alice, usd(200), btc(100)); diff --git a/src/test/app/AMMExtendedMPT_test.cpp b/src/test/app/AMMExtendedMPT_test.cpp index e6dcc95733..6de39b73ec 100644 --- a/src/test/app/AMMExtendedMPT_test.cpp +++ b/src/test/app/AMMExtendedMPT_test.cpp @@ -85,14 +85,14 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 200'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 2'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // Must be two offers at the same quality // "taker gets" must be XRP @@ -240,7 +240,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 100'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(150'000), btc(50'000'000)); @@ -272,7 +272,7 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(500'000'000))); AMM const ammAlice(env, alice_, XRP(150'000), btc(51'000'000)); @@ -297,7 +297,7 @@ private: env.require(Owners(bob_, 0)); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(1'000'000'000))); env.require(Owners(alice_, 1), Owners(bob_, 1)); @@ -330,7 +330,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 30'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(10'000'000'000))); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000'000'000)); @@ -368,7 +368,7 @@ private: env.fund(XRP(1'000), bob_); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(10'100'000'000))); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'100'000'000)); @@ -392,7 +392,7 @@ private: env.fund(XRP(1'000), bob_); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(40'000'000'000))); AMM const ammAlice(env, alice_, XRP(10'100), btc(10'000'000'000)); @@ -437,7 +437,7 @@ private: env(offer(dan, XRP(500), eth(50'000'000'000'000))); env.close(); - json::Value jtp{json::ValueType::Array}; + json::Value jtp{json::ArrayValue}; jtp[0u][0u][jss::currency] = "XRP"; env(pay(alice_, bob_, eth(30'000'000'000'000)), Json(jss::Paths, jtp), @@ -470,11 +470,11 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); // Created only to increase one reserve count for alice MPTTester const eth( - {.env = env, .issuer = gw_, .holders = {alice_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(1'200'000'000'000'000))); @@ -508,7 +508,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .transferFee = 500, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(1'000'000'000'000))); env(pay(gw_, alice_, btc(200'000'000'000'000))); @@ -539,7 +539,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(10'100))); AMM const ammAlice(env, alice_, XRP(9'900), btc(10'100)); @@ -569,7 +569,7 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(2'200'000'000))); AMM const ammBob(env, bob_, XRP(1'000), btc(2'200'000'000)); @@ -602,13 +602,13 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const xxx( {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, xts(1'000'000'000'000'000), xxx(1'000'000'000'000'000)); @@ -621,7 +621,7 @@ private: 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] = - xts(15'000'000'000'000).value().getJson(JsonOptions::Values::None); + xts(15'000'000'000'000).value().getJson(JsonOptions::KNone); 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"); @@ -649,13 +649,13 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // The scenario: // o BTC/XRP AMM is created. @@ -688,13 +688,13 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // The scenario: // o BTC/XRP AMM is created. @@ -729,13 +729,13 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 15'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // The scenario: // o BTC/XRP offer is created. @@ -779,7 +779,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 20'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(20'000), btc(200'000'000)); // alice submits a tfSell | tfFillOrKill offer that does not cross. env(offer(alice_, btc(2'100'000), XRP(210), tfSell | tfFillOrKill), Ter(tecKILLED)); @@ -796,7 +796,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(20'000), btc(200'000'000'000'000)); // alice submits a tfSell | tfFillOrKill offer that crosses. // Even though tfSell is present it doesn't matter this time. @@ -818,7 +818,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(20'000), btc(200'000'000'000'000)); env(offer(alice_, btc(10'000'000'000'000), XRP(1'500), tfSell | tfFillOrKill)); @@ -843,7 +843,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 10'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(5000), btc(10'000'000)); env(offer(alice_, btc(1'000'000), XRP(501), tfSell | tfFillOrKill), Ter(tecKILLED)); @@ -872,7 +872,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 30'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(10'100'000))); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'100'000)); @@ -898,7 +898,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 30'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(10'000'000))); AMM const ammAlice(env, alice_, XRP(10'100), btc(10'000'000)); @@ -924,14 +924,14 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 15'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 15'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // The scenario: // o BTC/XRP AMM is created. @@ -969,14 +969,14 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 15'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 15'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // The scenario: // o BTC/XRP AMM is created. @@ -1022,7 +1022,7 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = bob_, .holders = {alice_}, .flags = kMptDexFlags}); + {.env = env, .issuer = bob_, .holders = {alice_}, .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(10'000), btc(10'100)); @@ -1058,10 +1058,10 @@ private: env.close(); MPTTester const aBux( - {.env = env, .issuer = ann, .holders = {bob, cam, carol}, .flags = kMptDexFlags}); + {.env = env, .issuer = ann, .holders = {bob, cam, carol}, .flags = kMPT_DEX_FLAGS}); MPTTester const bBux( - {.env = env, .issuer = bob, .holders = {ann, cam, carol}, .flags = kMptDexFlags}); + {.env = env, .issuer = bob, .holders = {ann, cam, carol}, .flags = kMPT_DEX_FLAGS}); env(pay(ann, cam, aBux(350'000'000'000'000))); env(pay(bob, cam, bBux(350'000'000'000'000))); @@ -1103,7 +1103,7 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, bob_}, - .flags = tfMPTRequireAuth | kMptDexFlags}); + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS}); // Authorize bob and alice btc.authorize({.holder = alice_}); @@ -1145,7 +1145,7 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, bob_}, - .flags = tfMPTRequireAuth | kMptDexFlags}); + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS}); // Alice doesn't have the funds { @@ -1225,7 +1225,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 100'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammCarol(env, carol_, XRP(100), eth(100'000'000'000'000)); @@ -1262,14 +1262,14 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .transferFee = 10'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .transferFee = 10'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, carol_, eth(51))); env.close(); @@ -1300,7 +1300,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, charlie}, .pay = 11'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammCharlie(env, charlie, XRP(10), eth(11'000'000'000'000)); auto [st, sa, da] = findPaths(env, alice_, bob_, eth(-1), XRP(1).value()); @@ -1324,7 +1324,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, charlie}, .pay = 11'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammCharlie(env, charlie, XRP(11), eth(10'000'000'000'000)); env.close(); @@ -1363,16 +1363,16 @@ private: env.close(); MPTTester const xyzG1( - {.env = env, .issuer = g1, .holders = {a1, m1, a2}, .flags = kMptDexFlags}); + {.env = env, .issuer = g1, .holders = {a1, m1, a2}, .flags = kMPT_DEX_FLAGS}); MPTTester const xyzG2( - {.env = env, .issuer = g2, .holders = {a2, m1, a1}, .flags = kMptDexFlags}); + {.env = env, .issuer = g2, .holders = {a2, m1, a1}, .flags = kMPT_DEX_FLAGS}); MPTTester const abcG3( - {.env = env, .issuer = g3, .holders = {a1, a2, m1, a3}, .flags = kMptDexFlags}); + {.env = env, .issuer = g3, .holders = {a1, a2, m1, a3}, .flags = kMPT_DEX_FLAGS}); MPTTester const abcA2( - {.env = env, .issuer = a2, .holders = {g3, a1}, .flags = kMptDexFlags}); + {.env = env, .issuer = a2, .holders = {g3, a1}, .flags = kMPT_DEX_FLAGS}); env(pay(g1, a1, xyzG1(3'500'000'000))); env(pay(g3, a1, abcG3(1'200'000'000))); @@ -1444,7 +1444,7 @@ private: .issuer = g3, .holders = {a1, a2, m1}, .pay = 1'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammM1(env, m1, eth(1'000'000'000), XRP(10'010)); @@ -1483,14 +1483,14 @@ private: .issuer = g1, .holders = {a1, m1}, .pay = 5'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const hkdG2( {.env = env, .issuer = g2, .holders = {a2, m1}, .pay = 5'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammM1(env, m1, hkdG1(1'000'000'000), hkdG2(1'010'000'000)); @@ -1522,10 +1522,16 @@ private: env.close(); MPTTester const eth( - {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .flags = kMptDexFlags}); + {.env = env, + .issuer = gw_, + .holders = {alice_, bob_, carol_}, + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .flags = kMptDexFlags}); + {.env = env, + .issuer = gw_, + .holders = {alice_, bob_, carol_}, + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, eth(50'000))); env(pay(gw_, bob_, btc(150'000))); @@ -1604,14 +1610,14 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 150'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBobBtcXrp(env, bob_, btc(100'000), XRP(150)); AMM const ammBobXrpEth(env, bob_, XRP(100), eth(150'000)); @@ -1638,7 +1644,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 150'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(100), eth(150'000)); @@ -1661,7 +1667,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, eth(100'000), XRP(150)); @@ -1753,19 +1759,19 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester gbp( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(60'000'000))); env(pay(gw_, bob_, btc(100'000'000))); @@ -1912,7 +1918,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( {.env = env, @@ -1920,7 +1926,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, bob_, gbp(1'000'000'000'000'000), btc(1'000'000'000'000'000)); @@ -1954,7 +1960,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( {.env = env, @@ -1962,7 +1968,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -1970,7 +1976,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(ed, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)), Txflags(tfPassive)); @@ -2015,7 +2021,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const btc( {.env = env, @@ -2023,7 +2029,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2031,7 +2037,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm1(env, bob_, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)); AMM const amm2(env, ed, eth(1'000'000'000'000'000), btc(1'000'000'000'000'000)); @@ -2070,7 +2076,7 @@ private: .holders = {alice_, bob_}, .transferFee = 25'000, .pay = 1'100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2078,7 +2084,7 @@ private: .holders = {alice_, bob_}, .transferFee = 25'000, .pay = 1'100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, bob_, btc(1'000'000), eth(1'100'000)); env(offer(alice_, eth(100'000), btc(100'000))); @@ -2103,7 +2109,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2111,7 +2117,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, bob_, gbp(1'000'000'000'000'000), btc(1'000'000'000'000'000)); @@ -2147,7 +2153,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'200'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2155,7 +2161,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'200'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, bob_, gbp(1'000'000'000'000'000), btc(1'200'000'000'000'000)); @@ -2193,7 +2199,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2201,7 +2207,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2209,7 +2215,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(ed, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)), Txflags(tfPassive)); @@ -2259,7 +2265,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2267,7 +2273,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2275,7 +2281,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, bob_, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)); @@ -2326,7 +2332,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2334,7 +2340,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2342,7 +2348,7 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm1(env, bob_, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)); AMM const amm2(env, ed, eth(1'000'000'000'000'000), btc(1'400'000'000'000'000)); @@ -2385,7 +2391,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, @@ -2393,7 +2399,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, @@ -2401,7 +2407,7 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 1'400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm1(env, alice_, gbp(1'000'000'000'000'000), eth(1'000'000'000'000'000)); AMM const amm2(env, bob_, eth(1'000'000'000'000'000), btc(1'400'000'000'000'000)); @@ -2447,7 +2453,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 2'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(1'000), eth(1'050'000)); env(offer(bob_, XRP(100), eth(50'000))); @@ -2605,7 +2611,7 @@ private: env.fund(XRP(100'000'000), gw_, alice_, bob_, carol_, dan, ed); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, ed, btc(11'000'000'000'000))); env(pay(gw_, bob_, btc(1'000'000'000'000))); @@ -2629,7 +2635,7 @@ private: // Carol offers to buy 1000 XRP for 1000e12 BTC. She removes Bob's // next 1000 offers as unfunded and hits the step limit. env(offer(carol_, btc(1'000'000'000'000'000), XRP(1'000))); - env.require(Balance(carol_, MPT(btc)(kNone))); + env.require(Balance(carol_, MPT(btc)(kNONE))); env.require(Owners(carol_, 1)); env.require(Balance(bob_, btc(0))); env.require(Owners(bob_, 1)); @@ -2651,7 +2657,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_, dan, ed}, .pay = 10000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env.trust(BTC(11'000'000'000'000), ed); env(pay(gw_, ed, BTC(11'000'000'000'000))); @@ -2696,7 +2702,7 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, ed, btc(11'000'000'000'000))); env(pay(gw_, bob_, btc(1'000'000'000'000))); @@ -2726,13 +2732,13 @@ private: env.close(); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {bob_, dan, ed}, .flags = kMPT_DEX_FLAGS}); MPTTester const usd( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_, dan, ed}, .pay = 10000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, ed, btc(11'000'000'000'000))); env(pay(gw_, bob_, btc(1'000'000'000'000))); @@ -2768,7 +2774,7 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(alice_, bob_, btc(10'000)), DeliverMin(btc(10'000)), Ter(temBAD_AMOUNT)); env(pay(alice_, bob_, btc(10'000)), @@ -2805,7 +2811,7 @@ private: fund(env, gw_, {alice_, bob_}, XRP(10'000)); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, bob_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(1'100'000))); AMM const ammBob(env, bob_, XRP(1'000), btc(1'100'000)); @@ -2857,7 +2863,7 @@ private: fund(env, gw_, {alice_, bob_, carol_}, XRP(10'000)); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {bob_, carol_}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {bob_, carol_}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(1'200'000))); AMM const ammBob(env, bob_, XRP(5'500), btc(1'200'000)); @@ -2926,7 +2932,10 @@ private: fund(env, gw_, {alice_, bob_, carol_, dan}, XRP(10'000)); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {bob_, carol_, dan}, .flags = kMptDexFlags}); + {.env = env, + .issuer = gw_, + .holders = {bob_, carol_, dan}, + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(100'000'000))); env(pay(gw_, dan, btc(1'100'000'000))); @@ -2958,7 +2967,7 @@ private: fund(env, gw_, {alice_, becky}, XRP(5'000)); MPTTester const btc( - {.env = env, .issuer = gw_, .holders = {alice_, becky}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw_, .holders = {alice_, becky}, .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(500'000))); env.close(); @@ -2996,7 +3005,10 @@ private: fund(env, gw_, {alice_, bob_, carol_}, XRP(10'000)); MPTTester btc( - {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .flags = kMptDexFlags}); + {.env = env, + .issuer = gw_, + .holders = {alice_, bob_, carol_}, + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, alice_, btc(150'000))); env(pay(gw_, carol_, btc(150'000))); @@ -3091,7 +3103,7 @@ private: {.env = env, .issuer = g1, .holders = {alice, bob}, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); env(pay(g1, bob, btc(10))); env(pay(g1, alice, btc(205))); @@ -3114,8 +3126,10 @@ private: btc.set({.holder = bob, .flags = tfMPTLock}); { - env(offer(bob, btc(5), XRP(25)), Ter(tecLOCKED)); + // different from IOU. The offer is created but not crossed. + env(offer(bob, btc(5), XRP(25))); env.close(); + BEAST_EXPECT(expectOffers(env, bob, 1, {{{btc(5), XRP(25)}}})); BEAST_EXPECT(ammAlice.expectBalances(XRP(500), btc(105), ammAlice.tokens())); } @@ -3165,13 +3179,13 @@ private: {.env = env, .issuer = g1, .holders = {a1, a2, a3, a4}, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester btc( {.env = env, .issuer = g1, .holders = {a1, a2, a3, a4}, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); env(pay(g1, a1, eth(1'000))); env(pay(g1, a2, eth(100))); @@ -3218,7 +3232,7 @@ private: btc.set({.flags = tfMPTLock}); // assets can't be bought on the market - AMM const ammA3(env, a3, btc(1), XRP(1), Ter(tecLOCKED)); + AMM const ammA3(env, a3, btc(1), XRP(1), Ter(tecFROZEN)); // direct issues can be sent env(pay(g1, a2, btc(1))); @@ -3260,7 +3274,7 @@ private: {.env = env, .issuer = g1, .holders = {a2, a3, a4}, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); env(pay(g1, a3, btc(2'000))); env(pay(g1, a4, btc(2'001))); @@ -3326,7 +3340,7 @@ private: .issuer = gw_, .holders = {alice, becky, zelda}, .pay = 20'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // alice uses a regular key with the master disabled. Account const alie{"alie", KeyType::Secp256k1}; @@ -3336,8 +3350,8 @@ private: // Attach signers to alice. env(signers(alice, 2, {{becky, 1}, {bogie, 1}}), Sig(alie)); env.close(); - static constexpr int kSignerListOwners{2}; - env.require(Owners(alice, kSignerListOwners + 0)); + int constexpr kSIGNER_LIST_OWNERS{2}; + env.require(Owners(alice, kSIGNER_LIST_OWNERS + 0)); Msig const ms{becky, bogie}; @@ -3432,14 +3446,14 @@ private: .issuer = bob_, .holders = {alice_, gw_}, .pay = 100'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = bob_, .holders = {alice_, gw_}, .pay = 100'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammXrpBtc(env, bob_, XRP(100), btc(100'000)); env(offer(gw_, XRP(100), btc(100'000)), Txflags(tfPassive)); @@ -3473,7 +3487,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(100), btc(100)); @@ -3494,7 +3508,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 100'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammBob(env, bob_, XRP(100), btc(100)); @@ -3522,7 +3536,7 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(pay(gw_, bob_, btc(100'000'000))); env(pay(gw_, alice_, btc(100'000'000))); diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index a0a7d0fb15..8132c012ad 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -65,15 +65,10 @@ namespace xrpl::test { /** * Tests of AMM that use offers too. */ -class AMMExtended_test : public jtx::AMMTest +struct AMMExtended_test : public jtx::AMMTest { // Use small Number mantissas for the life of this test. - NumberMantissaScaleGuard const sg_{xrpl::MantissaRange::MantissaScale::Small}; - - // For now, just disable SAV entirely, which locks in the small Number - // mantissas - FeatureBitset const all_{ - testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; + NumberMantissaScaleGuard const sg{xrpl::MantissaRange::MantissaScale::Small}; private: void @@ -511,7 +506,7 @@ private: env(offer(dan, XRP(500), euR1(50))); env.close(); - json::Value jtp{json::ValueType::Array}; + 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.close(); @@ -686,8 +681,7 @@ private: 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::Values::None); + payment[jss::tx_json][jss::SendMax] = bob_["XTS"](1.5).value().getJson(JsonOptions::KNone); 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"); @@ -1125,14 +1119,14 @@ private: env(pay(ann, cam, dBux(60)), Path(localBob, dan), Sendmax(aBux(200))); env.close(); - BEAST_EXPECT(expectHolding(env, ann, aBux(kNone))); - BEAST_EXPECT(expectHolding(env, ann, dBux(kNone))); + BEAST_EXPECT(expectHolding(env, ann, aBux(kNONE))); + BEAST_EXPECT(expectHolding(env, ann, dBux(kNONE))); BEAST_EXPECT(expectHolding(env, localBob, aBux(72))); BEAST_EXPECT(expectHolding(env, localBob, dBux(40))); - BEAST_EXPECT(expectHolding(env, cam, aBux(kNone))); + BEAST_EXPECT(expectHolding(env, cam, aBux(kNONE))); BEAST_EXPECT(expectHolding(env, cam, dBux(60))); - BEAST_EXPECT(expectHolding(env, dan, aBux(kNone))); - BEAST_EXPECT(expectHolding(env, dan, dBux(kNone))); + BEAST_EXPECT(expectHolding(env, dan, aBux(kNONE))); + BEAST_EXPECT(expectHolding(env, dan, dBux(kNONE))); AMM const ammBob(env, localBob, aBux(30), dBux(30)); @@ -1144,12 +1138,12 @@ private: env.close(); BEAST_EXPECT(ammBob.expectBalances(aBux(30), dBux(30), ammBob.tokens())); - BEAST_EXPECT(expectHolding(env, ann, aBux(kNone))); + BEAST_EXPECT(expectHolding(env, ann, aBux(kNONE))); BEAST_EXPECT(expectHolding(env, ann, dBux(0))); - BEAST_EXPECT(expectHolding(env, cam, aBux(kNone))); + BEAST_EXPECT(expectHolding(env, cam, aBux(kNONE))); BEAST_EXPECT(expectHolding(env, cam, dBux(60))); BEAST_EXPECT(expectHolding(env, dan, aBux(0))); - BEAST_EXPECT(expectHolding(env, dan, dBux(kNone))); + BEAST_EXPECT(expectHolding(env, dan, dBux(kNONE))); } } @@ -1354,33 +1348,37 @@ private: testOffers() { using namespace jtx; + // For now, just disable SAV entirely, which locks in the small Number + // mantissas + FeatureBitset const all{ + testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; - testRmFundedOffer(all_); - testRmFundedOffer(all_ - fixAMMv1_1 - fixAMMv1_3); - testEnforceNoRipple(all_); - testFillModes(all_); - testOfferCrossWithXRP(all_); - testOfferCrossWithLimitOverride(all_); - testCurrencyConversionEntire(all_); - testCurrencyConversionInParts(all_); - testCrossCurrencyStartXRP(all_); - testCrossCurrencyEndXRP(all_); - testCrossCurrencyBridged(all_); - testOfferFeesConsumeFunds(all_); - testOfferCreateThenCross(all_); - testSellFlagExceedLimit(all_); - testGatewayCrossCurrency(all_); - testGatewayCrossCurrency(all_ - fixAMMv1_1 - fixAMMv1_3); - testBridgedCross(all_); - testSellWithFillOrKill(all_); - testTransferRateOffer(all_); - testSelfIssueOffer(all_); - testBadPathAssert(all_); - testSellFlagBasic(all_); - testDirectToDirectPath(all_); - testDirectToDirectPath(all_ - fixAMMv1_1 - fixAMMv1_3); - testRequireAuth(all_); - testMissingAuth(all_); + testRmFundedOffer(all); + testRmFundedOffer(all - fixAMMv1_1 - fixAMMv1_3); + testEnforceNoRipple(all); + testFillModes(all); + testOfferCrossWithXRP(all); + testOfferCrossWithLimitOverride(all); + testCurrencyConversionEntire(all); + testCurrencyConversionInParts(all); + testCrossCurrencyStartXRP(all); + testCrossCurrencyEndXRP(all); + testCrossCurrencyBridged(all); + testOfferFeesConsumeFunds(all); + testOfferCreateThenCross(all); + testSellFlagExceedLimit(all); + testGatewayCrossCurrency(all); + testGatewayCrossCurrency(all - fixAMMv1_1 - fixAMMv1_3); + testBridgedCross(all); + testSellWithFillOrKill(all); + testTransferRateOffer(all); + testSelfIssueOffer(all); + testBadPathAssert(all); + testSellFlagBasic(all); + testDirectToDirectPath(all); + testDirectToDirectPath(all - fixAMMv1_1 - fixAMMv1_3); + testRequireAuth(all); + testMissingAuth(all); } void @@ -2715,7 +2713,7 @@ private: // Carol offers to buy 1000 XRP for 1000 USD. She removes Bob's next // 1000 offers as unfunded and hits the step limit. env(offer(carol_, USD(1'000), XRP(1'000))); - env.require(Balance(carol_, USD(kNone))); + env.require(Balance(carol_, USD(kNONE))); env.require(Owners(carol_, 1)); env.require(Balance(bob_, USD(0))); env.require(Owners(bob_, 1)); @@ -3086,14 +3084,12 @@ 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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + ff[sfLowLimit.fieldName] == g1["USD"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -3517,11 +3513,15 @@ private: testFlow() { using namespace jtx; + // For now, just disable SAV entirely, which locks in the small Number + // mantissas in the transaction engine + FeatureBitset const all{ + testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; - testFalseDry(all_); - testBookStep(all_); - testTransferRateNoOwnerFee(all_); - testTransferRateNoOwnerFee(all_ - fixAMMv1_1 - fixAMMv1_3); + testFalseDry(all); + testBookStep(all); + testTransferRateNoOwnerFee(all); + testTransferRateNoOwnerFee(all - fixAMMv1_1 - fixAMMv1_3); testLimitQuality(); testXRPPathLoop(); } @@ -3530,22 +3530,34 @@ private: testCrossingLimits() { using namespace jtx; - testStepLimit(all_); - testStepLimit(all_ - fixAMMv1_1 - fixAMMv1_3); + // For now, just disable SAV entirely, which locks in the small Number + // mantissas in the transaction engine + FeatureBitset const all{ + testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; + testStepLimit(all); + testStepLimit(all - fixAMMv1_1 - fixAMMv1_3); } void testDeliverMin() { using namespace jtx; - testConvertAllOfAnAsset(all_); - testConvertAllOfAnAsset(all_ - fixAMMv1_1 - fixAMMv1_3); + // For now, just disable SAV entirely, which locks in the small Number + // mantissas in the transaction engine + FeatureBitset const all{ + testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; + testConvertAllOfAnAsset(all); + testConvertAllOfAnAsset(all - fixAMMv1_1 - fixAMMv1_3); } void testDepositAuth() { - testPayment(all_); + // For now, just disable SAV entirely, which locks in the small Number + // mantissas in the transaction engine + FeatureBitset const all{ + jtx::testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; + testPayment(all); testPayIOU(); } @@ -3553,9 +3565,13 @@ private: testFreeze() { using namespace test::jtx; - testRippleState(all_); - testGlobalFreeze(all_); - testOffersWhenFrozen(all_); + // For now, just disable SAV entirely, which locks in the small Number + // mantissas in the transaction engine + FeatureBitset const sa{ + testableAmendments() - featureSingleAssetVault - featureLendingProtocol}; + testRippleState(sa); + testGlobalFreeze(sa); + testOffersWhenFrozen(sa); } void diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp index 31b54ceee0..4318a19503 100644 --- a/src/test/app/AMMMPT_test.cpp +++ b/src/test/app/AMMMPT_test.cpp @@ -128,7 +128,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); AMM const ammAlice(env, alice_, USD(10'000), btc(10'000)); } @@ -142,9 +142,9 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); usd.set({.flags = tfMPTLock}); - AMM const ammAliceFail(env, alice_, XRP(10'000), usd(10'000), Ter(tecLOCKED)); + AMM const ammAliceFail(env, alice_, XRP(10'000), usd(10'000), Ter(tecFROZEN)); usd.set({.flags = tfMPTUnlock}); AMM const ammAlice(env, alice_, XRP(10'000), usd(10'000)); } @@ -346,9 +346,9 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); btc.set({.flags = tfMPTLock}); - AMM const ammAlice(env, alice_, USD(10'000), btc(10'000), Ter(tecLOCKED)); + AMM const ammAlice(env, alice_, USD(10'000), btc(10'000), Ter(tecFROZEN)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -361,11 +361,11 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); btc.set({.holder = alice_, .flags = tfMPTLock}); // alice's token is locked - AMM const ammAlice(env, alice_, USD(10'000), btc(10'000), Ter(tecLOCKED)); + AMM const ammAlice(env, alice_, USD(10'000), btc(10'000), Ter(tecFROZEN)); BEAST_EXPECT(!ammAlice.ammExists()); // bob can create @@ -411,14 +411,13 @@ private: // LPTokenOut can not be MPT { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::Account] = alice_.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::KNone); jv[jss::Asset2] = - STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::Values::None); - jv[jss::LPTokenOut] = - MPT(ammAlice[1])(100).value().getJson(JsonOptions::Values::None); + STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::KNone); + jv[jss::LPTokenOut] = MPT(ammAlice[1])(100).value().getJson(JsonOptions::KNone); jv[jss::Flags] = tfLPToken; env(jv, Ter(telENV_RPC_FAILED)); } @@ -426,13 +425,13 @@ private: // Provided LPTokenOut does not match AMM pool's LPToken // asset { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::Account] = alice_.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::KNone); jv[jss::Asset2] = - STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::Values::None); - jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::Values::None); + STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::KNone); + jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::KNone); jv[jss::Flags] = tfLPToken; env(jv, Ter(temBAD_AMM_TOKENS)); } @@ -496,7 +495,7 @@ private: {.env = env, .issuer = gw_, .holders = {alice_, carol_}, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .authHolder = true}); // Depositing mismatched token, invalid Asset1In.issue @@ -687,21 +686,21 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, USD(10'000), btc(10'000)); btc.set({.flags = tfMPTLock}); ammAlice.deposit( - carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); - ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, USD(100), btc(100), std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, USD(100), btc(100), std::nullopt, std::nullopt, Ter(tecFROZEN)); } // Individually lock MPT or freeze IOU (AMM) with IOU/MPT AMM @@ -713,7 +712,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, USD(10'000), btc(10'000)); @@ -722,19 +721,20 @@ private: // Carol can not deposit locked mpt ammAlice.deposit( - carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); - ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); if (!features[featureAMMClawback]) { - ammAlice.deposit(carol_, USD(100), std::nullopt, std::nullopt, std::nullopt); + ammAlice.deposit( + carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); } else { - // Carol can not deposit non-frozen token either + // Carol can not deposit non-forzen token either ammAlice.deposit( - carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); } // Alice can deposit because she's not individually locked @@ -777,9 +777,9 @@ private: ammAlice.deposit(carol_, USD(100), std::nullopt, std::nullopt, std::nullopt); // Can not deposit locked token - ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); // Unlock AMM MPT btc.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); @@ -798,23 +798,23 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester usd( {.env = env, .issuer = gw_, .holders = {alice_, carol_}, .pay = 40'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, usd(10'000), btc(10'000)); // Carol's BTC is locked btc.set({.holder = carol_, .flags = tfMPTLock}); ammAlice.deposit( - carol_, usd(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, usd(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); // Unlock carol's BTC btc.set({.holder = carol_, .flags = tfMPTUnlock}); @@ -830,9 +830,9 @@ private: ammAlice.deposit(carol_, usd(100), std::nullopt, std::nullopt, std::nullopt); // Can not deposit locked token BTC - ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, btc(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); // Unlock AMM MPT BTC btc.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); @@ -847,9 +847,9 @@ private: ammAlice.deposit(carol_, btc(100), std::nullopt, std::nullopt, std::nullopt); // Can not deposit locked token USD - ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.deposit(carol_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); ammAlice.deposit( - carol_, usd(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecLOCKED)); + carol_, usd(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN)); // Unlock AMM MPT USD usd.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); @@ -870,7 +870,7 @@ private: {.maxAmt = 1'000'000, .authorize = {{alice}}, .pay = {{{alice}, 10'000}}, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); AMM amm(env, alice, XRP(10'000), btc(10'000)); @@ -903,7 +903,7 @@ private: AMM amm(env, gw, XRP(10'000), btc(10'000)); - amm.deposit({.account = alice, .asset1In = btc(10), .err = Ter(tecNO_AUTH)}); + amm.deposit({.account = alice, .asset1In = btc(10), .err = Ter(tecNO_PERMISSION)}); } // Insufficient XRP balance @@ -2035,7 +2035,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'000)); WithdrawArg const args{ @@ -2053,7 +2053,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 2'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); // Invalid tokens ammAlice.withdraw(alice_, 0, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS)); @@ -2224,7 +2224,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); MPT const btc = btcm; @@ -2245,22 +2245,23 @@ private: Env env{*this}; env.fund(XRP(30'000), gw_, alice_); env.close(); - auto btc = MPTTester( + auto btcm = MPTTester( {.env = env, .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer, + .flags = tfMPTCanTrade, .authHolder = true}); + MPT const btc = btcm; AMM amm(env, gw_, XRP(10'000), btc(10'000)); - amm.deposit(DepositArg{.account = alice_, .asset1In = XRP(200), .asset2In = btc(200)}); - // Allow to withdraw if transfer is disabled - btc.set({.mutableFlags = tmfMPTClearCanTransfer}); amm.withdraw( - WithdrawArg{.account = alice_, .asset1Out = btc(100), .assets = {{XRP, btc}}}); + WithdrawArg{ + .account = alice_, + .asset1Out = btc(100), + .assets = {{XRP, btc}}, + .err = Ter(tecNO_PERMISSION)}); } // Globally locked MPT @@ -2274,15 +2275,15 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .authHolder = true}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.flags = tfMPTLock}); ammAlice.withdraw( - alice_, MPT(ammAlice[1])(100), std::nullopt, std::nullopt, Ter(tecLOCKED)); - ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); + alice_, MPT(ammAlice[1])(100), std::nullopt, std::nullopt, Ter(tecFROZEN)); + ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); // can single withdraw the other asset ammAlice.withdraw({.account = alice_, .asset1Out = XRP(100)}); @@ -2298,20 +2299,20 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester const usd( {.env = env, .issuer = gw_, .holders = {alice_}, .pay = 40'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, usd(10'000), btc(10'000)); // Alice's BTC is locked btc.set({.holder = alice_, .flags = tfMPTLock}); - ammAlice.withdraw(alice_, 1000, std::nullopt, std::nullopt, Ter(tecLOCKED)); - ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.withdraw(alice_, 1000, std::nullopt, std::nullopt, Ter(tecFROZEN)); + ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecFROZEN)); // can withdraw the other asset ammAlice.withdraw(alice_, usd(100), std::nullopt, std::nullopt); @@ -2332,15 +2333,15 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, USD(10'000), btc(10'000)); // Alice's BTC is locked btc.set({.holder = alice_, .flags = tfMPTLock}); - ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); - ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); + ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecFROZEN)); // can still single withdraw the unlocked other asset ammAlice.withdraw(alice_, USD(100), std::nullopt, std::nullopt); @@ -2359,8 +2360,8 @@ private: ammAlice.withdraw(alice_, USD(100), std::nullopt, std::nullopt); // Can not withdraw locked token BTC - ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecLOCKED)); - ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecLOCKED)); + ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN)); + ammAlice.withdraw(alice_, btc(100), std::nullopt, std::nullopt, Ter(tecFROZEN)); // Unlock AMM MPT btc.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); @@ -3475,7 +3476,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 2'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM amm(env, gw_, XRP(1'000), btc(1'000), false, 1'000); // auction slot is owned by the creator of the AMM i.e. gw @@ -3500,7 +3501,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 2'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM amm(env, gw_, XRP(1'000), btc(1'000), false, 1'000); // auction slot is owned by the creator of the AMM i.e. gw @@ -3608,7 +3609,7 @@ private: .issuer = gw_, .holders = {alice_, carol_, bob_}, .pay = 30'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, btc(10'000'000'000), USD(10'000)); ammAlice.deposit(carol_, 1'000'000); @@ -3644,7 +3645,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 1'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM amm(env, gw_, XRP(10), btc(1'000)); auto const lpIssue = amm.lptIssue(); env.trust(STAmount{lpIssue, 100}, alice_); @@ -3709,7 +3710,7 @@ private: .issuer = gw_, .holders = {alice_, carol_, bob_}, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'000)); ammAlice.deposit(carol_, 1'000'000); @@ -3754,7 +3755,7 @@ private: .issuer = gw_, .holders = {alice_, carol_, bob_}, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'000)); ammAlice.deposit(carol_, 1'000'000); @@ -3768,17 +3769,18 @@ private: // 1st Interval after close, price for 0th interval. env(ammAlice.bid({.account = bob_})); - env.close(seconds(kAuctionSlotIntervalDuration + 1)); + env.close(seconds(kAUCTION_SLOT_INTERVAL_DURATION + 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 * kAuctionSlotIntervalDuration) + 1)); + env.close(seconds((10 * kAUCTION_SLOT_INTERVAL_DURATION) + 1)); 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((kAuctionSlotTimeIntervals * kAuctionSlotIntervalDuration) + 1)); + env.close( + seconds((kAUCTION_SLOT_TIME_INTERVALS * kAUCTION_SLOT_INTERVAL_DURATION) + 1)); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); // 0 Interval. @@ -3881,7 +3883,7 @@ private: btc(13'000'000'671), STAmount{USD, UINT64_C(13'114'03663044931), -11}, ammTokens)); // Auction slot expired, no discounted fee - env.close(seconds(kTotalTimeSlotSecs + 1)); + env.close(seconds(kTOTAL_TIME_SLOT_SECS + 1)); // clock is parent's based env.close(); @@ -3914,7 +3916,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { // Bid a tiny amount - auto const tiny = Number{STAmount::kMinValue, STAmount::kMinOffset}; + auto const tiny = Number{STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET}; 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. @@ -3925,7 +3927,7 @@ private: // Bid the tiny amount env(ammAlice.bid({ .account = alice_, - .bidMin = IOUAmount{STAmount::kMinValue, STAmount::kMinOffset}, + .bidMin = IOUAmount{STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET}, })); // Pay slightly higher price BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny * Number{105, -2}})); @@ -3968,7 +3970,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 2'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); fund(env, gw_, {alice_, bob_}, {USD(2'000)}, Fund::TokenOnly); AMM amm(env, gw_, btc(1'000'000'000), USD(1'010), false, 1'000); auto const lpIssue = amm.lptIssue(); @@ -4004,7 +4006,7 @@ private: .issuer = gw_, .holders = {alice_, bob_}, .pay = 2'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM amm(env, gw_, XRP(1'000), btc(1'010), false, 1'000); json::Value const tx = amm.bid({.account = alice_, .bidMin = 500}); @@ -4065,7 +4067,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); // to clawback from AMM account, must use AMMClawback instead of // Clawback @@ -4100,7 +4102,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 100, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // XRP balance is below reserve AMM const ammAlice(env, acct, XRP(10), btc(10)); // Pay below reserve @@ -4119,7 +4121,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 20'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); // XRP balance is above reserve AMM const ammAlice(env, acct, XRP(1'000'000), btc(10'000)); // Pay below reserve @@ -4135,16 +4137,16 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { env(escrow::create(carol_, ammAlice.ammAccount(), MPT(ammAlice[1])(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(1'500), Ter(tecNO_PERMISSION)); env(escrow::create(carol_, ammAlice.ammAccount(), XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(1'500), Ter(tecNO_PERMISSION)); }, @@ -4229,7 +4231,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.flags = tfMPTLock}); @@ -4255,7 +4257,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.holder = carol_, .flags = tfMPTLock}); @@ -4276,7 +4278,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.holder = alice_, .flags = tfMPTLock}); @@ -4297,13 +4299,13 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, eth(10'000), btc(10'000)); btc.set({.holder = carol_, .flags = tfMPTLock}); @@ -4333,7 +4335,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); @@ -4632,7 +4634,7 @@ private: .holders = {alice_, carol_}, .transferFee = 10'000, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); auto ammAlice = AMM(env, alice_, XRP(10'000), btc(10'010'000'000'000'000)); env.close(); auto carolMPT = env.balance(carol_, MPT(btc)); @@ -4760,13 +4762,13 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 3'000'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, carol_}, .pay = 3'000'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env.fund(XRP(1'000), bob_); env.close(); auto ammEthXrp = AMM(env, alice_, XRP(10'000), eth(1'000'000'000'000'000'000)); @@ -4810,13 +4812,13 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 3'000'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_}, .pay = 1'000'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); auto ammAlice = AMM(env, alice_, XRP(10'000), btc(1'000'000'000'000'000'000)); env.fund(XRP(1'000), bob_); env.close(); @@ -4858,7 +4860,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'100'000'000'000'000)); env(offer(bob_, XRP(100), MPT(ammAlice[1])(100'000'000'000'000)), Txflags(tfPassive)); env.close(); @@ -4893,7 +4895,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 2'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(bob_, XRP(50), btc(150)), Txflags(tfPassive)); env.close(); AMM const ammAlice(env, alice_, XRP(1'000), btc(1'050)); @@ -4912,7 +4914,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM ammAlice(env, alice_, XRP(10'000), btc(10'100)); env(offer(bob_, MPT(ammAlice[1])(100), XRP(100))); env.close(); @@ -4938,14 +4940,14 @@ private: .holders = {alice_, carol_}, .transferFee = 25'000, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, carol_}, .transferFee = 25'000, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, btc(1'000'000'000'000'000), eth(1'100'000'000'000'000)); // This offer succeeds to cross pre- and post-amendment // because the strand's out amount is small enough to match @@ -4974,7 +4976,7 @@ private: .holders = {alice_, carol_}, .transferFee = 100, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, alice_, XRP(1'000), btc(500'000'000'000'000)); env(offer(carol_, XRP(100), btc(55'000'000'000'000))); env.close(); @@ -4997,7 +4999,7 @@ private: .holders = {alice_, carol_}, .transferFee = 100, .pay = 3'000'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const amm(env, alice_, XRP(1'000), btc(50'000'000'000'000'000)); env(offer(carol_, XRP(10), btc(5'500'000'000'000'000))); env.close(); @@ -5017,14 +5019,14 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 20'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_, ed}, .transferFee = 25'000, .pay = 20'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice( env, alice_, btc(10'000'000'000'000'000), eth(11'000'000'000'000'000)); @@ -5064,14 +5066,14 @@ private: .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .transferFee = 25'000, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, btc(1'000), eth(1'100)); env(rate(gw_, 1.25)); env.close(); @@ -5107,28 +5109,28 @@ private: .holders = {alice_, bob_, carol_, dan, ed}, .transferFee = 25'000, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_, dan, ed}, .transferFee = 25'000, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const can( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_, dan, ed}, .transferFee = 25'000, .pay = 2'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const gbp( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_, dan, ed}, .transferFee = 25'000, .pay = 3'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, gbp(1'000'000), eth(10'125)); env(pay(gw_, bob_, can(1'953'125))); env.close(); @@ -5187,25 +5189,25 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 500'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 500'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const usd( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 500'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eur( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 500'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const xrpEur(env, alice_, XRP(10'100), eur(100'000'000'000'000'000)); AMM const eurBtc( env, alice_, eur(100'000'000'000'000'000), btc(102'000'000'000'000'000)); @@ -5260,25 +5262,25 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 50'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 50'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const usd( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 50'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eur( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 50'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const xrpEur(env, alice_, XRP(10'100), eur(10'000'000'000'000'000)); AMM const eurBtc(env, alice_, eur(10'000'000'000'000'000), btc(10'200'000'000'000'000)); AMM const btcUsd(env, alice_, btc(10'100'000'000'000'000), usd(10'000'000'000'000'000)); @@ -5313,13 +5315,13 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000'000'000'000'000)); for (int i = 0; i < 30; ++i) @@ -5349,13 +5351,13 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 400'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000'000'000'000'000)); for (int i = 0; i < 29; ++i) @@ -5386,7 +5388,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000'000'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(bob_, XRP(100), btc(100'001'000'000'000))); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'100'000'000'000'000)); @@ -5409,7 +5411,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.holder = carol_, .flags = tfMPTLock}); @@ -5430,7 +5432,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM const ammAlice(env, alice_, XRP(10'000), btc(10'000)); btc.set({.holder = alice_, .flags = tfMPTLock}); @@ -5601,7 +5603,7 @@ private: env.fund(XRP(10'000), lP1); env.fund(XRP(10'000), lP2); MPTTester const tst( - {.env = env, .issuer = gw, .holders = {lP1, lP2}, .flags = kMptDexFlags}); + {.env = env, .issuer = gw, .holders = {lP1, lP2}, .flags = kMPT_DEX_FLAGS}); env(offer(gw, XRP(11'500'000'000), tst(1'000'000'000'000'000))); @@ -5817,7 +5819,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_}, .pay = 30'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); auto const usd = gw_["USD"]; env.trust(usd(30'000), alice_); @@ -5940,7 +5942,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_, ed}, .pay = 30'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(carol_, btc(5'000000), USD(5))); AMM const ammAlice(env, alice_, USD(1'005), btc(1'000'000000)); @@ -5969,7 +5971,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_, ed}, .pay = 30'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(carol_, btc(5'000000), USD(5))); // Set 0.25% fee @@ -5996,7 +5998,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_, ed}, .pay = 30'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(carol_, btc(10'000000), USD(10))); // Set 1% fee @@ -6024,7 +6026,7 @@ private: .issuer = gw_, .holders = {alice_, bob_, carol_, ed}, .pay = 30'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(carol_, btc(9'000000), USD(9))); // Set 1% fee @@ -6070,7 +6072,7 @@ private: .issuer = gw, .holders = holders, .pay = 40'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); auto const usd = gw["USD"]; for (auto const& holder : holders) @@ -6161,7 +6163,7 @@ private: .issuer = gw, .holders = holders, .pay = 40'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); auto const usd = gw["USD"]; for (auto const& holder : holders) @@ -6254,8 +6256,7 @@ private: amm.deposit(carol_, 1'000); - auto affected = - env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; try { bool found = false; @@ -6297,9 +6298,9 @@ private: struct MPTList { - MPTTester const usd; - MPTTester const eth; - MPTTester const can; + MPTTester const USD; + MPTTester const ETH; + MPTTester const CAN; }; auto prep = [&](Env& env, uint16_t gwTransferFee, uint16_t gw1TransferFee) -> MPTList { @@ -6310,34 +6311,34 @@ private: .holders = {alice_, bob_, carol_, ed}, .transferFee = gwTransferFee, .pay = 2'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = gw1, .holders = {alice_, bob_, carol_, ed}, .transferFee = gw1TransferFee, .pay = 2'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); MPTTester can( {.env = env, .issuer = gw1, .holders = {alice_, bob_, carol_, ed}, .transferFee = gw1TransferFee, .pay = 2'000'000'000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env.close(); return MPTList{ - .usd = std::move(usd), - .eth = std::move(eth), - .can = std::move(can), + .USD = std::move(usd), + .ETH = std::move(eth), + .CAN = std::move(can), }; }; - static constexpr std::uint32_t kLowRate = 10'000; - static constexpr std::uint32_t kHighRate = 50'000; + std::uint32_t constexpr kLOW_RATE = 10'000; + std::uint32_t constexpr kHIGH_RATE = 50'000; for (auto const& rates : - {std::make_pair(kLowRate, kHighRate), std::make_pair(kHighRate, kLowRate)}) + {std::make_pair(kLOW_RATE, kHIGH_RATE), std::make_pair(kHIGH_RATE, kLOW_RATE)}) { // Offer Selection @@ -6355,9 +6356,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.usd; - auto eth = mpts.eth; - auto can = mpts.can; + auto usd = mpts.USD; + auto eth = mpts.ETH; + auto can = mpts.CAN; std::optional amm; if (i == 0 || i == 2) @@ -6400,9 +6401,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.usd; - auto eth = mpts.eth; - auto can = mpts.can; + auto usd = mpts.USD; + auto eth = mpts.ETH; + auto can = mpts.CAN; std::optional amm; if (i == 0 || i == 2) { @@ -6445,9 +6446,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.usd; - auto eth = mpts.eth; - auto can = mpts.can; + auto usd = mpts.USD; + auto eth = mpts.ETH; + auto can = mpts.CAN; std::optional amm; if (i == 0 || i == 2) { @@ -6471,7 +6472,7 @@ private: if (i == 2) { - if (rates.first == kLowRate) + if (rates.first == kLOW_RATE) { BEAST_EXPECT(expectOffers( env, @@ -6511,9 +6512,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.usd; - auto eth = mpts.eth; - auto can = mpts.can; + auto usd = mpts.USD; + auto eth = mpts.ETH; + auto can = mpts.CAN; std::optional amm; if (i == 0 || i == 2) { @@ -6536,7 +6537,7 @@ private: // limitQuality if (i == 2) { - if (rates.first == kLowRate) + if (rates.first == kLOW_RATE) { // Ed offer is partially crossed. // The updated rounding makes limitQuality @@ -6589,9 +6590,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.usd; - auto eth = mpts.eth; - auto can = mpts.can; + auto usd = mpts.USD; + auto eth = mpts.ETH; + auto can = mpts.CAN; std::optional amm; if (i == 0 || i == 2) @@ -6615,7 +6616,7 @@ private: { // NOLINTBEGIN(bugprone-unchecked-optional-access) i==2 implies amm is // emplaced (i>0) - if (rates.first == kLowRate) + if (rates.first == kLOW_RATE) { // Liquidity is consumed from AMM strand only BEAST_EXPECT(amm->expectBalances( @@ -6705,7 +6706,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 2'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); WithdrawArg const args{ .asset1Out = XRP(100), .asset2Out = btc(100), @@ -6728,7 +6729,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 2'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); btc(100).value().setJson(jv[jss::EPrice]); env(jv, Ter(telENV_RPC_FAILED)); }, @@ -6753,7 +6754,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 40'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(alice_, btc(1), USD(0.01))); env.close(); @@ -6787,7 +6788,7 @@ private: .issuer = gw_, .holders = {alice_, carol_}, .pay = 40'000'000000, - .flags = kMptDexFlags}); + .flags = kMPT_DEX_FLAGS}); env(offer(alice_, btc(1), XRP(0.01))); env.close(); @@ -6837,7 +6838,7 @@ private: .issuer = gw, .holders = {alice, bob}, .pay = 40'000'000000, - .flags = tfMPTCanClawback | tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanClawback | tfMPTCanLock | kMPT_DEX_FLAGS}); AMM amm(env, alice, btc(2), usd(1)); amm.deposit(alice, IOUAmount{1'876123487565916, -15}); @@ -6876,7 +6877,7 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); AMM amm(env, alice_, btc(100), XRP(100)); env.close(); @@ -6884,33 +6885,33 @@ private: cb(amm, btc); }; - // Deposit two assets, one of which is locked, - // then we should get tecLOCKED error. + // Deposit two assets, one of which is frozen, + // then we should get tecFROZEN error. { Env env(*this); testAMMDeposit(env, [&](AMM& amm, MPTTester& btc) { - amm.deposit(alice_, btc(100), XRP(100), std::nullopt, tfTwoAsset, Ter(tecLOCKED)); + amm.deposit(alice_, btc(100), XRP(100), std::nullopt, tfTwoAsset, Ter(tecFROZEN)); }); } - // Deposit one asset, which is the locked token, - // then we should get tecLOCKED error. + // Deposit one asset, which is the frozen token, + // then we should get tecFROZEN error. { Env env(*this); testAMMDeposit(env, [&](AMM& amm, MPTTester& btc) { amm.deposit( - alice_, btc(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecLOCKED)); + alice_, btc(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecFROZEN)); }); } // Deposit one asset which is not the frozen token, - // but the other asset is frozen. We should get tecLOCKED error + // but the other asset is frozen. We should get tecFROZEN error // when feature AMMClawback is enabled. { Env env(*this); testAMMDeposit(env, [&](AMM& amm, MPTTester& btc) { amm.deposit( - alice_, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecLOCKED)); + alice_, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecFROZEN)); }); } } @@ -6927,7 +6928,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); @@ -6935,7 +6936,7 @@ private: MPTTester const usd({.env = env, .issuer = gw_, .holders = {alice_}, .pay = 20'000}); MPTTester const btc({.env = env, .issuer = gw_, .holders = {alice_}, .pay = 20'000}); AMM amm(env, gw_, usd(10'000), btc(10'000)); - for (auto i = 0; i < kMaxDeletableAmmTrustLines + 10; ++i) + for (auto i = 0; i < kMAX_DELETABLE_AMM_TRUST_LINES + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); @@ -6981,7 +6982,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); @@ -6989,7 +6990,7 @@ private: MPTTester const usd({.env = env, .issuer = gw_, .holders = {alice_}, .pay = 20'000}); MPTTester const btc({.env = env, .issuer = gw_, .holders = {alice_}, .pay = 20'000}); AMM amm(env, gw_, usd(10'000), btc(10'000)); - for (auto i = 0; i < (kMaxDeletableAmmTrustLines * 2) + 10; ++i) + for (auto i = 0; i < (kMAX_DELETABLE_AMM_TRUST_LINES * 2) + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); @@ -7016,7 +7017,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); @@ -7035,12 +7036,12 @@ private: } // This test validates both invariant changes work together for - // the specific case of MPT/MPT pools with > kMaxDeletableAmmTrustLines. + // the specific case of MPT/MPT pools with > maxDeletableAMMTrustLines. { Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); @@ -7053,7 +7054,7 @@ private: // MPT/MPT pool with MANY trustlines AMM amm(env, gw_, usd(10'000), btc(10'000)); - for (auto i = 0; i < (kMaxDeletableAmmTrustLines * 2) + 10; ++i) + for (auto i = 0; i < (kMAX_DELETABLE_AMM_TRUST_LINES * 2) + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 64972c24ab..8e2c0255ef 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -553,11 +552,11 @@ private: { // bad preflight1 - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::Account] = alice_.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::KNone); jv[jss::Fee] = "-1"; env(jv, Ter(temBAD_FEE)); } @@ -568,12 +567,12 @@ private: alice_, IOUAmount{-1}, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS)); { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::Account] = alice_.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::Values::None); - jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::KNone); + jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::KNone); jv[jss::Flags] = tfLPToken; env(jv, Ter(temBAD_AMM_TOKENS)); } @@ -2625,6 +2624,10 @@ private: using namespace jtx; using namespace std::chrono; + // For now, just disable SAV entirely, which locks in the small Number + // mantissas + features = features - featureSingleAssetVault - featureLendingProtocol; + // Auction slot initially is owned by AMM creator, who pays 0 price. // Bid 110 tokens. Pay bidMin. @@ -2727,17 +2730,18 @@ private: // 1st Interval after close, price for 0th interval. env(ammAlice.bid({.account = bob_})); - env.close(seconds(kAuctionSlotIntervalDuration + 1)); + env.close(seconds(kAUCTION_SLOT_INTERVAL_DURATION + 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 * kAuctionSlotIntervalDuration) + 1)); + env.close(seconds((10 * kAUCTION_SLOT_INTERVAL_DURATION) + 1)); 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((kAuctionSlotTimeIntervals * kAuctionSlotIntervalDuration) + 1)); + env.close( + seconds((kAUCTION_SLOT_TIME_INTERVALS * kAUCTION_SLOT_INTERVAL_DURATION) + 1)); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); // 0 Interval. @@ -2964,7 +2968,7 @@ private: ammTokens)); } // Auction slot expired, no discounted fee - env.close(seconds(kTotalTimeSlotSecs + 1)); + env.close(seconds(kTOTAL_TIME_SLOT_SECS + 1)); // clock is parent's based env.close(); if (!features[fixAMMv1_1]) @@ -3053,7 +3057,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { // Bid a tiny amount - auto const tiny = Number{STAmount::kMinValue, STAmount::kMinOffset}; + auto const tiny = Number{STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET}; 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. @@ -3063,7 +3067,7 @@ private: // Bid the tiny amount env(ammAlice.bid({ .account = alice_, - .bidMin = IOUAmount{STAmount::kMinValue, STAmount::kMinOffset}, + .bidMin = IOUAmount{STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET}, })); // Pay slightly higher price BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny * Number{105, -2}})); @@ -3221,9 +3225,9 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const baseFee = env.current()->fees().base; env(escrow::create(carol_, ammAlice.ammAccount(), XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); }); @@ -3333,6 +3337,11 @@ private: testcase("Basic Payment"); using namespace jtx; + // For now, just disable SAV entirely, which locks in the small Number + // mantissas + features = + features - featureSingleAssetVault - featureLendingProtocol - featureLendingProtocol; + // Payment 100USD for 100XRP. // Force one path with tfNoRippleDirect. testAMM( @@ -5084,13 +5093,13 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); fund(env, gw_, {alice_}, XRP(20'000), {USD(10'000)}); AMM amm(env, gw_, XRP(10'000), USD(10'000)); - for (auto i = 0; i < kMaxDeletableAmmTrustLines + 10; ++i) + for (auto i = 0; i < kMAX_DELETABLE_AMM_TRUST_LINES + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); @@ -5142,13 +5151,13 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); + cfg->FEES.reference_fee = XRPAmount(1); return cfg; }), all); fund(env, gw_, {alice_}, XRP(20'000), {USD(10'000)}); AMM amm(env, gw_, XRP(10'000), USD(10'000)); - for (auto i = 0; i < (kMaxDeletableAmmTrustLines * 2) + 10; ++i) + for (auto i = 0; i < (kMAX_DELETABLE_AMM_TRUST_LINES * 2) + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); @@ -5206,8 +5215,7 @@ private: fail(); } amm.deposit(carol_, 1'000); - auto affected = - env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; try { bool found = false; @@ -6718,9 +6726,9 @@ private: AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); env(pay(env.master.id(), accountId, XRP(1000)), - Seq(kAutofill), - Fee(kAutofill), - Sig(kAutofill)); + Seq(kAUTOFILL), + Fee(kAUTOFILL), + Sig(kAUTOFILL)); } AMM const ammAlice( @@ -7072,95 +7080,6 @@ private: {all}); } - void - testStaleAuthAccountsAfterReinit(FeatureBitset features) - { - testcase("Test AuthAccounts reset after empty pool reinitialization"); - using namespace jtx; - - Env env( - *this, - envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = XRPAmount(1); - return cfg; - }), - features); - Account const dan("dan"); - Account const ed("ed"); - fund(env, gw_, {alice_, carol_, bob_, dan, ed}, XRP(50'000), {USD(50'000)}); - AMM amm(env, alice_, XRP(10'000), USD(10'000)); - // Create excess trustlines to prevent AMM auto-deletion on withdrawal. - for (auto i = 0; i < kMaxDeletableAmmTrustLines + 10; ++i) - { - Account const a{std::to_string(i)}; - env.fund(XRP(1'000), a); - env(trust(a, STAmount{amm.lptIssue(), 10'000})); - env.close(); - } - // Carol deposits so she has LP tokens to bid. - amm.deposit(carol_, 1'000'000); - // Carol wins the auction slot, authorizing bob and dan. - env(amm.bid({ - .account = carol_, - .bidMin = 100, - .authAccounts = {bob_, dan}, - })); - env.close(); - BEAST_EXPECT(amm.expectAuctionSlot({bob_.id(), dan.id()})); - // Withdraw all — AMM enters empty state but is not deleted because - // excess trustlines prevent auto-deletion. - amm.withdrawAll(alice_); - amm.withdrawAll(carol_); - BEAST_EXPECT(amm.ammExists()); - // Pre-conditions before re-init: AMM is empty and stale sfAuthAccounts - // from carol's bid are still present. - BEAST_EXPECT(amm.getLPTokensBalance() == IOUAmount{0}); - BEAST_EXPECT(amm.expectAuctionSlot({bob_.id(), dan.id()})); - // Ed re-initializes the AMM via tfTwoAssetIfEmpty with fee=500. - amm.deposit( - ed, - std::nullopt, - XRP(10'000), - USD(10'000), - std::nullopt, - tfTwoAssetIfEmpty, - std::nullopt, - std::nullopt, - 500); - - auto const ammSle = env.current()->read(keylet::amm(amm[0], amm[1])); - BEAST_EXPECT(ammSle && ammSle->isFieldPresent(sfAuctionSlot)); - auto const& slot = safeDowncast(ammSle->peekAtField(sfAuctionSlot)); - - // sfDiscountedFee = 500 / AUCTION_SLOT_DISCOUNTED_FEE_FRACTION = 50, - // sfPrice = 0 (reset on init), time interval = 0 (freshly issued slot). - BEAST_EXPECT(amm.expectAuctionSlot(50, 0, IOUAmount{0})); - // sfAccount must be the re-initializing depositor, not the previous - // slot holder (carol). - BEAST_EXPECT(slot[sfAccount] == ed.id()); - // sfTradingFee on the AMM SLE must reflect ed's deposit fee. - BEAST_EXPECT(ammSle->getFieldU16(sfTradingFee) == 500); - // sfVoteSlots must be reset to a single entry for ed. - auto const& votes = ammSle->getFieldArray(sfVoteSlots); - BEAST_EXPECT(votes.size() == 1); - if (!votes.empty()) - { - BEAST_EXPECT(votes[0].getAccountID(sfAccount) == ed.id()); - BEAST_EXPECT(votes[0].getFieldU16(sfTradingFee) == 500); - BEAST_EXPECT(votes[0].getFieldU32(sfVoteWeight) == kVoteWeightScaleFactor); - } - // sfAuthAccounts behaviour depends on the fix. - if (features[fixCleanup3_2_0]) - { - BEAST_EXPECT(!slot.isFieldPresent(sfAuthAccounts)); - } - else - { - BEAST_EXPECT( - slot.isFieldPresent(sfAuthAccounts) && !slot.getFieldArray(sfAuthAccounts).empty()); - } - } - void run() override { @@ -7231,8 +7150,6 @@ private: testWithdrawRounding(all); testWithdrawRounding(all - fixAMMv1_3); testFailedPseudoAccount(); - testStaleAuthAccountsAfterReinit(all); - testStaleAuthAccountsAfterReinit(all - fixCleanup3_2_0); } }; diff --git a/src/test/app/AccountDelete_test.cpp b/src/test/app/AccountDelete_test.cpp index 951f99919b..a30691b175 100644 --- a/src/test/app/AccountDelete_test.cpp +++ b/src/test/app/AccountDelete_test.cpp @@ -57,8 +57,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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; // Verify DeliveredAmount and delivered_amount metadata are correct. // We can't use env.meta() here, because meta() doesn't include @@ -72,7 +71,7 @@ private: // DeliveredAmount and delivered_amount should both be present and // equal amount. - json::Value const jsonExpect{amount.getJson(JsonOptions::Values::None)}; + json::Value const jsonExpect{amount.getJson(JsonOptions::KNone)}; BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == jsonExpect); BEAST_EXPECT(meta[jss::delivered_amount] == jsonExpect); } @@ -91,7 +90,7 @@ private: jv[jss::TransactionType] = jss::PaymentChannelCreate; jv[jss::Account] = account.human(); jv[jss::Destination] = to.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv[sfSettleDelay.jsonName] = settleDelay.count(); jv[sfCancelAfter.jsonName] = cancelAfter.time_since_epoch().count() + 2; jv[sfPublicKey.jsonName] = strHex(pk.slice()); @@ -215,7 +214,7 @@ public: 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::kTicket(carol.id(), carolTicketSeq))); + BEAST_EXPECT(env.closed()->exists(keylet::kTICKET(carol.id(), carolTicketSeq))); BEAST_EXPECT(env.closed()->exists(keylet::signers(carol.id()))); // Delete carol's account even with stuff in her directory. Show @@ -229,7 +228,7 @@ public: 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::kTicket(carol.id(), carolTicketSeq))); + BEAST_EXPECT(!env.closed()->exists(keylet::kTICKET(carol.id(), carolTicketSeq))); BEAST_EXPECT(!env.closed()->exists(keylet::signers(carol.id()))); // Verify that Carol's XRP, minus the fee, was transferred to becky. @@ -341,8 +340,8 @@ public: using namespace std::chrono_literals; std::uint32_t const escrowSeq{env.seq(alice)}; env(escrow::create(alice, becky, XRP(333)), - escrow::kFinishTime(env.now() + 3s), - escrow::kCancelTime(env.now() + 4s)); + escrow::kFINISH_TIME(env.now() + 3s), + escrow::kCANCEL_TIME(env.now() + 4s)); env.close(); // alice and becky should be unable to delete their accounts because @@ -370,8 +369,8 @@ public: std::uint32_t const escrowSeq{env.seq(carol)}; env(escrow::create(carol, becky, usd(1)), - escrow::kFinishTime(env.now() + 3s), - escrow::kCancelTime(env.now() + 4s)); + escrow::kFINISH_TIME(env.now() + 3s), + escrow::kCANCEL_TIME(env.now() + 4s)); env.close(); incLgrSeqForAccDel(env, gw1); @@ -461,8 +460,8 @@ public: // Alice creates 1001 offers. This is one greater than the number of // directory entries an AccountDelete will remove. std::uint32_t const offerSeq0{env.seq(alice)}; - static constexpr int kOfferCount{1001}; - for (int i{0}; i < kOfferCount; ++i) + constexpr int kOFFER_COUNT{1001}; + for (int i{0}; i < kOFFER_COUNT; ++i) { env(offer(alice, gw[currency](1), XRP(1))); env.close(); @@ -498,11 +497,11 @@ public: BEAST_EXPECT(closed->exists(aliceOwnerDirKey)); // alice's directory nodes. - for (std::uint32_t i{0}; i < ((kOfferCount / 32) + 1); ++i) + for (std::uint32_t i{0}; i < ((kOFFER_COUNT / 32) + 1); ++i) BEAST_EXPECT(closed->exists(keylet::page(aliceOwnerDirKey, i))); // alice's offers. - for (std::uint32_t i{0}; i < kOfferCount; ++i) + for (std::uint32_t i{0}; i < kOFFER_COUNT; ++i) BEAST_EXPECT(closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); } @@ -513,10 +512,10 @@ public: env(acctdelete(alice, gw), Fee(acctDelFee), Ter(tefTOO_BIG)); // Cancel one of alice's offers. Then the account delete can succeed. - env.require(offers(alice, kOfferCount)); + env.require(offers(alice, kOFFER_COUNT)); env(offerCancel(alice, offerSeq0)); env.close(); - env.require(offers(alice, kOfferCount - 1)); + env.require(offers(alice, kOFFER_COUNT - 1)); // alice successfully deletes her account. auto const alicePreDelBal{env.balance(alice)}; @@ -532,11 +531,11 @@ public: BEAST_EXPECT(!closed->exists(aliceOwnerDirKey)); // alice's former directory nodes. - for (std::uint32_t i{0}; i < ((kOfferCount / 32) + 1); ++i) + for (std::uint32_t i{0}; i < ((kOFFER_COUNT / 32) + 1); ++i) BEAST_EXPECT(!closed->exists(keylet::page(aliceOwnerDirKey, i))); // alice's former offers. - for (std::uint32_t i{0}; i < kOfferCount; ++i) + for (std::uint32_t i{0}; i < kOFFER_COUNT; ++i) BEAST_EXPECT(!closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); } } @@ -662,7 +661,7 @@ public: BEAST_EXPECT(closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { - BEAST_EXPECT(closed->exists(keylet::kTicket(bob.id(), ticketSeq + i))); + BEAST_EXPECT(closed->exists(keylet::kTICKET(bob.id(), ticketSeq + i))); } } @@ -681,7 +680,7 @@ public: BEAST_EXPECT(!closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { - BEAST_EXPECT(!closed->exists(keylet::kTicket(bob.id(), ticketSeq + i))); + BEAST_EXPECT(!closed->exists(keylet::kTICKET(bob.id(), ticketSeq + i))); } } } diff --git a/src/test/app/AccountSet_test.cpp b/src/test/app/AccountSet_test.cpp index 6688e3693f..c30553dad9 100644 --- a/src/test/app/AccountSet_test.cpp +++ b/src/test/app/AccountSet_test.cpp @@ -536,7 +536,7 @@ public: env(fset(alice, asfRequireAuth), Ter(tecOWNERS)); // Remove the signer list. After that asfRequireAuth should succeed. - env(signers(alice, test::jtx::kNone)); + env(signers(alice, test::jtx::kNONE)); env.close(); BEAST_EXPECT(dirIsEmpty(*env.closed(), keylet::ownerDir(alice))); diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index 30ea780eef..6697be44e0 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -30,7 +30,7 @@ class AccountTxPaging_test : public beast::unit_test::Suite int ledgerMax, int limit, bool forward, - json::Value const& marker = json::ValueType::Null) + json::Value const& marker = json::NullValue) { json::Value jvc; jvc[jss::account] = account.human(); diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index 219aaabdda..5d4ca6f745 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -208,7 +208,7 @@ public: std::unique_ptr makeTable(test::jtx::Env& env, std::chrono::seconds majorityTime) { - static std::vector const kSupported = combine( + static std::vector const kSUPPORTED = combine( makeDefaultYes(yes_), // Use non-intuitive default votes for "enabled_" and "vetoed_" // so that when the tests later explicitly enable or veto them, @@ -218,7 +218,7 @@ public: makeDefaultYes(vetoed_), makeObsolete(obsolete_)); return makeTable( - env.app(), majorityTime, kSupported, makeSection(enabled_), makeSection(vetoed_)); + env.app(), majorityTime, kSUPPORTED, makeSection(enabled_), makeSection(vetoed_)); } void @@ -1165,7 +1165,7 @@ public: testcase("hasUnsupportedEnabled"); using namespace std::chrono_literals; - constexpr weeks kW(1); + weeks constexpr kW(1); test::jtx::Env env{*this, makeConfig()}; auto table = makeTable(env, kW); BEAST_EXPECT(!table->hasUnsupportedEnabled()); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 8755fe9f9c..8010b1e120 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -388,8 +388,8 @@ class Batch_test : public beast::unit_test::Suite auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 2); auto tx1 = pay(alice, bob, XRP(1)); - tx1[sfSigners.jsonName] = json::ValueType::Array; - tx1[sfSigners.jsonName][0U][sfSigner.jsonName] = json::ValueType::Object; + 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()); @@ -1363,8 +1363,8 @@ class Batch_test : public beast::unit_test::Suite auto const ammCreate = [&alice](STAmount const& amount, STAmount const& amount2) { json::Value jv; jv[jss::Account] = alice.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); - jv[jss::Amount2] = amount2.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); + jv[jss::Amount2] = amount2.getJson(JsonOptions::KNone); jv[jss::TradingFee] = 0; jv[jss::TransactionType] = jss::AMMCreate; return jv; @@ -2346,7 +2346,7 @@ class Batch_test : public beast::unit_test::Suite // + has `tfInnerBatchTxn` flag { auto txn = batch::Inner(pay(alice, bob, XRP(1)), env.seq(alice)); - txn[sfSigners] = json::ValueType::Array; + txn[sfSigners] = json::ArrayValue; STParsedJSONObject parsed("test", txn.getTxn()); Serializer s; parsed.object->add(s); // NOLINT(bugprone-unchecked-optional-access) @@ -2401,7 +2401,7 @@ class Batch_test : public beast::unit_test::Suite obj.setFieldU32(sfLedgerSequence, seq); obj.setFieldU32(sfFlags, tfInnerBatchTxn); }); - auto txn = batch::Inner(amendTx.getJson(JsonOptions::Values::None), env.seq(alice)); + auto txn = batch::Inner(amendTx.getJson(JsonOptions::KNone), env.seq(alice)); STParsedJSONObject parsed("test", txn.getTxn()); Serializer s; parsed.object->add(s); // NOLINT(bugprone-unchecked-optional-access) @@ -2658,7 +2658,7 @@ class Batch_test : public beast::unit_test::Suite testcase("loan"); bool const lendingBatchEnabled = !std::ranges::any_of( - Batch::kDisabledTxTypes, + Batch::kDISABLED_TX_TYPES, [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); using namespace test::jtx; @@ -2699,10 +2699,10 @@ class Batch_test : public beast::unit_test::Suite { using namespace loanBroker; env(set(lender, vaultKeylet.key), - kManagementFeeRate(TenthBips16(100)), - kDebtMaximum(debtMaximumValue), - kCoverRateMinimum(TenthBips32(percentageToTenthBips(10))), - kCoverRateLiquidation(TenthBips32(percentageToTenthBips(25)))); + kMANAGEMENT_FEE_RATE(TenthBips16(100)), + kDEBT_MAXIMUM(debtMaximumValue), + kCOVER_RATE_MINIMUM(TenthBips32(percentageToTenthBips(10))), + kCOVER_RATE_LIQUIDATION(TenthBips32(percentageToTenthBips(25)))); env(coverDeposit(lender, brokerKeylet.key, coverDepositValue)); @@ -2727,9 +2727,9 @@ class Batch_test : public beast::unit_test::Suite set(lender, brokerKeylet.key, asset(1000).value()), // Not allowed to include the counterparty signature Sig(sfCounterpartySignature, borrower), - Sig(kNone), - Fee(kNone), - Seq(kNone)), + Sig(kNONE), + Fee(kNONE), + Seq(kNONE)), lenderSeq + 1), batch::Inner( pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), @@ -2744,9 +2744,9 @@ class Batch_test : public beast::unit_test::Suite env.json( set(lender, brokerKeylet.key, asset(1000).value()), // Counterparty must be set - Sig(kNone), - Fee(kNone), - Seq(kNone)), + Sig(kNONE), + Fee(kNONE), + Seq(kNONE)), lenderSeq + 1), batch::Inner( pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), @@ -2761,10 +2761,10 @@ class Batch_test : public beast::unit_test::Suite env.json( set(lender, brokerKeylet.key, asset(1000).value()), // Counterparty must sign the outer transaction - kCounterparty(borrower.id()), - Sig(kNone), - Fee(kNone), - Seq(kNone)), + kCOUNTERPARTY(borrower.id()), + Sig(kNONE), + Fee(kNONE), + Seq(kNONE)), lenderSeq + 1), batch::Inner( pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), @@ -2782,10 +2782,10 @@ class Batch_test : public beast::unit_test::Suite batch::Inner( env.json( set(lender, brokerKeylet.key, asset(1000).value()), - kCounterparty(borrower.id()), - Sig(kNone), - Fee(kNone), - Seq(kNone)), + kCOUNTERPARTY(borrower.id()), + Sig(kNONE), + Fee(kNONE), + Seq(kNONE)), lenderSeq + 1), batch::Inner( pay( @@ -2814,10 +2814,10 @@ class Batch_test : public beast::unit_test::Suite batch::Inner( env.json( set(lender, brokerKeylet.key, asset(1000).value()), - kCounterparty(borrower.id()), - Sig(kNone), - Fee(kNone), - Seq(kNone)), + kCOUNTERPARTY(borrower.id()), + Sig(kNONE), + Fee(kNONE), + Seq(kNONE)), lenderSeq + 1), batch::Inner(manage(lender, loanKeylet.key, tfLoanImpair), lenderSeq + 2), batch::Sig(borrower)); @@ -3784,7 +3784,7 @@ class Batch_test : public beast::unit_test::Suite makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), features, nullptr, - beast::Severity::Error}; + beast::severities::KError}; auto alice = Account("alice"); auto bob = Account("bob"); @@ -3840,7 +3840,7 @@ class Batch_test : public beast::unit_test::Suite makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), features, nullptr, - beast::Severity::Error}; + beast::severities::KError}; auto alice = Account("alice"); auto bob = Account("bob"); @@ -3885,7 +3885,7 @@ class Batch_test : public beast::unit_test::Suite using namespace test::jtx; using namespace std::literals; - Env env(*this, envconfig(), features, nullptr, beast::Severity::Disabled); + Env env(*this, envconfig(), features, nullptr, beast::severities::KDisabled); auto alice = Account("alice"); auto bob = Account("bob"); @@ -4321,7 +4321,7 @@ class Batch_test : public beast::unit_test::Suite 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(kInitialXrp)); + BEAST_EXPECT(txBaseFee == XRPAmount(kINITIAL_XRP)); } // bad: Raw Transactions array exceeds max entries. @@ -4342,7 +4342,7 @@ class Batch_test : public beast::unit_test::Suite batch::Inner(pay(alice, bob, XRP(1)), seq + 9)); XRPAmount const txBaseFee = getBaseFee(jtx); - BEAST_EXPECT(txBaseFee == XRPAmount(kInitialXrp)); + BEAST_EXPECT(txBaseFee == XRPAmount(kINITIAL_XRP)); } // bad: Signers array exceeds max entries. @@ -4356,7 +4356,7 @@ class Batch_test : public beast::unit_test::Suite batch::Inner(pay(alice, bob, XRP(5)), seq + 2), batch::Sig(bob, carol, alice, bob, carol, alice, bob, carol, alice, alice)); XRPAmount const txBaseFee = getBaseFee(jtx); - BEAST_EXPECT(txBaseFee == XRPAmount(kInitialXrp)); + BEAST_EXPECT(txBaseFee == XRPAmount(kINITIAL_XRP)); } // good: diff --git a/src/test/app/CheckMPT_test.cpp b/src/test/app/CheckMPT_test.cpp index 861a115fc9..418b7a4a71 100644 --- a/src/test/app/CheckMPT_test.cpp +++ b/src/test/app/CheckMPT_test.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -53,11 +54,11 @@ namespace xrpl { class CheckMPT_test : public beast::unit_test::Suite { // Helper function that returns the Checks on an account. - static std::vector + static std::vector> checksOnAccount(test::jtx::Env& env, test::jtx::Account account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle && sle->getType() == ltCHECK) result.push_back(sle); }); @@ -72,8 +73,7 @@ class CheckMPT_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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; // Verify DeliveredAmount and delivered_amount metadata are correct. env.close(); @@ -85,8 +85,8 @@ class CheckMPT_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::Values::None)); - BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::Values::None)); + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == amount.getJson(JsonOptions::KNone)); + BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::KNone)); } void @@ -282,7 +282,7 @@ class CheckMPT_test : public beast::unit_test::Suite STAmount const startBalance{XRP(1'000).value()}; env.fund(startBalance, gw1, gwF, alice, bob); - auto usdm = MPTTester({.env = env, .issuer = gw1, .flags = kMptDexFlags | tfMPTCanLock}); + auto usdm = MPTTester({.env = env, .issuer = gw1, .flags = kMPT_DEX_FLAGS | tfMPTCanLock}); MPT const usd = usdm; // Bad fee. @@ -348,7 +348,7 @@ class CheckMPT_test : public beast::unit_test::Suite // Globally frozen asset. env.close(); auto usfm = - MPTTester({.env = env, .issuer = gwF, .flags = kMptDexFlags | tfMPTCanLock}); + MPTTester({.env = env, .issuer = gwF, .flags = kMPT_DEX_FLAGS | tfMPTCanLock}); MPT const usf = usfm; usfm.set({.flags = tfMPTLock}); @@ -662,7 +662,7 @@ class CheckMPT_test : public beast::unit_test::Suite {.env = env, .issuer = gw, .holders = {alice}, - .flags = kMptDexFlags | tfMPTRequireAuth, + .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth, .maxAmt = 20}); MPT const usd = usdm; usdm.authorize({.holder = alice}); @@ -855,7 +855,7 @@ class CheckMPT_test : public beast::unit_test::Suite {.env = env, .issuer = gw, .holders = {alice}, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .maxAmt = maxAmt}); MPT const usd = usdm; @@ -928,7 +928,7 @@ class CheckMPT_test : public beast::unit_test::Suite // Both Amount and DeliverMin present. { json::Value tx{check::cash(bob, chkId, amount)}; - tx[sfDeliverMin.jsonName] = amount.getJson(JsonOptions::Values::None); + tx[sfDeliverMin.jsonName] = amount.getJson(JsonOptions::KNone); env(tx, Ter(temMALFORMED)); env.close(); } @@ -1421,7 +1421,7 @@ class CheckMPT_test : public beast::unit_test::Suite Throw("AccountOwns: must be issuer"); if (auto const& it = mpts.find(s); it != mpts.end()) return it->second[s]; - auto flags = kMptDexFlags | tfMPTCanLock; + auto flags = kMPT_DEX_FLAGS | tfMPTCanLock; if (requireAuth) flags |= tfMPTRequireAuth; auto [it, _] = @@ -1859,10 +1859,10 @@ class CheckMPT_test : public beast::unit_test::Suite // Use offers to automatically create MPT. MPT const oF4 = gw1["OF4"]; gw1.set(oF4, tfMPTLock); - env(offer(gw1, XRP(92), oF4(92)), Ter(tecLOCKED)); + env(offer(gw1, XRP(92), oF4(92)), Ter(tecFROZEN)); env.close(); BEAST_EXPECT(env.le(keylet::mptoken(oF4, alice)) == nullptr); - env(offer(alice, oF4(92), XRP(92)), Ter(tecLOCKED)); + env(offer(alice, oF4(92), XRP(92)), Ter(tecFROZEN)); env.close(); // No one's owner count should have changed. @@ -1950,10 +1950,10 @@ class CheckMPT_test : public beast::unit_test::Suite // Use offers to automatically create MPT. MPT const oF4 = gw1["OF4"]; gw1.set(oF4, tfMPTLock); - env(offer(alice, XRP(91), oF4(91)), Ter(tecLOCKED)); + env(offer(alice, XRP(91), oF4(91)), Ter(tecFROZEN)); env.close(); BEAST_EXPECT(env.le(keylet::mptoken(oF4, alice)) == nullptr); - env(offer(bob, oF4(91), XRP(91)), Ter(tecLOCKED)); + env(offer(bob, oF4(91), XRP(91)), Ter(tecFROZEN)); env.close(); // No one's owner count should have changed. diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 9b814a24b1..ad44ff5729 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -43,6 +43,7 @@ #include #include +#include #include #include @@ -57,11 +58,11 @@ class Check_test : public beast::unit_test::Suite } // Helper function that returns the Checks on an account. - static std::vector + static std::vector> checksOnAccount(test::jtx::Env& env, test::jtx::Account account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle && sle->getType() == ltCHECK) result.push_back(sle); }); @@ -76,8 +77,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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; // Verify DeliveredAmount and delivered_amount metadata are correct. env.close(); @@ -89,8 +89,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::Values::None)); - BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::Values::None)); + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == amount.getJson(JsonOptions::KNone)); + BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::KNone)); } void @@ -1326,7 +1326,7 @@ class Check_test : public beast::unit_test::Suite // Both Amount and DeliverMin present. { json::Value tx{check::cash(bob, chkId, amount)}; - tx[sfDeliverMin.jsonName] = amount.getJson(JsonOptions::Values::None); + tx[sfDeliverMin.jsonName] = amount.getJson(JsonOptions::KNone); env(tx, Ter(temMALFORMED)); env.close(); } @@ -1727,8 +1727,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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; env.close(); json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; diff --git a/src/test/app/ClawbackMPT_test.cpp b/src/test/app/ClawbackMPT_test.cpp deleted file mode 100644 index 299e63d028..0000000000 --- a/src/test/app/ClawbackMPT_test.cpp +++ /dev/null @@ -1,435 +0,0 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace xrpl { - -class ClawbackMPT_test : public beast::unit_test::Suite -{ - static std::uint32_t - ticketCount(test::jtx::Env const& env, test::jtx::Account const& acct) - { - std::uint32_t ret{0}; - if (auto const sleAcct = env.le(acct)) - ret = sleAcct->at(~sfTicketCount).value_or(0); - return ret; - } - - void - testValidation(FeatureBitset features) - { - testcase("Validation"); - using namespace test::jtx; - - // MPT clawback fails when featureMPTokensV1 is disabled - { - Env env(*this, features - featureMPTokensV1); - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(1000), alice, bob); - env.close(); - - auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); - - env(claw(alice, mpt(5), bob), Ter(temDISABLED)); - env.close(); - } - - // MPT clawback fails when tfMPTCanClawback is not set on the issuance - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 100); - - mptAlice.claw(alice, bob, 10, tecNO_PERMISSION); - } - - // Test preflight validation failures - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(1000), alice, bob); - env.close(); - - auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); - - // fails due to invalid flag - env(claw(alice, mpt(5), bob), Txflags(0x00008000), Ter(temINVALID_FLAG)); - env.close(); - - // fails due to zero amount - env(claw(alice, mpt(0), bob), Ter(temBAD_AMOUNT)); - env.close(); - - // fails due to negative amount - env(claw(alice, mpt(-1), bob), Ter(temBAD_AMOUNT)); - env.close(); - - // fails when holder is not specified - env(claw(alice, mpt(5)), Ter(temMALFORMED)); - env.close(); - - // fails when issuer and holder are the same account - env(claw(alice, mpt(5), alice), Ter(temMALFORMED)); - env.close(); - } - - // Test preclaim failures - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - - auto const fakeMpt = - xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); - - // clawback fails when the issuance does not exist - env(claw(alice, fakeMpt(5), bob), Ter(tecOBJECT_NOT_FOUND)); - env.close(); - - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - - // clawback fails when bob has no MPToken - mptAlice.claw(alice, bob, 5, tecOBJECT_NOT_FOUND); - - mptAlice.authorize({.account = bob}); - - // clawback fails because bob's balance is 0 - mptAlice.claw(alice, bob, 5, tecINSUFFICIENT_FUNDS); - } - } - - void - testPermission(FeatureBitset features) - { - testcase("Permission"); - using namespace test::jtx; - - // Clawing back from a non-existent account fails - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - // bob is not funded and does not exist - MPTTester mptAlice(env, alice, MPTInit{}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - - mptAlice.claw(alice, bob, 5, terNO_ACCOUNT); - } - - // A non-issuer cannot claw back MPT - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const cindy{"cindy"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - env.fund(XRP(1000), cindy); - env.close(); - - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - // cindy fails to claw because she is not the issuer - mptAlice.claw(cindy, bob, 200, tecNO_PERMISSION); - } - } - - void - testEnabled(FeatureBitset features) - { - testcase("Enable clawback"); - using namespace test::jtx; - - // Test that alice is able to successfully clawback MPT from bob - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 1000)); - - // alice claws back 200 tokens from bob - mptAlice.claw(alice, bob, 200); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 800)); - - // alice claws back remaining 800 tokens - mptAlice.claw(alice, bob, 800); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 0)); - } - - void - testMultiIssuance(FeatureBitset features) - { - testcase("Multi issuance"); - using namespace test::jtx; - - // Two issuers each issue their own MPT to cindy. - // Clawback from one does not affect the other. - { - Env env(*this, features); - - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const cindy{"cindy"}; - - MPTTester mptAlice(env, alice, {.holders = {cindy}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = cindy}); - mptAlice.pay(alice, cindy, 1000); - - MPTTester mptBob(env, bob, MPTInit{}); // cindy already funded by mptAlice - mptBob.create({.ownerCount = 1, .flags = tfMPTCanClawback}); - mptBob.authorize({.account = cindy}); - mptBob.pay(bob, cindy, 1000); - - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 1000)); - BEAST_EXPECT(mptBob.checkMPTokenAmount(cindy, 1000)); - - // alice claws back 200 from cindy, bob's issuance is unaffected - mptAlice.claw(alice, cindy, 200); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 800)); - BEAST_EXPECT(mptBob.checkMPTokenAmount(cindy, 1000)); - - // bob claws back 600 from cindy, alice's issuance is unaffected - mptBob.claw(bob, cindy, 600); - BEAST_EXPECT(mptBob.checkMPTokenAmount(cindy, 400)); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 800)); - } - - // One issuer issues MPT to two different holders. - // Clawback from one holder does not affect the other. - { - Env env(*this, features); - - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const cindy{"cindy"}; - - MPTTester mptAlice(env, alice, {.holders = {bob, cindy}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.authorize({.account = cindy}); - mptAlice.pay(alice, bob, 600); - mptAlice.pay(alice, cindy, 1000); - - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 600)); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 1000)); - - // alice claws back 500 from bob, cindy's balance is unchanged - mptAlice.claw(alice, bob, 500); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 100)); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 1000)); - - // alice claws back 300 from cindy, bob's balance is unchanged - mptAlice.claw(alice, cindy, 300); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(cindy, 700)); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 100)); - } - } - - void - testZeroBalanceAfterClawback(FeatureBitset features) - { - testcase("Zero balance after clawback"); - using namespace test::jtx; - - // After clawback reduces balance to zero, the MPToken object - // still exists (unlike IOU trustlines which are deleted). - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - BEAST_EXPECT(ownerCount(env, bob) == 1); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 1000)); - - // alice claws back the full amount - mptAlice.claw(alice, bob, 1000); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 0)); - - // bob still holds the MPToken object (balance 0, not deleted) - BEAST_EXPECT(ownerCount(env, bob) == 1); - } - - void - testLockedMPT(FeatureBitset features) - { - testcase("Locked MPT"); - using namespace test::jtx; - - // Test that globally locked MPT can still be clawed back - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - // globally lock the issuance - mptAlice.set({.account = alice, .flags = tfMPTLock}); - - // clawback succeeds despite global lock - mptAlice.claw(alice, bob, 200); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 800)); - } - - // Test that individually locked MPT can still be clawed back - { - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - // individually lock bob's MPToken - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); - - // clawback succeeds despite individual lock - mptAlice.claw(alice, bob, 200); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 800)); - } - } - - void - testAmountExceedsAvailable(FeatureBitset features) - { - testcase("Amount exceeds available"); - using namespace test::jtx; - - // When alice tries to claw back more than bob holds, - // only the available balance is clawed back - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 1000); - - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 1000)); - - // alice tries to claw back 2000, but bob only has 1000 - mptAlice.claw(alice, bob, 2000); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 0)); - BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(0)); - - // MPToken object still exists with 0 balance - BEAST_EXPECT(ownerCount(env, bob) == 1); - } - - void - testTickets(FeatureBitset features) - { - testcase("Tickets"); - using namespace test::jtx; - - // Tests MPT clawback using tickets - Env env(*this, features); - Account const alice{"alice"}; - Account const bob{"bob"}; - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); - mptAlice.authorize({.account = bob}); - mptAlice.pay(alice, bob, 100); - - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 100)); - - // alice creates 10 tickets - std::uint32_t ticketCnt = 10; - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; - env(ticket::create(alice, ticketCnt)); - env.close(); - std::uint32_t const aliceSeq{env.seq(alice)}; - BEAST_EXPECT(ticketCount(env, alice) == ticketCnt); - BEAST_EXPECT(ownerCount(env, alice) == ticketCnt + 1); // tickets + issuance - - while (ticketCnt > 0) - { - // alice claws back 5 tokens using a ticket - env(claw(alice, mptAlice.mpt(5), bob), ticket::Use(aliceTicketSeq++)); - env.close(); - - ticketCnt--; - BEAST_EXPECT(ticketCount(env, alice) == ticketCnt); - } - - // alice clawed back 50 tokens total, 50 remain - BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 50)); - - // account sequence numbers did not advance - BEAST_EXPECT(env.seq(alice) == aliceSeq); - } - - void - testWithFeats(FeatureBitset features) - { - testValidation(features); - testPermission(features); - testEnabled(features); - testMultiIssuance(features); - testZeroBalanceAfterClawback(features); - testLockedMPT(features); - testAmountExceedsAvailable(features); - testTickets(features); - } - -public: - void - run() override - { - using namespace test::jtx; - FeatureBitset const all{testableAmendments()}; - testWithFeats(all); - } -}; - -BEAST_DEFINE_TESTSUITE(ClawbackMPT, app, xrpl); -} // namespace xrpl diff --git a/src/test/app/ConfidentialTransferExtended_test.cpp b/src/test/app/ConfidentialTransferExtended_test.cpp index f8f3d832c4..d2a2fa0967 100644 --- a/src/test/app/ConfidentialTransferExtended_test.cpp +++ b/src/test/app/ConfidentialTransferExtended_test.cpp @@ -564,7 +564,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase {.account = carol, .payAmount = 100, .convertAmount = 50}}}; auto& mpt = confEnv.mpt; - auto constexpr kCredIdx = + auto constexpr kCRED_IDX = "48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288B" "E4"; @@ -572,7 +572,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase .account = carol, .dest = bob, .amt = 10, - .credentials = {{kCredIdx}}, + .credentials = {{kCRED_IDX}}, .err = temDISABLED, }); } @@ -604,7 +604,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create({ - .flags = kMptDexFlags | tfMPTCanClawback | tfMPTCanConfidentialAmount, + .flags = kMPT_DEX_FLAGS | tfMPTCanClawback | tfMPTCanConfidentialAmount, }); mptAlice.authorize({.account = bob}); mptAlice.pay(alice, bob, 1'000); @@ -631,7 +631,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase .account = alice, .holder = ammHolder, .amt = 100, - .proof = strHex(gMakeZeroBuffer(kEcClawbackProofLength)), + .proof = strHex(gMakeZeroBuffer(kEC_CLAWBACK_PROOF_LENGTH)), .err = tecNO_PERMISSION, }); } @@ -1897,7 +1897,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID()); jv[sfHolder] = bob.human(); jv[sfMPTAmount.jsonName] = "50"; - jv[sfZKProof.jsonName] = std::string(kEcClawbackProofLength * 2, '0'); + jv[sfZKProof.jsonName] = std::string(kEC_CLAWBACK_PROOF_LENGTH * 2, '0'); env(jv, delegate::As(dave), Ter(temMALFORMED)); } @@ -1910,7 +1910,7 @@ class ConfidentialTransferExtended_test : public ConfidentialTransferTestBase jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID()); jv[sfHolder] = carol.human(); jv[sfMPTAmount.jsonName] = "100"; - jv[sfZKProof.jsonName] = std::string(kEcClawbackProofLength * 2, '0'); + jv[sfZKProof.jsonName] = std::string(kEC_CLAWBACK_PROOF_LENGTH * 2, '0'); env(jv, delegate::As(dave), Ter(temMALFORMED)); } } diff --git a/src/test/app/ConfidentialTransfer_test.cpp b/src/test/app/ConfidentialTransfer_test.cpp index b18d72a257..f28570c3e3 100644 --- a/src/test/app/ConfidentialTransfer_test.cpp +++ b/src/test/app/ConfidentialTransfer_test.cpp @@ -132,7 +132,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase }); } - // Edge case: kMaxMpTokenAmount + // Edge case: kMAX_MP_TOKEN_AMOUNT // Using raw JSON to avoid automatic decryption checks in MPTTester // which don't work for very large amounts (brute-force decryption is slow) { @@ -149,7 +149,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.authorize({ .account = bob, }); - mptAlice.pay(alice, bob, kMaxMpTokenAmount); + mptAlice.pay(alice, bob, kMAX_MP_TOKEN_AMOUNT); mptAlice.generateKeyPair(alice); mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)}); @@ -163,18 +163,18 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .holderPubKey = mptAlice.getPubKey(bob), }); - // Second convert with kMaxMpTokenAmount using raw JSON + // Second convert with kMAX_MP_TOKEN_AMOUNT using raw JSON Buffer const blindingFactor = generateBlindingFactor(); auto const holderCiphertext = - mptAlice.encryptAmount(bob, kMaxMpTokenAmount, blindingFactor); + mptAlice.encryptAmount(bob, kMAX_MP_TOKEN_AMOUNT, blindingFactor); auto const issuerCiphertext = - mptAlice.encryptAmount(alice, kMaxMpTokenAmount, blindingFactor); + mptAlice.encryptAmount(alice, kMAX_MP_TOKEN_AMOUNT, blindingFactor); json::Value jv; jv[jss::Account] = bob.human(); jv[jss::TransactionType] = jss::ConfidentialMPTConvert; jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID()); - jv[sfMPTAmount.jsonName] = std::to_string(kMaxMpTokenAmount); + jv[sfMPTAmount.jsonName] = std::to_string(kMAX_MP_TOKEN_AMOUNT); jv[sfHolderEncryptedAmount.jsonName] = strHex(holderCiphertext); jv[sfIssuerEncryptedAmount.jsonName] = strHex(issuerCiphertext); jv[sfBlindingFactor.jsonName] = strHex(blindingFactor); @@ -364,7 +364,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Amount exceeds maximum allowed MPT amount mptAlice.convert({ .account = bob, - .amt = kMaxMpTokenAmount + 1, + .amt = kMAX_MP_TOKEN_AMOUNT + 1, .holderPubKey = mptAlice.getPubKey(bob), .err = temBAD_AMOUNT, }); @@ -400,7 +400,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.convert({ .account = bob, .amt = 10, - .holderPubKey = gMakeZeroBuffer(kEcPubKeyLength), + .holderPubKey = gMakeZeroBuffer(kEC_PUB_KEY_LENGTH), .err = temMALFORMED, }); } @@ -636,7 +636,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Issuer pub key has correct length but invalid EC point data mptAlice.set({ .account = alice, - .issuerPubKey = gMakeZeroBuffer(kEcPubKeyLength), + .issuerPubKey = gMakeZeroBuffer(kEC_PUB_KEY_LENGTH), .err = temMALFORMED, }); @@ -652,7 +652,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.set({ .account = alice, .issuerPubKey = mptAlice.getPubKey(alice), - .auditorPubKey = gMakeZeroBuffer(kEcPubKeyLength), + .auditorPubKey = gMakeZeroBuffer(kEC_PUB_KEY_LENGTH), .err = temMALFORMED, }); @@ -1529,7 +1529,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.convert({ .account = bob, .amt = 10, - .proof = std::string(kEcSchnorrProofLength * 2, 'A'), + .proof = std::string(kEC_SCHNORR_PROOF_LENGTH * 2, 'A'), .holderPubKey = mptAlice.getPubKey(bob), .err = tecBAD_PROOF, }); @@ -1997,9 +1997,9 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .account = bob, .dest = carol, .amt = 10, - .senderEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), - .destEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), - .issuerEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), + .senderEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), + .destEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), + .issuerEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), .err = temDISABLED, }); } @@ -2099,7 +2099,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .dest = carol, .amt = 10, .proof = getTrivialSendProofHex(), - .senderEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), + .senderEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), .amountCommitment = getTrivialCommitment(), .balanceCommitment = getTrivialCommitment(), .err = temBAD_CIPHERTEXT, @@ -2111,7 +2111,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .dest = carol, .amt = 10, .proof = getTrivialSendProofHex(), - .destEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), + .destEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), .amountCommitment = getTrivialCommitment(), .balanceCommitment = getTrivialCommitment(), .err = temBAD_CIPHERTEXT, @@ -2123,7 +2123,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .dest = carol, .amt = 10, .proof = getTrivialSendProofHex(), - .issuerEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength), + .issuerEncryptedAmt = gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH), .amountCommitment = getTrivialCommitment(), .balanceCommitment = getTrivialCommitment(), .err = temBAD_CIPHERTEXT, @@ -2168,7 +2168,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .dest = carol, .amt = 10, .proof = getTrivialSendProofHex(), - .amountCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength), + .amountCommitment = gMakeZeroBuffer(kEC_PEDERSEN_COMMITMENT_LENGTH), .balanceCommitment = getTrivialCommitment(), .err = temMALFORMED, }); @@ -2180,7 +2180,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase .amt = 10, .proof = getTrivialSendProofHex(), .amountCommitment = getTrivialCommitment(), - .balanceCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength), + .balanceCommitment = gMakeZeroBuffer(kEC_PEDERSEN_COMMITMENT_LENGTH), .err = temMALFORMED, }); } @@ -3141,12 +3141,12 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase if (!sle) return false; // Inject dummy confidential balance fields - Buffer dummyCiphertext(kEcGamalEncryptedTotalLength); - std::memset(dummyCiphertext.data(), 0, kEcGamalEncryptedTotalLength); - dummyCiphertext.data()[0] = kEcCompressedPrefixEvenY; - dummyCiphertext.data()[kEcGamalEncryptedLength] = kEcCompressedPrefixEvenY; - dummyCiphertext.data()[kEcGamalEncryptedLength - 1] = 0x01; - dummyCiphertext.data()[kEcGamalEncryptedTotalLength - 1] = 0x01; + Buffer dummyCiphertext(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(dummyCiphertext.data(), 0, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + dummyCiphertext.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + dummyCiphertext.data()[kEC_GAMAL_ENCRYPTED_LENGTH] = kEC_COMPRESSED_PREFIX_EVEN_Y; + dummyCiphertext.data()[kEC_GAMAL_ENCRYPTED_LENGTH - 1] = 0x01; + dummyCiphertext.data()[kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH - 1] = 0x01; sle->setFieldVL(sfConfidentialBalanceSpending, dummyCiphertext); sle->setFieldVL(sfConfidentialBalanceInbox, dummyCiphertext); sle->setFieldVL(sfIssuerEncryptedBalance, dummyCiphertext); @@ -3207,7 +3207,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase }); } - // Edge case: kMaxMpTokenAmount + // Edge case: kMAX_MP_TOKEN_AMOUNT // Using raw JSON to avoid automatic decryption checks in MPTTester // which don't work for very large amounts (brute-force decryption is slow) // TODO: improve this test once there is bounded decryption or optimized decryption for @@ -3226,19 +3226,19 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.authorize({ .account = bob, }); - mptAlice.pay(alice, bob, kMaxMpTokenAmount); + mptAlice.pay(alice, bob, kMAX_MP_TOKEN_AMOUNT); mptAlice.generateKeyPair(alice); mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)}); mptAlice.generateKeyPair(bob); - // Convert kMaxMpTokenAmount to confidential using raw JSON + // Convert kMAX_MP_TOKEN_AMOUNT to confidential using raw JSON Buffer const convertBlindingFactor = generateBlindingFactor(); auto const convertHolderCiphertext = - mptAlice.encryptAmount(bob, kMaxMpTokenAmount, convertBlindingFactor); + mptAlice.encryptAmount(bob, kMAX_MP_TOKEN_AMOUNT, convertBlindingFactor); auto const convertIssuerCiphertext = - mptAlice.encryptAmount(alice, kMaxMpTokenAmount, convertBlindingFactor); + mptAlice.encryptAmount(alice, kMAX_MP_TOKEN_AMOUNT, convertBlindingFactor); auto const convertContextHash = getConvertContextHash(bob.id(), mptAlice.issuanceID(), env.seq(bob)); auto const schnorrProof = mptAlice.getSchnorrProof(bob, convertContextHash); @@ -3249,7 +3249,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase jv[jss::Account] = bob.human(); jv[jss::TransactionType] = jss::ConfidentialMPTConvert; jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID()); - jv[sfMPTAmount.jsonName] = std::to_string(kMaxMpTokenAmount); + jv[sfMPTAmount.jsonName] = std::to_string(kMAX_MP_TOKEN_AMOUNT); jv[sfHolderEncryptionKey.jsonName] = strHex(*mptAlice.getPubKey(bob)); jv[sfHolderEncryptedAmount.jsonName] = strHex(convertHolderCiphertext); jv[sfIssuerEncryptedAmount.jsonName] = strHex(convertIssuerCiphertext); @@ -3269,10 +3269,10 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase env(jv, Ter(tesSUCCESS)); } - // ConvertBack kMaxMpTokenAmount - 1 using raw JSON - // After convert + merge, spending balance = kMaxMpTokenAmount - // We convert back kMaxMpTokenAmount - 1 to leave remainder of 1 - std::uint64_t const convertBackAmt = kMaxMpTokenAmount - 1; + // ConvertBack kMAX_MP_TOKEN_AMOUNT - 1 using raw JSON + // After convert + merge, spending balance = kMAX_MP_TOKEN_AMOUNT + // We convert back kMAX_MP_TOKEN_AMOUNT - 1 to leave remainder of 1 + std::uint64_t const convertBackAmt = kMAX_MP_TOKEN_AMOUNT - 1; Buffer const convertBackBlindingFactor = generateBlindingFactor(); auto const convertBackHolderCiphertext = @@ -3288,7 +3288,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Generate pedersen commitment for the known spending balance Buffer const pcBlindingFactor = generateBlindingFactor(); Buffer const pedersenCommitment = - mptAlice.getPedersenCommitment(kMaxMpTokenAmount, pcBlindingFactor); + mptAlice.getPedersenCommitment(kMAX_MP_TOKEN_AMOUNT, pcBlindingFactor); // Generate the proof using known spending balance value auto const version = mptAlice.getMPTokenVersion(bob); @@ -3301,7 +3301,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase convertBackContextHash, { .pedersenCommitment = pedersenCommitment, - .amt = kMaxMpTokenAmount, + .amt = kMAX_MP_TOKEN_AMOUNT, .encryptedAmt = *encryptedSpendingBalance, .blindingFactor = pcBlindingFactor, }); @@ -3404,7 +3404,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.convertBack({ .account = bob, - .amt = kMaxMpTokenAmount + 1, + .amt = kMAX_MP_TOKEN_AMOUNT + 1, .err = temBAD_AMOUNT, }); @@ -3412,7 +3412,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.convertBack({ .account = bob, .amt = 30, - .pedersenCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength), + .pedersenCommitment = gMakeZeroBuffer(kEC_PEDERSEN_COMMITMENT_LENGTH), .err = temMALFORMED, }); @@ -4308,7 +4308,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase jv[sfHolder] = bob.human(); jv[jss::TransactionType] = jss::ConfidentialMPTClawback; jv[sfMPTAmount] = std::to_string(10); - std::string const dummyProof(kEcClawbackProofLength * 2, '0'); + std::string const dummyProof(kEC_CLAWBACK_PROOF_LENGTH * 2, '0'); jv[sfZKProof] = dummyProof; jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID()); @@ -5661,7 +5661,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase /* This test verifies that xrpld correctly rejects attempts to * overflow the maximum allowable token amount via homomorphic manipulation. * It simulates an attack where an individual takes a valid ciphertext encrypting - * the maximum amount (kMaxMpTokenAmount) and homomorphically adds an encryption of + * the maximum amount (kMAX_MP_TOKEN_AMOUNT) and homomorphically adds an encryption of * 1 to it, producing a ciphertext for MAX+1. The test confirms that the Bulletproof * range proof or inner-product constraints detect this overflow and invalidate the * transaction, preserving the supply invariant. */ @@ -5681,7 +5681,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase auto& mptAlice = confEnv.mpt; // Bob sends 10 to carol. The send amount (10) and Bob's remaining balance - // (90) are both within [0, kMaxMpTokenAmount]. Range proof passes. + // (90) are both within [0, kMAX_MP_TOKEN_AMOUNT]. Range proof passes. mptAlice.send({.account = bob, .dest = carol, .amt = 10}); // Bob's spending balance is 90 after the baseline send. @@ -5689,9 +5689,9 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase mptAlice.getDecryptedBalance(bob, MPTTester::HolderEncryptedSpending); BEAST_EXPECT(bobSpendingBefore == 90); - // Construct Enc(kMaxMpTokenAmount) with Bob's public key. + // Construct Enc(kMAX_MP_TOKEN_AMOUNT) with Bob's public key. Buffer const bf1 = generateBlindingFactor(); - Buffer const encMax = mptAlice.encryptAmount(bob, kMaxMpTokenAmount, bf1); + Buffer const encMax = mptAlice.encryptAmount(bob, kMAX_MP_TOKEN_AMOUNT, bf1); // Construct Enc(1) with a separate blinding factor. Buffer const bf2 = generateBlindingFactor(); @@ -5703,13 +5703,13 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase Buffer overflowedCt = std::move(*overflowedOpt); // Submit the send transaction with the tampered ciphertext. - // Setting amt = kMaxMpTokenAmount + 1 drives proof generation for the - // overflowed value. The bulletproof range check [0, kMaxMpTokenAmount] + // Setting amt = kMAX_MP_TOKEN_AMOUNT + 1 drives proof generation for the + // overflowed value. The bulletproof range check [0, kMAX_MP_TOKEN_AMOUNT] // rejects MAX+1; the validator must return tecBAD_PROOF. mptAlice.send({ .account = bob, .dest = carol, - .amt = kMaxMpTokenAmount + 1, + .amt = kMAX_MP_TOKEN_AMOUNT + 1, .senderEncryptedAmt = overflowedCt, .err = tecBAD_PROOF, }); @@ -5724,7 +5724,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase * simulates a scenario where an attacker takes a ciphertext encrypting zero * and subtracts an encryption of 1, resulting in a value of -1. * The test asserts that the range proof verification fails because the resulting - * value falls outside the valid non-negative range [0, kMaxMpTokenAmount], + * value falls outside the valid non-negative range [0, kMAX_MP_TOKEN_AMOUNT], * causing the validator to reject the transaction with tecBAD_PROOF. */ void testConvertBackHomomorphicUnderflow(FeatureBitset features) @@ -5739,7 +5739,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase auto& mptAlice = confEnv.mpt; // Converting back 1 from 10 leaves remaining balance = 9 (non-negative). - // Range proof [0, kMaxMpTokenAmount] passes. + // Range proof [0, kMAX_MP_TOKEN_AMOUNT] passes. mptAlice.convertBack({.account = bob, .amt = 1}); // Bob's spending balance is now 9; public balance is 1. @@ -5758,19 +5758,19 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase Buffer const encOne = mptAlice.encryptAmount(bob, 1, bf2); // Homomorphically subtract to produce CB_S_holder' = Enc(0) − Enc(1) - // = Enc(−1), which lies below [0, kMaxMpTokenAmount]. + // = Enc(−1), which lies below [0, kMAX_MP_TOKEN_AMOUNT]. auto underflowedOpt = homomorphicSubtract(encZero, encOne); BEAST_EXPECT(underflowedOpt.has_value()); Buffer underflowedCt = std::move(*underflowedOpt); // The underflowed value as uint64_t: 0 - 1 wraps to 0xFFFFFFFFFFFFFFFF. // Generate a real proof using this wrapped value. The validator must still reject it - // because 0xFFFFFFFFFFFFFFFE (remaining balance) is outside [0, kMaxMpTokenAmount]. - constexpr std::uint64_t kUnderflowedAmt = + // because 0xFFFFFFFFFFFFFFFE (remaining balance) is outside [0, kMAX_MP_TOKEN_AMOUNT]. + constexpr std::uint64_t kUNDERFLOWED_AMT = static_cast(0) - static_cast(1); Buffer const pcBf = generateBlindingFactor(); - Buffer const pedersenCommitment = mptAlice.getPedersenCommitment(kUnderflowedAmt, pcBf); + Buffer const pedersenCommitment = mptAlice.getPedersenCommitment(kUNDERFLOWED_AMT, pcBf); auto const currentVersion = mptAlice.getMPTokenVersion(bob); uint256 const contextHash = @@ -5782,7 +5782,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase contextHash, { .pedersenCommitment = pedersenCommitment, - .amt = kUnderflowedAmt, + .amt = kUNDERFLOWED_AMT, .encryptedAmt = underflowedCt, .blindingFactor = pcBf, }); @@ -5869,9 +5869,9 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // used to tie the proof to the transfer amount and sender balance. // A commitment with a valid-looking prefix but an impossible // x-coordinate must also be rejected. - Buffer badCommitment(kEcPedersenCommitmentLength); - std::memset(badCommitment.data(), 0xFF, kEcPedersenCommitmentLength); - badCommitment.data()[0] = kEcCompressedPrefixEvenY; + Buffer badCommitment(kEC_PEDERSEN_COMMITMENT_LENGTH); + std::memset(badCommitment.data(), 0xFF, kEC_PEDERSEN_COMMITMENT_LENGTH); + badCommitment.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; mptAlice.send({ .account = bob, @@ -5909,9 +5909,9 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase {.account = carol, .payAmount = 50, .convertAmount = 30}}}; auto& mptAlice = confEnv.mpt; - Buffer badProof(kEcSendProofLength); - std::memset(badProof.data(), 0xFF, kEcSendProofLength); - badProof.data()[0] = kEcCompressedPrefixEvenY; + Buffer badProof(kEC_SEND_PROOF_LENGTH); + std::memset(badProof.data(), 0xFF, kEC_SEND_PROOF_LENGTH); + badProof.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; mptAlice.send({ .account = bob, @@ -5941,19 +5941,19 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase auto const& tc = getTrivialCiphertext(); // C1 = bad (0xFF...FF), C2 = valid trivial point - Buffer badC1goodC2(kEcGamalEncryptedTotalLength); - std::memset(badC1goodC2.data(), 0xFF, kEcGamalEncryptedTotalLength); - badC1goodC2.data()[0] = kEcCompressedPrefixEvenY; + Buffer badC1goodC2(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(badC1goodC2.data(), 0xFF, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + badC1goodC2.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; std::memcpy( - badC1goodC2.data() + kEcGamalEncryptedLength, - tc.data() + kEcGamalEncryptedLength, - kEcGamalEncryptedLength); + badC1goodC2.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + tc.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + kEC_GAMAL_ENCRYPTED_LENGTH); // C1 = valid trivial point, C2 = bad (0xFF...FF) - Buffer goodC1badC2(kEcGamalEncryptedTotalLength); - std::memset(goodC1badC2.data(), 0xFF, kEcGamalEncryptedTotalLength); - std::memcpy(goodC1badC2.data(), tc.data(), kEcGamalEncryptedLength); - goodC1badC2.data()[kEcGamalEncryptedLength] = kEcCompressedPrefixEvenY; + Buffer goodC1badC2(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(goodC1badC2.data(), 0xFF, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memcpy(goodC1badC2.data(), tc.data(), kEC_GAMAL_ENCRYPTED_LENGTH); + goodC1badC2.data()[kEC_GAMAL_ENCRYPTED_LENGTH] = kEC_COMPRESSED_PREFIX_EVEN_Y; // sender's encrypted amount — bad C1 mptAlice.send({ @@ -6039,23 +6039,23 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // // P-256 generator x: // 6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 - static constexpr std::uint8_t kP256GeneratorX[32] = { + static constexpr std::uint8_t kP256_GENERATOR_X[32] = { 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96, }; // A 66-byte encrypted amount using the P-256 x-coordinate for both halves. - Buffer wrongGroupCt(kEcGamalEncryptedTotalLength); - wrongGroupCt.data()[0] = kEcCompressedPrefixEvenY; - std::memcpy(wrongGroupCt.data() + 1, kP256GeneratorX, 32); - wrongGroupCt.data()[kEcGamalEncryptedLength] = kEcCompressedPrefixEvenY; - std::memcpy(wrongGroupCt.data() + kEcGamalEncryptedLength + 1, kP256GeneratorX, 32); + Buffer wrongGroupCt(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + wrongGroupCt.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + std::memcpy(wrongGroupCt.data() + 1, kP256_GENERATOR_X, 32); + wrongGroupCt.data()[kEC_GAMAL_ENCRYPTED_LENGTH] = kEC_COMPRESSED_PREFIX_EVEN_Y; + std::memcpy(wrongGroupCt.data() + kEC_GAMAL_ENCRYPTED_LENGTH + 1, kP256_GENERATOR_X, 32); // A 33-byte commitment using the same wrong-curve x-coordinate. - Buffer wrongGroupCommitment(kEcPedersenCommitmentLength); - wrongGroupCommitment.data()[0] = kEcCompressedPrefixEvenY; - std::memcpy(wrongGroupCommitment.data() + 1, kP256GeneratorX, 32); + Buffer wrongGroupCommitment(kEC_PEDERSEN_COMMITMENT_LENGTH); + wrongGroupCommitment.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + std::memcpy(wrongGroupCommitment.data() + 1, kP256_GENERATOR_X, 32); // sender's encrypted amount uses a coordinate from the wrong curve mptAlice.send({ @@ -6131,7 +6131,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase using namespace test::jtx; // 33 zero bytes — not a real public key; no valid secret maps to this. - Buffer const nullKey = gMakeZeroBuffer(kEcPubKeyLength); + Buffer const nullKey = gMakeZeroBuffer(kEC_PUB_KEY_LENGTH); // Recipient (holder) tries to register an all-zero key. // Must be rejected so no account ends up with an unprotected balance. @@ -6588,7 +6588,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Corrupt bulletproof bytes. Buffer forgedProof = *validProof; - for (size_t i = kBulletproofOffset; i < forgedProof.size(); i += 7) + for (size_t i = kBULLETPROOF_OFFSET; i < forgedProof.size(); i += 7) forgedProof.data()[i] ^= 0xFF; // Submit — rejected due to commitment mismatch. @@ -6651,11 +6651,11 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase ctxHash); Buffer forgedProof(validProof->size()); - std::memcpy(forgedProof.data(), validProof->data(), kBulletproofOffset); + std::memcpy(forgedProof.data(), validProof->data(), kBULLETPROOF_OFFSET); std::memcpy( - forgedProof.data() + kBulletproofOffset, + forgedProof.data() + kBULLETPROOF_OFFSET, forgedBulletproof.data(), - kEcDoubleBulletproofLength); + kEC_DOUBLE_BULLETPROOF_LENGTH); mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF)); @@ -6802,11 +6802,11 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase Buffer forgedProof = *proof; - static constexpr size_t kSigmaScalarSize = 32; - static constexpr size_t kChallengeOffset = 0; - static constexpr size_t kResponseOffset = kChallengeOffset + kSigmaScalarSize; - static constexpr size_t kResponseSize = 5 * kSigmaScalarSize; // z_m..z_sk - std::memset(forgedProof.data() + kResponseOffset, 0, kResponseSize); + static constexpr size_t kSIGMA_SCALAR_SIZE = 32; + static constexpr size_t kCHALLENGE_OFFSET = 0; + static constexpr size_t kRESPONSE_OFFSET = kCHALLENGE_OFFSET + kSIGMA_SCALAR_SIZE; + static constexpr size_t kRESPONSE_SIZE = 5 * kSIGMA_SCALAR_SIZE; // z_m..z_sk + std::memset(forgedProof.data() + kRESPONSE_OFFSET, 0, kRESPONSE_SIZE); mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF)); } @@ -6817,8 +6817,8 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase if (!BEAST_EXPECT(proof.has_value())) return; - Buffer invalidCiphertext(kEcGamalEncryptedTotalLength); - std::memset(invalidCiphertext.data(), 0, kEcGamalEncryptedTotalLength); + Buffer invalidCiphertext(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(invalidCiphertext.data(), 0, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); auto args = setup.sendArgs(bob, carol, *proof, temBAD_CIPHERTEXT); args.senderEncryptedAmt = invalidCiphertext; @@ -6831,8 +6831,8 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase if (!BEAST_EXPECT(proof.has_value())) return; - Buffer invalidCommitment(kEcPedersenCommitmentLength); - std::memset(invalidCommitment.data(), 0, kEcPedersenCommitmentLength); + Buffer invalidCommitment(kEC_PEDERSEN_COMMITMENT_LENGTH); + std::memset(invalidCommitment.data(), 0, kEC_PEDERSEN_COMMITMENT_LENGTH); auto args = setup.sendArgs(bob, carol, *proof, temMALFORMED); args.amountCommitment = invalidCommitment; @@ -6847,14 +6847,14 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase Buffer forgedProof = *proof; - static constexpr unsigned char kCurveOrder[32] = { + static constexpr unsigned char kCURVE_ORDER[32] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, // 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, // 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41 // }; - std::memcpy(forgedProof.data() + 32, kCurveOrder, 32); + std::memcpy(forgedProof.data() + 32, kCURVE_ORDER, 32); mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF)); } @@ -6867,14 +6867,14 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase Buffer forgedProof = *proof; - static constexpr unsigned char kOverflowScalar[32] = { + static constexpr unsigned char kOVERFLOW_SCALAR[32] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, // 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, // 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x42 // }; - std::memcpy(forgedProof.data() + 32, kOverflowScalar, 32); + std::memcpy(forgedProof.data() + 32, kOVERFLOW_SCALAR, 32); mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF)); } @@ -6942,7 +6942,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Resize the convertBack proof to match the expected send proof // size so it passes preflight's size check and reaches the actual // ZK verification in doApply. - auto const expectedSendSize = kEcSendProofLength; + auto const expectedSendSize = kEC_SEND_PROOF_LENGTH; Buffer resizedProof(expectedSendSize); auto const copyLen = std::min(convertBackProof.size(), expectedSendSize); std::memcpy(resizedProof.data(), convertBackProof.data(), copyLen); @@ -7114,8 +7114,8 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // swaps them: -P has the same x but opposite y. auto negateCiphertext = [](Buffer const& ct) -> Buffer { Buffer neg = ct; - neg.data()[0] ^= 0x01; // negate C1 - neg.data()[kEcGamalEncryptedLength] ^= 0x01; // negate C2 + neg.data()[0] ^= 0x01; // negate C1 + neg.data()[kEC_GAMAL_ENCRYPTED_LENGTH] ^= 0x01; // negate C2 return neg; }; @@ -7329,7 +7329,7 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase auto substituteC1 = [](Buffer const& target, Buffer const& source) -> Buffer { Buffer result = target; // Copy C1 (first ecGamalEncryptedLength bytes) from source - std::memcpy(result.data(), source.data(), kEcGamalEncryptedLength); + std::memcpy(result.data(), source.data(), kEC_GAMAL_ENCRYPTED_LENGTH); return result; }; @@ -7434,14 +7434,14 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase // Replace sender ciphertext with zero-randomness form: // C1 = all zeros (identity element — invalid encoding) // C2 = valid trivial point (simulating mG) - Buffer zeroCiphertext(kEcGamalEncryptedTotalLength); - std::memset(zeroCiphertext.data(), 0, kEcGamalEncryptedTotalLength); + Buffer zeroCiphertext(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(zeroCiphertext.data(), 0, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); // C2 half: use a valid point so only C1 is the problem auto const& tc = getTrivialCiphertext(); std::memcpy( - zeroCiphertext.data() + kEcGamalEncryptedLength, - tc.data() + kEcGamalEncryptedLength, - kEcGamalEncryptedLength); + zeroCiphertext.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + tc.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + kEC_GAMAL_ENCRYPTED_LENGTH); obj.setFieldVL(sfSenderEncryptedAmount, zeroCiphertext); // Re-serialize with the original (now-stale) signature @@ -7465,13 +7465,13 @@ class ConfidentialTransfer_test : public ConfidentialTransferTestBase { // Build zero-randomness ciphertext: C1 = all zeros (identity), // C2 = valid trivial point (simulating mG) - Buffer zeroCiphertext(kEcGamalEncryptedTotalLength); - std::memset(zeroCiphertext.data(), 0, kEcGamalEncryptedTotalLength); + Buffer zeroCiphertext(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(zeroCiphertext.data(), 0, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); auto const& tc = getTrivialCiphertext(); std::memcpy( - zeroCiphertext.data() + kEcGamalEncryptedLength, - tc.data() + kEcGamalEncryptedLength, - kEcGamalEncryptedLength); + zeroCiphertext.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + tc.data() + kEC_GAMAL_ENCRYPTED_LENGTH, + kEC_GAMAL_ENCRYPTED_LENGTH); mptAlice.send( {.account = bob, diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index 9416ca222f..fa180d0603 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -5,12 +5,9 @@ #include #include #include -#include #include #include #include -#include -#include #include #include #include @@ -27,13 +24,11 @@ #include #include #include -#include #include #include #include #include -#include #include #include @@ -142,7 +137,7 @@ 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->isFlag(lsfAccepted)); + BEAST_EXPECT((sleCred->getFieldU32(sfFlags) & lsfAccepted)); BEAST_EXPECT( sleCred->getFieldU64(sfIssuerNode) == sleCred->getFieldU64(sfSubjectNode)); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -461,17 +456,17 @@ struct Credentials_test : public beast::unit_test::Suite testcase( "Credentials fail, credentialType length > " "maxCredentialTypeLength."); - static constexpr std::string_view kLongCredType = + constexpr std::string_view kLONG_CRED_TYPE = "abcdefghijklmnopqrstuvwxyz01234567890qwertyuiop[]" "asdfghjkl;'zxcvbnm8237tr28weufwldebvfv8734t07p"; - static_assert(kLongCredType.size() > kMaxCredentialTypeLength); - auto jv = credentials::create(subject, issuer, kLongCredType); + static_assert(kLONG_CRED_TYPE.size() > kMAX_CREDENTIAL_TYPE_LENGTH); + auto jv = credentials::create(subject, issuer, kLONG_CRED_TYPE); env(jv, Ter(temMALFORMED)); } { testcase("Credentials fail, URI length > 256."); - static constexpr std::string_view kLongUri = + constexpr std::string_view kLONG_URI = "abcdefghijklmnopqrstuvwxyz01234567890qwertyuiop[]" "asdfghjkl;'zxcvbnm8237tr28weufwldebvfv8734t07p " "9hfup;wDJFBVSD8f72 " @@ -480,9 +475,9 @@ struct Credentials_test : public beast::unit_test::Suite "vujhgWQIE7F6WEUYFGWUKEYFVQW87FGWOEFWEFUYWVEF8723GFWEFB" "WULE" "fv28o37gfwEFB3872TFO8GSDSDVD"; - static_assert(kLongUri.size() > kMaxCredentialUriLength); + static_assert(kLONG_URI.size() > kMAX_CREDENTIAL_URI_LENGTH); env(credentials::create(subject, issuer, credType), - credentials::Uri(kLongUri), + credentials::Uri(kLONG_URI), Ter(temMALFORMED)); } @@ -1033,121 +1028,6 @@ struct Credentials_test : public beast::unit_test::Suite } } - void - testRemoveExpiredCorruption(FeatureBitset features) - { - bool const fixEnabled = features[fixCleanup3_1_3]; - testcase( - "removeExpired ignores deleteSLE failure " + - (fixEnabled ? std::string(" after fix") : std::string(" before fix"))); - - using namespace test::jtx; - - char const credType[] = "abcde"; - Account const issuer{"issuer"}; - Account const subject{"subject"}; - Account const becky{"becky"}; - - Env env{*this, features}; - env.fund(XRP(10000), issuer, subject, becky); - env.close(); - - // Create credential with short expiration - auto jv = credentials::create(subject, issuer, credType); - uint32_t const expiration = - env.current()->header().parentCloseTime.time_since_epoch().count() + 40; - jv[sfExpiration.jsonName] = expiration; - env(jv); - env.close(); - - auto const credLE = credentials::ledgerEntry(env, subject, issuer, credType); - std::string const credIdx = credLE[jss::result][jss::index].asString(); - - // Subject accepts the credential - env(credentials::accept(subject, issuer, credType)); - env.close(); - - // Build the credential keylet - auto const credKeylet = - keylet::credential(subject.id(), issuer.id(), Slice(credType, std::strlen(credType))); - - // Verify credential exists and is accepted - { - auto const sleCred = env.current()->read(credKeylet); - BEAST_EXPECT(sleCred && sleCred->isFlag(lsfAccepted)); - } - - // Create DepositPreauth - env(deposit::authCredentials(becky, {{subject, credType}})); - env.close(); - // env(); - auto jtx = env.jt(pay(subject, becky, XRP(100)), credentials::Ids({credIdx})); - if (!BEAST_EXPECT(jtx.stx)) - return; - auto const stx = std::make_shared(*jtx.stx); - - // Create PermissionedDomain - env(pdomain::setTx(becky, {{issuer, credType}})); - env.close(); - auto const objects = pdomain::getObjects(becky, env); - if (!BEAST_EXPECT(!objects.empty())) - return; - auto const domain = objects.begin()->first; - - using namespace std::chrono_literals; - env.close(50s); - - // Verify time has advanced past expiration - { - auto const sleCred = env.current()->read(credKeylet); - BEAST_EXPECT( - sleCred && - xrpl::credentials::checkExpired(*sleCred, env.current()->header().parentCloseTime)); - } - - // Create an ApplyViewImpl on top of the current closed ledger - // and corrupt it by erasing the issuer's account SLE - auto const open = env.current(); - ApplyViewImpl av(&*open, TapNone); - - // Erase the issuer's account to simulate ledger corruption - auto sleIssuer = av.peek(keylet::account(issuer.id())); - if (!BEAST_EXPECT(sleIssuer)) - return; - av.erase(sleIssuer); - BEAST_EXPECT(!av.exists(keylet::account(issuer.id()))); - - // Credential still exists before removeExpired - BEAST_EXPECT(av.exists(credKeylet)); - - // Call removeExpired on the corrupted view - STVector256 credHashes; - credHashes.pushBack(credKeylet.key); - beast::Journal const j{beast::Journal::getNullSink()}; - - auto const dpTer = xrpl::verifyDepositPreauth(*stx, av, subject, becky, {}, j); - auto sleCredAfter = av.read(credKeylet); - BEAST_EXPECT(sleCredAfter && sleCredAfter->isFlag(lsfAccepted)); - - auto const domTer = xrpl::verifyValidDomain(av, subject.id(), domain, j); - sleCredAfter = av.read(credKeylet); - BEAST_EXPECT(sleCredAfter && sleCredAfter->isFlag(lsfAccepted)); - - if (fixEnabled) - { - // removeExpired returns error, cred wasn't deleted - BEAST_EXPECT(dpTer == tecINTERNAL); - BEAST_EXPECT(domTer == tecINTERNAL); - } - else - { - // removeExpired returns true (claims it found & deleted expired - // creds) - BEAST_EXPECT(dpTer == tecEXPIRED); - BEAST_EXPECT(isTesSuccess(domTer)); - } - } - void run() override { @@ -1163,9 +1043,6 @@ struct Credentials_test : public beast::unit_test::Suite testFlags(all - fixInvalidTxFlags); testFlags(all); testRPC(); - - testRemoveExpiredCorruption(all - fixCleanup3_1_3); - testRemoveExpiredCorruption(all | fixCleanup3_1_3); } }; diff --git a/src/test/app/CrossingLimitsMPT_test.cpp b/src/test/app/CrossingLimitsMPT_test.cpp index 4a016f31dc..e9a9861a3a 100644 --- a/src/test/app/CrossingLimitsMPT_test.cpp +++ b/src/test/app/CrossingLimitsMPT_test.cpp @@ -52,7 +52,7 @@ public: // Carol offers to buy 1000 XRP for 1000 USD. She removes Bob's next // 1000 offers as unfunded and hits the step limit. env(offer("carol", usd(1'000), XRP(1'000))); - env.require(Balance("carol", usd(kNone))); + env.require(Balance("carol", usd(kNONE))); env.require(Owners("carol", 1)); env.require(Balance("bob", usd(0))); env.require(Owners("bob", 1)); @@ -198,13 +198,13 @@ public: .token = "USD", .issuer = gw, .holders = {alice, carol}, - .limit = kMaxMpTokenAmount}); + .limit = kMAX_MP_TOKEN_AMOUNT}); auto const eur = issue2( {.env = env, .token = "EUR", .issuer = gw, .holders = {bob}, - .limit = kMaxMpTokenAmount}); + .limit = kMAX_MP_TOKEN_AMOUNT}); env(pay(gw, alice, usd(4'000))); env(pay(gw, carol, usd(3))); @@ -289,13 +289,13 @@ public: .token = "USD", .issuer = gw, .holders = {alice, carol}, - .limit = kMaxMpTokenAmount}); + .limit = kMAX_MP_TOKEN_AMOUNT}); auto const eur = issue2( {.env = env, .token = "EUR", .issuer = gw, .holders = {bob}, - .limit = kMaxMpTokenAmount}); + .limit = kMAX_MP_TOKEN_AMOUNT}); env(pay(gw, alice, usd(4'000))); env(pay(gw, carol, usd(3))); diff --git a/src/test/app/CrossingLimits_test.cpp b/src/test/app/CrossingLimits_test.cpp index 3cf8f50990..331afddad1 100644 --- a/src/test/app/CrossingLimits_test.cpp +++ b/src/test/app/CrossingLimits_test.cpp @@ -51,7 +51,7 @@ public: // Carol offers to buy 1000 XRP for 1000 USD. She removes Bob's next // 1000 offers as unfunded and hits the step limit. env(offer("carol", usd(1000), XRP(1000))); - env.require(Balance("carol", usd(kNone))); + env.require(Balance("carol", usd(kNONE))); env.require(Owners("carol", 1)); env.require(Balance("bob", usd(0))); env.require(Owners("bob", 1)); diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 54b287577f..c087d3ae3f 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -196,7 +195,7 @@ class Delegate_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::DelegateSet; jv[jss::Account] = gw.human(); jv[sfAuthorize.jsonName] = alice.human(); - json::Value permissionsJson(json::ValueType::Array); + json::Value permissionsJson(json::ArrayValue); json::Value permissionValue; permissionValue[sfPermissionValue.jsonName] = "Payment"; json::Value permissionObj; @@ -553,27 +552,27 @@ class Delegate_test : public beast::unit_test::Suite for (auto i = 0; i < 20; ++i) { - // bob is the delegated account, his sequence won't kIncrement + // bob is the delegated account, his sequence won't kINCREMENT env(pay(alice, carol, XRP(10)), Fee(XRP(10)), delegate::As(bob)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); BEAST_EXPECT(env.seq(bob) == bobSeq); aliceSeq = env.seq(alice); - // bob sends payment for himself, his sequence will kIncrement + // bob sends payment for himself, his sequence will kINCREMENT env(pay(bob, carol, XRP(10)), Fee(XRP(10))); BEAST_EXPECT(env.seq(alice) == aliceSeq); BEAST_EXPECT(env.seq(bob) == bobSeq + 1); bobSeq = env.seq(bob); - // alice is the delegated account, her sequence won't kIncrement + // alice is the delegated account, her sequence won't kINCREMENT env(pay(bob, carol, XRP(10)), Fee(XRP(10)), delegate::As(alice)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); BEAST_EXPECT(env.seq(bob) == bobSeq + 1); bobSeq = env.seq(bob); - // alice sends payment for herself, her sequence will kIncrement + // alice sends payment for herself, her sequence will kINCREMENT env(pay(alice, carol, XRP(10)), Fee(XRP(10))); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); BEAST_EXPECT(env.seq(bob) == bobSeq); @@ -1880,149 +1879,6 @@ class Delegate_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(edward) == edwardBalance); } - void - testMultiSignDelegatorAsSigner() - { - // checkMultiSign disallows the owner of the account to - // be part of the multisigner list. When it is a delegated transaction, - // the delegate account should not be part of the multisigner list. - testcase("test delegator as multisigner in delegate's signer list"); - using namespace jtx; - - Env env(*this); - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const carol{"carol"}; - Account const daria{"daria"}; - env.fund(XRP(100000), alice, bob, carol, daria); - env.close(); - - env(delegate::set(alice, bob, {"Payment"})); - env.close(); - - // bob's signer list includes the delegator alice and daria - env(signers(bob, 2, {{alice, 1}, {daria, 1}})); - env.close(); - - auto aliceBalance = env.balance(alice); - auto bobBalance = env.balance(bob); - auto carolBalance = env.balance(carol); - auto const amt = 100; - - // alice can sign as a multisigner for bob - env(pay(alice, carol, XRP(100)), Fee(XRP(10)), delegate::As(bob), Msig(alice, daria)); - env.close(); - - BEAST_EXPECT(env.balance(alice) == aliceBalance - XRP(amt)); - BEAST_EXPECT(env.balance(bob) == bobBalance - XRP(10)); - BEAST_EXPECT(env.balance(carol) == carolBalance + XRP(amt)); - - // alice can not sign as a multisigner if she sent the transaction by herself. - env(pay(alice, carol, XRP(100)), Fee(XRP(10)), Msig(alice, daria), Ter(telENV_RPC_FAILED)); - env.close(); - - // Get new balances - aliceBalance = env.balance(alice); - bobBalance = env.balance(bob); - carolBalance = env.balance(carol); - - // bob (the delegate) should not appear as a multisigner in his transaction sent on behalf - // of alice. STTx::checkMultiSign catches this at the local-check stage, so the jtx - // framework returns telENV_RPC_FAILED. - env(pay(alice, carol, XRP(50)), - Fee(XRP(10)), - delegate::As(bob), - Msig(alice, bob), - Ter(telENV_RPC_FAILED)); - env.close(); - BEAST_EXPECT(env.balance(alice) == aliceBalance); - BEAST_EXPECT(env.balance(bob) == bobBalance); - BEAST_EXPECT(env.balance(carol) == carolBalance); - } - - void - testSignForDelegated() - { - // In sortAndValidateSigners, if it is a delegated transaction, the delegate account is - // the forbidden account from appearing in its own Signers array. - testcase("test sign_for with delegated transaction"); - using namespace jtx; - - Env env(*this); - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const carol{"carol"}; - Account const daria{"daria"}; - env.fund(XRP(100000), alice, bob, carol, daria); - env.close(); - - env(delegate::set(alice, bob, {"Payment"})); - env.close(); - - // bob's signer list includes the delegator alice and daria - env(signers(bob, 2, {{alice, 1}, {daria, 1}})); - env.close(); - - auto const baseFee = env.current()->fees().base; - - auto const sendAmt = 1'000'000; - auto makeDelegateTx = [&]() -> json::Value { - json::Value jv; - jv[jss::tx_json][jss::Account] = alice.human(); - jv[jss::tx_json][sfDelegate.jsonName] = bob.human(); - jv[jss::tx_json][jss::TransactionType] = jss::Payment; - jv[jss::tx_json][jss::Destination] = carol.human(); - jv[jss::tx_json][jss::Amount] = sendAmt; - jv[jss::tx_json][jss::Fee] = std::to_string((10 * baseFee).drops()); - jv[jss::tx_json][jss::Sequence] = env.seq(alice); - jv[jss::tx_json][jss::SigningPubKey] = ""; - return jv; - }; - - // The delegator alice and daria both sign via sign_for, which is valid - { - auto const aliceBalance = env.balance(alice); - auto const bobBalance = env.balance(bob); - auto const dariaBalance = env.balance(daria); - auto const carolBalance = env.balance(carol); - - json::Value jv = makeDelegateTx(); - jv[jss::account] = alice.human(); - jv[jss::secret] = alice.name(); - auto jrr = env.rpc("json", "sign_for", to_string(jv))[jss::result]; - BEAST_EXPECT(jrr[jss::status] == "success"); - - json::Value jv2; - jv2[jss::tx_json] = jrr[jss::tx_json]; - jv2[jss::account] = daria.human(); - jv2[jss::secret] = daria.name(); - jrr = env.rpc("json", "sign_for", to_string(jv2))[jss::result]; - BEAST_EXPECT(jrr[jss::status] == "success"); - - json::Value jvSubmit; - jvSubmit[jss::tx_json] = jrr[jss::tx_json]; - jrr = env.rpc("json", "submit_multisigned", to_string(jvSubmit))[jss::result]; - BEAST_EXPECT(jrr[jss::status] == "success"); - env.close(); - BEAST_EXPECT(env.balance(alice) == aliceBalance - XRPAmount(sendAmt)); - BEAST_EXPECT(env.balance(bob) == bobBalance - (10 * baseFee)); - BEAST_EXPECT(env.balance(daria) == dariaBalance); - BEAST_EXPECT(env.balance(carol) == carolBalance + XRPAmount(sendAmt)); - } - - // The delegated account bob attempts sign_for, will be rejected. - { - json::Value jv = makeDelegateTx(); - jv[jss::account] = bob.human(); - jv[jss::secret] = bob.name(); - auto jrr = env.rpc("json", "sign_for", to_string(jv))[jss::result]; - BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message].asString().find( - "A Signer may not be the transaction's Account") != std::string::npos); - } - } - void testPermissionValue(FeatureBitset features) { @@ -2042,7 +1898,7 @@ class Delegate_test : public beast::unit_test::Suite jv[jss::Account] = alice.human(); jv[sfAuthorize.jsonName] = bob.human(); - json::Value permissionsJson(json::ValueType::Array); + json::Value permissionsJson(json::ArrayValue); json::Value permissionValue; permissionValue[sfPermissionValue.jsonName] = value; json::Value permissionObj; @@ -2230,8 +2086,6 @@ class Delegate_test : public beast::unit_test::Suite testSingleSignBadSecret(); testMultiSign(); testMultiSignQuorumNotMet(); - testMultiSignDelegatorAsSigner(); - testSignForDelegated(); testPermissionValue(all); testTxRequireFeatures(all); testTxDelegableCount(); diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index 98597a175f..e0b48d8572 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -58,7 +58,7 @@ reserve(jtx::Env& env, std::uint32_t count) static bool hasDepositAuth(jtx::Env const& env, jtx::Account const& acct) { - return env.le(acct)->isFlag(lsfDepositAuth); + return ((*env.le(acct))[sfFlags] & lsfDepositAuth) == lsfDepositAuth; } struct DepositAuth_test : public beast::unit_test::Suite @@ -370,7 +370,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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); for (auto const& o : auth) { @@ -795,7 +795,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite // Alice can't pay - empty credentials array { auto jv = pay(alice, bob, XRP(100)); - jv[sfCredentialIDs.jsonName] = json::ValueType::Array; + jv[sfCredentialIDs.jsonName] = json::ArrayValue; env(jv, Ter(temMALFORMED)); env.close(); } @@ -929,7 +929,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite { // both included [AuthorizeCredentials UnauthorizeCredentials] auto jv = deposit::authCredentials(bob, {{issuer, credType}}); - jv[sfUnauthorizeCredentials.jsonName] = json::ValueType::Array; + jv[sfUnauthorizeCredentials.jsonName] = json::ArrayValue; env(jv, Ter(temMALFORMED)); } @@ -971,7 +971,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite // invalid issuer auto jv = deposit::authCredentials(bob, {}); auto& arr(jv[sfAuthorizeCredentials.jsonName]); - json::Value cred = json::ValueType::Object; + json::Value cred = json::ObjectValue; cred[jss::Issuer] = to_string(xrpAccount()); cred[sfCredentialType.jsonName] = strHex(std::string_view(credType)); json::Value credParent; @@ -1232,7 +1232,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite env.close(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), escrow::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); env.close(); // zelda can't finish escrow with invalid credentials diff --git a/src/test/app/Discrepancy_test.cpp b/src/test/app/Discrepancy_test.cpp index 8d2038fe94..0d3460dd2a 100644 --- a/src/test/app/Discrepancy_test.cpp +++ b/src/test/app/Discrepancy_test.cpp @@ -93,7 +93,7 @@ class Discrepancy_test : public beast::unit_test::Suite json::Value jrq2; jrq2[jss::binary] = false; - jrq2[jss::transaction] = env.tx()->getJson(JsonOptions::Values::None)[jss::hash]; + jrq2[jss::transaction] = env.tx()->getJson(JsonOptions::KNone)[jss::hash]; jrq2[jss::id] = 3; auto jrr = env.rpc("json", "tx", to_string(jrq2))[jss::result]; uint64_t const fee{jrr[jss::Fee].asUInt()}; diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 5bb1303dba..bf7cf90bf2 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -122,23 +122,23 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), createResult); env.close(); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), finishResult); env.close(); auto const seq2 = env.seq(alice); env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), createResult); env.close(); @@ -166,8 +166,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_TARGET)); env.close(); @@ -203,16 +203,16 @@ struct EscrowToken_test : public beast::unit_test::Suite // Create Escrow #1 & #2 auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); auto const seq2 = env.seq(alice); env(escrow::create(alice, bob, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 3s), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 3s), Fee(baseFee), Ter(tesSUCCESS)); env.close(); @@ -224,16 +224,16 @@ struct EscrowToken_test : public beast::unit_test::Suite // Cannot Create Escrow without asfAllowTrustLineLocking env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); // Can finish the escrow created before the flag was cleared env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -260,7 +260,7 @@ struct EscrowToken_test : public beast::unit_test::Suite env.fund(XRP(5000), alice, bob, gw); env(escrow::create(alice, bob, usd(1)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Fee(XRP(-1)), Ter(temBAD_FEE)); env.close(); @@ -277,8 +277,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.fund(XRP(5000), alice, bob, gw); env(escrow::create(alice, bob, usd(-1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(temBAD_AMOUNT)); env.close(); @@ -295,8 +295,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.fund(XRP(5000), alice, bob, gw); env(escrow::create(alice, bob, bad(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(temBAD_CURRENCY)); env.close(); @@ -321,8 +321,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.fund(XRP(5000), alice, bob, gw); env(escrow::create(gw, alice, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -341,8 +341,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.memoize(gw); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_ISSUER)); env.close(); @@ -365,8 +365,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(gw, alice, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -384,8 +384,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env(fset(gw, asfAllowTrustLineLocking)); env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_LINE)); env.close(); @@ -409,8 +409,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -434,8 +434,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -465,8 +465,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -496,8 +496,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -520,8 +520,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecINSUFFICIENT_FUNDS)); env.close(); @@ -547,8 +547,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, usd(10'001)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecINSUFFICIENT_FUNDS)); env.close(); @@ -577,8 +577,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(largeMantissa ? (TER)tesSUCCESS : (TER)tecPRECISION_LOSS)); env.close(); @@ -616,8 +616,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -632,8 +632,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob cannot finish because he is not authorized env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -658,8 +658,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -669,8 +669,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob cannot finish because of deep freeze env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -706,16 +706,16 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); // bob cannot finish because insufficient reserve to create line env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_LINE_INSUF_RESERVE)); env.close(); @@ -740,16 +740,16 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); // alice cannot finish because bob does not have a trustline env(escrow::finish(alice, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_LINE)); env.close(); @@ -774,8 +774,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(5)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -785,8 +785,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice cannot finish because bob's limit is too low env(escrow::finish(alice, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecLIMIT_EXCEEDED)); env.close(); @@ -811,8 +811,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(5)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -824,8 +824,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const bobPreLimit = env.limit(bob, usd); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -866,8 +866,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, usd(1)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee), Ter(tesSUCCESS)); env.close(); @@ -886,70 +886,6 @@ struct EscrowToken_test : public beast::unit_test::Suite } } - void - testIOUCancelDoApply(FeatureBitset features) - { - testcase("IOU Cancel DoApply"); - using namespace jtx; - using namespace std::literals; - - { - Env env{*this, features}; - auto const baseFee = env.current()->fees().base; - auto const alice = Account("alice"); - auto const bob = Account("bob"); - auto const gw = Account("gw"); - auto const usd = gw["USD"]; - - env.fund(XRP(10'000), alice, bob, gw); - env.close(); - - env(fset(gw, asfAllowTrustLineLocking)); - env.close(); - - env.trust(usd(100'000), alice); - env.trust(usd(100'000), bob); - env.close(); - - env(pay(gw, alice, usd(10'000))); - env.close(); - - auto const seq = env.seq(alice); - env(escrow::create(alice, bob, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), - Fee(baseFee)); - env.close(); - - BEAST_EXPECT(env.balance(alice, usd) == usd(9'000)); - - env(pay(alice, gw, usd(9'000))); - env.close(); - - env(trust(alice, usd(0))); - env.close(); - - auto const trustLineKey = keylet::line(alice.id(), gw.id(), usd.currency); - BEAST_EXPECT(!env.current()->exists(trustLineKey)); - - env.close(); - env.close(); - - auto const expectedResult = env.current()->rules().enabled(fixCleanup3_2_0) - ? Ter(tesSUCCESS) - : Ter(tefEXCEPTION); - env(escrow::cancel(alice, alice, seq), Fee(baseFee), expectedResult); - env.close(); - - if (env.current()->rules().enabled(fixCleanup3_2_0)) - { - BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), seq))); - BEAST_EXPECT(env.current()->exists(trustLineKey)); - BEAST_EXPECT(env.balance(alice, usd) == usd(1'000)); - } - } - } - void testIOUBalances(FeatureBitset features) { @@ -981,8 +917,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceUSD = env.balance(alice, usd); auto const preBobUSD = env.balance(bob, usd); env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -996,8 +932,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceUSD = env.balance(alice, usd); auto const preBobUSD = env.balance(bob, usd); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -1014,9 +950,9 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceUSD = env.balance(alice, usd); auto const preBobUSD = env.balance(bob, usd); env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -1067,8 +1003,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const bseq = env.seq(bob); env(escrow::create(alice, alice, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 500s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 500s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1091,8 +1027,8 @@ struct EscrowToken_test : public beast::unit_test::Suite } env(escrow::create(bob, bob, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1177,13 +1113,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::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bob, usd(1'000)), escrow::kFINISH_TIME(env.now() + 1s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1309,14 +1245,14 @@ 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::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, gw, usd(1'000)), escrow::kFINISH_TIME(env.now() + 1s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(gw, carol, usd(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Ter(tecNO_PERMISSION)); env.close(5s); @@ -1458,8 +1394,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(t.src); auto const delta = usd(1'000); env(escrow::create(t.src, t.dst, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -1468,8 +1404,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preDst = env.balance(t.dst, usd); env(escrow::finish(t.dst, t.src, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -1510,8 +1446,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // issuer cannot create escrow env(escrow::create(gw, alice, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -1548,15 +1484,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(t.src); auto const preSrc = env.balance(t.src, usd); env(escrow::create(t.src, t.dst, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // issuer can finish escrow, no dest trustline env(escrow::finish(t.dst, t.src, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); auto const preAmount = 10'000; @@ -1578,8 +1514,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // issuer cannot receive escrow env(escrow::create(gw, gw, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -1619,8 +1555,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); @@ -1628,8 +1564,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob can finish escrow env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -1656,8 +1592,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); @@ -1669,8 +1605,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob can finish escrow - rate unchanged env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -1698,8 +1634,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); @@ -1711,8 +1647,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob can finish escrow - rate changed env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -1740,8 +1676,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 3s), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 3s), Fee(baseFee)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); @@ -1789,16 +1725,16 @@ struct EscrowToken_test : public beast::unit_test::Suite auto seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // bob can finish auto const preBobLimit = env.limit(bob, usd); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); auto const postBobLimit = env.limit(bob, usd); @@ -1840,8 +1776,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto seq1 = env.seq(alice); auto const delta = usd(125); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -1856,15 +1792,15 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice can create escrow - bob has auth seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // bob can finish env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); } @@ -1904,8 +1840,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow fails - frozen trustline env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -1917,8 +1853,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -1928,8 +1864,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob finish escrow success regardless of frozen assets env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -1940,8 +1876,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -1979,8 +1915,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow fails - frozen trustline env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -1992,8 +1928,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -2003,8 +1939,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob finish escrow success regardless of frozen assets env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -2016,8 +1952,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -2055,8 +1991,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow fails - frozen trustline env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -2068,8 +2004,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -2079,8 +2015,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob finish escrow fails because of deep frozen assets env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecFROZEN)); env.close(); @@ -2093,8 +2029,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success seq1 = env.seq(alice); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -2137,8 +2073,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // create escrow success auto const delta = usd(1'000); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); env(pay(alice, gw, usd(10'000)), Ter(tecPATH_PARTIAL)); @@ -2160,14 +2096,14 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const delta = usd(1'000); env(escrow::create(alice, bob, delta), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); env(escrow::create(alice, bob, usd(10'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecINSUFFICIENT_FUNDS)); env.close(); @@ -2205,8 +2141,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, usd(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(largeMantissa ? (TER)tesSUCCESS : (TER)tecPRECISION_LOSS)); env.close(); @@ -2214,15 +2150,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); // alice can create escrow for 1'000 iou env(escrow::create(alice, bob, usd(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // bob finish escrow success env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); } @@ -2259,22 +2195,22 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), createResult); env.close(); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), finishResult); env.close(); auto const seq2 = env.seq(alice); env(escrow::create(alice, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), createResult); env.close(); @@ -2308,8 +2244,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const result = withMPT ? Ter(temBAD_AMOUNT) : Ter(temDISABLED); env(jv, - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), result); env.close(); @@ -2334,8 +2270,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, mpt(-1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(temBAD_AMOUNT)); env.close(); @@ -2365,8 +2301,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(gw, alice, mpt(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -2387,8 +2323,8 @@ struct EscrowToken_test : public beast::unit_test::Suite jv[jss::Amount][jss::mpt_issuance_id] = "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; env(jv, - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecOBJECT_NOT_FOUND)); env.close(); @@ -2412,8 +2348,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, mpt(3)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -2433,8 +2369,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const mpt = mptGw["MPT"]; env(escrow::create(alice, bob, mpt(4)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecOBJECT_NOT_FOUND)); env.close(); @@ -2463,8 +2399,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); env(escrow::create(alice, bob, mpt(5)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -2496,8 +2432,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.authorize({.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); env(escrow::create(alice, bob, mpt(6)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -2527,8 +2463,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.set({.account = gw, .holder = alice, .flags = tfMPTLock}); env(escrow::create(alice, bob, mpt(7)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecLOCKED)); env.close(); @@ -2558,8 +2494,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.set({.account = gw, .holder = bob, .flags = tfMPTLock}); env(escrow::create(alice, bob, mpt(8)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecLOCKED)); env.close(); @@ -2583,8 +2519,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, mpt(9)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -2608,8 +2544,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, mpt(11)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecINSUFFICIENT_FUNDS)); env.close(); @@ -2634,8 +2570,8 @@ struct EscrowToken_test : public beast::unit_test::Suite env.close(); env(escrow::create(alice, bob, mpt(11)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecINSUFFICIENT_FUNDS)); env.close(); @@ -2673,8 +2609,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -2683,8 +2619,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.authorize({.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -2713,8 +2649,8 @@ struct EscrowToken_test : public beast::unit_test::Suite }); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecOBJECT_NOT_FOUND)); env.close(); @@ -2742,8 +2678,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(8)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -2752,8 +2688,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.set({.account = gw, .holder = bob, .flags = tfMPTLock}); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecLOCKED)); env.close(); @@ -2790,15 +2726,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecINSUFFICIENT_RESERVE)); env.close(); @@ -2824,15 +2760,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -2859,15 +2795,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); env(escrow::finish(carol, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); env.close(); @@ -2905,8 +2841,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCancelTime(env.now() + 2s), - escrow::kCondition(escrow::kCb1), + escrow::kCANCEL_TIME(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -2978,8 +2914,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceMPT = env.balance(alice, mpt); auto const preBobMPT = env.balance(bob, mpt); env(escrow::create(alice, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -2995,8 +2931,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceMPT = env.balance(alice, mpt); auto const preBobMPT = env.balance(bob, mpt); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3015,9 +2951,9 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preAliceMPT = env.balance(alice, mpt); auto const preBobMPT = env.balance(bob, mpt); env(escrow::create(alice, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3048,8 +2984,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq = env.seq(alice); auto const preAliceMPT = env.balance(alice, mpt); env(escrow::create(alice, alice, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3060,8 +2996,8 @@ struct EscrowToken_test : public beast::unit_test::Suite BEAST_EXPECT(issuerMPTEscrowed(env, mpt) == 1'000); env(escrow::finish(alice, alice, seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3077,9 +3013,9 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq = env.seq(alice); auto const preAliceMPT = env.balance(alice, mpt); env(escrow::create(alice, alice, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3104,15 +3040,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const preBobMPT = env.balance(bob, mpt); auto const preCarolMPT = env.balance(carol, mpt); env(escrow::create(alice, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); env(escrow::create(carol, bob, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3141,7 +3077,7 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const mpt = mptGw["MPT"]; - env(pay(gw, alice, mpt(kMaxMpTokenAmount))); + env(pay(gw, alice, mpt(kMAX_MP_TOKEN_AMOUNT))); env.close(); auto const preAliceMPT = env.balance(alice, mpt); @@ -3150,8 +3086,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -3163,8 +3099,8 @@ struct EscrowToken_test : public beast::unit_test::Suite BEAST_EXPECT(issuerMPTEscrowed(env, mpt) == 1); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3194,7 +3130,7 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const mpt = mptGw["MPT"]; - env(pay(gw, alice, mpt(kMaxMpTokenAmount))); + env(pay(gw, alice, mpt(kMAX_MP_TOKEN_AMOUNT))); env.close(); auto const preAliceMPT = env.balance(alice, mpt); @@ -3203,44 +3139,44 @@ struct EscrowToken_test : public beast::unit_test::Suite // Escrow Max MPT - 10 auto const seq1 = env.seq(alice); - env(escrow::create(alice, bob, mpt(kMaxMpTokenAmount - 10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + env(escrow::create(alice, bob, mpt(kMAX_MP_TOKEN_AMOUNT - 10)), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // Escrow 10 MPT auto const seq2 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); - BEAST_EXPECT(env.balance(alice, mpt) == preAliceMPT - mpt(kMaxMpTokenAmount)); - BEAST_EXPECT(mptEscrowed(env, alice, mpt) == kMaxMpTokenAmount); + BEAST_EXPECT(env.balance(alice, mpt) == preAliceMPT - mpt(kMAX_MP_TOKEN_AMOUNT)); + BEAST_EXPECT(mptEscrowed(env, alice, mpt) == kMAX_MP_TOKEN_AMOUNT); BEAST_EXPECT(env.balance(bob, mpt) == preBobMPT); BEAST_EXPECT(mptEscrowed(env, bob, mpt) == 0); BEAST_EXPECT(env.balance(gw, mpt) == outstandingMPT); - BEAST_EXPECT(issuerMPTEscrowed(env, mpt) == kMaxMpTokenAmount); + BEAST_EXPECT(issuerMPTEscrowed(env, mpt) == kMAX_MP_TOKEN_AMOUNT); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); env(escrow::finish(bob, alice, seq2), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(env.balance(alice, mpt) == preAliceMPT - mpt(kMaxMpTokenAmount)); + BEAST_EXPECT(env.balance(alice, mpt) == preAliceMPT - mpt(kMAX_MP_TOKEN_AMOUNT)); BEAST_EXPECT(mptEscrowed(env, alice, mpt) == 0); - BEAST_EXPECT(env.balance(bob, mpt) == preBobMPT + mpt(kMaxMpTokenAmount)); + BEAST_EXPECT(env.balance(bob, mpt) == preBobMPT + mpt(kMAX_MP_TOKEN_AMOUNT)); BEAST_EXPECT(mptEscrowed(env, bob, mpt) == 0); BEAST_EXPECT(env.balance(gw, mpt) == outstandingMPT); BEAST_EXPECT(issuerMPTEscrowed(env, mpt) == 0); @@ -3274,8 +3210,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const bseq = env.seq(bob); env(escrow::create(alice, alice, mpt(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 500s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 500s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -3298,8 +3234,8 @@ struct EscrowToken_test : public beast::unit_test::Suite } env(escrow::create(bob, bob, mpt(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -3367,13 +3303,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::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bob, mpt(1'000)), escrow::kFINISH_TIME(env.now() + 1s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, mpt(1'000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -3490,8 +3426,8 @@ struct EscrowToken_test : public beast::unit_test::Suite BEAST_EXPECT(preEscrowed == 0); env(escrow::create(alice, gw, mpt(1'000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -3502,8 +3438,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // issuer (dest) can finish escrow env(escrow::finish(gw, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -3553,8 +3489,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = mpt(125); env(escrow::create(alice, bob, mpt(125)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); @@ -3566,8 +3502,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob can finish escrow env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -3609,9 +3545,9 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = mpt(125); env(escrow::create(alice, bob, mpt(125)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 3s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 3s), Fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); @@ -3654,8 +3590,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); auto const delta = mpt(125); env(escrow::create(alice, gw, mpt(125)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); @@ -3667,8 +3603,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob can finish escrow env(escrow::finish(gw, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); @@ -3709,15 +3645,15 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const delta = mpt(125); // alice can create escrow - is authorized env(escrow::create(alice, bob, mpt(100)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // bob can finish escrow - is authorized env(escrow::finish(bob, alice, seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); } @@ -3750,9 +3686,9 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice create escrow auto seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(100)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150)); env.close(); @@ -3762,8 +3698,8 @@ struct EscrowToken_test : public beast::unit_test::Suite // bob cannot finish env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecLOCKED)); env.close(); @@ -3797,9 +3733,9 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice cannot create escrow to non issuer env(escrow::create(alice, bob, mpt(100)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150), Ter(tecNO_AUTH)); env.close(); @@ -3809,15 +3745,15 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice an create escrow to issuer auto seq = env.seq(alice); env(escrow::create(alice, gw, mpt(100)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); // gw can finish env(escrow::finish(gw, alice, seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); env.close(); } @@ -3827,9 +3763,9 @@ struct EscrowToken_test : public beast::unit_test::Suite // alice an create escrow to issuer auto seq = env.seq(alice); env(escrow::create(alice, gw, mpt(100)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150)); env.close(); @@ -3866,8 +3802,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); @@ -3883,8 +3819,8 @@ struct EscrowToken_test : public beast::unit_test::Suite mptGw.destroy({.id = mptGw.issuanceID(), .ownerCount = 1, .err = tecHAS_OBLIGATIONS}); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3913,8 +3849,8 @@ struct EscrowToken_test : public beast::unit_test::Suite auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, mpt(10)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3928,8 +3864,8 @@ struct EscrowToken_test : public beast::unit_test::Suite {.account = alice, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); env(escrow::finish(bob, alice, seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -3951,7 +3887,6 @@ struct EscrowToken_test : public beast::unit_test::Suite testIOUFinishPreclaim(features); testIOUFinishDoApply(features); testIOUCancelPreclaim(features); - testIOUCancelDoApply(features); testIOUBalances(features); testIOUMetaAndOwnership(features); testIOURippleState(features); @@ -3993,7 +3928,6 @@ public: {all - featureSingleAssetVault - featureLendingProtocol, all}) { testIOUWithFeats(feats); - testIOUWithFeats(feats - fixCleanup3_2_0); testMPTWithFeats(feats); testMPTWithFeats(feats - fixTokenEscrowV1); } diff --git a/src/test/app/Escrow_test.cpp b/src/test/app/Escrow_test.cpp index 3e76524cf1..408e9c4edf 100644 --- a/src/test/app/Escrow_test.cpp +++ b/src/test/app/Escrow_test.cpp @@ -47,27 +47,27 @@ 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::kFinishTime(env.now() + 1s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); env.close(); auto const seq1 = env.seq("alice"); env(escrow::create("alice", "bob", XRP(1000)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); env.close(); env(escrow::finish("bob", "alice", seq1), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); auto const seq2 = env.seq("alice"); env(escrow::create("alice", "bob", XRP(1000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s), + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s), Fee(baseFee * 150)); env.close(); env(escrow::cancel("bob", "alice", seq2), Fee(baseFee * 150)); @@ -90,7 +90,7 @@ 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::kFinishTime(ts)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::kFINISH_TIME(ts)); // Advance the ledger, verifying that the finish won't complete // prematurely. @@ -112,8 +112,8 @@ struct Escrow_test : public beast::unit_test::Suite auto const seq = env.seq("alice"); env(escrow::create("alice", "bob", XRP(1000)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(ts)); + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(ts)); // Advance the ledger, verifying that the cancel won't complete // prematurely. @@ -122,8 +122,8 @@ struct Escrow_test : public beast::unit_test::Suite // Verify that a finish won't work anymore. env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); @@ -144,8 +144,8 @@ struct Escrow_test : public beast::unit_test::Suite auto const seq = env.seq("alice"); env(escrow::create("alice", "bob", XRP(1000)), - escrow::kFinishTime(fts), - escrow::kCancelTime(cts)); + escrow::kFINISH_TIME(fts), + escrow::kCANCEL_TIME(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. @@ -175,8 +175,8 @@ struct Escrow_test : public beast::unit_test::Suite auto const seq = env.seq("alice"); env(escrow::create("alice", "bob", XRP(1000)), - escrow::kFinishTime(fts), - escrow::kCancelTime(cts)); + escrow::kFINISH_TIME(fts), + escrow::kCANCEL_TIME(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. @@ -219,14 +219,14 @@ struct Escrow_test : public beast::unit_test::Suite // required: env(fset(bob, asfRequireDest)); env(escrow::create(alice, bob, XRP(1000)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_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::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Stag(1), Dtag(2)); @@ -259,7 +259,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::kFinishTime(env.now() + 1s)); + env(escrow::create("bob", "george", XRP(10)), escrow::kFINISH_TIME(env.now() + 1s)); } } @@ -278,21 +278,21 @@ struct Escrow_test : public beast::unit_test::Suite // Creating an escrow with only a cancel time is not allowed: env(escrow::create("alice", "bob", XRP(100)), - escrow::kCancelTime(env.now() + 90s), + escrow::kCANCEL_TIME(env.now() + 90s), Fee(baseFee * 150), Ter(temMALFORMED)); - // Creating an escrow with only a cancel time and a kCondition is + // Creating an escrow with only a cancel time and a kCONDITION is // allowed: auto const seq = env.seq("alice"); env(escrow::create("alice", "bob", XRP(100)), - escrow::kCancelTime(env.now() + 90s), - escrow::kCondition(escrow::kCb1), + escrow::kCANCEL_TIME(env.now() + 90s), + escrow::kCONDITION(escrow::kCB1), Fee(baseFee * 150)); env.close(); env(escrow::finish("carol", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150)); BEAST_EXPECT(env.balance("bob") == XRP(5100)); @@ -300,9 +300,9 @@ struct Escrow_test : public beast::unit_test::Suite // allowed: auto const seqFt = env.seq("alice"); env(escrow::create("alice", "bob", XRP(100)), - escrow::kFinishTime(env.now()), // Set finish time to now so that - // we can call finish immediately. - escrow::kCancelTime(env.now() + 50s), + escrow::kFINISH_TIME(env.now()), // Set finish time to now so that + // we can call finish immediately. + escrow::kCANCEL_TIME(env.now() + 50s), Fee(baseFee * 150)); env.close(); env(escrow::finish("carol", "alice", seqFt), Fee(150 * baseFee)); @@ -324,24 +324,24 @@ struct Escrow_test : public beast::unit_test::Suite // temINVALID_FLAG env(escrow::create("alice", "bob", XRP(1000)), - escrow::kFinishTime(env.now() + 5s), + escrow::kFINISH_TIME(env.now() + 5s), Txflags(tfPassive), Ter(temINVALID_FLAG)); // Finish time is in the past env(escrow::create("alice", "bob", XRP(1000)), - escrow::kFinishTime(env.now() - 5s), + escrow::kFINISH_TIME(env.now() - 5s), Ter(tecNO_PERMISSION)); // Cancel time is in the past env(escrow::create("alice", "bob", XRP(1000)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() - 5s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() - 5s), Ter(tecNO_PERMISSION)); // no destination account env(escrow::create("alice", "carol", XRP(1000)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Ter(tecNO_DST)); env.fund(XRP(5000), "carol"); @@ -353,43 +353,43 @@ struct Escrow_test : public beast::unit_test::Suite // set the asfAllowTrustLineLocking flag auto const txResult = withTokenEscrow ? Ter(tecNO_PERMISSION) : Ter(temBAD_AMOUNT); env(escrow::create("alice", "carol", Account("alice")["USD"](500)), - escrow::kFinishTime(env.now() + 5s), + escrow::kFINISH_TIME(env.now() + 5s), txResult); } // Sending zero or no XRP: env(escrow::create("alice", "carol", XRP(0)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Ter(temBAD_AMOUNT)); env(escrow::create("alice", "carol", XRP(-1000)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_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 kCondition are attached: + // Fail if neither a FinishTime nor a kCONDITION are attached: env(escrow::create("alice", "carol", XRP(1)), - escrow::kCancelTime(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 1s), Ter(temMALFORMED)); // Fail if FinishAfter has already passed: env(escrow::create("alice", "carol", XRP(1)), - escrow::kFinishTime(env.now() - 1s), + escrow::kFINISH_TIME(env.now() - 1s), Ter(tecNO_PERMISSION)); // If both CancelAfter and FinishAfter are set, then CancelAfter must // be strictly later than FinishAfter. env(escrow::create("alice", "carol", XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 10s), - escrow::kCancelTime(env.now() + 10s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 10s), + escrow::kCANCEL_TIME(env.now() + 10s), Ter(temBAD_EXPIRATION)); env(escrow::create("alice", "carol", XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 10s), - escrow::kCancelTime(env.now() + 5s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 10s), + escrow::kCANCEL_TIME(env.now() + 5s), Ter(temBAD_EXPIRATION)); // Carol now requires the use of a destination tag @@ -397,14 +397,14 @@ struct Escrow_test : public beast::unit_test::Suite // missing destination tag env(escrow::create("alice", "carol", XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s), Ter(tecDST_TAG_NEEDED)); // Success! env(escrow::create("alice", "carol", XRP(1)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s), Dtag(1)); { // Fail if the sender wants to send more than he has: @@ -413,17 +413,17 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(accountReserve + accountIncrement + XRP(50), "daniel"); env(escrow::create("daniel", "bob", XRP(51)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Ter(tecUNFUNDED)); env.fund(accountReserve + accountIncrement + XRP(50), "evan"); env(escrow::create("evan", "bob", XRP(50)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Ter(tecUNFUNDED)); env.fund(accountReserve, "frank"); env(escrow::create("frank", "bob", XRP(1)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Ter(tecINSUFFICIENT_RESERVE)); } @@ -431,21 +431,21 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "hannah"); auto const seq = env.seq("hannah"); env(escrow::create("hannah", "hannah", XRP(10)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Fee(150 * baseFee)); env.close(); env(escrow::finish("hannah", "hannah", seq + 7), Fee(150 * baseFee), Ter(tecNO_TARGET)); } - { // Try to specify a kCondition for a non-conditional payment + { // Try to specify a kCONDITION for a non-conditional payment env.fund(XRP(5000), "ivan"); auto const seq = env.seq("ivan"); - env(escrow::create("ivan", "ivan", XRP(10)), escrow::kFinishTime(env.now() + 1s)); + env(escrow::create("ivan", "ivan", XRP(10)), escrow::kFINISH_TIME(env.now() + 1s)); env.close(); env(escrow::finish("ivan", "ivan", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); } @@ -465,7 +465,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::kFinishTime(env.now() + 5s)); + env(escrow::create("alice", "alice", XRP(1000)), escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -489,7 +489,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::kFinishTime(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -519,7 +519,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::kFinishTime(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -559,7 +559,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::kFinishTime(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); env.close(); @@ -581,8 +581,8 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "alice", "bob"); auto const seq = env.seq("alice"); env(escrow::create("alice", "alice", XRP(1000)), - escrow::kCondition(escrow::kCb2), - escrow::kFinishTime(env.now() + 5s)); + escrow::kCONDITION(escrow::kCB2), + escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -591,20 +591,20 @@ struct Escrow_test : public beast::unit_test::Suite env(escrow::cancel("bob", "alice", seq), Ter(tecNO_PERMISSION)); env(escrow::finish("alice", "alice", seq), Ter(tecNO_PERMISSION)); env(escrow::finish("alice", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee), Ter(tecNO_PERMISSION)); env(escrow::finish("bob", "alice", seq), Ter(tecNO_PERMISSION)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee), Ter(tecNO_PERMISSION)); env.close(); // Cancel continues to not be possible. Finish is possible but - // requires the kFulfillment associated with the escrow. + // requires the kFULFILLMENT 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)); @@ -612,8 +612,8 @@ struct Escrow_test : public beast::unit_test::Suite env.close(); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee)); } { @@ -624,8 +624,8 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "alice", "bob"); auto const seq = env.seq("alice"); env(escrow::create("alice", "alice", XRP(1000)), - escrow::kCondition(escrow::kCb3), - escrow::kFinishTime(env.now() + 5s)); + escrow::kCONDITION(escrow::kCB3), + escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); env.close(); @@ -639,18 +639,18 @@ struct Escrow_test : public beast::unit_test::Suite env.close(); env(escrow::finish("alice", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee), Ter(tecNO_PERMISSION)); env(escrow::finish("alice", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee)); } { @@ -661,8 +661,8 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "alice", "bob", "zelda"); auto const seq = env.seq("alice"); env(escrow::create("alice", "alice", XRP(1000)), - escrow::kCondition(escrow::kCb3), - escrow::kFinishTime(env.now() + 5s)); + escrow::kCONDITION(escrow::kCB3), + escrow::kFINISH_TIME(env.now() + 5s)); env.require(Balance("alice", XRP(4000) - drops(baseFee))); env.close(); @@ -682,18 +682,18 @@ struct Escrow_test : public beast::unit_test::Suite env.close(); env(escrow::finish("alice", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee), Ter(tecNO_PERMISSION)); env(escrow::finish("zelda", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee)); } } @@ -713,63 +713,63 @@ struct Escrow_test : public beast::unit_test::Suite auto const seq = env.seq("alice"); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 0); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(env.now() + 1s)); + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(env.now() + 1s)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); env.require(Balance("alice", XRP(4000) - drops(baseFee))); env.require(Balance("carol", XRP(5000))); env(escrow::cancel("bob", "alice", seq), Ter(tecNO_PERMISSION)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); - // Attempt to finish without a kFulfillment + // Attempt to finish without a kFULFILLMENT env(escrow::finish("bob", "alice", seq), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); - // Attempt to finish with a kCondition instead of a kFulfillment + // Attempt to finish with a kCONDITION instead of a kFULFILLMENT env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kCb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kCB1), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kCb2), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kCB2), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kCb3), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kCB3), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); - // Attempt to finish with an incorrect kCondition and various + // Attempt to finish with an incorrect kCONDITION and various // combinations of correct and incorrect fulfillments. env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB1), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); - // Attempt to finish with the correct kCondition & kFulfillment + // Attempt to finish with the correct kCONDITION & kFULFILLMENT env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(150 * baseFee)); // SLE removed on finish @@ -780,15 +780,15 @@ struct Escrow_test : public beast::unit_test::Suite BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 0); env(escrow::cancel("bob", "carol", 1), Ter(tecNO_TARGET)); } - { // Test cancel when kCondition is present + { // Test cancel when kCONDITION is present Env env(*this, features); auto const baseFee = env.current()->fees().base; env.fund(XRP(5000), "alice", "bob", "carol"); auto const seq = env.seq("alice"); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 0); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(escrow::kCb2), - escrow::kCancelTime(env.now() + 1s)); + escrow::kCONDITION(escrow::kCB2), + escrow::kCANCEL_TIME(env.now() + 1s)); env.close(); env.require(Balance("alice", XRP(4000) - drops(baseFee))); // balance restored on cancel @@ -804,8 +804,8 @@ struct Escrow_test : public beast::unit_test::Suite env.close(); auto const seq = env.seq("alice"); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(escrow::kCb3), - escrow::kCancelTime(env.now() + 1s)); + escrow::kCONDITION(escrow::kCB3), + escrow::kCANCEL_TIME(env.now() + 1s)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); // cancel fails before expiration env(escrow::cancel("bob", "alice", seq), Ter(tecNO_PERMISSION)); @@ -813,8 +813,8 @@ struct Escrow_test : public beast::unit_test::Suite env.close(); // finish fails after expiration env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee), Ter(tecNO_PERMISSION)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); @@ -825,8 +825,8 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "alice", "bob", "carol"); std::vector v; - v.resize(escrow::kCb1.size() + 2, 0x78); - std::memcpy(v.data() + 1, escrow::kCb1.data(), escrow::kCb1.size()); + v.resize(escrow::kCB1.size() + 2, 0x78); + std::memcpy(v.data() + 1, escrow::kCB1.data(), escrow::kCB1.size()); auto const p = v.data(); auto const s = v.size(); @@ -834,45 +834,45 @@ struct Escrow_test : public beast::unit_test::Suite auto const ts = env.now() + 1s; // All these are expected to fail, because the - // kCondition we pass in is malformed in some way + // kCONDITION we pass in is malformed in some way env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p, s}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p, s}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p, s - 1}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p, s - 1}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p, s - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p, s - 2}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p + 1, s - 1}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p + 1, s - 1}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p + 1, s - 3}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p + 1, s - 3}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p + 2, s - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p + 2, s - 2}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p + 2, s - 3}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p + 2, s - 3}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); auto const seq = env.seq("alice"); auto const baseFee = env.current()->fees().base; env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{p + 1, s - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{p + 1, s - 2}), + escrow::kCANCEL_TIME(ts), Fee(10 * baseFee)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(150 * baseFee)); env.require(Balance("alice", XRP(4000) - drops(10 * baseFee))); env.require(Balance("bob", XRP(5000) - drops(150 * baseFee))); @@ -883,15 +883,15 @@ struct Escrow_test : public beast::unit_test::Suite env.fund(XRP(5000), "alice", "bob", "carol"); std::vector cv; - cv.resize(escrow::kCb2.size() + 2, 0x78); - std::memcpy(cv.data() + 1, escrow::kCb2.data(), escrow::kCb2.size()); + cv.resize(escrow::kCB2.size() + 2, 0x78); + std::memcpy(cv.data() + 1, escrow::kCB2.data(), escrow::kCB2.size()); auto const cp = cv.data(); auto const cs = cv.size(); std::vector fv; - fv.resize(escrow::kFb2.size() + 2, 0x13); - std::memcpy(fv.data() + 1, escrow::kFb2.data(), escrow::kFb2.size()); + fv.resize(escrow::kFB2.size() + 2, 0x13); + std::memcpy(fv.data() + 1, escrow::kFB2.data(), escrow::kFB2.size()); auto const fp = fv.data(); auto const fs = fv.size(); @@ -899,181 +899,181 @@ struct Escrow_test : public beast::unit_test::Suite auto const ts = env.now() + 1s; // All these are expected to fail, because the - // kCondition we pass in is malformed in some way + // kCONDITION we pass in is malformed in some way env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp, cs}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp, cs}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp, cs - 1}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp, cs - 1}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp, cs - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp, cs - 2}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp + 1, cs - 1}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp + 1, cs - 1}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp + 1, cs - 3}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp + 1, cs - 3}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp + 2, cs - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp + 2, cs - 2}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp + 2, cs - 3}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp + 2, cs - 3}), + escrow::kCANCEL_TIME(ts), Ter(temMALFORMED)); auto const seq = env.seq("alice"); auto const baseFee = env.current()->fees().base; env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kCancelTime(ts), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kCANCEL_TIME(ts), Fee(10 * baseFee)); // Now, try to fulfill using the same sequence of // malformed conditions. env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp, cs}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp, cs}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp, cs - 1}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp, cs - 1}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp, cs - 2}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp, cs - 2}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 1}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp + 1, cs - 1}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 3}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp + 1, cs - 3}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 2, cs - 2}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp + 2, cs - 2}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 2, cs - 3}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp + 2, cs - 3}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); - // Now, using the correct kCondition, try malformed fulfillments: + // Now, using the correct kCONDITION, try malformed fulfillments: env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp, fs}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp, fs}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp, fs - 1}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp, fs - 1}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp, fs - 2}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp, fs - 2}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp + 1, fs - 1}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp + 1, fs - 1}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp + 1, fs - 3}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp + 1, fs - 3}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp + 1, fs - 3}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp + 1, fs - 3}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp + 2, fs - 2}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp + 2, fs - 2}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{cp + 1, cs - 2}), - escrow::kFulfillment(Slice{fp + 2, fs - 3}), + escrow::kCONDITION(Slice{cp + 1, cs - 2}), + escrow::kFULFILLMENT(Slice{fp + 2, fs - 3}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); // Now try for the right one env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb2), - escrow::kFulfillment(escrow::kFb2), + escrow::kCONDITION(escrow::kCB2), + escrow::kFULFILLMENT(escrow::kFB2), Fee(150 * baseFee)); env.require(Balance("alice", XRP(4000) - drops(10 * baseFee))); env.require(Balance("carol", XRP(6000))); } - { // Test empty kCondition during creation and - // empty kCondition & kFulfillment during finish + { // Test empty kCONDITION during creation and + // empty kCONDITION & kFULFILLMENT during finish Env env(*this, features); env.fund(XRP(5000), "alice", "bob", "carol"); env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(Slice{}), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(Slice{}), + escrow::kCANCEL_TIME(env.now() + 1s), Ter(temMALFORMED)); auto const seq = env.seq("alice"); auto const baseFee = env.current()->fees().base; env(escrow::create("alice", "carol", XRP(1000)), - escrow::kCondition(escrow::kCb3), - escrow::kCancelTime(env.now() + 1s)); + escrow::kCONDITION(escrow::kCB3), + escrow::kCANCEL_TIME(env.now() + 1s)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{}), - escrow::kFulfillment(Slice{}), + escrow::kCONDITION(Slice{}), + escrow::kFULFILLMENT(Slice{}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(Slice{}), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(Slice{}), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); env(escrow::finish("bob", "alice", seq), - escrow::kCondition(Slice{}), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(Slice{}), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee), Ter(tecCRYPTOCONDITION_ERROR)); // 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::kCondition(escrow::kCb3), + escrow::kCONDITION(escrow::kCB3), Ter(temMALFORMED)); env(escrow::finish("bob", "alice", seq), - escrow::kFulfillment(escrow::kFb3), + escrow::kFULFILLMENT(escrow::kFB3), Ter(temMALFORMED)); // Now finish it. env(escrow::finish("bob", "alice", seq), - escrow::kCondition(escrow::kCb3), - escrow::kFulfillment(escrow::kFb3), + escrow::kCONDITION(escrow::kCB3), + escrow::kFULFILLMENT(escrow::kFB3), Fee(150 * baseFee)); env.require(Balance("carol", XRP(6000))); env.require(Balance("alice", XRP(4000) - drops(baseFee))); } - { // Test a kCondition other than PreimageSha256, which + { // Test a kCONDITION other than PreimageSha256, which // would require a separate amendment Env env(*this, features); env.fund(XRP(5000), "alice", "bob"); @@ -1087,8 +1087,8 @@ struct Escrow_test : public beast::unit_test::Suite // FIXME: this transaction should, eventually, return temDISABLED // instead of temMALFORMED. env(escrow::create("alice", "bob", XRP(1000)), - escrow::kCondition(cb), - escrow::kCancelTime(env.now() + 1s), + escrow::kCONDITION(cb), + escrow::kCANCEL_TIME(env.now() + 1s), Ter(temMALFORMED)); } } @@ -1112,8 +1112,8 @@ struct Escrow_test : public beast::unit_test::Suite auto const bseq = env.seq(bruce); env(escrow::create(alice, alice, XRP(1000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 500s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 500s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1129,8 +1129,8 @@ struct Escrow_test : public beast::unit_test::Suite } env(escrow::create(bruce, bruce, XRP(1000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1187,13 +1187,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::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bruce, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bruce, carol, XRP(1000)), - escrow::kFinishTime(env.now() + 1s), - escrow::kCancelTime(env.now() + 2s)); + escrow::kFINISH_TIME(env.now() + 1s), + escrow::kCANCEL_TIME(env.now() + 2s)); BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); @@ -1296,7 +1296,7 @@ struct Escrow_test : public beast::unit_test::Suite { auto const jtx = env.jt( escrow::create("alice", "carol", XRP(1000)), - escrow::kFinishTime(env.now() + 1s), + escrow::kFINISH_TIME(env.now() + 1s), Seq(1), Fee(baseFee)); auto const pf = @@ -1352,12 +1352,12 @@ struct Escrow_test : public beast::unit_test::Suite // bob creates a bunch of tickets because he will be burning // through them with tec transactions. Just because we can // we'll use them up starting from largest and going smaller. - static constexpr std::uint32_t kBobTicketCount{20}; - env(ticket::create(bob, kBobTicketCount)); + constexpr static std::uint32_t kBOB_TICKET_COUNT{20}; + env(ticket::create(bob, kBOB_TICKET_COUNT)); env.close(); std::uint32_t bobTicket{env.seq(bob)}; env.require(tickets(alice, 1)); - env.require(tickets(bob, kBobTicketCount)); + env.require(tickets(bob, kBOB_TICKET_COUNT)); // Note that from here on all transactions use tickets. No account // root sequences should change. @@ -1369,11 +1369,11 @@ struct Escrow_test : public beast::unit_test::Suite std::uint32_t const escrowSeq = aliceTicket; env(escrow::create(alice, bob, XRP(1000)), - escrow::kFinishTime(ts), + escrow::kFINISH_TIME(ts), ticket::Use(aliceTicket)); BEAST_EXPECT(env.seq(alice) == aliceRootSeq); env.require(tickets(alice, 0)); - env.require(tickets(bob, kBobTicketCount)); + env.require(tickets(bob, kBOB_TICKET_COUNT)); // Advance the ledger, verifying that the finish won't complete // prematurely. Note that each tec consumes one of bob's tickets. @@ -1412,12 +1412,12 @@ struct Escrow_test : public beast::unit_test::Suite // bob creates a bunch of tickets because he will be burning // through them with tec transactions. - static constexpr std::uint32_t kBobTicketCount{20}; + constexpr std::uint32_t kBOB_TICKET_COUNT{20}; std::uint32_t bobTicket{env.seq(bob) + 1}; - env(ticket::create(bob, kBobTicketCount)); + env(ticket::create(bob, kBOB_TICKET_COUNT)); env.close(); env.require(tickets(alice, 1)); - env.require(tickets(bob, kBobTicketCount)); + env.require(tickets(bob, kBOB_TICKET_COUNT)); // Note that from here on all transactions use tickets. No account // root sequences should change. @@ -1429,12 +1429,12 @@ struct Escrow_test : public beast::unit_test::Suite std::uint32_t const escrowSeq = aliceTicket; env(escrow::create(alice, bob, XRP(1000)), - escrow::kCondition(escrow::kCb1), - escrow::kCancelTime(ts), + escrow::kCONDITION(escrow::kCB1), + escrow::kCANCEL_TIME(ts), ticket::Use(aliceTicket)); BEAST_EXPECT(env.seq(alice) == aliceRootSeq); env.require(tickets(alice, 0)); - env.require(tickets(bob, kBobTicketCount)); + env.require(tickets(bob, kBOB_TICKET_COUNT)); // Advance the ledger, verifying that the cancel won't complete // prematurely. @@ -1449,8 +1449,8 @@ struct Escrow_test : public beast::unit_test::Suite // Verify that a finish won't work anymore. env(escrow::finish(bob, alice, escrowSeq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(150 * baseFee), ticket::Use(bobTicket++), Ter(tecNO_PERMISSION)); @@ -1491,7 +1491,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::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); env.close(); env(fset(bob, asfDepositAuth)); @@ -1517,7 +1517,7 @@ struct Escrow_test : public beast::unit_test::Suite std::string const credIdx = jv[jss::result][jss::index].asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), escrow::kFinishTime(env.now() + 50s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::kFINISH_TIME(env.now() + 50s)); env.close(); // Bob require pre-authorization @@ -1570,7 +1570,7 @@ struct Escrow_test : public beast::unit_test::Suite std::string const credIdx = jv[jss::result][jss::index].asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), escrow::kFinishTime(env.now() + 50s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::kFINISH_TIME(env.now() + 50s)); // time advance env.close(); env.close(); @@ -1595,7 +1595,7 @@ struct Escrow_test : public beast::unit_test::Suite .asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), escrow::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); env.close(); // Bob require pre-authorization diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 22e8322bb5..8300b458b6 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -213,18 +213,18 @@ class FeeVote_test : public beast::unit_test::Suite // defaults Section const config; auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); - BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); - BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); + BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); + BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); + BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); } { Section config; config.append( {"reference_fee = 50", "account_reserve = 1234567", "owner_reserve = 1234"}); auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.referenceFee == 50); - BEAST_EXPECT(setup.accountReserve == 1234567); - BEAST_EXPECT(setup.ownerReserve == 1234); + BEAST_EXPECT(setup.reference_fee == 50); + BEAST_EXPECT(setup.account_reserve == 1234567); + BEAST_EXPECT(setup.owner_reserve == 1234); } { Section config; @@ -232,9 +232,9 @@ class FeeVote_test : public beast::unit_test::Suite {"reference_fee = blah", "account_reserve = yada", "owner_reserve = foo"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); - BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); - BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); + BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); + BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); + BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); } { Section config; @@ -242,9 +242,9 @@ class FeeVote_test : public beast::unit_test::Suite {"reference_fee = -50", "account_reserve = -1234567", "owner_reserve = -1234"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); - BEAST_EXPECT(setup.accountReserve == static_cast(-1234567)); - BEAST_EXPECT(setup.ownerReserve == static_cast(-1234)); + BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); + BEAST_EXPECT(setup.account_reserve == static_cast(-1234567)); + BEAST_EXPECT(setup.owner_reserve == static_cast(-1234)); } { auto const big64 = std::to_string( @@ -256,9 +256,9 @@ class FeeVote_test : public beast::unit_test::Suite "owner_reserve = " + big64}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); - BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); - BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); + BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); + BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); + BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); } } @@ -271,9 +271,9 @@ class FeeVote_test : public beast::unit_test::Suite { jtx::Env env(*this, jtx::testableAmendments() - featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -301,9 +301,9 @@ class FeeVote_test : public beast::unit_test::Suite { jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -334,9 +334,9 @@ class FeeVote_test : public beast::unit_test::Suite { jtx::Env env(*this, jtx::testableAmendments() - featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -356,9 +356,9 @@ class FeeVote_test : public beast::unit_test::Suite { jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -383,9 +383,9 @@ class FeeVote_test : public beast::unit_test::Suite jtx::Env env(*this, jtx::testableAmendments()); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -422,9 +422,9 @@ class FeeVote_test : public beast::unit_test::Suite jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -470,9 +470,9 @@ class FeeVote_test : public beast::unit_test::Suite jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -501,9 +501,9 @@ class FeeVote_test : public beast::unit_test::Suite jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -547,9 +547,9 @@ class FeeVote_test : public beast::unit_test::Suite jtx::Env env(*this, jtx::testableAmendments() | featureXRPFees); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -578,9 +578,9 @@ class FeeVote_test : public beast::unit_test::Suite using namespace jtx; FeeSetup setup; - setup.referenceFee = 42; - setup.accountReserve = 1234567; - setup.ownerReserve = 7654321; + setup.reference_fee = 42; + setup.account_reserve = 1234567; + setup.owner_reserve = 7654321; // Test with XRPFees enabled { @@ -588,9 +588,9 @@ class FeeVote_test : public beast::unit_test::Suite auto feeVote = makeFeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -609,7 +609,7 @@ class FeeVote_test : public beast::unit_test::Suite feeVote->doValidation(currentFees, ledger->rules(), *val); BEAST_EXPECT(val->isFieldPresent(sfBaseFeeDrops)); - BEAST_EXPECT(val->getFieldAmount(sfBaseFeeDrops) == XRPAmount(setup.referenceFee)); + BEAST_EXPECT(val->getFieldAmount(sfBaseFeeDrops) == XRPAmount(setup.reference_fee)); } // Test with XRPFees disabled (legacy format) @@ -618,9 +618,9 @@ class FeeVote_test : public beast::unit_test::Suite auto feeVote = makeFeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -638,7 +638,7 @@ class FeeVote_test : public beast::unit_test::Suite // In legacy mode, should vote using legacy fields BEAST_EXPECT(val->isFieldPresent(sfBaseFee)); - BEAST_EXPECT(val->getFieldU64(sfBaseFee) == setup.referenceFee); + BEAST_EXPECT(val->getFieldU64(sfBaseFee) == setup.reference_fee); } } @@ -650,9 +650,9 @@ class FeeVote_test : public beast::unit_test::Suite using namespace jtx; FeeSetup setup; - setup.referenceFee = 42; - setup.accountReserve = 1234567; - setup.ownerReserve = 7654321; + setup.reference_fee = 42; + setup.account_reserve = 1234567; + setup.owner_reserve = 7654321; Env env(*this, testableAmendments() | featureXRPFees); @@ -663,9 +663,9 @@ class FeeVote_test : public beast::unit_test::Suite auto feeVote = makeFeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -689,9 +689,9 @@ class FeeVote_test : public beast::unit_test::Suite env.app().getTimeKeeper().now(), pub, sec, calcNodeID(pub), [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, ledger->seq()); // Vote for different fees than current - v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.referenceFee}); - v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.accountReserve}); - v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.ownerReserve}); + v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.reference_fee}); + v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.account_reserve}); + v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.owner_reserve}); }); if ((i % 2) != 0) val->setTrusted(); @@ -723,10 +723,10 @@ class FeeVote_test : public beast::unit_test::Suite BEAST_EXPECT(!feeTx.isFieldPresent(sfReferenceFeeUnits)); // Check the values - BEAST_EXPECT(feeTx.getFieldAmount(sfBaseFeeDrops) == XRPAmount{setup.referenceFee}); - BEAST_EXPECT(feeTx.getFieldAmount(sfReserveBaseDrops) == XRPAmount{setup.accountReserve}); + 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.ownerReserve}); + 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 cfe2fd1808..f77d924c94 100644 --- a/src/test/app/FixNFTokenPageLinks_test.cpp +++ b/src/test/app/FixNFTokenPageLinks_test.cpp @@ -173,13 +173,6 @@ class FixNFTokenPageLinks_test : public beast::unit_test::Suite tx.removeMember(sfOwner.jsonName); env(tx, Fee(linkFixFee), Ter(temINVALID)); } - { - // NFTokenPageLink fixes require sfOwner and reject fields that - // belong to other LedgerStateFix types. - json::Value tx = ledgerStateFix::nftPageLinks(alice, alice); - tx[sfBookDirectory.jsonName] = to_string(uint256{1}); - env(tx, Fee(linkFixFee), Ter(temINVALID)); - } { // Invalid LedgerFixType codes. json::Value tx = ledgerStateFix::nftPageLinks(alice, alice); diff --git a/src/test/app/FlowMPT_test.cpp b/src/test/app/FlowMPT_test.cpp index 2e224a7eb1..9bb91755c8 100644 --- a/src/test/app/FlowMPT_test.cpp +++ b/src/test/app/FlowMPT_test.cpp @@ -37,6 +37,7 @@ #include #include +#include #include #include #include @@ -432,7 +433,7 @@ struct FlowMPT_test : public beast::unit_test::Suite env.require(Balance(bob, eur(999))); // Show that bob's USD offer is now a blocker. - SLE::const_pointer const usdOffer = env.le(bobUsdOffer); + std::shared_ptr const usdOffer = env.le(bobUsdOffer); if (BEAST_EXPECT(usdOffer)) { std::uint64_t const bookRate = [&usdOffer]() { @@ -729,11 +730,11 @@ struct FlowMPT_test : public beast::unit_test::Suite } // Helper function that returns the Offers on an account. - static std::vector + static std::vector> offersOnAccount(jtx::Env& env, jtx::Account account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) result.push_back(sle); }); @@ -1773,7 +1774,8 @@ struct FlowMPT_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(alice, usd) == usd(0)); BEAST_EXPECT(env.balance(carol, usd) == usd(0)); BEAST_EXPECT(env.balance(bob, usd) == usd(100 - d.expBobSellUSD)); - BEAST_EXPECT(env.balance(gw) == XRPAmount{d.expGwXRP * kDropsPerXrp - baseFee * 9}); + BEAST_EXPECT( + env.balance(gw) == XRPAmount{d.expGwXRP * kDROPS_PER_XRP - baseFee * 9}); BEAST_EXPECT(expectOffers(env, john, 0)); BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); BEAST_EXPECT(expectOffers(env, dan, d.expOffersDan())); @@ -1791,7 +1793,7 @@ struct FlowMPT_test : public beast::unit_test::Suite // but OutstandingAmount is 300USD because gw's sell offer is balanced out by // gw's buy offer. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=400, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=400, .outstandingUSD=300, .expEdBuyUSD=100, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false}, + { 400, 400, 400, 400, 300, 100, 100, 100, 1100, 0, false}, // Sell USD: alice, carol, bob, gw are consumed. // Buy USD: john, gw, dan, ed (partially) are consumed. // gw's sell USD is partially consumed because there is available balance (50USD). @@ -1800,32 +1802,32 @@ struct FlowMPT_test : public beast::unit_test::Suite // gw's offer is removed from the order book because it's partially consumed and // the remaining offer is unfunded. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=350, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=350, .outstandingUSD=250, .expEdBuyUSD=50, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=false}, + { 350, 400, 400, 350, 250, 50, 100, 100, 1050, 0, false}, // Sell USD: alice, carol, bob are consumed; gw's is unfunded // since OutstandingAmount is initially at MaximumAmount. // Buy USD: john, gw, dan are consumed; ed's remains on the order // book since 300USD is the sell limit. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 400, 400, 300, 200, 0, 100, 100, 1000, 0, false}, // Same as above. bill's trustline limit sets the output to 300USD. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=400, .dstTrustLimit=300, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 400, 300, 300, 200, 0, 100, 100, 1000, 0, false}, // Sell USD: alice, carol, bob are consumed; gw's removed from // the order book since it's unfunded. // Buy USD: john, gw, dan are consumed; ed's remains on the order // book since 300USD is the limit. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=400, .dstTrustLimit=300, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 400, 300, 300, 200, 0, 100, 100, 1000, 0, true}, // Sell USD: alice, carol are consumed; gw's removed from // the order book in rev pass since it's unfunded; bob's // remains on the order book. // Buy USD: john, gw; ed's, dan's remains on the order // book since 300USD is the limit. //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=200, .dstTrustLimit=300, .dstExpectEUR=200, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=0, .expBobSellUSD=0, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 200, 300, 200, 200, 0, 0, 0, 1000, 0, false}, // Same as three tests above since limited by buy 300USD (gw offer is unfunded) //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=380, .dstTrustLimit=400, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 380, 400, 300, 200, 0, 100, 100, 1000, 0, false}, }; // clang-format on for (auto const& t : tests) @@ -1899,7 +1901,8 @@ struct FlowMPT_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(bob, usd) == usd(d.expBobBuyUSD)); BEAST_EXPECT(env.balance(ed) == XRP(d.dstExpectXRP)); BEAST_EXPECT(env.balance(gw, usd) == usd(-d.outstandingUSD)); - BEAST_EXPECT(env.balance(gw) == XRPAmount{d.expGwXRP * kDropsPerXrp - baseFee * 3}); + BEAST_EXPECT( + env.balance(gw) == XRPAmount{d.expGwXRP * kDROPS_PER_XRP - baseFee * 3}); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob())); BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); @@ -1911,26 +1914,26 @@ struct FlowMPT_test : public beast::unit_test::Suite // Gw gets 300USD from alice; carol and bob buy 200USD, // therefore OutstandingAmount is 200. //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .gwOffer=100, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 300, 100, 1300, 200, 100, 900, 0, false}, // Same as above. Gw offer location in the order book doesn't matter //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .gwOffer=100, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 300, 100, 1300, 200, 100, 900, 0, true}, // Buy USD: carol, gw are consumed. bob's offer remains on the order book. // Gw gets 300USD from alice; carol buys 100USD, // therefore OutstandingAmount is 100. //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .gwOffer=200, .dstExpectXRP=1300, .outstandingUSD=100, .expBobBuyUSD=0, .expGwXRP=800, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 300, 200, 1300, 100, 0, 800, 0, false}, // Buy USD: carol, bob are consumed; gw's is partially consumed (100/100) since it's last. // Gw gets 300USD from alice; carol and bob buy 200USD, // therefore OutstandingAmount is 200. //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .gwOffer=200, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=1, .lastGwBuyUSD=true}, + { 300, 300, 200, 1300, 200, 100, 900, 1, true}, // Buy USD: carol, bob are consumed; gw's is partially consumed (50/50) since it's last // and sendMax limits the output. // Gw gets 250USD from alice; carol and bob buy 200USD, alice has 50USD left, // therefore OutstandingAmount is 200. //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=250, .gwOffer=200, .dstExpectXRP=1250, .outstandingUSD=250, .expBobBuyUSD=100, .expGwXRP=950, .expOffersGw=1, .lastGwBuyUSD=true}, + { 300, 250, 200, 1250, 250, 100, 950, 1, true}, }; // clang-format on for (auto const& t : tests) @@ -2004,7 +2007,7 @@ struct FlowMPT_test : public beast::unit_test::Suite auto const baseFee = env.current()->fees().base.drops(); BEAST_EXPECT( - env.balance(alice) == XRPAmount{d.expAliceXRP * kDropsPerXrp - baseFee}); + env.balance(alice) == XRPAmount{d.expAliceXRP * kDROPS_PER_XRP - baseFee}); BEAST_EXPECT(env.balance(carol, usd) == usd(0)); BEAST_EXPECT(env.balance(bob, usd) == usd(100 - d.expBobSellUSD)); BEAST_EXPECT(env.balance(ed, usd) == usd(d.dstExpectUSD)); @@ -2012,7 +2015,7 @@ struct FlowMPT_test : public beast::unit_test::Suite BEAST_EXPECT( env.balance(gw) == XRPAmount{ - d.expGwXRP * kDropsPerXrp - baseFee * (4 + (d.initDst != 0 ? 1 : 0))}); + d.expGwXRP * kDROPS_PER_XRP - baseFee * (4 + (d.initDst != 0 ? 1 : 0))}); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob())); BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); @@ -2023,10 +2026,10 @@ struct FlowMPT_test : public beast::unit_test::Suite // Sell USD: carol, gw, bob are consumed. // ed buys 300USD from carol, gw, bob therefore OutstandingAmount is 300. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .initDst=0, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=700, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 300, 0, 100, 300, 300, 700, 100, 1100, 0, false}, // Same as above. Gw offer location in the order book doesn't matter //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .initDst=0, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=700, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 300, 0, 100, 300, 300, 700, 100, 1100, 0, true}, // Sell USD: carol, bob are consumed, gw is partially consumed. // ed buys 200 from carol and bob and 50 from gw because gw can only issue 50 // (300(max) - 200(carol+bob) - 50(ed)). ed buys 250 from carol, gw, bob and has 50 initially, @@ -2034,33 +2037,33 @@ struct FlowMPT_test : public beast::unit_test::Suite // gw's offer is removed from the order book because it's partially consumed and the remaining // offer is unfunded. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 300, 50, 100, 300, 300, 750, 100, 1050, 0, false}, // Same as above. Gw offer location in the order book doesn't matter. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 300, 50, 100, 300, 300, 750, 100, 1050, 0, true}, // Same as above. Gw offer size doesn't matter. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=200, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 300, 50, 200, 300, 300, 750, 100, 1050, 0, true}, // Sell USD: carol, gw are consumed, bob is partially consumed. // ed buys 200 from carol and gw and 50 form bob because of sendMax limit. bob keeps 50, // therefore OutstandingAmount is 300. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=250, .initDst=0, .gwOffer=100, .dstExpectUSD=250, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=50, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false}, + { 300, 250, 0, 100, 250, 300, 750, 50, 1100, 0, false}, // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit. // ed buys 200 from carol and bob and 50 from gw. Therefore, OutstandingAmount is 250. // gw's offer remains on the order book because it's partially consumed and has more funds. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=250, .initDst=0, .gwOffer=100, .dstExpectUSD=250, .outstandingUSD=250, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=1, .lastGwBuyUSD=true}, + { 300, 250, 0, 100, 250, 250, 750, 100, 1050, 1, true}, // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit, also // there is only 50 available to issue. ed buys 200 from carol and bob and 50 from gw, plus // he has initially 50, therefore OutstandingAmount is 300. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=250, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 250, 50, 100, 300, 300, 750, 100, 1050, 0, true}, // Sell USD: carol, bob are consumed, gw is not consumed because there is not available funds // to issue. ed buys 200 from carol and bob and, plus he has initially 100, // therefore OutstandingAmount is 300. gw offer is removed because it's unfunded. //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw - { .maxAmt=300, .sendMax=250, .initDst=100, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=800, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=true}, + { 300, 250, 100, 100, 300, 300, 800, 100, 1000, 0, true}, }; // clang-format on for (auto const& t : tests) diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 5f56a0ceb1..c6f4cf59d1 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -43,6 +43,7 @@ #include #include +#include #include #include #include @@ -571,7 +572,7 @@ struct Flow_test : public beast::unit_test::Suite env.require(Balance(bob, eur(999))); // Show that bob's USD offer is now a blocker. - SLE::const_pointer const usdOffer = env.le(bobUsdOffer); + std::shared_ptr const usdOffer = env.le(bobUsdOffer); if (BEAST_EXPECT(usdOffer)) { std::uint64_t const bookRate = [&usdOffer]() { @@ -710,11 +711,11 @@ struct Flow_test : public beast::unit_test::Suite } // Helper function that returns the Offers on an account. - static std::vector + static std::vector> offersOnAccount(jtx::Env& env, jtx::Account account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) result.push_back(sle); }); diff --git a/src/test/app/Freeze_test.cpp b/src/test/app/Freeze_test.cpp index 2b5ca831da..26b7a1e70a 100644 --- a/src/test/app/Freeze_test.cpp +++ b/src/test/app/Freeze_test.cpp @@ -95,14 +95,12 @@ 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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + ff[sfLowLimit.fieldName] == g1["USD"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfLowFreeze); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -112,16 +110,14 @@ 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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + ff[sfHighLimit.fieldName] == bob["USD"](100).value().getJson(JsonOptions::KNone)); auto amt = STAmount{Issue{toCurrency("USD"), noAccount()}, -15}.value().getJson( - JsonOptions::Values::None); + JsonOptions::KNone); BEAST_EXPECT(ff[sfBalance.fieldName] == amt); env.close(); } @@ -178,14 +174,12 @@ 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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + ff[sfLowLimit.fieldName] == g1["USD"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -365,8 +359,7 @@ class Freeze_test : public beast::unit_test::Suite // trust line env(trust(g1, a1["USD"](0), tfSetFreeze | tfClearFreeze)); { - auto affected = - env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; BEAST_EXPECT(checkArraySize(affected, 1u)); // means no trustline changes } } @@ -606,8 +599,7 @@ class Freeze_test : public beast::unit_test::Suite // 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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 1u))) return; @@ -673,8 +665,7 @@ class Freeze_test : public beast::unit_test::Suite if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; BEAST_EXPECT( - offers[0u][jss::taker_gets] == - g1["USD"](999).value().getJson(JsonOptions::Values::None)); + offers[0u][jss::taker_gets] == g1["USD"](999).value().getJson(JsonOptions::KNone)); // test: someone else creates an offer providing liquidity env(offer(a4, XRP(999), g1["USD"](999))); @@ -682,12 +673,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::Values::None)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + BEAST_EXPECT(ff[sfHighLimit.fieldName] == g1["USD"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfHighFreeze); env.close(); @@ -709,19 +699,18 @@ 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::Values::None)[sfAffectedNodes.fieldName]; + affected = env.meta()->getJson(JsonOptions::KNone)[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::Values::None)); + BEAST_EXPECT(ff[sfLowLimit.fieldName] == g1["USD"](0).value().getJson(JsonOptions::KNone)); 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::Values::None)[sfAffectedNodes.fieldName]; + affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 8u))) return; auto created = affected[0u][sfCreatedNode.fieldName]; @@ -1925,8 +1914,7 @@ class Freeze_test : public beast::unit_test::Suite bool modified = true) { using namespace test::jtx; - auto const affected = - env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName]; + auto const affected = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, expectedArraySize))) return 0; diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index c7156fb3a2..6dbf335b6c 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -27,7 +27,7 @@ namespace { -constexpr std::string_view kCaCertContent = +constexpr std::string_view kCA_CERT_CONTENT = "-----BEGIN CERTIFICATE-----\n" "MIIFhjCCA26gAwIBAgIJAL9P70zX30oiMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNV\n" "BAYTAlVTMQ0wCwYDVQQIDARUZXN0MQ0wCwYDVQQHDARUZXN0MRgwFgYDVQQKDA9S\n" @@ -61,7 +61,7 @@ constexpr std::string_view kCaCertContent = "fAbAYqu0rfMFHUYjzIVnu8WRCC56qYHO5tU=\n" "-----END CERTIFICATE-----\n"; -constexpr std::string_view kServerCertContent = +constexpr std::string_view kSERVER_CERT_CONTENT = "-----BEGIN CERTIFICATE-----\n" "MIIFizCCA3OgAwIBAgIJAIErcpMflkrRMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNV\n" "BAYTAlVTMQ0wCwYDVQQIDARUZXN0MQ0wCwYDVQQHDARUZXN0MRgwFgYDVQQKDA9S\n" @@ -95,7 +95,7 @@ constexpr std::string_view kServerCertContent = "YSyd81wvumIpP+I7BDkQLgTb+NzMmoBIjRg3aVvXSg==\n" "-----END CERTIFICATE-----\n"; -constexpr std::string_view kServerKeyContent = +constexpr std::string_view kSERVER_KEY_CONTENT = "-----BEGIN PRIVATE KEY-----\n" "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCv+Lj9LJfPuSOE\n" "yZqTn2gmG5tJt02ywnuIQet7N5tduxnNs50yXQ00Jeb40dth0HwI5I+AsEVNPIG3\n" @@ -149,7 +149,7 @@ constexpr std::string_view kServerKeyContent = "S/RYUSUkZ4VvqFUfo7wT8x18urb87w==\n" "-----END PRIVATE KEY-----\n"; -constexpr std::string_view kClientCertContent = +constexpr std::string_view kCLIENT_CERT_CONTENT = "-----BEGIN CERTIFICATE-----\n" "MIIFeDCCA2CgAwIBAgIJAIErcpMflkrSMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNV\n" "BAYTAlVTMQ0wCwYDVQQIDARUZXN0MQ0wCwYDVQQHDARUZXN0MRgwFgYDVQQKDA9S\n" @@ -183,7 +183,7 @@ constexpr std::string_view kClientCertContent = "cTe8jkzRqYdUfAoV\n" "-----END CERTIFICATE-----\n"; -constexpr std::string_view kClientKeyContent = +constexpr std::string_view kCLIENT_KEY_CONTENT = "-----BEGIN PRIVATE KEY-----\n" "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDPQHttw3TLjOqY\n" "S3VkLF3KMRaP2ZtO6A1mXfTbqbKvD41Fazf/cM/v9lPMAlRd2SEY3MeE8KVddKJw\n" @@ -246,26 +246,26 @@ constexpr std::string_view kClientKeyContent = class TemporaryTLSCertificates { public: - static constexpr std::string_view kCaCertFilename = "ca.pem"; - static constexpr std::string_view kServerCertFilename = "server_cert.pem"; - static constexpr std::string_view kServerKeyFilename = "server_key.pem"; - static constexpr std::string_view kClientCertFilename = "client_cert.pem"; - static constexpr std::string_view kClientKeyFilename = "client_key.pem"; - static constexpr std::string_view kCertsDirPrefix = "grpc_tls_test_"; + static constexpr std::string_view kCA_CERT_FILENAME = "ca.pem"; + static constexpr std::string_view kSERVER_CERT_FILENAME = "server_cert.pem"; + static constexpr std::string_view kSERVER_KEY_FILENAME = "server_key.pem"; + static constexpr std::string_view kCLIENT_CERT_FILENAME = "client_cert.pem"; + static constexpr std::string_view kCLIENT_KEY_FILENAME = "client_key.pem"; + static constexpr std::string_view kCERTS_DIR_PREFIX = "grpc_tls_test_"; TemporaryTLSCertificates() { auto tmpDir = std::filesystem::temp_directory_path(); auto uniqueDirName = - boost::filesystem::unique_path(std::string(kCertsDirPrefix) + "%%%%%%%%"); + boost::filesystem::unique_path(std::string(kCERTS_DIR_PREFIX) + "%%%%%%%%"); tempDir_ = tmpDir / uniqueDirName.string(); std::filesystem::create_directories(tempDir_); - writeFile(tempDir_ / kCaCertFilename, kCaCertContent); - writeFile(tempDir_ / kServerCertFilename, kServerCertContent); - writeFile(tempDir_ / kServerKeyFilename, kServerKeyContent); - writeFile(tempDir_ / kClientCertFilename, kClientCertContent); - writeFile(tempDir_ / kClientKeyFilename, kClientKeyContent); + writeFile(tempDir_ / kCA_CERT_FILENAME, kCA_CERT_CONTENT); + writeFile(tempDir_ / kSERVER_CERT_FILENAME, kSERVER_CERT_CONTENT); + writeFile(tempDir_ / kSERVER_KEY_FILENAME, kSERVER_KEY_CONTENT); + writeFile(tempDir_ / kCLIENT_CERT_FILENAME, kCLIENT_CERT_CONTENT); + writeFile(tempDir_ / kCLIENT_KEY_FILENAME, kCLIENT_KEY_CONTENT); } virtual ~TemporaryTLSCertificates() @@ -284,31 +284,31 @@ public: [[nodiscard]] std::filesystem::path getCACertPath() const { - return tempDir_ / kCaCertFilename; + return tempDir_ / kCA_CERT_FILENAME; } [[nodiscard]] std::filesystem::path getServerCertPath() const { - return tempDir_ / kServerCertFilename; + return tempDir_ / kSERVER_CERT_FILENAME; } [[nodiscard]] std::filesystem::path getServerKeyPath() const { - return tempDir_ / kServerKeyFilename; + return tempDir_ / kSERVER_KEY_FILENAME; } [[nodiscard]] std::filesystem::path getClientCertPath() const { - return tempDir_ / kClientCertFilename; + return tempDir_ / kCLIENT_CERT_FILENAME; } [[nodiscard]] std::filesystem::path getClientKeyPath() const { - return tempDir_ / kClientKeyFilename; + return tempDir_ / kCLIENT_KEY_FILENAME; } [[nodiscard]] std::filesystem::path @@ -409,7 +409,7 @@ public: // Test 2: TLS client with server CA should succeed grpc::SslCredentialsOptions sslOpts; - sslOpts.pem_root_certs = std::string(kCaCertContent); + sslOpts.pem_root_certs = std::string(kCA_CERT_CONTENT); auto tlsStub = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOpts))); BEAST_EXPECT(makeTestGRPCCall(tlsStub)); @@ -441,16 +441,16 @@ public: // Test 1: TLS client WITHOUT client certificate should FAIL (mTLS requires client cert) grpc::SslCredentialsOptions sslOptsNoClient; - sslOptsNoClient.pem_root_certs = std::string(kCaCertContent); + sslOptsNoClient.pem_root_certs = std::string(kCA_CERT_CONTENT); auto tlsStubNoClient = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOptsNoClient))); BEAST_EXPECT(!makeTestGRPCCall(tlsStubNoClient)); // Test 2: TLS client WITH client certificate should succeed grpc::SslCredentialsOptions sslOptsWithClient; - sslOptsWithClient.pem_root_certs = std::string(kCaCertContent); - sslOptsWithClient.pem_cert_chain = std::string(kClientCertContent); - sslOptsWithClient.pem_private_key = std::string(kClientKeyContent); + sslOptsWithClient.pem_root_certs = std::string(kCA_CERT_CONTENT); + sslOptsWithClient.pem_cert_chain = std::string(kCLIENT_CERT_CONTENT); + sslOptsWithClient.pem_private_key = std::string(kCLIENT_KEY_CONTENT); auto tlsStubWithClient = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOptsWithClient))); BEAST_EXPECT(makeTestGRPCCall(tlsStubWithClient)); @@ -665,7 +665,7 @@ public: // Test: TLS client should be able to connect (no client cert required) grpc::SslCredentialsOptions sslOpts; - sslOpts.pem_root_certs = std::string(kCaCertContent); + sslOpts.pem_root_certs = std::string(kCA_CERT_CONTENT); auto tlsStub = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOpts))); BEAST_EXPECT(makeTestGRPCCall(tlsStub)); @@ -819,16 +819,16 @@ public: // Test 1: TLS client WITHOUT client certificate should FAIL (mTLS requires client cert) grpc::SslCredentialsOptions sslOptsNoClient; - sslOptsNoClient.pem_root_certs = std::string(kCaCertContent); + sslOptsNoClient.pem_root_certs = std::string(kCA_CERT_CONTENT); auto tlsStubNoClient = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOptsNoClient))); BEAST_EXPECT(!makeTestGRPCCall(tlsStubNoClient)); // Test 2: TLS client WITH client certificate should succeed grpc::SslCredentialsOptions sslOptsWithClient; - sslOptsWithClient.pem_root_certs = std::string(kCaCertContent); - sslOptsWithClient.pem_cert_chain = std::string(kClientCertContent); - sslOptsWithClient.pem_private_key = std::string(kClientKeyContent); + sslOptsWithClient.pem_root_certs = std::string(kCA_CERT_CONTENT); + sslOptsWithClient.pem_cert_chain = std::string(kCLIENT_CERT_CONTENT); + sslOptsWithClient.pem_private_key = std::string(kCLIENT_KEY_CONTENT); auto tlsStubWithClient = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::SslCredentials(sslOptsWithClient))); BEAST_EXPECT(makeTestGRPCCall(tlsStubWithClient)); diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index ff848ee723..aa776f5166 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -51,7 +50,6 @@ #include #include #include -#include #include #include @@ -96,7 +94,7 @@ class Invariants_test : public beast::unit_test::Suite static FeatureBitset defaultAmendments() { - return xrpl::test::jtx::testableAmendments() | fixCleanup3_1_3 | fixCleanup3_2_0; + return xrpl::test::jtx::testableAmendments() | featureInvariantsV1_1 | fixSecurity3_1_3; } /** Run a specific test case to put the ledger into a state that will be @@ -178,13 +176,13 @@ class Invariants_test : public beast::unit_test::Suite using namespace test::jtx; OpenView ov{*env.current()}; - test::StreamSink sink{beast::Severity::Warning}; + test::StreamSink sink{beast::severities::KWarning}; beast::Journal const jlog{sink}; ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog}; // Invariants normally run in the Transaction's "apply" (operator()) context, and can always // access global Rules. - CurrentTransactionRulesGuard const rulesGuard(ov.rules()); + CurrentTransactionRulesGuard const rg(ov.rules()); BEAST_EXPECT(precheck(a1, a2, ac)); @@ -257,7 +255,7 @@ class Invariants_test : public beast::unit_test::Suite // 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::kZero; + sle->at(sfBalance) = beast::kZERO; ac.view().erase(sle); return true; }); @@ -286,8 +284,8 @@ class Invariants_test : public beast::unit_test::Suite // Clear the balance so the "account deletion left behind a // non-zero balance" check doesn't trip earlier than the desired // check. - sleA1->at(sfBalance) = beast::kZero; - sleA2->at(sfBalance) = beast::kZero; + sleA1->at(sfBalance) = beast::kZERO; + sleA2->at(sfBalance) = beast::kZERO; ac.view().erase(sleA1); ac.view().erase(sleA2); return true; @@ -311,7 +309,7 @@ class Invariants_test : public beast::unit_test::Suite auto const sleA1 = ac.view().peek(keylet::account(a1)); if (!sleA1) return false; - if (!BEAST_EXPECT(*sleA1->at(sfBalance) != beast::kZero)) + if (!BEAST_EXPECT(*sleA1->at(sfBalance) != beast::kZERO)) return false; ac.view().erase(sleA1); @@ -333,7 +331,7 @@ class Invariants_test : public beast::unit_test::Suite // Clear the balance so the "account deletion left behind a // non-zero balance" check doesn't trip earlier than the desired // check. - sleA1->at(sfBalance) = beast::kZero; + sleA1->at(sfBalance) = beast::kZERO; BEAST_EXPECT(sleA1->at(sfOwnerCount) == 0); adjustOwnerCount(ac.view(), sleA1, 1, ac.journal); @@ -344,7 +342,7 @@ class Invariants_test : public beast::unit_test::Suite XRPAmount{}, STTx{ttACCOUNT_DELETE, [](STObject& tx) {}}); - for (auto const& keyletInfo : kDirectAccountKeylets) + for (auto const& keyletInfo : kDIRECT_ACCOUNT_KEYLETS) { // TODO: Use structured binding once LLVM 16 is the minimum // supported version. See also: @@ -374,7 +372,7 @@ class Invariants_test : public beast::unit_test::Suite // Clear the balance so the "account deletion left behind a // non-zero balance" check doesn't trip earlier than the // desired check. - sleA1->at(sfBalance) = beast::kZero; + sleA1->at(sfBalance) = beast::kZERO; ac.view().erase(sleA1); return true; @@ -394,7 +392,7 @@ class Invariants_test : public beast::unit_test::Suite // 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::kZero; + sle->at(sfBalance) = beast::kZERO; sle->at(sfOwnerCount) = 0; ac.view().erase(sle); return true; @@ -429,7 +427,7 @@ class Invariants_test : public beast::unit_test::Suite // 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::kZero; + sle->at(sfBalance) = beast::kZERO; sle->at(sfOwnerCount) = 0; ac.view().erase(sle); @@ -493,7 +491,7 @@ class Invariants_test : public beast::unit_test::Suite // 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::kZero; + sle->at(sfBalance) = beast::kZERO; sle->at(sfOwnerCount) = 0; ac.view().erase(sle); @@ -765,7 +763,7 @@ class Invariants_test : public beast::unit_test::Suite return false; // Use `drops(1)` to bypass a call to STAmount::canonicalize // with an invalid value - sle->setFieldAmount(sfBalance, kInitialXrp + drops(1)); + sle->setFieldAmount(sfBalance, kINITIAL_XRP + drops(1)); BEAST_EXPECT(!sle->getFieldAmount(sfBalance).negative()); ac.view().update(sle); return true; @@ -799,10 +797,10 @@ class Invariants_test : public beast::unit_test::Suite XRPAmount{-1}); doInvariantCheck( - {{"fee paid exceeds system limit: "s + to_string(kInitialXrp)}, - {"XRP net change of 0 doesn't match fee "s + to_string(kInitialXrp)}}, + {{"fee paid exceeds system limit: "s + to_string(kINITIAL_XRP)}, + {"XRP net change of 0 doesn't match fee "s + to_string(kINITIAL_XRP)}}, [](Account const&, Account const&, ApplyContext&) { return true; }, - XRPAmount{kInitialXrp}); + XRPAmount{kINITIAL_XRP}); doInvariantCheck( {{"fee paid is 20 exceeds fee specified in transaction."}, @@ -894,7 +892,7 @@ class Invariants_test : public beast::unit_test::Suite 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, kInitialXrp + drops(1)); + sleNew->setFieldAmount(sfAmount, kINITIAL_XRP + drops(1)); ac.view().insert(sleNew); return true; }); @@ -1277,7 +1275,7 @@ class Invariants_test : public beast::unit_test::Suite }); } - static SLE::pointer + static std::shared_ptr createPermissionedDomain( ApplyContext& ac, test::jtx::Account const& a1, @@ -1293,8 +1291,8 @@ class Invariants_test : public beast::unit_test::Suite if (numCreds != 0u) { - // This array is sorted naturally, but if you are going to change - // this behavior, don't forget to use credentials::makeSorted + // 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) { @@ -1316,11 +1314,11 @@ class Invariants_test : public beast::unit_test::Suite { using namespace test::jtx; - bool const fixEnabled = features[fixCleanup3_1_3]; + bool const fixPDEnabled = features[fixPermissionedDomainInvariant]; std::initializer_list const badTers = {tecINVARIANT_FAILED, tecINVARIANT_FAILED}; std::initializer_list const failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; - testcase << "PermissionedDomain" + std::string(fixEnabled ? " fix" : ""); + testcase << "PermissionedDomain" + std::string(fixPDEnabled ? " fix" : ""); doInvariantCheck( Env(*this, features), @@ -1330,20 +1328,20 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 2"; - static constexpr auto kTooBig = kMaxPermissionedDomainCredentialsArraySize + 1; + auto constexpr kTOO_BIG = kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE + 1; doInvariantCheck( Env(*this, features), - {{"permissioned domain bad credentials size " + std::to_string(kTooBig)}}, + {{"permissioned domain bad credentials size " + std::to_string(kTOO_BIG)}}, [](Account const& a1, Account const& a2, ApplyContext& ac) { - return !!createPermissionedDomain(ac, a1, a2, kTooBig); + return !!createPermissionedDomain(ac, a1, a2, kTOO_BIG); }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 3"; doInvariantCheck( @@ -1367,7 +1365,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 4"; doInvariantCheck( @@ -1390,7 +1388,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 1"; doInvariantCheck( @@ -1411,21 +1409,21 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 2"; doInvariantCheck( Env(*this, features), - {{"permissioned domain bad credentials size " + std::to_string(kTooBig)}}, + {{"permissioned domain bad credentials size " + std::to_string(kTOO_BIG)}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { // create PD auto slePd = createPermissionedDomain(ac, a1, a2); // update PD { - STArray credentials(sfAcceptedCredentials, kTooBig); + STArray credentials(sfAcceptedCredentials, kTOO_BIG); - for (std::size_t n = 0; n < kTooBig; ++n) + for (std::size_t n = 0; n < kTOO_BIG; ++n) { auto cred = STObject::makeInnerObject(sfCredential); cred.setAccountID(sfIssuer, a2); @@ -1442,7 +1440,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 3"; doInvariantCheck( @@ -1472,7 +1470,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 4"; doInvariantCheck( @@ -1500,7 +1498,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : badTers); + fixPDEnabled ? failTers : badTers); std::initializer_list const goodTers = {tesSUCCESS, tesSUCCESS}; @@ -1518,7 +1516,7 @@ class Invariants_test : public beast::unit_test::Suite testcase << "PermissionedDomain set 2 domains "; doInvariantCheck( Env(*this, features), - fixEnabled ? badMoreThan1 : emptyV, + fixPDEnabled ? badMoreThan1 : emptyV, [](Account const& a1, Account const& a2, ApplyContext& ac) { createPermissionedDomain(ac, a1, a2); createPermissionedDomain(ac, a1, a2, 2, 11); @@ -1526,7 +1524,7 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : goodTers); + fixPDEnabled ? failTers : goodTers); } { @@ -1547,7 +1545,7 @@ class Invariants_test : public beast::unit_test::Suite std::move(env1), a1, a2, - fixEnabled ? badMoreThan1 : emptyV, + 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}); @@ -1557,18 +1555,18 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, - fixEnabled ? failTers : goodTers); + fixPDEnabled ? failTers : goodTers); } { testcase << "PermissionedDomain set 0 domains "; doInvariantCheck( Env(*this, features), - fixEnabled ? badNoDomains : emptyV, + fixPDEnabled ? badNoDomains : emptyV, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? badTers : goodTers); + fixPDEnabled ? badTers : goodTers); } { @@ -1589,11 +1587,11 @@ class Invariants_test : public beast::unit_test::Suite Env(*this, features), a1, a2, - fixEnabled ? badNoDomains : emptyV, + fixPDEnabled ? badNoDomains : emptyV, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, - fixEnabled ? badTers : goodTers); + fixPDEnabled ? badTers : goodTers); } { @@ -1613,7 +1611,7 @@ class Invariants_test : public beast::unit_test::Suite std::move(env1), a1, a2, - fixEnabled ? badDeleted : emptyV, + fixPDEnabled ? badDeleted : emptyV, [&pd1](Account const&, Account const&, ApplyContext& ac) { auto sle1 = ac.view().peek({ltPERMISSIONED_DOMAIN, pd1}); ac.view().erase(sle1); @@ -1621,28 +1619,28 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - fixEnabled ? failTers : goodTers); + fixPDEnabled ? failTers : goodTers); } { testcase << "PermissionedDomain del, create domain "; doInvariantCheck( Env(*this, features), - fixEnabled ? badNotDeleted : emptyV, + fixPDEnabled ? badNotDeleted : emptyV, [](Account const& a1, Account const& a2, ApplyContext& ac) { createPermissionedDomain(ac, a1, a2); return true; }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, - fixEnabled ? failTers : goodTers); + fixPDEnabled ? failTers : goodTers); } { testcase << "PermissionedDomain invalid tx"; doInvariantCheck( - fixEnabled ? badTx : emptyV, + fixPDEnabled ? badTx : emptyV, [&](Account const& a1, Account const& a2, ApplyContext& ac) { createPermissionedDomain(ac, a1, a2); return true; @@ -1785,7 +1783,7 @@ class Invariants_test : public beast::unit_test::Suite for (std::size_t n = 0; n < numCreds; ++n) { auto credType = "cred_type" + std::to_string(n); - credentials.push_back({.issuer = a2, .credType = credType}); + credentials.push_back({a2, credType}); } std::uint32_t const seq = env.seq(a1); @@ -1802,9 +1800,11 @@ class Invariants_test : public beast::unit_test::Suite { using namespace test::jtx; - bool const fixEnabled = features[fixCleanup3_1_3]; + bool const fixPDEnabled = features[fixPermissionedDomainInvariant]; + bool const fixS313Enabled = features[fixSecurity3_1_3]; - testcase << "PermissionedDEX" + std::string(fixEnabled ? " fix" : ""); + testcase << "PermissionedDEX" + std::string(fixPDEnabled ? " fixPD" : "") + + std::string(fixS313Enabled ? " fixS313" : ""); doInvariantCheck( Env(*this, features), @@ -1908,8 +1908,8 @@ class Invariants_test : public beast::unit_test::Suite std::move(env1), a1, a2, - fixEnabled ? std::vector{{"hybrid offer is malformed"}} - : std::vector{}, + fixS313Enabled ? std::vector{{"hybrid offer is malformed"}} + : std::vector{}, [&pd1](Account const& a1, Account const& a2, ApplyContext& ac) { Keylet const offerKey = keylet::offer(a2.id(), 10); auto sleOffer = std::make_shared(offerKey); @@ -1926,8 +1926,9 @@ class Invariants_test : public beast::unit_test::Suite }, XRPAmount{}, STTx{ttOFFER_CREATE, [&](STObject&) {}}, - fixEnabled ? std::initializer_list{tecINVARIANT_FAILED, tecINVARIANT_FAILED} - : std::initializer_list{tesSUCCESS, tesSUCCESS}); + fixS313Enabled + ? std::initializer_list{tecINVARIANT_FAILED, tecINVARIANT_FAILED} + : std::initializer_list{tesSUCCESS, tesSUCCESS}); } // hybrid offer missing sfAdditionalBooks @@ -2039,170 +2040,6 @@ class Invariants_test : public beast::unit_test::Suite } } - void - testBookDirectoryExchangeRate() - { - using namespace test::jtx; - testcase << "book directory exchange rate"; - - auto const getBookRootKey = [](Account const& account, std::uint64_t quality) { - Book const book{xrpIssue(), account["USD"], std::nullopt}; - return keylet::quality(keylet::kBook(book), quality); - }; - - // Root book-directory pages carry exchange-rate metadata that must - // match the quality encoded in the directory key. - auto const makeRootPage = [](Keylet const& dir, std::uint64_t exchangeRate) { - auto sleDir = std::make_shared(dir); - sleDir->setFieldH256(sfRootIndex, dir.key); - STVector256 indexes; - indexes.pushBack(uint256{1}); - sleDir->setFieldV256(sfIndexes, indexes); - sleDir->setFieldU64(sfExchangeRate, exchangeRate); - return sleDir; - }; - - // Child pages do not carry quality metadata; they only point back to - // the root directory. - auto const makeChildPage = [](Keylet const& rootDir) { - auto sleDir = std::make_shared(keylet::page(rootDir, 1)); - sleDir->setFieldH256(sfRootIndex, rootDir.key); - STVector256 indexes; - indexes.pushBack(uint256{2}); - sleDir->setFieldV256(sfIndexes, indexes); - return sleDir; - }; - - auto const makeOfferCreateTx = [] { - return STTx{ttOFFER_CREATE, [](STObject& tx) { - Account const account{"A1"}; - tx.setFieldAmount(sfTakerPays, XRP(1)); - tx.setFieldAmount(sfTakerGets, account["USD"](1)); - }}; - }; - std::initializer_list const failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; - - // Creating a root book directory with mismatched exchange-rate - // metadata violates the invariant. - doInvariantCheck( - {{"book directory exchange rate does not match directory quality"}}, - [&](Account const& a1, Account const&, ApplyContext& ac) { - auto const directoryQuality = STAmount::kURateOne; - auto const dir = getBookRootKey(a1, directoryQuality); - ac.view().insert(makeRootPage(dir, directoryQuality + 1)); - return true; - }, - XRPAmount{}, - makeOfferCreateTx(), - failTers); - - // A new child page must point to an existing root page. - doInvariantCheck( - {{"book directory root missing"}}, - [&](Account const& a1, Account const&, ApplyContext& ac) { - auto const directoryQuality = STAmount::kURateOne; - auto const rootDir = getBookRootKey(a1, directoryQuality); - // Insert only the child page. It points at rootDir, but the - // corresponding root page is intentionally missing. - ac.view().insert(makeChildPage(rootDir)); - return true; - }, - XRPAmount{}, - makeOfferCreateTx(), - failTers); - - // Legacy bad-root tolerance: - // - The view contains a pre-existing root page with bad sfExchangeRate - // metadata. - // - The simulated transaction only creates a child page pointing to - // that root. - // - The invariant must pass because this transaction did not create - // the bad root, only adding a child page. - { - Env env{*this, defaultAmendments()}; - Account const a1{"A1"}; - env.fund(XRP(1000), a1); - env.close(); - - OpenView view{*env.current()}; - auto const directoryQuality = STAmount::kURateOne; - auto const rootDir = getBookRootKey(a1, directoryQuality); - view.rawInsert(makeRootPage(rootDir, directoryQuality + 1)); - - ValidBookDirectory invariant; - invariant.visitEntry(false, nullptr, makeChildPage(rootDir)); - - test::StreamSink sink{beast::Severity::Warning}; - beast::Journal const jlog{sink}; - BEAST_EXPECT( - invariant.finalize(makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, jlog)); - } - - // A bad root is rejected when added, ignored when a legacy bad root is - // modified without changing sfRootIndex or deleted, and checked when a - // modified directory changes sfRootIndex. - { - Env env{*this, defaultAmendments()}; - Account const a1{"A1"}; - env.fund(XRP(1000), a1); - env.close(); - - OpenView view{*env.current()}; - auto const directoryQuality = STAmount::kURateOne; - auto const rootDir = getBookRootKey(a1, directoryQuality); - auto const missingRootDir = getBookRootKey(a1, directoryQuality + 1); - auto const badRoot = makeRootPage(rootDir, directoryQuality + 1); - view.rawInsert(badRoot); - - test::StreamSink sink{beast::Severity::Warning}; - beast::Journal const jlog{sink}; - - { - // add - ValidBookDirectory invariant; - invariant.visitEntry(false, nullptr, badRoot); - - BEAST_EXPECT( - !invariant.finalize(makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, jlog)); - } - { - // modify (without changing the sfRootIndex) - ValidBookDirectory invariant; - invariant.visitEntry(false, badRoot, badRoot); - - BEAST_EXPECT( - invariant.finalize(makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, jlog)); - } - { - // modify (changing sfRootIndex to a missing root) - auto const childBefore = makeChildPage(rootDir); - auto const childAfter = std::make_shared(*childBefore, childBefore->key()); - childAfter->setFieldH256(sfRootIndex, missingRootDir.key); - - ValidBookDirectory invariant; - invariant.visitEntry(false, childBefore, childAfter); - - test::StreamSink missingRootSink{beast::Severity::Warning}; - beast::Journal const missingRootJlog{missingRootSink}; - BEAST_EXPECT(!invariant.finalize( - makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, missingRootJlog)); - BEAST_EXPECT( - missingRootSink.messages().str().find("book directory root missing") != - std::string::npos); - } - { - // delete - view.rawErase(badRoot); - BEAST_EXPECT(!view.exists(rootDir)); - - ValidBookDirectory invariant; - invariant.visitEntry(true, badRoot, badRoot); - BEAST_EXPECT( - invariant.finalize(makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, jlog)); - } - } - } - Keylet createLoanBroker(jtx::Account const& a, jtx::Env& env, jtx::PrettyAsset const& asset) { @@ -2222,7 +2059,7 @@ class Invariants_test : public beast::unit_test::Suite auto const loanBrokerKeylet = keylet::loanbroker(a.id(), env.seq(a)); // Create a Loan Broker with all default values. - env(set(a, vaultID), Fee(kIncrement)); + env(set(a, vaultID), Fee(kINCREMENT)); return loanBrokerKeylet; }; @@ -2326,7 +2163,7 @@ class Invariants_test : public beast::unit_test::Suite return iouAsset; } case Asset::MPT: { - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = alice}); @@ -2550,7 +2387,7 @@ class Invariants_test : public beast::unit_test::Suite } // Test: cover available greater than pseudo-account asset balance - // (requires fixCleanup3_1_3) + // (requires fixSecurity3_1_3) doInvariantCheck( {{"Loan Broker cover available is greater than pseudo-account asset balance"}}, [&](Account const&, Account const&, ApplyContext& ac) { @@ -2593,7 +2430,7 @@ class Invariants_test : public beast::unit_test::Suite std::optional accountShares = std::nullopt; // NOLINTEND(readability-redundant-member-init) }; - constexpr auto kAdjust = [&](ApplyView& ac, xrpl::Keylet keylet, Adjustments args) { + auto constexpr kADJUST = [&](ApplyView& ac, xrpl::Keylet keylet, Adjustments args) { auto sleVault = ac.peek(keylet); if (!sleVault) return false; @@ -2692,7 +2529,7 @@ class Invariants_test : public beast::unit_test::Suite return true; }; - static constexpr auto kArgs = [](AccountID id, int adjustment, auto fn) -> Adjustments { + constexpr auto kARGS = [](AccountID id, int adjustment, auto fn) -> Adjustments { Adjustments sample = { .assetsTotal = adjustment, .assetsAvailable = adjustment, @@ -3081,9 +2918,9 @@ class Invariants_test : public beast::unit_test::Suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) { - sample.assetsAvailable = (kDropsPerXrp * -100).value(); - sample.assetsTotal = (kDropsPerXrp * -200).value(); + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) { + sample.assetsAvailable = (kDROPS_PER_XRP * -100).value(); + sample.assetsTotal = (kDROPS_PER_XRP * -200).value(); sample.sharesTotal = -1; })); }, @@ -3146,7 +2983,7 @@ class Invariants_test : public beast::unit_test::Suite "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 kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) { sample.lossUnrealized = 13; sample.assetsTotal = 20; })); @@ -3163,7 +3000,7 @@ class Invariants_test : public beast::unit_test::Suite "vault transaction must not change loss unrealized"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 100, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 100, [&](Adjustments& sample) { sample.lossUnrealized = 13; })); }, @@ -3178,7 +3015,7 @@ class Invariants_test : public beast::unit_test::Suite {"set assets outstanding must not exceed assets maximum"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); }, @@ -3192,7 +3029,7 @@ class Invariants_test : public beast::unit_test::Suite {"assets maximum must be positive"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = -1; })); }, @@ -3238,7 +3075,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleShares)[sfMaximumAmount] = 10; ac.view().update(sleShares); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [](Adjustments&) {})); + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [](Adjustments&) {})); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, @@ -3250,7 +3087,7 @@ 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()); - kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [](Adjustments&) {})); + kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [](Adjustments&) {})); auto sleVault = ac.view().peek(keylet); if (!sleVault) @@ -3258,7 +3095,7 @@ class Invariants_test : public beast::unit_test::Suite auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; - (*sleShares)[sfOutstandingAmount] = kMaxMpTokenAmount + 1; + (*sleShares)[sfOutstandingAmount] = kMAX_MP_TOKEN_AMOUNT + 1; ac.view().update(sleShares); return true; }, @@ -3475,7 +3312,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) = kVaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3535,7 +3372,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) = kVaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3564,7 +3401,7 @@ class Invariants_test : public beast::unit_test::Suite sleShares->at(sfFlags) = 0; // Setting wrong pseudo account ID - sleShares->at(sfIssuer) = AccountID(42); + sleShares->at(sfIssuer) = AccountID(uint160(42)); sleShares->at(sfOutstandingAmount) = 0; sleShares->at(sfSequence) = sequence; @@ -3576,7 +3413,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) = kVaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3591,7 +3428,7 @@ class Invariants_test : public beast::unit_test::Suite {"deposit must change vault balance"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); }, @@ -3604,7 +3441,7 @@ class Invariants_test : public beast::unit_test::Suite {"deposit assets outstanding must not exceed assets maximum"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 200, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 200, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); }, @@ -3631,7 +3468,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return kAdjust(ac.view(), keylet, kArgs(a3.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a3.id(), -10, [&](Adjustments& sample) { sample.accountAssets->amount = -100; })); }, @@ -3661,7 +3498,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] + 10; ac.view().update(sleA3); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.vaultAssets = -20; sample.accountAssets->amount = 10; })); @@ -3684,7 +3521,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] - 10; ac.view().update(sleA3); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.accountAssets->amount = 0; })); }, @@ -3698,7 +3535,7 @@ class Invariants_test : public beast::unit_test::Suite {"deposit must change depositor shares"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, @@ -3713,7 +3550,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 kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [](Adjustments& sample) { sample.sharesTotal = 0; })); }, @@ -3730,7 +3567,7 @@ 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 kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.accountShares->amount = -5; sample.sharesTotal = -10; })); @@ -3749,7 +3586,7 @@ class Invariants_test : public beast::unit_test::Suite ac.view().update(sleA3); auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.assetsTotal = 11; })); }, @@ -3770,7 +3607,7 @@ class Invariants_test : public beast::unit_test::Suite "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 kAdjust(ac.view(), keylet, kArgs(a2.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 10, [&](Adjustments& sample) { sample.assetsTotal = 7; sample.assetsAvailable = 7; })); @@ -3786,7 +3623,7 @@ class Invariants_test : public beast::unit_test::Suite {"withdrawal must change vault balance"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); }, @@ -3811,7 +3648,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return kAdjust(ac.view(), keylet, kArgs(a3.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a3.id(), -10, [&](Adjustments& sample) { sample.accountAssets->amount = -100; })); }, @@ -3845,7 +3682,7 @@ class Invariants_test : public beast::unit_test::Suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] + 10; ac.view().update(sleA3); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.vaultAssets = 10; sample.accountAssets->amount = -20; })); @@ -3860,7 +3697,7 @@ class Invariants_test : public beast::unit_test::Suite {"withdrawal must change one destination balance"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - if (!kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + if (!kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { *sample.vaultAssets -= 5; }))) return false; @@ -3881,7 +3718,7 @@ class Invariants_test : public beast::unit_test::Suite {"withdrawal must change depositor shares"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, @@ -3895,7 +3732,7 @@ class Invariants_test : public beast::unit_test::Suite {"withdrawal must change vault shares"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [](Adjustments& sample) { sample.sharesTotal = 0; })); }, @@ -3911,7 +3748,7 @@ 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 kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.accountShares->amount = 5; sample.sharesTotal = 10; })); @@ -3927,7 +3764,7 @@ class Invariants_test : public beast::unit_test::Suite "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 kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.assetsTotal = -15; sample.assetsAvailable = -15; })); @@ -3946,7 +3783,7 @@ class Invariants_test : public beast::unit_test::Suite ac.view().update(sleA3); auto const keylet = keylet::vault(a1.id(), ac.view().seq()); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.assetsTotal = -7; })); }, @@ -4014,7 +3851,7 @@ 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 kAdjust(ac.view(), keylet, kArgs(a2.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -10, [&](Adjustments& sample) { sample.accountShares->amount = 5; })); }, @@ -4029,7 +3866,7 @@ class Invariants_test : public beast::unit_test::Suite {"clawback must change vault balance"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq() - 2); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), -1, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a2.id(), -1, [&](Adjustments& sample) { sample.vaultAssets.reset(); })); }, @@ -4043,7 +3880,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 kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) {})); + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) {})); }, XRPAmount{}, STTx{ttVAULT_CLAWBACK, [](STObject&) {}}, @@ -4055,7 +3892,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() - 2); - return kAdjust(ac.view(), keylet, kArgs(a2.id(), 0, [&](Adjustments& sample) {})); + return kADJUST(ac.view(), keylet, kARGS(a2.id(), 0, [&](Adjustments& sample) {})); }, XRPAmount{}, STTx{ttVAULT_CLAWBACK, [&](STObject& tx) { tx[sfAccount] = a4.id(); }}, @@ -4068,7 +3905,7 @@ class Invariants_test : public beast::unit_test::Suite "clawback must change vault shares"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq() - 2); - return kAdjust(ac.view(), keylet, kArgs(a4.id(), 10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a4.id(), 10, [&](Adjustments& sample) { sample.sharesTotal = 0; })); }, @@ -4086,7 +3923,7 @@ class Invariants_test : public beast::unit_test::Suite {"clawback must change holder shares"}, [&](Account const& a1, Account const& a2, ApplyContext& ac) { auto const keylet = keylet::vault(a1.id(), ac.view().seq() - 2); - return kAdjust(ac.view(), keylet, kArgs(a4.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a4.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, @@ -4106,7 +3943,7 @@ 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 kAdjust(ac.view(), keylet, kArgs(a4.id(), -10, [&](Adjustments& sample) { + return kADJUST(ac.view(), keylet, kARGS(a4.id(), -10, [&](Adjustments& sample) { sample.accountShares->amount = -8; sample.assetsTotal = -7; sample.assetsAvailable = -7; @@ -4129,63 +3966,6 @@ class Invariants_test : public beast::unit_test::Suite using namespace test::jtx; testcase << "MPT"; - MPTIssue const nonCanonicalMPTIssue{makeMptID(1, AccountID(0x4985601))}; - auto const nonCanonicalMPTAmount = [&](SField const& field) { - return STAmount{ - field, - nonCanonicalMPTIssue, - kMaxMpTokenAmount + std::uint64_t{1}, - 0, - false, - STAmount::Unchecked{}}; - }; - auto const negativeMPTAmount = [&](SField const& field) { - return STAmount{field, nonCanonicalMPTIssue, 2, 0, true, STAmount::Unchecked{}}; - }; - auto const nonCanonicalMPTPayment = [&]() { - return STTx{ttPAYMENT, [&](STObject& tx) { - tx.setFieldAmount(sfAmount, nonCanonicalMPTAmount(sfAmount)); - }}; - }; - - doInvariantCheck( - Env{*this, defaultAmendments() - fixCleanup3_2_0}, - {}, - [](Account const&, Account const&, ApplyContext&) { return true; }, - XRPAmount{}, - nonCanonicalMPTPayment(), - {tesSUCCESS, tesSUCCESS}); - - doInvariantCheck( - {{"ledger entry contains non-canonical MPT or XRP amount"}}, - [&](Account const& a1, Account const& a2, ApplyContext& ac) { - auto const sle = ac.view().peek(keylet::account(a1.id())); - if (!sle) - return false; - - auto sleNew = std::make_shared(keylet::check(a1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, a1.id()); - sleNew->setAccountID(sfDestination, a2.id()); - sleNew->setFieldAmount(sfSendMax, nonCanonicalMPTAmount(sfSendMax)); - ac.view().insert(sleNew); - return true; - }); - - doInvariantCheck( - {{"ledger entry contains non-canonical MPT or XRP amount"}}, - [&](Account const& a1, Account const& a2, ApplyContext& ac) { - auto const sle = ac.view().peek(keylet::account(a1.id())); - if (!sle) - return false; - - auto sleNew = std::make_shared(keylet::check(a1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, a1.id()); - sleNew->setAccountID(sfDestination, a2.id()); - sleNew->setFieldAmount(sfSendMax, negativeMPTAmount(sfSendMax)); - ac.view().insert(sleNew); - return true; - }); - // MPT OutstandingAmount > MaximumAmount doInvariantCheck( {{"OutstandingAmount overflow"}}, @@ -4326,297 +4106,6 @@ class Invariants_test : public beast::unit_test::Suite return true; }); } - - // sfReferenceHolding can only be set on creation by VaultCreate. A - // non-VaultCreate transaction that creates an MPTokenIssuance with - // sfReferenceHolding present must trip the invariant. - doInvariantCheck( - {{"sfReferenceHolding set on a new MPTokenIssuance by a " - "non-VaultCreate transaction"}}, - [](Account const& a1, Account const&, ApplyContext& ac) { - auto const sleAcct = ac.view().peek(keylet::account(a1.id())); - if (!sleAcct) - return false; - MPTIssue const mpt{makeMptID(sleAcct->getFieldU32(sfSequence), a1)}; - auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); - sleNew->setFieldH256(sfReferenceHolding, uint256{1}); - ac.view().insert(sleNew); - return true; - }, - XRPAmount{}, - STTx{ttACCOUNT_SET, [](STObject&) {}}); - - // sfReferenceHolding is immutable: changing the field on an - // existing MPTokenIssuance must trip the invariant. Set up a real - // vault via preclose (so the share issuance carries - // sfReferenceHolding), then mutate it in precheck to produce a - // before/after pair. - { - uint256 vaultKey; - doInvariantCheck( - {{"sfReferenceHolding was modified on an existing " - "MPTokenIssuance"}}, - [&](Account const&, Account const&, ApplyContext& ac) { - auto const sleVault = ac.view().peek(keylet::vault(vaultKey)); - if (!sleVault) - return false; - auto sleIssuance = - ac.view().peek(keylet::mptIssuance(sleVault->at(sfShareMPTID))); - if (!sleIssuance) - return false; - sleIssuance->setFieldH256(sfReferenceHolding, uint256{2}); - ac.view().update(sleIssuance); - return true; - }, - XRPAmount{}, - STTx{ttACCOUNT_SET, [](STObject&) {}}, - {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, - [&](Account const& a1, Account const&, Env& env) { - Account const issuer{"issuer"}; - env.fund(XRP(10'000), issuer); - env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = a1}); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = a1, .asset = asset}); - env(tx); - env.close(); - vaultKey = keylet.key; - return true; - }); - } - - // A vault pseudo-account's MPToken cannot be deleted by anything - // other than a VaultDelete transaction. Set up a vault, then have - // an arbitrary tx erase the pseudo's MPToken in precheck. - { - uint256 vaultKey; - doInvariantCheck( - {{"vault pseudo-account holding deleted by a " - "non-VaultDelete transaction"}}, - [&](Account const&, Account const&, ApplyContext& ac) { - auto const sleVault = ac.view().peek(keylet::vault(vaultKey)); - if (!sleVault) - return false; - auto const sleIssuance = - ac.view().peek(keylet::mptIssuance(sleVault->at(sfShareMPTID))); - if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) - return false; - auto sleHolding = ac.view().peek( - keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); - if (!sleHolding) - return false; - ac.view().erase(sleHolding); - return true; - }, - XRPAmount{}, - STTx{ttACCOUNT_SET, [](STObject&) {}}, - {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, - [&](Account const& a1, Account const&, Env& env) { - Account const issuer{"issuer"}; - env.fund(XRP(10'000), issuer); - env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = a1}); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = a1, .asset = asset}); - env(tx); - env.close(); - vaultKey = keylet.key; - return true; - }); - } - - // Invalid transfer - std::array, 3> const invalidTransferTests = { - std::make_pair(ttAMM_WITHDRAW, false), - std::make_pair(ttPAYMENT, false), - std::make_pair(ttPAYMENT, true)}; - for (auto const enabled : {true, false}) - { - for (auto const& [tx, crossCurrencyPayment] : invalidTransferTests) - { - for (auto const flag : - {static_cast(lsfMPTLocked), - ~lsfMPTCanTransfer, - ~lsfMPTCanTrade, - 0u}) - { - MPTID id{}; - auto const isSuccess = !enabled || flag == 0 || - (tx == ttPAYMENT && !crossCurrencyPayment && (flag == ~lsfMPTCanTrade)) || - (tx == ttAMM_WITHDRAW && - (flag == ~lsfMPTCanTrade || flag == ~lsfMPTCanTransfer)); - std::pair const error = isSuccess - ? std::make_pair(TER(tesSUCCESS), TER(tesSUCCESS)) - : std::make_pair(TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)); - doInvariantCheck( - {{isSuccess ? "" : "invalid MPToken transfer between holders"}}, - [&](Account const& a1, Account const& a2, ApplyContext& ac) { - auto update = [&](AccountID const& a, std::uint64_t v) { - auto sle = ac.view().peek(keylet::mptoken(id, a)); - if (!sle) - return false; - sle->at(sfMPTAmount) = v; - ac.view().update(sle); - return true; - }; - auto issuanceSle = ac.view().peek(keylet::mptIssuance(id)); - if (!issuanceSle) - return false; - auto const flags = issuanceSle->at(sfFlags); - if (flag == lsfMPTLocked) - { - issuanceSle->at(sfFlags) = flags | lsfMPTLocked; - } - else if (flag != 0u) - { - issuanceSle->at(sfFlags) = flags & flag; - } - issuanceSle->at(sfOutstandingAmount) = 200; - ac.view().update(issuanceSle); - return update(a1, 101) && update(a2, 99); - }, - XRPAmount{}, - STTx{ - tx, - [&](STObject& tx) { - if (crossCurrencyPayment) - { - tx.setFieldAmount( - sfSendMax, STAmount(MPTAmount{100}, MPTIssue{id})); - } - }}, - {error.first, error.second}, - [&](Account const& a1, Account const& a2, Env& env) { - Account const gw("gw"); - env.fund(XRP(1'000), gw); - MPTTester const usd( - {.env = env, .issuer = gw, .holders = {a1, a2}, .pay = 100}); - id = usd.issuanceID(); - if (!enabled) - { - env.disableFeature(featureMPTokensV2); - } - return true; - }); - } - } - } - } - - void - testAMM() - { - testcase << "AMM"; - using namespace jtx; - - MPTID mptID{}; - uint256 ammID{}; - AccountID ammAccountID{}; - Account const gw{"gw"}; - Issue lptIssue{}; - PrettyAsset poolAsset{xrpIssue()}; - - auto deleteAMMAccount = [&](ApplyContext& ac, bool) { - auto sle = ac.view().peek(keylet::account(ammAccountID)); - if (!sle) - return false; - ac.view().erase(sle); - return true; - }; - - auto updateLPTokensBalance = [&](ApplyContext& ac, std::int64_t amount) { - auto sle = ac.view().peek(keylet::amm(ammID)); - if (!sle) - return false; - sle->setFieldAmount(sfLPTokenBalance, STAmount{lptIssue, amount}); - ac.view().update(sle); - return true; - }; - auto updateLPTokensBadAmount = [&](ApplyContext& ac, bool) { - return updateLPTokensBalance(ac, -1); - }; - auto updateLPTokensBadBalance = [&](ApplyContext& ac, bool) { - return updateLPTokensBalance(ac, 200'000'000); - }; - auto updateAMM = [&](ApplyContext& ac, bool) { return updateLPTokensBalance(ac, 10); }; - - auto updateAMMPool = [&](ApplyContext& ac, bool isMPT) { - if (isMPT) - { - auto sle = ac.view().peek(keylet::mptoken(mptID, ammAccountID)); - if (!sle) - return false; - sle->setFieldU64(sfMPTAmount, 1); - ac.view().update(sle); - return true; - } - auto sle = ac.view().peek(keylet::account(ammAccountID)); - if (!sle) - return false; - sle->setFieldAmount(sfBalance, XRP(1)); - ac.view().update(sle); - return true; - }; - - auto test = [&](auto const txType, - auto&& update, - bool isMPT, - TER error = tecINVARIANT_FAILED) { - doInvariantCheck( - {{"AMM"}}, - [&](Account const&, Account const&, ApplyContext& ac) { return update(ac, isMPT); }, - XRPAmount{}, - STTx{txType, [&](STObject& tx) {}}, - {tecINVARIANT_FAILED, error}, - [&](Account const&, Account const&, Env& env) { - env.fund(XRP(1'000), gw); - poolAsset = [&]() -> PrettyAsset { - if (isMPT) - { - MPT const mpt = MPTTester({.env = env, .issuer = gw}); - mptID = mpt.issuanceID; - return mpt; - } - return gw["USD"]; - }(); - AMM const amm(env, gw, XRP(100), poolAsset(100)); - ammAccountID = amm.ammAccount(); - ammID = amm.ammID(); - lptIssue = amm.lptIssue(); - return true; - }); - }; - - for (bool const isMPT : {false, true}) - { - auto const error = isMPT ? TER(tecINVARIANT_FAILED) : TER(tefINVARIANT_FAILED); - for (auto txType : {ttAMM_CREATE, ttAMM_DEPOSIT, ttAMM_CLAWBACK, ttAMM_WITHDRAW}) - { - test(txType, deleteAMMAccount, isMPT, tefINVARIANT_FAILED); - test(txType, updateLPTokensBadAmount, isMPT); - test(txType, updateLPTokensBadBalance, isMPT); - } - for (auto txType : {ttAMM_BID, ttAMM_VOTE}) - { - test(txType, updateAMMPool, isMPT, error); - test(txType, updateLPTokensBadAmount, isMPT); - test(txType, updateLPTokensBadBalance, isMPT); - } - for (auto txType : {ttAMM_DELETE, ttCHECK_CASH, ttOFFER_CREATE, ttPAYMENT}) - { - test(txType, updateAMM, isMPT); - } - } } // Test the invariant overwrite fix for both pre- and post-amendment @@ -4627,7 +4116,7 @@ class Invariants_test : public beast::unit_test::Suite testInvariantOverwrite(FeatureBitset features) { using namespace test::jtx; - bool const fixEnabled = features[fixCleanup3_1_3]; + bool const fixEnabled = features[fixSecurity3_1_3]; std::initializer_list const failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; std::initializer_list const passTers = {tesSUCCESS, tesSUCCESS}; @@ -4740,8 +4229,8 @@ class Invariants_test : public beast::unit_test::Suite MPTIssue const mpt{makeMptID(1, AccountID(0x4985601))}; auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); - // outstanding exceeds kMaxMpTokenAmount -> checkAmount sets bad_ - sleNew->setFieldU64(sfOutstandingAmount, kMaxMpTokenAmount + 1); + // outstanding exceeds kMAX_MP_TOKEN_AMOUNT -> checkAmount sets bad_ + sleNew->setFieldU64(sfOutstandingAmount, kMAX_MP_TOKEN_AMOUNT + 1); // locked is valid and <= outstanding -> must NOT clear bad_ sleNew->setFieldU64(sfLockedAmount, 10); ac.view().insert(sleNew); @@ -4767,119 +4256,109 @@ class Invariants_test : public beast::unit_test::Suite std::vector values; }; - for (auto const mantissaScale : { - MantissaRange::MantissaScale::LargeLegacy, - MantissaRange::MantissaScale::Large, - }) + NumberMantissaScaleGuard const g{MantissaRange::MantissaScale::Large}; + + auto makeDelta = [&vaultAsset](Number const& n) -> ValidVault::DeltaInfo { + return {.delta = n, .scale = scale(n, vaultAsset.raw())}; + }; + + auto const testCases = std::vector{ + { + .name = "No values", + .expectedMinScale = 0, + .values = {}, + }, + { + .name = "Mixed integer and Number values", + .expectedMinScale = -15, + .values = {makeDelta(1), makeDelta(-1), makeDelta(Number{10, -1})}, + }, + { + .name = "Mixed scales", + .expectedMinScale = -17, + .values = + {makeDelta(Number{1, -2}), makeDelta(Number{5, -3}), makeDelta(Number{3, -2})}, + }, + { + .name = "Equal scales", + .expectedMinScale = -16, + .values = + {makeDelta(Number{1, -1}), makeDelta(Number{5, -1}), makeDelta(Number{1, -1})}, + }, + { + .name = "Mixed mantissa sizes", + .expectedMinScale = -12, + .values = + {makeDelta(Number{1}), + makeDelta(Number{1234, -3}), + makeDelta(Number{12345, -6}), + makeDelta(Number{123, 1})}, + }, + }; + + for (auto const& tc : testCases) { - NumberMantissaScaleGuard const g{mantissaScale}; + testcase("vault computeCoarsestScale: " + tc.name); - auto makeDelta = [&vaultAsset](Number const& n) -> ValidVault::DeltaInfo { - return {.delta = n, .scale = scale(n, vaultAsset.raw())}; - }; + auto const actualScale = ValidVault::computeCoarsestScale(tc.values); - auto const testCases = std::vector{ - { - .name = "No values", - .expectedMinScale = 0, - .values = {}, - }, - { - .name = "Mixed integer and Number values", - .expectedMinScale = -15, - .values = {makeDelta(1), makeDelta(-1), makeDelta(Number{10, -1})}, - }, - { - .name = "Mixed scales", - .expectedMinScale = -17, - .values = - {makeDelta(Number{1, -2}), - makeDelta(Number{5, -3}), - makeDelta(Number{3, -2})}, - }, - { - .name = "Equal scales", - .expectedMinScale = -16, - .values = - {makeDelta(Number{1, -1}), - makeDelta(Number{5, -1}), - makeDelta(Number{1, -1})}, - }, - { - .name = "Mixed mantissa sizes", - .expectedMinScale = -12, - .values = - {makeDelta(Number{1}), - makeDelta(Number{1234, -3}), - makeDelta(Number{12345, -6}), - makeDelta(Number{123, 1})}, - }, - }; - - for (auto const& tc : testCases) + BEAST_EXPECTS( + actualScale == tc.expectedMinScale, + "expected: " + std::to_string(tc.expectedMinScale) + + ", actual: " + std::to_string(actualScale)); + for (auto const& num : tc.values) { - testcase("vault computeCoarsestScale: " + tc.name); - - auto const actualScale = ValidVault::computeCoarsestScale(tc.values); - + // None of these scales are far enough apart that rounding the + // values would lose information, so check that the rounded + // value matches the original. + auto const actualRounded = roundToAsset(vaultAsset, num.delta, actualScale); BEAST_EXPECTS( - actualScale == tc.expectedMinScale, - "expected: " + std::to_string(tc.expectedMinScale) + - ", actual: " + std::to_string(actualScale)); - for (auto const& num : tc.values) - { - // None of these scales are far enough apart that rounding the - // values would lose information, so check that the rounded - // value matches the original. - auto const actualRounded = roundToAsset(vaultAsset, num.delta, actualScale); - BEAST_EXPECTS( - actualRounded == num.delta, - "number " + to_string(num.delta) + " rounded to scale " + - std::to_string(actualScale) + " is " + to_string(actualRounded)); - } + actualRounded == num.delta, + "number " + to_string(num.delta) + " rounded to scale " + + std::to_string(actualScale) + " is " + to_string(actualRounded)); } + } - auto const testCases2 = std::vector{ - { - .name = "False equivalence", - .expectedMinScale = -15, - .values = - { - makeDelta(Number{1234567890123456789, -18}), - makeDelta(Number{12345, -4}), - makeDelta(Number{1}), - }, - }, - }; - - // Unlike the first set of test cases, the values in these test could - // look equivalent if using the wrong scale. - for (auto const& tc : testCases2) + auto const testCases2 = std::vector{ { - testcase("vault computeCoarsestScale: " + tc.name); - - auto const actualScale = ValidVault::computeCoarsestScale(tc.values); - - BEAST_EXPECTS( - actualScale == tc.expectedMinScale, - "expected: " + std::to_string(tc.expectedMinScale) + - ", actual: " + std::to_string(actualScale)); - std::optional first; - Number firstRounded; - for (auto const& num : tc.values) - { - if (!first) + .name = "False equivalence", + .expectedMinScale = -15, + .values = { - first = num.delta; - firstRounded = roundToAsset(vaultAsset, num.delta, actualScale); - continue; - } - auto const numRounded = roundToAsset(vaultAsset, num.delta, actualScale); - BEAST_EXPECTS( - numRounded != firstRounded, - "at a scale of " + std::to_string(actualScale) + " " + - to_string(num.delta) + " == " + to_string(*first)); + makeDelta(Number{1234567890123456789, -18}), + makeDelta(Number{12345, -4}), + makeDelta(Number{1}), + }, + }, + }; + + // Unlike the first set of test cases, the values in these test could + // look equivalent if using the wrong scale. + for (auto const& tc : testCases2) + { + testcase("vault computeCoarsestScale: " + tc.name); + + auto const actualScale = ValidVault::computeCoarsestScale(tc.values); + + BEAST_EXPECTS( + actualScale == tc.expectedMinScale, + "expected: " + std::to_string(tc.expectedMinScale) + + ", actual: " + std::to_string(actualScale)); + std::optional first; + Number firstRounded; + for (auto const& num : tc.values) + { + if (!first) + { + first = num.delta; + firstRounded = roundToAsset(vaultAsset, num.delta, actualScale); + continue; } + auto const numRounded = roundToAsset(vaultAsset, num.delta, actualScale); + BEAST_EXPECTS( + numRounded != firstRounded, + "at a scale of " + std::to_string(actualScale) + " " + to_string(num.delta) + + " == " + to_string(*first)); } } } @@ -5129,11 +4608,14 @@ public: testNoZeroEscrow(); testValidNewAccountRoot(); testNFTokenPageInvariants(); - testPermissionedDomainInvariants(defaultAmendments() | fixCleanup3_1_3); - testPermissionedDomainInvariants(defaultAmendments() - fixCleanup3_1_3); - testPermissionedDEX(defaultAmendments() | fixCleanup3_1_3); - testPermissionedDEX(defaultAmendments() - fixCleanup3_1_3); - testBookDirectoryExchangeRate(); + testPermissionedDomainInvariants(defaultAmendments() | fixPermissionedDomainInvariant); + testPermissionedDomainInvariants(defaultAmendments() - fixPermissionedDomainInvariant); + testPermissionedDEX(defaultAmendments() | fixPermissionedDomainInvariant); + testPermissionedDEX(defaultAmendments() - fixPermissionedDomainInvariant); + testPermissionedDEX( + (defaultAmendments() | fixPermissionedDomainInvariant) - fixSecurity3_1_3); + testPermissionedDEX( + defaultAmendments() - fixPermissionedDomainInvariant - fixSecurity3_1_3); testNoModifiedUnmodifiableFields(); testValidPseudoAccounts(); testValidLoanBroker(); @@ -5141,9 +4623,8 @@ public: testConfidentialMPTTransfer(); testMPT(); testInvariantOverwrite(defaultAmendments()); - testInvariantOverwrite(defaultAmendments() - fixCleanup3_1_3); + testInvariantOverwrite(defaultAmendments() - fixSecurity3_1_3); testVaultComputeCoarsestScale(); - testAMM(); } }; diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index 3d0e546678..396ec8db2d 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -48,9 +48,9 @@ public: { assert(!stx); return std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); } diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index ee3bfe5192..3345f45aa6 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -40,9 +40,9 @@ class LedgerLoad_test : public beast::unit_test::Suite StartUpType type, std::optional trapTxHash) { - cfg->startLedger = ledger; - cfg->startUp = type; - cfg->trapTxHash = trapTxHash; + cfg->START_LEDGER = ledger; + cfg->START_UP = type; + cfg->TRAP_TX_HASH = trapTxHash; assert(!dbPath.empty()); cfg->legacy("database_path", dbPath); return cfg; @@ -127,7 +127,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, sd.ledgerFile, StartUpType::LoadFile, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT( sd.ledger[jss::ledger][jss::accountState].size() == @@ -147,7 +147,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, "", StartUpType::LoadFile, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); }); // file does not exist @@ -157,7 +157,7 @@ class LedgerLoad_test : public beast::unit_test::Suite envconfig( ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LoadFile, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); }); // make a corrupted version of the ledger file (last 10 bytes removed). @@ -183,7 +183,7 @@ class LedgerLoad_test : public beast::unit_test::Suite StartUpType::LoadFile, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); }); } @@ -200,7 +200,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Load, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() == 98); BEAST_EXPECT( @@ -221,7 +221,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() == 97); // in replace mode do not automatically accept the ledger being replayed @@ -247,7 +247,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, sd.trapTxHash), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() == 97); // in replace mode do not automatically accept the ledger being replayed @@ -277,7 +277,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, ~sd.trapTxHash), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); BEAST_EXPECT(false); } catch (std::runtime_error const&) @@ -301,7 +301,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, "latest", StartUpType::Load, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT( sd.ledger[jss::ledger][jss::accountState].size() == @@ -319,7 +319,7 @@ class LedgerLoad_test : public beast::unit_test::Suite *this, envconfig(ledgerConfig, sd.dbPath, "43", StartUpType::Load, std::nullopt), nullptr, - beast::Severity::Disabled); + beast::severities::KDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT( sd.ledger[jss::ledger][jss::accountState].size() == diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index 3cf9b3a9d9..ee14a93d07 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -27,9 +27,9 @@ class LedgerMaster_test : public beast::unit_test::Suite { using namespace jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->networkId = networkID; + cfg->NETWORK_ID = networkID; // This test relies on ledger hash so must lock it to fee 10. - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; }); } diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 1978d04fe1..a96fa2c499 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -291,8 +291,8 @@ public: [[nodiscard]] uint256 const& getClosedLedgerHash() const override { - static uint256 const kHash{}; - return kHash; + static uint256 const kHASH{}; + return kHASH; } [[nodiscard]] bool hasLedger(uint256 const& hash, std::uint32_t seq) const override @@ -445,8 +445,8 @@ struct TestPeerSet : public PeerSet [[nodiscard]] std::set const& getPeerIds() const override { - static std::set const kEmptyPeers; - return kEmptyPeers; + static std::set const kEMPTY_PEERS; + return kEMPTY_PEERS; } LedgerReplayMsgHandler& local; @@ -511,7 +511,7 @@ struct LedgerServer assert(param.initLedgers > 0); createAccounts(param.initAccounts); createLedgerHistory(); - app.getLogs().threshold(beast::Severity::Warning); + app.getLogs().threshold(beast::severities::KWarning); } /** @@ -561,9 +561,9 @@ struct LedgerServer accounts[toIdx], jtx::drops(ledgerMaster.getClosedLedger()->fees().base) + jtx::XRP(param.txAmount)), - jtx::Seq(jtx::kAutofill), - jtx::Fee(jtx::kAutofill), - jtx::Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + jtx::Fee(jtx::kAUTOFILL), + jtx::Sig(jtx::kAUTOFILL)); } env.close(); } @@ -611,7 +611,7 @@ public: PeerSetBehavior behavior = PeerSetBehavior::Good, InboundLedgersBehavior inboundBhvr = InboundLedgersBehavior::Good, PeerFeature peerFeature = PeerFeature::LedgerReplayEnabled) - : env(suite, jtx::envconfig(), nullptr, beast::Severity::Disabled) + : env(suite, jtx::envconfig(), nullptr, beast::severities::KDisabled) , app(env.app()) , ledgerMaster(env.app().getLedgerMaster()) , inboundLedgers(server.app.getLedgerMaster(), ledgerMaster, inboundBhvr) @@ -843,9 +843,12 @@ public: LedgerReplayer replayer; }; -using beast::Severity; +using namespace beast::severities; void -logAll(LedgerServer& server, LedgerReplayClient& client, beast::Severity level = Severity::Trace) +logAll( + LedgerServer& server, + LedgerReplayClient& client, + beast::severities::Severity level = Severity::KTrace) { server.app.getLogs().threshold(level); client.app.getLogs().threshold(level); @@ -1062,7 +1065,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite testcase("config test"); { Config const c; - BEAST_EXPECT(c.ledgerReplay == false); + BEAST_EXPECT(c.LEDGER_REPLAY == false); } { @@ -1072,7 +1075,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite 1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.ledgerReplay == true); + BEAST_EXPECT(c.LEDGER_REPLAY == true); } { @@ -1082,7 +1085,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite 0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.ledgerReplay == false); + BEAST_EXPECT(c.LEDGER_REPLAY == false); } } @@ -1095,16 +1098,17 @@ struct LedgerReplayer_test : public beast::unit_test::Suite http_request_type httpRequest; httpRequest.version(request.version()); httpRequest.base() = request.base(); - bool const serverResult = peerFeatureEnabled(httpRequest, kFeatureLedgerReplay, server); + bool const serverResult = + peerFeatureEnabled(httpRequest, kFEATURE_LEDGER_REPLAY, server); if (serverResult != expecting) return false; beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); jtx::Env serverEnv(*this); - serverEnv.app().config().ledgerReplay = server; + serverEnv.app().config().LEDGER_REPLAY = server; auto httpResp = xrpl::makeResponse( true, httpRequest, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); - auto const clientResult = peerFeatureEnabled(httpResp, kFeatureLedgerReplay, client); + auto const clientResult = peerFeatureEnabled(httpResp, kFEATURE_LEDGER_REPLAY, client); return clientResult == expecting; }; diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index ac8e0764fc..cbfd9da884 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -7,17 +7,9 @@ #include #include #include -#include -#include -#include -#include -#include -#include #include #include -#include -#include #include #include @@ -25,13 +17,63 @@ namespace xrpl::test { class LendingHelpers_test : public beast::unit_test::Suite { + void + testComputeRaisedRate() + { + using namespace jtx; + using namespace xrpl::detail; + struct TestCase + { + std::string name; + Number periodicRate; + std::uint32_t paymentsRemaining; + Number expectedRaisedRate; + }; + + auto const testCases = std::vector{ + { + .name = "Zero payments remaining", + .periodicRate = Number{5, -2}, + .paymentsRemaining = 0, + .expectedRaisedRate = Number{1}, // (1 + r)^0 = 1 + }, + { + .name = "One payment remaining", + .periodicRate = Number{5, -2}, + .paymentsRemaining = 1, + .expectedRaisedRate = Number{105, -2}, + }, // 1.05^1 + { + .name = "Multiple payments remaining", + .periodicRate = Number{5, -2}, + .paymentsRemaining = 3, + .expectedRaisedRate = Number{1157625, -6}, + }, // 1.05^3 + { + .name = "Zero periodic rate", + .periodicRate = Number{0}, + .paymentsRemaining = 5, + .expectedRaisedRate = Number{1}, // (1 + 0)^5 = 1 + }}; + + for (auto const& tc : testCases) + { + testcase("computeRaisedRate: " + tc.name); + + auto const computedRaisedRate = + computeRaisedRate(tc.periodicRate, tc.paymentsRemaining); + BEAST_EXPECTS( + computedRaisedRate == tc.expectedRaisedRate, + "Raised rate mismatch: expected " + to_string(tc.expectedRaisedRate) + ", got " + + to_string(computedRaisedRate)); + } + } + void testComputePaymentFactor() { using namespace jtx; using namespace xrpl::detail; - Env const env{*this}; - auto const& rules = env.current()->rules(); struct TestCase { std::string name; @@ -72,7 +114,7 @@ class LendingHelpers_test : public beast::unit_test::Suite testcase("computePaymentFactor: " + tc.name); auto const computedPaymentFactor = - computePaymentFactor(rules, tc.periodicRate, tc.paymentsRemaining); + computePaymentFactor(tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPaymentFactor == tc.expectedPaymentFactor, "Payment factor mismatch: expected " + to_string(tc.expectedPaymentFactor) + @@ -85,8 +127,6 @@ class LendingHelpers_test : public beast::unit_test::Suite { using namespace jtx; using namespace xrpl::detail; - Env const env{*this}; - auto const& rules = env.current()->rules(); struct TestCase { @@ -132,8 +172,8 @@ class LendingHelpers_test : public beast::unit_test::Suite { testcase("loanPeriodicPayment: " + tc.name); - auto const computedPeriodicPayment = loanPeriodicPayment( - rules, 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) + @@ -146,8 +186,6 @@ class LendingHelpers_test : public beast::unit_test::Suite { using namespace jtx; using namespace xrpl::detail; - Env const env{*this}; - auto const& rules = env.current()->rules(); struct TestCase { @@ -194,7 +232,7 @@ class LendingHelpers_test : public beast::unit_test::Suite testcase("loanPrincipalFromPeriodicPayment: " + tc.name); auto const computedPrincipalOutstanding = loanPrincipalFromPeriodicPayment( - rules, tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); + tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPrincipalOutstanding == tc.expectedPrincipalOutstanding, "Principal outstanding mismatch: expected " + @@ -203,296 +241,6 @@ class LendingHelpers_test : public beast::unit_test::Suite } } - void - testComputePowerMinusOne() - { - using namespace jtx; - using namespace xrpl::detail; - - // Edge cases. - { - testcase("computePowerMinusOne: zero rate returns zero"); - BEAST_EXPECT(computePowerMinusOne(0, 5) == 0); - } - { - testcase("computePowerMinusOne: zero paymentsRemaining returns zero"); - Number const fivePercent{5, -2}; - BEAST_EXPECT(computePowerMinusOne(fivePercent, 0) == 0); - } - // (1.05)^3 - 1 = 0.157625, computed independently by hand. - { - testcase("computePowerMinusOne: standard case (1.05)^3 - 1 = 0.157625"); - Number const r{5, -2}; - Number const expected{157625, -6}; - BEAST_EXPECT(computePowerMinusOne(r, 3) == expected); - } - // (1+1)^1 - 1 = 1. - { - testcase("computePowerMinusOne: r=1, n=1"); - BEAST_EXPECT(computePowerMinusOne(1, 1) == 1); - } - - // Property check at near-zero rate (the bug regime): for n=2 the - // mathematical identity is `(1+r)^2 - 1 = 2r + r^2`. We compute - // `2r + r^2` by direct multiplication in Number arithmetic — a - // path that doesn't share any code with the binomial loop — and - // assert the two paths agree. - { - testcase("computePowerMinusOne: near-zero rate matches independent 2r + r^2"); - // r = 1 TenthBips32 over 600s payment interval, computed - // independently below using xrpl::detail::loanPeriodicRate. - Number const r = loanPeriodicRate(TenthBips32{1}, 600); - Number const independentExpected = 2 * r + r * r; // (1+r)^2 - 1 - BEAST_EXPECT(computePowerMinusOne(r, 2) == independentExpected); - } - // Same property at n=3: (1+r)^3 - 1 = 3r + 3r^2 + r^3. - { - testcase("computePowerMinusOne: near-zero rate matches independent 3r + 3r^2 + r^3"); - Number const r = loanPeriodicRate(TenthBips32{1}, 600); - Number const independentExpected = 3 * r + 3 * r * r + r * r * r; - BEAST_EXPECT(computePowerMinusOne(r, 3) == independentExpected); - } - - // Larger-n stress test for the loop's early-termination logic. - // At very small r the binomial terms decrease by a factor of - // ~r*(n-k)/(k+1) per step, so even at n=1000 the loop should - // terminate in a small handful of iterations. Cross-check the - // result against the hybrid (which dispatches to this same - // binomial path when r*n < 1e-9). - { - testcase("computePowerMinusOne: large n, early termination matches hybrid output"); - // r*n = 1e-10 and 1e-12 — both clearly below the 1e-9 threshold. - Number const r1{1, -13}; - std::uint32_t const n1 = 1'000; - Number const r2{1, -15}; - std::uint32_t const n2 = 1'000; - BEAST_EXPECT(computePowerMinusOne(r1, n1) == computePowerMinusOneHybrid(r1, n1)); - BEAST_EXPECT(computePowerMinusOne(r2, n2) == computePowerMinusOneHybrid(r2, n2)); - BEAST_EXPECT(computePowerMinusOne(r1, n1) > 0); - BEAST_EXPECT(computePowerMinusOne(r2, n2) > 0); - } - } - - // Direct tests of `computePowerMinusOneHybrid`. Verifies the dispatcher - // picks the right branch and produces the right result on each side - // of the threshold. - void - testComputePowerMinusOneHybrid() - { - using namespace jtx; - using namespace xrpl::detail; - - // Above threshold (r * n >= 1e-9): hybrid must agree with the closed - // form `power(1+r, n) - 1` exactly (it is the closed form). - { - testcase("computePowerMinusOneHybrid: r*n >= 1e-9 uses closed form (bit-exact match)"); - - struct AboveThreshold - { - std::string name; - Number r; - std::uint32_t n; - }; - auto const cases = std::vector{ - {.name = "r=5%, n=3", .r = Number{5, -2}, .n = 3}, - {.name = "r=0.1%, n=1000", .r = Number{1, -3}, .n = 1'000}, - {.name = "r=1e-7, n=100 (above threshold by 10x)", .r = Number{1, -7}, .n = 100}, - }; - for (auto const& tc : cases) - { - Number const closed = power(1 + tc.r, tc.n) - 1; - Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n); - BEAST_EXPECTS( - hybrid == closed, - tc.name + ": closed=" + to_string(closed) + ", hybrid=" + to_string(hybrid)); - } - } - - // Below threshold (r * n < 1e-9): hybrid must agree with - // `computePowerMinusOne` (the binomial expansion). At this regime - // the closed form is provably wrong (cancellation); we verify the - // dispatcher routes to the binomial path. - { - testcase( - "computePowerMinusOneHybrid: r*n < 1e-9 uses binomial expansion (bit-exact match)"); - - struct BelowThreshold - { - std::string name; - Number r; - std::uint32_t n; - }; - auto const cases = std::vector{ - // bug regime: r = 1 TenthBips32 over 600s payment interval - // → r ≈ 1.9e-10, r*n ≈ 3.8e-10 < 1e-9. - {.name = "bug regime: r~1.9e-10, n=2", - .r = loanPeriodicRate(TenthBips32{1}, 600), - .n = 2}, - {.name = "r=1e-12, n=100", .r = Number{1, -12}, .n = 100}, - }; - for (auto const& tc : cases) - { - Number const binom = computePowerMinusOne(tc.r, tc.n); - Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n); - BEAST_EXPECTS( - hybrid == binom, - tc.name + ": binom=" + to_string(binom) + ", hybrid=" + to_string(hybrid)); - } - } - - // Edge cases. - { - testcase("computePowerMinusOneHybrid: edge cases"); - Number const fivePercent{5, -2}; - BEAST_EXPECT(computePowerMinusOneHybrid(0, 100) == 0); - BEAST_EXPECT(computePowerMinusOneHybrid(fivePercent, 0) == 0); - BEAST_EXPECT(computePowerMinusOneHybrid(0, 0) == 0); - } - - // Threshold boundary: r*n = 1e-9 exactly. Hybrid uses `>=` against - // the threshold, so this case must take the closed-form branch. - // We also verify that the binomial path agrees with the closed - // form to high precision at this crossover — confirming the - // threshold is placed where both paths give "adequate" answers. - { - testcase("computePowerMinusOneHybrid: threshold boundary r*n = 1e-9"); - - // Construct exactly r*n = 1e-9 with two distinct (r, n) pairs. - struct Boundary - { - std::string name; - Number r; - std::uint32_t n; - }; - auto const cases = std::vector{ - {.name = "r=1e-9, n=1", .r = Number{1, -9}, .n = 1}, - {.name = "r=1e-12, n=1000", .r = Number{1, -12}, .n = 1'000}, - }; - - for (auto const& tc : cases) - { - Number const closed = power(1 + tc.r, tc.n) - 1; - Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n); - Number const binom = computePowerMinusOne(tc.r, tc.n); - - // At exact threshold, hybrid must take closed-form path: - // bit-exact match with closed. - BEAST_EXPECTS( - hybrid == closed, - tc.name + ": hybrid should equal closed at threshold; got hybrid=" + - to_string(hybrid) + ", closed=" + to_string(closed)); - - // Closed-form and binomial must agree at the threshold to - // within Number's post-subtraction precision (~10 sig - // digits of `r*n = 1e-9`, i.e. ~1e-19 absolute error). - Number const tolerance{1, -18}; - Number const diff = abs(closed - binom); - BEAST_EXPECTS( - diff < tolerance, - tc.name + ": closed and binomial diverge at threshold by " + to_string(diff)); - } - } - } - - // Regression: at near-zero rate, `loanPrincipalFromPeriodicPayment` - // must satisfy `principal <= periodicPayment * paymentsRemaining` for - // any non-negative rate. The naive closed-form path violated this - // bound due to catastrophic cancellation in `(1+r)^n - 1`. - void - testLoanPrincipalFromPeriodicPaymentNearZeroRate() - { - testcase("loanPrincipalFromPeriodicPayment: principal <= payment*n at near-zero rate"); - using namespace jtx; - using namespace xrpl::detail; - Env const env{*this}; - auto const& rules = env.current()->rules(); - - // Inputs from the bug reproduction in Loan_test.cpp: - // InterestRate = 1 TenthBips32 (0.001 % per year), - // PaymentInterval = 600 s, principal = 100, 3 payments. - // periodicRate is ~1.9e-10. - auto const periodicRate = loanPeriodicRate(TenthBips32{1}, 600); - auto const periodicPayment = loanPeriodicPayment(rules, 100, periodicRate, 3); - - for (auto const n : {3u, 2u, 1u}) - { - auto const computed = - loanPrincipalFromPeriodicPayment(rules, periodicPayment, periodicRate, n); - auto const upperBound = periodicPayment * Number{n}; - BEAST_EXPECTS( - computed <= upperBound, - "n=" + std::to_string(n) + ": payment*n=" + to_string(upperBound) + - ", principal=" + to_string(computed)); - } - } - - // Regression: `computeTheoreticalLoanState` must produce a non-negative - // `interestDue` for any non-negative rate. Pre-fix, near-zero rates - // produced a negative `interestDue` because `(1+r)^n - 1` lost most of - // its precision to cancellation. - void - testComputeTheoreticalLoanStateNearZeroRate() - { - testcase("computeTheoreticalLoanState: non-negative interestDue at near-zero rate"); - using namespace jtx; - using namespace xrpl::detail; - Env const env{*this}; - auto const& rules = env.current()->rules(); - - auto const periodicRate = loanPeriodicRate(TenthBips32{1}, 600); - auto const periodicPayment = loanPeriodicPayment(rules, 100, periodicRate, 3); - - auto const state = - computeTheoreticalLoanState(rules, periodicPayment, periodicRate, 2, TenthBips32{0}); - - BEAST_EXPECT(state.principalOutstanding <= state.valueOutstanding); - BEAST_EXPECT(state.interestDue >= 0); - BEAST_EXPECT(state.managementFeeDue == 0); - } - - // Direct gating proof: at near-zero rate, `computePaymentFactor` must - // return different values with `fixCleanup3_2_0` disabled vs enabled. - // The enabled path agrees with an independent polynomial reference; - // the disabled path diverges by a measurable amount due to the - // catastrophic cancellation in `(1+r)^n - 1`. - void - testComputePaymentFactorNearZeroRate() - { - testcase("computePaymentFactor: near-zero rate, amendment disabled vs enabled"); - using namespace jtx; - using namespace xrpl::detail; - - Number const r = loanPeriodicRate(TenthBips32{1}, 600); - std::uint32_t const n = 3; - - // Independent reference: expand F(r,3) = r*(1+r)^3/((1+r)^3-1) - // algebraically for n=3, dividing numerator and denominator by r: - // F(r,3) = (1 + 3r + 3r^2 + r^3) / (3 + 3r + r^2) - // No power(), no binomial series — pure polynomial arithmetic in - // Number. - Number const reference = (1 + 3 * r + 3 * r * r + r * r * r) / (3 + 3 * r + r * r); - - // Pre-fix: closed form power(1+r, n) - 1 suffers catastrophic - // cancellation when r*n ~ 5.7e-10. - Env const envBug{*this, testableAmendments() - fixCleanup3_2_0}; - Number const buggyFactor = computePaymentFactor(envBug.current()->rules(), r, n); - - // Post-fix: hybrid binomial path avoids cancellation. - Env const envFix{*this}; - Number const correctFactor = computePaymentFactor(envFix.current()->rules(), r, n); - - // The amendment must change the computed factor in this regime. - BEAST_EXPECT(buggyFactor != correctFactor); - - // The fixed factor must agree with the polynomial reference to - // within a few ULPs of Number's 19-digit precision. - BEAST_EXPECT(abs(correctFactor - reference) < Number(1, -15)); - - // The buggy factor must diverge from the reference by a measurable - // amount — empirically ~1e-10 in this regime. - BEAST_EXPECT(abs(buggyFactor - reference) > Number(1, -12)); - } - void testComputeOverpaymentComponents() { @@ -514,9 +262,7 @@ class LendingHelpers_test : public beast::unit_test::Suite auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100 auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500 - Env const env{*this}; auto const components = xrpl::detail::computeOverpaymentComponents( - env.current()->rules(), iou, loanScale, overpayment, @@ -857,16 +603,9 @@ class LendingHelpers_test : public beast::unit_test::Suite Number const overpaymentAmount{50}; auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), - asset, - loanScale, - overpaymentAmount, - TenthBips32(0), - TenthBips32(0), - managementFeeRate); + asset, loanScale, overpaymentAmount, TenthBips32(0), TenthBips32(0), managementFeeRate); auto const loanProperties = computeLoanProperties( - env.current()->rules(), asset, loanPrincipal, loanInterestRate, @@ -876,7 +615,6 @@ class LendingHelpers_test : public beast::unit_test::Suite loanScale); auto const ret = tryOverpayment( - env.current()->rules(), asset, loanScale, overpaymentComponents, @@ -951,7 +689,6 @@ class LendingHelpers_test : public beast::unit_test::Suite auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), asset, loanScale, Number{50, 0}, @@ -960,7 +697,6 @@ class LendingHelpers_test : public beast::unit_test::Suite managementFeeRate); auto const loanProperties = computeLoanProperties( - env.current()->rules(), asset, loanPrincipal, loanInterestRate, @@ -970,7 +706,6 @@ class LendingHelpers_test : public beast::unit_test::Suite loanScale); auto const ret = tryOverpayment( - env.current()->rules(), asset, loanScale, overpaymentComponents, @@ -1047,7 +782,6 @@ class LendingHelpers_test : public beast::unit_test::Suite auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), asset, loanScale, Number{50, 0}, @@ -1056,7 +790,6 @@ class LendingHelpers_test : public beast::unit_test::Suite managementFeeRate); auto const loanProperties = computeLoanProperties( - env.current()->rules(), asset, loanPrincipal, loanInterestRate, @@ -1066,7 +799,6 @@ class LendingHelpers_test : public beast::unit_test::Suite loanScale); auto const ret = tryOverpayment( - env.current()->rules(), asset, loanScale, overpaymentComponents, @@ -1149,7 +881,6 @@ class LendingHelpers_test : public beast::unit_test::Suite auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), asset, loanScale, Number{50, 0}, @@ -1158,7 +889,6 @@ class LendingHelpers_test : public beast::unit_test::Suite managementFeeRate); auto const loanProperties = computeLoanProperties( - env.current()->rules(), asset, loanPrincipal, loanInterestRate, @@ -1168,7 +898,6 @@ class LendingHelpers_test : public beast::unit_test::Suite loanScale); auto const ret = tryOverpayment( - env.current()->rules(), asset, loanScale, overpaymentComponents, @@ -1259,7 +988,6 @@ class LendingHelpers_test : public beast::unit_test::Suite auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), asset, loanScale, Number{50, 0}, @@ -1268,7 +996,6 @@ class LendingHelpers_test : public beast::unit_test::Suite managementFeeRate); auto const loanProperties = computeLoanProperties( - env.current()->rules(), asset, loanPrincipal, loanInterestRate, @@ -1278,7 +1005,6 @@ class LendingHelpers_test : public beast::unit_test::Suite loanScale); auto const ret = tryOverpayment( - env.current()->rules(), asset, loanScale, overpaymentComponents, @@ -1357,6 +1083,7 @@ class LendingHelpers_test : public beast::unit_test::Suite using namespace jtx; using namespace xrpl::detail; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -1367,9 +1094,7 @@ class LendingHelpers_test : public beast::unit_test::Suite std::uint32_t const paymentsRemaining = 10; auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - Env const env{*this}; auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), asset, loanScale, Number{50, 0}, @@ -1377,178 +1102,88 @@ class LendingHelpers_test : public beast::unit_test::Suite TenthBips32(10'000), // 10% overpayment fee managementFeeRate); - struct Outcome - { - LoanPaymentParts parts; - LoanState oldState; - LoanState newState; - }; + auto const loanProperties = computeLoanProperties( + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); - // Run tryOverpayment under a given amendment set. At this (non-near-zero) - // rate computeLoanProperties is amendment-independent, so the loan state - // is identical across the amendment; only tryOverpayment's fixCleanup3_2_0 - // behaviour (the exact-principal pin and the management-fee re-derivation - // from that principal) differs. - auto run = [&](FeatureBitset features) -> std::optional { - Env const env{*this, features}; - auto const loanProperties = computeLoanProperties( - env.current()->rules(), - asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); - auto const ret = tryOverpayment( - env.current()->rules(), - asset, - loanScale, - overpaymentComponents, - loanProperties.loanState, - loanProperties.periodicPayment, - periodicRate, - paymentsRemaining, - managementFeeRate, - env.journal); - if (!BEAST_EXPECT(ret)) - return std::nullopt; - return Outcome{ - .parts = ret->first, - .oldState = loanProperties.loanState, - .newState = ret->second.loanState}; - }; + auto const ret = tryOverpayment( + asset, + loanScale, + overpaymentComponents, + loanProperties.loanState, + loanProperties.periodicPayment, + periodicRate, + paymentsRemaining, + managementFeeRate, + env.journal); - auto const fixedOpt = run(testableAmendments()); - auto const legacyOpt = run(testableAmendments() - fixCleanup3_2_0); - if (!fixedOpt || !legacyOpt) - { - BEAST_EXPECT(fixedOpt.has_value()); - BEAST_EXPECT(legacyOpt.has_value()); - return; - } - Outcome const& fixed = *fixedOpt; - Outcome const& legacy = *legacyOpt; + BEAST_EXPECT(ret); - // Components that the amendment does not change. The management fee is - // charged against the overpayment interest portion first, so interest - // paid stays 4.5 and fee paid 5.5; the principal repaid is 40 in both. - auto checkCommon = [&](Outcome const& o, char const* tag) { - BEAST_EXPECTS( - (o.parts.interestPaid == Number{45, -1}), - std::string(tag) + " interestPaid " + to_string(o.parts.interestPaid)); - BEAST_EXPECTS( - (o.parts.feePaid == Number{55, -1}), - std::string(tag) + " feePaid " + to_string(o.parts.feePaid)); - BEAST_EXPECTS( - o.parts.principalPaid == 40, - std::string(tag) + " principalPaid " + to_string(o.parts.principalPaid)); - BEAST_EXPECT( - o.parts.principalPaid == - o.oldState.principalOutstanding - o.newState.principalOutstanding); - // v = p + i + m identity: the non-interest part of valueChange equals - // the interest-due change. - BEAST_EXPECT( - o.parts.valueChange - o.parts.interestPaid == - o.newState.interestDue - o.oldState.interestDue); - }; - checkCommon(fixed, "fixed"); - checkCommon(legacy, "legacy"); + auto const& [actualPaymentParts, newLoanProperties] = *ret; + auto const& newState = newLoanProperties.loanState; - // With fixCleanup3_2_0 the management fee is re-derived from the exact - // principal; without it, from the one-scale-unit-high round-trip - // principal. So the management fee outstanding (and hence the value - // change, via v = p + i + m) differ by exactly one scale-unit (1e-5 at - // loanScale -5) between the two paths. - BEAST_EXPECT((fixed.parts.valueChange == Number{-164738, -5} + fixed.parts.interestPaid)); - BEAST_EXPECT( - (fixed.newState.managementFeeDue - fixed.oldState.managementFeeDue == - Number{-18303, -5})); - BEAST_EXPECT((legacy.parts.valueChange == Number{-164737, -5} + legacy.parts.interestPaid)); - BEAST_EXPECT( - (legacy.newState.managementFeeDue - legacy.oldState.managementFeeDue == - Number{-18304, -5})); + // =========== VALIDATE PAYMENT PARTS =========== + + // Since there is loan management fee, the fee is charged against + // 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)); + + // With overpayment interest portion, value change should equal the + // interest decrease plus overpayment interest portion + BEAST_EXPECTS( + (actualPaymentParts.valueChange == + Number{-164737, -5} + actualPaymentParts.interestPaid), + " valueChange mismatch: expected " + + to_string(Number{-164737, -5} + actualPaymentParts.interestPaid) + ", got " + + to_string(actualPaymentParts.valueChange)); + + // 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)); + + BEAST_EXPECTS( + actualPaymentParts.principalPaid == 40, + " principalPaid mismatch: expected 40, got `" + + to_string(actualPaymentParts.principalPaid)); + + // =========== VALIDATE STATE CHANGES =========== + + BEAST_EXPECTS( + actualPaymentParts.principalPaid == + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, + " principalPaid mismatch: expected " + + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); + + // Note that the management fee value change is not captured, as this + // value is not needed to correctly update the Vault state. + BEAST_EXPECTS( + (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == + Number{-18304, -5}), + " management fee change mismatch: expected " + to_string(Number{-18304, -5}) + + ", got " + + to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue)); + + BEAST_EXPECTS( + actualPaymentParts.valueChange - actualPaymentParts.interestPaid == + newState.interestDue - loanProperties.loanState.interestDue, + " valueChange mismatch: expected " + + to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " + + to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid)); } public: - void - testCanApplyToBrokerCover() - { - using namespace jtx; - - Account const issuer{"issuer"}; - PrettyAsset const iou = issuer["IOU"]; - - // sfCoverAvailable = Number{10} on an IOU → STAmount exponent = -14, - // so coverScale = -14. The ULP boundary is 5e-15; anything below - // that rounds to zero at cover scale. Number{1,-16} = 1e-16 is our - // representative sub-ULP probe. - struct TestCase - { - std::string name; - Number coverAvailable; - STAmount amount; - TER expected; - }; - - auto const testCases = std::vector{ - { - .name = "Zero amount", - .coverAvailable = Number{10}, - .amount = STAmount{iou, Number{0}}, - .expected = tecPRECISION_LOSS, - }, - { - .name = "Rounds to zero at cover scale", - .coverAvailable = Number{10}, - .amount = STAmount{iou, Number{1, -16}}, - .expected = tecPRECISION_LOSS, - }, - { - .name = "Zero coverAvailable, whole-unit amount", - // coverScale = 0 (zero STAmount exponent); 1 IOU is not - // zero at integer scale → tesSUCCESS. - .coverAvailable = Number{0}, - .amount = STAmount{iou, Number{1}}, - .expected = tesSUCCESS, - }, - { - .name = "Supra-ULP amount", - .coverAvailable = Number{10}, - .amount = STAmount{iou, Number{1, -13}}, - .expected = tesSUCCESS, - }, - }; - - Env const env{*this}; - - for (auto const& tc : testCases) - { - testcase("canApplyToBrokerCover: " + tc.name); - auto sle = std::make_shared(ltLOAN_BROKER, uint256{1u}); - sle->at(sfCoverAvailable) = tc.coverAvailable; - BEAST_EXPECT( - canApplyToBrokerCover(*env.current(), sle, iou, tc.amount, env.journal, "test") == - tc.expected); - } - - // Amendment off → guard is bypassed regardless of amount. - { - testcase("canApplyToBrokerCover: amendment disabled"); - Env const envOff{*this, testableAmendments() - fixCleanup3_2_0}; - auto sle = std::make_shared(ltLOAN_BROKER, uint256{1u}); - sle->at(sfCoverAvailable) = Number{10}; - BEAST_EXPECT( - canApplyToBrokerCover( - *envOff.current(), - sle, - iou, - STAmount{iou, Number{0}}, - envOff.journal, - "test") == tesSUCCESS); - } - } - void run() override { @@ -1564,15 +1199,10 @@ public: testLoanLatePaymentInterest(); testLoanPeriodicPayment(); testLoanPrincipalFromPeriodicPayment(); - testLoanPrincipalFromPeriodicPaymentNearZeroRate(); + testComputeRaisedRate(); testComputePaymentFactor(); - testComputePowerMinusOne(); - testComputePowerMinusOneHybrid(); - testComputeTheoreticalLoanStateNearZeroRate(); - testComputePaymentFactorNearZeroRate(); testComputeOverpaymentComponents(); testComputeInterestAndFeeParts(); - testCanApplyToBrokerCover(); } }; diff --git a/src/test/app/LoadFeeTrack_test.cpp b/src/test/app/LoadFeeTrack_test.cpp index aba0b35062..1122ac4ad6 100644 --- a/src/test/app/LoadFeeTrack_test.cpp +++ b/src/test/app/LoadFeeTrack_test.cpp @@ -17,9 +17,9 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.fees.referenceFee; - f.reserve = 200 * kDropsPerXrp; - f.increment = 50 * kDropsPerXrp; + f.base = d.FEES.reference_fee; + f.reserve = 200 * kDROPS_PER_XRP; + f.increment = 50 * kDROPS_PER_XRP; return f; }(); @@ -30,9 +30,9 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.fees.referenceFee * 10; - f.reserve = 200 * kDropsPerXrp; - f.increment = 50 * kDropsPerXrp; + f.base = d.FEES.reference_fee * 10; + f.reserve = 200 * kDROPS_PER_XRP; + f.increment = 50 * kDROPS_PER_XRP; return f; }(); @@ -43,9 +43,9 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.fees.referenceFee; - f.reserve = 200 * kDropsPerXrp; - f.increment = 50 * kDropsPerXrp; + f.base = d.FEES.reference_fee; + f.reserve = 200 * kDROPS_PER_XRP; + f.increment = 50 * kDROPS_PER_XRP; return f; }(); diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 92949256fd..58c925c043 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -55,7 +55,6 @@ #include #include #include -#include #include namespace xrpl::test { @@ -100,11 +99,11 @@ class LoanBroker_test : public beast::unit_test::Suite env(coverWithdraw(alice, brokerKeylet.key, asset(1000)), Ter(temDISABLED)); // 3. LoanBrokerCoverClawback env(coverClawback(alice), Ter(temDISABLED)); - env(coverClawback(alice), kLoanBrokerId(brokerKeylet.key), Ter(temDISABLED)); - env(coverClawback(alice), kAmount(asset(0)), Ter(temDISABLED)); + env(coverClawback(alice), kLOAN_BROKER_ID(brokerKeylet.key), Ter(temDISABLED)); + env(coverClawback(alice), kAMOUNT(asset(0)), Ter(temDISABLED)); env(coverClawback(alice), - kLoanBrokerId(brokerKeylet.key), - kAmount(asset(1000)), + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(asset(1000)), Ter(temDISABLED)); // 4. LoanBrokerDelete env(del(alice, brokerKeylet.key), Ter(temDISABLED)); @@ -167,15 +166,15 @@ class LoanBroker_test : public beast::unit_test::Suite using namespace loanBroker; // Bogus assets to use in test cases - static PrettyAsset const kBadMptAsset = [&]() { - MPTTester badMptt{env, evan, kMptInitNoFund}; + static PrettyAsset const kBAD_MPT_ASSET = [&]() { + MPTTester badMptt{env, evan, kMPT_INIT_NO_FUND}; badMptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); return badMptt["BAD"]; }(); - static PrettyAsset const kBadIouAsset = evan["BAD"]; - static Account const kNonExistent{"NonExistent"}; - static PrettyAsset const kGhostIouAsset = kNonExistent["GST"]; + static PrettyAsset const kBAD_IOU_ASSET = evan["BAD"]; + static Account const kNON_EXISTENT{"NonExistent"}; + static PrettyAsset const kGHOST_IOU_ASSET = kNON_EXISTENT["GST"]; PrettyAsset const vaultPseudoIouAsset = vault.pseudoAccount["PSD"]; auto const badKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); @@ -236,7 +235,7 @@ class LoanBroker_test : public beast::unit_test::Suite BEAST_EXPECT( pseudo->at(sfFlags) == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); BEAST_EXPECT(pseudo->at(sfSequence) == 0); - BEAST_EXPECT(pseudo->at(sfBalance) == beast::kZero); + BEAST_EXPECT(pseudo->at(sfBalance) == beast::kZERO); BEAST_EXPECT(pseudo->at(sfOwnerCount) == (vault.asset.raw().native() ? 0 : 1)); BEAST_EXPECT(!pseudo->isFieldPresent(sfAccountTxnID)); BEAST_EXPECT(!pseudo->isFieldPresent(sfRegularKey)); @@ -301,41 +300,41 @@ class LoanBroker_test : public beast::unit_test::Suite // Test cover clawback failure cases BEFORE depositing any cover // Need one of brokerID or amount env(coverClawback(alice), Ter(temINVALID)); - env(coverClawback(alice), kLoanBrokerId(uint256(0)), Ter(temINVALID)); - env(coverClawback(alice), kAmount(XRP(1000)), Ter(temBAD_AMOUNT)); - env(coverClawback(alice), kAmount(vault.asset(-10)), Ter(temBAD_AMOUNT)); + env(coverClawback(alice), kLOAN_BROKER_ID(uint256(0)), Ter(temINVALID)); + env(coverClawback(alice), kAMOUNT(XRP(1000)), Ter(temBAD_AMOUNT)); + env(coverClawback(alice), kAMOUNT(vault.asset(-10)), Ter(temBAD_AMOUNT)); // Clawbacks with an MPT need to specify the broker ID - env(coverClawback(alice), kAmount(kBadMptAsset(1)), Ter(temINVALID)); - env(coverClawback(evan), kLoanBrokerId(vault.vaultID), Ter(tecNO_ENTRY)); + env(coverClawback(alice), kAMOUNT(kBAD_MPT_ASSET(1)), Ter(temINVALID)); + env(coverClawback(evan), kLOAN_BROKER_ID(vault.vaultID), Ter(tecNO_ENTRY)); // Only the issuer can clawback - env(coverClawback(alice), kLoanBrokerId(keylet.key), Ter(tecNO_PERMISSION)); + env(coverClawback(alice), kLOAN_BROKER_ID(keylet.key), Ter(tecNO_PERMISSION)); if (vault.asset.raw().native()) { // Can not clawback XRP under any circumstances - env(coverClawback(issuer), kLoanBrokerId(keylet.key), Ter(tecNO_PERMISSION)); + env(coverClawback(issuer), kLOAN_BROKER_ID(keylet.key), Ter(tecNO_PERMISSION)); } else { if (vault.asset.raw().holds()) { - // Clawbacks without a kLoanBrokerId need to specify an IOU + // Clawbacks without a kLOAN_BROKER_ID need to specify an IOU // with the broker's pseudo-account as the issuer - env(coverClawback(alice), kAmount(kGhostIouAsset(1)), Ter(tecNO_ENTRY)); - env(coverClawback(alice), kAmount(kBadIouAsset(1)), Ter(tecOBJECT_NOT_FOUND)); + env(coverClawback(alice), kAMOUNT(kGHOST_IOU_ASSET(1)), Ter(tecNO_ENTRY)); + env(coverClawback(alice), kAMOUNT(kBAD_IOU_ASSET(1)), Ter(tecOBJECT_NOT_FOUND)); // Pseudo-account is not for a broker env(coverClawback(alice), - kAmount(vaultPseudoIouAsset(1)), + kAMOUNT(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), - kLoanBrokerId(keylet.key), - kAmount(badBrokerPseudoIouAsset(10)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(badBrokerPseudoIouAsset(10)), Ter(tecWRONG_ASSET)); PrettyAsset const brokerWrongCurrencyAsset = pseudoAccount["WAT"]; env(coverClawback(issuer), - kLoanBrokerId(keylet.key), - kAmount(brokerWrongCurrencyAsset(10)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(brokerWrongCurrencyAsset(10)), Ter(tecWRONG_ASSET)); } else @@ -343,13 +342,13 @@ 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), kAmount(vault.asset(10)), Ter(temINVALID)); + env(coverClawback(alice), kAMOUNT(vault.asset(10)), Ter(temINVALID)); } // Since no cover has been deposited, there's nothing to claw // back env(coverClawback(issuer), - kLoanBrokerId(keylet.key), - kAmount(vault.asset(10)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(vault.asset(10)), Ter(tecINSUFFICIENT_FUNDS)); } env.close(); @@ -372,13 +371,13 @@ class LoanBroker_test : public beast::unit_test::Suite { TER const expected = vault.asset.raw().holds() ? tecNO_AUTH : tecNO_LINE; env(coverWithdraw(alice, keylet.key, vault.asset(1)), - kDestination(bystander), + kDESTINATION(bystander), Ter(expected)); } // Can not withdraw to the zero address env(coverWithdraw(alice, keylet.key, vault.asset(1)), - kDestination(AccountID{}), + kDESTINATION(AccountID{}), Ter(temMALFORMED)); // Withdraw some of the cover amount @@ -393,20 +392,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)), kDestination(evan)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), kDESTINATION(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)), kDestination(evan), Dtag(3)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), kDESTINATION(evan), Dtag(3)); env.close(); verifyCoverAmount(6); if (!vault.asset.raw().native()) { // Issuer claws back some of the cover - env(coverClawback(issuer), kLoanBrokerId(keylet.key), kAmount(vault.asset(2))); + env(coverClawback(issuer), kLOAN_BROKER_ID(keylet.key), kAMOUNT(vault.asset(2))); env.close(); verifyCoverAmount(4); @@ -420,32 +419,32 @@ class LoanBroker_test : public beast::unit_test::Suite // defer autofills until submission time env.json( coverClawback(issuer), - kLoanBrokerId(keylet.key), - Fee(kNone), - Seq(kNone), - Sig(kNone)), + kLOAN_BROKER_ID(keylet.key), + Fee(kNONE), + Seq(kNONE), + Sig(kNONE)), env.json( coverClawback(issuer), - kLoanBrokerId(keylet.key), - kAmount(vault.asset(0)), - Fee(kNone), - Seq(kNone), - Sig(kNone)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(vault.asset(0)), + Fee(kNONE), + Seq(kNONE), + Sig(kNONE)), env.json( coverClawback(issuer), - kLoanBrokerId(keylet.key), - kAmount(vault.asset(6)), - Fee(kNone), - Seq(kNone), - Sig(kNone)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(vault.asset(6)), + Fee(kNONE), + Seq(kNONE), + Sig(kNONE)), // amount will be truncated to what's available env.json( coverClawback(issuer), - kLoanBrokerId(keylet.key), - kAmount(vault.asset(100)), - Fee(kNone), - Seq(kNone), - Sig(kNone)), + kLOAN_BROKER_ID(keylet.key), + kAMOUNT(vault.asset(100)), + Fee(kNONE), + Seq(kNONE), + Sig(kNONE)), }) { // Issuer claws it all back @@ -461,7 +460,7 @@ class LoanBroker_test : public beast::unit_test::Suite } // no-op - env(set(alice, vault.vaultID), kLoanBrokerId(keylet.key)); + env(set(alice, vault.vaultID), kLOAN_BROKER_ID(keylet.key)); env.close(); // Make modifications to the broker @@ -478,9 +477,9 @@ class LoanBroker_test : public beast::unit_test::Suite // Debt maximum: explicit 0 // Data: explicit empty env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kDebtMaximum(Number(0)), - kData("")); + kLOAN_BROKER_ID(broker->key()), + kDEBT_MAXIMUM(Number(0)), + kDATA("")); env.close(); // Check the updated fields @@ -505,7 +504,7 @@ class LoanBroker_test : public beast::unit_test::Suite auto const aliceBalance = env.balance(alice, vault.asset); auto const coverFunds = env.balance(pseudoAccount, vault.asset); BEAST_EXPECT(coverFunds.number() == broker->at(sfCoverAvailable)); - BEAST_EXPECT(coverFunds != beast::kZero); + BEAST_EXPECT(coverFunds != beast::kZERO); verifyCoverAmount(6); // delete the broker @@ -531,7 +530,7 @@ class LoanBroker_test : public beast::unit_test::Suite (aliceBalance.value().native() ? STAmount(env.current()->fees().base.value()) : vault.asset(0)); env.require(Balance(alice, expectedBalance)); - env.require(Balance(pseudoAccount, vault.asset(kNone))); + env.require(Balance(pseudoAccount, vault.asset(kNONE))); } } @@ -573,7 +572,7 @@ class LoanBroker_test : public beast::unit_test::Suite env(pay(issuer, alice, iouAsset(100'000))); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); PrettyAsset const mptAsset = mptt["MPT"]; @@ -654,56 +653,58 @@ class LoanBroker_test : public beast::unit_test::Suite // field length validation // sfData: good length, bad account env(set(evan, vault.vaultID), - kData(std::string(kMaxDataPayloadLength, 'X')), + kDATA(std::string(kMAX_DATA_PAYLOAD_LENGTH, 'X')), Ter(tecNO_PERMISSION)); // sfData: too long env(set(evan, vault.vaultID), - kData(std::string(kMaxDataPayloadLength + 1, 'Y')), + kDATA(std::string(kMAX_DATA_PAYLOAD_LENGTH + 1, 'Y')), Ter(temINVALID)); // sfManagementFeeRate: good value, bad account env(set(evan, vault.vaultID), - kManagementFeeRate(kMaxManagementFeeRate), + kMANAGEMENT_FEE_RATE(kMAX_MANAGEMENT_FEE_RATE), Ter(tecNO_PERMISSION)); // sfManagementFeeRate: too big env(set(evan, vault.vaultID), - kManagementFeeRate(kMaxManagementFeeRate + TenthBips16(10)), + kMANAGEMENT_FEE_RATE(kMAX_MANAGEMENT_FEE_RATE + TenthBips16(10)), Ter(temINVALID)); // sfCoverRateMinimum and sfCoverRateLiquidation are linked // Cover: good value, bad account env(set(evan, vault.vaultID), - kCoverRateMinimum(kMaxCoverRate), - kCoverRateLiquidation(kMaxCoverRate), + kCOVER_RATE_MINIMUM(kMAX_COVER_RATE), + kCOVER_RATE_LIQUIDATION(kMAX_COVER_RATE), Ter(tecNO_PERMISSION)); // CoverMinimum: too big env(set(evan, vault.vaultID), - kCoverRateMinimum(kMaxCoverRate + 1), - kCoverRateLiquidation(kMaxCoverRate + 1), + kCOVER_RATE_MINIMUM(kMAX_COVER_RATE + 1), + kCOVER_RATE_LIQUIDATION(kMAX_COVER_RATE + 1), Ter(temINVALID)); // CoverLiquidation: too big env(set(evan, vault.vaultID), - kCoverRateMinimum(kMaxCoverRate / 2), - kCoverRateLiquidation(kMaxCoverRate + 1), + kCOVER_RATE_MINIMUM(kMAX_COVER_RATE / 2), + kCOVER_RATE_LIQUIDATION(kMAX_COVER_RATE + 1), Ter(temINVALID)); // Cover: zero min, non-zero liquidation - implicit and // explicit zero values. - env(set(evan, vault.vaultID), kCoverRateLiquidation(kMaxCoverRate), Ter(temINVALID)); env(set(evan, vault.vaultID), - kCoverRateMinimum(tenthBipsZero), - kCoverRateLiquidation(kMaxCoverRate), + kCOVER_RATE_LIQUIDATION(kMAX_COVER_RATE), + Ter(temINVALID)); + env(set(evan, vault.vaultID), + kCOVER_RATE_MINIMUM(tenthBipsZero), + kCOVER_RATE_LIQUIDATION(kMAX_COVER_RATE), Ter(temINVALID)); // Cover: non-zero min, zero liquidation - implicit and // explicit zero values. - env(set(evan, vault.vaultID), kCoverRateMinimum(kMaxCoverRate), Ter(temINVALID)); + env(set(evan, vault.vaultID), kCOVER_RATE_MINIMUM(kMAX_COVER_RATE), Ter(temINVALID)); env(set(evan, vault.vaultID), - kCoverRateMinimum(kMaxCoverRate), - kCoverRateLiquidation(tenthBipsZero), + kCOVER_RATE_MINIMUM(kMAX_COVER_RATE), + kCOVER_RATE_LIQUIDATION(tenthBipsZero), Ter(temINVALID)); // sfDebtMaximum: good value, bad account - env(set(evan, vault.vaultID), kDebtMaximum(Number(0)), Ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), kDEBT_MAXIMUM(Number(0)), Ter(tecNO_PERMISSION)); // sfDebtMaximum: overflow - env(set(evan, vault.vaultID), kDebtMaximum(Number(1, 100)), Ter(temINVALID)); + env(set(evan, vault.vaultID), kDEBT_MAXIMUM(Number(1, 100)), Ter(temINVALID)); // sfDebtMaximum: negative - env(set(evan, vault.vaultID), kDebtMaximum(Number(-1)), Ter(temINVALID)); + env(set(evan, vault.vaultID), kDEBT_MAXIMUM(Number(-1)), Ter(temINVALID)); std::string testData; lifecycle( @@ -738,57 +739,61 @@ class LoanBroker_test : public beast::unit_test::Suite // fields that can't be changed // LoanBrokerID - env(set(alice, vault.vaultID), kLoanBrokerId(nextKeylet.key), Ter(tecNO_ENTRY)); + env(set(alice, vault.vaultID), + kLOAN_BROKER_ID(nextKeylet.key), + Ter(tecNO_ENTRY)); // VaultID - env(set(alice, nextKeylet.key), kLoanBrokerId(broker->key()), Ter(tecNO_ENTRY)); + env(set(alice, nextKeylet.key), + kLOAN_BROKER_ID(broker->key()), + Ter(tecNO_ENTRY)); // Owner env(set(evan, vault.vaultID), - kLoanBrokerId(broker->key()), + kLOAN_BROKER_ID(broker->key()), Ter(tecNO_PERMISSION)); // ManagementFeeRate env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kManagementFeeRate(kMaxManagementFeeRate), + kLOAN_BROKER_ID(broker->key()), + kMANAGEMENT_FEE_RATE(kMAX_MANAGEMENT_FEE_RATE), Ter(temINVALID)); // CoverRateMinimum env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kCoverRateMinimum(kMaxManagementFeeRate), + kLOAN_BROKER_ID(broker->key()), + kCOVER_RATE_MINIMUM(kMAX_MANAGEMENT_FEE_RATE), Ter(temINVALID)); // CoverRateLiquidation env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kCoverRateLiquidation(kMaxManagementFeeRate), + kLOAN_BROKER_ID(broker->key()), + kCOVER_RATE_LIQUIDATION(kMAX_MANAGEMENT_FEE_RATE), Ter(temINVALID)); // fields that can be changed testData = "Test Data 1234"; // Bad data: too long env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kData(std::string(kMaxDataPayloadLength + 1, 'W')), + kLOAN_BROKER_ID(broker->key()), + kDATA(std::string(kMAX_DATA_PAYLOAD_LENGTH + 1, 'W')), Ter(temINVALID)); // Bad debt maximum env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kDebtMaximum(Number(-175, -1)), + kLOAN_BROKER_ID(broker->key()), + kDEBT_MAXIMUM(Number(-175, -1)), Ter(temINVALID)); Number debtMax{175, -1}; if (vault.asset.integral()) { env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kData(testData), - kDebtMaximum(debtMax), + kLOAN_BROKER_ID(broker->key()), + kDATA(testData), + kDEBT_MAXIMUM(debtMax), Ter(tecPRECISION_LOSS)); roundToAsset(vault.asset, debtMax); } // Data & Debt maximum env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kData(testData), - kDebtMaximum(debtMax)); + kLOAN_BROKER_ID(broker->key()), + kDATA(testData), + kDEBT_MAXIMUM(debtMax)); }, [&](SLE::const_ref broker) { // Check the updated fields @@ -811,15 +816,15 @@ class LoanBroker_test : public beast::unit_test::Suite badVault, [&](jtx::JTx const& jv) { testData = "spam spam spam spam"; - // Finally, create another Loan Broker with kNone of the + // Finally, create another Loan Broker with kNONE of the // values at default return env.jt( jv, - kData(testData), - kManagementFeeRate(TenthBips16(123)), - kDebtMaximum(Number(9)), - kCoverRateMinimum(TenthBips32(100)), - kCoverRateLiquidation(TenthBips32(200))); + kDATA(testData), + kMANAGEMENT_FEE_RATE(TenthBips16(123)), + kDEBT_MAXIMUM(Number(9)), + kCOVER_RATE_MINIMUM(TenthBips32(100)), + kCOVER_RATE_LIQUIDATION(TenthBips32(200))); }, [&](SLE::const_ref broker) { // Extra checks @@ -832,9 +837,9 @@ class LoanBroker_test : public beast::unit_test::Suite [&](SLE::const_ref broker) { // Reset Data & Debt maximum to default values env(set(alice, vault.vaultID), - kLoanBrokerId(broker->key()), - kData(""), - kDebtMaximum(Number(0))); + kLOAN_BROKER_ID(broker->key()), + kDATA(""), + kDEBT_MAXIMUM(Number(0))); }, [&](SLE::const_ref broker) { // Check the updated fields @@ -958,7 +963,7 @@ class LoanBroker_test : public beast::unit_test::Suite // preclaim: tecNO_DST Account const bogus{"bogus"}; env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(bogus), + kDESTINATION(bogus), Ter(tecNO_DST)); // preclaim: tecDST_TAG_NEEDED @@ -967,7 +972,7 @@ class LoanBroker_test : public beast::unit_test::Suite env(fset(dest, asfRequireDest)); env.close(); env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(dest), + kDESTINATION(dest), Ter(tecDST_TAG_NEEDED)); // preclaim: tecNO_PERMISSION @@ -975,7 +980,7 @@ class LoanBroker_test : public beast::unit_test::Suite env(fset(dest, asfDepositAuth)); env.close(); env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(dest), + kDESTINATION(dest), Ter(tecNO_PERMISSION)); // preclaim: tecFROZEN @@ -984,19 +989,19 @@ class LoanBroker_test : public beast::unit_test::Suite env(fset(issuer, asfGlobalFreeze)); env.close(); env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(dest), + kDESTINATION(dest), Ter(tecFROZEN)); // preclaim:: tecFROZEN (deep frozen) env(fclear(issuer, asfGlobalFreeze)); env(trust(issuer, asset(1'000), dest, tfSetFreeze | tfSetDeepFreeze)); env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(dest), + kDESTINATION(dest), Ter(tecFROZEN)); // preclaim: tecPSEUDO_ACCOUNT env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - kDestination(vaultInfo.pseudoAccount), + kDESTINATION(vaultInfo.pseudoAccount), Ter(tecPSEUDO_ACCOUNT)); } @@ -1006,32 +1011,32 @@ class LoanBroker_test : public beast::unit_test::Suite testZeroBrokerID([&]() { return env.json( coverClawback(alice), - kLoanBrokerId(brokerKeylet.key), - kAmount(vaultInfo.asset(2))); + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(vaultInfo.asset(2))); }); if (asset.holds()) { // preclaim: AllowTrustLineClawback is not set env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(vaultInfo.asset(2)), + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(vaultInfo.asset(2)), Ter(tecNO_PERMISSION)); // preclaim: NoFreeze is set env(fset(issuer, asfAllowTrustLineClawback | asfNoFreeze)); env.close(); env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(vaultInfo.asset(2)), + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(vaultInfo.asset(2)), Ter(tecNO_PERMISSION)); } else { // preclaim: MPTCanClawback is not set or MPTCanLock is not set env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(vaultInfo.asset(2)), + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(vaultInfo.asset(2)), Ter(tecNO_PERMISSION)); } env.close(); @@ -1073,11 +1078,11 @@ class LoanBroker_test : public beast::unit_test::Suite { // preflight: temINVALID (empty/zero broker id) testZeroBrokerID([&]() { - return env.json(set(alice, vaultInfo.vaultID), kLoanBrokerId(brokerKeylet.key)); + return env.json(set(alice, vaultInfo.vaultID), kLOAN_BROKER_ID(brokerKeylet.key)); }); // preflight: temINVALID (empty/zero vault id) testZeroVaultID([&]() { - return env.json(set(alice, vaultInfo.vaultID), kLoanBrokerId(brokerKeylet.key)); + return env.json(set(alice, vaultInfo.vaultID), kLOAN_BROKER_ID(brokerKeylet.key)); }); if (asset.holds()) @@ -1116,13 +1121,13 @@ class LoanBroker_test : public beast::unit_test::Suite env.fund(XRP(100'000), alice); env.close(); - auto jtx = env.jt(coverClawback(alice), kAmount(usd(100))); + auto jtx = env.jt(coverClawback(alice), kAMOUNT(usd(100))); // holder == account env(jtx, Ter(temINVALID)); // holder == beast::zero - STAmount const bad(Issue{usd.currency, beast::kZero}, 100); + STAmount const bad(Issue{usd.currency, beast::kZERO}, 100); jtx.jv[sfAmount] = bad.getJson(); jtx.stx = env.ust(jtx); Serializer s; @@ -1244,7 +1249,7 @@ class LoanBroker_test : public beast::unit_test::Suite // Create a writable view cloned from the current ledger and remove the // vault SLE OpenView ov{*env.current()}; - test::StreamSink sink{beast::Severity::Warning}; + test::StreamSink sink{beast::severities::KWarning}; beast::Journal const jlog{sink}; ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog}; @@ -1282,7 +1287,7 @@ class LoanBroker_test : public beast::unit_test::Suite .env = env, .issuer = issuer, .holders = {alice}, - .flags = kMptDexFlags | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, .authHolder = true, }); @@ -1366,8 +1371,8 @@ class LoanBroker_test : public beast::unit_test::Suite // Issuer can always cover clawback. The holder authorization is n/a. forUnauthAuth([&](bool) { env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(vaultInfo.asset(1))); + kLOAN_BROKER_ID(brokerKeylet.key), + kAMOUNT(vaultInfo.asset(1))); }); } @@ -1386,7 +1391,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); PrettyAsset const asset = [&]() { - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); PrettyAsset const mptAsset = mptt["MPT"]; @@ -1440,33 +1445,33 @@ class LoanBroker_test : public beast::unit_test::Suite tx2[sfDebtMaximum] = 0; env(tx2, Ter(tesSUCCESS)); - tx2[sfDebtMaximum] = json::Value::kMaxInt; + tx2[sfDebtMaximum] = json::Value::kMAX_INT; env(tx2, Ter(tesSUCCESS)); { auto const dm = power(2, 64) - 1; - BEAST_EXPECT(dm > kMaxMpTokenAmount); + BEAST_EXPECT(dm > kMAX_MP_TOKEN_AMOUNT); tx2[sfDebtMaximum] = dm; env(tx2, Ter(temINVALID)); } { auto const dm = power(2, 63) - 1; - BEAST_EXPECTS(dm > kMaxMpTokenAmount, to_string(dm)); + BEAST_EXPECTS(dm > kMAX_MP_TOKEN_AMOUNT, to_string(dm)); tx2[sfDebtMaximum] = dm; env(tx2, Ter(temINVALID)); } { auto const dm = power(2, 63) - 3; - BEAST_EXPECTS(dm == kMaxMpTokenAmount, to_string(dm)); + BEAST_EXPECTS(dm == kMAX_MP_TOKEN_AMOUNT, to_string(dm)); tx2[sfDebtMaximum] = dm; env(tx2, Ter(tesSUCCESS)); } { auto const dm = 2 * (power(2, 62) - 1) + 1; - BEAST_EXPECTS(dm == kMaxMpTokenAmount, to_string(dm)); + BEAST_EXPECTS(dm == kMAX_MP_TOKEN_AMOUNT, to_string(dm)); tx2[sfDebtMaximum] = dm; env(tx2, Ter(tesSUCCESS)); } @@ -1528,14 +1533,14 @@ class LoanBroker_test : public beast::unit_test::Suite {2'000, 2'500, 250, tesSUCCESS}, // issuer can issue 500 tokens (250 VaultDeposit + // 250 LoanBrokerCoverDeposit). MaximumAmount is default. - {kMaxMpTokenAmount - 500, std::nullopt, 250, tesSUCCESS}, + {kMAX_MP_TOKEN_AMOUNT - 500, std::nullopt, 250, tesSUCCESS}, // issuer can issue 500, and fails on depositing 1'000 {2'000, 2'500, 1'000, tecINSUFFICIENT_FUNDS}, // issuer has already issued MaximumAmount {2'000, 2'000, 1'000, tecINSUFFICIENT_FUNDS}, // issuer has already issued MaximumAmount. MaximumAmount is // default. - {kMaxMpTokenAmount, std::nullopt, 250, tecINSUFFICIENT_FUNDS}, + {kMAX_MP_TOKEN_AMOUNT, std::nullopt, 250, tecINSUFFICIENT_FUNDS}, }; for (auto const& [pay, max, deposit, err] : mptTests) { @@ -1545,7 +1550,7 @@ class LoanBroker_test : public beast::unit_test::Suite .issuer = issuer, .holders = {holder}, .pay = pay, - .flags = kMptDexFlags, + .flags = kMPT_DEX_FLAGS, .maxAmt = max}); return std::make_tuple(token, token(deposit), err); }); @@ -1577,210 +1582,6 @@ class LoanBroker_test : public beast::unit_test::Suite env(loanBroker::set(lender, vaultKeylet.key), Ter(tecFROZEN)); } - void - testLoanBrokerDeleteLockedMPT(FeatureBitset features) - { - testcase << "LoanBrokerDelete - locked broker pseudo-account MPT"; - using namespace jtx; - using namespace loanBroker; - - Account const issuer("issuer"); - Account const alice("alice"); - - auto const withFix = features[fixCleanup3_2_0]; - Env env(*this, features); - env.fund(XRP(100'000), issuer, alice); - env.close(); - - // Create MPT with locking enabled - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - - PrettyAsset const mpt{mptt.issuanceID()}; - - // Fund alice - mptt.authorize({.account = alice}); - env.close(); - env(pay(issuer, alice, mpt(100'000))); - env.close(); - - // Create vault - Vault const vault{env}; - auto [tx, vaultKeylet] = vault.create({.owner = alice, .asset = mpt}); - env(tx); - env.close(); - - // Deposit into vault - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = mpt(10'000)})); - env.close(); - - // Create loan broker - auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); - env(set(alice, vaultKeylet.key)); - env.close(); - - // Deposit cover - env(coverDeposit(alice, brokerKeylet.key, mpt(5'000).value())); - env.close(); - - // Verify cover is deposited - auto const broker = env.le(brokerKeylet); - if (!BEAST_EXPECT(broker)) - return; - BEAST_EXPECT(broker->at(sfCoverAvailable) > 0); - - // Get the broker pseudo-account ID - auto const brokerPseudoID = broker->at(sfAccount); - - // Verify the broker pseudo-account has an MPToken - auto const pseudoMptKey = keylet::mptoken(mptt.issuanceID(), brokerPseudoID); - auto const pseudoMpt = env.le(pseudoMptKey); - if (!BEAST_EXPECT(pseudoMpt)) - return; - - // Issuer locks the broker pseudo-account's individual MPToken - { - json::Value jv; - jv[jss::Account] = issuer.human(); - jv[sfMPTokenIssuanceID] = to_string(mptt.issuanceID()); - jv[jss::Holder] = toBase58(brokerPseudoID); - jv[jss::TransactionType] = jss::MPTokenIssuanceSet; - jv[jss::Flags] = tfMPTLock; - env(jv); - env.close(); - } - - // Verify the pseudo-account's MPToken is now locked - { - auto const sle = env.le(pseudoMptKey); - if (!BEAST_EXPECT(sle)) - return; - BEAST_EXPECT(sle->isFlag(lsfMPTLocked)); - } - - // Record alice's balance before deletion - auto const aliceBalanceBefore = env.balance(alice, mpt); - - // With fixCleanup3_2_0, preclaim() checks the broker pseudo-account's - // freeze/lock state via checkFrozen(), so deletion is blocked. - // Without the fix, the check is missing and the locked cover is - // returned to the owner. - if (withFix) - { - env(del(alice, brokerKeylet.key), Ter(tecLOCKED)); - env.close(); - - // Verify the broker is not deleted - BEAST_EXPECT(env.le(brokerKeylet) != nullptr); - - // Verify alice did not receive the cover despite the lock - auto const aliceBalanceAfter = env.balance(alice, mpt); - BEAST_EXPECT(aliceBalanceAfter == aliceBalanceBefore); - - // Verify the locked MPToken was not deleted - BEAST_EXPECT(env.le(pseudoMptKey) != nullptr); - } - else - { - env(del(alice, brokerKeylet.key), Ter(tesSUCCESS)); - env.close(); - - // Verify the broker is deleted - BEAST_EXPECT(env.le(brokerKeylet) == nullptr); - - // Verify alice received the cover despite the lock - auto const aliceBalanceAfter = env.balance(alice, mpt); - BEAST_EXPECT(aliceBalanceAfter > aliceBalanceBefore); - - // Verify the locked MPToken was deleted - BEAST_EXPECT(env.le(pseudoMptKey) == nullptr); - } - } - - void - testLoanBrokerDeleteFrozenIOU(FeatureBitset features) - { - testcase << "LoanBrokerDelete - frozen broker pseudo-account IOU"; - using namespace jtx; - using namespace loanBroker; - - Account const issuer("issuer"); - Account const alice("alice"); - - auto const withFix = features[fixCleanup3_2_0]; - Env env(*this, features); - env.fund(XRP(100'000), issuer, alice); - env.close(); - - auto const iou = issuer["IOU"]; - - // Set up trust lines and fund alice - env(trust(alice, iou(1'000'000))); - env.close(); - env(pay(issuer, alice, iou(100'000))); - env.close(); - - // Create vault - Vault const vault{env}; - auto [tx, vaultKeylet] = vault.create({.owner = alice, .asset = iou.asset()}); - env(tx); - env.close(); - - // Deposit into vault - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = iou(10'000)})); - env.close(); - - // Create loan broker - auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); - env(set(alice, vaultKeylet.key)); - env.close(); - - // Deposit cover - env(coverDeposit(alice, brokerKeylet.key, iou(5'000))); - env.close(); - - // Verify cover is deposited - auto const broker = env.le(brokerKeylet); - if (!BEAST_EXPECT(broker)) - return; - BEAST_EXPECT(broker->at(sfCoverAvailable) > 0); - - // Get the broker pseudo-account - auto const brokerPseudoID = broker->at(sfAccount); - auto const brokerPseudo = Account("BrokerPseudo", brokerPseudoID); - - // Issuer freezes the broker pseudo-account's trust line - env(trust(issuer, brokerPseudo["IOU"](0), tfSetFreeze)); - env.close(); - - // Record alice's balance before deletion attempt - auto const aliceBalanceBefore = env.balance(alice, iou); - - // With fixCleanup3_2_0, preclaim() checks the broker - // pseudo-account's freeze state via checkFrozen(), so - // deletion is blocked early with tecFROZEN. - // Without the fix, preclaim() does not check the pseudo-account, - // but the TransfersNotFrozen invariant catches the frozen transfer - // in doApply() and fails with tecINVARIANT_FAILED. - // Either way, the broker survives and alice's balance is unchanged. - if (withFix) - { - env(del(alice, brokerKeylet.key), Ter(tecFROZEN)); - } - else - { - env(del(alice, brokerKeylet.key), Ter(tecINVARIANT_FAILED)); - } - env.close(); - - // Broker still exists - BEAST_EXPECT(env.le(brokerKeylet) != nullptr); - - // Alice's balance unchanged - auto const aliceBalanceAfter = env.balance(alice, iou); - BEAST_EXPECT(aliceBalanceAfter == aliceBalanceBefore); - } - void testRIPD4274IOU() { @@ -1865,7 +1666,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)}), - loanBroker::kDestination(dest), + loanBroker::kDESTINATION(dest), Ter(std::ignore)); BEAST_EXPECT(env.ter() == tecNO_LINE); env.close(); @@ -1882,7 +1683,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), - loanBroker::kDestination(dest), + loanBroker::kDESTINATION(dest), Ter(std::ignore)); BEAST_EXPECT(env.ter() == tecNO_LINE); env.close(); @@ -1894,7 +1695,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), - loanBroker::kDestination(dest), + loanBroker::kDESTINATION(dest), Ter(std::ignore)); BEAST_EXPECT(env.ter() == tecNO_LINE); env.close(); @@ -1939,7 +1740,7 @@ class LoanBroker_test : public beast::unit_test::Suite .issuer = issuer, .holders = {broker, dest}, .pay = 2'000, - .flags = kMptDexFlags | tfMPTRequireAuth, + .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth, .authHolder = true, .maxAmt = 5'000}); // unauthorize dest @@ -1953,7 +1754,7 @@ class LoanBroker_test : public beast::unit_test::Suite .issuer = issuer, .holders = {broker, dest}, .pay = 2'000, - .flags = kMptDexFlags, + .flags = kMPT_DEX_FLAGS, .maxAmt = 4'000}); BEAST_EXPECT(env.balance(issuer, tester) == tester(-4'000)); return tester; @@ -1964,7 +1765,7 @@ class LoanBroker_test : public beast::unit_test::Suite .issuer = issuer, .holders = {broker}, .pay = 2'000, - .flags = kMptDexFlags, + .flags = kMPT_DEX_FLAGS, .maxAmt = 4'000}); } default: @@ -1986,7 +1787,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)}), - loanBroker::kDestination(dest), + loanBroker::kDESTINATION(dest), Ter(std::ignore)); // Shouldn't fail if at MaximumAmount since no new tokens are issued @@ -2010,7 +1811,7 @@ class LoanBroker_test : public beast::unit_test::Suite env.close(); env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), - loanBroker::kDestination(dest), + loanBroker::kDESTINATION(dest), Ter(std::ignore)); BEAST_EXPECT(env.ter() == err); env.close(); @@ -2028,221 +1829,10 @@ class LoanBroker_test : public beast::unit_test::Suite testRIPD4274MPT(); } - // Exercises canApplyToBrokerCover (fixCleanup3_2_0): a deposit, withdraw, - // or clawback whose amount rounds to zero at sfCoverAvailable's precision - // scale must be rejected with tecPRECISION_LOSS once the amendment is on, - // and must silently succeed without changing sfCoverAvailable when off. - void - testCoverPrecisionGuard() - { - using namespace jtx; - using namespace loanBroker; - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - - // sfCoverAvailable = 10 IOU → STAmount exponent = -14. - // Anything < 5e-15 rounds to zero at that scale. - // 1e-16 is the representative sub-ULP probe amount. - - // Shared setup: funds accounts, creates a vault + broker with 10 IOU - // cover, and returns {brokerKeylet, iou}. - auto const setup = [&](Env& env) -> std::pair { - Vault const vault{env}; - - env.fund(XRP(100'000), issuer, alice); - env.close(); - env(fset(issuer, asfAllowTrustLineClawback)); - env.close(); - - PrettyAsset const iou = issuer["IOU"]; - env(trust(alice, iou(1'000'000))); - env.close(); - env(pay(issuer, alice, iou(1'000))); - env.close(); - - auto [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = iou}); - env(createTx); - env.close(); - - auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); - env(set(alice, vaultKeylet.key)); - env.close(); - - env(coverDeposit(alice, brokerKeylet.key, iou(10))); - env.close(); - - return {brokerKeylet, iou}; - }; - - auto runTestCases = [&](FeatureBitset features) { - TER const expected = - features[fixCleanup3_2_0] ? TER{tecPRECISION_LOSS} : TER{tesSUCCESS}; - - { - testcase("Cover precision guard: Deposit zero-at-scale"); - Env env{*this, features}; - auto const [brokerKeylet, iou] = setup(env); - PrettyAmount const subUlpAmt = iou(Number{1, -16}); - auto const coverBefore = env.le(brokerKeylet)->at(sfCoverAvailable); - env(coverDeposit(alice, brokerKeylet.key, subUlpAmt), Ter(expected)); - env.close(); - if (expected == tesSUCCESS) - { - if (auto const broker = env.le(brokerKeylet); BEAST_EXPECT(broker)) - BEAST_EXPECT(broker->at(sfCoverAvailable) == coverBefore); - } - } - - { - testcase("Cover precision guard: Deposit rounds down"); - // Both cases succeed; post-fix the amount is rounded DOWN to - // cover scale first, so the delta differs from pre-fix - // Input: 1.8e-14 IOU (sub-scale at cover scale -14) - // Pre-fix: 10 + 1.8e-14 → round-to-nearest → - // 10.00000000000002 → delta 2e-14 - // Post-fix: roundToScale(1.8e-14, -14, Downward) = 1e-14; - // 10 + 1e-14 = 10.00000000000001 → delta 1e-14 - Env env{*this, features}; - auto const [brokerKeylet, iou] = setup(env); - PrettyAmount const subUlpAmt = iou(Number{18, -15}); - auto const coverBefore = env.le(brokerKeylet)->at(sfCoverAvailable); - env(coverDeposit(alice, brokerKeylet.key, subUlpAmt), Ter(tesSUCCESS)); - env.close(); - auto const brokerAfter = env.le(brokerKeylet); - if (!BEAST_EXPECT(brokerAfter)) - return; - - Number const delta = features[fixCleanup3_2_0] ? Number{1, -14} : Number{2, -14}; - BEAST_EXPECT(brokerAfter->at(sfCoverAvailable) - coverBefore == delta); - } - - // Property: post-fix, when the user deposits `x` and cover - // gains `x'`, we always have 0 <= x - x' < 1 ULP at cover - // scale (cover holds 10 IOU → ULP = 1e-14). Pre-fix uses - // STAmount's default round-to-nearest during `+=`, which can - // over-deposit (x' > x), so the property only holds with - // fixCleanup3_2_0 enabled. - if (features[fixCleanup3_2_0]) - { - testcase("Cover precision guard: Deposit rounding bound"); - Env env{*this, features}; - auto const [brokerKeylet, iou] = setup(env); - Number const oneUlp{1, -14}; - // Each requested amount lies strictly between 1·ULP and - // 2·ULP at cover scale; post-fix `roundDown` credits - // exactly `oneUlp` and leaves a strictly-positive, - // strictly-sub-ULP residual. - for (Number const requested : {Number{11, -15}, Number{15, -15}, Number{19, -15}}) - { - auto const broker = env.le(brokerKeylet); - if (!BEAST_EXPECT(broker)) - return; - Number const coverBefore = broker->at(sfCoverAvailable); - env(coverDeposit(alice, brokerKeylet.key, iou(requested)), Ter(tesSUCCESS)); - env.close(); - auto const brokerAfter = env.le(brokerKeylet); - if (!BEAST_EXPECT(brokerAfter)) - return; - Number const coverAfter = brokerAfter->at(sfCoverAvailable); - Number const actual = coverAfter - coverBefore; - Number const lost = requested - actual; - BEAST_EXPECT(lost >= Number{0}); - BEAST_EXPECT(lost < oneUlp); - } - } - - { - testcase("Cover precision guard: Withdraw"); - Env env{*this, features}; - auto const [brokerKeylet, iou] = setup(env); - PrettyAmount const subUlpAmt = iou(Number{1, -16}); - auto const coverBefore = env.le(brokerKeylet)->at(sfCoverAvailable); - auto const aliceBalanceBefore = env.balance(alice, iou); - env(coverWithdraw(alice, brokerKeylet.key, subUlpAmt), Ter(expected)); - env.close(); - if (expected == tesSUCCESS) - { - if (auto const broker = env.le(brokerKeylet); BEAST_EXPECT(broker)) - BEAST_EXPECT(broker->at(sfCoverAvailable) == coverBefore); - BEAST_EXPECT(env.balance(alice, iou) == aliceBalanceBefore); - } - } - - { - testcase("Cover precision guard: Clawback"); - Env env{*this, features}; - auto const [brokerKeylet, iou] = setup(env); - PrettyAmount const subUlpAmt = iou(Number{1, -16}); - auto const coverBefore = env.le(brokerKeylet)->at(sfCoverAvailable); - env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(subUlpAmt), - Ter(expected)); - env.close(); - if (expected == tesSUCCESS) - { - if (auto const broker = env.le(brokerKeylet); BEAST_EXPECT(broker)) - BEAST_EXPECT(broker->at(sfCoverAvailable) == coverBefore); - } - } - - // MPT amounts are integers; scale is 0; the guard never rejects a - // positive integer amount. Verify all three callsites pass with amendment on. - { - testcase("Cover precision guard: MPT min amount passes"); - Env env{*this, all_}; - - env.fund(XRP(100'000), issuer, alice); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - env.close(); - - PrettyAsset const mptAsset = mptt["MPT"]; - mptt.authorize({.account = alice}); - env.close(); - - env(pay(issuer, alice, mptAsset(100))); - env.close(); - - Vault const vault{env}; - auto [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = mptAsset}); - env(createTx); - env.close(); - - auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); - env(set(alice, vaultKeylet.key)); - env.close(); - - env(coverDeposit(alice, brokerKeylet.key, mptAsset(10))); - env.close(); - - env(coverDeposit(alice, brokerKeylet.key, mptAsset(1)), Ter(tesSUCCESS)); - env.close(); - - env(coverWithdraw(alice, brokerKeylet.key, mptAsset(1)), Ter(tesSUCCESS)); - env.close(); - - env(coverClawback(issuer), - kLoanBrokerId(brokerKeylet.key), - kAmount(mptAsset(1)), - Ter(tesSUCCESS)); - env.close(); - } - }; - - runTestCases(all_); - runTestCases(all_ - fixCleanup3_2_0); - } - public: void run() override { - testCoverPrecisionGuard(); - testLoanBrokerSetDebtMaximum(); testLoanBrokerCoverDepositNullVault(); @@ -2260,12 +1850,6 @@ public: testRIPD4274(); - testLoanBrokerDeleteLockedMPT(all_); - testLoanBrokerDeleteLockedMPT(all_ - fixCleanup3_2_0); - - testLoanBrokerDeleteFrozenIOU(all_); - testLoanBrokerDeleteFrozenIOU(all_ - fixCleanup3_2_0); - // TODO: Write clawback failure tests with an issuer / MPT that doesn't // have the right flags set. } diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index c3b5850231..f189196a82 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -26,8 +25,6 @@ #include #include -#include - #include #include #include @@ -69,7 +66,6 @@ #include #include #include -#include #include #include #include @@ -91,25 +87,8 @@ class Loan_test : public beast::unit_test::Suite protected: // Ensure that all the features needed for Lending Protocol are included, // even if they are set to unsupported. - FeatureBitset const all_{jtx::testableAmendments()}; - // All 2^N permutations of `all_` with each subset of the given features - // excluded. The first entry is always `all_` itself (empty exclusion); - // the last excludes every feature in the list. - std::vector - amendmentCombinations(std::initializer_list features) const - { - std::vector result{all_}; - for (auto const& f : features) - { - auto const n = result.size(); - for (std::size_t i = 0; i < n; ++i) - result.push_back(result[i] - f); - } - return result; - } - std::string const iouCurrency_{"IOU"}; void @@ -169,16 +148,12 @@ protected: TenthBips32 coverRateLiquidation = percentageToTenthBips(25); std::string data = {}; // NOLINT(readability-redundant-member-init) std::uint32_t flags = 0; - // If set, the vault is created with this sfScale value. Useful for - // tests that need finer loanScale to exercise rounding edge cases. - std::optional vaultScale = - std::nullopt; // NOLINT(readability-redundant-member-init) [[nodiscard]] Number maxCoveredLoanValue(Number const& currentDebt) const { NumberRoundModeGuard const mg(Number::RoundingMode::Downward); - auto debtLimit = coverDeposit * kTenthBipsPerUnity.value() / coverRateMin.value(); + auto debtLimit = coverDeposit * kTENTH_BIPS_PER_UNITY.value() / coverRateMin.value(); return debtLimit - currentDebt; } @@ -186,8 +161,8 @@ protected: static BrokerParameters const& defaults() { - static BrokerParameters const kResult{}; - return kResult; + static BrokerParameters const kRESULT{}; + return kRESULT; } // TODO: create an operator() which returns a transaction similar to @@ -278,31 +253,31 @@ protected: Fee{setFee.value_or(env.current()->fees().base * 2)}(env, jt); if (counterpartyExplicit) - kCounterparty(counter)(env, jt); + kCOUNTERPARTY(counter)(env, jt); if (originationFee) - kLoanOriginationFee(broker.asset(*originationFee).number())(env, jt); + kLOAN_ORIGINATION_FEE(broker.asset(*originationFee).number())(env, jt); if (serviceFee) - kLoanServiceFee(broker.asset(*serviceFee).number())(env, jt); + kLOAN_SERVICE_FEE(broker.asset(*serviceFee).number())(env, jt); if (lateFee) - kLatePaymentFee(broker.asset(*lateFee).number())(env, jt); + kLATE_PAYMENT_FEE(broker.asset(*lateFee).number())(env, jt); if (closeFee) - kClosePaymentFee(broker.asset(*closeFee).number())(env, jt); + kCLOSE_PAYMENT_FEE(broker.asset(*closeFee).number())(env, jt); if (overFee) - kOverpaymentFee (*overFee)(env, jt); + kOVERPAYMENT_FEE (*overFee)(env, jt); if (interest) - kInterestRate (*interest)(env, jt); + kINTEREST_RATE (*interest)(env, jt); if (lateInterest) - kLateInterestRate (*lateInterest)(env, jt); + kLATE_INTEREST_RATE (*lateInterest)(env, jt); if (closeInterest) - kCloseInterestRate (*closeInterest)(env, jt); + kCLOSE_INTEREST_RATE (*closeInterest)(env, jt); if (overpaymentInterest) - kOverpaymentInterestRate (*overpaymentInterest)(env, jt); + kOVERPAYMENT_INTEREST_RATE (*overpaymentInterest)(env, jt); if (payTotal) - kPaymentTotal (*payTotal)(env, jt); + kPAYMENT_TOTAL (*payTotal)(env, jt); if (payInterval) - kPaymentInterval (*payInterval)(env, jt); + kPAYMENT_INTERVAL (*payInterval)(env, jt); if (gracePd) - kGracePeriod (*gracePd)(env, jt); + kGRACE_PERIOD (*gracePd)(env, jt); return env.jt(jt, fN...); } @@ -319,8 +294,8 @@ protected: static PaymentParameters const& defaults() { - static PaymentParameters const kResult{}; - return kResult; + static PaymentParameters const kRESULT{}; + return kRESULT; } }; @@ -393,11 +368,16 @@ protected: env.balance(vaultPseudo, broker.asset).number()); if (ownerCount == 0) { - // The Vault must be perfectly balanced if there - // are no loans outstanding + // Allow some slop for rounding IOUs + + // TODO: This needs to be an exact match once all the + // other rounding issues are worked out. auto const total = vaultSle->at(sfAssetsTotal); auto const available = vaultSle->at(sfAssetsAvailable); - env.test.BEAST_EXPECT(total == available); + 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); } } @@ -422,7 +402,7 @@ protected: env.balance(account, broker.asset) - (balanceBefore - balanceChangeAmount), borrowerScale); env.test.expect( - roundToScale(difference, loanScale) >= beast::kZero, + roundToScale(difference, loanScale) >= beast::kZERO, "Balance before: " + to_string(balanceBefore.value()) + ", expected change: " + to_string(balanceChangeAmount) + ", difference (balance after - expected): " + to_string(difference), @@ -526,8 +506,6 @@ protected: auto const coverRateMinValue = params.coverRateMin; auto [tx, vaultKeylet] = vault.create({.owner = lender, .asset = asset}); - if (params.vaultScale) - tx[sfScale] = *params.vaultScale; env(tx); env.close(); BEAST_EXPECT(env.le(vaultKeylet)); @@ -543,13 +521,13 @@ protected: using namespace loanBroker; env(set(lender, vaultKeylet.key, params.flags), - kData(params.data), - kManagementFeeRate(params.managementFeeRate), - kDebtMaximum(debtMaximumValue), - kCoverRateMinimum(coverRateMinValue), - kCoverRateLiquidation(TenthBips32(params.coverRateLiquidation))); + kDATA(params.data), + kMANAGEMENT_FEE_RATE(params.managementFeeRate), + kDEBT_MAXIMUM(debtMaximumValue), + kCOVER_RATE_MINIMUM(coverRateMinValue), + kCOVER_RATE_LIQUIDATION(TenthBips32(params.coverRateLiquidation))); - if (coverDepositValue != beast::kZero) + if (coverDepositValue != beast::kZERO) env(coverDeposit(lender, keylet.key, coverDepositValue)); env.close(); @@ -695,7 +673,7 @@ protected: if (!env.le(keylet::account(borrower))) env.fund(env.current()->fees().accountReserve(10) * 10, noripple(borrower)); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); // Scale the MPT asset so interest is interesting PrettyAsset const asset{mptt.issuanceID(), 10'000}; @@ -731,11 +709,10 @@ protected: 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::kDefaultPaymentInterval); - auto const total = loanParams.payTotal.value_or(LoanSet::kDefaultPaymentTotal); + auto const interval = loanParams.payInterval.value_or(LoanSet::kDEFAULT_PAYMENT_INTERVAL); + auto const total = loanParams.payTotal.value_or(LoanSet::kDEFAULT_PAYMENT_TOTAL); auto const feeRate = brokerParams.managementFeeRate; auto const props = computeLoanProperties( - env.current()->rules(), asset, principal, interest, @@ -759,8 +736,8 @@ protected: BEAST_EXPECT(!checkLoanGuards( asset, asset(loanParams.principalRequest).number(), - loanParams.interest.value_or(TenthBips32{}) != beast::kZero, - loanParams.payTotal.value_or(LoanSet::kDefaultPaymentTotal), + loanParams.interest.value_or(TenthBips32{}) != beast::kZERO, + loanParams.payTotal.value_or(LoanSet::kDEFAULT_PAYMENT_TOTAL), props, env.journal)); } @@ -867,7 +844,7 @@ protected: auto const shortage = totalNeeded - borrowerBalance.number(); - if (shortage > beast::kZero && (broker.asset.native() || issuer != borrower)) + if (shortage > beast::kZERO && (broker.asset.native() || issuer != borrower)) { env( pay((broker.asset.native() ? env.master : issuer), @@ -941,7 +918,6 @@ protected: state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); { auto const raw = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining, @@ -985,7 +961,6 @@ protected: std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining, @@ -996,7 +971,7 @@ protected: return; auto const totalSpent = (totalPaid.trackedValueDelta + totalFeesPaid + - (broker.asset.native() ? Number(baseFee) * totalPaymentsMade : kNumZero)); + (broker.asset.native() ? Number(baseFee) * totalPaymentsMade : kNUM_ZERO)); BEAST_EXPECT( env.balance(borrower, broker.asset).number() == borrowerInitialBalance - totalSpent); @@ -1015,7 +990,6 @@ protected: validateBorrowerBalance(); // Compute the expected principal amount auto const paymentComponents = xrpl::detail::computePaymentComponents( - env.current()->rules(), broker.asset.raw(), state.loanScale, state.totalValue, @@ -1036,7 +1010,6 @@ protected: paymentComponents.trackedManagementFeeDelta); xrpl::LoanState const nextTrueState = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining - 1, @@ -1080,13 +1053,13 @@ protected: Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::Final || - diff == beast::kZero || - (diff > beast::kZero && + diff == beast::kZERO || + (diff > beast::kZERO && ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); BEAST_EXPECT( - paymentComponents.trackedPrincipalDelta >= beast::kZero && + paymentComponents.trackedPrincipalDelta >= beast::kZERO && paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( paymentComponents.specialCase != xrpl::detail::PaymentSpecialCase::Final || @@ -1225,8 +1198,7 @@ protected: runLoan( AssetType assetType, BrokerParameters const& brokerParams, - LoanParameters const& loanParams, - FeatureBitset features) + LoanParameters const& loanParams) { using namespace jtx; @@ -1234,7 +1206,7 @@ protected: Account const lender("lender"); Account const borrower("borrower"); - Env env(*this, features); + Env env(*this, all_); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); @@ -1435,7 +1407,6 @@ protected: auto state = getCurrentState(env, broker, keylet, verifyLoanStatus); auto const loanProperties = computeLoanProperties( - env.current()->rules(), broker.asset.raw(), state.principalOutstanding, state.interestRate, @@ -1535,8 +1506,8 @@ protected: // Delete the loan // Either the borrower or the lender can delete the loan. Alternate // between who does it across tests. - static unsigned kDeleteCounter = 0; - auto const deleter = ((++kDeleteCounter % 2) != 0u) ? lender : borrower; + static unsigned kDELETE_COUNTER = 0; + auto const deleter = ((++kDELETE_COUNTER % 2) != 0u) ? lender : borrower; env(del(deleter, keylet.key)); env.close(); @@ -1655,13 +1626,13 @@ protected: // sfData: good length, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kData(std::string(kMaxDataPayloadLength, 'X')), + kDATA(std::string(kMAX_DATA_PAYLOAD_LENGTH, 'X')), loanSetFee, Ter(tefBAD_AUTH)); // sfData: too long env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kData(std::string(kMaxDataPayloadLength + 1, 'Y')), + kDATA(std::string(kMAX_DATA_PAYLOAD_LENGTH + 1, 'Y')), loanSetFee, Ter(temINVALID)); @@ -1669,148 +1640,148 @@ protected: // sfOverpaymentFee: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kOverpaymentFee(kMaxOverpaymentFee), + kOVERPAYMENT_FEE(kMAX_OVERPAYMENT_FEE), loanSetFee, Ter(tefBAD_AUTH)); // sfOverpaymentFee: too big env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kOverpaymentFee(kMaxOverpaymentFee + 1), + kOVERPAYMENT_FEE(kMAX_OVERPAYMENT_FEE + 1), loanSetFee, Ter(temINVALID)); // sfInterestRate: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kInterestRate(kMaxInterestRate), + kINTEREST_RATE(kMAX_INTEREST_RATE), loanSetFee, Ter(tefBAD_AUTH)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kInterestRate(TenthBips32(0)), + kINTEREST_RATE(TenthBips32(0)), loanSetFee, Ter(tefBAD_AUTH)); // sfInterestRate: too big env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kInterestRate(kMaxInterestRate + 1), + kINTEREST_RATE(kMAX_INTEREST_RATE + 1), loanSetFee, Ter(temINVALID)); // sfInterestRate: too small env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32(-1)), + kINTEREST_RATE(TenthBips32(-1)), loanSetFee, Ter(temINVALID)); // sfLateInterestRate: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kLateInterestRate(kMaxLateInterestRate), + kLATE_INTEREST_RATE(kMAX_LATE_INTEREST_RATE), loanSetFee, Ter(tefBAD_AUTH)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kLateInterestRate(TenthBips32(0)), + kLATE_INTEREST_RATE(TenthBips32(0)), loanSetFee, Ter(tefBAD_AUTH)); // sfLateInterestRate: too big env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kLateInterestRate(kMaxLateInterestRate + 1), + kLATE_INTEREST_RATE(kMAX_LATE_INTEREST_RATE + 1), loanSetFee, Ter(temINVALID)); // sfLateInterestRate: too small env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kLateInterestRate(TenthBips32(-1)), + kLATE_INTEREST_RATE(TenthBips32(-1)), loanSetFee, Ter(temINVALID)); // sfCloseInterestRate: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kCloseInterestRate(kMaxCloseInterestRate), + kCLOSE_INTEREST_RATE(kMAX_CLOSE_INTEREST_RATE), loanSetFee, Ter(tefBAD_AUTH)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kCloseInterestRate(TenthBips32(0)), + kCLOSE_INTEREST_RATE(TenthBips32(0)), loanSetFee, Ter(tefBAD_AUTH)); // sfCloseInterestRate: too big env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kCloseInterestRate(kMaxCloseInterestRate + 1), + kCLOSE_INTEREST_RATE(kMAX_CLOSE_INTEREST_RATE + 1), loanSetFee, Ter(temINVALID)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kCloseInterestRate(TenthBips32(-1)), + kCLOSE_INTEREST_RATE(TenthBips32(-1)), loanSetFee, Ter(temINVALID)); // sfOverpaymentInterestRate: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kOverpaymentInterestRate(kMaxOverpaymentInterestRate), + kOVERPAYMENT_INTEREST_RATE(kMAX_OVERPAYMENT_INTEREST_RATE), loanSetFee, Ter(tefBAD_AUTH)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kOverpaymentInterestRate(TenthBips32(0)), + kOVERPAYMENT_INTEREST_RATE(TenthBips32(0)), loanSetFee, Ter(tefBAD_AUTH)); // sfOverpaymentInterestRate: too big env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kOverpaymentInterestRate(kMaxOverpaymentInterestRate + 1), + kOVERPAYMENT_INTEREST_RATE(kMAX_OVERPAYMENT_INTEREST_RATE + 1), loanSetFee, Ter(temINVALID)); env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kOverpaymentInterestRate(TenthBips32(-1)), + kOVERPAYMENT_INTEREST_RATE(TenthBips32(-1)), loanSetFee, Ter(temINVALID)); // sfPaymentTotal: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kPaymentTotal(LoanSet::kMinPaymentTotal), + kPAYMENT_TOTAL(LoanSet::kMIN_PAYMENT_TOTAL), loanSetFee, Ter(tefBAD_AUTH)); // sfPaymentTotal: too small (there is no max) env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kPaymentTotal(LoanSet::kMinPaymentTotal - 1), + kPAYMENT_TOTAL(LoanSet::kMIN_PAYMENT_TOTAL - 1), loanSetFee, Ter(temINVALID)); // sfPaymentInterval: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kPaymentInterval(LoanSet::kMinPaymentInterval), + kPAYMENT_INTERVAL(LoanSet::kMIN_PAYMENT_INTERVAL), loanSetFee, Ter(tefBAD_AUTH)); // sfPaymentInterval: too small (there is no max) env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kPaymentInterval(LoanSet::kMinPaymentInterval - 1), + kPAYMENT_INTERVAL(LoanSet::kMIN_PAYMENT_INTERVAL - 1), loanSetFee, Ter(temINVALID)); // sfGracePeriod: good value, bad account env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, borrower), - kPaymentInterval(LoanSet::kMinPaymentInterval * 2), - kGracePeriod(LoanSet::kMinPaymentInterval * 2), + kPAYMENT_INTERVAL(LoanSet::kMIN_PAYMENT_INTERVAL * 2), + kGRACE_PERIOD(LoanSet::kMIN_PAYMENT_INTERVAL * 2), loanSetFee, Ter(tefBAD_AUTH)); // sfGracePeriod: larger than paymentInterval env(set(evan, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), - kPaymentInterval(LoanSet::kMinPaymentInterval * 2), - kGracePeriod(LoanSet::kMinPaymentInterval * 3), + kPAYMENT_INTERVAL(LoanSet::kMIN_PAYMENT_INTERVAL * 2), + kGRACE_PERIOD(LoanSet::kMIN_PAYMENT_INTERVAL * 3), loanSetFee, Ter(temINVALID)); @@ -1822,30 +1793,30 @@ protected: env(signers(lender, 2, {{evan, 1}, {borrower, 1}})); env(signers(borrower, 2, {{evan, 1}, {lender, 1}})); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(evan, lender), Msig(sfCounterpartySignature, evan, borrower), Fee(env.current()->fees().base * 5 - 1), Ter(telINSUF_FEE_P)); // Bad multisign signatures for borrower (Account) env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(alice, issuer), Msig(sfCounterpartySignature, evan, borrower), Fee(env.current()->fees().base * 5), Ter(tefBAD_SIGNATURE)); // Bad multisign signatures for issuer (Counterparty) env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(evan, lender), Msig(sfCounterpartySignature, alice, issuer), Fee(env.current()->fees().base * 5 - 1), Ter(tefBAD_SIGNATURE)); - env(signers(lender, kNone)); - env(signers(borrower, kNone)); + env(signers(lender, kNONE)); + env(signers(borrower, kNONE)); // multisign sufficient fee, but no signers set up env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(evan, lender), Msig(sfCounterpartySignature, evan, borrower), Fee(env.current()->fees().base * 5), @@ -1858,7 +1829,7 @@ protected: Ter(tefBAD_AUTH)); // not the broker owner, counterparty is borrower env(set(evan, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), loanSetFee, Ter(tecNO_PERMISSION)); @@ -1869,13 +1840,13 @@ protected: Ter(temBAD_SIGNER)); // not a LoanBroker object, counterparty is valid env(set(lender, badKeylet.key, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), loanSetFee, Ter(tecNO_ENTRY)); // borrower doesn't exist env(set(lender, broker.brokerID, principalRequest), - kCounterparty(alice), + kCOUNTERPARTY(alice), Sig(sfCounterpartySignature, alice), loanSetFee, Ter(terNO_ACCOUNT)); @@ -2163,25 +2134,24 @@ protected: // If the loan does not allow overpayments, send a payment that // tries to make an overpayment. Do not include `txFlags`, so we // don't end up duplicating the next test transaction. - // - // fixCleanup3_1_3 gates tfLoanOverpayment as a valid flag: - // with fix on → preflight passes, apply returns tecNO_PERMISSION; - // with fix off → preflight rejects the flag, returns temINVALID_FLAG. - bool const hasFix313 = env.current()->rules().enabled(fixCleanup3_1_3); - STAmount const overpayAmount{broker.asset, state.periodicPayment * Number{15, -1}}; - XRPAmount const overpayFee{ - baseFee * (Number{15, -1} / kLoanPaymentsPerFeeIncrement + 1)}; - env(pay(borrower, loanKeylet.key, overpayAmount, tfLoanOverpayment), - Fee(overpayFee), - Ter(hasFix313 ? TER{tecNO_PERMISSION} : TER{temINVALID_FLAG})); + env(pay(borrower, + loanKeylet.key, + STAmount{broker.asset, state.periodicPayment * Number{15, -1}}, + tfLoanOverpayment), + Fee(XRPAmount{ + baseFee * (Number{15, -1} / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}), + Ter(tecNO_PERMISSION)); - if (hasFix313) { - env.disableFeature(fixCleanup3_1_3); - env(pay(borrower, loanKeylet.key, overpayAmount, tfLoanOverpayment), - Fee(overpayFee), + env.disableFeature(fixSecurity3_1_3); + env(pay(borrower, + loanKeylet.key, + STAmount{broker.asset, state.periodicPayment * Number{15, -1}}, + tfLoanOverpayment), + Fee(XRPAmount{ + baseFee * (Number{15, -1} / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}), Ter(temINVALID_FLAG)); - env.enableFeature(fixCleanup3_1_3); + env.enableFeature(fixSecurity3_1_3); } } // Try to send a payment marked as multiple mutually exclusive @@ -2232,7 +2202,7 @@ protected: XRPAmount const badFee{ baseFee * (borrowerBalanceBeforePayment.number() * 2 / state.periodicPayment / - kLoanPaymentsPerFeeIncrement + + kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; env(pay(borrower, loanKeylet.key, @@ -2241,7 +2211,7 @@ protected: Fee(badFee), Ter(tecINSUFFICIENT_FUNDS)); - XRPAmount const goodFee{baseFee * (numPayments / kLoanPaymentsPerFeeIncrement + 1)}; + XRPAmount const goodFee{baseFee * (numPayments / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; env(pay(borrower, loanKeylet.key, transactionAmount, txFlags), Fee(goodFee)); env.close(); @@ -2291,7 +2261,7 @@ 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) / kSecondsInYear; + auto const periodicRate = interval * Number(12, -2) / kSECONDS_IN_YEAR; BEAST_EXPECT( periodicRate == Number(2283105022831050228ULL, -24, Number::Normalized{})); STAmount const principalOutstanding{broker.asset, state.principalOutstanding}; @@ -2531,7 +2501,7 @@ 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) / kSecondsInYear; + auto const periodicRate = interval * Number(12, -2) / kSECONDS_IN_YEAR; BEAST_EXPECT( periodicRate == Number(2283105022831050228, -24, Number::Normalized{})); STAmount const roundedPeriodicPayment{ @@ -2570,7 +2540,6 @@ protected: { auto const raw = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining, @@ -2608,7 +2577,6 @@ protected: std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining, @@ -2618,7 +2586,6 @@ protected: { // Compute the expected principal amount auto const paymentComponents = xrpl::detail::computePaymentComponents( - env.current()->rules(), broker.asset.raw(), state.loanScale, state.totalValue, @@ -2636,7 +2603,6 @@ protected: ", periodic payment: " + to_string(roundedPeriodicPayment)); xrpl::LoanState const nextTrueState = computeTheoreticalLoanState( - env.current()->rules(), state.periodicPayment, periodicRate, state.paymentRemaining - 1, @@ -2671,8 +2637,8 @@ protected: Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::Final || - diff == beast::kZero || - (diff > beast::kZero && + diff == beast::kZERO || + (diff > beast::kZERO && ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); @@ -2698,7 +2664,7 @@ protected: state.loanScale, Number::RoundingMode::Upward)); BEAST_EXPECT( - paymentComponents.trackedPrincipalDelta >= beast::kZero && + paymentComponents.trackedPrincipalDelta >= beast::kZERO && paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( paymentComponents.specialCase != xrpl::detail::PaymentSpecialCase::Final || @@ -2831,8 +2797,8 @@ protected: pseudoAcct, tfLoanOverpayment, [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { - // Estimate optimal values for kLoanPaymentsPerFeeIncrement and - // kLoanMaximumPaymentsPerTransaction. + // Estimate optimal values for loanPaymentsPerFeeIncrement and + // loanMaximumPaymentsPerTransaction. using namespace loan; auto const state = getCurrentState(env, broker, verifyLoanStatus.keylet); @@ -2850,7 +2816,7 @@ protected: // Make all but the final payment auto const numPayments = (state.paymentRemaining - 2); STAmount const bigPayment{broker.asset, totalDue * numPayments}; - XRPAmount const bigFee{baseFee * (numPayments / kLoanPaymentsPerFeeIncrement + 1)}; + XRPAmount const bigFee{baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; time("ten payments", [&]() { env(pay(borrower, loanKeylet.key, bigPayment), Fee(bigFee)); }); @@ -2923,7 +2889,7 @@ protected: } void - testLoanSet(FeatureBitset features) + testLoanSet() { using namespace jtx; @@ -2942,7 +2908,7 @@ protected: std::function mptTest, std::function iouTest, CaseArgs args = {}) { - Env env(*this, features); + Env env(*this, all_); env.fund(XRP(args.initialXRP), issuer, lender, borrower); env.close(); if (args.requireAuth) @@ -2953,12 +2919,12 @@ protected: // We need two different asset types, MPT and IOU. Prepare MPT // first - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; - auto const kNone = LedgerSpecificFlags(0); + auto const kNONE = LedgerSpecificFlags(0); mptt.create( {.flags = tfMPTCanTransfer | tfMPTCanLock | - (args.requireAuth ? tfMPTRequireAuth : kNone)}); + (args.requireAuth ? tfMPTRequireAuth : kNONE)}); env.close(); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = lender}); @@ -3019,13 +2985,13 @@ protected: testcase("MPT issuer is borrower, issuer submits"); env(set(issuer, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); testcase("MPT issuer is borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(issuer), + kCOUNTERPARTY(issuer), Sig(sfCounterpartySignature, issuer), Fee(env.current()->fees().base * 5)); }, @@ -3035,13 +3001,13 @@ protected: testcase("IOU issuer is borrower, issuer submits"); env(set(issuer, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); testcase("IOU issuer is borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(issuer), + kCOUNTERPARTY(issuer), Sig(sfCounterpartySignature, issuer), Fee(env.current()->fees().base * 5)); }, @@ -3054,14 +3020,14 @@ protected: testcase("MPT unauthorized borrower, borrower submits"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); testcase("MPT unauthorized borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); @@ -3072,14 +3038,14 @@ protected: testcase("IOU unauthorized borrower, borrower submits"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); testcase("IOU unauthorized borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); @@ -3089,8 +3055,8 @@ protected: auto const [acctReserve, incReserve] = [this]() -> std::pair { Env const env{*this, testableAmendments()}; return { - env.current()->fees().accountReserve(0).drops() / kDropsPerXrp.drops(), - env.current()->fees().increment.drops() / kDropsPerXrp.drops()}; + env.current()->fees().accountReserve(0).drops() / kDROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / kDROPS_PER_XRP.drops()}; }(); testCase( @@ -3114,7 +3080,7 @@ protected: // Cannot create loan, not enough reserve to create MPToken env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecINSUFFICIENT_RESERVE}); @@ -3124,7 +3090,7 @@ protected: env(pay(issuer, borrower, XRP(incReserve))); env.close(); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); env.close(); @@ -3160,7 +3126,7 @@ protected: // Cannot create loan, not enough reserve to create trust line env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_LINE_INSUF_RESERVE}); @@ -3170,7 +3136,7 @@ protected: env(pay(issuer, borrower, XRP(incReserve))); env.close(); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); env.close(); @@ -3207,8 +3173,8 @@ protected: // Cannot create loan, not enough reserve to create MPToken env(set(borrower, broker.brokerID, principalRequest), - kLoanOriginationFee(broker.asset(1).value()), - kCounterparty(lender), + kLOAN_ORIGINATION_FEE(broker.asset(1).value()), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecINSUFFICIENT_RESERVE}); @@ -3218,8 +3184,8 @@ protected: env(pay(issuer, lender, XRP(incReserve))); env.close(); env(set(borrower, broker.brokerID, principalRequest), - kLoanOriginationFee(broker.asset(1).value()), - kCounterparty(lender), + kLOAN_ORIGINATION_FEE(broker.asset(1).value()), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); env.close(); @@ -3258,8 +3224,8 @@ protected: // Cannot create loan, not enough reserve to create trust line env(set(borrower, broker.brokerID, principalRequest), - kLoanOriginationFee(broker.asset(1).value()), - kCounterparty(lender), + kLOAN_ORIGINATION_FEE(broker.asset(1).value()), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_LINE_INSUF_RESERVE}); @@ -3269,8 +3235,8 @@ protected: env(pay(issuer, lender, XRP(incReserve))); env.close(); env(set(borrower, broker.brokerID, principalRequest), - kLoanOriginationFee(broker.asset(1).value()), - kCounterparty(lender), + kLOAN_ORIGINATION_FEE(broker.asset(1).value()), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); env.close(); @@ -3301,8 +3267,8 @@ protected: // Cannot create loan, lender not authorized to receive fee env(set(borrower, broker.brokerID, principalRequest), - kLoanOriginationFee(broker.asset(1).value()), - kCounterparty(lender), + kLOAN_ORIGINATION_FEE(broker.asset(1).value()), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); @@ -3310,7 +3276,7 @@ protected: // Cannot create loan, even without an origination fee env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter{tecNO_AUTH}); @@ -3330,7 +3296,7 @@ protected: testcase("MPT authorized borrower, borrower submits"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); }, @@ -3340,7 +3306,7 @@ protected: testcase("IOU authorized borrower, borrower submits"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5)); }, @@ -3353,7 +3319,7 @@ protected: testcase("MPT authorized borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), Fee(env.current()->fees().base * 5)); }, @@ -3363,7 +3329,7 @@ protected: testcase("IOU authorized borrower, lender submits"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), Fee(env.current()->fees().base * 5)); }, @@ -3387,7 +3353,7 @@ protected: "MPT authorized borrower, borrower submits, lender " "multisign"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(sfCounterpartySignature, alice, bella), Fee(env.current()->fees().base * 5)); }, @@ -3400,7 +3366,7 @@ protected: "IOU authorized borrower, borrower submits, lender " "multisign"); env(set(borrower, broker.brokerID, principalRequest), - kCounterparty(lender), + kCOUNTERPARTY(lender), Msig(sfCounterpartySignature, alice, bella), Fee(env.current()->fees().base * 5)); }, @@ -3416,7 +3382,7 @@ protected: "MPT authorized borrower, lender submits, borrower " "multisign"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Msig(sfCounterpartySignature, alice, bella), Fee(env.current()->fees().base * 5)); }, @@ -3429,7 +3395,7 @@ protected: "IOU authorized borrower, lender submits, borrower " "multisign"); env(set(lender, broker.brokerID, principalRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Msig(sfCounterpartySignature, alice, bella), Fee(env.current()->fees().base * 5)); }, @@ -3447,8 +3413,8 @@ protected: testcase("Vault at maximum value"); env(set(issuer, broker.brokerID, principalRequest), - kCounterparty(lender), - kInterestRate(TenthBips32(10'000)), + kCOUNTERPARTY(lender), + kINTEREST_RATE(TenthBips32(10'000)), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), Ter(tecLIMIT_EXCEEDED)); @@ -3468,26 +3434,26 @@ protected: testcase("Vault maximum value exceeded"); env(set(issuer, broker.brokerID, principalRequest), - kCounterparty(lender), - kInterestRate(TenthBips32(100'000)), + kCOUNTERPARTY(lender), + kINTEREST_RATE(TenthBips32(100'000)), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 5), - kPaymentTotal(2), - kPaymentInterval(3600 * 24), + kPAYMENT_TOTAL(2), + kPAYMENT_INTERVAL(3600 * 24), Ter(tecLIMIT_EXCEEDED)); }, nullptr); } void - testLifecycle(FeatureBitset features) + testLifecycle() { testcase("Lifecycle"); using namespace jtx; // Create 3 loan brokers: one for XRP, one for an IOU, and one for // an MPT. That'll require three corresponding SAVs. - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; // For simplicity, lender will be the sole actor for the vault & @@ -3517,7 +3483,7 @@ protected: env(pay(issuer, borrower, iouAsset(10'000))); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; 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}; @@ -3574,7 +3540,7 @@ protected: } void - testSelfLoan(FeatureBitset features) + testSelfLoan() { testcase << "Self Loan"; @@ -3582,7 +3548,7 @@ protected: using namespace std::chrono_literals; // Create 3 loan brokers: one for XRP, one for an IOU, and one for // an MPT. That'll require three corresponding SAVs. - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; // For simplicity, lender will be the sole actor for the vault & @@ -3613,7 +3579,7 @@ protected: // Adding an empty counterparty signature object also fails, but // at the RPC level. - createJson = env.json(createJson, Json(sfCounterpartySignature, json::ValueType::Object)); + 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)) @@ -3631,7 +3597,7 @@ protected: } // Copy the transaction signature into the counterparty signature. - json::Value counterpartyJson{json::ValueType::Object}; + json::Value counterpartyJson{json::ObjectValue}; counterpartyJson[sfTxnSignature] = createJson[sfTxnSignature]; counterpartyJson[sfSigningPubKey] = createJson[sfSigningPubKey]; if (!BEAST_EXPECT(!createJson.isMember(jss::Signers))) @@ -3663,7 +3629,7 @@ protected: } } auto const loanID = [&]() { - json::Value params(json::ValueType::Object); + 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)); @@ -3709,18 +3675,18 @@ protected: } void - testBatchBypassCounterparty(FeatureBitset features) + testBatchBypassCounterparty() { // From FIND-001 testcase << "Batch Bypass Counterparty"; bool const lendingBatchEnabled = !std::ranges::any_of( - Batch::kDisabledTxTypes, + Batch::kDISABLED_TX_TYPES, [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); using namespace jtx; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all_); Account const lender{"lender"}; Account const borrower{"borrower"}; @@ -3740,9 +3706,9 @@ protected: auto forgedLoanSet = set(borrower, broker.brokerID, principalRequest, 0); - json::Value randomData{json::ValueType::Object}; + json::Value randomData{json::ObjectValue}; randomData[jss::SigningPubKey] = json::StaticString{"2600"}; - json::Value sigObject{json::ValueType::Object}; + json::Value sigObject{json::ObjectValue}; sigObject[jss::SigningPubKey] = strHex(lender.pk().slice()); Serializer ss; ss.add32(HashPrefix::TxSign); @@ -3766,7 +3732,7 @@ protected: // ? Check that the loan was NOT created { - json::Value params(json::ValueType::Object); + 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)); @@ -3776,14 +3742,14 @@ protected: } void - testWrongMaxDebtBehavior(FeatureBitset features) + testWrongMaxDebtBehavior() { // From FIND-003 testcase << "Wrong Max Debt Behavior"; using namespace jtx; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -3809,7 +3775,7 @@ protected: auto createJson = env.json(set(lender, broker.brokerID, principalRequest), Fee(loanSetFee)); - json::Value counterpartyJson{json::ValueType::Object}; + json::Value counterpartyJson{json::ObjectValue}; counterpartyJson[sfTxnSignature] = createJson[sfTxnSignature]; counterpartyJson[sfSigningPubKey] = createJson[sfSigningPubKey]; if (!BEAST_EXPECT(!createJson.isMember(jss::Signers))) @@ -3822,7 +3788,7 @@ protected: } void - testLoanPayComputePeriodicPaymentValidRateInvariant(FeatureBitset features) + testLoanPayComputePeriodicPaymentValidRateInvariant() { // From FIND-012 testcase << "LoanPay xrpl::detail::computePeriodicPayment : " @@ -3830,7 +3796,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -3854,9 +3820,9 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - kLoanServiceFee(serviceFee), - kPaymentTotal(numPayments), - Json(sfCounterpartySignature, json::ValueType::Object)); + kLOAN_SERVICE_FEE(serviceFee), + kPAYMENT_TOTAL(numPayments), + Json(sfCounterpartySignature, json::ObjectValue)); createJson["CloseInterestRate"] = 55374; createJson["ClosePaymentFee"] = "3825205248"; @@ -3890,7 +3856,7 @@ protected: } void - testRPC(FeatureBitset features) + testRPC() { // This will expand as more test cases are added. Some functionality // is tested in other test functions. @@ -3898,7 +3864,7 @@ protected: using namespace jtx; - Env env(*this, features); + Env env(*this, all_); auto lowerFee = [&]() { // Run the local fee back down. @@ -3925,12 +3891,12 @@ protected: { testcase("RPC AccountSet"); - json::Value txJson{json::ValueType::Object}; + json::Value txJson{json::ObjectValue}; txJson[sfTransactionType] = "AccountSet"; txJson[sfAccount] = borrower.human(); auto const signParams = [&]() { - json::Value signParams{json::ValueType::Object}; + json::Value signParams{json::ObjectValue}; signParams[jss::passphrase] = borrowerPass; signParams[jss::key_type] = "ed25519"; signParams[jss::tx_json] = txJson; @@ -3953,18 +3919,18 @@ protected: jSubmit[jss::result][jss::engine_result].asString() == "tesSUCCESS"); lowerFee(); - env(jtx.jv, Sig(kNone), Seq(kNone), Fee(kNone), Ter(tefPAST_SEQ)); + env(jtx.jv, Sig(kNONE), Seq(kNONE), Fee(kNONE), Ter(tefPAST_SEQ)); } { testcase("RPC LoanSet - illegal signature_target"); - json::Value txJson{json::ValueType::Object}; + json::Value txJson{json::ObjectValue}; txJson[sfTransactionType] = "AccountSet"; txJson[sfAccount] = borrower.human(); auto const borrowerSignParams = [&]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::passphrase] = borrowerPass; params[jss::key_type] = "ed25519"; params[jss::signature_target] = "Destination"; @@ -3982,7 +3948,7 @@ protected: { testcase("RPC LoanSet - sign and submit borrower initiated"); // 1. Borrower creates the transaction - json::Value txJson{json::ValueType::Object}; + json::Value txJson{json::ObjectValue}; txJson[sfTransactionType] = "LoanSet"; txJson[sfAccount] = borrower.human(); txJson[sfCounterparty] = lender.human(); @@ -3999,7 +3965,7 @@ protected: // 2. Borrower signs the transaction auto const borrowerSignParams = [&]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::passphrase] = borrowerPass; params[jss::key_type] = "ed25519"; params[jss::tx_json] = txJson; @@ -4031,7 +3997,7 @@ protected: // 3. Borrower sends the signed transaction to the lender // 4. Lender signs the transaction auto const lenderSignParams = [&]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::passphrase] = lenderPass; params[jss::key_type] = "ed25519"; params[jss::signature_target] = "CounterpartySignature"; @@ -4089,7 +4055,7 @@ protected: { testcase("RPC LoanSet - sign and submit lender initiated"); // 1. Lender creates the transaction - json::Value txJson{json::ValueType::Object}; + json::Value txJson{json::ObjectValue}; txJson[sfTransactionType] = "LoanSet"; txJson[sfAccount] = lender.human(); txJson[sfCounterparty] = borrower.human(); @@ -4106,7 +4072,7 @@ protected: // 2. Lender signs the transaction auto const lenderSignParams = [&]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::passphrase] = lenderPass; params[jss::key_type] = "ed25519"; params[jss::tx_json] = txJson; @@ -4137,7 +4103,7 @@ protected: // 3. Lender sends the signed transaction to the Borrower // 4. Borrower signs the transaction auto const borrowerSignParams = [&]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::passphrase] = borrowerPass; params[jss::key_type] = "ed25519"; params[jss::signature_target] = "CounterpartySignature"; @@ -4240,8 +4206,8 @@ protected: env(set(borrower, brokerInfo.brokerID, 10'000), Sig(sfCounterpartySignature, broker), - kLoanServiceFee(iou(100).value()), - kPaymentInterval(100), + kLOAN_SERVICE_FEE(iou(100).value()), + kPAYMENT_INTERVAL(100), Fee(XRP(100))); env.close(); @@ -4292,9 +4258,9 @@ protected: env.fund(XRP(1'000), issuer, lender); - static constexpr std::int64_t kIssuerBalance = 10'000'000; + std::int64_t constexpr kISSUER_BALANCE = 10'000'000; MPTTester const asset( - {.env = env, .issuer = issuer, .holders = {lender}, .pay = kIssuerBalance}); + {.env = env, .issuer = issuer, .holders = {lender}, .pay = kISSUER_BALANCE}); BrokerParameters const brokerParams{ .debtMax = 200, @@ -4307,13 +4273,13 @@ protected: // Issuer should not create MPToken BEAST_EXPECT(!env.le(keylet::mptoken(asset.issuanceID(), issuer))); // Issuer "borrowed" 200, OutstandingAmount decreased by 200 - BEAST_EXPECT(env.balance(issuer, asset) == asset(-kIssuerBalance + 200)); + BEAST_EXPECT(env.balance(issuer, asset) == asset(-kISSUER_BALANCE + 200)); // Pay Loan auto const loanKeylet = keylet::loan(broker.brokerID, 1); env(pay(borrower, loanKeylet.key, asset(200))); env.close(); // Issuer "re-payed" 200, OutstandingAmount increased by 200 - BEAST_EXPECT(env.balance(issuer, asset) == asset(-kIssuerBalance)); + BEAST_EXPECT(env.balance(issuer, asset) == asset(-kISSUER_BALANCE)); } void @@ -4329,7 +4295,7 @@ protected: Env env(*this); env.fund(XRP(1'000), alice); env.close(); - env(del(alice, beast::kZero), Ter(temINVALID)); + env(del(alice, beast::kZERO), Ter(temINVALID)); } } @@ -4346,7 +4312,7 @@ protected: Env env(*this); env.fund(XRP(1'000), alice); env.close(); - env(manage(alice, beast::kZero, tfLoanDefault), Ter(temINVALID)); + env(manage(alice, beast::kZERO, tfLoanDefault), Ter(temINVALID)); } } @@ -4462,22 +4428,22 @@ protected: // zero grace period env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), Sig(sfCounterpartySignature, lender), - kGracePeriod(0), + kGRACE_PERIOD(0), loanSetFee, Ter(temINVALID)); // grace period less than default minimum env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), Sig(sfCounterpartySignature, lender), - kGracePeriod(LoanSet::kDefaultGracePeriod - 1), + kGRACE_PERIOD(LoanSet::kDEFAULT_GRACE_PERIOD - 1), loanSetFee, Ter(temINVALID)); // grace period greater than payment interval env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), Sig(sfCounterpartySignature, lender), - kPaymentInterval(120), - kGracePeriod(121), + kPAYMENT_INTERVAL(120), + kGRACE_PERIOD(121), loanSetFee, Ter(temINVALID)); } @@ -4569,7 +4535,7 @@ protected: } void - testAccountSendMptMinAmountInvariant(FeatureBitset features) + testAccountSendMptMinAmountInvariant() { // (From FIND-006) testcase << "LoanSet trigger xrpl::accountSendMPT : minimum amount " @@ -4577,7 +4543,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -4586,7 +4552,7 @@ protected: env.fund(XRP(1'000'000), issuer, lender, borrower); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = lender}); @@ -4605,7 +4571,7 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); + Json(sfCounterpartySignature, json::ObjectValue)); createJson["CloseInterestRate"] = 76671; createJson["ClosePaymentFee"] = "2061925410"; @@ -4629,7 +4595,7 @@ protected: } void - testLoanPayDebtDecreaseInvariant(FeatureBitset features) + testLoanPayDebtDecreaseInvariant() { // From FIND-007 testcase << "LoanPay xrpl::LoanPay::doApply : debtDecrease " @@ -4638,7 +4604,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; using namespace Lending; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -4669,7 +4635,7 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); + Json(sfCounterpartySignature, json::ObjectValue)); createJson["ClosePaymentFee"] = "0"; createJson["GracePeriod"] = 60; @@ -4705,7 +4671,7 @@ protected: Number const payment{3'269'349'176'470'588, -12}; XRPAmount const payFee{ baseFee * - ((payment / originalState.periodicPayment) / kLoanPaymentsPerFeeIncrement + 1)}; + ((payment / originalState.periodicPayment) / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, payment}), Fee(payFee)); BEAST_EXPECT(to_string(payment) == "3269.349176470588"); @@ -4722,14 +4688,14 @@ protected: } void - testLoanPayComputePeriodicPaymentValidTotalInterestInvariant(FeatureBitset features) + testLoanPayComputePeriodicPaymentValidTotalInterestInvariant() { // From FIND-010 testcase << "xrpl::loanComputePaymentParts : valid total interest"; using namespace jtx; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -4759,7 +4725,7 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); + Json(sfCounterpartySignature, json::ObjectValue)); createJson["CloseInterestRate"] = 47299; createJson["ClosePaymentFee"] = "3985819770"; @@ -4787,17 +4753,15 @@ protected: } void - testDosLoanPay(FeatureBitset features) + testDosLoanPay() { - bool const feeCapped = features[fixCleanup3_1_3]; - // From FIND-005 - testcase << "DoS LoanPay: fee calculation " << (feeCapped ? "capped" : "uncapped"); + testcase << "DoS LoanPay"; using namespace jtx; using namespace std::chrono_literals; using namespace Lending; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -4806,8 +4770,6 @@ protected: env.fund(XRP(1'000'000), issuer, lender, borrower); env.close(); - BEAST_EXPECT(feeCapped == env.current()->rules().enabled(fixCleanup3_1_3)); - PrettyAsset const iouAsset = issuer[iouCurrency_]; env(trust(lender, iouAsset(100'000'000))); env(trust(borrower, iouAsset(100'000'000))); @@ -4820,116 +4782,56 @@ protected: using namespace loan; auto const loanSetFee = Fee(env.current()->fees().base * 2); - Number const principalRequest{3959'37, -2}; + Number const principalRequest{1, 3}; auto const baseFee = env.current()->fees().base; - auto const createJson = env.json( + auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object), - kClosePaymentFee(0), - kGracePeriod(60), - kInterestRate(TenthBips32(20930)), - kLateInterestRate(TenthBips32(77049)), - kLatePaymentFee(0), - kLoanServiceFee(0), - kOverpaymentFee(TenthBips32(7)), - kOverpaymentInterestRate(TenthBips32(66653)), - kPaymentInterval(60), - kPaymentTotal(3239184)); + Json(sfCounterpartySignature, json::ObjectValue)); + + createJson["ClosePaymentFee"] = "0"; + createJson["GracePeriod"] = 60; + createJson["InterestRate"] = 20930; + createJson["LateInterestRate"] = 77049; + createJson["LatePaymentFee"] = "0"; + createJson["LoanServiceFee"] = "0"; + createJson["OverpaymentFee"] = 7; + createJson["OverpaymentInterestRate"] = 66653; + createJson["PaymentInterval"] = 60; + createJson["PaymentTotal"] = 3239184; + createJson["PrincipalRequested"] = "3959.37"; - // There are enough payments due on this loan that it only needs to be - // created once, and can be paid on multiple times. Just don't create a - // gazillion test cases. auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); - env(createJson, Sig(sfCounterpartySignature, lender)); + createJson = env.json(createJson, Sig(sfCounterpartySignature, lender)); + env(createJson, Ter(tesSUCCESS)); env.close(); - auto const roundedPayment = [&]() { - auto const stateBefore = getCurrentState(env, broker, keylet); - BEAST_EXPECT(stateBefore.paymentRemaining == 3239184); - BEAST_EXPECT(stateBefore.paymentRemaining > kLoanMaximumPaymentsPerTransaction); + auto const stateBefore = getCurrentState(env, broker, keylet); + BEAST_EXPECT(stateBefore.paymentRemaining == 3239184); + BEAST_EXPECT(stateBefore.paymentRemaining > kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION); - return roundToAsset( - iouAsset, - stateBefore.periodicPayment, - stateBefore.loanScale, - Number::RoundingMode::Upward); - }(); + 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 / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; + env(loanPayTx, Ter(tesSUCCESS), Fee(payFee)); + env.close(); - auto test = [&](int const payFactor, - int const feeFactor, - TER const expectedTer = tesSUCCESS) { - auto const stateBefore = getCurrentState(env, broker, keylet); - BEAST_EXPECT(stateBefore.paymentRemaining <= 3239184); - BEAST_EXPECT(stateBefore.paymentRemaining > kLoanMaximumPaymentsPerTransaction); - - Number const amount = roundedPayment * payFactor; - auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, amount})); - XRPAmount const payFee{baseFee * feeFactor}; - env(loanPayTx, Ter(expectedTer), Fee(payFee)); - env.close(); - auto const expectedChange = isTesSuccess(expectedTer) - ? std::min(kLoanMaximumPaymentsPerTransaction, payFactor) - : 0; - - auto const stateAfter = getCurrentState(env, broker, keylet); - BEAST_EXPECT( - stateAfter.paymentRemaining == stateBefore.paymentRemaining - expectedChange); - }; - - static constexpr std::int64_t kMaxFeeIncrements = - kLoanMaximumPaymentsPerTransaction / kLoanPaymentsPerFeeIncrement; - - TER const failWithoutFix = feeCapped ? (TER)tesSUCCESS : (TER)telINSUF_FEE_P; - - // * Amount well above threshold -> capped fee - // The original test case - way over the limit - more fee is always ok - test(1819878, 363976); - // The capped fee is only sufficient if the amendment is enabled. - test(1819878, kMaxFeeIncrements, failWithoutFix); - - // * Amount exactly at threshold -> capped fee - test(kLoanMaximumPaymentsPerTransaction, kMaxFeeIncrements); - // More fee is always ok - test(kLoanMaximumPaymentsPerTransaction, kMaxFeeIncrements + 10); - - // * Amount below threshold -> normal calculation - test(1, 1); - test(kLoanPaymentsPerFeeIncrement * 2, 2); - test(0, 0, temBAD_AMOUNT); - test(0, 1, temBAD_AMOUNT); - // Fee difference rounds evenly - test( - kLoanMaximumPaymentsPerTransaction - 10, - ((kLoanMaximumPaymentsPerTransaction - 10) / kLoanPaymentsPerFeeIncrement) - 1, - telINSUF_FEE_P); - test( - kLoanMaximumPaymentsPerTransaction - 10, - ((kLoanMaximumPaymentsPerTransaction - 10) / kLoanPaymentsPerFeeIncrement)); - // More fee is always ok - test( - kLoanMaximumPaymentsPerTransaction - 10, - ((kLoanMaximumPaymentsPerTransaction - 10) / kLoanPaymentsPerFeeIncrement) + 3); - // Fee rounds up - for (int under = 1; under < kLoanPaymentsPerFeeIncrement; ++under) - { - test(kLoanMaximumPaymentsPerTransaction - under, kMaxFeeIncrements - 1, telINSUF_FEE_P); - test(kLoanMaximumPaymentsPerTransaction - under, kMaxFeeIncrements); - } - // Only when you get one less fee increment can you pay less - test( - kLoanMaximumPaymentsPerTransaction - kLoanPaymentsPerFeeIncrement, - kMaxFeeIncrements - 1); - // And again, more fee is always ok. - test(kLoanMaximumPaymentsPerTransaction - kLoanPaymentsPerFeeIncrement, kMaxFeeIncrements); + auto const stateAfter = getCurrentState(env, broker, keylet); + BEAST_EXPECT( + stateAfter.paymentRemaining == + stateBefore.paymentRemaining - kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION); } void - testLoanPayComputePeriodicPaymentValidTotalPrincipalPaidInvariant(FeatureBitset features) + testLoanPayComputePeriodicPaymentValidTotalPrincipalPaidInvariant() { // From FIND-009 testcase << "xrpl::loanComputePaymentParts : totalPrincipalPaid " @@ -4938,7 +4840,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; using namespace Lending; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -4968,7 +4870,7 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); + Json(sfCounterpartySignature, json::ObjectValue)); createJson["ClosePaymentFee"] = "0"; createJson["InterestRate"] = 24346; @@ -4998,7 +4900,7 @@ protected: BEAST_EXPECT(to_string(amount) == "3074.745058823529"); XRPAmount const payFee{ baseFee * - (amount / stateBefore.periodicPayment / kLoanPaymentsPerFeeIncrement + 1)}; + (amount / stateBefore.periodicPayment / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, Fee(payFee), Ter(tesSUCCESS)); env.close(); @@ -5010,7 +4912,7 @@ protected: BEAST_EXPECT(to_string(amount) == "6732.118170944051"); XRPAmount const payFee{ baseFee * - (amount / stateBefore.periodicPayment / kLoanPaymentsPerFeeIncrement + 1)}; + (amount / stateBefore.periodicPayment / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, Fee(payFee), Ter(tesSUCCESS)); env.close(); @@ -5031,7 +4933,7 @@ protected: } void - testLoanPayComputePeriodicPaymentValidTotalInterestPaidInvariant(FeatureBitset features) + testLoanPayComputePeriodicPaymentValidTotalInterestPaidInvariant() { // From FIND-008 testcase << "xrpl::loanComputePaymentParts : loanValueChange rounded"; @@ -5039,7 +4941,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; using namespace Lending; - Env env(*this, features); + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -5074,7 +4976,7 @@ protected: auto createJson = env.json( set(borrower, broker.brokerID, principalRequest), Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); + Json(sfCounterpartySignature, json::ObjectValue)); createJson["ClosePaymentFee"] = "0"; createJson["InterestRate"] = 12833; @@ -5098,13 +5000,14 @@ protected: auto const stateBefore = getCurrentState(env, broker, keylet); BEAST_EXPECT(stateBefore.paymentRemaining == 5678); - BEAST_EXPECT(stateBefore.paymentRemaining > kLoanMaximumPaymentsPerTransaction); + BEAST_EXPECT(stateBefore.paymentRemaining > kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION); 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 / kLoanPaymentsPerFeeIncrement + 1)}; + baseFee * + (amount / stateBefore.periodicPayment / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, Fee(payFee), Ter(tesSUCCESS)); env.close(); @@ -5112,11 +5015,11 @@ protected: auto const stateAfter = getCurrentState(env, broker, keylet); BEAST_EXPECT( stateAfter.paymentRemaining == - stateBefore.paymentRemaining - kLoanMaximumPaymentsPerTransaction); + stateBefore.paymentRemaining - kLOAN_MAXIMUM_PAYMENTS_PER_TRANSACTION); } void - testLoanNextPaymentDueDateOverflow(FeatureBitset features) + testLoanNextPaymentDueDateOverflow() { // For FIND-013 testcase << "Prevent nextPaymentDueDate overflow"; @@ -5124,7 +5027,7 @@ protected: using namespace jtx; using namespace std::chrono_literals; using namespace Lending; - Env env{*this, features}; + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -5153,20 +5056,20 @@ protected: using timeType = decltype(sfNextPaymentDueDate)::type::value_type; static_assert(std::is_same_v); - constexpr timeType kMaxTime = std::numeric_limits::max(); - static_assert(kMaxTime == 4'294'967'295); + timeType constexpr kMAX_TIME = std::numeric_limits::max(); + static_assert(kMAX_TIME == 4'294'967'295); auto const baseJson = [&]() { auto createJson = env.json( set(borrower, broker.brokerID, Number{55524'81, -2}), Fee(loanSetFee), - kClosePaymentFee(0), - kGracePeriod(LoanSet::kDefaultGracePeriod), - kInterestRate(TenthBips32(12833)), - kLateInterestRate(TenthBips32(77048)), - kLatePaymentFee(0), - kLoanOriginationFee(218), - Json(sfCounterpartySignature, json::ValueType::Object)); + kCLOSE_PAYMENT_FEE(0), + kGRACE_PERIOD(LoanSet::kDEFAULT_GRACE_PERIOD), + kINTEREST_RATE(TenthBips32(12833)), + kLATE_INTEREST_RATE(TenthBips32(77048)), + kLATE_PAYMENT_FEE(0), + kLOAN_ORIGINATION_FEE(218), + Json(sfCounterpartySignature, json::ObjectValue)); createJson.removeMember(sfSequence.getJsonName()); @@ -5183,14 +5086,15 @@ protected: BEAST_EXPECT(startDate >= 50); - return kMaxTime - startDate; + return kMAX_TIME - startDate; }; { // straight-up overflow: interval auto const interval = maxLoanTime() + 1; auto const total = 1; - auto createJson = env.json(baseJson, kPaymentInterval(interval), kPaymentTotal(total)); + auto createJson = + env.json(baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); env.close(); @@ -5200,7 +5104,8 @@ protected: // min interval is 60 auto const interval = 60; auto const total = maxLoanTime() + 1; - auto createJson = env.json(baseJson, kPaymentInterval(interval), kPaymentTotal(total)); + auto createJson = + env.json(baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); env.close(); @@ -5212,7 +5117,7 @@ protected: auto const total = 1; auto const grace = interval; auto createJson = env.json( - baseJson, kPaymentInterval(interval), kPaymentTotal(total), kGracePeriod(grace)); + baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total), kGRACE_PERIOD(grace)); // The grace period can't be larger than the interval. env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); @@ -5222,7 +5127,8 @@ protected: // Overflow with multiplication of a few large intervals auto const interval = 1'000'000'000; auto const total = 10; - auto createJson = env.json(baseJson, kPaymentInterval(interval), kPaymentTotal(total)); + auto createJson = + env.json(baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); env.close(); @@ -5232,7 +5138,8 @@ protected: // min interval is 60 auto const interval = 60; auto const total = 1'000'000'000; - auto createJson = env.json(baseJson, kPaymentInterval(interval), kPaymentTotal(total)); + auto createJson = + env.json(baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); env.close(); @@ -5244,7 +5151,7 @@ protected: auto const interval = (maxLoanTime() - total) / total; auto const grace = interval; auto createJson = env.json( - baseJson, kPaymentInterval(interval), kPaymentTotal(total), kGracePeriod(grace)); + baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total), kGRACE_PERIOD(grace)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tecKILLED)); env.close(); @@ -5259,7 +5166,7 @@ protected: auto const interval = maxLoanTime() - grace; auto const total = 1; auto createJson = env.json( - baseJson, kPaymentInterval(interval), kPaymentTotal(total), kGracePeriod(grace)); + baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total), kGRACE_PERIOD(grace)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tesSUCCESS)); env.close(); @@ -5282,12 +5189,12 @@ protected: auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); - auto const closeStartDate = ((parentCloseTime() / 10) + 1) * 10; + auto const closeStartDate = (parentCloseTime() / 10 + 1) * 10; auto const grace = 5'000; - auto const interval = kMaxTime - closeStartDate - grace; + auto const interval = kMAX_TIME - closeStartDate - grace; auto const total = 1; auto createJson = env.json( - baseJson, kPaymentInterval(interval), kPaymentTotal(total), kGracePeriod(grace)); + baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total), kGRACE_PERIOD(grace)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tesSUCCESS)); env.close(); @@ -5301,7 +5208,7 @@ protected: // This loan exists auto const afterState = getCurrentState(env, broker, keylet); - BEAST_EXPECT(afterState.nextPaymentDate == kMaxTime - grace); + BEAST_EXPECT(afterState.nextPaymentDate == kMAX_TIME - grace); BEAST_EXPECT(afterState.previousPaymentDate == 0); BEAST_EXPECT(afterState.paymentRemaining == 1); } @@ -5311,9 +5218,9 @@ protected: env(pay(issuer, borrower, iouAsset(Number{1'055'524'81, -2}))); // Start date when the ledger is closed will be larger - auto const closeStartDate = ((parentCloseTime() / 10) + 1) * 10; + auto const closeStartDate = (parentCloseTime() / 10 + 1) * 10; auto const grace = 5'000; - auto const maxLoanTime = kMaxTime - closeStartDate - grace; + auto const maxLoanTime = kMAX_TIME - closeStartDate - grace; auto const total = [&]() { if (maxLoanTime % 5 == 0) return 5; @@ -5333,7 +5240,7 @@ protected: auto const interval = maxLoanTime / total; auto createJson = env.json( - baseJson, kPaymentInterval(interval), kPaymentTotal(total), kGracePeriod(grace)); + baseJson, kPAYMENT_INTERVAL(interval), kPAYMENT_TOTAL(total), kGRACE_PERIOD(grace)); env(createJson, Sig(sfCounterpartySignature, lender), Ter(tesSUCCESS)); env.close(); @@ -5349,7 +5256,8 @@ protected: { NumberRoundModeGuard const mg{Number::RoundingMode::Upward}; Number const payment = beforeState.periodicPayment * (total - 1); - XRPAmount const payFee{baseFee * ((total - 1) / kLoanPaymentsPerFeeIncrement + 1)}; + XRPAmount const payFee{ + baseFee * ((total - 1) / kLOAN_PAYMENTS_PER_FEE_INCREMENT + 1)}; STAmount const paymentAmount = roundToScale(STAmount{broker.asset, payment}, beforeState.loanScale); auto loanPayTx = env.json(pay(borrower, keylet.key, paymentAmount), Fee(payFee)); @@ -5360,8 +5268,8 @@ protected: // The loan is on the last payment auto const afterState = getCurrentState(env, broker, keylet); BEAST_EXPECT(afterState.paymentRemaining == 1); - BEAST_EXPECT(afterState.nextPaymentDate == kMaxTime - grace); - BEAST_EXPECT(afterState.previousPaymentDate == kMaxTime - grace - interval); + BEAST_EXPECT(afterState.nextPaymentDate == kMAX_TIME - grace); + BEAST_EXPECT(afterState.previousPaymentDate == kMAX_TIME - grace - interval); } } @@ -5383,7 +5291,7 @@ protected: .env = env, .issuer = issuer, .holders = {lender, borrower}, - .flags = kMptDexFlags | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, .authHolder = true, }); @@ -5412,8 +5320,8 @@ protected: err); }); - static constexpr std::uint32_t kLoanSequence = 1; - auto const loanKeylet = keylet::loan(brokerInfo.brokerID, kLoanSequence); + std::uint32_t constexpr kLOAN_SEQUENCE = 1; + auto const loanKeylet = keylet::loan(brokerInfo.brokerID, kLOAN_SEQUENCE); // Can't loan pay if the borrower is not authorized forUnauthAuth([&](bool authorized) { @@ -5425,7 +5333,7 @@ protected: void testCoverDepositWithdrawNonTransferableMPT(FeatureBitset feature) { - testcase("CoverDeposit blocked, CoverWithdraw allowed when CanTransfer cleared"); + testcase("CoverDeposit and CoverWithdraw reject MPT without CanTransfer"); using namespace jtx; using namespace loanBroker; @@ -5437,14 +5345,19 @@ protected: env.fund(XRP(100'000), issuer, alice); env.close(); - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {alice}, - .pay = 100, - .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester mpt{env, issuer, kMPT_INIT_NO_FUND}; + + mpt.create({.flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateCanTransfer}); + + env.close(); + PrettyAsset const asset = mpt["MPT"]; + mpt.authorize({.account = alice}); + env.close(); + + // Issuer can fund the holder even if CanTransfer is not set. + env(pay(issuer, alice, asset(100))); + env.close(); Vault const vault{env}; auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); @@ -5461,9 +5374,30 @@ protected: Account const pseudoAccount{"Loan Broker pseudo-account", brokerSle->at(sfAccount)}; - // First, deposit some cover while CanTransfer is set so we have an - // existing position to withdraw from after the governance action. + // Remove CanTransfer after the broker is set up. + mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); + env.close(); + + // Standard Payment path should forbid third-party transfers. + auto const err = feature[featureMPTokensV2] ? tecNO_PERMISSION : tecNO_AUTH; + env(pay(alice, pseudoAccount, asset(1)), Ter(err)); + env.close(); + + // Cover cannot be transferred to broker account auto const depositAmount = asset(1); + env(coverDeposit(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); + env.close(); + + if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) + { + BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); + env.require(Balance(pseudoAccount, asset(0))); + } + + // Set CanTransfer again and transfer some deposit + mpt.set({.mutableFlags = tmfMPTSetCanTransfer}); + env.close(); + env(coverDeposit(alice, brokerKeylet.key, depositAmount)); env.close(); @@ -5473,189 +5407,38 @@ protected: env.require(Balance(pseudoAccount, depositAmount)); } - // Issuer governance: clear CanTransfer. + // Remove CanTransfer after the deposit mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); env.close(); - // Standard Payment path still forbids third-party transfers. - auto const err = feature[featureMPTokensV2] ? tecNO_PERMISSION : tecNO_AUTH; - env(pay(alice, pseudoAccount, asset(1)), Ter(err)); + // Cover cannot be transferred from broker account + env(coverWithdraw(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); env.close(); - // New cover deposits are blocked - this would create new exposure. - env(coverDeposit(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); + // Set CanTransfer again and withdraw + mpt.set({.mutableFlags = tmfMPTSetCanTransfer}); + env.close(); + + env(coverWithdraw(alice, brokerKeylet.key, depositAmount)); env.close(); if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); - env.require(Balance(pseudoAccount, depositAmount)); + BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); + env.require(Balance(pseudoAccount, asset(0))); } - - bool const postAmendment = feature[fixCleanup3_2_0]; - if (postAmendment) - { - // Post-fixCleanup3_2_0: existing cover can always be withdrawn - // even when CanTransfer is cleared, so the broker is not trapped. - env(coverWithdraw(alice, brokerKeylet.key, depositAmount)); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); - env.require(Balance(pseudoAccount, asset(0))); - } - } - else - { - // Pre-fixCleanup3_2_0 regression: cover withdraw was blocked, - // trapping the broker's first-loss capital. - env(coverWithdraw(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); - env.require(Balance(pseudoAccount, depositAmount)); - } - } - } - - void - testLoanSetBlockedLoanPayAllowedWhenCanTransferCleared() - { - testcase("LoanSet blocked, LoanPay allowed when CanTransfer cleared"); - using namespace jtx; - using namespace loan; - - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env.close(); - - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {lender, borrower}, - .flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mpt.issuanceID(); - env(pay(issuer, lender, asset(10'000'000))); - // Fund the borrower with enough to cover principal+interest+fees - env(pay(issuer, borrower, asset(100'000))); - env.close(); - - // Create vault and broker while CanTransfer is set. - auto const broker = createVaultAndBroker(env, asset, lender); - - auto const loanSetFee = Fee(env.current()->fees().base * 2); - - // Create an existing loan while CanTransfer is set. - env(set(borrower, broker.brokerID, 1'000), - Sig(sfCounterpartySignature, lender), - loanSetFee); - env.close(); - auto const loanKeylet = keylet::loan(broker.brokerID, 1); - BEAST_EXPECT(env.le(loanKeylet)); - - // Issuer governance: clear CanTransfer. - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Issuing a NEW loan is blocked - it would create new exposure into - // a pool the issuer is restricting. - env(set(borrower, broker.brokerID, 1'000), - Sig(sfCounterpartySignature, lender), - loanSetFee, - Ter{tecNO_AUTH}); - env.close(); - - // Repaying an existing loan is always allowed - blocking it would - // create irrecoverable bad debt and trap SAV depositor principal. - env(pay(borrower, loanKeylet.key, asset(1'000))); - env.close(); - } - - void - testLendingCanTradeClearedNoImpact() - { - testcase("Lending: CanTrade cleared has no impact"); - using namespace jtx; - using namespace loan; - using namespace loanBroker; - - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env.close(); - - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {lender, borrower}, - .flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTrade}); - PrettyAsset const asset = mpt.issuanceID(); - env(pay(issuer, lender, asset(10'000'000))); - env(pay(issuer, borrower, asset(100'000))); - env.close(); - - auto const broker = createVaultAndBroker(env, asset, lender); - - // Sanity: while CanTrade is set, the asset can be placed on the DEX. - env(offer(lender, XRP(1), asset(10))); - env.close(); - - // Issuer governance: clear CanTrade. Loan origination and repayment - // are not trades: nothing in the Lending Protocol should be impacted. - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - env.close(); - - // Control: clearing CanTrade is observable on the DEX path. - env(offer(lender, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); - env.close(); - - auto const loanSetFee = Fee(env.current()->fees().base * 2); - - // New cover deposits still work. - env(coverDeposit(lender, broker.brokerID, asset(100))); - env.close(); - - // New loan issuance still works. - env(loan::set(borrower, broker.brokerID, 1'000), - Sig(sfCounterpartySignature, lender), - loanSetFee); - env.close(); - auto const loanKeylet = keylet::loan(broker.brokerID, 1); - BEAST_EXPECT(env.le(loanKeylet)); - - // Repayment still works. - env(pay(borrower, loanKeylet.key, asset(1'000))); - env.close(); - - // Cover withdrawal still works. - env(coverWithdraw(lender, broker.brokerID, asset(100))); - env.close(); } #if LOAN_TODO void - testLoanPayLateFullPaymentBypassesPenalties(FeatureBitset features) + testLoanPayLateFullPaymentBypassesPenalties() { testcase("LoanPay full payment skips late penalties"); using namespace jtx; using namespace loan; using namespace std::chrono_literals; - Env env(*this, features); + Env env(*this, all); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -5689,15 +5472,15 @@ protected: env(set(borrower, broker.brokerID, principal), Sig(sfCounterpartySignature, lender), - kLoanServiceFee(serviceFee), - kLatePaymentFee(lateFee), - kClosePaymentFee(closeFee), - kInterestRate(percentageToTenthBips(12)), - kLateInterestRate(percentageToTenthBips(24) / 10), - kCloseInterestRate(percentageToTenthBips(5)), - kPaymentTotal(12), - kPaymentInterval(600), - kGracePeriod(0), + kLOAN_SERVICE_FEE(serviceFee), + kLATE_PAYMENT_FEE(lateFee), + kCLOSE_PAYMENT_FEE(closeFee), + kINTEREST_RATE(percentageToTenthBips(12)), + kLATE_INTEREST_RATE(percentageToTenthBips(24) / 10), + kCLOSE_INTEREST_RATE(percentageToTenthBips(5)), + kPAYMENT_TOTAL(12), + kPAYMENT_INTERVAL(600), + kGRACE_PERIOD(0), Fee(loanSetFee)); env.close(); @@ -5733,11 +5516,7 @@ protected: auto const periodicRate = loanPeriodicRate(interestRateValue, state.paymentInterval); auto const rawLoanState = computeTheoreticalLoanState( - env.current()->rules(), - state.periodicPayment, - periodicRate, - state.paymentRemaining, - managementFeeRate); + state.periodicPayment, periodicRate, state.paymentRemaining, managementFeeRate); auto const parentCloseTime = env.current()->parentCloseTime(); auto const startDateSeconds = @@ -5801,7 +5580,7 @@ protected: } void - testLoanCoverMinimumRoundingExploit(FeatureBitset features) + testLoanCoverMinimumRoundingExploit() { auto testLoanCoverMinimumRoundingExploit = [&, this](Number const& principalRequest) { testcase << "LoanBrokerCoverClawback drains cover via rounding" @@ -5811,7 +5590,7 @@ protected: using namespace loan; using namespace loanBroker; - Env env(*this, features); + Env env(*this, all); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -5839,9 +5618,9 @@ protected: set(borrower, broker.brokerID, principalRequest), Sig(sfCounterpartySignature, lender), loanSetFee, - kPaymentInterval(600), - kPaymentTotal(1), - kGracePeriod(60)); + kPAYMENT_INTERVAL(600), + kPAYMENT_TOTAL(1), + kGRACE_PERIOD(60)); env(createTx); env.close(); @@ -5887,7 +5666,7 @@ protected: #endif void - testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic(FeatureBitset features) + testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic() { // --- PoC Summary ---------------------------------------------------- // Scenario: Borrower makes one periodic payment early (before next due) @@ -5909,7 +5688,7 @@ protected: using namespace loan; using namespace std::chrono_literals; - Env env{*this, features}; + Env env(*this, all_); Account const lender{"poc_lender4"}; Account const borrower{"poc_borrower4"}; @@ -5940,18 +5719,18 @@ protected: auto createJtx = env.jt( set(borrower, broker.brokerID, principalRequest, 0), Sig(sfCounterpartySignature, lender), - kLoanOriginationFee(originationFee), - kLoanServiceFee(serviceFee), - kLatePaymentFee(lateFee), - kClosePaymentFee(closeFee), - kOverpaymentFee(percentageToTenthBips(5) / 10), - kInterestRate(interest), - kLateInterestRate(lateInterest), - kCloseInterestRate(closeInterest), - kOverpaymentInterestRate(overpaymentInterest), - kPaymentTotal(total), - kPaymentInterval(interval), - kGracePeriod(grace), + kLOAN_ORIGINATION_FEE(originationFee), + kLOAN_SERVICE_FEE(serviceFee), + kLATE_PAYMENT_FEE(lateFee), + kCLOSE_PAYMENT_FEE(closeFee), + kOVERPAYMENT_FEE(percentageToTenthBips(5) / 10), + kINTEREST_RATE(interest), + kLATE_INTEREST_RATE(lateInterest), + kCLOSE_INTEREST_RATE(closeInterest), + kOVERPAYMENT_INTEREST_RATE(overpaymentInterest), + kPAYMENT_TOTAL(total), + kPAYMENT_INTERVAL(interval), + kGRACE_PERIOD(grace), Fee(loanSetFee)); auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -5966,7 +5745,6 @@ protected: auto state = getCurrentState(env, broker, loanKeylet); Number const periodicRate = loanPeriodicRate(state.interestRate, state.paymentInterval); auto const components = xrpl::detail::computePaymentComponents( - env.current()->rules(), asset.raw(), state.loanScale, state.totalValue, @@ -6000,10 +5778,7 @@ protected: // schedule auto const fullPaymentInterest = computeFullPaymentInterest( xrpl::detail::loanPrincipalFromPeriodicPayment( - env.current()->rules(), - after.periodicPayment, - periodicRate2, - after.paymentRemaining), + after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, @@ -6036,10 +5811,7 @@ protected: auto const prevClamped = std::min(after.previousPaymentDate, nowSecs); auto const fullPaymentInterestClamped = computeFullPaymentInterest( xrpl::detail::loanPrincipalFromPeriodicPayment( - env.current()->rules(), - after.periodicPayment, - periodicRate2, - after.paymentRemaining), + after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, @@ -6112,13 +5884,13 @@ protected: } void - testDustManipulation(FeatureBitset features) + testDustManipulation() { testcase("Dust manipulation"); using namespace jtx; using namespace std::chrono_literals; - Env env{*this, features}; + Env env(*this, all_); // Setup: Create accounts Account const issuer{"issuer"}; @@ -6252,7 +6024,7 @@ protected: } void - testRIPD3831(FeatureBitset features) + testRIPD3831() { using namespace jtx; @@ -6279,7 +6051,7 @@ protected: auto const assetType = AssetType::XRP; - Env env{*this, features}; + Env env(*this, all_); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); @@ -6325,7 +6097,7 @@ protected: } void - testRIPD3459(FeatureBitset features) + testRIPD3459() { testcase("RIPD-3459 - LoanBroker incorrect debt total"); @@ -6350,7 +6122,7 @@ protected: auto const assetType = AssetType::MPT; - Env env{*this, features}; + Env env(*this, all_); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); @@ -6388,7 +6160,7 @@ protected: if (auto const loanSle = env.le(loanKeylet); BEAST_EXPECT(loanSle)) { BEAST_EXPECT(brokerSle->at(sfDebtTotal) == loanSle->at(sfTotalValueOutstanding)); - BEAST_EXPECT(brokerSle->at(sfDebtTotal) == beast::kZero); + BEAST_EXPECT(brokerSle->at(sfDebtTotal) == beast::kZERO); } } } @@ -6430,9 +6202,9 @@ protected: env(set(borrower, brokerKeyLet.key, debtMaximumRequest), Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32(50'000)), - kPaymentTotal(2), - kPaymentInterval(150), + kINTEREST_RATE(TenthBips32(50'000)), + kPAYMENT_TOTAL(2), + kPAYMENT_INTERVAL(150), Txflags(tfLoanOverpayment), txFee); env.close(); @@ -6450,14 +6222,14 @@ protected: } void - testRoundingAllowsUndercoverage(FeatureBitset features) + testRoundingAllowsUndercoverage() { testcase("Minimum cover rounding allows undercoverage (XRP)"); using namespace jtx; using namespace loanBroker; - Env env{*this, features}; + Env env(*this, all_); Account const lender{"lender"}; Account const borrower{"borrower"}; @@ -6486,7 +6258,7 @@ protected: // 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()), - loan::kInterestRate(TenthBips32(0)), + loan::kINTEREST_RATE(TenthBips32(0)), Sig(sfCounterpartySignature, lender), Fee(env.current()->fees().base * 2)); BEAST_EXPECT(env.ter() == tesSUCCESS); @@ -6529,7 +6301,7 @@ protected: } void - testRIPD3902(FeatureBitset features) + testRIPD3902() { testcase("RIPD-3902 - 1 IOU loan payments"); @@ -6556,7 +6328,7 @@ protected: auto const assetType = AssetType::IOU; - Env env{*this, features}; + Env env(*this, all_); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); @@ -6632,10 +6404,10 @@ protected: auto const serviceFee = 101; env(set(broker, brokerKeylet.key, debtMaximumRequest), - kCounterparty(borrower), + kCOUNTERPARTY(borrower), Sig(sfCounterpartySignature, borrower), - kLoanServiceFee(serviceFee), - kPaymentTotal(10), + kLOAN_SERVICE_FEE(serviceFee), + kPAYMENT_TOTAL(10), txFee); env.close(); @@ -6700,7 +6472,7 @@ protected: } void - testIssuerIsBorrower(FeatureBitset features) + testIssuerIsBorrower() { testcase("RIPD-4096 - Issuer as borrower"); @@ -6720,7 +6492,7 @@ protected: auto const assetType = AssetType::IOU; - Env env{*this, features}; + Env env(*this, all_); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, issuer); @@ -6776,7 +6548,7 @@ protected: auto const assetType = AssetType::XRP; - Env env(*this, makeConfig(), all_, nullptr, beast::Severity::Warning); + Env env(*this, makeConfig(), all_, nullptr, beast::severities::Severity::KWarning); auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); @@ -6817,14 +6589,14 @@ protected: } void - testOverpaymentManagementFee(FeatureBitset features) + testOverpaymentManagementFee() { testcase("testOverpaymentManagementFee"); using namespace jtx; using namespace loan; - Env env{*this, features}; + Env env(*this, all_); Account const lender{"lender"}, borrower{"borrower"}; @@ -6849,9 +6621,9 @@ protected: env(loan::set( borrower, result.brokerKeylet().key, asset(10'000).value(), tfLoanOverpayment), Sig(sfCounterpartySignature, lender), - loan::kPaymentInterval(86400 * 30), - loan::kPaymentTotal(3), - loan::kOverpaymentInterestRate(TenthBips32(percentageToTenthBips(20))), + loan::kPAYMENT_INTERVAL(86400 * 30), + loan::kPAYMENT_TOTAL(3), + loan::kOVERPAYMENT_INTEREST_RATE(TenthBips32(percentageToTenthBips(20))), loanSetFee); // From calculator @@ -6870,7 +6642,7 @@ protected: } void - testLoanPayBrokerOwnerMissingTrustline(FeatureBitset features) + testLoanPayBrokerOwnerMissingTrustline() { testcase << "LoanPay Broker Owner Missing Trustline (PoC)"; using namespace jtx; @@ -6879,7 +6651,7 @@ protected: Account const borrower("borrower"); Account const broker("broker"); auto const iou = issuer["IOU"]; - Env env(*this, features); + Env env(*this, all_); env.fund(XRP(20'000), issuer, broker, borrower); env.close(); // Set up trustlines and fund accounts @@ -6894,8 +6666,8 @@ protected: auto const keylet = keylet::loan(brokerInfo.brokerID, 1); env(set(borrower, brokerInfo.brokerID, 10'000), Sig(sfCounterpartySignature, broker), - kLoanServiceFee(iou(100).value()), - kPaymentInterval(100), + kLOAN_SERVICE_FEE(iou(100).value()), + kPAYMENT_INTERVAL(100), Fee(XRP(100))); env.close(); // Ensure broker has sufficient cover so brokerPayee == brokerOwner @@ -6938,7 +6710,7 @@ protected: } void - testLoanPayBrokerOwnerUnauthorizedMPT(FeatureBitset features) + testLoanPayBrokerOwnerUnauthorizedMPT() { testcase << "LoanPay Broker Owner MPT unauthorized"; using namespace jtx; @@ -6948,11 +6720,11 @@ protected: Account const borrower("borrower"); Account const broker("broker"); - Env env{*this, features}; + Env env(*this, all_); env.fund(XRP(20'000), issuer, broker, borrower); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mpt{mptt.issuanceID()}; @@ -6974,8 +6746,8 @@ protected: auto const keylet = keylet::loan(brokerInfo.brokerID, 1); env(set(borrower, brokerInfo.brokerID, 10'000), Sig(sfCounterpartySignature, broker), - kLoanServiceFee(mpt(100).value()), - kPaymentInterval(100), + kLOAN_SERVICE_FEE(mpt(100).value()), + kPAYMENT_INTERVAL(100), Fee(XRP(100))); env.close(); // Ensure broker has sufficient cover so brokerPayee == brokerOwner @@ -7019,7 +6791,7 @@ protected: } void - testLoanPayBrokerOwnerNoPermissionedDomainMPT(FeatureBitset features) + testLoanPayBrokerOwnerNoPermissionedDomainMPT() { testcase << "LoanPay Broker Owner without permissioned domain of the MPT"; using namespace jtx; @@ -7029,13 +6801,13 @@ protected: Account const borrower("borrower"); Account const broker("broker"); - Env env{*this, features}; + Env env(*this, all_); env.fund(XRP(20'000), issuer, broker, borrower); env.close(); auto credType = "credential1"; - pdomain::Credentials const credentials1 = {{.issuer = issuer, .credType = credType}}; + pdomain::Credentials const credentials1{{issuer, credType}}; env(pdomain::setTx(issuer, credentials1)); env.close(); @@ -7049,7 +6821,7 @@ protected: env(credentials::accept(borrower, issuer, credType)); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({ .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | tfMPTCanLock, .domainID = domainID, @@ -7074,8 +6846,8 @@ protected: auto const keylet = keylet::loan(brokerInfo.brokerID, 1); env(set(borrower, brokerInfo.brokerID, 10'000), Sig(sfCounterpartySignature, broker), - kLoanServiceFee(mpt(100).value()), - kPaymentInterval(100), + kLOAN_SERVICE_FEE(mpt(100).value()), + kPAYMENT_INTERVAL(100), Fee(XRP(100))); env.close(); // Ensure broker has sufficient cover so brokerPayee == brokerOwner @@ -7122,7 +6894,7 @@ protected: } void - testLoanSetBrokerOwnerNoPermissionedDomainMPT(FeatureBitset features) + testLoanSetBrokerOwnerNoPermissionedDomainMPT() { testcase << "LoanSet Broker Owner without permissioned domain of the MPT"; using namespace jtx; @@ -7132,13 +6904,13 @@ protected: Account const borrower("borrower"); Account const broker("broker"); - Env env{*this, features}; + Env env(*this, all_); env.fund(XRP(20'000), issuer, broker, borrower); env.close(); auto credType = "credential1"; - pdomain::Credentials const credentials1{{.issuer = issuer, .credType = credType}}; + pdomain::Credentials const credentials1{{issuer, credType}}; env(pdomain::setTx(issuer, credentials1)); env.close(); @@ -7153,7 +6925,7 @@ protected: env(credentials::accept(borrower, issuer, credType)); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({ .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | tfMPTCanLock, .domainID = domainID, @@ -7186,15 +6958,15 @@ protected: // Create a loan, this should fail for tecNO_AUTH env(set(borrower, brokerInfo.brokerID, 10'000), Sig(sfCounterpartySignature, broker), - kLoanServiceFee(mpt(100).value()), - kPaymentInterval(100), + kLOAN_SERVICE_FEE(mpt(100).value()), + kPAYMENT_INTERVAL(100), Fee(XRP(100)), Ter(tecNO_AUTH)); env.close(); } void - testSequentialFLCDepletion(FeatureBitset features) + testSequentialFLCDepletion() { testcase << "First-Loss Capital Depletion on Sequential Defaults"; @@ -7202,7 +6974,7 @@ protected: using namespace loan; using namespace loanBroker; - Env env{*this, features}; + Env env(*this, all_); Account const issuer{"issuer"}; Account const lender{"lender"}; @@ -7243,10 +7015,10 @@ protected: auto loanATx = env.jt( set(borrowerA, brokerKeylet.key, principalAmount), Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32(500)), // 5% - kPaymentTotal(12), - loan::kPaymentInterval(loanPaymentInterval), - loan::kGracePeriod(loanGracePeriod), + kINTEREST_RATE(TenthBips32(500)), // 5% + kPAYMENT_TOTAL(12), + loan::kPAYMENT_INTERVAL(loanPaymentInterval), + loan::kGRACE_PERIOD(loanGracePeriod), Fee(XRP(10))); // Sufficient fee for multi-sig transaction env(loanATx); env.close(); @@ -7257,10 +7029,10 @@ protected: auto loanBTx = env.jt( set(borrowerB, brokerKeylet.key, principalAmount), Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32(500)), // 5% - kPaymentTotal(12), - loan::kPaymentInterval(loanPaymentInterval), - loan::kGracePeriod(loanGracePeriod), + kINTEREST_RATE(TenthBips32(500)), // 5% + kPAYMENT_TOTAL(12), + loan::kPAYMENT_INTERVAL(loanPaymentInterval), + loan::kGRACE_PERIOD(loanGracePeriod), Fee(XRP(10))); // Sufficient fee for multi-sig transaction env(loanBTx); env.close(); @@ -7312,149 +7084,11 @@ protected: BEAST_EXPECT(afterSecondCoverAvailable == 0); } - void - testYieldTheftRounding(std::uint32_t flags) - { - testcase("Rounding manipulation does not permit yield theft"); - using namespace jtx; - using namespace loan; - - // 1. Setup Environment - Env env(*this, all_); - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1000), issuer, lender, borrower); - env.close(); - - // 2. Asset Selection - PrettyAsset const iou = issuer["USD"]; - env(trust(lender, iou(100'000'000))); - env(trust(borrower, iou(100'000'000))); - env(pay(issuer, lender, iou(100'000'000))); - env(pay(issuer, borrower, iou(100'000'000))); - env.close(); - - // 3. Create Vault and Broker with High Debt Limit (100M) - auto const brokerInfo = createVaultAndBroker( - env, - iou, - lender, - { - .vaultDeposit = 5'000'000, - .debtMax = Number{100'000'000}, - .coverDeposit = 500'000, - }); - auto const [currentSeq, vaultKeylet] = [&]() { - auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); - if (!BEAST_EXPECT(brokerSle)) - return std::make_tuple(0u, keylet::unchecked(beast::kZero)); - auto const currentSeq = brokerSle->at(sfLoanSequence); - auto const vaultKeylet = keylet::vault(brokerSle->at(sfVaultID)); - return std::make_tuple(currentSeq, vaultKeylet); - }(); - - // 4. Loan Parameters (Attack Vector) - Number const principal = 1'000'000; - TenthBips32 const interestRate = TenthBips32{1}; // 0.001% - std::uint32_t const paymentInterval = 86400; - std::uint32_t const paymentTotal = 3650; - - auto const loanSetFee = Fee(env.current()->fees().base * 2); - env(set(borrower, brokerInfo.brokerID, iou(principal).value(), flags), - Sig(sfCounterpartySignature, lender), - loan::kInterestRate(interestRate), - loan::kPaymentInterval(paymentInterval), - loan::kPaymentTotal(paymentTotal), - Fee(loanSetFee)); - env.close(); - - // --- RETRIEVE OBJECTS & SETUP ATTACK --- - - auto borrowerBalance = [&]() { return env.balance(borrower, iou); }; - auto const borrowerScale = static_cast(borrowerBalance()).exponent(); - - auto const loanKeylet = keylet::loan(brokerInfo.brokerID, currentSeq); - auto const maybePeriodicPayment = [&]() -> std::optional { - auto const loanSle = env.le(loanKeylet); - if (!BEAST_EXPECT(loanSle)) - return std::nullopt; - // Construct Payment - return STAmount{iou, loanSle->at(sfPeriodicPayment)}; - }(); - if (!maybePeriodicPayment) - return; - auto const periodicPayment = *maybePeriodicPayment; - auto const roundedPayment = - roundToScale(periodicPayment, borrowerScale, Number::RoundingMode::Upward); - - // ATTACK: Add dust buffer (1e-9) to force 'excess' logic execution - STAmount const paymentBuffer{iou, Number(1, -9)}; - STAmount const attackPayment = periodicPayment + paymentBuffer; - - auto const maybeInitialVaultAssets = [&]() -> std::optional { - auto const vault = env.le(vaultKeylet); - if (!BEAST_EXPECT(vault)) - return std::nullopt; - return vault->at(sfAssetsTotal); - }(); - if (!maybeInitialVaultAssets) - return; - auto const initialVaultAssets = *maybeInitialVaultAssets; - - // 5. Execution Loop - int yieldTheftCount = 0; - auto previousAssetsTotal = initialVaultAssets; - - for (int i = 0; i < 100; ++i) - { - auto const balanceBefore = borrowerBalance(); - env(pay(borrower, loanKeylet.key, attackPayment, flags)); - env.close(); - auto const borrowerDelta = balanceBefore - borrowerBalance(); - BEAST_EXPECT(borrowerDelta.signum() == roundedPayment.signum()); - - auto const loanSle = env.le(loanKeylet); - if (!BEAST_EXPECT(loanSle)) - break; - auto const updatedPayment = STAmount{iou, loanSle->at(sfPeriodicPayment)}; - BEAST_EXPECT( - (roundToScale(updatedPayment, borrowerScale, Number::RoundingMode::Upward) == - roundedPayment)); - BEAST_EXPECT( - (updatedPayment == periodicPayment) || - (flags == tfLoanOverpayment && i >= 2 && updatedPayment < periodicPayment)); - - auto const currentVaultSle = env.le(vaultKeylet); - if (!BEAST_EXPECT(currentVaultSle)) - break; - - auto const currentAssetsTotal = currentVaultSle->at(sfAssetsTotal); - auto const delta = currentAssetsTotal - previousAssetsTotal; - - BEAST_EXPECT( - (delta == beast::kZero && borrowerDelta <= roundedPayment) || - (delta > beast::kZero && borrowerDelta > roundedPayment)); - - // If tx succeeded but Assets Total didn't change, interest was - // stolen. - if (delta == beast::kZero && borrowerDelta > roundedPayment) - { - yieldTheftCount++; - } - - previousAssetsTotal = currentAssetsTotal; - } - - BEAST_EXPECTS(yieldTheftCount == 0, std::to_string(yieldTheftCount)); - } - // Tests that vault withdrawals work correctly when the vault has unrealized // loss from an impaired loan, ensuring the invariant check properly // accounts for the loss. void - testWithdrawReflectsUnrealizedLoss(FeatureBitset features) + testWithdrawReflectsUnrealizedLoss() { using namespace jtx; using namespace loan; @@ -7463,17 +7097,17 @@ protected: testcase("Vault withdraw reflects sfLossUnrealized"); // Test constants - static constexpr std::int64_t kInitialFunding = 1'000'000; - static constexpr std::int64_t kLenderInitialIou = 5'000'000; - static constexpr std::int64_t kDepositorInitialIou = 1'000'000; - static constexpr std::int64_t kBorrowerInitialIou = 100'000; - static constexpr std::int64_t kDepositAmount = 5'000; - static constexpr std::int64_t kPrincipalAmount = 99; - static constexpr std::uint64_t kExpectedSharesPerDepositor = 5'000'000'000; - static constexpr std::uint32_t kLocalPaymentInterval = 600; - static constexpr std::uint32_t kLocalPaymentTotal = 2; + static constexpr std::int64_t kINITIAL_FUNDING = 1'000'000; + static constexpr std::int64_t kLENDER_INITIAL_IOU = 5'000'000; + static constexpr std::int64_t kDEPOSITOR_INITIAL_IOU = 1'000'000; + static constexpr std::int64_t kBORROWER_INITIAL_IOU = 100'000; + static constexpr std::int64_t kDEPOSIT_AMOUNT = 5'000; + static constexpr std::int64_t kPRINCIPAL_AMOUNT = 99; + static constexpr std::uint64_t kEXPECTED_SHARES_PER_DEPOSITOR = 5'000'000'000; + static constexpr std::uint32_t kLOCAL_PAYMENT_INTERVAL = 600; + static constexpr std::uint32_t kLOCAL_PAYMENT_TOTAL = 2; - Env env{*this, features}; + Env env(*this, all_); // Setup accounts Account const issuer{"issuer"}; @@ -7482,7 +7116,7 @@ protected: Account const depositorB{"lpB"}; Account const borrower{"borrowerA"}; - env.fund(XRP(kInitialFunding), issuer, lender, depositorA, depositorB, borrower); + env.fund(XRP(kINITIAL_FUNDING), issuer, lender, depositorA, depositorB, borrower); env.close(); // Setup trust lines @@ -7494,10 +7128,10 @@ protected: env.close(); // Fund accounts with IOUs - env(pay(issuer, lender, iouAsset(kLenderInitialIou))); - env(pay(issuer, depositorA, iouAsset(kDepositorInitialIou))); - env(pay(issuer, depositorB, iouAsset(kDepositorInitialIou))); - env(pay(issuer, borrower, iouAsset(kBorrowerInitialIou))); + env(pay(issuer, lender, iouAsset(kLENDER_INITIAL_IOU))); + env(pay(issuer, depositorA, iouAsset(kDEPOSITOR_INITIAL_IOU))); + env(pay(issuer, depositorB, iouAsset(kDEPOSITOR_INITIAL_IOU))); + env(pay(issuer, borrower, iouAsset(kBORROWER_INITIAL_IOU))); env.close(); // Create vault and broker, then add deposits from two depositors @@ -7507,13 +7141,13 @@ protected: env(v.deposit({ .depositor = depositorA, .id = broker.vaultKeylet().key, - .amount = iouAsset(kDepositAmount), + .amount = iouAsset(kDEPOSIT_AMOUNT), }), Ter(tesSUCCESS)); env(v.deposit({ .depositor = depositorB, .id = broker.vaultKeylet().key, - .amount = iouAsset(kDepositAmount), + .amount = iouAsset(kDEPOSIT_AMOUNT), }), Ter(tesSUCCESS)); env.close(); @@ -7525,10 +7159,10 @@ protected: auto const loanKeylet = keylet::loan(broker.brokerID, sleBroker->at(sfLoanSequence)); - env(set(borrower, broker.brokerID, kPrincipalAmount), + env(set(borrower, broker.brokerID, kPRINCIPAL_AMOUNT), Sig(sfCounterpartySignature, lender), - kPaymentTotal(kLocalPaymentTotal), - kPaymentInterval(kLocalPaymentInterval), + kPAYMENT_TOTAL(kLOCAL_PAYMENT_TOTAL), + kPAYMENT_INTERVAL(kLOCAL_PAYMENT_INTERVAL), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); env.close(); @@ -7543,7 +7177,7 @@ protected: return; BEAST_EXPECT( - vaultAfterImpair->at(sfLossUnrealized) == broker.asset(kPrincipalAmount).value()); + vaultAfterImpair->at(sfLossUnrealized) == broker.asset(kPRINCIPAL_AMOUNT).value()); // Helper to get share balance for a depositor auto const shareAsset = vaultAfterImpair->at(sfShareMPTID); @@ -7555,8 +7189,8 @@ protected: // Verify both depositors have equal shares auto const sharesLpA = getShareBalance(depositorA); auto const sharesLpB = getShareBalance(depositorB); - BEAST_EXPECT(sharesLpA == kExpectedSharesPerDepositor); - BEAST_EXPECT(sharesLpB == kExpectedSharesPerDepositor); + BEAST_EXPECT(sharesLpA == kEXPECTED_SHARES_PER_DEPOSITOR); + BEAST_EXPECT(sharesLpB == kEXPECTED_SHARES_PER_DEPOSITOR); BEAST_EXPECT(sharesLpA == sharesLpB); // Helper to attempt withdrawal @@ -7580,1216 +7214,62 @@ protected: attemptWithdrawShares(depositorB, sharesLpB, tesSUCCESS); } - // A residual overpayment can reduce the stored principal by one scale-unit - // *less* than computeOverpaymentComponents predicts, firing the - // "principal change agrees" XRPL_ASSERT_PARTS in doOverpayment: - // - // trackedPrincipalDelta == principalOutstanding - newPrincipalOutstanding - // - // tryOverpayment re-amortizes the loan at the reduced principal, then - // re-derives the theoretical principal from the new periodic payment via - // (P * paymentFactor) / paymentFactor. That round-trip is not exact in - // Number's 19-digit arithmetic; a positive residual pushes the recomputed - // principal a hair above the exact grid point `oldPrincipal - delta`, and - // the Upward rounding in tryOverpayment then bumps it a full scale-unit - // higher. The principal therefore drops by `delta - 1 unit`, not `delta`. - // - // Concrete case (isolated, at the tryOverpayment level): - // A 100 USD loan at the minimum non-zero rate, 3 payments, loanScale -10. - // After one regular payment (principalOutstanding 66.6666666674) a residual overpayment of - // 0.049999998 yields trackedPrincipalDelta 0.048999998 but only reduces the principal by - // 0.0489999979 (newPrincipal 66.6176666695) — short by 1e-10. - // - // With fixCleanup3_2_0, tryOverpayment pins the new principal to the exact, - // on-grid reduction (oldPrincipal - trackedPrincipalDelta) instead of the - // lossy (P*factor)/factor round-trip, so the assertion holds and the - // overpayment applies cleanly. The three "principal change agrees" / - // "interest paid agrees" / "principal payment matches" assertions are - // gated behind the same amendment, so without it they are disabled (the - // server does not abort) and the loan keeps the pre-amendment computation. - // - // The test runs the same scenario under both amendment settings and checks - // the stored principal against a ground-truth value derived independently of - // the loan-state computation under test. - void - testBugOverpaymentPrincipalChange() - { - testcase("bug: doOverpayment asserts 'principal change agrees'"); - - using namespace jtx; - using namespace loan; - using namespace xrpl::detail; - - struct Params - { - TenthBips32 interestRate; - TenthBips16 managementFeeRate; - std::uint32_t paymentTotal; - std::uint32_t paymentInterval; - std::int64_t principal; - Number overpayment; - TenthBips32 overpaymentInterestRate; - TenthBips32 overpaymentFeeRate; - std::optional vaultScale; - }; - - struct Result - { - Number principalOutstanding; // stored principal after the LoanPay - Number expectedNewPrincipal; // ground truth, independent of the fix - Number managementFeeChange; // managementFeeOutstanding after - before - Number unit; // one scale-unit at the loan scale - }; - - auto runScenario = [this](FeatureBitset features, Params const& p) -> Result { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const lender{"vaultOwner"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const iouAsset = issuer["USD"]; - Asset const asset = iouAsset.raw(); - STAmount const iouLimit{asset, Number{9'999'999'999'999'999LL}}; - env(trust(lender, iouLimit)); - env(trust(borrower, iouLimit)); - env(pay(issuer, lender, iouAsset(1'000'000))); - env(pay(issuer, borrower, iouAsset(1'000'000))); - env.close(); - - auto const broker = createVaultAndBroker( - env, - iouAsset, - lender, - {.vaultDeposit = 900'000, - .debtMax = 0, - .managementFeeRate = p.managementFeeRate, - .vaultScale = p.vaultScale}); - - auto const brokerSle = env.le(broker.brokerKeylet()); - BEAST_EXPECT(brokerSle); - auto const loanSequence = brokerSle ? brokerSle->at(sfLoanSequence) : 0; - auto const loanKeylet = keylet::loan(broker.brokerID, loanSequence); - - env(set(borrower, broker.brokerID, Number{p.principal}, tfLoanOverpayment), - Sig(sfCounterpartySignature, lender), - kInterestRate(p.interestRate), - kPaymentTotal(p.paymentTotal), - kPaymentInterval(p.paymentInterval), - kGracePeriod(p.paymentInterval), - kOverpaymentFee(p.overpaymentFeeRate), - kOverpaymentInterestRate(p.overpaymentInterestRate), - Fee(env.current()->fees().base * 2), - Ter(tesSUCCESS)); - env.close(); - - // The single LoanPay below makes one regular payment (the overpayment - // is smaller than one period) and leaves the residual as an - // overpayment. - auto const s = getCurrentState(env, broker, loanKeylet); - auto const periodicRate = loanPeriodicRate(s.interestRate, s.paymentInterval); - auto const onePeriod = computePaymentComponents( - env.current()->rules(), - asset, - s.loanScale, - s.totalValue, - s.principalOutstanding, - s.managementFeeOutstanding, - s.periodicPayment, - periodicRate, - s.paymentRemaining, - p.managementFeeRate); - - // Ground truth: the stored principal must drop by exactly the regular - // payment's principal portion plus the overpayment's principal - // portion. computeOverpaymentComponents depends only on the - // overpayment amount and rates (not on the loan-state computation - // under test), so it is an independent oracle. Both components are - // computed under the same rules as the env so the payment factor - // matches. - auto const overpaymentComponents = computeOverpaymentComponents( - env.current()->rules(), - asset, - s.loanScale, - p.overpayment, - p.overpaymentInterestRate, - p.overpaymentFeeRate, - p.managementFeeRate); - Number const expectedNewPrincipal = s.principalOutstanding - - onePeriod.trackedPrincipalDelta - overpaymentComponents.trackedPrincipalDelta; - - Number const managementFeeBefore = s.managementFeeOutstanding; - - STAmount const payAmount{asset, onePeriod.trackedValueDelta + p.overpayment}; - env(pay(borrower, loanKeylet.key, payAmount), - Txflags(tfLoanOverpayment), - Ter(tesSUCCESS)); - env.close(); - - auto const loanSle = env.le(loanKeylet); - BEAST_EXPECT(loanSle); - - return Result{ - .principalOutstanding = loanSle ? Number{loanSle->at(sfPrincipalOutstanding)} : 0, - .expectedNewPrincipal = expectedNewPrincipal, - .managementFeeChange = - (loanSle ? Number{loanSle->at(sfManagementFeeOutstanding)} : Number{0}) - - managementFeeBefore, - .unit = Number{1, s.loanScale}}; - }; - - // Scenario 1: the original near-zero-rate principal reproduction - // (loanScale -10, no management fee). 0.049999998 is smaller than one - // period, so it stays a residual overpayment. - Params const principalCase{ - .interestRate = TenthBips32{1}, - .managementFeeRate = TenthBips16{0}, - .paymentTotal = 3, - .paymentInterval = 60, - .principal = 100, - .overpayment = Number{49999998, -9}, - .overpaymentInterestRate = TenthBips32{1000}, - .overpaymentFeeRate = TenthBips32{1000}, - .vaultScale = 1}; - - // With fixCleanup3_2_0 the stored principal lands exactly on the - // ground-truth grid point: it is reduced by exactly the overpayment's - // principal portion. This is the key correctness check: if the principal - // pin were removed (even with the assertions still gated off), the lossy - // (P * factor) / factor round-trip would leave the principal one - // scale-unit high and this would fail. - Result const fixed = runScenario(all_, principalCase); - BEAST_EXPECTS( - fixed.principalOutstanding == fixed.expectedNewPrincipal, - "fixed principal " + to_string(fixed.principalOutstanding) + " != expected " + - to_string(fixed.expectedNewPrincipal)); - - // Without the amendment the loan amortizes with the catastrophically - // cancelling near-zero payment factor, so its schedule (and ground truth) - // differ from the fixed case; the gated assertions keep the server from - // aborting and the overpayment still lands exactly on that schedule. - Result const legacy = runScenario(all_ - fixCleanup3_2_0, principalCase); - BEAST_EXPECTS( - legacy.principalOutstanding == legacy.expectedNewPrincipal, - "legacy principal " + to_string(legacy.principalOutstanding) + " != expected " + - to_string(legacy.expectedNewPrincipal)); - - // Scenario 2: a normal-rate loan with a 10% management fee. At a normal - // rate the payment factor is identical across the amendment, so toggling - // fixCleanup3_2_0 isolates the fix. This overpayment (found by search) - // lands on a state where both the principal and the management fee differ - // by one scale-unit between the fixed and legacy paths. - Params const feeCase{ - .interestRate = TenthBips32{10000}, - .managementFeeRate = TenthBips16{10000}, - .paymentTotal = 6, - .paymentInterval = 30u * 24 * 60 * 60, - .principal = 1000, - .overpayment = Number{214367363, -10}, - .overpaymentInterestRate = TenthBips32{0}, - .overpaymentFeeRate = TenthBips32{0}, - .vaultScale = std::nullopt}; - - Result const feeFixed = runScenario(all_, feeCase); - Result const feeLegacy = runScenario(all_ - fixCleanup3_2_0, feeCase); - - // With the fix the principal is the exact reduction; without it the lossy - // (P * factor) / factor round-trip leaves it one scale-unit high. - BEAST_EXPECTS( - feeFixed.principalOutstanding == feeFixed.expectedNewPrincipal, - "fee-case fixed principal " + to_string(feeFixed.principalOutstanding) + - " != expected " + to_string(feeFixed.expectedNewPrincipal)); - BEAST_EXPECTS( - feeLegacy.principalOutstanding == feeLegacy.expectedNewPrincipal + feeLegacy.unit, - "fee-case legacy principal " + to_string(feeLegacy.principalOutstanding) + - " != expected " + to_string(feeLegacy.expectedNewPrincipal + feeLegacy.unit)); - - // Management fee: the overpayment re-amortizes a fee-bearing loan, so the management fee - // outstanding drops. - // - // Unlike the principal that is already at the correct precision, the re-amortized - // management fee is tenthBipsOfValue of the new schedule's gross interest, which depends - // on the recomputed periodic payment. So the expected change below is a pinned constant - // captured from a passing run a magic value only because there is nothing simpler to - // compare against. - // - // At the integration level, toggling the amendment also changes the regular payment's - // rounding so a fixed-vs-legacy comparison cannot isolate the overpayment management-fee - // fix. - BEAST_EXPECT(feeFixed.managementFeeChange == feeLegacy.managementFeeChange); - BEAST_EXPECTS( - (feeFixed.managementFeeChange == Number{-8219709543, -10}), - "fee-case mgmt fee change " + to_string(feeFixed.managementFeeChange)); - } - - // A LoanSet with InterestRate = 1 (0.001% annualized, the minimum non-zero - // rate). At such a near-zero rate the closed-form payment factor - // (1 + r)^n - 1 cancels catastrophically. - // - // Without fixCleanup3_2_0 the resulting amortization is degenerate and the - // LoanSet is rejected with tecPRECISION_LOSS (no loan created). With the - // amendment, computePowerMinusOneHybrid uses a numerically-stable series - // expansion, so the loan is created and the scheduled payments - // (2 * periodicPayment) cover the principal — no economic underpayment - // (yield theft). - // - // The test runs the same LoanSet under both amendment settings and pins the - // exact outcome for each. - void - testLoanSetNearZeroInterestRateSucceeds() - { - testcase("LoanSet near-zero interest rate covers principal"); - - using namespace jtx; - using namespace loan; - - Number const principalRequested{1000}; - - struct Result - { - TER ter = tesSUCCESS; - bool created = false; - std::int32_t loanScale = 0; - Number principal; - Number totalValue; - Number managementFee; - Number periodicPayment; - }; - - auto runScenario = [&](FeatureBitset features, TER expectedTer) -> Result { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const lender{"vaultOwner"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const iouAsset = issuer["USD"]; - STAmount const iouLimit{iouAsset.raw(), Number{9'999'999'999'999'999LL}}; - env(trust(lender, iouLimit)); - env(trust(borrower, iouLimit)); - env(pay(issuer, lender, iouAsset(1'000'000))); - env(pay(issuer, borrower, iouAsset(1'000'000))); - env.close(); - - auto const broker = createVaultAndBroker( - env, - iouAsset, - lender, - {.vaultDeposit = 100'000, .debtMax = 0, .managementFeeRate = TenthBips16{0}}); - - auto const brokerSle = env.le(broker.brokerKeylet()); - BEAST_EXPECT(brokerSle); - auto const loanSequence = brokerSle ? brokerSle->at(sfLoanSequence) : 0; - auto const loanKeylet = keylet::loan(broker.brokerID, loanSequence); - - env(set(borrower, broker.brokerID, principalRequested), - Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32{1}), - kPaymentTotal(2), - kPaymentInterval(400), - Fee(env.current()->fees().base * 2), - Ter(expectedTer)); - env.close(); - - Result r; - r.ter = env.ter(); - if (auto const loanSle = env.le(loanKeylet)) - { - r.created = true; - r.loanScale = loanSle->at(sfLoanScale); - r.principal = loanSle->at(sfPrincipalOutstanding); - r.totalValue = loanSle->at(sfTotalValueOutstanding); - r.managementFee = loanSle->at(sfManagementFeeOutstanding); - r.periodicPayment = loanSle->at(sfPeriodicPayment); - } - return r; - }; - - Result const fixed = runScenario(all_, tesSUCCESS); - Result const legacy = runScenario(all_ - fixCleanup3_2_0, tecPRECISION_LOSS); - - // Without the amendment, the catastrophically-cancelling closed-form - // payment factor produces a degenerate amortization that fails - // checkLoanGuards: the LoanSet is rejected with tecPRECISION_LOSS and no - // loan is created. - BEAST_EXPECT(legacy.ter == tecPRECISION_LOSS); - BEAST_EXPECT(!legacy.created); - - // With the amendment the stable series expansion produces a valid loan - // at loanScale -10. - BEAST_EXPECT(fixed.ter == tesSUCCESS); - BEAST_EXPECT(fixed.created); - BEAST_EXPECT(fixed.loanScale == -10); - BEAST_EXPECT(fixed.principal == principalRequested); - BEAST_EXPECT((fixed.totalValue == Number{10000000001903, -10})); - BEAST_EXPECT(fixed.managementFee == beast::kZero); - - // Periodic payment from the numerically-stable series expansion, and the - // scheduled total (2 * periodicPayment) which exceeds the 1000 principal - // — no economic underpayment / yield theft. - BEAST_EXPECT((fixed.periodicPayment == Number{5000000000951293762, -16})); - BEAST_EXPECT((fixed.periodicPayment * 2 == Number{1000000000190258752, -15})); - BEAST_EXPECT(fixed.periodicPayment * 2 > principalRequested); - } - - // An overpayment whose residual amount has more precision than loanScale - // fires the isRounded(asset, overpayment, loanScale) assertion in - // computeOverpaymentComponents (and a downstream "interest paid agrees" - // assertion in doOverpayment). fixCleanup3_2_0 rounds the residual down - // to loanScale before passing it in. The pre-amendment path can't be - // tested here because the assertion fires in Debug builds and aborts - // the test process — see the PR description for context. - void - testBugOverpayUnroundedAmount() - { - testcase("bug: computeOverpaymentComponents isRounded assertion"); - - using namespace jtx; - using namespace loan; - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"vaultOwner"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const iouAsset = issuer["USD"]; - STAmount const iouLimit{iouAsset.raw(), Number{9'999'999'999'999'999LL}}; - env(trust(lender, iouLimit)); - env(trust(borrower, iouLimit)); - env(pay(issuer, lender, iouAsset(1'000'000))); - env(pay(issuer, borrower, iouAsset(1'000'000))); - env.close(); - - auto const broker = createVaultAndBroker( - env, - iouAsset, - lender, - {.vaultDeposit = 100'000, - .debtMax = 5000, - .managementFeeRate = TenthBips16{1000}, - .vaultScale = 1}); - - auto const sleBroker = env.le(broker.brokerKeylet()); - if (!BEAST_EXPECT(sleBroker)) - return; - auto const loanSequence = sleBroker->at(sfLoanSequence); - auto const loanKeylet = keylet::loan(broker.brokerID, loanSequence); - - using namespace loan; - env(set(borrower, broker.brokerID, Number{1000}, tfLoanOverpayment), - Sig(sfCounterpartySignature, lender), - kInterestRate(TenthBips32{10000}), - kPaymentTotal(12), - kPaymentInterval(60), - kGracePeriod(60), - kOverpaymentFee(TenthBips32{1000}), - kOverpaymentInterestRate(TenthBips32{1000}), - Fee(env.current()->fees().base * 2), - Ter(tesSUCCESS)); - env.close(); - - // periodic * 1.5 at 15-sig-digit precision: 125.000154585042. This - // has too many digits to round cleanly to loanScale=-10, so the - // overpayment residual fails the isRounded check. - STAmount const payAmount{iouAsset.raw(), Number{125'000'154'585'042LL, -12}}; - env(pay(borrower, loanKeylet.key, payAmount), Txflags(tfLoanOverpayment), Ter(tesSUCCESS)); - env.close(); - } - - // Regression for the dual-rounding fix at coarse (integer-MPT) scale. - // - // Loan: P=1, r=50% (50000 tenth-bips), n=3, yearly interval. The - // amortization schedule produces a fractional principal - // (~0.47) which under round-to-nearest collapses to 0 in a single - // step, causing `doPayment`'s strict `>` assertion on principal to - // fire mid-loan. With fixCleanup3_2_0 enabled, principal is rounded - // upward (sticks at 1 across the first two periods) and only clears - // in the final payment. - // - // The test pays one period at a time across three LoanPay - // transactions and verifies the loan completes (paymentRemaining=0) - // with totals matching the loan's economics (1 principal + 2 interest). - void - testIntegerScalePrincipalSticks(FeatureBitset features) - { - // Without fixCleanup3_2_0, this behavior will abort the server, so - // don't run without it. - if (!features[fixCleanup3_2_0]) - return; - - testcase("edge: integer MPT principal stuck mid-loan completes via final"); - - using namespace jtx; - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(100'000), issuer, lender, borrower); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.maxAmt = 100'000, .flags = tfMPTCanTransfer}); - PrettyAsset const asset{mptt.issuanceID()}; - - mptt.authorize({.account = lender}); - mptt.authorize({.account = borrower}); - - env(pay(issuer, lender, asset(10'000))); - env(pay(issuer, borrower, asset(10'000))); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = lender, .asset = asset}); - env(vaultTx); - env.close(); - - env(vault.deposit({.depositor = lender, .id = vaultKeylet.key, .amount = asset(5'000)})); - env.close(); - - auto const brokerKeylet = keylet::loanbroker(lender.id(), env.seq(lender)); - env(loanBroker::set(lender, vaultKeylet.key), - loanBroker::kDebtMaximum(Number{100}), - Fee(env.current()->fees().base * 2)); - env.close(); - - auto const brokerStateBefore = env.le(brokerKeylet); - if (!BEAST_EXPECT(brokerStateBefore)) - return; - auto const loanSequence = brokerStateBefore->at(sfLoanSequence); - auto const loanKeylet = keylet::loan(brokerKeylet.key, loanSequence); - - env(loan::set(borrower, brokerKeylet.key, Number{1}), - Sig(sfCounterpartySignature, lender), - loan::kInterestRate(TenthBips32{50'000}), - loan::kPaymentTotal(3), - loan::kPaymentInterval(31'536'000), - Fee(env.current()->fees().base * 2)); - env.close(); - - auto const borrowerStart = env.balance(borrower, asset).value(); - - // Three separate periodic payments of 1 each. Expected per-period - // evolution at integer MPT scale (TVO = PO + interestDue + - // managementFeeDue): - // start: PO=1, TVO=3, paymentRemaining=3 - // after pay #1: PO=1, TVO=2, paymentRemaining=2 (principal sticks) - // after pay #2: PO=1, TVO=1, paymentRemaining=1 (principal sticks) - // after pay #3: PO=0, TVO=0, paymentRemaining=0 (final clears) - std::array const expectedPO{Number{1}, Number{1}, Number{0}}; - std::array const expectedTVO{Number{2}, Number{1}, Number{0}}; - std::array const expectedRemaining{2, 1, 0}; - - for (int i = 0; i < 3; ++i) - { - env(loan::pay(borrower, loanKeylet.key, asset(1)), Ter(tesSUCCESS)); - env.close(); - - auto const sle = env.le(loanKeylet); - if (!BEAST_EXPECT(sle)) - return; - BEAST_EXPECT(sle->at(sfPrincipalOutstanding) == expectedPO[i]); - BEAST_EXPECT(sle->at(sfTotalValueOutstanding) == expectedTVO[i]); - BEAST_EXPECT(sle->at(sfPaymentRemaining) == expectedRemaining[i]); - } - - // Borrower paid 3 total regardless of fee split (1 principal + 2 - // interest+fee, matching loan economics). - auto const borrowerEnd = env.balance(borrower, asset).value(); - BEAST_EXPECT(borrowerStart - borrowerEnd == asset(3).value()); - } - - // A near-zero interest rate on a 100 USD loan - // produces total interest of ~6 units at loanScale -9. Numerical error - // in the amortization formula pushes the theoretical principal above - // the theoretical value, producing a negative theoretical interest. - // The payment delta then exceeds the actual outstanding interest, - // violating XRPL_ASSERT_PARTS in computePaymentComponents. - void - testBugInterestDueDeltaCrash() - { - testcase("bug: LoanPay asserts 'interest due delta' on near-zero rate"); - - using namespace jtx; - using namespace std::chrono_literals; - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const iouAsset = issuer["USD"]; - env(trust(lender, iouAsset(1'000'000'000))); - env(trust(borrower, iouAsset(1'000'000'000))); - env(pay(issuer, lender, iouAsset(5'000'000))); - env(pay(issuer, borrower, iouAsset(5'000'000))); - env.close(); - - BrokerParameters const brokerParams{ - .vaultDeposit = 1'000'000, - .debtMax = 1'000'000, - .coverRateMin = TenthBips32{0}, - .coverDeposit = 0, - .managementFeeRate = TenthBips16{0}, - .coverRateLiquidation = TenthBips32{0}}; - - BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender, brokerParams)}; - - using namespace loan; - - auto const loanSetFee = Fee(env.current()->fees().base * 2); - Number const principalRequest{100}; - - auto createJson = env.json( - set(borrower, broker.brokerID, principalRequest), - Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); - - createJson["InterestRate"] = 1; // minimum non-zero rate - createJson["PaymentTotal"] = 3; - createJson["PaymentInterval"] = 600; - - auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); - auto const loanSequence = brokerStateBefore->at(sfLoanSequence); - auto const keylet = keylet::loan(broker.brokerID, loanSequence); - - createJson = env.json(createJson, Sig(sfCounterpartySignature, lender)); - env(createJson, Ter(tesSUCCESS)); - env.close(); - - // For principal=100, n=3 the amortization schedule produces a - // periodic payment ≈ 33.33 USD. We pay 35 USD, which is more than - // one period's worth — enough for the LoanPay path to enter - // computePaymentComponents and reach the assertion that fires - // when the bug is present. With the fix, the tx applies cleanly. - env(pay(borrower, keylet.key, iouAsset(35)), Ter(tesSUCCESS)); - env.close(); - } - - // Integration test: full lifecycle of a $1B loan in the bug regime. - // Verifies that the vault collects the economically-correct interest - // income and that conservation holds at the trust-line level. - // - // Pre-fix (closed-form `power(1+r, n) - 1`): vault collected only - // ~$0.058 per $1B due to cancellation of `(1+r)^n - 1` at r*n ~ 5.7e-10. - // Post-fix (hybrid binomial path): vault collects ~$0.38 per $1B, - // matching the value computed independently with arbitrary-precision - // Decimal arithmetic. - void - testFullLifecycleVaultPnLNearZeroRate() - { - testcase("integration: full loan lifecycle, vault interest at near-zero rate"); - - using namespace jtx; - using namespace jtx::loan; - using namespace std::chrono_literals; - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const iouAsset = issuer["USD"]; - STAmount const trustLimit{iouAsset.raw(), Number{1, 17}}; - env(trust(lender, trustLimit)); - env(trust(borrower, trustLimit)); - env.close(); - env(pay(issuer, lender, iouAsset(5'000'000'000LL))); - env(pay(issuer, borrower, iouAsset(5'000'000'000LL))); - env.close(); - - auto usdBalance = [&](Account const& a) { - return env.balance(a, iouAsset.raw().get()).value(); - }; - STAmount const borrowerStartBal = usdBalance(borrower); - - BrokerParameters const brokerParams{ - .vaultDeposit = Number{2, 9}, - .debtMax = Number{0}, - .coverRateMin = TenthBips32{0}, - .coverDeposit = 0, - .managementFeeRate = TenthBips16{0}, - .coverRateLiquidation = TenthBips32{0}}; - BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender, brokerParams)}; - - auto const vaultBefore = env.le(broker.vaultKeylet()); - BEAST_EXPECT(vaultBefore); - Number const vaultAvailableBefore = vaultBefore->at(sfAssetsAvailable); - - // Loan: $1B principal, 3 payments, 600s interval, rate=1 TenthBips32. - auto const loanSetFee = Fee(env.current()->fees().base * 2); - Number const principalRequest{1, 9}; - auto createJson = env.json( - set(borrower, broker.brokerID, principalRequest), - Fee(loanSetFee), - Json(sfCounterpartySignature, json::ValueType::Object)); - createJson["InterestRate"] = 1; - createJson["PaymentTotal"] = 3; - createJson["PaymentInterval"] = 600; - - auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); - auto const loanSequence = brokerStateBefore->at(sfLoanSequence); - auto const loanKeylet = keylet::loan(broker.brokerID, loanSequence); - createJson = env.json(createJson, Sig(sfCounterpartySignature, lender)); - env(createJson, Ter(tesSUCCESS)); - env.close(); - - auto const loanSle = env.le(loanKeylet); - BEAST_EXPECT(loanSle); - Number const expectedTotalInterest = - loanSle->at(sfTotalValueOutstanding) - loanSle->at(sfPrincipalOutstanding); - - env(pay(borrower, loanKeylet.key, iouAsset(1'500'000'000LL)), Ter(tesSUCCESS)); - env.close(); - - auto const vaultAfter = env.le(broker.vaultKeylet()); - Number const vaultAvailableAfter = vaultAfter->at(sfAssetsAvailable); - Number const vaultGain = vaultAvailableAfter - vaultAvailableBefore; - - STAmount const borrowerEndBal = usdBalance(borrower); - STAmount const borrowerNetOut = borrowerStartBal - borrowerEndBal; - - // Self-consistency: vault gained exactly the expected interest - // computed at LoanSet, and the borrower's outflow matches. - BEAST_EXPECT(vaultGain == expectedTotalInterest); - BEAST_EXPECT(Number(borrowerNetOut) == expectedTotalInterest); - - // Mathematical correctness: the total interest for this loan - // configuration is 0.38051750382930729983, calculated - // independently using 50-digit Decimal arithmetic (no - // cancellation possible at that precision). At Number's 19-digit - // mantissa this rounds to 0.38051750382930729 — the literal - // below. The vault's actual gain must agree to within - // sub-microcent precision. - Number const decimalReference{38051750382930729LL, -17}; - Number const tolerance{1, -6}; // 1e-6 USD = sub-microcent - Number const error = abs(vaultGain - decimalReference); - BEAST_EXPECTS( - error < tolerance, - "vault gain " + to_string(vaultGain) + " differs from Decimal reference " + - to_string(decimalReference) + " by " + to_string(error) + " — exceeds tolerance " + - to_string(tolerance)); - } - - // Verify that LoanPay, LoanBrokerCoverWithdraw, and LoanSet all use the - // same vault-scale minimum cover when fixCleanup3_2_0 is enabled. - // Before the amendment, each transactor computed its minimum cover at a - // different precision (loanScale, debtScale, or the raw unrounded - // tenthBipsOfValue), which could lead to inconsistent decisions for the - // same broker state. After the amendment all three use - // minimumBrokerCover at vaultScale. - void - testMinimumBrokerCoverConsistency(FeatureBitset features) - { - using namespace jtx; - using namespace loan; - using namespace loanBroker; - - bool const withAmendment = features[fixCleanup3_2_0]; - - struct Ctx - { - jtx::Account issuer; - jtx::Account lender; - jtx::Account borrower; - jtx::PrettyAsset iou; - BrokerInfo broker; - BrokerParameters brokerParams; - }; - - // Shared setup, parametrized by vaultDeposit (the only varying setup - // field across the three scenarios). Each call runs in its own Env - // so multiple invocations within one scenario cannot interfere. - // The caller is responsible for invoking testcase(...) before the - // first runTest call of each scenario. - auto runTest = [&](Number vaultDeposit, auto&& body) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000'000), issuer, lender, borrower); - env.close(); - - // Enable clawback on the issuer *before* any trust lines exist - // (asfAllowTrustLineClawback requires an empty owner directory). - env(fset(issuer, asfAllowTrustLineClawback)); - env.close(); - - PrettyAsset const iou = issuer[iouCurrency_]; - env(trust(lender, iou(1'000'000'000))); - env(trust(borrower, iou(1'000'000'000))); - env.close(); - env(pay(issuer, lender, iou(100'000'000))); - env(pay(issuer, borrower, iou(100'000'000))); - env.close(); - - // 13.37% — non-round rate produces a messier minimum. - BrokerParameters const brokerParams{ - .vaultDeposit = vaultDeposit, - .debtMax = 0, - .coverRateMin = TenthBips32{13'370}, - .coverDeposit = 5'000, - .managementFeeRate = TenthBips16{500}}; - - BrokerInfo const broker = createVaultAndBroker(env, iou, lender, brokerParams); - - body( - env, - Ctx{.issuer = issuer, - .lender = lender, - .borrower = borrower, - .iou = iou, - .broker = broker, - .brokerParams = brokerParams}); - }; - - // Scenario 1 — LoanPay - // - // Verify that LoanPay's minimum cover check uses vault scale (not - // loan scale). Before the amendment, different loans could produce - // different fee routing decisions for the same broker-level state. - // Small vault deposit => vaultScale = -12. - testcase("LoanPay minimum cover scale consistency"); - { - struct LoanKeylets - { - Keylet tiny; - Keylet big; - }; - - // Create the tiny + big loans and reduce cover via clawback so - // that subsequent LoanPay calls hit the minimum-cover boundary. - // Used by the two pay-and-check sub-tests below so each can run - // in its own Env. - auto setupLoansAndClawback = [&](Env& env, Ctx const& c) -> std::optional { - Asset const asset{c.iou}; - - // Create the TINY loan first (while vaultScale is still - // small). principal 0.01, 0% interest, 1 payment => - // loanScale = vaultScale. - auto const brokerSle1 = env.le(keylet::loanbroker(c.broker.brokerID)); - if (!BEAST_EXPECT(brokerSle1)) - return std::nullopt; - auto const tinyLoanSeq = brokerSle1->at(sfLoanSequence); - auto const tinyLoanKeylet = keylet::loan(c.broker.brokerID, tinyLoanSeq); - - env(set(c.borrower, c.broker.brokerID, Number{1, -2}), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{0}), - kPaymentTotal(1), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - env.close(); - - // Create the BIG loan second. 100% annual interest over 20 - // payments pushes totalValueOutstanding high enough that - // loanScale > vaultScale. - auto const brokerSle2 = env.le(keylet::loanbroker(c.broker.brokerID)); - if (!BEAST_EXPECT(brokerSle2)) - return std::nullopt; - auto const bigLoanSeq = brokerSle2->at(sfLoanSequence); - auto const bigLoanKeylet = keylet::loan(c.broker.brokerID, bigLoanSeq); - - env(set(c.borrower, c.broker.brokerID, Number{500}), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{100'000}), - kPaymentTotal(20), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - env.close(); - - // The tiny loan's scale is frozen at the vault's pre-big-loan - // scale, so it is strictly smaller than the big loan's. - // After the big loan is created the vault absorbs its value, - // pushing vaultScale up to match bigLoanScale. - auto const tinyLoanSle = env.le(tinyLoanKeylet); - auto const bigLoanSle = env.le(bigLoanKeylet); - auto const vaultSle = env.le(keylet::vault(c.broker.vaultID)); - if (!BEAST_EXPECT(tinyLoanSle) || !BEAST_EXPECT(bigLoanSle) || - !BEAST_EXPECT(vaultSle)) - return std::nullopt; - if (!BEAST_EXPECT(tinyLoanSle->at(sfLoanScale) == -12) || - !BEAST_EXPECT(bigLoanSle->at(sfLoanScale) == -11) || - !BEAST_EXPECT(getAssetsTotalScale(vaultSle) == -11)) - return std::nullopt; - - // Use issuer clawback to reduce cover to the minimum the - // clawback transactor allows. Compute the amount as - // initialCover - expectedCoverAfter so we exercise the exact - // clawback rather than relying on the transactor to clip - // down. - // - // Before the amendment the clawback minimum is the - // *unrounded* tenthBipsOfValue — strictly less than the - // rounded-at-vaultScale minimum LoanPay uses for the big - // loan. After the amendment both clawback and LoanPay use - // the same rounded minimum (via minimumBrokerCover), so - // cover lands exactly at that threshold. - Number const expectedCoverAfter = withAmendment ? Number{1330651855688460000, -15} - : Number{1330651855688458000, -15}; - Number const clawbackAmount = - Number{c.brokerParams.coverDeposit} - expectedCoverAfter; - - env(coverClawback(c.issuer), - kLoanBrokerId(c.broker.brokerID), - kAmount(STAmount{asset, clawbackAmount})); - env.close(); - - auto const brokerSle = env.le(keylet::loanbroker(c.broker.brokerID)); - if (!BEAST_EXPECT(brokerSle) || - !BEAST_EXPECT(brokerSle->at(sfCoverAvailable) == expectedCoverAfter)) - return std::nullopt; - - return LoanKeylets{.tiny = tinyLoanKeylet, .big = bigLoanKeylet}; - }; - - // Pay one loan and report whether the fee went to the broker's - // pseudo account (the fallback when cover < minimum) rather - // than to the owner. - auto feeGoesToPseudo = [&](Env& env, Ctx const& c, Keylet const& loanKeylet) -> bool { - Asset const asset{c.iou}; - auto const brokerSle = env.le(keylet::loanbroker(c.broker.brokerID)); - if (!BEAST_EXPECT(brokerSle)) - return false; - auto const pseudoAcct = Account("pseudo", brokerSle->at(sfAccount)); - auto const pseudoBefore = env.balance(pseudoAcct, c.iou); - - auto const payLoan = env.le(loanKeylet); - if (!BEAST_EXPECT(payLoan)) - return false; - auto const periodicPayment = payLoan->at(sfPeriodicPayment); - auto const serviceFee = payLoan->at(sfLoanServiceFee); - std::int32_t const loanScale = payLoan->at(sfLoanScale); - - auto const payment = roundPeriodicPayment(asset, periodicPayment, loanScale); - auto const payAmt = STAmount{asset, payment + serviceFee}; - - env(loan::pay(c.borrower, loanKeylet.key, payAmt), Fee(XRP(10))); - env.close(); - - auto const pseudoAfter = env.balance(pseudoAcct, c.iou); - return pseudoAfter.number() > pseudoBefore.number(); - }; - - // Pay the BIG loan in its own Env so its outcome cannot affect - // the TINY-loan check. With the fix, LoanPay and clawback use - // the same vaultScale minimum (cover == minAtVaultScale => - // fee to owner). Without the fix, LoanPay uses bigLoanScale=-11, - // rounds up to a larger minimum than what clawback used => - // cover < min => fee to pseudo. - runTest(/*vaultDeposit=*/1'000, [&](Env& env, Ctx const& c) { - auto const loans = setupLoansAndClawback(env, c); - if (!loans) - return; - BEAST_EXPECT(feeGoesToPseudo(env, c, loans->big) == !withAmendment); - }); - - // Pay the TINY loan in its own Env. Fee goes to the owner - // either way: - // - With the fix: LoanPay uses vaultScale=-11 (same as - // clawback) => owner. - // - Without the fix: LoanPay uses tinyLoanScale=-12, rounds - // up at -12 (a no-op) => min == cover => owner. - runTest(/*vaultDeposit=*/1'000, [&](Env& env, Ctx const& c) { - auto const loans = setupLoansAndClawback(env, c); - if (!loans) - return; - BEAST_EXPECT(!feeGoesToPseudo(env, c, loans->tiny)); - }); - } - - // Scenario 2 — LoanBrokerCoverWithdraw - // - // Verify that CoverWithdraw's minimum cover check uses vault scale - // (not scale(debtTotal, asset)). Before the amendment, CoverWithdraw - // used: - // roundToAsset(asset, tenthBipsOfValue(debt, rate), scale(debt, asset)) - // which could disagree with LoanPay's minimum (which used loanScale). - // - // Use a large vault deposit so that vaultScale (from AssetsTotal) is - // strictly larger than debtScale (from DebtTotal). With - // vaultDeposit = 100,000: after the big loan - // AssetsTotal ≈ 109,500 → vaultScale = -10 - // DebtTotal ≈ 10,000 → debtScale = -11 - // The one-order-of-magnitude gap makes roundToAsset at -10 truncate - // more aggressively than at -11, exposing the bug. - testcase("CoverWithdraw minimum cover scale consistency"); - runTest( - /*vaultDeposit=*/100'000, [&](Env& env, Ctx const& c) { - Asset const asset{c.iou}; - - // Create only the big loan to push DebtTotal up to ~10,000 - // while AssetsTotal stays around 109,500 (dominated by the - // large vault deposit). - env(set(c.borrower, c.broker.brokerID, Number{500}), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{100'000}), - kPaymentTotal(20), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - env.close(); - - // Read broker state and compute both old and new minimums. - auto const brokerSle = env.le(keylet::loanbroker(c.broker.brokerID)); - auto const vaultSle = env.le(keylet::vault(c.broker.vaultID)); - if (!BEAST_EXPECT(brokerSle) || !BEAST_EXPECT(vaultSle)) - return; - - auto const coverAvail = brokerSle->at(sfCoverAvailable); - auto const debtTotal = brokerSle->at(sfDebtTotal); - auto const vaultScale = getAssetsTotalScale(vaultSle); - auto const debtScale = scale(debtTotal, asset); - - // Sanity: debt scale differs from vault scale for this setup. - BEAST_EXPECT(debtScale < vaultScale); - - auto const oldMin = [&]() { - NumberRoundModeGuard const mg(Number::RoundingMode::Upward); - return roundToAsset( - asset, - tenthBipsOfValue(debtTotal, TenthBips32{c.brokerParams.coverRateMin}), - debtScale); - }(); - auto const newMin = minimumBrokerCover( - debtTotal, TenthBips32{c.brokerParams.coverRateMin}, vaultSle); - - // The new (vaultScale) minimum must be strictly larger than - // the old (debtScale) minimum — that is the gap the amendment - // closes. - Number const expectedNewMin{1330650518688500000, -15}; - Number const expectedOldMin{1330650518688472000, -15}; - BEAST_EXPECT(newMin == expectedNewMin); - BEAST_EXPECT(oldMin == expectedOldMin); - - // Try to withdraw so that remaining cover lands between the - // two minimums: oldMin < target < newMin. - auto const target = oldMin + (newMin - oldMin) / 2; - auto const withdrawAmount = STAmount{asset, coverAvail - target}; - - if (withAmendment) - { - // CoverWithdraw now uses vaultScale: target < newMin - // => FAILS. - env(coverWithdraw(c.lender, c.broker.brokerID, withdrawAmount), - Ter(tecINSUFFICIENT_FUNDS)); - } - else - { - // Old CoverWithdraw uses debtScale: target > oldMin - // => SUCCEEDS. - env(coverWithdraw(c.lender, c.broker.brokerID, withdrawAmount)); - } - env.close(); - }); - - // Scenario 3 — LoanSet - // - // Verify that LoanSet's minimum cover check uses vault scale (not the - // raw unrounded tenthBipsOfValue). Before the amendment, LoanSet - // used tenthBipsOfValue(newDebtTotal, coverRateMinimum) (no - // roundToAsset), while clawback/withdraw used different formulas. - // After the amendment all use minimumBrokerCover at vaultScale, and - // rounding at a coarser scale can absorb a tiny debt increase — - // allowing a loan that would otherwise be rejected. - testcase("LoanSet minimum cover scale consistency"); - runTest( - /*vaultDeposit=*/1'000, [&](Env& env, Ctx const& c) { - // Create the tiny loan (scale -12) AND the big loan (scale - // -11). Both loans are needed so that DebtTotal has a full - // 16-digit mantissa — a "messy" value where roundToAsset at - // vaultScale actually truncates digits and produces a - // different result from the raw tenthBipsOfValue. With only - // the big loan, DebtTotal has ~4 significant digits and - // rounding at scale -11 is a no-op, masking the amendment's - // effect. - env(set(c.borrower, c.broker.brokerID, Number{1, -2}), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{0}), - kPaymentTotal(1), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - env.close(); - - env(set(c.borrower, c.broker.brokerID, Number{500}), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{100'000}), - kPaymentTotal(20), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - env.close(); - - // Clawback to reduce cover to the clawback transactor's - // minimum. Pass the exact amount rather than relying on the - // transactor to clip down; the setup matches Scenario 1 so - // the same residual-cover values apply. - Number const expectedCoverAfter = withAmendment ? Number{1330651855688460000, -15} - : Number{1330651855688458000, -15}; - Number const clawbackAmount = - Number{c.brokerParams.coverDeposit} - expectedCoverAfter; - env(coverClawback(c.issuer), - kLoanBrokerId(c.broker.brokerID), - kAmount(c.iou(clawbackAmount))); - env.close(); - - // Verify scales. - auto const vaultSle = env.le(keylet::vault(c.broker.vaultID)); - if (!BEAST_EXPECT(vaultSle)) - return; - auto const vaultScale = getAssetsTotalScale(vaultSle); - BEAST_EXPECT(vaultScale == -11); - - // Now try to create a tiny additional loan. Principal is - // 1e-11 (the smallest value that survives the precision - // check at loanScale = vaultScale = -11), with 0% interest - // and 1 payment. - // - // The tiny debt increase adds ~1.337e-12 to the unrounded - // minimum. - // - Without the amendment: the old LoanSet formula rounds - // up during tenthBipsOfValue (16-digit Number - // normalisation), pushing the minimum past the cover left - // by clawback => tecINSUFFICIENT_FUNDS. - // - With the amendment: minimumBrokerCover rounds at - // vaultScale=-11, which absorbs the tiny increase — the - // rounded minimum stays the same => tesSUCCESS. - auto const tinyPrincipal = Number{1, -11}; - - if (withAmendment) - { - env(set(c.borrower, c.broker.brokerID, tinyPrincipal), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{0}), - kPaymentTotal(1), - kPaymentInterval(86400 * 365), - Fee(XRP(10))); - } - else - { - env(set(c.borrower, c.broker.brokerID, tinyPrincipal), - Sig(sfCounterpartySignature, c.lender), - kInterestRate(TenthBips32{0}), - kPaymentTotal(1), - kPaymentInterval(86400 * 365), - Fee(XRP(10)), - Ter(tecINSUFFICIENT_FUNDS)); - } - env.close(); - }); - } - - void - runAmendmentIndependent() - { - testDisabled(); - testInvalidLoanSet(); - testInvalidLoanDelete(); - testInvalidLoanManage(); - testInvalidLoanPay(); - testIssuerLoan(); - testServiceFeeOnBrokerDeepFreeze(); - testRequireAuth(); - testRIPD3901(); - testBorrowerIsBroker(); - testLimitExceeded(); - testLoanSetBlockedLoanPayAllowedWhenCanTransferCleared(); - testLendingCanTradeClearedNoImpact(); - testBugOverpaymentPrincipalChange(); - testBugOverpayUnroundedAmount(); - - for (auto const flags : {0u, tfLoanOverpayment}) - testYieldTheftRounding(flags); - testBugInterestDueDeltaCrash(); - testFullLifecycleVaultPnLNearZeroRate(); - testLoanSetNearZeroInterestRateSucceeds(); - } - - // Tests run under each entry in amendmentCombinations(). - void - runAmendmentSensitive(FeatureBitset features) - { -#if LOAN_TODO - testLoanPayLateFullPaymentBypassesPenalties(features); - testLoanCoverMinimumRoundingExploit(features); -#endif - // Lifecycle - testLifecycle(features); - testLoanSet(features); - testDosLoanPay(features); - testSelfLoan(features); - - // Payment paths - testWithdrawReflectsUnrealizedLoss(features); - testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic(features); - testBatchBypassCounterparty(features); - testLoanNextPaymentDueDateOverflow(features); - testCoverDepositWithdrawNonTransferableMPT(features); - testSequentialFLCDepletion(features); - - // Invariants - testLoanPayComputePeriodicPaymentValidRateInvariant(features); - testAccountSendMptMinAmountInvariant(features); - testLoanPayDebtDecreaseInvariant(features); - testWrongMaxDebtBehavior(features); - testLoanPayComputePeriodicPaymentValidTotalInterestInvariant(features); - testLoanPayComputePeriodicPaymentValidTotalPrincipalPaidInvariant(features); - testLoanPayComputePeriodicPaymentValidTotalInterestPaidInvariant(features); - - // RPC - testRPC(features); - - // Edge / rounding - testDustManipulation(features); - testRoundingAllowsUndercoverage(features); - testOverpaymentManagementFee(features); - testIssuerIsBorrower(features); - testIntegerScalePrincipalSticks(features); - testMinimumBrokerCoverConsistency(features); - - // RIPD regressions - testRIPD3831(features); - testRIPD3459(features); - testRIPD3902(features); - - // Broker-owner permissions - testLoanPayBrokerOwnerMissingTrustline(features); - testLoanPayBrokerOwnerUnauthorizedMPT(features); - testLoanPayBrokerOwnerNoPermissionedDomainMPT(features); - testLoanSetBrokerOwnerNoPermissionedDomainMPT(features); - } - public: void run() override { - runAmendmentIndependent(); - for (auto const& features : - amendmentCombinations({fixCleanup3_1_3, fixCleanup3_2_0, featureMPTokensV2})) - runAmendmentSensitive(features); +#if LOAN_TODO + testLoanPayLateFullPaymentBypassesPenalties(); + testLoanCoverMinimumRoundingExploit(); +#endif + testWithdrawReflectsUnrealizedLoss(); + testInvalidLoanSet(); + + auto const all = jtx::testableAmendments(); + testCoverDepositWithdrawNonTransferableMPT(all); + testCoverDepositWithdrawNonTransferableMPT(all - featureMPTokensV2); + testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic(); + + testDisabled(); + testSelfLoan(); + testIssuerLoan(); + testLoanSet(); + testLifecycle(); + testServiceFeeOnBrokerDeepFreeze(); + + testRPC(); + testInvalidLoanDelete(); + testInvalidLoanManage(); + testInvalidLoanPay(); + + testBatchBypassCounterparty(); + testLoanPayComputePeriodicPaymentValidRateInvariant(); + testAccountSendMptMinAmountInvariant(); + testLoanPayDebtDecreaseInvariant(); + testWrongMaxDebtBehavior(); + testLoanPayComputePeriodicPaymentValidTotalInterestInvariant(); + testDosLoanPay(); + testLoanPayComputePeriodicPaymentValidTotalPrincipalPaidInvariant(); + testLoanPayComputePeriodicPaymentValidTotalInterestPaidInvariant(); + testLoanNextPaymentDueDateOverflow(); + + testRequireAuth(); + testDustManipulation(); + + testRIPD3831(); + testRIPD3459(); + testRIPD3901(); + testRIPD3902(); + testRoundingAllowsUndercoverage(); + testBorrowerIsBroker(); + testIssuerIsBorrower(); + testLimitExceeded(); + testOverpaymentManagementFee(); + testLoanPayBrokerOwnerMissingTrustline(); + testLoanPayBrokerOwnerUnauthorizedMPT(); + testLoanPayBrokerOwnerNoPermissionedDomainMPT(); + testLoanSetBrokerOwnerNoPermissionedDomainMPT(); + testSequentialFLCDepletion(); } }; @@ -8854,7 +7334,7 @@ protected: .payInterval = payInterval, }; - runLoan(assetType, brokerParams, loanParams, all_); + runLoan(assetType, brokerParams, loanParams); } public: @@ -8913,7 +7393,7 @@ class LoanArbitrary_test : public LoanBatch_test .payTotal = 2, .payInterval = 200}; - runLoan(AssetType::XRP, brokerParams, loanParams, all_); + runLoan(AssetType::XRP, brokerParams, loanParams); } }; diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 1ceeed3033..24aee2c6e9 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -25,18 +25,14 @@ #include #include #include -#include #include #include #include #include -#include -#include #include #include #include -#include #include #include #include @@ -51,7 +47,6 @@ #include #include #include -#include #include #include #include @@ -60,17 +55,13 @@ #include #include -#include #include #include #include -#include -#include #include #include #include #include -#include #include #include #include @@ -157,7 +148,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.create( {.maxAmt = 100, .assetScale = 0, - .transferFee = kMaxTransferFee + 1, + .transferFee = kMAX_TRANSFER_FEE + 1, .metadata = "test", .flags = tfMPTCanTransfer, .err = temBAD_TRANSFER_FEE}); @@ -166,7 +157,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.create( {.maxAmt = 100, .assetScale = 0, - .transferFee = kMaxTransferFee, + .transferFee = kMAX_TRANSFER_FEE, .metadata = "test", .err = temMALFORMED}); @@ -194,28 +185,12 @@ class MPToken_test : public beast::unit_test::Suite .metadata = "test", .err = temMALFORMED}); mptAlice.create( - {.maxAmt = kMaxMpTokenAmount + 1, // 9'223'372'036'854'775'808 + {.maxAmt = kMAX_MP_TOKEN_AMOUNT + 1, // 9'223'372'036'854'775'808 .assetScale = 0, .transferFee = 0, .metadata = "test", .err = temMALFORMED}); } - - // sfReferenceHolding is populated internally only by VaultCreate. - // A user-submitted MPTokenIssuanceCreate carrying the field must be - // rejected at preflight under fixCleanup3_2_0. - if (features[fixCleanup3_2_0]) - { - Env env{*this, features}; - env.fund(XRP(1'000), alice); - env.close(); - - json::Value jv; - jv[sfAccount] = alice.human(); - jv[sfTransactionType] = jss::MPTokenIssuanceCreate; - jv[sfReferenceHolding] = to_string(uint256{1}); - env(jv, Ter(temMALFORMED)); - } } void @@ -232,7 +207,7 @@ class MPToken_test : public beast::unit_test::Suite Env env{*this, features}; MPTTester mptAlice(env, alice); mptAlice.create( - {.maxAmt = kMaxMpTokenAmount, // 9'223'372'036'854'775'807 + {.maxAmt = kMAX_MP_TOKEN_AMOUNT, // 9'223'372'036'854'775'807 .assetScale = 1, .transferFee = 10, .metadata = "123", @@ -241,8 +216,7 @@ class MPToken_test : public beast::unit_test::Suite tfMPTCanTransfer | tfMPTCanClawback}); // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; json::Value const result = env.rpc("tx", txHash)[jss::result]; BEAST_EXPECT(result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); @@ -262,13 +236,13 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer1, credentials1)); auto const domainId1 = [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); MPTTester mptAlice(env, alice); mptAlice.create({ - .maxAmt = kMaxMpTokenAmount, // 9'223'372'036'854'775'807 + .maxAmt = kMAX_MP_TOKEN_AMOUNT, // 9'223'372'036'854'775'807 .assetScale = 1, .transferFee = 10, .metadata = "123", @@ -280,7 +254,7 @@ class MPToken_test : public beast::unit_test::Suite // Get the hash for the most recent transaction. std::string const txHash{ - env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString()}; + env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; json::Value const result = env.rpc("tx", txHash)[jss::result]; BEAST_EXPECT(result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); @@ -845,7 +819,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -859,7 +833,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer2, credentials2)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -1122,7 +1096,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -1164,7 +1138,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -1221,7 +1195,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer1, credentials)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -1233,7 +1207,7 @@ class MPToken_test : public beast::unit_test::Suite env(pdomain::setTx(credIssuer2, credentials)); return [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); }(); @@ -1543,7 +1517,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.authorize({.account = bob}); // issuer sends holder the default max amount allowed - mptAlice.pay(alice, bob, kMaxMpTokenAmount); + mptAlice.pay(alice, bob, kMAX_MP_TOKEN_AMOUNT); // issuer tries to exceed max amount auto const err = mpTokensV2 ? tecPATH_DRY : tecPATH_PARTIAL; @@ -1559,7 +1533,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(kMaxMpTokenAmount + 1); + jv[jss::tx_json][jss::Amount][jss::value] = std::to_string(kMAX_MP_TOKEN_AMOUNT + 1); auto const jrr = env.rpc("json", "submit", to_string(jv)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); } @@ -1588,8 +1562,7 @@ class MPToken_test : public beast::unit_test::Suite // payment between the holders env(pay(bob, carol, mpt(10'000)), Sendmax(mpt(10'000)), Txflags(tfPartialPayment)); // Verify the metadata - auto const meta = - env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName]; + auto const meta = env.meta()->getJson(JsonOptions::KNone)[sfAffectedNodes.fieldName]; // Issuer got 10 in the transfer fees BEAST_EXPECT( meta[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName] @@ -1618,7 +1591,7 @@ class MPToken_test : public beast::unit_test::Suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); mptAlice.create( - {.maxAmt = kMaxMpTokenAmount, + {.maxAmt = kMAX_MP_TOKEN_AMOUNT, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); @@ -1628,14 +1601,14 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.authorize({.account = carol}); // issuer sends holder the max amount allowed - mptAlice.pay(alice, bob, kMaxMpTokenAmount); - BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(kMaxMpTokenAmount)); + mptAlice.pay(alice, bob, kMAX_MP_TOKEN_AMOUNT); + BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(kMAX_MP_TOKEN_AMOUNT)); // payment between the holders - mptAlice.pay(bob, carol, kMaxMpTokenAmount); - BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(kMaxMpTokenAmount)); + mptAlice.pay(bob, carol, kMAX_MP_TOKEN_AMOUNT); + BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(kMAX_MP_TOKEN_AMOUNT)); // holder pays back to the issuer - mptAlice.pay(carol, alice, kMaxMpTokenAmount); + mptAlice.pay(carol, alice, kMAX_MP_TOKEN_AMOUNT); BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(0)); } @@ -1803,7 +1776,7 @@ class MPToken_test : public beast::unit_test::Suite env.close(); // Bob authorize credentials - env(deposit::authCredentials(bob, {{.issuer = dpIssuer, .credType = credType}})); + env(deposit::authCredentials(bob, {{dpIssuer, credType}})); env.close(); // alice try to send 100 MPT to bob, not authorized @@ -1939,7 +1912,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::Asset] = toJson(xrpIssue()); jv[jss::Asset2] = toJson(usd.issue()); if (withAmount) - jv[field.fieldName] = usd(10).value().getJson(JsonOptions::Values::None); + jv[field.fieldName] = usd(10).value().getJson(JsonOptions::KNone); if (field == sfAsset) { jv[jss::Asset] = toJson(mpt.get()); @@ -1950,7 +1923,7 @@ class MPToken_test : public beast::unit_test::Suite } else { - jv[field.fieldName] = mpt.getJson(JsonOptions::Values::None); + jv[field.fieldName] = mpt.getJson(JsonOptions::KNone); } }; // All transactions with sfAmount, which don't support MPT. @@ -1997,7 +1970,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::Destination] = carol.human(); jv[jss::SettleDelay] = 1; jv[sfPublicKey.fieldName] = strHex(alice.pk().slice()); - jv[jss::Amount] = mpt.getJson(JsonOptions::Values::None); + jv[jss::Amount] = mpt.getJson(JsonOptions::KNone); test(jv, jss::Amount.cStr()); } // PaymentChannelFund @@ -2006,7 +1979,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::PaymentChannelFund; jv[jss::Account] = alice.human(); jv[sfChannel.fieldName] = to_string(uint256{1}); - jv[jss::Amount] = mpt.getJson(JsonOptions::Values::None); + jv[jss::Amount] = mpt.getJson(JsonOptions::KNone); test(jv, jss::Amount.cStr()); } // PaymentChannelClaim @@ -2015,7 +1988,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::PaymentChannelClaim; jv[jss::Account] = alice.human(); jv[sfChannel.fieldName] = to_string(uint256{1}); - jv[jss::Amount] = mpt.getJson(JsonOptions::Values::None); + jv[jss::Amount] = mpt.getJson(JsonOptions::KNone); test(jv, jss::Amount.cStr()); } // NFTokenCreateOffer @@ -2024,7 +1997,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::NFTokenCreateOffer; jv[jss::Account] = alice.human(); jv[sfNFTokenID.fieldName] = to_string(uint256{1}); - jv[jss::Amount] = mpt.getJson(JsonOptions::Values::None); + jv[jss::Amount] = mpt.getJson(JsonOptions::KNone); test(jv, jss::Amount.cStr()); } // NFTokenAcceptOffer @@ -2032,7 +2005,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::Values::None); + jv[sfNFTokenBrokerFee.fieldName] = mpt.getJson(JsonOptions::KNone); test(jv, sfNFTokenBrokerFee.fieldName); } // NFTokenMint @@ -2041,7 +2014,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::NFTokenMint; jv[jss::Account] = alice.human(); jv[sfNFTokenTaxon.fieldName] = 1; - jv[jss::Amount] = mpt.getJson(JsonOptions::Values::None); + jv[jss::Amount] = mpt.getJson(JsonOptions::KNone); test(jv, jss::Amount.cStr()); } // TrustSet @@ -2050,7 +2023,7 @@ class MPToken_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::TrustSet; jv[jss::Account] = alice.human(); jv[jss::Flags] = 0; - jv[field.fieldName] = mpt.getJson(JsonOptions::Values::None); + jv[field.fieldName] = mpt.getJson(JsonOptions::KNone); test(jv, field.fieldName); }; trustSet(sfLimitAmount); @@ -2082,7 +2055,7 @@ class MPToken_test : public beast::unit_test::Suite 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::Values::None); + jv[field] = mpt.getJson(JsonOptions::KNone); test(jv, field); } } @@ -2091,7 +2064,7 @@ class MPToken_test : public beast::unit_test::Suite json::Value jv = sidechainXchainAccountCreate(alice, jvb, alice, mpt, XRP(10)); for (auto const& field : {sfAmount.fieldName, sfSignatureReward.fieldName}) { - jv[field] = mpt.getJson(JsonOptions::Values::None); + jv[field] = mpt.getJson(JsonOptions::KNone); test(jv, field); } } @@ -2104,9 +2077,9 @@ 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::Values::None); + jv[sfSignatureReward.fieldName] = rewardAmount.getJson(JsonOptions::KNone); jv[sfMinAccountCreateAmount.fieldName] = - minAccountAmount.getJson(JsonOptions::Values::None); + minAccountAmount.getJson(JsonOptions::KNone); test(jv, field); }; auto reward = STAmount{sfSignatureReward, mpt}; @@ -2123,864 +2096,6 @@ class MPToken_test : public beast::unit_test::Suite BEAST_EXPECT(txWithAmounts.empty()); } - void - testNonCanonicalMPTAmountCleanup(FeatureBitset features) - { - using namespace test::jtx; - using namespace std::literals; - FeatureBitset const withoutFix = features - fixCleanup3_2_0; - FeatureBitset const withFix = features | fixCleanup3_2_0; - FeatureBitset const withoutFixAndV2 = withoutFix - featureMPTokensV2; - FeatureBitset const withFixAndWithoutV2 = withFix - featureMPTokensV2; - - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const gw{"gw"}; - - using MPTValue = MPTAmount::value_type; - MPTValue const mptMin = std::numeric_limits::min(); - MPTValue const mptMax = std::numeric_limits::max(); - std::uint64_t const u64Max = std::numeric_limits::max(); - std::uint64_t const firstInvalidMPTMantissa = static_cast(mptMax) + 1; - MPTValue const alice0 = 10'000; - MPTValue const gw0 = -20'000; - TER const success = tesSUCCESS; - TER const invariantFailed = tecINVARIANT_FAILED; - TER const pathPartial = tecPATH_PARTIAL; - TER const badAmountTer = temBAD_AMOUNT; - - struct BadMPTAmount - { - std::string_view name; - std::uint64_t mantissa; - bool negative; - MPTValue mptValue; - TER issuerToHolderPreFixTer; - TER holderSourcePreFixTer; - MPTValue issuerToHolderAliceAfterPreFix; - MPTValue issuerToHolderIssuerAfterPreFix; - MPTValue issuerToHolderAliceAfterPostFix; - MPTValue issuerToHolderIssuerAfterPostFix; - }; - // clang-format off - std::array const badMPTAmounts = {{ - { .name="INT64_MAX + 1", .mantissa=firstInvalidMPTMantissa, .negative=false, .mptValue=mptMin, .issuerToHolderPreFixTer=invariantFailed, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0, .issuerToHolderIssuerAfterPreFix=gw0, .issuerToHolderAliceAfterPostFix=alice0 - 1, .issuerToHolderIssuerAfterPostFix=gw0 + 1}, - { .name="INT64_MAX + 10", .mantissa=firstInvalidMPTMantissa + 9, .negative=false, .mptValue=mptMin + 9, .issuerToHolderPreFixTer=invariantFailed, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0, .issuerToHolderIssuerAfterPreFix=gw0, .issuerToHolderAliceAfterPostFix=alice0 - 1, .issuerToHolderIssuerAfterPostFix=gw0 + 1}, - { .name="UINT64_MAX - 9998", .mantissa=u64Max - 9'998, .negative=false, .mptValue=MPTValue{-9'999}, .issuerToHolderPreFixTer=success, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0 - 9'999, .issuerToHolderIssuerAfterPreFix=gw0 + 9'999, .issuerToHolderAliceAfterPostFix=alice0 - 10'000, .issuerToHolderIssuerAfterPostFix=gw0 + 10'000}, - { .name="UINT64_MAX - 9", .mantissa=u64Max - 9, .negative=false, .mptValue=MPTValue{-10}, .issuerToHolderPreFixTer=success, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0 - 10, .issuerToHolderIssuerAfterPreFix=gw0 + 10, .issuerToHolderAliceAfterPostFix=alice0 - 11, .issuerToHolderIssuerAfterPostFix=gw0 + 11}, - { .name="UINT64_MAX - 1", .mantissa=u64Max - 1, .negative=false, .mptValue=MPTValue{-2}, .issuerToHolderPreFixTer=success, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0 - 2, .issuerToHolderIssuerAfterPreFix=gw0 + 2, .issuerToHolderAliceAfterPostFix=alice0 - 3, .issuerToHolderIssuerAfterPostFix=gw0 + 3}, - { .name="UINT64_MAX", .mantissa=u64Max, .negative=false, .mptValue=MPTValue{-1}, .issuerToHolderPreFixTer=success, .holderSourcePreFixTer=pathPartial, .issuerToHolderAliceAfterPreFix=alice0 - 1, .issuerToHolderIssuerAfterPreFix=gw0 + 1, .issuerToHolderAliceAfterPostFix=alice0 - 2, .issuerToHolderIssuerAfterPostFix=gw0 + 2}, - { .name="-2", .mantissa=std::uint64_t{2}, .negative=true, .mptValue=MPTValue{-2}, .issuerToHolderPreFixTer=badAmountTer, .holderSourcePreFixTer=badAmountTer, .issuerToHolderAliceAfterPreFix=alice0, .issuerToHolderIssuerAfterPreFix=gw0, .issuerToHolderAliceAfterPostFix=alice0 - 1, .issuerToHolderIssuerAfterPostFix=gw0 + 1} - }}; - // clang-format on - auto const badMPTAmount = [&](MPTIssue const& issue, BadMPTAmount const& bad) { - return STAmount{issue, bad.mantissa, 0, bad.negative, STAmount::Unchecked{}}; - }; - auto const makeIssue = [&](Env& env) { - MPTTester const mpt{ - {.env = env, - .issuer = gw, - .holders = {alice, bob}, - .pay = 10'000, - .flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanEscrow | tfMPTCanClawback}}; - return MPTIssue{mpt.issuanceID()}; - }; - auto const withNonCanonicalMPTAmount = - [](JTx jt, SField const& field, STAmount const& amount, Account const& signer) { - STTx tx{*jt.stx}; - tx.setFieldAmount(field, amount); - tx.sign(signer.pk(), signer.sk()); - jt.stx = std::make_shared(tx); - return jt; - }; - auto const roundTrip = [](STTx const& tx) { - Serializer s; - tx.add(s); - SerialIter sit{s.slice()}; - return STTx{sit}; - }; - auto const expectRoundTripBadMPT = - [&](JTx const& jt, SField const& field, BadMPTAmount const& bad) { - auto const roundTripped = roundTrip(*jt.stx); - auto const persisted = roundTripped.getFieldAmount(field); - BEAST_EXPECT(persisted.holds()); - BEAST_EXPECT(persisted.mantissa() == bad.mantissa); - BEAST_EXPECT(persisted.exponent() == 0); - BEAST_EXPECT(persisted.negative() == bad.negative); - BEAST_EXPECT(persisted.mpt().value() == bad.mptValue); - if (!bad.negative) - BEAST_EXPECT(persisted.mantissa() > kMaxMpTokenAmount); - }; - - for (auto const& bad : badMPTAmounts) - { - testcase("fixCleanup3_2_0 rejects non-canonical MPT Payment amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto malformedHolderToHolder = withNonCanonicalMPTAmount( - env.jt(pay(alice, bob, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - alice); - expectRoundTripBadMPT(malformedHolderToHolder, sfAmount, bad); - malformedHolderToHolder.ter = bad.holderSourcePreFixTer; - env.submit(malformedHolderToHolder); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'000}, issue})); - - env.enableFeature(fixCleanup3_2_0); - env.close(); - env(env.jt(pay(bob, alice, STAmount{issue, std::uint64_t{1}})), Ter{tesSUCCESS}); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'001}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{9'999}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'000}, issue})); - } - { - Env env{*this, envconfig(), withoutFixAndV2, nullptr, beast::Severity::Disabled}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto malformedIssuerToHolder = withNonCanonicalMPTAmount( - env.jt(pay(gw, alice, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - gw); - expectRoundTripBadMPT(malformedIssuerToHolder, sfAmount, bad); - malformedIssuerToHolder.ter = bad.issuerToHolderPreFixTer; - env.submit(malformedIssuerToHolder); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == - STAmount{MPTAmount{bad.issuerToHolderAliceAfterPreFix}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == - STAmount{MPTAmount{bad.issuerToHolderIssuerAfterPreFix}, issue})); - - env.enableFeature(fixCleanup3_2_0); - env.close(); - env(env.jt(pay(alice, gw, STAmount{issue, std::uint64_t{1}})), Ter{tesSUCCESS}); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == - STAmount{MPTAmount{bad.issuerToHolderAliceAfterPostFix}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == - STAmount{MPTAmount{bad.issuerToHolderIssuerAfterPostFix}, issue})); - } - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto malformedHolderToIssuer = withNonCanonicalMPTAmount( - env.jt(pay(alice, gw, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - alice); - expectRoundTripBadMPT(malformedHolderToIssuer, sfAmount, bad); - malformedHolderToIssuer.ter = bad.holderSourcePreFixTer; - env.submit(malformedHolderToIssuer); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'000}, issue})); - - env.enableFeature(fixCleanup3_2_0); - env.close(); - env(env.jt(pay(gw, alice, STAmount{issue, std::uint64_t{1}})), Ter{tesSUCCESS}); - env.close(); - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'001}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'001}, issue})); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(pay(alice, bob, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(pay(gw, alice, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - gw); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(pay(alice, gw, STAmount{issue, std::uint64_t{1}})), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("fixCleanup3_2_0 rejects non-canonical MPT Check amounts"); - { - Env env{*this, envconfig(), withoutFix, nullptr, beast::Severity::Disabled}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badSendMax = badMPTAmount(issue, bad); - auto const checkSeq = env.seq(alice); - auto tx = withNonCanonicalMPTAmount( - env.jt(check::create(alice, bob, STAmount{issue, std::uint64_t{10}})), - sfSendMax, - badSendMax, - alice); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tesSUCCESS}; - env.submit(tx); - env.close(); - - auto const checkKeylet = keylet::check(alice.id(), checkSeq); - auto const sleCheck = env.le(checkKeylet); - BEAST_EXPECT((sleCheck != nullptr) == !bad.negative); - if (sleCheck && !bad.negative) - { - auto const persisted = sleCheck->getFieldAmount(sfSendMax); - BEAST_EXPECT(persisted.holds()); - BEAST_EXPECT(persisted.mantissa() == bad.mantissa); - BEAST_EXPECT(persisted.negative() == bad.negative); - } - } - { - Env env{*this, envconfig(), withoutFix, nullptr, beast::Severity::Disabled}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badSendMax = badMPTAmount(issue, bad); - auto const checkSeq = env.seq(alice); - auto tx = withNonCanonicalMPTAmount( - env.jt(check::create(alice, bob, STAmount{issue, std::uint64_t{10}})), - sfSendMax, - badSendMax, - alice); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tesSUCCESS}; - env.submit(tx); - env.close(); - - auto const checkKeylet = keylet::check(alice.id(), checkSeq); - BEAST_EXPECT((env.le(checkKeylet) != nullptr) == !bad.negative); - if (!bad.negative) - { - // CheckCancel has no amount fields, but it must be able to - // remove a malformed legacy Check while the fix is disabled. - env(env.jt(check::cancel(alice, checkKeylet.key)), Ter{tesSUCCESS}); - env.close(); - BEAST_EXPECT(env.le(checkKeylet) == nullptr); - } - } - { - Env env{*this, envconfig(), withoutFix, nullptr, beast::Severity::Disabled}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badSendMax = badMPTAmount(issue, bad); - auto const checkSeq = env.seq(alice); - auto tx = withNonCanonicalMPTAmount( - env.jt(check::create(alice, bob, STAmount{issue, std::uint64_t{10}})), - sfSendMax, - badSendMax, - alice); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tesSUCCESS}; - env.submit(tx); - env.close(); - - auto const checkKeylet = keylet::check(alice.id(), checkSeq); - BEAST_EXPECT((env.le(checkKeylet) != nullptr) == !bad.negative); - if (!bad.negative) - { - env.enableFeature(fixCleanup3_2_0); - env.close(); - - // Once the fix is enabled, CheckCancel should still remove - // a legacy Check because it does not consume the bad amount. - env(env.jt(check::cancel(alice, checkKeylet.key)), Ter{tesSUCCESS}); - env.close(); - BEAST_EXPECT(env.le(checkKeylet) == nullptr); - } - } - { - Env env{*this, envconfig(), withoutFix, nullptr, beast::Severity::Disabled}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badSendMax = badMPTAmount(issue, bad); - auto const checkSeq = env.seq(alice); - auto tx = withNonCanonicalMPTAmount( - env.jt(check::create(alice, bob, STAmount{issue, std::uint64_t{10}})), - sfSendMax, - badSendMax, - alice); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tesSUCCESS}; - env.submit(tx); - env.close(); - - auto const checkKeylet = keylet::check(alice.id(), checkSeq); - BEAST_EXPECT((env.le(checkKeylet) != nullptr) == !bad.negative); - if (!bad.negative) - { - env.enableFeature(fixCleanup3_2_0); - env.close(); - - auto const cashAmount = STAmount{sfAmount, issue, std::uint64_t{1}, 0, false}; - env(env.jt(check::cash(bob, checkKeylet.key, cashAmount)), Ter{tefBAD_LEDGER}); - env.close(); - BEAST_EXPECT(env.le(checkKeylet) != nullptr); - } - } - { - Env env{*this, withoutFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const sendMax = STAmount{sfSendMax, issue, std::uint64_t{10}, 0, false}; - auto const checkSeq = env.seq(alice); - env(env.jt(check::create(alice, bob, sendMax)), Ter{tesSUCCESS}); - env.close(); - - auto const badCashAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - check::cash( - bob, - keylet::check(alice.id(), checkSeq).key, - STAmount{issue, std::uint64_t{1}})), - sfAmount, - badCashAmount, - bob); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = bad.holderSourcePreFixTer; - env.submit(tx); - env.close(); - BEAST_EXPECT(env.le(keylet::check(alice.id(), checkSeq)) != nullptr); - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'000}, issue})); - } - { - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const sendMax = STAmount{sfSendMax, issue, std::uint64_t{10}, 0, false}; - auto const checkSeq = env.seq(alice); - env(env.jt(check::create(alice, bob, sendMax)), Ter{tesSUCCESS}); - env.close(); - - auto const badCashAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - check::cash( - bob, - keylet::check(alice.id(), checkSeq).key, - STAmount{issue, std::uint64_t{1}})), - sfAmount, - badCashAmount, - bob); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("fixCleanup3_2_0 rejects non-canonical MPT Escrow amounts"); - { - Env env{*this, withoutFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const escrowSeq = env.seq(alice); - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - escrow::create(alice, bob, STAmount{issue, std::uint64_t{1}}), - escrow::kFinishTime(env.now() + 1s)), - sfAmount, - badAmount, - alice); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tecINSUFFICIENT_FUNDS}; - env.submit(tx); - env.close(); - BEAST_EXPECT(env.le(keylet::escrow(alice.id(), escrowSeq)) == nullptr); - } - { - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - escrow::create(alice, bob, STAmount{issue, std::uint64_t{1}}), - escrow::kFinishTime(env.now() + 1s)), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("fixCleanup3_2_0 rejects non-canonical MPT Clawback amounts"); - { - Env env{*this, withoutFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(claw(gw, STAmount{issue, std::uint64_t{1}}, bob)), - sfAmount, - badAmount, - gw); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = bad.negative ? TER{temBAD_AMOUNT} : TER{tesSUCCESS}; - env.submit(tx); - env.close(); - - MPTValue const bobAfter = bad.negative ? MPTValue{10'000} : MPTValue{0}; - MPTValue const gwAfter = bad.negative ? MPTValue{-20'000} : MPTValue{-10'000}; - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{bobAfter}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{gwAfter}, issue})); - } - { - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(claw(gw, STAmount{issue, std::uint64_t{1}}, bob)), - sfAmount, - badAmount, - gw); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - env.close(); - - BEAST_EXPECT( - (env.balance(alice, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(bob, issue).value() == STAmount{MPTAmount{10'000}, issue})); - BEAST_EXPECT( - (env.balance(gw, issue).value() == STAmount{MPTAmount{-20'000}, issue})); - } - - testcase("featureMPTokensV2 disabled rejects MPT OfferCreate amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badTakerPays = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(offer(alice, STAmount{issue, std::uint64_t{1}}, XRP(10))), - sfTakerPays, - badTakerPays, - alice); - expectRoundTripBadMPT(tx, sfTakerPays, bad); - tx.ter = temDISABLED; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badTakerPays = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(offer(alice, STAmount{issue, std::uint64_t{1}}, XRP(10))), - sfTakerPays, - badTakerPays, - alice); - tx.ter = temDISABLED; - env.submit(tx); - } - { - // sfTakerPays is MPT: both amendments active. Negative offers - // fail in OfferCreate::preflight() before the universal check; - // positive non-canonical amounts fail in the universal check. - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badTakerPays = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(offer(alice, STAmount{issue, std::uint64_t{1}}, XRP(10))), - sfTakerPays, - badTakerPays, - alice); - tx.ter = TER{temBAD_AMOUNT}; - env.submit(tx); - } - { - // sfTakerGets is MPT: both amendments active. Negative offers - // fail in OfferCreate::preflight() before the universal check; - // positive non-canonical amounts fail in the universal check. - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badTakerGets = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt(offer(alice, XRP(10), STAmount{issue, std::uint64_t{1}})), - sfTakerGets, - badTakerGets, - alice); - tx.ter = TER{temBAD_AMOUNT}; - env.submit(tx); - } - - testcase("featureMPTokensV2 disabled rejects MPT AMMCreate amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::createJv(alice.id(), STAmount{issue, std::uint64_t{1}}, XRP(1), 0), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = temDISABLED; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::createJv(alice.id(), STAmount{issue, std::uint64_t{1}}, XRP(1), 0), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temDISABLED; - env.submit(tx); - } - { - // sfAmount is MPT: both amendments active, expect temBAD_AMOUNT - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::createJv(alice.id(), STAmount{issue, std::uint64_t{1}}, XRP(1), 0), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("featureMPTokensV2 disabled rejects MPT AMMDeposit amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::depositJv( - {.account = alice, - .asset1In = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = temDISABLED; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::depositJv( - {.account = alice, - .asset1In = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temDISABLED; - env.submit(tx); - } - { - // sfAmount is MPT: both amendments active, expect temBAD_AMOUNT - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::depositJv( - {.account = alice, - .asset1In = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("featureMPTokensV2 disabled rejects MPT AMMWithdraw amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::withdrawJv( - {.account = alice, - .asset1Out = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = temDISABLED; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::withdrawJv( - {.account = alice, - .asset1Out = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temDISABLED; - env.submit(tx); - } - { - // sfAmount is MPT: both amendments active, expect temBAD_AMOUNT - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - AMM::withdrawJv( - {.account = alice, - .asset1Out = STAmount{issue, std::uint64_t{1}}, - .assets = std::make_pair(Asset{issue}, Asset{xrpIssue()})}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - alice); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("featureMPTokensV2 disabled rejects MPT AMMClawback amounts"); - { - Env env{*this, withoutFixAndV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - amm::ammClawback( - gw, - alice, - Asset{issue}, - Asset{xrpIssue()}, - std::make_optional(STAmount{issue, std::uint64_t{1}})), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - gw); - expectRoundTripBadMPT(tx, sfAmount, bad); - tx.ter = temDISABLED; - env.submit(tx); - } - { - Env env{*this, withFixAndWithoutV2}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - amm::ammClawback( - gw, - alice, - Asset{issue}, - Asset{xrpIssue()}, - std::make_optional(STAmount{issue, std::uint64_t{1}})), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - gw); - tx.ter = temDISABLED; - env.submit(tx); - } - { - // sfAmount is MPT: both amendments active, expect temBAD_AMOUNT - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - auto tx = withNonCanonicalMPTAmount( - env.jt( - amm::ammClawback( - gw, - alice, - Asset{issue}, - Asset{xrpIssue()}, - std::make_optional(STAmount{issue, std::uint64_t{1}})), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - gw); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - - testcase("fixCleanup3_2_0 rejects non-canonical MPT VaultClawback amounts"); - { - Env env{*this, withFix}; - env.fund(XRP(100'000), alice, bob, gw); - env.close(); - auto const issue = makeIssue(env); - - auto const badAmount = badMPTAmount(issue, bad); - uint256 const fakeVaultId = keylet::vault(gw.id(), 1).key; - auto tx = withNonCanonicalMPTAmount( - env.jt( - Vault::clawback( - {.issuer = gw, - .id = fakeVaultId, - .holder = alice, - .amount = STAmount{issue, std::uint64_t{1}}}), - Fee(static_cast(env.current()->fees().increment.drops()))), - sfAmount, - badAmount, - gw); - tx.ter = temBAD_AMOUNT; - env.submit(tx); - } - } - } - void testTxJsonMetaFields(FeatureBitset features) { @@ -2992,14 +2107,13 @@ class MPToken_test : public beast::unit_test::Suite Account const alice{"alice"}; auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env{*this, std::move(cfg), features}; MPTTester mptAlice(env, alice); mptAlice.create(); - std::string const txHash{ - env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; BEAST_EXPECTS( txHash == "E11F0E0CA14219922B7881F060B9CEE67CFBC87E4049A441ED2AE348FF8FAC" @@ -3150,7 +2264,7 @@ class MPToken_test : public beast::unit_test::Suite 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(kMaxMpTokenAmount + 1); + jv[jss::Amount][jss::value] = std::to_string(kMAX_MP_TOKEN_AMOUNT + 1); json::Value jv1; jv1[jss::secret] = alice.name(); jv1[jss::tx_json] = jv; @@ -3597,7 +2711,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); - std::string const metadata(kMaxMpTokenMetadataLength + 1, 'a'); + std::string const metadata(kMAX_MP_TOKEN_METADATA_LENGTH + 1, 'a'); mptAlice.set({.account = alice, .metadata = metadata, .err = temMALFORMED}); } @@ -3621,7 +2735,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.set( {.account = alice, .id = mptID, - .transferFee = kMaxTransferFee + 1, + .transferFee = kMAX_TRANSFER_FEE + 1, .err = temBAD_TRANSFER_FEE}); } @@ -3775,8 +2889,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, kMaxTransferFee}) + for (std::uint16_t const fee : std::initializer_list{ + 1, 10, 100, 200, 500, 1000, kMAX_TRANSFER_FEE}) { mptAlice.set({.account = alice, .transferFee = fee}); BEAST_EXPECT(mptAlice.checkTransferFee(fee)); @@ -4036,23 +3150,23 @@ class MPToken_test : public beast::unit_test::Suite // MPTCanEscrow is not enabled env(escrow::create(carol, bob, mpt(3)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); // MPTCanEscrow is enabled now mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanEscrow}); env(escrow::create(carol, bob, mpt(3)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150)); // Clear MPTCanEscrow mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanEscrow}); env(escrow::create(carol, bob, mpt(3)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tecNO_PERMISSION)); } @@ -4195,7 +3309,7 @@ class MPToken_test : public beast::unit_test::Suite testMultiSendMaximumAmount(FeatureBitset features) { // Verify that directSendNoLimitMultiMPT correctly enforces MaximumAmount - // when the issuer sends to multiple receivers. Pre-fixCleanup3_1_3, + // when the issuer sends to multiple receivers. Pre-fixSecurity3_1_3, // a stale view.read() snapshot caused per-iteration checks to miss // aggregate overflows. Post-fix, a running total is used instead. testcase("Multi-send MaximumAmount enforcement"); @@ -4206,11 +3320,11 @@ class MPToken_test : public beast::unit_test::Suite Account const alice("alice"); Account const bob("bob"); - static constexpr std::uint64_t kMaxAmt = 150; + std::uint64_t constexpr kMAX_AMT = 150; Env env{*this, features}; MPTTester mptTester(env, issuer, {.holders = {alice, bob}}); - mptTester.create({.maxAmt = kMaxAmt, .ownerCount = 1, .flags = tfMPTCanTransfer}); + mptTester.create({.maxAmt = kMAX_AMT, .ownerCount = 1, .flags = tfMPTCanTransfer}); mptTester.authorize({.account = alice}); mptTester.authorize({.account = bob}); @@ -4247,14 +3361,14 @@ class MPToken_test : public beast::unit_test::Suite std::nullopt, "aggregate exceeds max"); - runTest(R{{alice.id(), 75}, {bob.id(), 75}}, tesSUCCESS, kMaxAmt, "aggregate at boundary"); + runTest(R{{alice.id(), 75}, {bob.id(), 75}}, tesSUCCESS, kMAX_AMT, "aggregate at boundary"); runTest(R{{alice.id(), 50}, {bob.id(), 50}}, tesSUCCESS, 100, "aggregate within limit"); runTest( R{{alice.id(), 150}, {bob.id(), 0}}, tesSUCCESS, - kMaxAmt, + kMAX_AMT, "one receiver at max, other zero"); runTest( @@ -4272,7 +3386,7 @@ class MPToken_test : public beast::unit_test::Suite runTest( R{{alice.id(), 50}, {bob.id(), 50}}, tesSUCCESS, - kMaxAmt, + kMAX_AMT, "nonzero outstanding, aggregate at boundary"); runTest( @@ -4284,7 +3398,7 @@ class MPToken_test : public beast::unit_test::Suite runTest( R{{alice.id(), 100}, {bob.id(), 0}}, tesSUCCESS, - kMaxAmt, + kMAX_AMT, "nonzero outstanding, single send at remaining capacity"); runTest( @@ -4297,14 +3411,14 @@ class MPToken_test : public beast::unit_test::Suite // individual send (100 <= 150) even though the aggregate (200) // exceeds MaximumAmount. Preserved for ledger replay. { - // KNOWN BUG (pre-fixCleanup3_1_3): preserved for ledger replay only - env.disableFeature(fixCleanup3_1_3); + // KNOWN BUG (pre-fixSecurity3_1_3): preserved for ledger replay only + env.disableFeature(fixSecurity3_1_3); runTest( R{{alice.id(), 100}, {bob.id(), 100}}, tesSUCCESS, 250, "pre-amendment allows over-send"); - env.enableFeature(fixCleanup3_1_3); + env.enableFeature(fixSecurity3_1_3); } } @@ -4366,10 +3480,10 @@ class MPToken_test : public beast::unit_test::Suite auto const [errBuy, errSell] = [&]() -> std::pair { // Global lock if (lockMPTIssue) - return std::make_pair(tecLOCKED, tecLOCKED); + return std::make_pair(tecFROZEN, tecFROZEN); // Local lock if (lockMPToken) - return std::make_pair(error(tecLOCKED), error(tecUNFUNDED_OFFER)); + return std::make_pair(tesSUCCESS, error(tecUNFUNDED_OFFER)); // MPToken doesn't exist if (requireAuth) return std::make_pair(error(tecNO_AUTH), error(tecUNFUNDED_OFFER)); @@ -4432,77 +3546,51 @@ class MPToken_test : public beast::unit_test::Suite env(offer(alice, btc(10), eth(10)), Ter(tecUNFUNDED_OFFER)); } - // MPTLock flag is set: MPT/MPT offer crossing with independent issuers. - // gw2 issues BTC and gw issues ETH so each asset can be frozen independently. - // Passive setup: bob sells BTC (offer(bob, ETH, BTC)); dan sells ETH (offer(dan, BTC, - // ETH)). + // MPTLock flag is set and the account is not the issuer of MPT { - Account const gw2 = Account("gw2"); Account const bob = Account("bob"); Account const dan = Account("dan"); Env env(*this); - env.fund(XRP(1'000), gw, gw2, alice, carol, bob, dan); + env.fund(XRP(1'000), gw, alice, carol, bob, dan); MPTTester btc( {.env = env, - .issuer = gw2, - .holders = {alice, carol, bob, dan, gw}, + .issuer = gw, + .holders = {alice, carol, bob, dan}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = gw, - .holders = {alice, carol, bob, dan, gw2}, + .holders = {alice, carol, bob, dan}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); - // bob sells BTC (takerGets=BTC); dan sells ETH (takerGets=ETH) env(offer(bob, eth(10), btc(10)), Txflags(tfPassive)); env(offer(dan, btc(10), eth(10)), Txflags(tfPassive)); - env.close(); - // --- Individual lock on BTC --- - // alice sells locked BTC (takerGets): balance zeroed, offer unfunded - btc.set({.holder = alice, .flags = tfMPTLock}); - env(offer(alice, eth(1), btc(1)), Ter(tecUNFUNDED_OFFER)); - btc.set({.holder = alice, .flags = tfMPTUnlock}); - // carol buys locked BTC (takerPays): locked MPToken cannot receive - btc.set({.holder = carol, .flags = tfMPTLock}); - env(offer(carol, btc(1), eth(1)), Ter(tecLOCKED)); - btc.set({.holder = carol, .flags = tfMPTUnlock}); - // gw2 is BTC issuer: individual lock on holders does not affect issuer - env(offer(gw2, eth(1), btc(1))); + auto test = [&](auto const& flag, bool gwOwner = false) { + btc.set({.holder = carol, .flags = flag}); + btc.set({.holder = alice, .flags = flag}); - // --- Individual lock on ETH --- - // alice sells locked ETH (takerGets): balance zeroed, offer unfunded - eth.set({.holder = alice, .flags = tfMPTLock}); - env(offer(alice, btc(1), eth(1)), Ter(tecUNFUNDED_OFFER)); - eth.set({.holder = alice, .flags = tfMPTUnlock}); - // carol buys locked ETH (takerPays): locked MPToken cannot receive - eth.set({.holder = carol, .flags = tfMPTLock}); - env(offer(carol, eth(1), btc(1)), Ter(tecLOCKED)); - eth.set({.holder = carol, .flags = tfMPTUnlock}); - // gw is ETH issuer: individual lock on holders does not affect issuer - env(offer(gw, btc(1), eth(1))); + if (gwOwner) + { + // Succeeds if the account is the issuer + env(offer(gw, eth(1), btc(1))); + env(offer(gw, btc(1), eth(1))); + } + else + { + auto const err = flag == tfMPTLock ? Ter(tecUNFUNDED_OFFER) : Ter(tesSUCCESS); + env(offer(alice, eth(1), btc(1)), err); + // Offer created by not crossed + env(offer(carol, btc(1), eth(1))); + BEAST_EXPECT(expectOffers(env, carol, 1, {{btc(1), eth(1)}})); + } + }; - // --- Global lock on BTC --- - // All accounts fail regardless of role: global lock is checked in OfferCreate - // before offer crossing, so it applies even to the issuer. - btc.set({.flags = tfMPTLock}); - env(offer(alice, eth(1), btc(1)), Ter(tecLOCKED)); // alice sells BTC - env(offer(alice, btc(1), eth(1)), Ter(tecLOCKED)); // alice buys BTC - env(offer(gw2, eth(1), btc(1)), Ter(tecLOCKED)); // gw2 is BTC issuer, still fails - btc.set({.flags = tfMPTUnlock}); - - // --- Global lock on ETH --- - eth.set({.flags = tfMPTLock}); - env(offer(alice, btc(1), eth(1)), Ter(tecLOCKED)); // alice sells ETH - env(offer(alice, eth(1), btc(1)), Ter(tecLOCKED)); // alice buys ETH - env(offer(gw, btc(1), eth(1)), Ter(tecLOCKED)); // gw is ETH issuer, still fails - eth.set({.flags = tfMPTUnlock}); - - // --- After all locks cleared: normal crossing succeeds --- - env(offer(alice, eth(1), btc(1))); - env(offer(carol, btc(1), eth(1))); + test(tfMPTLock); + test(tfMPTLock, true); + test(tfMPTUnlock); } // MPTRequireAuth flag is set and the account is not authorized @@ -4514,14 +3602,14 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 100, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); MPTTester const eth( {.env = env, .issuer = gw, .holders = {alice}, .pay = 100, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); btc.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); @@ -4717,7 +3805,6 @@ class MPToken_test : public beast::unit_test::Suite testcase("Cross Asset Payment"); using namespace test::jtx; Account const gw = Account("gw"); - Account const gw2 = Account("gw2"); Account const alice = Account("alice"); Account const carol = Account("carol"); Account const bob = Account("bob"); @@ -4829,7 +3916,7 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer}); MPTTester eth( @@ -4837,21 +3924,21 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .mutableFlags = tmfMPTCanMutateCanTransfer}); MPTTester const usd( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .mutableFlags = tmfMPTCanMutateCanTransfer}); MPTTester const cad( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .mutableFlags = tmfMPTCanMutateCanTransfer}); env(offer(bob, eth(1'000), btc(1'000)), Txflags(tfPassive)); @@ -4894,7 +3981,6 @@ class MPToken_test : public beast::unit_test::Suite env(pay(ed, gw, btc(10)), Path(~btc), Sendmax(eth(10))); // BTC is transferred from issuer to bob env(pay(gw, ed, eth(10)), Path(~eth), Sendmax(btc(10))); - // // BTC is transferred from ed to bob, ed is not authorized env(pay(ed, gw, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecNO_AUTH)); env.close(); @@ -4909,11 +3995,13 @@ class MPToken_test : public beast::unit_test::Suite env(pay(carol, ed, btc(10)), Path(~btc), Sendmax(eth(10)), Ter(tecPATH_PARTIAL)); env(pay(ed, carol, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecPATH_PARTIAL)); env(pay(carol, ed, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecPATH_PARTIAL)); - // Fail because BTC, which has CanTransfer disabled, is sent to bob + // Fail because BTC, which has CanTransfer disabled, is sent to + // bob env(pay(ed, gw, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecPATH_PARTIAL)); env(pay(ed, gw, btc(10)), Path(~btc), Sendmax(eth(10)), Ter(tesSUCCESS)); env(pay(gw, ed, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tesSUCCESS)); - // Fail because BTC, which has CanTransfer disabled, is sent to ed + // Fail because BTC, which has CanTransfer disabled, is sent to + // ed env(pay(gw, ed, btc(10)), Path(~btc), Sendmax(eth(10)), Ter(tecPATH_PARTIAL)); env.close(); env(offer(gw, eth(100), btc(100)), Txflags(tfPassive)); @@ -4939,28 +4027,28 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .mutableFlags = tmfMPTCanMutateCanTransfer}); MPTTester eth( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .mutableFlags = tmfMPTCanMutateCanTransfer}); MPTTester usd( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .mutableFlags = tmfMPTCanMutateCanTransfer}); MPTTester cad( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .mutableFlags = tmfMPTCanMutateCanTransfer}); // takerGets can transfer if: // - CanTransfer is set @@ -5088,17 +4176,7 @@ class MPToken_test : public beast::unit_test::Suite env(pay(gw, carol, usd(1)), Path(~btc, ~eth, ~usd), Sendmax(XRP(1)), - Txflags(tfPartialPayment | tfNoRippleDirect), - Ter(tecNO_PERMISSION)); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - - env(pay(carol, bob, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, bob, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); - env(pay(gw, bob, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(gw, bob, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, gw, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, gw, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); + Ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(expectOffers(env, bob, 3)); } @@ -5133,36 +4211,31 @@ class MPToken_test : public beast::unit_test::Suite auto getMPT = [&](Env& env) { MPTTester const btc( {.env = env, - .issuer = gw2, - .holders = {alice, carol, bob, gw}, + .issuer = gw, + .holders = {alice, carol, bob}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester const eth( {.env = env, .issuer = gw, - .holders = {alice, carol, bob, gw2}, + .holders = {alice, carol, bob}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); return std::make_pair(btc, eth); }; auto getIOU = [&](Env& env) { - for (auto const& a : {alice, carol, bob}) + for (auto const& iou : {gw["BTC"], gw["ETH"]}) { - env(fset(a, asfDefaultRipple)); - env.close(); - env(trust(a, gw["ETH"](200))); - env(pay(gw, a, gw["ETH"](100))); - env(trust(a, gw2["BTC"](200))); - env(pay(gw2, a, gw2["BTC"](100))); - env.close(); + for (auto const& a : {alice, carol, bob}) + { + env(fset(a, asfDefaultRipple)); + env.close(); + env(trust(a, iou(200))); + env(pay(gw, a, iou(100))); + env.close(); + } } - // gw2 needs an ETH trust line to receive ETH when its offers fill - // gw needs BTC to sell BTC - env(trust(gw2, gw["ETH"](200))); - env(trust(gw, gw2["BTC"](200))); - env(pay(gw2, gw, gw2["BTC"](100))); - env.close(); - return std::make_pair(gw2["BTC"], gw["ETH"]); + return std::make_pair(gw["BTC"], gw["ETH"]); }; auto lock = [&]( Env& env, Account const& account, Token& token, LockType lock) { @@ -5172,12 +4245,12 @@ class MPToken_test : public beast::unit_test::Suite { if (lock == LockType::Global) { - env(fset(token.account, asfGlobalFreeze)); + env(fset(gw, asfGlobalFreeze)); } else { IOU const iou{account, token.currency}; - env(trust(token.account, iou(0), tfSetFreeze)); + env(trust(gw, iou(0), tfSetFreeze)); } } else if constexpr (std::is_same_v) @@ -5194,7 +4267,7 @@ class MPToken_test : public beast::unit_test::Suite }; auto test = [&](auto&& getTokens, TestArg const& arg) { Env env(*this); - env.fund(XRP(1'000), gw, gw2, alice, carol, bob); + env.fund(XRP(1'000), gw, alice, carol, bob); auto [btc, eth] = getTokens(env); @@ -5212,7 +4285,7 @@ class MPToken_test : public beast::unit_test::Suite } if (arg.globalFlagSell != LockType::None) { - lock(env, gw2, btc, LockType::Global); + lock(env, gw, btc, LockType::Global); } else { @@ -5230,58 +4303,34 @@ class MPToken_test : public beast::unit_test::Suite }; // clang-format off std::vector const tests = { - // ----- src=alice (holder), dst=carol (holder), offerOwner=bob (holder) ----- - // alice's ETH locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = bob, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, - // carol's BTC locked: caught in MPT check(); IOU dst can still receive when frozen - {.src = alice, .dst = carol, .offerOwner = bob, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, - // ETH globally locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagBuy = LockType::Global, .err = tecPATH_DRY}, - // BTC globally locked: bob's offer unfunded in OfferStream - {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagSell = LockType::Global, .err = tecPATH_PARTIAL}, - // bob's ETH (takerPays) locked: MPT offer unfunded in OfferStream (locked holder cannot receive); IOU can still receive - {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, - // bob's BTC (takerGets) locked: offer unfunded in OfferStream - {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, - // ----- src=alice (holder), dst=carol (holder), offerOwner=gw2 (BTC issuer) ----- - // alice's ETH locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = gw2, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, - // carol's BTC locked: caught in MPT check(); IOU dst can still receive when frozen - {.src = alice, .dst = carol, .offerOwner = gw2, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, - // ETH globally locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = gw2, .globalFlagBuy = LockType::Global, .err = tecPATH_DRY}, - // BTC globally locked: gw2 is the BTC issuer, offer always permitted regardless of global freeze - {.src = alice, .dst = carol, .offerOwner = gw2, .globalFlagSell = LockType::Global, .err = tesSUCCESS}, - // ----- src=alice (holder), dst=carol (holder), offerOwner=gw (ETH issuer, BTC holder) ----- - // alice's ETH locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = gw, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, - // carol's BTC locked: caught in MPT check(); IOU dst can still receive when frozen - {.src = alice, .dst = carol, .offerOwner = gw, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, - // ETH globally locked: caught in check() - {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagBuy = LockType::Global, .err = tecPATH_DRY}, - // BTC globally locked: gw holds BTC as a holder (not BTC issuer), offer unfunded in OfferStream - {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagSell = LockType::Global, .err = tecPATH_PARTIAL}, - // ----- src=gw (ETH issuer), dst=carol (holder), offerOwner=bob (holder) ----- - // ETH globally locked, src is ETH issuer: no first MPTEndpointStep so check() passes; - // MPT offer unfunded in OfferStream (globally-locked ETH cannot flow to holder via DEX); IOU issuer can still issue - {.src = gw, .dst = carol, .offerOwner = bob, .srcFlag = LockType::Global, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, - // BTC globally locked: last MPTEndpointStep only checks individual freeze, check() passes; offer unfunded in OfferStream - {.src = gw, .dst = carol, .offerOwner = bob, .dstFlag = LockType::Global, .err = tecPATH_PARTIAL}, - // carol's BTC locked: caught in MPT check(); IOU dst can still receive when frozen - {.src = gw, .dst = carol, .offerOwner = bob, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, - // bob's ETH (takerPays) locked: MPT offer unfunded in OfferStream (locked holder cannot receive); IOU can still receive - {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, - // bob's BTC (takerGets) locked: offer unfunded in OfferStream - {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, - // ----- src=alice (holder), dst=gw2 (BTC issuer), offerOwner=bob (holder) ----- - // alice's ETH locked: caught in check() - {.src = alice, .dst = gw2, .offerOwner = bob, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, - // BTC globally locked, dst is BTC issuer: no last MPTEndpointStep so check() passes; offer unfunded in OfferStream - {.src = alice, .dst = gw2, .offerOwner = bob, .dstFlag = LockType::Global, .err = tecPATH_PARTIAL}, - // bob's ETH (takerPays) locked: MPT offer unfunded in OfferStream (locked holder cannot receive); IOU can still receive - {.src = alice, .dst = gw2, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, - // bob's BTC (takerGets) locked: offer unfunded in OfferStream - {.src = alice, .dst = gw2, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, + // src, dst, offer's owner are a holder + {.src = alice, .dst = carol, .offerOwner = bob, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, + // dst can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = bob, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagBuy = LockType::Global, .err = tecPATH_DRY}, + {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagSell = LockType::Global, .err = tecPATH_DRY}, + // offer's owner can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = + tecPATH_PARTIAL, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, + // src, dst are a holder, offer's owner is an issuer + {.src = alice, .dst = carol, .offerOwner = gw, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, + // dst can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = gw, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagBuy = LockType::Global, .err = tecPATH_DRY}, + {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagSell = LockType::Global, .err = tecPATH_DRY}, + // src is issuer, dst and offer's owner are a holder + // dst can receive IOU even if the account is frozen + {.src = gw, .dst = carol, .offerOwner = bob, .dstFlag = LockType::Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + // offer's owner can receive IOU from an issuer even if takerBuys is frozen, MPT offer is unfunded in this case + {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, + {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, + // dst is issuer, src and offer's owner are a holder + {.src = alice, .dst = gw, .offerOwner = bob, .srcFlag = LockType::Individual, .err = tecPATH_DRY}, + // offer's owner can receive IOU even if the account is frozen + {.src = alice, .dst = gw, .offerOwner = bob, .offerFlagBuy = LockType::Individual, .err = tecPATH_PARTIAL, + .errIOU = tesSUCCESS}, + {.src = alice, .dst = gw, .offerOwner = bob, .offerFlagSell = LockType::Individual, .err = tecPATH_PARTIAL}, }; // clang-format on @@ -5300,13 +4349,13 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol, bob}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); MPTTester eth( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 100, - .flags = tfMPTCanLock | kMptDexFlags}); + .flags = tfMPTCanLock | kMPT_DEX_FLAGS}); env(trust(alice, usd(100))); env(pay(gw, alice, usd(100))); @@ -6792,7 +5841,7 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol}, .pay = 100, - .flags = kMptDexFlags | tfMPTCanLock}); + .flags = kMPT_DEX_FLAGS | tfMPTCanLock}); mpt.set({.flags = tfMPTLock}); @@ -6863,7 +5912,7 @@ class MPToken_test : public beast::unit_test::Suite {.env = env, .issuer = gw, .holders = {alice, carol}, - .flags = tfMPTRequireAuth | kMptDexFlags}); + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS}); uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, carol, btc(50))); env.close(); @@ -6882,7 +5931,7 @@ class MPToken_test : public beast::unit_test::Suite env.close(); } - // MPTCanTransfer is disabled + // MPTCanTransfer disabled { Env env{*this, features}; env.fund(XRP(1'000), gw, alice, carol); @@ -6923,50 +5972,49 @@ class MPToken_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(alice, mpt) == mpt(0)); BEAST_EXPECT(env.balance(gw, mpt) == mpt(0)); - // neither src nor dst is issuer, can't create - checkId = keylet::check(alice, env.seq(alice)).key; - env(check::create(alice, carol, mpt(100)), Ter(tecNO_AUTH)); - env.close(); - - // can create now - mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTransfer}); + // neither src nor dst is issuer, can still create checkId = keylet::check(alice, env.seq(alice)).key; env(check::create(alice, carol, mpt(100))); env.close(); + + // can't cash + env(check::cash(carol, checkId, mpt(10)), Ter(tecPATH_PARTIAL)); + env.close(); + + // can cash now + mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTransfer}); env(pay(gw, alice, mpt(10))); env.close(); - // can't cash - mpt.set({.account = gw, .mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - env(check::cash(carol, checkId, mpt(10)), Ter(tecNO_AUTH)); - env.close(); - // can cash - mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTransfer}); env(check::cash(carol, checkId, mpt(10))); env.close(); } - // MPTCanTrade is disabled + // MPTCanTrade disabled { Env env{*this, features}; env.fund(XRP(1'000), gw, alice, carol); env.close(); - MPT const mpt = MPTTester( + MPTTester mpt( {.env = env, .issuer = gw, .holders = {alice, carol}, - .pay = 10, - .flags = tfMPTCanTransfer}); + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTrade}); - uint256 const checkId{keylet::check(alice, env.seq(alice)).key}; + uint256 checkId{keylet::check(gw, env.seq(gw)).key}; - // can create - env(check::create(alice, carol, mpt(100))); + // can't create + env(check::create(gw, alice, mpt(100)), Ter(tecNO_PERMISSION)); env.close(); + mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTrade}); - // can cash - env(check::cash(carol, checkId, mpt(10))); + // can't cash + checkId = keylet::check(gw, env.seq(gw)).key; + env(check::create(gw, carol, mpt(100))); + env.close(); + mpt.set({.account = gw, .mutableFlags = tmfMPTClearCanTrade}); + env(check::cash(carol, checkId, mpt(10)), Ter(tecNO_PERMISSION)); env.close(); } @@ -7011,7 +6059,7 @@ class MPToken_test : public beast::unit_test::Suite {.env = env, .issuer = gw, .holders = {alice}, - .flags = tfMPTRequireAuth | kMptDexFlags, + .flags = tfMPTRequireAuth | kMPT_DEX_FLAGS, .authHolder = true}); uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, carol, btc(1))); @@ -7021,6 +6069,33 @@ class MPToken_test : public beast::unit_test::Suite env.close(); } + // MPTCanTransfer is not set and the account is not the issuer of MPT + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + + auto eur = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol}, .flags = tfMPTCanTrade}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + // alice can create + env(check::create(alice, carol, eur(1))); + env.close(); + + // carol can't cash + env(check::cash(carol, chkId, eur(1)), Ter(tecPATH_PARTIAL)); + env.close(); + + // if issuer creates a check then carol can cash since + // it's a transfer from the issuer + uint256 const chkId1{getCheckIndex(gw, env.seq(gw))}; + // alice can't create since CanTransfer is not set + env(check::create(gw, carol, eur(1))); + env.close(); + + env(check::cash(carol, chkId1, eur(1))); + env.close(); + } + // Can create check if src/dst don't own MPT { Env env{*this, features}; @@ -7108,7 +6183,7 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000, - .flags = tfMPTCanLock | tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanLock | tfMPTCanClawback | kMPT_DEX_FLAGS}); env.trust(usd(10'000), alice); env(pay(gw, alice, usd(10'000))); @@ -7139,7 +6214,7 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 40'000, - .flags = tfMPTRequireAuth | tfMPTCanClawback | kMptDexFlags, + .flags = tfMPTRequireAuth | tfMPTCanClawback | kMPT_DEX_FLAGS, .authHolder = true}); env.trust(usd(10'000), alice); @@ -7181,7 +6256,8 @@ class MPToken_test : public beast::unit_test::Suite AMM amm(env, gw, btc(100), usd(100)); env.close(); // alice can't deposit since MPTCanTransfer is not set - amm.deposit(DepositArg{.account = alice, .tokens = 1'000, .err = Ter(tecNO_AUTH)}); + amm.deposit( + DepositArg{.account = alice, .tokens = 1'000, .err = Ter(tecNO_PERMISSION)}); env.close(); // can't clawback since alice is not an LP @@ -7222,9 +6298,9 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice}, .pay = 10'000, - .flags = tfMPTCanClawback | kMptDexFlags}); + .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); auto eur = - MPTTester({.env = env, .issuer = gw, .flags = tfMPTCanClawback | kMptDexFlags}); + MPTTester({.env = env, .issuer = gw, .flags = tfMPTCanClawback | kMPT_DEX_FLAGS}); AMM amm(env, gw, usd(1'000), eur(1'000)); amm.deposit({.account = alice, .asset1In = usd(1'000)}); // MPToken doesn't exist @@ -7363,7 +6439,7 @@ class MPToken_test : public beast::unit_test::Suite auto usd = MPTTester( {.env = env, .issuer = gw, - .flags = tfMPTCanLock | kMptDexFlags, + .flags = tfMPTCanLock | kMPT_DEX_FLAGS, .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTransfer | tmfMPTCanMutateCanClawback | tmfMPTCanMutateCanTrade}); auto eur = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000'000}); @@ -7414,8 +6490,8 @@ class MPToken_test : public beast::unit_test::Suite // alice and issuer can't create usd.set({.flags = tfMPTLock}); - createFail(alice, tecLOCKED); - createFail(gw, tecLOCKED); + createFail(alice, tecFROZEN); + createFail(gw, tecFROZEN); // MPTRequireAuth is set @@ -7435,7 +6511,7 @@ class MPToken_test : public beast::unit_test::Suite usd.set({.mutableFlags = tmfMPTClearRequireAuth}); usd.set({.mutableFlags = tmfMPTClearCanTransfer}); // alice can't create - createFail(alice, tecNO_AUTH); + createFail(alice, tecNO_PERMISSION); // issuer can create createDeleteAMM(gw); usd.set({.mutableFlags = tmfMPTSetCanTransfer}); @@ -7481,12 +6557,12 @@ class MPToken_test : public beast::unit_test::Suite {.account = account, .asset1In = usd(1), .asset2In = eur(1), - .err = Ter(tecLOCKED)}); + .err = Ter(tecFROZEN)}); amm.deposit( {.account = account, .asset1In = eur(1), .assets = std::make_pair(eur, usd), - .err = Ter(tecLOCKED)}); + .err = Ter(tecFROZEN)}); } usd.set({.flags = tfMPTUnlock}); @@ -7499,6 +6575,8 @@ class MPToken_test : public beast::unit_test::Suite eur.authorize({.account = carol}); env(pay(gw, carol, eur(1'000'000))); usd.set({.mutableFlags = tmfMPTSetRequireAuth}); + // have to authorize amm account + usd.authorize({.account = gw, .holder = Account{"amm", amm.ammAccount()}}); env.close(); amm.deposit( {.account = carol, .asset1In = usd(1), .asset2In = eur(1), .err = Ter(tecNO_AUTH)}); @@ -7512,16 +6590,6 @@ class MPToken_test : public beast::unit_test::Suite // carol is authorized, can deposit usd.authorize({.account = gw, .holder = carol}); amm.deposit({.account = carol, .tokens = 1'000}); - // Can't authorize or unauthorize AMM pseudo-account - usd.authorize( - {.account = gw, - .holder = Account{"amm", amm.ammAccount()}, - .err = tecNO_PERMISSION}); - usd.authorize( - {.account = gw, - .holder = Account{"amm", amm.ammAccount()}, - .flags = tfMPTUnauthorize, - .err = tecNO_PERMISSION}); // MPTCanTransfer is not set @@ -7529,12 +6597,15 @@ class MPToken_test : public beast::unit_test::Suite usd.set({.mutableFlags = tmfMPTClearCanTransfer}); // carol can't deposit amm.deposit( - {.account = carol, .asset1In = usd(1), .asset2In = eur(1), .err = Ter(tecNO_AUTH)}); + {.account = carol, + .asset1In = usd(1), + .asset2In = eur(1), + .err = Ter(tecNO_PERMISSION)}); amm.deposit( {.account = carol, .asset1In = eur(1), .assets = std::make_pair(eur, usd), - .err = Ter(tecNO_AUTH)}); + .err = Ter(tecNO_PERMISSION)}); // issuer can deposit amm.deposit({.account = gw, .tokens = 1'000}); // carol can deposit @@ -7576,8 +6647,8 @@ class MPToken_test : public beast::unit_test::Suite {.account = account, .asset1Out = usd(1), .asset2Out = eur(1), - .err = Ter(tecLOCKED)}); - amm.withdraw({.account = account, .tokens = 1'000, .err = Ter(tecLOCKED)}); + .err = Ter(tecFROZEN)}); + amm.withdraw({.account = account, .tokens = 1'000, .err = Ter(tecFROZEN)}); // can single withdraw another asset amm.withdraw( {.account = account, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); @@ -7603,38 +6674,29 @@ class MPToken_test : public beast::unit_test::Suite usd.authorize({.account = gw, .holder = carol}); amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); - // MPTCanTransfer is not set, allow to withdraw + // MPTCanTransfer is set usd.set({.mutableFlags = tmfMPTClearRequireAuth}); usd.set({.mutableFlags = tmfMPTClearCanTransfer}); - // carol can withdraw - amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); + // carol can't withdraw + amm.withdraw( + {.account = carol, + .asset1Out = usd(1), + .asset2Out = eur(1), + .err = Ter(tecNO_PERMISSION)}); // can withdraw another asset amm.withdraw( {.account = carol, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); // issuer can withdraw amm.withdraw({.account = gw, .asset1Out = usd(1), .asset2Out = eur(1)}); - // Holder can't transfer to another holder - env.fund(XRP(1'000), bob); - usd.authorize({.account = bob}); - env(pay(carol, bob, usd(1)), Ter(tecNO_AUTH)); - usd.authorize({.account = bob, .flags = tfMPTUnauthorize}); - // Can redeem - env(pay(carol, gw, usd(1))); // carol can withdraw usd.set({.mutableFlags = tmfMPTSetCanTransfer}); amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - - // MPTCanTrade is not set, allow to withdraw - usd.set({.mutableFlags = tmfMPTClearCanTrade}); - amm.withdraw({.account = gw, .tokens = 1'000}); - amm.withdraw({.account = carol, .tokens = 1'000}); - // Can't DEX - amm.deposit( - DepositArg{.account = carol, .asset1In = usd(1), .err = Ter(tecNO_PERMISSION)}); + amm.withdraw({.account = gw, .tokens = 1'000, .err = Ter(tecNO_PERMISSION)}); + amm.withdraw({.account = carol, .tokens = 1'000, .err = Ter(tecNO_PERMISSION)}); usd.set({.mutableFlags = tmfMPTSetCanTrade}); // MPToken created on withdraw @@ -7653,99 +6715,6 @@ class MPToken_test : public beast::unit_test::Suite } } - void - testFixDoubleOwnerCount(FeatureBitset all) - { - testcase("Fix Double adjustOwnerCount in AMMWithdraw"); - - using namespace jtx; - - // Carol deposits XRP into an XRP/MPT pool, then withdraws MPT. - // Carol has no MPToken before the withdrawal. If the bug exists, - // her ownerCount will be inflated by +1 extra. - Account const gw{"gw"}; - Account const alice{"alice"}; - Account const carol{"carol"}; - Env env(*this, all); - env.fund(XRP(30'000), gw, alice, carol); - env.close(); - - // Create MPT with DEX flags. Only alice is a holder initially. - MPT const btc = MPTTester( - {.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000, .flags = kMptDexFlags}); - - // Alice creates XRP/MPT AMM pool - AMM amm(env, alice, XRP(10'000), btc(10'000)); - - // Carol deposits XRP (single asset) into the pool. - // Carol gets LP tokens but does NOT have an MPToken yet. - auto const carolOwnersBefore = ownerCount(env, carol); - amm.deposit(carol, XRP(1'000), std::nullopt, std::nullopt, tfSingleAsset); - auto const carolOwnersAfterDeposit = ownerCount(env, carol); - // Carol should have +1 for LP token trustline - BEAST_EXPECT(carolOwnersAfterDeposit == carolOwnersBefore + 1); - - auto const carolOwnersBeforeWithdraw = ownerCount(env, carol); - // Carol withdraws single MPT asset. She doesn't have an MPToken, - // so one must be created. Bug: ownerCount incremented twice. - amm.withdraw({.account = carol, .asset1Out = btc(100), .flags = tfSingleAsset}); - auto const carolOwnersAfterWithdraw = ownerCount(env, carol); - - // Expected: +1 for the new MPToken (so total increase = 1) - BEAST_EXPECT(carolOwnersAfterWithdraw == carolOwnersBeforeWithdraw + 1); - } - - void - testTradeAndTransfer() - { - using namespace jtx; - testcase("Trade and Transfer"); - - // Verify canMPTTradeAndTransfer validates the flags when from == to and from != to - - Account const gw{"gw"}; - Account const alice{"alice"}; - Account const carol{"carol"}; - Env env(*this); - env.fund(XRP(1'000), gw, alice, carol); - - MPTTester mpt( - {.env = env, - .issuer = gw, - .holders = {alice, carol}, - .pay = 100, - .flags = kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateCanTrade}); - - // Both flags are enabled - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol))); - - // MPTCanTrade is disabled - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_PERMISSION); - - // MPTCanTransfer is disabled - mpt.set({.mutableFlags = tmfMPTSetCanTrade}); - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice))); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_AUTH); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_AUTH); - - // Both flags are disabled - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_PERMISSION); - } - public: void run() override @@ -7814,7 +6783,7 @@ public: // Test MPT Amount is invalid in Tx, which don't support MPT testMPTInvalidInTx(all); - testNonCanonicalMPTAmountCleanup(all); + // Test parsed MPTokenIssuanceID in API response metadata testTxJsonMetaFields(all); @@ -7852,12 +6821,6 @@ public: // Test AMM testBasicAMM(all); - - // Test Trade/Transfer - testTradeAndTransfer(); - - // Fixes - testFixDoubleOwnerCount(all); } }; diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index d559ecd7b5..f20847ae5c 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -115,7 +115,7 @@ public: SecretKey const& ssk, int seq) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -137,7 +137,7 @@ public: { auto const pk = derivePublicKey(type, sk); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; @@ -156,7 +156,7 @@ public: { auto const pk = derivePublicKey(type, sk); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; @@ -186,7 +186,7 @@ public: auto const pk = derivePublicKey(type, sk); auto const spk = derivePublicKey(stype, ssk); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -363,7 +363,7 @@ public: auto const kp = randomKeyPair(KeyType::Secp256k1); auto const m = makeManifest(sk, KeyType::Ed25519, kp.second, KeyType::Secp256k1, 0); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 0; st[sfPublicKey] = pk; st[sfSigningPubKey] = kp.first; @@ -495,7 +495,7 @@ public: auto const spk = derivePublicKey(KeyType::Secp256k1, ssk); auto buildManifestObject = [&](std::uint16_t version) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 3; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -573,7 +573,7 @@ public: std::optional domain, bool noSigningPublic = false, bool noSignature = false) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = seq; st[sfPublicKey] = pk; @@ -724,7 +724,7 @@ public: } { // reject matching master & ephemeral keys - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 314159; st[sfPublicKey] = pk; st[sfSigningPubKey] = pk; @@ -797,7 +797,7 @@ public: auto const pk2 = derivePublicKey(KeyType::Secp256k1, sk2); auto test = [&](std::string domain) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 7; st[sfPublicKey] = pk1; st[sfDomain] = makeSlice(domain); diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index f21611df0e..55e1b73158 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -143,7 +143,7 @@ public: env.require(Owners(alice, 1)); } // Remove alice's signer list and get the owner count back. - env(signers(alice, jtx::kNone)); + env(signers(alice, jtx::kNONE)); env.close(); env.require(Owners(alice, 0)); } @@ -692,7 +692,7 @@ public: { aliceSeq = env.seq(alice); json::Value jv = setupTx(); - jv[jss::tx_json][sfSigners.fieldName] = json::Value{json::ValueType::Array}; + jv[jss::tx_json][sfSigners.fieldName] = json::Value{json::ArrayValue}; beckySign(jv); auto jrr = env.rpc("json", "submit_multisigned", to_string(jv))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); @@ -826,7 +826,7 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq); // Remove alice's signer list and get the owner count back. - env(signers(alice, jtx::kNone), Sig(alie)); + env(signers(alice, jtx::kNONE), Sig(alie)); env.close(); env.require(Owners(alice, 0)); } @@ -871,23 +871,23 @@ public: env(fset(alice, asfDisableMaster), Sig(alice)); // R0: A lone regular key cannot be removed. - env(regkey(alice, kDisabled), Sig(alie), Ter(tecNO_ALTERNATIVE_KEY)); + env(regkey(alice, kDISABLED), Sig(alie), Ter(tecNO_ALTERNATIVE_KEY)); // Add a signer list. env(signers(alice, 1, {{bogie_, 1}}), Sig(alie)); // R1: The regular key can be removed if there's a signer list. - env(regkey(alice, kDisabled), Sig(alie)); + env(regkey(alice, kDISABLED), Sig(alie)); // L0: A lone signer list cannot be removed. auto const baseFee = env.current()->fees().base; - env(signers(alice, jtx::kNone), Msig(bogie_), Fee(2 * baseFee), Ter(tecNO_ALTERNATIVE_KEY)); + env(signers(alice, jtx::kNONE), Msig(bogie_), Fee(2 * baseFee), Ter(tecNO_ALTERNATIVE_KEY)); // Enable the master key. env(fclear(alice, asfDisableMaster), Msig(bogie_), Fee(2 * baseFee)); // L1: The signer list can be removed if the master key is enabled. - env(signers(alice, jtx::kNone), Msig(bogie_), Fee(2 * baseFee)); + env(signers(alice, jtx::kNONE), Msig(bogie_), Fee(2 * baseFee)); // Add a signer list. env(signers(alice, 1, {{bogie_, 1}}), Sig(alice)); @@ -899,13 +899,13 @@ public: env(regkey(alice, alie), Msig(bogie_), Fee(2 * baseFee)); // L2: The signer list can be removed if there's a regular key. - env(signers(alice, jtx::kNone), Sig(alie)); + env(signers(alice, jtx::kNONE), Sig(alie)); // Enable the master key. env(fclear(alice, asfDisableMaster), Sig(alie)); // R2: The regular key can be removed if the master key is enabled. - env(regkey(alice, kDisabled), Sig(alie)); + env(regkey(alice, kDISABLED), Sig(alie)); } // Verify that the first regular key can be made for free using the @@ -1398,7 +1398,7 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq); // Should also be able to remove the signer list using a ticket. - env(signers(alice, jtx::kNone), ticket::Use(aliceTicketSeq++)); + env(signers(alice, jtx::kNONE), ticket::Use(aliceTicketSeq++)); env.close(); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -1420,8 +1420,8 @@ public: uint8_t tag2[] = "hello world some ascii 32b long"; // including 1 byte for NUL - uint256 bogieTag = xrpl::BaseUInt<256>::fromVoid(tag1); - uint256 demonTag = xrpl::BaseUInt<256>::fromVoid(tag2); + uint256 bogieTag = xrpl::BaseUint<256>::fromVoid(tag1); + uint256 demonTag = xrpl::BaseUint<256>::fromVoid(tag2); // Attach phantom signers to alice and use them for a transaction. env(signers(alice, 1, {{bogie_, 1, bogieTag}, {demon_, 1, demonTag}})); diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index 4929cadd65..da5760f387 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -582,11 +582,11 @@ public: run() override { using namespace test::jtx; - static FeatureBitset const kAll{testableAmendments()}; + static FeatureBitset const kALL{testableAmendments()}; - static std::array const kFeatures = {kAll - fixEnforceNFTokenTrustlineV2, kAll}; + static std::array const kFEATURES = {kALL - fixEnforceNFTokenTrustlineV2, kALL}; - for (auto const feature : kFeatures) + for (auto const feature : kFEATURES) { testBuyOfferUnauthorizedSeller(feature); testCreateBuyOfferUnauthorizedBuyer(feature); diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 482d275d51..56bb6b75d7 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -67,7 +67,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite using namespace test::jtx; uint256 const nftokenID = token::getNextID(env, owner, 0, tfTransferable); env(token::mint(owner, 0), - token::Uri(std::string(kMaxTokenUriLength, 'u')), + token::Uri(std::string(kMAX_TOKEN_URI_LENGTH, 'u')), Txflags(tfTransferable)); env.close(); @@ -200,7 +200,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite // way each time. std::mt19937 engine; std::uniform_int_distribution feeDist( - decltype(kMaxTransferFee){}, kMaxTransferFee); + decltype(kMAX_TRANSFER_FEE){}, kMAX_TRANSFER_FEE); alice.nfts.reserve(105); while (alice.nfts.size() < 105) @@ -337,7 +337,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite BEAST_EXPECT(nftCount(env, becky.acct) == 0); BEAST_EXPECT(nftCount(env, minter.acct) == 0); - // When all nfts are burned kNone of the accounts should have + // When all nfts are burned kNONE of the accounts should have // an ownerCount. BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, becky) == 0); @@ -515,7 +515,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite { // Removing the last token from the last page deletes the // _previous_ page because we need to preserve that last - // page as an anchor. The contents of the next-to-last page + // page an an anchor. The contents of the next-to-last page // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpageMax(alice)); BEAST_EXPECT(lastNFTokenPage); @@ -694,7 +694,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite { // Removing the last token from the last page deletes the // _previous_ page because we need to preserve that last - // page as an anchor. The contents of the next-to-last page + // page an an anchor. The contents of the next-to-last page // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpageMax(alice)); BEAST_EXPECT(lastNFTokenPage); @@ -771,7 +771,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite // checks. These variables must outlive the ApplyContext. OpenView ov{*env.current()}; STTx const tx{ttACCOUNT_SET, [](STObject&) {}}; - test::StreamSink sink{beast::Severity::Warning}; + test::StreamSink sink{beast::severities::KWarning}; beast::Journal const jlog{sink}; ApplyContext ac{ env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog}; @@ -804,7 +804,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite // checks. These variables must outlive the ApplyContext. OpenView ov{*env.current()}; STTx const tx{ttACCOUNT_SET, [](STObject&) {}}; - test::StreamSink sink{beast::Severity::Warning}; + test::StreamSink sink{beast::severities::KWarning}; beast::Journal const jlog{sink}; ApplyContext ac{ env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog}; @@ -861,8 +861,8 @@ class NFTokenBurn_test : public beast::unit_test::Suite // When the token is burned, 498 sell offers and 1 buy offer are // removed. In total, 499 offers are removed std::vector offerIndexes; - auto const nftokenID = - createNftAndOffers(env, alice, offerIndexes, kMaxDeletableTokenOfferEntries - 2); + auto const nftokenID = createNftAndOffers( + env, alice, offerIndexes, kMAX_DELETABLE_TOKEN_OFFER_ENTRIES - 2); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -908,8 +908,8 @@ class NFTokenBurn_test : public beast::unit_test::Suite // After we burn the token, 500 of the sell offers should be // removed, and one is left over std::vector offerIndexes; - auto const nftokenID = - createNftAndOffers(env, alice, offerIndexes, kMaxDeletableTokenOfferEntries + 1); + auto const nftokenID = createNftAndOffers( + env, alice, offerIndexes, kMAX_DELETABLE_TOKEN_OFFER_ENTRIES + 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -929,10 +929,10 @@ class NFTokenBurn_test : public beast::unit_test::Suite offerDeletedCount++; } - BEAST_EXPECT(offerIndexes.size() == kMaxTokenOfferCancelCount + 1); + BEAST_EXPECT(offerIndexes.size() == kMAX_TOKEN_OFFER_CANCEL_COUNT + 1); // 500 sell offers should be removed - BEAST_EXPECT(offerDeletedCount == kMaxTokenOfferCancelCount); + BEAST_EXPECT(offerDeletedCount == kMAX_TOKEN_OFFER_CANCEL_COUNT); // alice should have ownerCounts of one for the orphaned sell offer BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -952,8 +952,8 @@ class NFTokenBurn_test : public beast::unit_test::Suite // are removed. // In total, 500 offers are removed std::vector offerIndexes; - auto const nftokenID = - createNftAndOffers(env, alice, offerIndexes, kMaxDeletableTokenOfferEntries - 1); + auto const nftokenID = createNftAndOffers( + env, alice, offerIndexes, kMAX_DELETABLE_TOKEN_OFFER_ENTRIES - 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 117f2bc816..fbae51406b 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -126,10 +126,10 @@ class NFTokenDir_test : public beast::unit_test::Suite // Mint 100 sequential NFTs. Tweak the taxon so zero is always stored. // That's what makes them sequential. - static constexpr std::size_t kNftCount = 100; + constexpr std::size_t kNFT_COUNT = 100; std::vector nftIDs; - nftIDs.reserve(kNftCount); - for (int i = 0; i < kNftCount; ++i) + nftIDs.reserve(kNFT_COUNT); + for (int i = 0; i < kNFT_COUNT; ++i) { std::uint32_t const taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); nftIDs.emplace_back(token::getNextID(env, issuer, taxon, tfTransferable)); @@ -272,7 +272,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // These seeds cause a lopsided split where the new NFT is added // to the upper page. - static std::initializer_list const kSplitAndAddToHi{ + static std::initializer_list const kSPLIT_AND_ADD_TO_HI{ "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea @@ -318,7 +318,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // These seeds cause a lopsided split where the new NFT is added // to the lower page. - static std::initializer_list const kSplitAndAddToLo{ + static std::initializer_list const kSPLIT_AND_ADD_TO_LO{ "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea @@ -363,8 +363,8 @@ class NFTokenDir_test : public beast::unit_test::Suite }; // Run the test cases. - exerciseLopsided(kSplitAndAddToHi); - exerciseLopsided(kSplitAndAddToLo); + exerciseLopsided(kSPLIT_AND_ADD_TO_HI); + exerciseLopsided(kSPLIT_AND_ADD_TO_LO); } void @@ -381,7 +381,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // Lambda that exercises the split. auto exercise = [this, &features](std::initializer_list seeds) { - Env env{*this, envconfig(), features, nullptr, beast::Severity::Disabled}; + Env env{*this, envconfig(), features, nullptr, beast::severities::KDisabled}; // Eventually all of the NFTokens will be owned by buyer. Account const buyer{"buyer"}; @@ -480,7 +480,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // These seeds fill the last 17 entries of the initial page with // equivalent NFTs. The split should keep these together. - static std::initializer_list const kSeventeenHi{ + static std::initializer_list const kSEVENTEEN_HI{ // These 16 need to be kept together by the implementation. "sp6JS7f14BuwFY8Mw5EYu5z86hKDL", // 0. 0x399187e9 "sp6JS7f14BuwFY8Mw5PUAMwc5ygd7", // 1. 0x399187e9 @@ -521,7 +521,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // These seeds fill the first entries of the initial page with // equivalent NFTs. The split should keep these together. - static std::initializer_list const kSeventeenLo{ + static std::initializer_list const kSEVENTEEN_LO{ // These 17 need to be kept together by the implementation. "sp6JS7f14BuwFY8Mw5EYu5z86hKDL", // 0. 0x399187e9 "sp6JS7f14BuwFY8Mw5PUAMwc5ygd7", // 1. 0x399187e9 @@ -561,8 +561,8 @@ class NFTokenDir_test : public beast::unit_test::Suite }; // Run the test cases. - exercise(kSeventeenHi); - exercise(kSeventeenLo); + exercise(kSEVENTEEN_HI); + exercise(kSEVENTEEN_LO); } void @@ -583,7 +583,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // Here are 33 seeds that produce identical low 32-bits in their // corresponding AccountIDs. - static std::initializer_list const kSeeds{ + static std::initializer_list const kSEEDS{ "sp6JS7f14BuwFY8Mw5FnqmbciPvH6", // 0. 0x9a8ebed3 "sp6JS7f14BuwFY8Mw5MBGbyMSsXLp", // 1. 0x9a8ebed3 "sp6JS7f14BuwFY8Mw5S4PnDyBdKKm", // 2. 0x9a8ebed3 @@ -621,8 +621,8 @@ class NFTokenDir_test : public beast::unit_test::Suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; - accounts.reserve(kSeeds.size()); - for (std::string_view const seed : kSeeds) + accounts.reserve(kSEEDS.size()); + for (std::string_view const seed : kSEEDS) { Account const& account = accounts.emplace_back(Account::AcctStringType::Base58Seed, std::string(seed)); @@ -656,10 +656,10 @@ class NFTokenDir_test : public beast::unit_test::Suite env.close(); // Verify that the low 96 bits of all generated NFTs is identical. - uint256 const expectLowBits = nftIDs.front() & nft::kPageMask; + uint256 const expectLowBits = nftIDs.front() & nft::kPAGE_MASK; for (uint256 const& nftID : nftIDs) { - BEAST_EXPECT(expectLowBits == (nftID & nft::kPageMask)); + BEAST_EXPECT(expectLowBits == (nftID & nft::kPAGE_MASK)); } // Remove one NFT and offer from the vectors. This offer is the one @@ -731,7 +731,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // // All of the NFTs should be acquired by the buyer. // - // Lastly, kNone of the remaining NFTs should be acquirable by the + // Lastly, kNONE of the remaining NFTs should be acquirable by the // buyer. They would cause page overflow. testcase("NFToken consecutive packing"); @@ -747,7 +747,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // Here are 33 seeds that produce identical low 32-bits in their // corresponding AccountIDs. - static std::initializer_list const kSeeds{ + static std::initializer_list const kSEEDS{ "sp6JS7f14BuwFY8Mw56vZeiBuhePx", // 0. 0x115d0525 "sp6JS7f14BuwFY8Mw5BodF9tGuTUe", // 1. 0x115d0525 "sp6JS7f14BuwFY8Mw5EnhC1cg84J7", // 2. 0x115d0525 @@ -785,8 +785,8 @@ class NFTokenDir_test : public beast::unit_test::Suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; - accounts.reserve(kSeeds.size()); - for (std::string_view const seed : kSeeds) + accounts.reserve(kSEEDS.size()); + for (std::string_view const seed : kSEEDS) { Account const& account = accounts.emplace_back(Account::AcctStringType::Base58Seed, std::string(seed)); @@ -832,10 +832,10 @@ class NFTokenDir_test : public beast::unit_test::Suite // sequence is identical. for (auto const& vec : nftIDsByPage) { - uint256 const expectLowBits = vec.front() & nft::kPageMask; + uint256 const expectLowBits = vec.front() & nft::kPAGE_MASK; for (uint256 const& nftID : vec) { - BEAST_EXPECT(expectLowBits == (nftID & nft::kPageMask)); + BEAST_EXPECT(expectLowBits == (nftID & nft::kPAGE_MASK)); } } @@ -850,11 +850,11 @@ class NFTokenDir_test : public beast::unit_test::Suite { overflowNFTs.push_back(nftIDsByPage[i].back()); nftIDsByPage[i].pop_back(); - BEAST_EXPECT(nftIDsByPage[i].size() == kSeeds.size() - 1); + BEAST_EXPECT(nftIDsByPage[i].size() == kSEEDS.size() - 1); overflowOffers.push_back(offers[i].back()); offers[i].pop_back(); - BEAST_EXPECT(offers[i].size() == kSeeds.size() - 1); + BEAST_EXPECT(offers[i].size() == kSEEDS.size() - 1); } // buyer accepts all of the offers that won't cause an overflow. @@ -892,7 +892,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // See what the account_objects command does with "nft_offer". { - json::Value ownedNftOffers(json::ValueType::Array); + json::Value ownedNftOffers(json::ArrayValue); std::string marker; do { @@ -965,7 +965,7 @@ class NFTokenDir_test : public beast::unit_test::Suite // Verify that the ledger reports all of the NFTs owned by buyer. // Use the account_nfts rpc call to get the values. - json::Value ownedNFTs(json::ValueType::Array); + json::Value ownedNFTs(json::ArrayValue); std::string marker; do { diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index ebd470ec92..3f4260e1b1 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -508,11 +508,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // Can't set a transfer fee if the NFT does not have the tfTRANSFERABLE // flag set. - env(token::mint(alice, 0u), token::XferFee(kMaxTransferFee), Ter(temMALFORMED)); + env(token::mint(alice, 0u), token::XferFee(kMAX_TRANSFER_FEE), Ter(temMALFORMED)); // Set a bad transfer fee. env(token::mint(alice, 0u), - token::XferFee(kMaxTransferFee + 1), + token::XferFee(kMAX_TRANSFER_FEE + 1), Txflags(tfTransferable), Ter(temBAD_NFTOKEN_TRANSFER_FEE)); @@ -524,7 +524,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // Invalid URI: too long. env(token::mint(alice, 0u), - token::Uri(std::string(kMaxTokenUriLength + 1, 'q')), + token::Uri(std::string(kMAX_TOKEN_URI_LENGTH + 1, 'q')), Ter(temMALFORMED)); //---------------------------------------------------------------------- @@ -886,7 +886,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // Empty list of tokens to delete. { json::Value jv = token::cancelOffer(buyer); - jv[sfNFTokenOffers.jsonName] = json::ValueType::Array; + jv[sfNFTokenOffers.jsonName] = json::ArrayValue; env(jv, Ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -894,7 +894,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // List of tokens to delete is too long. { - std::vector const offers(kMaxTokenOfferCancelCount + 1, buyerOfferIndex); + std::vector const offers(kMAX_TOKEN_OFFER_CANCEL_COUNT + 1, buyerOfferIndex); env(token::cancelOffer(buyer, offers), Ter(temMALFORMED)); env.close(); @@ -1058,7 +1058,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // A buy offer may not contain a sfNFTokenBrokerFee field. { json::Value jv = token::acceptBuyOffer(buyer, noXferOfferIndex); - jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::Values::None); + jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::KNone); env(jv, Ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1067,7 +1067,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // A sell offer may not contain a sfNFTokenBrokerFee field. { json::Value jv = token::acceptSellOffer(buyer, noXferOfferIndex); - jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::Values::None); + jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::KNone); env(jv, Ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1084,7 +1084,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // preclaim // The buy offer must be non-zero. - env(token::acceptBuyOffer(buyer, beast::kZero), Ter(tecOBJECT_NOT_FOUND)); + env(token::acceptBuyOffer(buyer, beast::kZERO), Ter(tecOBJECT_NOT_FOUND)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1095,17 +1095,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The buy offer must not have expired. - // NOTE: this is only a preclaim check with the fixCleanup3_1_3 amendment disabled. + // NOTE: this is only a preclaim check with the fixSecurity3_1_3 amendment disabled. env(token::acceptBuyOffer(alice, buyerExpOfferIndex), Ter(tecEXPIRED)); env.close(); - if (features[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { buyerCount--; } BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The sell offer must be non-zero. - env(token::acceptSellOffer(buyer, beast::kZero), Ter(tecOBJECT_NOT_FOUND)); + env(token::acceptSellOffer(buyer, beast::kZERO), Ter(tecOBJECT_NOT_FOUND)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1115,13 +1115,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The sell offer must not have expired. - // NOTE: this is only a preclaim check with the fixCleanup3_1_3 amendment disabled. + // NOTE: this is only a preclaim check with the fixSecurity3_1_3 amendment disabled. env(token::acceptSellOffer(buyer, aliceExpOfferIndex), Ter(tecEXPIRED)); env.close(); // Alice's count is decremented by one when the expired offer is // removed. - if (features[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { aliceCount--; } @@ -1320,7 +1320,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite //---------------------------------------------------------------------- // doApply // - // As far as I can see kNone of the failure modes are accessible as + // As far as I can see kNONE of the failure modes are accessible as // long as the preflight and preclaim conditions are met. } @@ -2140,13 +2140,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // A transfer fee greater than 50% is not allowed. env(token::mint(alice), Txflags(tfTransferable), - token::XferFee(kMaxTransferFee + 1), + token::XferFee(kMAX_TRANSFER_FEE + 1), Ter(temBAD_NFTOKEN_TRANSFER_FEE)); env.close(); // Make an nft with a transfer fee of 50%. - uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, kMaxTransferFee); - env(token::mint(alice), Txflags(tfTransferable), token::XferFee(kMaxTransferFee)); + uint256 const nftID = + token::getNextID(env, alice, 0u, tfTransferable, kMAX_TRANSFER_FEE); + env(token::mint(alice), Txflags(tfTransferable), token::XferFee(kMAX_TRANSFER_FEE)); env.close(); // Becky buys the nft for XAU(10). Check balances. @@ -2297,14 +2298,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite env(pay(becky, gw, env.balance(becky, gwXAU))); env.close(); - STAmount const startXAUBalance(gwXAU, STAmount::kMinValue, STAmount::kMinOffset + 5); + STAmount const startXAUBalance(gwXAU, STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET + 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 const tinyXAU(gwXAU, STAmount::kMinValue, STAmount::kMinOffset); + STAmount const tinyXAU(gwXAU, STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET); // minter buys the nft for tinyXAU. Since the transfer involves // alice there should be no transfer fee. @@ -2337,7 +2338,7 @@ 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, STAmount::kMinValue, STAmount::kMinOffset + 5); + STAmount const cheapNFT(gwXAU, STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET + 5); STAmount beckyBalance = env.balance(becky, gwXAU); uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; @@ -3100,10 +3101,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // No one can accept an expired sell offer. env(token::acceptSellOffer(buyer, offer1), Ter(tecEXPIRED)); - // With fixCleanup3_1_3 amendment, the first accept + // With fixSecurity3_1_3 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[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { // After amendment: offer was deleted by first accept attempt minterCount--; @@ -3122,7 +3123,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, minter) == minterCount); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); - if (!features[fixCleanup3_1_3]) + if (!features[fixSecurity3_1_3]) { // Before amendment: expired offer still exists and needs to be // cancelled @@ -3188,10 +3189,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // An expired buy offer cannot be accepted. env(token::acceptBuyOffer(minter, offer1), Ter(tecEXPIRED)); - // With fixCleanup3_1_3 amendment, the first accept + // With fixSecurity3_1_3 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[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { // After amendment: offer was deleted by first accept attempt buyerCount--; @@ -3210,7 +3211,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, minter) == minterCount); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); - if (!features[fixCleanup3_1_3]) + if (!features[fixSecurity3_1_3]) { // Before amendment: expired offer still exists and can be // cancelled @@ -3287,7 +3288,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite env(token::brokerOffers(issuer, buyOffer1, sellOffer1), Ter(tecEXPIRED)); env.close(); - if (features[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { // With amendment: expired offers are deleted minterCount--; @@ -3297,7 +3298,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, minter) == minterCount); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); - if (features[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { // The buy offer was deleted, so no need to cancel it // The sell offer still exists, so we can cancel it @@ -3376,7 +3377,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); - if (features[fixCleanup3_1_3]) + if (features[fixSecurity3_1_3]) { // After amendment: expired offers were deleted during broker // attempt @@ -3462,7 +3463,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // The expired offers are still in the ledger. BEAST_EXPECT(ownerCount(env, issuer) == 0); - if (!features[fixCleanup3_1_3]) + if (!features[fixSecurity3_1_3]) { // Before amendment: expired offers still exist in ledger BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -3618,10 +3619,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite env.fund(XRP(1000), alice); env.close(); - std::string const uri(kMaxTokenUriLength, '?'); + std::string const uri(kMAX_TOKEN_URI_LENGTH, '?'); std::vector offerIndexes; - offerIndexes.reserve(kMaxTokenOfferCancelCount + 1); - for (uint32_t i = 0; i < kMaxTokenOfferCancelCount + 1; ++i) + offerIndexes.reserve(kMAX_TOKEN_OFFER_CANCEL_COUNT + 1); + for (uint32_t i = 0; i < kMAX_TOKEN_OFFER_CANCEL_COUNT + 1; ++i) { Account const nftAcct(std::string("nftAcct") + std::to_string(i)); Account const offerAcct(std::string("offerAcct") + std::to_string(i)); @@ -3866,7 +3867,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite { checkOwnerCountIsOne({issuer, minter, buyer, broker}, __LINE__); - uint256 const nftID = mintNFT(kMaxTransferFee); + uint256 const nftID = mintNFT(kMAX_TRANSFER_FEE); // minter creates their offer. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; @@ -3908,7 +3909,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite { checkOwnerCountIsOne({issuer, minter, buyer, broker}, __LINE__); - uint256 const nftID = mintNFT(kMaxTransferFee); + uint256 const nftID = mintNFT(kMAX_TRANSFER_FEE); // minter creates their offer. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; @@ -4058,7 +4059,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite checkOwnerCountIsOne({issuer, minter, buyer, broker}, __LINE__); setXAUBalance({issuer, minter, buyer, broker}, 1000, __LINE__); - uint256 const nftID = mintNFT(kMaxTransferFee); + uint256 const nftID = mintNFT(kMAX_TRANSFER_FEE); // minter creates their offer. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; @@ -4136,7 +4137,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite checkOwnerCountIsOne({issuer, minter, buyer, broker}, __LINE__); setXAUBalance({issuer, minter, buyer, broker}, 1000, __LINE__); - uint256 const nftID = mintNFT(kMaxTransferFee / 2); // 25% + uint256 const nftID = mintNFT(kMAX_TRANSFER_FEE / 2); // 25% // minter creates their offer. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; @@ -4173,7 +4174,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite checkOwnerCountIsOne({issuer, minter, buyer, broker}, __LINE__); setXAUBalance({issuer, minter, buyer}, 1000, __LINE__); setXAUBalance({broker}, 500, __LINE__); - uint256 const nftID = mintNFT(kMaxTransferFee / 2); // 25% + uint256 const nftID = mintNFT(kMAX_TRANSFER_FEE / 2); // 25% // minter creates their offer. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; @@ -4488,7 +4489,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite int expectMarkerCount, int line) { int markerCount = 0; - json::Value allOffers(json::ValueType::Array); + json::Value allOffers(json::ArrayValue); std::string marker; // The do/while collects results until no marker is returned. @@ -5127,7 +5128,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite } { // Minter attempts to sell the token for XPB 10, which they - // have no trust line for and buyer has kNone of (sellside). + // have no trust line for and buyer has kNONE of (sellside). reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); auto const offerID = createSellOffer(minter, nftID, gwXPB(10)); @@ -5138,7 +5139,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite } { // Minter attempts to sell the token for XPB 10, which they - // have no trust line for and buyer has kNone of (buyside). + // have no trust line for and buyer has kNONE of (buyside). reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); auto const offerID = createBuyOffer( @@ -6100,8 +6101,7 @@ 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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; env.close(); json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; @@ -6121,8 +6121,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // 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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; env.close(); json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; @@ -6160,8 +6159,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // 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::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; env.close(); json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; @@ -6367,7 +6365,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, bob) == 0); - // Send bob an kIncrement reserve and base fee (to make up for + // Send bob an kINCREMENT reserve and base fee (to make up for // the transaction fee burnt from the prev failed tx) Bob now // owns 250,000,000 drops env(pay(env.master, bob, incReserve + drops(baseFee))); @@ -6496,8 +6494,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite env.fund(XRP(10000), alice); env.close(); - // Bob is funded with account reserve + kIncrement reserve + 1 XRP - // kIncrement reserve is for the buy offer, and 1 XRP is for offer + // Bob is funded with account reserve + kINCREMENT reserve + 1 XRP + // kINCREMENT reserve is for the buy offer, and 1 XRP is for offer // price env.fund(acctReserve + incReserve + XRP(1), bob); env.close(); @@ -6962,7 +6960,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // Invalid URI length > 256 env(token::modify(issuer, nftId), - token::Uri(std::string(kMaxTokenUriLength + 1, 'q')), + token::Uri(std::string(kMAX_TOKEN_URI_LENGTH + 1, 'q')), Ter(temMALFORMED)); env.close(); } @@ -7192,7 +7190,7 @@ public: { testWithFeats( allFeatures_ - fixNFTokenReserve - featureNFTokenMintOffer - featureDynamicNFT - - fixCleanup3_1_3); + fixSecurity3_1_3); } }; @@ -7229,7 +7227,7 @@ class NfTokenWoExpiredOfferRemovalTest : public NFTokenBaseUtil_test void run() override { - testWithFeats(allFeatures_ - fixCleanup3_1_3); + testWithFeats(allFeatures_ - fixSecurity3_1_3); } }; diff --git a/src/test/app/NetworkID_test.cpp b/src/test/app/NetworkID_test.cpp index 677d8f166d..a98fbd6b4f 100644 --- a/src/test/app/NetworkID_test.cpp +++ b/src/test/app/NetworkID_test.cpp @@ -37,7 +37,7 @@ public: { using namespace jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->networkId = networkID; + cfg->NETWORK_ID = networkID; return cfg; }); } diff --git a/src/test/app/NetworkOPs_test.cpp b/src/test/app/NetworkOPs_test.cpp index d0a692b894..02667ce275 100644 --- a/src/test/app/NetworkOPs_test.cpp +++ b/src/test/app/NetworkOPs_test.cpp @@ -38,7 +38,8 @@ public: { using namespace jtx; auto const alice = Account{"alice"}; - Env env{*this, envconfig(), std::make_unique(&logs), beast::Severity::All}; + Env env{ + *this, envconfig(), std::make_unique(&logs), beast::severities::KAll}; env.memoize(env.master); env.memoize(alice); diff --git a/src/test/app/OfferMPT_test.cpp b/src/test/app/OfferMPT_test.cpp index e0f2f4eab0..21ee05289c 100644 --- a/src/test/app/OfferMPT_test.cpp +++ b/src/test/app/OfferMPT_test.cpp @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -521,9 +522,9 @@ public: // carol's offer can be partially crossed when EUR is IOU: // 10e-3EUR/1USD using tEUR = std::decay_t; - static constexpr bool kIsEuriou = std::is_same_v; + bool constexpr kIS_EURIOU = std::is_same_v; // partially crossed if IOU, removed but not taken if MPT - auto const balanceCarolUSD = kIsEuriou ? usd(0) : initialCarolUSD; + auto const balanceCarolUSD = kIS_EURIOU ? usd(0) : initialCarolUSD; env.require(offers(carol, 0), Balance(carol, balanceCarolUSD)); if (crossBothOffers) @@ -534,7 +535,7 @@ public: else { // partially crossed if IOU, not crossed if MPT - auto const balanceAliceUSD = kIsEuriou ? usd(1) : usd(0); + auto const balanceAliceUSD = kIS_EURIOU ? usd(1) : usd(0); env.require(offers(alice, 1), Balance(alice, balanceAliceUSD)); } } @@ -589,9 +590,9 @@ public: // carol's offer can be partially crossed when EUR is IOU: // 10e-3EUR/1USD using tEUR = std::decay_t; - static constexpr bool kIsEuriou = std::is_same_v; + bool constexpr kIS_EURIOU = std::is_same_v; // partially crossed if IOU, removed but not taken if MPT - auto const balanceCarolUSD = kIsEuriou ? usd(0) : initialCarolUSD; + auto const balanceCarolUSD = kIS_EURIOU ? usd(0) : initialCarolUSD; env.require(offers(carol, 0)); env.require(Balance(carol, balanceCarolUSD)); } @@ -720,11 +721,11 @@ public: } // Helper function that returns the Offers on an account. - static std::vector + static std::vector> offersOnAccount(jtx::Env& env, jtx::Account account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) result.push_back(sle); }); @@ -783,7 +784,7 @@ public: Owners(alice, 1), offers(alice, 0), Balance(bob, startBalance - (f * 2)), - Balance(bob, usd(kNone)), + Balance(bob, usd(kNONE)), Owners(bob, 1), offers(bob, 1)); @@ -972,7 +973,7 @@ public: // Offers with negative amounts { - env(offer(alice, -usd(1'000), XRP(1'000)), Ter(temBAD_AMOUNT)); + env(offer(alice, -usd(1'000), XRP(1'000)), Ter(temBAD_OFFER)); env.require(Owners(alice, 1), offers(alice, 0)); } @@ -1056,7 +1057,7 @@ public: offers(alice, 0), Owners(alice, 1), Balance(bob, startBalance - f), - Balance(bob, usd(kNone)), + Balance(bob, usd(kNONE)), offers(bob, 1), Owners(bob, 1)); } @@ -1442,7 +1443,7 @@ public: 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::Values::None)); + jro[jss::node][jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone)); env(pay(alice, alice, XRP(500)), Sendmax(usd(100))); @@ -1522,8 +1523,7 @@ 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == usd(60).value().getJson(JsonOptions::KNone)); // the balance between alice and gw is 160 USD..200 less the 40 taken // by the offer @@ -1601,8 +1601,7 @@ public: BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "475"); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == usd(25).value().getJson(JsonOptions::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == usd(25).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(250).value().getText()); } @@ -1644,8 +1643,7 @@ public: 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == usd(25).value().getJson(JsonOptions::KNone)); } void @@ -1680,7 +1678,7 @@ public: auto const danOfferSeq = env.seq(dan); env(offer(dan, XRP(500), eur(50))); - json::Value jtp{json::ValueType::Array}; + json::Value jtp{json::ArrayValue}; jtp[0u][0u][jss::currency] = "XRP"; env(pay(alice, bob, eur(30)), Json(jss::Paths, jtp), Sendmax(usd(333))); @@ -1692,13 +1690,11 @@ public: 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::Values::None)); + jro[jss::node][jss::TakerPays] == usd(20).value().getJson(JsonOptions::KNone)); jro = ledgerEntryOffer(env, dan, danOfferSeq); BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == - eur(20).value().getJson(JsonOptions::Values::None)); + jro[jss::node][jss::TakerGets] == eur(20).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); }; testHelper2TokensMix(test); @@ -1763,7 +1759,7 @@ public: env.require(Owners(alice, 2)); env.require(Balance(carol, usd(0))); - env.require(Balance(carol, eur(kNone))); + env.require(Balance(carol, eur(kNONE))); env.require(offers(carol, 0)); env.require(Owners(carol, 1)); @@ -1974,8 +1970,7 @@ public: 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] = - xts(15).value().getJson(JsonOptions::Values::None); + payment[jss::tx_json][jss::SendMax] = xts(15).value().getJson(JsonOptions::KNone); auto jrr = wsc->invoke("submit", payment); BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -2308,8 +2303,8 @@ public: env.close(); env.require(Balance(alice, usd(1'000))); - env.require(Balance(alice, eur(kNone))); - env.require(Balance(bob, usd(kNone))); + env.require(Balance(alice, eur(kNONE))); + env.require(Balance(bob, usd(kNONE))); env.require(Balance(bob, eur(1'000))); env.require(offers(alice, 0)); env.require(offers(bob, 0)); @@ -2666,7 +2661,7 @@ public: // alice submits a tfSell | tfFillOrKill offer that does not cross. env(offer(alice, usd(21), XRP(2'100), tfSell | tfFillOrKill), Ter(tecKILLED)); env.close(); - env.require(Balance(alice, usd(kNone))); + env.require(Balance(alice, usd(kNONE))); env.require(offers(alice, 0)); env.require(Balance(bob, usd(100))); } @@ -2763,7 +2758,7 @@ public: // USD(125) was removed from his account due to the gateway fee. // // A comparable payment would look like this: - // env (pay (bob, alice, USD(100)), Sendmax(USD(125))) + // env (pay (bob, alice, USD(100)), sendmax(USD(125))) env(offer(bob, XRP(1), usd(10'000))); env.close(); @@ -3011,92 +3006,6 @@ public: } }; testHelper2TokensMix(test); - - // Payment trIn: MPT transfer fee must be charged when the payment - // destination is the MPT issuer and MPT crosses the DEX (1-hop). - // Bug: rate() returned parity because strandDst_ == MPT issuer. - // Fix: parity only when this asset IS the final delivered asset. - { - auto const gw = Account("gw_tr1"); - auto const alice = Account("alice_tr1"); - auto const bob = Account("bob_tr1"); - - Env env{*this, features}; - env.fund(XRP(10'000), gw, alice, bob); - env.close(); - - MPT const usd = MPTTester( - {.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 25'000}); - - // alice needs MPT(1250): MPT(1000) to bob's offer + MPT(250) transfer fee (25%) - env(pay(gw, alice, usd(1'250))); - // bob's offer: give XRP(1000), want MPT(1000) - env(offer(bob, usd(1'000), XRP(1'000))); - env.close(); - - // alice pays gw (MPT issuer) XRP(1000) using MPT as source - // strand: alice -> [MPT/XRP BookStep] -> gw - // strandDst_ = gw = MPT issuer, strandDeliver_ = XRP - // trIn = rate(MPT, gw): fix charges 25% (MPT != strandDeliver_) - env(pay(alice, gw, XRP(1'000)), Path(~XRP), Sendmax(usd(1'250))); - env.close(); - - // alice consumed all MPT(1250): MPT(1000) to bob + MPT(250) fee - BEAST_EXPECT(env.balance(alice, usd) == usd(0)); - // bob received MPT(1000) net - BEAST_EXPECT(env.balance(bob, usd) == usd(1'000)); - } - - // Payment trIn (2-hop): MPT transfer fee must be charged when MPT is - // intermediate and the destination is the MPT issuer. - // BookStep2(MPT/XRP) prevStep=BookStep1 returns redeems direction - // (ownerPaysTransferFee_=false for Payment), so trIn applies. - // Bug: parity because strandDst_ == MPT issuer. - // Fix: 25% fee because MPT != strandDeliver_(XRP). - { - auto const gw = Account("gw_tr2"); - auto const gw2 = Account("gw2_tr2"); - auto const alice = Account("alice_tr2"); - auto const bob = Account("bob_tr2"); - auto const carol = Account("carol_tr2"); - - Env env{*this, features}; - env.fund(XRP(10'000), gw, gw2, alice, bob, carol); - env.close(); - - MPT const musd = MPTTester( - {.env = env, .issuer = gw, .holders = {bob, carol}, .transferFee = 25'000}); - auto const gusd = gw2["USD"]; - - env(trust(alice, gusd(10'000))); - env(trust(bob, gusd(10'000))); - env.close(); - - env(pay(gw2, alice, gusd(1'000))); - env(pay(gw, bob, musd(1'000))); - env.close(); - - // bob's offer: give MPT(1000), want GUSD(1000) - env(offer(bob, gusd(1'000), musd(1'000))); - // carol's offer: give XRP(800), want MPT(800) - env(offer(carol, musd(800), XRP(800))); - env.close(); - - // Payment: alice GUSD -> [BookStep1: GUSD/MUSD] -> [BookStep2: MUSD/XRP] -> gw XRP - // strandDst_ = gw = MPT issuer, strandDeliver_ = XRP - // BookStep2 trIn: fix = 1.25 -> upstream needs MUSD(1000) for carol's MUSD(800) offer - // => alice must provide full GUSD(1000) to bob's offer; without fix alice only pays - // GUSD(800) - env(pay(alice, gw, XRP(800)), Path(~musd), Sendmax(gusd(1'000))); - env.close(); - - // alice spent all GUSD(1000); bug would leave GUSD(200) unspent - BEAST_EXPECT(env.balance(alice, gusd) == gusd(0)); - // bob gave MPT(1000) and received GUSD(1000) - BEAST_EXPECT(env.balance(bob, musd) == musd(0)); - // carol received MPT(800) net (MPT(200) went to gw as fee) - BEAST_EXPECT(env.balance(carol, musd) == musd(800)); - } } void @@ -3524,14 +3433,14 @@ public: .token = "JPY", .issuer = gw, .holders = {alice}, - .limit = kMaxMpTokenAmount, + .limit = kMAX_MP_TOKEN_AMOUNT, .transferFee = 2'000}); auto const btc = issue2( {.env = env, .token = "BTC", .issuer = gw, .holders = {bob}, - .limit = kMaxMpTokenAmount, + .limit = kMAX_MP_TOKEN_AMOUNT, .transferFee = 2'000}); env(pay(gw, alice, jpy(3'699'034'802'280'317))); @@ -3730,7 +3639,9 @@ public: auto const offerCount = std::distance( actorOffers.begin(), std::remove_if( - actorOffers.begin(), actorOffers.end(), [](SLE::const_pointer& offer) { + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { return (*offer)[sfTakerGets].signum() == 0; })); BEAST_EXPECT(offerCount == actor.offers); @@ -3900,7 +3811,9 @@ public: auto const offerCount = std::distance( actorOffers.begin(), std::remove_if( - actorOffers.begin(), actorOffers.end(), [](SLE::const_pointer& offer) { + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { return (*offer)[sfTakerGets].signum() == 0; })); BEAST_EXPECT(offerCount == actor.offers); @@ -3940,7 +3853,7 @@ public: // GW requires authorization for holders of its IOUs auto gwMUSD = - MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth}); + MPTTester({.env = env, .issuer = gw, .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth}); MPT const gwUSD = gwMUSD; // Have gw authorize bob and alice @@ -3999,7 +3912,7 @@ public: env.close(); auto gwMUSD = - MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth}); + MPTTester({.env = env, .issuer = gw, .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth}); MPT const gwUSD = gwMUSD; // alice can't create an offer because alice doesn't own @@ -4008,7 +3921,7 @@ public: env.close(); env.require(offers(alice, 0)); - env.require(Balance(alice, gwUSD(kNone))); + env.require(Balance(alice, gwUSD(kNONE))); gwMUSD.authorize({.account = bob}); gwMUSD.authorize({.account = gw, .holder = bob}); @@ -4079,7 +3992,7 @@ public: env.close(); auto gwMUSD = - MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth}); + MPTTester({.env = env, .issuer = gw, .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth}); MPT const gwUSD = gwMUSD; // Test that gw can create an offer to buy gw's currency. @@ -4234,13 +4147,15 @@ public: } // Helper function that returns offers on an account sorted by sequence. - static std::vector + static std::vector> sortedOffersOnAccount(jtx::Env& env, jtx::Account const& acct) { - std::vector offers{offersOnAccount(env, acct)}; - std::ranges::sort(offers, [](SLE::const_ref rhs, SLE::const_ref lhs) { - return (*rhs)[sfSequence] < (*lhs)[sfSequence]; - }); + std::vector> offers{offersOnAccount(env, acct)}; + std::ranges::sort( + offers, + [](std::shared_ptr const& rhs, std::shared_ptr const& lhs) { + return (*rhs)[sfSequence] < (*lhs)[sfSequence]; + }); return offers; } @@ -4685,14 +4600,14 @@ public: // IOU/IOU, XRP/IOU, IOU/XRP offers have TickSize logic unchanged // IOU/MPT, MPT/IOU have TickSize logic applied to adjust IOU only std::vector const tests = { - {.toAsset1 = getIOU, .toAsset2 = getIOU, .val1 = 10, .val2 = 30}, - {.toAsset1 = getIOU, .toAsset2 = getXRP, .val1 = 10, .val2 = 30'000'000}, - {.toAsset1 = getXRP, .toAsset2 = getIOU, .val1 = 10'000'000, .val2 = 30}, - {.toAsset1 = getMPT, .toAsset2 = getXRP, .val1 = 10'000'000, .val2 = 30'000'000}, - {.toAsset1 = getXRP, .toAsset2 = getMPT, .val1 = 10'000'000, .val2 = 30'000'000}, - {.toAsset1 = getIOU, .toAsset2 = getMPT, .val1 = 10, .val2 = 30'000'000}, - {.toAsset1 = getMPT, .toAsset2 = getIOU, .val1 = 10'000'000, .val2 = 30}, - {.toAsset1 = getMPT, .toAsset2 = getMPT, .val1 = 10'000'000, .val2 = 30'000'000}}; + {getIOU, getIOU, 10, 30}, + {getIOU, getXRP, 10, 30'000'000}, + {getXRP, getIOU, 10'000'000, 30}, + {getMPT, getXRP, 10'000'000, 30'000'000}, + {getXRP, getMPT, 10'000'000, 30'000'000}, + {getIOU, getMPT, 10, 30'000'000}, + {getMPT, getIOU, 10'000'000, 30}, + {getMPT, getMPT, 10'000'000, 30'000'000}}; for (TestInfo const& t : tests) { Env env{*this, features}; @@ -4724,7 +4639,7 @@ public: env(offer(alice, xts(t.val2), xxx(t.val1)), Json(jss::Flags, tfSell)); std::map> offers; - forEachItem(*env.current(), alice, [&](SLE::const_ref sle) { + forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) { offers.emplace( @@ -4786,101 +4701,6 @@ public: } } - void - testAutoCreateReserve(FeatureBitset features) - { - // When an offer on the book is partially crossed, the payment engine - // auto-creates a new ledger object (MPToken or IOU trustline) for the - // offer owner to hold the incoming asset. This happens inside - // BookStep::forEachOffer (MPT: checkCreateMPT) and BookStep::consumeOffer - // (IOU: directSendNoFeeIOU -> trustCreate) without a reserve sufficiency - // check. The offer owner can therefore end up with more objects than - // their XRP balance can reserve for, consistent with IOU behavior. - - testcase("Auto-Create Object Without Reserve Check During Partial Crossing"); - - using namespace jtx; - - auto const gw = Account{"gateway"}; - auto const alice = Account{"alice"}; - auto const carol = Account{"carol"}; - auto const bob = Account{"bob"}; - - auto test = [&](auto&& getToken, auto&& execTx) { - // MPT/IOU: carol's existing offer buys MPT/IOU by selling XRP. - // carol has no MPToken/Trustline for this issuance. When alice partially crosses - // carol's offer, an MPToken/Trustline is auto-created for carol without checking - // that she can afford the extra reserve slot. - Env env{*this, features}; - - auto const f = env.current()->fees().base; - auto const r = reserve(env, 0); - auto const inc = reserve(env, 1) - r; - - env.fund(XRP(10'000), gw, alice, bob); - - // getToken: - // - Create MPT with CanTransfer + CanTrade; authorize alice as holder. - // - Create IOU trustline - auto const token = getToken(env); - - // carol: reserve(0) + 1 increment + fee covers placing one offer. - // After the offer tx she has exactly reserve(1) + XRP(30). - // XRP(30) < inc (50 XRP), so receiving a second object will put her - // below reserve(2). - if (BEAST_EXPECT(inc > XRP(30))) - env.fund(r + inc + f + XRP(30), carol); - - // carol's offer goes on the book (no counterpart yet). - // TakerPays=Token(30): carol will receive Token when crossed. - // TakerGets=XRP(30): carol will give XRP when crossed. - env(offer(carol, token(30), XRP(30))); - env.require(Owners(carol, 1)); - - // Execute offer create or cross-currency payment - // alice partially crosses carol's offer. - // alice sends Token(15) to carol and receives XRP(15). - // Token: - // - MPT: checkCreateMPT auto-creates an MPToken for carol (no reserve check). - // - IOU: directSendNoFeeIOU auto-creates an Trustline for carol (no reserve check). - execTx(env, token); - - // Carol now owns 2 objects (remaining offer + new MPToken) even - // though her XRP balance is only reserve(1) + XRP(15), which is - // below reserve(2) = reserve(1) + inc. - auto const carolBalance = r + inc + XRP(15); - env.require(Owners(carol, 2), Balance(carol, token(15)), Balance(carol, carolBalance)); - BEAST_EXPECT(carolBalance < r + 2 * inc); // below reserve(2) - }; - std::function const getIOU = [&](Env& env) -> PrettyAsset { - env.trust(gw["USD"](1'000), alice); - env(pay(gw, alice, gw["USD"](100))); - return gw["USD"]; - }; - std::function const getMPT = [&](Env& env) -> PrettyAsset { - MPT const mpT1 = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 100}); - return mpT1; - }; - for (auto&& getToken : {getIOU, getMPT}) - { - test(getToken, [&](Env& env, PrettyAsset const& token) { - // alice partially crosses carol's offer. - // alice sends Token(15) to carol and receives XRP(15). - // Token is MPT: checkCreateMPT auto-creates an MPToken for carol (no reserve - // check). Token is IOU: directSendNoFeeIOU auto-creates a trustline for carol (no - // reserve check). - env(offer(alice, XRP(15), token(15))); - }); - test(getToken, [&](Env& env, PrettyAsset const& token) { - // Similar to above but with cross-currency payment. - env(pay(alice, bob, XRP(15)), - Sendmax(token(15)), - Path(~XRP), - Txflags(tfNoRippleDirect | tfPartialPayment)); - }); - } - } - void testAll(FeatureBitset features) { @@ -4937,15 +4757,14 @@ public: testRmSmallIncreasedQOffersMPT(features); testFillOrKill(features); testTickSize(features); - testAutoCreateReserve(features); } void run() override { using namespace jtx; - static FeatureBitset const kAll{testableAmendments()}; - testAll(kAll); + static FeatureBitset const kALL{testableAmendments()}; + testAll(kALL); } }; diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 83c58884e0..5d5f16981c 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -259,7 +260,7 @@ public: for (int i = 0; i < 101; ++i) env(offer(carol, usd(1), eur(2))); - env(pay(alice, bob, eur(kEpsilon)), Path(~eur), Sendmax(usd(100))); + env(pay(alice, bob, eur(kEPSILON)), Path(~eur), Sendmax(usd(100))); } void @@ -754,11 +755,11 @@ public: } // Helper function that returns the Offers on an account. - static std::vector + static std::vector> offersOnAccount(jtx::Env& env, jtx::Account const& account) { - std::vector result; - forEachItem(*env.current(), account, [&result](SLE::const_ref sle) { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) result.push_back(sle); }); @@ -817,7 +818,7 @@ public: Owners(alice, 1), offers(alice, 0), Balance(bob, startBalance - (f * 2)), - Balance(bob, usd(kNone)), + Balance(bob, usd(kNONE)), Owners(bob, 1), offers(bob, 1)); @@ -1127,7 +1128,7 @@ public: offers(alice, 0), Owners(alice, 1), Balance(bob, startBalance - f), - Balance(bob, usd(kNone)), + Balance(bob, usd(kNONE)), offers(bob, 1), Owners(bob, 1)); } @@ -1238,7 +1239,7 @@ public: BEAST_EXPECT(isOffer(env, accountToTest, XRP(1000), usd(50))); // now make an offer that will cross and auto-bridge, meaning - // the outstanding offers will be taken leaving us with kNone + // the outstanding offers will be taken leaving us with kNONE env(offer(accountToTest, usd(50), btc(250))); auto jrr = getBookOffers(env, usd, btc); @@ -1571,7 +1572,7 @@ public: 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::Values::None)); + jro[jss::node][jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone)); env(pay(alice, alice, XRP(500)), Sendmax(usd(100))); @@ -1650,8 +1651,7 @@ 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == usd(60).value().getJson(JsonOptions::KNone)); // the balance between alice and gw is 160 USD..200 less the 40 taken // by the offer @@ -1732,8 +1732,7 @@ 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == usd(25).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(250).value().getText()); } @@ -1778,8 +1777,7 @@ public: 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == usd(25).value().getJson(JsonOptions::KNone)); } void @@ -1817,7 +1815,7 @@ public: auto const danOfferSeq = env.seq(dan); env(offer(dan, XRP(500), eur(50))); - json::Value jtp{json::ValueType::Array}; + json::Value jtp{json::ArrayValue}; jtp[0u][0u][jss::currency] = "XRP"; env(pay(alice, bob, eur(30)), Json(jss::Paths, jtp), Sendmax(usd(333))); @@ -1835,13 +1833,11 @@ public: 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::Values::None)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == usd(20).value().getJson(JsonOptions::KNone)); jro = ledgerEntryOffer(env, dan, danOfferSeq); BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == - gw2["EUR"](20).value().getJson(JsonOptions::Values::None)); + jro[jss::node][jss::TakerGets] == gw2["EUR"](20).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); } @@ -1906,7 +1902,7 @@ public: env.require(Owners(alice, 2)); env.require(Balance(carol, usd(0))); - env.require(Balance(carol, eur(kNone))); + env.require(Balance(carol, eur(kNONE))); env.require(offers(carol, 0)); env.require(Owners(carol, 1)); @@ -2153,8 +2149,7 @@ public: 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::Values::None); + payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::KNone); auto jrr = wsc->invoke("submit", payment); BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -2534,8 +2529,8 @@ public: env.close(); env.require(Balance(alice, usd(1000))); - env.require(Balance(alice, eur(kNone))); - env.require(Balance(bob, usd(kNone))); + env.require(Balance(alice, eur(kNONE))); + env.require(Balance(bob, usd(kNONE))); env.require(Balance(bob, eur(1000))); env.require(offers(alice, 0)); env.require(offers(bob, 0)); @@ -2880,7 +2875,7 @@ public: // alice submits a tfSell | tfFillOrKill offer that does not cross. env(offer(alice, usd(21), XRP(2100), tfSell | tfFillOrKill), Ter(killedCode)); env.close(); - env.require(Balance(alice, usd(kNone))); + env.require(Balance(alice, usd(kNONE))); env.require(offers(alice, 0)); env.require(Balance(bob, usd(100))); } @@ -3155,14 +3150,14 @@ public: env(pay(kim, meg, nBux(60)), Path(lex, ned), Sendmax(kBux(200))); env.close(); - env.require(Balance(kim, kBux(kNone))); - env.require(Balance(kim, nBux(kNone))); + env.require(Balance(kim, kBux(kNONE))); + env.require(Balance(kim, nBux(kNONE))); env.require(Balance(lex, kBux(72))); env.require(Balance(lex, nBux(40))); - env.require(Balance(meg, kBux(kNone))); + env.require(Balance(meg, kBux(kNONE))); env.require(Balance(meg, nBux(60))); - env.require(Balance(ned, kBux(kNone))); - env.require(Balance(ned, nBux(kNone))); + env.require(Balance(ned, kBux(kNONE))); + env.require(Balance(ned, nBux(kNONE))); // Now verify that offer crossing is unaffected by QualityOut. env(offer(lex, kBux(30), nBux(30))); @@ -3171,14 +3166,14 @@ public: env(offer(kim, nBux(30), kBux(30))); env.close(); - env.require(Balance(kim, kBux(kNone))); + env.require(Balance(kim, kBux(kNONE))); env.require(Balance(kim, nBux(30))); env.require(Balance(lex, kBux(102))); env.require(Balance(lex, nBux(10))); - env.require(Balance(meg, kBux(kNone))); + env.require(Balance(meg, kBux(kNONE))); env.require(Balance(meg, nBux(60))); env.require(Balance(ned, kBux(-30))); - env.require(Balance(ned, nBux(kNone))); + env.require(Balance(ned, nBux(kNONE))); } { // Make sure things work right when we're auto-bridging as well. @@ -3511,14 +3506,14 @@ public: env(pay(ann, cam, dBux(60)), Path(bob, dan), Sendmax(aBux(200))); env.close(); - env.require(Balance(ann, aBux(kNone))); - env.require(Balance(ann, dBux(kNone))); + env.require(Balance(ann, aBux(kNONE))); + env.require(Balance(ann, dBux(kNONE))); env.require(Balance(bob, aBux(72))); env.require(Balance(bob, dBux(40))); - env.require(Balance(cam, aBux(kNone))); + env.require(Balance(cam, aBux(kNONE))); env.require(Balance(cam, dBux(60))); - env.require(Balance(dan, aBux(kNone))); - env.require(Balance(dan, dBux(kNone))); + env.require(Balance(dan, aBux(kNONE))); + env.require(Balance(dan, dBux(kNONE))); env(offer(bob, aBux(30), dBux(30))); env.close(); @@ -3533,14 +3528,14 @@ public: Ter(temBAD_PATH)); env.close(); - env.require(Balance(ann, aBux(kNone))); + env.require(Balance(ann, aBux(kNONE))); env.require(Balance(ann, dBux(0))); env.require(Balance(bob, aBux(72))); env.require(Balance(bob, dBux(40))); - env.require(Balance(cam, aBux(kNone))); + env.require(Balance(cam, aBux(kNONE))); env.require(Balance(cam, dBux(60))); env.require(Balance(dan, aBux(0))); - env.require(Balance(dan, dBux(kNone))); + env.require(Balance(dan, dBux(kNONE))); } } @@ -3927,10 +3922,10 @@ public: // clang-format off TestData const tests[]{ // btcStart --------------------- actor[0] --------------------- -------------------- actor[1] ------------------- - {.self=0, .leg0=0, .leg1=1, .btcStart=btc(20), .actors={{.acct="ann", .offers=0, .xrp=drops(3900000'000000 - (4 * baseFee)), .btc=btc(20.0), .usd=usd(3000)}, {.acct="abe", .offers=0, .xrp=drops(4100000'000000 - (3 * baseFee)), .btc=btc( 0), .usd=usd(750)}}}, // no BTC xfer fee - {.self=0, .leg0=1, .leg1=0, .btcStart=btc(20), .actors={{.acct="bev", .offers=0, .xrp=drops(4100000'000000 - (4 * baseFee)), .btc=btc( 7.5), .usd=usd(2000)}, {.acct="bob", .offers=0, .xrp=drops(3900000'000000 - (3 * baseFee)), .btc=btc(10), .usd=usd( 0)}}}, // no USD xfer fee - {.self=0, .leg0=0, .leg1=0, .btcStart=btc(20), .actors={{.acct="cam", .offers=0, .xrp=drops(4000000'000000 - (5 * baseFee)), .btc=btc(20.0), .usd=usd(2000)} }}, // no xfer fee - {.self=0, .leg0=1, .leg1=0, .btcStart=btc( 5), .actors={{.acct="deb", .offers=1, .xrp=drops(4040000'000000 - (4 * baseFee)), .btc=btc( 0.0), .usd=usd(2000)}, {.acct="dan", .offers=1, .xrp=drops(3960000'000000 - (3 * baseFee)), .btc=btc( 4), .usd=usd( 0)}}}, // no USD xfer fee + {.self=0, .leg0=0, .leg1=1, .btcStart=btc(20), .actors={{"ann", 0, drops(3900000'000000 - (4 * baseFee)), btc(20.0), usd(3000)}, {"abe", 0, drops(4100000'000000 - (3 * baseFee)), btc( 0), usd(750)}}}, // no BTC xfer fee + {.self=0, .leg0=1, .leg1=0, .btcStart=btc(20), .actors={{"bev", 0, drops(4100000'000000 - (4 * baseFee)), btc( 7.5), usd(2000)}, {"bob", 0, drops(3900000'000000 - (3 * baseFee)), btc(10), usd( 0)}}}, // no USD xfer fee + {.self=0, .leg0=0, .leg1=0, .btcStart=btc(20), .actors={{"cam", 0, drops(4000000'000000 - (5 * baseFee)), btc(20.0), usd(2000)} }}, // no xfer fee + {.self=0, .leg0=1, .leg1=0, .btcStart=btc( 5), .actors={{"deb", 1, drops(4040000'000000 - (4 * baseFee)), btc( 0.0), usd(2000)}, {"dan", 1, drops(3960000'000000 - (3 * baseFee)), btc( 4), usd( 0)}}}, // no USD xfer fee }; // clang-format on @@ -3979,7 +3974,7 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::ranges::remove_if(actorOffers, [](SLE::const_pointer& offer) { + std::ranges::remove_if(actorOffers, [](std::shared_ptr& offer) { return (*offer)[sfTakerGets].signum() == 0; }).begin()); BEAST_EXPECT(offerCount == actor.offers); @@ -4075,8 +4070,8 @@ public: // clang-format off TestData const tests[]{ // btcStart ------------------- actor[0] -------------------- ------------------- actor[1] -------------------- - {.self=0, .leg0=0, .leg1=1, .btcStart=btc(5), .actors={{.acct="gay", .offers=1, .xrp=drops(3950000'000000 - (4 * baseFee)), .btc=btc(5), .usd=usd(2500)}, {.acct="gar", .offers=1, .xrp=drops(4050000'000000 - (3 * baseFee)), .btc=btc(0), .usd=usd(1375)}}}, // no BTC xfer fee - {.self=0, .leg0=0, .leg1=0, .btcStart=btc(5), .actors={{.acct="hye", .offers=2, .xrp=drops(4000000'000000 - (5 * baseFee)), .btc=btc(5), .usd=usd(2000)} }} // no xfer fee + {.self=0, .leg0=0, .leg1=1, .btcStart=btc(5), .actors={{"gay", 1, drops(3950000'000000 - (4 * baseFee)), btc(5), usd(2500)}, {"gar", 1, drops(4050000'000000 - (3 * baseFee)), btc(0), usd(1375)}}}, // no BTC xfer fee + {.self=0, .leg0=0, .leg1=0, .btcStart=btc(5), .actors={{"hye", 2, drops(4000000'000000 - (5 * baseFee)), btc(5), usd(2000)} }} // no xfer fee }; // clang-format on @@ -4125,7 +4120,7 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::ranges::remove_if(actorOffers, [](SLE::const_pointer& offer) { + std::ranges::remove_if(actorOffers, [](std::shared_ptr& offer) { return (*offer)[sfTakerGets].signum() == 0; }).begin()); BEAST_EXPECT(offerCount == actor.offers); @@ -4236,7 +4231,7 @@ public: env.close(); env.require(offers(alice, 1)); - env.require(Balance(alice, gwUSD(kNone))); + env.require(Balance(alice, gwUSD(kNONE))); env(fset(gw, asfRequireAuth)); env.close(); @@ -4260,7 +4255,7 @@ public: env.require(offers(alice, 0)); // alice's unauthorized offer is deleted & bob's offer not crossed. - env.require(Balance(alice, gwUSD(kNone))); + env.require(Balance(alice, gwUSD(kNONE))); env.require(offers(bob, 1)); env.require(Balance(bob, gwUSD(50))); @@ -4271,7 +4266,7 @@ public: env.close(); env.require(offers(alice, 0)); - env.require(Balance(alice, gwUSD(kNone))); + env.require(Balance(alice, gwUSD(kNONE))); env.require(offers(bob, 1)); env.require(Balance(bob, gwUSD(50))); @@ -4585,25 +4580,25 @@ public: env.close(); auto txn = noop(gw); - txn[sfTickSize.fieldName] = Quality::kMinTickSize - 1; + txn[sfTickSize.fieldName] = Quality::kMIN_TICK_SIZE - 1; env(txn, Ter(temBAD_TICK_SIZE)); - txn[sfTickSize.fieldName] = Quality::kMinTickSize; + txn[sfTickSize.fieldName] = Quality::kMIN_TICK_SIZE; env(txn); - BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::kMinTickSize); + BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::kMIN_TICK_SIZE); txn = noop(gw); - txn[sfTickSize.fieldName] = Quality::kMaxTickSize; + txn[sfTickSize.fieldName] = Quality::kMAX_TICK_SIZE; env(txn); BEAST_EXPECT(!env.le(gw)->isFieldPresent(sfTickSize)); txn = noop(gw); - txn[sfTickSize.fieldName] = Quality::kMaxTickSize - 1; + txn[sfTickSize.fieldName] = Quality::kMAX_TICK_SIZE - 1; env(txn); - BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::kMaxTickSize - 1); + BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::kMAX_TICK_SIZE - 1); txn = noop(gw); - txn[sfTickSize.fieldName] = Quality::kMaxTickSize + 1; + txn[sfTickSize.fieldName] = Quality::kMAX_TICK_SIZE + 1; env(txn, Ter(temBAD_TICK_SIZE)); txn[sfTickSize.fieldName] = 0; @@ -4640,7 +4635,7 @@ public: env(offer(alice, xts(30), xxx(10)), Json(jss::Flags, tfSell)); std::map> offers; - forEachItem(*env.current(), alice, [&](SLE::const_ref sle) { + forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) { offers.emplace( @@ -4675,13 +4670,15 @@ public: } // Helper function that returns offers on an account sorted by sequence. - static std::vector + static std::vector> sortedOffersOnAccount(jtx::Env& env, jtx::Account const& acct) { - std::vector offers{offersOnAccount(env, acct)}; - std::ranges::sort(offers, [](SLE::const_ref rhs, SLE::const_ref lhs) { - return (*rhs)[sfSequence] < (*lhs)[sfSequence]; - }); + std::vector> offers{offersOnAccount(env, acct)}; + std::ranges::sort( + offers, + [](std::shared_ptr const& rhs, std::shared_ptr const& lhs) { + return (*rhs)[sfSequence] < (*lhs)[sfSequence]; + }); return offers; } diff --git a/src/test/app/Oracle_test.cpp b/src/test/app/Oracle_test.cpp index 7e7f5e9bd0..84ef568d52 100644 --- a/src/test/app/Oracle_test.cpp +++ b/src/test/app/Oracle_test.cpp @@ -286,7 +286,7 @@ private: .err = Ter(tecINVALID_UPDATE_TIME)}); oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); BEAST_EXPECT(oracle.expectLastUpdateTime( - static_cast(kTestStartTime.count() + 450))); + static_cast(kTEST_START_TIME.count() + 450))); // Less than the previous lastUpdateTime oracle.set( UpdateArg{ @@ -298,7 +298,7 @@ private: oracle.set( UpdateArg{ .series = {{"XRP", "USD", 740, 1}}, - .lastUpdateTime = static_cast(kEpochOffset.count() - 1), + .lastUpdateTime = static_cast(kEPOCH_OFFSET.count() - 1), .fee = baseFee, .err = Ter(tecINVALID_UPDATE_TIME)}); } @@ -344,7 +344,7 @@ private: Oracle const oracle( env, {.owner = owner, - .series = {{"USD", "BTC", 740, kMaxPriceScale + 1}}, + .series = {{"USD", "BTC", 740, kMAX_PRICE_SCALE + 1}}, .fee = baseFee, .err = Ter(temMALFORMED)}); } @@ -748,7 +748,7 @@ private: .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::kNone), Sig(alie)); + env(signers(alice, jtx::kNONE), Sig(alie)); env.close(); env.require(Owners(alice, 1)); // create new signer list diff --git a/src/test/app/PathMPT_test.cpp b/src/test/app/PathMPT_test.cpp index 3ba67b58a6..ef8aa587f8 100644 --- a/src/test/app/PathMPT_test.cpp +++ b/src/test/app/PathMPT_test.cpp @@ -48,14 +48,14 @@ rpf(jtx::Account const& src, xrpl::test::jtx::MPT const& usd, std::vector const& numSrc) { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::command] = "ripple_path_find"; jv[jss::source_account] = toBase58(src); if (!numSrc.empty()) { - auto& sc = (jv[jss::source_currencies] = json::ValueType::Array); - json::Value j = json::ValueType::Object; + auto& sc = (jv[jss::source_currencies] = json::ArrayValue); + json::Value j = json::ObjectValue; for (auto const& id : numSrc) { j[jss::mpt_issuance_id] = to_string(id); @@ -66,7 +66,7 @@ rpf(jtx::Account const& src, auto const d = toBase58(dst); jv[jss::destination_account] = d; - json::Value& j = (jv[jss::destination_amount] = json::ValueType::Object); + json::Value& j = (jv[jss::destination_amount] = json::ObjectValue); j[jss::mpt_issuance_id] = to_string(usd.mpt()); j[jss::value] = "1"; @@ -87,9 +87,9 @@ class PathMPT_test : public beast::unit_test::Suite // with the search parameters that the tests were written for. using namespace jtx; return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->pathSearchOld = 7; - cfg->pathSearch = 7; - cfg->pathSearchMax = 10; + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; return cfg; })); } @@ -112,7 +112,7 @@ public: MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 100}); auto& app = env.app(); - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; Resource::Consumer c; RPC::JsonContext context{ @@ -125,15 +125,15 @@ public: .role = Role::USER, .coro = {}, .infoSub = {}, - .apiVersion = RPC::kApiVersionIfUnspecified}, + .apiVersion = RPC::kAPI_VERSION_IF_UNSPECIFIED}, {}, {}}; json::Value result; Gate g; // Test RPC::Tuning::max_src_cur source currencies. std::vector numSrc; - numSrc.reserve(RPC::Tuning::kMaxSrcCur); - for (std::uint8_t i = 0; i < RPC::Tuning::kMaxSrcCur; ++i) + numSrc.reserve(RPC::Tuning::kMAX_SRC_CUR); + for (std::uint8_t i = 0; i < RPC::Tuning::kMAX_SRC_CUR; ++i) numSrc.push_back(makeMptID(i, bob)); app.getJobQueue().postCoro(JtClient, "RPC-Client", [&](auto const& coro) { context.params = xrpl::test::detail::rpf(alice, bob, usd, numSrc); @@ -145,7 +145,7 @@ public: BEAST_EXPECT(!result.isMember(jss::error)); // Test more than RPC::Tuning::max_src_cur source currencies. - numSrc.push_back(makeMptID(RPC::Tuning::kMaxSrcCur, bob)); + numSrc.push_back(makeMptID(RPC::Tuning::kMAX_SRC_CUR, bob)); app.getJobQueue().postCoro(JtClient, "RPC-Client", [&](auto const& coro) { context.params = xrpl::test::detail::rpf(alice, bob, usd, numSrc); context.coro = coro; @@ -157,7 +157,7 @@ public: // Test RPC::Tuning::max_auto_src_cur source currencies. numSrc.clear(); - for (auto i = 0; i < (RPC::Tuning::kMaxAutoSrcCur - 1); ++i) + for (auto i = 0; i < (RPC::Tuning::kMAX_AUTO_SRC_CUR - 1); ++i) { auto curm = MPTTester({.env = env, .issuer = alice, .holders = {bob}}); numSrc.push_back(curm.issuanceID()); diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 4cfe938798..9424bc05bf 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -63,14 +63,14 @@ namespace xrpl::test { json::Value rpf(jtx::Account const& src, jtx::Account const& dst, std::uint32_t numSrc) { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::command] = "ripple_path_find"; jv[jss::source_account] = toBase58(src); if (numSrc > 0) { - auto& sc = (jv[jss::source_currencies] = json::ValueType::Array); - json::Value j = json::ValueType::Object; + auto& sc = (jv[jss::source_currencies] = json::ArrayValue); + json::Value j = json::ObjectValue; while ((numSrc--) != 0u) { j[jss::currency] = std::to_string(numSrc + 100); @@ -81,7 +81,7 @@ rpf(jtx::Account const& src, jtx::Account const& dst, std::uint32_t numSrc) auto const d = toBase58(dst); jv[jss::destination_account] = d; - json::Value& j = (jv[jss::destination_amount] = json::ValueType::Object); + json::Value& j = (jv[jss::destination_amount] = json::ObjectValue); j[jss::currency] = "USD"; j[jss::value] = "0.01"; j[jss::issuer] = d; @@ -101,9 +101,9 @@ class Path_test : public beast::unit_test::Suite // with the search parameters that the tests were written for. using namespace jtx; return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->pathSearchOld = 7; - cfg->pathSearch = 7; - cfg->pathSearchMax = 10; + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; return cfg; })); } @@ -151,7 +151,7 @@ public: using namespace jtx; auto& app = env.app(); - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; Resource::Consumer c; RPC::JsonContext context{ @@ -164,21 +164,21 @@ public: .role = Role::USER, .coro = {}, .infoSub = {}, - .apiVersion = RPC::kApiVersionIfUnspecified}, + .apiVersion = RPC::kAPI_VERSION_IF_UNSPECIFIED}, {}, {}}; - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; 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::Values::None); + params[jss::destination_amount] = saDstAmount.getJson(JsonOptions::KNone); if (saSendMax) - params[jss::send_max] = saSendMax->getJson(JsonOptions::Values::None); + params[jss::send_max] = saSendMax->getJson(JsonOptions::KNone); if (saSrcCurrency) { - auto& sc = params[jss::source_currencies] = json::ValueType::Array; - json::Value j = json::ValueType::Object; + auto& sc = params[jss::source_currencies] = json::ArrayValue; + json::Value j = json::ObjectValue; j[jss::currency] = to_string(saSrcCurrency.value()); sc.append(j); } @@ -216,7 +216,7 @@ public: STAmount da; if (result.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, result[jss::destination_amount]); + da = amountFromJson(kSF_GENERIC, result[jss::destination_amount]); STAmount sa; STPathSet paths; @@ -228,10 +228,10 @@ public: auto const& path = alts[0u]; if (path.isMember(jss::source_amount)) - sa = amountFromJson(sfGeneric, path[jss::source_amount]); + sa = amountFromJson(kSF_GENERIC, path[jss::source_amount]); if (path.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, path[jss::destination_amount]); + da = amountFromJson(kSF_GENERIC, path[jss::destination_amount]); if (path.isMember(jss::paths_computed)) { @@ -262,7 +262,7 @@ public: env.close(); auto& app = env.app(); - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; Resource::Consumer c; RPC::JsonContext context{ @@ -275,14 +275,14 @@ public: .role = Role::USER, .coro = {}, .infoSub = {}, - .apiVersion = RPC::kApiVersionIfUnspecified}, + .apiVersion = RPC::kAPI_VERSION_IF_UNSPECIFIED}, {}, {}}; 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::kMaxSrcCur); + context.params = rpf(Account("alice"), Account("bob"), RPC::Tuning::kMAX_SRC_CUR); context.coro = coro; RPC::doCommand(context, result); g.signal(); @@ -292,7 +292,7 @@ public: // 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::kMaxSrcCur + 1); + context.params = rpf(Account("alice"), Account("bob"), RPC::Tuning::kMAX_SRC_CUR + 1); context.coro = coro; RPC::doCommand(context, result); g.signal(); @@ -301,7 +301,7 @@ public: BEAST_EXPECT(result.isMember(jss::error)); // Test RPC::Tuning::max_auto_src_cur source currencies. - for (auto i = 0; i < (RPC::Tuning::kMaxAutoSrcCur - 1); ++i) + for (auto i = 0; i < (RPC::Tuning::kMAX_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); @@ -881,7 +881,7 @@ public: jv); auto const jvL = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"])) - ->getJson(JsonOptions::Values::None); + ->getJson(JsonOptions::KNone); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jvL[it.memberName()]); } @@ -923,7 +923,7 @@ public: jv); auto const jvL = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"])) - ->getJson(JsonOptions::Values::None); + ->getJson(JsonOptions::KNone); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jvL[it.memberName()]); @@ -973,7 +973,7 @@ public: jv); auto const jvL = env.le(keylet::line(Account("alice").id(), Account("bob")["USD"])) - ->getJson(JsonOptions::Values::None); + ->getJson(JsonOptions::KNone); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jvL[it.memberName()]); diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index 0b4222ca48..c775dd2b6a 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -56,7 +57,7 @@ using namespace jtx::paychan; struct PayChan_test : public beast::unit_test::Suite { - static std::pair + static std::pair> channelKeyAndSle(ReadView const& view, jtx::Account const& account, jtx::Account const& dst) { auto const sle = view.read(keylet::account(account)); @@ -245,7 +246,7 @@ struct PayChan_test : public beast::unit_test::Suite BEAST_EXPECT(!channelExists(*env.current(), chan)); auto const feeDrops = env.current()->fees().base; auto const delta = chanAmt - chanBal; - assert(delta > beast::kZero); + assert(delta > beast::kZERO); BEAST_EXPECT(env.balance(alice) == preAlice + delta); BEAST_EXPECT(env.balance(bob) == preBob - feeDrops); } @@ -868,7 +869,7 @@ struct PayChan_test : public beast::unit_test::Suite env.close(); // Setup deposit authorization - env(deposit::authCredentials(bob, {{.issuer = carol, .credType = credType}})); + env(deposit::authCredentials(bob, {{carol, credType}})); env.close(); // Fail, credentials doesn’t belong to root account @@ -1028,9 +1029,9 @@ struct PayChan_test : public beast::unit_test::Suite testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } { // test destination_account non-string @@ -1047,9 +1048,9 @@ struct PayChan_test : public beast::unit_test::Suite testInvalidDestAccountParam(1); testInvalidDestAccountParam(1.1); testInvalidDestAccountParam(true); - testInvalidDestAccountParam(json::Value(json::ValueType::Null)); - testInvalidDestAccountParam(json::Value(json::ValueType::Object)); - testInvalidDestAccountParam(json::Value(json::ValueType::Array)); + testInvalidDestAccountParam(json::Value(json::NullValue)); + testInvalidDestAccountParam(json::Value(json::ObjectValue)); + testInvalidDestAccountParam(json::Value(json::ArrayValue)); } { auto const r = env.rpc("account_channels", alice.human(), bob.human()); @@ -1126,7 +1127,7 @@ struct PayChan_test : public beast::unit_test::Suite auto testLimit = [](test::jtx::Env& env, test::jtx::Account const& src, std::optional limit = std::nullopt, - json::Value const& marker = json::ValueType::Null, + json::Value const& marker = json::NullValue, std::optional const& dst = std::nullopt) { json::Value jvc; jvc[jss::account] = src.human(); @@ -1160,7 +1161,7 @@ struct PayChan_test : public beast::unit_test::Suite auto const numFull = bobs.size() / limit; auto const numNonFull = ((bobs.size() % limit) != 0u) ? 1 : 0; - json::Value marker = json::ValueType::Null; + json::Value marker = json::NullValue; auto const testIt = [&](bool expectMarker, int expectedBatchSize) { auto const r = testLimit(env, alice, limit, marker); @@ -1250,7 +1251,7 @@ struct PayChan_test : public beast::unit_test::Suite env(create(alice, bob, channelFunds, settleDelay, pk)); env.close(); - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::channel_id] = chan1Str; args[jss::key_type] = "ed255191"; args[jss::seed] = "snHq1rzQoN2qiUkC3XF5RyxBzUtN"; @@ -1481,7 +1482,7 @@ struct PayChan_test : public beast::unit_test::Suite BEAST_EXPECT(rs[jss::error] == "channelAmtMalformed"); { // Missing channel_id - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = "2000"; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; @@ -1490,7 +1491,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // Missing amount - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; @@ -1499,7 +1500,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // Missing key_type and no secret. - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = "2000"; args[jss::channel_id] = chan1Str; args[jss::passphrase] = "passphrase_can_be_anything"; @@ -1508,7 +1509,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // Both passphrase and seed specified. - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = "2000"; args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; @@ -1519,7 +1520,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // channel_id is not exact hex. - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = "2000"; args[jss::channel_id] = chan1Str + "1"; args[jss::key_type] = "secp256k1"; @@ -1529,7 +1530,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // amount is not a string - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = 2000; args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; @@ -1539,7 +1540,7 @@ struct PayChan_test : public beast::unit_test::Suite } { // Amount is not a decimal string. - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::amount] = "TwoThousand"; args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; @@ -1664,8 +1665,9 @@ struct PayChan_test : public beast::unit_test::Suite auto const settleDelay = 100s; auto const pk = alice.pk(); - auto inOwnerDir = - [](ReadView const& view, Account const& acc, SLE::const_ref 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())); // NOLINTNEXTLINE(modernize-use-ranges) return std::find(ownerDir.begin(), ownerDir.end(), chan) != ownerDir.end(); @@ -1914,7 +1916,7 @@ struct PayChan_test : public beast::unit_test::Suite STAmount const reqAmt = authAmt + drops(1); assert(reqAmt <= chanAmt); // Note that since claim() returns a tem (neither tec nor tes), - // the ticket is not consumed. So we don't kIncrement bobTicket. + // the ticket is not consumed. So we don't kINCREMENT bobTicket. auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqAmt, authAmt, Slice(sig), alice.pk()), ticket::Use(bobTicketSeq), @@ -1949,7 +1951,7 @@ struct PayChan_test : public beast::unit_test::Suite BEAST_EXPECT(!channelExists(*env.current(), chan)); auto const feeDrops = env.current()->fees().base; auto const delta = chanAmt - chanBal; - assert(delta > beast::kZero); + assert(delta > beast::kZERO); BEAST_EXPECT(env.balance(alice) == preAlice + delta); BEAST_EXPECT(env.balance(bob) == preBob - feeDrops); } diff --git a/src/test/app/PayStrandMPT_test.cpp b/src/test/app/PayStrandMPT_test.cpp index 20e582fbf7..5550a26ab2 100644 --- a/src/test/app/PayStrandMPT_test.cpp +++ b/src/test/app/PayStrandMPT_test.cpp @@ -328,7 +328,7 @@ struct PayStrandMPT_test : public beast::unit_test::Suite {.env = env, .issuer = gw, .holders = {alice, bob}, - .flags = kMptDexFlags | tfMPTCanLock, + .flags = kMPT_DEX_FLAGS | tfMPTCanLock, .maxAmt = 1'000}); MPT const usd = usdm; env(pay(gw, alice, usd(100))); @@ -361,7 +361,7 @@ struct PayStrandMPT_test : public beast::unit_test::Suite auto usdm = MPTTester( {.env = env, .issuer = gw, - .flags = kMptDexFlags | tfMPTRequireAuth, + .flags = kMPT_DEX_FLAGS | tfMPTRequireAuth, .maxAmt = 1'000}); MPT const usd = usdm; diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 67a37833b2..78b152d690 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -308,12 +308,12 @@ struct ExistingElementPool currencyNames.clear(); currencyNames.reserve(numCur); - static constexpr size_t kBufSize = 32; - char buf[kBufSize]; + constexpr size_t kBUF_SIZE = 32; + char buf[kBUF_SIZE]; for (size_t id = 0; id < numAct; ++id) { - snprintf(buf, kBufSize, "A%zu", id); + snprintf(buf, kBUF_SIZE, "A%zu", id); accounts.emplace_back(buf); } @@ -321,15 +321,15 @@ struct ExistingElementPool { if (id < 10) { - snprintf(buf, kBufSize, "CC%zu", id); + snprintf(buf, kBUF_SIZE, "CC%zu", id); } else if (id < 100) { - snprintf(buf, kBufSize, "C%zu", id); + snprintf(buf, kBUF_SIZE, "C%zu", id); } else { - snprintf(buf, kBufSize, "%zu", id); + snprintf(buf, kBUF_SIZE, "%zu", id); } currencies.emplace_back(toCurrency(buf)); currencyNames.emplace_back(buf); diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index a88cbaa868..a0b16aa557 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -7,9 +7,6 @@ #include #include #include -#include -#include -#include #include #include // IWYU pragma: keep #include @@ -37,7 +34,6 @@ #include #include #include -#include #include #include @@ -144,7 +140,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite static uint256 getBookDirKey(Book const& book, STAmount const& takerPays, STAmount const& takerGets) { - return keylet::quality(keylet::kBook(book), getRate(takerGets, takerPays)).key; + return keylet::quality(keylet::kBOOK(book), getRate(takerGets, takerPays)).key; } static std::optional @@ -197,20 +193,6 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); } - // test preflight - malformed DomainID being zero - // Only test this with fixCleanup3_2_0 enabled. Without the fix, - // an assert-enabled build can crash when Ledger::read() receives - // a zero-key PermissionedDomain keylet. - if (features[fixCleanup3_2_0]) - { - Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = - PermissionedDEX(env); - - env(offer(bob_, XRP(10), USD(10)), Domain(uint256{}), Ter(temMALFORMED)); - env.close(); - } - // preclaim - someone outside of the domain cannot create domain offer { Env env(*this, features); @@ -410,24 +392,6 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); } - // test preflight - malformed DomainID being zero - // Only test this with fixCleanup3_2_0 enabled. Without the fix, - // an assert-enabled build can crash when Ledger::read() receives - // a zero-key PermissionedDomain keylet. - if (features[fixCleanup3_2_0]) - { - Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = - PermissionedDEX(env); - - env(pay(bob_, alice_, USD(10)), - Path(~USD), - Sendmax(XRP(10)), - Domain(uint256{}), - Ter(temMALFORMED)); - env.close(); - } - // preclaim - cannot send payment with non existent domain { Env env(*this, features); @@ -1428,12 +1392,13 @@ class PermissionedDEX_test : public beast::unit_test::Suite void testHybridMalformedOffer(FeatureBitset features) { - bool const fixEnabled = features[fixCleanup3_1_3]; + bool const fixS313Enabled = features[fixSecurity3_1_3]; testcase << "Hybrid offer with empty AdditionalBooks" - << (fixEnabled ? " (fixCleanup3_1_3 enabled)" : " (fixCleanup3_1_3 disabled)"); + << (fixS313Enabled ? " (fixSecurity3_1_3 enabled)" + : " (fixSecurity3_1_3 disabled)"); - // offerInDomain has two code paths gated by fixCleanup3_1_3: + // offerInDomain has two code paths gated by fixSecurity3_1_3: // // pre-fix: only rejects a hybrid offer when sfAdditionalBooks is // entirely absent — an empty array (size 0) passes through. @@ -1460,7 +1425,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite // Directly manipulate the offer SLE in the open ledger so that // sfAdditionalBooks is present but empty (size 0). This is the - // malformed state that fixCleanup3_1_3 is designed to catch. + // malformed state that fixSecurity3_1_3 is designed to catch. auto const offerKey = keylet::offer(bob.id(), bobOfferSeq); env.app().getOpenLedger().modify([&offerKey](OpenView& view, beast::Journal) { auto const sle = view.read(offerKey); @@ -1472,9 +1437,9 @@ class PermissionedDEX_test : public beast::unit_test::Suite return true; }); - if (fixEnabled) + if (fixS313Enabled) { - // post-fixCleanup3_1_3: offerInDomain rejects the malformed + // post-fixSecurity3_1_3: offerInDomain rejects the malformed // offer (size == 0), so no valid domain offer is found. env(pay(alice, carol, USD(10)), Path(~USD), @@ -1484,318 +1449,13 @@ class PermissionedDEX_test : public beast::unit_test::Suite } else { - // pre-fixCleanup3_1_3: offerInDomain only checks for a missing + // pre-fixSecurity3_1_3: offerInDomain only checks for a missing // sfAdditionalBooks field; size == 0 passes through, so the // malformed offer is crossed and the payment succeeds. env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); } } - void - testHybridOfferCrossingQuality(FeatureBitset features) - { - bool const fixEnabled = features[fixCleanup3_2_0]; - testcase << "Hybrid offer crossing quality" - << (fixEnabled ? " (fixCleanup3_2_0)" : " (pre-fix)"); - - // Partially-crossed hybrid offer should have consistent quality - // across both book directories. - // - // Steps: - // - Bob places a hybrid offer. - // - Alice places an opposing hybrid offer that partially crosses. - // - // Verify: - // - Domain-book key quality == its sfExchangeRate. - // - Post-fix: open-book key quality == domain-book key quality. - // - Pre-fix: open-book key quality != domain-book key quality - // (key used post-crossing rate, sfExchangeRate used pre-crossing). - - Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = - PermissionedDEX(env); - - // Bob places a hybrid offer: TakerPays = XRP(100), TakerGets = USD(40) - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(100), USD(40)), Txflags(tfHybrid), Domain(domainID)); - env.close(); - BEAST_EXPECT(offerExists(env, bob_, bobOfferSeq)); - - // Alice places a hybrid offer in the opposite direction that - // partially crosses Bob's offer. - // Alice: TakerPays = USD(100), TakerGets = XRP(300) (rate = 3 XRP/USD) - // Bob's offer is at a better rate (2.5 XRP/USD) so crossing occurs. - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(100), XRP(300)), Txflags(tfHybrid), Domain(domainID)); - env.close(); - - // After crossing, Alice's remaining offer should be placed. - auto const sle = env.le(keylet::offer(alice_.id(), aliceOfferSeq)); - BEAST_EXPECT(sle); - BEAST_EXPECT(sle->isFieldPresent(sfAdditionalBooks)); - BEAST_EXPECT(sle->getFieldArray(sfAdditionalBooks).size() == 1); - - auto const domainDirKey = sle->getFieldH256(sfBookDirectory); - auto const openDirKey = - sle->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); - - auto const domainQuality = getQuality(domainDirKey); - auto const openQuality = getQuality(openDirKey); - - // Read the directory SLEs and check sfExchangeRate vs key quality. - auto const domainDirSle = env.le(Keylet(ltDIR_NODE, domainDirKey)); - auto const openDirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); - BEAST_EXPECT(domainDirSle); - BEAST_EXPECT(openDirSle); - - auto const domainExRate = domainDirSle->getFieldU64(sfExchangeRate); - auto const openExRate = openDirSle->getFieldU64(sfExchangeRate); - auto const preCrossingQuality = std::uint64_t{5623825668291712342ULL}; - auto const postCrossingQuality = std::uint64_t{5623825668291712341ULL}; - - // Domain directory: sfExchangeRate should always match key quality - // (both use the pre-crossing rate). Correct behavior. - BEAST_EXPECT(domainQuality == preCrossingQuality); - BEAST_EXPECT(domainExRate == preCrossingQuality); - BEAST_EXPECT(domainExRate == domainQuality); - - if (fixEnabled) - { - // Correct behavior: both directory keys use the pre-crossing rate. - BEAST_EXPECT(openQuality == preCrossingQuality); - BEAST_EXPECT(domainQuality == openQuality); - - // sfExchangeRate matches key quality on both directories. - BEAST_EXPECT(openExRate == preCrossingQuality); - BEAST_EXPECT(openExRate == openQuality); - } - else - { - // Wrong legacy behavior: the open-book directory key uses the - // post-crossing rate instead of the domain-book rate. - BEAST_EXPECT(openQuality == postCrossingQuality); - BEAST_EXPECT(domainQuality != openQuality); - - // The open-book sfExchangeRate still uses the pre-crossing rate, - // so it no longer matches the actual quality encoded in the - // open-book directory key. - BEAST_EXPECT(openExRate == preCrossingQuality); - BEAST_EXPECT(openExRate != openQuality); - BEAST_EXPECT(openExRate == domainQuality); - } - } - - void - testBookExchangeRateFix(FeatureBitset features) - { - testcase("LedgerStateFix BookExchangeRate"); - - // Use the pre-fix path to create a hybrid offer with a mismatched - // sfExchangeRate, then apply LedgerStateFix to correct it. - // - // Steps: - // - Create a partially-crossed hybrid offer (pre-fixCleanup3_2_0) - // so the open-book directory has wrong sfExchangeRate. - // - Re-enable fixCleanup3_2_0 and submit a LedgerStateFix to - // repair the open-book directory's sfExchangeRate. - // - // Verify: - // - Before fix: sfExchangeRate != getQuality(key). - // - After fix: sfExchangeRate == getQuality(key). - - { - // Amendment gate: BookExchangeRate fixes require fixCleanup3_2_0. - Env env(*this, features - fixCleanup3_2_0); - Account const carol{"carol"}; - - env.fund(XRP(1000), carol); - env.close(); - - env(ledgerStateFix::bookExchangeRate(carol, uint256{1}), Ter(temDISABLED)); - } - - { - // Preflight check: BookExchangeRate fixes only accept their - // required fix-specific field. - Env env(*this, features); - Account const carol{"carol"}; - - env.fund(XRP(1000), carol); - env.close(); - - // BookExchangeRate fixes require sfBookDirectory. - auto missingBookDirectory = ledgerStateFix::bookExchangeRate(carol, uint256{1}); - missingBookDirectory.removeMember(sfBookDirectory.jsonName); - env(missingBookDirectory, Ter(temINVALID)); - - // BookExchangeRate fixes reject fields that belong to other - // LedgerStateFix types. - auto extraOwner = ledgerStateFix::bookExchangeRate(carol, uint256{1}); - extraOwner[sfOwner.jsonName] = carol.human(); - env(extraOwner, Ter(temINVALID)); - } - - { - Env env(*this, features); - auto const setup = PermissionedDEX(env); - auto const fixFee = drops(env.current()->fees().increment); - - { - // Preclaim check: the target directory must exist. - env(ledgerStateFix::bookExchangeRate(setup.carol, uint256{1}), - Fee(fixFee), - Ter(tecOBJECT_NOT_FOUND)); - } - - { - // Preclaim check: the target directory must be a book root - // page. Owner directories are ltDIR_NODE entries, but they do - // not carry sfExchangeRate. - auto const ownerDir = keylet::ownerDir(setup.bob.id()); - auto const ownerDirSle = env.le(ownerDir); - BEAST_EXPECT(ownerDirSle); - BEAST_EXPECT(!ownerDirSle->isFieldPresent(sfExchangeRate)); - - env(ledgerStateFix::bookExchangeRate(setup.carol, ownerDir.key), - Fee(fixFee), - Ter(tecNO_PERMISSION)); - } - - { - // Preclaim check: a correct sfExchangeRate leaves nothing to - // repair. - auto const bobOfferSeq{env.seq(setup.bob)}; - env(offer(setup.bob, XRP(100), setup.usd(40))); - env.close(); - - auto const sle = env.le(keylet::offer(setup.bob.id(), bobOfferSeq)); - BEAST_EXPECT(sle); - - auto const dirKey = sle->getFieldH256(sfBookDirectory); - { - auto const dirSle = env.le(Keylet(ltDIR_NODE, dirKey)); - BEAST_EXPECT(dirSle); - auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); - auto const quality = getQuality(dirKey); - BEAST_EXPECT(exchangeRate == quality); - } - - env(ledgerStateFix::bookExchangeRate(setup.carol, dirKey), - Fee(fixFee), - Ter(tecNO_PERMISSION)); - } - } - - { - // Repair path: start without fixCleanup3_2_0 to produce the - // mismatch, then enable the amendment and fix it. - Env env(*this, features - fixCleanup3_2_0); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = - PermissionedDEX(env); - - // Bob places a hybrid offer. - env(offer(bob_, XRP(100), USD(40)), Txflags(tfHybrid), Domain(domainID)); - env.close(); - - // Alice partially crosses Bob. - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(100), XRP(300)), Txflags(tfHybrid), Domain(domainID)); - env.close(); - - auto const sle = env.le(keylet::offer(alice_.id(), aliceOfferSeq)); - BEAST_EXPECT(sle); - - auto const openDirKey = - sle->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); - - auto const preCrossingQuality = std::uint64_t{5623825668291712342ULL}; - auto const postCrossingQuality = std::uint64_t{5623825668291712341ULL}; - - // Confirm mismatch exists. - { - auto const dirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); - BEAST_EXPECT(dirSle); - auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); - auto const quality = getQuality(openDirKey); - BEAST_EXPECT(exchangeRate == preCrossingQuality); - BEAST_EXPECT(quality == postCrossingQuality); - BEAST_EXPECT(exchangeRate != quality); - } - - // Enable fixCleanup3_2_0 and apply the LedgerStateFix. - env.enableFeature(fixCleanup3_2_0); - env.close(); - - auto const fixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::bookExchangeRate(carol_, openDirKey), Fee(fixFee)); - env.close(); - - // Confirm sfExchangeRate now matches the key quality. - { - auto const dirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); - BEAST_EXPECT(dirSle); - auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); - auto const quality = getQuality(openDirKey); - BEAST_EXPECT(exchangeRate == postCrossingQuality); - BEAST_EXPECT(quality == postCrossingQuality); - BEAST_EXPECT(exchangeRate == quality); - } - - // Submitting again should fail — nothing to fix. - env(ledgerStateFix::bookExchangeRate(carol_, openDirKey), - Fee(fixFee), - Ter(tecNO_PERMISSION)); - } - } - - void - testCancelRegularOfferWithDomainCreate(FeatureBitset features) - { - bool const fixEnabled = features[fixCleanup3_2_0]; - - testcase << "Cancel regular offer via domain OfferCreate" - << (fixEnabled ? " (fixCleanup3_2_0 enabled)" : " (fixCleanup3_2_0 disabled)"); - - // An OfferCreate with sfDomainID and sfOfferSequence pointing to - // the user's own non-domain offer should atomically cancel the - // regular offer and place the new domain offer. - // - // Pre-fixCleanup3_2_0: ValidPermissionedDEX flagged the deleted - // regular offer, so the transaction failed with tecINVARIANT_FAILED. - // Post-fixCleanup3_2_0: the invariant ignores deletions and the - // transaction succeeds. - - Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); - - auto const regularSeq = env.seq(bob); - env(offer(bob, XRP(10), USD(10))); - env.close(); - BEAST_EXPECT(checkOffer(env, bob, regularSeq, XRP(10), USD(10), 0, false)); - - auto const domainSeq = env.seq(bob); - if (fixEnabled) - { - env(offer(bob, XRP(20), USD(20)), - Domain(domainID), - Json(jss::OfferSequence, regularSeq)); - env.close(); - BEAST_EXPECT(!offerExists(env, bob, regularSeq)); - BEAST_EXPECT(checkOffer(env, bob, domainSeq, XRP(20), USD(20), 0, true)); - } - else - { - env(offer(bob, XRP(20), USD(20)), - Domain(domainID), - Json(jss::OfferSequence, regularSeq), - Ter(tecINVARIANT_FAILED)); - env.close(); - BEAST_EXPECT(offerExists(env, bob, regularSeq)); - BEAST_EXPECT(!offerExists(env, bob, domainSeq)); - } - } - public: void run() override @@ -1804,9 +1464,7 @@ public: // Test domain offer (w/o hybrid) testOfferCreate(all); - testOfferCreate(all - fixCleanup3_2_0); testPayment(all); - testPayment(all - fixCleanup3_2_0); testBookStep(all); testRippling(all); testOfferTokenIssuerInDomain(all); @@ -1820,15 +1478,7 @@ public: testHybridInvalidOffer(all); testHybridOfferDirectories(all); testHybridMalformedOffer(all); - testHybridMalformedOffer(all - fixCleanup3_1_3); - testHybridOfferCrossingQuality(all); - testHybridOfferCrossingQuality(all - fixCleanup3_2_0); - testBookExchangeRateFix(all); - - // Cancelling a regular offer in a domain OfferCreate is allowed - // only after fixCleanup3_2_0. - testCancelRegularOfferWithDomainCreate(all); - testCancelRegularOfferWithDomainCreate(all - fixCleanup3_2_0); + testHybridMalformedOffer(all - fixSecurity3_1_3); } }; diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index 0857a4bdef..a49f913861 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -49,10 +49,14 @@ exceptionExpected(Env& env, json::Value const& jv) class PermissionedDomains_test : public beast::unit_test::Suite { + FeatureBitset withoutFeature_{testableAmendments() - featurePermissionedDomains}; FeatureBitset withFeature_{ - (testableAmendments() | featurePermissionedDomains | featureCredentials) - fixCleanup3_1_3}; + testableAmendments() // + | featurePermissionedDomains | featureCredentials}; + FeatureBitset withFix_{ - testableAmendments() | featurePermissionedDomains | featureCredentials | fixCleanup3_1_3}; + testableAmendments() // + | featurePermissionedDomains | featureCredentials}; // Verify that each tx type can execute if the feature is enabled. void @@ -94,7 +98,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite { testcase("Disabled"); Account const alice("alice"); - Env env(*this, testableAmendments() - featurePermissionedDomains); + Env env(*this, withoutFeature_); env.fund(XRP(1000), alice); pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials), Ter(temDISABLED)); @@ -135,7 +139,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite {alice10, "credential9"}, {alice11, "credential10"}, {alice12, "credential11"}}; - BEAST_EXPECT(credentials11.size() == kMaxPermissionedDomainCredentialsArraySize + 1); + BEAST_EXPECT(credentials11.size() == kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE + 1); env(pdomain::setTx(account, credentials11, domain), Ter(temARRAY_TOO_LARGE)); // Test credentials including non-existent issuer. @@ -172,12 +176,12 @@ class PermissionedDomains_test : public beast::unit_test::Suite env(txJsonMutable, Ter(temMALFORMED)); // Make too long CredentialType. - static constexpr std::string_view kLongCredentialType = + constexpr std::string_view kLONG_CREDENTIAL_TYPE = "Cred0123456789012345678901234567890123456789012345678901234567890"; - static_assert(kLongCredentialType.size() == kMaxCredentialTypeLength + 1); + static_assert(kLONG_CREDENTIAL_TYPE.size() == kMAX_CREDENTIAL_TYPE_LENGTH + 1); txJsonMutable["AcceptedCredentials"][2u] = credentialOrig; txJsonMutable["AcceptedCredentials"][2u][jss::Credential]["CredentialType"] = - std::string(kLongCredentialType); + std::string(kLONG_CREDENTIAL_TYPE); BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Remove Credentialtype from a credential and apply. @@ -294,7 +298,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite { env(pdomain::setTx(alice[0], credentials1)); BEAST_EXPECT(env.ownerCount(alice[0]) == 1); - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); BEAST_EXPECT(tx[jss::TransactionType] == "PermissionedDomainSet"); BEAST_EXPECT(tx["Account"] == alice[0].human()); auto objects = pdomain::getObjects(alice[0], env); @@ -309,19 +313,19 @@ class PermissionedDomains_test : public beast::unit_test::Suite // Make longest possible CredentialType. { - static constexpr std::string_view kLongCredentialType = + constexpr std::string_view kLONG_CREDENTIAL_TYPE = "Cred0123456789012345678901234567890123456789012345678901234567" "89"; - static_assert(kLongCredentialType.size() == kMaxCredentialTypeLength); + static_assert(kLONG_CREDENTIAL_TYPE.size() == kMAX_CREDENTIAL_TYPE_LENGTH); pdomain::Credentials const longCredentials{ - {alice[1], std::string(kLongCredentialType)}}; + {alice[1], std::string(kLONG_CREDENTIAL_TYPE)}}; env(pdomain::setTx(alice[0], longCredentials)); // One account can create multiple domains BEAST_EXPECT(env.ownerCount(alice[0]) == 2); - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); BEAST_EXPECT(tx[jss::TransactionType] == "PermissionedDomainSet"); BEAST_EXPECT(tx["Account"] == alice[0].human()); @@ -358,10 +362,10 @@ class PermissionedDomains_test : public beast::unit_test::Suite }; uint256 domain2; { - BEAST_EXPECT(credentials10.size() == kMaxPermissionedDomainCredentialsArraySize); + BEAST_EXPECT(credentials10.size() == kMAX_PERMISSIONED_DOMAIN_CREDENTIALS_ARRAY_SIZE); BEAST_EXPECT(credentials10 != pdomain::sortCredentials(credentials10)); env(pdomain::setTx(alice[0], credentials10)); - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); domain2 = pdomain::getNewDomain(env.meta()); auto objects = pdomain::getObjects(alice[0], env); auto object = objects[domain2]; @@ -402,11 +406,11 @@ class PermissionedDomains_test : public beast::unit_test::Suite // Try to delete the account with domains. auto const acctDelFee(drops(env.current()->fees().increment)); - static constexpr std::size_t kDeleteDelta = 255; + constexpr std::size_t kDELETE_DELTA = 255; { // Close enough ledgers to make it potentially deletable if empty. std::size_t const ownerSeq = env.seq(alice[0]); - while (kDeleteDelta + ownerSeq > env.current()->seq()) + while (kDELETE_DELTA + ownerSeq > env.current()->seq()) env.close(); env(acctdelete(alice[0], alice[2]), Fee(acctDelFee), Ter(tecHAS_OBLIGATIONS)); } @@ -417,7 +421,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite env(pdomain::deleteTx(alice[0], objs.first)); env.close(); std::size_t const ownerSeq = env.seq(alice[0]); - while (kDeleteDelta + ownerSeq > env.current()->seq()) + while (kDELETE_DELTA + ownerSeq > env.current()->seq()) env.close(); env(acctdelete(alice[0], alice[2]), Fee(acctDelFee)); } @@ -466,7 +470,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite // Delete domain that belongs to user. env(pdomain::deleteTx(alice, domain)); - auto const tx = env.tx()->getJson(JsonOptions::Values::None); + auto const tx = env.tx()->getJson(JsonOptions::KNone); BEAST_EXPECT(tx[jss::TransactionType] == "PermissionedDomainDelete"); // Make sure the owner count goes back to 0. diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index c3b0ddea9c..6b3ea8cdbe 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -69,9 +69,9 @@ class RCLValidations_test : public beast::unit_test::Suite jtx::Env env(*this); Config const config; auto prev = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); @@ -235,9 +235,9 @@ class RCLValidations_test : public beast::unit_test::Suite auto& j = env.journal; Config const config; auto prev = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index 47a2c1294c..4a2c2dba0a 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -560,8 +560,8 @@ public: 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 kAliceInitialOffer(usd(2), drops(3382562)); - env(offer(alice, kAliceInitialOffer.in, kAliceInitialOffer.out)); + static Amounts const kALICE_INITIAL_OFFER(usd(2), drops(3382562)); + env(offer(alice, kALICE_INITIAL_OFFER.in, kALICE_INITIAL_OFFER.out)); env.close(); STAmount const initialRate = Quality(jsonOfferToAmounts(ledgerEntryOffer( env, alice, aliceOfferSeq)[jss::node])) @@ -598,8 +598,8 @@ public: Amounts const aliceReducedOffer = jsonOfferToAmounts(aliceOffer[jss::node]); - BEAST_EXPECT(aliceReducedOffer.in < kAliceInitialOffer.in); - BEAST_EXPECT(aliceReducedOffer.out < kAliceInitialOffer.out); + BEAST_EXPECT(aliceReducedOffer.in < kALICE_INITIAL_OFFER.in); + BEAST_EXPECT(aliceReducedOffer.out < kALICE_INITIAL_OFFER.out); STAmount const inLedgerRate = Quality(aliceReducedOffer).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; @@ -641,12 +641,12 @@ public: return badRate; }; - static constexpr int kLoopCount = 100; + constexpr int kLOOP_COUNT = 100; unsigned int blockedCount = 0; { STAmount increaseGets = usd(0); STAmount const step(increaseGets.asset(), 1, -8); - for (unsigned int i = 0; i < kLoopCount; ++i) + for (unsigned int i = 0; i < kLOOP_COUNT; ++i) { blockedCount += exerciseOfferTrio(Amounts(drops(1642020), usd(1) + increaseGets)); diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 1c83e97e61..d7c92f1748 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -85,12 +85,12 @@ 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( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); - auto expectedDrops = kInitialXrp; + auto expectedDrops = kINITIAL_XRP; BEAST_EXPECT(closed->header().drops == expectedDrops); auto const aliceXRP = 400; @@ -138,7 +138,7 @@ struct Regression_test : public beast::unit_test::Suite BEAST_EXPECT(balance == XRP(0)); } - expectedDrops -= aliceXRP * kDropsPerXrp; + expectedDrops -= aliceXRP * kDROPS_PER_XRP; BEAST_EXPECT(next->header().drops == expectedDrops); } @@ -194,7 +194,7 @@ struct Regression_test : public beast::unit_test::Suite using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })); EnvSs envs(env); @@ -202,7 +202,7 @@ struct Regression_test : public beast::unit_test::Suite auto const alice = Account("alice"); env.fund(XRP(100000), alice); - auto params = json::Value(json::ValueType::Object); + auto params = json::Value(json::ObjectValue); // Max fee = 50k drops params[jss::fee_mult_max] = 5000; std::vector const expectedFees({10, 10, 8889, 13889, 20000}); @@ -211,7 +211,7 @@ struct Regression_test : public beast::unit_test::Suite // our fee limit. for (int i = 0; i < 5; ++i) { - envs(noop(alice), Fee(kNone), Seq(kNone))(params); + envs(noop(alice), Fee(kNONE), Seq(kNONE))(params); auto tx = env.tx(); if (BEAST_EXPECT(tx)) @@ -299,7 +299,7 @@ struct Regression_test : public beast::unit_test::Suite SHAMapHash digest; if (!state.peekItem(bobIndex, digest)) return std::nullopt; - return digest.asUInt256(); + return digest.asUint256(); }(); auto const mapCounts = [&](CountedObjects::List const& list) { diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index 6e279eadb2..574874e005 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -36,14 +36,14 @@ namespace xrpl::test { class SHAMapStore_test : public beast::unit_test::Suite { - static auto const kDeleteInterval = 8; + static auto const kDELETE_INTERVAL = 8; static auto onlineDelete(std::unique_ptr cfg) { - cfg->ledgerHistory = kDeleteInterval; + cfg->LEDGER_HISTORY = kDELETE_INTERVAL; auto& section = cfg->section(ConfigSection::nodeDatabase()); - section.set("online_delete", std::to_string(kDeleteInterval)); + section.set("online_delete", std::to_string(kDELETE_INTERVAL)); return cfg; } @@ -196,7 +196,7 @@ public: auto const firstSeq = waitForReady(env); auto lastRotated = firstSeq - 1; - for (auto i = firstSeq + 1; i < kDeleteInterval + firstSeq; ++i) + for (auto i = firstSeq + 1; i < kDELETE_INTERVAL + firstSeq; ++i) { env.fund(XRP(10000), noripple("test" + std::to_string(i))); env.close(); @@ -206,7 +206,7 @@ public: } BEAST_EXPECT(store.getLastRotated() == lastRotated); - for (auto i = 3; i < kDeleteInterval + lastRotated; ++i) + for (auto i = 3; i < kDELETE_INTERVAL + lastRotated; ++i) { ledgers.emplace(i, env.rpc("ledger", std::to_string(i))); BEAST_EXPECT( @@ -214,31 +214,31 @@ public: !getHash(ledgers[i]).empty()); } - ledgerCheck(env, kDeleteInterval + 1, 2); - transactionCheck(env, kDeleteInterval); - accountTransactionCheck(env, 2 * kDeleteInterval); + ledgerCheck(env, kDELETE_INTERVAL + 1, 2); + transactionCheck(env, kDELETE_INTERVAL); + accountTransactionCheck(env, 2 * kDELETE_INTERVAL); { // Closing one more ledger triggers a rotate env.close(); auto ledger = env.rpc("ledger", "current"); - BEAST_EXPECT(goodLedger(env, ledger, std::to_string(kDeleteInterval + 4))); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(kDELETE_INTERVAL + 4))); } store.rendezvous(); - BEAST_EXPECT(store.getLastRotated() == kDeleteInterval + 3); + BEAST_EXPECT(store.getLastRotated() == kDELETE_INTERVAL + 3); lastRotated = store.getLastRotated(); BEAST_EXPECT(lastRotated == 11); // That took care of the fake hashes - ledgerCheck(env, kDeleteInterval + 1, 3); - transactionCheck(env, kDeleteInterval); - accountTransactionCheck(env, 2 * kDeleteInterval); + ledgerCheck(env, kDELETE_INTERVAL + 1, 3); + transactionCheck(env, kDELETE_INTERVAL); + accountTransactionCheck(env, 2 * kDELETE_INTERVAL); // The last iteration of this loop should trigger a rotate - for (auto i = lastRotated - 1; i < lastRotated + kDeleteInterval - 1; ++i) + for (auto i = lastRotated - 1; i < lastRotated + kDELETE_INTERVAL - 1; ++i) { env.close(); @@ -247,7 +247,7 @@ public: ledgers.emplace(i, env.rpc("ledger", std::to_string(i))); BEAST_EXPECT( - store.getLastRotated() == lastRotated || i == lastRotated + kDeleteInterval - 2); + store.getLastRotated() == lastRotated || i == lastRotated + kDELETE_INTERVAL - 2); BEAST_EXPECT( goodLedger(env, ledgers[i], std::to_string(i), true) && !getHash(ledgers[i]).empty()); @@ -255,9 +255,9 @@ public: store.rendezvous(); - BEAST_EXPECT(store.getLastRotated() == kDeleteInterval + lastRotated); + BEAST_EXPECT(store.getLastRotated() == kDELETE_INTERVAL + lastRotated); - ledgerCheck(env, kDeleteInterval + 1, lastRotated); + ledgerCheck(env, kDELETE_INTERVAL + 1, lastRotated); transactionCheck(env, 0); accountTransactionCheck(env, 0); } @@ -283,7 +283,7 @@ public: BEAST_EXPECT(bad(canDelete, RpcNotEnabled)); // Close ledgers without triggering a rotate - for (; ledgerSeq < lastRotated + kDeleteInterval; ++ledgerSeq) + for (; ledgerSeq < lastRotated + kDELETE_INTERVAL; ++ledgerSeq) { env.close(); @@ -314,7 +314,7 @@ public: lastRotated = store.getLastRotated(); // Close enough ledgers to trigger another rotate - for (; ledgerSeq < lastRotated + kDeleteInterval + 1; ++ledgerSeq) + for (; ledgerSeq < lastRotated + kDELETE_INTERVAL + 1; ++ledgerSeq) { env.close(); @@ -324,7 +324,7 @@ public: store.rendezvous(); - ledgerCheck(env, kDeleteInterval + 1, lastRotated); + ledgerCheck(env, kDELETE_INTERVAL + 1, lastRotated); BEAST_EXPECT(lastRotated != store.getLastRotated()); } @@ -352,7 +352,7 @@ public: BEAST_EXPECT(!RPC::containsError(canDelete[jss::result])); BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == 0); - auto const firstBatch = kDeleteInterval + ledgerSeq; + auto const firstBatch = kDELETE_INTERVAL + ledgerSeq; for (; ledgerSeq < firstBatch; ++ledgerSeq) { env.close(); @@ -367,9 +367,9 @@ public: BEAST_EXPECT(lastRotated == store.getLastRotated()); // This does not kick off a cleanup - canDelete = env.rpc("can_delete", std::to_string(ledgerSeq + (kDeleteInterval / 2))); + canDelete = env.rpc("can_delete", std::to_string(ledgerSeq + (kDELETE_INTERVAL / 2))); BEAST_EXPECT(!RPC::containsError(canDelete[jss::result])); - BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq + (kDeleteInterval / 2)); + BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq + (kDELETE_INTERVAL / 2)); store.rendezvous(); @@ -391,7 +391,7 @@ public: BEAST_EXPECT(store.getLastRotated() == ledgerSeq - 1); lastRotated = ledgerSeq - 1; - for (; ledgerSeq < lastRotated + kDeleteInterval; ++ledgerSeq) + for (; ledgerSeq < lastRotated + kDELETE_INTERVAL; ++ledgerSeq) { // No cleanups in this loop. env.close(); @@ -425,7 +425,7 @@ public: BEAST_EXPECT( canDelete[jss::result][jss::can_delete] == std::numeric_limits::max()); - for (; ledgerSeq < lastRotated + kDeleteInterval; ++ledgerSeq) + for (; ledgerSeq < lastRotated + kDELETE_INTERVAL; ++ledgerSeq) { // No cleanups in this loop. env.close(); @@ -458,7 +458,7 @@ public: BEAST_EXPECT(!RPC::containsError(canDelete[jss::result])); BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq - 1); - for (; ledgerSeq < lastRotated + kDeleteInterval; ++ledgerSeq) + for (; ledgerSeq < lastRotated + kDELETE_INTERVAL; ++ledgerSeq) { // No cleanups in this loop. env.close(); @@ -520,25 +520,6 @@ public: ///////////////////////////////////////////////////////////// // Create NodeStore with two backends to allow online deletion of data. // Normally, SHAMapStoreImp handles all these details. - auto nscfg = env.app().config().section(ConfigSection::nodeDatabase()); - - // 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))); - } - NodeStoreScheduler scheduler(env.app().getJobQueue()); std::string const writableDb = "write"; @@ -546,10 +527,11 @@ public: auto writableBackend = makeBackendRotating(env, scheduler, writableDb); auto archiveBackend = makeBackendRotating(env, scheduler, archiveDb); - static constexpr int kReadThreads = 4; + constexpr int kREAD_THREADS = 4; + auto nscfg = env.app().config().section(ConfigSection::nodeDatabase()); auto dbr = std::make_unique( scheduler, - kReadThreads, + kREAD_THREADS, std::move(writableBackend), std::move(archiveBackend), nscfg, diff --git a/src/test/app/SetAuth_test.cpp b/src/test/app/SetAuth_test.cpp index df0c6fe5d0..f2e6aa29cc 100644 --- a/src/test/app/SetAuth_test.cpp +++ b/src/test/app/SetAuth_test.cpp @@ -32,7 +32,7 @@ struct SetAuth_test : public beast::unit_test::Suite json::Value jv; jv[jss::Account] = account.human(); jv[jss::LimitAmount] = - STAmount(Issue{toCurrency(currency), dest}).getJson(JsonOptions::Values::None); + STAmount(Issue{toCurrency(currency), dest}).getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::TrustSet; jv[jss::Flags] = tfSetfAuth; return jv; diff --git a/src/test/app/SetRegularKey_test.cpp b/src/test/app/SetRegularKey_test.cpp index b5d1af9ef0..00b1fe3f84 100644 --- a/src/test/app/SetRegularKey_test.cpp +++ b/src/test/app/SetRegularKey_test.cpp @@ -54,7 +54,7 @@ public: env(noop(alice), Sig(alice)); testcase("Revoke regular key"); - env(regkey(alice, kDisabled)); + env(regkey(alice, kDISABLED)); env(noop(alice), Sig(bob), Ter(tefBAD_AUTH)); env(noop(alice), Sig(alice)); } @@ -84,12 +84,15 @@ public: env.fund(XRP(10000), alice, bob); auto ar = env.le(alice); - BEAST_EXPECT(ar->isFieldPresent(sfFlags) && !ar->isFlag(lsfPasswordSpent)); + 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->isFlag(lsfPasswordSpent)); + BEAST_EXPECT( + 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)); @@ -97,7 +100,8 @@ public: env.trust(bob["USD"](1), alice); env(pay(bob, alice, bob["USD"](1))); ar = env.le(alice); - BEAST_EXPECT(ar->isFieldPresent(sfFlags) && !ar->isFlag(lsfPasswordSpent)); + BEAST_EXPECT( + ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); } void @@ -154,7 +158,7 @@ public: env.close(); // Disable the regular key using a ticket. - env(regkey(alice, kDisabled), Sig(alie), ticket::Use(--ticketSeq)); + env(regkey(alice, kDISABLED), Sig(alie), ticket::Use(--ticketSeq)); env.close(); // alice should be able to sign using the master key but not the diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index 8f7d844019..ed6f91f475 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -125,9 +125,9 @@ class RandomAccountParams std::uint32_t const initialBalance_; // probability of changing a value from its default - static constexpr double kProbChangeDefault = 0.75; + constexpr static double kPROB_CHANGE_DEFAULT = 0.75; // probability that an account redeems into another account - static constexpr double kProbRedeem = 0.5; + constexpr static double kPROB_REDEEM = 0.5; std::uniform_real_distribution<> zeroOneDist_{0.0, 1.0}; std::uniform_real_distribution<> transferRateDist_{1.0, 2.0}; std::uniform_real_distribution<> qualityPercentDist_{80, 120}; @@ -135,7 +135,7 @@ class RandomAccountParams bool shouldSet() { - return zeroOneDist_(engine_) <= kProbChangeDefault; + return zeroOneDist_(engine_) <= kPROB_CHANGE_DEFAULT; }; void @@ -206,7 +206,7 @@ public: Currency const& currency) { using namespace jtx; - if (zeroOneDist_(engine_) > kProbRedeem) + if (zeroOneDist_(engine_) > kPROB_REDEEM) return; setInitialBalance(env, acc, peer, currency); } @@ -290,8 +290,8 @@ class TheoreticalQuality_test : public beast::unit_test::Suite auto compareClose = [](Quality const& q1, Quality const& q2) { // relative diff is fabs(a-b)/min(a,b) // can't get access to internal value. Use the rate - static constexpr double kTolerance = 0.0000001; - return relativeDistance(q1, q2) <= kTolerance; + constexpr double kTOLERANCE = 0.0000001; + return relativeDistance(q1, q2) <= kTOLERANCE; }; for (auto const& strand : sr.second) @@ -339,7 +339,7 @@ public: auto const currency = toCurrency("USD"); - static constexpr std::size_t kNumAccounts = 4; + constexpr std::size_t const kNUM_ACCOUNTS = 4; // There are three relevant trust lines: `alice->bob`, `bob->carol`, and // `carol->dan`. There are four accounts. If we count the number of @@ -355,7 +355,7 @@ public: // randomly sample the test space. int const numTestIterations = reqNumIterations.value_or(250); - static constexpr std::uint32_t kPaymentAmount = 1; + constexpr std::uint32_t kPAYMENT_AMOUNT = 1; // Class to randomly set account transfer rates, qualities, and other // params. @@ -373,15 +373,15 @@ public: auto const bob = Account("bob" + iterAsStr); auto const carol = Account("carol" + iterAsStr); auto const dan = Account("dan" + iterAsStr); - std::array accounts{{alice, bob, carol, dan}}; - static_assert(kNumAccounts == 4, "Path is only correct for four accounts"); + std::array accounts{{alice, bob, carol, dan}}; + static_assert(kNUM_ACCOUNTS == 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(); // iterate through all pairs of accounts, randomly set the transfer // rate, qIn, qOut, and if the account issues or redeems - for (std::size_t ii = 0; ii < kNumAccounts; ++ii) + for (std::size_t ii = 0; ii < kNUM_ACCOUNTS; ++ii) { rndAccParams.maybeSetTransferRate(env, accounts[ii]); // The payment is from: @@ -389,7 +389,7 @@ public: // set the trust lines and initial balances for each pair of // neighboring accounts std::size_t const j = ii + 1; - if (j == kNumAccounts) + if (j == kNUM_ACCOUNTS) continue; rndAccParams.setupTrustLines(env, accounts[ii], accounts[j], currency); @@ -399,7 +399,7 @@ public: // Accounts are set up, make the payment IOU const iou{accounts.back(), currency}; RippleCalcTestParams const rcp{env.json( - pay(accounts.front(), accounts.back(), iou(kPaymentAmount)), + pay(accounts.front(), accounts.back(), iou(kPAYMENT_AMOUNT)), accountsPath, Txflags(tfNoRippleDirect))}; @@ -422,7 +422,7 @@ public: int const numTestIterations = reqNumIterations.value_or(100); - static constexpr std::uint32_t kPaymentAmount = 1; + constexpr std::uint32_t kPAYMENT_AMOUNT = 1; Currency const eurCurrency = toCurrency("EUR"); Currency const usdCurrency = toCurrency("USD"); @@ -444,8 +444,8 @@ public: auto const oscar = Account("oscar" + iterAsStr); // offer owner auto const usdb = bob["USD"]; auto const eurc = carol["EUR"]; - static constexpr std::size_t kNumAccounts = 5; - std::array const accounts{{alice, bob, carol, dan, oscar}}; + constexpr std::size_t const kNUM_ACCOUNTS = 5; + std::array const accounts{{alice, bob, carol, dan, oscar}}; // sendmax should be in USDB and delivered amount should be in EURC // normalized path should be: @@ -478,8 +478,8 @@ public: IOU const srcIOU{bob, usdCurrency}; IOU const dstIOU{carol, eurCurrency}; RippleCalcTestParams const rcp{env.json( - pay(alice, dan, dstIOU(kPaymentAmount)), - Sendmax(srcIOU(100 * kPaymentAmount)), + pay(alice, dan, dstIOU(kPAYMENT_AMOUNT)), + Sendmax(srcIOU(100 * kPAYMENT_AMOUNT)), bookPath, Txflags(tfNoRippleDirect))}; diff --git a/src/test/app/Ticket_test.cpp b/src/test/app/Ticket_test.cpp index 626cdbe44d..d266ec12d2 100644 --- a/src/test/app/Ticket_test.cpp +++ b/src/test/app/Ticket_test.cpp @@ -55,7 +55,7 @@ class Ticket_test : public beast::unit_test::Suite { using namespace std::string_literals; - json::Value const& tx{env.tx()->getJson(JsonOptions::Values::None)}; + json::Value const& tx{env.tx()->getJson(JsonOptions::KNone)}; { std::string const txType = tx[sfTransactionType.jsonName].asString(); @@ -71,7 +71,7 @@ class Ticket_test : public beast::unit_test::Suite std::uint32_t const txSeq = {tx[sfSequence.jsonName].asUInt()}; std::string const account = tx[sfAccount.jsonName].asString(); - json::Value const& metadata = env.meta()->getJson(JsonOptions::Values::None); + json::Value const& metadata = env.meta()->getJson(JsonOptions::KNone); if (!BEAST_EXPECTS( metadata.isMember(sfTransactionResult.jsonName) && metadata[sfTransactionResult.jsonName].asString() == "tesSUCCESS", @@ -241,7 +241,7 @@ class Ticket_test : public beast::unit_test::Suite void checkTicketConsumeMeta(test::jtx::Env& env) { - json::Value const& tx{env.tx()->getJson(JsonOptions::Values::None)}; + json::Value const& tx{env.tx()->getJson(JsonOptions::KNone)}; // Verify that the transaction includes a TicketSequence. @@ -274,7 +274,7 @@ class Ticket_test : public beast::unit_test::Suite std::uint32_t const ticketSeq{tx[sfTicketSequence.jsonName].asUInt()}; - json::Value const& metadata{env.meta()->getJson(JsonOptions::Values::None)}; + json::Value const& metadata{env.meta()->getJson(JsonOptions::KNone)}; if (!BEAST_EXPECTS( metadata.isMember(sfTransactionResult.jsonName), "Metadata is missing TransactionResult.")) @@ -673,12 +673,12 @@ class Ticket_test : public beast::unit_test::Suite // Successfully create several tickets (using a sequence). std::uint32_t ticketSeq{env.seq(alice)}; - static constexpr std::uint32_t kTicketCount{10}; - env(ticket::create(alice, kTicketCount)); + static constexpr std::uint32_t kTICKET_COUNT{10}; + env(ticket::create(alice, kTICKET_COUNT)); uint256 const txHash1{getTxID()}; // Just for grins use the tickets in reverse from largest to smallest. - ticketSeq += kTicketCount; + ticketSeq += kTICKET_COUNT; env(noop(alice), ticket::Use(--ticketSeq)); uint256 const txHash2{getTxID()}; @@ -757,7 +757,7 @@ class Ticket_test : public beast::unit_test::Suite testSignWithTicketSequence() { // The sign and the submit RPC commands automatically fill in the - // Sequence field of a transaction if kNone is provided. If a + // Sequence field of a transaction if kNONE is provided. If a // TicketSequence is provided in the transaction, then the // auto-filled Sequence should be zero. testcase("Sign with TicketSequence"); @@ -779,11 +779,11 @@ class Ticket_test : public beast::unit_test::Suite { // Test that the "sign" RPC command fills in a "Sequence": 0 field - // if kNone is provided. + // if kNONE is provided. // Create a noop transaction using a TicketSequence but don't fill // in the Sequence field. - json::Value tx = json::ValueType::Object; + json::Value tx = json::ObjectValue; tx[jss::tx_json] = noop(alice); tx[jss::tx_json][sfTicketSequence.jsonName] = ticketSeq; tx[jss::secret] = toBase58(generateSeed("alice")); @@ -812,11 +812,11 @@ class Ticket_test : public beast::unit_test::Suite } { // Test that the "submit" RPC command fills in a "Sequence": 0 - // field if kNone is provided. + // field if kNONE is provided. // Create a noop transaction using a TicketSequence but don't fill // in the Sequence field. - json::Value tx = json::ValueType::Object; + json::Value tx = json::ObjectValue; tx[jss::tx_json] = noop(alice); tx[jss::tx_json][sfTicketSequence.jsonName] = ticketSeq + 1; tx[jss::secret] = toBase58(generateSeed("alice")); diff --git a/src/test/app/Transaction_ordering_test.cpp b/src/test/app/Transaction_ordering_test.cpp index 7c0721cde3..50340497a4 100644 --- a/src/test/app/Transaction_ordering_test.cpp +++ b/src/test/app/Transaction_ordering_test.cpp @@ -64,7 +64,7 @@ struct Transaction_ordering_test : public beast::unit_test::Suite testcase("Incorrect order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->forceMultiThread = false; + cfg->FORCE_MULTI_THREAD = false; return cfg; })); @@ -102,7 +102,7 @@ struct Transaction_ordering_test : public beast::unit_test::Suite testcase("Incorrect order multiple intermediaries"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->forceMultiThread = true; + cfg->FORCE_MULTI_THREAD = true; return cfg; })); @@ -110,16 +110,16 @@ struct Transaction_ordering_test : public beast::unit_test::Suite env.fund(XRP(1000), noripple(alice)); auto const aliceSequence = env.seq(alice); - static constexpr auto kSize = 5; + static constexpr auto kSIZE = 5; std::vector tx; - tx.reserve(kSize); - for (auto i = 0; i < kSize; ++i) + tx.reserve(kSIZE); + for (auto i = 0; i < kSIZE; ++i) { tx.emplace_back(env.jt(noop(alice), Seq(aliceSequence + i), LastLedgerSeq(7))); } - for (auto i = 1; i < kSize; ++i) + for (auto i = 1; i < kSIZE; ++i) { env(tx[i], Ter(terPRE_SEQ)); BEAST_EXPECT(env.seq(alice) == aliceSequence); @@ -127,11 +127,11 @@ struct Transaction_ordering_test : public beast::unit_test::Suite env(tx[0]); env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(env.seq(alice) == aliceSequence + kSize); + BEAST_EXPECT(env.seq(alice) == aliceSequence + kSIZE); env.close(); - for (auto i = 0; i < kSize; ++i) + for (auto i = 0; i < kSIZE; ++i) { 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 78670bf6fb..fe3d442f73 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -215,9 +215,9 @@ class TrustAndBalance_test : public beast::unit_test::Suite if (subscribe) { json::Value jvs; - jvs[jss::accounts] = json::ValueType::Array; + jvs[jss::accounts] = json::ArrayValue; jvs[jss::accounts].append(gw.human()); - jvs[jss::streams] = json::ValueType::Array; + jvs[jss::streams] = json::ArrayValue; jvs[jss::streams].append("transactions"); jvs[jss::streams].append("ledger"); auto jv = wsc->invoke("subscribe", jvs); @@ -400,9 +400,9 @@ class TrustAndBalance_test : public beast::unit_test::Suite env.close(); json::Value jvs; - jvs[jss::accounts] = json::ValueType::Array; + jvs[jss::accounts] = json::ArrayValue; jvs[jss::accounts].append(env.master.human()); - jvs[jss::streams] = json::ValueType::Array; + jvs[jss::streams] = json::ArrayValue; jvs[jss::streams].append("transactions"); BEAST_EXPECT(wsc->invoke("subscribe", jvs)[jss::status] == "success"); diff --git a/src/test/app/TrustSet_test.cpp b/src/test/app/TrustSet_test.cpp index e9f0553840..31b7e97ee7 100644 --- a/src/test/app/TrustSet_test.cpp +++ b/src/test/app/TrustSet_test.cpp @@ -284,7 +284,7 @@ public: { json::Value jv; jv[jss::Account] = a.human(); - jv[jss::LimitAmount] = amt.getJson(JsonOptions::Values::None); + jv[jss::LimitAmount] = amt.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::TrustSet; jv[jss::Flags] = 0; return jv; diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 8333fce3b3..52781ee9e3 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -60,8 +60,8 @@ namespace xrpl::test { class TxQPosNegFlows_test : public beast::unit_test::Suite { // Same as corresponding values from TxQ.h - static constexpr FeeLevel64 kBaseFeeLevel{256}; - static constexpr FeeLevel64 kMinEscalationFeeLevel = kBaseFeeLevel * 500; + static constexpr FeeLevel64 kBASE_FEE_LEVEL{256}; + static constexpr FeeLevel64 kMIN_ESCALATION_FEE_LEVEL = kBASE_FEE_LEVEL * 500; static void fillQueue(jtx::Env& env, jtx::Account const& account) @@ -109,7 +109,7 @@ class TxQPosNegFlows_test : public beast::unit_test::Suite { FeeLevel64 const expectedMedFeeLevel = (feeLevel1 + feeLevel2 + FeeLevel64{1}) / 2; - return std::max(expectedMedFeeLevel, kMinEscalationFeeLevel).fee(); + return std::max(expectedMedFeeLevel, kMIN_ESCALATION_FEE_LEVEL).fee(); } static auto @@ -276,8 +276,8 @@ public: ////////////////////////////////////////////////////////////// - static constexpr auto kLargeFeeMultiplier = 700; - auto const largeFee = baseFee * kLargeFeeMultiplier; + constexpr auto kLARGE_FEE_MULTIPLIER = 700; + auto const largeFee = baseFee * kLARGE_FEE_MULTIPLIER; // Stuff the ledger and queue so we can verify that // stuff gets kicked out. @@ -319,7 +319,7 @@ public: // is put back in. Neat. env.close(); // clang-format off - checkMetrics(*this, env, 2, 8, 5, 4, kBaseFeeLevel.fee(), calcMedFeeLevel(FeeLevel64{kBaseFeeLevel.fee() * kLargeFeeMultiplier})); + checkMetrics(*this, env, 2, 8, 5, 4, kBASE_FEE_LEVEL.fee(), calcMedFeeLevel(FeeLevel64{kBASE_FEE_LEVEL.fee() * kLARGE_FEE_MULTIPLIER})); // clang-format on env.close(); @@ -742,8 +742,8 @@ public: // Queue an item with a sufficient LastLedgerSeq. env(noop(alice), LastLedgerSeq(8), queued); - static constexpr auto kLargeFeeMultiplier = 700; - auto const largeFee = baseFee * kLargeFeeMultiplier; + constexpr auto kLARGE_FEE_MULTIPLIER = 700; + auto const largeFee = baseFee * kLARGE_FEE_MULTIPLIER; // Queue items with higher fees to force the previous // txn to wait. @@ -756,7 +756,7 @@ public: auto& txQ = env.app().getTxQ(); auto aliceStat = txQ.getAccountTxs(alice.id()); BEAST_EXPECT(aliceStat.size() == 1); - BEAST_EXPECT(aliceStat.begin()->feeLevel == kBaseFeeLevel); + BEAST_EXPECT(aliceStat.begin()->feeLevel == kBASE_FEE_LEVEL); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(aliceStat.begin()->lastValid && *aliceStat.begin()->lastValid == 8); BEAST_EXPECT(!aliceStat.begin()->consequences.isBlocker()); @@ -764,11 +764,12 @@ public: auto bobStat = txQ.getAccountTxs(bob.id()); BEAST_EXPECT(bobStat.size() == 1); BEAST_EXPECT( - bobStat.begin()->feeLevel == FeeLevel64{kBaseFeeLevel.fee() * kLargeFeeMultiplier}); + bobStat.begin()->feeLevel == + FeeLevel64{kBASE_FEE_LEVEL.fee() * kLARGE_FEE_MULTIPLIER}); BEAST_EXPECT(!bobStat.begin()->lastValid); BEAST_EXPECT(!bobStat.begin()->consequences.isBlocker()); - auto noStat = txQ.getAccountTxs(Account::kMaster.id()); + auto noStat = txQ.getAccountTxs(Account::kMASTER.id()); BEAST_EXPECT(noStat.empty()); } @@ -786,12 +787,12 @@ public: env.close(); // alice's transaction is still hanging around // clang-format off - checkMetrics(*this, env, 1, 8, 5, 4, kBaseFeeLevel.fee(), kBaseFeeLevel.fee() * kLargeFeeMultiplier); + checkMetrics(*this, env, 1, 8, 5, 4, kBASE_FEE_LEVEL.fee(), kBASE_FEE_LEVEL.fee() * kLARGE_FEE_MULTIPLIER); // clang-format on BEAST_EXPECT(env.seq(alice) == 3); - static constexpr auto kAnotherLargeFeeMultiplier = 800; - auto const anotherLargeFee = baseFee * kAnotherLargeFeeMultiplier; + constexpr auto kANOTHER_LARGE_FEE_MULTIPLIER = 800; + auto const anotherLargeFee = baseFee * kANOTHER_LARGE_FEE_MULTIPLIER; // Keep alice's transaction waiting. // clang-format off env(noop(bob), Fee(anotherLargeFee), queued); @@ -801,7 +802,7 @@ public: env(noop(edgar), Fee(anotherLargeFee), queued); env(noop(felicia), Fee(anotherLargeFee - 1), queued); env(noop(felicia), Fee(anotherLargeFee - 1), Seq(env.seq(felicia) + 1), queued); - checkMetrics(*this, env, 8, 8, 5, 4, kBaseFeeLevel.fee() + 1, kBaseFeeLevel.fee() * kLargeFeeMultiplier); + checkMetrics(*this, env, 8, 8, 5, 4, kBASE_FEE_LEVEL.fee() + 1, kBASE_FEE_LEVEL.fee() * kLARGE_FEE_MULTIPLIER); // clang-format on env.close(); @@ -809,7 +810,7 @@ public: // into the ledger, so her transaction is gone, // though one of felicia's is still in the queue. // clang-format off - checkMetrics(*this, env, 1, 10, 6, 5, kBaseFeeLevel.fee(), kBaseFeeLevel.fee() * kLargeFeeMultiplier); + checkMetrics(*this, env, 1, 10, 6, 5, kBASE_FEE_LEVEL.fee(), kBASE_FEE_LEVEL.fee() * kLARGE_FEE_MULTIPLIER); // clang-format on BEAST_EXPECT(env.seq(alice) == 3); BEAST_EXPECT(env.seq(felicia) == 7); @@ -817,7 +818,7 @@ public: env.close(); // And now the queue is empty // clang-format off - checkMetrics(*this, env, 0, 12, 1, 6, kBaseFeeLevel.fee(), kBaseFeeLevel.fee() * kAnotherLargeFeeMultiplier); + checkMetrics(*this, env, 0, 12, 1, 6, kBASE_FEE_LEVEL.fee(), kBASE_FEE_LEVEL.fee() * kANOTHER_LARGE_FEE_MULTIPLIER); // clang-format on BEAST_EXPECT(env.seq(alice) == 3); BEAST_EXPECT(env.seq(felicia) == 8); @@ -867,8 +868,8 @@ public: fillQueue(env, alice); checkMetrics(*this, env, 0, 6, 4, 3); - static constexpr auto kAliceFeeMultiplier = 3; - auto feeAlice = baseFee * kAliceFeeMultiplier; + constexpr auto kALICE_FEE_MULTIPLIER = 3; + auto feeAlice = baseFee * kALICE_FEE_MULTIPLIER; auto seqAlice = env.seq(alice); for (int i = 0; i < 4; ++i) { @@ -893,7 +894,7 @@ public: ++seqCarol; } // clang-format off - checkMetrics(*this, env, 6, 6, 4, 3, (kBaseFeeLevel.fee() * kAliceFeeMultiplier) + 1); + checkMetrics(*this, env, 6, 6, 4, 3, (kBASE_FEE_LEVEL.fee() * kALICE_FEE_MULTIPLIER) + 1); // clang-format on // Carol submits high enough to beat Bob's average fee which kicks @@ -1022,21 +1023,16 @@ public: checkMetrics(*this, env, 0, std::nullopt, 0, 3); // ledgers in queue is 2 because of makeConfig - initFee(env, 3, 2, 10, 200, 50); - // Close an empty ledger to shrink queue from the flag-ledger - // size to 2*3=6, independent of amendment count. - env.close(); - static constexpr std::size_t kInitQueueMax = 6; - checkMetrics(*this, env, 0, kInitQueueMax, 0, 3); + auto const initQueueMax = initFee(env, 3, 2, 10, 200, 50); // Create several accounts while the fee is cheap so they all apply. env.fund(drops(2000), noripple(alice)); env.fund(XRP(500000), noripple(bob, charlie, daria)); - checkMetrics(*this, env, 0, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 0, initQueueMax, 4, 3); // Alice - price starts exploding: held env(noop(alice), Fee(11), queued); - checkMetrics(*this, env, 1, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 1, initQueueMax, 4, 3); auto aliceSeq = env.seq(alice); auto bobSeq = env.seq(bob); @@ -1044,28 +1040,28 @@ public: // Alice - try to queue a second transaction, but leave a gap env(noop(alice), Seq(aliceSeq + 2), Fee(100), Ter(telCAN_NOT_QUEUE)); - checkMetrics(*this, env, 1, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 1, initQueueMax, 4, 3); // Alice - queue a second transaction. Yay! env(noop(alice), Seq(aliceSeq + 1), Fee(13), queued); - checkMetrics(*this, env, 2, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 2, initQueueMax, 4, 3); // Alice - queue a third transaction. Yay. env(noop(alice), Seq(aliceSeq + 2), Fee(17), queued); - checkMetrics(*this, env, 3, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 3, initQueueMax, 4, 3); // Bob - queue a transaction env(noop(bob), queued); - checkMetrics(*this, env, 4, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 4, initQueueMax, 4, 3); // Bob - queue a second transaction env(noop(bob), Seq(bobSeq + 1), Fee(50), queued); - checkMetrics(*this, env, 5, kInitQueueMax, 4, 3); + checkMetrics(*this, env, 5, initQueueMax, 4, 3); // Charlie - queue a transaction, with a higher fee // than default env(noop(charlie), Fee(15), queued); - checkMetrics(*this, env, 6, kInitQueueMax, 4, 3, 257); + checkMetrics(*this, env, 6, initQueueMax, 4, 3, 257); BEAST_EXPECT(env.seq(alice) == aliceSeq); BEAST_EXPECT(env.seq(bob) == bobSeq); @@ -1259,7 +1255,7 @@ public: testcase("tie breaking"); auto cfg = makeConfig({{"minimum_txn_in_ledger_standalone", "4"}}); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); auto alice = Account("alice"); @@ -1535,7 +1531,7 @@ public: { double const feeMultiplier = static_cast(cost.drops()) / baseFee; medFeeLevel = - FeeLevel64{static_cast(feeMultiplier * kBaseFeeLevel.fee())}; + FeeLevel64{static_cast(feeMultiplier * kBASE_FEE_LEVEL.fee())}; } env(noop(alice), Fee(cost)); @@ -1546,7 +1542,7 @@ public: env.close(); // If not for the maximum, the per ledger would be 11. // clang-format off - checkMetrics(*this, env, 0, 10, 0, 5, kBaseFeeLevel.fee(), calcMedFeeLevel(medFeeLevel)); + checkMetrics(*this, env, 0, 10, 0, 5, kBASE_FEE_LEVEL.fee(), calcMedFeeLevel(medFeeLevel)); // clang-format on } @@ -2653,7 +2649,7 @@ public: {{"minimum_txn_in_ledger_standalone", "1"}, {"ledgers_in_queue", "10"}, {"maximum_txn_per_account", "11"}}); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); auto const baseFee = env.current()->fees().base.drops(); @@ -2793,7 +2789,7 @@ public: auto const aliceSeq = env.seq(alice); auto const lastLedgerSeq = env.current()->header().seq + 2; - auto submitParams = json::Value(json::ValueType::Object); + auto submitParams = json::Value(json::ObjectValue); for (int i = 0; i < 5; ++i) { if (i == 2) @@ -2801,13 +2797,13 @@ public: envs( noop(alice), Fee(baseFee * 100), - Seq(kNone), + Seq(kNONE), Json(jss::LastLedgerSequence, lastLedgerSeq), Ter(terQUEUED))(submitParams); } else { - envs(noop(alice), Fee(baseFee * 100), Seq(kNone), Ter(terQUEUED))(submitParams); + envs(noop(alice), Fee(baseFee * 100), Seq(kNONE), Ter(terQUEUED))(submitParams); } } checkMetrics(*this, env, 5, std::nullopt, 7, 6); @@ -2818,7 +2814,7 @@ public: for (auto const& tx : aliceStat) { BEAST_EXPECT(tx.seqProxy == seq); - BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBaseFeeLevel.fee() * 100}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBASE_FEE_LEVEL.fee() * 100}); if (seq.value() == aliceSeq + 2) { BEAST_EXPECT(tx.lastValid && *tx.lastValid == lastLedgerSeq); @@ -2833,7 +2829,7 @@ public: // Put some txs in the queue for bob. // Give them a higher fee so they'll beat alice's. for (int i = 0; i < 8; ++i) - envs(noop(bob), Fee(baseFee * 200), Seq(kNone), Ter(terQUEUED))(); + envs(noop(bob), Fee(baseFee * 200), Seq(kNONE), Ter(terQUEUED))(); checkMetrics(*this, env, 13, std::nullopt, 7, 6); env.close(); @@ -2842,14 +2838,14 @@ public: // Give them a higher fee so they'll beat alice's. fillQueue(env, bob); for (int i = 0; i < 9; ++i) - envs(noop(bob), Fee(baseFee * 200), Seq(kNone), Ter(terQUEUED))(); + envs(noop(bob), Fee(baseFee * 200), Seq(kNONE), Ter(terQUEUED))(); checkMetrics(*this, env, 14, 14, 8, 7, 25601); env.close(); // Put some more txs in the queue for bob. // Give them a higher fee so they'll beat alice's. fillQueue(env, bob); for (int i = 0; i < 10; ++i) - envs(noop(bob), Fee(baseFee * 200), Seq(kNone), Ter(terQUEUED))(); + envs(noop(bob), Fee(baseFee * 200), Seq(kNONE), Ter(terQUEUED))(); checkMetrics(*this, env, 15, 16, 9, 8); env.close(); checkMetrics(*this, env, 4, 18, 10, 9); @@ -2871,13 +2867,13 @@ public: ++seq; BEAST_EXPECT(tx.seqProxy.isSeq() && tx.seqProxy.value() == seq); - BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBaseFeeLevel.fee() * 100}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBASE_FEE_LEVEL.fee() * 100}); BEAST_EXPECT(!tx.lastValid); ++seq; } } // Now, fill the gap. - envs(noop(alice), Fee(baseFee * 100), Seq(kNone), Ter(terQUEUED))(submitParams); + envs(noop(alice), Fee(baseFee * 100), Seq(kNONE), Ter(terQUEUED))(submitParams); checkMetrics(*this, env, 5, 18, 10, 9); { auto aliceStat = txQ.getAccountTxs(alice.id()); @@ -2886,7 +2882,7 @@ public: for (auto const& tx : aliceStat) { BEAST_EXPECT(tx.seqProxy.isSeq() && tx.seqProxy.value() == seq); - BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBaseFeeLevel * 100}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBASE_FEE_LEVEL * 100}); BEAST_EXPECT(!tx.lastValid); ++seq; } @@ -2978,11 +2974,11 @@ public: BEAST_EXPECT(!queueData.isMember(jss::transactions)); } - auto submitParams = json::Value(json::ValueType::Object); - envs(noop(alice), Fee(baseFee * 10), Seq(kNone), Ter(terQUEUED))(submitParams); - envs(noop(alice), Fee(baseFee * 10), Seq(kNone), Ter(terQUEUED))(submitParams); - envs(noop(alice), Fee(baseFee * 10), Seq(kNone), Ter(terQUEUED))(submitParams); - envs(noop(alice), Fee(baseFee * 10), Seq(kNone), Ter(terQUEUED))(submitParams); + auto submitParams = json::Value(json::ObjectValue); + envs(noop(alice), Fee(baseFee * 10), Seq(kNONE), Ter(terQUEUED))(submitParams); + envs(noop(alice), Fee(baseFee * 10), Seq(kNONE), Ter(terQUEUED))(submitParams); + envs(noop(alice), Fee(baseFee * 10), Seq(kNONE), Ter(terQUEUED))(submitParams); + envs(noop(alice), Fee(baseFee * 10), Seq(kNONE), Ter(terQUEUED))(submitParams); checkMetrics(*this, env, 4, 6, 4, 3); { @@ -3013,7 +3009,7 @@ 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(kBaseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(kBASE_FEE_LEVEL.fee() * 10)); BEAST_EXPECT(!item.isMember(jss::LastLedgerSequence)); BEAST_EXPECT(item.isMember(jss::fee)); @@ -3030,12 +3026,12 @@ public: checkMetrics(*this, env, 0, 8, 4, 4); // Fill the ledger and then queue up a blocker. - envs(noop(alice), Seq(kNone))(submitParams); + envs(noop(alice), Seq(kNONE))(submitParams); envs( fset(alice, asfAccountTxnID), Fee(baseFee * 10), - Seq(kNone), + Seq(kNONE), Json(jss::LastLedgerSequence, 10), Ter(terQUEUED))(submitParams); checkMetrics(*this, env, 1, 8, 5, 4); @@ -3068,7 +3064,7 @@ 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(kBaseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(kBASE_FEE_LEVEL.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)); @@ -3089,7 +3085,7 @@ public: } } - envs(noop(alice), Fee(baseFee * 10), Seq(kNone), Ter(telCAN_NOT_QUEUE_BLOCKED))( + envs(noop(alice), Fee(baseFee * 10), Seq(kNONE), Ter(telCAN_NOT_QUEUE_BLOCKED))( submitParams); checkMetrics(*this, env, 1, 8, 5, 4); @@ -3121,7 +3117,7 @@ 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(kBaseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(kBASE_FEE_LEVEL.fee() * 10)); if (i == queued.size() - 1) { @@ -3224,7 +3220,7 @@ public: checkMetrics(*this, env, 0, 6, 4, 3); auto aliceSeq = env.seq(alice); - auto submitParams = json::Value(json::ValueType::Object); + 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); checkMetrics(*this, env, 4, 6, 4, 3); @@ -3411,7 +3407,7 @@ public: auto const baseFee = env.current()->fees().base.drops(); json::Value stream; - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("server"); auto wsc = makeWSClient(env.app().config()); { @@ -3682,7 +3678,7 @@ public: for (auto const& tx : aliceQueue) { BEAST_EXPECT(tx.seqProxy == seq); - BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBaseFeeLevel.fee() * 10}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{kBASE_FEE_LEVEL.fee() * 10}); seq.advanceBy(1); } @@ -4061,17 +4057,17 @@ public: Account const ellie("ellie"); Account const fiona("fiona"); - static constexpr int kLedgersInQueue = 30; + constexpr int kLEDGERS_IN_QUEUE = 30; auto cfg = makeConfig( {{"minimum_txn_in_ledger_standalone", "1"}, - {"ledgers_in_queue", std::to_string(kLedgersInQueue)}, + {"ledgers_in_queue", std::to_string(kLEDGERS_IN_QUEUE)}, {"maximum_txn_per_account", "10"}}, {{"account_reserve", "1000"}, {"owner_reserve", "50"}}); auto& votingSection = cfg->section("voting"); - votingSection.set("account_reserve", std::to_string(cfg->fees.referenceFee.drops() * 100)); + votingSection.set("account_reserve", std::to_string(cfg->FEES.reference_fee.drops() * 100)); - votingSection.set("reference_fee", std::to_string(cfg->fees.referenceFee.drops())); + votingSection.set("reference_fee", std::to_string(cfg->FEES.reference_fee.drops())); Env env(*this, std::move(cfg)); @@ -4089,7 +4085,7 @@ public: env.close(); auto const metrics = env.app().getTxQ().getMetrics(*env.current()); - checkMetrics(*this, env, 0, kLedgersInQueue * metrics.txPerLedger, 0, 2); + checkMetrics(*this, env, 0, kLEDGERS_IN_QUEUE * metrics.txPerLedger, 0, 2); // Close ledgers until the amendments show up. int i = 0; @@ -4100,7 +4096,7 @@ public: break; } auto expectedPerLedger = xrpl::detail::numUpVotedAmendments() + 1; - checkMetrics(*this, env, 0, kLedgersInQueue * expectedPerLedger, 0, expectedPerLedger); + checkMetrics(*this, env, 0, kLEDGERS_IN_QUEUE * 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, @@ -4119,7 +4115,7 @@ public: *this, env, 0, - kLedgersInQueue * expectedPerLedger, + kLEDGERS_IN_QUEUE * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); @@ -4152,7 +4148,7 @@ public: *this, env, expectedInQueue, - kLedgersInQueue * expectedPerLedger, + kLEDGERS_IN_QUEUE * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); @@ -4178,7 +4174,7 @@ public: *this, env, expectedInQueue, - kLedgersInQueue * expectedPerLedger, + kLEDGERS_IN_QUEUE * expectedPerLedger, expectedInLedger, expectedPerLedger); { @@ -4382,7 +4378,7 @@ public: // b) For just now having a queued transaction fail on apply() // because of the sequence gap. // - // Verify that kNone of alice's queued transactions actually applied to + // Verify that kNONE of alice's queued transactions actually applied to // her account. BEAST_EXPECT(env.seq(alice) == seqSaveAlice); seqAlice = seqSaveAlice; diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index 83267bf0a7..fa8ec7ea3d 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -66,7 +66,7 @@ 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::Severity::Disabled}; + test::jtx::Env env{*this, test::jtx::envconfig(), nullptr, beast::severities::KDisabled}; beast::Journal const journal{env.app().getJournal("ValidatorKeys_test")}; // Keys/ID when using [validation_seed] diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 20a3557db5..52ab2e69aa 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -81,7 +81,7 @@ private: SecretKey const& ssk, int seq) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = seq; st[sfPublicKey] = pk; @@ -104,7 +104,7 @@ private: static std::string makeRevocationString(PublicKey const& pk, SecretKey const& sk) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; @@ -220,7 +220,7 @@ private: { testcase("Config Load"); - jtx::Env env(*this, jtx::envconfig(), nullptr, beast::Severity::Disabled); + jtx::Env env(*this, jtx::envconfig(), nullptr, beast::severities::KDisabled); auto& app = env.app(); std::vector const emptyCfgKeys; std::vector const emptyCfgPublishers; @@ -603,15 +603,15 @@ private: BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); std::map> const lists = []() { - static constexpr auto kListSize = 20; - static constexpr auto kNumLists = 9; + auto constexpr kLIST_SIZE = 20; + auto constexpr kNUM_LISTS = 9; std::map> lists; // 1-based to correspond with the individually named blobs below. - for (auto i = 1; i <= kNumLists; ++i) + for (auto i = 1; i <= kNUM_LISTS; ++i) { auto& list = lists[i]; - list.reserve(kListSize); - while (list.size() < kListSize) + list.reserve(kLIST_SIZE); + while (list.size() < kLIST_SIZE) list.push_back(randomValidator()); } return lists; @@ -949,10 +949,10 @@ private: BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); std::vector const list = []() { - static constexpr auto kListSize = 20; + auto constexpr kLIST_SIZE = 20; std::vector list; - list.reserve(kListSize); - while (list.size() < kListSize) + list.reserve(kLIST_SIZE); + while (list.size() < kLIST_SIZE) list.push_back(randomValidator()); return list; }(); @@ -1545,10 +1545,10 @@ private: // locals[0]: from 0 to maxKeys - 4 // locals[1]: from 1 to maxKeys - 2 // locals[2]: from 2 to maxKeys - static constexpr int kPublishers = 3; + constexpr static int kPUBLISHERS = 3; std::array< std::pair, - kPublishers> + kPUBLISHERS> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), @@ -1588,7 +1588,7 @@ private: }; // Apply multiple published lists - for (auto i = 0; i < kPublishers; ++i) + for (auto i = 0; i < kPUBLISHERS; ++i) addPublishedList(i); BEAST_EXPECT(trustedKeys->getListThreshold() == 1); @@ -1635,10 +1635,10 @@ private: // locals[2]: from 2 to maxKeys // intersection of at least 2: same as locals[1] // intersection when 1 is dropped: from 2 to maxKeys - 4 - static constexpr int kPublishers = 3; + constexpr static int kPUBLISHERS = 3; std::array< std::pair, - kPublishers> + kPUBLISHERS> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), @@ -1703,7 +1703,7 @@ private: // Apply multiple published lists // validUntil1 is expiration time for locals[1] NetClock::time_point validUntil1, validUntil2; - for (auto i = 0; i < kPublishers; ++i) + for (auto i = 0; i < kPUBLISHERS; ++i) addPublishedList(i, validUntil1, validUntil2); BEAST_EXPECT(trustedKeys->getListThreshold() == 2); @@ -2257,7 +2257,7 @@ private: auto extractProtocolMessage1 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); if (BEAST_EXPECT(header) && - BEAST_EXPECT(header->messageType == protocol::mtVALIDATOR_LIST)) + BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST)) { auto const msg = detail::parseMessageContent(*header, buffers.data()); @@ -2269,7 +2269,7 @@ private: auto extractProtocolMessage2 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); if (BEAST_EXPECT(header) && - BEAST_EXPECT(header->messageType == protocol::mtVALIDATOR_LIST_COLLECTION)) + BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST_COLLECTION)) { auto const msg = detail::parseMessageContent( *header, buffers.data()); @@ -2548,10 +2548,10 @@ private: jtx::Env env(*this); auto& app = env.app(); - static constexpr std::size_t kMaxKeys = 20; + constexpr std::size_t kMAX_KEYS = 20; hash_set activeValidators; std::vector valKeys; - while (valKeys.size() != kMaxKeys) + while (valKeys.size() != kMAX_KEYS) { valKeys.push_back(randomValidator()); activeValidators.emplace(calcNodeID(valKeys.back().masterPublic)); @@ -2592,13 +2592,13 @@ private: auto const pubSigningKeys = randomKeyPair(KeyType::Secp256k1); cfgPublishers.push_back(strHex(publisherPublic)); - constexpr auto kRevoked = std::numeric_limits::max(); + constexpr auto kREVOKED = std::numeric_limits::max(); auto const manifest = base64Encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, - i < countRevoked ? kRevoked : 1)); + i < countRevoked ? kREVOKED : 1)); publishers.push_back( Publisher{ .revoked = i < countRevoked, @@ -2640,7 +2640,7 @@ private: }; // Test cases use 5 publishers. - constexpr auto kQuorumDisabled = std::numeric_limits::max(); + constexpr auto kQUORUM_DISABLED = std::numeric_limits::max(); { // List threshold = 5 (same as number of trusted publishers) ManifestCache pubManifests; @@ -2688,7 +2688,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -2746,7 +2746,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; @@ -2811,7 +2811,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -2881,7 +2881,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -2947,7 +2947,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3014,7 +3014,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; @@ -3080,7 +3080,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); @@ -3139,7 +3139,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); @@ -3197,7 +3197,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); @@ -3253,7 +3253,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); for (auto const& val : valKeys) @@ -3298,7 +3298,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; @@ -3319,7 +3319,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3365,7 +3365,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; @@ -3385,7 +3385,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3432,7 +3432,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; @@ -3452,7 +3452,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; @@ -3512,7 +3512,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3573,7 +3573,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3634,7 +3634,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; @@ -3696,7 +3696,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3843,7 +3843,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; @@ -3911,7 +3911,7 @@ private: env.app().getOPs(), env.app().getOverlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->quorum() == kQuorumDisabled); + BEAST_EXPECT(trustedKeys->quorum() == kQUORUM_DISABLED); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); hash_set removed; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index f7f805faa2..4145b4f8b1 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -45,8 +45,8 @@ realValidatorContents() )vl"; } -constexpr auto kDefaultExpires = std::chrono::seconds{3600}; -constexpr auto kDefaultEffectiveOverlap = std::chrono::seconds{30}; +auto constexpr kDEFAULT_EXPIRES = std::chrono::seconds{3600}; +auto constexpr kDEFAULT_EFFECTIVE_OVERLAP = std::chrono::seconds{30}; } // namespace detail namespace test { @@ -62,7 +62,7 @@ private: using namespace jtx; - Env env(*this, envconfig(), nullptr, beast::Severity::Disabled); + Env env(*this, envconfig(), nullptr, beast::severities::KDisabled); auto trustedSites = std::make_unique(env.app(), env.journal); // load should accept empty sites list @@ -78,7 +78,7 @@ private: "http://207.261.33.37:8080/validators", "https://ripple.com/validators", "https://ripple.com:443/validators", - "file:///etc/xrpld/validators.txt", + "file:///etc/opt/xrpld/validators.txt", "file:///C:/Lib/validators.txt" #if !_MSC_VER , @@ -129,8 +129,8 @@ private: bool failFetch = false; bool failApply = false; int serverVersion = 1; - std::chrono::seconds expiresFromNow = detail::kDefaultExpires; - std::chrono::seconds effectiveOverlap = detail::kDefaultEffectiveOverlap; + std::chrono::seconds expiresFromNow = detail::kDEFAULT_EXPIRES; + std::chrono::seconds effectiveOverlap = detail::kDEFAULT_EFFECTIVE_OVERLAP; int expectedRefreshMin = 0; }; void @@ -172,7 +172,7 @@ private: }; std::vector servers; - static constexpr auto kListSize = 20; + auto constexpr kLIST_SIZE = 20; std::vector cfgPublishers; for (auto const& cfg : paths) @@ -180,8 +180,8 @@ private: servers.emplace_back(cfg); auto& item = servers.back(); item.isRetry = cfg.path == "/bad-resource"; - item.list.reserve(kListSize); - while (item.list.size() < kListSize) + item.list.reserve(kLIST_SIZE); + while (item.list.size() < kLIST_SIZE) item.list.push_back(TrustedPublisherServer::randomValidator()); NetClock::time_point const expires = env.timeKeeper().now() + cfg.expiresFromNow; @@ -405,7 +405,7 @@ public: false, false, 1, - detail::kDefaultExpires, + detail::kDEFAULT_EXPIRES, std::chrono::seconds{-90}}}); // fetch single site with unending redirect (fails to load) testFetchList( @@ -495,7 +495,7 @@ public: false, true, 1, - std::chrono::seconds{json::Value::kMinInt}}}); + std::chrono::seconds{json::Value::kMIN_INT}}}); // force an out-of-range validUntil value on the future list // The first list is accepted. The second fails. The parser // returns the "best" result, so this looks like a success. @@ -507,7 +507,7 @@ public: false, false, 1, - std::chrono::seconds{json::Value::kMaxInt - 300}, + std::chrono::seconds{json::Value::kMAX_INT - 300}, 299s}}); // force an out-of-range validFrom value // The first list is accepted. The second fails. The parser @@ -520,7 +520,7 @@ public: false, false, 1, - std::chrono::seconds{json::Value::kMaxInt - 300}, + std::chrono::seconds{json::Value::kMAX_INT - 300}, 301s}}); // force an out-of-range validUntil value on _both_ lists testFetchList( @@ -531,8 +531,8 @@ public: false, true, 1, - std::chrono::seconds{json::Value::kMinInt}, - std::chrono::seconds{json::Value::kMaxInt - 6000}}}); + std::chrono::seconds{json::Value::kMIN_INT}, + std::chrono::seconds{json::Value::kMAX_INT - 6000}}}); // verify refresh intervals are properly clamped testFetchList( good, @@ -542,8 +542,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 1}}); // minimum of 1 minute testFetchList( good, @@ -553,8 +553,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 1}}); // minimum of 1 minute testFetchList( good, @@ -564,8 +564,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 10}}); // 10 minutes is fine testFetchList( good, @@ -575,8 +575,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 10}}); // 10 minutes is fine testFetchList( good, @@ -586,8 +586,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 60 * 24}}); // max of 24 hours testFetchList( good, @@ -597,8 +597,8 @@ public: false, false, 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, + detail::kDEFAULT_EXPIRES, + detail::kDEFAULT_EFFECTIVE_OVERLAP, 60 * 24}}); // max of 24 hours } using namespace boost::filesystem; diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index bf707afae9..b0b93e0b3f 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -9,12 +9,9 @@ #include #include #include -#include -#include #include #include #include -#include #include #include #include @@ -72,7 +69,7 @@ class Vault_test : public beast::unit_test::Suite using PrettyAsset = xrpl::test::jtx::PrettyAsset; using PrettyAmount = xrpl::test::jtx::PrettyAmount; - static constexpr auto kNegativeAmount = [](PrettyAsset const& asset) -> PrettyAmount { + static auto constexpr kNEGATIVE_AMOUNT = [](PrettyAsset const& asset) -> PrettyAmount { return {STAmount{asset.raw(), 1ul, 0, true, STAmount::Unchecked{}}, ""}; }; @@ -209,7 +206,7 @@ class Vault_test : public beast::unit_test::Suite { testcase(prefix + " fail to set domain on public vault"); auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{tecNO_PERMISSION}); env.close(); } @@ -573,7 +570,7 @@ class Vault_test : public beast::unit_test::Suite }); testCases("MPT", [&](Env& env) -> Asset { - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = depositor}); @@ -637,7 +634,7 @@ class Vault_test : public beast::unit_test::Suite { auto tx = vault.set({.owner = owner, .id = keylet.key}); - env(tx, kData("test"), Ter{resultAfterCreate}); + env(tx, kDATA("test"), Ter{resultAfterCreate}); } { @@ -681,14 +678,14 @@ class Vault_test : public beast::unit_test::Suite env(tx); tx[sfFlags] = tx[sfFlags].asUInt() | tfVaultPrivate; - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{temDISABLED}); { auto tx = vault.set({.owner = owner, .id = keylet.key}); - env(tx, kData("Test")); + env(tx, kDATA("Test")); - tx[sfDomainID] = to_string(BaseUInt<256>(13ul)); + tx[sfDomainID] = to_string(BaseUint<256>(13ul)); env(tx, Ter{temDISABLED}); } }, @@ -789,12 +786,12 @@ class Vault_test : public beast::unit_test::Suite testcase("disabled permissioned domain"); auto [tx, keylet] = vault.create({.owner = owner, .asset = xrpIssue()}); - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{temDISABLED}); { auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{temDISABLED}); } @@ -818,33 +815,33 @@ class Vault_test : public beast::unit_test::Suite { auto tx = vault.set({ .owner = owner, - .id = beast::kZero, + .id = beast::kZERO, }); env(tx, Ter{temMALFORMED}); } { auto tx = - vault.deposit({.depositor = owner, .id = beast::kZero, .amount = asset(10)}); + vault.deposit({.depositor = owner, .id = beast::kZERO, .amount = asset(10)}); env(tx, Ter(temMALFORMED)); } { auto tx = - vault.withdraw({.depositor = owner, .id = beast::kZero, .amount = asset(10)}); + vault.withdraw({.depositor = owner, .id = beast::kZERO, .amount = asset(10)}); env(tx, Ter{temMALFORMED}); } { auto tx = vault.clawback( - {.issuer = issuer, .id = beast::kZero, .holder = owner, .amount = asset(10)}); + {.issuer = issuer, .id = beast::kZERO, .holder = owner, .amount = asset(10)}); env(tx, Ter{temMALFORMED}); } { auto tx = vault.del({ .owner = owner, - .id = beast::kZero, + .id = beast::kZERO, }); env(tx, Ter{temMALFORMED}); } @@ -985,7 +982,7 @@ class Vault_test : public beast::unit_test::Suite { auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfAssetsMaximum] = kNegativeAmount(asset).number(); + tx[sfAssetsMaximum] = kNEGATIVE_AMOUNT(asset).number(); env(tx, Ter{temMALFORMED}); } }); @@ -998,7 +995,7 @@ class Vault_test : public beast::unit_test::Suite { auto tx = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = kNegativeAmount(asset)}); + {.depositor = owner, .id = keylet.key, .amount = kNEGATIVE_AMOUNT(asset)}); env(tx, Ter(temBAD_AMOUNT)); } @@ -1030,7 +1027,7 @@ class Vault_test : public beast::unit_test::Suite { auto tx = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = kNegativeAmount(asset)}); + {.depositor = owner, .id = keylet.key, .amount = kNEGATIVE_AMOUNT(asset)}); env(tx, Ter(temBAD_AMOUNT)); } @@ -1063,7 +1060,7 @@ class Vault_test : public beast::unit_test::Suite {.issuer = issuer, .id = keylet.key, .holder = owner, - .amount = kNegativeAmount(asset)}); + .amount = kNEGATIVE_AMOUNT(asset)}); env(tx, Ter(temBAD_AMOUNT)); } }); @@ -1082,13 +1079,13 @@ class Vault_test : public beast::unit_test::Suite { auto tx = tx1; - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{temMALFORMED}); } { auto tx = tx1; - tx[sfAssetsMaximum] = kNegativeAmount(asset).number(); + tx[sfAssetsMaximum] = kNEGATIVE_AMOUNT(asset).number(); env(tx, Ter{temMALFORMED}); } @@ -1241,7 +1238,7 @@ class Vault_test : public beast::unit_test::Suite Vault& vault) { auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfFlags] = tfVaultPrivate; - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); testcase("non-existing domain"); env(tx, Ter{tecOBJECT_NOT_FOUND}); }); @@ -1418,7 +1415,7 @@ class Vault_test : public beast::unit_test::Suite env.fund(XRP(1000), issuer, owner, depositor); env.close(); Vault vault{env}; - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; // Locked because that is the default flag. mptt.create(); Asset const asset = mptt.issuanceID(); @@ -1591,12 +1588,12 @@ class Vault_test : public beast::unit_test::Suite env.close(); Vault vault{env}; - MPTTester mptt{env, issuer, kMptInitNoFund}; - auto const kNone = LedgerSpecificFlags(0); + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; + auto const kNONE = LedgerSpecificFlags(0); mptt.create( {.flags = tfMPTCanTransfer | tfMPTCanLock | - (args.enableClawback ? tfMPTCanClawback : kNone) | - (args.requireAuth ? tfMPTRequireAuth : kNone), + (args.enableClawback ? tfMPTCanClawback : kNONE) | + (args.requireAuth ? tfMPTRequireAuth : kNONE), .mutableFlags = tmfMPTCanMutateCanTransfer}); PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = owner}); @@ -1875,8 +1872,8 @@ class Vault_test : public beast::unit_test::Suite auto const [acctReserve, incReserve] = [this]() -> std::pair { Env const env{*this, testableAmendments()}; return { - env.current()->fees().accountReserve(0).drops() / kDropsPerXrp.drops(), - env.current()->fees().increment.drops() / kDropsPerXrp.drops()}; + env.current()->fees().accountReserve(0).drops() / kDROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / kDROPS_PER_XRP.drops()}; }(); testCase( @@ -2214,7 +2211,7 @@ class Vault_test : public beast::unit_test::Suite env.close(); Vault const vault{env}; - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create( {.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | tfMPTRequireAuth}); mptt.authorize({.account = owner}); @@ -2244,7 +2241,7 @@ class Vault_test : public beast::unit_test::Suite PrettyAsset const& asset, Vault& vault, MPTTester& mptt) { - testcase("MPT non-transferable: block deposit, allow withdraw"); + testcase("MPT non-transferable"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); @@ -2254,19 +2251,22 @@ class Vault_test : public beast::unit_test::Suite env(tx); env.close(); - // Issuer governance: clear CanTransfer. New exposure must be - // blocked, but recovery paths must remain open so existing - // depositors are not trapped. + // Remove CanTransfer mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); env.close(); - // New deposit is blocked. env(tx, Ter{tecNO_AUTH}); env.close(); - // Existing depositor can always withdraw, even though the asset - // is no longer freely transferable. tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + + env(tx, Ter{tecNO_AUTH}); + env.close(); + + // Restore CanTransfer + mptt.set({.mutableFlags = tmfMPTSetCanTransfer}); + env.close(); + env(tx); env.close(); @@ -2274,322 +2274,6 @@ class Vault_test : public beast::unit_test::Suite env(vault.del({.owner = owner, .id = keylet.key})); }); - { - testcase("MPT non-transferable: pre-fixCleanup3_2_0 withdraw blocked"); - - // Regression: before fixCleanup3_2_0 a depositor was trapped if - // the issuer cleared lsfMPTCanTransfer. Verify that the legacy - // (broken) behavior is preserved when the amendment is disabled. - Env env{*this, testableAmendments() - fixCleanup3_2_0}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const depositor{"depositor"}; - env.fund(XRP(10'000), issuer, owner, depositor); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = depositor}); - env(pay(issuer, depositor, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)})); - env.close(); - - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Pre-amendment: deposit blocked (matches new behavior). - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}), - Ter{tecNO_AUTH}); - env.close(); - - // Pre-amendment: withdraw is also blocked - this is the bug - // that fixCleanup3_2_0 fixes. - env(vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}), - Ter{tecNO_AUTH}); - env.close(); - } - - { - testcase("MPT non-transferable: vault shares inherit restriction"); - - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - env.fund(XRP(10'000), issuer, owner, alice, bob); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = alice}); - mptt.authorize({.account = bob}); - env(pay(issuer, alice, asset(1'000))); - env(pay(issuer, bob, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(500)})); - // Bob also deposits so he has a share MPToken to receive into. - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(500)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - - // Sanity: while CanTransfer is set on the underlying, peer-to-peer - // share transfers are allowed. - env(pay(alice, bob, shares(1))); - env.close(); - - // Issuer governance: clear CanTransfer on the underlying. - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Vault shares inherit the restriction: third-party share-to-share - // payments are blocked. - env(pay(alice, bob, shares(1)), Ter{tecNO_AUTH}); - env.close(); - - // Recovery path: existing share holders can still redeem shares - // for the underlying asset via VaultWithdraw. - env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = shares(1)})); - env.close(); - } - - { - testcase("MPT locked: vault shares inherit underlying lock"); - - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const carol{"carol"}; - env.fund(XRP(10'000), issuer, owner, alice, bob, carol); - env.close(); - Vault const vault{env}; - - MPTTester asset{ - {.env = env, - .issuer = issuer, - .holders = {owner, alice, bob, carol}, - .flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock}}; - env(pay(issuer, alice, asset(1'000))); - env(pay(issuer, bob, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(500)})); - // Bob also deposits so he has a share MPToken to receive into. - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(500)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - auto const shareMptID = shares.raw().get().getMptID(); - auto const shareBalance = [&](Account const& account) { - auto const sle = env.le(keylet::mptoken(shareMptID, account)); - return sle ? sle->at(sfMPTAmount) : 0; - }; - - // Sanity: before the underlying lock, peer-to-peer share - // transfers are allowed. - env(pay(alice, bob, shares(1))); - env.close(); - - // Create the offer while shares are spendable, then lock the - // underlying to test whether a stale offer can still be crossed. - env(offer(alice, XRP(1), shares(1))); - env.close(); - - // Lock the underlying after the vault and share balances exist. - asset.set({.account = issuer, .flags = tfMPTLock}); - env.close(); - - // Direct vault share payment inherits the underlying lock via - // sfReferenceHolding. - BEAST_EXPECT(shareBalance(alice) == 499); - BEAST_EXPECT(shareBalance(bob) == 501); - env(pay(alice, bob, shares(1)), Ter{tecLOCKED}); - env.close(); - BEAST_EXPECT(shareBalance(alice) == 499); - BEAST_EXPECT(shareBalance(bob) == 501); - - // The same inherited lock must also block DEX payment paths that - // would consume an offer selling vault shares. - env(pay(carol, bob, shares(1)), - Sendmax(XRP(1)), - Path(BookSpec{shares.raw()}), - Ter{tecPATH_PARTIAL}); - env.close(); - BEAST_EXPECT(shareBalance(alice) == 499); - BEAST_EXPECT(shareBalance(bob) == 501); - BEAST_EXPECT(expectOffers(env, alice, 1)); - } - - { - testcase("MPT non-transferable: pre-fixCleanup3_2_0 share transfer succeeds"); - - // Regression: before fixCleanup3_2_0 a peer-to-peer share Payment - // succeeded even when the underlying asset's lsfMPTCanTransfer - // was cleared. Verify that the legacy (non-inheriting) behavior - // is preserved when the amendment is disabled. - Env env{*this, testableAmendments() - fixCleanup3_2_0}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - env.fund(XRP(10'000), issuer, owner, alice, bob); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = alice}); - mptt.authorize({.account = bob}); - env(pay(issuer, alice, asset(1'000))); - env(pay(issuer, bob, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(500)})); - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(500)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Pre-amendment: share transfer leaks past underlying restriction. - env(pay(alice, bob, shares(1))); - env.close(); - } - - { - testcase("MPT CanTrade governance: share inherits underlying on DEX and AMM"); - - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - env.fund(XRP(100'000), issuer, owner, alice, bob); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTrade}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = alice}); - mptt.authorize({.account = bob}); - env(pay(issuer, alice, asset(10'000))); - env(pay(issuer, bob, asset(10'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - // Seed shares so we can later place them on trading venues. - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(5'000)})); - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(5'000)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - - // Sanity: while CanTrade is set on the underlying, both the asset - // and the vault share can be placed on the DEX. - env(offer(alice, XRP(1), asset(10))); - env(offer(alice, XRP(1), shares(1))); - env.close(); - - // Issuer governance: clear CanTrade on the underlying. - mptt.set({.mutableFlags = tmfMPTClearCanTrade}); - env.close(); - - // Control: clearing CanTrade on the underlying is observable on - // the DEX path for that asset. - env(offer(alice, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); - env.close(); - - // Control: clearing CanTrade on the underlying is also observable - // on the AMM path for that asset. - AMM const ammUnderlyingFails( - env, alice, XRP(1'000), asset(1'000), Ter{tecNO_PERMISSION}); - - // Post-fixCleanup3_2_0: vault shares inherit the underlying's - // CanTrade restriction on the DEX path (canTrade reads the - // share's sfReferenceHolding and dispatches to the underlying). - env(offer(bob, XRP(1), shares(1)), Ter{tecNO_PERMISSION}); - env.close(); - - // checkMPTAllowed mirrors the inheritance for AMM/Offer- - // crossing/Check paths, so a share AMM also cannot be created - // when the underlying CanTrade is cleared. - AMM const ammShares(env, alice, XRP(1'000), shares(100), Ter{tecNO_PERMISSION}); - - // Deposit still works (canAddHolding does not consult the field). - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(100)})); - env.close(); - - // Peer-to-peer share transfers still work (CanTransfer is set on - // both layers). - env(pay(alice, bob, shares(1))); - env.close(); - - // Withdraw still works. - env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = asset(100)})); - env.close(); - } - { testcase("MPT OutstandingAmount > MaximumAmount"); @@ -2716,7 +2400,7 @@ class Vault_test : public beast::unit_test::Suite jv[jss::Account] = issuer.human(); { auto& ja = jv[jss::LimitAmount] = - foo(0).value().getJson(JsonOptions::Values::None); + foo(0).value().getJson(JsonOptions::KNone); ja[jss::issuer] = toBase58(account); } jv[jss::TransactionType] = jss::TrustSet; @@ -2769,8 +2453,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::Values::None); + auto& ja = jv[jss::LimitAmount] = asset(0).value().getJson(JsonOptions::KNone); ja[jss::issuer] = toBase58(account); } jv[jss::TransactionType] = jss::TrustSet; @@ -3052,7 +2735,7 @@ class Vault_test : public beast::unit_test::Suite { // Create MPToken for shares held by Charlie - json::Value tx{json::ValueType::Object}; + json::Value tx{json::ObjectValue}; tx[sfAccount] = charlie.human(); tx[sfMPTokenIssuanceID] = to_string(shares.raw().get().getMptID()); @@ -3060,17 +2743,16 @@ class Vault_test : public beast::unit_test::Suite env(tx); env.close(); } - // Behavioral shift introduced by share inheritance: - // before fixCleanup3_2_0 this share Payment succeeded - // and the underlying IOU's NoRipple restriction surfaced - // only later on Charlie's withdrawal (terNO_RIPPLE). - // Post-amendment, canTransfer reads the share's - // sfReferenceHolding and dispatches to the underlying IOU; - // rippling is disabled between owner and charlie so the - // share payment itself is now blocked. tecPATH_DRY is - // the path-find layer's translation of the underlying - // terNO_RIPPLE under featureMPTokensV2. - env(pay(owner, charlie, shares(100)), Ter{tecPATH_DRY}); + env(pay(owner, charlie, shares(100))); + env.close(); + + // Charlie cannot withdraw + auto tx3 = vault.withdraw( + {.depositor = charlie, .id = keylet.key, .amount = shares(100)}); + env(tx3, Ter{terNO_RIPPLE}); + env.close(); + + env(pay(charlie, owner, shares(100))); env.close(); } @@ -3137,10 +2819,10 @@ class Vault_test : public beast::unit_test::Suite { BEAST_EXPECT(env.balance(owner, asset) == startingOwnerBalance.value()); - BEAST_EXPECT(env.balance(vaultAccount(keylet), asset) == beast::kZero); + BEAST_EXPECT(env.balance(vaultAccount(keylet), asset) == beast::kZERO); auto const vault = env.le(keylet); - BEAST_EXPECT(vault->at(sfAssetsAvailable) == beast::kZero); - BEAST_EXPECT(vault->at(sfAssetsTotal) == beast::kZero); + BEAST_EXPECT(vault->at(sfAssetsAvailable) == beast::kZERO); + BEAST_EXPECT(vault->at(sfAssetsTotal) == beast::kZERO); } env(vault.del({.owner = owner, .id = keylet.key})); @@ -3151,8 +2833,8 @@ class Vault_test : public beast::unit_test::Suite auto const [acctReserve, incReserve] = [this]() -> std::pair { Env const env{*this, testableAmendments()}; return { - env.current()->fees().accountReserve(0).drops() / kDropsPerXrp.drops(), - env.current()->fees().increment.drops() / kDropsPerXrp.drops()}; + env.current()->fees().accountReserve(0).drops() / kDROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / kDROPS_PER_XRP.drops()}; }(); testCase( @@ -3383,7 +3065,7 @@ class Vault_test : public beast::unit_test::Suite { testcase("private vault cannot set non-existing domain"); auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfDomainID] = to_string(BaseUInt<256>(42ul)); + tx[sfDomainID] = to_string(BaseUint<256>(42ul)); env(tx, Ter{tecOBJECT_NOT_FOUND}); } @@ -3396,7 +3078,7 @@ class Vault_test : public beast::unit_test::Suite env(pdomain::setTx(pdOwner, credentials1)); auto const domainId1 = [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); @@ -3417,7 +3099,7 @@ class Vault_test : public beast::unit_test::Suite env(pdomain::setTx(pdOwner, credentials)); auto const domainId = [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); @@ -3634,7 +3316,7 @@ class Vault_test : public beast::unit_test::Suite env(pdomain::setTx(owner, credentials)); auto const domainId = [&]() { - auto tx = env.tx()->getJson(JsonOptions::Values::None); + auto tx = env.tx()->getJson(JsonOptions::KNone); return pdomain::getNewDomain(env.meta()); }(); @@ -3693,9 +3375,9 @@ class Vault_test : public beast::unit_test::Suite AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); env(pay(env.master.id(), accountId, XRP(1000)), - Seq(kAutofill), - Fee(kAutofill), - Sig(kAutofill)); + Seq(kAUTOFILL), + Fee(kAUTOFILL), + Sig(kAUTOFILL)); } auto [tx, keylet1] = vault.create({.owner = owner, .asset = xrpIssue()}); @@ -4515,10 +4197,10 @@ class Vault_test : public beast::unit_test::Suite // Borrow 40: assetsAvailable=60, assetsTotal=100 env(set(d.depositor, brokerKeylet.key, STAmount(d.asset, Number(40, 0))), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, d.owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -4594,20 +4276,20 @@ 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::ValueType::Null) { + json::Value const& issuance = json::NullValue) { BEAST_EXPECT(vault.isObject()); - static constexpr auto kCheckString = + constexpr auto kCHECK_STRING = [](auto& node, SField const& field, std::string v) -> bool { return node.isMember(field.fieldName) && node[field.fieldName].isString() && node[field.fieldName] == v; }; - static constexpr auto kCheckObject = + constexpr auto kCHECK_OBJECT = [](auto& node, SField const& field, json::Value v) -> bool { return node.isMember(field.fieldName) && node[field.fieldName].isObject() && node[field.fieldName] == v; }; - static constexpr auto kCheckInt = [](auto& node, SField const& field, int v) -> bool { + constexpr auto kCHECK_INT = [](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))); @@ -4615,30 +4297,31 @@ class Vault_test : public beast::unit_test::Suite BEAST_EXPECT(vault["LedgerEntryType"].asString() == "Vault"); BEAST_EXPECT(vault[jss::index].asString() == strHex(keylet.key)); - BEAST_EXPECT(kCheckInt(vault, sfFlags, 0)); + BEAST_EXPECT(kCHECK_INT(vault, sfFlags, 0)); // Ignore all other standard fields, this test doesn't care - BEAST_EXPECT(kCheckString(vault, sfAccount, toBase58(sle->at(sfAccount)))); - BEAST_EXPECT(kCheckObject(vault, sfAsset, toJson(sle->at(sfAsset)))); - BEAST_EXPECT(kCheckString(vault, sfAssetsAvailable, "50")); - BEAST_EXPECT(kCheckString(vault, sfAssetsMaximum, "1000")); - BEAST_EXPECT(kCheckString(vault, sfAssetsTotal, "50")); + BEAST_EXPECT(kCHECK_STRING(vault, sfAccount, toBase58(sle->at(sfAccount)))); + BEAST_EXPECT(kCHECK_OBJECT(vault, sfAsset, toJson(sle->at(sfAsset)))); + BEAST_EXPECT(kCHECK_STRING(vault, sfAssetsAvailable, "50")); + BEAST_EXPECT(kCHECK_STRING(vault, sfAssetsMaximum, "1000")); + BEAST_EXPECT(kCHECK_STRING(vault, sfAssetsTotal, "50")); BEAST_EXPECT(!vault.isMember(sfLossUnrealized.getJsonName())); auto const strShareID = strHex(sle->at(sfShareMPTID)); - BEAST_EXPECT(kCheckString(vault, sfShareMPTID, strShareID)); - BEAST_EXPECT(kCheckString(vault, sfOwner, toBase58(owner.id()))); - BEAST_EXPECT(kCheckInt(vault, sfSequence, sequence)); - BEAST_EXPECT(kCheckInt(vault, sfWithdrawalPolicy, kVaultStrategyFirstComeFirstServe)); + BEAST_EXPECT(kCHECK_STRING(vault, sfShareMPTID, strShareID)); + BEAST_EXPECT(kCHECK_STRING(vault, sfOwner, toBase58(owner.id()))); + BEAST_EXPECT(kCHECK_INT(vault, sfSequence, sequence)); + BEAST_EXPECT( + kCHECK_INT(vault, sfWithdrawalPolicy, kVAULT_STRATEGY_FIRST_COME_FIRST_SERVE)); if (issuance.isObject()) { BEAST_EXPECT(issuance["LedgerEntryType"].asString() == "MPTokenIssuance"); BEAST_EXPECT(issuance[jss::mpt_issuance_id].asString() == strShareID); - BEAST_EXPECT(kCheckInt(issuance, sfSequence, 1)); - BEAST_EXPECT(kCheckInt( + BEAST_EXPECT(kCHECK_INT(issuance, sfSequence, 1)); + BEAST_EXPECT(kCHECK_INT( issuance, sfFlags, int(lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer))); - BEAST_EXPECT(kCheckString(issuance, sfOutstandingAmount, "50000000")); + BEAST_EXPECT(kCHECK_STRING(issuance, sfOutstandingAmount, "50000000")); } }; @@ -4971,7 +4654,7 @@ class Vault_test : public beast::unit_test::Suite using namespace test::jtx; using namespace loanBroker; using namespace loan; - Env env(*this, beast::Severity::Warning); + Env env(*this, beast::severities::KWarning); auto const vaultAssetBalance = [&](Keylet const& vaultKeylet) { auto const sleVault = env.le(vaultKeylet); @@ -5032,10 +4715,10 @@ class Vault_test : public beast::unit_test::Suite // Create a simple Loan for the full amount of Vault assets env(set(depositor, brokerKeylet.key, asset(100).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5213,7 +4896,7 @@ class Vault_test : public beast::unit_test::Suite testCase(iou, "IOU (owner is issuer)", issuer, depositor); // Test MPT - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mpt = mptt.issuanceID(); mptt.authorize({.account = owner}); @@ -5232,7 +4915,7 @@ class Vault_test : public beast::unit_test::Suite using namespace loanBroker; using namespace loan; Env env(*this); - env.enableFeature(fixCleanup3_1_3); + env.enableFeature(fixSecurity3_1_3); auto const setupVault = [&](PrettyAsset const& asset, Account const& owner, @@ -5423,10 +5106,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows 40 units, reducing assetsAvailable to 60 // while assetsTotal stays at 100 env(set(depositor, brokerKeylet.key, asset(40).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5480,10 +5163,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows 40 units env(set(depositor, brokerKeylet.key, asset(40).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5535,10 +5218,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows 40 units: assetsAvailable=60, assetsTotal=100 env(set(depositor, brokerKeylet.key, asset(40).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5589,10 +5272,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows 40 units: assetsAvailable=60, assetsTotal=100 env(set(depositor, brokerKeylet.key, asset(40).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5637,10 +5320,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows all 100 units: assetsAvailable=0, assetsTotal=100 env(set(depositor, brokerKeylet.key, asset(100).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5709,7 +5392,7 @@ class Vault_test : public beast::unit_test::Suite testCase(iou, "IOU", owner, depositor, issuer); // Test MPT - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mpt = mptt.issuanceID(); @@ -5719,14 +5402,14 @@ class Vault_test : public beast::unit_test::Suite env.close(); testCase(mpt, "MPT", owner, depositor, issuer); - // Test pre-fixCleanup3_1_3 legacy path: zero-amount clawback + // Test pre-fixSecurity3_1_3 legacy path: zero-amount clawback // returns early without clamping to assetsAvailable. { testcase( - "VaultClawback (asset) - IOU pre-fixCleanup3_1_3" + "VaultClawback (asset) - IOU pre-fixSecurity3_1_3" " zero-amount clawback unclamped with outstanding loan"); - env.disableFeature(fixCleanup3_1_3); + env.disableFeature(fixSecurity3_1_3); auto [vault, vaultKeylet] = setupVault(iou, owner, depositor, issuer); @@ -5745,10 +5428,10 @@ class Vault_test : public beast::unit_test::Suite // Depositor borrows 40 units, reducing assetsAvailable to 60 // while assetsTotal stays at 100 env(set(depositor, brokerKeylet.key, iou(40).value()), - loan::kInterestRate(TenthBips32(0)), - kGracePeriod(60), - kPaymentInterval(120), - kPaymentTotal(10), + loan::kINTEREST_RATE(TenthBips32(0)), + kGRACE_PERIOD(60), + kPAYMENT_INTERVAL(120), + kPAYMENT_TOTAL(10), Sig(sfCounterpartySignature, owner), Fee(env.current()->fees().base * 2), Ter(tesSUCCESS)); @@ -5784,7 +5467,7 @@ class Vault_test : public beast::unit_test::Suite BEAST_EXPECT(sharesAfter == sharesBefore); } - env.enableFeature(fixCleanup3_1_3); + env.enableFeature(fixSecurity3_1_3); } } @@ -5811,10 +5494,10 @@ class Vault_test : public beast::unit_test::Suite static_cast(std::numeric_limits::max()) + 1); BEAST_EXPECT(maxInt64Plus1 == "9223372036854775808"); - auto const initialXRP = to_string(kInitialXrp); + auto const initialXRP = to_string(kINITIAL_XRP); BEAST_EXPECT(initialXRP == "100000000000000000"); - auto const initialXRPPlus1 = to_string(kInitialXrp + 1); + auto const initialXRPPlus1 = to_string(kINITIAL_XRP + 1); BEAST_EXPECT(initialXRPPlus1 == "100000000000000001"); { @@ -5862,7 +5545,7 @@ class Vault_test : public beast::unit_test::Suite testcase("Assets Maximum: MPT"); PrettyAsset const mptAsset = [&]() { - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); PrettyAsset const mptAsset = mptt["MPT"]; @@ -6002,7 +5685,7 @@ class Vault_test : public beast::unit_test::Suite if (!BEAST_EXPECT(vaultSle)) return; - BEAST_EXPECT(vaultSle->at(sfAssetsMaximum) == kNumZero); + BEAST_EXPECT(vaultSle->at(sfAssetsMaximum) == kNUM_ZERO); } // What _can't_ IOUs do? @@ -6054,7 +5737,7 @@ class Vault_test : public beast::unit_test::Suite env.fund(XRP(10000), issuer, owner, depositor, bob); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create( {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock | tfMPTCanEscrow}); mptt.authorize({.account = owner}); @@ -6067,8 +5750,8 @@ class Vault_test : public beast::unit_test::Suite // Escrow 60 of 100 MPT tokens: sfMPTAmount drops to 40 auto const escrowSeq = env.seq(depositor); env(escrow::create(depositor, bob, asset(60)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -6096,8 +5779,8 @@ class Vault_test : public beast::unit_test::Suite // Clean up escrow env(escrow::finish(bob, depositor, escrowSeq), - escrow::kCondition(escrow::kCb1), - escrow::kFulfillment(escrow::kFb1), + escrow::kCONDITION(escrow::kCB1), + escrow::kFULFILLMENT(escrow::kFB1), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -6116,7 +5799,7 @@ class Vault_test : public beast::unit_test::Suite env.fund(XRP(10000), issuer, owner, depositor, bob); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create( {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock | tfMPTCanEscrow}); mptt.authorize({.account = owner}); @@ -6156,8 +5839,8 @@ class Vault_test : public beast::unit_test::Suite // Escrow 60% of shares auto const escrowAmount = shares(Number{6, vaultSle->at(sfScale) + 1}); env(escrow::create(depositor, bob, escrowAmount), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -6183,7 +5866,7 @@ class Vault_test : public beast::unit_test::Suite { testcase("Vault clawback only recovers unlocked shares"); - Env env{*this, testableAmendments() | fixCleanup3_1_3}; + Env env{*this, testableAmendments() | fixSecurity3_1_3}; auto const baseFee = env.current()->fees().base; Account const owner{"owner"}; Account const depositor{"depositor"}; @@ -6193,7 +5876,7 @@ class Vault_test : public beast::unit_test::Suite env.fund(XRP(10000), issuer, owner, depositor, bob); env.close(); - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create( {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock | tfMPTCanEscrow}); mptt.authorize({.account = owner}); @@ -6233,8 +5916,8 @@ class Vault_test : public beast::unit_test::Suite // Escrow 60% of shares auto const escrowAmount = shares(Number{6, vaultSle->at(sfScale) + 1}); env(escrow::create(depositor, bob, escrowAmount), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -6273,9 +5956,9 @@ class Vault_test : public beast::unit_test::Suite auto const allAmendments = testableAmendments() | featureSingleAssetVault; - for (auto const& features : {allAmendments, allAmendments - fixCleanup3_1_3}) + for (auto const& features : {allAmendments, allAmendments - fixSecurity3_1_3}) { - bool const withFix = features[fixCleanup3_1_3]; + bool const withFix = features[fixSecurity3_1_3]; Env env{*this, features}; Account const owner{"owner"}; @@ -6382,7 +6065,7 @@ class Vault_test : public beast::unit_test::Suite Vault const vault{env}; // Create an MPT asset for the vault - MPTTester mptt{env, issuer, kMptInitNoFund}; + MPTTester mptt{env, issuer, kMPT_INIT_NO_FUND}; mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = owner}); @@ -6413,8 +6096,8 @@ class Vault_test : public beast::unit_test::Suite // Escrow 500 of those shares env(escrow::create(depositor, bob, STAmount{shareIssue, 500}), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), + escrow::kCONDITION(escrow::kCB1), + escrow::kFINISH_TIME(env.now() + 1s), Fee(baseFee * 150), Ter(tesSUCCESS)); env.close(); @@ -6433,7 +6116,7 @@ class Vault_test : public beast::unit_test::Suite env.close(); auto const sleMptAfter = env.le(keylet::mptoken(shareMptID, depositor)); - if (!f[fixCleanup3_1_3]) + if (!f[fixSecurity3_1_3]) { // Without the fix, removeEmptyHolding deletes the MPToken // even though sfLockedAmount > 0, leaving the escrow's locked @@ -6453,1581 +6136,14 @@ class Vault_test : public beast::unit_test::Suite } }; - runTest(amendments - fixCleanup3_1_3); + runTest(amendments - fixSecurity3_1_3); runTest(amendments); } - // ----------------------------------------------------------------------- - // Helpers and tests: sole-shareholder / stuck-depositor (XLS-0065 + - // fixCleanup3_2_0). The vault-level withdraw behavior is tested here; - // the loan-protocol setup is incidental. - // ----------------------------------------------------------------------- - - FeatureBitset const all_{test::jtx::testableAmendments()}; - std::string const iouCurrency_{"IOU"}; - - // design doc: - // AssetsAvailable ≈ 3,333.50 - // AssetsTotal ≈ 6,666.50 (3,333.50 cash + 3,333 receivable) - // LossUnrealized = 3,333 - // OutstandingShares = sharesLender (5e9 at IOU scale 1e6) - struct StuckDepositorFixture - { - test::jtx::Account issuer{"issuer"}; - test::jtx::Account lender{"lender"}; - test::jtx::Account bob{"bob"}; - test::jtx::Account borrower{"borrower"}; - std::optional asset; - std::optional vaultKeylet; - uint256 brokerID; - std::optional loanKeylet; - MPTID shareAsset; - std::uint64_t sharesLender = 0; - }; - - static constexpr std::int64_t kStuckFunding = 1'000'000; - static constexpr std::int64_t kStuckDepositorIOU = 1'000'000; - static constexpr std::int64_t kStuckBorrowerIOU = 100'000; - static constexpr std::int64_t kStuckDeposit = 5'000; - static constexpr std::int64_t kStuckPrincipal = 3'333; - static constexpr std::uint32_t kStuckPayInterval = 600; - static constexpr std::uint32_t kStuckPayTotal = 2; - - [[nodiscard]] StuckDepositorFixture - setupStuckDepositor(test::jtx::Env& env) - { - using namespace test::jtx; - - StuckDepositorFixture f; - f.asset = f.issuer[iouCurrency_]; - - env.fund(XRP(kStuckFunding), f.issuer, f.lender, f.bob, f.borrower); - env.close(); - - env(trust(f.lender, (*f.asset)(10'000'000))); - env(trust(f.bob, (*f.asset)(10'000'000))); - env(trust(f.borrower, (*f.asset)(10'000'000))); - env.close(); - - env(pay(f.issuer, f.lender, (*f.asset)(kStuckDepositorIOU))); - env(pay(f.issuer, f.bob, (*f.asset)(kStuckDepositorIOU))); - env(pay(f.issuer, f.borrower, (*f.asset)(kStuckBorrowerIOU))); - env.close(); - - // Vault: Lender creates and seeds it; Bob matches the deposit for a - // clean 50/50 split. - Vault const v{env}; - auto [createTx, vaultKeylet] = v.create({.owner = f.lender, .asset = *f.asset}); - env(createTx); - env.close(); - if (!BEAST_EXPECT(env.le(vaultKeylet))) - return f; - f.vaultKeylet = vaultKeylet; - - env(v.deposit({ - .depositor = f.lender, - .id = vaultKeylet.key, - .amount = (*f.asset)(kStuckDeposit), - }), - Ter(tesSUCCESS)); - env(v.deposit({ - .depositor = f.bob, - .id = vaultKeylet.key, - .amount = (*f.asset)(kStuckDeposit), - }), - Ter(tesSUCCESS)); - env.close(); - - // Loan broker: no cover, no management fee, debt cap 10x principal. - f.brokerID = keylet::loanbroker(f.lender.id(), env.seq(f.lender)).key; - { - using namespace loanBroker; - env(set(f.lender, vaultKeylet.key), - kDebtMaximum((*f.asset)(kStuckPrincipal * 10).value())); - env.close(); - } - - // Loan: 3,333 USD principal, impaired immediately. - auto const sleBroker = env.le(keylet::loanbroker(f.brokerID)); - if (!BEAST_EXPECT(sleBroker)) - return f; - f.loanKeylet = keylet::loan(f.brokerID, sleBroker->at(sfLoanSequence)); - - { - using namespace loan; - env(set(f.borrower, f.brokerID, kStuckPrincipal), - Sig(sfCounterpartySignature, f.lender), - kPaymentTotal(kStuckPayTotal), - kPaymentInterval(kStuckPayInterval), - Fee(env.current()->fees().base * 2), - Ter(tesSUCCESS)); - env.close(); - env(manage(f.lender, f.loanKeylet->key, tfLoanImpair), Ter(tesSUCCESS)); - env.close(); - } - - auto const vaultSle = env.le(vaultKeylet); - if (!BEAST_EXPECT(vaultSle)) - return f; - BEAST_EXPECT(vaultSle->at(sfLossUnrealized) == (*f.asset)(kStuckPrincipal).value()); - - f.shareAsset = vaultSle->at(sfShareMPTID); - - auto const tokenBob = env.le(keylet::mptoken(f.shareAsset, f.bob.id())); - if (!BEAST_EXPECT(tokenBob)) - return f; - std::uint64_t const sharesBob = tokenBob->getFieldU64(sfMPTAmount); - - // Bob (non-sole) exits at the discounted rate. Always succeeds. - STAmount const bobShareAmt{MPTIssue{f.shareAsset}, Number(sharesBob)}; - env(v.withdraw({ - .depositor = f.bob, - .id = vaultKeylet.key, - .amount = bobShareAmt, - }), - Ter(tesSUCCESS)); - env.close(); - - auto const tokenLender = env.le(keylet::mptoken(f.shareAsset, f.lender.id())); - if (!BEAST_EXPECT(tokenLender)) - return f; - f.sharesLender = tokenLender->getFieldU64(sfMPTAmount); - - auto const sleIssuance = env.le(keylet::mptIssuance(f.shareAsset)); - if (!BEAST_EXPECT(sleIssuance)) - return f; - BEAST_EXPECT(sleIssuance->getFieldU64(sfOutstandingAmount) == f.sharesLender); - - auto const vaultAfterBob = env.le(vaultKeylet); - if (!BEAST_EXPECT(vaultAfterBob)) - return f; - // After Bob's exit: loss is unchanged (3,333 receivable), and the - // gap between assetsTotal and assetsAvailable equals exactly that - // receivable. - BEAST_EXPECT(vaultAfterBob->at(sfLossUnrealized) == (*f.asset)(kStuckPrincipal).value()); - BEAST_EXPECT( - vaultAfterBob->at(sfAssetsTotal) - vaultAfterBob->at(sfAssetsAvailable) == - vaultAfterBob->at(sfLossUnrealized)); - - return f; - } - - // Reproduces the worked example from the XLS-0065 design doc. The sole - // remaining shareholder asks (via fixed-asset input) for the vault's - // entire AssetsAvailable. Pre-fix this fails with the zero-sized-vault - // invariant violation. Post-fix the full-price exchange rate burns - // only a portion of the shares, the depositor receives all of - // AssetsAvailable, and the residual shares remain backed by the - // impaired-loan receivable. - void - testWithdrawSoleShareholderFixedAssetExit(FeatureBitset features) - { - using namespace test::jtx; - - bool const withFix = features[fixCleanup3_2_0]; - testcase( - std::string{"Vault withdraw: sole shareholder exits via " - "fixed-asset amount with impaired loan"} + - (withFix ? " (fixCleanup3_2_0)" : " (pre-fix)")); - - Env env(*this, features); - auto const f = setupStuckDepositor(env); - if (!f.vaultKeylet || !f.asset || f.sharesLender == 0) - { - BEAST_EXPECT(false); - return; - } - Keylet const& vaultKey = *f.vaultKeylet; - PrettyAsset const& asset = *f.asset; - - auto const vaultBefore = env.le(vaultKey); - if (!BEAST_EXPECT(vaultBefore)) - return; - Number const availableBefore = vaultBefore->at(sfAssetsAvailable); - Number const totalBefore = vaultBefore->at(sfAssetsTotal); - Number const lossBefore = vaultBefore->at(sfLossUnrealized); - - STAmount const lenderBalanceBefore = env.balance(f.lender, asset); - - // The requested amount differs between feature regimes because - // the two regimes are testing different behaviors: - // - // - Pre-fix: request the full AssetsAvailable (3,333.50). Under - // the discounted formula this would burn every outstanding - // share, hitting the zero-sized-vault invariant. The - // transaction is rejected with tecINVARIANT_FAILED — the - // stuck-depositor bug. - // - // - Post-fix: request a strictly smaller amount (1,000 USD). - // The full-price formula burns only ~30% of the outstanding - // shares; the vault retains the rest, backed by the impaired - // receivable. Requesting *exactly* AssetsAvailable post-fix - // would currently fail with tecINSUFFICIENT_FUNDS due to the - // round-to-nearest used by assetsToSharesWithdraw (the - // recomputed payout can overshoot the request by a few ULPs). - // The "force payout to AssetsAvailable" branch in doApply - // only triggers when every share is burned, which is covered - // by the loan-repayment test. - STAmount const requestAssets = - withFix ? asset(1000).value() : STAmount{asset.raw(), availableBefore}; - Vault const v{env}; - env(v.withdraw({ - .depositor = f.lender, - .id = vaultKey.key, - .amount = requestAssets, - }), - Ter(withFix ? TER{tesSUCCESS} : TER{tecINVARIANT_FAILED})); - env.close(); - - auto const vaultAfter = env.le(vaultKey); - if (!BEAST_EXPECT(vaultAfter)) - return; - auto const issuanceAfter = env.le(keylet::mptIssuance(f.shareAsset)); - if (!BEAST_EXPECT(issuanceAfter)) - return; - - std::uint64_t const sharesAfter = issuanceAfter->getFieldU64(sfOutstandingAmount); - Number const availableAfter = vaultAfter->at(sfAssetsAvailable); - Number const totalAfter = vaultAfter->at(sfAssetsTotal); - Number const lossAfter = vaultAfter->at(sfLossUnrealized); - - if (!withFix) - { - // Pre-fix: rejected — vault state unchanged. - BEAST_EXPECT(sharesAfter == f.sharesLender); - BEAST_EXPECT(availableAfter == availableBefore); - BEAST_EXPECT(totalAfter == totalBefore); - BEAST_EXPECT(lossAfter == lossBefore); - return; - } - - // Post-fix exact-value derivation (fixture: sharesLender=5e9, - // totalBefore=6666.5, request=1000): - // sharesRedeemed = round(sharesLender * request / totalBefore) - // = round(750,018,750.469) = 750,018,750 - // received = totalBefore * sharesRedeemed / sharesLender - // = 999.999999375 (slightly under 1,000 due to - // integer-share rounding) - constexpr std::uint64_t kExpectedSharesRedeemed = 750'018'750; - Number const expectedReceived = - totalBefore * Number(kExpectedSharesRedeemed) / Number(f.sharesLender); - - BEAST_EXPECT(sharesAfter == f.sharesLender - kExpectedSharesRedeemed); - - // LossUnrealized is unchanged: the loan-protocol side is untouched. - BEAST_EXPECT(lossAfter == lossBefore); - - // The entire (total - available) gap is the impaired receivable, - // i.e. equal to lossUnrealized. - BEAST_EXPECT(totalAfter - availableAfter == lossAfter); - - STAmount const lenderBalanceAfter = env.balance(f.lender, asset); - Number const received{lenderBalanceAfter - lenderBalanceBefore}; - BEAST_EXPECT(received == expectedReceived); - - // Conservation: assets removed from the vault equal what the - // depositor received. - BEAST_EXPECT(totalBefore - totalAfter == received); - BEAST_EXPECT(availableBefore - availableAfter == received); - } - - // Sole shareholder attempts to burn ALL outstanding shares via - // fixed-shares input while the vault still holds an impaired - // receivable. Pre-fix this fails with the zero-sized-vault invariant - // violation. Post-fix the full-price rate causes assetsWithdrawn to - // equal assetsTotal, which exceeds assetsAvailable, so the transaction - // is rejected with tecINSUFFICIENT_FUNDS. - void - testWithdrawSoleShareholderFullSharesRejected(FeatureBitset features) - { - using namespace test::jtx; - - bool const withFix = features[fixCleanup3_2_0]; - testcase( - std::string{"Vault withdraw: sole shareholder full-shares " - "burn is rejected while loss outstanding"} + - (withFix ? " (fixCleanup3_2_0)" : " (pre-fix)")); - - Env env(*this, features); - auto const f = setupStuckDepositor(env); - if (!f.vaultKeylet || f.sharesLender == 0) - { - BEAST_EXPECT(false); - return; - } - Keylet const& vaultKey = *f.vaultKeylet; - - auto const vaultBefore = env.le(vaultKey); - if (!BEAST_EXPECT(vaultBefore)) - return; - Number const availableBefore = vaultBefore->at(sfAssetsAvailable); - Number const totalBefore = vaultBefore->at(sfAssetsTotal); - Number const lossBefore = vaultBefore->at(sfLossUnrealized); - - // Fixed-shares input: ask for ALL outstanding shares. - STAmount const shareAmt{MPTIssue{f.shareAsset}, Number(f.sharesLender)}; - Vault const v{env}; - env(v.withdraw({ - .depositor = f.lender, - .id = vaultKey.key, - .amount = shareAmt, - }), - Ter(withFix ? TER{tecINSUFFICIENT_FUNDS} : TER{tecINVARIANT_FAILED})); - env.close(); - - // Either way the transaction was rejected; vault state unchanged. - auto const vaultAfter = env.le(vaultKey); - if (!BEAST_EXPECT(vaultAfter)) - return; - auto const issuanceAfter = env.le(keylet::mptIssuance(f.shareAsset)); - if (!BEAST_EXPECT(issuanceAfter)) - return; - BEAST_EXPECT(issuanceAfter->getFieldU64(sfOutstandingAmount) == f.sharesLender); - BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == availableBefore); - BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == totalBefore); - BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == lossBefore); - } - - // Post-fix end-to-end resolution: after the sole-shareholder partial - // exit, the loan is repaid in full. With unrealized loss cleared and - // all assets back as cash, the depositor can burn all remaining - // shares and fully exit the vault. The final withdrawal hits the - // "force payout to assetsAvailable" branch in doApply. - void - testWithdrawSoleShareholderLoanRepaymentExit() - { - using namespace test::jtx; - using namespace loan; - - testcase( - "Vault withdraw: sole shareholder fully exits after impaired " - "loan is repaid (fixCleanup3_2_0)"); - - Env env(*this, all_ | fixCleanup3_2_0); - auto const f = setupStuckDepositor(env); - if (!f.vaultKeylet || !f.asset || !f.loanKeylet || f.sharesLender == 0) - { - BEAST_EXPECT(false); - return; - } - Keylet const& vaultKey = *f.vaultKeylet; - Keylet const& loanKey = *f.loanKeylet; - PrettyAsset const& asset = *f.asset; - - Vault const v{env}; - - // Sole-shareholder partial exit (see comment in - // testWithdrawSoleShareholderFixedAssetExit for why we request - // less than full AssetsAvailable). - { - STAmount const requestAssets = asset(1000).value(); - env(v.withdraw({ - .depositor = f.lender, - .id = vaultKey.key, - .amount = requestAssets, - }), - Ter(tesSUCCESS)); - env.close(); - } - - // Confirm the "dormant-but-alive" state from the design doc. The - // partial exit burned exactly 750,018,750 shares (see derivation - // in testWithdrawSoleShareholderFixedAssetExit). - auto const tokenAfterExit = env.le(keylet::mptoken(f.shareAsset, f.lender.id())); - if (!BEAST_EXPECT(tokenAfterExit)) - return; - std::uint64_t const retainedShares = tokenAfterExit->getFieldU64(sfMPTAmount); - BEAST_EXPECT(retainedShares == f.sharesLender - 750'018'750); - - // Borrower repays the loan in full (pays more than the outstanding - // total; the loan transactor caps the receivable). - env(pay(f.borrower, loanKey.key, asset(kStuckPrincipal * 2)), Ter(tesSUCCESS)); - env.close(); - - auto const vaultAfterRepay = env.le(vaultKey); - if (!BEAST_EXPECT(vaultAfterRepay)) - return; - // Repayment converts the 3,333 receivable back to cash; assetsTotal - // is unchanged but assetsAvailable jumps by exactly the same amount, - // and lossUnrealized clears to zero. - BEAST_EXPECT(vaultAfterRepay->at(sfLossUnrealized) == beast::kZero); - BEAST_EXPECT(vaultAfterRepay->at(sfAssetsAvailable) == vaultAfterRepay->at(sfAssetsTotal)); - - STAmount const lenderBalanceBeforeFinal = env.balance(f.lender, asset); - Number const availableBeforeFinal = vaultAfterRepay->at(sfAssetsAvailable); - - // Burn all remaining shares — the clean-state preconditions of - // the "final withdrawal" guard are now satisfied. - STAmount const allShares{MPTIssue{f.shareAsset}, Number(retainedShares)}; - env(v.withdraw({ - .depositor = f.lender, - .id = vaultKey.key, - .amount = allShares, - }), - Ter(tesSUCCESS)); - env.close(); - - auto const vaultFinal = env.le(vaultKey); - if (!BEAST_EXPECT(vaultFinal)) - return; - auto const issuanceFinal = env.le(keylet::mptIssuance(f.shareAsset)); - if (!BEAST_EXPECT(issuanceFinal)) - return; - - // Zero-sized vault invariant satisfied: 0 shares, 0 assets. - BEAST_EXPECT(issuanceFinal->getFieldU64(sfOutstandingAmount) == 0); - BEAST_EXPECT(vaultFinal->at(sfAssetsTotal) == beast::kZero); - BEAST_EXPECT(vaultFinal->at(sfAssetsAvailable) == beast::kZero); - BEAST_EXPECT(vaultFinal->at(sfLossUnrealized) == beast::kZero); - - // The final payout equals exactly the AssetsAvailable that - // existed before the call (the "force payout" branch). - STAmount const lenderBalanceAfter = env.balance(f.lender, asset); - Number const finalReceived{lenderBalanceAfter - lenderBalanceBeforeFinal}; - BEAST_EXPECT(finalReceived == availableBeforeFinal); - } - - // Clean-state regression: with no impaired loan, a sole shareholder - // burning all their shares fully empties the vault under both the - // pre-fix and post-fix code paths. Confirms the new logic doesn't - // break the existing happy-path close-out. - void - testWithdrawSoleShareholderCleanVaultUnaffected(FeatureBitset features) - { - using namespace test::jtx; - - bool const withFix = features[fixCleanup3_2_0]; - testcase( - std::string{"Vault withdraw: sole shareholder clean-state " - "close-out unchanged"} + - (withFix ? " (fixCleanup3_2_0)" : " (pre-fix)")); - - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - - env.fund(XRP(kStuckFunding), issuer, lender); - env.close(); - - PrettyAsset const asset = issuer[iouCurrency_]; - env(trust(lender, asset(10'000'000))); - env.close(); - env(pay(issuer, lender, asset(kStuckDepositorIOU))); - env.close(); - - // Sole shareholder of a clean vault — no loan broker needed. - Vault const v{env}; - auto [createTx, vaultKeylet] = v.create({.owner = lender, .asset = asset}); - env(createTx); - env.close(); - - env(v.deposit({ - .depositor = lender, - .id = vaultKeylet.key, - .amount = asset(kStuckDeposit), - }), - Ter(tesSUCCESS)); - env.close(); - - auto const vaultBefore = env.le(vaultKeylet); - if (!BEAST_EXPECT(vaultBefore)) - return; - auto const shareAsset = vaultBefore->at(sfShareMPTID); - auto const tokenLender = env.le(keylet::mptoken(shareAsset, lender.id())); - if (!BEAST_EXPECT(tokenLender)) - return; - std::uint64_t const sharesLender = tokenLender->getFieldU64(sfMPTAmount); - - // Sole shareholder, no loans, no loss. Burn everything. - STAmount const allShares{MPTIssue{shareAsset}, Number(sharesLender)}; - env(v.withdraw({ - .depositor = lender, - .id = vaultKeylet.key, - .amount = allShares, - }), - Ter(tesSUCCESS)); - env.close(); - - auto const vaultFinal = env.le(vaultKeylet); - if (!BEAST_EXPECT(vaultFinal)) - return; - auto const issuanceFinal = env.le(keylet::mptIssuance(shareAsset)); - if (!BEAST_EXPECT(issuanceFinal)) - return; - BEAST_EXPECT(issuanceFinal->getFieldU64(sfOutstandingAmount) == 0); - BEAST_EXPECT(vaultFinal->at(sfAssetsTotal) == beast::kZero); - BEAST_EXPECT(vaultFinal->at(sfAssetsAvailable) == beast::kZero); - BEAST_EXPECT(vaultFinal->at(sfLossUnrealized) == beast::kZero); - - // (Pre-fix path takes the regular code path; post-fix path enters - // the new final-withdrawal guard, which forces payout to exactly - // assetsAvailable. Either way the result is identical for a clean - // vault.) - (void)withFix; - } - - // Sole shareholder in an impaired vault redeems a *partial* count of - // shares via fixed-shares input. Pre-fix the discounted formula is - // used; post-fix the full-price formula is used (waiveUnrealizedLoss - // = Yes). The relative payout therefore differs, and post-fix the - // depositor recovers proportionally more of the residual cash for - // the shares burned. In both cases the vault is left in a valid - // (non-empty) state. - void - testWithdrawSoleShareholderPartialFixedSharesUsesFullPrice() - { - using namespace test::jtx; - - testcase( - "Vault withdraw: sole-shareholder partial fixed-shares uses " - "full-price rate (fixCleanup3_2_0)"); - - Env env(*this, all_ | fixCleanup3_2_0); - auto const f = setupStuckDepositor(env); - if (!f.vaultKeylet || !f.asset || f.sharesLender == 0) - { - BEAST_EXPECT(false); - return; - } - Keylet const& vaultKey = *f.vaultKeylet; - PrettyAsset const& asset = *f.asset; - - auto const vaultBefore = env.le(vaultKey); - if (!BEAST_EXPECT(vaultBefore)) - return; - Number const totalBefore = vaultBefore->at(sfAssetsTotal); - Number const availableBefore = vaultBefore->at(sfAssetsAvailable); - Number const lossBefore = vaultBefore->at(sfLossUnrealized); - - // Burn exactly half of the outstanding shares. - std::uint64_t const halfShares = f.sharesLender / 2; - STAmount const halfAmt{MPTIssue{f.shareAsset}, Number(halfShares)}; - - STAmount const lenderBalanceBefore = env.balance(f.lender, asset); - - Vault const v{env}; - env(v.withdraw({ - .depositor = f.lender, - .id = vaultKey.key, - .amount = halfAmt, - }), - Ter(tesSUCCESS)); - env.close(); - - // Expected payout under the full-price formula: - // assets = totalBefore * halfShares / sharesLender - // which (with halfShares == sharesLender/2) is roughly - // totalBefore / 2. - STAmount const lenderBalanceAfter = env.balance(f.lender, asset); - Number const received{lenderBalanceAfter - lenderBalanceBefore}; - Number const expected = totalBefore * Number(halfShares) / Number(f.sharesLender); - BEAST_EXPECT(received == expected); - - // The full-price payout exceeds the discounted formula by exactly - // lossBefore * halfShares / sharesLender — that's the whole point - // of the waive. - Number const discounted = - (totalBefore - lossBefore) * Number(halfShares) / Number(f.sharesLender); - Number const expectedDelta = lossBefore * Number(halfShares) / Number(f.sharesLender); - BEAST_EXPECT(received - discounted == expectedDelta); - - auto const vaultAfter = env.le(vaultKey); - if (!BEAST_EXPECT(vaultAfter)) - return; - auto const issuanceAfter = env.le(keylet::mptIssuance(f.shareAsset)); - if (!BEAST_EXPECT(issuanceAfter)) - return; - - // Vault remains valid: half the shares remain, lossUnrealized - // is untouched, and the entire (total - available) gap is still - // the impaired receivable. - BEAST_EXPECT( - issuanceAfter->getFieldU64(sfOutstandingAmount) == f.sharesLender - halfShares); - BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == totalBefore - received); - BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == lossBefore); - BEAST_EXPECT( - vaultAfter->at(sfAssetsTotal) - vaultAfter->at(sfAssetsAvailable) == - vaultAfter->at(sfLossUnrealized)); - - // Conservation: vault delta matches the depositor's gain. - BEAST_EXPECT(totalBefore - vaultAfter->at(sfAssetsTotal) == received); - BEAST_EXPECT(availableBefore - vaultAfter->at(sfAssetsAvailable) == received); - } - - // Bug: DeltaInfo::makeDelta uses max(scale(after), scale(before)) for the - // sfAssetsTotal and sfAssetsAvailable deltas, and visitEntry applies the - // same max() for the vault pseudo-account RippleState. When - // sfAssetsTotal sits exactly at 1e16 (IOU exponent 1, ULP = 10) and a - // withdrawal of 5 USD brings it to 9.999...995e15 (IOU exponent 0, - // ULP = 1), all three computations pick the anterior coarser scale 1. - // roundToAsset(-5, scale=1) collapses to 0, so the invariant check - // vaultPseudoDeltaAssets >= kZero fires even though the state change is - // valid and fully consistent at IOU precision. - // - // Fix (fixCleanup3_2_0): finalize compares the vault pseudo-account and - // sfAssetsTotal/Available deltas directly in Number space, bypassing - // scale-coarsened rounding. - void - testBugMakeDeltaAnteriorScale() - { - using namespace test::jtx; - - auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - - env.fund(XRP(100'000), issuer, alice); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - // Trust limit of 2e16, fund exactly 1e16 so deposit lands at the - // IOU scale-1 boundary (exponent 1, ULP = 10). - STAmount const fundAndDeposit{usd.raw(), Number{1, 16}}; - - env(trust(alice, STAmount{usd.raw(), 2, 16})); - env.close(); - env(pay(issuer, alice, fundAndDeposit)); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - - // sfAssetsTotal = sfAssetsAvailable = 1e16 (exponent 1, ULP = 10). - env(vault.deposit( - {.depositor = alice, .id = vaultKeylet.key, .amount = fundAndDeposit})); - env.close(); - - // Withdraw 5 USD: -5 is sub-ULP at the anterior scale (ULP = 10) - // but exact at the posterior scale (ULP = 1). The state change is - // consistent; only the invariant's scale selection is wrong. - env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(5)}), - Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultWithdraw across IOU scale boundary fires invariant " - "(pre-fixCleanup3_2_0)"); - runScenario(testableAmendments() - fixCleanup3_2_0, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultWithdraw across IOU scale boundary succeeds " - "(post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), tesSUCCESS); - } - } - - // Bug: DeltaInfo::makeDelta uses max(scale(after), scale(before)) for - // sfAssetsTotal/Available deltas. This is symmetric to - // testBugMakeDeltaAnteriorScale but in the opposite direction: a deposit - // pushes assetsTotal from just below 1e16 (IOU exponent 0, ULP = 1) to just - // above it (exponent 1, ULP = 10). makeDelta picks the coarser *posterior* - // scale 1. The trust line balance rounds from atEdge + 2 = 10,000,000,000,000,001 - // → 1e16, so the pseudo-account delta is only +1 in IOU space. - // roundToAsset(+1, scale=1) = 0 fires "deposit must increase vault balance" - // even though the state change is consistent at every precision boundary. - // - // Fix (fixCleanup3_2_0): computeVaultMinScale uses the posterior Number-space - // scale of sfAssetsTotal (which retains the full value 10,000,000,000,000,001, - // exponent 0), giving minScale = 0. roundToAsset(+1, scale=0) = 1 > 0 and - // the invariant passes. However the transactor's own precision guard fires - // first (bob pays 2 USD, vault receives only 1 due to IOU rounding), so the - // post-amendment result is tecPRECISION_LOSS rather than tesSUCCESS — - // the depositor is protected from silently losing 1 USD to rounding. - void - testBugMakeDeltaPosteriorScale() - { - using namespace test::jtx; - - auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(100'000), issuer, alice, bob); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - // atEdge is the largest IOU value with exponent 0 (ULP = 1). - // A deposit of 2 USD brings assetsTotal to 10,000,000,000,000,001 - // in Number space, crossing the 1e16 boundary in IOU space. - STAmount const atEdge{usd.raw(), Number{9'999'999'999'999'999LL}}; - - env(trust(alice, STAmount{usd.raw(), 2, 16})); - env(trust(bob, usd(100))); - env.close(); - env(pay(issuer, alice, atEdge)); - env(pay(issuer, bob, usd(2))); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - - // sfAssetsTotal = sfAssetsAvailable = atEdge (exponent 0, ULP = 1) - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = atEdge})); - env.close(); - - // Deposit 2 USD: +2 is sub-ULP at the posterior IOU scale (ULP = 10) - // but exact at the Number scale retained by sfAssetsTotal. - env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = usd(2)}), - Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultDeposit across IOU scale boundary fires invariant " - "(pre-fixCleanup3_2_0)"); - runScenario(testableAmendments() - fixCleanup3_2_0, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultDeposit across IOU scale boundary succeeds " - "(post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), tecPRECISION_LOSS); - } - } - - // Bug: ValidVault::visitEntry computes destinationDelta.scale as - // max(before_exponent, after_exponent) for RippleState entries. When a - // withdrawal credits a destination whose IOU balance sits just below a - // power-of-10 boundary (atEdge = 9'999'999'999'999'999), the post-credit - // STAmount rounds up one exponent (exponent 0 → 1), making - // destinationDelta.scale = 1. The invariant then calls - // roundToAsset(+2 USD, scale=1) = 0 and incorrectly fires - // "withdrawal must increase destination balance". - // - // Fix (fixCleanup3_2_0): finalize compares destination delta directly in - // Number space, bypassing scale-coarsened rounding. The transaction - // itself succeeds because the effective IOU credit is non-trivial at - // Number precision even though the STAmount exponent shifted. - void - testVaultWithdrawCanonicalizeToZero() - { - using namespace test::jtx; - - enum class DestKind : bool { ThirdParty = false, Self = true }; - - auto runScenario = [this](FeatureBitset features, DestKind destKind, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(100'000), issuer, alice, bob); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - STAmount const aliceLimit{usd.raw(), 2, 16}; - STAmount const bobLimit{usd.raw(), 2, 16}; - STAmount const atEdge{usd.raw(), Number{9'999'999'999'999'999LL}}; - - env(trust(alice, aliceLimit)); - if (destKind == DestKind::ThirdParty) - env(trust(bob, bobLimit)); - env.close(); - - env(pay(issuer, alice, usd(1'000))); - if (destKind == DestKind::ThirdParty) - env(pay(issuer, bob, atEdge)); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1'000)})); - env.close(); - - // For the self-destination case, push alice's own trust line to - // the IOU edge so the next withdraw inflow crosses the boundary. - if (destKind == DestKind::Self) - { - env(pay(issuer, alice, atEdge)); - env.close(); - } - - auto tx = vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(2)}); - if (destKind == DestKind::ThirdParty) - tx[sfDestination] = bob.human(); - env(tx, Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultWithdraw to third-party at IOU edge fires invariant " - "(pre-fixCleanup3_2_0)"); - runScenario( - testableAmendments() - fixCleanup3_2_0, DestKind::ThirdParty, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultWithdraw to third-party at IOU edge succeeds " - "(post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), DestKind::ThirdParty, tesSUCCESS); - } - { - testcase( - "bug: VaultWithdraw to self at IOU edge fires invariant " - "(pre-fixCleanup3_2_0)"); - runScenario( - testableAmendments() - fixCleanup3_2_0, DestKind::Self, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultWithdraw to self at IOU edge succeeds " - "(post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), DestKind::Self, tesSUCCESS); - } - } - - // Bug: the equality check (vault outflow == destination inflow) was - // skipped whenever the destination delta rounded to zero at localMinScale, - // including cases where the vault outflow rounded to a non-zero value and - // a representable amount of value was genuinely destroyed. - // - // Scenario: Bob's IOU balance sits 5 units below the 10^16 STAmount - // precision boundary (atEdge2 = 9,999,999,999,999,995). A withdrawal of - // 6 USD shifts his balance across that boundary: the exponent increments - // (0 → 1), so his effective inflow in Number space is only +5 — 1 USD is - // consumed by the precision-boundary rounding and cannot be credited. - // - // The destroyed amount (1 USD) is sub-ULP at destinationScale=1 (step=10), - // so the check treats it as an unavoidable IOU-precision artefact and - // lets the transaction succeed. - // - // Contrast: if 15 USD were destroyed at the same scale (destroyed ≥ step), - // floor(15/10)=1 ≠ 0 and the invariant would fire — that discrepancy IS - // representable and indicates a real accounting bug. - // - // Pre-fixCleanup3_2_0: the "must increase destination balance" check fires - // because roundedDestinationDelta = 0 ≤ 0. - void - testVaultWithdrawEqualityEnforced() - { - using namespace test::jtx; - - auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(100'000), issuer, alice, bob); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - STAmount const aliceLimit{usd.raw(), 2, 16}; - STAmount const bobLimit{usd.raw(), 2, 16}; - // Bob's balance sits 5 units below the 10^16 STAmount precision - // boundary. Receiving 6 USD shifts his exponent 0 → 1; the - // STAmount records +5, not +6 (1 USD is lost to rounding). - STAmount const atEdge2{usd.raw(), Number{9'999'999'999'999'995LL}}; - - env(trust(alice, aliceLimit)); - env(trust(bob, bobLimit)); - env.close(); - - env(pay(issuer, alice, usd(1'000))); - env(pay(issuer, bob, atEdge2)); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1'000)})); - env.close(); - - // Withdraw 6 USD to Bob: vault loses 6, Bob gains only 5. - // Destroyed amount = 1 USD, which is sub-ULP at destinationScale=1. - auto tx = vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(6)}); - tx[sfDestination] = bob.human(); - env(tx, Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultWithdraw to destination at IOU precision boundary fires " - "invariant (pre-fixCleanup3_2_0)"); - runScenario(testableAmendments() - fixCleanup3_2_0, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultWithdraw to destination at IOU precision boundary succeeds " - "when destroyed amount is sub-ULP (post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), tesSUCCESS); - } - } - - // Bug: when a depositor's IOU trustline balance is very large (e.g. - // ~1e17), adding a small deposit (e.g. 1 USD) leaves sfAssetsTotal - // unchanged at IOU precision because the increment is sub-ULP at the - // vault's current asset scale. The vault records the deposit, mints - // shares, and decrements the depositor's trustline, but sfAssetsTotal - // does not change — the conservation invariant fires because the rail - // delta is zero. - // - // Two sub-cases are exercised: - // 1. First-ever deposit into an empty vault: the depositor's own - // trustline has a large balance so 1 USD canonicalizes to zero - // when written back through the IOU rail. - // 2. Subsequent deposit after the vault already holds a large - // sfAssetsTotal: a different depositor (bob, with a small balance) - // sends 1 USD, which again rounds to zero at the vault's coarse - // asset scale. - // - // Fix (fixCleanup3_2_0): the deposit transactor checks whether - // roundToAsset(amount, vault_scale) == 0 and rejects early with - // tecPRECISION_LOSS before any state is modified. - void - testVaultDepositCanonicalizeToZero() - { - using namespace test::jtx; - auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - - env.fund(XRP(100'000), issuer, alice, bob); - env.close(); - - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - - STAmount const trustLimit{usd.raw(), Number{99'999'999'999'999'999LL}}; - STAmount const aliceFund{usd.raw(), Number{99'999'999'999'999'999LL}}; - - env(trust(alice, trustLimit)); - env(trust(bob, trustLimit)); - env.close(); - - env(pay(issuer, alice, aliceFund)); - env(pay(issuer, bob, usd(1000))); - env.close(); - - Vault const vault{env}; - - // Scale=0 so sfAssetsTotal stores whole USD - auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - - // Alice's deposit canonicalizes to zero at her own trustline scale - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1)}), - Ter(expected)); - - // Increase vault-scale - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = aliceFund})); - env.close(); - - env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = usd(1)}), - Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultDeposit below Vault precision canonicalized to zero " - "(pre-fixCleanup3_2_0)"); - runScenario(testableAmendments() - fixCleanup3_2_0, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultDeposit below Vault precision canonicalized to zero " - "(post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), tecPRECISION_LOSS); - } - } - - // VaultDeposit by issuer with the vault parked at the IOU 16-digit - // edge (9.999e15). Issuer mints 2 more USD; the vault trust line - // goes 9.999e15 → 10^16, gaining 1 unit instead of 2 (canonicalization). - // - // Pre-fixCleanup3_2_0: the proactive check is absent; the deposit - // applies, then VaultInvariant's "deposit must increase vault - // balance" assertion fires at finalize time on the rounded vault - // delta of zero, returning tecINVARIANT_FAILED. - // Post-amendment: reject deposit that is not representable at Vault scale. - void - testBugIssuerVaultDepositAtEdge() - { - using namespace test::jtx; - - auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); - - Account const issuer{"issuer"}; - Account const owner{"owner"}; - - env.fund(XRP(100'000), issuer, owner); - env.close(); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const usd{issuer["USD"]}; - STAmount const trustLimit{usd.raw(), 2, 16}; - STAmount const ownerFund{usd.raw(), Number{9'999'999'999'999'999LL}}; - - env(trust(owner, trustLimit)); - env.close(); - env(pay(issuer, owner, ownerFund)); - env.close(); - - Vault const vault{env}; - auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = usd}); - vaultTx[sfScale] = 0; - env(vaultTx); - env.close(); - env(vault.deposit({.depositor = owner, .id = vaultKeylet.key, .amount = ownerFund})); - env.close(); - - // Vault pseudo-account is now at 9.999e15. Issuer mints 2 - // more USD. Pre: tecINVARIANT_FAILED at finalize. Post: - // tecPRECISION_LOSS proactively. Either way, no value moves. - env(vault.deposit({.depositor = issuer, .id = vaultKeylet.key, .amount = usd(2)}), - Ter(expected)); - env.close(); - }; - - { - testcase( - "bug: VaultDeposit by issuer at IOU edge fires " - "tecINVARIANT_FAILED at finalize (pre-fixCleanup3_2_0)"); - runScenario(testableAmendments() - fixCleanup3_2_0, tecINVARIANT_FAILED); - } - { - testcase( - "bug: VaultDeposit by issuer at IOU edge rejects with " - "tecPRECISION_LOSS proactively (post-fixCleanup3_2_0)"); - runScenario(testableAmendments(), tecPRECISION_LOSS); - } - } - - void - testReferenceHolding() - { - using namespace test::jtx; - - auto readReferenceHolding = [&](Env const& env, - Keylet const& vaultKeylet) -> std::optional { - auto const sleVault = env.le(vaultKeylet); - if (!sleVault) - return std::nullopt; - auto const sleIssuance = env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); - if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) - return std::nullopt; - return sleIssuance->getFieldH256(sfReferenceHolding); - }; - - // Post-fixCleanup3_2_0: vault share carries sfReferenceHolding - // pointing to the vault pseudo's MPToken (for MPT-backed vaults) - // or RippleState (for IOU-backed vaults). - { - testcase("sfReferenceHolding: MPT-backed vault, post-amendment"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - auto const sleVault = env.le(keylet); - BEAST_EXPECT(sleVault != nullptr); - auto const pseudoId = sleVault->at(sfAccount); - auto const expected = keylet::mptoken(mptt.issuanceID(), pseudoId).key; - - auto const stored = readReferenceHolding(env, keylet); - BEAST_EXPECT(stored.has_value()); - BEAST_EXPECT(stored && *stored == expected); - // The pointed-to MPToken must actually exist. - BEAST_EXPECT(env.le(keylet::mptoken(mptt.issuanceID(), pseudoId)) != nullptr); - } - - { - testcase("sfReferenceHolding: IOU-backed vault, post-amendment"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const asset = issuer["IOU"]; - env.trust(asset(1'000'000), owner); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - auto const sleVault = env.le(keylet); - BEAST_EXPECT(sleVault != nullptr); - auto const pseudoId = sleVault->at(sfAccount); - auto const expected = keylet::line(pseudoId, asset.raw().get()).key; - - auto const stored = readReferenceHolding(env, keylet); - BEAST_EXPECT(stored.has_value()); - BEAST_EXPECT(stored && *stored == expected); - // The pointed-to RippleState must actually exist. - BEAST_EXPECT(env.le(keylet::line(pseudoId, asset.raw().get())) != nullptr); - } - - // XRP-backed vaults leave the field absent: XRP has no separate - // holding ledger entry and no transferability concept to inherit. - { - testcase("sfReferenceHolding: XRP-backed vault, field absent"); - Env env{*this, testableAmendments()}; - Account const owner{"owner"}; - env.fund(XRP(10'000), owner); - env.close(); - - PrettyAsset const asset{xrpIssue(), 1'000'000}; - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - BEAST_EXPECT(!readReferenceHolding(env, keylet).has_value()); - } - - // Pre-fixCleanup3_2_0: vault share has the field absent regardless - // of underlying type. - { - testcase("sfReferenceHolding: vault share, pre-amendment"); - Env env{*this, testableAmendments() - fixCleanup3_2_0}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - BEAST_EXPECT(!readReferenceHolding(env, keylet).has_value()); - } - - // Plain MPTokenIssuanceCreate (not a vault share) must never - // populate the field. Only the post-amendment case is - // interesting; pre-amendment nothing writes the field at all. - { - testcase("sfReferenceHolding: plain MPT issuance never set"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - env.fund(XRP(10'000), issuer); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - env.close(); - - auto const sleIssuance = env.le(keylet::mptIssuance(mptt.issuanceID())); - if (BEAST_EXPECT(sleIssuance)) - BEAST_EXPECT(!sleIssuance->isFieldPresent(sfReferenceHolding)); - } - } - - // Probe every transactor surface that might delete the vault pseudo- - // account's underlying holding (the MPToken or RippleState pointed to - // by sfReferenceHolding). Each scenario asserts either that the - // existing pseudo-account guards stop the deletion at preclaim, or - // that the ledger leaves the holding intact afterwards. This is a - // regression guard: if any of these guards regresses, the share's - // sfReferenceHolding pointer would dangle and the new ValidMPTIssuance - // invariant would catch it - but we want to fail much earlier, at - // the transactor's preclaim / doApply, not at invariant time. - void - testHoldingDeletionBlocked() - { - using namespace test::jtx; - - // Helper: read the share's referenced holding and confirm the - // pointed-to SLE still exists after the probe. - auto referencedHoldingExists = [&](Env const& env, Keylet const& vaultKeylet) -> bool { - auto const sleVault = env.le(vaultKeylet); - if (!sleVault) - return false; - auto const sleIssuance = env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); - if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) - return false; - auto const holdingKey = sleIssuance->getFieldH256(sfReferenceHolding); - return env.le(keylet::unchecked(holdingKey)) != nullptr; - }; - - // ---- MPT-backed vault ---------------------------------------- - { - testcase("vault pseudo MPToken: Clawback blocked by tecPSEUDO_ACCOUNT"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const depositor{"depositor"}; - env.fund(XRP(10'000), issuer, owner, depositor); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = depositor}); - env(pay(issuer, depositor, asset(1'000))); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(500)})); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - - Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; - // Issuer attempts to claw back the FULL underlying balance - // (500) directly from the vault pseudo-account. With the - // full amount, the doApply path would drain the pseudo's - // MPToken to zero and removeEmptyHolding would erase it - - // if doApply ever ran. SAV's pseudo-account guard at - // Clawback.cpp:201 refuses at preclaim with - // tecPSEUDO_ACCOUNT before any state change. - env(claw(issuer, asset(500), pseudoAccount), Ter{tecPSEUDO_ACCOUNT}); - env.close(); - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - // Sanity: pseudo's full balance is intact. - BEAST_EXPECT(env.balance(pseudoAccount, asset).number() == 500); - } - - { - testcase("vault pseudo MPToken: Issuer cannot Unauthorize pseudo"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = issuer, .holder = owner}); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - - auto const pseudoId = env.le(keylet)->at(sfAccount); - // Issuer attempts MPTokenAuthorize against the pseudo with - // tfMPTUnauthorize. MPTokenAuthorize.cpp blocks pseudo - // accounts via isPseudoAccount; the pseudo's MPToken is - // preserved. Construct the tx manually since the pseudo - // lacks a signing key, and the issuer-driven flavour is - // expressed via sfHolder. - json::Value jv; - jv[sfAccount] = issuer.human(); - jv[sfHolder] = toBase58(pseudoId); - jv[sfMPTokenIssuanceID] = to_string(mptt.issuanceID()); - jv[sfFlags] = tfMPTUnauthorize; - jv[sfTransactionType] = jss::MPTokenAuthorize; - env(jv, Ter{tecNO_PERMISSION}); - env.close(); - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - } - - { - testcase("vault pseudo MPToken: MPTokenIssuanceDestroy blocked while vault holds"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const depositor{"depositor"}; - env.fund(XRP(10'000), issuer, owner, depositor); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = depositor}); - env(pay(issuer, depositor, asset(1'000))); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(500)})); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - - // While the vault holds outstanding underlying, the issuer - // cannot destroy the issuance. tecHAS_OBLIGATIONS confirms - // the protection - and as a side effect, the share's - // sfReferenceHolding pointer cannot be left pointing at a - // ghost issuance. - mptt.destroy({.id = mptt.issuanceID(), .err = tecHAS_OBLIGATIONS}); - env.close(); - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - } - - // ---- IOU-backed vault ---------------------------------------- - { - testcase("vault pseudo trust line: Clawback blocked by tecPSEUDO_ACCOUNT"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env(fset(issuer, asfAllowTrustLineClawback)); - env.close(); - - PrettyAsset const asset = issuer["IOU"]; - env.trust(asset(1'000'000), owner); - env(pay(issuer, owner, asset(1'000))); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(500)})); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - - Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; - // Issuer attempts to claw back the FULL IOU balance (500) - // directly from the vault pseudo. With the full amount, the - // doApply path would drain the trust line to zero and (if - // both reserve flags clear) trustDelete would erase it - if - // doApply ever ran. The same SAV pseudo-account guard - // refuses at preclaim with tecPSEUDO_ACCOUNT. The amount's - // STAmount issuer field is the holder, per IOU clawback - // convention. - env(claw(issuer, pseudoAccount["IOU"](500)), Ter{tecPSEUDO_ACCOUNT}); - env.close(); - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - // Sanity: pseudo's full balance is intact. - BEAST_EXPECT(env.balance(pseudoAccount, asset).number() == 500); - } - - { - testcase("vault pseudo trust line: TrustSet limit=0 from issuer preserves line"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env(fset(issuer, asfDefaultRipple)); - env.close(); - - PrettyAsset const asset = issuer["IOU"]; - env.trust(asset(1'000'000), owner); - env(pay(issuer, owner, asset(1'000))); - env.close(); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(500)})); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - - // Issuer submits TrustSet with limit=0 against the vault - // pseudo. The pseudo's side of the line still has the - // original (non-zero) limit and a non-zero balance, so the - // line is preserved - even though the issuer cleared its - // own side. trustDelete only fires when both limits clear - // and the balance is zero. - Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; - env(trust(issuer, pseudoAccount["IOU"](0))); - env.close(); - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - } - - // ---- Positive control: VaultDelete is the only legitimate path - { - testcase("vault pseudo holding: VaultDelete is the legitimate cleanup path"); - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - env.fund(XRP(10'000), issuer, owner); - env.close(); - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - - Vault const vault{env}; - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - BEAST_EXPECT(referencedHoldingExists(env, keylet)); - auto const pseudoId = env.le(keylet)->at(sfAccount); - auto const sharedMptId = env.le(keylet)->at(sfShareMPTID); - auto const holdingKeylet = keylet::mptoken(mptt.issuanceID(), pseudoId); - - // VaultDelete tears down the vault pseudo's holding, the - // share issuance, and the pseudo-account itself. Invariant - // permits this because the tx is ttVAULT_DELETE. - env(vault.del({.owner = owner, .id = keylet.key})); - env.close(); - - BEAST_EXPECT(env.le(keylet) == nullptr); - BEAST_EXPECT(env.le(holdingKeylet) == nullptr); - BEAST_EXPECT(env.le(keylet::mptIssuance(sharedMptId)) == nullptr); - } - } - - // VaultDeposit::preclaim uses accountHolds(..., SpendableHandling:: - // shFULL_BALANCE), which for an IOU asset adds the counterparty's - // LowLimit/HighLimit to the depositor's raw balance (TokenHelpers.cpp: - // getTrustLineBalance with includeOppositeLimit=true). When the - // depositor's raw balance < deposit amount but raw + opposite limit >= - // amount, preclaim is satisfied. doApply then calls - // directSendNoFeeIOU, which unconditionally subtracts saAmount from - // saBalance — driving the trust line negative — and returns tesSUCCESS. - // The post-send sanity check uses the default shSIMPLE_BALANCE (no - // opposite-limit add), sees a negative balance, and returns tefINTERNAL. - void - testVaultDepositNegativeBalanceFromOppositeLimit() - { - auto runTest = [&](FeatureBitset f, TER expected) { - using namespace test::jtx; - using namespace std::literals; - - Env env{*this, f}; - Account const gw{"gateway"}; - Account const owner{"owner"}; - Account const depositor{"depositor"}; - - env.fund(XRP(10000), gw, owner, depositor); - env.close(); - - // Gateway with DefaultRipple so vault creation on its IOU works. - env(fset(gw, asfDefaultRipple)); - env.close(); - - // Depositor opens a trust line to gateway and receives a small - // balance. - PrettyAsset const usd = gw["USD"]; - env.trust(usd(1000), depositor); - env(pay(gw, depositor, usd(100))); // raw trust-line balance: 100 - env.close(); - - // Key precondition: gateway sets a non-zero limit on the same - // RippleState — the "opposite field" from depositor's perspective. - // This is what inflates shFULL_BALANCE in preclaim above the raw - // balance. - env(trust(gw, depositor["USD"](1000))); - env.close(); - - // Create the IOU vault. - Vault const vault{env}; - auto [vaultTx, keylet] = vault.create({.owner = owner, .asset = usd}); - env(vaultTx); - env.close(); - - // Submit a deposit of 500 USD: - // - raw balance: 100 USD - // - opposite limit (gw's side): 1000 USD - // - preclaim sees 100 + 1000 = 1100, passes (>= 500) - // - doApply transfers 500, depositor's trust-line balance - // becomes -400 - // - sanity check at VaultDeposit.cpp:256 fires - // - tx returns tefINTERNAL (BUG — should be tesSUCCESS. - auto depositTx = - vault.deposit({.depositor = depositor, .id = keylet.key, .amount = usd(500)}); - env(depositTx, Ter(expected)); - env.close(); - }; - - { - testcase( - "IOU vault deposit exceeding depositor's balance but " - "within counterparty's trust limit, pre-fixCleanup3_2_0 " - "(tefINTERNAL)"); - runTest(test::jtx::testableAmendments() - fixCleanup3_2_0, tefINTERNAL); - } - { - testcase( - "IOU vault deposit exceeding depositor's balance but " - "within counterparty's trust limit, post-fixCleanup3_2_0 " - "(tesSUCCESS)"); - runTest(test::jtx::testableAmendments(), tesSUCCESS); - } - } - public: void run() override { - testVaultWithdrawEqualityEnforced(); - testBugIssuerVaultDepositAtEdge(); - testBugMakeDeltaPosteriorScale(); - testBugMakeDeltaAnteriorScale(); - testVaultDepositCanonicalizeToZero(); - testVaultWithdrawCanonicalizeToZero(); - testVaultDepositNegativeBalanceFromOppositeLimit(); testSequences(); testPreflight(); testCreateFailXRP(); @@ -8047,18 +6163,6 @@ public: testAssetsMaximum(); testBug6LimitBypassWithShares(); testRemoveEmptyHoldingLockedAmount(); - - testWithdrawSoleShareholderFixedAssetExit(all_ - fixCleanup3_2_0); - testWithdrawSoleShareholderFixedAssetExit(all_); - testWithdrawSoleShareholderFullSharesRejected(all_ - fixCleanup3_2_0); - testWithdrawSoleShareholderFullSharesRejected(all_); - testWithdrawSoleShareholderCleanVaultUnaffected(all_ - fixCleanup3_2_0); - testWithdrawSoleShareholderCleanVaultUnaffected(all_); - testWithdrawSoleShareholderPartialFixedSharesUsesFullPrice(); - testWithdrawSoleShareholderLoanRepaymentExit(); - - testReferenceHolding(); - testHoldingDeletionBlocked(); } }; diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index de80444f2e..a8899e4e43 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -69,7 +69,7 @@ struct SEnv std::unique_ptr config, FeatureBitset features, std::unique_ptr logs = nullptr, - beast::Severity thresh = beast::Severity::Error) + beast::severities::Severity thresh = beast::severities::KError) : env(s, std::move(config), features, std::move(logs), thresh) { } @@ -150,18 +150,18 @@ struct SEnv return env.current()->fees().base; } - SLE::const_pointer + std::shared_ptr account(jtx::Account const& account) { return env.le(account); } - SLE::const_pointer + std::shared_ptr bridge(json::Value const& jvb) { STXChainBridge const b(jvb); - auto tryGet = [&](STXChainBridge::ChainType ct) -> SLE::const_pointer { + auto tryGet = [&](STXChainBridge::ChainType ct) -> std::shared_ptr { if (auto r = env.le(keylet::bridge(b, ct))) { if ((*r)[sfXChainBridge] == b) @@ -186,13 +186,13 @@ struct SEnv return (*bridge(jvb))[sfXChainClaimID]; } - SLE::const_pointer + std::shared_ptr claimID(json::Value const& jvb, std::uint64_t seq) { return env.le(keylet::xChainClaimID(STXChainBridge(jvb), seq)); } - SLE::const_pointer + std::shared_ptr caClaimID(json::Value const& jvb, std::uint64_t seq) { return env.le(keylet::xChainCreateAccountClaimID(STXChainBridge(jvb), seq)); @@ -231,7 +231,7 @@ struct XEnv : public jtx::XChainBridgeObjects, public SEnv this->fund(xrpFunds, s.account); // Signer's list must match the attestation signers - // env_(jtx::signers(Account::kMaster, quorum, signers)); + // env_(jtx::signers(Account::kMASTER, quorum, signers)); } this->close(); } @@ -266,8 +266,8 @@ struct BalanceTransfer balance from; balance to; - balance payer; // pays the rewards - std::vector rewardAccounts; // receives the reward + balance payer; // pays the rewards + std::vector reward_accounts; // receives the reward XRPAmount txFees; BalanceTransfer( @@ -281,7 +281,7 @@ struct BalanceTransfer : from(env, fromAcct) , to(env, toAcct) , payer(env, payer) - , rewardAccounts([&]() { + , reward_accounts([&]() { std::vector r; r.reserve(numPayees); for (size_t i = 0; i < numPayees; ++i) @@ -306,7 +306,7 @@ struct BalanceTransfer [[nodiscard]] bool payeesReceived(STAmount const& reward) const { - return std::all_of(rewardAccounts.begin(), rewardAccounts.end(), [&](balance const& b) { + return std::all_of(reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { return b.diff() == reward; }); } @@ -320,7 +320,7 @@ struct BalanceTransfer bool hasHappened(STAmount const& amt, STAmount const& reward, bool checkPayer = true) { - auto rewardCost = multiply(reward, STAmount(rewardAccounts.size()), reward.asset()); + auto rewardCost = multiply(reward, STAmount(reward_accounts.size()), reward.asset()); return checkMostBalances(amt, reward) && (!checkPayer || payer.diff() == -(rewardCost + txFees)); } @@ -500,7 +500,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // disabled. { Env env(*this, testableAmendments() - featureXChainBridge); - env(createBridge(Account::kMaster, jvb), Ter(temDISABLED)); + env(createBridge(Account::kMASTER, jvb), Ter(temDISABLED)); } // coverage test: BridgeCreate::preclaim() returns tecNO_ISSUER. @@ -772,7 +772,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj "Issuing chain is XRP and issuing chain door account is " "the root account ", [&](auto& env, bool) { - b = Account::kMaster; + b = Account::kMASTER; ib = xrpIssue(); })}; @@ -974,8 +974,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -987,11 +987,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -1007,7 +1007,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj scEnv.tx(xchainClaim(scAlice, jvb, claimID, amt, scBob)).close(); } - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); } // Check that the reward paid from a claim Id was the reward when @@ -1020,8 +1020,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1033,15 +1033,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // Now modify the reward on the bridge mcEnv.tx(bridgeModify(mcDoor, jvb, XRP(2), XRP(10))).close(); - scEnv.tx(bridgeModify(Account::kMaster, jvb, XRP(2), XRP(10))).close(); + scEnv.tx(bridgeModify(Account::kMASTER, jvb, XRP(2), XRP(10))).close(); BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -1059,7 +1059,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // make sure the reward accounts indeed received the original // split reward (1 split 5 ways) instead of the updated 2 XRP. - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); } // Check that the signatures used to verify attestations and decide @@ -1073,8 +1073,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1086,15 +1086,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // change signers - claim should not be processed is the batch // is signed by original signers - scEnv.tx(jtx::signers(Account::kMaster, quorum, altSigners)).close(); + scEnv.tx(jtx::signers(Account::kMASTER, quorum, alt_signers)).close(); BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); // submit claim using outdated signers - should fail @@ -1120,7 +1120,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // submit claim using current signers - should succeed scEnv .multiTx(claimAttestations( - scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, altSigners)) + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, alt_signers)) .close(); if (withClaim) { @@ -1132,7 +1132,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // make sure the transfer went through as we sent attestations // using new signers - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum, false)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum, false)); } // coverage test: bridge_modify transaction with incorrect flag @@ -1191,7 +1191,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // normal bridge create for sanity check with the exact necessary // account balance XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .fund(res1, scuAlice) // acct reserve + 1 object .close() .tx(xchainCreateClaimId(scuAlice, jvb, reward, mcAlice)) @@ -1203,7 +1203,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj test::Balance const scAliceBal(xenv, scAlice); - xenv.tx(createBridge(Account::kMaster, jvb)) + xenv.tx(createBridge(Account::kMASTER, jvb)) .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1219,8 +1219,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // Creating the new object would put the account below the reserve XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) - .fund(res1 - xrpDust, scuAlice) // barely not enough + .tx(createBridge(Account::kMASTER, jvb)) + .fund(res1 - xrp_dust, scuAlice) // barely not enough .close() .tx(xchainCreateClaimId(scuAlice, jvb, reward, mcAlice), Ter(tecINSUFFICIENT_RESERVE)) .close(); @@ -1229,15 +1229,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // by giving the reward amount for the other side, as well as a // completely non-matching reward) XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .close() - .tx(xchainCreateClaimId(scAlice, jvb, splitRewardQuorum, mcAlice), + .tx(xchainCreateClaimId(scAlice, jvb, split_reward_quorum, mcAlice), Ter(tecXCHAIN_REWARD_MISMATCH)) .close(); // A reward amount that isn't XRP XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .close() .tx(xchainCreateClaimId(scAlice, jvb, mcUSD(1), mcAlice), Ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)) @@ -1246,7 +1246,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // coverage test: xchain_create_claim_id transaction with incorrect // flag XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice), Txflags(tfFillOrKill), @@ -1256,7 +1256,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // coverage test: xchain_create_claim_id transaction with xchain // feature disabled XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .disableFeature(featureXChainBridge) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice), Ter(temDISABLED)) @@ -1273,7 +1273,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj testcase("Commit"); // Commit to a non-existent bridge - XEnv(*this).tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), Ter(tecNO_ENTRY)); + XEnv(*this).tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), Ter(tecNO_ENTRY)); // check that reward not deducted when doing the commit { @@ -1309,17 +1309,17 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // reserve (if XRP) XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + oneXrp - xrpDust, mcuAlice) // barely not enough + .fund(res0 + one_xrp - xrp_dust, mcuAlice) // barely not enough .close() - .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); XEnv(*this) .tx(createBridge(mcDoor, jvb)) .fund( - res0 + oneXrp + xrpDust, // "xrp_dust" for tx fees - mcuAlice) // exactly enough => should succeed + res0 + one_xrp + xrp_dust, // "xrp_dust" for tx fees + mcuAlice) // exactly enough => should succeed .close() - .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob)); + .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob)); // Commit an amount above the account's balance (for both XRP and // IOUs) @@ -1327,7 +1327,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj .tx(createBridge(mcDoor, jvb)) .fund(res0, mcuAlice) // barely not enough .close() - .tx(xchainCommit(mcuAlice, jvb, 1, res0 + oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, res0 + one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); auto jvbUsd = bridge(mcDoor, mcUSD, scGw, scUSD); @@ -1377,7 +1377,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv(*this) .tx(createBridge(mcDoor)) .close() - .tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), + .tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), Txflags(tfFillOrKill), Ter(temINVALID_FLAG)); @@ -1387,7 +1387,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj .tx(createBridge(mcDoor)) .disableFeature(featureXChainBridge) .close() - .tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), Ter(temDISABLED)); + .tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), Ter(temDISABLED)); } void @@ -1417,8 +1417,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1429,7 +1429,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj auto const amt = XRP(1000); mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); scEnv .multiTx(claimAttestations( @@ -1442,7 +1442,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimID, dst, signers, - kUtXchainDefaultQuorum)) + kUT_XCHAIN_DEFAULT_QUORUM)) .close(); scEnv .tx(claimAttestation( @@ -1450,11 +1450,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj jvb, mcAlice, amt, - payees[kUtXchainDefaultQuorum], + payees[kUT_XCHAIN_DEFAULT_QUORUM], true, claimID, dst, - signers[kUtXchainDefaultQuorum])) + signers[kUT_XCHAIN_DEFAULT_QUORUM])) .close(); if (withClaim) @@ -1467,7 +1467,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(scEnv.claimID(jvb) == claimID); } - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardEveryone)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_everyone)); } // Test that signature weights are correctly handled. Assign @@ -1483,12 +1483,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const quorum7 = 7; std::vector const signers = [] { - static constexpr int kNumSigners = 4; + constexpr int kNUM_SIGNERS = 4; std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account("signer_"s + std::to_string(i)); @@ -1499,8 +1499,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum7, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum7, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1513,7 +1513,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[0], 3, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[0], 3, withClaim); scEnv .multiTx(claimAttestations( @@ -1541,12 +1541,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const quorum7 = 7; std::vector const signers = [] { - static constexpr int kNumSigners = 4; + constexpr int kNUM_SIGNERS = 4; std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account("signer_"s + std::to_string(i)); @@ -1558,8 +1558,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum7, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum7, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1572,7 +1572,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[2], 2, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[2], 2, withClaim); scEnv .multiTx(claimAttestations( @@ -1600,12 +1600,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const quorum7 = 7; std::vector const signers = [] { - static constexpr int kNumSigners = 4; + constexpr int kNUM_SIGNERS = 4; std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account("signer_"s + std::to_string(i)); @@ -1616,8 +1616,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum7, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum7, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1630,7 +1630,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[0], 2, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[0], 2, withClaim); scEnv .multiTx(claimAttestations( @@ -1659,12 +1659,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const quorum7 = 7; std::vector const signers = [] { - static constexpr int kNumSigners = 4; + constexpr int kNUM_SIGNERS = 4; std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account("signer_"s + std::to_string(i)); @@ -1675,8 +1675,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum7, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum7, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -1690,7 +1690,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[1], 2, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[1], 2, withClaim); scEnv .multiTx(claimAttestations( @@ -1738,15 +1738,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(carol.diff() == -(amt + reward + fee)); } - scEnv.tx(createBridge(Account::kMaster, jvb, reward, XRP(20))) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, reward, XRP(20))) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); { // send first batch of account create attest for all 3 // account create test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(1, amt, scuAlice, 2)) .multiTx(attCreateAcctVec(3, amt, scuCarol, 2)) @@ -1767,7 +1767,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // complete attestations for 2nd account create => should // not complete test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(2, amt, scuBob, 3, 2)).close(); @@ -1783,7 +1783,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // complete attestations for 3rd account create => should // not complete test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(3, amt, scuCarol, 3, 2)).close(); @@ -1799,7 +1799,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // complete attestations for 1st account create => account // should be created test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(1, amt, scuAlice, 3, 1)).close(); @@ -1818,7 +1818,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // resend attestations for 3rd account create => still // should not complete test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(3, amt, scuCarol, 3, 2)).close(); @@ -1835,7 +1835,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // resend attestations for 2nd account create => account // should be created test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(2, amt, scuBob, 1)).close(); @@ -1851,7 +1851,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // resend attestations for 3rc account create => account // should be created test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(3, amt, scuCarol, 1)).close(); @@ -1885,12 +1885,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(carol.diff() == -(amtPlusReward + fee)); } - scEnv.tx(createBridge(Account::kMaster, jvb, reward, XRP(20))) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, reward, XRP(20))) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); scEnv.multiTx(attCreateAcctVec(1, amt, scuAlice, 2)).close(); BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present @@ -1926,12 +1926,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(carol.diff() == -(amtPlusReward + fee)); } - scEnv.tx(createBridge(Account::kMaster, jvb, reward, XRP(20))) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, reward, XRP(20))) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); test::Balance const alice(scEnv, scAlice); scEnv.multiTx(attCreateAcctVec(1, amt, scAlice, 2)).close(); @@ -1968,13 +1968,13 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(carol.diff() == -(amtPlusReward + fee)); } - scEnv.tx(createBridge(Account::kMaster, jvb, reward, XRP(20))) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, reward, XRP(20))) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .tx(fset("scAlice", asfDepositAuth)) // set deposit auth .close(); test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); test::Balance const alice(scEnv, scAlice); scEnv.multiTx(attCreateAcctVec(1, amt, scAlice, 2)).close(); @@ -2020,13 +2020,13 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj } std::uint32_t const redQuorum = 2; - scEnv.tx(createBridge(Account::kMaster, jvb, reward, XRP(20))) - .tx(jtx::signers(Account::kMaster, redQuorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, reward, XRP(20))) + .tx(jtx::signers(Account::kMASTER, redQuorum, signers)) .close(); { test::Balance const attester(scEnv, scAttester); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); auto const badAmt = XRP(10); std::uint32_t txCount = 0; @@ -2105,8 +2105,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // coverage test: add_attestation transaction with incorrect flag { XEnv scEnv(*this, true); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(claimAttestation( scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), @@ -2119,8 +2119,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // disabled { XEnv scEnv(*this, true); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .disableFeature(featureXChainBridge) .close() .tx(claimAttestation( @@ -2144,8 +2144,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2207,13 +2207,13 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj auto const amt = XRP(1000); std::uint32_t const claimID = 1; - for (auto i = 0; i < kUtXchainDefaultNumSigners - 2; ++i) - scEnv.fund(amt, altSigners[i].account); + for (auto i = 0; i < kUT_XCHAIN_DEFAULT_NUM_SIGNERS - 2; ++i) + scEnv.fund(amt, alt_signers[i].account); mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, altSigners)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, alt_signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2225,30 +2225,30 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { // G1: master key auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, altSigners[0]); + 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(altSigners[1].account, altSigners[0].account)).close(); + scEnv.tx(jtx::regkey(alt_signers[1].account, alt_signers[0].account)).close(); auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, altSigners[0]); - att[sfAttestationSignerAccount.getJsonName()] = altSigners[1].account.human(); + 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 = altSigners[kUtXchainDefaultNumSigners - 1]; - auto const unfundedSigner2 = altSigners[kUtXchainDefaultNumSigners - 2]; + auto const unfundedSigner1 = alt_signers[kUT_XCHAIN_DEFAULT_NUM_SIGNERS - 1]; + auto const unfundedSigner2 = alt_signers[kUT_XCHAIN_DEFAULT_NUM_SIGNERS - 2]; auto att = claimAttestation( scAttester, jvb, mcAlice, amt, - payees[kUtXchainDefaultNumSigners - 1], + payees[kUT_XCHAIN_DEFAULT_NUM_SIGNERS - 1], true, claimID, dst, @@ -2261,7 +2261,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { // B2: single item signer list std::vector tempSignerList = {signers[0]}; - scEnv.tx(jtx::signers(altSigners[2].account, 1, tempSignerList)); + scEnv.tx(jtx::signers(alt_signers[2].account, 1, tempSignerList)); auto att = claimAttestation( scAttester, jvb, @@ -2272,14 +2272,14 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimID, dst, tempSignerList.front()); - att[sfAttestationSignerAccount.getJsonName()] = altSigners[2].account.human(); + 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(altSigners[2].account, asfDisableMaster, 0)).close(); + scEnv.tx(fset(alt_signers[2].account, asfDisableMaster, 0)).close(); auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, altSigners[2]); + scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, alt_signers[2]); scEnv.tx(att, Ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { @@ -2292,11 +2292,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // --B5: missing sfAttestationSignerAccount field // Then submit the one with the field. Should reach quorum. auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, altSigners[3]); + 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()] = altSigners[3].account.human(); + att[sfAttestationSignerAccount.getJsonName()] = alt_signers[3].account.human(); scEnv.tx(att).close(); BEAST_EXPECT(dstStartBalance + amt == scEnv.env.balance(dst)); } @@ -2327,13 +2327,13 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BridgeDef xrpB{ .doorA = doorA, .issueA = xrpIssue(), - .doorB = Account::kMaster, + .doorB = Account::kMASTER, .issueB = xrpIssue(), .reward = XRP(1), // reward .minAccountCreate = XRP(20), // minAccountCreate .quorum = 4, // quorum .signers = signers, - .jvb = json::ValueType::Null}; + .jvb = json::NullValue}; xrpB.initBridge(mcEnv, scEnv); @@ -2399,8 +2399,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2412,11 +2412,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -2431,7 +2431,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj scEnv.tx(xchainClaim(scAlice, jvb, claimID, amt, scBob)).close(); } - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); } // Claim with just one attestation signed by the Master key @@ -2445,8 +2445,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); scEnv - .tx(createBridge(Account::kMaster, jvb)) - //.tx(jtx::signers(Account::kMaster, quorum, signers)) + .tx(createBridge(Account::kMASTER, jvb)) + //.tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2457,9 +2457,9 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[0], 1, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[0], 1, withClaim); - jtx::Signer const masterSigner(Account::kMaster); + jtx::Signer const masterSigner(Account::kMASTER); scEnv .tx(claimAttestation( scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, masterSigner), @@ -2481,9 +2481,9 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); scEnv - .tx(createBridge(Account::kMaster, jvb)) - //.tx(jtx::signers(Account::kMaster, quorum, signers)) - .tx(jtx::regkey(Account::kMaster, payees[0])) + .tx(createBridge(Account::kMASTER, jvb)) + //.tx(jtx::signers(Account::kMASTER, quorum, signers)) + .tx(jtx::regkey(Account::kMASTER, payees[0])) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2494,7 +2494,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::kMaster, scBob, scAlice, &payees[0], 1, withClaim); + scEnv, Account::kMASTER, scBob, scAlice, &payees[0], 1, withClaim); jtx::Signer const masterSigner(payees[0]); scEnv @@ -2515,10 +2515,10 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - auto jvbUnknown = bridge(mcBob, xrpIssue(), Account::kMaster, xrpIssue()); + auto jvbUnknown = bridge(mcBob, xrpIssue(), Account::kMASTER, xrpIssue()); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvbUnknown, reward, mcAlice), Ter(tecNO_ENTRY)) .close(); @@ -2529,7 +2529,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(xchainCommit(mcAlice, jvbUnknown, claimID, amt, dst), Ter(tecNO_ENTRY)) .close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); scEnv .tx(claimAttestation( scAttester, @@ -2565,8 +2565,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2576,7 +2576,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); // attest using non-existent claim id scEnv @@ -2605,8 +2605,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2618,11 +2618,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -2641,7 +2641,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj } else { - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); } } @@ -2654,8 +2654,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2665,7 +2665,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); // don't send any attestations @@ -2693,8 +2693,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2704,7 +2704,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); auto tooFew = quorum - 1; scEnv @@ -2734,8 +2734,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2745,7 +2745,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scAlice, payees, withClaim); scEnv .multiTx( @@ -2776,8 +2776,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2789,11 +2789,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -2822,8 +2822,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2835,11 +2835,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv @@ -2869,8 +2869,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj STAmount const hugeReward{XRP(20000)}; BEAST_EXPECT(hugeReward > scEnv.balance(scAlice)); - scEnv.tx(createBridge(Account::kMaster, jvb, hugeReward)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, hugeReward)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, hugeReward, mcAlice)) .close(); @@ -2882,11 +2882,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); if (withClaim) @@ -2905,7 +2905,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { auto txns = claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); - for (int i = 0; i < kUtXchainDefaultQuorum - 1; ++i) + for (int i = 0; i < kUT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); } @@ -2931,8 +2931,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .fund( res0 + reward, scuAlice) // just not enough because of fees @@ -2946,7 +2946,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchainCommit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::kMaster, scBob, scuAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::kMASTER, scBob, scuAlice, payees, withClaim); scEnv .tx(claimAttestation( @@ -2975,8 +2975,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .tx(fset("scBob", asfDepositAuth)) // set deposit auth .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) @@ -2989,15 +2989,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); auto txns = claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); - for (int i = 0; i < kUtXchainDefaultQuorum - 1; ++i) + for (int i = 0; i < kUT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); } @@ -3045,8 +3045,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .tx(fset("scBob", asfRequireDest)) // set dest tag .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) @@ -3059,15 +3059,15 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); auto txns = claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); - for (int i = 0; i < kUtXchainDefaultQuorum - 1; ++i) + for (int i = 0; i < kUT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); } @@ -3116,8 +3116,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .tx(fset("scBob", asfDepositAuth)) // set deposit auth .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) @@ -3153,8 +3153,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -3166,11 +3166,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); scEnv.multiTx(claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); @@ -3180,7 +3180,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // claim wrong amount scEnv - .tx(xchainClaim(scAlice, jvb, claimID, oneXrp, scBob), + .tx(xchainClaim(scAlice, jvb, claimID, one_xrp, scBob), Ter(tecXCHAIN_CLAIM_NO_QUORUM)) .close(); } @@ -3198,8 +3198,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcEnv.tx(createBridge(mcDoor, jvb)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -3211,11 +3211,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); test::Balance const scAliceBal(scEnv, scAlice); scEnv.multiTx(claimAttestations( @@ -3232,7 +3232,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimCost += fee; } - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); BEAST_EXPECT(scAliceBal.diff() == -claimCost); // because reward % 4 == 0 } @@ -3244,12 +3244,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv mcEnv(*this); XEnv scEnv(*this, true); - mcEnv.tx(createBridge(mcDoor, jvb, tinyReward)).close(); + mcEnv.tx(createBridge(mcDoor, jvb, tiny_reward)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb, tinyReward)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb, tiny_reward)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() - .tx(xchainCreateClaimId(scAlice, jvb, tinyReward, mcAlice)) + .tx(xchainCreateClaimId(scAlice, jvb, tiny_reward, mcAlice)) .close(); auto dst(withClaim ? std::nullopt : std::optional{scBob}); @@ -3259,16 +3259,16 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum, + kUT_XCHAIN_DEFAULT_QUORUM, withClaim); test::Balance const scAliceBal(scEnv, scAlice); scEnv.multiTx(claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); - STAmount claimCost = tinyReward; + STAmount claimCost = tiny_reward; if (withClaim) { @@ -3279,8 +3279,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimCost += fee; } - BEAST_EXPECT(transfer.hasHappened(amt, tinyRewardSplit)); - BEAST_EXPECT(scAliceBal.diff() == -(claimCost - tinyRewardRemainder)); + BEAST_EXPECT(transfer.hasHappened(amt, tiny_reward_split)); + BEAST_EXPECT(scAliceBal.diff() == -(claimCost - tiny_reward_remainder)); } // If a reward distribution fails for one of the reward accounts @@ -3298,8 +3298,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::vector altPayees{payees.begin(), payees.end() - 1}; altPayees.back() = Account("inexistent"); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -3311,11 +3311,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum - 1, + kUT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); scEnv.multiTx(claimAttestations( scAttester, jvb, mcAlice, amt, altPayees, true, claimID, dst, signers)); @@ -3331,7 +3331,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // this also checks that only 3 * split_reward was deducted from // scAlice (the payer account), since we passed alt_payees to // BalanceTransfer - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); } for (auto withClaim : {false, true}) @@ -3340,9 +3340,9 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv scEnv(*this, true); mcEnv.tx(createBridge(mcDoor, jvb)).close(); - auto& unpaid = payees[kUtXchainDefaultQuorum - 1]; - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + auto& unpaid = payees[kUT_XCHAIN_DEFAULT_QUORUM - 1]; + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .tx(fset(unpaid, asfDepositAuth)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) @@ -3361,11 +3361,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, - Account::kMaster, + Account::kMASTER, scBob, scAlice, &payees[0], - kUtXchainDefaultQuorum - 1, + kUT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); scEnv.multiTx(claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); @@ -3381,7 +3381,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // this also checks that only 3 * split_reward was deducted from // scAlice (the payer account), since we passed payees.size() - // 1 to BalanceTransfer - BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); + BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); // and make sure the account with deposit auth received nothing BEAST_EXPECT(lastSigner.diff() == STAmount(0)); @@ -3389,7 +3389,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // coverage test: xchain_claim transaction with incorrect flag XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .close() .tx(xchainClaim(scAlice, jvb, 1, XRP(1000), scBob), Txflags(tfFillOrKill), @@ -3399,7 +3399,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // coverage test: xchain_claim transaction with xchain feature // disabled XEnv(*this, true) - .tx(createBridge(Account::kMaster, jvb)) + .tx(createBridge(Account::kMASTER, jvb)) .disableFeature(featureXChainBridge) .close() .tx(xchainClaim(scAlice, jvb, 1, XRP(1000), scBob), Ter(temDISABLED)) @@ -3427,21 +3427,21 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj auto const amt = XRP(111); auto const amtPlusReward = amt + reward; - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); - test::Balance const door(scEnv, Account::kMaster); + test::Balance const door(scEnv, Account::kMASTER); // scEnv.tx(att_create_acct_batch1(1, amt, - // Account::kMaster)).close(); - scEnv.multiTx(attCreateAcctVec(1, amt, Account::kMaster, 2)).close(); + // Account::kMASTER)).close(); + scEnv.multiTx(attCreateAcctVec(1, amt, Account::kMASTER, 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::kMaster)).close(); - scEnv.multiTx(attCreateAcctVec(1, amt, Account::kMaster, 2, 2)).close(); + // Account::kMASTER)).close(); + scEnv.multiTx(attCreateAcctVec(1, amt, Account::kMASTER, 2, 2)).close(); BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count was incremented @@ -3578,17 +3578,17 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // commit where the fee dips into the reserve, this should succeed XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + oneXrp + fee - drops(1), mcuAlice) + .fund(res0 + one_xrp + fee - drops(1), mcuAlice) .close() - .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tesSUCCESS)); + .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tesSUCCESS)); // commit where the commit amount drips into the reserve, this should // fail XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + oneXrp - drops(1), mcuAlice) + .fund(res0 + one_xrp - drops(1), mcuAlice) .close() - .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); auto const minAccountCreate = XRP(20); @@ -3639,7 +3639,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { XEnv scEnv(*this, true); - scEnv.tx(createBridge(Account::kMaster, jvb)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -3666,8 +3666,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; std::optional const dst{scBob}; auto const amt = XRP(1000); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); scEnv.tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)).close(); auto jvAtt = claimAttestation( @@ -3675,11 +3675,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj jvb, mcAlice, amt, - payees[kUtXchainDefaultQuorum], + payees[kUT_XCHAIN_DEFAULT_QUORUM], true, claimID, dst, - signers[kUtXchainDefaultQuorum]); + signers[kUT_XCHAIN_DEFAULT_QUORUM]); { // Change to an invalid keytype auto k = jvAtt["PublicKey"].asString(); @@ -3696,8 +3696,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj Account const dst{scBob}; auto const amt = XRP(1000); auto const rewardAmt = XRP(1); - scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, signers)) + scEnv.tx(createBridge(Account::kMASTER, jvb)) + .tx(jtx::signers(Account::kMASTER, quorum, signers)) .close(); auto jvAtt = createAccountAttestation( scAttester, @@ -3705,11 +3705,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj mcAlice, amt, rewardAmt, - payees[kUtXchainDefaultQuorum], + payees[kUT_XCHAIN_DEFAULT_QUORUM], true, createCount, dst, - signers[kUtXchainDefaultQuorum]); + signers[kUT_XCHAIN_DEFAULT_QUORUM]); { // Change to an invalid keytype auto k = jvAtt["PublicKey"].asString(); @@ -3746,7 +3746,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj struct XChainSim_test : public beast::unit_test::Suite, public jtx::XChainBridgeObjects { private: - static constexpr size_t kNumSigners = 5; + static constexpr size_t kNUM_SIGNERS = 5; // -------------------------------------------------- enum class WithClaim { No, Yes }; @@ -3757,9 +3757,9 @@ private: jtx::Account finaldest; STAmount amt; bool a2b; // direction of transfer - WithClaim withClaim{WithClaim::No}; - uint32_t claimId{0}; - std::array attested{}; + WithClaim with_claim{WithClaim::No}; + uint32_t claim_id{0}; + std::array attested{}; }; struct AccountCreate @@ -3769,8 +3769,8 @@ private: STAmount amt; STAmount reward; bool a2b; - uint32_t claimId{0}; - std::array attested{}; + uint32_t claim_id{0}; + std::array attested{}; }; using ENV = XEnv; @@ -3806,7 +3806,7 @@ private: using CreateClaimVec = jtx::JValueVec; using CreateClaimMap = std::map; - ChainStateTrack(ENV& env) : env(env), txFee(env.env.current()->fees().base) + ChainStateTrack(ENV& env) : env(env), tx_fee(env.env.current()->fees().base) { } @@ -3851,30 +3851,31 @@ private: { callbackCalled = false; // cspell: ignore attns - for (size_t i = 0; i < signersAttns.size(); ++i) + for (size_t i = 0; i < signers_attns.size(); ++i) { - for (auto& [bridge, claims] : signersAttns[i]) + for (auto& [bridge, claims] : signers_attns[i]) { - sendAttestations(i, bridge, claims.xferClaims); + sendAttestations(i, bridge, claims.xfer_claims); auto& c = counters[bridge]; - auto& createClaims = claims.createClaims[c.claimCount]; + auto& createClaims = claims.create_claims[c.claim_count]; auto numAttns = createClaims.size(); if (numAttns != 0u) { - c.numCreateAttnSent += sendCreateAttestations(i, bridge, createClaims); + c.num_create_attn_sent += + sendCreateAttestations(i, bridge, createClaims); } - assert(claims.createClaims[c.claimCount].empty()); + assert(claims.create_claims[c.claim_count].empty()); } } for (auto& [bridge, c] : counters) { - if (c.numCreateAttnSent >= bridge->quorum) + if (c.num_create_attn_sent >= bridge->quorum) { callbackCalled = true; - c.createCallbacks[c.claimCount](c.signers); - ++c.claimCount; - c.numCreateAttnSent = 0; + c.create_callbacks[c.claim_count](c.signers); + ++c.claim_count; + c.num_create_attn_sent = 0; c.signers.clear(); } } @@ -3925,7 +3926,7 @@ private: void spendFee(jtx::Account const& acct, size_t times = 1) { - spend(acct, txFee, times); + spend(acct, tx_fee, times); } [[nodiscard]] bool @@ -3943,30 +3944,30 @@ private: { using complete_cb = std::function const& signers)>; - uint32_t claimId{0}; - uint32_t createCount{0}; // for account create. First should be 1 - uint32_t claimCount{0}; // for account create. Increments after quorum for - // current createCount (starts at 1) is reached. + uint32_t 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 numCreateAttnSent{0}; // for current claimCount + uint32_t num_create_attn_sent{0}; // for current claim_count std::vector signers; - std::vector createCallbacks; + std::vector create_callbacks; }; struct Claims { - ClaimVec xferClaims; - CreateClaimMap createClaims; + ClaimVec xfer_claims; + CreateClaimMap create_claims; }; using SignerAttns = std::unordered_map; - using SignersAttns = std::array; + using SignersAttns = std::array; ENV& env; std::map accounts; - SignersAttns signersAttns; + SignersAttns signers_attns; std::map counters; - STAmount txFee; + STAmount tx_fee; }; struct ChainStateTracker @@ -4085,7 +4086,7 @@ private: st.transfer(cr_.from, srcdoor, cr_.amt); st.transfer(cr_.from, srcdoor, cr_.reward); - return ++st.counters[&bridge_].createCount; + return ++st.counters[&bridge_].create_count; } void @@ -4095,17 +4096,18 @@ private: // check all signers, but start at a random one size_t i = 0; - for (i = 0; i < kNumSigners; ++i) + for (i = 0; i < kNUM_SIGNERS; ++i) { - size_t const signerIdx = (rnd + i) % kNumSigners; + size_t const signerIdx = (rnd + i) % kNUM_SIGNERS; if (!(cr_.attested[signerIdx])) { // enqueue one attestation for this signer cr_.attested[signerIdx] = true; - st.signersAttns[signerIdx][&bridge_].createClaims[cr_.claimId - 1].emplace_back( - createAccountAttestation( + st.signers_attns[signerIdx][&bridge_] + .create_claims[cr_.claim_id - 1] + .emplace_back(createAccountAttestation( bridge_.signers[signerIdx].account, bridge_.jvb, cr_.from, @@ -4113,26 +4115,26 @@ private: cr_.reward, bridge_.signers[signerIdx].account, cr_.a2b, - cr_.claimId, + cr_.claim_id, cr_.to, bridge_.signers[signerIdx])); break; } } - if (i == kNumSigners) + if (i == kNUM_SIGNERS) return; // did not attest auto& counters = st.counters[&bridge_]; - if (counters.createCallbacks.size() < cr_.claimId) - counters.createCallbacks.resize(cr_.claimId); + if (counters.create_callbacks.size() < cr_.claim_id) + counters.create_callbacks.resize(cr_.claim_id); auto completeCb = [&](std::vector const& signers) { auto numAttestors = signers.size(); st.env.close(); assert(numAttestors <= std::count(cr_.attested.begin(), cr_.attested.end(), true)); assert(numAttestors >= bridge_.quorum); - assert(cr_.claimId - 1 == counters.claimCount); + assert(cr_.claim_id - 1 == counters.claim_count); auto r = cr_.reward; auto reward = divide(r, STAmount(numAttestors), r.asset()); @@ -4143,20 +4145,20 @@ private: st.spend(dstDoor(), reward, numAttestors); st.transfer(dstDoor(), cr_.to, cr_.amt); st.env.env.memoize(cr_.to); - smState_ = SmState::Completed; + sm_state_ = SmState::Completed; }; - counters.createCallbacks[cr_.claimId - 1] = std::move(completeCb); + counters.create_callbacks[cr_.claim_id - 1] = std::move(completeCb); } SmState advance(uint64_t time, uint32_t rnd) { - switch (smState_) + switch (sm_state_) { case SmState::Initial: - cr_.claimId = issueAccountCreate(); - smState_ = SmState::Attesting; + cr_.claim_id = issueAccountCreate(); + sm_state_ = SmState::Attesting; break; case SmState::Attesting: @@ -4170,11 +4172,11 @@ private: case SmState::Completed: break; // will get this once } - return smState_; + return sm_state_; } private: - SmState smState_{SmState::Initial}; + SmState sm_state_{SmState::Initial}; AccountCreate cr_; }; @@ -4207,7 +4209,7 @@ private: .close(); // needed for claim_id sequence to be // correct' st.spendFee(xfer_.to); - return ++st.counters[&bridge_].claimId; + return ++st.counters[&bridge_].claim_id; } void @@ -4224,10 +4226,10 @@ private: st.env.tx(xchainCommit( xfer_.from, bridge_.jvb, - xfer_.claimId, + xfer_.claim_id, xfer_.amt, - xfer_.withClaim == 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); } @@ -4238,7 +4240,7 @@ private: auto r = bridge_.reward; auto reward = divide(r, STAmount(bridge_.quorum), r.asset()); - for (size_t i = 0; i < kNumSigners; ++i) + for (size_t i = 0; i < kNUM_SIGNERS; ++i) { if (xfer_.attested[i]) st.receive(bridge_.signers[i].account, reward); @@ -4252,23 +4254,23 @@ private: ChainStateTrack& st = destState(); // check all signers, but start at a random one - for (size_t i = 0; i < kNumSigners; ++i) + for (size_t i = 0; i < kNUM_SIGNERS; ++i) { - size_t const signerIdx = (rnd + i) % kNumSigners; + size_t const signerIdx = (rnd + i) % kNUM_SIGNERS; if (!(xfer_.attested[signerIdx])) { // enqueue one attestation for this signer xfer_.attested[signerIdx] = true; - st.signersAttns[signerIdx][&bridge_].xferClaims.emplace_back(claimAttestation( + st.signers_attns[signerIdx][&bridge_].xfer_claims.emplace_back(claimAttestation( bridge_.signers[signerIdx].account, bridge_.jvb, xfer_.from, xfer_.amt, bridge_.signers[signerIdx].account, xfer_.a2b, - xfer_.claimId, - xfer_.withClaim == WithClaim::Yes + xfer_.claim_id, + xfer_.with_claim == WithClaim::Yes ? std::nullopt : std::optional(xfer_.finaldest), bridge_.signers[signerIdx])); @@ -4279,7 +4281,7 @@ private: // return true if quorum was reached, false otherwise bool const quorum = std::count(xfer_.attested.begin(), xfer_.attested.end(), true) >= bridge_.quorum; - if (quorum && xfer_.withClaim == WithClaim::No) + if (quorum && xfer_.with_claim == WithClaim::No) { distributeReward(st); st.transfer(dstDoor(), xfer_.finaldest, xfer_.amt); @@ -4292,7 +4294,7 @@ private: { ChainStateTrack& st = destState(); st.env.tx( - xchainClaim(xfer_.to, bridge_.jvb, xfer_.claimId, xfer_.amt, xfer_.finaldest)); + xchainClaim(xfer_.to, bridge_.jvb, xfer_.claim_id, xfer_.amt, xfer_.finaldest)); distributeReward(st); st.transfer(dstDoor(), xfer_.finaldest, xfer_.amt); st.spendFee(xfer_.to); @@ -4301,34 +4303,34 @@ private: SmState advance(uint64_t time, uint32_t rnd) { - switch (smState_) + switch (sm_state_) { case SmState::Initial: - xfer_.claimId = createClaimId(); - smState_ = SmState::ClaimIdCreated; + xfer_.claim_id = createClaimId(); + sm_state_ = SmState::ClaimIdCreated; break; case SmState::ClaimIdCreated: commit(); - smState_ = SmState::Attesting; + sm_state_ = SmState::Attesting; break; case SmState::Attesting: if (attest(time, rnd)) { - smState_ = xfer_.withClaim == WithClaim::Yes ? SmState::Attested - : SmState::Completed; + sm_state_ = xfer_.with_claim == WithClaim::Yes ? SmState::Attested + : SmState::Completed; } else { - smState_ = SmState::Attesting; + sm_state_ = SmState::Attesting; } break; case SmState::Attested: - assert(xfer_.withClaim == WithClaim::Yes); + assert(xfer_.with_claim == WithClaim::Yes); claim(); - smState_ = SmState::Completed; + sm_state_ = SmState::Completed; break; default: @@ -4336,12 +4338,12 @@ private: assert(0); // should have been removed break; } - return smState_; + return sm_state_; } private: Transfer xfer_; - SmState smState_{SmState::Initial}; + SmState sm_state_{SmState::Initial}; }; // -------------------------------------------------- @@ -4429,12 +4431,12 @@ public: Account doorXRPLocking("doorXRPLocking"), doorUSDLocking("doorUSDLocking"), doorUSDIssuing("doorUSDIssuing"); - static constexpr size_t kNumAcct = 10; + constexpr size_t kNUM_ACCT = 10; auto a = [&doorXRPLocking, &doorUSDLocking, &doorUSDIssuing]() { using namespace std::literals; std::vector result; - result.reserve(kNumAcct); - for (int i = 0; i < kNumAcct; ++i) + result.reserve(kNUM_ACCT); + for (int i = 0; i < kNUM_ACCT; ++i) { result.emplace_back( "a"s + std::to_string(i), (i % 2) ? KeyType::Ed25519 : KeyType::Secp256k1); @@ -4468,7 +4470,7 @@ public: for (int i = 0; i < a.size(); ++i) { auto& acct{a[i]}; - if (i < kNumAcct) + if (i < kNUM_ACCT) { mcEnv.tx(trust(acct, usdLocking(100000))); scEnv.tx(trust(acct, usdIssuing(100000))); @@ -4478,15 +4480,15 @@ public: for (auto& s : signers) st->init(s.account); - st->b.init(Account::kMaster); + st->b.init(Account::kMASTER); // also create some unfunded accounts - static constexpr size_t kNumUa = 20; + constexpr size_t kNUM_UA = 20; auto ua = []() { using namespace std::literals; std::vector result; - result.reserve(kNumUa); - for (int i = 0; i < kNumUa; ++i) + result.reserve(kNUM_UA); + for (int i = 0; i < kNUM_UA; ++i) { result.emplace_back( "ua"s + std::to_string(i), (i % 2) ? KeyType::Ed25519 : KeyType::Secp256k1); @@ -4506,13 +4508,13 @@ public: BridgeDef xrpB{ .doorA = doorXRPLocking, .issueA = xrpIssue(), - .doorB = Account::kMaster, + .doorB = Account::kMASTER, .issueB = xrpIssue(), .reward = XRP(1), .minAccountCreate = XRP(20), .quorum = quorum, .signers = signers, - .jvb = json::ValueType::Null}; + .jvb = json::NullValue}; initBridge(xrpB); @@ -4527,7 +4529,7 @@ public: .minAccountCreate = XRP(20), .quorum = quorum, .signers = signers, - .jvb = json::ValueType::Null}; + .jvb = json::NullValue}; initBridge(usdB); @@ -4571,7 +4573,7 @@ public: .finaldest = a[1], .amt = XRP(6), .a2b = true, - .withClaim = WithClaim::No}); + .with_claim = WithClaim::No}); xfer( 1, st, @@ -4581,7 +4583,7 @@ public: .finaldest = a[1], .amt = XRP(8), .a2b = false, - .withClaim = WithClaim::No}); + .with_claim = WithClaim::No}); xfer( 1, st, xrpB, {.from = a[1], .to = a[1], .finaldest = a[1], .amt = XRP(1), .a2b = true}); xfer( @@ -4603,7 +4605,7 @@ public: .finaldest = a[1], .amt = XRP(7), .a2b = false, - .withClaim = WithClaim::No}); + .with_claim = WithClaim::No}); xfer( 2, st, xrpB, {.from = a[1], .to = a[1], .finaldest = a[1], .amt = XRP(9), .a2b = true}); runSimulation(st); diff --git a/src/test/basics/FileUtilities_test.cpp b/src/test/basics/FileUtilities_test.cpp index 0e050b5168..959d3ca695 100644 --- a/src/test/basics/FileUtilities_test.cpp +++ b/src/test/basics/FileUtilities_test.cpp @@ -18,8 +18,7 @@ public: using namespace xrpl::detail; using namespace boost::system; - static constexpr char const* kExpectedContents = - "This file is very short. That's all we need."; + constexpr char const* kEXPECTED_CONTENTS = "This file is very short. That's all we need."; FileDirGuard const file( *this, "test_file", "test.txt", "This is temporary text that should get overwritten"); @@ -27,21 +26,21 @@ public: error_code ec; auto const path = file.file(); - writeFileContents(ec, path, kExpectedContents); + writeFileContents(ec, path, kEXPECTED_CONTENTS); BEAST_EXPECT(!ec); { // Test with no max auto const good = getFileContents(ec, path); BEAST_EXPECT(!ec); - BEAST_EXPECT(good == kExpectedContents); + BEAST_EXPECT(good == kEXPECTED_CONTENTS); } { // Test with large max auto const good = getFileContents(ec, path, kilobytes(1)); BEAST_EXPECT(!ec); - BEAST_EXPECT(good == kExpectedContents); + BEAST_EXPECT(good == kEXPECTED_CONTENTS); } { diff --git a/src/test/basics/IOUAmount_test.cpp b/src/test/basics/IOUAmount_test.cpp index b652d27625..738990aac2 100644 --- a/src/test/basics/IOUAmount_test.cpp +++ b/src/test/basics/IOUAmount_test.cpp @@ -23,18 +23,18 @@ public: BEAST_EXPECT(z.exponent() == -100); BEAST_EXPECT(!z); BEAST_EXPECT(z.signum() == 0); - BEAST_EXPECT(z == beast::kZero); + BEAST_EXPECT(z == beast::kZERO); BEAST_EXPECT((z + z) == z); BEAST_EXPECT((z - z) == z); BEAST_EXPECT(z == -z); - IOUAmount const zz(beast::kZero); + IOUAmount const zz(beast::kZERO); BEAST_EXPECT(z == zz); // https://github.com/XRPLF/rippled/issues/5170 IOUAmount const zzz{}; - BEAST_EXPECT(zzz == beast::kZero); + BEAST_EXPECT(zzz == beast::kZERO); // BEAST_EXPECT(zzz == zz); } @@ -58,32 +58,32 @@ public: { testcase("beast::Zero Comparisons"); - using beast::kZero; + using beast::kZERO; { - IOUAmount const z(kZero); - BEAST_EXPECT(z == kZero); - BEAST_EXPECT(z >= kZero); - BEAST_EXPECT(z <= kZero); - unexpected(z != kZero); - unexpected(z > kZero); - unexpected(z < kZero); + IOUAmount const z(kZERO); + BEAST_EXPECT(z == kZERO); + BEAST_EXPECT(z >= kZERO); + BEAST_EXPECT(z <= kZERO); + unexpected(z != kZERO); + unexpected(z > kZERO); + unexpected(z < kZERO); } { IOUAmount const neg(-2, 0); - BEAST_EXPECT(neg < kZero); - BEAST_EXPECT(neg <= kZero); - BEAST_EXPECT(neg != kZero); - unexpected(neg == kZero); + BEAST_EXPECT(neg < kZERO); + BEAST_EXPECT(neg <= kZERO); + BEAST_EXPECT(neg != kZERO); + unexpected(neg == kZERO); } { IOUAmount const pos(2, 0); - BEAST_EXPECT(pos > kZero); - BEAST_EXPECT(pos >= kZero); - BEAST_EXPECT(pos != kZero); - unexpected(pos == kZero); + BEAST_EXPECT(pos > kZERO); + BEAST_EXPECT(pos >= kZERO); + BEAST_EXPECT(pos != kZERO); + unexpected(pos == kZERO); } } @@ -156,7 +156,8 @@ public: BEAST_EXPECTS(result == expected, ss.str()); }; - for (auto const mantissaSize : MantissaRange::getAllScales()) + for (auto const mantissaSize : + {MantissaRange::MantissaScale::Small, MantissaRange::MantissaScale::Large}) { NumberMantissaScaleGuard const mg(mantissaSize); @@ -178,68 +179,68 @@ public: testcase("mulRatio"); /* The range for the mantissa when normalized */ - static constexpr std::int64_t kMinMantissa = 1000000000000000ull; - static constexpr std::int64_t kMaxMantissa = 9999999999999999ull; + constexpr std::int64_t kMIN_MANTISSA = 1000000000000000ull; + constexpr std::int64_t kMAX_MANTISSA = 9999999999999999ull; // log(2,maxMantissa) ~ 53.15 /* The range for the exponent when normalized */ - static constexpr int kMinExponent = -96; - static constexpr int kMaxExponent = 80; - constexpr auto kMaxUInt = std::numeric_limits::max(); + constexpr int kMIN_EXPONENT = -96; + constexpr int kMAX_EXPONENT = 80; + constexpr auto kMAX_U_INT = std::numeric_limits::max(); { // multiply by a number that would overflow the mantissa, then // divide by the same number, and check we didn't lose any value - IOUAmount const bigMan(kMaxMantissa, 0); - BEAST_EXPECT(bigMan == mulRatio(bigMan, kMaxUInt, kMaxUInt, true)); + IOUAmount const bigMan(kMAX_MANTISSA, 0); + BEAST_EXPECT(bigMan == mulRatio(bigMan, kMAX_U_INT, kMAX_U_INT, true)); // rounding mode shouldn't matter as the result is exact - BEAST_EXPECT(bigMan == mulRatio(bigMan, kMaxUInt, kMaxUInt, false)); + BEAST_EXPECT(bigMan == mulRatio(bigMan, kMAX_U_INT, kMAX_U_INT, false)); } { // Similar test as above, but for negative values - IOUAmount const bigMan(-kMaxMantissa, 0); - BEAST_EXPECT(bigMan == mulRatio(bigMan, kMaxUInt, kMaxUInt, true)); + IOUAmount const bigMan(-kMAX_MANTISSA, 0); + BEAST_EXPECT(bigMan == mulRatio(bigMan, kMAX_U_INT, kMAX_U_INT, true)); // rounding mode shouldn't matter as the result is exact - BEAST_EXPECT(bigMan == mulRatio(bigMan, kMaxUInt, kMaxUInt, false)); + BEAST_EXPECT(bigMan == mulRatio(bigMan, kMAX_U_INT, kMAX_U_INT, false)); } { // small amounts - IOUAmount const tiny(kMinMantissa, kMinExponent); + IOUAmount const tiny(kMIN_MANTISSA, kMIN_EXPONENT); // Round up should give the smallest allowable number - BEAST_EXPECT(tiny == mulRatio(tiny, 1, kMaxUInt, true)); - BEAST_EXPECT(tiny == mulRatio(tiny, kMaxUInt - 1, kMaxUInt, true)); + BEAST_EXPECT(tiny == mulRatio(tiny, 1, kMAX_U_INT, true)); + BEAST_EXPECT(tiny == mulRatio(tiny, kMAX_U_INT - 1, kMAX_U_INT, true)); // rounding down should be zero - BEAST_EXPECT(beast::kZero == mulRatio(tiny, 1, kMaxUInt, false)); - BEAST_EXPECT(beast::kZero == mulRatio(tiny, kMaxUInt - 1, kMaxUInt, false)); + BEAST_EXPECT(beast::kZERO == mulRatio(tiny, 1, kMAX_U_INT, false)); + BEAST_EXPECT(beast::kZERO == mulRatio(tiny, kMAX_U_INT - 1, kMAX_U_INT, false)); // tiny negative numbers - IOUAmount const tinyNeg(-kMinMantissa, kMinExponent); + IOUAmount const tinyNeg(-kMIN_MANTISSA, kMIN_EXPONENT); // Round up should give zero - BEAST_EXPECT(beast::kZero == mulRatio(tinyNeg, 1, kMaxUInt, true)); - BEAST_EXPECT(beast::kZero == mulRatio(tinyNeg, kMaxUInt - 1, kMaxUInt, true)); + BEAST_EXPECT(beast::kZERO == mulRatio(tinyNeg, 1, kMAX_U_INT, true)); + BEAST_EXPECT(beast::kZERO == mulRatio(tinyNeg, kMAX_U_INT - 1, kMAX_U_INT, true)); // rounding down should be tiny - BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, 1, kMaxUInt, false)); - BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, kMaxUInt - 1, kMaxUInt, false)); + BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, 1, kMAX_U_INT, false)); + BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, kMAX_U_INT - 1, kMAX_U_INT, false)); } { // rounding { IOUAmount const one(1, 0); - auto const rup = mulRatio(one, kMaxUInt - 1, kMaxUInt, true); - auto const rdown = mulRatio(one, kMaxUInt - 1, kMaxUInt, false); + auto const rup = mulRatio(one, kMAX_U_INT - 1, kMAX_U_INT, true); + auto const rdown = mulRatio(one, kMAX_U_INT - 1, kMAX_U_INT, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } { - IOUAmount const big(kMaxMantissa, kMaxExponent); - auto const rup = mulRatio(big, kMaxUInt - 1, kMaxUInt, true); - auto const rdown = mulRatio(big, kMaxUInt - 1, kMaxUInt, false); + IOUAmount const big(kMAX_MANTISSA, kMAX_EXPONENT); + auto const rup = mulRatio(big, kMAX_U_INT - 1, kMAX_U_INT, true); + auto const rdown = mulRatio(big, kMAX_U_INT - 1, kMAX_U_INT, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } { IOUAmount const negOne(-1, 0); - auto const rup = mulRatio(negOne, kMaxUInt - 1, kMaxUInt, true); - auto const rdown = mulRatio(negOne, kMaxUInt - 1, kMaxUInt, false); + auto const rup = mulRatio(negOne, kMAX_U_INT - 1, kMAX_U_INT, true); + auto const rdown = mulRatio(negOne, kMAX_U_INT - 1, kMAX_U_INT, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } } @@ -252,7 +253,7 @@ public: { // overflow - IOUAmount big(kMaxMantissa, kMaxExponent); + IOUAmount big(kMAX_MANTISSA, kMAX_EXPONENT); except([&] { mulRatio(big, 2, 0, true); }); } } // namespace xrpl diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index 185b877f23..50d3fab7a2 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -87,8 +87,8 @@ enum class TrackedState : std::uint8_t { class TIBase : public IntrusiveRefCounts { public: - static constexpr std::size_t kMaxStates = 128; - static std::array, kMaxStates> state; + static constexpr std::size_t kMAX_STATES = 128; + static std::array, kMAX_STATES> state; static std::atomic nextId; static TrackedState getState(int id) @@ -99,7 +99,7 @@ public: static void resetStates(bool resetCallback) { - for (int i = 0; i < kMaxStates; ++i) + for (int i = 0; i < kMAX_STATES; ++i) { state[i].store(TrackedState::Uninitialized, std::memory_order_release); } @@ -179,7 +179,7 @@ private: } }; -std::array, TIBase::kMaxStates> TIBase::state; +std::array, TIBase::kMAX_STATES> TIBase::state; std::atomic TIBase::nextId{0}; std::function)> TIBase::tracingCallback = @@ -539,17 +539,17 @@ public: } return result; }; - static constexpr int kLoopIters = 2 * 1024; - static constexpr int kNumThreads = 16; + constexpr int kLOOP_ITERS = 2 * 1024; + constexpr int kNUM_THREADS = 16; std::vector> toClone; - Barrier loopStartSyncPoint{kNumThreads}; - Barrier postCreateToCloneSyncPoint{kNumThreads}; - Barrier postCreateVecOfPointersSyncPoint{kNumThreads}; + Barrier loopStartSyncPoint{kNUM_THREADS}; + Barrier postCreateToCloneSyncPoint{kNUM_THREADS}; + Barrier postCreateVecOfPointersSyncPoint{kNUM_THREADS}; auto engines = [&]() -> std::vector { std::random_device rd; std::vector result; - result.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) + result.reserve(kNUM_THREADS); + for (int i = 0; i < kNUM_THREADS; ++i) result.emplace_back(rd()); return result; }(); @@ -558,7 +558,7 @@ public: // strong and weak pointers and destroys them all at once. // threadId==0 is special. auto cloneAndDestroy = [&](int threadId) { - for (int i = 0; i < kLoopIters; ++i) + for (int i = 0; i < kLOOP_ITERS; ++i) { // ------ Sync Point ------ loopStartSyncPoint.arriveAndWait(); @@ -578,7 +578,7 @@ public: destructionState.store(0, std::memory_order_release); toClone.clear(); - toClone.resize(kNumThreads); + toClone.resize(kNUM_THREADS); auto strong = makeSharedIntrusive(); strong->tracingCallback = tracingCallback; std::ranges::fill(toClone, strong); @@ -597,12 +597,12 @@ public: } }; std::vector threads; - threads.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) + threads.reserve(kNUM_THREADS); + for (int i = 0; i < kNUM_THREADS; ++i) { threads.emplace_back(cloneAndDestroy, i); } - for (int i = 0; i < kNumThreads; ++i) + for (int i = 0; i < kNUM_THREADS; ++i) { threads[i].join(); } @@ -664,19 +664,19 @@ public: result.emplace_back(SharedIntrusive(toClone)); return result; }; - static constexpr int kLoopIters = 2 * 1024; - static constexpr int kFlipPointersLoopIters = 256; - static constexpr int kNumThreads = 16; + constexpr int kLOOP_ITERS = 2 * 1024; + constexpr int kFLIP_POINTERS_LOOP_ITERS = 256; + constexpr int kNUM_THREADS = 16; std::vector> toClone; - Barrier loopStartSyncPoint{kNumThreads}; - Barrier postCreateToCloneSyncPoint{kNumThreads}; - Barrier postCreateVecOfPointersSyncPoint{kNumThreads}; - Barrier postFlipPointersLoopSyncPoint{kNumThreads}; + Barrier loopStartSyncPoint{kNUM_THREADS}; + Barrier postCreateToCloneSyncPoint{kNUM_THREADS}; + Barrier postCreateVecOfPointersSyncPoint{kNUM_THREADS}; + Barrier postFlipPointersLoopSyncPoint{kNUM_THREADS}; auto engines = [&]() -> std::vector { std::random_device rd; std::vector result; - result.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) + result.reserve(kNUM_THREADS); + for (int i = 0; i < kNUM_THREADS; ++i) result.emplace_back(rd()); return result; }(); @@ -686,7 +686,7 @@ public: // changes strong pointers to weak pointers, and destroys them // all at once. auto cloneAndDestroy = [&](int threadId) { - for (int i = 0; i < kLoopIters; ++i) + for (int i = 0; i < kLOOP_ITERS; ++i) { // ------ Sync Point ------ loopStartSyncPoint.arriveAndWait(); @@ -705,7 +705,7 @@ public: destructionState.store(0, std::memory_order_release); toClone.clear(); - toClone.resize(kNumThreads); + toClone.resize(kNUM_THREADS); auto strong = makeSharedIntrusive(); strong->tracingCallback = tracingCallback; std::ranges::fill(toClone, strong); @@ -721,7 +721,7 @@ public: postCreateVecOfPointersSyncPoint.arriveAndWait(); std::uniform_int_distribution<> isStrongDist(0, 1); - for (int f = 0; f < kFlipPointersLoopIters; ++f) + for (int f = 0; f < kFLIP_POINTERS_LOOP_ITERS; ++f) { for (auto& p : v) { @@ -743,12 +743,12 @@ public: } }; std::vector threads; - threads.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) + threads.reserve(kNUM_THREADS); + for (int i = 0; i < kNUM_THREADS; ++i) { threads.emplace_back(cloneAndDestroy, i); } - for (int i = 0; i < kNumThreads; ++i) + for (int i = 0; i < kNUM_THREADS; ++i) { threads[i].join(); } @@ -795,19 +795,19 @@ public: } }; - static constexpr int kLoopIters = 2 * 1024; - static constexpr int kLockWeakLoopIters = 256; - static constexpr int kNumThreads = 16; + constexpr int kLOOP_ITERS = 2 * 1024; + constexpr int kLOCK_WEAK_LOOP_ITERS = 256; + constexpr int kNUM_THREADS = 16; std::vector> toLock; - Barrier loopStartSyncPoint{kNumThreads}; - Barrier postCreateToLockSyncPoint{kNumThreads}; - Barrier postLockWeakLoopSyncPoint{kNumThreads}; + Barrier loopStartSyncPoint{kNUM_THREADS}; + Barrier postCreateToLockSyncPoint{kNUM_THREADS}; + Barrier postLockWeakLoopSyncPoint{kNUM_THREADS}; // lockAndDestroy creates weak pointers from the strong pointer // and runs a loop that locks the weak pointer. At the end of the loop // all the pointers are destroyed all at once. auto lockAndDestroy = [&](int threadId) { - for (int i = 0; i < kLoopIters; ++i) + for (int i = 0; i < kLOOP_ITERS; ++i) { // ------ Sync Point ------ loopStartSyncPoint.arriveAndWait(); @@ -826,7 +826,7 @@ public: destructionState.store(0, std::memory_order_release); toLock.clear(); - toLock.resize(kNumThreads); + toLock.resize(kNUM_THREADS); auto strong = makeSharedIntrusive(); strong->tracingCallback = tracingCallback; std::ranges::fill(toLock, strong); @@ -838,7 +838,7 @@ public: // Multiple threads all create a weak pointer from the same // strong pointer WeakIntrusive const weak{toLock[threadId]}; - for (int wi = 0; wi < kLockWeakLoopIters; ++wi) + for (int wi = 0; wi < kLOCK_WEAK_LOOP_ITERS; ++wi) { BEAST_EXPECT(!weak.expired()); auto strong = weak.lock(); @@ -852,12 +852,12 @@ public: } }; std::vector threads; - threads.reserve(kNumThreads); - for (int i = 0; i < kNumThreads; ++i) + threads.reserve(kNUM_THREADS); + for (int i = 0; i < kNUM_THREADS; ++i) { threads.emplace_back(lockAndDestroy, i); } - for (int i = 0; i < kNumThreads; ++i) + for (int i = 0; i < kNUM_THREADS; ++i) { threads[i].join(); } diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index 81019970ad..9e06d6de53 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -6,14 +6,8 @@ #include #include -// NOLINTNEXTLINE(misc-include-cleaner) -#include -#include - #include -#include #include -#include #include #include #include @@ -25,58 +19,6 @@ namespace xrpl { class Number_test : public beast::unit_test::Suite { - using BigInt = boost::multiprecision::cpp_int; - - static std::string - fmt(BigInt const& value) - { - auto s = to_string(value); - std::string out; - int count = 0; - for (auto it = s.rbegin(); it != s.rend(); ++it) - { - if (count != 0 && count % 3 == 0 && (isdigit(*it) != 0)) - out.insert(out.begin(), '_'); - out.insert(out.begin(), *it); - ++count; - } - return out; - } - - using dec = boost::multiprecision::cpp_dec_float_50; - - template - static T - pow10(int n) - { - if (n == 0) - return 1; - if (n == 1) - return 10; - - if (n > 1) - { - auto r = pow10(n / 2); - r *= r; - if (n % 2 != 0) - r *= 10; - return r; - } - - // n < 0 - T p = 1; - p /= pow10(-n); - return p; - } - - static std::string - fmt(dec const& v) - { - std::ostringstream os; - os << std::setprecision(40) << v; - return os.str(); - } - public: void testZero() @@ -236,7 +178,8 @@ public: {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::kMaxRep - 1}, Number{1, 0}, Number{Number::kMaxRep}}, + {Number{Number::kMAX_REP}, Number{6, -1}, Number{Number::kMAX_REP / 10, 1}}, + {Number{Number::kMAX_REP - 1}, Number{1, 0}, Number{Number::kMAX_REP}}, // Test extremes { // Each Number operand rounds up, so the actual mantissa is @@ -246,22 +189,16 @@ public: Number{2, 19}, }, { - // Does not round. Mantissas are going to be > kMaxRep, so if + // Does not round. Mantissas are going to be > maxRep, so if // added together as uint64_t's, the result will overflow. // With addition using uint128_t, there's no problem. After // normalizing, the resulting mantissa ends up less than - // kMaxRep. + // 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{}}, }, }); - auto const cLargeLegacy = std::to_array({ - {Number{Number::kMaxRep}, Number{6, -1}, Number{Number::kMaxRep / 10, 1}}, - }); - auto const cLargeCorrected = std::to_array({ - {Number{Number::kMaxRep}, Number{6, -1}, Number{(Number::kMaxRep / 10) + 1, 1}}, - }); auto test = [this](auto const& c) { for (auto const& [x, y, z] : c) { @@ -278,14 +215,6 @@ public: else { test(cLarge); - if (scale == MantissaRange::MantissaScale::LargeLegacy) - { - test(cLargeLegacy); - } - else - { - test(cLargeCorrected); - } } { bool caught = false; @@ -357,14 +286,14 @@ public: {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::kMaxRep}, Number{6, -1}, Number{Number::kMaxRep - 1}}, - {Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}}, + {Number{Number::kMAX_REP}, Number{6, -1}, Number{Number::kMAX_REP - 1}}, + {Number{false, Number::kMAX_REP + 1, 0, Number::Normalized{}}, Number{1, 0}, - Number{(Number::kMaxRep / 10) + 1, 1}}, - {Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}}, + Number{(Number::kMAX_REP / 10) + 1, 1}}, + {Number{false, Number::kMAX_REP + 1, 0, Number::Normalized{}}, Number{3, 0}, - Number{Number::kMaxRep}}, - {power(2, 63), Number{3, 0}, Number{Number::kMaxRep}}, + Number{Number::kMAX_REP}}, + {power(2, 63), Number{3, 0}, Number{Number::kMAX_REP}}, }); auto test = [this](auto const& c) { for (auto const& [x, y, z] : c) @@ -473,8 +402,8 @@ public: Number{false, maxMantissa, 0, Number::Normalized{}}, Number{1, 38}}, // Maximum int64 range - {Number{Number::kMaxRep, 0}, - Number{Number::kMaxRep, 0}, + {Number{Number::kMAX_REP, 0}, + Number{Number::kMAX_REP, 0}, Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); @@ -540,8 +469,8 @@ public: Number{false, (maxMantissa / 10) - 1, 20, Number::Normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::kMaxRep, 0}, - Number{Number::kMaxRep, 0}, + {Number{Number::kMAX_REP, 0}, + Number{Number::kMAX_REP, 0}, Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); @@ -607,8 +536,8 @@ public: Number{false, (maxMantissa / 10) - 1, 20, Number::Normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::kMaxRep, 0}, - Number{Number::kMaxRep, 0}, + {Number{Number::kMAX_REP, 0}, + Number{Number::kMAX_REP, 0}, Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); @@ -674,8 +603,8 @@ public: Number{1, 38}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::kMaxRep, 0}, - Number{Number::kMaxRep, 0}, + {Number{Number::kMAX_REP, 0}, + Number{Number::kMAX_REP, 0}, Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); @@ -906,7 +835,7 @@ public: /* auto tests = [&](auto const& cSmall, auto const& cLarge) { test(cSmall); - if (scale != MantissaRange::MantissaScale::Small) + if (scale != MantissaRange::mantissa_scale::small) test(cLarge); }; */ @@ -928,10 +857,10 @@ public: {Number{false, Number::maxMantissa() - 9, 0, Number::Normalized{}}, 2, Number{false, 3'162'277'660'168'379'330, -9, Number::Normalized{}}}, - {Number{Number::kMaxRep}, + {Number{Number::kMAX_REP}, 2, Number{false, 3'037'000'499'976049692, -9, Number::Normalized{}}}, - {Number{Number::kMaxRep}, + {Number{Number::kMAX_REP}, 4, Number{false, 55'108'98747006743627, -14, Number::Normalized{}}}, }); @@ -989,7 +918,7 @@ public: Number{5, -1}, Number{0}, Number{5625, -4}, - Number{Number::kMaxRep}, + Number{Number::kMAX_REP}, }); test(cSmall); bool caught = false; @@ -1337,7 +1266,6 @@ public: "9223372036854775e3"); } break; - case MantissaRange::MantissaScale::LargeLegacy: case MantissaRange::MantissaScale::Large: // Test the edges // ((exponent < -(28)) || (exponent > -(8))))) @@ -1583,12 +1511,12 @@ public: if (scale == MantissaRange::MantissaScale::Small) { - BEAST_EXPECT(std::numeric_limits::max() > kInitialXrp.drops()); - BEAST_EXPECT(Number::maxMantissa() < kInitialXrp.drops()); - Number const initalXrp{kInitialXrp}; + BEAST_EXPECT(std::numeric_limits::max() > kINITIAL_XRP.drops()); + BEAST_EXPECT(Number::maxMantissa() < kINITIAL_XRP.drops()); + Number const initalXrp{kINITIAL_XRP}; BEAST_EXPECT(initalXrp.exponent() > 0); - Number const maxInt64{Number::kMaxRep}; + Number const maxInt64{Number::kMAX_REP}; 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})); @@ -1600,12 +1528,12 @@ public: } else { - BEAST_EXPECT(std::numeric_limits::max() > kInitialXrp.drops()); - BEAST_EXPECT(Number::maxMantissa() > kInitialXrp.drops()); - Number const initalXrp{kInitialXrp}; + BEAST_EXPECT(std::numeric_limits::max() > kINITIAL_XRP.drops()); + BEAST_EXPECT(Number::maxMantissa() > kINITIAL_XRP.drops()); + Number const initalXrp{kINITIAL_XRP}; BEAST_EXPECT(initalXrp.exponent() <= 0); - Number const maxInt64{Number::kMaxRep}; + Number const maxInt64{Number::kMAX_REP}; 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})); @@ -1623,258 +1551,11 @@ public: } } - void - testUpwardRoundsDown() - { - auto const scale = Number::getMantissaScale(); - { - testcase << "upward rounding produces a value below exact at kMaxRep cusp " - << to_string(scale); - - NumberRoundModeGuard const rg{Number::RoundingMode::Upward}; - - constexpr std::int64_t kAValue = 1'000'000'000'000'049'863LL; - constexpr std::int64_t kBValue = 9'223'372'036'854'315'903LL; - - Number const a = kAValue; - Number const b = kBValue; - Number const product = a * b; - - // Exact reference in BigInt. - BigInt const exactProduct = BigInt(kAValue) * BigInt(kBValue); - - // What Number actually stored. - BigInt storedValue = BigInt(product.mantissa()); - for (int i = 0; i < product.exponent(); ++i) - storedValue *= 10; - - BigInt const signedDifference = storedValue - exactProduct; - - log << "\n" - << " a = " << fmt(BigInt(kAValue)) << "\n" - << " b = " << fmt(BigInt(kBValue)) << "\n" - << " exact a*b = " << fmt(exactProduct) << "\n" - << " stored = " << fmt(storedValue) << "\n" - << " stored - exact = " << fmt(signedDifference) << "\n" - << " upward = " << (signedDifference >= 0 ? "held" : "VIOLATED") << "\n" - << " stored.mantissa = " << product.mantissa() << "\n" - << " stored.exponent = " << product.exponent() << "\n"; - log.flush(); - - switch (scale) - { - case MantissaRange::MantissaScale::Large: - BEAST_EXPECT(signedDifference >= 0); - BEAST_EXPECT(signedDifference < pow10(product.exponent())); - BEAST_EXPECT( - product.mantissa() == (std::numeric_limits::max() / 10) + 1); - BEAST_EXPECT(product.exponent() == 19); - break; - - case MantissaRange::MantissaScale::LargeLegacy: - BEAST_EXPECT(signedDifference < 0); - BEAST_EXPECT( - product.mantissa() == - (std::numeric_limits::max() / 100) * 100); - BEAST_EXPECT(product.exponent() == 18); - break; - - case MantissaRange::MantissaScale::Small: - // The seemingly weird rounding here is because - // a & b are both normalized, and both round up when - // being converted to Number, so you're really - // getting 1_000_000_000_000_050 * 9_223_372_036_854_316 - BEAST_EXPECT(signedDifference >= 0); - BEAST_EXPECT( - product.mantissa() == - (std::numeric_limits::max() / 1000) + 3); - BEAST_EXPECT(product.exponent() == 21); - break; - } - } - - { - /* Companion regression for the kMaxRep cusp behavior, but for - * `operator/=` on the cusp-fix-ENABLED `Large` scale. - * - * Before the dropped-remainder fix, `operator/=` with Upward - * rounding could return a value STRICTLY LESS than the exact quotient, - * violating Upward's directional invariant. - * - * Mechanism (fix-enabled path): - * 1. `operator/=` computes `numerator = nm * 10^17` and - * `zm = numerator / dm` (integer division, truncates remainder). - * 2. If `remainder != 0`, the correction block runs: - * zm *= 100000 - * correction = (remainder * 100000) / dm // also truncates - * zm += correction - * ze -= 5 - * The truncation in `correction` discards a sub-1/100000 residual. - * 3. `normalize`'s shift loop reduces zm to fit, but the discarded - * residual is BELOW the Guard's visibility, so the Guard sees fraction = 0. - * 4. Under Upward + positive, `round()` returns -1 (no round-up), and - * the algorithm returns the truncated zm - */ - testcase << "operator/= Upward on Large returns value < truth " << to_string(scale); - - NumberRoundModeGuard const roundGuard{Number::RoundingMode::Upward}; - - constexpr std::int64_t aValue = 2LL; - constexpr std::int64_t bValue = 1'000'000'000'000'000'007LL; - // bValue = 10^18 + 7 (prime, in [minMantissa, kMaxRep]). - - Number const a{aValue, 0}; - Number const b{bValue, 0}; - Number const quotient = a / b; - - dec const exact = dec(aValue) / dec(bValue); - dec const stored = dec(quotient.mantissa()) * pow10(quotient.exponent()); - dec const diff = stored - exact; - - log << "\n" - << " a = " << aValue << "\n" - << " b = " << bValue << "\n" - << " exact a/b = " << fmt(exact) << "\n" - << " stored a/b = " << fmt(stored) << "\n" - << " stored - exact = " << fmt(diff) - << " (negative => Upward gave value BELOW truth)\n" - << " quotient.mantissa = " << quotient.mantissa() << "\n" - << " quotient.exponent = " << quotient.exponent() << "\n"; - log.flush(); - - // Upward invariant: stored >= exact. Bug: stored < exact. - switch (scale) - { - case MantissaRange::MantissaScale::Large: - BEAST_EXPECT(stored >= exact); - BEAST_EXPECT(diff < pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::LargeLegacy: - BEAST_EXPECT(stored < exact); - BEAST_EXPECT(diff >= -pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::Small: - // Small mantissa doesn't have the correction for - // dropped remainders - BEAST_EXPECT(stored < exact); - break; - } - } - { - /* Companion test case for Upward positive operator/=: Downward negative - */ - testcase << "operator/= Downward on Large returns value < truth " << to_string(scale); - - NumberRoundModeGuard const roundGuard{Number::RoundingMode::Downward}; - - constexpr std::int64_t aValue = -2LL; - constexpr std::int64_t bValue = 1'000'000'000'000'000'007LL; - // bValue = 10^18 + 7 (prime, in [minMantissa, kMaxRep]). - - Number const a{aValue, 0}; - Number const b{bValue, 0}; - Number const quotient = a / b; - - dec const exact = dec(aValue) / dec(bValue); - dec const stored = dec(quotient.mantissa()) * pow10(quotient.exponent()); - dec const diff = stored - exact; - - log << "\n" - << " a = " << aValue << "\n" - << " b = " << bValue << "\n" - << " exact a/b = " << fmt(exact) << "\n" - << " stored a/b = " << fmt(stored) << "\n" - << " stored - exact = " << fmt(diff) - << " (positive => Downward gave value ABOVE truth)\n" - << " quotient.mantissa = " << quotient.mantissa() << "\n" - << " quotient.exponent = " << quotient.exponent() << "\n"; - log.flush(); - - // invariant: stored <= exact. Bug: stored > exact. - switch (scale) - { - case MantissaRange::MantissaScale::Large: - BEAST_EXPECT(stored <= exact); - BEAST_EXPECT(diff > -pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::LargeLegacy: - BEAST_EXPECT(stored > exact); - BEAST_EXPECT(diff <= pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::Small: - // Small mantissa doesn't have the correction for - // dropped remainders - BEAST_EXPECT(stored < exact); - break; - } - } - { - /* Companion test case for Upward positive operator/=: ToNearest - * - * With ToNearest, if the dropped digits are exactly "5", then the mantissa will be - * rounded to even. The numbers below result in a value where the unrounded mantissa - * ends in an even digit, and "infinite precision" would drop - * "500000000000000000145...", but doNormalize only sees "5". Without the rounding fix, - * doNormalize rounds down to the even value. With the rounding fix, doNormalize knows - * there are more digits beyond "5", and so rounds _up_ to the odd value. - */ - testcase << "operator/= ToNearest on Large returns value < truth " << to_string(scale); - - NumberRoundModeGuard const roundGuard{Number::RoundingMode::ToNearest}; - - constexpr std::int64_t aValue = 1'269'917'268'816'087'809LL; - constexpr std::int64_t bValue = 3'458'525'013'821'685'511LL; - // bValue = 10^18 + 7 (prime, in [minMantissa, kMaxRep]). - - Number const a{aValue, 0}; - Number const b{bValue, 0}; - Number const quotient = a / b; - - dec const exact = dec(aValue) / dec(bValue); - dec const stored = dec(quotient.mantissa()) * pow10(quotient.exponent()); - dec const diff = stored - exact; - - log << "\n" - << " a = " << aValue << "\n" - << " b = " << bValue << "\n" - << " exact a/b = " << fmt(exact) << "\n" - << " stored a/b = " << fmt(stored) << "\n" - << " stored - exact = " << fmt(diff) - << " (negative => ToNearest gave value BELOW truth)\n" - << " quotient.mantissa = " << quotient.mantissa() << "\n" - << " quotient.exponent = " << quotient.exponent() << "\n"; - log.flush(); - - // invariant: stored >= exact. Bug: stored < exact. - switch (scale) - { - case MantissaRange::MantissaScale::Large: - BEAST_EXPECT(stored >= exact); - BEAST_EXPECT(diff < pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::LargeLegacy: - BEAST_EXPECT(stored < exact); - BEAST_EXPECT(diff >= -pow10(quotient.exponent())); - break; - - case MantissaRange::MantissaScale::Small: - // Small mantissa doesn't have the correction for - // dropped remainders - BEAST_EXPECT(stored < exact); - break; - } - } - } - void run() override { - for (auto const scale : MantissaRange::getAllScales()) + for (auto const scale : + {MantissaRange::MantissaScale::Small, MantissaRange::MantissaScale::Large}) { NumberMantissaScaleGuard const sg(scale); testZero(); @@ -1898,8 +1579,6 @@ public: testTruncate(); testRounding(); testInt64(); - - testUpwardRoundsDown(); } } }; diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index c370c241c5..00b2f90c65 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -47,7 +47,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::Severity::Disabled}; + test::jtx::Env env_{*this, test::jtx::envconfig(), nullptr, beast::severities::KDisabled}; beast::Journal j_{env_.app().getJournal("PerfLog_test")}; struct Fixture @@ -154,9 +154,9 @@ class PerfLog_test : public beast::unit_test::Suite // Return a uint64 from a JSON string. static std::uint64_t - jsonToUInt64(json::Value const& jsonUIntAsString) + jsonToUint64(json::Value const& jsonUintAsString) { - return std::stoull(jsonUIntAsString.asString()); + return std::stoull(jsonUintAsString.asString()); } // The PerfLog's current state is easier to sort by duration if the @@ -183,7 +183,7 @@ class PerfLog_test : public beast::unit_test::Suite for (json::Value const& cur : currentJson) { currents.emplace_back( - jsonToUInt64(cur[jss::duration_us]), + jsonToUint64(cur[jss::duration_us]), cur.isMember(jss::job) ? cur[jss::job].asString() : cur[jss::method].asString()); } @@ -358,7 +358,7 @@ public: BEAST_EXPECT(total[jss::duration_us] == "0"); BEAST_EXPECT(total[jss::errored] == "0"); BEAST_EXPECT(total[jss::finished] == "0"); - BEAST_EXPECT(jsonToUInt64(total[jss::started]) == ids.size()); + BEAST_EXPECT(jsonToUint64(total[jss::started]) == ids.size()); } { // Verify that every entry in labels appears twice in currents. @@ -416,7 +416,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"); @@ -427,9 +427,9 @@ 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::finished]) == labels.size()); - BEAST_EXPECT(jsonToUInt64(total[jss::started]) == labels.size() * 2); + 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); }; auto validateFinalCurrent = [this, &labels](json::Value const& currentJson) { @@ -553,7 +553,7 @@ public: // Verify jss::total is present and has expected values. json::Value const& total{jqCounters[jss::total]}; BEAST_EXPECT(total.size() == 5); - BEAST_EXPECT(jsonToUInt64(total[jss::queued]) == i + 1); + BEAST_EXPECT(jsonToUint64(total[jss::queued]) == i + 1); BEAST_EXPECT(total[jss::started] == "0"); BEAST_EXPECT(total[jss::finished] == "0"); BEAST_EXPECT(total[jss::queued_duration_us] == "0"); @@ -589,7 +589,7 @@ public: for (int j = 0; j < jobs.size(); ++j) { json::Value const& counter{jqCounters[jobs[j].typeName]}; - std::uint64_t const queuedDurUs{jsonToUInt64(counter[jss::queued_duration_us])}; + std::uint64_t const queuedDurUs{jsonToUint64(counter[jss::queued_duration_us])}; if (j < i) { BEAST_EXPECT(counter[jss::started] == "2"); @@ -613,13 +613,13 @@ public: { // Verify values in jss::total are what we expect. json::Value const& total{jqCounters[jss::total]}; - BEAST_EXPECT(jsonToUInt64(total[jss::queued]) == jobs.size()); - BEAST_EXPECT(jsonToUInt64(total[jss::started]) == (i * 2) + 1); + BEAST_EXPECT(jsonToUint64(total[jss::queued]) == jobs.size()); + BEAST_EXPECT(jsonToUint64(total[jss::started]) == (i * 2) + 1); 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)); + jsonToUint64(total[jss::queued_duration_us]) == (((i * i) + 3 * i + 2) / 2)); BEAST_EXPECT(total[jss::running_duration_us] == "0"); } @@ -658,7 +658,7 @@ public: for (int j = 0; j < jobs.size(); ++j) { json::Value const& counter{jqCounters[jobs[j].typeName]}; - std::uint64_t const runningDurUs{jsonToUInt64(counter[jss::running_duration_us])}; + std::uint64_t const runningDurUs{jsonToUint64(counter[jss::running_duration_us])}; if (j < i) { BEAST_EXPECT(counter[jss::finished] == "0"); @@ -675,7 +675,7 @@ public: BEAST_EXPECT(runningDurUs == ((jobs.size() - j) * 4) - 1); } - std::uint64_t const queuedDurUs{jsonToUInt64(counter[jss::queued_duration_us])}; + std::uint64_t const queuedDurUs{jsonToUint64(counter[jss::queued_duration_us])}; BEAST_EXPECT(queuedDurUs == j + 1); BEAST_EXPECT(counter[jss::queued] == "1"); BEAST_EXPECT(counter[jss::started] == "2"); @@ -683,18 +683,18 @@ public: { // Verify values in jss::total are what we expect. json::Value const& total{jqCounters[jss::total]}; - BEAST_EXPECT(jsonToUInt64(total[jss::queued]) == jobs.size()); - BEAST_EXPECT(jsonToUInt64(total[jss::started]) == jobs.size() * 2); - BEAST_EXPECT(jsonToUInt64(total[jss::finished]) == finished); + BEAST_EXPECT(jsonToUint64(total[jss::queued]) == jobs.size()); + 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)); @@ -730,10 +730,10 @@ public: for (int i = jobs.size() - 1; i >= 0; --i) { json::Value const& counter{jobQueue[jobs[i].typeName]}; - std::uint64_t const runningDurUs{jsonToUInt64(counter[jss::running_duration_us])}; + std::uint64_t const runningDurUs{jsonToUint64(counter[jss::running_duration_us])}; BEAST_EXPECT(runningDurUs == ((jobs.size() - i) * 4) - 1); - std::uint64_t const queuedDurUs{jsonToUInt64(counter[jss::queued_duration_us])}; + std::uint64_t const queuedDurUs{jsonToUint64(counter[jss::queued_duration_us])}; BEAST_EXPECT(queuedDurUs == i + 1); BEAST_EXPECT(counter[jss::queued] == "1"); @@ -744,18 +744,18 @@ public: // Verify values in jss::total are what we expect. json::Value const& total{jobQueue[jss::total]}; int const finished = jobs.size() * 2; - BEAST_EXPECT(jsonToUInt64(total[jss::queued]) == jobs.size()); - BEAST_EXPECT(jsonToUInt64(total[jss::started]) == finished); - BEAST_EXPECT(jsonToUInt64(total[jss::finished]) == finished); + BEAST_EXPECT(jsonToUint64(total[jss::queued]) == jobs.size()); + BEAST_EXPECT(jsonToUint64(total[jss::started]) == finished); + 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); }; auto validateFinalCurrent = [this](json::Value const& currentJson) { @@ -867,12 +867,12 @@ public: 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(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]) == queuedUs); - BEAST_EXPECT(jsonToUInt64(job[jss::running_duration_us]) == runningUs); + BEAST_EXPECT(jsonToUint64(job[jss::queued_duration_us]) == queuedUs); + BEAST_EXPECT(jsonToUint64(job[jss::running_duration_us]) == runningUs); } }; diff --git a/src/test/basics/TaggedCache_test.cpp b/src/test/basics/TaggedCache_test.cpp index 77cd25e543..c728536e08 100644 --- a/src/test/basics/TaggedCache_test.cpp +++ b/src/test/basics/TaggedCache_test.cpp @@ -4,7 +4,6 @@ #include // IWYU pragma: keep #include #include -#include #include #include @@ -28,7 +27,7 @@ public: run() override { using namespace std::chrono_literals; - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("TaggedCache_test", *this); TestStopwatch clock; diff --git a/src/test/basics/Units_test.cpp b/src/test/basics/Units_test.cpp index dc780166c6..4a224a2708 100644 --- a/src/test/basics/Units_test.cpp +++ b/src/test/basics/Units_test.cpp @@ -96,56 +96,56 @@ private: { FeeLevel32 const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::UInt); + BEAST_EXPECT(y.type() == json::UintValue); BEAST_EXPECT(y == json::Value{x.fee()}); } { FeeLevel32 const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::UInt); + BEAST_EXPECT(y.type() == json::UintValue); BEAST_EXPECT(y == json::Value{x.fee()}); } { FeeLevel64 const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::UInt); + BEAST_EXPECT(y.type() == json::UintValue); BEAST_EXPECT(y == json::Value{std::numeric_limits::max()}); } { FeeLevel64 const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::UInt); + BEAST_EXPECT(y.type() == json::UintValue); BEAST_EXPECT(y == json::Value{0}); } { FeeLevelDouble const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::Real); + BEAST_EXPECT(y.type() == json::RealValue); BEAST_EXPECT(y == json::Value{std::numeric_limits::max()}); } { FeeLevelDouble const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::Real); + BEAST_EXPECT(y.type() == json::RealValue); BEAST_EXPECT(y == json::Value{std::numeric_limits::min()}); } { XRPAmount const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::Int); + BEAST_EXPECT(y.type() == json::IntValue); BEAST_EXPECT(y == json::Value{std::numeric_limits::max()}); } { XRPAmount const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); - BEAST_EXPECT(y.type() == json::ValueType::Int); + BEAST_EXPECT(y.type() == json::IntValue); BEAST_EXPECT(y == json::Value{std::numeric_limits::min()}); } } @@ -166,10 +166,10 @@ private: FeeLevel64 test{0}; BEAST_EXPECT(test.fee() == 0); - test = explicitmake(beast::kZero); + test = explicitmake(beast::kZERO); BEAST_EXPECT(test.fee() == 0); - test = beast::kZero; + test = beast::kZERO; BEAST_EXPECT(test.fee() == 0); test = explicitmake(100u); @@ -251,10 +251,10 @@ private: FeeLevelDouble test{0}; BEAST_EXPECT(test.fee() == 0); - test = explicitmake(beast::kZero); + test = explicitmake(beast::kZERO); BEAST_EXPECT(test.fee() == 0); - test = beast::kZero; + test = beast::kZERO; BEAST_EXPECT(test.fee() == 0); test = explicitmake(100.0); @@ -330,8 +330,8 @@ public: void run() override { - BEAST_EXPECT(kInitialXrp.drops() == 100'000'000'000'000'000); - BEAST_EXPECT(kInitialXrp == XRPAmount{100'000'000'000'000'000}); + BEAST_EXPECT(kINITIAL_XRP.drops() == 100'000'000'000'000'000); + BEAST_EXPECT(kINITIAL_XRP == XRPAmount{100'000'000'000'000'000}); testTypes(); testJson(); diff --git a/src/test/basics/XRPAmount_test.cpp b/src/test/basics/XRPAmount_test.cpp index f393003365..50cd17b3bc 100644 --- a/src/test/basics/XRPAmount_test.cpp +++ b/src/test/basics/XRPAmount_test.cpp @@ -39,25 +39,25 @@ public: { testcase("beast::Zero Comparisons"); - using beast::kZero; + using beast::kZERO; for (auto i : {-1, 0, 1}) { XRPAmount const x(i); - BEAST_EXPECT((i == 0) == (x == kZero)); - BEAST_EXPECT((i != 0) == (x != kZero)); - BEAST_EXPECT((i < 0) == (x < kZero)); - BEAST_EXPECT((i > 0) == (x > kZero)); - BEAST_EXPECT((i <= 0) == (x <= kZero)); - BEAST_EXPECT((i >= 0) == (x >= kZero)); + BEAST_EXPECT((i == 0) == (x == kZERO)); + BEAST_EXPECT((i != 0) == (x != kZERO)); + BEAST_EXPECT((i < 0) == (x < kZERO)); + BEAST_EXPECT((i > 0) == (x > kZERO)); + BEAST_EXPECT((i <= 0) == (x <= kZERO)); + BEAST_EXPECT((i >= 0) == (x >= kZERO)); - BEAST_EXPECT((0 == i) == (kZero == x)); - BEAST_EXPECT((0 != i) == (kZero != x)); - BEAST_EXPECT((0 < i) == (kZero < x)); - BEAST_EXPECT((0 > i) == (kZero > x)); - BEAST_EXPECT((0 <= i) == (kZero <= x)); - BEAST_EXPECT((0 >= i) == (kZero >= x)); + BEAST_EXPECT((0 == i) == (kZERO == x)); + BEAST_EXPECT((0 != i) == (kZERO != x)); + BEAST_EXPECT((0 < i) == (kZERO < x)); + BEAST_EXPECT((0 > i) == (kZERO > x)); + BEAST_EXPECT((0 <= i) == (kZERO <= x)); + BEAST_EXPECT((0 >= i) == (kZERO >= x)); } } @@ -109,7 +109,7 @@ public: testDecimal() { // Tautology - BEAST_EXPECT(kDropsPerXrp.decimalXRP() == 1); + BEAST_EXPECT(kDROPS_PER_XRP.decimalXRP() == 1); XRPAmount test{1}; BEAST_EXPECT(test.decimalXRP() == 0.000001); @@ -136,10 +136,10 @@ public: XRPAmount test{0}; BEAST_EXPECT(test.drops() == 0); - test = make(beast::kZero); + test = make(beast::kZERO); BEAST_EXPECT(test.drops() == 0); - test = beast::kZero; + test = beast::kZERO; BEAST_EXPECT(test.drops() == 0); test = make(100); @@ -212,17 +212,17 @@ public: { testcase("mulRatio"); - constexpr auto kMaxUInt32 = std::numeric_limits::max(); - constexpr auto kMaxXrp = std::numeric_limits::max(); - constexpr auto kMinXrp = std::numeric_limits::min(); + constexpr auto kMAX_U_INT32 = std::numeric_limits::max(); + constexpr auto kMAX_XRP = std::numeric_limits::max(); + constexpr auto kMIN_XRP = std::numeric_limits::min(); { // multiply by a number that would overflow then divide by the same // number, and check we didn't lose any value - XRPAmount big(kMaxXrp); - BEAST_EXPECT(big == mulRatio(big, kMaxUInt32, kMaxUInt32, true)); + XRPAmount big(kMAX_XRP); + BEAST_EXPECT(big == mulRatio(big, kMAX_U_INT32, kMAX_U_INT32, true)); // rounding mode shouldn't matter as the result is exact - BEAST_EXPECT(big == mulRatio(big, kMaxUInt32, kMaxUInt32, false)); + BEAST_EXPECT(big == mulRatio(big, kMAX_U_INT32, kMAX_U_INT32, false)); // multiply and divide by values that would overflow if done // naively, and check that it gives the correct answer @@ -234,10 +234,10 @@ public: { // Similar test as above, but for negative values - XRPAmount big(kMinXrp); // NOLINT TODO - BEAST_EXPECT(big == mulRatio(big, kMaxUInt32, kMaxUInt32, true)); + XRPAmount big(kMIN_XRP); // NOLINT TODO + BEAST_EXPECT(big == mulRatio(big, kMAX_U_INT32, kMAX_U_INT32, true)); // rounding mode shouldn't matter as the result is exact - BEAST_EXPECT(big == mulRatio(big, kMaxUInt32, kMaxUInt32, false)); + BEAST_EXPECT(big == mulRatio(big, kMAX_U_INT32, kMAX_U_INT32, false)); // multiply and divide by values that would overflow if done // naively, and check that it gives the correct answer @@ -250,39 +250,39 @@ public: // small amounts XRPAmount const tiny(1); // Round up should give the smallest allowable number - BEAST_EXPECT(tiny == mulRatio(tiny, 1, kMaxUInt32, true)); + BEAST_EXPECT(tiny == mulRatio(tiny, 1, kMAX_U_INT32, true)); // rounding down should be zero - BEAST_EXPECT(beast::kZero == mulRatio(tiny, 1, kMaxUInt32, false)); - BEAST_EXPECT(beast::kZero == mulRatio(tiny, kMaxUInt32 - 1, kMaxUInt32, false)); + BEAST_EXPECT(beast::kZERO == mulRatio(tiny, 1, kMAX_U_INT32, false)); + BEAST_EXPECT(beast::kZERO == mulRatio(tiny, kMAX_U_INT32 - 1, kMAX_U_INT32, false)); // tiny negative numbers XRPAmount const tinyNeg(-1); // Round up should give zero - BEAST_EXPECT(beast::kZero == mulRatio(tinyNeg, 1, kMaxUInt32, true)); - BEAST_EXPECT(beast::kZero == mulRatio(tinyNeg, kMaxUInt32 - 1, kMaxUInt32, true)); + BEAST_EXPECT(beast::kZERO == mulRatio(tinyNeg, 1, kMAX_U_INT32, true)); + BEAST_EXPECT(beast::kZERO == mulRatio(tinyNeg, kMAX_U_INT32 - 1, kMAX_U_INT32, true)); // rounding down should be tiny - BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, kMaxUInt32 - 1, kMaxUInt32, false)); + BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, kMAX_U_INT32 - 1, kMAX_U_INT32, false)); } { // rounding { XRPAmount const one(1); - auto const rup = mulRatio(one, kMaxUInt32 - 1, kMaxUInt32, true); - auto const rdown = mulRatio(one, kMaxUInt32 - 1, kMaxUInt32, false); + auto const rup = mulRatio(one, kMAX_U_INT32 - 1, kMAX_U_INT32, true); + auto const rdown = mulRatio(one, kMAX_U_INT32 - 1, kMAX_U_INT32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { - XRPAmount const big(kMaxXrp); - auto const rup = mulRatio(big, kMaxUInt32 - 1, kMaxUInt32, true); - auto const rdown = mulRatio(big, kMaxUInt32 - 1, kMaxUInt32, false); + XRPAmount const big(kMAX_XRP); + auto const rup = mulRatio(big, kMAX_U_INT32 - 1, kMAX_U_INT32, true); + auto const rdown = mulRatio(big, kMAX_U_INT32 - 1, kMAX_U_INT32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { XRPAmount const negOne(-1); - auto const rup = mulRatio(negOne, kMaxUInt32 - 1, kMaxUInt32, true); - auto const rdown = mulRatio(negOne, kMaxUInt32 - 1, kMaxUInt32, false); + auto const rup = mulRatio(negOne, kMAX_U_INT32 - 1, kMAX_U_INT32, true); + auto const rdown = mulRatio(negOne, kMAX_U_INT32 - 1, kMAX_U_INT32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } } @@ -295,14 +295,14 @@ public: { // overflow - XRPAmount big(kMaxXrp); + XRPAmount big(kMAX_XRP); except([&] { mulRatio(big, 2, 1, true); }); } { // underflow - XRPAmount const bigNegative(kMinXrp + 10); - BEAST_EXPECT(mulRatio(bigNegative, 2, 1, true) == kMinXrp); + XRPAmount const bigNegative(kMIN_XRP + 10); + BEAST_EXPECT(mulRatio(bigNegative, 2, 1, true) == kMIN_XRP); } } // namespace xrpl diff --git a/src/test/basics/base58_test.cpp b/src/test/basics/base58_test.cpp index 3c76308813..e0a9433f4e 100644 --- a/src/test/basics/base58_test.cpp +++ b/src/test/basics/base58_test.cpp @@ -38,12 +38,12 @@ randEngine() -> std::mt19937& return kR; } -constexpr int kNumTokenTypeIndexes = 9; +constexpr int kNUM_TOKEN_TYPE_INDEXES = 9; [[nodiscard]] inline auto tokenTypeAndSize(int i) -> std::tuple { - assert(i < kNumTokenTypeIndexes); + assert(i < kNUM_TOKEN_TYPE_INDEXES); switch (i) { @@ -166,11 +166,11 @@ class base58_test : public beast::unit_test::Suite using namespace boost::multiprecision; - static constexpr std::size_t kIters = 100000; + constexpr std::size_t kITERS = 100000; auto eng = randEngine(); std::uniform_int_distribution dist; std::uniform_int_distribution dist1(1); - for (int i = 0; i < kIters; ++i) + for (int i = 0; i < kITERS; ++i) { std::uint64_t const d = dist(eng); if (d == 0u) @@ -188,7 +188,7 @@ class base58_test : public beast::unit_test::Suite BEAST_EXPECT(refMod.convert_to() == mod); BEAST_EXPECT(foundDiv == refDiv); } - for (int i = 0; i < kIters; ++i) + for (int i = 0; i < kITERS; ++i) { std::uint64_t const d = dist(eng); auto bigInt = multiprecision_utils::randomBigInt(/*minSize*/ 2); @@ -207,7 +207,7 @@ class base58_test : public beast::unit_test::Suite auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd == foundAdd); } - for (int i = 0; i < kIters; ++i) + for (int i = 0; i < kITERS; ++i) { std::uint64_t const d = dist1(eng); // Force overflow @@ -224,7 +224,7 @@ class base58_test : public beast::unit_test::Suite auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd != foundAdd); } - for (int i = 0; i < kIters; ++i) + for (int i = 0; i < kITERS; ++i) { std::uint64_t const d = dist(eng); auto bigInt = multiprecision_utils::randomBigInt(/* minSize */ 2); @@ -242,7 +242,7 @@ class base58_test : public beast::unit_test::Suite auto const foundMul = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMul == foundMul); } - for (int i = 0; i < kIters; ++i) + for (int i = 0; i < kITERS; ++i) { std::uint64_t const d = dist1(eng); // Force overflow @@ -403,7 +403,7 @@ class base58_test : public beast::unit_test::Suite // test every token type with data where every byte is the same and the // bytes range from 0-255 - for (int i = 0; i < kNumTokenTypeIndexes; ++i) + for (int i = 0; i < kNUM_TOKEN_TYPE_INDEXES; ++i) { std::array b256DataBuf{}; auto const [tokType, tokSize] = tokenTypeAndSize(i); @@ -415,8 +415,8 @@ class base58_test : public beast::unit_test::Suite } // test with random data - static constexpr std::size_t kIters = 100000; - for (int i = 0; i < kIters; ++i) + constexpr std::size_t kITERS = 100000; + for (int i = 0; i < kITERS; ++i) { std::array b256DataBuf{}; auto const [tokType, b256Data] = randomB256TestData(b256DataBuf); diff --git a/src/test/basics/base_uint_test.cpp b/src/test/basics/base_uint_test.cpp index 5816b4eb59..cf5ece6240 100644 --- a/src/test/basics/base_uint_test.cpp +++ b/src/test/basics/base_uint_test.cpp @@ -26,30 +26,30 @@ namespace xrpl::test { template struct Nonhash { - static constexpr auto kEndian = boost::endian::order::big; - static constexpr std::size_t kWidth = Bits / 8; + static constexpr auto const kENDIAN = boost::endian::order::big; + static constexpr std::size_t kWIDTH = Bits / 8; - std::array data; + std::array data; Nonhash() = default; void operator()(void const* key, std::size_t len) noexcept { - assert(len == kWidth); + assert(len == kWIDTH); memcpy(data.data(), key, len); } explicit operator std::size_t() noexcept { - return kWidth; + return kWIDTH; } }; struct base_uint_test : beast::unit_test::Suite { - using test96 = BaseUInt<96>; + using test96 = BaseUint<96>; static_assert(std::is_copy_constructible_v); static_assert(std::is_copy_assignable_v); @@ -57,17 +57,18 @@ struct base_uint_test : beast::unit_test::Suite testComparisons() { { - static constexpr std::array, 6> kTestArgs{ - {{"0000000000000000", "0000000000000001"}, - {"0000000000000000", "ffffffffffffffff"}, - {"1234567812345678", "2345678923456789"}, - {"8000000000000000", "8000000000000001"}, - {"aaaaaaaaaaaaaaa9", "aaaaaaaaaaaaaaaa"}, - {"fffffffffffffffe", "ffffffffffffffff"}}}; + static constexpr std::array, 6> + kTEST_ARGS{ + {{"0000000000000000", "0000000000000001"}, + {"0000000000000000", "ffffffffffffffff"}, + {"1234567812345678", "2345678923456789"}, + {"8000000000000000", "8000000000000001"}, + {"aaaaaaaaaaaaaaa9", "aaaaaaaaaaaaaaaa"}, + {"fffffffffffffffe", "ffffffffffffffff"}}}; - for (auto const& arg : kTestArgs) + for (auto const& arg : kTEST_ARGS) { - xrpl::BaseUInt<64> const u{arg.first}, v{arg.second}; + xrpl::BaseUint<64> const u{arg.first}, v{arg.second}; BEAST_EXPECT(u < v); BEAST_EXPECT(u <= v); BEAST_EXPECT(u != v); @@ -86,8 +87,8 @@ struct base_uint_test : beast::unit_test::Suite } { - static constexpr std::array, 6> kTestArgs{ - { + static constexpr std::array, 6> + kTEST_ARGS{{ {"000000000000000000000000", "000000000000000000000001"}, {"000000000000000000000000", "ffffffffffffffffffffffff"}, {"0123456789ab0123456789ab", "123456789abc123456789abc"}, @@ -96,9 +97,9 @@ struct base_uint_test : beast::unit_test::Suite {"fffffffffffffffffffffffe", "ffffffffffffffffffffffff"}, }}; - for (auto const& arg : kTestArgs) + for (auto const& arg : kTEST_ARGS) { - xrpl::BaseUInt<96> const u{arg.first}, v{arg.second}; + xrpl::BaseUint<96> const u{arg.first}, v{arg.second}; BEAST_EXPECT(u < v); BEAST_EXPECT(u <= v); BEAST_EXPECT(u != v); @@ -131,9 +132,9 @@ struct base_uint_test : beast::unit_test::Suite std::unordered_set> uset; Blob const raw{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; - BEAST_EXPECT(test96::kBytes == raw.size()); + BEAST_EXPECT(test96::kBYTES == raw.size()); - test96 u = test96::fromRaw(raw); + test96 u{raw}; uset.insert(u); BEAST_EXPECT(raw.size() == u.size()); BEAST_EXPECT(to_string(u) == "0102030405060708090A0B0C"); @@ -154,7 +155,7 @@ struct base_uint_test : beast::unit_test::Suite // back into another base_uint (w) for comparison with the original Nonhash<96> h{}; hash_append(h, u); - test96 const w = test96::fromRaw(std::vector(h.data.begin(), h.data.end())); + test96 const w{std::vector(h.data.begin(), h.data.end())}; BEAST_EXPECT(w == u); test96 v{~u}; @@ -178,7 +179,7 @@ struct base_uint_test : beast::unit_test::Suite v = u; BEAST_EXPECT(v == u); - test96 z{beast::kZero}; + test96 z{beast::kZERO}; uset.insert(z); BEAST_EXPECT(to_string(z) == "000000000000000000000000"); BEAST_EXPECT(toShortString(z) == "00000000..."); @@ -198,12 +199,12 @@ struct base_uint_test : beast::unit_test::Suite n++; BEAST_EXPECT(n == test96(1)); n--; - BEAST_EXPECT(n == beast::kZero); + BEAST_EXPECT(n == beast::kZERO); BEAST_EXPECT(n == z); n--; BEAST_EXPECT(to_string(n) == "FFFFFFFFFFFFFFFFFFFFFFFF"); BEAST_EXPECT(toShortString(n) == "FFFFFFFF..."); - n = beast::kZero; + n = beast::kZERO; BEAST_EXPECT(n == z); test96 zp1{z}; @@ -326,16 +327,16 @@ struct base_uint_test : beast::unit_test::Suite // Verify that constexpr base_uints interpret a string the same // way parseHex() does. - struct StrBaseUInt + struct StrBaseUint { char const* const str; test96 tst; - constexpr StrBaseUInt(char const* s) : str(s), tst(s) + constexpr StrBaseUint(char const* s) : str(s), tst(s) { } }; - static constexpr StrBaseUInt kTestCases[] = { + constexpr StrBaseUint kTEST_CASES[] = { "000000000000000000000000", "000000000000000000000001", "fedcba9876543210ABCDEF91", @@ -343,7 +344,7 @@ struct base_uint_test : beast::unit_test::Suite "800000000000000000000000", "fFfFfFfFfFfFfFfFfFfFfFfF"}; - for (StrBaseUInt const& t : kTestCases) + for (StrBaseUint const& t : kTEST_CASES) { test96 t96; BEAST_EXPECT(t96.parseHex(t.str)); diff --git a/src/test/basics/hardened_hash_test.cpp b/src/test/basics/hardened_hash_test.cpp index 885ba9d60b..a4ecdf7081 100644 --- a/src/test/basics/hardened_hash_test.cpp +++ b/src/test/basics/hardened_hash_test.cpp @@ -90,22 +90,22 @@ private: static_assert(Bits >= (8 * sizeof(UInt)), "Bits must be at least 8*sizeof(UInt)"); - static std::size_t const kSize = Bits / (8 * sizeof(UInt)); + static std::size_t const kSIZE = Bits / (8 * sizeof(UInt)); - std::array vec_; + std::array vec_; public: using value_type = UInt; - static std::size_t const kBits = Bits; - static std::size_t const kBytes = kBits / 8; + static std::size_t const kBITS = Bits; + static std::size_t const kBYTES = kBITS / 8; template static UnsignedInteger fronumber(Int v) { UnsignedInteger result; - for (std::size_t i(1); i < kSize; ++i) + for (std::size_t i(1); i < kSIZE; ++i) result.vec_[i] = 0; result.vec_[0] = v; return result; @@ -134,7 +134,7 @@ public: friend std::ostream& operator<<(std::ostream& s, UnsignedInteger const& v) { - for (std::size_t i(0); i < kSize; ++i) + for (std::size_t i(0); i < kSIZE; ++i) s << std::hex << std::setfill('0') << std::setw(2 * sizeof(UInt)) << v.vec_[i]; return s; } @@ -143,7 +143,7 @@ public: using sha256_t = UnsignedInteger<256, std::size_t>; #ifndef __INTELLISENSE__ -static_assert(sha256_t::kBits == 256, "sha256_t must have 256 bits"); +static_assert(sha256_t::kBITS == 256, "sha256_t must have 256 bits"); #endif } // namespace xrpl diff --git a/src/test/basics/join_test.cpp b/src/test/basics/join_test.cpp index 1ee81f786a..cce8e19a92 100644 --- a/src/test/basics/join_test.cpp +++ b/src/test/basics/join_test.cpp @@ -58,8 +58,8 @@ struct join_test : beast::unit_test::Suite // vector with one item edge case using namespace jtx; test( - CollectionAndDelimiter(std::vector{Account::kMaster}, "xxx"), - Account::kMaster.human()); + CollectionAndDelimiter(std::vector{Account::kMASTER}, "xxx"), + Account::kMASTER.human()); } // empty vector edge case test(CollectionAndDelimiter(std::vector{}, ","), ""); diff --git a/src/test/beast/IPEndpoint_test.cpp b/src/test/beast/IPEndpoint_test.cpp index b1cd4709b4..0cf5e9794a 100644 --- a/src/test/beast/IPEndpoint_test.cpp +++ b/src/test/beast/IPEndpoint_test.cpp @@ -375,14 +375,14 @@ public: // test with hashed container std::unordered_set eps; - static constexpr auto kItems{100}; + constexpr auto kITEMS{100}; float maxLf{0}; - for (auto i = 0; i < kItems; ++i) + for (auto i = 0; i < kITEMS; ++i) { eps.insert(randomEP(xrpl::randInt(0, 1) == 1)); maxLf = std::max(maxLf, eps.load_factor()); } - BEAST_EXPECT(eps.bucket_count() >= kItems); + BEAST_EXPECT(eps.bucket_count() >= kITEMS); BEAST_EXPECT(maxLf > 0.90); } diff --git a/src/test/beast/beast_CurrentThreadName_test.cpp b/src/test/beast/beast_CurrentThreadName_test.cpp index 1aed0fb426..570dcae0ba 100644 --- a/src/test/beast/beast_CurrentThreadName_test.cpp +++ b/src/test/beast/beast_CurrentThreadName_test.cpp @@ -52,7 +52,7 @@ private: beast::setCurrentThreadName(nameToSet); // Initialize buffer to be safe. - char actualName[beast::kMaxThreadNameLength + 1] = {}; + char actualName[beast::kMAX_THREAD_NAME_LENGTH + 1] = {}; pthread_getname_np(pthread_self(), actualName, sizeof(actualName)); BEAST_EXPECT(std::string(actualName) == expectedName); diff --git a/src/test/beast/beast_Journal_test.cpp b/src/test/beast/beast_Journal_test.cpp index f2d4359f72..4b58ed29a8 100644 --- a/src/test/beast/beast_Journal_test.cpp +++ b/src/test/beast/beast_Journal_test.cpp @@ -14,7 +14,7 @@ public: int count_{0}; public: - TestSink() : Sink(Severity::Warning, false) + TestSink() : Sink(severities::KWarning, false) { } @@ -31,14 +31,14 @@ public: } void - write(Severity level, std::string const&) override + write(severities::Severity level, std::string const&) override { if (level >= threshold()) ++count_; } void - writeAlways(Severity level, std::string const&) override + writeAlways(severities::Severity level, std::string const&) override { ++count_; } @@ -49,7 +49,8 @@ public: { TestSink sink; - sink.threshold(Severity::Info); + using namespace beast::severities; + sink.threshold(KInfo); Journal const j(sink); @@ -68,7 +69,7 @@ public: sink.reset(); - sink.threshold(Severity::Debug); + sink.threshold(KDebug); j.trace() << " "; BEAST_EXPECT(sink.count() == 0); diff --git a/src/test/beast/beast_Zero_test.cpp b/src/test/beast/beast_Zero_test.cpp index bb61844caa..ca5f45ce6b 100644 --- a/src/test/beast/beast_Zero_test.cpp +++ b/src/test/beast/beast_Zero_test.cpp @@ -55,12 +55,12 @@ public: void testLhsZero(IntegerWrapper x) { - expectSame(x >= kZero, x.signum() >= 0, "lhs greater-than-or-equal-to"); - expectSame(x > kZero, x.signum() > 0, "lhs greater than"); - expectSame(x == kZero, x.signum() == 0, "lhs equal to"); - expectSame(x != kZero, x.signum() != 0, "lhs not equal to"); - expectSame(x < kZero, x.signum() < 0, "lhs less than"); - expectSame(x <= kZero, x.signum() <= 0, "lhs less-than-or-equal-to"); + expectSame(x >= kZERO, x.signum() >= 0, "lhs greater-than-or-equal-to"); + expectSame(x > kZERO, x.signum() > 0, "lhs greater than"); + expectSame(x == kZERO, x.signum() == 0, "lhs equal to"); + expectSame(x != kZERO, x.signum() != 0, "lhs not equal to"); + expectSame(x < kZERO, x.signum() < 0, "lhs less than"); + expectSame(x <= kZERO, x.signum() <= 0, "lhs less-than-or-equal-to"); } void @@ -76,12 +76,12 @@ public: void testRhsZero(IntegerWrapper x) { - expectSame(kZero >= x, 0 >= x.signum(), "rhs greater-than-or-equal-to"); - expectSame(kZero > x, 0 > x.signum(), "rhs greater than"); - expectSame(kZero == x, 0 == x.signum(), "rhs equal to"); - expectSame(kZero != x, 0 != x.signum(), "rhs not equal to"); - expectSame(kZero < x, 0 < x.signum(), "rhs less than"); - expectSame(kZero <= x, 0 <= x.signum(), "rhs less-than-or-equal-to"); + expectSame(kZERO >= x, 0 >= x.signum(), "rhs greater-than-or-equal-to"); + expectSame(kZERO > x, 0 > x.signum(), "rhs greater than"); + expectSame(kZERO == x, 0 == x.signum(), "rhs equal to"); + expectSame(kZERO != x, 0 != x.signum(), "rhs not equal to"); + expectSame(kZERO < x, 0 < x.signum(), "rhs less than"); + expectSame(kZERO <= x, 0 <= x.signum(), "rhs less-than-or-equal-to"); } void @@ -97,8 +97,8 @@ public: void testAdl() { - expect(AdlTester{} == kZero, "ADL failure!"); - expect(inner_adl_test::AdlTester2{} == kZero, "ADL failure!"); + expect(AdlTester{} == kZERO, "ADL failure!"); + expect(inner_adl_test::AdlTester2{} == kZERO, "ADL failure!"); } void diff --git a/src/test/beast/beast_io_latency_probe_test.cpp b/src/test/beast/beast_io_latency_probe_test.cpp index 5f183ef091..a884256986 100644 --- a/src/test/beast/beast_io_latency_probe_test.cpp +++ b/src/test/beast/beast_io_latency_probe_test.cpp @@ -112,7 +112,7 @@ class io_latency_probe_test : public beast::unit_test::Suite, public beast::test struct TestSampler { - beast::IOLatencyProbe probe; + beast::IoLatencyProbe probe; std::vector durations; TestSampler(std::chrono::milliseconds interval, boost::asio::io_context& ios) diff --git a/src/test/conditions/PreimageSha256_test.cpp b/src/test/conditions/PreimageSha256_test.cpp index e9c1de30b3..055ba4b12e 100644 --- a/src/test/conditions/PreimageSha256_test.cpp +++ b/src/test/conditions/PreimageSha256_test.cpp @@ -73,7 +73,7 @@ class PreimageSha256_test : public beast::unit_test::Suite BEAST_EXPECT(validate(*f2, *c2, makeSlice(known[0].first))); BEAST_EXPECT(validate(*f2, *c2, makeSlice(known[0].second))); - // Shouldn't validate if the kFulfillment & condition don't match + // Shouldn't validate if the kFULFILLMENT & condition don't match // regardless of the message. BEAST_EXPECT(!validate(*f2, *c1)); BEAST_EXPECT(!validate(*f2, *c1, makeSlice(known[0].first))); diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 6cc8d4fde1..51d99367e7 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -453,7 +453,7 @@ public: // Vary the time it takes to process validations to exercise detecting // the wrong LCL at different phases of consensus - for (auto validationDelay : {0ms, parms.ledgerMinClose}) + for (auto validationDelay : {0ms, parms.ledgerMIN_CLOSE}) { // Consider 10 peers: // 0 1 2 3 4 5 6 7 8 9 @@ -492,7 +492,7 @@ public: CollectByNode jumps; sim.collectors.add(jumps); - BEAST_EXPECT(sim.trustGraph.canFork(parms.minConsensusPct / 100.)); + BEAST_EXPECT(sim.trustGraph.canFork(parms.minCONSENSUS_PCT / 100.)); // initial round to set prior state sim.run(1); @@ -637,7 +637,7 @@ public: slow.connect(network, round(1.1 * parms.ledgerGRANULARITY)); // Run to the ledger *prior* to decreasing the resolution - sim.run(kIncreaseLedgerTimeResolutionEvery - 2); + sim.run(kINCREASE_LEDGER_TIME_RESOLUTION_EVERY - 2); // In order to create the discrepancy, we want a case where if // X = effCloseTime(closeTime, resolution, parentCloseTime) @@ -1039,7 +1039,7 @@ public: #if 0 // Have all beast::journal output printed to stdout for (Peer* p : network) - p->sink.threshold(beast::Severity::All); + p->sink.threshold(beast::severities::kAll); // Print ledger accept and fully validated events to stdout StreamCollector sc{std::cout}; @@ -1086,7 +1086,7 @@ public: ConsensusParms const p; std::size_t peersUnchanged = 0; - auto logs = std::make_unique(beast::Severity::Error); + auto logs = std::make_unique(beast::severities::KError); auto j = logs->journal("Test"); auto clog = std::make_unique(); diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index 632361c799..e56785a46a 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -24,7 +24,7 @@ class LedgerTiming_test : public beast::unit_test::Suite run(bool previousAgree, std::uint32_t rounds) { TestRes res; - auto closeResolution = kLedgerDefaultTimeResolution; + auto closeResolution = kLEDGER_DEFAULT_TIME_RESOLUTION; auto nextCloseResolution = closeResolution; std::uint32_t round = 0; do diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 142077a42f..b4c98eadef 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -237,9 +237,9 @@ class NegativeUNL_test : public beast::unit_test::Suite std::vector publicKeys = createPublicKeys(3); // genesis ledger auto l = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -554,12 +554,12 @@ struct NetworkHistory createNodes() { assert(param.numNodes <= 256); - unlKeys = createPublicKeys(param.numNodes); + UNLKeys = createPublicKeys(param.numNodes); for (int i = 0; i < param.numNodes; ++i) { - unlKeySet.insert(unlKeys[i]); - unlNodeIDs.push_back(calcNodeID(unlKeys[i])); - unlNodeIdSet.insert(unlNodeIDs.back()); + UNLKeySet.insert(UNLKeys[i]); + UNLNodeIDs.push_back(calcNodeID(UNLKeys[i])); + UNLNodeIDSet.insert(UNLNodeIDs.back()); } } @@ -570,12 +570,12 @@ struct NetworkHistory bool createLedgerHistory() { - static uint256 kFakeAmendment; // So we have different genesis ledgers + static uint256 kFAKE_AMENDMENT; // So we have different genesis ledgers auto l = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), - std::vector{kFakeAmendment++}, + env.app().config().FEES.toFees(), + std::vector{kFAKE_AMENDMENT++}, env.app().getNodeFamily()); history.push_back(l); @@ -593,7 +593,7 @@ struct NetworkHistory OpenView accum(&*l); if (l->negativeUNL().size() < param.negUNLSize) { - auto tx = createTx(true, l->seq(), unlKeys[nidx]); + auto tx = createTx(true, l->seq(), UNLKeys[nidx]); if (!applyAndTestResult(env, accum, tx, true)) break; ++nidx; @@ -602,14 +602,14 @@ struct NetworkHistory { if (param.hasToDisable) { - auto tx = createTx(true, l->seq(), unlKeys[nidx]); + auto tx = createTx(true, l->seq(), UNLKeys[nidx]); if (!applyAndTestResult(env, accum, tx, true)) break; ++nidx; } if (param.hasToReEnable) { - auto tx = createTx(false, l->seq(), unlKeys[0]); + auto tx = createTx(false, l->seq(), UNLKeys[0]); if (!applyAndTestResult(env, accum, tx, true)) break; } @@ -630,16 +630,16 @@ struct NetworkHistory std::shared_ptr createSTVal(std::shared_ptr const& ledger, NodeID const& v) { - static auto kEyPair = randomKeyPair(KeyType::Secp256k1); + static auto kEY_PAIR = randomKeyPair(KeyType::Secp256k1); return std::make_shared( env.app().getTimeKeeper().now(), - kEyPair.first, - kEyPair.second, + kEY_PAIR.first, + kEY_PAIR.second, v, [&](STValidation& v) { v.setFieldH256(sfLedgerHash, ledger->header().hash); v.setFieldU32(sfLedgerSequence, ledger->seq()); - v.setFlag(kVfFullValidation); + v.setFlag(kVF_FULL_VALIDATION); }); }; @@ -665,9 +665,9 @@ struct NetworkHistory { if (needVal(history[curr], i)) { - RCLValidation v(createSTVal(history[curr], unlNodeIDs[i])); + RCLValidation v(createSTVal(history[curr], UNLNodeIDs[i])); v.setTrusted(); - validations.add(unlNodeIDs[i], v); + validations.add(UNLNodeIDs[i], v); } } } @@ -682,10 +682,10 @@ struct NetworkHistory jtx::Env env; Parameter param; RCLValidations& validations; - std::vector unlKeys; - hash_set unlKeySet; - std::vector unlNodeIDs; - hash_set unlNodeIdSet; + std::vector UNLKeys; + hash_set UNLKeySet; + std::vector UNLNodeIDs; + hash_set UNLNodeIDSet; LedgerHistory history; bool goodHistory; }; @@ -714,7 +714,7 @@ voteAndCheck( pre(vote); auto txSet = std::make_shared(SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); - vote.doVoting(history.lastLedger(), history.unlKeySet, history.validations, txSet); + vote.doVoting(history.lastLedger(), history.UNLKeySet, history.validations, txSet); return countTx(txSet) == expect; } @@ -795,9 +795,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations)); + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -813,9 +813,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations)); + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -831,15 +831,15 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NodeID myId = history.unlNodeIDs[3]; + NodeID myId = history.UNLNodeIDs[3]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip half my validations. - return history.unlNodeIDs[idx] != myId || l->seq() % 2 != 0; + return history.UNLNodeIDs[idx] != myId || l->seq() % 2 != 0; }); NegativeUNLVote vote(myId, history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations)); + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -864,12 +864,12 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite if (history.goodHistory && wrongChainSuccess) { - NodeID myId = history.unlNodeIDs[3]; - NodeID const badNode = history.unlNodeIDs[4]; + NodeID myId = history.UNLNodeIDs[3]; + NodeID const badNode = history.UNLNodeIDs[4]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // everyone but me - return !(history.unlNodeIDs[idx] == myId); + return !(history.UNLNodeIDs[idx] == myId); }); // local node validate wrong chain @@ -887,7 +887,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite // local node still on wrong chain, can build a scoreTable, // but all other nodes' scores are zero auto scoreTable = vote.buildScoreTable( - wrongChain.back(), history.unlNodeIdSet, history.validations); + wrongChain.back(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -907,7 +907,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite // if local node switched to right history, but cannot build // scoreTable because not enough local validations BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations)); + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -927,9 +927,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); auto scoreTable = vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations); + history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -1001,72 +1001,72 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite hash_set negUnl012; for (std::uint32_t i = 0; i < 3; ++i) - negUnl012.insert(history.unlNodeIDs[i]); + negUnl012.insert(history.UNLNodeIDs[i]); // build a good scoreTable to use, or copy and modify hash_map goodScoreTable; - for (auto const& n : history.unlNodeIDs) - goodScoreTable[n] = NegativeUNLVote::kNegativeUnlHighWaterMark + 1; + for (auto const& n : history.UNLNodeIDs) + goodScoreTable[n] = NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK + 1; - NegativeUNLVote vote(history.unlNodeIDs[0], history.env.journal); + NegativeUNLVote vote(history.UNLNodeIDs[0], history.env.journal); { // all good scores BEAST_EXPECT( - checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, goodScoreTable, 0, 3)); + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, goodScoreTable, 0, 3)); } { // all bad scores hash_map scoreTable; - for (auto& n : history.unlNodeIDs) - scoreTable[n] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; + for (auto& n : history.UNLNodeIDs) + scoreTable[n] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK - 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 35 - 3, 0)); + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 35 - 3, 0)); } { // all between watermarks hash_map scoreTable; - for (auto& n : history.unlNodeIDs) - scoreTable[n] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; + for (auto& n : history.UNLNodeIDs) + scoreTable[n] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK + 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 0, 0)); + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 0, 0)); } { // 2 good scorers in negUnl auto scoreTable = goodScoreTable; - scoreTable[*negUnl012.begin()] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; + scoreTable[*negUnl012.begin()] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK + 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 0, 2)); + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 0, 2)); } { // 2 bad scorers not in negUnl auto scoreTable = goodScoreTable; - scoreTable[history.unlNodeIDs[11]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; - scoreTable[history.unlNodeIDs[12]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; + scoreTable[history.UNLNodeIDs[11]] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK - 1; + scoreTable[history.UNLNodeIDs[12]] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK - 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 2, 3)); + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 2, 3)); } { // 2 in negUnl but not in unl, have a remove candidate from score // table - hash_set unlTemp = history.unlNodeIdSet; - unlTemp.erase(history.unlNodeIDs[0]); - unlTemp.erase(history.unlNodeIDs[1]); + hash_set unlTemp = history.UNLNodeIDSet; + unlTemp.erase(history.UNLNodeIDs[0]); + unlTemp.erase(history.UNLNodeIDs[1]); BEAST_EXPECT(checkCandidateSizes(vote, unlTemp, negUnl012, goodScoreTable, 0, 3)); } { // 2 in negUnl but not in unl, no remove candidate from score table auto scoreTable = goodScoreTable; - scoreTable.erase(history.unlNodeIDs[0]); - scoreTable.erase(history.unlNodeIDs[1]); - scoreTable[history.unlNodeIDs[2]] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; - hash_set unlTemp = history.unlNodeIdSet; - unlTemp.erase(history.unlNodeIDs[0]); - unlTemp.erase(history.unlNodeIDs[1]); + scoreTable.erase(history.UNLNodeIDs[0]); + scoreTable.erase(history.UNLNodeIDs[1]); + scoreTable[history.UNLNodeIDs[2]] = NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK + 1; + hash_set unlTemp = history.UNLNodeIDSet; + unlTemp.erase(history.UNLNodeIDs[0]); + unlTemp.erase(history.UNLNodeIDs[1]); BEAST_EXPECT(checkCandidateSizes(vote, unlTemp, negUnl012, scoreTable, 0, 2)); } @@ -1075,15 +1075,15 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite NodeID const new1(0xbead); NodeID const new2(0xbeef); hash_set const nowTrusted = {new1, new2}; - hash_set unlTemp = history.unlNodeIdSet; + hash_set unlTemp = history.UNLNodeIDSet; unlTemp.insert(new1); unlTemp.insert(new2); vote.newValidators(256, nowTrusted); { // 2 new validators have good scores, already in negUnl auto scoreTable = goodScoreTable; - scoreTable[new1] = NegativeUNLVote::kNegativeUnlHighWaterMark + 1; - scoreTable[new2] = NegativeUNLVote::kNegativeUnlHighWaterMark + 1; + scoreTable[new1] = NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK + 1; + scoreTable[new2] = NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK + 1; hash_set negUnlTemp = negUnl012; negUnlTemp.insert(new1); negUnlTemp.insert(new2); @@ -1098,7 +1098,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite } { // expired the new validators have bad scores, not in negUnl - vote.purgeNewValidators(256 + NegativeUNLVote::kNewValidatorDisableSkip + 1); + vote.purgeNewValidators(256 + NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP + 1); auto scoreTable = goodScoreTable; scoreTable[new1] = 0; scoreTable[new2] = 0; @@ -1136,13 +1136,13 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite std::array const nUnlPercent = {0, 50, 100}; std::array scores = { 0, - NegativeUNLVote::kNegativeUnlLowWaterMark - 1, - NegativeUNLVote::kNegativeUnlLowWaterMark, - NegativeUNLVote::kNegativeUnlLowWaterMark + 1, - NegativeUNLVote::kNegativeUnlHighWaterMark - 1, - NegativeUNLVote::kNegativeUnlHighWaterMark, - NegativeUNLVote::kNegativeUnlHighWaterMark + 1, - NegativeUNLVote::kNegativeUnlMinLocalValsToVote}; + NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK - 1, + NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK, + NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK + 1, + NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK - 1, + NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK, + NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK + 1, + NegativeUNLVote::kNEGATIVE_UNL_MIN_LOCAL_VALS_TO_VOTE}; //== combination 1: { @@ -1182,21 +1182,21 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite std::size_t toReEnableExpect = 0; if (np == 0) { - if (score < NegativeUNLVote::kNegativeUnlLowWaterMark) + if (score < NegativeUNLVote::kNEGATIVE_UNL_LOW_WATER_MARK) { toDisableExpect = us; } } else if (np == 50) { - if (score > NegativeUNLVote::kNegativeUnlHighWaterMark) + if (score > NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK) { toReEnableExpect = us * np / 100; } } else { - if (score > NegativeUNLVote::kNegativeUnlHighWaterMark) + if (score > NegativeUNLVote::kNEGATIVE_UNL_HIGH_WATER_MARK) { toReEnableExpect = us; } @@ -1314,24 +1314,24 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(vote.newValidators_[n2] == 3); } - vote.newValidators(NegativeUNLVote::kNewValidatorDisableSkip, {n1, n2, n3}); + vote.newValidators(NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP, {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::kNewValidatorDisableSkip); + BEAST_EXPECT(vote.newValidators_[n3] == NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP); } - vote.purgeNewValidators(NegativeUNLVote::kNewValidatorDisableSkip + 2); + vote.purgeNewValidators(NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP + 2); BEAST_EXPECT(vote.newValidators_.size() == 3); - vote.purgeNewValidators(NegativeUNLVote::kNewValidatorDisableSkip + 3); + vote.purgeNewValidators(NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP + 3); BEAST_EXPECT(vote.newValidators_.size() == 2); - vote.purgeNewValidators(NegativeUNLVote::kNewValidatorDisableSkip + 4); + vote.purgeNewValidators(NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP + 4); BEAST_EXPECT(vote.newValidators_.size() == 1); BEAST_EXPECT(vote.newValidators_.begin()->first == n3); BEAST_EXPECT( - vote.newValidators_.begin()->second == NegativeUNLVote::kNewValidatorDisableSkip); + vote.newValidators_.begin()->second == NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP); } void @@ -1381,7 +1381,7 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NodeID myId = history.unlNodeIDs[3]; + NodeID myId = history.UNLNodeIDs[3]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { std::size_t k = 0; @@ -1400,19 +1400,19 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite bool const add50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; bool const add100 = scorePattern[sp][k] == 100; - bool const addMe = history.unlNodeIDs[idx] == myId; + bool const addMe = history.UNLNodeIDs[idx] == myId; return add50 || add100 || addMe; }); NegativeUNLVote vote(myId, history.env.journal); auto scoreTable = vote.buildScoreTable( - history.lastLedger(), history.unlNodeIdSet, history.validations); + history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { std::uint32_t i = 0; // looping unl auto checkScores = [&](std::uint32_t score, std::uint32_t k) -> bool { - if (history.unlNodeIDs[i] == myId) + if (history.UNLNodeIDs[i] == myId) return score == 256; if (scorePattern[sp][k] == 0) return score == 0; @@ -1427,15 +1427,15 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite }; for (; i < 2; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 0)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 0)); } for (; i < 4; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 1)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 1)); } for (; i < unlSize; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 2)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 2)); } } } @@ -1506,7 +1506,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1527,7 +1527,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 1)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1)); } } } @@ -1564,7 +1564,7 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::Suite // skip node 0 and node 1 return idx > 1; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 1)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 1)); } } @@ -1587,9 +1587,9 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::Suite history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip node 0 and node 1 - return history.unlNodeIDs[idx] != n1 && history.unlNodeIDs[idx] != n2; + return history.UNLNodeIDs[idx] != n1 && history.UNLNodeIDs[idx] != n2; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); } } } @@ -1626,7 +1626,7 @@ class NegativeUNLVoteMaxListed_test : public beast::unit_test::Suite // skip node 0 ~ 10 return idx > 10; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); } } } @@ -1662,7 +1662,7 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); - BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1705,9 +1705,9 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::Suite return idx > 1; }); BEAST_EXPECT( - voteAndCheck(history, history.unlNodeIDs.back(), 1, [&](NegativeUNLVote& vote) { - history.unlKeySet.erase(history.unlKeys[0]); - history.unlKeySet.erase(history.unlKeys[1]); + voteAndCheck(history, history.UNLNodeIDs.back(), 1, [&](NegativeUNLVote& vote) { + history.UNLKeySet.erase(history.UNLKeys[0]); + history.UNLKeySet.erase(history.UNLKeys[1]); })); } } @@ -1745,11 +1745,11 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::Suite return true; }); BEAST_EXPECT( - voteAndCheck(history, history.unlNodeIDs[0], 0, [&](NegativeUNLVote& vote) { + voteAndCheck(history, history.UNLNodeIDs[0], 0, [&](NegativeUNLVote& vote) { auto extraKey1 = randomKeyPair(KeyType::Ed25519).first; auto extraKey2 = randomKeyPair(KeyType::Ed25519).first; - history.unlKeySet.insert(extraKey1); - history.unlKeySet.insert(extraKey2); + history.UNLKeySet.insert(extraKey1); + history.UNLKeySet.insert(extraKey2); hash_set nowTrusted; nowTrusted.insert(calcNodeID(extraKey1)); nowTrusted.insert(calcNodeID(extraKey2)); @@ -1767,7 +1767,7 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::Suite .negUNLSize = 0, .hasToDisable = false, .hasToReEnable = false, - .numLedgers = NegativeUNLVote::kNewValidatorDisableSkip * 2}}; + .numLedgers = NegativeUNLVote::kNEW_VALIDATOR_DISABLE_SKIP * 2}}; BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { @@ -1776,11 +1776,11 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::Suite return true; }); BEAST_EXPECT( - voteAndCheck(history, history.unlNodeIDs[0], 1, [&](NegativeUNLVote& vote) { + voteAndCheck(history, history.UNLNodeIDs[0], 1, [&](NegativeUNLVote& vote) { auto extraKey1 = randomKeyPair(KeyType::Ed25519).first; auto extraKey2 = randomKeyPair(KeyType::Ed25519).first; - history.unlKeySet.insert(extraKey1); - history.unlKeySet.insert(extraKey2); + history.UNLKeySet.insert(extraKey1); + history.UNLKeySet.insert(extraKey2); hash_set nowTrusted; nowTrusted.insert(calcNodeID(extraKey1)); nowTrusted.insert(calcNodeID(extraKey2)); @@ -1805,9 +1805,9 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::Suite testcase("Filter Validations"); jtx::Env env(*this); auto l = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{env.app().config().features}, - env.app().config().fees.toFees(), + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -1820,7 +1820,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::Suite [&](STValidation& v) { v.setFieldH256(sfLedgerHash, l->header().hash); v.setFieldU32(sfLedgerSequence, l->seq()); - v.setFlag(kVfFullValidation); + v.setFlag(kVF_FULL_VALIDATION); }); }; diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index 606c6f2824..323f8fcb77 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -324,15 +324,15 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, -harness.parms().validationCurrentEarly, 0s))); + harness.add(n.validate(ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, harness.parms().validationCurrentWall, 0s))); + harness.add(n.validate(ledgerA, harness.parms().validationCURRENT_WALL, 0s))); BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, 0s, harness.parms().validationCurrentLocal))); + harness.add(n.validate(ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); } { @@ -357,7 +357,7 @@ class Validations_test : public beast::unit_test::Suite // If we advance far enough for AB to expire, we can fully // validate or partially validate that sequence number again BEAST_EXPECT(ValStatus::Conflicting == process(ledgerAZ)); - harness.clock().advance(harness.parms().validationSetExpires + 1ms); + harness.clock().advance(harness.parms().validationSET_EXPIRES + 1ms); BEAST_EXPECT(ValStatus::Current == process(ledgerAZ)); } } @@ -392,7 +392,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT( harness.vals().getPreferred(genesisLedger_) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); - harness.clock().advance(harness.parms().validationCurrentLocal); + harness.clock().advance(harness.parms().validationCURRENT_LOCAL); // trigger check for stale trigger(harness.vals()); @@ -487,7 +487,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(harness.vals().currentTrusted()[0].seq() == ledgerAC.seq()); // Pass enough time for it to go stale - harness.clock().advance(harness.parms().validationCurrentLocal); + harness.clock().advance(harness.parms().validationCURRENT_LOCAL); BEAST_EXPECT(harness.vals().currentTrusted().empty()); } @@ -528,7 +528,7 @@ class Validations_test : public beast::unit_test::Suite } // Pass enough time for them to go stale - harness.clock().advance(harness.parms().validationCurrentLocal); + harness.clock().advance(harness.parms().validationCURRENT_LOCAL); BEAST_EXPECT(harness.vals().getCurrentNodeIDs().empty()); } @@ -648,8 +648,8 @@ class Validations_test : public beast::unit_test::Suite LedgerHistoryHelper h; TestHarness harness(h.oracle); Node const a = harness.makeNode(); - constexpr Ledger::Seq kOne(1); - constexpr Ledger::Seq kTwo(2); + constexpr Ledger::Seq kONE(1); + constexpr Ledger::Seq kTWO(2); // simple cases Ledger const ledgerA = h["a"]; @@ -657,7 +657,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 1); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 1); - harness.clock().advance(harness.parms().validationSetExpires); + harness.clock().advance(harness.parms().validationSET_EXPIRES); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 0); @@ -665,15 +665,15 @@ class Validations_test : public beast::unit_test::Suite Ledger const ledgerB = h["ab"]; BEAST_EXPECT(ValStatus::Current == harness.add(a.validate(ledgerB))); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerB.id()) == 1); - harness.vals().setSeqToKeep(ledgerB.seq(), ledgerB.seq() + kOne); - harness.clock().advance(harness.parms().validationSetExpires); + harness.vals().setSeqToKeep(ledgerB.seq(), ledgerB.seq() + kONE); + harness.clock().advance(harness.parms().validationSET_EXPIRES); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerB.id()) == 1); // change toKeep - harness.vals().setSeqToKeep(ledgerB.seq() + kOne, ledgerB.seq() + kTwo); + harness.vals().setSeqToKeep(ledgerB.seq() + kONE, ledgerB.seq() + kTWO); // advance clock slowly int const loops = - harness.parms().validationSetExpires / harness.parms().validationFRESHNESS + 1; + harness.parms().validationSET_EXPIRES / harness.parms().validationFRESHNESS + 1; for (int i = 0; i < loops; ++i) { harness.clock().advance(harness.parms().validationFRESHNESS); @@ -685,8 +685,8 @@ class Validations_test : public beast::unit_test::Suite Ledger const ledgerC = h["abc"]; BEAST_EXPECT(ValStatus::Current == harness.add(a.validate(ledgerC))); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerC.id()) == 1); - harness.vals().setSeqToKeep(ledgerC.seq() - kOne, ledgerC.seq()); - harness.clock().advance(harness.parms().validationSetExpires); + harness.vals().setSeqToKeep(ledgerC.seq() - kONE, ledgerC.seq()); + harness.clock().advance(harness.parms().validationSET_EXPIRES); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerC.id()) == 0); } @@ -934,7 +934,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(enforcer(clock.now(), Seq{10}, p)); BEAST_EXPECT(!enforcer(clock.now(), Seq{5}, p)); BEAST_EXPECT(!enforcer(clock.now(), Seq{9}, p)); - clock.advance(p.validationSetExpires - 1ms); + clock.advance(p.validationSET_EXPIRES - 1ms); BEAST_EXPECT(!enforcer(clock.now(), Seq{1}, p)); clock.advance(2ms); BEAST_EXPECT(enforcer(clock.now(), Seq{1}, p)); diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index 18729a7322..d859c71520 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -18,7 +18,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::Severity::Disabled}; + test::jtx::Env env_{*this, jtx::envconfig(), nullptr, beast::severities::KDisabled}; beast::Journal j_{env_.app().getJournal("ClosureCounter_test")}; void @@ -205,7 +205,7 @@ class ClosureCounter_test : public beast::unit_test::Suite BEAST_EXPECT(strCounter.count() == 0); auto wrapped = strCounter.wrap([](TrackedString&& in) { - // Note that kNone of the compilers noticed that in was + // Note that kNONE of the compilers noticed that in was // leaving scope. So, without intervention, they would // do a copy for the return (June 2017). An explicit // std::move() was required. diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index ce6774827e..95f277212d 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -36,7 +36,7 @@ namespace detail { std::string configContents(std::string const& dbPath, std::string const& validatorsFile) { - static boost::format kConfigContentsTemplate(R"xrpldConfig( + static boost::format kCONFIG_CONTENTS_TEMPLATE(R"xrpldConfig( [server] port_rpc port_peer @@ -120,7 +120,7 @@ backend=sqlite std::string dbPathSection = dbPath.empty() ? "" : "[database_path]\n" + dbPath; std::string valFileSection = validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile; - return boost::str(kConfigContentsTemplate % dbPathSection % valFileSection); + return boost::str(kCONFIG_CONTENTS_TEMPLATE % dbPathSection % valFileSection); } /** @@ -154,7 +154,7 @@ public: , dataDir_(dbPath) { if (dbPath.empty()) - dataDir_ = subdir() / path(Config::kDatabaseDirName); + dataDir_ = subdir() / path(Config::kDATABASE_DIR_NAME); rmDataDir_ = !exists(dataDir_); config_.setup( @@ -248,7 +248,7 @@ public: : FileDirGuard( test, std::move(subDir), - path(validatorsFileName.empty() ? Config::kValidatorsFileName : validatorsFileName), + path(validatorsFileName.empty() ? Config::kVALIDATORS_FILE_NAME : validatorsFileName), valFileContents(), useCounter) { @@ -313,7 +313,8 @@ port_wss_admin auto const cwd = current_path(); // Test both config file names. - std::string_view const configFiles[] = {Config::kConfigFileName, Config::kConfigLegacyName}; + std::string_view const configFiles[] = { + Config::kCONFIG_FILE_NAME, Config::kCONFIG_LEGACY_NAME}; // Config file in current directory. for (auto const& configFile : configFiles) @@ -460,7 +461,7 @@ port_wss_admin path const dataDirRel("test_data_dir"); path const dataDirAbs(cwd / g0.subdir() / dataDirRel); detail::FileCfgGuard const g( - *this, g0.subdir(), dataDirAbs, Config::kConfigFileName, "", false); + *this, g0.subdir(), dataDirAbs, Config::kCONFIG_FILE_NAME, "", false); auto const& c(g.config()); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); @@ -469,7 +470,7 @@ port_wss_admin { // read from file relative path std::string const dbPath("my_db"); - detail::FileCfgGuard const g(*this, "test_db", dbPath, Config::kConfigFileName, ""); + detail::FileCfgGuard const g(*this, "test_db", dbPath, Config::kCONFIG_FILE_NAME, ""); auto const& c(g.config()); std::string const nativeDbPath = absolute(path(dbPath)).string(); BEAST_EXPECT(g.dataDirExists()); @@ -478,10 +479,10 @@ port_wss_admin } { // read from file no path - detail::FileCfgGuard const g(*this, "test_db", "", Config::kConfigFileName, ""); + detail::FileCfgGuard const g(*this, "test_db", "", Config::kCONFIG_FILE_NAME, ""); auto const& c(g.config()); std::string const nativeDbPath = - absolute(g.subdir() / path(Config::kDatabaseDirName)).string(); + absolute(g.subdir() / path(Config::kDATABASE_DIR_NAME)).string(); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); BEAST_EXPECT(c.legacy("database_path") == nativeDbPath); @@ -508,7 +509,7 @@ port_wss_admin { Config c; - static boost::format kConfigTemplate(R"xrpldConfig( + static boost::format kCONFIG_TEMPLATE(R"xrpldConfig( [validation_seed] %1% @@ -521,7 +522,7 @@ port_wss_admin "and [validator_token] config sections"; try { - c.loadFromString(boost::str(kConfigTemplate % validationSeed % token)); + c.loadFromString(boost::str(kCONFIG_TEMPLATE % validationSeed % token)); } catch (std::runtime_error const& e) { @@ -550,7 +551,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.networkId == 0); + BEAST_EXPECT(c.NETWORK_ID == 0); try { @@ -563,7 +564,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.networkId == 0); + BEAST_EXPECT(c.NETWORK_ID == 0); try { @@ -578,7 +579,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.networkId == 255); + BEAST_EXPECT(c.NETWORK_ID == 255); try { @@ -593,7 +594,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.networkId == 10000); + BEAST_EXPECT(c.NETWORK_ID == 10000); } void @@ -655,7 +656,7 @@ nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8 c.loadFromString(toLoad); BEAST_EXPECT(c.legacy("validators_file").empty()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 5); - BEAST_EXPECT(c.validatorListThreshold == std::nullopt); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::nullopt); } { // load validator list sites and keys from config @@ -685,7 +686,7 @@ trust-these-validators.gov "E566"); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "1"); - BEAST_EXPECT(c.validatorListThreshold == std::size_t(1)); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::size_t(1)); } { // load validator list sites and keys from config @@ -715,7 +716,7 @@ trust-these-validators.gov "E566"); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "0"); - BEAST_EXPECT(c.validatorListThreshold == std::nullopt); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::nullopt); } { // load should throw if [validator_list_threshold] is greater than @@ -836,7 +837,7 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] file name @@ -844,7 +845,7 @@ trust-these-validators.gov std::string const valFileName = "validators.txt"; detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", valFileName); detail::FileCfgGuard const rcg( - *this, vtg.subdir(), "", Config::kConfigFileName, valFileName, false); + *this, vtg.subdir(), "", Config::kCONFIG_FILE_NAME, valFileName, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -853,7 +854,7 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] relative path @@ -861,7 +862,7 @@ trust-these-validators.gov detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt"); auto const valFilePath = ".." / vtg.subdir() / "validators.txt"; detail::FileCfgGuard const rcg( - *this, vtg.subdir(), "", Config::kConfigFileName, valFilePath, false); + *this, vtg.subdir(), "", Config::kCONFIG_FILE_NAME, valFilePath, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -870,13 +871,13 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + 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::kConfigFileName, "", false); + *this, vtg.subdir(), "", Config::kCONFIG_FILE_NAME, "", false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -885,7 +886,7 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] instead @@ -896,7 +897,7 @@ trust-these-validators.gov *this, vtg.subdir(), "validators.txt", false); BEAST_EXPECT(vtgDefault.validatorsFileExists()); detail::FileCfgGuard const rcg( - *this, vtg.subdir(), "", Config::kConfigFileName, vtg.validatorsFile(), false); + *this, vtg.subdir(), "", Config::kCONFIG_FILE_NAME, vtg.validatorsFile(), false); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); @@ -904,7 +905,7 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { @@ -940,7 +941,7 @@ trust-these-validators.gov BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 4); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 3); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.validatorListThreshold == 2); + BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load should throw if [validator_list_threshold] is present both @@ -1002,7 +1003,7 @@ trust-these-validators.gov testSetup(bool explicitPath) { detail::FileCfgGuard const cfg( - *this, "testSetup", explicitPath ? "test_db" : "", Config::kConfigFileName, ""); + *this, "testSetup", explicitPath ? "test_db" : "", Config::kCONFIG_FILE_NAME, ""); /* 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. @@ -1017,7 +1018,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 256); + BEAST_EXPECT(config.LEDGER_HISTORY == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1030,7 +1031,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 256); + BEAST_EXPECT(config.LEDGER_HISTORY == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1043,7 +1044,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 256); + BEAST_EXPECT(config.LEDGER_HISTORY == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1056,7 +1057,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 256); + BEAST_EXPECT(config.LEDGER_HISTORY == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1069,7 +1070,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 0); + BEAST_EXPECT(config.LEDGER_HISTORY == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1082,7 +1083,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 0); + BEAST_EXPECT(config.LEDGER_HISTORY == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1095,7 +1096,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 0); + BEAST_EXPECT(config.LEDGER_HISTORY == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1108,7 +1109,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.ledgerHistory == 0); + BEAST_EXPECT(config.LEDGER_HISTORY == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } } @@ -1116,7 +1117,7 @@ trust-these-validators.gov void testPort() { - detail::FileCfgGuard const cfg(*this, "testPort", "", Config::kConfigFileName, ""); + detail::FileCfgGuard const cfg(*this, "testPort", "", Config::kCONFIG_FILE_NAME, ""); auto const& conf = cfg.config(); if (!BEAST_EXPECT(conf.exists("port_rpc"))) return; @@ -1125,11 +1126,11 @@ trust-these-validators.gov ParsedPort rpc; if (!unexcept([&]() { parsePort(rpc, conf["port_rpc"], log); })) return; - BEAST_EXPECT(rpc.adminNetsV4.size() + rpc.adminNetsV6.size() == 2); + BEAST_EXPECT(rpc.admin_nets_v4.size() + rpc.admin_nets_v6.size() == 2); ParsedPort wss; if (!unexcept([&]() { parsePort(wss, conf["port_wss_admin"], log); })) return; - BEAST_EXPECT(wss.adminNetsV4.size() + wss.adminNetsV6.size() == 1); + BEAST_EXPECT(wss.admin_nets_v4.size() + wss.admin_nets_v6.size() == 1); } void @@ -1141,7 +1142,7 @@ trust-these-validators.gov try { detail::FileCfgGuard const cfg( - *this, "testPort", "", Config::kConfigFileName, "", true, contents); + *this, "testPort", "", Config::kCONFIG_FILE_NAME, "", true, contents); BEAST_EXPECT(false); } catch (std::exception const& ex) @@ -1245,25 +1246,25 @@ r.ripple.com:51235 BEAST_EXPECT( cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 15 && cfg.section(SECTION_IPS_FIXED).values().size() == 15); - BEAST_EXPECT(cfg.ips[0] == "r.ripple.com 51235"); + BEAST_EXPECT(cfg.IPS[0] == "r.ripple.com 51235"); - BEAST_EXPECT(cfg.ipsFixed[0] == "s1.ripple.com 51235"); - BEAST_EXPECT(cfg.ipsFixed[1] == "s2.ripple.com 51235"); - BEAST_EXPECT(cfg.ipsFixed[2] == "anotherserversansport"); - BEAST_EXPECT(cfg.ipsFixed[3] == "anotherserverwithport 12"); - BEAST_EXPECT(cfg.ipsFixed[4] == "1.1.1.1 1"); - BEAST_EXPECT(cfg.ipsFixed[5] == "1.1.1.1 1"); - BEAST_EXPECT(cfg.ipsFixed[6] == "12.34.12.123 12345"); - BEAST_EXPECT(cfg.ipsFixed[7] == "12.34.12.123 12345"); + BEAST_EXPECT(cfg.IPS_FIXED[0] == "s1.ripple.com 51235"); + BEAST_EXPECT(cfg.IPS_FIXED[1] == "s2.ripple.com 51235"); + BEAST_EXPECT(cfg.IPS_FIXED[2] == "anotherserversansport"); + BEAST_EXPECT(cfg.IPS_FIXED[3] == "anotherserverwithport 12"); + BEAST_EXPECT(cfg.IPS_FIXED[4] == "1.1.1.1 1"); + BEAST_EXPECT(cfg.IPS_FIXED[5] == "1.1.1.1 1"); + BEAST_EXPECT(cfg.IPS_FIXED[6] == "12.34.12.123 12345"); + BEAST_EXPECT(cfg.IPS_FIXED[7] == "12.34.12.123 12345"); // all ipv6 should be ignored by colon replacer, howsoever formatted - BEAST_EXPECT(cfg.ipsFixed[8] == "::"); - BEAST_EXPECT(cfg.ipsFixed[9] == "2001:db8::"); - BEAST_EXPECT(cfg.ipsFixed[10] == "::1"); - BEAST_EXPECT(cfg.ipsFixed[11] == "::1:12345"); - BEAST_EXPECT(cfg.ipsFixed[12] == "[::1]:12345"); - BEAST_EXPECT(cfg.ipsFixed[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345"); - BEAST_EXPECT(cfg.ipsFixed[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); + BEAST_EXPECT(cfg.IPS_FIXED[8] == "::"); + BEAST_EXPECT(cfg.IPS_FIXED[9] == "2001:db8::"); + BEAST_EXPECT(cfg.IPS_FIXED[10] == "::1"); + BEAST_EXPECT(cfg.IPS_FIXED[11] == "::1:12345"); + BEAST_EXPECT(cfg.IPS_FIXED[12] == "[::1]:12345"); + BEAST_EXPECT(cfg.IPS_FIXED[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345"); + BEAST_EXPECT(cfg.IPS_FIXED[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); } void @@ -1274,51 +1275,51 @@ r.ripple.com:51235 std::string_view line; std::string_view field; std::string_view expect; - bool hadComment; + bool had_comment; }; std::array const tests = { {{.line = "password = aaaa\\#bbbb", .field = "password", .expect = "aaaa#bbbb", - .hadComment = false}, + .had_comment = false}, {.line = "password = aaaa#bbbb", .field = "password", .expect = "aaaa", - .hadComment = true}, + .had_comment = true}, {.line = "password = aaaa #bbbb", .field = "password", .expect = "aaaa", - .hadComment = true}, + .had_comment = true}, // since the value is all comment, this doesn't parse as k=v : {.line = "password = #aaaa #bbbb", .field = "", .expect = "password =", - .hadComment = true}, + .had_comment = true}, {.line = "password = aaaa\\# #bbbb", .field = "password", .expect = "aaaa#", - .hadComment = true}, + .had_comment = true}, {.line = "password = aaaa\\##bbbb", .field = "password", .expect = "aaaa#", - .hadComment = true}, - {.line = "aaaa#bbbb", .field = "", .expect = "aaaa", .hadComment = true}, - {.line = "aaaa\\#bbbb", .field = "", .expect = "aaaa#bbbb", .hadComment = false}, - {.line = "aaaa\\##bbbb", .field = "", .expect = "aaaa#", .hadComment = true}, - {.line = "aaaa #bbbb", .field = "", .expect = "aaaa", .hadComment = true}, - {.line = "1 #comment", .field = "", .expect = "1", .hadComment = true}, - {.line = "#whole thing is comment", .field = "", .expect = "", .hadComment = false}, + .had_comment = true}, + {.line = "aaaa#bbbb", .field = "", .expect = "aaaa", .had_comment = true}, + {.line = "aaaa\\#bbbb", .field = "", .expect = "aaaa#bbbb", .had_comment = false}, + {.line = "aaaa\\##bbbb", .field = "", .expect = "aaaa#", .had_comment = true}, + {.line = "aaaa #bbbb", .field = "", .expect = "aaaa", .had_comment = true}, + {.line = "1 #comment", .field = "", .expect = "1", .had_comment = true}, + {.line = "#whole thing is comment", .field = "", .expect = "", .had_comment = false}, {.line = " #whole comment with space", .field = "", .expect = "", - .hadComment = false}}}; + .had_comment = false}}}; for (auto const& t : tests) { Section s; s.append(std::string(t.line)); - BEAST_EXPECT(s.hadTrailingComments() == t.hadComment); + BEAST_EXPECT(s.hadTrailingComments() == t.had_comment); if (t.field.empty()) { BEAST_EXPECTS(s.legacy() == t.expect, s.legacy()); @@ -1481,7 +1482,7 @@ r.ripple.com:51235 c.loadFromString(toLoad); if (shouldPass) { - BEAST_EXPECT(c.amendmentMajorityTime.count() == val * sec); + BEAST_EXPECT(c.AMENDMENT_MAJORITY_TIME.count() == val * sec); } else { @@ -1512,7 +1513,7 @@ r.ripple.com:51235 { Config c; c.loadFromString("[overlay]\nmax_unknown_time=" + value); - return c.maxUnknownTime; + return c.MAX_UNKNOWN_TIME; } catch (std::runtime_error const&) { @@ -1546,7 +1547,7 @@ r.ripple.com:51235 { Config c; c.loadFromString("[overlay]\nmax_diverged_time=" + value); - return c.maxDivergedTime; + return c.MAX_DIVERGED_TIME; } catch (std::runtime_error const&) { diff --git a/src/test/core/Coroutine_test.cpp b/src/test/core/Coroutine_test.cpp index bf1d98c779..103191ec59 100644 --- a/src/test/core/Coroutine_test.cpp +++ b/src/test/core/Coroutine_test.cpp @@ -58,7 +58,7 @@ public: testcase("correct order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->forceMultiThread = true; + cfg->FORCE_MULTI_THREAD = true; return cfg; })); @@ -85,7 +85,7 @@ public: testcase("incorrect order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->forceMultiThread = true; + cfg->FORCE_MULTI_THREAD = true; return cfg; })); diff --git a/src/test/core/SociDB_test.cpp b/src/test/core/SociDB_test.cpp index f4c6fb04f1..29aeca7ce5 100644 --- a/src/test/core/SociDB_test.cpp +++ b/src/test/core/SociDB_test.cpp @@ -8,7 +8,7 @@ #include #include #include -#include // IWYU pragma: keep +#include #include #include diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index 3e9eed1c52..d3b35c19a1 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -496,7 +496,12 @@ struct Peer return Result( TxSet{openTxs}, Proposal( - prevLedger.id(), Proposal::kSeqJoin, TxSet::calcID(openTxs), closeTime, now(), id)); + prevLedger.id(), + Proposal::kSEQ_JOIN, + TxSet::calcID(openTxs), + closeTime, + now(), + id)); } void diff --git a/src/test/csf/Scheduler.h b/src/test/csf/Scheduler.h index ede43be854..c70b7d4854 100644 --- a/src/test/csf/Scheduler.h +++ b/src/test/csf/Scheduler.h @@ -91,7 +91,7 @@ private: make_multiset>::type; // alloc_ is owned by the scheduler boost::container::pmr::monotonic_buffer_resource* alloc_; - by_when_set byWhen_; + by_when_set by_when_; public: using iterator = typename by_when_set::iterator; @@ -258,7 +258,7 @@ inline Scheduler::QueueType::QueueType(boost::container::pmr::monotonic_buffer_r inline Scheduler::QueueType::~QueueType() { - for (auto iter = byWhen_.begin(); iter != byWhen_.end();) + for (auto iter = by_when_.begin(); iter != by_when_.end();) { auto e = &*iter; ++iter; @@ -270,19 +270,19 @@ inline Scheduler::QueueType::~QueueType() inline bool Scheduler::QueueType::empty() const { - return byWhen_.empty(); + return by_when_.empty(); } inline auto Scheduler::QueueType::begin() -> iterator { - return byWhen_.begin(); + return by_when_.begin(); } inline auto Scheduler::QueueType::end() -> iterator { - return byWhen_.end(); + return by_when_.end(); } template @@ -292,14 +292,14 @@ Scheduler::QueueType::emplace(time_point when, Handler&& h) -> typename by_when_ using event_type = EventImpl>; auto const p = alloc_->allocate(sizeof(event_type)); auto& e = *new (p) event_type(when, std::forward(h)); - return byWhen_.insert(e); + return by_when_.insert(e); } inline auto Scheduler::QueueType::erase(iterator iter) -> typename by_when_set::iterator { auto& e = *iter; - auto next = byWhen_.erase(iter); + auto next = by_when_.erase(iter); e.~Event(); alloc_->deallocate(&e, sizeof(e)); return next; diff --git a/src/test/csf/Sim.h b/src/test/csf/Sim.h index 89e6b95fe6..0b1b3473d6 100644 --- a/src/test/csf/Sim.h +++ b/src/test/csf/Sim.h @@ -22,12 +22,12 @@ class BasicSink : public beast::Journal::Sink public: BasicSink(Scheduler::clock_type const& clock) - : Sink(beast::Severity::Disabled, false), clock_{clock} + : Sink(beast::severities::KDisabled, false), clock_{clock} { } void - write(beast::Severity level, std::string const& text) override + write(beast::severities::Severity level, std::string const& text) override { if (level < threshold()) return; @@ -36,7 +36,7 @@ public: } void - writeAlways(beast::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; } diff --git a/src/test/csf/impl/ledgers.cpp b/src/test/csf/impl/ledgers.cpp index 46a3600307..0e3764d5ab 100644 --- a/src/test/csf/impl/ledgers.cpp +++ b/src/test/csf/impl/ledgers.cpp @@ -15,12 +15,12 @@ namespace xrpl::test::csf { -Ledger::Instance const Ledger::kGenesis; +Ledger::Instance const Ledger::kGENESIS; json::Value Ledger::getJson() const { - json::Value res(json::ValueType::Object); + json::Value res(json::ObjectValue); res["id"] = static_cast(id()); res["seq"] = static_cast(seq()); return res; @@ -76,7 +76,7 @@ mismatch(Ledger const& a, Ledger const& b) LedgerOracle::LedgerOracle() { - instances_.insert(InstanceEntry{Ledger::kGenesis, nextID()}); + instances_.insert(InstanceEntry{Ledger::kGENESIS, nextID()}); } Ledger::ID diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index 25672de133..96082bc987 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -66,7 +66,7 @@ private: TxSetType txs; // Resolution used to determine close time - NetClock::duration closeTimeResolution = kLedgerDefaultTimeResolution; + NetClock::duration closeTimeResolution = kLEDGER_DEFAULT_TIME_RESOLUTION; //! When the ledger closed (up to closeTimeResolution) NetClock::time_point closeTime; @@ -128,14 +128,14 @@ private: }; // Single common genesis instance - static Instance const kGenesis; + static Instance const kGENESIS; Ledger(ID id, Instance const* i) : id_{id}, instance_{i} { } public: - Ledger(MakeGenesis) : instance_(&kGenesis) + Ledger(MakeGenesis) : instance_(&kGENESIS) { } diff --git a/src/test/jtx/AMM.h b/src/test/jtx/AMM.h index deadd80290..2876522218 100644 --- a/src/test/jtx/AMM.h +++ b/src/test/jtx/AMM.h @@ -178,7 +178,7 @@ public: std::optional asset2 = std::nullopt, std::optional const& ammAccount = std::nullopt, bool ignoreParams = false, - unsigned apiVersion = RPC::kApiInvalidVersion) const; + unsigned apiVersion = RPC::kAPI_INVALID_VERSION) const; /** Verify the AMM balances. */ diff --git a/src/test/jtx/Account.h b/src/test/jtx/Account.h index b20b4a359a..2a11c5540e 100644 --- a/src/test/jtx/Account.h +++ b/src/test/jtx/Account.h @@ -23,7 +23,7 @@ private: public: /** The master account. */ - static Account const kMaster; + static Account const kMASTER; Account() = delete; Account(Account&&) = default; diff --git a/src/test/jtx/CaptureLogs.h b/src/test/jtx/CaptureLogs.h index b5fe302629..7effa30074 100644 --- a/src/test/jtx/CaptureLogs.h +++ b/src/test/jtx/CaptureLogs.h @@ -25,20 +25,23 @@ class CaptureLogs : public Logs std::stringstream& strm_; public: - CaptureSink(beast::Severity threshold, std::mutex& mutex, std::stringstream& strm) + CaptureSink( + beast::severities::Severity threshold, + std::mutex& mutex, + std::stringstream& strm) : beast::Journal::Sink(threshold, false), strmMutex_(mutex), strm_(strm) { } void - write(beast::Severity level, std::string const& text) override + write(beast::severities::Severity level, std::string const& text) override { std::scoped_lock const lock(strmMutex_); strm_ << text; } void - writeAlways(beast::Severity level, std::string const& text) override + writeAlways(beast::severities::Severity level, std::string const& text) override { std::scoped_lock const lock(strmMutex_); strm_ << text; @@ -46,7 +49,7 @@ class CaptureLogs : public Logs }; public: - explicit CaptureLogs(std::string* pResult) : Logs(beast::Severity::Info), pResult_(pResult) + explicit CaptureLogs(std::string* pResult) : Logs(beast::severities::KInfo), pResult_(pResult) { } @@ -56,7 +59,7 @@ public: } std::unique_ptr - makeSink(std::string const& partition, beast::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(threshold, strmMutex_, strm_); } diff --git a/src/test/jtx/CheckMessageLogs.h b/src/test/jtx/CheckMessageLogs.h index 2cc8c661eb..34e776e871 100644 --- a/src/test/jtx/CheckMessageLogs.h +++ b/src/test/jtx/CheckMessageLogs.h @@ -16,20 +16,20 @@ class CheckMessageLogs : public Logs CheckMessageLogs& owner_; public: - CheckMessageSink(beast::Severity threshold, CheckMessageLogs& owner) + CheckMessageSink(beast::severities::Severity threshold, CheckMessageLogs& owner) : beast::Journal::Sink(threshold, false), owner_(owner) { } void - write(beast::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::Severity level, std::string const& text) override + writeAlways(beast::severities::Severity level, std::string const& text) override { write(level, text); } @@ -43,12 +43,12 @@ public: found */ CheckMessageLogs(std::string msg, bool* pFound) - : Logs{beast::Severity::Debug}, msg_{std::move(msg)}, pFound_{pFound} + : Logs{beast::severities::KDebug}, msg_{std::move(msg)}, pFound_{pFound} { } std::unique_ptr - makeSink(std::string const& partition, beast::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(threshold, *this); } diff --git a/src/test/jtx/ConfidentialTransfer.h b/src/test/jtx/ConfidentialTransfer.h index 26f9a171fd..cf358bef76 100644 --- a/src/test/jtx/ConfidentialTransfer.h +++ b/src/test/jtx/ConfidentialTransfer.h @@ -61,7 +61,8 @@ class ConfidentialTransferTestBase : public beast::unit_test::Suite protected: // Offset where the bulletproof begins in a send proof blob. // Proof layout: [compact_sigma | bulletproof] - static constexpr size_t kBulletproofOffset = kEcSendProofLength - kEcDoubleBulletproofLength; + static constexpr size_t kBULLETPROOF_OFFSET = + kEC_SEND_PROOF_LENGTH - kEC_DOUBLE_BULLETPROOF_LENGTH; // Generate a forged aggregated bulletproof (double bulletproof) for // the given values and blinding factors. Used to test that splicing @@ -78,8 +79,8 @@ protected: secp256k1_pubkey h; secp256k1_mpt_get_h_generator(ctx, &h); - Buffer proof(kEcDoubleBulletproofLength); - size_t proofLen = kEcDoubleBulletproofLength; + Buffer proof(kEC_DOUBLE_BULLETPROOF_LENGTH); + size_t proofLen = kEC_DOUBLE_BULLETPROOF_LENGTH; unsigned char blindings[64]; std::memcpy(blindings, blindingFactors[0].data(), 32); @@ -104,16 +105,16 @@ protected: static Buffer const& getBadCiphertext() { - static Buffer const kBadCiphertext = []() { - Buffer buf(kEcGamalEncryptedTotalLength); - std::memset(buf.data(), 0xFF, kEcGamalEncryptedTotalLength); + static Buffer const kBAD_CIPHERTEXT = []() { + Buffer buf(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(buf.data(), 0xFF, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); - buf.data()[0] = kEcCompressedPrefixEvenY; - buf.data()[kEcGamalEncryptedLength] = kEcCompressedPrefixEvenY; + buf.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + buf.data()[kEC_GAMAL_ENCRYPTED_LENGTH] = kEC_COMPRESSED_PREFIX_EVEN_Y; return buf; }(); - return kBadCiphertext; + return kBAD_CIPHERTEXT; } // Get a trivial buffer that is structurally and mathematically valid, but @@ -122,20 +123,20 @@ protected: static Buffer const& getTrivialCiphertext() { - static Buffer const kTrivialCiphertext = []() { - Buffer buf(kEcGamalEncryptedTotalLength); - std::memset(buf.data(), 0, kEcGamalEncryptedTotalLength); + static Buffer const kTRIVIAL_CIPHERTEXT = []() { + Buffer buf(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); + std::memset(buf.data(), 0, kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); - buf.data()[0] = kEcCompressedPrefixEvenY; - buf.data()[kEcGamalEncryptedLength] = kEcCompressedPrefixEvenY; + buf.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + buf.data()[kEC_GAMAL_ENCRYPTED_LENGTH] = kEC_COMPRESSED_PREFIX_EVEN_Y; - buf.data()[kEcGamalEncryptedLength - 1] = 0x01; - buf.data()[kEcGamalEncryptedTotalLength - 1] = 0x01; + buf.data()[kEC_GAMAL_ENCRYPTED_LENGTH - 1] = 0x01; + buf.data()[kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH - 1] = 0x01; return buf; }(); - return kTrivialCiphertext; + return kTRIVIAL_CIPHERTEXT; } // Returns a valid compressed EC point (33 bytes) that can pass preflight @@ -143,31 +144,31 @@ protected: static Buffer const& getTrivialCommitment() { - static Buffer const kTrivialCommitment = []() { - Buffer buf(kEcPedersenCommitmentLength); - std::memset(buf.data(), 0, kEcPedersenCommitmentLength); + static Buffer const kTRIVIAL_COMMITMENT = []() { + Buffer buf(kEC_PEDERSEN_COMMITMENT_LENGTH); + std::memset(buf.data(), 0, kEC_PEDERSEN_COMMITMENT_LENGTH); - buf.data()[0] = kEcCompressedPrefixEvenY; + buf.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; // Set last byte to make it a valid x-coordinate on the curve - buf.data()[kEcPedersenCommitmentLength - 1] = 0x01; + buf.data()[kEC_PEDERSEN_COMMITMENT_LENGTH - 1] = 0x01; return buf; }(); - return kTrivialCommitment; + return kTRIVIAL_COMMITMENT; } static std::string getTrivialSendProofHex() { - Buffer buf(kEcSendProofLength); - std::memset(buf.data(), 0, kEcSendProofLength); + Buffer buf(kEC_SEND_PROOF_LENGTH); + std::memset(buf.data(), 0, kEC_SEND_PROOF_LENGTH); - for (std::size_t i = 0; i < kEcSendProofLength; i += kEcGamalEncryptedLength) + for (std::size_t i = 0; i < kEC_SEND_PROOF_LENGTH; i += kEC_GAMAL_ENCRYPTED_LENGTH) { - buf.data()[i] = kEcCompressedPrefixEvenY; - if (i + kEcGamalEncryptedLength - 1 < kEcSendProofLength) - buf.data()[i + kEcGamalEncryptedLength - 1] = 0x01; + buf.data()[i] = kEC_COMPRESSED_PREFIX_EVEN_Y; + if (i + kEC_GAMAL_ENCRYPTED_LENGTH - 1 < kEC_SEND_PROOF_LENGTH) + buf.data()[i + kEC_GAMAL_ENCRYPTED_LENGTH - 1] = 0x01; } return strHex(buf); diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 3d813d993c..45c42da2e2 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -75,7 +75,7 @@ noripple(Account const& account, Args const&... args) inline FeatureBitset testableAmendments() { - static FeatureBitset const kIds = [] { + static FeatureBitset const kIDS = [] { auto const& sa = allAmendments(); std::vector feats; feats.reserve(sa.size()); @@ -93,7 +93,7 @@ testableAmendments() } return FeatureBitset(feats); }(); - return kIds; + return kIDS; } //------------------------------------------------------------------------------ @@ -103,14 +103,15 @@ class SuiteLogs : public Logs beast::unit_test::Suite& suite_; public: - explicit SuiteLogs(beast::unit_test::Suite& suite) : Logs(beast::Severity::Error), 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::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(partition, threshold, suite_); } @@ -124,7 +125,7 @@ class Env public: beast::unit_test::Suite& test; - Account const& master = Account::kMaster; + Account const& master = Account::kMASTER; /// Used by parseResult() and postConditions() struct ParsedResult @@ -154,7 +155,7 @@ private: beast::unit_test::Suite& suite, std::unique_ptr config, std::unique_ptr logs, - beast::Severity thresh); + beast::severities::Severity thresh); ~AppBundle(); }; @@ -187,12 +188,12 @@ public: std::unique_ptr config, FeatureBitset features, std::unique_ptr logs = nullptr, - beast::Severity thresh = beast::Severity::Error) + beast::severities::Severity thresh = beast::severities::KError) : test(suite) , bundle_(suite, std::move(config), std::move(logs), thresh) , journal{bundle_.app->getJournal("Env")} { - memoize(Account::kMaster); + memoize(Account::kMASTER); Pathfinder::initPathTable(); foreachFeature(features, [&appFeats = app().config().features](uint256 const& f) { appFeats.insert(f); @@ -234,7 +235,7 @@ public: Env(beast::unit_test::Suite& suite, std::unique_ptr config, std::unique_ptr logs = nullptr, - beast::Severity thresh = beast::Severity::Error) + beast::severities::Severity thresh = beast::severities::KError) : Env(suite, std::move(config), testableAmendments(), std::move(logs), thresh) { } @@ -248,7 +249,8 @@ public: * * @param suite the current unit_test::suite */ - Env(beast::unit_test::Suite& suite, beast::Severity thresh = beast::Severity::Error) + Env(beast::unit_test::Suite& suite, + beast::severities::Severity thresh = beast::severities::KError) : Env(suite, envconfig(), nullptr, thresh) { } @@ -531,13 +533,13 @@ public: /** Return an account root. @return empty if the account does not exist. */ - [[nodiscard]] SLE::const_pointer + [[nodiscard]] std::shared_ptr le(Account const& account) const; /** Return a ledger entry. @return empty if the ledger entry does not exist */ - [[nodiscard]] SLE::const_pointer + [[nodiscard]] std::shared_ptr le(Keylet const& k) const; /** Create a JTx from parameters. */ @@ -604,7 +606,7 @@ public: void signAndSubmit( JTx const& jt, - json::Value params = json::ValueType::Null, + json::Value params = json::NullValue, std::source_location const& loc = std::source_location::current()); /** Check expected postconditions @@ -869,7 +871,7 @@ Env::rpc( Args&&... args) { return doRpc( - RPC::kApiCommandLineVersion, + RPC::kAPI_COMMAND_LINE_VERSION, std::vector{cmd, std::forward(args)...}, headers); } diff --git a/src/test/jtx/Env_ss.h b/src/test/jtx/Env_ss.h index ca0825eac7..a49cf96bb6 100644 --- a/src/test/jtx/Env_ss.h +++ b/src/test/jtx/Env_ss.h @@ -27,7 +27,7 @@ private: } void - operator()(json::Value const& params = json::ValueType::Null) + operator()(json::Value const& params = json::NullValue) { env_.signAndSubmit(jt_, params, loc_); } diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index 0c9e5ffe24..6a28a564b7 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -163,7 +163,7 @@ public: auto const get = [](AnyAmount a) { return a; }; BEAST_EXPECT(!get(usd(10)).isAny); - BEAST_EXPECT(get(kAny(usd(10))).isAny); + BEAST_EXPECT(get(kANY(usd(10))).isAny); } // Test Env @@ -240,13 +240,13 @@ public: env.fund(n, "alice"); env.require(Balance("alice", n)); env(noop("alice"), Fee(1), Ter(telINSUF_FEE_P)); - env(noop("alice"), Seq(kNone), Ter(temMALFORMED)); - env(noop("alice"), Seq(kNone), Fee(10), Ter(temMALFORMED)); - env(noop("alice"), Fee(kNone), Ter(temMALFORMED)); - env(noop("alice"), Sig(kNone), Ter(temMALFORMED)); - env(noop("alice"), Fee(kAutofill)); - env(noop("alice"), Fee(kAutofill), Seq(kAutofill)); - env(noop("alice"), Fee(kAutofill), Seq(kAutofill), Sig(kAutofill)); + env(noop("alice"), Seq(kNONE), Ter(temMALFORMED)); + env(noop("alice"), Seq(kNONE), Fee(10), Ter(temMALFORMED)); + env(noop("alice"), Fee(kNONE), Ter(temMALFORMED)); + env(noop("alice"), Sig(kNONE), Ter(temMALFORMED)); + env(noop("alice"), Fee(kAUTOFILL)); + env(noop("alice"), Fee(kAUTOFILL), Seq(kAUTOFILL)); + env(noop("alice"), Fee(kAUTOFILL), Seq(kAUTOFILL), Sig(kAUTOFILL)); } } @@ -258,11 +258,11 @@ public: Env env(*this); auto const gw = Account("gw"); auto const usd = gw["USD"]; - env.require(Balance("alice", kNone)); - env.require(Balance("alice", XRP(kNone))); + env.require(Balance("alice", kNONE)); + env.require(Balance("alice", XRP(kNONE))); env.fund(XRP(10000), "alice", gw); env.close(); - env.require(Balance("alice", usd(kNone))); + env.require(Balance("alice", usd(kNONE))); env.trust(usd(100), "alice"); env.require(Balance("alice", XRP(10000))); // fee refunded env.require(Balance("alice", usd(0))); @@ -324,11 +324,11 @@ public: env.require(Balance("carol", XRP(10000))); env.require(Balance(gw, XRP(10000))); - env(pay(env.master, "alice", XRP(1000)), Fee(kNone), Ter(temMALFORMED)); + env(pay(env.master, "alice", XRP(1000)), Fee(kNONE), Ter(temMALFORMED)); env(pay(env.master, "alice", XRP(1000)), Fee(1), Ter(telINSUF_FEE_P)); - env(pay(env.master, "alice", XRP(1000)), Seq(kNone), Ter(temMALFORMED)); + env(pay(env.master, "alice", XRP(1000)), Seq(kNONE), Ter(temMALFORMED)); env(pay(env.master, "alice", XRP(1000)), Seq(20), Ter(terPRE_SEQ)); - env(pay(env.master, "alice", XRP(1000)), Sig(kNone), Ter(temMALFORMED)); + env(pay(env.master, "alice", XRP(1000)), Sig(kNONE), Ter(temMALFORMED)); env(pay(env.master, "alice", XRP(1000)), Sig("bob"), Ter(tefBAD_AUTH)); env(pay(env.master, "dilbert", XRP(1000)), Sig(env.master)); @@ -342,9 +342,9 @@ public: env.require(Balance(gw, Account("carol")["USD"](-50))); env(offer("carol", XRP(50), usd(50)), Require(Owners("carol", 2))); - env(pay("alice", "bob", kAny(usd(10))), Ter(tecPATH_DRY)); - env(pay("alice", "bob", kAny(usd(10))), Paths(XRP), Sendmax(XRP(10)), Ter(tecPATH_PARTIAL)); - env(pay("alice", "bob", kAny(usd(10))), Paths(XRP), Sendmax(XRP(20))); + env(pay("alice", "bob", kANY(usd(10))), Ter(tecPATH_DRY)); + env(pay("alice", "bob", kANY(usd(10))), Paths(XRP), Sendmax(XRP(10)), Ter(tecPATH_PARTIAL)); + env(pay("alice", "bob", kANY(usd(10))), Paths(XRP), Sendmax(XRP(20))); env.require(Balance("bob", usd(10))); env.require(Balance("carol", usd(39.5))); @@ -359,7 +359,7 @@ public: env.require(Nflags("alice", asfDisableMaster)); env(fset("alice", asfDisableMaster), Sig("alice")); env.require(Flags("alice", asfDisableMaster)); - env(regkey("alice", kDisabled), Ter(tecNO_ALTERNATIVE_KEY)); + env(regkey("alice", kDISABLED), Ter(tecNO_ALTERNATIVE_KEY)); env(noop("alice")); env(noop("alice"), Sig("alice"), Ter(tefMASTER_DISABLED)); env(noop("alice"), Sig("eric")); @@ -368,7 +368,7 @@ public: env(fclear("alice", asfDisableMaster), Sig("alice"), Ter(tefMASTER_DISABLED)); env(fclear("alice", asfDisableMaster)); env.require(Nflags("alice", asfDisableMaster)); - env(regkey("alice", kDisabled)); + env(regkey("alice", kDISABLED)); env(noop("alice"), Sig("eric"), Ter(tefBAD_AUTH)); env(noop("alice")); } @@ -397,7 +397,7 @@ public: Serializer s; jt.stx->add(s); - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::tx_blob] = strHex(s.slice()); args[jss::fail_hard] = true; @@ -468,7 +468,7 @@ public: Fee(4 * baseFee), Ter(tefBAD_SIGNATURE)); - env(signers("alice", kNone)); + env(signers("alice", kNONE)); } void @@ -703,7 +703,7 @@ public: env.fund(XRP(10000), alice); { - envs(noop(alice), Fee(kNone), Seq(kNone))(); + envs(noop(alice), Fee(kNONE), Seq(kNONE))(); // Make sure we get the right account back. auto tx = env.tx(); @@ -715,8 +715,8 @@ public: } { - auto params = json::Value(json::ValueType::Null); - envs(noop(alice), Fee(kNone), Seq(kNone))(params); + auto params = json::Value(json::NullValue); + envs(noop(alice), Fee(kNONE), Seq(kNONE))(params); // Make sure we get the right account back. auto tx = env.tx(); @@ -728,14 +728,14 @@ public: } { - auto params = json::Value(json::ValueType::Object); + auto params = json::Value(json::ObjectValue); // Force the factor low enough to fail 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(kNone), Seq(kNone), Rpc(RpcHighFee, expectedErrorString))(params); + envs(noop(alice), Fee(kNONE), Seq(kNONE), Rpc(RpcHighFee, expectedErrorString))(params); auto tx = env.tx(); BEAST_EXPECT(!tx); @@ -867,7 +867,7 @@ public: return cfg; }), nullptr, - beast::Severity::Disabled}; + beast::severities::KDisabled}; }); pass(); } diff --git a/src/test/jtx/Oracle.h b/src/test/jtx/Oracle.h index cf091c6d13..becc572e4a 100644 --- a/src/test/jtx/Oracle.h +++ b/src/test/jtx/Oracle.h @@ -11,9 +11,9 @@ using OraclesData = std::vector, std::optional< // Special string value, which is converted to unquoted string in the string // passed to rpc. -constexpr char const* kNoneTag = "%None%"; -constexpr char const* kUnquotedNone = "None"; -constexpr char const* kNonePattern = "\"%None%\""; +constexpr char const* kNONE_TAG = "%None%"; +constexpr char const* kUNQUOTED_NONE = "None"; +constexpr char const* kNONE_PATTERN = "\"%None%\""; std::uint32_t asUInt(AnyValue const& v); @@ -83,7 +83,8 @@ 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}. -static constexpr std::chrono::seconds kTestStartTime = kEpochOffset + std::chrono::seconds(10'000); +constexpr static std::chrono::seconds kTEST_START_TIME = + kEPOCH_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, diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index a391adcb1b..9b5f893d5a 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -18,7 +18,7 @@ countOffers( Asset const& takerGets) { size_t count = 0; - forEachItem(*env.current(), account, [&](SLE::const_ref sle) { + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays).asset() == takerPays && sle->getFieldAmount(sfTakerGets).asset() == takerGets) ++count; @@ -34,7 +34,7 @@ countOffers( STAmount const& takerGets) { size_t count = 0; - forEachItem(*env.current(), account, [&](SLE::const_ref sle) { + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays) == takerPays && sle->getFieldAmount(sfTakerGets) == takerGets) ++count; @@ -109,7 +109,7 @@ TestPath::pushBack(Issue const& iss) { path.emplaceBack( STPathElement::TypeCurrency | STPathElement::TypeIssuer, - beast::kZero, + beast::kZERO, iss.currency, iss.account); return *this; @@ -120,7 +120,7 @@ TestPath::pushBack(MPTIssue const& iss) { path.emplaceBack( STPathElement::TypeMpt | STPathElement::TypeIssuer, - beast::kZero, + beast::kZERO, iss.getMptID(), iss.getIssuer()); return *this; @@ -129,7 +129,7 @@ TestPath::pushBack(MPTIssue const& iss) inline TestPath& TestPath::pushBack(jtx::Account const& account) { - path.emplaceBack(account.id(), Currency{beast::kZero}, beast::kZero); + path.emplaceBack(account.id(), Currency{beast::kZERO}, beast::kZERO); return *this; } @@ -145,7 +145,7 @@ TestPath::addHelper(First&& first, Rest&&... rest) inline json::Value TestPath::json() const { - return path.getJson(JsonOptions::Values::None); + return path.getJson(JsonOptions::KNone); } class PathSet @@ -170,7 +170,7 @@ public: json() const { json::Value v; - v["Paths"] = paths.getJson(JsonOptions::Values::None); + v["Paths"] = paths.getJson(JsonOptions::KNone); return v; } diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 27c54d830b..de0017bfa9 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -101,7 +101,7 @@ public: } }; -struct UInt256Field : public JTxField +struct Uint256Field : public JTxField { using SF = SF_UINT256; using SV = uint256; @@ -112,7 +112,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) { } @@ -163,7 +163,7 @@ public: [[nodiscard]] OV value() const override { - return value_.getJson(JsonOptions::Values::None); + return value_.getJson(JsonOptions::KNone); } }; @@ -274,9 +274,9 @@ using simpleField = JTxFieldWrapper>; /** General field definitions, or fields used in multiple transaction namespaces */ -auto const kData = JTxFieldWrapper(sfData); +auto const kDATA = JTxFieldWrapper(sfData); -auto const kAmount = JTxFieldWrapper(sfAmount); +auto const kAMOUNT = JTxFieldWrapper(sfAmount); // TODO We only need this long "requires" clause as polyfill, for C++20 // implementations which are missing header. Replace with @@ -356,7 +356,7 @@ checkVL(Slice const& result, std::string const& expected) [[nodiscard]] inline bool -checkVL(SLE::const_ref 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)); } @@ -714,7 +714,7 @@ create(A const& account, A const& dest, STAmount const& sendMax) { json::Value jv; jv[sfAccount.jsonName] = to_string(account); - jv[sfSendMax.jsonName] = sendMax.getJson(JsonOptions::Values::None); + jv[sfSendMax.jsonName] = sendMax.getJson(JsonOptions::KNone); jv[sfDestination.jsonName] = to_string(dest); jv[sfTransactionType.jsonName] = jss::CheckCreate; return jv; @@ -728,8 +728,8 @@ create(jtx::Account const& account, jtx::Account const& dest, STAmount const& se } // namespace check -static constexpr FeeLevel64 kBaseFeeLevel{TxQ::kBaseLevel}; -static constexpr FeeLevel64 kMinEscalationFeeLevel = kBaseFeeLevel * 500; +static constexpr FeeLevel64 kBASE_FEE_LEVEL{TxQ::kBASE_LEVEL}; +static constexpr FeeLevel64 kMIN_ESCALATION_FEE_LEVEL = kBASE_FEE_LEVEL * 500; inline uint256 getCheckIndex(AccountID const& account, std::uint32_t uSequence) @@ -746,8 +746,8 @@ checkMetrics( std::optional expectedMaxCount, std::size_t expectedInLedger, std::size_t expectedPerLedger, - std::uint64_t expectedMinFeeLevel = kBaseFeeLevel.fee(), - std::uint64_t expectedMedFeeLevel = kMinEscalationFeeLevel.fee(), + std::uint64_t expectedMinFeeLevel = kBASE_FEE_LEVEL.fee(), + std::uint64_t expectedMedFeeLevel = kMIN_ESCALATION_FEE_LEVEL.fee(), std::source_location const location = std::source_location::current()) { int const line = location.line(); @@ -757,11 +757,11 @@ checkMetrics( auto const metrics = env.app().getTxQ().getMetrics(*env.current()); using namespace std::string_literals; - metrics.referenceFeeLevel == kBaseFeeLevel + metrics.referenceFeeLevel == kBASE_FEE_LEVEL ? test.pass() : test.fail( "reference: "s + std::to_string(metrics.referenceFeeLevel.value()) + "/" + - std::to_string(kBaseFeeLevel.value()), + std::to_string(kBASE_FEE_LEVEL.value()), file, line); @@ -856,19 +856,20 @@ coverWithdraw( json::Value coverClawback(AccountID const& account, std::uint32_t flags = 0); -auto const kLoanBrokerId = JTxFieldWrapper(sfLoanBrokerID); +auto const kLOAN_BROKER_ID = JTxFieldWrapper(sfLoanBrokerID); -auto const kManagementFeeRate = +auto const kMANAGEMENT_FEE_RATE = valueUnitWrapper(sfManagementFeeRate); -auto const kDebtMaximum = simpleField(sfDebtMaximum); +auto const kDEBT_MAXIMUM = simpleField(sfDebtMaximum); -auto const kCoverRateMinimum = valueUnitWrapper(sfCoverRateMinimum); +auto const kCOVER_RATE_MINIMUM = + valueUnitWrapper(sfCoverRateMinimum); -auto const kCoverRateLiquidation = +auto const kCOVER_RATE_LIQUIDATION = valueUnitWrapper(sfCoverRateLiquidation); -auto const kDestination = JTxFieldWrapper(sfDestination); +auto const kDESTINATION = JTxFieldWrapper(sfDestination); } // namespace loanBroker @@ -882,35 +883,36 @@ set(AccountID const& account, Number principalRequested, std::uint32_t flags = 0); -auto const kCounterparty = JTxFieldWrapper(sfCounterparty); +auto const kCOUNTERPARTY = JTxFieldWrapper(sfCounterparty); // For `CounterPartySignature`, use `Sig(sfCounterpartySignature, ...)` -auto const kLoanOriginationFee = simpleField(sfLoanOriginationFee); +auto const kLOAN_ORIGINATION_FEE = simpleField(sfLoanOriginationFee); -auto const kLoanServiceFee = simpleField(sfLoanServiceFee); +auto const kLOAN_SERVICE_FEE = simpleField(sfLoanServiceFee); -auto const kLatePaymentFee = simpleField(sfLatePaymentFee); +auto const kLATE_PAYMENT_FEE = simpleField(sfLatePaymentFee); -auto const kClosePaymentFee = simpleField(sfClosePaymentFee); +auto const kCLOSE_PAYMENT_FEE = simpleField(sfClosePaymentFee); -auto const kOverpaymentFee = valueUnitWrapper(sfOverpaymentFee); +auto const kOVERPAYMENT_FEE = valueUnitWrapper(sfOverpaymentFee); -auto const kInterestRate = valueUnitWrapper(sfInterestRate); +auto const kINTEREST_RATE = valueUnitWrapper(sfInterestRate); -auto const kLateInterestRate = valueUnitWrapper(sfLateInterestRate); +auto const kLATE_INTEREST_RATE = + valueUnitWrapper(sfLateInterestRate); -auto const kCloseInterestRate = +auto const kCLOSE_INTEREST_RATE = valueUnitWrapper(sfCloseInterestRate); -auto const kOverpaymentInterestRate = +auto const kOVERPAYMENT_INTEREST_RATE = valueUnitWrapper(sfOverpaymentInterestRate); -auto const kPaymentTotal = simpleField(sfPaymentTotal); +auto const kPAYMENT_TOTAL = simpleField(sfPaymentTotal); -auto const kPaymentInterval = simpleField(sfPaymentInterval); +auto const kPAYMENT_INTERVAL = simpleField(sfPaymentInterval); -auto const kGracePeriod = simpleField(sfGracePeriod); +auto const kGRACE_PERIOD = simpleField(sfGracePeriod); json::Value manage(AccountID const& account, uint256 const& loanID, std::uint32_t flags); diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index 9a53a32481..05efc9eea2 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -101,7 +101,7 @@ public: SecretKey const& ssk, int seq) { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -339,7 +339,7 @@ public: static std::string const& cert() { - static std::string const kCert{R"cert( + static std::string const kCERT{R"cert( -----BEGIN CERTIFICATE----- MIIDczCCAlugAwIBAgIBATANBgkqhkiG9w0BAQsFADBjMQswCQYDVQQGEwJVUzEL MAkGA1UECAwCQ0ExFDASBgNVBAcMC0xvcyBBbmdlbGVzMRswGQYDVQQKDBJyaXBw @@ -362,13 +362,13 @@ GSGO8NEEq8BTVmp69zD1JyfvQcXzsi7WtkAX+/EOFZ7LesnZ6VsyjZ74wECCaQuD X1yu/XxHqchM+DOzzVw6wRKaM7Zsk80= -----END CERTIFICATE----- )cert"}; - return kCert; + return kCERT; } static std::string const& key() { - static std::string const kKey{R"pkey( + static std::string const kEY{R"pkey( -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAueZ1hgRxwPgfeVx2AdngUYx7zYcaxcGYXyqi7izJqTuBUcVc TRC/9Ip67RAEhfcgGudRS/a4Sv1ljwiRknSCcD/ZjzOFDLgbqYGSZNEs+T/qkwmc @@ -397,13 +397,13 @@ cK55dMILcbHqeIBq/wR6sIhw6IJcaDBfFfrJiKKDilfij2lHxR2FQrEngtTCCRV+ ZzARzaWhQPvbDqEtLJDWuXZNXfL8/PTIs5NmuKuQ8F4+gQJpkQgwaw== -----END RSA PRIVATE KEY----- )pkey"}; - return kKey; + return kEY; } static std::string const& caCert() { - static std::string const kCert{R"cert( + static std::string const kCERT{R"cert( -----BEGIN CERTIFICATE----- MIIDpzCCAo+gAwIBAgIUWc45WqaaNuaSLoFYTMC/Mjfqw/gwDQYJKoZIhvcNAQEL BQAwYzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRQwEgYDVQQHDAtMb3MgQW5n @@ -427,7 +427,7 @@ mRMyNekaRw+Npy4Hjou5sx272cXHHmPCSF5TjwdaibSaGjx1k0Q50mOf7S9KG5b5 7X1e3FekJlaD02EBEhtkXURIxogOQALdFncj -----END CERTIFICATE----- )cert"}; - return kCert; + return kCERT; } static std::string const& @@ -545,11 +545,11 @@ private: else { int refresh = 5; - static constexpr char const* kRefreshPrefix = "/validators2/refresh/"; - if (boost::starts_with(path, kRefreshPrefix)) + constexpr char const* kREFRESH_PREFIX = "/validators2/refresh/"; + if (boost::starts_with(path, kREFRESH_PREFIX)) { refresh = boost::lexical_cast( - path.substr(strlen(kRefreshPrefix))); + path.substr(strlen(kREFRESH_PREFIX))); } res.body() = getList2_(refresh); } @@ -569,11 +569,11 @@ private: else { int refresh = 5; - static constexpr char const* kRefreshPrefix = "/validators/refresh/"; - if (boost::starts_with(path, kRefreshPrefix)) + constexpr char const* kREFRESH_PREFIX = "/validators/refresh/"; + if (boost::starts_with(path, kREFRESH_PREFIX)) { refresh = boost::lexical_cast( - path.substr(strlen(kRefreshPrefix))); + path.substr(strlen(kREFRESH_PREFIX))); } res.body() = getList_(refresh); } diff --git a/src/test/jtx/WSClient_test.cpp b/src/test/jtx/WSClient_test.cpp index d77e0f948b..25d922d48e 100644 --- a/src/test/jtx/WSClient_test.cpp +++ b/src/test/jtx/WSClient_test.cpp @@ -20,7 +20,7 @@ public: auto wsc = makeWSClient(env.app().config()); { json::Value jv; - jv["streams"] = json::ValueType::Array; + jv["streams"] = json::ArrayValue; jv["streams"].append("ledger"); } env.fund(XRP(10000), "alice"); diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index db281419ef..4bf5bffd6b 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -55,7 +55,8 @@ struct None // This value is also defined in SystemParameters.h. It's // duplicated here to catch any possible future errors that // could change that value (however unlikely). -constexpr XRPAmount kJtxDropsPerXrp{1'000'000}; +// TODO: rename — clashes with xrpl::kDROPS_PER_XRP +constexpr XRPAmount kJTX_DROPS_PER_XRP{1'000'000}; /** Represents an XRP, IOU, or MPT quantity This customizes the string conversion and supports @@ -275,7 +276,7 @@ struct XrpT operator()(T v) const { using TOut = std::conditional_t, std::int64_t, std::uint64_t>; - return {TOut{v} * kJtxDropsPerXrp}; + return {TOut{v} * kJTX_DROPS_PER_XRP}; } /** Returns an amount of XRP as PrettyAmount, @@ -286,7 +287,7 @@ struct XrpT PrettyAmount operator()(Number v) const { - auto const c = kJtxDropsPerXrp.drops(); + auto const c = kJTX_DROPS_PER_XRP.drops(); auto const d = std::int64_t(v * c); if (Number(d) / c != v) Throw("unrepresentable"); @@ -296,7 +297,7 @@ struct XrpT PrettyAmount operator()(double v) const { - auto const c = kJtxDropsPerXrp.drops(); + auto const c = kJTX_DROPS_PER_XRP.drops(); if (v >= 0) { auto const d = std::uint64_t(std::round(v * c)); @@ -370,7 +371,7 @@ struct EpsilonT } }; -static EpsilonT const kEpsilon; +static EpsilonT const kEPSILON; /** Converts to IOU Issue or STAmount. @@ -611,7 +612,7 @@ AnyT::operator()(STAmount const& sta) const /** Returns an amount representing "any issuer" @note With respect to what the recipient will accept */ -extern AnyT const kAny; +extern AnyT const kANY; } // namespace test::jtx diff --git a/src/test/jtx/credentials.h b/src/test/jtx/credentials.h index c2719bf897..e441232825 100644 --- a/src/test/jtx/credentials.h +++ b/src/test/jtx/credentials.h @@ -47,7 +47,7 @@ public: void operator()(jtx::Env&, jtx::JTx& jtx) const { - auto& arr(jtx.jv[sfCredentialIDs.jsonName] = json::ValueType::Array); + auto& arr(jtx.jv[sfCredentialIDs.jsonName] = json::ArrayValue); for (auto const& hash : credentials_) arr.append(hash); } diff --git a/src/test/jtx/directory.h b/src/test/jtx/directory.h index 9a87266802..5f277d6c91 100644 --- a/src/test/jtx/directory.h +++ b/src/test/jtx/directory.h @@ -48,7 +48,7 @@ maximumPageIndex(Env const& env) -> std::uint64_t { if (env.enabled(fixDirectoryLimit)) return std::numeric_limits::max(); - return kDirNodeMaxPages - 1; + return kDIR_NODE_MAX_PAGES - 1; } } // namespace xrpl::test::jtx::directory diff --git a/src/test/jtx/escrow.h b/src/test/jtx/escrow.h index 58be9b701a..5cb6f65395 100644 --- a/src/test/jtx/escrow.h +++ b/src/test/jtx/escrow.h @@ -41,38 +41,38 @@ cancel(Account const& account, Account const& from, std::uint32_t seq) Rate rate(Env& env, Account const& account, std::uint32_t const& seq); -// A PreimageSha256 fulfillments and its associated kCondition. -std::array const kFb1 = {{0xA0, 0x02, 0x80, 0x00}}; +// A PreimageSha256 fulfillments and its associated kCONDITION. +std::array const kFB1 = {{0xA0, 0x02, 0x80, 0x00}}; -std::array const kCb1 = { +std::array const kCB1 = { {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 kCondition. -std::array const kFb2 = {{0xA0, 0x05, 0x80, 0x03, 0x61, 0x61, 0x61}}; +// Another PreimageSha256 fulfillments and its associated kCONDITION. +std::array const kFB2 = {{0xA0, 0x05, 0x80, 0x03, 0x61, 0x61, 0x61}}; -std::array const kCb2 = { +std::array const kCB2 = { {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 kFulfillment and its associated kCondition. -std::array const kFb3 = {{0xA0, 0x06, 0x80, 0x04, 0x6E, 0x69, 0x6B, 0x62}}; +// Another PreimageSha256 kFULFILLMENT and its associated kCONDITION. +std::array const kFB3 = {{0xA0, 0x06, 0x80, 0x04, 0x6E, 0x69, 0x6B, 0x62}}; -std::array const kCb3 = { +std::array const kCB3 = { {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 kFinishTime = JTxFieldWrapper(sfFinishAfter); +auto const kFINISH_TIME = JTxFieldWrapper(sfFinishAfter); /** Set the "CancelAfter" time tag on a JTx */ -auto const kCancelTime = JTxFieldWrapper(sfCancelAfter); +auto const kCANCEL_TIME = JTxFieldWrapper(sfCancelAfter); -auto const kCondition = JTxFieldWrapper(sfCondition); +auto const kCONDITION = JTxFieldWrapper(sfCondition); -auto const kFulfillment = JTxFieldWrapper(sfFulfillment); +auto const kFULFILLMENT = JTxFieldWrapper(sfFulfillment); } // namespace xrpl::test::jtx::escrow diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index c6dc14081a..5193034826 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -141,8 +141,8 @@ AMM::createJv( { json::Value jv; jv[jss::Account] = to_string(account); - jv[jss::Amount] = asset1.getJson(JsonOptions::Values::None); - jv[jss::Amount2] = asset2.getJson(JsonOptions::Values::None); + jv[jss::Amount] = asset1.getJson(JsonOptions::KNone); + jv[jss::Amount2] = asset2.getJson(JsonOptions::KNone); jv[jss::TradingFee] = tfee; jv[jss::TransactionType] = jss::AMMCreate; @@ -199,25 +199,25 @@ AMM::ammRpcInfo( if (asset1 || asset2) { if (asset1) - jv[jss::asset] = STIssue(sfAsset, *asset1).getJson(JsonOptions::Values::None); + jv[jss::asset] = STIssue(sfAsset, *asset1).getJson(JsonOptions::KNone); if (asset2) - jv[jss::asset2] = STIssue(sfAsset2, *asset2).getJson(JsonOptions::Values::None); + jv[jss::asset2] = STIssue(sfAsset2, *asset2).getJson(JsonOptions::KNone); } else if (!ammAccount) { - jv[jss::asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::Values::None); - jv[jss::asset2] = STIssue(sfAsset2, asset2_.asset()).getJson(JsonOptions::Values::None); + jv[jss::asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::KNone); + jv[jss::asset2] = STIssue(sfAsset2, asset2_.asset()).getJson(JsonOptions::KNone); } if (ammAccount) jv[jss::amm_account] = to_string(*ammAccount); } auto jr = - (apiVersion == RPC::kApiInvalidVersion + (apiVersion == RPC::kAPI_INVALID_VERSION ? 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::ValueType::Null; + return json::NullValue; } std::tuple @@ -374,13 +374,13 @@ AMM::setTokens(json::Value& jv, std::optional> const& as { if (assets) { - jv[jss::Asset] = STIssue(sfAsset, assets->first).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, assets->second).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, assets->first).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, assets->second).getJson(JsonOptions::KNone); } else { - jv[jss::Asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, asset2_.asset()).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, asset2_.asset()).getJson(JsonOptions::KNone); } } @@ -392,8 +392,8 @@ AMM::depositJv(DepositArg const& arg) Throw("AMM::depositJv: account or assets not set"); jv[jss::Account] = arg.account->human(); - jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::KNone); if (arg.tokens) arg.tokens->tokens().setJson(jv[jss::LPTokenOut]); if (arg.asset1In) @@ -538,8 +538,8 @@ AMM::withdrawJv(WithdrawArg const& arg) if (!arg.account || !arg.assets) Throw("AMM::withdrawJv: account or assets not set"); jv[jss::Account] = arg.account->human(); - jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::KNone); if (arg.tokens) arg.tokens->tokens().setJson(jv[jss::LPTokenIn]); if (arg.asset1Out) @@ -674,8 +674,8 @@ AMM::voteJv(VoteArg const& arg) if (!arg.account || !arg.assets) Throw("AMM::withdrawJv: account or assets not set"); jv[jss::Account] = arg.account->human(); - jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::KNone); jv[jss::TradingFee] = arg.tfee; if (arg.flags) jv[jss::Flags] = *arg.flags; @@ -758,7 +758,7 @@ AMM::bid(BidArg const& arg) } if (!arg.authAccounts.empty()) { - json::Value accounts(json::ValueType::Array); + json::Value accounts(json::ArrayValue); for (auto const& account : arg.authAccounts) { json::Value acct; @@ -875,8 +875,8 @@ AMM::deleteJv(AccountID const& account, Asset const& asset1, Asset const& asset2 { json::Value jv; jv[jss::Account] = to_string(account); - jv[jss::Asset] = STIssue(sfAsset, asset1).getJson(JsonOptions::Values::None); - jv[jss::Asset2] = STIssue(sfAsset, asset2).getJson(JsonOptions::Values::None); + jv[jss::Asset] = STIssue(sfAsset, asset1).getJson(JsonOptions::KNone); + jv[jss::Asset2] = STIssue(sfAsset, asset2).getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::AMMDelete; @@ -909,7 +909,7 @@ ammClawback( jv[jss::Asset] = toJson(asset); jv[jss::Asset2] = toJson(asset2); if (amount) - jv[jss::Amount] = amount->getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount->getJson(JsonOptions::KNone); return jv; } diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 46c5e44bd3..5801e8fb44 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -213,9 +213,9 @@ AMMTest::pathTestEnv() // different from the current defaults. This function creates an env // with the search parameters that the tests were written for. return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->pathSearchOld = 7; - cfg->pathSearch = 7; - cfg->pathSearchMax = 10; + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; return cfg; })); } diff --git a/src/test/jtx/impl/Account.cpp b/src/test/jtx/impl/Account.cpp index f82b997c3d..50e6c701f1 100644 --- a/src/test/jtx/impl/Account.cpp +++ b/src/test/jtx/impl/Account.cpp @@ -23,7 +23,7 @@ namespace xrpl::test::jtx { std::unordered_map, Account, beast::Uhash<>> Account::cache; -Account const Account::kMaster( +Account const Account::kMASTER( "master", generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")), Account::PrivateCtorTag{}); diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 707e1338a7..cc3db4f1e1 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -73,25 +73,25 @@ Env::AppBundle::AppBundle( beast::unit_test::Suite& suite, std::unique_ptr config, std::unique_ptr logs, - beast::Severity thresh) + beast::severities::Severity thresh) : AppBundle() { - using beast::Severity; + using namespace beast::severities; if (logs) { - setDebugLogSink(logs->makeSink("Debug", Severity::Fatal)); + setDebugLogSink(logs->makeSink("Debug", KFatal)); } else { logs = std::make_unique(suite); // Use kFatal threshold to reduce noise from STObject. - setDebugLogSink(std::make_unique("Debug", Severity::Fatal, suite)); + setDebugLogSink(std::make_unique("Debug", KFatal, suite)); } auto tk = std::make_unique(); timeKeeper = tk.get(); // Hack so we don't have to call Config::setup HTTPClient::initializeSSLContext( - config->sslVerifyDir, config->sslVerifyFile, config->sslVerify, debugLog()); + config->SSL_VERIFY_DIR, config->SSL_VERIFY_FILE, config->SSL_VERIFY, debugLog()); owned = makeApplication(std::move(config), std::move(logs), std::move(tk)); app = owned.get(); app->getLogs().threshold(thresh); @@ -280,13 +280,13 @@ Env::seq(Account const& account) const return sle->getFieldU32(sfSequence); } -SLE::const_pointer +std::shared_ptr Env::le(Account const& account) const { return le(keylet::account(account.id())); } -SLE::const_pointer +std::shared_ptr Env::le(Keylet const& k) const { return current()->read(k); @@ -301,23 +301,23 @@ Env::fund(bool setDefaultRipple, STAmount const& amount, Account const& account) // VFALCO NOTE Is the fee formula correct? apply( pay(master, account, amount + drops(current()->fees().base)), - jtx::Seq(jtx::kAutofill), - Fee(jtx::kAutofill), - Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + Fee(jtx::kAUTOFILL), + Sig(jtx::kAUTOFILL)); apply( fset(account, asfDefaultRipple), - jtx::Seq(jtx::kAutofill), - Fee(jtx::kAutofill), - Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + Fee(jtx::kAUTOFILL), + Sig(jtx::kAUTOFILL)); require(Flags(account, asfDefaultRipple)); } else { apply( pay(master, account, amount), - jtx::Seq(jtx::kAutofill), - Fee(jtx::kAutofill), - Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + Fee(jtx::kAUTOFILL), + Sig(jtx::kAUTOFILL)); require(Nflags(account, asfDefaultRipple)); } require(jtx::Balance(account, amount)); @@ -331,14 +331,14 @@ Env::trust(STAmount const& amount, Account const& account) auto const start = balance(account); apply( jtx::trust(account, amount), - jtx::Seq(jtx::kAutofill), - Fee(jtx::kAutofill), - Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + Fee(jtx::kAUTOFILL), + Sig(jtx::kAUTOFILL)); apply( pay(master, account, drops(current()->fees().base)), - jtx::Seq(jtx::kAutofill), - Fee(jtx::kAutofill), - Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + Fee(jtx::kAUTOFILL), + Sig(jtx::kAUTOFILL)); test.expect(balance(account) == start); } diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index cf81bfab0c..01b8b5863a 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -81,11 +81,11 @@ class JSONRPCClient : public AbstractClient boost::asio::ip::tcp::socket stream_; boost::beast::multi_buffer bin_; boost::beast::multi_buffer bout_; - unsigned rpcVersion_; + unsigned rpc_version_; public: explicit JSONRPCClient(Config const& cfg, unsigned rpcVersion) - : ep_(getEndpoint(cfg)), stream_(ios_), rpcVersion_(rpcVersion) + : ep_(getEndpoint(cfg)), stream_(ios_), rpc_version_(rpcVersion) { stream_.connect(ep_); } @@ -116,7 +116,7 @@ public: { json::Value jr; jr[jss::method] = cmd; - if (rpcVersion_ == 2) + if (rpc_version_ == 2) { jr[jss::jsonrpc] = "2.0"; jr[jss::ripplerpc] = "2.0"; @@ -124,7 +124,7 @@ public: } if (params) { - json::Value& ja = jr[jss::params] = json::ValueType::Array; + json::Value& ja = jr[jss::params] = json::ArrayValue; ja.append(params); } req.body() = to_string(jr); @@ -148,7 +148,7 @@ public: [[nodiscard]] unsigned version() const override { - return rpcVersion_; + return rpc_version_; } }; diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 991c84fc18..051e1f4470 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -39,7 +39,7 @@ Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) : env_(env) // on testStartTime since XRPL epoch. auto const now = env_.timeKeeper().now(); if (now.time_since_epoch().count() == 0 || arg.close) - env_.close(now + kTestStartTime - kEpochOffset); + env_.close(now + kTEST_START_TIME - kEPOCH_OFFSET); if (arg.owner) owner_ = *arg.owner; if (arg.documentID && validDocumentID(*arg.documentID)) @@ -167,7 +167,7 @@ Oracle::aggregatePrice( std::optional const& timeThreshold) { json::Value jv; - json::Value jvOracles(json::ValueType::Array); + json::Value jvOracles(json::ArrayValue); if (oracles) { for (auto const& id : *oracles) @@ -191,7 +191,7 @@ Oracle::aggregatePrice( toJson(jv[jss::time_threshold], *timeThreshold); // Convert "%None%" to None auto str = to_string(jv); - str = boost::regex_replace(str, boost::regex(kNonePattern), kUnquotedNone); + str = boost::regex_replace(str, boost::regex(kNONE_PATTERN), kUNQUOTED_NONE); auto jr = env.rpc("json", "get_aggregate_price", str); if (jr.isObject()) @@ -205,7 +205,7 @@ Oracle::aggregatePrice( return jr; } } - return json::ValueType::Null; + return json::NullValue; } void @@ -256,7 +256,7 @@ Oracle::set(UpdateArg const& arg) if (std::holds_alternative(*arg.lastUpdateTime)) { jv[jss::LastUpdateTime] = - to_string(kTestStartTime.count() + std::get(*arg.lastUpdateTime)); + to_string(kTEST_START_TIME.count() + std::get(*arg.lastUpdateTime)); } else { @@ -267,9 +267,9 @@ Oracle::set(UpdateArg const& arg) { jv[jss::LastUpdateTime] = to_string( duration_cast(env_.current()->header().closeTime.time_since_epoch()).count() + - kEpochOffset.count()); + kEPOCH_OFFSET.count()); } - json::Value dataSeries(json::ValueType::Array); + json::Value dataSeries(json::ArrayValue); auto assetToStr = [](std::string const& s) { // assume standard currency if (s.size() == 3) @@ -351,7 +351,7 @@ Oracle::ledgerEntry( } // Convert "%None%" to None auto str = to_string(jvParams); - str = boost::regex_replace(str, boost::regex(kNonePattern), kUnquotedNone); + str = boost::regex_replace(str, boost::regex(kNONE_PATTERN), kUNQUOTED_NONE); auto jr = env.rpc("json", "ledger_entry", str); if (jr.isObject()) @@ -361,7 +361,7 @@ Oracle::ledgerEntry( if (jr.isMember(jss::result) && jr[jss::result].isMember(jss::status)) return jr[jss::result]; } - return json::ValueType::Null; + return json::NullValue; } void diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index a8ec899c8a..6be3220220 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -146,17 +146,17 @@ rpf(jtx::Account const& src, std::optional const& srcAsset, std::optional const& srcIssuer) { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::command] = "ripple_path_find"; jv[jss::source_account] = toBase58(src); jv[jss::destination_account] = toBase58(dst); - jv[jss::destination_amount] = dstAmount.getJson(JsonOptions::Values::None); + jv[jss::destination_amount] = dstAmount.getJson(JsonOptions::KNone); if (sendMax) - jv[jss::send_max] = sendMax->getJson(JsonOptions::Values::None); + jv[jss::send_max] = sendMax->getJson(JsonOptions::KNone); if (srcAsset) { - auto& sc = jv[jss::source_currencies] = json::ValueType::Array; - json::Value j = json::ValueType::Object; + auto& sc = jv[jss::source_currencies] = json::ArrayValue; + json::Value j = json::ObjectValue; addSourceAsset(j, *srcAsset, srcIssuer); sc.append(j); } @@ -172,9 +172,9 @@ pathTestEnv(beast::unit_test::Suite& suite) // with the search parameters that the tests were written for. using namespace jtx; return Env(suite, envconfig([](std::unique_ptr cfg) { - cfg->pathSearchOld = 7; - cfg->pathSearch = 7; - cfg->pathSearchMax = 10; + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; return cfg; })); } @@ -193,7 +193,7 @@ findPathsRequest( using namespace jtx; auto& app = env.app(); - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; Resource::Consumer c; RPC::JsonContext context{ @@ -206,22 +206,22 @@ findPathsRequest( .role = Role::USER, .coro = {}, .infoSub = {}, - .apiVersion = RPC::kApiVersionIfUnspecified}, + .apiVersion = RPC::kAPI_VERSION_IF_UNSPECIFIED}, {}, {}}; - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; 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::Values::None); + params[jss::destination_amount] = saDstAmount.getJson(JsonOptions::KNone); if (saSendMax) - params[jss::send_max] = saSendMax->getJson(JsonOptions::Values::None); + params[jss::send_max] = saSendMax->getJson(JsonOptions::KNone); if (srcAsset) { - auto& sc = params[jss::source_currencies] = json::ValueType::Array; - json::Value j = json::ValueType::Object; + auto& sc = params[jss::source_currencies] = json::ArrayValue; + json::Value j = json::ObjectValue; addSourceAsset(j, *srcAsset, srcIssuer); sc.append(j); } @@ -262,7 +262,7 @@ findPaths( STAmount da; if (result.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, result[jss::destination_amount]); + da = amountFromJson(kSF_GENERIC, result[jss::destination_amount]); STAmount sa; STPathSet paths; @@ -274,10 +274,10 @@ findPaths( auto const& path = alts[0u]; if (path.isMember(jss::source_amount)) - sa = amountFromJson(sfGeneric, path[jss::source_amount]); + sa = amountFromJson(kSF_GENERIC, path[jss::source_amount]); if (path.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, path[jss::destination_amount]); + da = amountFromJson(kSF_GENERIC, path[jss::destination_amount]); if (path.isMember(jss::paths_computed)) { @@ -332,7 +332,7 @@ PrettyAmount xrpMinusFee(Env const& env, std::int64_t xrpAmount) { auto feeDrops = env.current()->fees().base; - return drops(kJtxDropsPerXrp * xrpAmount - feeDrops); + return drops(kJTX_DROPS_PER_XRP * xrpAmount - feeDrops); }; [[nodiscard]] bool @@ -402,7 +402,7 @@ expectOffers( { std::uint16_t cnt = 0; std::uint16_t matched = 0; - forEachItem(*env.current(), account, [&](SLE::const_ref sle) { + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { if (!sle) return false; if (sle->getType() == ltOFFER) @@ -434,7 +434,7 @@ ledgerEntryState(Env& env, Account const& acctA, Account const& acctB, std::stri json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::ripple_state][jss::currency] = currency; - jvParams[jss::ripple_state][jss::accounts] = json::ValueType::Array; + jvParams[jss::ripple_state][jss::accounts] = json::ArrayValue; jvParams[jss::ripple_state][jss::accounts].append(acctA.human()); jvParams[jss::ripple_state][jss::accounts].append(acctB.human()); return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; @@ -499,7 +499,7 @@ create( jv[jss::TransactionType] = jss::PaymentChannelCreate; jv[jss::Account] = to_string(account); jv[jss::Destination] = to_string(to); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv[jss::SettleDelay] = settleDelay.count(); jv[sfPublicKey.fieldName] = strHex(pk.slice()); if (cancelAfter) @@ -520,7 +520,7 @@ fund( jv[jss::TransactionType] = jss::PaymentChannelFund; jv[jss::Account] = to_string(account); jv[sfChannel.fieldName] = to_string(channel); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); if (expiration) jv[sfExpiration.fieldName] = expiration->time_since_epoch().count(); return jv; @@ -540,9 +540,9 @@ claim( jv[jss::Account] = to_string(account); jv["Channel"] = to_string(channel); if (amount) - jv[jss::Amount] = amount->getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount->getJson(JsonOptions::KNone); if (balance) - jv["Balance"] = balance->getJson(JsonOptions::Values::None); + jv["Balance"] = balance->getJson(JsonOptions::KNone); if (signature) jv["Signature"] = strHex(*signature); if (pk) @@ -760,7 +760,7 @@ coverDeposit( jv[sfTransactionType] = jss::LoanBrokerCoverDeposit; jv[sfAccount] = to_string(account); jv[sfLoanBrokerID] = to_string(brokerID); - jv[sfAmount] = amount.getJson(JsonOptions::Values::None); + jv[sfAmount] = amount.getJson(JsonOptions::KNone); jv[sfFlags] = flags; return jv; } @@ -776,7 +776,7 @@ coverWithdraw( jv[sfTransactionType] = jss::LoanBrokerCoverWithdraw; jv[sfAccount] = to_string(account); jv[sfLoanBrokerID] = to_string(brokerID); - jv[sfAmount] = amount.getJson(JsonOptions::Values::None); + jv[sfAmount] = amount.getJson(JsonOptions::KNone); jv[sfFlags] = flags; return jv; } diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index 551fd1404b..ba09647ce7 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -120,7 +120,7 @@ class WSClientImpl : public WSClient std::condition_variable cv_; std::list> msgs_; - unsigned rpcVersion_; + unsigned rpc_version_; void cleanup() @@ -157,7 +157,7 @@ public: , thread_([&] { ios_.run(); }) , stream_(ios_) , ws_(stream_) - , rpcVersion_(rpcVersion) + , rpc_version_(rpcVersion) { try { @@ -197,7 +197,7 @@ public: json::Value jp; if (params) jp = params; - if (rpcVersion_ == 2) + if (rpc_version_ == 2) { jp[jss::method] = cmd; jp[jss::jsonrpc] = "2.0"; @@ -284,7 +284,7 @@ public: [[nodiscard]] unsigned version() const override { - return rpcVersion_; + return rpc_version_; } private: diff --git a/src/test/jtx/impl/amount.cpp b/src/test/jtx/impl/amount.cpp index b07703dace..873eab1a6a 100644 --- a/src/test/jtx/impl/amount.cpp +++ b/src/test/jtx/impl/amount.cpp @@ -50,7 +50,7 @@ operator<<(std::ostream& os, PrettyAmount const& amount) if (issue.native()) { // measure in hundredths - auto const c = kJtxDropsPerXrp.drops() / 100; + auto const c = kJTX_DROPS_PER_XRP.drops() / 100; auto const n = amount.value().mantissa(); if (n < c) { @@ -65,7 +65,7 @@ operator<<(std::ostream& os, PrettyAmount const& amount) } else { - auto const d = double(n) / kJtxDropsPerXrp.drops(); + auto const d = double(n) / kJTX_DROPS_PER_XRP.drops(); if (amount.value().negative()) { os << "-"; @@ -117,6 +117,6 @@ operator<<(std::ostream& os, MPT const& mpt) return os; } -AnyT const kAny{}; +AnyT const kANY{}; } // namespace xrpl::test::jtx diff --git a/src/test/jtx/impl/balance.cpp b/src/test/jtx/impl/balance.cpp index ddb45a8a97..1290888ab6 100644 --- a/src/test/jtx/impl/balance.cpp +++ b/src/test/jtx/impl/balance.cpp @@ -18,12 +18,12 @@ namespace xrpl::test::jtx { ((cond) ? (env.test.pass(), true) : (env.test.fail((reason), __FILE__, __LINE__), false)) void -doBalance(Env& env, AccountID const& account, bool kNone, STAmount const& value, Issue const& issue) +doBalance(Env& env, AccountID const& account, bool kNONE, STAmount const& value, Issue const& issue) { if (isXRP(issue)) { auto const sle = env.le(keylet::account(account)); - if (kNone) + if (kNONE) { TEST_EXPECT(!sle); } @@ -37,7 +37,7 @@ doBalance(Env& env, AccountID const& account, bool kNone, STAmount const& value, else { auto const sle = env.le(keylet::line(account, issue)); - if (kNone) + if (kNONE) { TEST_EXPECT(!sle); } @@ -56,12 +56,12 @@ void doBalance( Env& env, AccountID const& account, - bool kNone, + bool kNONE, STAmount const& value, MPTIssue const& mptIssue) { auto const sle = env.le(keylet::mptoken(mptIssue.getMptID(), account)); - if (kNone) + if (kNONE) { TEST_EXPECT(!sle); } diff --git a/src/test/jtx/impl/batch.cpp b/src/test/jtx/impl/batch.cpp index 7f1df1e9f0..39051f892b 100644 --- a/src/test/jtx/impl/batch.cpp +++ b/src/test/jtx/impl/batch.cpp @@ -54,7 +54,7 @@ outer(jtx::Account const& account, uint32_t seq, STAmount const& fee, std::uint3 json::Value jv; jv[jss::TransactionType] = jss::Batch; jv[jss::Account] = account.human(); - jv[jss::RawTransactions] = json::Value{json::ValueType::Array}; + jv[jss::RawTransactions] = json::Value{json::ArrayValue}; jv[jss::Sequence] = seq; jv[jss::Flags] = flags; jv[jss::Fee] = to_string(fee); diff --git a/src/test/jtx/impl/check.cpp b/src/test/jtx/impl/check.cpp index 936cdcb818..ec3e4e12fc 100644 --- a/src/test/jtx/impl/check.cpp +++ b/src/test/jtx/impl/check.cpp @@ -16,7 +16,7 @@ cash(jtx::Account const& dest, uint256 const& checkId, STAmount const& amount) { json::Value jv; jv[sfAccount.jsonName] = dest.human(); - jv[sfAmount.jsonName] = amount.getJson(JsonOptions::Values::None); + jv[sfAmount.jsonName] = amount.getJson(JsonOptions::KNone); jv[sfCheckID.jsonName] = to_string(checkId); jv[sfTransactionType.jsonName] = jss::CheckCash; return jv; @@ -28,7 +28,7 @@ cash(jtx::Account const& dest, uint256 const& checkId, DeliverMin const& atLeast { json::Value jv; jv[sfAccount.jsonName] = dest.human(); - jv[sfDeliverMin.jsonName] = atLeast.value.getJson(JsonOptions::Values::None); + jv[sfDeliverMin.jsonName] = atLeast.value.getJson(JsonOptions::KNone); jv[sfCheckID.jsonName] = to_string(checkId); jv[sfTransactionType.jsonName] = jss::CheckCash; return jv; diff --git a/src/test/jtx/impl/delegate.cpp b/src/test/jtx/impl/delegate.cpp index 13464455e2..139311cf39 100644 --- a/src/test/jtx/impl/delegate.cpp +++ b/src/test/jtx/impl/delegate.cpp @@ -22,7 +22,7 @@ set(jtx::Account const& account, jv[jss::TransactionType] = jss::DelegateSet; jv[jss::Account] = account.human(); jv[sfAuthorize.jsonName] = authorize.human(); - json::Value permissionsJson(json::ValueType::Array); + json::Value permissionsJson(json::ArrayValue); for (auto const& permission : permissions) { json::Value permissionValue; diff --git a/src/test/jtx/impl/delivermin.cpp b/src/test/jtx/impl/delivermin.cpp index c0df67c4e5..4d13a06ac4 100644 --- a/src/test/jtx/impl/delivermin.cpp +++ b/src/test/jtx/impl/delivermin.cpp @@ -10,7 +10,7 @@ namespace xrpl::test::jtx { void DeliverMin::operator()(Env& env, JTx& jt) const { - jt.jv[jss::DeliverMin] = amount_.getJson(JsonOptions::Values::None); + jt.jv[jss::DeliverMin] = amount_.getJson(JsonOptions::KNone); } } // namespace xrpl::test::jtx diff --git a/src/test/jtx/impl/deposit.cpp b/src/test/jtx/impl/deposit.cpp index 942b874b52..daa35d5e20 100644 --- a/src/test/jtx/impl/deposit.cpp +++ b/src/test/jtx/impl/deposit.cpp @@ -39,7 +39,7 @@ authCredentials(jtx::Account const& account, std::vector c { json::Value jv; jv[sfAccount.jsonName] = account.human(); - jv[sfAuthorizeCredentials.jsonName] = json::ValueType::Array; + jv[sfAuthorizeCredentials.jsonName] = json::ArrayValue; auto& arr(jv[sfAuthorizeCredentials.jsonName]); for (auto const& o : auth) { @@ -57,7 +57,7 @@ unauthCredentials(jtx::Account const& account, std::vector { json::Value jv; jv[sfAccount.jsonName] = account.human(); - jv[sfUnauthorizeCredentials.jsonName] = json::ValueType::Array; + jv[sfUnauthorizeCredentials.jsonName] = json::ArrayValue; auto& arr(jv[sfUnauthorizeCredentials.jsonName]); for (auto const& o : auth) { diff --git a/src/test/jtx/impl/envconfig.cpp b/src/test/jtx/impl/envconfig.cpp index 56197e1078..93d976a7c9 100644 --- a/src/test/jtx/impl/envconfig.cpp +++ b/src/test/jtx/impl/envconfig.cpp @@ -20,12 +20,12 @@ setupConfigForUnitTests(Config& cfg) using namespace jtx; // Default fees to old values, so tests don't have to worry about changes in // Config.h - cfg.fees.referenceFee = UNIT_TEST_REFERENCE_FEE; - cfg.fees.accountReserve = XRP(200).value().xrp().drops(); - cfg.fees.ownerReserve = XRP(50).value().xrp().drops(); + cfg.FEES.reference_fee = UNIT_TEST_REFERENCE_FEE; + cfg.FEES.account_reserve = XRP(200).value().xrp().drops(); + cfg.FEES.owner_reserve = XRP(50).value().xrp().drops(); // The Beta API (currently v2) is always available to tests - cfg.betaRpcApi = true; + cfg.BETA_RPC_API = true; cfg.overwrite(ConfigSection::nodeDatabase(), "type", "memory"); cfg.overwrite(ConfigSection::nodeDatabase(), "path", "main"); @@ -54,7 +54,7 @@ setupConfigForUnitTests(Config& cfg) cfg[PORT_WS].set("admin", getEnvLocalhostAddr()); cfg[PORT_WS].set("port", "0"); cfg[PORT_WS].set("protocol", "ws"); - cfg.sslVerify = false; + cfg.SSL_VERIFY = false; } namespace jtx { @@ -72,7 +72,7 @@ secureGateway(std::unique_ptr cfg) { (*cfg)[PORT_RPC].set("admin", ""); (*cfg)[PORT_WS].set("admin", ""); - (*cfg)[PORT_RPC].set("secure_gateway", getEnvLocalhostAddr()); + (*cfg)[PORT_RPC].set("secureGateway", getEnvLocalhostAddr()); return cfg; } @@ -89,25 +89,25 @@ secureGatewayLocalnet(std::unique_ptr cfg) { (*cfg)[PORT_RPC].set("admin", ""); (*cfg)[PORT_WS].set("admin", ""); - (*cfg)[PORT_RPC].set("secure_gateway", "127.0.0.0/8"); - (*cfg)[PORT_WS].set("secure_gateway", "127.0.0.0/8"); + (*cfg)[PORT_RPC].set("secureGateway", "127.0.0.0/8"); + (*cfg)[PORT_WS].set("secureGateway", "127.0.0.0/8"); return cfg; } std::unique_ptr singleThreadIo(std::unique_ptr cfg) { - cfg->ioWorkers = 1; + cfg->IO_WORKERS = 1; return cfg; } -constexpr auto kDefaultSeed = "shUwVw52ofnCUX5m7kPTKzJdr4HEH"; +auto constexpr kDEFAULTSEED = "shUwVw52ofnCUX5m7kPTKzJdr4HEH"; 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() ? kDefaultSeed : seed}); + .append(std::vector{seed.empty() ? kDEFAULTSEED : seed}); return cfg; } @@ -127,7 +127,7 @@ addGrpcConfigWithSecureGateway(std::unique_ptr cfg, std::string const& s // Check https://man7.org/linux/man-pages/man7/ip.7.html // "ip_local_port_range" section for using 0 ports (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("secure_gateway", secureGateway); + (*cfg)[SECTION_PORT_GRPC].set("secureGateway", secureGateway); return cfg; } diff --git a/src/test/jtx/impl/escrow.cpp b/src/test/jtx/impl/escrow.cpp index 007f492849..f6fce08b66 100644 --- a/src/test/jtx/impl/escrow.cpp +++ b/src/test/jtx/impl/escrow.cpp @@ -25,7 +25,7 @@ create(AccountID const& account, AccountID const& to, STAmount const& amount) jv[jss::Flags] = tfFullyCanonicalSig; jv[jss::Account] = to_string(account); jv[jss::Destination] = to_string(to); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); return jv; } diff --git a/src/test/jtx/impl/fee.cpp b/src/test/jtx/impl/fee.cpp index 1bdc1251eb..4dd0f01ece 100644 --- a/src/test/jtx/impl/fee.cpp +++ b/src/test/jtx/impl/fee.cpp @@ -22,7 +22,7 @@ Fee::operator()(Env& env, JTx& jt) const } else if (amount_) { - jt[sfFee] = amount_->getJson(JsonOptions::Values::None); + jt[sfFee] = amount_->getJson(JsonOptions::KNone); } } diff --git a/src/test/jtx/impl/flags.cpp b/src/test/jtx/impl/flags.cpp index ad49f559f3..7733335668 100644 --- a/src/test/jtx/impl/flags.cpp +++ b/src/test/jtx/impl/flags.cpp @@ -34,7 +34,7 @@ Flags::operator()(Env& env) const } else if (sle->isFieldPresent(sfFlags)) { - env.test.expect(sle->isFlag(mask_)); + env.test.expect((sle->getFieldU32(sfFlags) & mask_) == mask_); } else { diff --git a/src/test/jtx/impl/ledgerStateFixes.cpp b/src/test/jtx/impl/ledgerStateFixes.cpp index 30c6659124..a4b6d9b986 100644 --- a/src/test/jtx/impl/ledgerStateFixes.cpp +++ b/src/test/jtx/impl/ledgerStateFixes.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -23,16 +22,4 @@ nftPageLinks(jtx::Account const& acct, jtx::Account const& owner) return jv; } -// Fix sfExchangeRate on a book directory. acct pays fee. -json::Value -bookExchangeRate(jtx::Account const& acct, uint256 const& bookDir) -{ - json::Value jv; - jv[sfAccount.jsonName] = acct.human(); - jv[sfLedgerFixType.jsonName] = static_cast(LedgerStateFix::FixType::BookExchangeRate); - jv[sfBookDirectory.jsonName] = to_string(bookDir); - jv[sfTransactionType.jsonName] = jss::LedgerStateFix; - return jv; -} - } // namespace xrpl::test::jtx::ledgerStateFix diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index 29aba95b5e..12f1ec6e42 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -827,14 +827,14 @@ MPTTester::getClawbackProof( return std::nullopt; auto const ciphertextBlob = sleHolder->getFieldVL(sfIssuerEncryptedBalance); - if (ciphertextBlob.size() != kEcGamalEncryptedTotalLength) + if (ciphertextBlob.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return std::nullopt; auto const pubKeyBlob = sleIssuance->getFieldVL(sfIssuerEncryptionKey); - if (pubKeyBlob.size() != kEcPubKeyLength) + if (pubKeyBlob.size() != kEC_PUB_KEY_LENGTH) return std::nullopt; - Buffer proof(kEcClawbackProofLength); + Buffer proof(kEC_CLAWBACK_PROOF_LENGTH); if (mpt_get_clawback_proof( privateKey.data(), @@ -854,14 +854,14 @@ std::optional MPTTester::getSchnorrProof(Account const& account, uint256 const& ctxHash) const { auto const pubKey = getPubKey(account); - if (!pubKey || pubKey->size() != kEcPubKeyLength) + if (!pubKey || pubKey->size() != kEC_PUB_KEY_LENGTH) return std::nullopt; auto const privKey = getPrivKey(account); - if (privKey->size() != kEcPrivKeyLength) + if (privKey->size() != kEC_PRIV_KEY_LENGTH) return std::nullopt; - Buffer proof(kEcSchnorrProofLength); + Buffer proof(kEC_SCHNORR_PROOF_LENGTH); if (mpt_get_convert_proof(pubKey->data(), privKey->data(), ctxHash.data(), proof.data()) != 0) return std::nullopt; @@ -881,7 +881,7 @@ MPTTester::getConfidentialSendProof( { auto const pedersenBalanceParams = makePedersenParams(balanceParams); - if (blindingFactor.size() != kEcBlindingFactorLength) + if (blindingFactor.size() != kEC_BLINDING_FACTOR_LENGTH) return std::nullopt; auto const senderPrivKey = getPrivKey(sender); @@ -889,10 +889,10 @@ MPTTester::getConfidentialSendProof( return std::nullopt; auto const senderPubKey = getPubKey(sender); - if (!senderPubKey || senderPubKey->size() != kEcPubKeyLength) + if (!senderPubKey || senderPubKey->size() != kEC_PUB_KEY_LENGTH) return std::nullopt; - if (amountParams.pedersenCommitment.size() != kEcPedersenCommitmentLength) + if (amountParams.pedersenCommitment.size() != kEC_PEDERSEN_COMMITMENT_LENGTH) return std::nullopt; // Build mpt_confidential_participant array @@ -900,8 +900,8 @@ MPTTester::getConfidentialSendProof( for (size_t i = 0; i < recipients.size(); ++i) { auto const& r = recipients[i]; - if (r.encryptedAmount.size() != kEcGamalEncryptedTotalLength || - r.publicKey.size() != kEcPubKeyLength) + if (r.encryptedAmount.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH || + r.publicKey.size() != kEC_PUB_KEY_LENGTH) { return std::nullopt; } @@ -909,7 +909,7 @@ MPTTester::getConfidentialSendProof( std::memcpy(participants[i].ciphertext, r.encryptedAmount.data(), kMPT_ELGAMAL_TOTAL_SIZE); } - size_t proofLen = kEcSendProofLength; + size_t proofLen = kEC_SEND_PROOF_LENGTH; Buffer proof(proofLen); if (mpt_get_confidential_send_proof( @@ -933,21 +933,21 @@ Buffer MPTTester::getPedersenCommitment(std::uint64_t const amount, Buffer const& pedersenBlindingFactor) { // Blinding factor (rho) must be a 32-byte scalar - if (pedersenBlindingFactor.size() != kEcBlindingFactorLength) + if (pedersenBlindingFactor.size() != kEC_BLINDING_FACTOR_LENGTH) Throw("Invalid blinding factor size"); // secp256k1_mpt_pedersen_commit doesn't handle amount 0, return a trivial // valid commitment for test purposes if (amount == 0) { - Buffer buf(kEcPedersenCommitmentLength); - std::memset(buf.data(), 0, kEcPedersenCommitmentLength); - buf.data()[0] = kEcCompressedPrefixEvenY; - buf.data()[kEcPedersenCommitmentLength - 1] = 0x01; + Buffer buf(kEC_PEDERSEN_COMMITMENT_LENGTH); + std::memset(buf.data(), 0, kEC_PEDERSEN_COMMITMENT_LENGTH); + buf.data()[0] = kEC_COMPRESSED_PREFIX_EVEN_Y; + buf.data()[kEC_PEDERSEN_COMMITMENT_LENGTH - 1] = 0x01; return buf; } - Buffer buf(kEcPedersenCommitmentLength); + Buffer buf(kEC_PEDERSEN_COMMITMENT_LENGTH); if (mpt_get_pedersen_commitment(amount, pedersenBlindingFactor.data(), buf.data()) != 0) Throw("Pedersen commitment generation failed"); @@ -963,20 +963,20 @@ MPTTester::getConvertBackProof( PedersenProofParams const& pcParams) const { // Expected total proof length: compact sigma proof (128 bytes) + single bulletproof (688 bytes) - std::size_t constexpr kExpectedProofLength = kEcConvertBackProofLength; + std::size_t constexpr kEXPECTED_PROOF_LENGTH = kEC_CONVERT_BACK_PROOF_LENGTH; auto const sleMptoken = env_.le(keylet::mptoken(*id_, holder.id())); if (!sleMptoken || !sleMptoken->isFieldPresent(sfConfidentialBalanceSpending)) - return gMakeZeroBuffer(kExpectedProofLength); + return gMakeZeroBuffer(kEXPECTED_PROOF_LENGTH); auto const holderPubKey = getPubKey(holder); auto const holderPrivKey = getPrivKey(holder); if (!holderPubKey || !holderPrivKey) - return gMakeZeroBuffer(kExpectedProofLength); + return gMakeZeroBuffer(kEXPECTED_PROOF_LENGTH); auto const pedersenParams = makePedersenParams(pcParams); - Buffer proof(kExpectedProofLength); + Buffer proof(kEXPECTED_PROOF_LENGTH); if (mpt_get_convert_back_proof( holderPrivKey->data(), @@ -985,7 +985,7 @@ MPTTester::getConvertBackProof( amount, &pedersenParams, proof.data()) != 0) - return gMakeZeroBuffer(kExpectedProofLength); + return gMakeZeroBuffer(kEXPECTED_PROOF_LENGTH); return proof; } @@ -1161,7 +1161,7 @@ MPTTester::convert(MPTConvert const& arg) } else { - jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEcSchnorrProofLength)); + jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEC_SCHNORR_PROOF_LENGTH)); } } @@ -1327,7 +1327,7 @@ MPTTester::convertJV(MPTConvert const& arg, std::uint32_t seq) } else { - jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEcSchnorrProofLength)); + jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEC_SCHNORR_PROOF_LENGTH)); } } @@ -1403,7 +1403,7 @@ MPTTester::send(MPTConfidentialSend const& arg) if (arg.credentials) { - auto& arr(jv[sfCredentialIDs.jsonName] = json::ValueType::Array); + auto& arr(jv[sfCredentialIDs.jsonName] = json::ArrayValue); for (auto const& hash : *arg.credentials) arr.append(hash); } @@ -1544,7 +1544,7 @@ MPTTester::send(MPTConfidentialSend const& arg) } else { - jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEcSendProofLength)); + jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEC_SEND_PROOF_LENGTH)); } } @@ -1709,7 +1709,7 @@ MPTTester::sendJV( if (arg.credentials) { - auto& arr(jv[sfCredentialIDs.jsonName] = json::ValueType::Array); + auto& arr(jv[sfCredentialIDs.jsonName] = json::ArrayValue); for (auto const& hash : *arg.credentials) arr.append(hash); } @@ -1821,7 +1821,7 @@ MPTTester::sendJV( } else { - jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEcSendProofLength)); + jv[sfZKProof.jsonName] = strHex(gMakeZeroBuffer(kEC_SEND_PROOF_LENGTH)); } } @@ -1921,7 +1921,7 @@ MPTTester::confidentialClaw(MPTConfidentialClawback const& arg) auto const contextHash = getClawbackContextHash(account.id(), *id_, seq, arg.holder->id()); auto const privKey = getPrivKey(account); - if (!privKey || privKey->size() != kEcPrivKeyLength) + if (!privKey || privKey->size() != kEC_PRIV_KEY_LENGTH) Throw("Failed to get clawback private key"); auto const proof = getClawbackProof(*arg.holder, *arg.amt, *privKey, contextHash); @@ -1932,7 +1932,7 @@ MPTTester::confidentialClaw(MPTConfidentialClawback const& arg) } else { - jv[sfZKProof] = strHex(gMakeZeroBuffer(kEcClawbackProofLength)); + jv[sfZKProof] = strHex(gMakeZeroBuffer(kEC_CLAWBACK_PROOF_LENGTH)); } } @@ -1978,23 +1978,23 @@ MPTTester::confidentialClaw(MPTConfidentialClawback const& arg) void MPTTester::generateKeyPair(Account const& account) { - unsigned char privKey[kEcPrivKeyLength]; + unsigned char privKey[kEC_PRIV_KEY_LENGTH]; secp256k1_pubkey pubKey; if (secp256k1_elgamal_generate_keypair(secp256k1Context(), privKey, &pubKey) == 0) Throw("failed to generate key pair"); // Serialize public key to compressed format (33 bytes) - unsigned char compressedPubKey[kEcPubKeyLength]; - size_t outLen = kEcPubKeyLength; + unsigned char compressedPubKey[kEC_PUB_KEY_LENGTH]; + size_t outLen = kEC_PUB_KEY_LENGTH; if (secp256k1_ec_pubkey_serialize( secp256k1Context(), compressedPubKey, &outLen, &pubKey, SECP256K1_EC_COMPRESSED) != 1 || - outLen != kEcPubKeyLength) + outLen != kEC_PUB_KEY_LENGTH) { Throw("failed to serialize public key"); } - pubKeys_.insert({account.id(), Buffer{compressedPubKey, kEcPubKeyLength}}); - privKeys_.insert({account.id(), Buffer{privKey, kEcPrivKeyLength}}); + pubKeys_.insert({account.id(), Buffer{compressedPubKey, kEC_PUB_KEY_LENGTH}}); + privKeys_.insert({account.id(), Buffer{privKey, kEC_PRIV_KEY_LENGTH}}); } std::optional @@ -2027,13 +2027,13 @@ MPTTester::encryptAmount(Account const& account, uint64_t const amt, Buffer cons // Return a dummy buffer on failure to allow testing of // failures that occur prior to encryption. - return gMakeZeroBuffer(kEcGamalEncryptedTotalLength); + return gMakeZeroBuffer(kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH); } std::optional MPTTester::decryptAmount(Account const& account, Buffer const& amt) const { - if (amt.size() != kEcGamalEncryptedTotalLength) + if (amt.size() != kEC_GAMAL_ENCRYPTED_TOTAL_LENGTH) return std::nullopt; auto const pair = makeEcPair(amt); @@ -2041,7 +2041,7 @@ MPTTester::decryptAmount(Account const& account, Buffer const& amt) const return std::nullopt; auto const privKey = getPrivKey(account); - if (!privKey || privKey->size() != kEcPrivKeyLength) + if (!privKey || privKey->size() != kEC_PRIV_KEY_LENGTH) return std::nullopt; uint64_t decryptedAmt = 0; @@ -2277,7 +2277,7 @@ MPTTester::convertBack(MPTConvertBack const& arg) // preflight/preclaim are checked if (!prevEncryptedSpendingBalance) { - proof = gMakeZeroBuffer(kEcConvertBackProofLength); + proof = gMakeZeroBuffer(kEC_CONVERT_BACK_PROOF_LENGTH); } else { @@ -2427,7 +2427,7 @@ MPTTester::convertBackJV(MPTConvertBack const& arg, std::uint32_t seq) Buffer proof; if (!prevEncSpending) { - proof = gMakeZeroBuffer(kEcConvertBackProofLength); + proof = gMakeZeroBuffer(kEC_CONVERT_BACK_PROOF_LENGTH); } else { diff --git a/src/test/jtx/impl/multisign.cpp b/src/test/jtx/impl/multisign.cpp index 66c5a4f27d..1ac65a0274 100644 --- a/src/test/jtx/impl/multisign.cpp +++ b/src/test/jtx/impl/multisign.cpp @@ -74,7 +74,7 @@ Msig::operator()(Env& env, JTx& jt) const } else if (sigObject.isNull()) { - sigObject = json::Value(json::ValueType::Object); + sigObject = json::Value(json::ObjectValue); } std::optional st; try diff --git a/src/test/jtx/impl/offer.cpp b/src/test/jtx/impl/offer.cpp index 5704349c83..2c40b9867b 100644 --- a/src/test/jtx/impl/offer.cpp +++ b/src/test/jtx/impl/offer.cpp @@ -19,8 +19,8 @@ offer( { json::Value jv; jv[jss::Account] = account.human(); - jv[jss::TakerPays] = takerPays.getJson(JsonOptions::Values::None); - jv[jss::TakerGets] = takerGets.getJson(JsonOptions::Values::None); + jv[jss::TakerPays] = takerPays.getJson(JsonOptions::KNone); + jv[jss::TakerGets] = takerGets.getJson(JsonOptions::KNone); if (flags != 0u) jv[jss::Flags] = flags; jv[jss::TransactionType] = jss::OfferCreate; diff --git a/src/test/jtx/impl/owners.cpp b/src/test/jtx/impl/owners.cpp index 2ff93757f0..cb2cd5af29 100644 --- a/src/test/jtx/impl/owners.cpp +++ b/src/test/jtx/impl/owners.cpp @@ -10,6 +10,8 @@ #include #include +#include + namespace xrpl { namespace detail { @@ -17,7 +19,7 @@ std::uint32_t ownedCountOf(ReadView const& view, AccountID const& id, LedgerEntryType type) { std::uint32_t count = 0; - forEachItem(view, id, [&count, type](SLE::const_ref sle) { + forEachItem(view, id, [&count, type](std::shared_ptr const& sle) { if (sle->getType() == type) ++count; }); diff --git a/src/test/jtx/impl/paths.cpp b/src/test/jtx/impl/paths.cpp index eb4b36ae4f..e644895cb0 100644 --- a/src/test/jtx/impl/paths.cpp +++ b/src/test/jtx/impl/paths.cpp @@ -61,20 +61,20 @@ Paths::operator()(Env& env, JTx& jt) const // VFALCO TODO API to allow caller to examine the STPathSet // VFALCO isDefault should be renamed to empty() if (!found.isDefault()) - jv[jss::Paths] = found.getJson(JsonOptions::Values::None); + jv[jss::Paths] = found.getJson(JsonOptions::KNone); } //------------------------------------------------------------------------------ Path::Path(STPath const& p) { - jv_ = p.getJson(JsonOptions::Values::None); + jv_ = p.getJson(JsonOptions::KNone); } json::Value& Path::create() { - return jv_.append(json::ValueType::Object); + return jv_.append(json::ObjectValue); } void diff --git a/src/test/jtx/impl/pay.cpp b/src/test/jtx/impl/pay.cpp index c220d9534b..90a9cd8df0 100644 --- a/src/test/jtx/impl/pay.cpp +++ b/src/test/jtx/impl/pay.cpp @@ -16,7 +16,7 @@ pay(AccountID const& account, AccountID const& to, AnyAmount amount) amount.to(to); json::Value jv; jv[jss::Account] = to_string(account); - jv[jss::Amount] = amount.value.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.value.getJson(JsonOptions::KNone); jv[jss::Destination] = to_string(to); jv[jss::TransactionType] = jss::Payment; jv[jss::Flags] = tfFullyCanonicalSig; diff --git a/src/test/jtx/impl/permissioned_dex.cpp b/src/test/jtx/impl/permissioned_dex.cpp index 5c059e9e80..012932fed5 100644 --- a/src/test/jtx/impl/permissioned_dex.cpp +++ b/src/test/jtx/impl/permissioned_dex.cpp @@ -48,7 +48,7 @@ PermissionedDEX::PermissionedDEX(Env& env) , alice("permdex-alice") , bob("permdex-bob") , carol("permdex-carol") - , usd(gw["USD"]) + , USD(gw["USD"]) , credType("permdex-abcde") { // Fund accounts @@ -59,10 +59,10 @@ PermissionedDEX::PermissionedDEX(Env& env) for (auto const& account : {alice, bob, carol, domainOwner}) { - env.trust(usd(1000), account); + env.trust(USD(1000), account); env.close(); - env(pay(gw, account, usd(100))); + env(pay(gw, account, USD(100))); env.close(); } } diff --git a/src/test/jtx/impl/permissioned_domains.cpp b/src/test/jtx/impl/permissioned_domains.cpp index 690451c7d8..f39c9a43ed 100644 --- a/src/test/jtx/impl/permissioned_domains.cpp +++ b/src/test/jtx/impl/permissioned_domains.cpp @@ -35,10 +35,10 @@ setTx(AccountID const& account, Credentials const& credentials, std::optional const& human2Acc) { Credentials ret; - json::Value credentials(json::ValueType::Array); + json::Value credentials(json::ArrayValue); credentials = object["AcceptedCredentials"]; for (auto const& credential : credentials) { - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); obj = credential[jss::Credential]; auto const& issuer = obj[jss::Issuer]; auto const& credentialType = obj["CredentialType"]; @@ -150,8 +150,8 @@ uint256 getNewDomain(std::shared_ptr const& meta) { uint256 ret; - auto metaJson = meta->getJson(JsonOptions::Values::None); - json::Value a(json::ValueType::Array); + auto metaJson = meta->getJson(JsonOptions::KNone); + json::Value a(json::ArrayValue); a = metaJson["AffectedNodes"]; for (auto const& node : a) diff --git a/src/test/jtx/impl/sendmax.cpp b/src/test/jtx/impl/sendmax.cpp index 2ea8605081..3bc39a4a59 100644 --- a/src/test/jtx/impl/sendmax.cpp +++ b/src/test/jtx/impl/sendmax.cpp @@ -10,7 +10,7 @@ namespace xrpl::test::jtx { void Sendmax::operator()(Env& env, JTx& jt) const { - jt.jv[jss::SendMax] = amount_.getJson(JsonOptions::Values::None); + jt.jv[jss::SendMax] = amount_.getJson(JsonOptions::KNone); } } // namespace xrpl::test::jtx diff --git a/src/test/jtx/impl/token.cpp b/src/test/jtx/impl/token.cpp index 8604b077c4..27d21c1694 100644 --- a/src/test/jtx/impl/token.cpp +++ b/src/test/jtx/impl/token.cpp @@ -50,7 +50,7 @@ Uri::operator()(Env& env, JTx& jt) const void Amount::operator()(Env& env, JTx& jt) const { - jt.jv[sfAmount.jsonName] = amount_.getJson(JsonOptions::Values::None); + jt.jv[sfAmount.jsonName] = amount_.getJson(JsonOptions::KNone); } uint256 @@ -98,7 +98,7 @@ createOffer(jtx::Account const& account, uint256 const& nftokenID, STAmount cons json::Value jv; jv[sfAccount.jsonName] = account.human(); jv[sfNFTokenID.jsonName] = to_string(nftokenID); - jv[sfAmount.jsonName] = amount.getJson(JsonOptions::Values::None); + jv[sfAmount.jsonName] = amount.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::NFTokenCreateOffer; return jv; } @@ -129,7 +129,7 @@ cancelOfferImpl(jtx::Account const& account, T const& nftokenOffers) jv[sfAccount.jsonName] = account.human(); if (!empty(nftokenOffers)) { - jv[sfNFTokenOffers.jsonName] = json::ValueType::Array; + jv[sfNFTokenOffers.jsonName] = json::ArrayValue; for (uint256 const& nftokenOffer : nftokenOffers) jv[sfNFTokenOffers.jsonName].append(to_string(nftokenOffer)); } @@ -192,7 +192,7 @@ brokerOffers( void BrokerFee::operator()(Env& env, JTx& jt) const { - jt.jv[sfNFTokenBrokerFee.jsonName] = brokerFee_.getJson(JsonOptions::Values::None); + jt.jv[sfNFTokenBrokerFee.jsonName] = brokerFee_.getJson(JsonOptions::KNone); } json::Value diff --git a/src/test/jtx/impl/trust.cpp b/src/test/jtx/impl/trust.cpp index 17fc6e594f..ffe14694d9 100644 --- a/src/test/jtx/impl/trust.cpp +++ b/src/test/jtx/impl/trust.cpp @@ -21,7 +21,7 @@ trust(Account const& account, STAmount const& amount, std::uint32_t flags) Throw("trust() requires IOU"); json::Value jv; jv[jss::Account] = account.human(); - jv[jss::LimitAmount] = amount.getJson(JsonOptions::Values::None); + jv[jss::LimitAmount] = amount.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::TrustSet; jv[jss::Flags] = flags; return jv; @@ -39,7 +39,7 @@ trust(Account const& account, STAmount const& amount, Account const& peer, std:: json::Value jv; jv[jss::Account] = account.human(); { - auto& ja = jv[jss::LimitAmount] = amount.getJson(JsonOptions::Values::None); + auto& ja = jv[jss::LimitAmount] = amount.getJson(JsonOptions::KNone); ja[jss::issuer] = peer.human(); } jv[jss::TransactionType] = jss::TrustSet; @@ -52,7 +52,7 @@ claw(Account const& account, STAmount const& amount, std::optional cons { json::Value jv; jv[jss::Account] = account.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::Clawback; if (mptHolder) diff --git a/src/test/jtx/impl/utility.cpp b/src/test/jtx/impl/utility.cpp index 63c9d94264..94275041f0 100644 --- a/src/test/jtx/impl/utility.cpp +++ b/src/test/jtx/impl/utility.cpp @@ -92,7 +92,7 @@ fillSeq(json::Value& jv, ReadView const& view) json::Value cmdToJSONRPC(std::vector const& args, beast::Journal j, unsigned int apiVersion) { - json::Value jv = json::Value(json::ValueType::Object); + json::Value jv = json::Value(json::ObjectValue); auto const paramsObj = rpcCmdToJson(args, jv, apiVersion, j); // Re-use jv to return our formatted result. @@ -104,7 +104,7 @@ cmdToJSONRPC(std::vector const& args, beast::Journal j, unsigned in // If paramsObj is not empty, put it in a [params] array. if (paramsObj.begin() != paramsObj.end()) { - auto& paramsArray = jv[jss::params] = json::ValueType::Array; + auto& paramsArray = jv[jss::params] = json::ArrayValue; paramsArray.append(paramsObj); } if (paramsObj.isMember(jss::jsonrpc)) diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index 24669e6d4f..8941067378 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -70,12 +70,9 @@ bridgeCreate( jv[jss::Account] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; - jv[sfSignatureReward.getJsonName()] = reward.getJson(JsonOptions::Values::None); + jv[sfSignatureReward.getJsonName()] = reward.getJson(JsonOptions::KNone); if (minAccountCreate) - { - jv[sfMinAccountCreateAmount.getJsonName()] = - minAccountCreate->getJson(JsonOptions::Values::None); - } + jv[sfMinAccountCreateAmount.getJsonName()] = minAccountCreate->getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::XChainCreateBridge; return jv; @@ -93,12 +90,9 @@ bridgeModify( jv[jss::Account] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; if (reward) - jv[sfSignatureReward.getJsonName()] = reward->getJson(JsonOptions::Values::None); + jv[sfSignatureReward.getJsonName()] = reward->getJson(JsonOptions::KNone); if (minAccountCreate) - { - jv[sfMinAccountCreateAmount.getJsonName()] = - minAccountCreate->getJson(JsonOptions::Values::None); - } + jv[sfMinAccountCreateAmount.getJsonName()] = minAccountCreate->getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::XChainModifyBridge; return jv; @@ -115,7 +109,7 @@ xchainCreateClaimId( jv[jss::Account] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; - jv[sfSignatureReward.getJsonName()] = reward.getJson(JsonOptions::Values::None); + jv[sfSignatureReward.getJsonName()] = reward.getJson(JsonOptions::KNone); jv[sfOtherChainSource.getJsonName()] = otherChainSource.human(); jv[jss::TransactionType] = jss::XChainCreateClaimID; @@ -135,7 +129,7 @@ xchainCommit( jv[jss::Account] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; jv[sfXChainClaimID.getJsonName()] = claimID; - jv[jss::Amount] = amt.value.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amt.value.getJson(JsonOptions::KNone); if (dst) jv[sfOtherChainDestination.getJsonName()] = dst->human(); @@ -157,7 +151,7 @@ xchainClaim( jv[sfXChainBridge.getJsonName()] = bridge; jv[sfXChainClaimID.getJsonName()] = claimID; jv[sfDestination.getJsonName()] = dst.human(); - jv[sfAmount.getJsonName()] = amt.value.getJson(JsonOptions::Values::None); + jv[sfAmount.getJsonName()] = amt.value.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::XChainClaim; return jv; @@ -176,8 +170,8 @@ sidechainXchainAccountCreate( jv[sfAccount.getJsonName()] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; jv[sfDestination.getJsonName()] = dst.human(); - jv[sfAmount.getJsonName()] = amt.value.getJson(JsonOptions::Values::None); - jv[sfSignatureReward.getJsonName()] = reward.value.getJson(JsonOptions::Values::None); + jv[sfAmount.getJsonName()] = amt.value.getJson(JsonOptions::KNone); + jv[sfSignatureReward.getJsonName()] = reward.value.getJson(JsonOptions::KNone); jv[jss::TransactionType] = jss::XChainAccountCreateCommit; return jv; @@ -219,11 +213,11 @@ claimAttestation( result[sfPublicKey.getJsonName()] = strHex(pk.slice()); result[sfSignature.getJsonName()] = strHex(sig); result[sfOtherChainSource.getJsonName()] = toBase58(sendingAccount); - result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::Values::None); + result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::KNone); result[sfAttestationRewardAccount.getJsonName()] = toBase58(rewardAccount); result[sfWasLockingChainSend.getJsonName()] = wasLockingChainSend ? 1 : 0; - result[sfXChainClaimID.getJsonName()] = STUInt64{claimID}.getJson(JsonOptions::Values::None); + result[sfXChainClaimID.getJsonName()] = STUInt64{claimID}.getJson(JsonOptions::KNone); if (dst) result[sfDestination.getJsonName()] = toBase58(*dst); @@ -270,14 +264,14 @@ createAccountAttestation( result[sfPublicKey.getJsonName()] = strHex(pk.slice()); result[sfSignature.getJsonName()] = strHex(sig); result[sfOtherChainSource.getJsonName()] = toBase58(sendingAccount); - result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::Values::None); + result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::KNone); result[sfAttestationRewardAccount.getJsonName()] = toBase58(rewardAccount); result[sfWasLockingChainSend.getJsonName()] = wasLockingChainSend ? 1 : 0; result[sfXChainAccountCreateCount.getJsonName()] = - STUInt64{createCount}.getJson(JsonOptions::Values::None); + STUInt64{createCount}.getJson(JsonOptions::KNone); result[sfDestination.getJsonName()] = toBase58(dst); - result[sfSignatureReward.getJsonName()] = rewardAmount.value.getJson(JsonOptions::Values::None); + result[sfSignatureReward.getJsonName()] = rewardAmount.value.getJson(JsonOptions::KNone); result[jss::TransactionType] = jss::XChainAddAccountCreateAttestation; @@ -379,15 +373,15 @@ XChainBridgeObjects::XChainBridgeObjects() , scuGw("scuGw") , mcUSD(mcGw["USD"]) , scUSD(scGw["USD"]) - , jvXRPBridgeRPC(bridgeRpc(mcDoor, xrpIssue(), Account::kMaster, xrpIssue())) - , jvb(bridge(mcDoor, xrpIssue(), Account::kMaster, xrpIssue())) - , jvub(bridge(mcuDoor, xrpIssue(), Account::kMaster, xrpIssue())) + , jvXRPBridgeRPC(bridgeRpc(mcDoor, xrpIssue(), Account::kMASTER, xrpIssue())) + , jvb(bridge(mcDoor, xrpIssue(), Account::kMASTER, xrpIssue())) + , jvub(bridge(mcuDoor, xrpIssue(), Account::kMASTER, xrpIssue())) , features(testableAmendments() | FeatureBitset{featureXChainBridge}) , signers([] { - static constexpr int kNumSigners = kUtXchainDefaultNumSigners; + constexpr int kNUM_SIGNERS = kUT_XCHAIN_DEFAULT_NUM_SIGNERS; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account( @@ -396,11 +390,11 @@ XChainBridgeObjects::XChainBridgeObjects() } return result; }()) - , altSigners([] { - static constexpr int kNumSigners = kUtXchainDefaultNumSigners; + , alt_signers([] { + constexpr int kNUM_SIGNERS = kUT_XCHAIN_DEFAULT_NUM_SIGNERS; std::vector result; - result.reserve(kNumSigners); - for (int i = 0; i < kNumSigners; ++i) + result.reserve(kNUM_SIGNERS); + for (int i = 0; i < kNUM_SIGNERS; ++i) { using namespace std::literals; auto const a = Account( @@ -431,16 +425,20 @@ XChainBridgeObjects::XChainBridgeObjects() return r; }()) , reward(XRP(1)) - , splitRewardQuorum(divide(reward, STAmount(kUtXchainDefaultQuorum), reward.get())) - , splitRewardEveryone(divide(reward, STAmount(kUtXchainDefaultNumSigners), reward.get())) - , tinyReward(drops(37)) - , tinyRewardSplit( - (divide(tinyReward, STAmount(kUtXchainDefaultQuorum), tinyReward.get()))) - , tinyRewardRemainder( - tinyReward - - multiply(tinyRewardSplit, STAmount(kUtXchainDefaultQuorum), tinyReward.get())) - , oneXrp(XRP(1)) - , xrpDust(divide(oneXrp, STAmount(10000), oneXrp.get())) + , split_reward_quorum(divide(reward, STAmount(kUT_XCHAIN_DEFAULT_QUORUM), reward.get())) + , split_reward_everyone( + divide(reward, STAmount(kUT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.get())) + , tiny_reward(drops(37)) + , tiny_reward_split( + (divide(tiny_reward, STAmount(kUT_XCHAIN_DEFAULT_QUORUM), tiny_reward.get()))) + , tiny_reward_remainder( + tiny_reward - + multiply( + tiny_reward_split, + STAmount(kUT_XCHAIN_DEFAULT_QUORUM), + tiny_reward.get())) + , one_xrp(XRP(1)) + , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.get())) { } @@ -468,13 +466,13 @@ XChainBridgeObjects::createScBridgeObjects(Env& scEnv) scEnv.fund(xrpFunds, scDoor, scAlice, scBob, scCarol, scGw, scAttester, scReward); // Signer's list must match the attestation signers - scEnv(jtx::signers(Account::kMaster, signers.size(), signers)); + scEnv(jtx::signers(Account::kMASTER, signers.size(), signers)); // create XRP bridges in both direction auto const reward = XRP(1); STAmount const minCreate = XRP(20); - scEnv(bridgeCreate(Account::kMaster, jvb, reward, minCreate)); + scEnv(bridgeCreate(Account::kMASTER, jvb, reward, minCreate)); scEnv.close(); } diff --git a/src/test/jtx/ledgerStateFix.h b/src/test/jtx/ledgerStateFix.h index 71f3f76101..769a28fb08 100644 --- a/src/test/jtx/ledgerStateFix.h +++ b/src/test/jtx/ledgerStateFix.h @@ -10,8 +10,4 @@ namespace xrpl::test::jtx::ledgerStateFix { json::Value nftPageLinks(jtx::Account const& acct, jtx::Account const& owner); -/** Repair sfExchangeRate on a book directory's first page. */ -json::Value -bookExchangeRate(jtx::Account const& acct, uint256 const& bookDir); - } // namespace xrpl::test::jtx::ledgerStateFix diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 5abc9298d8..d4f2c29b54 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -20,7 +20,7 @@ namespace xrpl::test::jtx { class MPTTester; -auto const kMptDexFlags = tfMPTCanTrade | tfMPTCanTransfer; +auto const kMPT_DEX_FLAGS = tfMPTCanTrade | tfMPTCanTransfer; /*Helper lambda to create a zero-initialized buffer. WHY THIS IS NEEDED: In C++, xrpl::Buffer(size) allocates uninitialized heap memory. @@ -127,7 +127,7 @@ struct MPTInit // create MPTIssuanceID if seated and follow rules for MPTCreate args std::optional create = std::nullopt; }; -static MPTInit const kMptInitNoFund{.fund = false}; +static MPTInit const kMPT_INIT_NO_FUND{.fund = false}; struct MPTInitDef { @@ -137,7 +137,7 @@ struct MPTInitDef std::optional auditor = std::nullopt; std::uint16_t transferFee = 0; std::optional pay = std::nullopt; - std::uint32_t flags = kMptDexFlags; + std::uint32_t flags = kMPT_DEX_FLAGS; std::optional mutableFlags = std::nullopt; bool authHolder = false; bool fund = false; diff --git a/src/test/jtx/multisign.h b/src/test/jtx/multisign.h index 3fef2ab446..62da7f65bc 100644 --- a/src/test/jtx/multisign.h +++ b/src/test/jtx/multisign.h @@ -46,7 +46,7 @@ public: SField const* const subField = nullptr; /// Used solely as a convenience placeholder for ctors that do _not_ specify /// a subfield. - static constexpr SField const* kTopLevel = nullptr; + static constexpr SField* const kTOP_LEVEL = nullptr; Msig(SField const* subField, std::vector signers) : signers(std::move(signers)), subField(subField) @@ -58,7 +58,7 @@ public: { } - Msig(std::vector signers) : Msig(kTopLevel, signers) + Msig(std::vector signers) : Msig(kTOP_LEVEL, signers) { } @@ -84,7 +84,7 @@ public: requires(std::convertible_to && !std::is_same_v) explicit Msig(AccountType&& a0, Accounts&&... aN) : Msig{ - kTopLevel, + kTOP_LEVEL, std::vector{std::forward(a0), std::forward(aN)...}} { } diff --git a/src/test/jtx/paths.h b/src/test/jtx/paths.h index a8a8f7900c..e2c88e215d 100644 --- a/src/test/jtx/paths.h +++ b/src/test/jtx/paths.h @@ -80,7 +80,7 @@ private: }; template -Path::Path(T const& t, Args const&... args) : jv_(json::ValueType::Array) +Path::Path(T const& t, Args const&... args) : jv_(json::ArrayValue) { append(t, args...); } diff --git a/src/test/jtx/permissioned_dex.h b/src/test/jtx/permissioned_dex.h index b0a4d4e2d5..025097116f 100644 --- a/src/test/jtx/permissioned_dex.h +++ b/src/test/jtx/permissioned_dex.h @@ -20,7 +20,7 @@ public: Account alice; Account bob; Account carol; - IOU usd; + IOU USD; uint256 domainID; std::string credType; diff --git a/src/test/jtx/sig.h b/src/test/jtx/sig.h index e88785ef15..374f106684 100644 --- a/src/test/jtx/sig.h +++ b/src/test/jtx/sig.h @@ -26,7 +26,7 @@ private: std::optional account_; /// Used solely as a convenience placeholder for ctors that do _not_ specify /// a subfield. - static constexpr SField const* kTopLevel = nullptr; + static constexpr SField* const kTOP_LEVEL = nullptr; public: explicit Sig(AutofillT) : manual_(false) @@ -46,7 +46,7 @@ public: { } - explicit Sig(Account const& account) : Sig(kTopLevel, account) + explicit Sig(Account const& account) : Sig(kTOP_LEVEL, account) { } diff --git a/src/test/jtx/tags.h b/src/test/jtx/tags.h index 4f4afbd1fa..66cf3b6ef7 100644 --- a/src/test/jtx/tags.h +++ b/src/test/jtx/tags.h @@ -6,19 +6,19 @@ struct NoneT { NoneT() = default; }; -static NoneT const kNone; +static NoneT const kNONE; struct AutofillT { AutofillT() = default; }; -static AutofillT const kAutofill; +static AutofillT const kAUTOFILL; struct DisabledT { DisabledT() = default; }; -static DisabledT const kDisabled; +static DisabledT const kDISABLED; /** Used for Fee() calls that use an owner reserve increment */ struct IncrementT @@ -26,6 +26,6 @@ struct IncrementT IncrementT() = default; }; -static IncrementT const kIncrement; +static IncrementT const kINCREMENT; } // namespace xrpl::test::jtx diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index e4c012510d..d33b3bf4ac 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -12,8 +12,8 @@ namespace xrpl::test::jtx { using JValueVec = std::vector; -constexpr std::size_t kUtXchainDefaultNumSigners = 5; -constexpr std::size_t kUtXchainDefaultQuorum = 4; +constexpr std::size_t kUT_XCHAIN_DEFAULT_NUM_SIGNERS = 5; +constexpr std::size_t kUT_XCHAIN_DEFAULT_QUORUM = 4; json::Value bridge( @@ -110,7 +110,7 @@ claimAttestations( std::uint64_t claimID, std::optional const& dst, std::vector const& signers, - std::size_t const numAtts = kUtXchainDefaultQuorum, + std::size_t const numAtts = kUT_XCHAIN_DEFAULT_QUORUM, std::size_t const fromIdx = 0); JValueVec @@ -125,7 +125,7 @@ createAccountAttestations( std::uint64_t createCount, jtx::Account const& dst, std::vector const& signers, - std::size_t const numAtts = kUtXchainDefaultQuorum, + std::size_t const numAtts = kUT_XCHAIN_DEFAULT_QUORUM, std::size_t const fromIdx = 0); struct XChainBridgeObjects @@ -165,23 +165,23 @@ struct XChainBridgeObjects FeatureBitset const features; std::vector const signers; - std::vector const altSigners; + std::vector const alt_signers; std::vector const payee; std::vector const payees; - std::uint32_t const quorum{kUtXchainDefaultQuorum}; + std::uint32_t const quorum{kUT_XCHAIN_DEFAULT_QUORUM}; - STAmount const reward; // 1 xrp - STAmount const splitRewardQuorum; // 250,000 drops - STAmount const splitRewardEveryone; // 200,000 drops + STAmount const reward; // 1 xrp + STAmount const split_reward_quorum; // 250,000 drops + STAmount const split_reward_everyone; // 200,000 drops - STAmount const tinyReward; // 37 drops - STAmount const tinyRewardSplit; // 9 drops - STAmount const tinyRewardRemainder; // 1 drops + STAmount const tiny_reward; // 37 drops + STAmount const tiny_reward_split; // 9 drops + STAmount const tiny_reward_remainder; // 1 drops - STAmount const oneXrp; - STAmount const xrpDust; + STAmount const one_xrp; + STAmount const xrp_dust; - static constexpr int kDropPerXrp = 1000000; + static constexpr int kDROP_PER_XRP = 1000000; XChainBridgeObjects(); @@ -220,12 +220,12 @@ struct XChainBridgeObjects [[nodiscard]] json::Value createBridge( Account const& acc, - json::Value const& bridge = json::ValueType::Null, + json::Value const& bridge = json::NullValue, STAmount const& reward = XRP(1), std::optional const& minAccountCreate = std::nullopt) const { return bridgeCreate( - acc, bridge == json::ValueType::Null ? jvb : bridge, reward, minAccountCreate); + acc, bridge == json::NullValue ? jvb : bridge, reward, minAccountCreate); } }; diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index a207b83f30..4f3c94f695 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -137,8 +137,8 @@ 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 * kDirNodeMaxEntries); - std::uint32_t const maxSeq = minSeq + kDirNodeMaxEntries; + std::uint32_t const minSeq = firstOfferSeq + (page * kDIR_NODE_MAX_ENTRIES); + std::uint32_t const maxSeq = minSeq + kDIR_NODE_MAX_ENTRIES; for (auto const& e : v) { @@ -189,14 +189,14 @@ struct Directory_test : public beast::unit_test::Suite env.close(); BEAST_EXPECT(!dirIsEmpty(*env.closed(), keylet::ownerDir(alice))); - env(signers(alice, jtx::kNone)); + env(signers(alice, jtx::kNONE)); env.close(); BEAST_EXPECT(dirIsEmpty(*env.closed(), keylet::ownerDir(alice))); std::vector const currencies = [this, &gw]() { std::vector c; - c.reserve((2 * kDirNodeMaxEntries) + 3); + c.reserve((2 * kDIR_NODE_MAX_ENTRIES) + 3); while (c.size() != c.capacity()) c.push_back(gw[currcode(c.size())]); @@ -295,7 +295,7 @@ struct Directory_test : public beast::unit_test::Suite // Fill up three pages of offers for (int i = 0; i < 3; ++i) { - for (int j = 0; j < kDirNodeMaxEntries; ++j) + for (int j = 0; j < kDIR_NODE_MAX_ENTRIES; ++j) env(offer(alice, XRP(1), usd(1))); } env.close(); @@ -303,9 +303,9 @@ struct Directory_test : public beast::unit_test::Suite // remove all the offers. Remove the middle page last for (auto page : {0, 2, 1}) { - for (int i = 0; i < kDirNodeMaxEntries; ++i) + for (int i = 0; i < kDIR_NODE_MAX_ENTRIES; ++i) { - env(offerCancel(alice, firstOfferSeq + (page * kDirNodeMaxEntries) + i)); + env(offerCancel(alice, firstOfferSeq + (page * kDIR_NODE_MAX_ENTRIES) + i)); env.close(); } } @@ -346,54 +346,54 @@ struct Directory_test : public beast::unit_test::Suite env.fund(XRP(10000), alice); env.close(); - constexpr uint256 kBase("fb71c9aa3310141da4b01d6c744a98286af2d72ab5448d5adc0910ca0c910880"); + constexpr uint256 kBASE("fb71c9aa3310141da4b01d6c744a98286af2d72ab5448d5adc0910ca0c910880"); - constexpr uint256 kItem("bad0f021aa3b2f6754a8fe82a5779730aa0bbbab82f17201ef24900efc2c7312"); + constexpr uint256 kITEM("bad0f021aa3b2f6754a8fe82a5779730aa0bbbab82f17201ef24900efc2c7312"); { // Create a chain of three pages: Sandbox sb(env.closed().get(), TapNone); - makePages(sb, kBase, 3); + makePages(sb, kBASE, 3); // Insert an item in the middle page: { - auto p = sb.peek(keylet::page(kBase, 1)); + auto p = sb.peek(keylet::page(kBASE, 1)); BEAST_EXPECT(p); STVector256 v; - v.pushBack(kItem); + v.pushBack(kITEM); p->setFieldV256(sfIndexes, v); sb.update(p); } // Now, try to delete the item from the middle // page. This should cause all pages to be deleted: - BEAST_EXPECT(sb.dirRemove(keylet::page(kBase, 0), 1, keylet::unchecked(kItem), false)); - BEAST_EXPECT(!sb.peek(keylet::page(kBase, 2))); - BEAST_EXPECT(!sb.peek(keylet::page(kBase, 1))); - BEAST_EXPECT(!sb.peek(keylet::page(kBase, 0))); + BEAST_EXPECT(sb.dirRemove(keylet::page(kBASE, 0), 1, keylet::unchecked(kITEM), false)); + BEAST_EXPECT(!sb.peek(keylet::page(kBASE, 2))); + BEAST_EXPECT(!sb.peek(keylet::page(kBASE, 1))); + BEAST_EXPECT(!sb.peek(keylet::page(kBASE, 0))); } { // Create a chain of four pages: Sandbox sb(env.closed().get(), TapNone); - makePages(sb, kBase, 4); + makePages(sb, kBASE, 4); // Now add items on pages 1 and 2: { - auto p1 = sb.peek(keylet::page(kBase, 1)); + auto p1 = sb.peek(keylet::page(kBASE, 1)); BEAST_EXPECT(p1); STVector256 v1; - v1.pushBack(~kItem); + v1.pushBack(~kITEM); p1->setFieldV256(sfIndexes, v1); sb.update(p1); - auto p2 = sb.peek(keylet::page(kBase, 2)); + auto p2 = sb.peek(keylet::page(kBASE, 2)); BEAST_EXPECT(p2); STVector256 v2; - v2.pushBack(kItem); + v2.pushBack(kITEM); p2->setFieldV256(sfIndexes, v2); sb.update(p2); } @@ -401,16 +401,16 @@ 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(kBase, 0), 2, keylet::unchecked(kItem), false)); - BEAST_EXPECT(!sb.peek(keylet::page(kBase, 3))); - BEAST_EXPECT(!sb.peek(keylet::page(kBase, 2))); + BEAST_EXPECT(sb.dirRemove(keylet::page(kBASE, 0), 2, keylet::unchecked(kITEM), false)); + BEAST_EXPECT(!sb.peek(keylet::page(kBASE, 3))); + BEAST_EXPECT(!sb.peek(keylet::page(kBASE, 2))); - auto p1 = sb.peek(keylet::page(kBase, 1)); + auto p1 = sb.peek(keylet::page(kBASE, 1)); BEAST_EXPECT(p1); BEAST_EXPECT(p1->getFieldU64(sfIndexNext) == 0); BEAST_EXPECT(p1->getFieldU64(sfIndexPrevious) == 0); - auto p0 = sb.peek(keylet::page(kBase, 0)); + auto p0 = sb.peek(keylet::page(kBASE, 0)); BEAST_EXPECT(p0); BEAST_EXPECT(p0->getFieldU64(sfIndexNext) == 1); BEAST_EXPECT(p0->getFieldU64(sfIndexPrevious) == 1); @@ -569,13 +569,13 @@ struct Directory_test : public beast::unit_test::Suite testableAmendments() - fixDirectoryLimit, [this](Env&) -> std::tuple { testcase("directory full without fixDirectoryLimit"); - return {kDirNodeMaxPages - 1, true}; + return {kDIR_NODE_MAX_PAGES - 1, true}; }); testCase( testableAmendments(), // [this](Env&) -> std::tuple { testcase("directory not full with fixDirectoryLimit"); - return {kDirNodeMaxPages - 1, false}; + return {kDIR_NODE_MAX_PAGES - 1, false}; }); testCase( testableAmendments(), // diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index f59b75091a..a100b4a51d 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -87,7 +87,7 @@ class PaymentSandbox_test : public beast::unit_test::Suite PathSet const paths(TestPath(gw1, usdGw2, gw2), TestPath(gw2, usdGw1, gw1)); - env(pay(snd, rcv, kAny(usdGw1(4))), + env(pay(snd, rcv, kANY(usdGw1(4))), Json(paths.json()), Txflags(tfNoRippleDirect | tfPartialPayment)); @@ -307,9 +307,9 @@ class PaymentSandbox_test : public beast::unit_test::Suite auto const issue = usd; STAmount const tinyAmt( - issue, STAmount::kMinValue, STAmount::kMinOffset + 1, false, STAmount::Unchecked{}); + issue, STAmount::kMIN_VALUE, STAmount::kMIN_OFFSET + 1, false, STAmount::Unchecked{}); STAmount const hugeAmt( - issue, STAmount::kMaxValue, STAmount::kMaxOffset - 1, false, STAmount::Unchecked{}); + issue, STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET - 1, false, STAmount::Unchecked{}); ApplyViewImpl av(&*env.current(), TapNone); PaymentSandbox pv(&av); @@ -354,7 +354,7 @@ class PaymentSandbox_test : public beast::unit_test::Suite auto r = accountSend(sb, alice, xrpAccount(), XRP(100), env.journal); BEAST_EXPECT(isTesSuccess(r)); } - BEAST_EXPECT(accountFundsXRP(sb, alice, env.journal) == beast::kZero); + BEAST_EXPECT(accountFundsXRP(sb, alice, env.journal) == beast::kZERO); } } diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index fd3cc2f214..dd4ebd27fd 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -23,9 +23,9 @@ class SkipList_test : public beast::unit_test::Suite { Config const config; auto prev = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index b62061d38d..2cf6517c8a 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -61,7 +61,7 @@ class View_test : public beast::unit_test::Suite } // Create SLE with key and payload - static SLE::pointer + static std::shared_ptr sle(std::uint64_t id, std::uint32_t seq = 1) { auto const le = std::make_shared(k(id)); @@ -79,7 +79,7 @@ class View_test : public beast::unit_test::Suite // Set payload on SLE static void - seq(SLE::ref le, std::uint32_t seq) + seq(std::shared_ptr const& le, std::uint32_t seq) { le->setFieldU32(sfSequence, seq); } @@ -151,9 +151,9 @@ class View_test : public beast::unit_test::Suite Env env(*this); Config const config; std::shared_ptr const genesis = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -419,9 +419,9 @@ class View_test : public beast::unit_test::Suite Env env(*this); Config const config; std::shared_ptr const genesis = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -628,9 +628,9 @@ class View_test : public beast::unit_test::Suite Env env(*this); Config const config; std::shared_ptr const genesis = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -935,7 +935,7 @@ class View_test : public beast::unit_test::Suite auto rdView = env.closed(); // Test with no rate set on gw1. - BEAST_EXPECT(transferRate(*rdView, gw1) == kParityRate); + BEAST_EXPECT(transferRate(*rdView, gw1) == kPARITY_RATE); env(rate(gw1, 1.02)); env.close(); @@ -958,7 +958,7 @@ class View_test : public beast::unit_test::Suite auto const bob = Account("bob"); // The first Env. - Env eA(*this, envconfig(), nullptr, beast::Severity::Disabled); + Env eA(*this, envconfig(), nullptr, beast::severities::KDisabled); eA.fund(XRP(10000), alice); eA.close(); @@ -970,7 +970,7 @@ class View_test : public beast::unit_test::Suite // The two Env's can't share the same ports, so modify the config // of the second Env to use higher port numbers - Env eB{*this, envconfig(), nullptr, beast::Severity::Disabled}; + Env eB{*this, envconfig(), nullptr, beast::severities::KDisabled}; // Make ledgers that are incompatible with the first ledgers. Note // that bob is funded before alice. @@ -1018,9 +1018,9 @@ class View_test : public beast::unit_test::Suite Env env(*this); Config const config; std::shared_ptr const genesis = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config.features}, - config.fees.toFees(), + config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = diff --git a/src/test/nodestore/Backend_test.cpp b/src/test/nodestore/Backend_test.cpp index 32b7d46868..110d142f57 100644 --- a/src/test/nodestore/Backend_test.cpp +++ b/src/test/nodestore/Backend_test.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include #include #include @@ -41,7 +40,7 @@ public: // Create a batch auto batch = createPredictableBatch(numObjsToTest, rng()); - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("Backend_test", *this); { diff --git a/src/test/nodestore/Basics_test.cpp b/src/test/nodestore/Basics_test.cpp index 5565399cc2..d0445cc1ab 100644 --- a/src/test/nodestore/Basics_test.cpp +++ b/src/test/nodestore/Basics_test.cpp @@ -21,13 +21,13 @@ public: { testcase("batch"); - auto batch1 = createPredictableBatch(kNumObjectsToTest, seedValue); + auto batch1 = createPredictableBatch(kNUM_OBJECTS_TO_TEST, seedValue); - auto batch2 = createPredictableBatch(kNumObjectsToTest, seedValue); + auto batch2 = createPredictableBatch(kNUM_OBJECTS_TO_TEST, seedValue); BEAST_EXPECT(areBatchesEqual(batch1, batch2)); - auto batch3 = createPredictableBatch(kNumObjectsToTest, seedValue + 1); + auto batch3 = createPredictableBatch(kNUM_OBJECTS_TO_TEST, seedValue + 1); BEAST_EXPECT(!areBatchesEqual(batch1, batch3)); } @@ -38,7 +38,7 @@ public: { testcase("encoding"); - auto batch = createPredictableBatch(kNumObjectsToTest, seedValue); + auto batch = createPredictableBatch(kNUM_OBJECTS_TO_TEST, seedValue); for (int i = 0; i < batch.size(); ++i) { diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index 50bdfefd4c..a152bb3a2d 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -74,13 +74,13 @@ public: auto& section = p->section("sqlite"); section.set("safety_level", "high"); } - p->ledgerHistory = 100'000'000; + p->LEDGER_HISTORY = 100'000'000; return Env( *this, std::move(p), std::make_unique(integrityWarning, &found), - beast::Severity::Warning); + beast::severities::KWarning); }(); BEAST_EXPECT(!found); @@ -103,13 +103,13 @@ public: auto& section = p->section("sqlite"); section.set("safety_level", "low"); } - p->ledgerHistory = 100'000'000; + p->LEDGER_HISTORY = 100'000'000; return Env( *this, std::move(p), std::make_unique(integrityWarning, &found), - beast::Severity::Warning); + beast::severities::KWarning); }(); BEAST_EXPECT(found); @@ -139,7 +139,7 @@ public: *this, std::move(p), std::make_unique(integrityWarning, &found), - beast::Severity::Warning); + beast::severities::KWarning); }(); // No warning, even though higher risk settings were used because @@ -166,13 +166,13 @@ public: section.set("synchronous", "extra"); section.set("temp_store", "default"); } - p->ledgerHistory = 50'000'000; + p->LEDGER_HISTORY = 50'000'000; return Env( *this, std::move(p), std::make_unique(integrityWarning, &found), - beast::Severity::Warning); + beast::severities::KWarning); }(); // No warning, even though higher risk settings were used because @@ -210,7 +210,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -239,7 +239,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -268,7 +268,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -297,7 +297,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -325,7 +325,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -353,7 +353,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -381,7 +381,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -409,7 +409,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -464,7 +464,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -487,7 +487,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -510,7 +510,7 @@ public: *this, std::move(p), std::make_unique(expected, &found), - beast::Severity::Warning); + beast::severities::KWarning); fail(); } catch (...) @@ -536,7 +536,7 @@ public: srcParams.set("path", nodeDb.path()); // Create a batch - auto batch = createPredictableBatch(kNumObjectsToTest, seedValue); + auto batch = createPredictableBatch(kNUM_OBJECTS_TO_TEST, seedValue); // Write to source db { @@ -647,7 +647,7 @@ public: { std::unique_ptr db = Manager::instance().makeDatabase( megabytes(4), scheduler, 2, nodeParams, journal_); - BEAST_EXPECT(db->earliestLedgerSeq() == kXrpLedgerEarliestSeq); + BEAST_EXPECT(db->earliestLedgerSeq() == kXRP_LEDGER_EARLIEST_SEQ); } // Set an invalid earliest ledger sequence @@ -676,7 +676,7 @@ public: try { // Set to default earliest ledger sequence - nodeParams.set("earliest_seq", std::to_string(kXrpLedgerEarliestSeq)); + nodeParams.set("earliest_seq", std::to_string(kXRP_LEDGER_EARLIEST_SEQ)); std::unique_ptr const db2 = Manager::instance().makeDatabase( megabytes(4), scheduler, 2, nodeParams, journal_); } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index fae13b9cc8..2c817c0d6c 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -78,7 +78,10 @@ private: // Helper function to test log messages void - testLogMessage(Section const& params, beast::Severity level, std::string const& expectedMessage) + testLogMessage( + Section const& params, + beast::severities::Severity level, + std::string const& expectedMessage) { test::StreamSink sink(level); beast::Journal const journal(sink); @@ -97,7 +100,7 @@ private: beast::TempDir const tempDir; auto params = createSection(tempDir.path(), size); - test::StreamSink sink(beast::Severity::Warning); + test::StreamSink sink(beast::severities::KWarning); beast::Journal const journal(sink); DummyScheduler scheduler; @@ -199,7 +202,7 @@ public: beast::TempDir const tempDir; auto params = createSection(tempDir.path(), "8192"); - testLogMessage(params, beast::Severity::Info, "Using custom NuDB block size: 8192"); + testLogMessage(params, beast::severities::KInfo, "Using custom NuDB block size: 8192"); } // Test invalid block size failure @@ -207,7 +210,7 @@ public: beast::TempDir const tempDir; auto params = createSection(tempDir.path(), "5000"); - test::StreamSink sink(beast::Severity::Warning); + test::StreamSink sink(beast::severities::KWarning); beast::Journal const journal(sink); DummyScheduler scheduler; @@ -232,7 +235,7 @@ public: beast::TempDir const tempDir; auto params = createSection(tempDir.path(), "invalid"); - test::StreamSink sink(beast::Severity::Warning); + test::StreamSink sink(beast::severities::KWarning); beast::Journal const journal(sink); DummyScheduler scheduler; @@ -277,7 +280,7 @@ public: // We test the validation logic by catching exceptions for invalid // values - test::StreamSink sink(beast::Severity::Warning); + test::StreamSink sink(beast::severities::KWarning); beast::Journal const journal(sink); DummyScheduler scheduler; @@ -345,7 +348,7 @@ public: beast::TempDir const tempDir; auto params = createSection(tempDir.path(), format); - test::StreamSink sink(beast::Severity::Info); + test::StreamSink sink(beast::severities::KInfo); beast::Journal const journal(sink); DummyScheduler scheduler; @@ -367,7 +370,7 @@ public: auto params = createSection(tempDir.path(), format); // Use a lower threshold to capture both info and warning messages - test::StreamSink sink(beast::Severity::Debug); + test::StreamSink sink(beast::severities::KDebug); beast::Journal const journal(sink); DummyScheduler scheduler; diff --git a/src/test/nodestore/TestBase.h b/src/test/nodestore/TestBase.h index c35042bd4f..7cde0266ab 100644 --- a/src/test/nodestore/TestBase.h +++ b/src/test/nodestore/TestBase.h @@ -47,9 +47,9 @@ class TestBase : public beast::unit_test::Suite public: // Tunable parameters // - static std::size_t const kMinPayloadBytes = 1; - static std::size_t const kMaxPayloadBytes = 2000; - static int const kNumObjectsToTest = 2000; + static std::size_t const kMIN_PAYLOAD_BYTES = 1; + static std::size_t const kMAX_PAYLOAD_BYTES = 2000; + static int const kNUM_OBJECTS_TO_TEST = 2000; public: // Create a predictable batch of objects @@ -83,7 +83,7 @@ public: uint256 hash; beast::rngfill(hash.begin(), hash.size(), rng); - Blob blob(randInt(rng, kMinPayloadBytes, kMaxPayloadBytes)); + Blob blob(randInt(rng, kMIN_PAYLOAD_BYTES, kMAX_PAYLOAD_BYTES)); beast::rngfill(blob.data(), blob.size(), rng); batch.push_back(NodeObject::createObject(type, std::move(blob), hash)); diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index 67feace198..dfc1a0235d 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -77,23 +77,22 @@ rngcpy(void* buffer, std::size_t bytes, Generator& g) class Sequence { private: - static constexpr auto kMinLedger = 1; - static constexpr auto kMaxLedger = 1000000; - static constexpr auto kMinSize = 250; - static constexpr auto kMaxSize = 1250; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { MinLedger = 1, MaxLedger = 1000000, MinSize = 250, MaxSize = 1250 }; beast::xor_shift_engine gen_; std::uint8_t prefix_; - std::discrete_distribution dType_; - std::uniform_int_distribution dSize_; + std::discrete_distribution d_type_; + std::uniform_int_distribution d_size_; public: explicit Sequence(std::uint8_t prefix) : prefix_(prefix) // uniform distribution over hotLEDGER - hotTRANSACTION_NODE // but exclude hotTRANSACTION = 2 (removed) - , dType_({1, 1, 0, 1, 1}) - , dSize_(kMinSize, kMaxSize) + , d_type_({1, 1, 0, 1, 1}) + , d_size_(MinSize, MaxSize) { } @@ -116,10 +115,10 @@ public: auto const data = static_cast(&*key.begin()); *data = prefix_; rngcpy(data + 1, key.size() - 1, gen_); - Blob value(dSize_(gen_)); + Blob value(d_size_(gen_)); rngcpy(&value[0], value.size(), gen_); return NodeObject::createObject( - safeCast(dType_(gen_)), std::move(value), key); + safeCast(d_type_(gen_)), std::move(value), key); } // returns a batch of NodeObjects starting at n @@ -138,13 +137,18 @@ public: class Timing_test : public beast::unit_test::Suite { public: - static constexpr auto kMissingNodePercent = 20; // percent of fetches for missing nodes + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + // percent of fetches for missing nodes + MissingNodePercent = 20 + }; - std::size_t const defaultRepeat = 3; + std::size_t const default_repeat = 3; #ifndef NDEBUG - std::size_t const defaultItems = 10000; + std::size_t const default_items = 10000; #else - std::size_t const defaultItems = 100000; // release + std::size_t const default_items = 100000; // release #endif using clock_type = std::chrono::steady_clock; @@ -462,7 +466,7 @@ public: { try { - if (rand_(gen_) < kMissingNodePercent) + if (rand_(gen_) < MissingNodePercent) { auto const hash = seq2_.key(dist_(gen_)); std::shared_ptr result; @@ -639,7 +643,7 @@ public: { w = std::max::size_type>(w, test.first.size()); } - log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << defaultItems + log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items << " Objects" << std::endl; { std::stringstream ss; @@ -649,15 +653,15 @@ public: log << ss.str() << std::endl; } - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("Timing_test", *this); for (auto const& configString : configStrings) { Params params{}; - params.items = defaultItems; + params.items = default_items; params.threads = threads; - for (auto i = defaultRepeat; (i--) != 0u;) + for (auto i = default_repeat; (i--) != 0u;) { beast::TempDir const tempDir; Section config = parse(configString); diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index a80b5ccc93..0ef7b2314f 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -253,7 +253,7 @@ std::map parseArgs(std::string const& s) { // '=' - static boost::regex const kRe1( + static boost::regex const kRE1( "^" // start of line "(?:\\s*)" // whitespace (optional) "([a-zA-Z][_a-zA-Z0-9]*)" // @@ -269,7 +269,7 @@ parseArgs(std::string const& s) for (auto const& kv : v) { boost::smatch m; - if (!boost::regex_match(kv, m, kRe1)) + if (!boost::regex_match(kv, m, kRE1)) Throw("invalid parameter " + kv); auto const result = map.emplace(m[1], m[2]); if (!result.second) diff --git a/src/test/nodestore/varint_test.cpp b/src/test/nodestore/varint_test.cpp index 68e88d831a..f45de568f3 100644 --- a/src/test/nodestore/varint_test.cpp +++ b/src/test/nodestore/varint_test.cpp @@ -17,7 +17,7 @@ public: testcase("encode, decode"); for (auto const v : vv) { - std::array::kMax> vi{}; + std::array::kMAX> vi{}; auto const n0 = writeVarint(vi.data(), v); expect(n0 > 0, "write error"); expect(n0 == sizeVarint(v), "size error"); diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index 961e1b7eb4..fa47f42740 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -213,7 +213,7 @@ class TMGetObjectByHash_test : public beast::unit_test::Suite void run() override { - int const limit = static_cast(Tuning::kHardMaxReplyNodes); + int const limit = static_cast(Tuning::HardMaxReplyNodes); testReplyLimit(limit + 1, limit); testReplyLimit(limit, limit); testReplyLimit(limit - 1, limit - 1); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index 60cc69a14f..0e75b26d51 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -112,23 +112,23 @@ public: return; std::vector decompressed; - decompressed.resize(header->uncompressedSize); + decompressed.resize(header->uncompressed_size); - BEAST_EXPECT(header->payloadWireSize == buffer.size() - header->headerSize); + BEAST_EXPECT(header->payload_wire_size == buffer.size() - header->header_size); ZeroCopyInputStream stream(buffers.data()); - stream.Skip(header->headerSize); + stream.Skip(header->header_size); auto decompressedSize = xrpl::compression::decompress( - stream, header->payloadWireSize, decompressed.data(), header->uncompressedSize); - BEAST_EXPECT(decompressedSize == header->uncompressedSize); + 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)); auto uncompressed = m.getBuffer(Compressed::Off); BEAST_EXPECT( std::equal( - uncompressed.begin() + xrpl::compression::kHeaderBytes, + uncompressed.begin() + xrpl::compression::kHEADER_BYTES, uncompressed.end(), decompressed.begin())); } @@ -142,7 +142,7 @@ public: { auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = i; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); @@ -299,7 +299,7 @@ public: auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 0; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); @@ -326,7 +326,7 @@ public: auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfSequence] = 0; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); @@ -350,7 +350,7 @@ public: void testProtocol() { - auto thresh = beast::Severity::Info; + auto thresh = beast::severities::Severity::KInfo; auto logs = std::make_unique(thresh); protocol::TMManifests const manifests; @@ -408,8 +408,9 @@ public: << enable << "\n"; c.loadFromString(str.str()); auto env = std::make_shared(*this); - env->app().config().compression = c.compression; - env->app().config().vpReduceRelayBaseSquelchEnable = c.vpReduceRelayBaseSquelchEnable; + env->app().config().COMPRESSION = c.COMPRESSION; + env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = + c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; return env; }; auto handshake = [&](int outboundEnable, int inboundEnable) { @@ -418,10 +419,10 @@ public: auto env = getEnv(outboundEnable); auto request = xrpl::makeRequest( true, - env->app().config().compression, + env->app().config().COMPRESSION, false, - env->app().config().txReduceRelayEnable, - env->app().config().vpReduceRelayBaseSquelchEnable); + env->app().config().TX_REDUCE_RELAY_ENABLE, + env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); http_request_type httpRequest; httpRequest.version(request.version()); httpRequest.base() = request.base(); @@ -431,7 +432,7 @@ public: // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled auto const inboundEnabled = - peerFeatureEnabled(httpRequest, kFeatureCompr, "lz4", inboundEnable); + peerFeatureEnabled(httpRequest, kFEATURE_COMPR, "lz4", inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); env.reset(); @@ -441,7 +442,7 @@ public: // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled auto const outboundEnabled = - peerFeatureEnabled(httpResp, kFeatureCompr, "lz4", outboundEnable); + peerFeatureEnabled(httpResp, kFEATURE_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 54d8f555a2..842e739fa6 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -60,9 +60,9 @@ using SquelchCB = std::function; using LinkIterCB = std::function; -static constexpr std::uint32_t kMaxPeers = 10; -static constexpr std::uint32_t kMaxValidators = 10; -static constexpr std::uint32_t kMaxMessages = 200000; +static constexpr std::uint32_t kMAX_PEERS = 10; +static constexpr std::uint32_t kMAX_VALIDATORS = 10; +static constexpr std::uint32_t kMAX_MESSAGES = 200000; /** Simulate two entities - peer directly connected to the server * (via squelch in PeerSim) and PeerImp (via Overlay) @@ -142,8 +142,8 @@ public: [[nodiscard]] uint256 const& getClosedLedgerHash() const override { - static uint256 const kHash{}; - return kHash; + static uint256 const kHASH{}; + return kHASH; } [[nodiscard]] bool hasLedger(uint256 const& hash, std::uint32_t seq) const override @@ -205,25 +205,25 @@ public: static void advance(duration d) noexcept { - kNow += d; + kNOW += d; } static void randAdvance(milliseconds min, milliseconds max) { - kNow += randDuration(min, max); + kNOW += randDuration(min, max); } static void reset() noexcept { - kNow = time_point(seconds(0)); + kNOW = time_point(seconds(0)); } static time_point now() noexcept { - return kNow; + return kNOW; } static duration @@ -235,7 +235,7 @@ public: explicit ManualClock() = default; private: - inline static time_point kNow = time_point(seconds(0)); + inline static time_point kNOW = time_point(seconds(0)); }; /** Simulate server's OverlayImpl */ @@ -704,8 +704,8 @@ public: void init() { - validators_.resize(kMaxValidators); - for (int p = 0; p < kMaxPeers; p++) + validators_.resize(kMAX_VALIDATORS); + for (int p = 0; p < kMAX_PEERS; p++) { auto peer = overlay_.addPeer(); for (auto& v : validators_) @@ -749,7 +749,7 @@ public: void purgePeers() { - while (overlay_.getNumPeers() > kMaxPeers) + while (overlay_.getNumPeers() > kMAX_PEERS) deleteLastPeer(); } @@ -817,8 +817,8 @@ public: void propagate( LinkIterCB link, - std::uint16_t nValidators = kMaxValidators, - std::uint32_t nMessages = kMaxMessages, + std::uint16_t nValidators = kMAX_VALIDATORS, + std::uint32_t nMessages = kMAX_MESSAGES, bool purge = true, bool resetClock = true) { @@ -973,7 +973,8 @@ protected: auto countingState = network_.overlay().isCountingState(validator); BEAST_EXPECT( countingState == false && - selected.size() == env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); + selected.size() == + env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); } // Trigger Link Down or Peer Disconnect event @@ -1050,7 +1051,7 @@ protected: auto d = reduce_relay::epoch(now).count() - std::get<3>(peers[event.peer]); mustHandle = event.isSelected && - d > milliseconds(reduce_relay::kIdled).count() && + d > milliseconds(reduce_relay::kIDLED).count() && network_.overlay().inState(*event.key, reduce_relay::PeerState::Squelched) > 0 && peers.contains(event.peer); @@ -1069,7 +1070,7 @@ protected: } if (event.state == State::WaitReset || (event.state == State::On && - (now - event.time > (reduce_relay::kIdled + seconds(2))))) + (now - event.time > (reduce_relay::kIDLED + seconds(2))))) { bool const handled = event.state == State::WaitReset || !event.handled; BEAST_EXPECT(handled); @@ -1162,16 +1163,18 @@ protected: { BEAST_EXPECT( squelched == - kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); + kMAX_PEERS - + env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); n++; } }, 1, - reduce_relay::kMaxMessageThreshold + 2, + reduce_relay::kMAX_MESSAGE_THRESHOLD + 2, purge, resetClock); auto selected = network_.overlay().getSelected(network_.validator(0)); - BEAST_EXPECT(selected.size() == env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); + 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); @@ -1232,7 +1235,7 @@ protected: id, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); BEAST_EXPECT( unsquelched == - kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); + kMAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1245,14 +1248,14 @@ protected: doTest("Selected Peer Stops Relaying", log, [this](bool log) { ManualClock::advance(seconds(601)); BEAST_EXPECT(propagateAndSquelch(log, true, false)); - ManualClock::advance(reduce_relay::kIdled + seconds(1)); + ManualClock::advance(reduce_relay::kIDLED + seconds(1)); std::uint16_t unsquelched = 0; network_.overlay().deleteIdlePeers( [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); auto peers = network_.overlay().getPeers(network_.validator(0)); BEAST_EXPECT( unsquelched == - kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); + kMAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1291,7 +1294,7 @@ vp_enable=1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == true); + BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == true); }); doTest("Test Config - squelch disabled (legacy)", log, [&](bool log) { @@ -1303,7 +1306,7 @@ vp_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == false); + BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); Config c1; @@ -1312,7 +1315,7 @@ vp_enable=0 )xrpldConfig"; c1.loadFromString(toLoad); - BEAST_EXPECT(c1.vpReduceRelayBaseSquelchEnable == false); + BEAST_EXPECT(c1.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); }); doTest("Test Config - squelch enabled", log, [&](bool log) { @@ -1324,7 +1327,7 @@ vp_base_squelch_enable=1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == true); + BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == true); }); doTest("Test Config - squelch disabled", log, [&](bool log) { @@ -1336,7 +1339,7 @@ vp_base_squelch_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == false); + BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); }); doTest("Test Config - legacy and new", log, [&](bool log) { @@ -1376,7 +1379,7 @@ vp_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.vpReduceRelaySquelchMaxSelectedPeers == 5); + BEAST_EXPECT(c.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS == 5); Config c1; @@ -1386,7 +1389,7 @@ vp_base_squelch_max_selected_peers=6 )xrpldConfig"; c1.loadFromString(toLoad); - BEAST_EXPECT(c1.vpReduceRelaySquelchMaxSelectedPeers == 6); + BEAST_EXPECT(c1.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS == 6); Config c2; @@ -1419,7 +1422,7 @@ vp_base_squelch_max_selected_peers=2 doTest("BaseSquelchReady", log, [&](bool log) { ManualClock::reset(); auto createSlots = [&](bool baseSquelchEnabled) -> reduce_relay::Slots { - env_.app().config().vpReduceRelayBaseSquelchEnable = baseSquelchEnabled; + env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = baseSquelchEnabled; return reduce_relay::Slots( env_.app(), network_.overlay(), env_.app().config()); }; @@ -1430,7 +1433,7 @@ vp_base_squelch_max_selected_peers=2 // bootup BEAST_EXPECT(!createSlots(true).baseSquelchReady()); - ManualClock::advance(reduce_relay::kWaitOnBootup + minutes{1}); + ManualClock::advance(reduce_relay::kWAIT_ON_BOOTUP + minutes{1}); // base squelch enabled and bootup time passed BEAST_EXPECT(createSlots(true).baseSquelchReady()); @@ -1467,7 +1470,7 @@ vp_base_squelch_max_selected_peers=2 peers = network_.overlay().getPeers(network_.validator(0)); BEAST_EXPECT(std::get<1>(peers[0]) == (nMessages - 1)); // advance the clock - ManualClock::advance(reduce_relay::kIdled + seconds(1)); + ManualClock::advance(reduce_relay::kIDLED + seconds(1)); network_.overlay().updateSlotAndSquelch( key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); peers = network_.overlay().getPeers(network_.validator(0)); @@ -1505,7 +1508,7 @@ vp_base_squelch_max_selected_peers=2 // 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::kMaxMessageThreshold + 2; m++) + for (int m = 1; m <= reduce_relay::kMAX_MESSAGE_THRESHOLD + 2; m++) { for (int peer = 0; peer < npeers; peer++) { @@ -1522,39 +1525,39 @@ vp_base_squelch_max_selected_peers=2 }; using namespace reduce_relay; - // expect max duration less than kMaxUnsquelchExpireDefault with + // expect max duration less than kMAX_UNSQUELCH_EXPIRE_DEFAULT with // less than or equal to 60 peers run(20); BEAST_EXPECT( - handler.maxDuration >= kMinUnsquelchExpire.count() && - handler.maxDuration <= kMaxUnsquelchExpireDefault.count()); + handler.maxDuration >= kMIN_UNSQUELCH_EXPIRE.count() && + handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_DEFAULT.count()); run(60); BEAST_EXPECT( - handler.maxDuration >= kMinUnsquelchExpire.count() && - handler.maxDuration <= kMaxUnsquelchExpireDefault.count()); - // expect max duration greater than kMinUnsquelchExpire and less - // than kMaxUnsquelchExpirePeers with peers greater than 60 + handler.maxDuration >= kMIN_UNSQUELCH_EXPIRE.count() && + handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_DEFAULT.count()); + // expect max duration greater than kMIN_UNSQUELCH_EXPIRE and less + // than kMAX_UNSQUELCH_EXPIRE_PEERS with peers greater than 60 // and less than 360 run(350); // can't make this condition stronger. squelch // duration is probabilistic and max condition may still fail. // log when the value is low BEAST_EXPECT( - handler.maxDuration >= kMinUnsquelchExpire.count() && - handler.maxDuration <= kMaxUnsquelchExpirePeers.count()); + handler.maxDuration >= kMIN_UNSQUELCH_EXPIRE.count() && + handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_PEERS.count()); using namespace beast::unit_test::detail; - if (handler.maxDuration <= kMaxUnsquelchExpireDefault.count()) + if (handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_DEFAULT.count()) { log << makeReason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; } - // more than 400 is still less than kMaxUnsquelchExpirePeers + // more than 400 is still less than kMAX_UNSQUELCH_EXPIRE_PEERS run(400); BEAST_EXPECT( - handler.maxDuration >= kMinUnsquelchExpire.count() && - handler.maxDuration <= kMaxUnsquelchExpirePeers.count()); - if (handler.maxDuration <= kMaxUnsquelchExpireDefault.count()) + handler.maxDuration >= kMIN_UNSQUELCH_EXPIRE.count() && + handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_PEERS.count()); + if (handler.maxDuration <= kMAX_UNSQUELCH_EXPIRE_DEFAULT.count()) { log << makeReason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl @@ -1575,10 +1578,10 @@ vp_base_squelch_max_selected_peers=2 << "[compression]\n" << "1\n"; c.loadFromString(str.str()); - env_.app().config().vpReduceRelayBaseSquelchEnable = - c.vpReduceRelayBaseSquelchEnable; + env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = + c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; - env_.app().config().compression = c.compression; + env_.app().config().COMPRESSION = c.COMPRESSION; }; auto handshake = [&](int outboundEnable, int inboundEnable) { beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); @@ -1586,10 +1589,10 @@ vp_base_squelch_max_selected_peers=2 setEnv(outboundEnable); auto request = xrpl::makeRequest( true, - env_.app().config().compression, + env_.app().config().COMPRESSION, false, - env_.app().config().txReduceRelayEnable, - env_.app().config().vpReduceRelayBaseSquelchEnable); + env_.app().config().TX_REDUCE_RELAY_ENABLE, + env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); http_request_type httpRequest; httpRequest.version(request.version()); httpRequest.base() = request.base(); @@ -1599,7 +1602,7 @@ vp_base_squelch_max_selected_peers=2 // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled auto const inboundEnabled = - peerFeatureEnabled(httpRequest, kFeatureVprr, inboundEnable); + peerFeatureEnabled(httpRequest, kFEATURE_VPRR, inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); setEnv(inboundEnable); @@ -1608,7 +1611,7 @@ vp_base_squelch_max_selected_peers=2 // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled auto const outboundEnabled = - peerFeatureEnabled(httpResp, kFeatureVprr, outboundEnable); + peerFeatureEnabled(httpResp, kFEATURE_VPRR, outboundEnable); BEAST_EXPECT(!(peerEnabled ^ outboundEnabled)); }; handshake(1, 1); @@ -1624,8 +1627,8 @@ vp_base_squelch_max_selected_peers=2 public: reduce_relay_test() : env_(*this, jtx::envconfig([](std::unique_ptr cfg) { - cfg->vpReduceRelayBaseSquelchEnable = true; - cfg->vpReduceRelaySquelchMaxSelectedPeers = 6; + cfg->VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = true; + cfg->VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = 6; return cfg; })) , network_(env_.app()) diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index 9af632d65c..1b608edee7 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -19,7 +19,7 @@ #include #include #include -#include // IWYU pragma: keep +#include #include #include @@ -62,7 +62,7 @@ private: using endpoint_type = boost::asio::ip::tcp::endpoint; using address_type = boost::asio::ip::address; - io_context_type ioContext_; + io_context_type io_context_; boost::optional> work_; std::thread thread_; std::shared_ptr context_; @@ -185,10 +185,10 @@ private: , server(server) , test(server.test_) , acceptor( - test.ioContext_, + test.io_context_, endpoint_type(boost::asio::ip::make_address(test::getEnvLocalhostAddr()), 0)) - , socket(test.ioContext_) - , strand(boost::asio::make_strand(test.ioContext_)) + , socket(test.io_context_) + , strand(boost::asio::make_strand(test.io_context_)) { acceptor.listen(); server.endpoint_ = acceptor.local_endpoint(); @@ -261,8 +261,8 @@ private: , test(server.test_) , socket(std::move(inSocket)) , stream(socket, *test.context_) - , strand(boost::asio::make_strand(test.ioContext_)) - , timer(test.ioContext_) + , strand(boost::asio::make_strand(test.io_context_)) + , timer(test.io_context_) { } @@ -450,10 +450,10 @@ private: : Child(client) , client(client) , test(client.test_) - , socket(test.ioContext_) + , socket(test.io_context_) , stream(socket, *test.context_) - , strand(boost::asio::make_strand(test.ioContext_)) - , timer(test.ioContext_) + , strand(boost::asio::make_strand(test.io_context_)) + , timer(test.io_context_) , ep(ep) { } @@ -632,10 +632,10 @@ private: public: short_read_test() - : work_(ioContext_.get_executor()) + : work_(io_context_.get_executor()) , thread_(std::thread([this]() { beast::setCurrentThreadName("io_context"); - this->ioContext_.run(); + this->io_context_.run(); })) , context_(makeSslContext("")) { diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index a0d91d3aed..e053774108 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -81,10 +81,10 @@ private: { c.loadFromString(str.str()); - BEAST_EXPECT(c.txReduceRelayEnable == enable); - BEAST_EXPECT(c.txReduceRelayMetrics == metrics); - BEAST_EXPECT(c.txReduceRelayMinPeers == min); - BEAST_EXPECT(c.txRelayPercentage == pct); + BEAST_EXPECT(c.TX_REDUCE_RELAY_ENABLE == enable); + BEAST_EXPECT(c.TX_REDUCE_RELAY_METRICS == metrics); + BEAST_EXPECT(c.TX_REDUCE_RELAY_MIN_PEERS == min); + BEAST_EXPECT(c.TX_RELAY_PERCENTAGE == pct); if (success) { pass(); @@ -173,7 +173,7 @@ private: std::uint16_t rid_{1}; shared_context context_; ProtocolVersion protocolVersion_; - boost::beast::multi_buffer readBuf_; + boost::beast::multi_buffer read_buf_; public: tx_reduce_relay_test() : context_(makeSslContext("")), protocolVersion_{1, 7} @@ -232,9 +232,9 @@ private: testcase(test); jtx::Env env(*this); std::vector> peers; - env.app().config().txReduceRelayEnable = txRREnabled; - env.app().config().txReduceRelayMinPeers = minPeers; - env.app().config().txRelayPercentage = relayPercentage; + env.app().config().TX_REDUCE_RELAY_ENABLE = txRREnabled; + env.app().config().TX_REDUCE_RELAY_MIN_PEERS = minPeers; + env.app().config().TX_RELAY_PERCENTAGE = relayPercentage; PeerTest::init(); lid_ = 0; rid_ = 0; diff --git a/src/test/peerfinder/Livecache_test.cpp b/src/test/peerfinder/Livecache_test.cpp index 9dae410b5b..28d5beef88 100644 --- a/src/test/peerfinder/Livecache_test.cpp +++ b/src/test/peerfinder/Livecache_test.cpp @@ -116,7 +116,7 @@ public: BEAST_EXPECT(c.size() == 1); // verify that advancing to 1 sec before expiration // leaves our entry intact - clock_.advance(Tuning::kLiveCacheSecondsToLive - 1s); + clock_.advance(Tuning::kLIVE_CACHE_SECONDS_TO_LIVE - 1s); c.expire(); BEAST_EXPECT(c.size() == 1); // now advance to the point of expiration @@ -129,9 +129,9 @@ public: testHistogram() { testcase("Histogram"); - static constexpr auto kNumEps = 40; + constexpr auto kNUM_EPS = 40; Livecache<> c(clock_, journal_); - for (auto i = 0; i < kNumEps; ++i) + for (auto i = 0; i < kNUM_EPS; ++i) add(beast::IP::randomEP(true), c, xrpl::randInt()); auto h = c.hops.histogram(); if (!BEAST_EXPECT(!h.empty())) @@ -145,7 +145,7 @@ public: sum += val; BEAST_EXPECT(val >= 0); } - BEAST_EXPECT(sum == kNumEps); + BEAST_EXPECT(sum == kNUM_EPS); } void @@ -154,10 +154,10 @@ public: testcase("Shuffle"); Livecache<> c(clock_, journal_); for (auto i = 0; i < 100; ++i) - add(beast::IP::randomEP(true), c, xrpl::randInt(Tuning::kMaxHops + 1)); + add(beast::IP::randomEP(true), c, xrpl::randInt(Tuning::kMAX_HOPS + 1)); using at_hop = std::vector; - using all_hops = std::array; + using all_hops = std::array; auto cmpEp = [](Endpoint const& a, Endpoint const& b) { return (b.hops < a.hops || (b.hops == a.hops && b.address < a.address)); diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index c4f129c1a3..17ce6835ef 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -421,10 +421,10 @@ public: c.loadFromString(toLoad); BEAST_EXPECT( - (c.peersMax == max && c.peersInMax == 0 && c.peersOutMax == 0) || - (c.peersInMax == *maxIn && c.peersOutMax == *maxOut)); + (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 const config = Config::makeConfig(c, port, false, 0, true); + Config const config = Config::makeConfig(c, port, false, 0); Counts counts; counts.onConfig(config); diff --git a/src/test/protocol/ApiVersion_test.cpp b/src/test/protocol/ApiVersion_test.cpp index c41fa6f6c0..588de6ee80 100644 --- a/src/test/protocol/ApiVersion_test.cpp +++ b/src/test/protocol/ApiVersion_test.cpp @@ -10,10 +10,11 @@ struct ApiVersion_test : beast::unit_test::Suite { testcase("API versions invariants"); - static_assert(RPC::kApiMinimumSupportedVersion <= RPC::kApiMaximumSupportedVersion); - static_assert(RPC::kApiMinimumSupportedVersion <= RPC::kApiMaximumValidVersion); - static_assert(RPC::kApiMaximumSupportedVersion <= RPC::kApiMaximumValidVersion); - static_assert(RPC::kApiBetaVersion <= RPC::kApiMaximumValidVersion); + static_assert( + RPC::kAPI_MINIMUM_SUPPORTED_VERSION <= RPC::kAPI_MAXIMUM_SUPPORTED_VERSION); + static_assert(RPC::kAPI_MINIMUM_SUPPORTED_VERSION <= RPC::kAPI_MAXIMUM_VALID_VERSION); + static_assert(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION <= RPC::kAPI_MAXIMUM_VALID_VERSION); + static_assert(RPC::kAPI_BETA_VERSION <= RPC::kAPI_MAXIMUM_VALID_VERSION); BEAST_EXPECT(true); } @@ -22,14 +23,14 @@ struct ApiVersion_test : beast::unit_test::Suite // Update when we change versions testcase("API versions"); - static_assert(RPC::kApiMinimumSupportedVersion >= 1); - static_assert(RPC::kApiMinimumSupportedVersion < 2); - static_assert(RPC::kApiMaximumSupportedVersion >= 2); - static_assert(RPC::kApiMaximumSupportedVersion < 3); - static_assert(RPC::kApiMaximumValidVersion >= 3); - static_assert(RPC::kApiMaximumValidVersion < 4); - static_assert(RPC::kApiBetaVersion >= 3); - static_assert(RPC::kApiBetaVersion < 4); + static_assert(RPC::kAPI_MINIMUM_SUPPORTED_VERSION >= 1); + static_assert(RPC::kAPI_MINIMUM_SUPPORTED_VERSION < 2); + static_assert(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION >= 2); + static_assert(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION < 3); + static_assert(RPC::kAPI_MAXIMUM_VALID_VERSION >= 3); + static_assert(RPC::kAPI_MAXIMUM_VALID_VERSION < 4); + static_assert(RPC::kAPI_BETA_VERSION >= 3); + static_assert(RPC::kAPI_BETA_VERSION < 4); BEAST_EXPECT(true); } diff --git a/src/test/protocol/Hooks_test.cpp b/src/test/protocol/Hooks_test.cpp index 082507aca7..e948c76365 100644 --- a/src/test/protocol/Hooks_test.cpp +++ b/src/test/protocol/Hooks_test.cpp @@ -73,7 +73,7 @@ class Hooks_test : public beast::unit_test::Suite { SField const& f = rf.get(); - STObject dummy{sfGeneric}; + STObject dummy{kSF_GENERIC}; BEAST_EXPECT(!dummy.isFieldPresent(f)); @@ -161,8 +161,8 @@ class Hooks_test : public beast::unit_test::Suite case STI_ARRAY: { STArray dummy2{f, 2}; - dummy2.pushBack(STObject{sfGeneric}); - dummy2.pushBack(STObject{sfGeneric}); + dummy2.pushBack(STObject{kSF_GENERIC}); + dummy2.pushBack(STObject{kSF_GENERIC}); dummy.setFieldArray(f, dummy2); BEAST_EXPECT(dummy.getFieldArray(f) == dummy2); BEAST_EXPECT(dummy.isFieldPresent(f)); diff --git a/src/test/protocol/InnerObjectFormats_test.cpp b/src/test/protocol/InnerObjectFormats_test.cpp index 5154153ecf..efef209c6b 100644 --- a/src/test/protocol/InnerObjectFormats_test.cpp +++ b/src/test/protocol/InnerObjectFormats_test.cpp @@ -21,7 +21,7 @@ struct TestJSONTxt bool const expectFail; }; -static TestJSONTxt const kTestArray[] = { +static TestJSONTxt const kTEST_ARRAY[] = { // Valid SignerEntry {.txt = R"({ @@ -162,7 +162,7 @@ public: // Instantiate a jtx::Env so debugLog writes are exercised. test::jtx::Env const env(*this); - for (auto const& test : kTestArray) + for (auto const& test : kTEST_ARRAY) { json::Value req; json::Reader().parse(test.txt, req); diff --git a/src/test/protocol/MultiApiJson_test.cpp b/src/test/protocol/MultiApiJson_test.cpp index c6f844a206..e66403e0ae 100644 --- a/src/test/protocol/MultiApiJson_test.cpp +++ b/src/test/protocol/MultiApiJson_test.cpp @@ -30,7 +30,7 @@ struct MultiApiJson_test : beast::unit_test::Suite static auto makeJson(char const* key, int val) { - json::Value obj1(json::ValueType::Object); + json::Value obj1(json::ObjectValue); obj1[key] = val; return obj1; } @@ -47,7 +47,7 @@ struct MultiApiJson_test : beast::unit_test::Suite MultiApiJson<1, 3> subject{}; static_assert(sizeof(subject) == sizeof(subject.val)); - static_assert(subject.kSize == subject.val.size()); + static_assert(subject.kSIZE == subject.val.size()); static_assert(std::is_same_v>); BEAST_EXPECT(subject.val.size() == 3); @@ -60,37 +60,42 @@ struct MultiApiJson_test : beast::unit_test::Suite testcase("forApiVersions, forAllApiVersions"); // Some static data for test inputs - static int const kPrimes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, + static int const kPRIMES[] = {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(kPrimes) > RPC::kApiMaximumValidVersion); + static_assert(std::size(kPRIMES) > RPC::kAPI_MAXIMUM_VALID_VERSION); MultiApiJson<1, 3> s1{}; static_assert( - s1.kSize == RPC::kApiMaximumValidVersion + 1 - RPC::kApiMinimumSupportedVersion); + s1.kSIZE == + RPC::kAPI_MAXIMUM_VALID_VERSION + 1 - RPC::kAPI_MINIMUM_SUPPORTED_VERSION); int productAllVersions = 1; - for (unsigned i = RPC::kApiMinimumSupportedVersion; i <= RPC::kApiMaximumValidVersion; + for (unsigned i = RPC::kAPI_MINIMUM_SUPPORTED_VERSION; + i <= RPC::kAPI_MAXIMUM_VALID_VERSION; ++i) { - auto const index = i - RPC::kApiMinimumSupportedVersion; + auto const index = i - RPC::kAPI_MINIMUM_SUPPORTED_VERSION; BEAST_EXPECT(index == s1.index(i)); BEAST_EXPECT(s1.valid(i)); - s1.val[index] = makeJson("value", kPrimes[i]); - productAllVersions *= kPrimes[i]; + s1.val[index] = makeJson("value", kPRIMES[i]); + productAllVersions *= kPRIMES[i]; } BEAST_EXPECT(!s1.valid(0)); - BEAST_EXPECT(!s1.valid(RPC::kApiMaximumValidVersion + 1)); + BEAST_EXPECT(!s1.valid(RPC::kAPI_MAXIMUM_VALID_VERSION + 1)); BEAST_EXPECT(!s1.valid( - std::numeric_limits::max())); + std::numeric_limits::max())); int result = 1; - static_assert(RPC::kApiMinimumSupportedVersion + 1 <= RPC::kApiMaximumValidVersion); - forApiVersions( + static_assert( + RPC::kAPI_MINIMUM_SUPPORTED_VERSION + 1 <= RPC::kAPI_MAXIMUM_VALID_VERSION); + forApiVersions< + RPC::kAPI_MINIMUM_SUPPORTED_VERSION, + RPC::kAPI_MINIMUM_SUPPORTED_VERSION + 1>( std::as_const(s1).visit(), [this](json::Value const& json, unsigned int version, int* result) { BEAST_EXPECT( - version >= RPC::kApiMinimumSupportedVersion && - version <= RPC::kApiMinimumSupportedVersion + 1); + version >= RPC::kAPI_MINIMUM_SUPPORTED_VERSION && + version <= RPC::kAPI_MINIMUM_SUPPORTED_VERSION + 1); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -99,15 +104,15 @@ struct MultiApiJson_test : beast::unit_test::Suite &result); BEAST_EXPECT( result == - kPrimes[RPC::kApiMinimumSupportedVersion] * - kPrimes[RPC::kApiMinimumSupportedVersion + 1]); + kPRIMES[RPC::kAPI_MINIMUM_SUPPORTED_VERSION] * + kPRIMES[RPC::kAPI_MINIMUM_SUPPORTED_VERSION + 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() == kPrimes[version]); + BEAST_EXPECT(json["value"].asInt() == kPRIMES[version]); } }); @@ -116,8 +121,8 @@ struct MultiApiJson_test : beast::unit_test::Suite std::as_const(s1).visit(), [this](json::Value const& json, unsigned int version, int* result) { BEAST_EXPECT( - version >= RPC::kApiMinimumSupportedVersion && - version <= RPC::kApiMaximumValidVersion); + version >= RPC::kAPI_MINIMUM_SUPPORTED_VERSION && + version <= RPC::kAPI_MAXIMUM_VALID_VERSION); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -273,7 +278,7 @@ struct MultiApiJson_test : beast::unit_test::Suite { testcase("set"); - auto x = MultiApiJson<1, 2>{json::ValueType::Object}; + auto x = MultiApiJson<1, 2>{json::ObjectValue}; x.set("name1", 42); BEAST_EXPECT(x.val[0].isMember("name1")); BEAST_EXPECT(x.val[1].isMember("name1")); @@ -291,8 +296,7 @@ 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::ValueType::Null); }; }(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)); @@ -358,14 +362,14 @@ struct MultiApiJson_test : beast::unit_test::Suite // Test different overloads static_assert([](auto&& v) { return requires { - v.kVisitor( + v.kVISITOR( v, std::integral_constant{}, [](json::Value&, std::integral_constant) {}); }; }(s1)); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, std::integral_constant{}, Overload{ @@ -377,11 +381,11 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return requires { - v.kVisitor(v, std::integral_constant{}, [](json::Value&) {}); + v.kVISITOR(v, std::integral_constant{}, [](json::Value&) {}); }; }(s1)); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, std::integral_constant{}, Overload{ @@ -391,14 +395,14 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return requires { - v.kVisitor( + v.kVISITOR( v, std::integral_constant{}, [](json::Value const&, std::integral_constant) {}); }; }(std::as_const(s1))); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), std::integral_constant{}, Overload{ @@ -410,11 +414,11 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return requires { - v.kVisitor(v, std::integral_constant{}, [](json::Value const&) {}); + v.kVISITOR(v, std::integral_constant{}, [](json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), std::integral_constant{}, Overload{ @@ -423,10 +427,10 @@ struct MultiApiJson_test : beast::unit_test::Suite [](auto...) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value&, unsigned) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value&, unsigned) {}); }; }(s1)); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // 3u, Overload{ @@ -435,9 +439,9 @@ struct MultiApiJson_test : beast::unit_test::Suite [](auto, auto) { return 0; }}) == 5); static_assert( - [](auto&& v) { return requires { v.kVisitor(v, 1, [](json::Value&) {}); }; }(s1)); + [](auto&& v) { return requires { v.kVISITOR(v, 1, [](json::Value&) {}); }; }(s1)); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // 3, Overload{ @@ -446,10 +450,10 @@ struct MultiApiJson_test : beast::unit_test::Suite [](auto...) { return 0; }}) == 5); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value const&, unsigned) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value const&, unsigned) {}); }; }(std::as_const(s1))); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), // 2u, Overload{ @@ -458,10 +462,10 @@ struct MultiApiJson_test : beast::unit_test::Suite [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value const&) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), // 2, Overload{ @@ -471,64 +475,64 @@ struct MultiApiJson_test : beast::unit_test::Suite // Test type conversions BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, std::integral_constant{}, // to unsigned [](json::Value& v, unsigned) { return v["value"].asInt(); }) == 2); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), std::integral_constant{}, // to unsigned [](json::Value const& v, unsigned) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // to const std::integral_constant{}, [](json::Value const& v, auto) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // to const std::integral_constant{}, [](json::Value const& v) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, 3, // to long [](json::Value& v, long) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( std::as_const(s1), 1, // to long [](json::Value const& v, long) { return v["value"].asInt(); }) == 2); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // to const 2, [](json::Value const& v, auto) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // type deduction 2, [](auto& v, auto) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // to const, type deduction 2, [](auto const& v, auto) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // type deduction 2, [](auto& v) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, // to const, type deduction 2, [](auto const& v) { return v["value"].asInt(); }) == 3); // Test passing of additional arguments BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, std::integral_constant{}, [](json::Value& v, auto ver, auto a1, auto a2) { @@ -537,7 +541,7 @@ struct MultiApiJson_test : beast::unit_test::Suite 5, 7) == 2 * 5 * 7 * 3); BEAST_EXPECT( - s1.kVisitor( + s1.kVISITOR( s1, std::integral_constant{}, [](json::Value& v, auto ver, auto... args) { @@ -549,7 +553,7 @@ struct MultiApiJson_test : beast::unit_test::Suite // Several overloads we want to fail static_assert([](auto&& v) { return !requires { - v.kVisitor( + v.kVISITOR( v, 1, // [](json::Value&, auto) {}); // missing const @@ -558,7 +562,7 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return !requires { - v.kVisitor( + v.kVISITOR( decltype(v){}, // cannot bind rvalue 1, [](json::Value&, auto) {}); @@ -567,7 +571,7 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return !requires { - v.kVisitor( + v.kVISITOR( v, 1, // []() {}); // missing parameter @@ -576,7 +580,7 @@ struct MultiApiJson_test : beast::unit_test::Suite static_assert([](auto&& v) { return !requires { - v.kVisitor( + v.kVISITOR( v, 1, // [](json::Value&, int, int) {}); // too many parameters @@ -584,39 +588,39 @@ struct MultiApiJson_test : beast::unit_test::Suite }(s1)); // Want these to be unambiguous - static_assert([](auto&& v) { return requires { v.kVisitor(v, 1, [](auto) {}); }; }(s1)); + static_assert([](auto&& v) { return requires { v.kVISITOR(v, 1, [](auto) {}); }; }(s1)); static_assert( - [](auto&& v) { return requires { v.kVisitor(v, 1, [](json::Value&) {}); }; }(s1)); + [](auto&& v) { return requires { v.kVISITOR(v, 1, [](json::Value&) {}); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value&, auto...) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value&, auto...) {}); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value const&) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value const&) {}); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](json::Value const&, auto...) {}); }; + return requires { v.kVISITOR(v, 1, [](json::Value const&, auto...) {}); }; }(s1)); static_assert( - [](auto&& v) { return requires { v.kVisitor(v, 1, [](auto...) {}); }; }(s1)); + [](auto&& v) { return requires { v.kVISITOR(v, 1, [](auto...) {}); }; }(s1)); static_assert( - [](auto&& v) { return requires { v.kVisitor(v, 1, [](auto, auto...) {}); }; }(s1)); + [](auto&& v) { return requires { v.kVISITOR(v, 1, [](auto, auto...) {}); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](auto, auto, auto...) {}); }; + return requires { v.kVISITOR(v, 1, [](auto, auto, auto...) {}); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](auto, auto, auto...) {}, ""); }; + return requires { v.kVISITOR(v, 1, [](auto, auto, auto...) {}, ""); }; }(s1)); static_assert([](auto&& v) { - return requires { v.kVisitor(v, 1, [](auto, auto, auto, auto...) {}, ""); }; + return requires { v.kVISITOR(v, 1, [](auto, auto, auto, auto...) {}, ""); }; }(s1)); } diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index 1494e57a5e..874eda8c65 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -46,12 +46,12 @@ public: } }; - static Table kLut; + static Table kLUT; out.reserve(std::distance(first, last) / 2); while (first != last) { - auto const hi(kLut[(*first++)]); - auto const lo(kLut[(*first++)]); + auto const hi(kLUT[(*first++)]); + auto const lo(kLUT[(*first++)]); out.push_back((hi * 16) + lo); } } diff --git a/src/test/protocol/Quality_test.cpp b/src/test/protocol/Quality_test.cpp index df95cea8ef..fe049f11f2 100644 --- a/src/test/protocol/Quality_test.cpp +++ b/src/test/protocol/Quality_test.cpp @@ -263,7 +263,7 @@ public: raw(2755280000000000ull, -15)); // 2.75528 STAmount const limit(raw(4131113916555555, -16)); // .4131113916555555 Amounts const result(q.ceilOut(value, limit)); - BEAST_EXPECT(result.in != beast::kZero); + BEAST_EXPECT(result.in != beast::kZERO); } } diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index 720fafa8f2..7c37d3e9bc 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -37,7 +37,7 @@ public: s.add(ser); SerialIter sit(ser.slice()); - return STAmount(sit, sfGeneric); + return STAmount(sit, kSF_GENERIC); } //-------------------------------------------------------------------------- @@ -54,7 +54,7 @@ public: { mantissa--; - if (mantissa < STAmount::kMinValue) + if (mantissa < STAmount::kMIN_VALUE) return {amount.asset(), mantissa, amount.exponent(), amount.negative()}; return { @@ -69,7 +69,7 @@ public: { mantissa++; - if (mantissa > STAmount::kMaxValue) + if (mantissa > STAmount::kMAX_VALUE) return {amount.asset(), mantissa, amount.exponent(), amount.negative()}; return { @@ -228,9 +228,9 @@ public: unexpected(serializeAndDeserialize(hundred) != hundred, "STAmount fail"); unexpected(!zeroSt.native(), "STAmount fail"); unexpected(!hundred.native(), "STAmount fail"); - unexpected(zeroSt != beast::kZero, "STAmount fail"); - unexpected(one == beast::kZero, "STAmount fail"); - unexpected(hundred == beast::kZero, "STAmount fail"); + unexpected(zeroSt != beast::kZERO, "STAmount fail"); + unexpected(one == beast::kZERO, "STAmount fail"); + unexpected(hundred == beast::kZERO, "STAmount fail"); unexpected((zeroSt < zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt < one), "STAmount fail"); unexpected(!(zeroSt < hundred), "STAmount fail"); @@ -314,9 +314,9 @@ public: unexpected(serializeAndDeserialize(hundred) != hundred, "STAmount fail"); unexpected(zeroSt.native(), "STAmount fail"); unexpected(hundred.native(), "STAmount fail"); - unexpected(zeroSt != beast::kZero, "STAmount fail"); - unexpected(one == beast::kZero, "STAmount fail"); - unexpected(hundred == beast::kZero, "STAmount fail"); + unexpected(zeroSt != beast::kZERO, "STAmount fail"); + unexpected(one == beast::kZERO, "STAmount fail"); + unexpected(hundred == beast::kZERO, "STAmount fail"); unexpected((zeroSt < zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt < one), "STAmount fail"); unexpected(!(zeroSt < hundred), "STAmount fail"); @@ -494,30 +494,34 @@ public: { testcase("underflow"); - STAmount const bigNative(STAmount::kMaxNative / 2); + STAmount const bigNative(STAmount::kMAX_NATIVE / 2); STAmount const bigValue( - noIssue(), (STAmount::kMinValue + STAmount::kMaxValue) / 2, STAmount::kMaxOffset - 1); + noIssue(), + (STAmount::kMIN_VALUE + STAmount::kMAX_VALUE) / 2, + STAmount::kMAX_OFFSET - 1); STAmount const smallValue( - noIssue(), (STAmount::kMinValue + STAmount::kMaxValue) / 2, STAmount::kMinOffset + 1); + noIssue(), + (STAmount::kMIN_VALUE + STAmount::kMAX_VALUE) / 2, + STAmount::kMIN_OFFSET + 1); STAmount const zeroSt(noIssue(), 0); STAmount const smallXSmall = multiply(smallValue, smallValue, noIssue()); - BEAST_EXPECT(smallXSmall == beast::kZero); + BEAST_EXPECT(smallXSmall == beast::kZERO); STAmount bigDsmall = divide(smallValue, bigValue, noIssue()); - BEAST_EXPECT(bigDsmall == beast::kZero); + BEAST_EXPECT(bigDsmall == beast::kZERO); - BEAST_EXPECT(bigDsmall == beast::kZero); + BEAST_EXPECT(bigDsmall == beast::kZERO); bigDsmall = divide(smallValue, bigValue, xrpIssue()); - BEAST_EXPECT(bigDsmall == beast::kZero); + BEAST_EXPECT(bigDsmall == beast::kZERO); bigDsmall = divide(smallValue, bigNative, xrpIssue()); - BEAST_EXPECT(bigDsmall == beast::kZero); + BEAST_EXPECT(bigDsmall == beast::kZERO); // very bad offer std::uint64_t r = getRate(smallValue, bigValue); @@ -614,17 +618,17 @@ public: BEAST_EXPECT(amountFromJson(sfNumber, "0") == XRPAmount(0)); BEAST_EXPECT(amountFromJson(sfNumber, "-0") == XRPAmount(0)); - constexpr auto kIMin = std::numeric_limits::min(); - BEAST_EXPECT(amountFromJson(sfNumber, kIMin) == XRPAmount(kIMin)); - BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kIMin)) == XRPAmount(kIMin)); + constexpr auto kIMIN = std::numeric_limits::min(); + BEAST_EXPECT(amountFromJson(sfNumber, kIMIN) == XRPAmount(kIMIN)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kIMIN)) == XRPAmount(kIMIN)); - constexpr auto kIMax = std::numeric_limits::max(); - BEAST_EXPECT(amountFromJson(sfNumber, kIMax) == XRPAmount(kIMax)); - BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kIMax)) == XRPAmount(kIMax)); + constexpr auto kIMAX = std::numeric_limits::max(); + BEAST_EXPECT(amountFromJson(sfNumber, kIMAX) == XRPAmount(kIMAX)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kIMAX)) == XRPAmount(kIMAX)); - constexpr auto kUMax = std::numeric_limits::max(); - BEAST_EXPECT(amountFromJson(sfNumber, kUMax) == XRPAmount(kUMax)); - BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kUMax)) == XRPAmount(kUMax)); + constexpr auto kUMAX = std::numeric_limits::max(); + BEAST_EXPECT(amountFromJson(sfNumber, kUMAX) == XRPAmount(kUMAX)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(kUMAX)) == XRPAmount(kUMAX)); // XRP does not handle fractional part try @@ -1203,98 +1207,6 @@ public: } } - void - testIsZeroAtScale() - { - testcase("isZeroAtScale"); - - Issue const usd{Currency(0x5553440000000000), AccountID(0x4985601)}; - - // IOU: 10 IOU — mantissa = kMinValue (10^15), exponent = -14. - // One ULP at this scale is 10^-14; half-ULP is 5*10^-15. - { - STAmount const ref{usd, STAmount::kMinValue, -14}; - int const refScale = ref.exponent(); // -14 - BEAST_EXPECT(refScale == -14); - - // Zero rounds to zero at any scale. - STAmount const iouZero{usd, 0}; - BEAST_EXPECT(iouZero.isZeroAtScale(refScale)); - - // Sub-ULP: 1e-16 IOU (mantissa = kMinValue, exponent = -31). - // Far below half-ULP → rounds to zero. - STAmount const subUlp{usd, STAmount::kMinValue, -31}; - BEAST_EXPECT(subUlp.isZeroAtScale(refScale)); - - // One ULP: 1e-14 IOU (mantissa = kMinValue, exponent = -29). - // Exactly the smallest representable unit at refScale → not zero. - STAmount const oneUlp{usd, STAmount::kMinValue, -29}; - BEAST_EXPECT(!oneUlp.isZeroAtScale(refScale)); - - // The reference value itself: exponent == scale → returned - // unchanged → not zero. - BEAST_EXPECT(!ref.isZeroAtScale(refScale)); - - // A much larger value: certainly not zero at this scale. - STAmount const large{usd, STAmount::kMinValue, 0}; // 1e15 IOU - BEAST_EXPECT(!large.isZeroAtScale(refScale)); - - // When scale equals the value's own exponent, roundToScale - // short-circuits and returns the value unchanged. - BEAST_EXPECT(!subUlp.isZeroAtScale(subUlp.exponent())); - BEAST_EXPECT(!oneUlp.isZeroAtScale(oneUlp.exponent())); - - // Half-ULP boundary. roundToScale forms (value + ref) - ref - // where ref = 10 IOU has mantissa 1e15 (LSB 0, even). - // Number's default rounding is to-nearest-even, so an exact - // half-ULP tie rounds toward the even-LSB neighbour — the - // reference itself — and the round-trip result is zero. - // Just below half-ULP rounds the same way; just above - // clears half-ULP and bumps the mantissa to 1e15 + 1. - STAmount const justBelowHalf{usd, STAmount::kMinValue * 4, -30}; - BEAST_EXPECT(justBelowHalf.isZeroAtScale(refScale)); - - STAmount const halfUlp{usd, STAmount::kMinValue * 5, -30}; - BEAST_EXPECT(halfUlp.isZeroAtScale(refScale)); - - STAmount const justAboveHalf{usd, STAmount::kMinValue * 6, -30}; - BEAST_EXPECT(!justAboveHalf.isZeroAtScale(refScale)); - - // Large magnitude gap: dust value far below an enormous scale. - // 1e-80 with scale +15 — the value vanishes utterly. - STAmount const dust{usd, STAmount::kMinValue, -95}; - BEAST_EXPECT(dust.isZeroAtScale(15)); - - // Negative values mirror positive behaviour. - STAmount const negSubUlp{usd, STAmount::kMinValue, -31, true}; - BEAST_EXPECT(negSubUlp.isZeroAtScale(refScale)); - - STAmount const negOneUlp{usd, STAmount::kMinValue, -29, true}; - BEAST_EXPECT(!negOneUlp.isZeroAtScale(refScale)); - } - - // XRP is integral — roundToScale short-circuits, value is preserved. - { - STAmount const xrp{XRPAmount{1}}; - BEAST_EXPECT(!xrp.isZeroAtScale(-14)); - BEAST_EXPECT(!xrp.isZeroAtScale(0)); - - STAmount const xrpZero{XRPAmount{0}}; - BEAST_EXPECT(xrpZero.isZeroAtScale(-14)); - } - - // MPT is integral — same short-circuit behaviour as XRP. - { - MPTIssue const mpt{makeMptID(1, AccountID(0x4985601))}; - STAmount const mptAmt{mpt, 1}; - BEAST_EXPECT(!mptAmt.isZeroAtScale(0)); - BEAST_EXPECT(!mptAmt.isZeroAtScale(-14)); - - STAmount const mptZero{mpt, 0}; - BEAST_EXPECT(mptZero.isZeroAtScale(0)); - } - } - //-------------------------------------------------------------------------- void @@ -1315,7 +1227,6 @@ public: testCanSubtractXRP(); testCanSubtractIOU(); testCanSubtractMPT(); - testIsZeroAtScale(); } }; diff --git a/src/test/protocol/STInteger_test.cpp b/src/test/protocol/STInteger_test.cpp index 789555560d..b28273ffb9 100644 --- a/src/test/protocol/STInteger_test.cpp +++ b/src/test/protocol/STInteger_test.cpp @@ -17,7 +17,7 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(u8.value() == 255); BEAST_EXPECT(u8.getText() == "255"); BEAST_EXPECT(u8.getSType() == STI_UINT8); - BEAST_EXPECT(u8.getJson(JsonOptions::Values::None) == 255); + BEAST_EXPECT(u8.getJson(JsonOptions::KNone) == 255); // there is some special handling for sfTransactionResult STUInt8 const tr(sfTransactionResult, 0); @@ -25,14 +25,14 @@ struct STInteger_test : public beast::unit_test::Suite 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::Values::None) == "tesSUCCESS"); + BEAST_EXPECT(tr.getJson(JsonOptions::KNone) == "tesSUCCESS"); // invalid transaction result STUInt8 const tr2(sfTransactionResult, 255); BEAST_EXPECT(tr2.value() == 255); BEAST_EXPECT(tr2.getText() == "255"); BEAST_EXPECT(tr2.getSType() == STI_UINT8); - BEAST_EXPECT(tr2.getJson(JsonOptions::Values::None) == 255); + BEAST_EXPECT(tr2.getJson(JsonOptions::KNone) == 255); } void @@ -43,21 +43,21 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(u16.value() == 65535); BEAST_EXPECT(u16.getText() == "65535"); BEAST_EXPECT(u16.getSType() == STI_UINT16); - BEAST_EXPECT(u16.getJson(JsonOptions::Values::None) == 65535); + BEAST_EXPECT(u16.getJson(JsonOptions::KNone) == 65535); // there is some special handling for sfLedgerEntryType STUInt16 const let(sfLedgerEntryType, ltACCOUNT_ROOT); BEAST_EXPECT(let.value() == ltACCOUNT_ROOT); BEAST_EXPECT(let.getText() == "AccountRoot"); BEAST_EXPECT(let.getSType() == STI_UINT16); - BEAST_EXPECT(let.getJson(JsonOptions::Values::None) == "AccountRoot"); + BEAST_EXPECT(let.getJson(JsonOptions::KNone) == "AccountRoot"); // there is some special handling for sfTransactionType STUInt16 const tlt(sfTransactionType, ttPAYMENT); BEAST_EXPECT(tlt.value() == ttPAYMENT); BEAST_EXPECT(tlt.getText() == "Payment"); BEAST_EXPECT(tlt.getSType() == STI_UINT16); - BEAST_EXPECT(tlt.getJson(JsonOptions::Values::None) == "Payment"); + BEAST_EXPECT(tlt.getJson(JsonOptions::KNone) == "Payment"); } void @@ -68,19 +68,19 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(u32.value() == 4'294'967'295u); BEAST_EXPECT(u32.getText() == "4294967295"); BEAST_EXPECT(u32.getSType() == STI_UINT32); - BEAST_EXPECT(u32.getJson(JsonOptions::Values::None) == 4'294'967'295u); + BEAST_EXPECT(u32.getJson(JsonOptions::KNone) == 4'294'967'295u); // there is some special handling for sfPermissionValue STUInt32 const pv(sfPermissionValue, ttPAYMENT + 1); BEAST_EXPECT(pv.value() == ttPAYMENT + 1); BEAST_EXPECT(pv.getText() == "Payment"); BEAST_EXPECT(pv.getSType() == STI_UINT32); - BEAST_EXPECT(pv.getJson(JsonOptions::Values::None) == "Payment"); + BEAST_EXPECT(pv.getJson(JsonOptions::KNone) == "Payment"); STUInt32 const pv2(sfPermissionValue, PaymentMint); BEAST_EXPECT(pv2.value() == PaymentMint); BEAST_EXPECT(pv2.getText() == "PaymentMint"); BEAST_EXPECT(pv2.getSType() == STI_UINT32); - BEAST_EXPECT(pv2.getJson(JsonOptions::Values::None) == "PaymentMint"); + BEAST_EXPECT(pv2.getJson(JsonOptions::KNone) == "PaymentMint"); } void @@ -93,7 +93,7 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(u64.getSType() == STI_UINT64); // By default, getJson returns hex string - auto jsonVal = u64.getJson(JsonOptions::Values::None); + auto jsonVal = u64.getJson(JsonOptions::KNone); BEAST_EXPECT(jsonVal.isString()); BEAST_EXPECT(jsonVal.asString() == "ffffffffffffffff"); @@ -101,7 +101,7 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(u642.value() == 0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u642.getText() == "18446744073709551615"); BEAST_EXPECT(u642.getSType() == STI_UINT64); - BEAST_EXPECT(u642.getJson(JsonOptions::Values::None) == "18446744073709551615"); + BEAST_EXPECT(u642.getJson(JsonOptions::KNone) == "18446744073709551615"); } void @@ -114,7 +114,7 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(i32.value() == minInt32); BEAST_EXPECT(i32.getText() == "-2147483648"); BEAST_EXPECT(i32.getSType() == STI_INT32); - BEAST_EXPECT(i32.getJson(JsonOptions::Values::None) == minInt32); + BEAST_EXPECT(i32.getJson(JsonOptions::KNone) == minInt32); } { @@ -123,7 +123,7 @@ struct STInteger_test : public beast::unit_test::Suite BEAST_EXPECT(i32.value() == maxInt32); BEAST_EXPECT(i32.getText() == "2147483647"); BEAST_EXPECT(i32.getSType() == STI_INT32); - BEAST_EXPECT(i32.getJson(JsonOptions::Values::None) == maxInt32); + BEAST_EXPECT(i32.getJson(JsonOptions::KNone) == maxInt32); } } diff --git a/src/test/protocol/STIssue_test.cpp b/src/test/protocol/STIssue_test.cpp index 1d6d750355..04364510f0 100644 --- a/src/test/protocol/STIssue_test.cpp +++ b/src/test/protocol/STIssue_test.cpp @@ -55,7 +55,7 @@ public: auto const data = "00000000000000000000000055534400000000000000000000000000000000" "000000000000000000"; - BaseUInt<320> uint; + BaseUint<320> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); STIssue const stissue(iter, sfAsset); @@ -89,7 +89,7 @@ public: auto const data = "0000000000000000000000005553440000000000ae123a8556f3cf91154711" "376afb0f894f832b3d"; - BaseUInt<320> uint; + BaseUint<320> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); STIssue const stissue(iter, sfAsset); @@ -103,7 +103,7 @@ public: try { auto const data = "0000000000000000000000000000000000000000"; - BaseUInt<160> uint; + BaseUint<160> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); STIssue const stissue(iter, sfAsset); diff --git a/src/test/protocol/STNumber_test.cpp b/src/test/protocol/STNumber_test.cpp index 5c9c3fd83c..914e2d003f 100644 --- a/src/test/protocol/STNumber_test.cpp +++ b/src/test/protocol/STNumber_test.cpp @@ -55,7 +55,7 @@ struct STNumber_test : public beast::unit_test::Suite testCombo(Number{mantissa}); std::initializer_list const exponents = { - Number::kMinExponent, -1, 0, 1, Number::kMaxExponent - 1}; + Number::kMIN_EXPONENT, -1, 0, 1, Number::kMAX_EXPONENT - 1}; for (std::int32_t const exponent : exponents) testCombo(Number{123, exponent}); @@ -128,23 +128,23 @@ struct STNumber_test : public beast::unit_test::Suite } } - constexpr auto kIMin = std::numeric_limits::min(); - BEAST_EXPECT(numberFromJson(sfNumber, kIMin) == STNumber(sfNumber, Number(kIMin, 0))); + constexpr auto kIMIN = std::numeric_limits::min(); + BEAST_EXPECT(numberFromJson(sfNumber, kIMIN) == STNumber(sfNumber, Number(kIMIN, 0))); BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(kIMin)) == - STNumber(sfNumber, Number(kIMin, 0))); + numberFromJson(sfNumber, std::to_string(kIMIN)) == + STNumber(sfNumber, Number(kIMIN, 0))); - constexpr auto kIMax = std::numeric_limits::max(); - BEAST_EXPECT(numberFromJson(sfNumber, kIMax) == STNumber(sfNumber, Number(kIMax, 0))); + constexpr auto kIMAX = std::numeric_limits::max(); + BEAST_EXPECT(numberFromJson(sfNumber, kIMAX) == STNumber(sfNumber, Number(kIMAX, 0))); BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(kIMax)) == - STNumber(sfNumber, Number(kIMax, 0))); + numberFromJson(sfNumber, std::to_string(kIMAX)) == + STNumber(sfNumber, Number(kIMAX, 0))); - constexpr auto kUMax = std::numeric_limits::max(); - BEAST_EXPECT(numberFromJson(sfNumber, kUMax) == STNumber(sfNumber, Number(kUMax, 0))); + constexpr auto kUMAX = std::numeric_limits::max(); + BEAST_EXPECT(numberFromJson(sfNumber, kUMAX) == STNumber(sfNumber, Number(kUMAX, 0))); BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(kUMax)) == - STNumber(sfNumber, Number(kUMax, 0))); + numberFromJson(sfNumber, std::to_string(kUMAX)) == + STNumber(sfNumber, Number(kUMAX, 0))); // Obvious non-numbers tested here try @@ -280,7 +280,8 @@ struct STNumber_test : public beast::unit_test::Suite { static_assert(!std::is_convertible_v); - for (auto const scale : MantissaRange::getAllScales()) + for (auto const scale : + {MantissaRange::MantissaScale::Small, MantissaRange::MantissaScale::Large}) { NumberMantissaScaleGuard const sg(scale); testcase << to_string(Number::getMantissaScale()); diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index 801eebbe63..a408f2503b 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -36,19 +36,19 @@ public: { testcase("serialization"); - unexpected(sfGeneric.isUseful(), "sfGeneric must not be useful"); + unexpected(kSF_GENERIC.isUseful(), "sfGeneric must not be useful"); { // Try to put sfGeneric in an SOTemplate. except( - [&]() { SOTemplate const elements{{sfGeneric, SoeRequired}}; }); + [&]() { SOTemplate const elements{{kSF_GENERIC, SoeRequired}}; }); } - unexpected(sfInvalid.isUseful(), "sfInvalid must not be useful"); + unexpected(kSF_INVALID.isUseful(), "sfInvalid must not be useful"); { // Test return of sfInvalid. auto testInvalid = [this](SerializedTypeID tid, int fv) { SField const& shouldBeInvalid{SField::getField(tid, fv)}; - BEAST_EXPECT(shouldBeInvalid == sfInvalid); + BEAST_EXPECT(shouldBeInvalid == kSF_INVALID); }; testInvalid(STI_VL, 255); testInvalid(STI_UINT256, 255); @@ -59,7 +59,7 @@ public: { // Try to put sfInvalid in an SOTemplate. except( - [&]() { SOTemplate const elements{{sfInvalid, SoeRequired}}; }); + [&]() { SOTemplate const elements{{kSF_INVALID, SoeRequired}}; }); } { // Try to put the same SField into an SOTemplate twice. @@ -103,8 +103,8 @@ public: if (object1.getSerializer() == object2.getSerializer()) { - log << "O1: " << object1.getJson(JsonOptions::Values::None) << '\n' - << "O2: " << object2.getJson(JsonOptions::Values::None) << std::endl; + log << "O1: " << object1.getJson(JsonOptions::KNone) << '\n' + << "O2: " << object2.getJson(JsonOptions::KNone) << std::endl; fail("STObject error 4"); } else @@ -188,7 +188,7 @@ public: { auto const st = [&]() { - STObject s(sfGeneric); + STObject s(kSF_GENERIC); s.setFieldU32(sf1Outer, 1); s.setFieldU32(sf2Outer, 2); return s; @@ -219,7 +219,7 @@ public: { auto const st = [&]() { - STObject s(sotOuter, sfGeneric); + STObject s(sotOuter, kSF_GENERIC); s.setFieldU32(sf1Outer, 1); s.setFieldU32(sf2Outer, 2); return s; @@ -239,7 +239,7 @@ public: // write free object { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); unexcept([&]() { st[sf1Outer]; }); except([&]() { return st[sf1Outer] == 0; }); BEAST_EXPECT(st[~sf1Outer] == std::nullopt); @@ -295,7 +295,7 @@ public: // Write templated object { - STObject st(sotOuter, sfGeneric); + STObject st(sotOuter, kSF_GENERIC); BEAST_EXPECT(!!st[~sf1Outer]); BEAST_EXPECT(st[~sf1Outer] != std::nullopt); BEAST_EXPECT(st[sf1Outer] == 0); @@ -353,7 +353,7 @@ public: // coercion operator to std::optional { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); auto const v = ~st[~sf1Outer]; static_assert( std::is_same_v, std::optional>, ""); @@ -362,7 +362,7 @@ public: // UDT scalar fields { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); st[sfAmount] = STAmount{}; st[sfAccount] = AccountID{}; st[sfDigest] = uint256{}; @@ -375,7 +375,7 @@ public: { { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); Buffer b(1); BEAST_EXPECT(!b.empty()); st[sf4] = std::move(b); @@ -392,7 +392,7 @@ public: BEAST_EXPECT(Slice(st[sf5]).size() == 2); } { - STObject st(sotOuter, sfGeneric); + STObject st(sotOuter, kSF_GENERIC); BEAST_EXPECT(st[sf5] == Slice{}); BEAST_EXPECT(!!st[~sf5]); BEAST_EXPECT(!!~st[~sf5]); @@ -408,7 +408,7 @@ public: // UDT blobs { - STObject st(sfGeneric); + STObject st(kSF_GENERIC); BEAST_EXPECT(!st[~sf5]); auto const kp = generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")); st[sf5] = kp.first; @@ -419,7 +419,7 @@ public: { auto const& sf = sfIndexes; - STObject st(sfGeneric); + STObject st(kSF_GENERIC); std::vector v; v.emplace_back(1); v.emplace_back(2); @@ -446,7 +446,7 @@ public: {sf3, SoeDefault}, }; - STObject st(sot, sfGeneric); + STObject st(sot, kSF_GENERIC); auto const& cst(st); BEAST_EXPECT(cst[sf1].empty()); BEAST_EXPECT(!cst[~sf2]); diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index bc5c72b4fc..ef2f8e971e 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -102,7 +102,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (not a string/int/uint) { json::Value j; - j[sfCloseResolution] = json::Value(json::ValueType::Array); + j[sfCloseResolution] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -110,7 +110,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (not a string/int/uint) { json::Value j; - j[sfCloseResolution] = json::Value(json::ValueType::Object); + j[sfCloseResolution] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -193,7 +193,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (not a string/int/uint) { json::Value j; - j[sfLedgerEntryType] = json::Value(json::ValueType::Array); + j[sfLedgerEntryType] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -201,7 +201,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (not a string/int/uint) { json::Value j; - j[sfLedgerEntryType] = json::Value(json::ValueType::Object); + j[sfLedgerEntryType] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -271,7 +271,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (arrayValue) { json::Value j; - j[sfNetworkID] = json::Value(json::ValueType::Array); + j[sfNetworkID] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -279,7 +279,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (objectValue) { json::Value j; - j[sfNetworkID] = json::Value(json::ValueType::Object); + j[sfNetworkID] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -348,7 +348,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // test arrayValue { json::Value j; - j[sfIndexNext] = json::Value(json::ValueType::Array); + j[sfIndexNext] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -356,7 +356,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // test objectValue { json::Value j; - j[sfIndexNext] = json::Value(json::ValueType::Object); + j[sfIndexNext] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -393,7 +393,7 @@ class STParsedJSON_test : public beast::unit_test::Suite 0xCD, 0xEF}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash) == uint128::fromRaw(expected)); + BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash) == uint128{expected}); } // Valid lowercase hex string for UInt128 @@ -458,7 +458,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for UInt128 (should fail) { json::Value j; - j[sfEmailHash] = json::Value(json::ValueType::Array); + j[sfEmailHash] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -466,7 +466,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for UInt128 (should fail) { json::Value j; - j[sfEmailHash] = json::Value(json::ValueType::Object); + j[sfEmailHash] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -488,9 +488,8 @@ class STParsedJSON_test : public beast::unit_test::Suite std::array const expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; - BEAST_EXPECT( - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - obj.object->getFieldH160(sfTakerPaysCurrency) == uint160::fromRaw(expected)); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency) == uint160{expected}); } // Valid lowercase hex string for UInt160 { @@ -546,7 +545,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for UInt160 (should fail) { json::Value j; - j[sfTakerPaysCurrency] = json::Value(json::ValueType::Array); + j[sfTakerPaysCurrency] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -554,7 +553,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for UInt160 (should fail) { json::Value j; - j[sfTakerPaysCurrency] = json::Value(json::ValueType::Object); + j[sfTakerPaysCurrency] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -576,9 +575,8 @@ class STParsedJSON_test : public beast::unit_test::Suite std::array const 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( - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - obj.object->getFieldH192(sfMPTokenIssuanceID) == uint192::fromRaw(expected)); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID) == uint192{expected}); } // Valid lowercase hex string for UInt192 @@ -643,7 +641,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for UInt192 (should fail) { json::Value j; - j[sfMPTokenIssuanceID] = json::Value(json::ValueType::Array); + j[sfMPTokenIssuanceID] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -651,7 +649,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for UInt192 (should fail) { json::Value j; - j[sfMPTokenIssuanceID] = json::Value(json::ValueType::Object); + j[sfMPTokenIssuanceID] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -678,7 +676,7 @@ class STParsedJSON_test : public beast::unit_test::Suite 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash) == uint256::fromRaw(expected)); + BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash) == uint256{expected}); } // Valid lowercase hex string for UInt256 { @@ -748,7 +746,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for UInt256 (should fail) { json::Value j; - j[sfLedgerHash] = json::Value(json::ValueType::Array); + j[sfLedgerHash] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -756,7 +754,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for UInt256 (should fail) { json::Value j; - j[sfLedgerHash] = json::Value(json::ValueType::Object); + j[sfLedgerHash] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -867,7 +865,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (arrayValue) { json::Value j; - j[sfLoanScale] = json::Value(json::ValueType::Array); + j[sfLoanScale] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -875,7 +873,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test bad_type (objectValue) { json::Value j; - j[sfLoanScale] = json::Value(json::ValueType::Object); + j[sfLoanScale] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -943,7 +941,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test array value for blob (should fail) { json::Value j; - j[sfPublicKey] = json::Value(json::ValueType::Array); + j[sfPublicKey] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -951,7 +949,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test object value for blob (should fail) { json::Value j; - j[sfPublicKey] = json::Value(json::ValueType::Object); + j[sfPublicKey] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -964,7 +962,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with valid array of hex strings for Vector256 { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append( "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCD" "EF"); @@ -985,7 +983,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test empty array for Vector256 (should be valid, size 0) { json::Value j; - json::Value const arr(json::ValueType::Array); + json::Value const arr(json::ArrayValue); j[sfHashes] = arr; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); @@ -999,7 +997,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test array with invalid hex string (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append("nothexstring"); j[sfHashes] = arr; STParsedJSONObject const obj("Test", j); @@ -1009,7 +1007,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test array with string of wrong length (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append("0123456789ABCDEF"); // too short for uint256 j[sfHashes] = arr; STParsedJSONObject const obj("Test", j); @@ -1019,7 +1017,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test array with non-string element (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append(12345); j[sfHashes] = arr; STParsedJSONObject const obj("Test", j); @@ -1037,8 +1035,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test array with object element (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); - json::Value objElem(json::ValueType::Object); + json::Value arr(json::ArrayValue); + json::Value objElem(json::ObjectValue); objElem["foo"] = "bar"; arr.append(objElem); j[sfHashes] = arr; @@ -1121,7 +1119,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for AccountID (should fail) { json::Value j; - j[sfAccount] = json::Value(json::ValueType::Array); + j[sfAccount] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1129,7 +1127,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for AccountID (should fail) { json::Value j; - j[sfAccount] = json::Value(json::ValueType::Object); + j[sfAccount] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1231,7 +1229,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Array value for currency (should fail) { json::Value j; - j[sfBaseAsset] = json::Value(json::ValueType::Array); + j[sfBaseAsset] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1239,7 +1237,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Object value for currency (should fail) { json::Value j; - j[sfBaseAsset] = json::Value(json::ValueType::Object); + j[sfBaseAsset] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1300,7 +1298,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with object value for Amount (should fail) { json::Value j; - j[sfAmount] = json::Value(json::ValueType::Object); + j[sfAmount] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1313,13 +1311,13 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid test: single path with single element { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["account"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; elem["currency"] = "USD"; elem["issuer"] = "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject obj("Test", j); @@ -1345,13 +1343,13 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid test: non-standard currency code { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["account"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; elem["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; elem["issuer"] = "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject obj("Test", j); @@ -1374,7 +1372,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with array containing non-array element (should fail) { json::Value j; - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append("notanarray"); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1385,9 +1383,9 @@ class STParsedJSON_test : public beast::unit_test::Suite // fail) { json::Value j; - json::Value path(json::ValueType::Array); + json::Value path(json::ArrayValue); path.append("notanobject"); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1398,11 +1396,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["foo"] = "bar"; // not a valid path element key path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1413,11 +1411,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // value (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["account"] = "notAValidBase58Account"; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1427,11 +1425,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with account not string (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["account"] = 12345; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1441,11 +1439,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with currency not string (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["currency"] = 12345; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1455,11 +1453,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with non-standard currency not hex (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["currency"] = "notAValidCurrency"; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1469,11 +1467,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with issuer not string (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["issuer"] = 12345; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1483,11 +1481,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with issuer not base58 (should fail) { json::Value j; - json::Value path(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value path(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["issuer"] = "notAValidBase58Account"; path.append(elem); - json::Value pathset(json::ValueType::Array); + json::Value pathset(json::ArrayValue); pathset.append(path); j[sfPaths] = pathset; STParsedJSONObject const obj("Test", j); @@ -1502,7 +1500,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid Issue: currency and issuer as base58 { json::Value j; - json::Value issueJson(json::ValueType::Object); + json::Value issueJson(json::ObjectValue); issueJson["currency"] = "USD"; issueJson["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issueJson; @@ -1525,7 +1523,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid Issue: currency as hex { json::Value j; - json::Value issueJson(json::ValueType::Object); + json::Value issueJson(json::ObjectValue); issueJson["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; issueJson["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issueJson; @@ -1543,7 +1541,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid Issue: MPTID { json::Value j; - json::Value issueJson(json::ValueType::Object); + json::Value issueJson(json::ObjectValue); issueJson["mpt_issuance_id"] = "0000000000000000000000004D5054494431323334234234"; j[sfAsset] = issueJson; STParsedJSONObject obj("Test", j); @@ -1559,7 +1557,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: missing currency { json::Value j; - json::Value issue(json::ValueType::Object); + json::Value issue(json::ObjectValue); issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; STParsedJSONObject const obj("Test", j); @@ -1569,7 +1567,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: missing issuer { json::Value j; - json::Value issue(json::ValueType::Object); + json::Value issue(json::ObjectValue); issue["currency"] = "USD"; j[sfAsset] = issue; STParsedJSONObject const obj("Test", j); @@ -1579,7 +1577,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: currency too long { json::Value j; - json::Value issue(json::ValueType::Object); + json::Value issue(json::ObjectValue); issue["currency"] = "USDD"; issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; @@ -1590,7 +1588,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: issuer not base58 or hex { json::Value j; - json::Value issue(json::ValueType::Object); + json::Value issue(json::ObjectValue); issue["currency"] = "USD"; issue["issuer"] = "notAValidIssuer"; j[sfAsset] = issue; @@ -1601,8 +1599,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: currency not string { json::Value j; - json::Value issue(json::ValueType::Object); - issue["currency"] = json::Value(json::ValueType::Array); + json::Value issue(json::ObjectValue); + issue["currency"] = json::Value(json::ArrayValue); issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; STParsedJSONObject const obj("Test", j); @@ -1612,9 +1610,9 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid Issue: issuer not string { json::Value j; - json::Value issue(json::ValueType::Object); + json::Value issue(json::ObjectValue); issue["currency"] = "USD"; - issue["issuer"] = json::Value(json::ValueType::Object); + issue["issuer"] = json::Value(json::ObjectValue); j[sfAsset] = issue; STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); @@ -1636,11 +1634,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid XChainBridge { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value issuingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value issuingChainIssue(json::ObjectValue); issuingChainIssue["currency"] = "USD"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1661,11 +1659,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Valid XChainBridge: issues as hex currency { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value issuingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value issuingChainIssue(json::ObjectValue); issuingChainIssue["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1686,8 +1684,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: missing LockingChainIssue { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value issuingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value issuingChainIssue(json::ObjectValue); issuingChainIssue["currency"] = "USD"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["IssuingChainIssue"] = issuingChainIssue; @@ -1701,8 +1699,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: missing IssuingChainIssue { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value lockingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1716,12 +1714,12 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: missing LockingChainDoor { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value issuingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value issuingChainIssue(json::ObjectValue); issuingChainIssue["currency"] = "USD"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["IssuingChainIssue"] = issuingChainIssue; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1734,12 +1732,12 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: missing IssuingChainDoor { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value issuingChainIssue(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value issuingChainIssue(json::ObjectValue); issuingChainIssue["currency"] = "USD"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["IssuingChainIssue"] = issuingChainIssue; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1752,7 +1750,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: IssuingChainIssue not an object { json::Value j; - json::Value bridge(json::ValueType::Object); + json::Value bridge(json::ObjectValue); bridge["LockingChainIssue"] = "notanobject"; bridge["IssuingChainIssue"] = "notanobject"; j[sfXChainBridge] = bridge; @@ -1763,10 +1761,10 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: IssuingChainIssue missing currency { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value asset(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value asset(json::ObjectValue); asset["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1779,10 +1777,10 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: asset missing issuer { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value asset(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value asset(json::ObjectValue); asset["currency"] = "USD"; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1795,11 +1793,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid XChainBridge: asset issuer not base58 { json::Value j; - json::Value bridge(json::ValueType::Object); - json::Value asset(json::ValueType::Object); + json::Value bridge(json::ObjectValue); + json::Value asset(json::ObjectValue); asset["currency"] = "USD"; asset["issuer"] = "notAValidBase58Account"; - json::Value lockingChainIssue(json::ValueType::Object); + json::Value lockingChainIssue(json::ObjectValue); lockingChainIssue["currency"] = "EUR"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; @@ -1905,7 +1903,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid array value for STNumber { json::Value j; - j[sfNumber] = json::Value(json::ValueType::Array); + j[sfNumber] = json::Value(json::ArrayValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1913,7 +1911,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Invalid object value for STNumber { json::Value j; - j[sfNumber] = json::Value(json::ValueType::Object); + j[sfNumber] = json::Value(json::ObjectValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1934,7 +1932,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with valid object for Object { json::Value j; - json::Value objVal(json::ValueType::Object); + json::Value objVal(json::ObjectValue); objVal[sfTransactionResult] = 1; j[sfTransactionMetaData] = objVal; STParsedJSONObject obj("Test", j); @@ -1957,7 +1955,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with array value for Object (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append(1); j[sfTransactionMetaData] = arr; STParsedJSONObject const obj("Test", j); @@ -1967,7 +1965,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with null value for Object (should fail) { json::Value j; - j[sfTransactionMetaData] = json::Value(json::ValueType::Null); + j[sfTransactionMetaData] = json::Value(json::NullValue); STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1976,11 +1974,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // max depth is 64 { json::Value j; - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); json::Value* current = &obj; for (int i = 0; i < 63; ++i) { - json::Value const next(json::ValueType::Object); + json::Value const next(json::ObjectValue); (*current)[sfTransactionMetaData] = next; current = &((*current)[sfTransactionMetaData]); } @@ -1995,11 +1993,11 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with depth exceeding maxDepth (should fail) { json::Value j; - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); json::Value* current = &obj; for (int i = 0; i < 64; ++i) { - json::Value const next(json::ValueType::Object); + json::Value const next(json::ObjectValue); (*current)[sfTransactionMetaData] = next; current = &((*current)[sfTransactionMetaData]); } @@ -2017,10 +2015,10 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with valid array for Array { json::Value j; - json::Value arr(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value arr(json::ArrayValue); + json::Value elem(json::ObjectValue); elem[sfTransactionResult] = 2; - json::Value elem2(json::ValueType::Object); + json::Value elem2(json::ObjectValue); elem2[sfTransactionMetaData] = elem; arr.append(elem2); j[sfSignerEntries] = arr; @@ -2040,7 +2038,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with array containing non-object element (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); + json::Value arr(json::ArrayValue); arr.append("notanobject"); j[sfSignerEntries] = arr; STParsedJSONObject const obj("Test", j); @@ -2050,8 +2048,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with array containing object with invalid field (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value arr(json::ArrayValue); + json::Value elem(json::ObjectValue); elem["invalidField"] = 1; arr.append(elem); j[sfSignerEntries] = arr; @@ -2062,8 +2060,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with array containing object with multiple keys (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value arr(json::ArrayValue); + json::Value elem(json::ObjectValue); elem[sfTransactionResult] = 2; elem[sfNetworkID] = 3; arr.append(elem); @@ -2084,8 +2082,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // (should fail) { json::Value j; - json::Value arr(json::ValueType::Array); - json::Value elem(json::ValueType::Object); + json::Value arr(json::ArrayValue); + json::Value elem(json::ObjectValue); elem[sfTransactionResult] = "notanint"; arr.append(elem); j[sfSignerEntries] = arr; @@ -2096,7 +2094,7 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with empty array for Array (should be valid) { json::Value j; - json::Value const arr(json::ValueType::Array); + json::Value const arr(json::ArrayValue); j[sfSignerEntries] = arr; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); @@ -2107,8 +2105,8 @@ class STParsedJSON_test : public beast::unit_test::Suite // Test with object provided but not object SField { json::Value j; - json::Value obj(json::ValueType::Array); - obj.append(json::Value(json::ValueType::Object)); + json::Value obj(json::ArrayValue); + obj.append(json::Value(json::ObjectValue)); obj[0u][sfTransactionResult] = 1; j[sfSignerEntries] = obj; STParsedJSONObject const parsed("Test", j); @@ -2175,7 +2173,7 @@ class STParsedJSON_test : public beast::unit_test::Suite { std::string const& serialized( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - to_string(parsed.object->getJson(JsonOptions::Values::None))); + to_string(parsed.object->getJson(JsonOptions::KNone))); BEAST_EXPECT(serialized == goodJson); } } @@ -2200,7 +2198,7 @@ class STParsedJSON_test : public beast::unit_test::Suite { std::string const& serialized( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - to_string(parsed.object->getJson(JsonOptions::Values::None))); + to_string(parsed.object->getJson(JsonOptions::KNone))); BEAST_EXPECT(serialized == expectedJson); } } @@ -2225,7 +2223,7 @@ class STParsedJSON_test : public beast::unit_test::Suite { std::string const& serialized( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - to_string(parsed.object->getJson(JsonOptions::Values::None))); + to_string(parsed.object->getJson(JsonOptions::KNone))); BEAST_EXPECT(serialized == expectedJson); } } @@ -2334,7 +2332,7 @@ class STParsedJSON_test : public beast::unit_test::Suite { std::string const& serialized( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - to_string(parsed.object->getJson(JsonOptions::Values::None))); + to_string(parsed.object->getJson(JsonOptions::KNone))); BEAST_EXPECT(serialized == expectedJson); } } diff --git a/src/test/protocol/STTx_test.cpp b/src/test/protocol/STTx_test.cpp index 21518d1406..87cbb56a6b 100644 --- a/src/test/protocol/STTx_test.cpp +++ b/src/test/protocol/STTx_test.cpp @@ -66,12 +66,12 @@ public: { testcase("Malformed serialized form"); - static constexpr unsigned char kPayload1[] = { + constexpr unsigned char kPAYLOAD1[] = { 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}; - static constexpr unsigned char kPayload2[] = { + constexpr unsigned char kPAYLOAD2[] = { 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, @@ -1063,7 +1063,7 @@ public: 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x43, 0x3b, 0x3b, 0xff, 0x3b, 0x12, 0xf1, 0x12, 0x12, 0x12, 0xff}; - static constexpr unsigned char kPayload3[] = { + constexpr unsigned char kPAYLOAD3[] = { 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, @@ -1083,7 +1083,7 @@ public: 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}; - static constexpr unsigned char kPayload4[] = { + constexpr unsigned char kPAYLOAD4[] = { 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, @@ -1279,7 +1279,7 @@ public: // from earlier versions results in "Unknown field". Either way, // we expect an exception from STTx, but the specific message will // vary. - BEAST_EXPECT(!tx2.ParseFromArray(kPayload1, sizeof(kPayload1))); + BEAST_EXPECT(!tx2.ParseFromArray(kPAYLOAD1, sizeof(kPAYLOAD1))); xrpl::SerialIter sit(xrpl::makeSlice(tx2.rawtransaction())); @@ -1293,7 +1293,7 @@ public: try { - xrpl::SerialIter sit{kPayload2}; + xrpl::SerialIter sit{kPAYLOAD2}; auto stx = std::make_shared(sit); fail("An exception should have been thrown"); } @@ -1304,7 +1304,7 @@ public: try { - xrpl::SerialIter sit{kPayload3}; + xrpl::SerialIter sit{kPAYLOAD3}; auto stx = std::make_shared(sit); fail("An exception should have been thrown"); } @@ -1315,7 +1315,7 @@ public: try { - xrpl::SerialIter sit{kPayload4}; + xrpl::SerialIter sit{kPAYLOAD4}; auto stx = std::make_shared(sit); fail("An exception should have been thrown"); } @@ -1352,8 +1352,8 @@ public: if (copy != j) { - log << "j=" << j.getJson(JsonOptions::Values::None) << '\n' - << "copy=" << copy.getJson(JsonOptions::Values::None) << std::endl; + log << "j=" << j.getJson(JsonOptions::KNone) << '\n' + << "copy=" << copy.getJson(JsonOptions::KNone) << std::endl; fail("Transaction fails serialize/deserialize test"); } else @@ -1361,15 +1361,15 @@ public: pass(); } - STParsedJSONObject parsed("test", j.getJson(JsonOptions::Values::None)); + STParsedJSONObject parsed("test", j.getJson(JsonOptions::KNone)); if (!parsed.object.has_value()) { fail("Unable to build object from json"); } else if (STObject(j) != parsed.object) { - log << "ORIG: " << j.getJson(JsonOptions::Values::None) << '\n' - << "BUILT " << parsed.object->getJson(JsonOptions::Values::None) << std::endl; + log << "ORIG: " << j.getJson(JsonOptions::KNone) << '\n' + << "BUILT " << parsed.object->getJson(JsonOptions::KNone) << std::endl; fail("Built a different transaction"); } else @@ -1390,7 +1390,7 @@ public: // Lambda that returns a Payment STObject. auto getPayment = [kp1, id1, id2]() { // Account id1 pays account id2 10,000 XRP. - STObject payment(sfGeneric); + STObject payment(kSF_GENERIC); payment.setFieldU16(sfTransactionType, ttPAYMENT); payment.setAccountID(sfAccount, id1); payment.setAccountID(sfDestination, id2); diff --git a/src/test/protocol/STValidation_test.cpp b/src/test/protocol/STValidation_test.cpp index e42411bd3f..6ad0f92b42 100644 --- a/src/test/protocol/STValidation_test.cpp +++ b/src/test/protocol/STValidation_test.cpp @@ -22,7 +22,7 @@ namespace xrpl { class STValidation_test : public beast::unit_test::Suite { // No public key: - static constexpr std::uint8_t kPayload1[] = { + static constexpr std::uint8_t kPAYLOAD1[] = { 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, @@ -36,7 +36,7 @@ class STValidation_test : public beast::unit_test::Suite 0x8E, 0x09, 0x11, 0x52, 0x28, 0x5A, 0x48, 0x8F, 0x98, 0x7A, 0x5A, 0x10, 0x74, 0xCC}; // Short public key: - static constexpr std::uint8_t kPayload2[] = { + static constexpr std::uint8_t kPAYLOAD2[] = { 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, @@ -52,7 +52,7 @@ class STValidation_test : public beast::unit_test::Suite 0xD7, 0xFF, 0x83, 0x9D, 0xEF, 0x7D, 0xF7, 0x6A}; // Long public key: - static constexpr std::uint8_t kPayload3[] = { + static constexpr std::uint8_t kPAYLOAD3[] = { 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, @@ -68,7 +68,7 @@ class STValidation_test : public beast::unit_test::Suite 0xEF, 0x4C, 0x73, 0xB3, 0xFF, 0xFE, 0xA9, 0x8E, 0x92, 0xE8}; // Ed25519 public key: - static constexpr std::uint8_t kPayload4[] = { + static constexpr std::uint8_t kPAYLOAD4[] = { 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, @@ -84,7 +84,7 @@ class STValidation_test : public beast::unit_test::Suite 0x7E, 0x84, 0x09}; // No ledger sequence: - static constexpr std::uint8_t kPayload5[] = { + static constexpr std::uint8_t kPAYLOAD5[] = { 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, @@ -100,7 +100,7 @@ class STValidation_test : public beast::unit_test::Suite 0xEA, 0x5F, 0xD9, 0xC7, 0xAA}; // No sign time: - static constexpr std::uint8_t kPayload6[] = { + static constexpr std::uint8_t kPAYLOAD6[] = { 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, @@ -116,7 +116,7 @@ class STValidation_test : public beast::unit_test::Suite 0x23, 0xE2, 0x14, 0x80, 0x54}; // No signature field: - static constexpr std::uint8_t kPayload7[] = { + static constexpr std::uint8_t kPAYLOAD7[] = { 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, @@ -127,7 +127,7 @@ class STValidation_test : public beast::unit_test::Suite 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32}; // Good: - static constexpr std::uint8_t kPayload8[] = { + static constexpr std::uint8_t kPAYLOAD8[] = { 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, @@ -150,7 +150,7 @@ public: try { - SerialIter sit{kPayload8}; + SerialIter sit{kPAYLOAD8}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); @@ -172,7 +172,7 @@ public: try { - SerialIter sit{kPayload1}; + SerialIter sit{kPAYLOAD1}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); @@ -184,7 +184,7 @@ public: try { - SerialIter sit{kPayload2}; + SerialIter sit{kPAYLOAD2}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); @@ -196,7 +196,7 @@ public: try { - SerialIter sit{kPayload3}; + SerialIter sit{kPAYLOAD3}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); @@ -208,7 +208,7 @@ public: try { - SerialIter sit{kPayload4}; + SerialIter sit{kPAYLOAD4}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); @@ -222,7 +222,7 @@ public: try { - SerialIter sit{kPayload5}; + SerialIter sit{kPAYLOAD5}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); @@ -234,7 +234,7 @@ public: try { - SerialIter sit{kPayload6}; + SerialIter sit{kPAYLOAD6}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); @@ -246,7 +246,7 @@ public: try { - SerialIter sit{kPayload7}; + SerialIter sit{kPAYLOAD7}; auto val = std::make_shared( sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); @@ -262,7 +262,7 @@ public: // Mutate a known-good validation and expect it to fail: std::vector v; - for (auto c : kPayload8) + for (auto c : kPAYLOAD8) v.push_back(c); beast::xor_shift_engine g(148979842); diff --git a/src/test/protocol/SecretKey_test.cpp b/src/test/protocol/SecretKey_test.cpp index 967c4417eb..5dbb0727e8 100644 --- a/src/test/protocol/SecretKey_test.cpp +++ b/src/test/protocol/SecretKey_test.cpp @@ -301,7 +301,7 @@ public: { testcase("secp256k1: key derivation"); - for (auto const& test : kSecP256K1TestVectors) + for (auto const& test : kSECP256K1_TEST_VECTORS) { auto const id = parseBase58(test.addr); BEAST_EXPECT(id); @@ -320,7 +320,7 @@ public: { testcase("ed25519: key derivation"); - for (auto const& test : kED25519TestVectors) + for (auto const& test : kED25519_TEST_VECTORS) { auto const id = parseBase58(test.addr); BEAST_EXPECT(id); @@ -352,7 +352,7 @@ public: private: // clang-format off -inline static TestKeyData const kSecP256K1TestVectors[] = { +inline static TestKeyData const kSECP256K1_TEST_VECTORS[] = { {.seed={0xDE,0xDC,0xE9,0xCE,0x67,0xB4,0x51,0xD8,0x52,0xFD,0x4E,0x84,0x6F,0xCD,0xE3,0x1C}, .pubkey={0x03,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}, @@ -925,7 +925,7 @@ inline static TestKeyData const kSecP256K1TestVectors[] = { .addr="rsYryUWhbYRiQivh693pgjnseAwPHezNj1"} }; -inline static TestKeyData const kED25519TestVectors[] = { +inline static TestKeyData const kED25519_TEST_VECTORS[] = { {.seed={0xAF,0x41,0xFF,0x66,0xF7,0x5E,0xBD,0x3A,0x6B,0x18,0xFB,0x7A,0x1D,0xF6,0x1C,0x97}, .pubkey={0xED,0x48,0xCB,0xBB,0xE0,0xEE,0x7B,0x86,0x86,0xA7,0xDE,0x9F,0x0A,0x01,0x59,0x73, 0x4E,0x65,0xF9,0xC3,0x69,0x94,0x7F,0x2E,0x26,0x96,0x23,0x2B,0x46,0x1E,0x55,0x32,0x13}, diff --git a/src/test/protocol/SeqProxy_test.cpp b/src/test/protocol/SeqProxy_test.cpp index 90345ddc22..7da5751506 100644 --- a/src/test/protocol/SeqProxy_test.cpp +++ b/src/test/protocol/SeqProxy_test.cpp @@ -64,157 +64,157 @@ 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 kUintMax{std::numeric_limits::max()}; - static constexpr SeqProxy::Type kSeq{SeqProxy::Type::Seq}; - static constexpr SeqProxy::Type kTicket{SeqProxy::Type::Ticket}; + static constexpr std::uint32_t kUINT_MAX{std::numeric_limits::max()}; + static constexpr SeqProxy::Type kSEQ{SeqProxy::Type::Seq}; + static constexpr SeqProxy::Type kTICKET{SeqProxy::Type::Ticket}; - static constexpr SeqProxy kSeqZero{kSeq, 0}; - static constexpr SeqProxy kSeqSmall{kSeq, 1}; - static constexpr SeqProxy kSeqMiD0{kSeq, 2}; - static constexpr SeqProxy kSeqMiD1{kSeqMiD0}; - static constexpr SeqProxy kSeqBig{kSeq, kUintMax}; + static constexpr SeqProxy kSEQ_ZERO{kSEQ, 0}; + static constexpr SeqProxy kSEQ_SMALL{kSEQ, 1}; + static constexpr SeqProxy kSEQ_MID0{kSEQ, 2}; + static constexpr SeqProxy kSEQ_MID1{kSEQ_MID0}; + static constexpr SeqProxy kSEQ_BIG{kSEQ, kUINT_MAX}; - static constexpr SeqProxy kTicZero{kTicket, 0}; - static constexpr SeqProxy kTicSmall{kTicket, 1}; - static constexpr SeqProxy kTicMid0{kTicket, 2}; - static constexpr SeqProxy kTicMid1{kTicMid0}; - static constexpr SeqProxy kTicBig{kTicket, kUintMax}; + static constexpr SeqProxy kTIC_ZERO{kTICKET, 0}; + static constexpr SeqProxy kTIC_SMALL{kTICKET, 1}; + static constexpr SeqProxy kTIC_MID0{kTICKET, 2}; + static constexpr SeqProxy kTIC_MID1{kTIC_MID0}; + static constexpr SeqProxy kTIC_BIG{kTICKET, kUINT_MAX}; // Verify operation of value(), isSeq() and isTicket(). - static_assert(expectValues(kSeqZero, 0, kSeq), ""); - static_assert(expectValues(kSeqSmall, 1, kSeq), ""); - static_assert(expectValues(kSeqMiD0, 2, kSeq), ""); - static_assert(expectValues(kSeqMiD1, 2, kSeq), ""); - static_assert(expectValues(kSeqBig, kUintMax, kSeq), ""); + static_assert(expectValues(kSEQ_ZERO, 0, kSEQ), ""); + static_assert(expectValues(kSEQ_SMALL, 1, kSEQ), ""); + static_assert(expectValues(kSEQ_MID0, 2, kSEQ), ""); + static_assert(expectValues(kSEQ_MID1, 2, kSEQ), ""); + static_assert(expectValues(kSEQ_BIG, kUINT_MAX, kSEQ), ""); - static_assert(expectValues(kTicZero, 0, kTicket), ""); - static_assert(expectValues(kTicSmall, 1, kTicket), ""); - static_assert(expectValues(kTicMid0, 2, kTicket), ""); - static_assert(expectValues(kTicMid1, 2, kTicket), ""); - static_assert(expectValues(kTicBig, kUintMax, kTicket), ""); + static_assert(expectValues(kTIC_ZERO, 0, kTICKET), ""); + static_assert(expectValues(kTIC_SMALL, 1, kTICKET), ""); + static_assert(expectValues(kTIC_MID0, 2, kTICKET), ""); + static_assert(expectValues(kTIC_MID1, 2, kTICKET), ""); + static_assert(expectValues(kTIC_BIG, kUINT_MAX, kTICKET), ""); // Verify expected behavior of comparison operators. - static_assert(expectEq(kSeqZero, kSeqZero), ""); - static_assert(expectLt(kSeqZero, kSeqSmall), ""); - static_assert(expectLt(kSeqZero, kSeqMiD0), ""); - static_assert(expectLt(kSeqZero, kSeqMiD1), ""); - static_assert(expectLt(kSeqZero, kSeqBig), ""); - static_assert(expectLt(kSeqZero, kTicZero), ""); - static_assert(expectLt(kSeqZero, kTicSmall), ""); - static_assert(expectLt(kSeqZero, kTicMid0), ""); - static_assert(expectLt(kSeqZero, kTicMid1), ""); - static_assert(expectLt(kSeqZero, kTicBig), ""); + static_assert(expectEq(kSEQ_ZERO, kSEQ_ZERO), ""); + static_assert(expectLt(kSEQ_ZERO, kSEQ_SMALL), ""); + static_assert(expectLt(kSEQ_ZERO, kSEQ_MID0), ""); + static_assert(expectLt(kSEQ_ZERO, kSEQ_MID1), ""); + static_assert(expectLt(kSEQ_ZERO, kSEQ_BIG), ""); + static_assert(expectLt(kSEQ_ZERO, kTIC_ZERO), ""); + static_assert(expectLt(kSEQ_ZERO, kTIC_SMALL), ""); + static_assert(expectLt(kSEQ_ZERO, kTIC_MID0), ""); + static_assert(expectLt(kSEQ_ZERO, kTIC_MID1), ""); + static_assert(expectLt(kSEQ_ZERO, kTIC_BIG), ""); - static_assert(expectGt(kSeqSmall, kSeqZero), ""); - static_assert(expectEq(kSeqSmall, kSeqSmall), ""); - static_assert(expectLt(kSeqSmall, kSeqMiD0), ""); - static_assert(expectLt(kSeqSmall, kSeqMiD1), ""); - static_assert(expectLt(kSeqSmall, kSeqBig), ""); - static_assert(expectLt(kSeqSmall, kTicZero), ""); - static_assert(expectLt(kSeqSmall, kTicSmall), ""); - static_assert(expectLt(kSeqSmall, kTicMid0), ""); - static_assert(expectLt(kSeqSmall, kTicMid1), ""); - static_assert(expectLt(kSeqSmall, kTicBig), ""); + static_assert(expectGt(kSEQ_SMALL, kSEQ_ZERO), ""); + static_assert(expectEq(kSEQ_SMALL, kSEQ_SMALL), ""); + static_assert(expectLt(kSEQ_SMALL, kSEQ_MID0), ""); + static_assert(expectLt(kSEQ_SMALL, kSEQ_MID1), ""); + static_assert(expectLt(kSEQ_SMALL, kSEQ_BIG), ""); + static_assert(expectLt(kSEQ_SMALL, kTIC_ZERO), ""); + static_assert(expectLt(kSEQ_SMALL, kTIC_SMALL), ""); + static_assert(expectLt(kSEQ_SMALL, kTIC_MID0), ""); + static_assert(expectLt(kSEQ_SMALL, kTIC_MID1), ""); + static_assert(expectLt(kSEQ_SMALL, kTIC_BIG), ""); - static_assert(expectGt(kSeqMiD0, kSeqZero), ""); - static_assert(expectGt(kSeqMiD0, kSeqSmall), ""); - static_assert(expectEq(kSeqMiD0, kSeqMiD0), ""); - static_assert(expectEq(kSeqMiD0, kSeqMiD1), ""); - static_assert(expectLt(kSeqMiD0, kSeqBig), ""); - static_assert(expectLt(kSeqMiD0, kTicZero), ""); - static_assert(expectLt(kSeqMiD0, kTicSmall), ""); - static_assert(expectLt(kSeqMiD0, kTicMid0), ""); - static_assert(expectLt(kSeqMiD0, kTicMid1), ""); - static_assert(expectLt(kSeqMiD0, kTicBig), ""); + static_assert(expectGt(kSEQ_MID0, kSEQ_ZERO), ""); + static_assert(expectGt(kSEQ_MID0, kSEQ_SMALL), ""); + static_assert(expectEq(kSEQ_MID0, kSEQ_MID0), ""); + static_assert(expectEq(kSEQ_MID0, kSEQ_MID1), ""); + static_assert(expectLt(kSEQ_MID0, kSEQ_BIG), ""); + static_assert(expectLt(kSEQ_MID0, kTIC_ZERO), ""); + static_assert(expectLt(kSEQ_MID0, kTIC_SMALL), ""); + static_assert(expectLt(kSEQ_MID0, kTIC_MID0), ""); + static_assert(expectLt(kSEQ_MID0, kTIC_MID1), ""); + static_assert(expectLt(kSEQ_MID0, kTIC_BIG), ""); - static_assert(expectGt(kSeqMiD1, kSeqZero), ""); - static_assert(expectGt(kSeqMiD1, kSeqSmall), ""); - static_assert(expectEq(kSeqMiD1, kSeqMiD0), ""); - static_assert(expectEq(kSeqMiD1, kSeqMiD1), ""); - static_assert(expectLt(kSeqMiD1, kSeqBig), ""); - static_assert(expectLt(kSeqMiD1, kTicZero), ""); - static_assert(expectLt(kSeqMiD1, kTicSmall), ""); - static_assert(expectLt(kSeqMiD1, kTicMid0), ""); - static_assert(expectLt(kSeqMiD1, kTicMid1), ""); - static_assert(expectLt(kSeqMiD1, kTicBig), ""); + static_assert(expectGt(kSEQ_MID1, kSEQ_ZERO), ""); + static_assert(expectGt(kSEQ_MID1, kSEQ_SMALL), ""); + static_assert(expectEq(kSEQ_MID1, kSEQ_MID0), ""); + static_assert(expectEq(kSEQ_MID1, kSEQ_MID1), ""); + static_assert(expectLt(kSEQ_MID1, kSEQ_BIG), ""); + static_assert(expectLt(kSEQ_MID1, kTIC_ZERO), ""); + static_assert(expectLt(kSEQ_MID1, kTIC_SMALL), ""); + static_assert(expectLt(kSEQ_MID1, kTIC_MID0), ""); + static_assert(expectLt(kSEQ_MID1, kTIC_MID1), ""); + static_assert(expectLt(kSEQ_MID1, kTIC_BIG), ""); - static_assert(expectGt(kSeqBig, kSeqZero), ""); - static_assert(expectGt(kSeqBig, kSeqSmall), ""); - static_assert(expectGt(kSeqBig, kSeqMiD0), ""); - static_assert(expectGt(kSeqBig, kSeqMiD1), ""); - static_assert(expectEq(kSeqBig, kSeqBig), ""); - static_assert(expectLt(kSeqBig, kTicZero), ""); - static_assert(expectLt(kSeqBig, kTicSmall), ""); - static_assert(expectLt(kSeqBig, kTicMid0), ""); - static_assert(expectLt(kSeqBig, kTicMid1), ""); - static_assert(expectLt(kSeqBig, kTicBig), ""); + static_assert(expectGt(kSEQ_BIG, kSEQ_ZERO), ""); + static_assert(expectGt(kSEQ_BIG, kSEQ_SMALL), ""); + static_assert(expectGt(kSEQ_BIG, kSEQ_MID0), ""); + static_assert(expectGt(kSEQ_BIG, kSEQ_MID1), ""); + static_assert(expectEq(kSEQ_BIG, kSEQ_BIG), ""); + static_assert(expectLt(kSEQ_BIG, kTIC_ZERO), ""); + static_assert(expectLt(kSEQ_BIG, kTIC_SMALL), ""); + static_assert(expectLt(kSEQ_BIG, kTIC_MID0), ""); + static_assert(expectLt(kSEQ_BIG, kTIC_MID1), ""); + static_assert(expectLt(kSEQ_BIG, kTIC_BIG), ""); - static_assert(expectGt(kTicZero, kSeqZero), ""); - static_assert(expectGt(kTicZero, kSeqSmall), ""); - static_assert(expectGt(kTicZero, kSeqMiD0), ""); - static_assert(expectGt(kTicZero, kSeqMiD1), ""); - static_assert(expectGt(kTicZero, kSeqBig), ""); - static_assert(expectEq(kTicZero, kTicZero), ""); - static_assert(expectLt(kTicZero, kTicSmall), ""); - static_assert(expectLt(kTicZero, kTicMid0), ""); - static_assert(expectLt(kTicZero, kTicMid1), ""); - static_assert(expectLt(kTicZero, kTicBig), ""); + static_assert(expectGt(kTIC_ZERO, kSEQ_ZERO), ""); + static_assert(expectGt(kTIC_ZERO, kSEQ_SMALL), ""); + static_assert(expectGt(kTIC_ZERO, kSEQ_MID0), ""); + static_assert(expectGt(kTIC_ZERO, kSEQ_MID1), ""); + static_assert(expectGt(kTIC_ZERO, kSEQ_BIG), ""); + static_assert(expectEq(kTIC_ZERO, kTIC_ZERO), ""); + static_assert(expectLt(kTIC_ZERO, kTIC_SMALL), ""); + static_assert(expectLt(kTIC_ZERO, kTIC_MID0), ""); + static_assert(expectLt(kTIC_ZERO, kTIC_MID1), ""); + static_assert(expectLt(kTIC_ZERO, kTIC_BIG), ""); - static_assert(expectGt(kTicSmall, kSeqZero), ""); - static_assert(expectGt(kTicSmall, kSeqSmall), ""); - static_assert(expectGt(kTicSmall, kSeqMiD0), ""); - static_assert(expectGt(kTicSmall, kSeqMiD1), ""); - static_assert(expectGt(kTicSmall, kSeqBig), ""); - static_assert(expectGt(kTicSmall, kTicZero), ""); - static_assert(expectEq(kTicSmall, kTicSmall), ""); - static_assert(expectLt(kTicSmall, kTicMid0), ""); - static_assert(expectLt(kTicSmall, kTicMid1), ""); - static_assert(expectLt(kTicSmall, kTicBig), ""); + static_assert(expectGt(kTIC_SMALL, kSEQ_ZERO), ""); + static_assert(expectGt(kTIC_SMALL, kSEQ_SMALL), ""); + static_assert(expectGt(kTIC_SMALL, kSEQ_MID0), ""); + static_assert(expectGt(kTIC_SMALL, kSEQ_MID1), ""); + static_assert(expectGt(kTIC_SMALL, kSEQ_BIG), ""); + static_assert(expectGt(kTIC_SMALL, kTIC_ZERO), ""); + static_assert(expectEq(kTIC_SMALL, kTIC_SMALL), ""); + static_assert(expectLt(kTIC_SMALL, kTIC_MID0), ""); + static_assert(expectLt(kTIC_SMALL, kTIC_MID1), ""); + static_assert(expectLt(kTIC_SMALL, kTIC_BIG), ""); - static_assert(expectGt(kTicMid0, kSeqZero), ""); - static_assert(expectGt(kTicMid0, kSeqSmall), ""); - static_assert(expectGt(kTicMid0, kSeqMiD0), ""); - static_assert(expectGt(kTicMid0, kSeqMiD1), ""); - static_assert(expectGt(kTicMid0, kSeqBig), ""); - static_assert(expectGt(kTicMid0, kTicZero), ""); - static_assert(expectGt(kTicMid0, kTicSmall), ""); - static_assert(expectEq(kTicMid0, kTicMid0), ""); - static_assert(expectEq(kTicMid0, kTicMid1), ""); - static_assert(expectLt(kTicMid0, kTicBig), ""); + static_assert(expectGt(kTIC_MID0, kSEQ_ZERO), ""); + static_assert(expectGt(kTIC_MID0, kSEQ_SMALL), ""); + static_assert(expectGt(kTIC_MID0, kSEQ_MID0), ""); + static_assert(expectGt(kTIC_MID0, kSEQ_MID1), ""); + static_assert(expectGt(kTIC_MID0, kSEQ_BIG), ""); + static_assert(expectGt(kTIC_MID0, kTIC_ZERO), ""); + static_assert(expectGt(kTIC_MID0, kTIC_SMALL), ""); + static_assert(expectEq(kTIC_MID0, kTIC_MID0), ""); + static_assert(expectEq(kTIC_MID0, kTIC_MID1), ""); + static_assert(expectLt(kTIC_MID0, kTIC_BIG), ""); - static_assert(expectGt(kTicMid1, kSeqZero), ""); - static_assert(expectGt(kTicMid1, kSeqSmall), ""); - static_assert(expectGt(kTicMid1, kSeqMiD0), ""); - static_assert(expectGt(kTicMid1, kSeqMiD1), ""); - static_assert(expectGt(kTicMid1, kSeqBig), ""); - static_assert(expectGt(kTicMid1, kTicZero), ""); - static_assert(expectGt(kTicMid1, kTicSmall), ""); - static_assert(expectEq(kTicMid1, kTicMid0), ""); - static_assert(expectEq(kTicMid1, kTicMid1), ""); - static_assert(expectLt(kTicMid1, kTicBig), ""); + static_assert(expectGt(kTIC_MID1, kSEQ_ZERO), ""); + static_assert(expectGt(kTIC_MID1, kSEQ_SMALL), ""); + static_assert(expectGt(kTIC_MID1, kSEQ_MID0), ""); + static_assert(expectGt(kTIC_MID1, kSEQ_MID1), ""); + static_assert(expectGt(kTIC_MID1, kSEQ_BIG), ""); + static_assert(expectGt(kTIC_MID1, kTIC_ZERO), ""); + static_assert(expectGt(kTIC_MID1, kTIC_SMALL), ""); + static_assert(expectEq(kTIC_MID1, kTIC_MID0), ""); + static_assert(expectEq(kTIC_MID1, kTIC_MID1), ""); + static_assert(expectLt(kTIC_MID1, kTIC_BIG), ""); - static_assert(expectGt(kTicBig, kSeqZero), ""); - static_assert(expectGt(kTicBig, kSeqSmall), ""); - static_assert(expectGt(kTicBig, kSeqMiD0), ""); - static_assert(expectGt(kTicBig, kSeqMiD1), ""); - static_assert(expectGt(kTicBig, kSeqBig), ""); - static_assert(expectGt(kTicBig, kTicZero), ""); - static_assert(expectGt(kTicBig, kTicSmall), ""); - static_assert(expectGt(kTicBig, kTicMid0), ""); - static_assert(expectGt(kTicBig, kTicMid1), ""); - static_assert(expectEq(kTicBig, kTicBig), ""); + static_assert(expectGt(kTIC_BIG, kSEQ_ZERO), ""); + static_assert(expectGt(kTIC_BIG, kSEQ_SMALL), ""); + static_assert(expectGt(kTIC_BIG, kSEQ_MID0), ""); + static_assert(expectGt(kTIC_BIG, kSEQ_MID1), ""); + static_assert(expectGt(kTIC_BIG, kSEQ_BIG), ""); + static_assert(expectGt(kTIC_BIG, kTIC_ZERO), ""); + static_assert(expectGt(kTIC_BIG, kTIC_SMALL), ""); + static_assert(expectGt(kTIC_BIG, kTIC_MID0), ""); + static_assert(expectGt(kTIC_BIG, kTIC_MID1), ""); + static_assert(expectEq(kTIC_BIG, kTIC_BIG), ""); // Verify streaming. - BEAST_EXPECT(streamTest(kSeqZero)); - BEAST_EXPECT(streamTest(kSeqSmall)); - BEAST_EXPECT(streamTest(kSeqMiD0)); - BEAST_EXPECT(streamTest(kSeqMiD1)); - BEAST_EXPECT(streamTest(kSeqBig)); - BEAST_EXPECT(streamTest(kTicZero)); - BEAST_EXPECT(streamTest(kTicSmall)); - BEAST_EXPECT(streamTest(kTicMid0)); - BEAST_EXPECT(streamTest(kTicMid1)); - BEAST_EXPECT(streamTest(kTicBig)); + BEAST_EXPECT(streamTest(kSEQ_ZERO)); + BEAST_EXPECT(streamTest(kSEQ_SMALL)); + BEAST_EXPECT(streamTest(kSEQ_MID0)); + BEAST_EXPECT(streamTest(kSEQ_MID1)); + BEAST_EXPECT(streamTest(kSEQ_BIG)); + BEAST_EXPECT(streamTest(kTIC_ZERO)); + BEAST_EXPECT(streamTest(kTIC_SMALL)); + BEAST_EXPECT(streamTest(kTIC_MID0)); + BEAST_EXPECT(streamTest(kTIC_MID1)); + BEAST_EXPECT(streamTest(kTIC_BIG)); } }; diff --git a/src/test/protocol/TER_test.cpp b/src/test/protocol/TER_test.cpp index af1cfced0e..d9028fa941 100644 --- a/src/test/protocol/TER_test.cpp +++ b/src/test/protocol/TER_test.cpp @@ -114,12 +114,12 @@ struct TER_test : public beast::unit_test::Suite // are not valid. // Examples of each kind of enum. - static auto const kTerEnums = std::make_tuple( + static auto const kTER_ENUMS = std::make_tuple( telLOCAL_ERROR, temMALFORMED, tefFAILURE, terRETRY, tesSUCCESS, tecCLAIM); - static int const kHiIndex{std::tuple_size_v - 1}; + static int const kHI_INDEX{std::tuple_size_v - 1}; // Verify that enums cannot be converted to other enum types. - testIterate(kTerEnums, *this); + testIterate(kTER_ENUMS, *this); // Lambda that verifies assignability and convertibility. auto isConvertible = [](auto from, auto to) { @@ -216,7 +216,7 @@ struct TER_test : public beast::unit_test::Suite // All of the TER-related types should be comparable. // Examples of all the types we expect to successfully compare. - static auto const kTers = std::make_tuple( + static auto const kTERS = std::make_tuple( telLOCAL_ERROR, temMALFORMED, tefFAILURE, @@ -225,11 +225,11 @@ struct TER_test : public beast::unit_test::Suite tecCLAIM, NotTEC{telLOCAL_ERROR}, TER{tecCLAIM}); - static int const kHiIndex{std::tuple_size_v - 1}; + static int const kHI_INDEX{std::tuple_size_v - 1}; // Verify that all types in the ters tuple can be compared with all // the other types in ters. - testIterate(kTers, *this); + testIterate(kTERS, *this); } void diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index de4575cb16..1f2dc8f4dc 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -86,7 +86,7 @@ public: TestLogic logic(j); - Charge const fee(kDropThreshold + 1); + Charge const fee(DropThreshold + 1); beast::IP::Endpoint const addr(beast::IP::Endpoint::fromString("192.0.2.2")); std::function const ep = limited @@ -179,7 +179,7 @@ public: using namespace std::chrono_literals; // Give Consumer time to become readmitted. Should never // exceed expiration time. - auto n = kSecondsUntilExpiration + 1s; + auto n = kSECONDS_UNTIL_EXPIRATION + 1s; while (--n > 0s) { ++logic.clock(); @@ -278,7 +278,7 @@ public: void run() override { - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("ResourceManager_test", *this); testDrop(journal, true); diff --git a/src/test/rpc/AccountCurrencies_test.cpp b/src/test/rpc/AccountCurrencies_test.cpp index cc7884cc36..5e8100f76f 100644 --- a/src/test/rpc/AccountCurrencies_test.cpp +++ b/src/test/rpc/AccountCurrencies_test.cpp @@ -62,9 +62,9 @@ class AccountCurrencies_test : public beast::unit_test::Suite testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } { @@ -80,9 +80,9 @@ class AccountCurrencies_test : public beast::unit_test::Suite testInvalidIdentParam(1); testInvalidIdentParam(1.1); testInvalidIdentParam(true); - testInvalidIdentParam(json::Value(json::ValueType::Null)); - testInvalidIdentParam(json::Value(json::ValueType::Object)); - testInvalidIdentParam(json::Value(json::ValueType::Array)); + testInvalidIdentParam(json::Value(json::NullValue)); + testInvalidIdentParam(json::Value(json::ObjectValue)); + testInvalidIdentParam(json::Value(json::ArrayValue)); } { diff --git a/src/test/rpc/AccountInfo_test.cpp b/src/test/rpc/AccountInfo_test.cpp index 385fc2f58a..2739b84d50 100644 --- a/src/test/rpc/AccountInfo_test.cpp +++ b/src/test/rpc/AccountInfo_test.cpp @@ -75,9 +75,9 @@ public: testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } { // Cannot pass a non-string into the `ident` param @@ -93,9 +93,9 @@ public: testInvalidIdentParam(1); testInvalidIdentParam(1.1); testInvalidIdentParam(true); - testInvalidIdentParam(json::Value(json::ValueType::Null)); - testInvalidIdentParam(json::Value(json::ValueType::Object)); - testInvalidIdentParam(json::Value(json::ValueType::Array)); + testInvalidIdentParam(json::Value(json::NullValue)); + testInvalidIdentParam(json::Value(json::ObjectValue)); + testInvalidIdentParam(json::Value(json::ArrayValue)); } } @@ -526,7 +526,7 @@ public: return res; }; - static constexpr std::array, 7> kAsFlags{ + static constexpr std::array, 7> kAS_FLAGS{ {{"defaultRipple", asfDefaultRipple}, {"depositAuth", asfDepositAuth}, {"disallowIncomingXRP", asfDisallowXRP}, @@ -535,7 +535,7 @@ public: {"requireAuthorization", asfRequireAuth}, {"requireDestinationTag", asfRequireDest}}}; - for (auto& asf : kAsFlags) + for (auto& asf : kAS_FLAGS) { // Clear a flag and check that account_info returns results // as expected @@ -555,13 +555,13 @@ public: } static constexpr std::array, 4> - kDisallowIncomingFlags{ + kDISALLOW_INCOMING_FLAGS{ {{"disallowIncomingCheck", asfDisallowIncomingCheck}, {"disallowIncomingNFTokenOffer", asfDisallowIncomingNFTokenOffer}, {"disallowIncomingPayChan", asfDisallowIncomingPayChan}, {"disallowIncomingTrustline", asfDisallowIncomingTrustline}}}; - for (auto& asf : kDisallowIncomingFlags) + for (auto& asf : kDISALLOW_INCOMING_FLAGS) { // Clear a flag and check that account_info returns results // as expected @@ -580,47 +580,47 @@ public: BEAST_EXPECT(f2.value()); // NOLINT(bugprone-unchecked-optional-access) } - static constexpr std::pair kAllowTrustLineClawbackFlag{ + static constexpr std::pair kALLOW_TRUST_LINE_CLAWBACK_FLAG{ "allowTrustLineClawback", asfAllowTrustLineClawback}; if (features[featureClawback]) { // must use bob's account because alice has noFreeze set - auto const f1 = getAccountFlag(kAllowTrustLineClawbackFlag.first, bob); + auto const f1 = getAccountFlag(kALLOW_TRUST_LINE_CLAWBACK_FLAG.first, bob); BEAST_EXPECT(f1.has_value()); BEAST_EXPECT(!f1.value()); // NOLINT(bugprone-unchecked-optional-access) // Set allowTrustLineClawback - env(fset(bob, kAllowTrustLineClawbackFlag.second)); + env(fset(bob, kALLOW_TRUST_LINE_CLAWBACK_FLAG.second)); env.close(); - auto const f2 = getAccountFlag(kAllowTrustLineClawbackFlag.first, bob); + auto const f2 = getAccountFlag(kALLOW_TRUST_LINE_CLAWBACK_FLAG.first, bob); BEAST_EXPECT(f2.has_value()); BEAST_EXPECT(f2.value()); // NOLINT(bugprone-unchecked-optional-access) } else { - BEAST_EXPECT(!getAccountFlag(kAllowTrustLineClawbackFlag.first, bob)); + BEAST_EXPECT(!getAccountFlag(kALLOW_TRUST_LINE_CLAWBACK_FLAG.first, bob)); } - static constexpr std::pair kAllowTrustLineLockingFlag{ + static constexpr std::pair kALLOW_TRUST_LINE_LOCKING_FLAG{ "allowTrustLineLocking", asfAllowTrustLineLocking}; if (features[featureTokenEscrow]) { - auto const f1 = getAccountFlag(kAllowTrustLineLockingFlag.first, bob); + auto const f1 = getAccountFlag(kALLOW_TRUST_LINE_LOCKING_FLAG.first, bob); BEAST_EXPECT(f1.has_value()); BEAST_EXPECT(!f1.value()); // NOLINT(bugprone-unchecked-optional-access) // Set allowTrustLineLocking - env(fset(bob, kAllowTrustLineLockingFlag.second)); + env(fset(bob, kALLOW_TRUST_LINE_LOCKING_FLAG.second)); env.close(); - auto const f2 = getAccountFlag(kAllowTrustLineLockingFlag.first, bob); + auto const f2 = getAccountFlag(kALLOW_TRUST_LINE_LOCKING_FLAG.first, bob); BEAST_EXPECT(f2.has_value()); BEAST_EXPECT(f2.value()); // NOLINT(bugprone-unchecked-optional-access) } else { - BEAST_EXPECT(!getAccountFlag(kAllowTrustLineLockingFlag.first, bob)); + BEAST_EXPECT(!getAccountFlag(kALLOW_TRUST_LINE_LOCKING_FLAG.first, bob)); } } diff --git a/src/test/rpc/AccountLines_test.cpp b/src/test/rpc/AccountLines_test.cpp index 8d55c5e19d..750ba9cc78 100644 --- a/src/test/rpc/AccountLines_test.cpp +++ b/src/test/rpc/AccountLines_test.cpp @@ -75,9 +75,9 @@ public: testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } Account const alice{"alice"}; { @@ -215,7 +215,7 @@ public: // Invalid index json::Value params; params[jss::account] = alice.human(); - params[jss::ledger_index] = json::ValueType::Object; + params[jss::ledger_index] = json::ObjectValue; auto const lines = env.rpc("json", "account_lines", to_string(params))[jss::result]; BEAST_EXPECT(lines[jss::error] == "invalidParams"); BEAST_EXPECT( @@ -528,7 +528,7 @@ public: jv[jss::TransactionType] = jss::PaymentChannelCreate; jv[jss::Account] = account.human(); jv[jss::Destination] = to.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv["SettleDelay"] = settleDelay.count(); jv["PublicKey"] = strHex(pk.slice()); return jv; @@ -554,8 +554,8 @@ public: env.close(); // Escrow, in each direction - env(escrow::create(alice, becky, XRP(1000)), escrow::kFinishTime(env.now() + 1s)); - env(escrow::create(becky, alice, XRP(1000)), escrow::kFinishTime(env.now() + 1s)); + env(escrow::create(alice, becky, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); + env(escrow::create(becky, alice, XRP(1000)), escrow::kFINISH_TIME(env.now() + 1s)); // Pay channels, in each direction env(payChan(alice, becky, XRP(1000), 100s, alice.pk())); @@ -618,7 +618,7 @@ public: // the list will be empty for most calls. auto getNextLine = [](Env& env, Account const& alice, std::optional const marker) { - json::Value params(json::ValueType::Object); + json::Value params(json::ObjectValue); params[jss::account] = alice.human(); params[jss::limit] = 1; if (marker) @@ -628,9 +628,9 @@ public: }; auto aliceLines = getNextLine(env, alice, std::nullopt); - static constexpr std::size_t kExpectedIterations = 16; - static constexpr std::size_t kExpectedLines = 2; - static constexpr std::size_t kExpectedNfTs = 1; + constexpr std::size_t kEXPECTED_ITERATIONS = 16; + constexpr std::size_t kEXPECTED_LINES = 2; + constexpr std::size_t kEXPECTED_NF_TS = 1; std::size_t foundLines = 0; auto hasMarker = [](auto const& aliceLines) { @@ -661,7 +661,7 @@ public: foundLines += aliceLines[jss::result][jss::lines].size(); ++iterations; } - BEAST_EXPECT(kExpectedLines == foundLines); + BEAST_EXPECT(kEXPECTED_LINES == foundLines); json::Value aliceObjectsParams2; aliceObjectsParams2[jss::account] = alice.human(); @@ -677,10 +677,10 @@ public: // this test will need to be updated. BEAST_EXPECT( aliceObjects[jss::result][jss::account_objects].size() == - iterations + kExpectedNfTs); + iterations + kEXPECTED_NF_TS); // If ledger object association ever changes, for whatever // reason, this test will need to be updated. - BEAST_EXPECTS(iterations == kExpectedIterations, std::to_string(iterations)); + BEAST_EXPECTS(iterations == kEXPECTED_ITERATIONS, std::to_string(iterations)); // Get becky's objects just to confirm that they're symmetrical json::Value beckyObjectsParams; diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 4307b7ab7f..6feec6334b 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -144,9 +144,9 @@ public: testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } // test error on malformed account string. { @@ -674,7 +674,7 @@ public: jvEscrow[jss::TransactionType] = jss::EscrowCreate; jvEscrow[jss::Account] = gw.human(); jvEscrow[jss::Destination] = gw.human(); - jvEscrow[jss::Amount] = XRP(100).value().getJson(JsonOptions::Values::None); + jvEscrow[jss::Amount] = XRP(100).value().getJson(JsonOptions::KNone); jvEscrow[sfFinishAfter.jsonName] = env.now().time_since_epoch().count() + 1; env(jvEscrow); env.close(); @@ -740,11 +740,11 @@ public: return scEnv.rpc("json", "account_objects", to_string(params)); }; - json::Value const resp = scEnvAcctObjs(Account::kMaster, jss::bridge); + json::Value const resp = scEnvAcctObjs(Account::kMASTER, jss::bridge); BEAST_EXPECT(acctObjsIsSize(resp, 1)); auto const& acctBridge = resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT(acctBridge[sfAccount.jsonName] == Account::kMaster.human()); + BEAST_EXPECT(acctBridge[sfAccount.jsonName] == Account::kMASTER.human()); BEAST_EXPECT(acctBridge[sfLedgerEntryType.getJsonName()] == "Bridge"); BEAST_EXPECT(acctBridge[sfXChainClaimID.getJsonName()].asUInt() == 0); BEAST_EXPECT(acctBridge[sfXChainAccountClaimCount.getJsonName()].asUInt() == 0); @@ -800,7 +800,7 @@ public: // send first batch of account create attestations, so the // xchain_create_account_claim_id_ should be present on the door - // account (Account::kMaster) to collect the signatures until a + // account (Account::kMASTER) to collect the signatures until a // quorum is reached scEnv( test::jtx::createAccountAttestation( @@ -827,13 +827,13 @@ public: { // Find the xchain_create_account_claim_id_ json::Value const resp = - scEnvAcctObjs(Account::kMaster, jss::xchain_owned_create_account_claim_id); + scEnvAcctObjs(Account::kMASTER, jss::xchain_owned_create_account_claim_id); BEAST_EXPECT(acctObjsIsSize(resp, 1)); auto const& xchainCreateAccountClaimId = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT( - xchainCreateAccountClaimId[sfAccount.jsonName] == Account::kMaster.human()); + xchainCreateAccountClaimId[sfAccount.jsonName] == Account::kMASTER.human()); BEAST_EXPECT( xchainCreateAccountClaimId[sfXChainAccountCreateCount.getJsonName()].asUInt() == 1); @@ -860,7 +860,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::Values::None); + jvPayChan[jss::Amount] = XRP(300).value().getJson(JsonOptions::KNone); jvPayChan[sfSettleDelay.jsonName] = 24 * 60 * 60; jvPayChan[sfPublicKey.jsonName] = strHex(gw.pk().slice()); env(jvPayChan); @@ -1061,8 +1061,8 @@ public: Account const bob{"bob"}; env.fund(XRP(10000), bob); - static constexpr unsigned kNftsSize = 10; - for (unsigned i = 0; i < kNftsSize; i++) + static constexpr unsigned kNFTS_SIZE = 10; + for (unsigned i = 0; i < kNFTS_SIZE; i++) { env(token::mint(bob, 0)); } @@ -1180,9 +1180,9 @@ public: testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } } diff --git a/src/test/rpc/AccountOffers_test.cpp b/src/test/rpc/AccountOffers_test.cpp index 7c81bb55e9..8236439a37 100644 --- a/src/test/rpc/AccountOffers_test.cpp +++ b/src/test/rpc/AccountOffers_test.cpp @@ -212,9 +212,9 @@ public: testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } { diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index 421f6bd1fa..4de0928555 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -131,7 +131,7 @@ class AccountTx_test : public beast::unit_test::Suite using namespace test::jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })); Account const a1{"A1"}; @@ -374,9 +374,9 @@ class AccountTx_test : public beast::unit_test::Suite testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } // test binary and forward for bool/non bool values { @@ -449,13 +449,13 @@ class AccountTx_test : public beast::unit_test::Suite RPC::expectedFieldMessage(jss::limit, "unsigned integer")); // Test case: limit = [] should fail (array instead of integer) - p[jss::limit] = json::Value(json::ValueType::Array); + p[jss::limit] = json::Value(json::ArrayValue); BEAST_EXPECT( env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expectedFieldMessage(jss::limit, "unsigned integer")); // Test case: limit = {} should fail (object instead of integer) - p[jss::limit] = json::Value(json::ValueType::Object); + p[jss::limit] = json::Value(json::ObjectValue); BEAST_EXPECT( env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expectedFieldMessage(jss::limit, "unsigned integer")); @@ -467,7 +467,7 @@ class AccountTx_test : public beast::unit_test::Suite RPC::expectedFieldMessage(jss::limit, "unsigned integer")); // Test case: limit = ["limit"] should fail (array with string) - p[jss::limit] = json::Value(json::ValueType::Array); + 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] == @@ -475,7 +475,7 @@ class AccountTx_test : public beast::unit_test::Suite // Test case: limit = {"limit": 10} should fail (object with // property) - p[jss::limit] = json::Value(json::ValueType::Object); + 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] == @@ -537,7 +537,7 @@ class AccountTx_test : public beast::unit_test::Suite escrow[jss::TransactionType] = jss::EscrowCreate; escrow[jss::Account] = account.human(); escrow[jss::Destination] = to.human(); - escrow[jss::Amount] = amount.getJson(JsonOptions::Values::None); + escrow[jss::Amount] = amount.getJson(JsonOptions::KNone); return escrow; }; @@ -583,7 +583,7 @@ 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::Values::None); + payChanCreate[jss::Amount] = XRP(500).value().getJson(JsonOptions::KNone); payChanCreate[sfSettleDelay.jsonName] = NetClock::duration{100s}.count(); payChanCreate[sfPublicKey.jsonName] = strHex(alice.pk().slice()); env(payChanCreate, Sig(alie)); @@ -596,7 +596,7 @@ class AccountTx_test : public beast::unit_test::Suite payChanFund[jss::TransactionType] = jss::PaymentChannelFund; payChanFund[jss::Account] = alice.human(); payChanFund[sfChannel.jsonName] = payChanIndex; - payChanFund[jss::Amount] = XRP(200).value().getJson(JsonOptions::Values::None); + payChanFund[jss::Amount] = XRP(200).value().getJson(JsonOptions::KNone); env(payChanFund, Sig(alie)); env.close(); } @@ -651,7 +651,7 @@ class AccountTx_test : public beast::unit_test::Suite // clang-format off // Do a sanity check on each returned transaction. They should // be returned in the reverse order of application to the ledger. - static const NodeSanity kSanity[]{ + static const NodeSanity kSANITY[]{ // txType, created, deleted, modified {0, jss::DepositPreauth, {jss::DepositPreauth}, {jss::Ticket}, {jss::AccountRoot, jss::DirectoryNode}}, {1, jss::TicketCreate, {jss::Ticket}, {}, {jss::AccountRoot, jss::DirectoryNode}}, @@ -678,11 +678,11 @@ class AccountTx_test : public beast::unit_test::Suite }; // clang-format on - BEAST_EXPECT(std::size(kSanity) == result[jss::result][jss::transactions].size()); + BEAST_EXPECT(std::size(kSANITY) == result[jss::result][jss::transactions].size()); - for (unsigned int index{0}; index < std::size(kSanity); ++index) + for (unsigned int index{0}; index < std::size(kSANITY); ++index) { - checkSanity(txs[index], kSanity[index]); + checkSanity(txs[index], kSANITY[index]); } } @@ -733,7 +733,7 @@ class AccountTx_test : public beast::unit_test::Suite // // Note that the first two transactions in sanity have not occurred // yet. We'll see those after becky's account is resurrected. - static const NodeSanity kSanity[] + static const NodeSanity kSANITY[] { // txType, created, deleted, modified /* becky pays alice */ { 0, jss::Payment, {}, {}, {jss::AccountRoot, jss::AccountRoot}}, @@ -759,22 +759,22 @@ class AccountTx_test : public beast::unit_test::Suite BEAST_EXPECT(result[jss::result][jss::transactions].isArray()); // The first two transactions listed in sanity haven't happened yet. - static constexpr unsigned int kBeckyDeletedOffset = 2; + constexpr unsigned int kBECKY_DELETED_OFFSET = 2; BEAST_EXPECT( - std::size(kSanity) == - result[jss::result][jss::transactions].size() + kBeckyDeletedOffset); + std::size(kSANITY) == + result[jss::result][jss::transactions].size() + kBECKY_DELETED_OFFSET); json::Value const& txs{result[jss::result][jss::transactions]}; - for (unsigned int index = kBeckyDeletedOffset; index < std::size(kSanity); ++index) + for (unsigned int index = kBECKY_DELETED_OFFSET; index < std::size(kSANITY); ++index) { - checkSanity(txs[index - kBeckyDeletedOffset], kSanity[index]); + checkSanity(txs[index - kBECKY_DELETED_OFFSET], kSANITY[index]); } } // 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)) - drops(1)), + env(pay(alice, becky, drops(env.current()->fees().accountReserve(0)) - XRP(1)), Ter(tecNO_DST_INSUF_XRP)); env.close(); @@ -802,13 +802,13 @@ class AccountTx_test : public beast::unit_test::Suite BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result][jss::transactions].isArray()); - BEAST_EXPECT(std::size(kSanity) == result[jss::result][jss::transactions].size()); + BEAST_EXPECT(std::size(kSANITY) == result[jss::result][jss::transactions].size()); json::Value const& txs{result[jss::result][jss::transactions]}; - for (unsigned int index = 0; index < std::size(kSanity); ++index) + for (unsigned int index = 0; index < std::size(kSANITY); ++index) { - checkSanity(txs[index], kSanity[index]); + checkSanity(txs[index], kSANITY[index]); } } @@ -821,7 +821,7 @@ class AccountTx_test : public beast::unit_test::Suite using namespace std::chrono_literals; auto cfg = makeConfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); Account const alice{"alice"}; @@ -841,8 +841,7 @@ class AccountTx_test : public beast::unit_test::Suite auto const& tx0(jv[jss::transactions][0u][jss::tx]); BEAST_EXPECT(tx0[jss::TransactionType] == txType); - std::string const txHash{ - env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; BEAST_EXPECT(tx0[jss::hash] == txHash); }; diff --git a/src/test/rpc/AmendmentBlocked_test.cpp b/src/test/rpc/AmendmentBlocked_test.cpp index ae4fb99542..4e0daaef0d 100644 --- a/src/test/rpc/AmendmentBlocked_test.cpp +++ b/src/test/rpc/AmendmentBlocked_test.cpp @@ -75,7 +75,7 @@ class AmendmentBlocked_test : public beast::unit_test::Suite pfReq[jss::subcommand] = "create"; pfReq[jss::source_account] = alice.human(); pfReq[jss::destination_account] = bob.human(); - pfReq[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::Values::None); + pfReq[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::KNone); jr = wsc->invoke("path_find", pfReq)[jss::result]; BEAST_EXPECT( jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && @@ -140,7 +140,7 @@ class AmendmentBlocked_test : public beast::unit_test::Suite pfReq[jss::subcommand] = "create"; pfReq[jss::source_account] = alice.human(); pfReq[jss::destination_account] = bob.human(); - pfReq[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::Values::None); + pfReq[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::KNone); jr = wsc->invoke("path_find", pfReq)[jss::result]; BEAST_EXPECT( jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && diff --git a/src/test/rpc/BookChanges_test.cpp b/src/test/rpc/BookChanges_test.cpp index 98a9372982..182b569fde 100644 --- a/src/test/rpc/BookChanges_test.cpp +++ b/src/test/rpc/BookChanges_test.cpp @@ -99,8 +99,7 @@ public: env(pay(bob, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - std::string const txHash{ - env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString()}; json::Value const txResult = env.rpc("tx", txHash)[jss::result]; auto const ledgerIndex = txResult[jss::ledger_index].asInt(); diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 83f7b64b4b..d7de678933 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -76,9 +76,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; @@ -109,8 +109,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -153,9 +153,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; @@ -175,10 +175,10 @@ public: jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::Values::None)); + XRP(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerPays] == - usd(100).value().getJson(JsonOptions::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -192,8 +192,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -229,9 +229,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "XRP"; @@ -264,8 +264,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -278,8 +278,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::Values::None) && - t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone); })); } @@ -315,9 +315,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "XRP"; @@ -340,16 +340,16 @@ public: 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::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::asks][0u][jss::TakerPays] == - XRP(500).value().getJson(JsonOptions::Values::None)); + XRP(500).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::Values::None)); + XRP(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][0u][jss::TakerPays] == - usd(100).value().getJson(JsonOptions::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -362,8 +362,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -376,8 +376,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::Values::None) && - t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone); })); } @@ -408,16 +408,16 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; j[jss::taker_pays][jss::issuer] = Account("alice").human(); } { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "CNY"; j[jss::taker_gets][jss::issuer] = Account("alice").human(); @@ -449,8 +449,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -470,8 +470,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] == jpy(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == jpy(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::KNone); })); } @@ -522,16 +522,16 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; j[jss::taker_pays][jss::issuer] = Account("alice").human(); } { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "CNY"; j[jss::taker_gets][jss::issuer] = Account("alice").human(); @@ -552,16 +552,16 @@ public: jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 2); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::Values::None)); + XRP(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerPays] == - usd(100).value().getJson(JsonOptions::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][1u][jss::TakerGets] == - cny(200).value().getJson(JsonOptions::Values::None)); + cny(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][1u][jss::TakerPays] == - jpy(100).value().getJson(JsonOptions::Values::None)); + jpy(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -575,8 +575,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -596,8 +596,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] == jpy(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == jpy(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::KNone); })); } @@ -635,9 +635,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "XRP"; @@ -645,7 +645,7 @@ public: j[jss::taker_pays][jss::issuer] = Account("alice").human(); } { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "CNY"; @@ -679,8 +679,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -693,8 +693,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::Values::None) && - t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone); })); } @@ -707,8 +707,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] == jpy(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == jpy(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::KNone); })); } @@ -721,8 +721,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::Values::None) && - t[jss::TakerPays] == jpy(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == cny(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == jpy(100).value().getJson(JsonOptions::KNone); })); } @@ -766,9 +766,9 @@ public: { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "XRP"; @@ -777,7 +777,7 @@ public: } // RPC subscribe to books stream { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::both] = true; j[jss::taker_gets][jss::currency] = "CNY"; @@ -801,28 +801,28 @@ public: 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::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::asks][0u][jss::TakerPays] == - XRP(500).value().getJson(JsonOptions::Values::None)); + XRP(500).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::asks][1u][jss::TakerGets] == - jpy(100).value().getJson(JsonOptions::Values::None)); + jpy(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::asks][1u][jss::TakerPays] == - cny(500).value().getJson(JsonOptions::Values::None)); + cny(500).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::Values::None)); + XRP(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][0u][jss::TakerPays] == - usd(100).value().getJson(JsonOptions::Values::None)); + usd(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][1u][jss::TakerGets] == - cny(200).value().getJson(JsonOptions::Values::None)); + cny(200).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::bids][1u][jss::TakerPays] == - jpy(100).value().getJson(JsonOptions::Values::None)); + jpy(100).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -835,8 +835,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] == usd(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == usd(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::KNone); })); } @@ -849,8 +849,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::Values::None) && - t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == usd(100).value().getJson(JsonOptions::KNone); })); } @@ -863,8 +863,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] == jpy(100).value().getJson(JsonOptions::Values::None) && - t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == jpy(100).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == cny(700).value().getJson(JsonOptions::KNone); })); } @@ -877,8 +877,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::Values::None) && - t[jss::TakerPays] == jpy(100).value().getJson(JsonOptions::Values::None); + t[jss::TakerGets] == cny(75).value().getJson(JsonOptions::KNone) && + t[jss::TakerPays] == jpy(100).value().getJson(JsonOptions::KNone); })); } @@ -909,9 +909,9 @@ public: json::Value books; { - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; @@ -968,9 +968,8 @@ public: 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::Values::None)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::Values::None)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == usd(10).value().getJson(JsonOptions::KNone)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jrOffer[jss::owner_funds] == "100"); BEAST_EXPECT(jrOffer[jss::quality] == "400000000"); @@ -978,9 +977,9 @@ 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::Values::None) && + t[jss::TakerGets] == usd(10).value().getJson(JsonOptions::KNone) && t[jss::owner_funds] == "100" && - t[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::Values::None); + t[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::KNone); })); env(offer(bob, XRP(2000), usd(5))); @@ -989,9 +988,9 @@ 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::Values::None) && + t[jss::TakerGets] == usd(5).value().getJson(JsonOptions::KNone) && t[jss::owner_funds] == "50" && - t[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::Values::None); + t[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::KNone); })); jv = wsc->invoke("book_offers", jvParams); @@ -1013,10 +1012,8 @@ public: 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::Values::None)); - BEAST_EXPECT( - jrNextOffer[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::Values::None)); + BEAST_EXPECT(jrNextOffer[jss::TakerGets] == usd(5).value().getJson(JsonOptions::KNone)); + BEAST_EXPECT(jrNextOffer[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jrNextOffer[jss::owner_funds] == "50"); BEAST_EXPECT(jrNextOffer[jss::quality] == "400000000"); @@ -1047,8 +1044,8 @@ public: return false; auto const& t = (*maybeJv)[jss::transaction]; if (t[jss::TransactionType] != jss::OfferCreate || - t[jss::TakerGets] != takerGets.value().getJson(JsonOptions::Values::None) || - t[jss::TakerPays] != takerPays.value().getJson(JsonOptions::Values::None)) + t[jss::TakerGets] != takerGets.value().getJson(JsonOptions::KNone) || + t[jss::TakerPays] != takerPays.value().getJson(JsonOptions::KNone)) return false; // Make sure no other message is waiting return wsc->getMsg(timeout) == std::nullopt; @@ -1096,9 +1093,9 @@ public: json::Value books; { // RPC subscribe to books stream - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = false; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; @@ -1172,9 +1169,9 @@ public: { // RPC subscribe to multiple book streams - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = false; j[jss::taker_gets][jss::currency] = "XRP"; j[jss::taker_pays][jss::currency] = "USD"; @@ -1182,7 +1179,7 @@ public: } { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = false; j[jss::taker_gets][jss::currency] = "EUR"; j[jss::taker_gets][jss::issuer] = gw.human(); @@ -1236,7 +1233,7 @@ public: { json::Value jvParams; jvParams[jss::ledger_index] = "validated"; - jvParams[jss::taker_pays] = json::ValueType::Object; + jvParams[jss::taker_pays] = json::ObjectValue; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_gets'."); @@ -1246,7 +1243,7 @@ public: json::Value jvParams; jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays] = "not an object"; - jvParams[jss::taker_gets] = json::ValueType::Object; + jvParams[jss::taker_gets] = json::ObjectValue; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays', not object."); @@ -1255,7 +1252,7 @@ public: { json::Value jvParams; jvParams[jss::ledger_index] = "validated"; - jvParams[jss::taker_pays] = json::ValueType::Object; + 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]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); @@ -1265,8 +1262,8 @@ public: { json::Value jvParams; jvParams[jss::ledger_index] = "validated"; - jvParams[jss::taker_pays] = json::ValueType::Object; - jvParams[jss::taker_gets] = json::ValueType::Object; + 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]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_pays.currency'."); @@ -1276,7 +1273,7 @@ public: json::Value jvParams; jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = 1; - jvParams[jss::taker_gets] = json::ValueType::Object; + jvParams[jss::taker_gets] = json::ObjectValue; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT( @@ -1287,7 +1284,7 @@ public: json::Value jvParams; jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = "XRP"; - jvParams[jss::taker_gets] = json::ValueType::Object; + jvParams[jss::taker_gets] = json::ObjectValue; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_gets.currency'."); @@ -1548,7 +1545,7 @@ public: auto usd = gw["USD"]; - for (auto i = 0; i <= RPC::Tuning::kBookOffers.rmax; i++) + for (auto i = 0; i <= RPC::Tuning::kBOOK_OFFERS.rmax; i++) env(offer(gw, XRP(50 + (1 * i)), usd(1.0 + (0.1 * i)))); if (asAdmin) @@ -1565,15 +1562,17 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == (asAdmin ? 1u : 0u)); // NOTE - a marker field is not returned for this method - jvParams[jss::limit] = RPC::Tuning::kBookOffers.rmax + 1; + jvParams[jss::limit] = RPC::Tuning::kBOOK_OFFERS.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::kBookOffers.rmax + 1 : 0u)); + BEAST_EXPECT( + jrr[jss::offers].size() == (asAdmin ? RPC::Tuning::kBOOK_OFFERS.rmax + 1 : 0u)); - jvParams[jss::limit] = json::ValueType::Null; + 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::kBookOffers.rDefault : 0u)); + BEAST_EXPECT( + jrr[jss::offers].size() == (asAdmin ? RPC::Tuning::kBOOK_OFFERS.rDefault : 0u)); } void @@ -1593,7 +1592,7 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.usd; + auto const usd = permDex.USD; auto wsc = makeWSClient(env.app().config()); @@ -1611,10 +1610,8 @@ public: 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::Values::None)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::Values::None)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == usd(10).value().getJson(JsonOptions::KNone)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); }; @@ -1638,10 +1635,10 @@ public: jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerGets] == - usd(10).value().getJson(JsonOptions::Values::None)); + usd(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::Values::None)); + XRP(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); @@ -1665,9 +1662,9 @@ public: // subscribe to domain book should return domain offer { json::Value books; - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_pays][jss::currency] = "XRP"; j[jss::taker_gets][jss::currency] = "USD"; @@ -1684,9 +1681,9 @@ public: // subscribe to open book should not return domain offer { json::Value books; - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_pays][jss::currency] = "XRP"; j[jss::taker_gets][jss::currency] = "USD"; @@ -1718,7 +1715,7 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.usd; + auto const usd = permDex.USD; auto wsc = makeWSClient(env.app().config()); @@ -1736,10 +1733,8 @@ public: 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::Values::None)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::Values::None)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == usd(10).value().getJson(JsonOptions::KNone)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT(jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); BEAST_EXPECT(jrOffer[sfAdditionalBooks.jsonName].size() == 1); }; @@ -1763,10 +1758,10 @@ public: jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerGets] == - usd(10).value().getJson(JsonOptions::Values::None)); + usd(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::Values::None)); + XRP(10).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); @@ -1790,9 +1785,9 @@ public: // subscribe to domain book should return hybrid offer { json::Value books; - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_pays][jss::currency] = "XRP"; j[jss::taker_gets][jss::currency] = "USD"; @@ -1814,9 +1809,9 @@ public: // subscribe to open book should return hybrid offer { json::Value books; - books[jss::books] = json::ValueType::Array; + books[jss::books] = json::ArrayValue; { - auto& j = books[jss::books].append(json::ValueType::Object); + auto& j = books[jss::books].append(json::ObjectValue); j[jss::snapshot] = true; j[jss::taker_pays][jss::currency] = "XRP"; j[jss::taker_gets][jss::currency] = "USD"; diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index ca5df7102e..213b4afd01 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -40,7 +40,7 @@ class CheckDeliveredAmount int numExpectedNotSet_ = 0; // Increment one of the expected numExpected{Available_, Unavailable_, - // NotSet_} values. Which value to kIncrement depends on: 1) If the ledger is + // NotSet_} values. Which value to kINCREMENT depends on: 1) If the ledger is // before or after the switch time 2) If the tx is a partial payment 3) If // the payment is successful or not void @@ -206,7 +206,7 @@ class DeliveredAmount_test : public beast::unit_test::Suite for (bool const afterSwitchTime : {true, false}) { auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); env.fund(XRP(10000), alice, bob, carol, gw); env.trust(usd(1000), alice, bob, carol); @@ -245,9 +245,9 @@ class DeliveredAmount_test : public beast::unit_test::Suite { json::Value stream; // RPC subscribe to ledger stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("ledger"); - stream[jss::accounts] = json::ValueType::Array; + stream[jss::accounts] = json::ArrayValue; stream[jss::accounts].append(toBase58(alice.id())); stream[jss::accounts].append(toBase58(bob.id())); stream[jss::accounts].append(toBase58(carol.id())); @@ -297,7 +297,7 @@ class DeliveredAmount_test : public beast::unit_test::Suite for (bool const afterSwitchTime : {true, false}) { auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); env.fund(XRP(10000), alice, bob, carol, gw); env.trust(usd(1000), alice, bob, carol); @@ -368,17 +368,15 @@ 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::Values::None)[jss::hash].asString()}; + std::string txHash{env.tx()->getJson(JsonOptions::KNone)[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::Values::None)); + meta[sfDeliveredAmount.jsonName] == STAmount{mpt(800)}.getJson(JsonOptions::KNone)); BEAST_EXPECT( - meta[jss::delivered_amount] == - STAmount{mpt(800)}.getJson(JsonOptions::Values::None)); + meta[jss::delivered_amount] == STAmount{mpt(800)}.getJson(JsonOptions::KNone)); } else { @@ -389,17 +387,15 @@ class DeliveredAmount_test : public beast::unit_test::Suite env(pay(bob, carol, mpt(1000)), Sendmax(mpt(1200)), Txflags(tfPartialPayment)); env.close(); - txHash = env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString(); + txHash = env.tx()->getJson(JsonOptions::KNone)[jss::hash].asString(); meta = env.rpc("tx", txHash)[jss::result][jss::meta]; if (features[fixMPTDeliveredAmount]) { BEAST_EXPECT( - meta[sfDeliveredAmount.jsonName] == - STAmount{mpt(960)}.getJson(JsonOptions::Values::None)); + meta[sfDeliveredAmount.jsonName] == STAmount{mpt(960)}.getJson(JsonOptions::KNone)); BEAST_EXPECT( - meta[jss::delivered_amount] == - STAmount{mpt(960)}.getJson(JsonOptions::Values::None)); + meta[jss::delivered_amount] == STAmount{mpt(960)}.getJson(JsonOptions::KNone)); } else { diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index 89053557a7..542f1c2c85 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -32,7 +32,7 @@ public: std::string const& ledger = "", std::vector const& credentials = {}) { - json::Value args{json::ValueType::Object}; + json::Value args{json::ObjectValue}; args[jss::source_account] = source.human(); args[jss::destination_account] = dest.human(); if (!ledger.empty()) @@ -40,7 +40,7 @@ public: if (!credentials.empty()) { - auto& arr(args[jss::credentials] = json::ValueType::Array); + auto& arr(args[jss::credentials] = json::ArrayValue); for (auto const& s : credentials) arr.append(s); } @@ -331,7 +331,7 @@ public: testcase("deposit_authorized with credentials failure: empty array."); auto args = depositAuthArgs(alice, becky, "validated"); - args[jss::credentials] = json::ValueType::Array; + args[jss::credentials] = json::ArrayValue; auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); checkCredentialsResponse(jv[jss::result], alice, becky, false, {}, "invalidParams"); @@ -343,7 +343,7 @@ public: "credentials"); auto args = depositAuthArgs(alice, becky, "validated"); - args[jss::credentials] = json::ValueType::Array; + args[jss::credentials] = json::ArrayValue; args[jss::credentials].append(1); args[jss::credentials].append(3); @@ -357,7 +357,7 @@ public: "credentials"); auto args = depositAuthArgs(alice, becky, "validated"); - args[jss::credentials] = json::ValueType::Array; + args[jss::credentials] = json::ArrayValue; args[jss::credentials].append("hello world"); auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); @@ -415,7 +415,7 @@ public: } { - static std::vector const kCredIds = { + static std::vector const kCRED_IDS = { "18004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288BE4", "28004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288BE4", "38004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288BE4", @@ -426,15 +426,15 @@ public: "88004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288BE4", "98004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288BE4", }; - assert(kCredIds.size() > kMaxCredentialsArraySize); + assert(kCRED_IDS.size() > kMAX_CREDENTIALS_ARRAY_SIZE); testcase("deposit_authorized too long credentials"); auto const jv = env.rpc( "json", "deposit_authorized", - depositAuthArgs(alice, becky, "validated", kCredIds).toStyledString()); + depositAuthArgs(alice, becky, "validated", kCRED_IDS).toStyledString()); checkCredentialsResponse( - jv[jss::result], alice, becky, false, kCredIds, "invalidParams"); + jv[jss::result], alice, becky, false, kCRED_IDS, "invalidParams"); } { diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index d899b6dfd9..3eedc5fa14 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -208,35 +208,35 @@ class Feature_test : public beast::unit_test::Suite BEAST_EXPECT(jrr[jss::error_message] == "Feature unknown or invalid."); // Test feature name size checks - static constexpr auto kOK63Name = [] { + constexpr auto kOK63_NAME = [] { return "123456789012345678901234567890123456789012345678901234567890123"; }; - static_assert(validFeatureNameSize(kOK63Name)); + static_assert(validFeatureNameSize(kOK63_NAME)); - static constexpr auto kBaD64Name = [] { + constexpr auto kBAD64_NAME = [] { return "1234567890123456789012345678901234567890123456789012345678901234"; }; - static_assert(!validFeatureNameSize(kBaD64Name)); + static_assert(!validFeatureNameSize(kBAD64_NAME)); - static constexpr auto kOK31Name = [] { return "1234567890123456789012345678901"; }; - static_assert(validFeatureNameSize(kOK31Name)); + constexpr auto kOK31_NAME = [] { return "1234567890123456789012345678901"; }; + static_assert(validFeatureNameSize(kOK31_NAME)); - static constexpr auto kBaD32Name = [] { return "12345678901234567890123456789012"; }; - static_assert(!validFeatureNameSize(kBaD32Name)); + constexpr auto kBAD32_NAME = [] { return "12345678901234567890123456789012"; }; + static_assert(!validFeatureNameSize(kBAD32_NAME)); - static constexpr auto kOK33Name = [] { return "123456789012345678901234567890123"; }; - static_assert(validFeatureNameSize(kOK33Name)); + constexpr auto kOK33_NAME = [] { return "123456789012345678901234567890123"; }; + static_assert(validFeatureNameSize(kOK33_NAME)); // Test feature character set checks - static constexpr auto kOkName = [] { return "AMM_123"; }; - static_assert(validFeatureName(kOkName)); + constexpr auto kOK_NAME = [] { return "AMM_123"; }; + static_assert(validFeatureName(kOK_NAME)); // First character is Greek Capital Alpha, visually confusable with ASCII 'A' - static constexpr auto kBadName = [] { return "ΑMM_123"; }; - static_assert(!validFeatureName(kBadName)); + constexpr auto kBAD_NAME = [] { return "ΑMM_123"; }; + static_assert(!validFeatureName(kBAD_NAME)); - static constexpr auto kBadEmoji = [] { return "🔥"; }; - static_assert(!validFeatureName(kBadEmoji)); + constexpr auto kBAD_EMOJI = [] { return "🔥"; }; + static_assert(!validFeatureName(kBAD_EMOJI)); } void @@ -258,9 +258,9 @@ class Feature_test : public beast::unit_test::Suite testInvalidParam(1); testInvalidParam(1.1); testInvalidParam(true); - testInvalidParam(json::Value(json::ValueType::Null)); - testInvalidParam(json::Value(json::ValueType::Object)); - testInvalidParam(json::Value(json::ValueType::Array)); + testInvalidParam(json::Value(json::NullValue)); + testInvalidParam(json::Value(json::ObjectValue)); + testInvalidParam(json::Value(json::ArrayValue)); { auto jrr = env.rpc("feature", "AllTheThings")[jss::result]; @@ -474,40 +474,40 @@ class Feature_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, FeatureBitset{featurePriceOracle}}; - static constexpr char const* kFeatureName = "fixAMMOverflowOffer"; + constexpr char const* kFEATURE_NAME = "fixAMMOverflowOffer"; - auto jrr = env.rpc("feature", kFeatureName)[jss::result]; + auto jrr = env.rpc("feature", kFEATURE_NAME)[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) return; jrr.removeMember(jss::status); if (!BEAST_EXPECT(jrr.size() == 1)) return; auto feature = *(jrr.begin()); - BEAST_EXPECTS(feature[jss::name] == kFeatureName, "name"); + BEAST_EXPECTS(feature[jss::name] == kFEATURE_NAME, "name"); BEAST_EXPECTS(feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), "vetoed"); - jrr = env.rpc("feature", kFeatureName, "reject")[jss::result]; + jrr = env.rpc("feature", kFEATURE_NAME, "reject")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) return; jrr.removeMember(jss::status); if (!BEAST_EXPECT(jrr.size() == 1)) return; feature = *(jrr.begin()); - BEAST_EXPECTS(feature[jss::name] == kFeatureName, "name"); + BEAST_EXPECTS(feature[jss::name] == kFEATURE_NAME, "name"); BEAST_EXPECTS(feature[jss::vetoed].isBool() && feature[jss::vetoed].asBool(), "vetoed"); - jrr = env.rpc("feature", kFeatureName, "accept")[jss::result]; + jrr = env.rpc("feature", kFEATURE_NAME, "accept")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) return; jrr.removeMember(jss::status); if (!BEAST_EXPECT(jrr.size() == 1)) return; feature = *(jrr.begin()); - BEAST_EXPECTS(feature[jss::name] == kFeatureName, "name"); + BEAST_EXPECTS(feature[jss::name] == kFEATURE_NAME, "name"); BEAST_EXPECTS(feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), "vetoed"); // anything other than accept or reject is an error - jrr = env.rpc("feature", kFeatureName, "maybe"); + jrr = env.rpc("feature", kFEATURE_NAME, "maybe"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid parameters."); } diff --git a/src/test/rpc/GatewayBalances_test.cpp b/src/test/rpc/GatewayBalances_test.cpp index 106b9b5f1a..4f23db7b66 100644 --- a/src/test/rpc/GatewayBalances_test.cpp +++ b/src/test/rpc/GatewayBalances_test.cpp @@ -190,7 +190,7 @@ public: auto usd = alice["USD"]; // The largest valid STAmount of USD: - STAmount const maxUSD(usd, STAmount::kMaxValue, STAmount::kMaxOffset); + STAmount const maxUSD(usd, STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); // Create a hotwallet Account const hw{"hw"}; @@ -259,7 +259,7 @@ public: // Bob creates an escrow of MPT to Alice. auto const MPT = mpt["MPT"]; // NOLINT(readability-identifier-naming) - env(escrow::create(bob, alice, MPT(100)), escrow::kFinishTime(env.now() + 10s)); + env(escrow::create(bob, alice, MPT(100)), escrow::kFINISH_TIME(env.now() + 10s)); env.close(); // Query gateway_balances for Bob. diff --git a/src/test/rpc/GetAggregatePrice_test.cpp b/src/test/rpc/GetAggregatePrice_test.cpp index 37ecc54172..418b36d703 100644 --- a/src/test/rpc/GetAggregatePrice_test.cpp +++ b/src/test/rpc/GetAggregatePrice_test.cpp @@ -25,22 +25,22 @@ public: using namespace jtx; Account const owner{"owner"}; Account const some{"some"}; - static OraclesData kOracles = {{owner, 1}}; + static OraclesData kORACLES = {{owner, 1}}; { Env env(*this); auto const baseFee = env.current()->fees().base; // missing base_asset - auto ret = Oracle::aggregatePrice(env, std::nullopt, "USD", kOracles); + auto ret = Oracle::aggregatePrice(env, std::nullopt, "USD", kORACLES); BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'base_asset'."); // missing quote_asset - ret = Oracle::aggregatePrice(env, "XRP", std::nullopt, kOracles); + ret = Oracle::aggregatePrice(env, "XRP", std::nullopt, kORACLES); BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'quote_asset'."); // invalid base_asset, quote_asset std::vector const invalidAsset = { - kNoneTag, + kNONE_TAG, 1, -1, 1.2, @@ -56,11 +56,11 @@ public: "012345678901234567890123456789012345678G"}; for (auto const& v : invalidAsset) { - ret = Oracle::aggregatePrice(env, "USD", v, kOracles); + ret = Oracle::aggregatePrice(env, "USD", v, kORACLES); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); - ret = Oracle::aggregatePrice(env, v, "USD", kOracles); + ret = Oracle::aggregatePrice(env, v, "USD", kORACLES); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); - ret = Oracle::aggregatePrice(env, v, v, kOracles); + ret = Oracle::aggregatePrice(env, v, v, kORACLES); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } @@ -73,7 +73,7 @@ public: BEAST_EXPECT(ret[jss::error].asString() == "oracleMalformed"); // no token pairs found - ret = Oracle::aggregatePrice(env, "YAN", "USD", kOracles); + ret = Oracle::aggregatePrice(env, "YAN", "USD", kORACLES); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid oracle document id @@ -81,7 +81,7 @@ public: ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, 2}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid values - std::vector const invalidDocument = {kNoneTag, 1.2, -1, "", "none", "1.2"}; + std::vector const invalidDocument = {kNONE_TAG, 1.2, -1, "", "none", "1.2"}; for (auto const& v : invalidDocument) { ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, v}}}); @@ -111,7 +111,8 @@ public: BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid trim value - std::vector const invalidTrim = {kNoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; + std::vector const invalidTrim = { + kNONE_TAG, 0, 26, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTrim) { ret = @@ -120,7 +121,7 @@ public: } // invalid time threshold value - std::vector const invalidTime = {kNoneTag, -1, 1.2, "", "none", "1.2"}; + std::vector const invalidTime = {kNONE_TAG, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTime) { ret = Oracle::aggregatePrice( @@ -177,7 +178,8 @@ public: auto const all = testableAmendments(); for (auto const& feats : {all - featureSingleAssetVault - featureLendingProtocol, all}) { - for (auto const mantissaSize : MantissaRange::getAllScales()) + for (auto const mantissaSize : + {MantissaRange::MantissaScale::Small, MantissaRange::MantissaScale::Large}) { // Regardless of the features enabled, RPC is controlled by // the global mantissa size. And since it's a thread-local, diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index 1f24d229f2..6c45815555 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -49,7 +49,7 @@ struct TxnTestData // 3. sign_for, and // 4. submit_multisigned. // The JSON is not valid for all of these interfaces, but it should - // crash kNone of them, and should provide reliable error messages. + // crash kNONE of them, and should provide reliable error messages. // // The expMsg array contains the expected error string for the above cases. std::array const expMsg; @@ -72,7 +72,7 @@ struct TxnTestData operator=(TxnTestData&&) = delete; }; -static constexpr TxnTestData kTxnTestArray[] = { +static constexpr TxnTestData kTXN_TEST_ARRAY[] = { {"Minimal payment, no Amount only DeliverMax", __LINE__, @@ -2602,7 +2602,7 @@ public: 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::UInt)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(json::ValueType::UintValue)); } { @@ -2629,7 +2629,7 @@ public: 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::UInt)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(json::ValueType::UintValue)); env.close(); } @@ -2655,7 +2655,7 @@ public: 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::UInt)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(json::ValueType::UintValue)); } { @@ -2687,7 +2687,7 @@ public: 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::UInt)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(json::ValueType::UintValue)); } } @@ -2697,7 +2697,7 @@ public: testcase("autofill NetworkID"); using namespace test::jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->networkId = 1025; + cfg->NETWORK_ID = 1025; return cfg; })}; @@ -2743,7 +2743,7 @@ public: // "c" (phantom signer) is rPcNzota6B8YBokhYtcTNqQVCngtbnWfux. Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })); env.fund(XRP(100000), a, ed, g); @@ -2777,26 +2777,26 @@ public: using TestStuff = std::tuple; - static TestStuff const kTestFuncs[] = { + static TestStuff const kTEST_FUNCS[] = { TestStuff{transactionSign, nullptr, "sign", 0}, TestStuff{nullptr, transactionSubmit, "submit", 1}, TestStuff{transactionSignFor, nullptr, "sign_for", 2}, TestStuff{nullptr, transactionSubmitMultiSigned, "submit_multisigned", 3}}; - for (auto testFunc : kTestFuncs) + for (auto testFunc : kTEST_FUNCS) { // For each JSON test. - for (auto const& txnTest : kTxnTestArray) + for (auto const& txnTest : kTXN_TEST_ARRAY) { json::Value req; json::Reader().parse(txnTest.json, req); if (RPC::containsError(req)) Throw("Internal JSONRPC_test error. Bad test JSON."); - static Role const kTestedRoles[] = { + static Role const kTESTED_ROLES[] = { Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; - for (Role const testRole : kTestedRoles) + for (Role const testRole : kTESTED_ROLES) { json::Value result; auto const signFn = get<0>(testFunc); diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index aafe6f75a5..0195657d7f 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -19,15 +19,15 @@ namespace xrpl::RPC { struct KeyStrings { - char const* accountId; - char const* masterKey; - char const* masterSeed; - char const* masterSeedHex; - char const* publicKey; - char const* publicKeyHex; - char const* secretKeyHex; + char const* account_id; + char const* master_key; + char const* master_seed; + char const* master_seed_hex; + char const* public_key; + char const* public_key_hex; + char const* secret_key_hex; char const* passphrase; - char const* passphraseWarning; + char const* passphrase_warning; }; namespace common { @@ -37,46 +37,46 @@ static char const* gMasterSeed = "snMwVWs2hZzfDUF3p2tHZ3EgmyhFs"; static char const* gMasterSeedHex = "BE6A670A19B209E112146D0A7ED2AAD7"; } // namespace common -static KeyStrings const kSecP256K1Strings = { - .accountId = "r4Vtj2jrfmTVZGfSP3gH9hQPMqFPQFin8f", - .masterKey = common::gMasterKey, - .masterSeed = common::gMasterSeed, - .masterSeedHex = common::gMasterSeedHex, - .publicKey = "aBQxK2YFNqzmAaXNczYcjqDjfiKkLsJUizsr1UBf44RCF8FHdrmX", - .publicKeyHex = "038AAE247B2344B1837FBED8F57389C8C11774510A3F7D784F2A09F0CB6843236C", - .secretKeyHex = "1949ECD889EA71324BC7A30C8E81F4E93CB73EE19D59E9082111E78CC3DDABC2", +static KeyStrings const kSECP256K1_STRINGS = { + .account_id = "r4Vtj2jrfmTVZGfSP3gH9hQPMqFPQFin8f", + .master_key = common::gMasterKey, + .master_seed = common::gMasterSeed, + .master_seed_hex = common::gMasterSeedHex, + .public_key = "aBQxK2YFNqzmAaXNczYcjqDjfiKkLsJUizsr1UBf44RCF8FHdrmX", + .public_key_hex = "038AAE247B2344B1837FBED8F57389C8C11774510A3F7D784F2A09F0CB6843236C", + .secret_key_hex = "1949ECD889EA71324BC7A30C8E81F4E93CB73EE19D59E9082111E78CC3DDABC2", .passphrase = common::gPassphrase, - .passphraseWarning = + .passphrase_warning = "This wallet was generated using a user-supplied " "passphrase that has low entropy and is vulnerable " "to brute-force attacks.", }; -static KeyStrings const kED25519Strings = { - .accountId = "r4qV6xTXerqaZav3MJfSY79ynmc1BSBev1", - .masterKey = common::gMasterKey, - .masterSeed = common::gMasterSeed, - .masterSeedHex = common::gMasterSeedHex, - .publicKey = "aKEQmgLMyZPMruJFejUuedp169LgW6DbJt1rej1DJ5hWUMH4pHJ7", - .publicKeyHex = "ED54C3F5BEDA8BD588B203D23A27398FAD9D20F88A974007D6994659CD7273FE1D", - .secretKeyHex = "77AAED2698D56D6676323629160F4EEF21CFD9EE3D0745CC78FA291461F98278", +static KeyStrings const kED25519_STRINGS = { + .account_id = "r4qV6xTXerqaZav3MJfSY79ynmc1BSBev1", + .master_key = common::gMasterKey, + .master_seed = common::gMasterSeed, + .master_seed_hex = common::gMasterSeedHex, + .public_key = "aKEQmgLMyZPMruJFejUuedp169LgW6DbJt1rej1DJ5hWUMH4pHJ7", + .public_key_hex = "ED54C3F5BEDA8BD588B203D23A27398FAD9D20F88A974007D6994659CD7273FE1D", + .secret_key_hex = "77AAED2698D56D6676323629160F4EEF21CFD9EE3D0745CC78FA291461F98278", .passphrase = common::gPassphrase, - .passphraseWarning = + .passphrase_warning = "This wallet was generated using a user-supplied " "passphrase that has low entropy and is vulnerable " "to brute-force attacks.", }; -static KeyStrings const kStrongBrainStrings = { - .accountId = "rBcvXmNb7KPkNdMkpckdWPpbvkWgcV3nir", - .masterKey = "TED AVON CAVE HOUR BRAG JEFF RIFT NEAL TOLD FAT SEW SAN", - .masterSeed = "shKdhWka8hS7Es3bpctCZXBiAwfUN", - .masterSeedHex = "74BA8389B44F98CF41E795CD91F9C93F", - .publicKey = "aBRL2sqVuzrsM6zikPB4v8UBHGn1aKkrsxhYEffhcQxB2LKyywE5", - .publicKeyHex = "03BD334FB9E06C58D69603E9922686528B18A754BC2F2E1ADA095FFE67DE952C64", - .secretKeyHex = "84262FB16AA25BE407174C7EDAB531220C30FA4D8A28AA9D564673FB3D34502C", +static KeyStrings const kSTRONG_BRAIN_STRINGS = { + .account_id = "rBcvXmNb7KPkNdMkpckdWPpbvkWgcV3nir", + .master_key = "TED AVON CAVE HOUR BRAG JEFF RIFT NEAL TOLD FAT SEW SAN", + .master_seed = "shKdhWka8hS7Es3bpctCZXBiAwfUN", + .master_seed_hex = "74BA8389B44F98CF41E795CD91F9C93F", + .public_key = "aBRL2sqVuzrsM6zikPB4v8UBHGn1aKkrsxhYEffhcQxB2LKyywE5", + .public_key_hex = "03BD334FB9E06C58D69603E9922686528B18A754BC2F2E1ADA095FFE67DE952C64", + .secret_key_hex = "84262FB16AA25BE407174C7EDAB531220C30FA4D8A28AA9D564673FB3D34502C", .passphrase = "A4yKIRGdzrw0YQ$2%TFKYG9HP*&ok^!sy7E@RwICs", - .passphraseWarning = + .passphrase_warning = "This wallet was generated using a user-supplied " "passphrase. It may be vulnerable to brute-force " "attacks.", @@ -120,11 +120,11 @@ public: json::Value result = walletPropose(params); BEAST_EXPECT(!containsError(result)); - expectEquals(result[jss::account_id], s.accountId); - expectEquals(result[jss::master_seed], s.masterSeed); - expectEquals(result[jss::master_seed_hex], s.masterSeedHex); - expectEquals(result[jss::public_key], s.publicKey); - expectEquals(result[jss::public_key_hex], s.publicKeyHex); + expectEquals(result[jss::account_id], s.account_id); + expectEquals(result[jss::master_seed], s.master_seed); + expectEquals(result[jss::master_seed_hex], s.master_seed_hex); + expectEquals(result[jss::public_key], s.public_key); + expectEquals(result[jss::public_key_hex], s.public_key_hex); expectEquals( result[jss::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); @@ -139,7 +139,7 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed] = strings.masterSeed; + params[jss::seed] = strings.master_seed; auto const wallet = testSecretWallet(params, strings); BEAST_EXPECT(!wallet.isMember(jss::warning)); @@ -153,7 +153,7 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed_hex] = strings.masterSeedHex; + params[jss::seed_hex] = strings.master_seed_hex; auto const wallet = testSecretWallet(params, strings); BEAST_EXPECT(!wallet.isMember(jss::warning)); @@ -173,7 +173,7 @@ public: auto const wallet = testSecretWallet(params, strings); if (value == strings.passphrase) { - BEAST_EXPECT(wallet[jss::warning] == strings.passphraseWarning); + BEAST_EXPECT(wallet[jss::warning] == strings.passphrase_warning); } else { @@ -187,9 +187,9 @@ public: testcase("passphrase"); testLegacyPassphrase(strings.passphrase, keyType, strings); - testLegacyPassphrase(strings.masterKey, keyType, strings); - testLegacyPassphrase(strings.masterSeed, keyType, strings); - testLegacyPassphrase(strings.masterSeedHex, keyType, strings); + testLegacyPassphrase(strings.master_key, keyType, strings); + testLegacyPassphrase(strings.master_seed, keyType, strings); + testLegacyPassphrase(strings.master_seed_hex, keyType, strings); } void @@ -205,8 +205,8 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed] = strings.masterSeed; - params[jss::seed_hex] = strings.masterSeedHex; + params[jss::seed] = strings.master_seed; + params[jss::seed_hex] = strings.master_seed_hex; // Secret fields are mutually exclusive. BEAST_EXPECT(containsError(walletPropose(params))); @@ -230,7 +230,7 @@ public: { json::Value params; params[jss::key_type] = "secp256k1"; - params[jss::seed] = json::ValueType::Object; + params[jss::seed] = json::ObjectValue; auto result = walletPropose(params); BEAST_EXPECT(containsError(result)); BEAST_EXPECT(result[jss::error_message] == "Invalid field 'seed', not string."); @@ -239,7 +239,7 @@ public: { json::Value params; params[jss::key_type] = "ed25519"; - params[jss::seed_hex] = json::ValueType::Array; + params[jss::seed_hex] = json::ArrayValue; auto result = walletPropose(params); BEAST_EXPECT(containsError(result)); BEAST_EXPECT(result[jss::error_message] == "Invalid field 'seed_hex', not string."); @@ -272,7 +272,7 @@ public: { json::Value params; - params[jss::key_type] = json::ValueType::Object; + params[jss::key_type] = json::ObjectValue; params[jss::seed_hex] = common::gMasterSeedHex; auto result = walletPropose(params); BEAST_EXPECT(containsError(result)); @@ -281,7 +281,7 @@ public: { json::Value params; - params[jss::key_type] = json::ValueType::Array; + params[jss::key_type] = json::ArrayValue; params[jss::seed] = common::gMasterSeed; auto result = walletPropose(params); BEAST_EXPECT(containsError(result)); @@ -294,7 +294,7 @@ public: { testcase("keypairForSignature - " + (keyType ? *keyType : "no key_type")); - auto const publicKey = parseBase58(TokenType::AccountPublic, strings.publicKey); + auto const publicKey = parseBase58(TokenType::AccountPublic, strings.public_key); BEAST_EXPECT(publicKey); if (!keyType) @@ -302,7 +302,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.masterSeed; + params[jss::secret] = strings.master_seed; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -316,7 +316,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.masterSeedHex; + params[jss::secret] = strings.master_seed_hex; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -330,7 +330,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.masterKey; + params[jss::secret] = strings.master_key; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -349,7 +349,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::seed] = strings.masterSeed; + params[jss::seed] = strings.master_seed; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -365,7 +365,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::seed_hex] = strings.masterSeedHex; + params[jss::seed_hex] = strings.master_seed_hex; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -381,7 +381,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::passphrase] = strings.masterKey; + params[jss::passphrase] = strings.master_key; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -410,7 +410,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = json::ValueType::Array; + params[jss::secret] = json::ArrayValue; params[jss::secret].append("array:0"); auto ret = keypairForSignature(params, error); @@ -422,7 +422,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = json::ValueType::Object; + params[jss::secret] = json::ObjectValue; params[jss::secret]["string"] = "string"; params[jss::secret]["number"] = 702; @@ -463,7 +463,7 @@ public: { json::Value params; json::Value error; - params[jss::key_type] = json::ValueType::Object; + params[jss::key_type] = json::ObjectValue; params[jss::seed_hex] = common::gMasterSeedHex; auto ret = keypairForSignature(params, error); @@ -475,7 +475,7 @@ public: { json::Value params; json::Value error; - params[jss::key_type] = json::ValueType::Array; + params[jss::key_type] = json::ArrayValue; params[jss::seed] = common::gMasterSeed; auto ret = keypairForSignature(params, error); @@ -501,7 +501,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::passphrase] = json::ValueType::Object; + params[jss::passphrase] = json::ObjectValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -513,7 +513,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::passphrase] = json::ValueType::Array; + params[jss::passphrase] = json::ArrayValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -550,7 +550,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::seed] = json::ValueType::Object; + params[jss::seed] = json::ObjectValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -562,7 +562,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::seed] = json::ValueType::Array; + params[jss::seed] = json::ArrayValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -623,7 +623,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::seed_hex] = json::ValueType::Object; + params[jss::seed_hex] = json::ObjectValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -635,7 +635,7 @@ public: json::Value params; json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::seed_hex] = json::ValueType::Array; + params[jss::seed_hex] = json::ArrayValue; auto ret = keypairForSignature(params, error); BEAST_EXPECT(containsError(error)); @@ -781,16 +781,16 @@ public: void run() override { - testKeyType(std::nullopt, kSecP256K1Strings); - testKeyType(std::string("secp256k1"), kSecP256K1Strings); - testKeyType(std::string("ed25519"), kED25519Strings); - testKeyType(std::string("secp256k1"), kStrongBrainStrings); + testKeyType(std::nullopt, kSECP256K1_STRINGS); + testKeyType(std::string("secp256k1"), kSECP256K1_STRINGS); + testKeyType(std::string("ed25519"), kED25519_STRINGS); + testKeyType(std::string("secp256k1"), kSTRONG_BRAIN_STRINGS); testBadInput(); - testKeypairForSignature(std::nullopt, kSecP256K1Strings); - testKeypairForSignature(std::string("secp256k1"), kSecP256K1Strings); - testKeypairForSignature(std::string("ed25519"), kED25519Strings); - testKeypairForSignature(std::string("secp256k1"), kStrongBrainStrings); + testKeypairForSignature(std::nullopt, kSECP256K1_STRINGS); + testKeypairForSignature(std::string("secp256k1"), kSECP256K1_STRINGS); + testKeypairForSignature(std::string("ed25519"), kED25519_STRINGS); + testKeypairForSignature(std::string("secp256k1"), kSTRONG_BRAIN_STRINGS); testXrplLibEd25519(); diff --git a/src/test/rpc/LedgerClosed_test.cpp b/src/test/rpc/LedgerClosed_test.cpp index f02d23030d..81919e04d0 100644 --- a/src/test/rpc/LedgerClosed_test.cpp +++ b/src/test/rpc/LedgerClosed_test.cpp @@ -23,7 +23,7 @@ public: // This test relies on ledger hash so must lock it to fee 10. auto p = envconfig(); - p->fees.referenceFee = 10; + p->FEES.reference_fee = 10; Env env{*this, std::move(p), FeatureBitset{}}; Account const alice{"alice"}; env.fund(XRP(10000), alice); diff --git a/src/test/rpc/LedgerData_test.cpp b/src/test/rpc/LedgerData_test.cpp index 94e6897036..f11b807529 100644 --- a/src/test/rpc/LedgerData_test.cpp +++ b/src/test/rpc/LedgerData_test.cpp @@ -333,7 +333,7 @@ public: jv[jss::TransactionType] = jss::EscrowCreate; jv[jss::Account] = Account{"bob5"}.human(); jv[jss::Destination] = Account{"bob6"}.human(); - jv[jss::Amount] = XRP(50).value().getJson(JsonOptions::Values::None); + jv[jss::Amount] = XRP(50).value().getJson(JsonOptions::KNone); jv[sfFinishAfter.fieldName] = NetClock::time_point{env.now() + 10s}.time_since_epoch().count(); env(jv); @@ -344,7 +344,7 @@ public: jv[jss::TransactionType] = jss::PaymentChannelCreate; jv[jss::Account] = Account{"bob6"}.human(); jv[jss::Destination] = Account{"bob7"}.human(); - jv[jss::Amount] = XRP(100).value().getJson(JsonOptions::Values::None); + jv[jss::Amount] = XRP(100).value().getJson(JsonOptions::KNone); jv[jss::SettleDelay] = NetClock::duration{10s}.count(); jv[sfPublicKey.fieldName] = strHex(Account{"bob6"}.pk().slice()); jv[sfCancelAfter.fieldName] = diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index d231a2d4a0..298d0e5149 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -163,7 +163,7 @@ class LedgerEntry_test : public beast::unit_test::Suite if (msg.empty()) { BEAST_EXPECTS( - jv[jss::error_message] == json::ValueType::Null || jv[jss::error_message] == "", + 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()); } @@ -180,19 +180,19 @@ class LedgerEntry_test : public beast::unit_test::Suite static std::vector getBadValues(FieldType fieldType) { - static json::Value const kInjectObject = []() { - json::Value obj(json::ValueType::Object); + static json::Value const kINJECT_OBJECT = []() { + json::Value obj(json::ObjectValue); obj[jss::account] = "rhigTLJJyXXSRUyRCQtqi1NoAZZzZnS4KU"; obj[jss::ledger_index] = "validated"; return obj; }(); - static json::Value const kInjectArray = []() { - json::Value arr(json::ValueType::Array); + static json::Value const kINJECT_ARRAY = []() { + json::Value arr(json::ArrayValue); arr[0u] = "rhigTLJJyXXSRUyRCQtqi1NoAZZzZnS4KU"; arr[1u] = "validated"; return arr; }(); - static std::array const kAllBadValues = { + static std::array const kALL_BAD_VALUES = { "", // 0 true, // 1 1, // 2 @@ -210,61 +210,61 @@ class LedgerEntry_test : public beast::unit_test::Suite "USD", // 14 "USDollars", // 15 "5233D68B4D44388F98559DE42903767803EFA7C1F8D01413FC16EE6B01403D" - "6D", // 16 - json::ValueType::Array, // 17 - json::ValueType::Object, // 18 - kInjectObject, // 19 - kInjectArray // 20 + "6D", // 16 + json::ArrayValue, // 17 + json::ObjectValue, // 18 + kINJECT_OBJECT, // 19 + kINJECT_ARRAY // 20 }; auto remove = [&](std::vector indices) -> std::vector { std::unordered_set const indexSet(indices.begin(), indices.end()); std::vector values; - values.reserve(kAllBadValues.size() - indexSet.size()); - for (std::size_t i = 0; i < kAllBadValues.size(); ++i) + values.reserve(kALL_BAD_VALUES.size() - indexSet.size()); + for (std::size_t i = 0; i < kALL_BAD_VALUES.size(); ++i) { if (!indexSet.contains(i)) { - values.push_back(kAllBadValues[i]); + values.push_back(kALL_BAD_VALUES[i]); } } return values; }; - static auto const& kBadAccountValues = remove({12}); - static auto const& kBadArrayValues = remove({17, 20}); - static auto const& kBadBlobValues = remove({3, 7, 8, 16}); - static auto const& kBadCurrencyValues = remove({14}); - static auto const& kBadHashValues = remove({2, 3, 7, 8, 16}); - static auto const& kBadFixedHashValues = remove({1, 2, 3, 4, 7, 8, 16}); - static auto const& kBadIndexValues = remove({12, 16, 18, 19}); - static auto const& kBadUInt32Values = remove({2, 3}); - static auto const& kBadUInt64Values = remove({2, 3}); - static auto const& kBadIssueValues = remove({}); + static auto const& kBAD_ACCOUNT_VALUES = remove({12}); + static auto const& kBAD_ARRAY_VALUES = remove({17, 20}); + static auto const& kBAD_BLOB_VALUES = remove({3, 7, 8, 16}); + static auto const& kBAD_CURRENCY_VALUES = remove({14}); + static auto const& kBAD_HASH_VALUES = remove({2, 3, 7, 8, 16}); + static auto const& kBAD_FIXED_HASH_VALUES = remove({1, 2, 3, 4, 7, 8, 16}); + static auto const& kBAD_INDEX_VALUES = remove({12, 16, 18, 19}); + static auto const& kBAD_U_INT32_VALUES = remove({2, 3}); + static auto const& kBAD_U_INT64_VALUES = remove({2, 3}); + static auto const& kBAD_ISSUE_VALUES = remove({}); switch (fieldType) { case FieldType::AccountField: - return kBadAccountValues; + return kBAD_ACCOUNT_VALUES; case FieldType::ArrayField: case FieldType::TwoAccountArrayField: - return kBadArrayValues; + return kBAD_ARRAY_VALUES; case FieldType::BlobField: - return kBadBlobValues; + return kBAD_BLOB_VALUES; case FieldType::CurrencyField: - return kBadCurrencyValues; + return kBAD_CURRENCY_VALUES; case FieldType::HashField: - return kBadHashValues; + return kBAD_HASH_VALUES; case FieldType::HashOrObjectField: - return kBadIndexValues; + return kBAD_INDEX_VALUES; case FieldType::FixedHashField: - return kBadFixedHashValues; + return kBAD_FIXED_HASH_VALUES; case FieldType::AssetField: - return kBadIssueValues; + return kBAD_ISSUE_VALUES; case FieldType::UInt32Field: - return kBadUInt32Values; + return kBAD_U_INT32_VALUES; case FieldType::UInt64Field: - return kBadUInt64Values; + return kBAD_U_INT64_VALUES; default: Throw( "unknown type " + std::to_string(static_cast(fieldType))); @@ -274,14 +274,14 @@ class LedgerEntry_test : public beast::unit_test::Suite static json::Value getCorrectValue(json::StaticString fieldName) { - static json::Value const kTwoAccountArray = []() { - json::Value arr(json::ValueType::Array); + static json::Value const kTWO_ACCOUNT_ARRAY = []() { + json::Value arr(json::ArrayValue); arr[0u] = "rhigTLJJyXXSRUyRCQtqi1NoAZZzZnS4KU"; arr[1u] = "r4MrUGTdB57duTnRs6KbsRGQXgkseGb1b5"; return arr; }(); - static json::Value const kIssueObject = []() { - json::Value arr(json::ValueType::Object); + static json::Value const kISSUE_OBJECT = []() { + json::Value arr(json::ObjectValue); arr[jss::currency] = "XRP"; return arr; }(); @@ -292,7 +292,7 @@ class LedgerEntry_test : public beast::unit_test::Suite case FieldType::AccountField: return "r4MrUGTdB57duTnRs6KbsRGQXgkseGb1b5"; case FieldType::ArrayField: - return json::ValueType::Array; + return json::ArrayValue; case FieldType::BlobField: return "ABCDEF"; case FieldType::CurrencyField: @@ -301,12 +301,12 @@ class LedgerEntry_test : public beast::unit_test::Suite return "5233D68B4D44388F98559DE42903767803EFA7C1F8D01413FC16EE6" "B01403D6D"; case FieldType::AssetField: - return kIssueObject; + return kISSUE_OBJECT; case FieldType::HashOrObjectField: return "5233D68B4D44388F98559DE42903767803EFA7C1F8D01413FC16EE6" "B01403D6D"; case FieldType::TwoAccountArrayField: - return kTwoAccountArray; + return kTWO_ACCOUNT_ARRAY; case FieldType::UInt32Field: return 1; case FieldType::UInt64Field: @@ -359,7 +359,7 @@ class LedgerEntry_test : public beast::unit_test::Suite } if (required) { - tryField(json::ValueType::Null); + tryField(json::NullValue); } }); } @@ -384,7 +384,7 @@ class LedgerEntry_test : public beast::unit_test::Suite checkErrorValue( jrr, "malformedRequest", RPC::missingFieldMessage(fieldName.cStr()), location); - correctRequest[parentFieldName][fieldName] = json::ValueType::Null; + correctRequest[parentFieldName][fieldName] = json::NullValue; json::Value const jrr2 = env.rpc( apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; checkErrorValue( @@ -451,7 +451,7 @@ class LedgerEntry_test : public beast::unit_test::Suite location); json::Value correctOutput; - correctOutput[parentField] = json::ValueType::Object; + correctOutput[parentField] = json::ObjectValue; for (auto const& subfield : subfields) { correctOutput[parentField][subfield.fieldName] = getCorrectValue(subfield.fieldName); @@ -528,7 +528,7 @@ class LedgerEntry_test : public beast::unit_test::Suite forAllApiVersions([&, this](unsigned apiVersion) { // "features" is not an option supported by ledger_entry. { - json::Value jvParams = json::ValueType::Object; + json::Value jvParams = json::ObjectValue; jvParams[jss::features] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAA"; @@ -555,7 +555,7 @@ class LedgerEntry_test : public beast::unit_test::Suite using namespace test::jtx; auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env{*this, std::move(cfg)}; Account const alice{"alice"}; @@ -584,7 +584,7 @@ class LedgerEntry_test : public beast::unit_test::Suite accountRootIndex = jrr[jss::index].asString(); } { - static constexpr char kAliceAcctRootBinary[]{ + constexpr char kALICE_ACCT_ROOT_BINARY[]{ "1100612200800000240000000425000000032D00000000559CE54C3B934E4" "73A995B477E92EC229F99CED5B62BF4D2ACE4DC42719103AE2F6240000002" "540BE4008114AE123A8556F3CF91154711376AFB0F894F832B3D"}; @@ -597,7 +597,7 @@ class LedgerEntry_test : public beast::unit_test::Suite 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] == kAliceAcctRootBinary); + BEAST_EXPECT(jrr[jss::node_binary] == kALICE_ACCT_ROOT_BINARY); } { // Request alice's account root using the index. @@ -759,14 +759,14 @@ class LedgerEntry_test : public beast::unit_test::Suite { json::Value jvParams; - json::Value ammParams(json::ValueType::Object); + json::Value ammParams(json::ObjectValue); { - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); obj[jss::currency] = "XRP"; ammParams[jss::asset] = obj; } { - json::Value const obj(json::ValueType::Object); + json::Value const obj(json::ObjectValue); ammParams[jss::asset2] = toJson(usd.raw()); } jvParams[jss::amm] = ammParams; @@ -1047,7 +1047,7 @@ 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); json::Value jo; @@ -1070,7 +1070,7 @@ class LedgerEntry_test : public beast::unit_test::Suite jvParams[jss::deposit_preauth][jss::owner] = bob.human(); auto tryField = [&](json::Value fieldValue) -> void { - json::Value arr = json::ValueType::Array; + json::Value arr = json::ArrayValue; json::Value jo; jo[jss::issuer] = fieldValue; jo[jss::credential_type] = strHex(std::string_view(credType)); @@ -1090,7 +1090,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { tryField(value); } - tryField(json::ValueType::Null); + tryField(json::NullValue); } { @@ -1099,7 +1099,7 @@ 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); json::Value jo; @@ -1121,7 +1121,7 @@ class LedgerEntry_test : public beast::unit_test::Suite jvParams[jss::deposit_preauth][jss::owner] = bob.human(); auto tryField = [&](json::Value fieldValue) -> void { - json::Value arr = json::ValueType::Array; + json::Value arr = json::ArrayValue; json::Value jo; jo[jss::issuer] = issuer.human(); jo[jss::credential_type] = fieldValue; @@ -1141,7 +1141,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { tryField(value); } - tryField(json::ValueType::Null); + tryField(json::NullValue); } { @@ -1151,7 +1151,7 @@ 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); json::Value jo; @@ -1187,7 +1187,7 @@ 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); arr.append("foobar"); @@ -1203,9 +1203,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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); - json::Value payload = json::ValueType::Array; + json::Value payload = json::ArrayValue; payload.append(42); arr.append(std::move(payload)); @@ -1221,7 +1221,7 @@ 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( @@ -1232,18 +1232,19 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Failed, authorized_credentials is too long - static std::array const kCredTypes = { + static std::array const kCRED_TYPES = { "cred1", "cred2", "cred3", "cred4", "cred5", "cred6", "cred7", "cred8", "cred9"}; - static_assert(sizeof(kCredTypes) / sizeof(kCredTypes[0]) > kMaxCredentialsArraySize); + static_assert( + sizeof(kCRED_TYPES) / sizeof(kCRED_TYPES[0]) > kMAX_CREDENTIALS_ARRAY_SIZE); 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::ValueType::Array; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = json::ArrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); - for (auto cred : kCredTypes) + for (auto cred : kCRED_TYPES) { json::Value jo; jo[jss::issuer] = issuer.human(); @@ -1304,7 +1305,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Locate directory by directory root. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + 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]; @@ -1313,7 +1314,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Locate directory by owner. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; json::Value const jrr = @@ -1323,7 +1324,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Locate directory by directory root and sub_index. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::directory][jss::sub_index] = 1; json::Value const jrr = @@ -1334,7 +1335,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Locate directory by owner and sub_index. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; @@ -1353,7 +1354,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Non-integer sub_index. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( @@ -1368,7 +1369,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Malformed owner entry. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( @@ -1383,7 +1384,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Malformed directory object. Specifies both dir_root and owner. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; @@ -1395,7 +1396,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Incomplete directory object. Missing both dir_root and owner. json::Value jvParams; - jvParams[jss::directory] = json::ValueType::Object; + jvParams[jss::directory] = json::ObjectValue; jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; json::Value const jrr = @@ -1424,7 +1425,7 @@ class LedgerEntry_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::EscrowCreate; jv[jss::Account] = account.human(); jv[jss::Destination] = to.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv[sfFinishAfter.jsonName] = cancelAfter.time_since_epoch().count() + 2; return jv; }; @@ -1438,7 +1439,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Request the escrow using owner and sequence. json::Value jvParams; - jvParams[jss::escrow] = json::ValueType::Object; + 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 = @@ -1644,7 +1645,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Request the offer using owner and sequence. json::Value jvParams; - jvParams[jss::offer] = json::ValueType::Object; + jvParams[jss::offer] = json::ObjectValue; jvParams[jss::offer][jss::account] = alice.human(); jvParams[jss::offer][jss::seq] = env.seq(alice) - 1; jvParams[jss::ledger_hash] = ledgerHash; @@ -1693,7 +1694,7 @@ class LedgerEntry_test : public beast::unit_test::Suite jv[jss::TransactionType] = jss::PaymentChannelCreate; jv[jss::Account] = account.human(); jv[jss::Destination] = to.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::Values::None); + jv[jss::Amount] = amount.getJson(JsonOptions::KNone); jv[sfSettleDelay.jsonName] = settleDelay.count(); jv[sfPublicKey.jsonName] = strHex(pk.slice()); return jv; @@ -1757,8 +1758,8 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Request the trust line using the accounts and currency. json::Value jvParams; - jvParams[fieldName] = json::ValueType::Object; - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName] = json::ObjectValue; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; @@ -1781,8 +1782,8 @@ class LedgerEntry_test : public beast::unit_test::Suite { // ripple_state one of the accounts is missing. json::Value jvParams; - jvParams[fieldName] = json::ValueType::Object; - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName] = json::ObjectValue; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; @@ -1797,8 +1798,8 @@ class LedgerEntry_test : public beast::unit_test::Suite { // ripple_state more than 2 accounts. json::Value jvParams; - jvParams[fieldName] = json::ValueType::Object; - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName] = json::ObjectValue; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::accounts][2u] = alice.human(); @@ -1815,11 +1816,11 @@ class LedgerEntry_test : public beast::unit_test::Suite { // ripple_state account[0] / account[1] is not an account. json::Value jvParams; - jvParams[fieldName] = json::ValueType::Object; + jvParams[fieldName] = json::ObjectValue; auto tryField = [&](json::Value badAccount) -> void { { // account[0] - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = badAccount; jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; @@ -1834,7 +1835,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // account[1] - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::accounts][1u] = badAccount; jvParams[fieldName][jss::currency] = "USD"; @@ -1853,13 +1854,13 @@ class LedgerEntry_test : public beast::unit_test::Suite { tryField(value); } - tryField(json::ValueType::Null); + tryField(json::NullValue); } { // ripple_state account[0] == account[1]. json::Value jvParams; - jvParams[fieldName] = json::ValueType::Object; - jvParams[fieldName][jss::accounts] = json::ValueType::Array; + jvParams[fieldName] = json::ObjectValue; + jvParams[fieldName][jss::accounts] = json::ArrayValue; jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::accounts][1u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; @@ -1919,7 +1920,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Second real ticket requested by account and sequence. json::Value jvParams; - jvParams[jss::ticket] = json::ValueType::Object; + jvParams[jss::ticket] = json::ObjectValue; jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 1; jvParams[jss::ledger_hash] = ledgerHash; @@ -1931,7 +1932,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Not a valid ticket requested by account and sequence. json::Value jvParams; - jvParams[jss::ticket] = json::ValueType::Object; + jvParams[jss::ticket] = json::ObjectValue; jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 2; jvParams[jss::ledger_hash] = ledgerHash; @@ -2128,7 +2129,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Request the MPToken using its owner + mptIssuanceID. json::Value jvParams; - jvParams[jss::mptoken] = json::ValueType::Object; + jvParams[jss::mptoken] = json::ObjectValue; jvParams[jss::mptoken][jss::account] = bob.human(); jvParams[jss::mptoken][jss::mpt_issuance_id] = strHex(mptAlice.issuanceID()); jvParams[jss::ledger_hash] = ledgerHash; @@ -2140,7 +2141,7 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Request the MPToken using a bad mptIssuanceID. json::Value jvParams; - jvParams[jss::mptoken] = json::ValueType::Object; + jvParams[jss::mptoken] = json::ObjectValue; jvParams[jss::mptoken][jss::account] = bob.human(); jvParams[jss::mptoken][jss::mpt_issuance_id] = badMptID; jvParams[jss::ledger_hash] = ledgerHash; @@ -2237,7 +2238,7 @@ class LedgerEntry_test : public beast::unit_test::Suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->startUp = StartUpType::Fresh; + cfg->START_UP = StartUpType::Fresh; return cfg; })}; @@ -2301,7 +2302,7 @@ class LedgerEntry_test : public beast::unit_test::Suite // "field":null json::Value params; params[jss::ledger_index] = jss::validated; - params[field] = json::ValueType::Null; + 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)); @@ -2430,7 +2431,7 @@ class LedgerEntry_test : public beast::unit_test::Suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->startUp = StartUpType::Fresh; + cfg->START_UP = StartUpType::Fresh; return cfg; })}; @@ -2498,7 +2499,7 @@ class LedgerEntry_test : public beast::unit_test::Suite // "hashes":null json::Value params; params[jss::ledger_index] = jss::validated; - params[jss::hashes] = json::ValueType::Null; + 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)); @@ -2695,8 +2696,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::ValueType::Null || 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))) { @@ -2763,7 +2763,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, // swap door accounts and make sure we get an error value json::Value jvParams; // Sidechain door account is "master", not scDoor - jvParams[jss::bridge_account] = Account::kMaster.human(); + jvParams[jss::bridge_account] = Account::kMASTER.human(); jvParams[jss::bridge] = jvb; jvParams[jss::ledger_hash] = ledgerHash; json::Value const jrr = @@ -2868,7 +2868,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, // send less than quorum of attestations (otherwise funds are // immediately transferred and no "claim" object is created) - static constexpr size_t kNumAttest = 3; + size_t constexpr kNUM_ATTEST = 3; auto attestations = createAccountAttestations( scAttester, jvb, @@ -2880,8 +2880,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, 1, scCarol, signers, - kUtXchainDefaultNumSigners); - for (size_t i = 0; i < kNumAttest; ++i) + kUT_XCHAIN_DEFAULT_NUM_SIGNERS); + for (size_t i = 0; i < kNUM_ATTEST; ++i) { scEnv(attestations[i]); } @@ -2900,7 +2900,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, auto r = jrr[jss::node]; BEAST_EXPECT(r.isMember(jss::Account)); - BEAST_EXPECT(r[jss::Account] == Account::kMaster.human()); + BEAST_EXPECT(r[jss::Account] == Account::kMASTER.human()); BEAST_EXPECT(r.isMember(sfXChainAccountCreateCount.jsonName)); BEAST_EXPECT(r[sfXChainAccountCreateCount.jsonName].asInt() == 1); @@ -2911,12 +2911,13 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, BEAST_EXPECT(attest.size() == 3); BEAST_EXPECT( attest[json::Value::UInt(0)].isMember(sfXChainCreateAccountProofSig.jsonName)); - json::Value a[kNumAttest]; - for (size_t i = 0; i < kNumAttest; ++i) + json::Value a[kNUM_ATTEST]; + for (size_t i = 0; i < kNUM_ATTEST; ++i) { a[i] = attest[json::Value::UInt(0)][sfXChainCreateAccountProofSig.jsonName]; BEAST_EXPECT( - a[i].isMember(jss::Amount) && a[i][jss::Amount].asInt() == 1000 * kDropPerXrp); + a[i].isMember(jss::Amount) && + a[i][jss::Amount].asInt() == 1000 * kDROP_PER_XRP); BEAST_EXPECT( a[i].isMember(jss::Destination) && a[i][jss::Destination] == scCarol.human()); BEAST_EXPECT( @@ -2934,13 +2935,13 @@ class LedgerEntry_XChain_test : public beast::unit_test::Suite, a[i][sfWasLockingChainSend.jsonName] == 1); BEAST_EXPECT( a[i].isMember(sfSignatureReward.jsonName) && - a[i][sfSignatureReward.jsonName].asInt() == 1 * kDropPerXrp); + a[i][sfSignatureReward.jsonName].asInt() == 1 * kDROP_PER_XRP); } } // complete attestations quorum - CreateAccountClaimID should not be // present anymore - for (size_t i = kNumAttest; i < kUtXchainDefaultNumSigners; ++i) + for (size_t i = kNUM_ATTEST; i < kUT_XCHAIN_DEFAULT_NUM_SIGNERS; ++i) { scEnv(attestations[i]); } diff --git a/src/test/rpc/LedgerHeader_test.cpp b/src/test/rpc/LedgerHeader_test.cpp index 0f6831a0e5..885fabb255 100644 --- a/src/test/rpc/LedgerHeader_test.cpp +++ b/src/test/rpc/LedgerHeader_test.cpp @@ -16,7 +16,7 @@ class LedgerHeader_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, envconfig(noAdmin)}; - json::Value params{json::ValueType::Object}; + 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]; @@ -33,7 +33,7 @@ class LedgerHeader_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, envconfig(noAdmin)}; - json::Value params{json::ValueType::Object}; + 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]; @@ -50,7 +50,7 @@ class LedgerHeader_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, envconfig(noAdmin)}; - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::api_version] = 2; auto const result = env.client().invoke("ledger_header", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "unknownCmd"); diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index f35dddffb1..13887e5710 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -38,8 +38,7 @@ class LedgerRPC_test : public beast::unit_test::Suite BEAST_EXPECT(jv[jss::error] == err); if (msg.empty()) { - BEAST_EXPECT( - jv[jss::error_message] == json::ValueType::Null || 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))) { @@ -268,7 +267,7 @@ class LedgerRPC_test : public beast::unit_test::Suite using namespace test::jtx; auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env{*this, std::move(cfg), FeatureBitset{}}; // hashes requested below // assume no amendments env.fund(XRP(10000), "alice"); @@ -437,7 +436,7 @@ class LedgerRPC_test : public beast::unit_test::Suite return cfg; }); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); json::Value jv; diff --git a/src/test/rpc/LedgerRequest_test.cpp b/src/test/rpc/LedgerRequest_test.cpp index 4759256b96..65c5a57712 100644 --- a/src/test/rpc/LedgerRequest_test.cpp +++ b/src/test/rpc/LedgerRequest_test.cpp @@ -20,12 +20,12 @@ namespace xrpl::RPC { class LedgerRequest_test : public beast::unit_test::Suite { - static constexpr char const* kHash1 = + static constexpr char const* kHASH1 = "3020EB9E7BE24EF7D7A060CB051583EC117384636D1781AFB5B87F3E348DA489"; - static constexpr char const* kAccountHash1 = + static constexpr char const* kACCOUNTHASH1 = "BD8A3D72CA73DDE887AD63666EC2BAD07875CBA997A102579B5B95ECDFFEAED8"; - static constexpr char const* kZeroHASH = + static constexpr char const* kZEROHASH = "0000000000000000000000000000000000000000000000000000000000000000"; public: @@ -149,7 +149,7 @@ public: using namespace test::jtx; auto cfg = envconfig(); - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; Env env{*this, std::move(cfg), FeatureBitset{}}; // the hashes being checked below // assume no amendments Account const gw{"gateway"}; @@ -173,32 +173,32 @@ public: BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "1"); 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] == kHash1); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kZeroHASH); - BEAST_EXPECT(result[jss::ledger][jss::account_hash] == kAccountHash1); - BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZeroHASH); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH1); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kZEROHASH); + BEAST_EXPECT(result[jss::ledger][jss::account_hash] == kACCOUNTHASH1); + BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZEROHASH); result = env.rpc("ledger_request", "2")[jss::result]; - static constexpr char const* kHash2 = + constexpr char const* kHASH2 = "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "2"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "100000000000000000"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); - BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHash2); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHash1); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH2); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHASH1); BEAST_EXPECT( result[jss::ledger][jss::account_hash] == "3C834285F7F464FBE99AFEB84D354A968EB2CAA24523FF26797A973D906A3D29"); - BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZeroHASH); + BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZEROHASH); result = env.rpc("ledger_request", "3")[jss::result]; - static constexpr char const* kHash3 = + constexpr char const* kHASH3 = "9FFD8AE09190D5002FE4252A1B29EABCF40DABBCE3B42619C6BD0BE381D51103"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "3"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999980"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); - BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHash3); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHash2); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH3); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHASH2); BEAST_EXPECT( result[jss::ledger][jss::account_hash] == "35738B8517F37D08983AF6BC7DA483CCA9CF6B41B1FECB31A20028D78FE0BB22"); @@ -207,13 +207,13 @@ public: "CBD7F0948EBFA2241DE4EA627939A0FFEE6B80A90FE09C42C825DA546E9B73FF"); result = env.rpc("ledger_request", "4")[jss::result]; - static constexpr char const* kHash4 = + constexpr char const* kHASH4 = "7C9B614445517B8C6477E0AB10A35FFC1A23A34FEA41A91ECBDE884CC097C6E1"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "4"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999960"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); - BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHash4); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHash3); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH4); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHASH3); BEAST_EXPECT( result[jss::ledger][jss::account_hash] == "1EE701DD2A150205173E1EDE8D474DF6803EC95253DAAEE965B9D896CFC32A04"); @@ -222,13 +222,13 @@ public: "9BBDDBF926100DFFF364E16268F544B19F5B9BC6ECCBBC104F98D13FA9F3BC35"); result = env.rpc("ledger_request", "5")[jss::result]; - static constexpr char const* kHash5 = + constexpr char const* kHASH5 = "98885D02145CCE4AD2605F1809F17188DB2053B14ED399CAC985DD8E03DCA8C0"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "5"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999940"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); - BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHash5); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHash4); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH5); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kHASH4); BEAST_EXPECT( result[jss::ledger][jss::account_hash] == "41D64D64796468DEA7AE2A7282C0BB525D6FD7ABC29453C5E5BC6406E947CBCE"); @@ -301,8 +301,8 @@ public: using namespace test::jtx; using namespace std::chrono_literals; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; - cfg->nodeSize = 0; + cfg->FEES.reference_fee = 10; + cfg->NODE_SIZE = 0; return cfg; })}; Account const gw{"gateway"}; @@ -322,10 +322,10 @@ public: BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "1"); 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] == kHash1); - BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kZeroHASH); - BEAST_EXPECT(result[jss::ledger][jss::account_hash] == kAccountHash1); - BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZeroHASH); + BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == kHASH1); + BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == kZEROHASH); + BEAST_EXPECT(result[jss::ledger][jss::account_hash] == kACCOUNTHASH1); + BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == kZEROHASH); } void @@ -342,7 +342,7 @@ public: // The current HTTP/S ServerHandler returns an HTTP 403 error code here // rather than a noPermission JSON error. The JSONRPCClient just eats // that error and returns an null result. - BEAST_EXPECT(result.type() == json::ValueType::Null); + BEAST_EXPECT(result.type() == json::NullValue); } void diff --git a/src/test/rpc/NoRippleCheck_test.cpp b/src/test/rpc/NoRippleCheck_test.cpp index 9c17d291a1..5099a2da2f 100644 --- a/src/test/rpc/NoRippleCheck_test.cpp +++ b/src/test/rpc/NoRippleCheck_test.cpp @@ -76,9 +76,9 @@ class NoRippleCheck_test : public beast::unit_test::Suite testInvalidAccountParam(1); testInvalidAccountParam(1.1); testInvalidAccountParam(true); - testInvalidAccountParam(json::Value(json::ValueType::Null)); - testInvalidAccountParam(json::Value(json::ValueType::Object)); - testInvalidAccountParam(json::Value(json::ValueType::Array)); + testInvalidAccountParam(json::Value(json::NullValue)); + testInvalidAccountParam(json::Value(json::ObjectValue)); + testInvalidAccountParam(json::Value(json::ArrayValue)); } { // invalid role field @@ -153,7 +153,7 @@ class NoRippleCheck_test : public beast::unit_test::Suite json::Value params; params[jss::account] = Account{"nobody"}.human(); params[jss::role] = "user"; - params[jss::ledger] = json::ValueType::Object; + params[jss::ledger] = json::ObjectValue; auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT( @@ -241,7 +241,7 @@ class NoRippleCheck_test : public beast::unit_test::Suite 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::Values::None)); + gw["USD"](100).value().getJson(JsonOptions::KNone)); } else { @@ -293,15 +293,15 @@ class NoRippleCheckLimits_test : public beast::unit_test::Suite Endpoint::fromString(test::getEnvLocalhostAddr())); // if we go above the warning threshold, reset - if (c.balance() > kWarningThreshold) + if (c.balance() > WarningThreshold) { using ct = beast::AbstractClock; - c.entry().localBalance = - DecayingSample{steady_clock::now()}; + c.entry().local_balance = + DecayingSample{steady_clock::now()}; } }; - for (auto i = 0; i < xrpl::RPC::Tuning::kNoRippleCheck.rmax + 5; ++i) + for (auto i = 0; i < xrpl::RPC::Tuning::kNO_RIPPLE_CHECK.rmax + 5; ++i) { if (!admin) checkBalance(); @@ -311,13 +311,13 @@ class NoRippleCheckLimits_test : public beast::unit_test::Suite env.memoize(gw); auto const baseFee = env.current()->fees().base; env(pay(env.master, gw, XRP(1000)), - Seq(kAutofill), + Seq(kAUTOFILL), Fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1), - Sig(kAutofill)); + Sig(kAUTOFILL)); env(fset(gw, asfDefaultRipple), - Seq(kAutofill), + Seq(kAUTOFILL), Fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1), - Sig(kAutofill)); + Sig(kAUTOFILL)); env(trust(alice, gw["USD"](10)), Fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1)); env.close(); diff --git a/src/test/rpc/OwnerInfo_test.cpp b/src/test/rpc/OwnerInfo_test.cpp index dc1e18f9d0..5704138272 100644 --- a/src/test/rpc/OwnerInfo_test.cpp +++ b/src/test/rpc/OwnerInfo_test.cpp @@ -56,8 +56,8 @@ class OwnerInfo_test : public beast::unit_test::Suite json::Value params; params[jss::account] = Account{"bob"}.human(); auto const result = env.rpc("json", "owner_info", to_string(params))[jss::result]; - BEAST_EXPECT(result[jss::accepted] == json::ValueType::Object); - BEAST_EXPECT(result[jss::current] == json::ValueType::Object); + BEAST_EXPECT(result[jss::accepted] == json::ObjectValue); + BEAST_EXPECT(result[jss::current] == json::ObjectValue); BEAST_EXPECT(result[jss::status] == "success"); } } @@ -103,23 +103,21 @@ class OwnerInfo_test : public beast::unit_test::Suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == (STAmount{Issue{toCurrency("CNY"), noAccount()}, 0}.value().getJson( - JsonOptions::Values::None))); + JsonOptions::KNone))); BEAST_EXPECT( lines[0u][sfHighLimit.fieldName] == - alice["CNY"](1000).value().getJson(JsonOptions::Values::None)); + alice["CNY"](1000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( - lines[0u][sfLowLimit.fieldName] == - gw["CNY"](0).value().getJson(JsonOptions::Values::None)); + lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == (STAmount{Issue{toCurrency("USD"), noAccount()}, 0}.value().getJson( - JsonOptions::Values::None))); + JsonOptions::KNone))); BEAST_EXPECT( lines[1u][sfHighLimit.fieldName] == - alice["USD"](1000).value().getJson(JsonOptions::Values::None)); - BEAST_EXPECT( - lines[1u][sfLowLimit.fieldName] == usd(0).value().getJson(JsonOptions::Values::None)); + alice["USD"](1000).value().getJson(JsonOptions::KNone)); + BEAST_EXPECT(lines[1u][sfLowLimit.fieldName] == usd(0).value().getJson(JsonOptions::KNone)); if (!BEAST_EXPECT(result[jss::accepted].isMember(jss::offers))) return; @@ -129,10 +127,9 @@ class OwnerInfo_test : public beast::unit_test::Suite BEAST_EXPECT(offers[0u][jss::Account] == alice.human()); BEAST_EXPECT( - offers[0u][sfTakerGets.fieldName] == - XRP(1000).value().getJson(JsonOptions::Values::None)); + offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( - offers[0u][sfTakerPays.fieldName] == usd(1).value().getJson(JsonOptions::Values::None)); + offers[0u][sfTakerPays.fieldName] == usd(1).value().getJson(JsonOptions::KNone)); // current ledger entry if (!BEAST_EXPECT(result[jss::current].isMember(jss::ripple_lines))) @@ -144,24 +141,22 @@ class OwnerInfo_test : public beast::unit_test::Suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == (STAmount{Issue{toCurrency("CNY"), noAccount()}, -50}.value().getJson( - JsonOptions::Values::None))); + JsonOptions::KNone))); BEAST_EXPECT( lines[0u][sfHighLimit.fieldName] == - alice["CNY"](1000).value().getJson(JsonOptions::Values::None)); + alice["CNY"](1000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( - lines[0u][sfLowLimit.fieldName] == - gw["CNY"](0).value().getJson(JsonOptions::Values::None)); + lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == (STAmount{Issue{toCurrency("USD"), noAccount()}, -50}.value().getJson( - JsonOptions::Values::None))); + JsonOptions::KNone))); BEAST_EXPECT( lines[1u][sfHighLimit.fieldName] == - alice["USD"](1000).value().getJson(JsonOptions::Values::None)); + alice["USD"](1000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( - lines[1u][sfLowLimit.fieldName] == - gw["USD"](0).value().getJson(JsonOptions::Values::None)); + lines[1u][sfLowLimit.fieldName] == gw["USD"](0).value().getJson(JsonOptions::KNone)); if (!BEAST_EXPECT(result[jss::current].isMember(jss::offers))) return; @@ -173,10 +168,9 @@ 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::Values::None)); + offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::KNone)); BEAST_EXPECT( - offers[0u][sfTakerPays.fieldName] == cny(2).value().getJson(JsonOptions::Values::None)); + offers[0u][sfTakerPays.fieldName] == cny(2).value().getJson(JsonOptions::KNone)); } public: diff --git a/src/test/rpc/RPCCall_test.cpp b/src/test/rpc/RPCCall_test.cpp index cd3cd3cb41..436044e771 100644 --- a/src/test/rpc/RPCCall_test.cpp +++ b/src/test/rpc/RPCCall_test.cpp @@ -66,7 +66,7 @@ struct RPCCallTestData operator=(RPCCallTestData&&) = delete; }; -static RPCCallTestData const kRpcCallTestArray[] = { +static RPCCallTestData const kRPC_CALL_TEST_ARRAY[] = { // account_channels // ------------------------------------------------------------ {"account_channels: minimal.", @@ -5832,9 +5832,9 @@ std::string updateAPIVersionString(char const* const req, unsigned apiVersion) { std::string const versionStr = std::to_string(apiVersion); - static auto const kPlaceHolder = "%API_VER%"; + static auto const kPLACE_HOLDER = "%API_VER%"; std::string jr(req); - boost::replace_all(jr, kPlaceHolder, versionStr); + boost::replace_all(jr, kPLACE_HOLDER, versionStr); return jr; } @@ -5843,7 +5843,7 @@ makeNetworkConfig(uint32_t networkID) { using namespace test::jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->networkId = networkID; + cfg->NETWORK_ID = networkID; return cfg; }); } @@ -5856,14 +5856,14 @@ public: { testcase << "RPCCall API version " << apiVersion; if (!BEAST_EXPECT( - apiVersion >= RPC::kApiMinimumSupportedVersion && - apiVersion <= RPC::kApiMaximumValidVersion)) + apiVersion >= RPC::kAPI_MINIMUM_SUPPORTED_VERSION && + apiVersion <= RPC::kAPI_MAXIMUM_VALID_VERSION)) return; test::jtx::Env const env(*this, makeNetworkConfig(11111)); // Used only for its Journal. // For each RPCCall test. - for (RPCCallTestData const& rpcCallTest : kRpcCallTestArray) + for (RPCCallTestData const& rpcCallTest : kRPC_CALL_TEST_ARRAY) { if (!BEAST_EXPECT(!rpcCallTest.exp.empty())) break; @@ -5871,11 +5871,11 @@ public: std::vector const args{rpcCallTest.args.begin(), rpcCallTest.args.end()}; char const* const expVersioned = - (apiVersion - RPC::kApiMinimumSupportedVersion) < rpcCallTest.exp.size() - ? rpcCallTest.exp[apiVersion - RPC::kApiMinimumSupportedVersion] + (apiVersion - RPC::kAPI_MINIMUM_SUPPORTED_VERSION) < rpcCallTest.exp.size() + ? rpcCallTest.exp[apiVersion - RPC::kAPI_MINIMUM_SUPPORTED_VERSION] : rpcCallTest.exp.back(); - // Note that, over the long term, kNone of these tests should + // Note that, over the long term, kNONE of these tests should // throw. But, for the moment, some of them do. So handle it. json::Value got; try diff --git a/src/test/rpc/RPCHelpers_test.cpp b/src/test/rpc/RPCHelpers_test.cpp index 1458c0aa80..8896bd081b 100644 --- a/src/test/rpc/RPCHelpers_test.cpp +++ b/src/test/rpc/RPCHelpers_test.cpp @@ -18,7 +18,7 @@ public: testcase("ChooseLedgerEntryType"); // Test no type. - json::Value tx = json::ValueType::Object; + json::Value tx = json::ObjectValue; auto result = RPC::chooseLedgerEntryType(tx); BEAST_EXPECT(result.first == RPC::Status::kOK); BEAST_EXPECT(result.second == 0); diff --git a/src/test/rpc/RPCOverload_test.cpp b/src/test/rpc/RPCOverload_test.cpp index b1030ebea5..c483c2f694 100644 --- a/src/test/rpc/RPCOverload_test.cpp +++ b/src/test/rpc/RPCOverload_test.cpp @@ -40,7 +40,7 @@ public: std::unique_ptr client = useWS ? makeWSClient(env.app().config()) : makeJSONRPCClient(env.app().config()); - json::Value tx = json::ValueType::Object; + json::Value tx = json::ObjectValue; tx[jss::tx_json] = pay(alice, bob, XRP(1)); tx[jss::secret] = toBase58(generateSeed("alice")); diff --git a/src/test/rpc/RobustTransaction_test.cpp b/src/test/rpc/RobustTransaction_test.cpp index 99668aff39..03339e1a78 100644 --- a/src/test/rpc/RobustTransaction_test.cpp +++ b/src/test/rpc/RobustTransaction_test.cpp @@ -32,7 +32,7 @@ public: { // RPC subscribe to transactions stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("transactions"); jv = wsc->invoke("subscribe", jv); BEAST_EXPECT(jv[jss::status] == "success"); @@ -123,7 +123,7 @@ public: { // RPC unsubscribe to transactions stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("transactions"); jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) @@ -242,7 +242,7 @@ public: { // RPC subscribe to ledger stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("ledger"); jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) @@ -276,7 +276,7 @@ public: { // RPC unsubscribe to ledger stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("ledger"); jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) @@ -295,7 +295,7 @@ public: { // RPC subscribe to ledger stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("ledger"); jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) @@ -329,7 +329,7 @@ public: { // RPC unsubscribe to ledger stream json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams].append("ledger"); jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) @@ -378,7 +378,7 @@ public: { // RPC subscribe to accounts_proposed stream json::Value jv; - jv[jss::accounts_proposed] = json::ValueType::Array; + jv[jss::accounts_proposed] = json::ArrayValue; jv[jss::accounts_proposed].append(Account("alice").human()); jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) @@ -416,7 +416,7 @@ public: { // RPC unsubscribe to accounts_proposed stream json::Value jv; - jv[jss::accounts_proposed] = json::ValueType::Array; + jv[jss::accounts_proposed] = json::ArrayValue; jv[jss::accounts_proposed].append(Account("alice").human()); jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) diff --git a/src/test/rpc/ServerDefinitions_test.cpp b/src/test/rpc/ServerDefinitions_test.cpp index bac1b4f7a5..d53c845726 100644 --- a/src/test/rpc/ServerDefinitions_test.cpp +++ b/src/test/rpc/ServerDefinitions_test.cpp @@ -8,9 +8,6 @@ #include #include -#include -#include - namespace xrpl::test { class ServerDefinitions_test : public beast::unit_test::Suite @@ -40,23 +37,20 @@ public: { auto const firstField = result[jss::result][jss::FIELDS][0u]; - BEAST_EXPECT(firstField[0u].asString() == "Invalid"); + 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::isVLEncoded].asBool() == false); - BEAST_EXPECT(firstField[1][jss::nth].asInt() == -1); + BEAST_EXPECT(firstField[1][jss::nth].asUInt() == 0); BEAST_EXPECT(firstField[1][jss::type].asString() == "Unknown"); } - { - auto const field = result[jss::result][jss::FIELDS][6u]; - BEAST_EXPECT(field[0u].asString() == "LedgerEntryType"); - BEAST_EXPECT(field[1][jss::isSerialized].asBool() == true); - BEAST_EXPECT(field[1][jss::isSigningField].asBool() == true); - BEAST_EXPECT(field[1][jss::isVLEncoded].asBool() == false); - BEAST_EXPECT(field[1][jss::nth].asUInt() == 1); - BEAST_EXPECT(field[1][jss::type].asString() == "UInt16"); - } + 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 { @@ -80,34 +74,17 @@ public: BEAST_EXPECT(fieldExists("index")); } - // verify no duplicate field names in FIELDS array - { - std::set fieldNames; - for (auto const& field : result[jss::result][jss::FIELDS]) - { - auto const name = field[0u].asString(); - BEAST_EXPECT(fieldNames.insert(name).second); - } - } - // test that base_uint types are replaced with "Hash" prefix { auto const types = result[jss::result][jss::TYPES]; - BEAST_EXPECT(types.isMember("Hash128") && types["Hash128"].asUInt() == 4); - BEAST_EXPECT(types.isMember("Hash160") && types["Hash160"].asUInt() == 17); - BEAST_EXPECT(types.isMember("Hash192") && types["Hash192"].asUInt() == 21); - BEAST_EXPECT(types.isMember("Hash256") && types["Hash256"].asUInt() == 5); - BEAST_EXPECT(types.isMember("Hash384") && types["Hash384"].asUInt() == 22); - BEAST_EXPECT(types.isMember("Hash512") && types["Hash512"].asUInt() == 23); + BEAST_EXPECT(types["Hash128"].asUInt() == 4); + BEAST_EXPECT(types["Hash160"].asUInt() == 17); + BEAST_EXPECT(types["Hash192"].asUInt() == 21); + BEAST_EXPECT(types["Hash256"].asUInt() == 5); + BEAST_EXPECT(types["Hash384"].asUInt() == 22); + BEAST_EXPECT(types["Hash512"].asUInt() == 23); } - 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); - // test the properties of the LEDGER_ENTRY_FLAGS section { BEAST_EXPECT(result[jss::result].isMember(jss::LEDGER_ENTRY_FLAGS)); diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 1d52f3b83e..b47d37c0cf 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -16,9 +16,9 @@ namespace xrpl::test { namespace validator_data { -static auto const kPublicKey = "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; +static auto const kPUBLIC_KEY = "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; -static auto const kToken = +static auto const kTOKEN = "eyJ2YWxpZGF0aW9uX3NlY3JldF9rZXkiOiI5ZWQ0NWY4NjYyNDFjYzE4YTI3NDdiNT\n" "QzODdjMDYyNTkwNzk3MmY0ZTcxOTAyMzFmYWE5Mzc0NTdmYTlkYWY2IiwibWFuaWZl\n" "c3QiOiJKQUFBQUFGeEllMUZ0d21pbXZHdEgyaUNjTUpxQzlnVkZLaWxHZncxL3ZDeE\n" @@ -54,7 +54,8 @@ protocol = wss2 admin = 127.0.0.1 )xrpldConfig"); - p->loadFromString(boost::str(toLoad % validator_data::kToken % validator_data::kPublicKey)); + p->loadFromString( + boost::str(toLoad % validator_data::kTOKEN % validator_data::kPUBLIC_KEY)); setupConfigForUnitTests(*p); @@ -121,7 +122,7 @@ admin = 127.0.0.1 BEAST_EXPECT(result[jss::result].isMember(jss::info)); BEAST_EXPECT( result[jss::result][jss::info][jss::pubkey_validator] == - validator_data::kPublicKey); + validator_data::kPUBLIC_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 9206bf42ac..ca5fa2133c 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -66,7 +66,7 @@ class Simulate_test : public beast::unit_test::Suite { auto const unHexed = strUnHex(result[jss::tx_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); // NOLINT(bugprone-unchecked-optional-access) - txJson = STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); + txJson = STObject(std::ref(sitTrans), kSF_GENERIC).getJson(JsonOptions::KNone); } BEAST_EXPECT(txJson[jss::TransactionType] == tx[jss::TransactionType]); BEAST_EXPECT(txJson[jss::Account] == tx[jss::Account]); @@ -162,7 +162,7 @@ class Simulate_test : public beast::unit_test::Suite { auto unHexed = strUnHex(txResult[jss::meta_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); // NOLINT(bugprone-unchecked-optional-access) - return STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); + return STObject(std::ref(sitTrans), kSF_GENERIC).getJson(JsonOptions::KNone); } return txResult[jss::meta]; @@ -179,7 +179,7 @@ class Simulate_test : public beast::unit_test::Suite { // No params - json::Value const params = json::ValueType::Object; + json::Value const params = json::ObjectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); BEAST_EXPECT( resp[jss::result][jss::error_message] == @@ -187,8 +187,8 @@ class Simulate_test : public beast::unit_test::Suite } { // Providing both `tx_json` and `tx_blob` - json::Value params = json::ValueType::Object; - params[jss::tx_json] = json::ValueType::Object; + json::Value params = json::ObjectValue; + params[jss::tx_json] = json::ObjectValue; params[jss::tx_blob] = "1200"; auto const resp = env.rpc("json", "simulate", to_string(params)); @@ -198,7 +198,7 @@ class Simulate_test : public beast::unit_test::Suite } { // `binary` isn't a boolean - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::tx_blob] = "1200"; params[jss::binary] = "100"; auto const resp = env.rpc("json", "simulate", to_string(params)); @@ -206,7 +206,7 @@ class Simulate_test : public beast::unit_test::Suite } { // Invalid `tx_blob` - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::tx_blob] = "12"; auto const resp = env.rpc("json", "simulate", to_string(params)); @@ -214,8 +214,8 @@ class Simulate_test : public beast::unit_test::Suite } { // Empty `tx_json` - json::Value params = json::ValueType::Object; - params[jss::tx_json] = json::ValueType::Object; + json::Value params = json::ObjectValue; + params[jss::tx_json] = json::ObjectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); BEAST_EXPECT( @@ -223,8 +223,8 @@ class Simulate_test : public beast::unit_test::Suite } { // No tx.Account - json::Value params = json::ValueType::Object; - json::Value txJson = json::ValueType::Object; + json::Value params = json::ObjectValue; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::Payment; params[jss::tx_json] = txJson; @@ -233,7 +233,7 @@ class Simulate_test : public beast::unit_test::Suite } { // Empty `tx_blob` - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::tx_blob] = ""; auto const resp = env.rpc("json", "simulate", to_string(params)); @@ -249,7 +249,7 @@ class Simulate_test : public beast::unit_test::Suite } { // Non-object `tx_json` - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::tx_json] = ""; auto const resp = env.rpc("json", "simulate", to_string(params)); @@ -258,9 +258,9 @@ class Simulate_test : public beast::unit_test::Suite } { // `seed` field included - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::seed] = "random_data"; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); params[jss::tx_json] = txJson; @@ -269,9 +269,9 @@ class Simulate_test : public beast::unit_test::Suite } { // `secret` field included - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::secret] = "random_data"; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); params[jss::tx_json] = txJson; @@ -280,9 +280,9 @@ class Simulate_test : public beast::unit_test::Suite } { // `seed_hex` field included - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::seed_hex] = "random_data"; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); params[jss::tx_json] = txJson; @@ -291,9 +291,9 @@ class Simulate_test : public beast::unit_test::Suite } { // `passphrase` field included - json::Value params = json::ValueType::Object; + json::Value params = json::ObjectValue; params[jss::passphrase] = "random_data"; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); params[jss::tx_json] = txJson; @@ -302,8 +302,8 @@ class Simulate_test : public beast::unit_test::Suite } { // Invalid transaction - json::Value params = json::ValueType::Object; - json::Value txJson = json::ValueType::Object; + json::Value params = json::ObjectValue; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::Payment; txJson[jss::Account] = env.master.human(); params[jss::tx_json] = txJson; @@ -316,7 +316,7 @@ class Simulate_test : public beast::unit_test::Suite { // Bad account json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = "badAccount"; params[jss::tx_json] = txJson; @@ -330,7 +330,7 @@ class Simulate_test : public beast::unit_test::Suite { // Account doesn't exist for Sequence autofill json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = alice.human(); params[jss::tx_json] = txJson; @@ -341,7 +341,7 @@ class Simulate_test : public beast::unit_test::Suite { // Invalid Signers field json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); txJson[sfSigners] = "1"; @@ -353,10 +353,10 @@ class Simulate_test : public beast::unit_test::Suite { // Invalid Signers field json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); - txJson[sfSigners] = json::ValueType::Array; + txJson[sfSigners] = json::ArrayValue; txJson[sfSigners].append("1"); params[jss::tx_json] = txJson; @@ -366,7 +366,7 @@ class Simulate_test : public beast::unit_test::Suite { // Invalid transaction json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); txJson["foo"] = "bar"; @@ -378,7 +378,7 @@ class Simulate_test : public beast::unit_test::Suite } { // non-`"binary"` second param for CLI - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = alice.human(); auto const resp = env.rpc("simulate", to_string(txJson), "1"); @@ -387,7 +387,7 @@ class Simulate_test : public beast::unit_test::Suite { // Signed transaction json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); txJson[jss::TxnSignature] = "1200ABCD"; @@ -400,10 +400,10 @@ class Simulate_test : public beast::unit_test::Suite { // Signed multisig transaction json::Value params; - json::Value txJson = json::ValueType::Object; + json::Value txJson = json::ObjectValue; txJson[jss::TransactionType] = jss::AccountSet; txJson[jss::Account] = env.master.human(); - txJson[sfSigners] = json::ValueType::Array; + txJson[sfSigners] = json::ArrayValue; { json::Value signer; signer[jss::Account] = alice.human(); @@ -492,10 +492,10 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->networkId = 0; + cfg->NETWORK_ID = 0; return cfg; })}; - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; { auto validateOutput = [&](json::Value const& resp, json::Value const& tx) { @@ -521,7 +521,7 @@ class Simulate_test : public beast::unit_test::Suite auto modifiedNode = node[sfModifiedNode]; BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; - BEAST_EXPECT(finalFields[sfDomain] == kNewDomain); + BEAST_EXPECT(finalFields[sfDomain] == kNEW_DOMAIN); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); @@ -533,7 +533,7 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = env.master.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; + tx[sfDomain] = kNEW_DOMAIN; // test with autofill testTx(env, tx, validateOutput); @@ -666,7 +666,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env(*this); - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; Account const alice("alice"); Account const becky("becky"); Account const carol("carol"); @@ -706,7 +706,7 @@ class Simulate_test : public beast::unit_test::Suite auto modifiedNode = node[sfModifiedNode]; BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; - BEAST_EXPECT(finalFields[sfDomain] == kNewDomain); + BEAST_EXPECT(finalFields[sfDomain] == kNEW_DOMAIN); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); @@ -718,12 +718,12 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = alice.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; + tx[sfDomain] = kNEW_DOMAIN; // test with autofill testTx(env, tx, validateOutput, false); - tx[sfSigners] = json::ValueType::Array; + tx[sfSigners] = json::ArrayValue; { json::Value signer; signer[jss::Account] = becky.human(); @@ -755,7 +755,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env(*this); - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; Account const alice{"alice"}; env(regkey(env.master, alice)); env(fset(env.master, asfDisableMaster), Sig(env.master)); @@ -779,7 +779,7 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = env.master.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; + tx[sfDomain] = kNEW_DOMAIN; // master key is disabled, so this is invalid tx[jss::SigningPubKey] = strHex(env.master.pk().slice()); @@ -804,7 +804,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env(*this); - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; Account const alice("alice"); Account const becky("becky"); Account const carol("carol"); @@ -834,10 +834,10 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = env.master.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; + tx[sfDomain] = kNEW_DOMAIN; // master key is disabled, so this is invalid tx[jss::SigningPubKey] = strHex(env.master.pk().slice()); - tx[sfSigners] = json::ValueType::Array; + tx[sfSigners] = json::ArrayValue; { json::Value signer; signer[jss::Account] = becky.human(); @@ -867,7 +867,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env(*this); - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; Account const alice("alice"); Account const becky("becky"); Account const carol("carol"); @@ -899,8 +899,8 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = alice.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; - tx[sfSigners] = json::ValueType::Array; + tx[sfDomain] = kNEW_DOMAIN; + tx[sfSigners] = json::ArrayValue; { json::Value signer; signer[jss::Account] = becky.human(); @@ -1032,10 +1032,10 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->networkId = 1025; + cfg->NETWORK_ID = 1025; return cfg; })}; - static auto const kNewDomain = "123ABC"; + static auto const kNEW_DOMAIN = "123ABC"; { auto validateOutput = [&](json::Value const& resp, json::Value const& tx) { @@ -1061,7 +1061,7 @@ class Simulate_test : public beast::unit_test::Suite auto modifiedNode = node[sfModifiedNode]; BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; - BEAST_EXPECT(finalFields[sfDomain] == kNewDomain); + BEAST_EXPECT(finalFields[sfDomain] == kNEW_DOMAIN); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); @@ -1073,7 +1073,7 @@ class Simulate_test : public beast::unit_test::Suite tx[jss::Account] = env.master.human(); tx[jss::TransactionType] = jss::AccountSet; - tx[sfDomain] = kNewDomain; + tx[sfDomain] = kNEW_DOMAIN; // test with autofill testTx(env, tx, validateOutput); @@ -1097,7 +1097,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; using namespace std::chrono_literals; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->networkId = 1025; + cfg->NETWORK_ID = 1025; return cfg; })}; diff --git a/src/test/rpc/Submit_test.cpp b/src/test/rpc/Submit_test.cpp index 8dff2d75ec..fe86a6c550 100644 --- a/src/test/rpc/Submit_test.cpp +++ b/src/test/rpc/Submit_test.cpp @@ -60,8 +60,8 @@ public: testInvalidFailHard(1); testInvalidFailHard(0); testInvalidFailHard(1.5); - testInvalidFailHard(json::Value(json::ValueType::Object)); - testInvalidFailHard(json::Value(json::ValueType::Array)); + testInvalidFailHard(json::Value(json::ObjectValue)); + testInvalidFailHard(json::Value(json::ArrayValue)); // Valid boolean values should work (not return invalidParams) { diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index 090a599e7c..78dc7fcf30 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -70,7 +70,7 @@ public: { // RPC subscribe to server stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("server"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -136,7 +136,7 @@ public: { // RPC subscribe to ledger stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("ledger"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -195,7 +195,7 @@ public: { // RPC subscribe to transactions stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("transactions"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -267,8 +267,8 @@ public: { // RPC subscribe to accounts stream - stream = json::ValueType::Object; - stream[jss::accounts] = json::ValueType::Array; + stream = json::ObjectValue; + stream[jss::accounts] = json::ArrayValue; stream[jss::accounts].append(Account("alice").human()); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -321,17 +321,17 @@ public: using namespace std::chrono_literals; using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; cfg = singleThreadIo(std::move(cfg)); return cfg; })); auto wsc = makeWSClient(env.app().config()); - json::Value stream{json::ValueType::Object}; + json::Value stream{json::ObjectValue}; { // RPC subscribe to transactions stream stream[jss::api_version] = 2; - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("transactions"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -401,7 +401,7 @@ public: { // RPC subscribe to manifests stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("manifests"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -447,7 +447,7 @@ public: { // RPC subscribe to validations stream - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("validations"); auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) @@ -474,7 +474,7 @@ public: if (jv[jss::ledger_index] != std::to_string(env.closed()->header().seq)) return false; - if (jv[jss::flags] != (kVfFullyCanonicalSig | kVfFullValidation)) + if (jv[jss::flags] != (kVF_FULLY_CANONICAL_SIG | kVF_FULL_VALIDATION)) return false; if (jv[jss::full] != true) @@ -546,7 +546,7 @@ public: jv[jss::url] = "http://localhost/events"; jv[jss::url_username] = "admin"; jv[jss::url_password] = "password"; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams][0u] = "validations"; auto jr = env.rpc("json", "subscribe", to_string(jv))[jss::result]; BEAST_EXPECT(jr[jss::status] == "success"); @@ -616,13 +616,13 @@ public: } std::initializer_list const nonArrays{ - json::ValueType::Null, - json::ValueType::Int, - json::ValueType::UInt, - json::ValueType::Real, + json::NullValue, + json::IntValue, + json::UintValue, + json::RealValue, "", - json::ValueType::Boolean, - json::ValueType::Object}; + json::BooleanValue, + json::ObjectValue}; for (auto const& f : {jss::accounts_proposed, jss::accounts}) { @@ -637,7 +637,7 @@ public: { json::Value jv; - jv[f] = json::ValueType::Array; + jv[f] = json::ArrayValue; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "actMalformed"); BEAST_EXPECT(jr[jss::error_message] == "Account malformed."); @@ -655,7 +655,7 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; + jv[jss::books] = json::ArrayValue; jv[jss::books][0u] = 1; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "invalidParams"); @@ -664,10 +664,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object; + jv[jss::books] = json::ArrayValue; + jv[jss::books][0u] = json::ObjectValue; + jv[jss::books][0u][jss::taker_gets] = json::ObjectValue; + jv[jss::books][0u][jss::taker_pays] = json::ObjectValue; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcCurMalformed"); @@ -676,10 +676,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object; + jv[jss::books] = json::ArrayValue; + jv[jss::books][0u] = json::ObjectValue; + 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] = "ZZZZ"; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcCurMalformed"); @@ -688,10 +688,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object; + jv[jss::books] = json::ArrayValue; + jv[jss::books][0u] = json::ObjectValue; + 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] = 1; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -701,10 +701,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object; - jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object; + jv[jss::books] = json::ArrayValue; + jv[jss::books][0u] = json::ObjectValue; + 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"; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -714,11 +714,11 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); - jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object; + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); + jv[jss::books][0u][jss::taker_gets] = json::ObjectValue; auto const 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"); @@ -728,10 +728,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "ZZZZ"; auto const jr = wsc->invoke(method, jv)[jss::result]; // NOTE: this error is slightly incongruous with the @@ -743,10 +743,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD"; jv[jss::books][0u][jss::taker_gets][jss::issuer] = 1; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -756,10 +756,10 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD"; jv[jss::books][0u][jss::taker_gets][jss::issuer] = Account{"gateway"}.human() + "DEAD"; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -769,12 +769,12 @@ public: { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets] = - Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "badMarket"); BEAST_EXPECT(jr[jss::error_message] == "No such market."); @@ -791,7 +791,7 @@ public: { json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams][0u] = 1; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "malformedStream"); @@ -800,7 +800,7 @@ public: { json::Value jv; - jv[jss::streams] = json::ValueType::Array; + jv[jss::streams] = json::ArrayValue; jv[jss::streams][0u] = "not_a_stream"; auto const jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "malformedStream"); @@ -812,10 +812,10 @@ public: // invalid taker - not a string { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP"; jv[jss::books][0u][jss::taker] = 1; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -826,10 +826,10 @@ public: // invalid taker - malformed account string { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP"; jv[jss::books][0u][jss::taker] = "not_an_account"; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -840,10 +840,10 @@ public: // invalid taker - account string with extra characters { json::Value jv; - jv[jss::books] = json::ValueType::Array; - jv[jss::books][0u] = json::ValueType::Object; + 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::Values::IncludeDate); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::KIncludeDate); jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP"; jv[jss::books][0u][jss::taker] = Account{"alice"}.human() + "DEAD"; auto const jr = wsc->invoke(method, jv)[jss::result]; @@ -932,9 +932,9 @@ public: auto& from = (i % 2 == 0) ? a : b; auto& to = (i % 2 == 0) ? b : a; env(pay(from, to, jtx::XRP(numXRP)), - jtx::Seq(jtx::kAutofill), - jtx::Fee(jtx::kAutofill), - jtx::Sig(jtx::kAutofill)); + jtx::Seq(jtx::kAUTOFILL), + jtx::Fee(jtx::kAUTOFILL), + jtx::Sig(jtx::kAUTOFILL)); } for (int i = 0; i < ledgersToClose; ++i) BEAST_EXPECT(env.syncClose()); @@ -1033,7 +1033,7 @@ public: Env env(*this, singleThreadIo(envconfig())); auto wscTxHistory = makeWSClient(env.app().config()); json::Value request; - request[jss::account_history_tx_stream] = json::ValueType::Object; + request[jss::account_history_tx_stream] = json::ObjectValue; request[jss::account_history_tx_stream][jss::account] = alice.human(); auto jv = wscTxHistory->invoke("subscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) @@ -1076,7 +1076,7 @@ public: Env env(*this, singleThreadIo(envconfig())); auto wscTxHistory = makeWSClient(env.app().config()); json::Value request; - request[jss::account_history_tx_stream] = json::ValueType::Object; + request[jss::account_history_tx_stream] = json::ObjectValue; request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; auto jv = wscTxHistory->invoke("subscribe", request); @@ -1159,8 +1159,8 @@ public: BEAST_EXPECT(env.syncClose()); // subscribe account - json::Value stream = json::ValueType::Object; - stream[jss::accounts] = json::ValueType::Array; + json::Value stream = json::ObjectValue; + stream[jss::accounts] = json::ArrayValue; stream[jss::accounts].append(alice.human()); auto jv = wscAccount->invoke("subscribe", stream); @@ -1172,7 +1172,7 @@ public: // subscribe account tx history json::Value request; - request[jss::account_history_tx_stream] = json::ValueType::Object; + request[jss::account_history_tx_stream] = json::ObjectValue; request[jss::account_history_tx_stream][jss::account] = alice.human(); jv = wscTxHistory->invoke("subscribe", request); @@ -1236,7 +1236,7 @@ public: // subscribe json::Value request; - request[jss::account_history_tx_stream] = json::ValueType::Object; + request[jss::account_history_tx_stream] = json::ObjectValue; request[jss::account_history_tx_stream][jss::account] = carol.human(); auto ws = makeWSClient(env.app().config()); auto jv = ws->invoke("subscribe", request); @@ -1270,7 +1270,7 @@ public: // subscribe json::Value request; - request[jss::account_history_tx_stream] = json::ValueType::Object; + request[jss::account_history_tx_stream] = json::ObjectValue; request[jss::account_history_tx_stream][jss::account] = carol.human(); auto wscLong = makeWSClient(env.app().config()); auto jv = wscLong->invoke("subscribe", request); @@ -1319,12 +1319,12 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.usd; + auto const usd = permDex.USD; auto wsc = makeWSClient(env.app().config()); json::Value streams; - streams[jss::streams] = json::ValueType::Array; + streams[jss::streams] = json::ArrayValue; streams[jss::streams][0u] = "book_changes"; auto jv = wsc->invoke("subscribe", streams); @@ -1380,7 +1380,7 @@ public: auto wsc = test::makeWSClient(env.app().config()); json::Value stream; - stream[jss::streams] = json::ValueType::Array; + stream[jss::streams] = json::ArrayValue; stream[jss::streams].append("transactions"); auto jv = wsc->invoke("subscribe", stream); diff --git a/src/test/rpc/TransactionEntry_test.cpp b/src/test/rpc/TransactionEntry_test.cpp index 8724e2974d..ff0897f59a 100644 --- a/src/test/rpc/TransactionEntry_test.cpp +++ b/src/test/rpc/TransactionEntry_test.cpp @@ -32,7 +32,7 @@ class TransactionEntry_test : public beast::unit_test::Suite testcase("Invalid request params"); using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })}; @@ -44,7 +44,7 @@ class TransactionEntry_test : public beast::unit_test::Suite } { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::ledger] = 20; auto const result = env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "lgrNotFound"); @@ -52,7 +52,7 @@ class TransactionEntry_test : public beast::unit_test::Suite } { - json::Value params{json::ValueType::Object}; + 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]; @@ -61,7 +61,7 @@ class TransactionEntry_test : public beast::unit_test::Suite } { - json::Value params{json::ValueType::Object}; + 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]; @@ -139,7 +139,7 @@ class TransactionEntry_test : public beast::unit_test::Suite testcase("Basic request API version " + std::to_string(apiVersion)); using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })}; @@ -151,7 +151,7 @@ class TransactionEntry_test : public beast::unit_test::Suite std::string const closeTimeIso = "") { // first request using ledger_index to lookup json::Value const resIndex{[&env, index, &txhash, apiVersion]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::ledger_index] = index; params[jss::tx_hash] = txhash; params[jss::api_version] = apiVersion; @@ -206,7 +206,7 @@ class TransactionEntry_test : public beast::unit_test::Suite // second request using ledger_hash to lookup and verify // both responses match { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::ledger_hash] = resIndex[jss::ledger_hash]; params[jss::tx_hash] = txhash; params[jss::api_version] = apiVersion; diff --git a/src/test/rpc/TransactionHistory_test.cpp b/src/test/rpc/TransactionHistory_test.cpp index 6227a1b75b..8adf28fc9b 100644 --- a/src/test/rpc/TransactionHistory_test.cpp +++ b/src/test/rpc/TransactionHistory_test.cpp @@ -36,7 +36,7 @@ class TransactionHistory_test : public beast::unit_test::Suite { // test at 1 greater than the allowed non-admin limit - json::Value params{json::ValueType::Object}; + 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]; BEAST_EXPECT(result[jss::error] == "noPermission"); @@ -51,7 +51,7 @@ class TransactionHistory_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, envconfig(noAdmin)}; - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::api_version] = 2; auto const result = env.client().invoke("tx_history", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "unknownCmd"); @@ -86,7 +86,7 @@ class TransactionHistory_test : public beast::unit_test::Suite // verify the latest transaction in env (offer) // is available in tx_history. - json::Value params{json::ValueType::Object}; + 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)) @@ -94,7 +94,7 @@ class TransactionHistory_test : public beast::unit_test::Suite // search for a tx in history matching the last offer bool const txFound = [&] { - auto const toFind = env.tx()->getJson(JsonOptions::Values::None); + auto const toFind = env.tx()->getJson(JsonOptions::KNone); for (auto tx : result[jss::txs]) { tx.removeMember(jss::inLedger); @@ -113,7 +113,7 @@ class TransactionHistory_test : public beast::unit_test::Suite std::unordered_map typeCounts; while (start < 120) { - json::Value params{json::ValueType::Object}; + 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)) @@ -133,7 +133,7 @@ class TransactionHistory_test : public beast::unit_test::Suite // also, try a request with max non-admin start value { - json::Value params{json::ValueType::Object}; + 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]; BEAST_EXPECT(result[jss::status] == "success"); diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index 8c50736b85..8374abe445 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -47,7 +47,7 @@ class Transaction_test : public beast::unit_test::Suite { using namespace test::jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->networkId = networkID; + cfg->NETWORK_ID = networkID; return cfg; }); } @@ -697,7 +697,7 @@ class Transaction_test : public beast::unit_test::Suite json::Value params; params[jss::id] = 1; - auto const hash = env.tx()->getJson(JsonOptions::Values::None)[jss::hash]; + auto const hash = env.tx()->getJson(JsonOptions::KNone)[jss::hash]; params[jss::transaction] = hash; auto const jrr = env.rpc("json", "tx", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::hash] == hash); @@ -749,7 +749,7 @@ class Transaction_test : public beast::unit_test::Suite using std::to_string; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })}; Account const alice{"alice"}; @@ -771,7 +771,7 @@ class Transaction_test : public beast::unit_test::Suite std::shared_ptr const meta = env.closed()->txRead(env.tx()->getTransactionID()).second; - json::Value expected = txn->getJson(JsonOptions::Values::None); + json::Value expected = txn->getJson(JsonOptions::KNone); expected[jss::DeliverMax] = expected[jss::Amount]; if (apiVersion > 1) { @@ -780,7 +780,7 @@ class Transaction_test : public beast::unit_test::Suite } json::Value const result = {[&env, txn, apiVersion]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::transaction] = to_string(txn->getTransactionID()); params[jss::binary] = false; params[jss::api_version] = apiVersion; @@ -827,7 +827,7 @@ class Transaction_test : public beast::unit_test::Suite using std::to_string; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->fees.referenceFee = 10; + cfg->FEES.reference_fee = 10; return cfg; })}; Account const alice{"alice"}; @@ -847,7 +847,7 @@ class Transaction_test : public beast::unit_test::Suite std::string const expectedMetaBlob = serializeHex(*meta); json::Value const result = [&env, txn, apiVersion]() { - json::Value params{json::ValueType::Object}; + json::Value params{json::ObjectValue}; params[jss::transaction] = to_string(txn->getTransactionID()); params[jss::binary] = true; params[jss::api_version] = apiVersion; diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index 20740bfe53..d465672aa7 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -32,7 +32,7 @@ class Version_test : public beast::unit_test::Suite auto jrr = env.rpc( "json", "version", - "{\"api_version\": " + std::to_string(RPC::kApiMaximumSupportedVersion) + + "{\"api_version\": " + std::to_string(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION) + "}")[jss::result]; BEAST_EXPECT(isCorrectReply(jrr)); @@ -62,16 +62,17 @@ class Version_test : public beast::unit_test::Suite auto re = env.rpc( "json", "version", - "{\"api_version\": " + std::to_string(RPC::kApiMinimumSupportedVersion - 1) + "}"); + "{\"api_version\": " + std::to_string(RPC::kAPI_MINIMUM_SUPPORTED_VERSION - 1) + "}"); BEAST_EXPECT(badVersion(re)); - BEAST_EXPECT(env.app().config().betaRpcApi); + BEAST_EXPECT(env.app().config().BETA_RPC_API); re = env.rpc( "json", "version", "{\"api_version\": " + std::to_string( - std::max(RPC::kApiMaximumSupportedVersion.value, RPC::kApiBetaVersion.value) + + std::max( + RPC::kAPI_MAXIMUM_SUPPORTED_VERSION.value, RPC::kAPI_BETA_VERSION.value) + 1) + "}"); BEAST_EXPECT(badVersion(re)); @@ -86,38 +87,40 @@ class Version_test : public beast::unit_test::Suite testcase("test getAPIVersionNumber function"); unsigned int const versionIfUnspecified = - RPC::kApiVersionIfUnspecified < RPC::kApiMinimumSupportedVersion - ? RPC::kApiInvalidVersion - : RPC::kApiVersionIfUnspecified; + RPC::kAPI_VERSION_IF_UNSPECIFIED < RPC::kAPI_MINIMUM_SUPPORTED_VERSION + ? RPC::kAPI_INVALID_VERSION + : RPC::kAPI_VERSION_IF_UNSPECIFIED; - json::Value const jArray = json::Value(json::ValueType::Array); - json::Value const jNull = json::Value(json::ValueType::Null); + json::Value const jArray = json::Value(json::ArrayValue); + json::Value const jNull = json::Value(json::NullValue); BEAST_EXPECT(RPC::getAPIVersionNumber(jArray, false) == versionIfUnspecified); BEAST_EXPECT(RPC::getAPIVersionNumber(jNull, false) == versionIfUnspecified); - json::Value jObject = json::Value(json::ValueType::Object); + json::Value jObject = json::Value(json::ObjectValue); BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == versionIfUnspecified); - jObject[jss::api_version] = RPC::kApiVersionIfUnspecified.value; + jObject[jss::api_version] = RPC::kAPI_VERSION_IF_UNSPECIFIED.value; BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == versionIfUnspecified); - jObject[jss::api_version] = RPC::kApiMinimumSupportedVersion.value; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiMinimumSupportedVersion); - jObject[jss::api_version] = RPC::kApiMaximumSupportedVersion.value; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiMaximumSupportedVersion); + jObject[jss::api_version] = RPC::kAPI_MINIMUM_SUPPORTED_VERSION.value; + BEAST_EXPECT( + RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_MINIMUM_SUPPORTED_VERSION); + jObject[jss::api_version] = RPC::kAPI_MAXIMUM_SUPPORTED_VERSION.value; + BEAST_EXPECT( + RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_MAXIMUM_SUPPORTED_VERSION); - jObject[jss::api_version] = RPC::kApiMinimumSupportedVersion - 1; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiInvalidVersion); - jObject[jss::api_version] = RPC::kApiMaximumSupportedVersion + 1; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiInvalidVersion); - jObject[jss::api_version] = RPC::kApiBetaVersion.value; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, true) == RPC::kApiBetaVersion); - jObject[jss::api_version] = RPC::kApiBetaVersion + 1; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, true) == RPC::kApiInvalidVersion); + jObject[jss::api_version] = RPC::kAPI_MINIMUM_SUPPORTED_VERSION - 1; + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_INVALID_VERSION); + jObject[jss::api_version] = RPC::kAPI_MAXIMUM_SUPPORTED_VERSION + 1; + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_INVALID_VERSION); + jObject[jss::api_version] = RPC::kAPI_BETA_VERSION.value; + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, true) == RPC::kAPI_BETA_VERSION); + jObject[jss::api_version] = RPC::kAPI_BETA_VERSION + 1; + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, true) == RPC::kAPI_INVALID_VERSION); - jObject[jss::api_version] = RPC::kApiInvalidVersion.value; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiInvalidVersion); + jObject[jss::api_version] = RPC::kAPI_INVALID_VERSION.value; + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_INVALID_VERSION); jObject[jss::api_version] = "a"; - BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kApiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(jObject, false) == RPC::kAPI_INVALID_VERSION); } void @@ -141,7 +144,7 @@ class Version_test : public beast::unit_test::Suite "\"method\": \"version\", " "\"params\": { " "\"api_version\": " + - std::to_string(RPC::kApiMaximumSupportedVersion) + "}}"; + std::to_string(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION) + "}}"; auto re = env.rpc("json2", '[' + withoutApiVerion + ", " + withApiVerion + ']'); if (!BEAST_EXPECT(re.isArray())) @@ -160,7 +163,7 @@ class Version_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this}; - BEAST_EXPECT(env.app().config().betaRpcApi); + BEAST_EXPECT(env.app().config().BETA_RPC_API); auto const withoutApiVerion = std::string("{ ") + "\"jsonrpc\": \"2.0\", " "\"ripplerpc\": \"2.0\", " @@ -176,7 +179,8 @@ class Version_test : public beast::unit_test::Suite "\"params\": { " "\"api_version\": " + std::to_string( - std::max(RPC::kApiMaximumSupportedVersion.value, RPC::kApiBetaVersion.value) + 1) + + std::max(RPC::kAPI_MAXIMUM_SUPPORTED_VERSION.value, RPC::kAPI_BETA_VERSION.value) + + 1) + "}}"; auto re = env.rpc("json2", '[' + withoutApiVerion + ", " + withWrongApiVerion + ']'); @@ -194,19 +198,19 @@ class Version_test : public beast::unit_test::Suite testcase("config test"); { Config const c; - BEAST_EXPECT(c.betaRpcApi == false); + BEAST_EXPECT(c.BETA_RPC_API == false); } { Config c; c.loadFromString("\n[beta_rpc_api]\n1\n"); - BEAST_EXPECT(c.betaRpcApi == true); + BEAST_EXPECT(c.BETA_RPC_API == true); } { Config c; c.loadFromString("\n[beta_rpc_api]\n0\n"); - BEAST_EXPECT(c.betaRpcApi == false); + BEAST_EXPECT(c.BETA_RPC_API == false); } } @@ -220,21 +224,21 @@ class Version_test : public beast::unit_test::Suite c->loadFromString("\n[beta_rpc_api]\n1\n"); return c; })}; - if (!BEAST_EXPECT(env.app().config().betaRpcApi == true)) + if (!BEAST_EXPECT(env.app().config().BETA_RPC_API == true)) return; auto jrr = env.rpc( "json", "version", - "{\"api_version\": " + std::to_string(RPC::kApiBetaVersion) + "}")[jss::result]; + "{\"api_version\": " + std::to_string(RPC::kAPI_BETA_VERSION) + "}")[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)) return; - BEAST_EXPECT(jrr[jss::version][jss::first] == RPC::kApiMinimumSupportedVersion.value); - BEAST_EXPECT(jrr[jss::version][jss::last] == RPC::kApiBetaVersion.value); + BEAST_EXPECT(jrr[jss::version][jss::first] == RPC::kAPI_MINIMUM_SUPPORTED_VERSION.value); + BEAST_EXPECT(jrr[jss::version][jss::last] == RPC::kAPI_BETA_VERSION.value); } public: diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 6569a2d2a4..87f1d0e927 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -246,14 +246,14 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En { json::Value jrr; - json::Value jp = json::ValueType::Object; + json::Value jp = json::ObjectValue; if (!user.empty()) { jp["admin_user"] = user; if (subobject) { // special case of bad password..passed as object - json::Value jpi = json::ValueType::Object; + json::Value jpi = json::ObjectValue; jpi["admin_password"] = password; jp["admin_password"] = jpi; } @@ -692,19 +692,19 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En auto sendAndParse = [&](std::string const& req) -> json::Value { ws.async_write_some(true, buffer(req), yield[ec]); if (!BEAST_EXPECT(!ec)) - return json::ValueType::Object; + return json::ObjectValue; boost::beast::multi_buffer sb; ws.async_read(sb, yield[ec]); if (!BEAST_EXPECT(!ec)) - return json::ValueType::Object; + return json::ObjectValue; json::Value resp; json::Reader jr; if (!BEAST_EXPECT(jr.parse( boost::lexical_cast(boost::beast::make_printable(sb.data())), resp))) - return json::ValueType::Object; + return json::ObjectValue; sb.consume(sb.size()); return resp; }; @@ -843,7 +843,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); // with ELB_SUPPORT, status still does not indicate a problem - env.app().config().elbSupport = true; + env.app().config().ELB_SUPPORT = true; doRequest( yield, @@ -973,7 +973,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); - env.app().config().elbSupport = true; + env.app().config().ELB_SUPPORT = true; doRequest( yield, @@ -1021,7 +1021,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En { boost::beast::http::response resp; - json::Value jv(json::ValueType::Array); + 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); @@ -1030,7 +1030,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En { boost::beast::http::response resp; - json::Value jv(json::ValueType::Array); + json::Value jv(json::ArrayValue); json::Value j; j["invalid"] = 1; jv.append(j); @@ -1053,7 +1053,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En boost::beast::http::response resp; json::Value jv; jv[jss::method] = "batch"; - jv[jss::params] = json::ValueType::Object; + 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); @@ -1063,7 +1063,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En json::Value jv; { boost::beast::http::response resp; - jv[jss::method] = json::ValueType::Null; + 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.body() == "Null method\r\n"); @@ -1096,7 +1096,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En { boost::beast::http::response resp; - jv[jss::params] = json::ValueType::Array; + 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); @@ -1111,7 +1111,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->elbSupport = true; + cfg->ELB_SUPPORT = true; return cfg; })}; diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 263fb9451f..3bddf489d6 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -48,15 +48,15 @@ public: class TestThread { private: - boost::asio::io_context ioContext_; + boost::asio::io_context io_context_; std::optional> work_; std::thread thread_; public: TestThread() - : work_(std::in_place, boost::asio::make_work_guard(ioContext_)) - , thread_([&]() { this->ioContext_.run(); }) + : work_(std::in_place, boost::asio::make_work_guard(io_context_)) + , thread_([&]() { this->io_context_.run(); }) { } @@ -69,7 +69,7 @@ public: boost::asio::io_context& getIoContext() { - return ioContext_; + return io_context_; } }; @@ -81,12 +81,12 @@ public: public: explicit TestSink(beast::unit_test::Suite& suite) - : Sink(beast::Severity::Warning, false), suite_(suite) + : Sink(beast::severities::KWarning, false), suite_(suite) { } void - write(beast::Severity level, std::string const& text) override + write(beast::severities::Severity level, std::string const& text) override { if (level < threshold()) return; @@ -95,7 +95,7 @@ public: } void - writeAlways(beast::Severity level, std::string const& text) override + writeAlways(beast::severities::Severity level, std::string const& text) override { suite_.log << text << std::endl; } @@ -295,7 +295,7 @@ public: testcase("Basic client/server"); TestSink sink{*this}; TestThread thread; - sink.threshold(beast::Severity::All); + sink.threshold(beast::severities::Severity::KAll); beast::Journal const journal{sink}; TestHandler handler; auto s = makeServer(handler, thread.getIoContext(), journal); @@ -365,7 +365,7 @@ public: } }; - using beast::Severity; + using namespace beast::severities; SuiteJournal journal("Server_test", *this); NullHandler h; diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index b2fc185b31..85cccfd6ab 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -33,8 +33,9 @@ namespace xrpl::tests { class FetchPack_test : public beast::unit_test::Suite { public: - static constexpr auto kTableItems = 100; - static constexpr auto kTableItemsExtra = 20; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { TableItems = 100, TableItemsExtra = 20 }; using Map = hash_map; using Table = SHAMap; @@ -104,14 +105,14 @@ public: void onFetch(Map& map, SHAMapHash const& hash, Blob const& blob) { - BEAST_EXPECT(sha512Half(makeSlice(blob)) == hash.asUInt256()); + BEAST_EXPECT(sha512Half(makeSlice(blob)) == hash.asUint256()); map.emplace(hash, blob); } void run() override { - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("FetchPack_test", *this); TestNodeFamily f(journal); diff --git a/src/test/shamap/SHAMapSync_test.cpp b/src/test/shamap/SHAMapSync_test.cpp index 9e9a490977..18ab73fc96 100644 --- a/src/test/shamap/SHAMapSync_test.cpp +++ b/src/test/shamap/SHAMapSync_test.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -84,7 +83,7 @@ public: void run() override { - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("SHAMapSync_test", *this); TestNodeFamily f(journal), f2(journal); diff --git a/src/test/shamap/SHAMap_test.cpp b/src/test/shamap/SHAMap_test.cpp index ab7e01e3af..37def20f81 100644 --- a/src/test/shamap/SHAMap_test.cpp +++ b/src/test/shamap/SHAMap_test.cpp @@ -114,7 +114,7 @@ public: void run() override { - using beast::Severity; + using namespace beast::severities; test::SuiteJournal journal("SHAMap_test", *this); run(true, journal); @@ -222,7 +222,7 @@ public: testcase("build/tear unbacked"); } { - static constexpr std::array keys{ + constexpr std::array kEYS{ uint256( "b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" "5a772c6ca8"), @@ -248,7 +248,7 @@ public: "292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" "5a772c6ca8")}; - static constexpr std::array kHashes{ + constexpr std::array kHASHES{ uint256( "B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C" "64B6281F7F"), @@ -278,21 +278,21 @@ public: if (!backed) map.setUnbacked(); - BEAST_EXPECT(map.getHash() == beast::kZero); - for (int k = 0; k < keys.size(); ++k) + BEAST_EXPECT(map.getHash() == beast::kZERO); + for (int k = 0; k < kEYS.size(); ++k) { BEAST_EXPECT(map.addItem( - SHAMapNodeType::TnTransactionNm, makeShamapitem(keys[k], intToVuc(k)))); - BEAST_EXPECT(map.getHash().asUInt256() == kHashes[k]); + SHAMapNodeType::TnTransactionNm, makeShamapitem(kEYS[k], intToVuc(k)))); + BEAST_EXPECT(map.getHash().asUint256() == kHASHES[k]); map.invariants(); } - for (int k = keys.size() - 1; k >= 0; --k) + for (int k = kEYS.size() - 1; k >= 0; --k) { - BEAST_EXPECT(map.getHash().asUInt256() == kHashes[k]); - BEAST_EXPECT(map.delItem(keys[k])); + BEAST_EXPECT(map.getHash().asUint256() == kHASHES[k]); + BEAST_EXPECT(map.delItem(kEYS[k])); map.invariants(); } - BEAST_EXPECT(map.getHash() == beast::kZero); + BEAST_EXPECT(map.getHash() == beast::kZERO); } if (backed) @@ -305,7 +305,7 @@ public: } { - static constexpr std::array keys{ + constexpr std::array kEYS{ uint256( "f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" "5a772c6ca8"), @@ -335,7 +335,7 @@ public: SHAMap map{SHAMapType::FREE, tf}; if (!backed) map.setUnbacked(); - for (auto const& k : keys) + for (auto const& k : kEYS) { map.addItem(SHAMapNodeType::TnTransactionNm, makeShamapitem(k, intToVuc(0))); map.invariants(); @@ -344,7 +344,7 @@ public: int h = 7; for (auto const& k : map) { - BEAST_EXPECT(k.key() == keys[h]); + BEAST_EXPECT(k.key() == kEYS[h]); --h; } } @@ -373,7 +373,7 @@ class SHAMapPathProof_test : public beast::unit_test::Suite SHAMapNodeType::TnAccountState, makeShamapitem(k, Slice{k.data(), k.size()})); map.invariants(); - auto root = map.getHash().asUInt256(); + auto root = map.getHash().asUint256(); auto path = map.getProofPath(k); BEAST_EXPECT(path); if (!path) diff --git a/src/test/unit_test/FileDirGuard.h b/src/test/unit_test/FileDirGuard.h index 19110469ee..4966b8089c 100644 --- a/src/test/unit_test/FileDirGuard.h +++ b/src/test/unit_test/FileDirGuard.h @@ -45,9 +45,9 @@ public: { using namespace boost::filesystem; - static auto kSubDirCounter = 0; + static auto kSUB_DIR_COUNTER = 0; if (useCounter) - subDir_ += std::to_string(++kSubDirCounter); + subDir_ += std::to_string(++kSUB_DIR_COUNTER); if (!exists(subDir_)) { create_directory(subDir_); diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index bd54683031..32b085ffe6 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -14,7 +14,7 @@ class SuiteJournalSink : public beast::Journal::Sink public: SuiteJournalSink( std::string const& partition, - beast::Severity threshold, + beast::severities::Severity threshold, beast::unit_test::Suite& suite) : Sink(threshold, false), partition_(partition + " "), suite_(suite) { @@ -22,20 +22,20 @@ public: // For unit testing, always generate logging text. [[nodiscard]] bool - active(beast::Severity level) const override + active(beast::severities::Severity level) const override { return true; } void - write(beast::Severity level, std::string const& text) override; + write(beast::severities::Severity level, std::string const& text) override; void - writeAlways(beast::Severity level, std::string const& text) override; + writeAlways(beast::severities::Severity level, std::string const& text) override; }; inline void -SuiteJournalSink::write(beast::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()) @@ -43,33 +43,33 @@ SuiteJournalSink::write(beast::Severity level, std::string const& text) } inline void -SuiteJournalSink::writeAlways(beast::Severity level, std::string const& text) +SuiteJournalSink::writeAlways(beast::severities::Severity level, std::string const& text) { - using beast::Severity; + using namespace beast::severities; char const* const s = [level]() { switch (level) { - case Severity::Trace: + case KTrace: return "TRC:"; - case Severity::Debug: + case KDebug: return "DBG:"; - case Severity::Info: + case KInfo: return "INF:"; - case Severity::Warning: + case KWarning: return "WRN:"; - case Severity::Error: + case KError: return "ERR:"; default: break; - case Severity::Fatal: + case KFatal: break; } return "FTL:"; }(); - static std::mutex kLogMutex; - std::scoped_lock const lock(kLogMutex); + static std::mutex kLOG_MUTEX; + std::scoped_lock const lock(kLOG_MUTEX); suite_.log << s << partition_ << text << std::endl; } @@ -82,7 +82,7 @@ public: SuiteJournal( std::string const& partition, beast::unit_test::Suite& suite, - beast::Severity threshold = beast::Severity::Fatal) + beast::severities::Severity threshold = beast::severities::KFatal) : sink_(partition, threshold, suite), journal_(sink_) { } @@ -100,12 +100,13 @@ class StreamSink : public beast::Journal::Sink std::stringstream strm_; public: - StreamSink(beast::Severity threshold = beast::Severity::Debug) : Sink(threshold, false) + StreamSink(beast::severities::Severity threshold = beast::severities::KDebug) + : Sink(threshold, false) { } void - write(beast::Severity level, std::string const& text) override + write(beast::severities::Severity level, std::string const& text) override { if (level < threshold()) return; @@ -113,7 +114,7 @@ public: } void - writeAlways(beast::Severity level, std::string const& text) override + writeAlways(beast::severities::Severity level, std::string const& text) override { strm_ << text << std::endl; } diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index 3a56d22654..86c075caf2 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -75,19 +75,19 @@ Results::add(SuiteResults const& r) if (iter != top.end()) { - if (top.size() == kMaxTop && iter == top.end() - 1) + if (top.size() == MaxTop && iter == top.end() - 1) { // avoid invalidating the iterator *iter = run_time{static_string{static_string::string_view_type{r.name}}, elapsed}; } else { - if (top.size() == kMaxTop) + if (top.size() == MaxTop) top.resize(top.size() - 1); top.emplace(iter, static_string{static_string::string_view_type{r.name}}, elapsed); } } - else if (top.size() < kMaxTop) + else if (top.size() < MaxTop) { top.emplace_back(static_string{static_string::string_view_type{r.name}}, elapsed); } @@ -103,14 +103,14 @@ Results::merge(Results const& r) failed += r.failed; // combine the two top collections - boost::container::static_vector topResult; + boost::container::static_vector topResult; topResult.resize(top.size() + r.top.size()); std::ranges::merge(top, r.top, topResult.begin(), [](run_time const& t1, run_time const& t2) { return t1.second > t2.second; }); - if (topResult.size() > kMaxTop) - topResult.resize(kMaxTop); + if (topResult.size() > MaxTop) + topResult.resize(MaxTop); top = topResult; } @@ -139,28 +139,28 @@ template std::size_t MultiRunnerBase::Inner::checkoutJobIndex() { - return jobIndex++; + return job_index++; } template std::size_t MultiRunnerBase::Inner::checkoutTestIndex() { - return testIndex++; + return test_index++; } template bool MultiRunnerBase::Inner::anyFailed() const { - return anyFailedFlag; + return any_failed; } template void MultiRunnerBase::Inner::anyFailed(bool v) { - anyFailedFlag = anyFailedFlag || v; + any_failed = any_failed || v; } template @@ -183,14 +183,14 @@ template void MultiRunnerBase::Inner::incKeepAliveCount() { - ++keepAlive; + ++keep_alive; } template std::size_t MultiRunnerBase::Inner::getKeepAliveCount() { - return keepAlive; + return keep_alive; } template @@ -218,34 +218,34 @@ MultiRunnerBase::MultiRunnerBase() if (IsParent) { // cleanup any leftover state for any previous failed runs - boost::interprocess::shared_memory_object::remove(kSharedMemName); - boost::interprocess::message_queue::remove(kMessageQueueName); + boost::interprocess::shared_memory_object::remove(kSHARED_MEM_NAME); + boost::interprocess::message_queue::remove(kMESSAGE_QUEUE_NAME); } - sharedMem_ = boost::interprocess::shared_memory_object{ + shared_mem_ = boost::interprocess::shared_memory_object{ std::conditional_t< IsParent, boost::interprocess::create_only_t, boost::interprocess::open_only_t>{}, - kSharedMemName, + kSHARED_MEM_NAME, boost::interprocess::read_write}; if (IsParent) { - sharedMem_.truncate(sizeof(Inner)); - messageQueue_ = std::make_unique( + shared_mem_.truncate(sizeof(Inner)); + message_queue_ = std::make_unique( boost::interprocess::create_only, - kMessageQueueName, + kMESSAGE_QUEUE_NAME, /*max messages*/ 16, /*max message size*/ 1 << 20); } else { - messageQueue_ = std::make_unique( - boost::interprocess::open_only, kMessageQueueName); + message_queue_ = std::make_unique( + boost::interprocess::open_only, kMESSAGE_QUEUE_NAME); } - region_ = boost::interprocess::mapped_region{sharedMem_, boost::interprocess::read_write}; + region_ = boost::interprocess::mapped_region{shared_mem_, boost::interprocess::read_write}; if (IsParent) { inner_ = new (region_.get_address()) Inner{}; @@ -259,8 +259,8 @@ MultiRunnerBase::MultiRunnerBase() { if (IsParent) { - boost::interprocess::shared_memory_object::remove(kSharedMemName); - boost::interprocess::message_queue::remove(kMessageQueueName); + boost::interprocess::shared_memory_object::remove(kSHARED_MEM_NAME); + boost::interprocess::message_queue::remove(kMESSAGE_QUEUE_NAME); } throw; } @@ -272,8 +272,8 @@ MultiRunnerBase::~MultiRunnerBase() if (IsParent) { inner_->~Inner(); - boost::interprocess::shared_memory_object::remove(kSharedMemName); - boost::interprocess::message_queue::remove(kMessageQueueName); + boost::interprocess::shared_memory_object::remove(kSHARED_MEM_NAME); + boost::interprocess::message_queue::remove(kMESSAGE_QUEUE_NAME); } } @@ -340,8 +340,8 @@ MultiRunnerBase::messageQueueSend(MessageType mt, std::string const& s { // must use a mutex since the two "sends" must happen in order std::scoped_lock const l{inner_->m}; - messageQueue_->send(&mt, sizeof(mt), /*priority*/ 0); - messageQueue_->send(s.c_str(), s.size(), /*priority*/ 0); + message_queue_->send(&mt, sizeof(mt), /*priority*/ 0); + message_queue_->send(s.c_str(), s.size(), /*priority*/ 0); } template @@ -376,13 +376,13 @@ namespace test { MultiRunnerParent::MultiRunnerParent() : os_(std::cout) { - messageQueueThread_ = std::thread([this] { + message_queue_thread_ = std::thread([this] { std::vector buf(1 << 20); - while (this->continueMessageQueue_ || this->messageQueue_->get_num_msg()) + while (this->continue_message_queue_ || this->message_queue_->get_num_msg()) { // let children know the parent is still alive this->incKeepAliveCount(); - if (!this->messageQueue_->get_num_msg()) + if (!this->message_queue_->get_num_msg()) { // If a child does not see the keep alive count incremented, // it will assume the parent has died. This sleep time needs @@ -395,13 +395,13 @@ MultiRunnerParent::MultiRunnerParent() : os_(std::cout) { std::size_t recvdSize = 0; unsigned int priority = 0; - this->messageQueue_->receive(buf.data(), buf.size(), recvdSize, priority); + this->message_queue_->receive(buf.data(), buf.size(), recvdSize, priority); if (!recvdSize) continue; assert(recvdSize == 1); MessageType const mt{*reinterpret_cast(buf.data())}; - this->messageQueue_->receive(buf.data(), buf.size(), recvdSize, priority); + this->message_queue_->receive(buf.data(), buf.size(), recvdSize, priority); if (recvdSize) { std::string s{buf.data(), recvdSize}; @@ -412,10 +412,10 @@ MultiRunnerParent::MultiRunnerParent() : os_(std::cout) this->os_.flush(); break; case MessageType::TestStart: - runningSuites_.insert(std::move(s)); + running_suites_.insert(std::move(s)); break; case MessageType::TestEnd: - runningSuites_.erase(s); + running_suites_.erase(s); break; default: assert(0); // unknown message type @@ -440,14 +440,14 @@ MultiRunnerParent::~MultiRunnerParent() { using namespace beast::unit_test; - continueMessageQueue_ = false; - messageQueueThread_.join(); + continue_message_queue_ = false; + message_queue_thread_.join(); - addFailures(runningSuites_.size()); + addFailures(running_suites_.size()); printResults(os_); - for (auto const& s : runningSuites_) + for (auto const& s : running_suites_) { os_ << "\nSuite: " << s << " failed to complete. The child process may have crashed.\n"; } @@ -480,13 +480,16 @@ MultiRunnerParent::addFailures(std::size_t failures) //------------------------------------------------------------------------------ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLog) - : jobIndex_{checkoutJobIndex()}, numJobs_{numJobs}, quiet_{quiet}, printLog_{!quiet || printLog} + : job_index_{checkoutJobIndex()} + , num_jobs_{numJobs} + , quiet_{quiet} + , print_log_{!quiet || printLog} { - if (numJobs_ > 1) + if (num_jobs_ > 1) { - keepAliveThread_ = std::thread([this] { + keep_alive_thread_ = std::thread([this] { std::size_t lastCount = getKeepAliveCount(); - while (this->continueKeepAlive_) + while (this->continue_keep_alive_) { // Use a small sleep time so in the normal case the child // process may shutdown quickly. However, to protect against @@ -501,7 +504,7 @@ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLo if (curCount == lastCount) { // assume parent process is no longer alive - std::cerr << "multi_runner_child " << jobIndex_ + std::cerr << "multi_runner_child " << job_index_ << ": Assuming parent died, exiting.\n"; std::exit(EXIT_FAILURE); } @@ -514,10 +517,10 @@ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLo MultiRunnerChild::~MultiRunnerChild() { - if (numJobs_ > 1) + if (num_jobs_ > 1) { - continueKeepAlive_ = false; - keepAliveThread_.join(); + continue_keep_alive_ = false; + keep_alive_thread_.join(); } add(results_); @@ -545,74 +548,75 @@ MultiRunnerChild::addFailures(std::size_t failures) void MultiRunnerChild::onSuiteBegin(beast::unit_test::SuiteInfo const& info) { - suiteResults_ = detail::SuiteResults{info.fullName()}; - messageQueueSend(MessageType::TestStart, suiteResults_.name); + suite_results_ = detail::SuiteResults{info.fullName()}; + messageQueueSend(MessageType::TestStart, suite_results_.name); } void MultiRunnerChild::onSuiteEnd() { - if (printLog_ || suiteResults_.failed > 0) + if (print_log_ || suite_results_.failed > 0) { std::stringstream s; - if (numJobs_ > 1) - s << jobIndex_ << "> "; - s << (suiteResults_.failed > 0 ? "failed: " : "") << suiteResults_.name << " had " - << suiteResults_.failed << " failures." << std::endl; + if (num_jobs_ > 1) + s << job_index_ << "> "; + s << (suite_results_.failed > 0 ? "failed: " : "") << suite_results_.name << " had " + << suite_results_.failed << " failures." << std::endl; messageQueueSend(MessageType::Log, s.str()); } - results_.add(suiteResults_); - messageQueueSend(MessageType::TestEnd, suiteResults_.name); + results_.add(suite_results_); + messageQueueSend(MessageType::TestEnd, suite_results_.name); } void MultiRunnerChild::onCaseBegin(std::string const& name) { - caseResults_ = detail::CaseResults(name); + case_results_ = detail::CaseResults(name); if (quiet_) return; std::stringstream s; - if (numJobs_ > 1) - s << jobIndex_ << "> "; - s << suiteResults_.name << (caseResults_.name.empty() ? "" : (" " + caseResults_.name)) << '\n'; + if (num_jobs_ > 1) + s << job_index_ << "> "; + s << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) + << '\n'; messageQueueSend(MessageType::Log, s.str()); } void MultiRunnerChild::onCaseEnd() { - suiteResults_.add(caseResults_); + suite_results_.add(case_results_); } void MultiRunnerChild::onPass() { - ++caseResults_.total; + ++case_results_.total; } void MultiRunnerChild::onFail(std::string const& reason) { - ++caseResults_.failed; - ++caseResults_.total; + ++case_results_.failed; + ++case_results_.total; std::stringstream s; - if (numJobs_ > 1) - s << jobIndex_ << "> "; - s << "#" << caseResults_.total << " failed" << (reason.empty() ? "" : ": ") << reason << '\n'; + if (num_jobs_ > 1) + s << job_index_ << "> "; + s << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << '\n'; messageQueueSend(MessageType::Log, s.str()); } void MultiRunnerChild::onLog(std::string const& msg) { - if (!printLog_) + if (!print_log_) return; std::stringstream s; - if (numJobs_ > 1) - s << jobIndex_ << "> "; + if (num_jobs_ > 1) + s << job_index_ << "> "; s << msg; messageQueueSend(MessageType::Log, s.str()); } diff --git a/src/test/unit_test/multi_runner.h b/src/test/unit_test/multi_runner.h index 8b07559e8c..9c83c29141 100644 --- a/src/test/unit_test/multi_runner.h +++ b/src/test/unit_test/multi_runner.h @@ -59,13 +59,15 @@ struct Results // pointers from different memory spaces do not co-mingle using run_time = std::pair; - static constexpr auto kMaxTop = 10; + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { MaxTop = 10 }; std::size_t suites = 0; std::size_t cases = 0; std::size_t total = 0; std::size_t failed = 0; - boost::container::static_vector top; + boost::container::static_vector top; typename clock_type::time_point start = clock_type::now(); void @@ -87,14 +89,14 @@ class MultiRunnerBase // way they communicate is through message queues. struct Inner { - std::atomic jobIndex{0}; - std::atomic testIndex{0}; - std::atomic anyFailedFlag{false}; - // A parent process will periodically increment `keepAlive`. The child - // processes will check if `keepAlive` is being incremented. If it is + std::atomic job_index{0}; + std::atomic test_index{0}; + std::atomic any_failed{false}; + // A parent process will periodically increment `keep_alive_`. The child + // processes will check if `keep_alive_` is being incremented. If it is // not incremented for a sufficiently long time, the child will assume // the parent process has died. - std::atomic keepAlive{0}; + std::atomic keep_alive{0}; mutable boost::interprocess::interprocess_mutex m; detail::Results results; @@ -131,19 +133,19 @@ class MultiRunnerBase printResults(S& s); }; - static constexpr char const* kSharedMemName = "XrpldUnitTestSharedMem"; + static constexpr char const* kSHARED_MEM_NAME = "XrpldUnitTestSharedMem"; // name of the message queue a multi_runner_child will use to communicate // with multi_runner_parent - static constexpr char const* kMessageQueueName = "XrpldUnitTestMessageQueue"; + static constexpr char const* kMESSAGE_QUEUE_NAME = "XrpldUnitTestMessageQueue"; // `inner_` will be created in shared memory Inner* inner_; // shared memory to use for the `inner` member - boost::interprocess::shared_memory_object sharedMem_; + boost::interprocess::shared_memory_object shared_mem_; boost::interprocess::mapped_region region_; protected: - std::unique_ptr messageQueue_; + std::unique_ptr message_queue_; enum class MessageType : std::uint8_t { TestStart, TestEnd, Log }; void @@ -201,10 +203,10 @@ class MultiRunnerParent : private detail::MultiRunnerBase private: // message_queue_ is used to collect log messages from the children std::ostream& os_; - std::atomic continueMessageQueue_{true}; - std::thread messageQueueThread_; + std::atomic continue_message_queue_{true}; + std::thread message_queue_thread_; // track running suites so if a child crashes the culprit can be flagged - std::set runningSuites_; + std::set running_suites_; public: MultiRunnerParent(MultiRunnerParent const&) = delete; @@ -235,16 +237,16 @@ class MultiRunnerChild : public beast::unit_test::Runner, private detail::MultiRunnerBase { private: - std::size_t jobIndex_; + std::size_t job_index_; detail::Results results_; - detail::SuiteResults suiteResults_; - detail::CaseResults caseResults_; - std::size_t numJobs_{0}; + detail::SuiteResults suite_results_; + detail::CaseResults case_results_; + std::size_t num_jobs_{0}; bool quiet_{false}; - bool printLog_{true}; + bool print_log_{true}; - std::atomic continueKeepAlive_{true}; - std::thread keepAliveThread_; + std::atomic continue_keep_alive_{true}; + std::thread keep_alive_thread_; public: MultiRunnerChild(MultiRunnerChild const&) = delete; @@ -318,12 +320,12 @@ MultiRunnerChild::runMulti(Pred pred) } catch (...) { - if (numJobs_ <= 1) + if (num_jobs_ <= 1) throw; // a single process can die // inform the parent std::stringstream s; - s << jobIndex_ << "> failed Unhandled exception in test.\n"; + s << job_index_ << "> failed Unhandled exception in test.\n"; messageQueueSend(MessageType::Log, s.str()); failed = true; } diff --git a/src/test/unit_test/utils.h b/src/test/unit_test/utils.h index 028823c763..beccf1c92e 100644 --- a/src/test/unit_test/utils.h +++ b/src/test/unit_test/utils.h @@ -10,8 +10,8 @@ namespace xrpl::test { inline bool equal(SecretKey const& lhs, SecretKey const& rhs) { - return lhs.size() == SecretKey::kSize && rhs.size() == SecretKey::kSize && - std::memcmp(lhs.data(), rhs.data(), SecretKey::kSize) == 0; + return lhs.size() == SecretKey::kSIZE && rhs.size() == SecretKey::kSIZE && + std::memcmp(lhs.data(), rhs.data(), SecretKey::kSIZE) == 0; } } // namespace xrpl::test diff --git a/src/tests/libxrpl/basics/MallocTrim.cpp b/src/tests/libxrpl/basics/MallocTrim.cpp index 6ac8957f0e..b8e2c9fd30 100644 --- a/src/tests/libxrpl/basics/MallocTrim.cpp +++ b/src/tests/libxrpl/basics/MallocTrim.cpp @@ -161,15 +161,15 @@ TEST(mallocTrim, with_debug_logging) { struct DebugSink : public beast::Journal::Sink { - DebugSink() : Sink(beast::Severity::Debug, false) + DebugSink() : Sink(beast::severities::KDebug, false) { } void - write(beast::Severity, std::string const&) override + write(beast::severities::Severity, std::string const&) override { } void - writeAlways(beast::Severity, std::string const&) override + writeAlways(beast::severities::Severity, std::string const&) override { } }; diff --git a/src/tests/libxrpl/basics/Slice.cpp b/src/tests/libxrpl/basics/Slice.cpp index 02287dddc6..f999d99934 100644 --- a/src/tests/libxrpl/basics/Slice.cpp +++ b/src/tests/libxrpl/basics/Slice.cpp @@ -8,7 +8,7 @@ using namespace xrpl; -static std::uint8_t const kData[] = { +static std::uint8_t const kDATA[] = { 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}; @@ -21,9 +21,9 @@ TEST(Slice, equality_and_inequality) EXPECT_EQ(s0, s0); // Test slices of equal and unequal size pointing to same data: - for (std::size_t i = 0; i != sizeof(kData); ++i) + for (std::size_t i = 0; i != sizeof(kDATA); ++i) { - Slice const s1{kData, i}; + Slice const s1{kDATA, i}; EXPECT_EQ(s1.size(), i); EXPECT_NE(s1.data(), nullptr); @@ -37,9 +37,9 @@ TEST(Slice, equality_and_inequality) EXPECT_NE(s1, s0); } - for (std::size_t j = 0; j != sizeof(kData); ++j) + for (std::size_t j = 0; j != sizeof(kDATA); ++j) { - Slice const s2{kData, j}; + Slice const s2{kDATA, j}; if (i == j) { @@ -53,11 +53,11 @@ TEST(Slice, equality_and_inequality) } // Test slices of equal size but pointing to different data: - std::array a{}; - std::array b{}; + std::array a{}; + std::array b{}; - for (std::size_t i = 0; i != sizeof(kData); ++i) - a[i] = b[i] = kData[i]; + for (std::size_t i = 0; i != sizeof(kDATA); ++i) + a[i] = b[i] = kDATA[i]; EXPECT_EQ(makeSlice(a), makeSlice(b)); b[7]++; @@ -68,23 +68,23 @@ TEST(Slice, equality_and_inequality) TEST(Slice, indexing) { - Slice const s{kData, sizeof(kData)}; + Slice const s{kDATA, sizeof(kDATA)}; - for (std::size_t i = 0; i != sizeof(kData); ++i) - EXPECT_EQ(s[i], kData[i]); + for (std::size_t i = 0; i != sizeof(kDATA); ++i) + EXPECT_EQ(s[i], kDATA[i]); } TEST(Slice, advancing) { - for (std::size_t i = 0; i < sizeof(kData); ++i) + for (std::size_t i = 0; i < sizeof(kDATA); ++i) { - for (std::size_t j = 0; i + j < sizeof(kData); ++j) + for (std::size_t j = 0; i + j < sizeof(kDATA); ++j) { - Slice s(kData + i, sizeof(kData) - i); + Slice s(kDATA + i, sizeof(kDATA) - i); s += j; - EXPECT_EQ(s.data(), kData + i + j); - EXPECT_EQ(s.size(), sizeof(kData) - i - j); + EXPECT_EQ(s.data(), kDATA + i + j); + EXPECT_EQ(s.size(), sizeof(kDATA) - i - j); } } } diff --git a/src/tests/libxrpl/helpers/Account.cpp b/src/tests/libxrpl/helpers/Account.cpp index 4862309c82..736ae0a24b 100644 --- a/src/tests/libxrpl/helpers/Account.cpp +++ b/src/tests/libxrpl/helpers/Account.cpp @@ -7,7 +7,7 @@ namespace xrpl::test { -Account const Account::kMaster{"masterpassphrase"}; +Account const Account::master{"masterpassphrase"}; Account::Account(std::string_view name, KeyType type) : name_(name) diff --git a/src/tests/libxrpl/helpers/Account.h b/src/tests/libxrpl/helpers/Account.h index a92497f2c3..4e2d6e547f 100644 --- a/src/tests/libxrpl/helpers/Account.h +++ b/src/tests/libxrpl/helpers/Account.h @@ -26,7 +26,7 @@ public: * This account is created in the genesis ledger with all 100 billion XRP. * It uses the well-known seed "masterpassphrase". */ - static Account const kMaster; + static Account const master; /** * @brief Create an account from a name. @@ -39,28 +39,28 @@ public: explicit Account(std::string_view name, KeyType type = KeyType::Secp256k1); /** @brief Return the human-readable name. */ - [[nodiscard]] std::string const& + std::string const& name() const noexcept { return name_; } /** @brief Return the AccountID. */ - [[nodiscard]] AccountID const& + AccountID const& id() const noexcept { return id_; } /** @brief Return the public key. */ - [[nodiscard]] PublicKey const& + PublicKey const& pk() const noexcept { return keyPair_.first; } /** @brief Return the secret key. */ - [[nodiscard]] SecretKey const& + SecretKey const& sk() const noexcept { return keyPair_.second; diff --git a/src/tests/libxrpl/helpers/IOU.h b/src/tests/libxrpl/helpers/IOU.h index d80f962edf..18bc69cf33 100644 --- a/src/tests/libxrpl/helpers/IOU.h +++ b/src/tests/libxrpl/helpers/IOU.h @@ -49,7 +49,8 @@ public: * @param currency The Currency object. * @param issuer The account that issues this currency. */ - IOU(Currency currency, Account const& issuer) : currency_(currency), issuer_(issuer.id()) + IOU(Currency currency, Account const& issuer) + : currency_(std::move(currency)), issuer_(issuer.id()) { XRPL_ASSERT(!isXRP(currency_), "IOU: currency code must not resolve to XRP"); } diff --git a/src/tests/libxrpl/helpers/TestFamily.h b/src/tests/libxrpl/helpers/TestFamily.h index dea7a6d4b4..2f69a26faf 100644 --- a/src/tests/libxrpl/helpers/TestFamily.h +++ b/src/tests/libxrpl/helpers/TestFamily.h @@ -7,7 +7,8 @@ #include -namespace xrpl::test { +namespace xrpl { +namespace test { /** Test implementation of Family for unit tests. @@ -48,7 +49,7 @@ public: return *db_; } - [[nodiscard]] NodeStore::Database const& + NodeStore::Database const& db() const override { return *db_; @@ -94,8 +95,8 @@ public: void reset() override { - (*fbCache_).reset(); - (*tnCache_).reset(); + fbCache_->reset(); + tnCache_->reset(); } /** Access the test clock for time manipulation in tests. */ @@ -106,4 +107,5 @@ public: } }; -} // namespace xrpl::test +} // namespace test +} // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TestServiceRegistry.h b/src/tests/libxrpl/helpers/TestServiceRegistry.h index 0536176344..bb92a71e5d 100644 --- a/src/tests/libxrpl/helpers/TestServiceRegistry.h +++ b/src/tests/libxrpl/helpers/TestServiceRegistry.h @@ -16,18 +16,19 @@ #include #include -namespace xrpl::test { +namespace xrpl { +namespace test { /** Logs implementation that creates TestSink instances. */ class TestLogs : public Logs { public: - explicit TestLogs(beast::Severity level = beast::Severity::Warning) : Logs(level) + explicit TestLogs(beast::severities::Severity level = beast::severities::KWarning) : Logs(level) { } std::unique_ptr - makeSink(std::string const&, beast::Severity threshold) override + makeSink(std::string const&, beast::severities::Severity threshold) override { return std::make_unique(threshold); } @@ -61,8 +62,8 @@ private: */ class TestServiceRegistry : public ServiceRegistry { - TestLogs logs_{beast::Severity::Warning}; - boost::asio::io_context ioContext_; + TestLogs logs_{beast::severities::KWarning}; + boost::asio::io_context io_context_; TestFamily family_{logs_.journal("TestFamily")}; LoadFeeTrack feeTrack_{logs_.journal("LoadFeeTrack")}; TestNetworkIDService networkIDService_; @@ -343,7 +344,7 @@ public: boost::asio::io_context& getIOContext() override { - return ioContext_; + return io_context_; } Logs& @@ -373,4 +374,5 @@ public: } }; -} // namespace xrpl::test +} // namespace test +} // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TestSink.cpp b/src/tests/libxrpl/helpers/TestSink.cpp index 428b7ad95b..403fd23392 100644 --- a/src/tests/libxrpl/helpers/TestSink.cpp +++ b/src/tests/libxrpl/helpers/TestSink.cpp @@ -18,12 +18,12 @@ namespace xrpl { -TestSink::TestSink(beast::Severity threshold) : Sink(threshold, false) +TestSink::TestSink(beast::severities::Severity threshold) : Sink(threshold, false) { } void -TestSink::write(beast::Severity level, std::string const& text) +TestSink::write(beast::severities::Severity level, std::string const& text) { if (level < threshold()) return; @@ -31,7 +31,7 @@ TestSink::write(beast::Severity level, std::string const& text) } void -TestSink::writeAlways(beast::Severity level, std::string const& text) +TestSink::writeAlways(beast::severities::Severity level, std::string const& text) { auto supportsColor = [] { // 1. Check for "NO_COLOR" environment variable (Standard convention) @@ -64,17 +64,17 @@ TestSink::writeAlways(beast::Severity level, std::string const& text) auto color = [level]() { switch (level) { - case beast::Severity::Trace: + case beast::severities::KTrace: return "\033[34m"; // blue - case beast::Severity::Debug: + case beast::severities::KDebug: return "\033[32m"; // green - case beast::Severity::Info: + case beast::severities::KInfo: return "\033[36m"; // cyan - case beast::Severity::Warning: + case beast::severities::KWarning: return "\033[33m"; // yellow - case beast::Severity::Error: + case beast::severities::KError: return "\033[31m"; // red - case beast::Severity::Fatal: + case beast::severities::KFatal: default: break; } @@ -84,17 +84,17 @@ TestSink::writeAlways(beast::Severity level, std::string const& text) auto prefix = [level]() { switch (level) { - case beast::Severity::Trace: + case beast::severities::KTrace: return "TRC:"; - case beast::Severity::Debug: + case beast::severities::KDebug: return "DBG:"; - case beast::Severity::Info: + case beast::severities::KInfo: return "INF:"; - case beast::Severity::Warning: + case beast::severities::KWarning: return "WRN:"; - case beast::Severity::Error: + case beast::severities::KError: return "ERR:"; - case beast::Severity::Fatal: + case beast::severities::KFatal: default: break; } @@ -104,19 +104,19 @@ TestSink::writeAlways(beast::Severity level, std::string const& text) auto& stream = [level]() -> std::ostream& { switch (level) { - case beast::Severity::Error: - case beast::Severity::Fatal: + case beast::severities::KError: + case beast::severities::KFatal: return std::cerr; default: return std::cout; } }(); - static constexpr auto kReset = "\033[0m"; + constexpr auto kRESET = "\033[0m"; if (supportsColor) { - stream << color << prefix << " " << text << kReset << std::endl; + stream << color << prefix << " " << text << kRESET << std::endl; } else { diff --git a/src/tests/libxrpl/helpers/TestSink.h b/src/tests/libxrpl/helpers/TestSink.h index 28c85f00e4..a96000b04f 100644 --- a/src/tests/libxrpl/helpers/TestSink.h +++ b/src/tests/libxrpl/helpers/TestSink.h @@ -13,12 +13,12 @@ public: return sink; } - TestSink(beast::Severity threshold = beast::Severity::Debug); + TestSink(beast::severities::Severity threshold = beast::severities::KDebug); void - write(beast::Severity level, std::string const& text) override; + write(beast::severities::Severity level, std::string const& text) override; void - writeAlways(beast::Severity level, std::string const& text) override; + writeAlways(beast::severities::Severity level, std::string const& text) override; }; } // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TxTest.cpp b/src/tests/libxrpl/helpers/TxTest.cpp index aeaa805b27..29db311fce 100644 --- a/src/tests/libxrpl/helpers/TxTest.cpp +++ b/src/tests/libxrpl/helpers/TxTest.cpp @@ -41,7 +41,7 @@ namespace xrpl::test { FeatureBitset allFeatures() { - static FeatureBitset const kFeatures = [] { + static FeatureBitset const kFEATURES = [] { auto const& sa = allAmendments(); std::vector feats; feats.reserve(sa.size()); @@ -52,7 +52,7 @@ allFeatures() } return FeatureBitset(feats); }(); - return kFeatures; + return kFEATURES; } //------------------------------------------------------------------------------ @@ -73,7 +73,7 @@ TxTest::TxTest(std::optional features) // Create a genesis ledger as the base closedLedger_ = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) *rules_, fees, @@ -85,7 +85,7 @@ TxTest::TxTest(std::optional features) // Create an open view on top of the genesis ledger openLedger_ = - std::make_shared(kOpenLedger, closedLedger_.get(), *rules_, closedLedger_); + std::make_shared(kOPEN_LEDGER, closedLedger_.get(), *rules_, closedLedger_); } bool @@ -123,7 +123,7 @@ void TxTest::createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags) { auto const paymentTer = - submit(transactions::PaymentBuilder{Account::kMaster, account, xrp}, Account::kMaster).ter; + submit(transactions::PaymentBuilder{Account::master, account, xrp}, Account::master).ter; if (paymentTer != tesSUCCESS) { @@ -213,7 +213,7 @@ TxTest::close() openLedger_ = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - std::make_shared(kOpenLedger, closedLedger_.get(), *rules_, closedLedger_); + std::make_shared(kOPEN_LEDGER, closedLedger_.get(), *rules_, closedLedger_); } void diff --git a/src/tests/libxrpl/helpers/TxTest.h b/src/tests/libxrpl/helpers/TxTest.h index 1b3ce460a2..8ba9898d99 100644 --- a/src/tests/libxrpl/helpers/TxTest.h +++ b/src/tests/libxrpl/helpers/TxTest.h @@ -44,9 +44,9 @@ namespace xrpl::test { */ template constexpr XRPAmount -XRP(T xrp) // NOLINT(readability-identifier-naming) +XRP(T xrp) { - return XRPAmount{static_cast(xrp) * kDropsPerXrp.drops()}; + return XRPAmount{static_cast(xrp) * kDROPS_PER_XRP.drops()}; } /** @@ -58,7 +58,7 @@ template XRPAmount XRP(T xrp) { - return XRPAmount{static_cast(std::round(xrp * kDropsPerXrp.drops()))}; + return XRPAmount{static_cast(std::round(xrp * kDROPS_PER_XRP.drops()))}; } /** @@ -69,7 +69,7 @@ XRP(T xrp) inline XRPAmount XRP(Number const& xrp) { - return XRPAmount{static_cast(xrp * kDropsPerXrp.drops())}; + return XRPAmount{static_cast(xrp * kDROPS_PER_XRP.drops())}; } //------------------------------------------------------------------------------ diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index 03f565dffb..994491b4db 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -23,38 +23,38 @@ namespace xrpl { TEST(json_value, limits) { using namespace json; - static_assert(Value::kMinInt == Int(~(UInt(-1) / 2))); - static_assert(Value::kMaxInt == Int(UInt(-1) / 2)); - static_assert(Value::kMaxUInt == UInt(-1)); + static_assert(Value::kMIN_INT == Int(~(UInt(-1) / 2))); + static_assert(Value::kMAX_INT == Int(UInt(-1) / 2)); + static_assert(Value::kMAX_U_INT == UInt(-1)); } TEST(json_value, construct_and_compare_Json_StaticString) { - static constexpr char kSample[]{"Contents of a json::StaticString"}; + static constexpr char kSAMPLE[]{"Contents of a json::StaticString"}; - static constexpr json::StaticString kTest1(kSample); - char const* addrTest1{kTest1}; + static constexpr json::StaticString kTEST1(kSAMPLE); + char const* addrTest1{kTEST1}; - EXPECT_EQ(addrTest1, &kSample[0]); - EXPECT_EQ(kTest1.cStr(), &kSample[0]); + EXPECT_EQ(addrTest1, &kSAMPLE[0]); + EXPECT_EQ(kTEST1.cStr(), &kSAMPLE[0]); - static constexpr json::StaticString kTest2{"Contents of a json::StaticString"}; - static constexpr json::StaticString kTest3{"Another StaticString"}; + static constexpr json::StaticString kTEST2{"Contents of a json::StaticString"}; + static constexpr json::StaticString kTEST3{"Another StaticString"}; - EXPECT_EQ(kTest1, kTest2); - EXPECT_NE(kTest1, kTest3); + EXPECT_EQ(kTEST1, kTEST2); + EXPECT_NE(kTEST1, kTEST3); - std::string const str{kSample}; - EXPECT_EQ(str, kTest2); - EXPECT_NE(str, kTest3); - EXPECT_EQ(kTest2, str); - EXPECT_NE(kTest3, str); + std::string const str{kSAMPLE}; + EXPECT_EQ(str, kTEST2); + EXPECT_NE(str, kTEST3); + EXPECT_EQ(kTEST2, str); + EXPECT_NE(kTEST3, str); } TEST(json_value, different_types) { // Exercise ValueType constructor - static constexpr json::StaticString kStaticStr{"staticStr"}; + static constexpr json::StaticString kSTATIC_STR{"staticStr"}; auto testCopy = [](json::ValueType typ) { json::Value val{typ}; @@ -64,7 +64,7 @@ TEST(json_value, different_types) return val; }; { - json::Value const nullV{testCopy(json::ValueType::Null)}; + json::Value const nullV{testCopy(json::NullValue)}; EXPECT_TRUE(nullV.isNull()); EXPECT_FALSE(nullV.isBool()); EXPECT_FALSE(nullV.isInt()); @@ -79,7 +79,7 @@ TEST(json_value, different_types) EXPECT_TRUE(nullV.isObjectOrNull()); } { - json::Value const intV{testCopy(json::ValueType::Int)}; + json::Value const intV{testCopy(json::IntValue)}; EXPECT_FALSE(intV.isNull()); EXPECT_FALSE(intV.isBool()); EXPECT_TRUE(intV.isInt()); @@ -94,7 +94,7 @@ TEST(json_value, different_types) EXPECT_FALSE(intV.isObjectOrNull()); } { - json::Value const uintV{testCopy(json::ValueType::UInt)}; + json::Value const uintV{testCopy(json::UintValue)}; EXPECT_FALSE(uintV.isNull()); EXPECT_FALSE(uintV.isBool()); EXPECT_FALSE(uintV.isInt()); @@ -109,7 +109,7 @@ TEST(json_value, different_types) EXPECT_FALSE(uintV.isObjectOrNull()); } { - json::Value const realV{testCopy(json::ValueType::Real)}; + json::Value const realV{testCopy(json::RealValue)}; EXPECT_FALSE(realV.isNull()); EXPECT_FALSE(realV.isBool()); EXPECT_FALSE(realV.isInt()); @@ -124,7 +124,7 @@ TEST(json_value, different_types) EXPECT_FALSE(realV.isObjectOrNull()); } { - json::Value const stringV{testCopy(json::ValueType::String)}; + json::Value const stringV{testCopy(json::StringValue)}; EXPECT_FALSE(stringV.isNull()); EXPECT_FALSE(stringV.isBool()); EXPECT_FALSE(stringV.isInt()); @@ -139,11 +139,11 @@ TEST(json_value, different_types) EXPECT_FALSE(stringV.isObjectOrNull()); } { - json::Value const staticStrV{kStaticStr}; + json::Value const staticStrV{kSTATIC_STR}; { json::Value const cpy{staticStrV}; - EXPECT_EQ(staticStrV.type(), json::ValueType::String); - EXPECT_EQ(cpy.type(), json::ValueType::String); + EXPECT_EQ(staticStrV.type(), json::StringValue); + EXPECT_EQ(cpy.type(), json::StringValue); } EXPECT_FALSE(staticStrV.isNull()); EXPECT_FALSE(staticStrV.isBool()); @@ -159,7 +159,7 @@ TEST(json_value, different_types) EXPECT_FALSE(staticStrV.isObjectOrNull()); } { - json::Value const boolV{testCopy(json::ValueType::Boolean)}; + json::Value const boolV{testCopy(json::BooleanValue)}; EXPECT_FALSE(boolV.isNull()); EXPECT_TRUE(boolV.isBool()); EXPECT_FALSE(boolV.isInt()); @@ -174,7 +174,7 @@ TEST(json_value, different_types) EXPECT_FALSE(boolV.isObjectOrNull()); } { - json::Value const arrayV{testCopy(json::ValueType::Array)}; + json::Value const arrayV{testCopy(json::ArrayValue)}; EXPECT_FALSE(arrayV.isNull()); EXPECT_FALSE(arrayV.isBool()); EXPECT_FALSE(arrayV.isInt()); @@ -189,7 +189,7 @@ TEST(json_value, different_types) EXPECT_FALSE(arrayV.isObjectOrNull()); } { - json::Value const objectV{testCopy(json::ValueType::Object)}; + json::Value const objectV{testCopy(json::ObjectValue)}; EXPECT_FALSE(objectV.isNull()); EXPECT_FALSE(objectV.isBool()); EXPECT_FALSE(objectV.isInt()); @@ -223,24 +223,24 @@ TEST(json_value, compare_strings) json::Value const null0; json::Value const intNeg1{-1}; - json::Value const int0{json::ValueType::Int}; + json::Value const int0{json::IntValue}; json::Value const intPos1{1}; - json::Value const uint0{json::ValueType::UInt}; + json::Value const uint0{json::UintValue}; json::Value const uint1{1u}; json::Value const realNeg1{-1.0}; - json::Value const real0{json::ValueType::Real}; + json::Value const real0{json::RealValue}; json::Value const realPos1{1.0}; - json::Value const str0{json::ValueType::String}; + json::Value const str0{json::StringValue}; json::Value const str1{"1"}; json::Value const boolF{false}; json::Value const boolT{true}; - json::Value const array0{json::ValueType::Array}; + json::Value const array0{json::ArrayValue}; json::Value const array1{[]() { json::Value array1; array1[0u] = 1; return array1; }()}; - json::Value const obj0{json::ValueType::Object}; + json::Value const obj0{json::ObjectValue}; json::Value const obj1{[]() { json::Value obj1; obj1["one"] = 1; @@ -571,12 +571,12 @@ TEST(json_value, bool) EXPECT_TRUE(bool(json::Value(0))); EXPECT_TRUE(bool(json::Value(1))); - json::Value array(json::ValueType::Array); + json::Value array(json::ArrayValue); EXPECT_FALSE(array); array.append(0); EXPECT_TRUE(bool(array)); - json::Value object(json::ValueType::Object); + json::Value object(json::ObjectValue); EXPECT_FALSE(object); object[""] = false; EXPECT_TRUE(bool(object)); @@ -594,19 +594,19 @@ TEST(json_value, bad_json) TEST(json_value, edge_cases) { - std::uint32_t const maxUInt = std::numeric_limits::max(); + std::uint32_t const maxUint = std::numeric_limits::max(); std::int32_t const maxInt = std::numeric_limits::max(); std::int32_t const minInt = std::numeric_limits::min(); - std::uint32_t const aUInt = maxUInt - 1978; + std::uint32_t const aUint = maxUint - 1978; std::int32_t const aLargeInt = maxInt - 1978; std::int32_t const aSmallInt = minInt + 1978; { - std::string json = "{\"max_uint\":" + std::to_string(maxUInt); + std::string json = "{\"max_uint\":" + std::to_string(maxUint); json += ",\"max_int\":" + std::to_string(maxInt); json += ",\"min_int\":" + std::to_string(minInt); - json += ",\"a_uint\":" + std::to_string(aUInt); + json += ",\"a_uint\":" + std::to_string(aUint); json += ",\"a_large_int\":" + std::to_string(aLargeInt); json += ",\"a_small_int\":" + std::to_string(aSmallInt); json += "}"; @@ -615,26 +615,26 @@ TEST(json_value, edge_cases) json::Reader r1; EXPECT_TRUE(r1.parse(json, j1)); - EXPECT_EQ(j1["max_uint"].asUInt(), maxUInt); - EXPECT_EQ(j1["max_uint"].asAbsUInt(), maxUInt); + EXPECT_EQ(j1["max_uint"].asUInt(), maxUint); + EXPECT_EQ(j1["max_uint"].asAbsUInt(), maxUint); EXPECT_EQ(j1["max_int"].asInt(), maxInt); EXPECT_EQ(j1["max_int"].asAbsUInt(), maxInt); EXPECT_EQ(j1["min_int"].asInt(), minInt); EXPECT_EQ(j1["min_int"].asAbsUInt(), static_cast(minInt) * -1); - EXPECT_EQ(j1["a_uint"].asUInt(), aUInt); - EXPECT_EQ(j1["a_uint"].asAbsUInt(), aUInt); + EXPECT_EQ(j1["a_uint"].asUInt(), aUint); + EXPECT_EQ(j1["a_uint"].asAbsUInt(), aUint); EXPECT_GT(j1["a_uint"], aLargeInt); EXPECT_GT(j1["a_uint"], aSmallInt); EXPECT_EQ(j1["a_large_int"].asInt(), aLargeInt); EXPECT_EQ(j1["a_large_int"].asAbsUInt(), aLargeInt); EXPECT_EQ(j1["a_large_int"].asUInt(), aLargeInt); - EXPECT_LT(j1["a_large_int"], aUInt); + EXPECT_LT(j1["a_large_int"], aUint); EXPECT_EQ(j1["a_small_int"].asInt(), aSmallInt); EXPECT_EQ(j1["a_small_int"].asAbsUInt(), static_cast(aSmallInt) * -1); - EXPECT_LT(j1["a_small_int"], aUInt); + EXPECT_LT(j1["a_small_int"], aUint); } - std::uint64_t const overflow = std::uint64_t(maxUInt) + 1; + std::uint64_t const overflow = std::uint64_t(maxUint) + 1; { std::string json = "{\"overflow\":"; json += std::to_string(overflow); @@ -859,7 +859,9 @@ TEST(json_value, compact) TEST(json_value, conversions) { - // We have json::ValueType::Real but json::Value::asDouble. + // We have json::Int, but not json::Double or json::Real. + // We have json::Int, json::Value::Int, and json::ValueType::intValue. + // We have json::ValueType::realValue but json::Value::asDouble. // TODO: What's the thinking here? { // null @@ -873,14 +875,14 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), 0.0); EXPECT_FALSE(val.asBool()); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_TRUE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_TRUE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_TRUE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_TRUE(val.isConvertibleTo(json::ObjectValue)); } { // int @@ -894,14 +896,14 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), -1234.0); EXPECT_TRUE(val.asBool()); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_FALSE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_FALSE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // uint @@ -915,14 +917,14 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), 1234.0); EXPECT_TRUE(val.asBool()); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_FALSE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_TRUE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // real @@ -936,14 +938,14 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), 2.0); EXPECT_TRUE(val.asBool()); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_FALSE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_TRUE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // numeric string @@ -957,18 +959,18 @@ TEST(json_value, conversions) EXPECT_THROW([&] { return val.asDouble(); }(), json::Error); EXPECT_TRUE(val.asBool()); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_FALSE(val.isConvertibleTo(json::NullValue)); + EXPECT_FALSE(val.isConvertibleTo(json::IntValue)); + EXPECT_FALSE(val.isConvertibleTo(json::UintValue)); + EXPECT_FALSE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_FALSE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // non-numeric string - json::Value const val(json::ValueType::String); + json::Value const val(json::StringValue); EXPECT_TRUE(val.isString()); EXPECT_EQ(val.asCString(), nullptr); EXPECT_EQ(val.asString(), ""); @@ -978,14 +980,14 @@ TEST(json_value, conversions) EXPECT_THROW([&] { return val.asDouble(); }(), std::exception); EXPECT_TRUE(val.asBool() == false); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_TRUE(val.isConvertibleTo(json::NullValue)); + EXPECT_FALSE(val.isConvertibleTo(json::IntValue)); + EXPECT_FALSE(val.isConvertibleTo(json::UintValue)); + EXPECT_FALSE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_FALSE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // bool false @@ -999,14 +1001,14 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), 0.0); EXPECT_FALSE(val.asBool()); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_TRUE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_TRUE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // bool true @@ -1020,18 +1022,18 @@ TEST(json_value, conversions) EXPECT_EQ(val.asDouble(), 1.0); EXPECT_TRUE(val.asBool()); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_FALSE(val.isConvertibleTo(json::NullValue)); + EXPECT_TRUE(val.isConvertibleTo(json::IntValue)); + EXPECT_TRUE(val.isConvertibleTo(json::UintValue)); + EXPECT_TRUE(val.isConvertibleTo(json::RealValue)); + EXPECT_TRUE(val.isConvertibleTo(json::StringValue)); + EXPECT_TRUE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // array type - json::Value const val(json::ValueType::Array); + json::Value const val(json::ArrayValue); EXPECT_TRUE(val.isArray()); // val.asCString should trigger an assertion failure EXPECT_THROW([&] { return val.asString(); }(), json::Error); @@ -1041,18 +1043,18 @@ TEST(json_value, conversions) EXPECT_THROW([&] { return val.asDouble(); }(), json::Error); EXPECT_FALSE(val.asBool()); // empty or not - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_TRUE(val.isConvertibleTo(json::NullValue)); + EXPECT_FALSE(val.isConvertibleTo(json::IntValue)); + EXPECT_FALSE(val.isConvertibleTo(json::UintValue)); + EXPECT_FALSE(val.isConvertibleTo(json::RealValue)); + EXPECT_FALSE(val.isConvertibleTo(json::StringValue)); + EXPECT_FALSE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_TRUE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ObjectValue)); } { // object type - json::Value const val(json::ValueType::Object); + json::Value const val(json::ObjectValue); EXPECT_TRUE(val.isObject()); // val.asCString should trigger an assertion failure EXPECT_THROW([&] { return val.asString(); }(), json::Error); @@ -1062,29 +1064,29 @@ TEST(json_value, conversions) EXPECT_THROW([&] { return val.asDouble(); }(), json::Error); EXPECT_FALSE(val.asBool()); // empty or not - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Null)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Int)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::UInt)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Real)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::String)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Boolean)); - EXPECT_FALSE(val.isConvertibleTo(json::ValueType::Array)); - EXPECT_TRUE(val.isConvertibleTo(json::ValueType::Object)); + EXPECT_TRUE(val.isConvertibleTo(json::NullValue)); + EXPECT_FALSE(val.isConvertibleTo(json::IntValue)); + EXPECT_FALSE(val.isConvertibleTo(json::UintValue)); + EXPECT_FALSE(val.isConvertibleTo(json::RealValue)); + EXPECT_FALSE(val.isConvertibleTo(json::StringValue)); + EXPECT_FALSE(val.isConvertibleTo(json::BooleanValue)); + EXPECT_FALSE(val.isConvertibleTo(json::ArrayValue)); + EXPECT_TRUE(val.isConvertibleTo(json::ObjectValue)); } } TEST(json_value, access_members) { json::Value val; - EXPECT_EQ(val.type(), json::ValueType::Null); + EXPECT_EQ(val.type(), json::NullValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); { json::Value const constVal = val; - EXPECT_EQ(constVal[7u].type(), json::ValueType::Null); + EXPECT_EQ(constVal[7u].type(), json::NullValue); EXPECT_FALSE(constVal.isMember("key")); - EXPECT_EQ(constVal["key"].type(), json::ValueType::Null); + EXPECT_EQ(constVal["key"].type(), json::NullValue); EXPECT_TRUE(constVal.getMemberNames().empty()); EXPECT_EQ(constVal.get(1u, "default0"), "default0"); EXPECT_EQ(constVal.get(std::string("not"), "oh"), "oh"); @@ -1092,74 +1094,74 @@ TEST(json_value, access_members) } val = -7; - EXPECT_EQ(val.type(), json::ValueType::Int); + EXPECT_EQ(val.type(), json::IntValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); val = 42u; - EXPECT_EQ(val.type(), json::ValueType::UInt); + EXPECT_EQ(val.type(), json::UintValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); val = std::numbers::pi; - EXPECT_EQ(val.type(), json::ValueType::Real); + EXPECT_EQ(val.type(), json::RealValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); val = true; - EXPECT_EQ(val.type(), json::ValueType::Boolean); + EXPECT_EQ(val.type(), json::BooleanValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); val = "string"; - EXPECT_EQ(val.type(), json::ValueType::String); + EXPECT_EQ(val.type(), json::StringValue); EXPECT_EQ(val.size(), 0); EXPECT_FALSE(val.isValidIndex(0)); EXPECT_FALSE(val.isMember("key")); - val = json::Value(json::ValueType::Object); - EXPECT_EQ(val.type(), json::ValueType::Object); + val = json::Value(json::ObjectValue); + EXPECT_EQ(val.type(), json::ObjectValue); EXPECT_EQ(val.size(), 0); - static json::StaticString const kStaticThree("three"); - val[kStaticThree] = 3; + static json::StaticString const kSTATIC_THREE("three"); + val[kSTATIC_THREE] = 3; val["two"] = 2; EXPECT_EQ(val.size(), 2); EXPECT_TRUE(val.isValidIndex(1)); EXPECT_FALSE(val.isValidIndex(2)); - EXPECT_EQ(val[kStaticThree], 3); + EXPECT_EQ(val[kSTATIC_THREE], 3); EXPECT_TRUE(val.isMember("two")); - EXPECT_TRUE(val.isMember(kStaticThree)); + EXPECT_TRUE(val.isMember(kSTATIC_THREE)); EXPECT_FALSE(val.isMember("key")); { json::Value const constVal = val; EXPECT_EQ(constVal["two"], 2); - EXPECT_EQ(constVal["four"].type(), json::ValueType::Null); - EXPECT_EQ(constVal[kStaticThree], 3); + EXPECT_EQ(constVal["four"].type(), json::NullValue); + EXPECT_EQ(constVal[kSTATIC_THREE], 3); EXPECT_TRUE(constVal.isMember("two")); - EXPECT_TRUE(constVal.isMember(kStaticThree)); + EXPECT_TRUE(constVal.isMember(kSTATIC_THREE)); EXPECT_FALSE(constVal.isMember("key")); EXPECT_EQ(val.get(std::string("two"), "backup"), 2); EXPECT_EQ(val.get("missing", "default2"), "default2"); } - val = json::Value(json::ValueType::Array); - EXPECT_EQ(val.type(), json::ValueType::Array); + val = json::Value(json::ArrayValue); + EXPECT_EQ(val.type(), json::ArrayValue); EXPECT_EQ(val.size(), 0); val[0u] = "zero"; val[1u] = "one"; EXPECT_EQ(val.size(), 2); EXPECT_TRUE(val.isValidIndex(1)); EXPECT_FALSE(val.isValidIndex(2)); - EXPECT_EQ(val[20u].type(), json::ValueType::Null); + EXPECT_EQ(val[20u].type(), json::NullValue); EXPECT_FALSE(val.isMember("key")); { json::Value const constVal = val; EXPECT_EQ(constVal[0u], "zero"); - EXPECT_EQ(constVal[2u].type(), json::ValueType::Null); + EXPECT_EQ(constVal[2u].type(), json::NullValue); EXPECT_FALSE(constVal.isMember("key")); EXPECT_EQ(val.get(1u, "default0"), "one"); EXPECT_EQ(val.get(3u, "default1"), "default1"); @@ -1169,27 +1171,27 @@ TEST(json_value, access_members) TEST(json_value, remove_members) { json::Value val; - EXPECT_EQ(val.removeMember(std::string("member")).type(), json::ValueType::Null); + EXPECT_EQ(val.removeMember(std::string("member")).type(), json::NullValue); - val = json::Value(json::ValueType::Object); - static json::StaticString const kStaticThree("three"); - val[kStaticThree] = 3; + val = json::Value(json::ObjectValue); + static json::StaticString const kSTATIC_THREE("three"); + val[kSTATIC_THREE] = 3; val["two"] = 2; EXPECT_EQ(val.size(), 2); - EXPECT_EQ(val.removeMember(std::string("six")).type(), json::ValueType::Null); + EXPECT_EQ(val.removeMember(std::string("six")).type(), json::NullValue); EXPECT_EQ(val.size(), 2); - EXPECT_EQ(val.removeMember(kStaticThree), 3); + EXPECT_EQ(val.removeMember(kSTATIC_THREE), 3); EXPECT_EQ(val.size(), 1); - EXPECT_EQ(val.removeMember(kStaticThree).type(), json::ValueType::Null); + EXPECT_EQ(val.removeMember(kSTATIC_THREE).type(), json::NullValue); EXPECT_EQ(val.size(), 1); EXPECT_EQ(val.removeMember(std::string("two")), 2); EXPECT_EQ(val.size(), 0); - EXPECT_EQ(val.removeMember(std::string("two")).type(), json::ValueType::Null); + EXPECT_EQ(val.removeMember(std::string("two")).type(), json::NullValue); EXPECT_EQ(val.size(), 0); } @@ -1197,7 +1199,7 @@ TEST(json_value, iterator) { { // Iterating an array. - json::Value arr{json::ValueType::Array}; + json::Value arr{json::ArrayValue}; arr[0u] = "zero"; arr[1u] = "one"; arr[2u] = "two"; @@ -1235,7 +1237,7 @@ TEST(json_value, iterator) { // Iterating a const object. json::Value const obj{[]() { - json::Value obj{json::ValueType::Object}; + json::Value obj{json::ObjectValue}; obj["0"] = 0; obj["1"] = 1; obj["2"] = 2; @@ -1295,14 +1297,14 @@ TEST(json_value, nest_limits) { // Within object nest limit - auto json{nest(std::min(10u, json::Reader::kNestLimit))}; + auto json{nest(std::min(10u, json::Reader::kNEST_LIMIT))}; json::Value j; EXPECT_TRUE(r.parse(json, j)); } { // Exceed object nest limit - auto json{nest(json::Reader::kNestLimit + 1)}; + auto json{nest(json::Reader::kNEST_LIMIT + 1)}; json::Value j; EXPECT_FALSE(r.parse(json, j)); } @@ -1319,7 +1321,7 @@ TEST(json_value, nest_limits) }; { // Exceed array nest limit - auto json{nest(json::Reader::kNestLimit + 1)}; + auto json{nest(json::Reader::kNEST_LIMIT + 1)}; json::Value j; EXPECT_FALSE(r.parse(json, j)); } @@ -1332,27 +1334,27 @@ TEST(json_value, memory_leak) { json::Value a; a[0u] = 1; - EXPECT_EQ(a.type(), json::ValueType::Array); - EXPECT_EQ(a[0u].type(), json::ValueType::Int); + EXPECT_EQ(a.type(), json::ArrayValue); + EXPECT_EQ(a[0u].type(), json::IntValue); a = std::move(a[0u]); - EXPECT_EQ(a.type(), json::ValueType::Int); + EXPECT_EQ(a.type(), json::IntValue); } { json::Value b; json::Value temp; temp["a"] = "Probably avoids the small string optimization"; temp["b"] = "Also probably avoids the small string optimization"; - EXPECT_EQ(temp.type(), json::ValueType::Object); + EXPECT_EQ(temp.type(), json::ObjectValue); b.append(temp); - EXPECT_EQ(temp.type(), json::ValueType::Object); + EXPECT_EQ(temp.type(), json::ObjectValue); EXPECT_EQ(b.size(), 1); b.append(std::move(temp)); EXPECT_EQ(b.size(), 2); - // Note that the type() == ValueType::Null check is implementation + // Note that the type() == nullValue check is implementation // specific and not guaranteed to be valid in the future. - EXPECT_EQ(temp.type(), json::ValueType::Null); // NOLINT(bugprone-use-after-move) + EXPECT_EQ(temp.type(), json::NullValue); // NOLINT(bugprone-use-after-move) } } diff --git a/src/tests/libxrpl/json/Writer.cpp b/src/tests/libxrpl/json/Writer.cpp index 25218f81f0..772428ecb5 100644 --- a/src/tests/libxrpl/json/Writer.cpp +++ b/src/tests/libxrpl/json/Writer.cpp @@ -164,7 +164,7 @@ TEST_F(WriterFixture, complex_object) TEST_F(WriterFixture, json_value) { - json::Value value(json::ValueType::Object); + json::Value value(json::ObjectValue); value["foo"] = 23; writer_->startRoot(Writer::CollectionType::Object); writer_->set("hello", value); diff --git a/src/tests/libxrpl/protocol_autogen/TestHelpers.h b/src/tests/libxrpl/protocol_autogen/TestHelpers.h index a32ab5e20c..dbc5aac40a 100644 --- a/src/tests/libxrpl/protocol_autogen/TestHelpers.h +++ b/src/tests/libxrpl/protocol_autogen/TestHelpers.h @@ -28,60 +28,60 @@ namespace xrpl { // Typed field canonical values -using UInt8Value = std::decay_t; -inline UInt8Value +using Uint8Value = std::decay_t; +inline Uint8Value canonical_UINT8() { - return UInt8Value{1}; + return Uint8Value{1}; } -using UInt16Value = std::decay_t; -inline UInt16Value +using Uint16Value = std::decay_t; +inline Uint16Value canonical_UINT16() { - return UInt16Value{1}; + return Uint16Value{1}; } -using UInt32Value = std::decay_t; -inline UInt32Value +using Uint32Value = std::decay_t; +inline Uint32Value canonical_UINT32() { - return UInt32Value{1}; + return Uint32Value{1}; } -using UInt64Value = std::decay_t; -inline UInt64Value +using Uint64Value = std::decay_t; +inline Uint64Value canonical_UINT64() { - return UInt64Value{1}; + return Uint64Value{1}; } -using UInt128Value = std::decay_t; -inline UInt128Value +using Uint128Value = std::decay_t; +inline Uint128Value canonical_UINT128() { - return UInt128Value{1}; + return Uint128Value{1}; } -using UInt160Value = std::decay_t; -inline UInt160Value +using Uint160Value = std::decay_t; +inline Uint160Value canonical_UINT160() { - return UInt160Value{1}; + return Uint160Value{1}; } -using UInt192Value = std::decay_t; -inline UInt192Value +using Uint192Value = std::decay_t; +inline Uint192Value canonical_UINT192() { - return UInt192Value{1}; + return Uint192Value{1}; } -using UInt256Value = std::decay_t; -inline UInt256Value +using Uint256Value = std::decay_t; +inline Uint256Value canonical_UINT256() { - return UInt256Value{1}; + return Uint256Value{1}; } using Int32Value = std::decay_t; @@ -159,7 +159,7 @@ canonical_ARRAY() inline STObject canonical_OBJECT() { - return STObject{sfGeneric}; + return STObject{kSF_GENERIC}; } inline STPathSet diff --git a/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp b/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp index 8dc5960ee0..4936a3babc 100644 --- a/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp +++ b/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp @@ -33,7 +33,6 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) auto const previousTxnLgrSeqValue = canonical_UINT32(); auto const domainIDValue = canonical_UINT256(); auto const mutableFlagsValue = canonical_UINT32(); - auto const referenceHoldingValue = canonical_UINT256(); auto const issuerEncryptionKeyValue = canonical_VL(); auto const auditorEncryptionKeyValue = canonical_VL(); auto const confidentialOutstandingAmountValue = canonical_UINT64(); @@ -54,7 +53,6 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) builder.setMPTokenMetadata(mPTokenMetadataValue); builder.setDomainID(domainIDValue); builder.setMutableFlags(mutableFlagsValue); - builder.setReferenceHolding(referenceHoldingValue); builder.setIssuerEncryptionKey(issuerEncryptionKeyValue); builder.setAuditorEncryptionKey(auditorEncryptionKeyValue); builder.setConfidentialOutstandingAmount(confidentialOutstandingAmountValue); @@ -160,14 +158,6 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) EXPECT_TRUE(entry.hasMutableFlags()); } - { - auto const& expected = referenceHoldingValue; - auto const actualOpt = entry.getReferenceHolding(); - ASSERT_TRUE(actualOpt.has_value()); - expectEqualField(expected, *actualOpt, "sfReferenceHolding"); - EXPECT_TRUE(entry.hasReferenceHolding()); - } - { auto const& expected = issuerEncryptionKeyValue; auto const actualOpt = entry.getIssuerEncryptionKey(); @@ -218,7 +208,6 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) auto const previousTxnLgrSeqValue = canonical_UINT32(); auto const domainIDValue = canonical_UINT256(); auto const mutableFlagsValue = canonical_UINT32(); - auto const referenceHoldingValue = canonical_UINT256(); auto const issuerEncryptionKeyValue = canonical_VL(); auto const auditorEncryptionKeyValue = canonical_VL(); auto const confidentialOutstandingAmountValue = canonical_UINT64(); @@ -238,7 +227,6 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) sle->at(sfPreviousTxnLgrSeq) = previousTxnLgrSeqValue; sle->at(sfDomainID) = domainIDValue; sle->at(sfMutableFlags) = mutableFlagsValue; - sle->at(sfReferenceHolding) = referenceHoldingValue; sle->at(sfIssuerEncryptionKey) = issuerEncryptionKeyValue; sle->at(sfAuditorEncryptionKey) = auditorEncryptionKeyValue; sle->at(sfConfidentialOutstandingAmount) = confidentialOutstandingAmountValue; @@ -403,19 +391,6 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) expectEqualField(expected, *fromBuilderOpt, "sfMutableFlags"); } - { - auto const& expected = referenceHoldingValue; - - auto const fromSleOpt = entryFromSle.getReferenceHolding(); - auto const fromBuilderOpt = entryFromBuilder.getReferenceHolding(); - - ASSERT_TRUE(fromSleOpt.has_value()); - ASSERT_TRUE(fromBuilderOpt.has_value()); - - expectEqualField(expected, *fromSleOpt, "sfReferenceHolding"); - expectEqualField(expected, *fromBuilderOpt, "sfReferenceHolding"); - } - { auto const& expected = issuerEncryptionKeyValue; @@ -533,8 +508,6 @@ TEST(MPTokenIssuanceTests, OptionalFieldsReturnNullopt) EXPECT_FALSE(entry.getDomainID().has_value()); EXPECT_FALSE(entry.hasMutableFlags()); EXPECT_FALSE(entry.getMutableFlags().has_value()); - EXPECT_FALSE(entry.hasReferenceHolding()); - EXPECT_FALSE(entry.getReferenceHolding().has_value()); EXPECT_FALSE(entry.hasIssuerEncryptionKey()); EXPECT_FALSE(entry.getIssuerEncryptionKey().has_value()); EXPECT_FALSE(entry.hasAuditorEncryptionKey()); diff --git a/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp b/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp index 5b78f0cfdd..60034255c7 100644 --- a/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp +++ b/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp @@ -31,7 +31,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) // Transaction-specific field values auto const ledgerFixTypeValue = canonical_UINT16(); auto const ownerValue = canonical_ACCOUNT(); - auto const bookDirectoryValue = canonical_UINT256(); LedgerStateFixBuilder builder{ accountValue, @@ -42,7 +41,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) // Set optional fields builder.setOwner(ownerValue); - builder.setBookDirectory(bookDirectoryValue); auto tx = builder.build(publicKey, secretKey); @@ -74,14 +72,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) EXPECT_TRUE(tx.hasOwner()); } - { - auto const& expected = bookDirectoryValue; - auto const actualOpt = tx.getBookDirectory(); - ASSERT_TRUE(actualOpt.has_value()) << "Optional field sfBookDirectory should be present"; - expectEqualField(expected, *actualOpt, "sfBookDirectory"); - EXPECT_TRUE(tx.hasBookDirectory()); - } - } // 2 & 4) Start from an STTx, construct a builder from it, build a new wrapper, @@ -100,7 +90,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) // Transaction-specific field values auto const ledgerFixTypeValue = canonical_UINT16(); auto const ownerValue = canonical_ACCOUNT(); - auto const bookDirectoryValue = canonical_UINT256(); // Build an initial transaction LedgerStateFixBuilder initialBuilder{ @@ -111,7 +100,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) }; initialBuilder.setOwner(ownerValue); - initialBuilder.setBookDirectory(bookDirectoryValue); auto initialTx = initialBuilder.build(publicKey, secretKey); @@ -143,13 +131,6 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) expectEqualField(expected, *actualOpt, "sfOwner"); } - { - auto const& expected = bookDirectoryValue; - auto const actualOpt = rebuiltTx.getBookDirectory(); - ASSERT_TRUE(actualOpt.has_value()) << "Optional field sfBookDirectory should be present"; - expectEqualField(expected, *actualOpt, "sfBookDirectory"); - } - } // 3) Verify wrapper throws when constructed from wrong transaction type. @@ -209,8 +190,6 @@ TEST(TransactionsLedgerStateFixTests, OptionalFieldsReturnNullopt) // Verify optional fields are not present EXPECT_FALSE(tx.hasOwner()); EXPECT_FALSE(tx.getOwner().has_value()); - EXPECT_FALSE(tx.hasBookDirectory()); - EXPECT_FALSE(tx.getBookDirectory().has_value()); } } diff --git a/src/tests/libxrpl/tx/AccountSet.cpp b/src/tests/libxrpl/tx/AccountSet.cpp index 726e6e9024..4187ec1115 100644 --- a/src/tests/libxrpl/tx/AccountSet.cpp +++ b/src/tests/libxrpl/tx/AccountSet.cpp @@ -382,7 +382,7 @@ TEST(AccountSet, WalletID) // Clear the wallet locator by setting to zero EXPECT_EQ( - env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(beast::kZero), alice) + env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(beast::kZERO), alice) .ter, tesSUCCESS); env.close(); @@ -414,7 +414,7 @@ TEST(AccountSet, EmailHash) // Clear the email hash by setting to zero EXPECT_EQ( - env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(beast::kZero), alice).ter, + env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(beast::kZERO), alice).ter, tesSUCCESS); env.close(); @@ -432,13 +432,13 @@ TEST(AccountSet, TransferRate) // Test data: {rate to set, expected TER, expected stored rate} std::vector const testData = { - {.set = 1.0, .code = tesSUCCESS, .get = 1.0}, - {.set = 1.1, .code = tesSUCCESS, .get = 1.1}, - {.set = 2.0, .code = tesSUCCESS, .get = 2.0}, - {.set = 2.1, .code = temBAD_TRANSFER_RATE, .get = 2.0}, // > 2.0 is invalid - {.set = 0.0, .code = tesSUCCESS, .get = 1.0}, // 0 clears; default rate is 1.0 - {.set = 2.0, .code = tesSUCCESS, .get = 2.0}, - {.set = 0.9, .code = temBAD_TRANSFER_RATE, .get = 2.0}, // < 1.0 is invalid + {1.0, tesSUCCESS, 1.0}, + {1.1, tesSUCCESS, 1.1}, + {2.0, tesSUCCESS, 2.0}, + {2.1, temBAD_TRANSFER_RATE, 2.0}, // > 2.0 is invalid + {0.0, tesSUCCESS, 1.0}, // 0 clears the rate (default = 1.0) + {2.0, tesSUCCESS, 2.0}, + {0.9, temBAD_TRANSFER_RATE, 2.0}, // < 1.0 is invalid }; TxTest env; @@ -619,7 +619,7 @@ TEST(AccountSet, Ticket) // Verify alice has 1 owner object (the ticket) EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 1u); // Verify ticket exists - EXPECT_TRUE(env.getClosedLedger().exists(keylet::kTicket(alice.id(), ticketSeq))); + EXPECT_TRUE(env.getClosedLedger().exists(keylet::kTICKET(alice.id(), ticketSeq))); // Try using a ticket that alice doesn't have EXPECT_EQ( @@ -629,7 +629,7 @@ TEST(AccountSet, Ticket) env.close(); // Verify ticket still exists - EXPECT_TRUE(env.getClosedLedger().exists(keylet::kTicket(alice.id(), ticketSeq))); + EXPECT_TRUE(env.getClosedLedger().exists(keylet::kTICKET(alice.id(), ticketSeq))); // Get alice's sequence before using the ticket std::uint32_t const aliceSeq = env.getAccountRoot(alice.id()).getSequence(); @@ -642,7 +642,7 @@ TEST(AccountSet, Ticket) // Verify ticket is consumed (no owner objects) EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 0u); - EXPECT_FALSE(env.getClosedLedger().exists(keylet::kTicket(alice.id(), ticketSeq))); + EXPECT_FALSE(env.getClosedLedger().exists(keylet::kTICKET(alice.id(), ticketSeq))); // Verify alice's sequence did NOT advance (ticket use doesn't increment seq) EXPECT_EQ(env.getAccountRoot(alice.id()).getSequence(), aliceSeq); diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index a474c9c339..b5a643568b 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -130,7 +130,7 @@ RCLConsensus::Adaptor::Adaptor( JLOG(j_.info()) << "Consensus engine started (cookie: " + std::to_string(valCookie_) + ")"; - if (validatorKeys_.nodeID != beast::kZero && validatorKeys_.keys) + if (validatorKeys_.nodeID != beast::kZERO && validatorKeys_.keys) { JLOG(j_.info()) << "Validator identity: " << toBase58(TokenType::NodePublic, validatorKeys_.keys->masterPublicKey); @@ -214,8 +214,8 @@ RCLConsensus::Adaptor::share(RCLCxTx const& tx) msg.set_rawtransaction(slice.data(), slice.size()); msg.set_status(protocol::tsNEW); msg.set_receivetimestamp(app_.getTimeKeeper().now().time_since_epoch().count()); - static std::set const kSkip{}; - app_.getOverlay().relay(tx.id(), msg, kSkip); + static std::set const kSKIP{}; + app_.getOverlay().relay(tx.id(), msg, kSKIP); } else { @@ -400,13 +400,13 @@ RCLConsensus::Adaptor::onClose( } // Needed because of the move below. - auto const setHash = initialSet->getHash().asUInt256(); + auto const setHash = initialSet->getHash().asUint256(); return Result{ std::move(initialSet), RCLCxPeerPos::Proposal{ initialLedger->header().parentHash, - RCLCxPeerPos::Proposal::kSeqJoin, + RCLCxPeerPos::Proposal::kSEQ_JOIN, setHash, closeTime, app_.getTimeKeeper().closeTime(), @@ -499,7 +499,7 @@ RCLConsensus::Adaptor::doAccept( // we use the hash of the set. // // FIXME: Use a std::vector and a custom sorter instead of CanonicalTXSet? - CanonicalTXSet retriableTxs{result.txns.map->getHash().asUInt256()}; + CanonicalTXSet retriableTxs{result.txns.map->getHash().asUint256()}; JLOG(j_.debug()) << "Building canonical tx set: " << retriableTxs.key(); @@ -557,7 +557,7 @@ RCLConsensus::Adaptor::doAccept( auto const wait = curr - seq; - if (wait && (wait % kCensorshipWarnInternal == 0)) + if (wait && (wait % kCENSORSHIP_WARN_INTERNAL == 0)) { std::ostringstream ss; ss << "Potential Censorship: Eligible tx " << id @@ -733,8 +733,8 @@ RCLConsensus::Adaptor::notify( s.set_ledgerseq(ledger.seq()); s.set_networktime(app_.getTimeKeeper().now().time_since_epoch().count()); s.set_ledgerhashprevious( - ledger.parentID().begin(), std::decay_t::kBytes); - s.set_ledgerhash(ledger.id().begin(), std::decay_t::kBytes); + ledger.parentID().begin(), std::decay_t::kBYTES); + s.set_ledgerhash(ledger.id().begin(), std::decay_t::kBYTES); std::uint32_t uMin = 0, uMax = 0; if (!ledgerMaster_.getFullValidatedRange(uMin, uMax)) @@ -831,7 +831,7 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, v.setFieldU32(sfLedgerSequence, ledger.seq()); if (proposing) - v.setFlag(kVfFullValidation); + v.setFlag(kVF_FULL_VALIDATION); // Attest to the hash of what we consider to be the last fully // validated ledger. This may be the hash of the ledger we are @@ -1090,7 +1090,7 @@ RclConsensusLogger::~RclConsensusLogger() std::stringstream outSs; outSs << header_ << "duration " << (duration.count() / 1000) << '.' << std::setw(3) << std::setfill('0') << (duration.count() % 1000) << "s. " << ss_->str(); - j_.sink().writeAlways(beast::Severity::Info, outSs.str()); + j_.sink().writeAlways(beast::severities::KInfo, outSs.str()); } } // namespace xrpl diff --git a/src/xrpld/app/consensus/RCLConsensus.h b/src/xrpld/app/consensus/RCLConsensus.h index 32759300fa..62a83d107e 100644 --- a/src/xrpld/app/consensus/RCLConsensus.h +++ b/src/xrpld/app/consensus/RCLConsensus.h @@ -33,7 +33,7 @@ class RCLConsensus { /** Warn for transactions that haven't been included every so many ledgers. */ - static constexpr unsigned int kCensorshipWarnInternal = 15; + constexpr static unsigned int kCENSORSHIP_WARN_INTERNAL = 15; // Implements the Adaptor template interface required by Consensus. class Adaptor diff --git a/src/xrpld/app/consensus/RCLCxTx.h b/src/xrpld/app/consensus/RCLCxTx.h index 52637d32b3..634b8ca915 100644 --- a/src/xrpld/app/consensus/RCLCxTx.h +++ b/src/xrpld/app/consensus/RCLCxTx.h @@ -131,7 +131,7 @@ public: [[nodiscard]] ID id() const { - return map->getHash().asUInt256(); + return map->getHash().asUint256(); } /** Find transactions not in common between this and another transaction diff --git a/src/xrpld/app/ledger/AccountStateSF.cpp b/src/xrpld/app/ledger/AccountStateSF.cpp index a0c3e3600d..c12c2864ec 100644 --- a/src/xrpld/app/ledger/AccountStateSF.cpp +++ b/src/xrpld/app/ledger/AccountStateSF.cpp @@ -19,13 +19,13 @@ AccountStateSF::gotNode( Blob&& nodeData, SHAMapNodeType) const { - db_.store(NodeObjectType::AccountNode, std::move(nodeData), nodeHash.asUInt256(), ledgerSeq); + db_.store(NodeObjectType::AccountNode, std::move(nodeData), nodeHash.asUint256(), ledgerSeq); } std::optional AccountStateSF::getNode(SHAMapHash const& nodeHash) const { - return fp_.getFetchPack(nodeHash.asUInt256()); + return fp_.getFetchPack(nodeHash.asUint256()); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 7c74c10b1b..029c16e7e4 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -53,7 +53,7 @@ ConsensusTransSetSF::gotNode( SerialIter sit(s.slice()); auto stx = std::make_shared(std::ref(sit)); XRPL_ASSERT( - stx->getTransactionID() == nodeHash.asUInt256(), + stx->getTransactionID() == nodeHash.asUint256(), "xrpl::ConsensusTransSetSF::gotNode : transaction hash " "match"); auto const pap = &app_; @@ -75,7 +75,7 @@ ConsensusTransSetSF::getNode(SHAMapHash const& nodeHash) const if (nodeCache_.retrieve(nodeHash, nodeData)) return nodeData; - auto txn = app_.getMasterTransaction().fetchFromCache(nodeHash.asUInt256()); + auto txn = app_.getMasterTransaction().fetchFromCache(nodeHash.asUint256()); if (txn) { @@ -85,7 +85,7 @@ ConsensusTransSetSF::getNode(SHAMapHash const& nodeHash) const s.add32(HashPrefix::TransactionId); txn->getSTransaction()->add(s); XRPL_ASSERT( - sha512Half(s.slice()) == nodeHash.asUInt256(), + sha512Half(s.slice()) == nodeHash.asUint256(), "xrpl::ConsensusTransSetSF::getNode : transaction hash match"); nodeData = s.peekData(); return nodeData; diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index d155c5902c..5f27c0c2c4 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -78,7 +78,7 @@ public: using neededHash_t = std::pair; - /** Return a json::ValueType::Object. */ + /** Return a json::objectValue. */ json::Value getJson(int); diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 8520fc941f..76bf4122e1 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -36,14 +36,14 @@ namespace xrpl { LedgerHistory::LedgerHistory(beast::insight::Collector::ptr const& collector, Application& app) : app_(app) , collector_(collector) - , mismatchCounter_(collector->makeCounter("ledger.history", "mismatch")) - , ledgersByHash_( + , mismatch_counter_(collector->makeCounter("ledger.history", "mismatch")) + , ledgers_by_hash_( "LedgerCache", app_.config().getValueFor(SizedItem::LedgerSize), std::chrono::seconds{app_.config().getValueFor(SizedItem::LedgerAge)}, stopwatch(), app_.getJournal("TaggedCache")) - , consensusValidated_( + , consensus_validated_( "ConsensusValidated", 64, std::chrono::minutes{5}, @@ -62,9 +62,10 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate XRPL_ASSERT( ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); - std::unique_lock const sl(ledgersByHash_.peekMutex()); + std::unique_lock const sl(ledgers_by_hash_.peekMutex()); - bool const alreadyHad = ledgersByHash_.canonicalizeReplaceCache(ledger->header().hash, ledger); + bool const alreadyHad = + ledgers_by_hash_.canonicalizeReplaceCache(ledger->header().hash, ledger); if (validated) ledgersByIndex_[ledger->header().seq] = ledger->header().hash; @@ -74,7 +75,7 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate LedgerHash LedgerHistory::getLedgerHash(LedgerIndex index) { - std::unique_lock const sl(ledgersByHash_.peekMutex()); + std::unique_lock const sl(ledgers_by_hash_.peekMutex()); if (auto it = ledgersByIndex_.find(index); it != ledgersByIndex_.end()) return it->second; return {}; @@ -84,7 +85,7 @@ std::shared_ptr LedgerHistory::getLedgerBySeq(LedgerIndex index) { { - std::unique_lock sl(ledgersByHash_.peekMutex()); + std::unique_lock sl(ledgers_by_hash_.peekMutex()); auto it = ledgersByIndex_.find(index); if (it != ledgersByIndex_.end()) @@ -96,7 +97,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) } Rules const rules{app_.config().features}; - Fees const fees = app_.config().fees.toFees(); + Fees const fees = app_.config().FEES.toFees(); std::shared_ptr ret = loadByIndex(index, rules, fees, app_); if (!ret) @@ -107,11 +108,11 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) { // Add this ledger to the local tracking by index - std::unique_lock const sl(ledgersByHash_.peekMutex()); + std::unique_lock const sl(ledgers_by_hash_.peekMutex()); XRPL_ASSERT( ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); - ledgersByHash_.canonicalizeReplaceClient(ret->header().hash, ret); + ledgers_by_hash_.canonicalizeReplaceClient(ret->header().hash, ret); ledgersByIndex_[ret->header().seq] = ret->header().hash; return (ret->header().seq == index) ? ret : nullptr; } @@ -120,7 +121,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) std::shared_ptr LedgerHistory::getLedgerByHash(LedgerHash const& hash) { - auto ret = ledgersByHash_.fetch(hash); + auto ret = ledgers_by_hash_.fetch(hash); if (ret) { @@ -136,7 +137,7 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) } Rules const rules{app_.config().features}; - Fees const fees = app_.config().fees.toFees(); + Fees const fees = app_.config().FEES.toFees(); ret = loadByHash(hash, rules, fees, app_); if (!ret) @@ -147,7 +148,7 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) XRPL_ASSERT( ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); - ledgersByHash_.canonicalizeReplaceClient(ret->header().hash, ret); + ledgers_by_hash_.canonicalizeReplaceClient(ret->header().hash, ret); XRPL_ASSERT( ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : result hash match"); @@ -163,7 +164,7 @@ logOne(ReadView const& ledger, uint256 const& tx, char const* msg, beast::Journa { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg << " is missing this transaction:\n" - << metaData->getJson(JsonOptions::Values::None); + << metaData->getJson(JsonOptions::KNone); } else { @@ -244,38 +245,38 @@ logMetadataDifference( { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result, index and nodes!"; - JLOG(j.debug()) << " Built:\n" << builtMetaData->getJson(JsonOptions::Values::None); - JLOG(j.debug()) << " Valid:\n" << validMetaData->getJson(JsonOptions::Values::None); + JLOG(j.debug()) << " Built:\n" << builtMetaData->getJson(JsonOptions::KNone); + JLOG(j.debug()) << " Valid:\n" << validMetaData->getJson(JsonOptions::KNone); } else if (resultDiff) { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result and nodes!"; JLOG(j.debug()) << " Built:" << " Result: " << builtMetaData->getResult() << " Nodes:\n" - << builtNodes.getJson(JsonOptions::Values::None); + << builtNodes.getJson(JsonOptions::KNone); JLOG(j.debug()) << " Valid:" << " Result: " << validMetaData->getResult() << " Nodes:\n" - << validNodes.getJson(JsonOptions::Values::None); + << validNodes.getJson(JsonOptions::KNone); } else if (indexDiff) { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different index and nodes!"; JLOG(j.debug()) << " Built:" << " Index: " << builtMetaData->getIndex() << " Nodes:\n" - << builtNodes.getJson(JsonOptions::Values::None); + << builtNodes.getJson(JsonOptions::KNone); JLOG(j.debug()) << " Valid:" << " Index: " << validMetaData->getIndex() << " Nodes:\n" - << validNodes.getJson(JsonOptions::Values::None); + << validNodes.getJson(JsonOptions::KNone); } else // nodes_diff { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different nodes!"; JLOG(j.debug()) << " Built:" << " Nodes:\n" - << builtNodes.getJson(JsonOptions::Values::None); + << builtNodes.getJson(JsonOptions::KNone); JLOG(j.debug()) << " Valid:" << " Nodes:\n" - << validNodes.getJson(JsonOptions::Values::None); + << validNodes.getJson(JsonOptions::KNone); } } @@ -285,13 +286,13 @@ logMetadataDifference( if (validMetaData) { JLOG(j.error()) << "MISMATCH on TX " << tx << ": Metadata Difference. Valid=\n" - << validMetaData->getJson(JsonOptions::Values::None); + << validMetaData->getJson(JsonOptions::KNone); } if (builtMetaData) { JLOG(j.error()) << "MISMATCH on TX " << tx << ": Metadata Difference. Built=\n" - << builtMetaData->getJson(JsonOptions::Values::None); + << builtMetaData->getJson(JsonOptions::KNone); } } @@ -318,7 +319,7 @@ LedgerHistory::handleMismatch( json::Value const& consensus) { XRPL_ASSERT(built != valid, "xrpl::LedgerHistory::handleMismatch : unequal hashes"); - ++mismatchCounter_; + ++mismatch_counter_; auto builtLedger = getLedgerByHash(built); auto validLedger = getLedgerByHash(valid); @@ -429,10 +430,10 @@ LedgerHistory::builtLedger( LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::builtLedger : nonzero hash"); - std::unique_lock const sl(consensusValidated_.peekMutex()); + std::unique_lock const sl(consensus_validated_.peekMutex()); auto entry = std::make_shared(); - consensusValidated_.canonicalizeReplaceClient(index, entry); + consensus_validated_.canonicalizeReplaceClient(index, entry); if (entry->validated && !entry->built) { @@ -468,10 +469,10 @@ LedgerHistory::validatedLedger( LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::validatedLedger : nonzero hash"); - std::unique_lock const sl(consensusValidated_.peekMutex()); + std::unique_lock const sl(consensus_validated_.peekMutex()); auto entry = std::make_shared(); - consensusValidated_.canonicalizeReplaceClient(index, entry); + consensus_validated_.canonicalizeReplaceClient(index, entry); if (entry->built && !entry->validated) { @@ -503,7 +504,7 @@ LedgerHistory::validatedLedger( bool LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) { - std::unique_lock const sl(ledgersByHash_.peekMutex()); + std::unique_lock const sl(ledgers_by_hash_.peekMutex()); auto it = ledgersByIndex_.find(ledgerIndex); if ((it != ledgersByIndex_.end()) && (it->second != ledgerHash)) @@ -517,11 +518,11 @@ LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) void LedgerHistory::clearLedgerCachePrior(LedgerIndex seq) { - for (LedgerHash const it : ledgersByHash_.getKeys()) + for (LedgerHash const it : ledgers_by_hash_.getKeys()) { auto const ledger = getLedgerByHash(it); if (!ledger || ledger->header().seq < seq) - ledgersByHash_.del(it, false); + ledgers_by_hash_.del(it, false); } } diff --git a/src/xrpld/app/ledger/LedgerHistory.h b/src/xrpld/app/ledger/LedgerHistory.h index 057de7b1bc..01c88b1517 100644 --- a/src/xrpld/app/ledger/LedgerHistory.h +++ b/src/xrpld/app/ledger/LedgerHistory.h @@ -30,7 +30,7 @@ public: float getCacheHitRate() { - return ledgersByHash_.getHitRate(); + return ledgers_by_hash_.getHitRate(); } /** Get a ledger given its sequence number */ @@ -53,8 +53,8 @@ public: void sweep() { - ledgersByHash_.sweep(); - consensusValidated_.sweep(); + ledgers_by_hash_.sweep(); + consensus_validated_.sweep(); } /** Report that we have locally built a particular ledger */ @@ -99,11 +99,11 @@ private: Application& app_; beast::insight::Collector::ptr collector_; - beast::insight::Counter mismatchCounter_; + beast::insight::Counter mismatch_counter_; using LedgersByHash = TaggedCache; - LedgersByHash ledgersByHash_; + LedgersByHash ledgers_by_hash_; // Maps ledger indexes to the corresponding hashes // For debug and logging purposes @@ -121,7 +121,7 @@ private: std::optional consensus; }; using ConsensusValidated = TaggedCache; - ConsensusValidated consensusValidated_; + ConsensusValidated consensus_validated_; // Maps ledger indexes to the corresponding hash. std::map ledgersByIndex_; // validated ledgers diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index 885ab6db25..0b3310ea79 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -347,20 +347,20 @@ private: bool const standalone_; // How many ledgers before the current ledger do we allow peers to request? - std::uint32_t const fetchDepth_; + std::uint32_t const fetch_depth_; // How much history do we want to keep - std::uint32_t const ledgerHistorySize_; + std::uint32_t const ledger_history_; - std::uint32_t const ledgerFetchSize_; + std::uint32_t const ledger_fetch_size_; - TaggedCache fetchPacks_; + TaggedCache fetch_packs_; - std::uint32_t fetchSeq_{0}; + std::uint32_t fetch_seq_{0}; // Try to keep a validator from switching from test to live network // without first wiping the database. - LedgerIndex const maxLedgerDifference_{1000000}; + LedgerIndex const max_ledger_difference_{1000000}; // Time that the previous upgrade warning was issued. TimeKeeper::time_point upgradeWarningPrevTime_; diff --git a/src/xrpld/app/ledger/LedgerReplayer.h b/src/xrpld/app/ledger/LedgerReplayer.h index e2d256f597..5d537bfd24 100644 --- a/src/xrpld/app/ledger/LedgerReplayer.h +++ b/src/xrpld/app/ledger/LedgerReplayer.h @@ -17,33 +17,33 @@ class LedgerReplayClient; namespace LedgerReplayParameters { // timeout value for LedgerReplayTask -constexpr auto kTaskTimeout = std::chrono::milliseconds{500}; +auto constexpr kTASK_TIMEOUT = std::chrono::milliseconds{500}; // for LedgerReplayTask to calculate max allowed timeouts -// = max( kTaskMaxTimeoutsMinimum, -// (# of ledger to replay) * kTaskMaxTimeoutsMultiplier) -constexpr std::uint32_t kTaskMaxTimeoutsMultiplier = 2; -constexpr std::uint32_t kTaskMaxTimeoutsMinimum = 10; +// = max( kTASK_MAX_TIMEOUTS_MINIMUM, +// (# of ledger to replay) * kTASK_MAX_TIMEOUTS_MULTIPLIER) +std::uint32_t constexpr kTASK_MAX_TIMEOUTS_MULTIPLIER = 2; +std::uint32_t constexpr kTASK_MAX_TIMEOUTS_MINIMUM = 10; // timeout value for subtasks: LedgerDeltaAcquire and SkipListAcquire -constexpr auto kSubTaskTimeout = std::chrono::milliseconds{250}; +auto constexpr kSUB_TASK_TIMEOUT = std::chrono::milliseconds{250}; // max of allowed subtask timeouts -constexpr std::uint32_t kSubTaskMaxTimeouts = 10; +std::uint32_t constexpr kSUB_TASK_MAX_TIMEOUTS = 10; // max number of peers that do not support the ledger replay feature // returned by the PeerSet before switch to fallback -constexpr auto kMaxNoFeaturePeerCount = 2; +auto constexpr kMAX_NO_FEATURE_PEER_COUNT = 2; // subtask timeout value after fallback -constexpr auto kSubTaskFallbackTimeout = std::chrono::milliseconds{1000}; +auto constexpr kSUB_TASK_FALLBACK_TIMEOUT = std::chrono::milliseconds{1000}; // for LedgerReplayer to limit the number of LedgerReplayTask -constexpr std::uint32_t kMaxTasks = 10; +std::uint32_t constexpr kMAX_TASKS = 10; // for LedgerReplayer to limit the number of ledgers to replay in one task -constexpr std::uint32_t kMaxTaskSize = 256; +std::uint32_t constexpr kMAX_TASK_SIZE = 256; // to limit the number of LedgerReplay related jobs in JobQueue -constexpr std::uint32_t kMaxQueuedTasks = 100; +std::uint32_t constexpr kMAX_QUEUED_TASKS = 100; } // namespace LedgerReplayParameters /** diff --git a/src/xrpld/app/ledger/LedgerToJson.h b/src/xrpld/app/ledger/LedgerToJson.h index 853d4468cd..981af07a0e 100644 --- a/src/xrpld/app/ledger/LedgerToJson.h +++ b/src/xrpld/app/ledger/LedgerToJson.h @@ -23,7 +23,9 @@ struct LedgerFill closeTime = context->ledgerMaster.getCloseTimeBySeq(ledger.seq()); } - enum class Options { + // Bitwise bitmask + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum Options { DumpTxrp = 1, DumpState = 2, Expand = 4, diff --git a/src/xrpld/app/ledger/LocalTxs.h b/src/xrpld/app/ledger/LocalTxs.h index 1575a18075..779dd4f02c 100644 --- a/src/xrpld/app/ledger/LocalTxs.h +++ b/src/xrpld/app/ledger/LocalTxs.h @@ -17,7 +17,7 @@ public: // The number of ledgers to hold a transaction is essentially // arbitrary. It should be sufficient to allow the transaction to // get into a fully-validated ledger. - static constexpr int kHoldLedgers = 5; + static constexpr int kHOLD_LEDGERS = 5; virtual ~LocalTxs() = default; diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 02e073bc9a..884b6b02db 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -33,8 +33,8 @@ class OpenLedger private: beast::Journal const j_; CachedSLEs& cache_; - std::mutex mutable modifyMutex_; - std::mutex mutable currentMutex_; + std::mutex mutable modify_mutex_; + std::mutex mutable current_mutex_; std::shared_ptr current_; public: diff --git a/src/xrpld/app/ledger/TransactionStateSF.cpp b/src/xrpld/app/ledger/TransactionStateSF.cpp index 52c761aa10..fc57c567eb 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.cpp +++ b/src/xrpld/app/ledger/TransactionStateSF.cpp @@ -24,13 +24,13 @@ TransactionStateSF::gotNode( XRPL_ASSERT( type != SHAMapNodeType::TnTransactionNm, "xrpl::TransactionStateSF::gotNode : valid input"); db_.store( - NodeObjectType::TransactionNode, std::move(nodeData), nodeHash.asUInt256(), ledgerSeq); + NodeObjectType::TransactionNode, std::move(nodeData), nodeHash.asUint256(), ledgerSeq); } std::optional TransactionStateSF::getNode(SHAMapHash const& nodeHash) const { - return fp_.getFetchPack(nodeHash.asUInt256()); + return fp_.getFetchPack(nodeHash.asUint256()); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index a77c1c9c50..5143769178 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -73,7 +73,7 @@ buildLedgerImpl( // Accept ledger XRPL_ASSERT( - built->header().seq < kXrpLedgerEarliestFees || built->read(keylet::fees()), + built->header().seq < kXRP_LEDGER_EARLIEST_FEES || built->read(keylet::fees()), "xrpl::buildLedgerImpl : valid ledger fees"); built->setAccepted(closeTime, closeResolution, closeTimeCorrect); @@ -225,7 +225,7 @@ buildLedger( return buildLedgerImpl( replayData.parent(), replayLedger->header().closeTime, - ((replayLedger->header().closeFlags & kSLcfNoConsensusTime) == 0), + ((replayLedger->header().closeFlags & kS_LCF_NO_CONSENSUS_TIME) == 0), replayLedger->header().closeTimeResolution, app, j, diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 9ba7bdf22e..b4082485d3 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -55,17 +55,39 @@ namespace xrpl { using namespace std::chrono_literals; -static constexpr auto kPeerCountStart = 5; // Number of peers to start with -static constexpr auto kPeerCountAdd = 3; // Number of peers to add on a timeout -static constexpr auto kLedgerTimeoutRetriesMax = 6; // how many timeouts before we give up -static constexpr auto kLedgerBecomeAggressiveThreshold = - 4; // how many timeouts before we get aggressive -static constexpr auto kMissingNodesFind = 256; // Number of nodes to find initially -static constexpr auto kReqNodesReply = 128; // Number of nodes to request for a reply -static constexpr auto kReqNodes = 12; // Number of nodes to request blindly +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + // Number of peers to start with + PeerCountStart = 5 + + // Number of peers to add on a timeout + , + PeerCountAdd = 3 + + // how many timeouts before we give up + , + LedgerTimeoutRetriesMax = 6 + + // how many timeouts before we get aggressive + , + LedgerBecomeAggressiveThreshold = 4 + + // Number of nodes to find initially + , + MissingNodesFind = 256 + + // Number of nodes to request for a reply + , + ReqNodesReply = 128 + + // Number of nodes to request blindly + , + ReqNodes = 12 +}; // millisecond for each ledger timeout -constexpr auto kLedgerAcquireTimeout = 3000ms; +auto constexpr kLEDGER_ACQUIRE_TIMEOUT = 3000ms; InboundLedger::InboundLedger( Application& app, @@ -77,7 +99,7 @@ InboundLedger::InboundLedger( : TimeoutCounter( app, hash, - kLedgerAcquireTimeout, + kLEDGER_ACQUIRE_TIMEOUT, {.jobType = JtLedgerData, .jobName = "InboundLedger", .jobLimit = 5}, app.getJournal("InboundLedger")) , clock_(clock) @@ -109,7 +131,7 @@ InboundLedger::init(ScopedLockType& collectionLock) JLOG(journal_.debug()) << "Acquiring ledger we already have in " << " local store. " << hash_; XRPL_ASSERT( - ledger_->header().seq < kXrpLedgerEarliestFees || ledger_->read(keylet::fees()), + ledger_->header().seq < kXRP_LEDGER_EARLIEST_FEES || ledger_->read(keylet::fees()), "xrpl::InboundLedger::init : valid ledger fees"); ledger_->setImmutable(); @@ -331,7 +353,7 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) JLOG(journal_.debug()) << "Had everything locally"; complete_ = true; XRPL_ASSERT( - ledger_->header().seq < kXrpLedgerEarliestFees || ledger_->read(keylet::fees()), + ledger_->header().seq < kXRP_LEDGER_EARLIEST_FEES || ledger_->read(keylet::fees()), "xrpl::InboundLedger::tryDB : valid ledger fees"); ledger_->setImmutable(); } @@ -350,7 +372,7 @@ InboundLedger::onTimer(bool wasProgress, ScopedLockType&) return; } - if (timeouts_ > kLedgerTimeoutRetriesMax) + if (timeouts_ > LedgerTimeoutRetriesMax) { if (seq_ != 0) { @@ -391,7 +413,7 @@ void InboundLedger::addPeers() { peerSet_->addPeers( - (getPeerCount() == 0) ? kPeerCountStart : kPeerCountAdd, + (getPeerCount() == 0) ? PeerCountStart : PeerCountAdd, [this](auto peer) { return peer->hasLedger(hash_, seq_); }, [this](auto peer) { // For historical nodes, do not trigger too soon @@ -427,7 +449,7 @@ InboundLedger::done() if (complete_ && !failed_ && ledger_) { XRPL_ASSERT( - ledger_->header().seq < kXrpLedgerEarliestFees || ledger_->read(keylet::fees()), + ledger_->header().seq < kXRP_LEDGER_EARLIEST_FEES || ledger_->read(keylet::fees()), "xrpl::InboundLedger::done : valid ledger fees"); ledger_->setImmutable(); switch (reason_) @@ -505,7 +527,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_ && byHash_ && (timeouts_ > kLedgerBecomeAggressiveThreshold)) + if (!progress_ && !failed_ && byHash_ && (timeouts_ > LedgerBecomeAggressiveThreshold)) { auto need = getNeededHashes(); @@ -615,7 +637,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // Release the lock while we process the large state map sl.unlock(); - auto nodes = ledger_->stateMap().getMissingNodes(kMissingNodesFind, &filter); + auto nodes = ledger_->stateMap().getMissingNodes(MissingNodesFind, &filter); sl.lock(); // Make sure nothing happened while we released the lock @@ -684,7 +706,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) { TransactionStateSF filter(ledger_->txMap().family().db(), app_.getLedgerMaster()); - auto nodes = ledger_->txMap().getMissingNodes(kMissingNodesFind, &filter); + auto nodes = ledger_->txMap().getMissingNodes(MissingNodesFind, &filter); if (nodes.empty()) { @@ -761,7 +783,7 @@ InboundLedger::filterNodes( nodes.erase(dup.begin(), dup.end()); } - std::size_t const limit = (reason == TriggerReason::Reply) ? kReqNodesReply : kReqNodes; + std::size_t const limit = (reason == TriggerReason::Reply) ? ReqNodesReply : ReqNodes; if (nodes.size() > limit) nodes.resize(limit); @@ -1033,7 +1055,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p if (packet.nodes().empty()) { JLOG(journal_.warn()) << peer->id() << ": empty header data"; - peer->charge(Resource::kFeeMalformedRequest, "ledger_data empty header"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "ledger_data empty header"); return -1; } @@ -1048,7 +1070,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p if (!takeHeader(packet.nodes(0).nodedata())) { JLOG(journal_.warn()) << "Got invalid header data"; - peer->charge(Resource::kFeeMalformedRequest, "ledger_data invalid header"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "ledger_data invalid header"); return -1; } @@ -1071,7 +1093,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p { JLOG(journal_.warn()) << "Included AS/TX root invalid: " << ex.what(); using namespace std::string_literals; - peer->charge(Resource::kFeeInvalidData, "ledger_data "s + ex.what()); + peer->charge(Resource::kFEE_INVALID_DATA, "ledger_data "s + ex.what()); return -1; } @@ -1087,7 +1109,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p if (packet.nodes().empty()) { JLOG(journal_.info()) << peer->id() << ": response with no nodes"; - peer->charge(Resource::kFeeMalformedRequest, "ledger_data no nodes"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "ledger_data no nodes"); return -1; } @@ -1099,7 +1121,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p if (!node.has_nodeid() || !node.has_nodedata()) { JLOG(journal_.warn()) << "Got bad node"; - peer->charge(Resource::kFeeMalformedRequest, "ledger_data bad node"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "ledger_data bad node"); return -1; } } @@ -1201,7 +1223,7 @@ void InboundLedger::runData() { // Maximum number of peers to request data from - static constexpr std::size_t kMaxUsefulPeers = 6; + constexpr std::size_t kMAX_USEFUL_PEERS = 6; decltype(receivedData_) data; @@ -1239,7 +1261,7 @@ InboundLedger::runData() // Select a random sample of the peers that gives us the most nodes that are // useful dataCounts.prune(); - dataCounts.sampleN(kMaxUsefulPeers, [&](std::shared_ptr const& peer) { + dataCounts.sampleN(kMAX_USEFUL_PEERS, [&](std::shared_ptr const& peer) { trigger(peer, TriggerReason::Reply); }); } @@ -1247,7 +1269,7 @@ InboundLedger::runData() json::Value InboundLedger::getJson(int) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ScopedLockType const sl(mtx_); @@ -1274,7 +1296,7 @@ InboundLedger::getJson(int) if (haveHeader_ && !haveState_) { - json::Value hv(json::ValueType::Array); + json::Value hv(json::ArrayValue); for (auto const& h : neededStateHashes(16, nullptr)) { hv.append(to_string(h)); @@ -1284,7 +1306,7 @@ InboundLedger::getJson(int) if (haveHeader_ && !haveTransactions_) { - json::Value hv(json::ValueType::Array); + json::Value hv(json::ArrayValue); for (auto const& h : neededTxHashes(16, nullptr)) { hv.append(to_string(h)); diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index 95e3e46f73..a175528978 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -53,7 +53,7 @@ private: public: // How long before we try again to acquire the same ledger - static constexpr std::chrono::minutes kReacquireInterval{5}; + static constexpr std::chrono::minutes const kREACQUIRE_INTERVAL{5}; InboundLedgersImp( Application& app, @@ -232,7 +232,7 @@ public: { ScopedLockType const sl(lock_); - beast::expire(recentFailures_, kReacquireInterval); + beast::expire(recentFailures_, kREACQUIRE_INTERVAL); return recentFailures_.find(h) != recentFailures_.end(); } @@ -264,7 +264,7 @@ public: newNode->serializeWithPrefix(s); app_.getLedgerMaster().addFetchPack( - newNode->getHash().asUInt256(), std::make_shared(s.begin(), s.end())); + newNode->getHash().asUint256(), std::make_shared(s.begin(), s.end())); } } catch (std::exception const&) // NOLINT(bugprone-empty-catch) @@ -300,7 +300,7 @@ public: json::Value getInfo() override { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); std::vector>> acqs; @@ -405,7 +405,7 @@ public: } } - beast::expire(recentFailures_, kReacquireInterval); + beast::expire(recentFailures_, kREACQUIRE_INTERVAL); } JLOG(j_.debug()) diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index d744075869..598a8b5c4c 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -28,8 +28,14 @@ namespace xrpl { // Need to be named before converting -static constexpr auto kStartPeers = 2; // ideal number of peers to start with -static constexpr auto kSetKeepRounds = 3; // how many rounds to keep a set +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + // Ideal number of peers to start with + StartPeers = 2, + + // How many rounds to keep a set + SetKeepRounds = 3, +}; class InboundTransactionSet { @@ -114,7 +120,7 @@ public: obj.seq = seq_; } - ta->init(kStartPeers); + ta->init(StartPeers); return {}; } @@ -136,7 +142,7 @@ public: if (ta == nullptr) { - peer->charge(Resource::kFeeUselessData, "ledger_data"); + peer->charge(Resource::kFEE_USELESS_DATA, "ledger_data"); return; } @@ -147,7 +153,7 @@ public: { if (!node.has_nodeid() || !node.has_nodedata()) { - peer->charge(Resource::kFeeMalformedRequest, "ledger_data"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "ledger_data"); return; } @@ -155,7 +161,7 @@ public: if (!id) { - peer->charge(Resource::kFeeInvalidData, "ledger_data"); + peer->charge(Resource::kFEE_INVALID_DATA, "ledger_data"); return; } @@ -163,7 +169,7 @@ public: } if (!ta->takeNodes(data, peer).isUseful()) - peer->charge(Resource::kFeeUselessData, "ledger_data not useful"); + peer->charge(Resource::kFEE_USELESS_DATA, "ledger_data not useful"); } void @@ -208,8 +214,8 @@ public: auto it = map_.begin(); - std::uint32_t const minSeq = (seq < kSetKeepRounds) ? 0 : (seq - kSetKeepRounds); - std::uint32_t const maxSeq = seq + kSetKeepRounds; + std::uint32_t const minSeq = (seq < SetKeepRounds) ? 0 : (seq - SetKeepRounds); + std::uint32_t const maxSeq = seq + SetKeepRounds; while (it != map_.end()) { diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 9f2db9d2f2..86201ca627 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -257,7 +257,7 @@ private: app_.getInboundLedgers().acquire( ledger->header().hash, ledger->header().seq, InboundLedger::Reason::GENERIC); } - return hash ? *hash : beast::kZero; // kludge + return hash ? *hash : beast::kZERO; // kludge } /** Process a single ledger @@ -286,7 +286,7 @@ private: } Rules const rules{app_.config().features}; - Fees const fees = app_.config().fees.toFees(); + Fees const fees = app_.config().FEES.toFees(); auto const dbLedger = loadByIndex(ledgerIndex, rules, fees, app_); if (!dbLedger || (dbLedger->header().hash != ledgerHash) || (dbLedger->header().parentHash != nodeLedger->header().parentHash)) diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index 4c79068bca..9ebe890ae1 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -41,10 +41,10 @@ LedgerDeltaAcquire::LedgerDeltaAcquire( : TimeoutCounter( app, ledgerHash, - LedgerReplayParameters::kSubTaskTimeout, + LedgerReplayParameters::kSUB_TASK_TIMEOUT, {.jobType = JtReplayTask, .jobName = "LedReplDelta", - .jobLimit = LedgerReplayParameters::kMaxQueuedTasks}, + .jobLimit = LedgerReplayParameters::kMAX_QUEUED_TASKS}, app.getJournal("LedgerReplayDelta")) , inboundLedgers_(inboundLedgers) , ledgerSeq_(ledgerSeq) @@ -99,10 +99,10 @@ LedgerDeltaAcquire::trigger(std::size_t limit, ScopedLockType& sl) } else { - if (++noFeaturePeerCount_ >= LedgerReplayParameters::kMaxNoFeaturePeerCount) + if (++noFeaturePeerCount_ >= LedgerReplayParameters::kMAX_NO_FEATURE_PEER_COUNT) { JLOG(journal_.debug()) << "Fall back for " << hash_; - timerInterval_ = LedgerReplayParameters::kSubTaskFallbackTimeout; + timerInterval_ = LedgerReplayParameters::kSUB_TASK_FALLBACK_TIMEOUT; fallBack_ = true; } } @@ -117,7 +117,7 @@ void LedgerDeltaAcquire::onTimer(bool progress, ScopedLockType& sl) { JLOG(journal_.trace()) << "timeouts_=" << timeouts_ << " for " << hash_; - if (timeouts_ > LedgerReplayParameters::kSubTaskMaxTimeouts) + if (timeouts_ > LedgerReplayParameters::kSUB_TASK_MAX_TIMEOUTS) { failed_ = true; JLOG(journal_.debug()) << "too many timeouts " << hash_; diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 9baad0ec90..34ded1d14f 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -81,13 +81,13 @@ namespace xrpl { // Don't catch up more than 100 ledgers (cannot exceed 256) -static constexpr int kMaxLedgerGap{100}; +static constexpr int kMAX_LEDGER_GAP{100}; // Don't acquire history if ledger is too old -static constexpr std::chrono::minutes kMaxLedgerAgeAcquire{1}; +static constexpr std::chrono::minutes kMAX_LEDGER_AGE_ACQUIRE{1}; // Don't acquire history if write load is too high -static constexpr int kMaxWriteLoadAcquire{8192}; +static constexpr int kMAX_WRITE_LOAD_ACQUIRE{8192}; // Helper function for LedgerMaster::doAdvance() // Return true if candidateLedger should be fetched from the network. @@ -127,10 +127,10 @@ LedgerMaster::LedgerMaster( , journal_(journal) , ledgerHistory_(collector, app) , standalone_(app_.config().standalone()) - , fetchDepth_(app_.getSHAMapStore().clampFetchDepth(app_.config().fetchDepth)) - , ledgerHistorySize_(app_.config().ledgerHistory) - , ledgerFetchSize_(app_.config().getValueFor(SizedItem::LedgerFetch)) - , fetchPacks_( + , 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}, @@ -189,12 +189,12 @@ LedgerMaster::getPublishedLedgerAge() std::chrono::seconds ret = app_.getTimeKeeper().closeTime().time_since_epoch(); ret -= pubClose; ret = (ret > 0s) ? ret : 0s; - static std::chrono::seconds kLastRet = -1s; + static std::chrono::seconds kLAST_RET = -1s; - if (ret != kLastRet) + if (ret != kLAST_RET) { JLOG(journal_.trace()) << "Published ledger age is " << ret.count(); - kLastRet = ret; + kLAST_RET = ret; } return ret; } @@ -214,12 +214,12 @@ LedgerMaster::getValidatedLedgerAge() std::chrono::seconds ret = app_.getTimeKeeper().closeTime().time_since_epoch(); ret -= valClose; ret = (ret > 0s) ? ret : 0s; - static std::chrono::seconds kLastRet = -1s; + static std::chrono::seconds kLAST_RET = -1s; - if (ret != kLastRet) + if (ret != kLAST_RET) { JLOG(journal_.trace()) << "Validated ledger age is " << ret.count(); - kLastRet = ret; + kLAST_RET = ret; } return ret; } @@ -286,9 +286,9 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) validLedgerSign_ = signTime.time_since_epoch().count(); XRPL_ASSERT( validLedgerSeq_ || !app_.getMaxDisallowedLedger() || - l->header().seq + maxLedgerDifference_ > app_.getMaxDisallowedLedger(), + l->header().seq + max_ledger_difference_ > app_.getMaxDisallowedLedger(), "xrpl::LedgerMaster::setValidLedger : valid ledger sequence"); - (void)maxLedgerDifference_; + (void)max_ledger_difference_; validLedgerSeq_ = l->header().seq; app_.getOPs().updateLocalTx(*l); @@ -629,9 +629,9 @@ LedgerMaster::getEarliestFetch() // unless that creates a larger range than allowed std::uint32_t e = getClosedLedger()->header().seq; - if (e > fetchDepth_) + if (e > fetch_depth_) { - e -= fetchDepth_; + e -= fetch_depth_; } else { @@ -1047,12 +1047,12 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) // and (3) the calculation won't cause divide-by-zero. if (higherVersionCount > 0 && xrpldCount > 0) { - static constexpr std::size_t kReportingPercent = 90; - static constexpr std::size_t kCutoffPercent = 60; + constexpr std::size_t kREPORTING_PERCENT = 90; + constexpr std::size_t kCUTOFF_PERCENT = 60; auto const unlSize{app_.getValidators().getQuorumKeys().second.size()}; needPrint = unlSize > 0 && - calculatePercent(vals.size(), unlSize) >= kReportingPercent && - calculatePercent(higherVersionCount, xrpldCount) >= kCutoffPercent; + calculatePercent(vals.size(), unlSize) >= kREPORTING_PERCENT && + calculatePercent(higherVersionCount, xrpldCount) >= kCUTOFF_PERCENT; } } // To throttle the warning messages, instead of printing a warning @@ -1219,7 +1219,7 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl return {validLedger_.get()}; } - if (validLedgerSeq_ > (pubLedgerSeq_ + kMaxLedgerGap)) + if (validLedgerSeq_ > (pubLedgerSeq_ + kMAX_LEDGER_GAP)) { JLOG(journal_.warn()) << "Gap in validated ledger stream " << pubLedgerSeq_ << " - " << validLedgerSeq_ - 1; @@ -1257,7 +1257,7 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl // VFALCO TODO Restructure this code so that zero is not // used. if (!hash) - hash = beast::kZero; // kludge + hash = beast::kZERO; // kludge if (seq == valSeq) { // We need to publish the ledger we just fully validated @@ -1277,10 +1277,10 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl ledger = ledgerHistory_.getLedgerByHash(*hash); } - if (!app_.config().ledgerReplay) + if (!app_.config().LEDGER_REPLAY) { // Can we try to acquire the ledger we need? - if (!ledger && (++acqCount < ledgerFetchSize_)) + if (!ledger && (++acqCount < ledger_fetch_size_)) { ledger = app_.getInboundLedgers().acquire( *hash, seq, InboundLedger::Reason::GENERIC); @@ -1304,7 +1304,7 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl << ex.what(); } - if (app_.config().ledgerReplay) + if (app_.config().LEDGER_REPLAY) { /* Narrow down the gap of ledgers, and try to replay them. * When replaying a ledger gap, if the local node has @@ -1737,7 +1737,7 @@ void LedgerMaster::sweep() { ledgerHistory_.sweep(); - fetchPacks_.sweep(); + fetch_packs_.sweep(); } float @@ -1789,11 +1789,11 @@ LedgerMaster::fetchForHistory( if (!app_.getInboundLedgers().isFailure(*hash)) { ledger = app_.getInboundLedgers().acquire(*hash, missing, reason); - if (!ledger && missing != fetchSeq_ && + if (!ledger && missing != fetch_seq_ && missing > app_.getNodeStore().earliestLedgerSeq()) { JLOG(journal_.trace()) << "fetchForHistory want fetch pack " << missing; - fetchSeq_ = missing; + fetch_seq_ = missing; getFetchPack(missing, reason); } else @@ -1833,7 +1833,8 @@ LedgerMaster::fetchForHistory( // Do not fetch ledger sequences lower // than the earliest ledger sequence fetchSz = app_.getNodeStore().earliestLedgerSeq(); - fetchSz = missing >= fetchSz ? std::min(ledgerFetchSize_, (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) @@ -1883,8 +1884,8 @@ LedgerMaster::doAdvance(std::unique_lock& sl) if (!standalone_ && !app_.getFeeTrack().isLoadedLocal() && (app_.getJobQueue().getJobCount(JtPuboldledger) < 10) && (validLedgerSeq_ == pubLedgerSeq_) && - (getValidatedLedgerAge() < kMaxLedgerAgeAcquire) && - (app_.getNodeStore().getWriteLoad() < kMaxWriteLoadAcquire)) + (getValidatedLedgerAge() < kMAX_LEDGER_AGE_ACQUIRE) && + (app_.getNodeStore().getWriteLoad() < kMAX_WRITE_LOAD_ACQUIRE)) { // We are in sync, so can acquire InboundLedger::Reason const reason = InboundLedger::Reason::HISTORY; @@ -1902,7 +1903,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) if ((fillInProgress_ == 0 || *missing > fillInProgress_) && shouldAcquire( validLedgerSeq_, - ledgerHistorySize_, + ledger_history_, app_.getSHAMapStore().minimumOnline(), *missing, journal_)) @@ -1961,16 +1962,16 @@ LedgerMaster::doAdvance(std::unique_lock& sl) void LedgerMaster::addFetchPack(uint256 const& hash, std::shared_ptr data) { - fetchPacks_.canonicalizeReplaceClient(hash, data); + fetch_packs_.canonicalizeReplaceClient(hash, data); } std::optional LedgerMaster::getFetchPack(uint256 const& hash) { Blob data; - if (fetchPacks_.retrieve(hash, data)) + if (fetch_packs_.retrieve(hash, data)) { - fetchPacks_.del(hash, false); + fetch_packs_.del(hash, false); if (hash == sha512Half(makeSlice(data))) return data; } @@ -2034,7 +2035,7 @@ populateFetchPack( s.erase(); n.serializeWithPrefix(s); - auto const& hash = n.getHash().asUInt256(); + auto const& hash = n.getHash().asUint256(); protocol::TMIndexedObject* obj = into->add_objects(); obj->set_ledgerseq(seq); @@ -2075,21 +2076,21 @@ LedgerMaster::makeFetchPack( if (!have) { JLOG(journal_.info()) << "Peer requests fetch pack for ledger we don't have: " << have; - peer->charge(Resource::kFeeRequestNoReply, "get_object ledger"); + peer->charge(Resource::kFEE_REQUEST_NO_REPLY, "get_object ledger"); return; } if (have->open()) { JLOG(journal_.warn()) << "Peer requests fetch pack from open ledger: " << have; - peer->charge(Resource::kFeeMalformedRequest, "get_object ledger open"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "get_object ledger open"); return; } if (have->header().seq < getEarliestFetch()) { JLOG(journal_.debug()) << "Peer requests fetch pack that is too early"; - peer->charge(Resource::kFeeMalformedRequest, "get_object ledger early"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "get_object ledger early"); return; } @@ -2099,7 +2100,7 @@ LedgerMaster::makeFetchPack( { JLOG(journal_.info()) << "Peer requests fetch pack for ledger whose predecessor we " << "don't have: " << have; - peer->charge(Resource::kFeeRequestNoReply, "get_object ledger no parent"); + peer->charge(Resource::kFEE_REQUEST_NO_REPLY, "get_object ledger no parent"); return; } @@ -2169,7 +2170,7 @@ LedgerMaster::makeFetchPack( std::size_t LedgerMaster::getFetchPackCacheSize() const { - return fetchPacks_.getCacheSize(); + return fetch_packs_.getCacheSize(); } // Returns the minimum ledger sequence in SQL database, if any. diff --git a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp index 579f66063c..70e2684e1c 100644 --- a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp +++ b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp @@ -122,7 +122,7 @@ finishLoadByIndexOrHash(std::shared_ptr const& ledger, beast::Journal j) return; XRPL_ASSERT( - ledger->header().seq < kXrpLedgerEarliestFees || ledger->read(keylet::fees()), + ledger->header().seq < kXRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "xrpl::finishLoadByIndexOrHash : valid ledger fees"); ledger->setImmutable(); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index 07738d99f4..3df1e99cae 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -56,8 +56,8 @@ LedgerReplayMsgHandler::processProofPathRequest( reply.set_ledgerhash(packet.ledgerhash()); reply.set_type(packet.type()); - uint256 const key = uint256::fromRaw(packet.key()); - uint256 const ledgerHash = uint256::fromRaw(packet.ledgerhash()); + uint256 const key(packet.key()); + uint256 const ledgerHash(packet.ledgerhash()); auto ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash); if (!ledger) { @@ -107,8 +107,7 @@ LedgerReplayMsgHandler::processProofPathResponse( { protocol::TMProofPathResponse const& reply = *msg; if (reply.has_error() || !reply.has_key() || !reply.has_ledgerhash() || !reply.has_type() || - !reply.has_ledgerheader() || reply.path_size() == 0 || - reply.ledgerhash().size() != uint256::size() || reply.key().size() != uint256::size()) + !reply.has_ledgerheader() || reply.path_size() == 0) { JLOG(journal_.debug()) << "Bad message: Error reply"; return false; @@ -122,7 +121,7 @@ LedgerReplayMsgHandler::processProofPathResponse( // deserialize the header auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); - uint256 const replyHash = uint256::fromRaw(reply.ledgerhash()); + uint256 const replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { JLOG(journal_.debug()) << "Bad message: Hash mismatch"; @@ -130,7 +129,7 @@ LedgerReplayMsgHandler::processProofPathResponse( } info.hash = replyHash; - uint256 const key = uint256::fromRaw(reply.key()); + uint256 const key(reply.key()); if (key != keylet::skip().key) { JLOG(journal_.debug()) << "Bad message: we only support the short skip list for now. " @@ -186,7 +185,7 @@ LedgerReplayMsgHandler::processReplayDeltaRequest( } reply.set_ledgerhash(packet.ledgerhash()); - uint256 const ledgerHash = uint256::fromRaw(packet.ledgerhash()); + uint256 const ledgerHash{packet.ledgerhash()}; auto ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash); if (!ledger || !ledger->isImmutable()) { @@ -206,7 +205,7 @@ LedgerReplayMsgHandler::processReplayDeltaRequest( }); JLOG(journal_.debug()) << "getReplayDelta for ledger " << ledgerHash << " txMap hash " - << txMap.getHash().asUInt256(); + << txMap.getHash().asUint256(); return reply; } @@ -215,15 +214,14 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( std::shared_ptr const& msg) { protocol::TMReplayDeltaResponse const& reply = *msg; - if (reply.has_error() || !reply.has_ledgerheader() || !reply.has_ledgerhash() || - reply.ledgerhash().size() != uint256::size()) + if (reply.has_error() || !reply.has_ledgerheader()) { JLOG(journal_.debug()) << "Bad message: Error reply"; return false; } auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); - uint256 const replyHash = uint256::fromRaw(reply.ledgerhash()); + uint256 const replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { JLOG(journal_.debug()) << "Bad message: Hash mismatch"; @@ -273,7 +271,7 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( return false; } - if (txMap.getHash().asUInt256() != info.txHash) + if (txMap.getHash().asUint256() != info.txHash) { JLOG(journal_.debug()) << "Bad message: Transactions verify failed"; return false; diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index f9f1aa3188..dcc09faa13 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -86,18 +86,18 @@ LedgerReplayTask::LedgerReplayTask( : TimeoutCounter( app, parameter.finishHash, - LedgerReplayParameters::kTaskTimeout, + LedgerReplayParameters::kTASK_TIMEOUT, {.jobType = JtReplayTask, .jobName = "LedReplTask", - .jobLimit = LedgerReplayParameters::kMaxQueuedTasks}, + .jobLimit = LedgerReplayParameters::kMAX_QUEUED_TASKS}, app.getJournal("LedgerReplayTask")) , inboundLedgers_(inboundLedgers) , replayer_(replayer) , parameter_(parameter) , maxTimeouts_( std::max( - LedgerReplayParameters::kTaskMaxTimeoutsMinimum, - parameter.totalLedgers * LedgerReplayParameters::kTaskMaxTimeoutsMultiplier)) + LedgerReplayParameters::kTASK_MAX_TIMEOUTS_MINIMUM, + parameter.totalLedgers * LedgerReplayParameters::kTASK_MAX_TIMEOUTS_MULTIPLIER)) , skipListAcquirer_(skipListAcquirer) { JLOG(journal_.trace()) << "Create " << hash_; diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 3bb5ca9434..132bf9ccaa 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -51,7 +51,7 @@ LedgerReplayer::replay( { XRPL_ASSERT( finishLedgerHash.isNonZero() && totalNumLedgers > 0 && - totalNumLedgers <= LedgerReplayParameters::kMaxTaskSize, + totalNumLedgers <= LedgerReplayParameters::kMAX_TASK_SIZE, "xrpl::LedgerReplayer::replay : valid inputs"); // NOLINTNEXTLINE(misc-const-correctness) @@ -64,7 +64,7 @@ LedgerReplayer::replay( std::scoped_lock const lock(mtx_); if (app_.isStopping()) return; - if (tasks_.size() >= LedgerReplayParameters::kMaxTasks) + if (tasks_.size() >= LedgerReplayParameters::kMAX_TASKS) { JLOG(j_.info()) << "Too many replay tasks, dropping new task " << parameter.finishHash; return; diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index 7a581e2389..5248c3621a 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -38,19 +38,19 @@ namespace { bool isFull(LedgerFill const& fill) { - return (fill.options & static_cast(LedgerFill::Options::Full)) != 0; + return (fill.options & LedgerFill::Full) != 0; } bool isExpanded(LedgerFill const& fill) { - return isFull(fill) || ((fill.options & static_cast(LedgerFill::Options::Expand)) != 0); + return isFull(fill) || ((fill.options & LedgerFill::Expand) != 0); } bool isBinary(LedgerFill const& fill) { - return (fill.options & static_cast(LedgerFill::Options::Binary)) != 0; + return (fill.options & LedgerFill::Binary) != 0; } void @@ -119,7 +119,7 @@ fillJsonTx( if (!bExpanded) return to_string(txn->getTransactionID()); - json::Value txJson{json::ValueType::Object}; + json::Value txJson{json::ObjectValue}; auto const txnType = txn->getTxnType(); if (bBinary) { @@ -133,13 +133,13 @@ fillJsonTx( } else if (fill.context->apiVersion > 1) { - copyFrom(txJson[jss::tx_json], txn->getJson(JsonOptions::Values::DisableApiPriorV2, false)); + copyFrom(txJson[jss::tx_json], txn->getJson(JsonOptions::KDisableApiPriorV2, false)); txJson[jss::hash] = to_string(txn->getTransactionID()); RPC::insertDeliverMax(txJson[jss::tx_json], txnType, fill.context->apiVersion); if (stMeta) { - txJson[jss::meta] = stMeta->getJson(JsonOptions::Values::None); + txJson[jss::meta] = stMeta->getJson(JsonOptions::KNone); // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) @@ -171,11 +171,11 @@ fillJsonTx( } else { - copyFrom(txJson, txn->getJson(JsonOptions::Values::None)); + copyFrom(txJson, txn->getJson(JsonOptions::KNone)); RPC::insertDeliverMax(txJson, txnType, fill.context->apiVersion); if (stMeta) { - txJson[jss::metaData] = stMeta->getJson(JsonOptions::Values::None); + txJson[jss::metaData] = stMeta->getJson(JsonOptions::KNone); // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) @@ -193,8 +193,7 @@ fillJsonTx( } } - if (((fill.options & static_cast(LedgerFill::Options::OwnerFunds)) != 0) && - txn->getTxnType() == ttOFFER_CREATE) + if (((fill.options & LedgerFill::OwnerFunds) != 0) && txn->getTxnType() == ttOFFER_CREATE) { auto const account = txn->getAccountID(sfAccount); auto const amount = txn->getFieldAmount(sfTakerGets); @@ -219,7 +218,7 @@ fillJsonTx( void fillJsonTx(json::Value& json, LedgerFill const& fill) { - auto& txns = json[jss::transactions] = json::ValueType::Array; + auto& txns = json[jss::transactions] = json::ArrayValue; auto bBinary = isBinary(fill); auto bExpanded = isExpanded(fill); @@ -248,7 +247,7 @@ void fillJsonState(json::Value& json, LedgerFill const& fill) { auto& ledger = fill.ledger; - auto& array = json[jss::accountState] = json::ValueType::Array; + auto& array = json[jss::accountState] = json::ArrayValue; auto expanded = isExpanded(fill); auto binary = isBinary(fill); @@ -256,13 +255,13 @@ fillJsonState(json::Value& json, LedgerFill const& fill) { if (binary) { - auto& obj = array.append(json::ValueType::Object); + auto& obj = array.append(json::ObjectValue); obj[jss::hash] = to_string(sle->key()); obj[jss::tx_blob] = serializeHex(*sle); } else if (expanded) { - array.append(sle->getJson(JsonOptions::Values::None)); + array.append(sle->getJson(JsonOptions::KNone)); } else { @@ -274,13 +273,13 @@ fillJsonState(json::Value& json, LedgerFill const& fill) void fillJsonQueue(json::Value& json, LedgerFill const& fill) { - auto& queueData = json[jss::queue_data] = json::ValueType::Array; + auto& queueData = json[jss::queue_data] = json::ArrayValue; auto bBinary = isBinary(fill); auto bExpanded = isExpanded(fill); for (auto const& tx : fill.txQueue) { - auto& txJson = queueData.append(json::ValueType::Object); + auto& txJson = queueData.append(json::ObjectValue); txJson[jss::fee_level] = to_string(tx.feeLevel); if (tx.lastValid) txJson[jss::LastLedgerSequence] = *tx.lastValid; @@ -297,24 +296,13 @@ fillJsonQueue(json::Value& json, LedgerFill const& fill) txJson["last_result"] = transToken(*tx.lastResult); auto&& temp = fillJsonTx(fill, bBinary, bExpanded, tx.txn, nullptr); - if (temp.isObject()) + if (fill.context->apiVersion > 1) { - if (fill.context->apiVersion > 1) - { - copyFrom(txJson, temp); - } - else - { - copyFrom(txJson[jss::tx], temp); - } - } - else if (fill.context->apiVersion > 1) - { - txJson[jss::hash] = temp; + copyFrom(txJson, temp); } else { - txJson[jss::tx] = temp; + copyFrom(txJson[jss::tx], temp); } } } @@ -337,13 +325,13 @@ fillJson(json::Value& json, LedgerFill const& fill) fill.ledger.header(), bFull, ((fill.context != nullptr) ? fill.context->apiVersion - : RPC::kApiMaximumSupportedVersion)); + : RPC::kAPI_MAXIMUM_SUPPORTED_VERSION)); } - if (bFull || ((fill.options & static_cast(LedgerFill::Options::DumpTxrp)) != 0)) + if (bFull || ((fill.options & LedgerFill::DumpTxrp) != 0)) fillJsonTx(json, fill); - if (bFull || ((fill.options & static_cast(LedgerFill::Options::DumpState)) != 0)) + if (bFull || ((fill.options & LedgerFill::DumpState) != 0)) fillJsonState(json, fill); } @@ -352,14 +340,11 @@ fillJson(json::Value& json, LedgerFill const& fill) void addJson(json::Value& json, LedgerFill const& fill) { - auto& object = json[jss::ledger] = json::ValueType::Object; + auto& object = json[jss::ledger] = json::ObjectValue; fillJson(object, fill); - if (((fill.options & static_cast(LedgerFill::Options::DumpQueue)) != 0) && - !fill.txQueue.empty()) - { + if (((fill.options & LedgerFill::DumpQueue) != 0) && !fill.txQueue.empty()) fillJsonQueue(json, fill); - } } json::Value diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index d843acfe44..0f355367e5 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -48,7 +48,7 @@ class LocalTx public: LocalTx(LedgerIndex index, std::shared_ptr const& txn) : txn_(txn) - , expire_(index + LocalTxs::kHoldLedgers) + , expire_(index + LocalTxs::kHOLD_LEDGERS) , id_(txn->getTransactionID()) , account_(txn->getAccountID(sfAccount)) , seqProxy_(txn->getSeqProxy()) @@ -163,7 +163,7 @@ public: // Ticket should have been created by now. Remove if ticket // does not exist. - return !view.exists(keylet::kTicket(acctID, seqProx)); + return !view.exists(keylet::kTICKET(acctID, seqProx)); }); } diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 3bee4b9d13..5774dd8863 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -48,26 +48,26 @@ OpenLedger::OpenLedger( bool OpenLedger::empty() const { - std::scoped_lock const lock(modifyMutex_); + std::scoped_lock const lock(modify_mutex_); return current_->txCount() == 0; } std::shared_ptr OpenLedger::current() const { - std::scoped_lock const lock(currentMutex_); + std::scoped_lock const lock(current_mutex_); return current_; } bool OpenLedger::modify(modify_type const& f) { - std::scoped_lock const lock1(modifyMutex_); + std::scoped_lock const lock1(modify_mutex_); auto next = std::make_shared(*current_); auto const changed = f(*next, j_); if (changed) { - std::scoped_lock const lock2(currentMutex_); + std::scoped_lock const lock2(current_mutex_); current_ = std::move(next); } return changed; @@ -96,7 +96,7 @@ OpenLedger::accept( // Block calls to modify, otherwise // new tx going into the open ledger // would get lost. - std::scoped_lock const lock1(modifyMutex_); + std::scoped_lock const lock1(modify_mutex_); // Apply tx from the current open view if (!current_->txs.empty()) { @@ -154,7 +154,7 @@ OpenLedger::accept( } // Switch to the new open view - std::scoped_lock const lock2(currentMutex_); + std::scoped_lock const lock2(current_mutex_); current_ = std::move(next); } @@ -164,7 +164,7 @@ std::shared_ptr OpenLedger::create(Rules const& rules, std::shared_ptr const& ledger) { return std::make_shared( - kOpenLedger, rules, std::make_shared(ledger, cache_)); + kOPEN_LEDGER, rules, std::make_shared(ledger, cache_)); } auto diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 6c6679ed87..e6b41198bb 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -35,10 +35,10 @@ SkipListAcquire::SkipListAcquire( : TimeoutCounter( app, ledgerHash, - LedgerReplayParameters::kSubTaskTimeout, + LedgerReplayParameters::kSUB_TASK_TIMEOUT, {.jobType = JtReplayTask, .jobName = "SkipListAcq", - .jobLimit = LedgerReplayParameters::kMaxQueuedTasks}, + .jobLimit = LedgerReplayParameters::kMAX_QUEUED_TASKS}, app.getJournal("LedgerReplaySkipList")) , inboundLedgers_(inboundLedgers) , peerSet_(std::move(peerSet)) @@ -94,10 +94,10 @@ SkipListAcquire::trigger(std::size_t limit, ScopedLockType& sl) { JLOG(journal_.trace()) << "Add a no feature peer " << peer->id() << " for " << hash_; - if (++noFeaturePeerCount_ >= LedgerReplayParameters::kMaxNoFeaturePeerCount) + if (++noFeaturePeerCount_ >= LedgerReplayParameters::kMAX_NO_FEATURE_PEER_COUNT) { JLOG(journal_.debug()) << "Fall back for " << hash_; - timerInterval_ = LedgerReplayParameters::kSubTaskFallbackTimeout; + timerInterval_ = LedgerReplayParameters::kSUB_TASK_FALLBACK_TIMEOUT; fallBack_ = true; } } @@ -112,7 +112,7 @@ void SkipListAcquire::onTimer(bool progress, ScopedLockType& sl) { JLOG(journal_.trace()) << "timeouts_=" << timeouts_ << " for " << hash_; - if (timeouts_ > LedgerReplayParameters::kSubTaskMaxTimeouts) + if (timeouts_ > LedgerReplayParameters::kSUB_TASK_MAX_TIMEOUTS) { failed_ = true; JLOG(journal_.debug()) << "too many timeouts " << hash_; diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 62312b04d2..f79620f99d 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -29,10 +29,14 @@ namespace xrpl { using namespace std::chrono_literals; // Timeout interval in milliseconds -constexpr auto kTxAcquireTimeout = 250ms; +auto constexpr kTX_ACQUIRE_TIMEOUT = 250ms; -static constexpr auto kNormTimeouts = 4; -static constexpr auto kMaxTimeouts = 20; +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + NormTimeouts = 4, + MaxTimeouts = 20, +}; TransactionAcquire::TransactionAcquire( Application& app, @@ -41,7 +45,7 @@ TransactionAcquire::TransactionAcquire( : TimeoutCounter( app, hash, - kTxAcquireTimeout, + kTX_ACQUIRE_TIMEOUT, {.jobType = JtTxnData, .jobName = "TxAcq", .jobLimit = {}}, app.getJournal("TransactionAcquire")) , peerSet_(std::move(peerSet)) @@ -81,14 +85,14 @@ TransactionAcquire::done() void TransactionAcquire::onTimer(bool progress, ScopedLockType& psl) { - if (timeouts_ > kMaxTimeouts) + if (timeouts_ > MaxTimeouts) { failed_ = true; done(); return; } - if (timeouts_ >= kNormTimeouts) + if (timeouts_ >= NormTimeouts) trigger(nullptr); addPeers(1); @@ -255,7 +259,7 @@ TransactionAcquire::stillNeed() { ScopedLockType const sl(mtx_); - timeouts_ = std::min(timeouts_, kNormTimeouts); + timeouts_ = std::min(timeouts_, NormTimeouts); failed_ = false; } diff --git a/src/xrpld/app/ledger/detail/TransactionMaster.cpp b/src/xrpld/app/ledger/detail/TransactionMaster.cpp index 129681b906..71a1ca629f 100644 --- a/src/xrpld/app/ledger/detail/TransactionMaster.cpp +++ b/src/xrpld/app/ledger/detail/TransactionMaster.cpp @@ -142,7 +142,7 @@ void TransactionMaster::canonicalize(std::shared_ptr* pTransaction) { uint256 const tid = (*pTransaction)->getID(); - if (tid != beast::kZero) + if (tid != beast::kZERO) { auto txn = *pTransaction; // VFALCO NOTE canonicalize can change the value of txn! diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 508dfc8590..800d398eca 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -141,16 +141,16 @@ fixConfigPorts(Config& config, Endpoints const& endpoints); class ApplicationImp : public Application, public BasicApp { private: - class IOLatencySampler + class IoLatencySampler { private: beast::insight::Event event_; beast::Journal journal_; - beast::IOLatencyProbe probe_; + beast::IoLatencyProbe probe_; std::atomic lastSample_; public: - IOLatencySampler( + IoLatencySampler( beast::insight::Event ev, beast::Journal journal, std::chrono::milliseconds interval, @@ -272,7 +272,7 @@ public: std::unique_ptr resolver_; - IOLatencySampler io_latency_sampler_; + IoLatencySampler io_latency_sampler_; std::unique_ptr grpcServer_; // NOLINTEND(readability-identifier-naming) @@ -286,14 +286,14 @@ public: return 1; #else - if (config.ioWorkers > 0) - return config.ioWorkers; + if (config.IO_WORKERS > 0) + return config.IO_WORKERS; auto const cores = std::thread::hardware_concurrency(); // Use a single thread when running on under-provisioned systems // or if we are configured to use minimal resources. - if ((cores == 1) || ((config.nodeSize == 0) && (cores == 2))) + if ((cores == 1) || ((config.NODE_SIZE == 0) && (cores == 2))) return 1; // Otherwise, prefer six threads. @@ -316,7 +316,7 @@ public: // PerfLog must be started before any other threads are launched. , perfLog_( perf::makePerfLog( - perf::setupPerfLog(config_->section("perf"), config_->configDir), + perf::setupPerfLog(config_->section("perf"), config_->CONFIG_DIR), *this, logs_->journal("PerfLog"), [this] { signalStop("PerfLog"); })) @@ -326,22 +326,22 @@ public: , jobQueue_( std::make_unique( [](std::unique_ptr const& config) { - if (config->standalone() && !config->forceMultiThread) + if (config->standalone() && !config->FORCE_MULTI_THREAD) return 1; - if (config->workers) - return config->workers; + if (config->WORKERS) + return config->WORKERS; auto count = static_cast(std::thread::hardware_concurrency()); // Be more aggressive about the number of threads to use // for the job queue if the server is configured as // "large" or "huge" if there are enough cores. - if (config->nodeSize >= 4 && count >= 16) + if (config->NODE_SIZE >= 4 && count >= 16) { count = 6 + std::min(count, 8); } - else if (config->nodeSize >= 3 && count >= 8) + else if (config->NODE_SIZE >= 3 && count >= 8) { count = 4 + std::min(count, 6); } @@ -370,16 +370,16 @@ public: std::chrono::minutes(1), stopwatch(), logs_->journal("CachedSLEs")) - , networkIDService_(std::make_unique(config_->networkId)) + , networkIDService_(std::make_unique(config_->NETWORK_ID)) , validatorKeys_(*config_, journal_) , resourceManager_( Resource::makeManager(collectorManager_->collector(), logs_->journal("Resource"))) , nodeStore_(shaMapStore_->makeNodeStore( - config_->prefetchWorkers > 0 ? config_->prefetchWorkers : 4)) + config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) , nodeFamily_(*this, *collectorManager_) , orderBookDB_(makeOrderBookDb( *this, - {.pathSearchMax = config_->pathSearchMax, .standalone = config_->standalone()})) + {.pathSearchMax = config_->PATH_SEARCH_MAX, .standalone = config_->standalone()})) , pathRequestManager_( std::make_unique( *this, @@ -415,8 +415,8 @@ public: *this, stopwatch(), config_->standalone(), - config_->networkQuorum, - config_->startValid, + config_->NETWORK_QUORUM, + config_->START_VALID, *jobQueue_, *ledgerMaster_, validatorKeys_, @@ -435,7 +435,7 @@ public: *timeKeeper_, config_->legacy("database_path"), logs_->journal("ValidatorList"), - config_->validationQuorum)) + config_->VALIDATION_QUORUM)) , validatorSites_(std::make_unique(*this)) , serverHandler_(makeServerHandler( *this, @@ -918,7 +918,7 @@ public: { using namespace std::chrono; sweepTimer_.expires_after( - seconds{config_->sweepInterval.value_or( + seconds{config_->SWEEP_INTERVAL.value_or( config_->getValueFor(SizedItem::SweepInterval))}); sweepTimer_.async_wait(std::move(*optionalCountedHandler)); } @@ -998,10 +998,6 @@ public: JLOG(journal_.debug()) << "MasterTransaction sweep. Size before: " << oldMasterTxSize << "; size after: " << masterTxCache.size(); } - { - // Sweep NodeStore database cache(s), if enabled. - getNodeStore().sweep(); - } { std::size_t const oldLedgerMasterCacheSize = getLedgerMaster().getFetchPackCacheSize(); @@ -1180,9 +1176,9 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) if (!logs_->open(debugLog)) std::cerr << "Can't open log file " << debugLog << '\n'; - using beast::Severity; - if (logs_->threshold() > Severity::Debug) - logs_->threshold(Severity::Debug); + using namespace beast::severities; + if (logs_->threshold() > KDebug) + logs_->threshold(KDebug); } JLOG(journal_.info()) << "Process starting: " << BuildInfo::getFullVersionString() @@ -1230,7 +1226,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) amendmentTable_ = makeAmendmentTable( *this, - config().amendmentMajorityTime, + config().AMENDMENT_MAJORITY_TIME, supported, upVoted, downVoted, @@ -1239,7 +1235,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) Pathfinder::initPathTable(); - auto const startUp = config_->startUp; + auto const startUp = config_->START_UP; JLOG(journal_.debug()) << "startUp: " << startUp; if (startUp == StartUpType::Fresh) { @@ -1254,13 +1250,13 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) JLOG(journal_.info()) << "Loading specified Ledger"; if (!loadOldLedger( - config_->startLedger, + config_->START_LEDGER, startUp == StartUpType::Replay, startUp == StartUpType::LoadFile, - config_->trapTxHash)) + config_->TRAP_TX_HASH)) { JLOG(journal_.error()) << "The specified ledger could not be loaded."; - if (config_->fastLoad) + if (config_->FAST_LOAD) { // Fall back to syncing from the network, such as // when there's no existing data. @@ -1286,7 +1282,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) startGenesisLedger(); } - if (auto const& forcedRange = config().forcedLedgerRangePresent) + if (auto const& forcedRange = config().FORCED_LEDGER_RANGE_PRESENT) { ledgerMaster_->setLedgerRangePresent(forcedRange->first, forcedRange->second); } @@ -1332,7 +1328,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) localSigningKey, config().section(SECTION_VALIDATORS).values(), config().section(SECTION_VALIDATOR_LIST_KEYS).values(), - config().validatorListThreshold)) + config().VALIDATOR_LIST_THRESHOLD)) { JLOG(journal_.fatal()) << "Invalid entry in validator configuration."; return false; @@ -1361,7 +1357,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // if (!config_.standalone()) overlay_ = makeOverlay( *this, - setupOverlay(*config_, journal_), + setupOverlay(*config_), *serverHandler_, *resourceManager_, *resolver_, @@ -1403,7 +1399,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) { // Should this message be here, conceptually? In theory this sort // of message, if displayed, should be displayed from PeerFinder. - if (config_->peerPrivate && config_->ipsFixed.empty()) + if (config_->PEER_PRIVATE && config_->IPS_FIXED.empty()) { JLOG(journal_.warn()) << "No outbound peer connections will be made"; } @@ -1455,7 +1451,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) JLOG(journal_.fatal()) << "Startup RPC: " << jvCommand << std::endl; } - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; Resource::Consumer c; RPC::JsonContext context{ {.j = getJournal("RPCHandler"), @@ -1467,7 +1463,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) .role = Role::ADMIN, .coro = {}, .infoSub = {}, - .apiVersion = RPC::kApiMaximumSupportedVersion}, + .apiVersion = RPC::kAPI_MAXIMUM_SUPPORTED_VERSION}, jvCommand}; json::Value jvResult; @@ -1663,14 +1659,14 @@ ApplicationImp::fdRequired() const void ApplicationImp::startGenesisLedger() { - std::vector const initialAmendments = (config_->startUp == StartUpType::Fresh) + std::vector const initialAmendments = (config_->START_UP == StartUpType::Fresh) ? amendmentTable_->getDesired() : std::vector{}; std::shared_ptr const genesis = std::make_shared( - kCreateGenesis, + kCREATE_GENESIS, Rules{config_->features}, - config_->fees.toFees(), + config_->FEES.toFees(), initialAmendments, nodeFamily_); ledgerMaster_->storeLedger(genesis); @@ -1678,7 +1674,7 @@ ApplicationImp::startGenesisLedger() auto const next = std::make_shared(*genesis, getTimeKeeper().closeTime()); next->updateSkipList(); XRPL_ASSERT( - next->header().seq < kXrpLedgerEarliestFees || next->read(keylet::fees()), + next->header().seq < kXRP_LEDGER_EARLIEST_FEES || next->read(keylet::fees()), "xrpl::ApplicationImp::startGenesisLedger : valid ledger fees"); next->setImmutable(); openLedger_.emplace(next, cachedSLEs_, logs_->journal("OpenLedger")); @@ -1694,13 +1690,13 @@ ApplicationImp::getLastFullLedger() try { auto const [ledger, seq, hash] = - getLatestLedger(Rules{config_->features}, config_->fees.toFees(), *this); + getLatestLedger(Rules{config_->features}, config_->FEES.toFees(), *this); if (!ledger) return ledger; XRPL_ASSERT( - ledger->header().seq < kXrpLedgerEarliestFees || ledger->read(keylet::fees()), + ledger->header().seq < kXRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "xrpl::ApplicationImp::getLastFullLedger : valid ledger fees"); ledger->setImmutable(); @@ -1717,7 +1713,7 @@ ApplicationImp::getLastFullLedger() { stream << "Failed on ledger"; json::Value p; - addJson(p, {*ledger, nullptr, static_cast(LedgerFill::Options::Full)}); + addJson(p, {*ledger, nullptr, LedgerFill::Full}); stream << p; } @@ -1806,7 +1802,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) } auto loadLedger = std::make_shared( - seq, closeTime, Rules{config_->features}, config_->fees.toFees(), nodeFamily_); + seq, closeTime, Rules{config_->features}, config_->FEES.toFees(), nodeFamily_); loadLedger->setTotalDrops(totalDrops); for (json::UInt index = 0; index < ledger.get().size(); ++index) @@ -1851,7 +1847,8 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) loadLedger->stateMap().flushDirty(NodeObjectType::AccountNode); XRPL_ASSERT( - loadLedger->header().seq < kXrpLedgerEarliestFees || loadLedger->read(keylet::fees()), + loadLedger->header().seq < kXRP_LEDGER_EARLIEST_FEES || + loadLedger->read(keylet::fees()), "xrpl::ApplicationImp::loadLedgerFromFile : valid ledger fees"); loadLedger->setAccepted(closeTime, closeTimeResolution, !closeTimeEstimated); @@ -1887,7 +1884,7 @@ ApplicationImp::loadOldLedger( if (hash.parseHex(ledgerID)) { loadLedger = - loadByHash(hash, Rules{config_->features}, config_->fees.toFees(), *this); + loadByHash(hash, Rules{config_->features}, config_->FEES.toFees(), *this); if (!loadLedger) { @@ -1916,7 +1913,7 @@ ApplicationImp::loadOldLedger( if (beast::lexicalCastChecked(index, ledgerID)) { loadLedger = - loadByIndex(index, Rules{config_->features}, config_->fees.toFees(), *this); + loadByIndex(index, Rules{config_->features}, config_->FEES.toFees(), *this); } } @@ -1935,7 +1932,7 @@ ApplicationImp::loadOldLedger( loadLedger = loadByHash( replayLedger->header().parentHash, Rules{config_->features}, - config_->fees.toFees(), + config_->FEES.toFees(), *this); if (!loadLedger) { @@ -1967,13 +1964,13 @@ ApplicationImp::loadOldLedger( } using namespace std::chrono_literals; using namespace date; - static constexpr NetClock::time_point kLedgerWarnTimePoint{ + static constexpr NetClock::time_point kLEDGER_WARN_TIME_POINT{ sys_days{January / 1 / 2018} - sys_days{January / 1 / 2000}}; - if (loadLedger->header().closeTime < kLedgerWarnTimePoint) + if (loadLedger->header().closeTime < kLEDGER_WARN_TIME_POINT) { JLOG(journal_.fatal()) << "\n\n*** WARNING ***\n" "You are replaying a ledger from before " - << to_string(kLedgerWarnTimePoint) + << to_string(kLEDGER_WARN_TIME_POINT) << " UTC.\n" "This replay will not handle your ledger as it was " "originally " @@ -2082,7 +2079,7 @@ ApplicationImp::loadOldLedger( bool ApplicationImp::serverOkay(std::string& reason) { - if (!config().elbSupport) + if (!config().ELB_SUPPORT) return true; if (isStopping()) diff --git a/src/xrpld/app/main/BasicApp.cpp b/src/xrpld/app/main/BasicApp.cpp index c530c170cb..71138c6517 100644 --- a/src/xrpld/app/main/BasicApp.cpp +++ b/src/xrpld/app/main/BasicApp.cpp @@ -9,14 +9,14 @@ BasicApp::BasicApp(std::size_t numberOfThreads) { - work_.emplace(boost::asio::make_work_guard(ioContext_)); + work_.emplace(boost::asio::make_work_guard(io_context_)); threads_.reserve(numberOfThreads); for (std::size_t i = 0; i < numberOfThreads; ++i) { threads_.emplace_back([this, i]() { beast::setCurrentThreadName("io svc #" + std::to_string(i)); - this->ioContext_.run(); + this->io_context_.run(); }); } } diff --git a/src/xrpld/app/main/BasicApp.h b/src/xrpld/app/main/BasicApp.h index 5ba7c719e3..d55ab858db 100644 --- a/src/xrpld/app/main/BasicApp.h +++ b/src/xrpld/app/main/BasicApp.h @@ -12,7 +12,7 @@ class BasicApp private: std::optional> work_; std::vector threads_; - boost::asio::io_context ioContext_; + boost::asio::io_context io_context_; public: BasicApp(std::size_t numberOfThreads); @@ -21,7 +21,7 @@ public: boost::asio::io_context& getIoContext() { - return ioContext_; + return io_context_; } [[nodiscard]] size_t diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 7a622f632f..e0f0798dbc 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -204,7 +204,7 @@ GRPCServerImpl::CallData::process(std::shared_ptr("Error setting grpc server address"); } - auto const optSecureGateway = section.get("secure_gateway"); + auto const optSecureGateway = section.get("secureGateway"); if (optSecureGateway) { try @@ -376,8 +376,8 @@ 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"); + << "secureGateway section of port_grpc"; + Throw("Unspecified IP in secureGateway section"); } secureGatewayIPs_.emplace_back(addr); @@ -386,7 +386,7 @@ 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"); + Throw("Error parsing secureGateway section"); } } @@ -526,7 +526,6 @@ GRPCServerImpl::handleRpcs() std::vector> GRPCServerImpl::setupListeners() { - using RPC::Condition; std::vector> requests; auto addToRequests = [&requests](auto callData) { requests.push_back(std::move(callData)); }; @@ -543,8 +542,8 @@ GRPCServerImpl::setupListeners() &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedger, doLedgerGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedger, - Condition::NoCondition, - Resource::kFeeMediumBurdenRpc, + RPC::NoCondition, + Resource::kFEE_MEDIUM_BURDEN_RPC, secureGatewayIPs_)); } { @@ -560,8 +559,8 @@ GRPCServerImpl::setupListeners() &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerData, doLedgerDataGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerData, - Condition::NoCondition, - Resource::kFeeMediumBurdenRpc, + RPC::NoCondition, + Resource::kFEE_MEDIUM_BURDEN_RPC, secureGatewayIPs_)); } { @@ -577,8 +576,8 @@ GRPCServerImpl::setupListeners() &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerDiff, doLedgerDiffGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerDiff, - Condition::NoCondition, - Resource::kFeeMediumBurdenRpc, + RPC::NoCondition, + Resource::kFEE_MEDIUM_BURDEN_RPC, secureGatewayIPs_)); } { @@ -594,8 +593,8 @@ GRPCServerImpl::setupListeners() &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerEntry, doLedgerEntryGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerEntry, - Condition::NoCondition, - Resource::kFeeMediumBurdenRpc, + RPC::NoCondition, + Resource::kFEE_MEDIUM_BURDEN_RPC, secureGatewayIPs_)); } return requests; diff --git a/src/xrpld/app/main/GRPCServer.h b/src/xrpld/app/main/GRPCServer.h index 7d299474d9..6d9af236dc 100644 --- a/src/xrpld/app/main/GRPCServer.h +++ b/src/xrpld/app/main/GRPCServer.h @@ -93,7 +93,7 @@ private: template using Handler = std::function(RPC::GRPCContext&)>; // This implementation is currently limited to v1 of the API - static constexpr unsigned kApiVersion = 1; + static unsigned constexpr kAPI_VERSION = 1; template using Forward = std::function(steady_clock::now() - lastHeartbeat); - static constexpr auto kReportingIntervalSeconds = 10s; - static constexpr auto kStallFatalLogMessageTimeLimit = 90s; - static constexpr auto kStallLogicErrorTimeLimit = 600s; + constexpr auto kREPORTING_INTERVAL_SECONDS = 10s; + constexpr auto kSTALL_FATAL_LOG_MESSAGE_TIME_LIMIT = 90s; + constexpr auto kSTALL_LOGIC_ERROR_TIME_LIMIT = 600s; - if (armed && (timeSpentStalled >= kReportingIntervalSeconds)) + if (armed && (timeSpentStalled >= kREPORTING_INTERVAL_SECONDS)) { // Report the stalled condition every reportingIntervalSeconds - if ((timeSpentStalled % kReportingIntervalSeconds) == 0s) + if ((timeSpentStalled % kREPORTING_INTERVAL_SECONDS) == 0s) { - if (timeSpentStalled < kStallFatalLogMessageTimeLimit) + if (timeSpentStalled < kSTALL_FATAL_LOG_MESSAGE_TIME_LIMIT) { JLOG(journal_.warn()) << "Server stalled for " << timeSpentStalled.count() << " seconds."; @@ -141,7 +141,7 @@ LoadManager::run() // If we go over the stallLogicErrorTimeLimit spent stalled, it // means that the stall resolution code has failed, which qualifies // as a LogicError - if (timeSpentStalled >= kStallLogicErrorTimeLimit) + if (timeSpentStalled >= kSTALL_LOGIC_ERROR_TIME_LIMIT) { JLOG(journal_.fatal()) << "LogicError: Fatal server stall detected. Stalled time: " << timeSpentStalled.count() << "s"; diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index f470a2d80f..167cd2b023 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -627,7 +627,7 @@ run(int argc, char** argv) { throw std::runtime_error("Invalid force_ledger_present_range parameter"); } - config->forcedLedgerRangePresent.emplace(r[0], r[1]); + config->FORCED_LEDGER_RANGE_PRESENT.emplace(r[0], r[1]); } else { @@ -646,7 +646,7 @@ run(int argc, char** argv) if (vm.contains("start")) { - config->startUp = StartUpType::Fresh; + config->START_UP = StartUpType::Fresh; } if (vm.contains("import")) @@ -654,17 +654,17 @@ run(int argc, char** argv) if (vm.contains("ledger")) { - config->startLedger = vm["ledger"].as(); + config->START_LEDGER = vm["ledger"].as(); if (vm.contains("replay")) { - config->startUp = StartUpType::Replay; + config->START_UP = StartUpType::Replay; if (vm.contains("trap_tx_hash")) { uint256 tmp = {}; auto hash = vm["trap_tx_hash"].as(); if (tmp.parseHex(hash)) { - config->trapTxHash = tmp; + config->TRAP_TX_HASH = tmp; } else { @@ -677,17 +677,17 @@ run(int argc, char** argv) } else { - config->startUp = StartUpType::Load; + config->START_UP = StartUpType::Load; } } else if (vm.contains("ledgerfile")) { - config->startLedger = vm["ledgerfile"].as(); - config->startUp = StartUpType::LoadFile; + config->START_LEDGER = vm["ledgerfile"].as(); + config->START_UP = StartUpType::LoadFile; } - else if (vm.contains("load") || config->fastLoad) + else if (vm.contains("load") || config->FAST_LOAD) { - config->startUp = StartUpType::Load; + config->START_UP = StartUpType::Load; } if (vm.contains("trap_tx_hash") && !vm.contains("replay")) @@ -696,20 +696,20 @@ run(int argc, char** argv) return -1; } - if (vm.contains("net") && !config->fastLoad) + if (vm.contains("net") && !config->FAST_LOAD) { - if ((config->startUp == StartUpType::Load) || (config->startUp == StartUpType::Replay)) + if ((config->START_UP == StartUpType::Load) || (config->START_UP == StartUpType::Replay)) { std::cerr << "Net and load/replay options are incompatible" << std::endl; return -1; } - config->startUp = StartUpType::Network; + config->START_UP = StartUpType::Network; } if (vm.contains("valid")) { - config->startValid = true; + config->START_VALID = true; } // Override the RPC destination IP address. This must @@ -747,15 +747,15 @@ run(int argc, char** argv) } } - config->rpcIp = std::move(*endpoint); + config->rpc_ip = std::move(*endpoint); } if (vm.contains("quorum")) { try { - config->validationQuorum = vm["quorum"].as(); - if (config->validationQuorum == std::size_t{}) + config->VALIDATION_QUORUM = vm["quorum"].as(); + if (config->VALIDATION_QUORUM == std::size_t{}) { throw std::domain_error("0"); } @@ -768,16 +768,16 @@ run(int argc, char** argv) } // Construct the logs object at the configured severity - using beast::Severity; - Severity thresh = Severity::Info; + using namespace beast::severities; + Severity thresh = KInfo; if (vm.contains("quiet")) { - thresh = Severity::Fatal; + thresh = KFatal; } else if (vm.contains("verbose")) { - thresh = Severity::Trace; + thresh = KTrace; } auto logs = std::make_unique(thresh); @@ -802,7 +802,7 @@ run(int argc, char** argv) return -1; if (vm.contains("debug")) - setDebugLogSink(logs->makeSink("Debug", beast::Severity::Trace)); + setDebugLogSink(logs->makeSink("Debug", beast::severities::KTrace)); auto app = makeApplication(std::move(config), std::move(logs), std::make_unique()); diff --git a/src/xrpld/app/main/Tuning.h b/src/xrpld/app/main/Tuning.h index d61f27ec03..4d2c4e01e7 100644 --- a/src/xrpld/app/main/Tuning.h +++ b/src/xrpld/app/main/Tuning.h @@ -4,9 +4,9 @@ namespace xrpl { -constexpr std::size_t kFullBelowTargetSize = 524288; -constexpr std::chrono::seconds kFullBelowExpiration = std::chrono::minutes{10}; +constexpr std::size_t kFULL_BELOW_TARGET_SIZE = 524288; +constexpr std::chrono::seconds kFULL_BELOW_EXPIRATION = std::chrono::minutes{10}; -constexpr std::size_t kMaxPoppedTransactions = 10; +constexpr std::size_t kMAX_POPPED_TRANSACTIONS = 10; } // namespace xrpl diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index c4e6c3cdc2..4369a4642d 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -135,10 +135,13 @@ FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation v[sfield] = target; } }; - vote(lastFees.base, target_.referenceFee, "base fee", sfBaseFeeDrops); - vote(lastFees.reserve, target_.accountReserve, "base reserve", sfReserveBaseDrops); + vote(lastFees.base, target_.reference_fee, "base fee", sfBaseFeeDrops); + vote(lastFees.reserve, target_.account_reserve, "base reserve", sfReserveBaseDrops); vote( - lastFees.increment, target_.ownerReserve, "reserve increment", sfReserveIncrementDrops); + lastFees.increment, + target_.owner_reserve, + "reserve increment", + sfReserveIncrementDrops); } else { @@ -159,11 +162,11 @@ FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation } }; - vote(lastFees.base, target_.referenceFee, to64, "base fee", sfBaseFee); - vote(lastFees.reserve, target_.accountReserve, to32, "base reserve", sfReserveBase); + vote(lastFees.base, target_.reference_fee, to64, "base fee", sfBaseFee); + vote(lastFees.reserve, target_.account_reserve, to32, "base reserve", sfReserveBase); vote( lastFees.increment, - target_.ownerReserve, + target_.owner_reserve, to32, "reserve increment", sfReserveIncrement); @@ -181,11 +184,11 @@ FeeVoteImpl::doVoting( lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); - detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.referenceFee); + detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.reference_fee); - detail::VotableValue baseReserveVote(lastClosedLedger->fees().reserve, target_.accountReserve); + detail::VotableValue baseReserveVote(lastClosedLedger->fees().reserve, target_.account_reserve); - detail::VotableValue incReserveVote(lastClosedLedger->fees().increment, target_.ownerReserve); + detail::VotableValue incReserveVote(lastClosedLedger->fees().increment, target_.owner_reserve); auto const& rules = lastClosedLedger->rules(); if (rules.enabled(featureXRPFees)) @@ -292,7 +295,7 @@ FeeVoteImpl::doVoting( baseReserve.first.dropsAs(baseReserveVote.current()); obj[sfReserveIncrement] = incReserve.first.dropsAs(incReserveVote.current()); - obj[sfReferenceFeeUnits] = kFeeUnitsDeprecated; + obj[sfReferenceFeeUnits] = kFEE_UNITS_DEPRECATED; } }); diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index 2ed440fba8..0da94ad75f 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -141,7 +141,7 @@ NodeID NegativeUNLVote::choose(uint256 const& randomPadData, std::vector const& candidates) { XRPL_ASSERT(!candidates.empty(), "xrpl::NegativeUNLVote::choose : non-empty input"); - static_assert(NodeID::kBytes <= uint256::kBytes); + static_assert(NodeID::kBYTES <= uint256::kBYTES); NodeID const randomPad = NodeID::fromVoid(randomPadData.data()); NodeID txNodeID = candidates[0]; for (int j = 1; j < candidates.size(); ++j) @@ -167,7 +167,7 @@ NegativeUNLVote::buildScoreTable( // Ask the validation container to keep enough validation message history // for next time. auto const seq = prevLedger->header().seq + 1; - validations.setSeqToKeep(seq - 1, seq + kFlagLedgerInterval); + validations.setSeqToKeep(seq - 1, seq + kFLAG_LEDGER_INTERVAL); // Find FLAG_LEDGER_INTERVAL (i.e. 256) previous ledger hashes auto const hashIndex = prevLedger->read(keylet::skip()); @@ -178,7 +178,7 @@ NegativeUNLVote::buildScoreTable( } auto const ledgerAncestors = hashIndex->getFieldV256(sfHashes).value(); auto const numAncestors = ledgerAncestors.size(); - if (numAncestors < kFlagLedgerInterval) + if (numAncestors < kFLAG_LEDGER_INTERVAL) { JLOG(j_.debug()) << "N-UNL: ledger " << seq << " not enough history. Can trace back only " << numAncestors << " ledgers."; @@ -194,7 +194,7 @@ NegativeUNLVote::buildScoreTable( // Query the validation container for every ledger hash and fill // the score table. - for (int i = 0; i < kFlagLedgerInterval; ++i) + for (int i = 0; i < kFLAG_LEDGER_INTERVAL; ++i) { for (auto const& v : validations.getTrustedForLedger(ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) @@ -211,16 +211,16 @@ NegativeUNLVote::buildScoreTable( return it->second; return 0; }(); - if (myValidationCount < kNegativeUnlMinLocalValsToVote) + if (myValidationCount < kNEGATIVE_UNL_MIN_LOCAL_VALS_TO_VOTE) { JLOG(j_.debug()) << "N-UNL: ledger " << seq << ". Local node only issued " - << myValidationCount << " validations in last " << kFlagLedgerInterval + << myValidationCount << " validations in last " << kFLAG_LEDGER_INTERVAL << " ledgers." << " The reliability measurement could be wrong."; return {}; } - if (myValidationCount > kNegativeUnlMinLocalValsToVote && - myValidationCount <= kFlagLedgerInterval) + if (myValidationCount > kNEGATIVE_UNL_MIN_LOCAL_VALS_TO_VOTE && + myValidationCount <= kFLAG_LEDGER_INTERVAL) { return scoreTable; } @@ -228,7 +228,7 @@ 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 " << kFlagLedgerInterval << " ledgers. Too many!"; + << " validations in last " << kFLAG_LEDGER_INTERVAL << " ledgers. Too many!"; return {}; } @@ -241,7 +241,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() * kNegativeUnlMaxListed)); + static_cast(std::ceil(unl.size() * kNEGATIVE_UNL_MAX_LISTED)); std::size_t negativeListed = 0; for (auto const& n : unl) { @@ -250,9 +250,10 @@ NegativeUNLVote::findAllCandidates( } bool const result = negativeListed < maxNegativeListed; JLOG(j_.trace()) << "N-UNL: nodeId " << myId_ << " lowWaterMark " - << kNegativeUnlLowWaterMark << " highWaterMark " - << kNegativeUnlHighWaterMark << " canAdd " << result << " negativeListed " - << negativeListed << " maxNegativeListed " << maxNegativeListed; + << kNEGATIVE_UNL_LOW_WATER_MARK << " highWaterMark " + << kNEGATIVE_UNL_HIGH_WATER_MARK << " canAdd " << result + << " negativeListed " << negativeListed << " maxNegativeListed " + << maxNegativeListed; return result; }(); @@ -266,7 +267,7 @@ NegativeUNLVote::findAllCandidates( // (2) has less than negativeUNLLowWaterMark validations, // (3) is not in negUnl, and // (4) is not a new validator. - if (canAdd && score < kNegativeUnlLowWaterMark && !negUnl.contains(nodeId) && + if (canAdd && score < kNEGATIVE_UNL_LOW_WATER_MARK && !negUnl.contains(nodeId) && !newValidators_.contains(nodeId)) { JLOG(j_.trace()) << "N-UNL: toDisable candidate " << nodeId; @@ -276,7 +277,7 @@ NegativeUNLVote::findAllCandidates( // Find toReEnable Candidates: check if // (1) has more than negativeUNLHighWaterMark validations, // (2) is in negUnl - if (score > kNegativeUnlHighWaterMark && negUnl.contains(nodeId)) + if (score > kNEGATIVE_UNL_HIGH_WATER_MARK && negUnl.contains(nodeId)) { JLOG(j_.trace()) << "N-UNL: toReEnable candidate " << nodeId; candidates.toReEnableCandidates.push_back(nodeId); @@ -327,7 +328,7 @@ NegativeUNLVote::purgeNewValidators(LedgerIndex seq) auto i = newValidators_.begin(); while (i != newValidators_.end()) { - if (seq - i->second > kNewValidatorDisableSkip) + if (seq - i->second > kNEW_VALIDATOR_DISABLE_SKIP) { i = newValidators_.erase(i); } diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 5c2d3f8630..4cedc4743f 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -32,26 +32,26 @@ public: * An unreliable validator is a candidate to be disabled by the NegativeUNL * protocol. */ - static constexpr size_t kNegativeUnlLowWaterMark = kFlagLedgerInterval * 50 / 100; + static constexpr size_t kNEGATIVE_UNL_LOW_WATER_MARK = kFLAG_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 kNegativeUnlHighWaterMark = kFlagLedgerInterval * 80 / 100; + static constexpr size_t kNEGATIVE_UNL_HIGH_WATER_MARK = kFLAG_LEDGER_INTERVAL * 80 / 100; /** * The minimum number of validations of the local node for it to * participate in the voting. */ - static constexpr size_t kNegativeUnlMinLocalValsToVote = kFlagLedgerInterval * 90 / 100; + static constexpr size_t kNEGATIVE_UNL_MIN_LOCAL_VALS_TO_VOTE = kFLAG_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. */ - static constexpr size_t kNewValidatorDisableSkip = kFlagLedgerInterval * 2; + static constexpr size_t kNEW_VALIDATOR_DISABLE_SKIP = kFLAG_LEDGER_INTERVAL * 2; /** * We only want to put 25% of the UNL on the NegativeUNL. */ - static constexpr float kNegativeUnlMaxListed = 0.25; + static constexpr float kNEGATIVE_UNL_MAX_LISTED = 0.25; /** * A flag indicating whether a UNLModify Tx is to disable or to re-enable diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 54cf85ba35..638489a9fa 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -189,7 +189,7 @@ class NetworkOPsImp final : public NetworkOPs Running, }; - static std::array const kStates; + static std::array const kSTATES; /** * State accounting records two attributes for each possible server state: @@ -221,7 +221,7 @@ class NetworkOPsImp final : public NetworkOPs 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 kStates; + static std::array const kSTATES; public: explicit StateAccounting() @@ -327,7 +327,7 @@ public: validatorKeys.keys ? validatorKeys.keys->masterPublicKey : decltype(validatorMasterPK_){}) , ledgerMaster_(ledgerMaster) - , jobQueue_(jobQueue) + , job_queue_(jobQueue) , standalone_(standalone) , minPeerCount_(startValid ? 0 : minPeerCount) , stats_(std::bind(&NetworkOPsImp::collectMetrics, this), collector) @@ -828,7 +828,7 @@ private: ServerFeeSummary lastFeeSummary_; - JobQueue& jobQueue_; + JobQueue& job_queue_; // Whether we are in standalone mode. bool const standalone_; @@ -853,34 +853,34 @@ private: template Stats(Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->makeHook(handler)) - , disconnectedDuration( + , disconnected_duration( collector->makeGauge("State_Accounting", "Disconnected_duration")) - , connectedDuration(collector->makeGauge("State_Accounting", "Connected_duration")) - , syncingDuration(collector->makeGauge("State_Accounting", "Syncing_duration")) - , trackingDuration(collector->makeGauge("State_Accounting", "Tracking_duration")) - , fullDuration(collector->makeGauge("State_Accounting", "Full_duration")) - , disconnectedTransitions( + , connected_duration(collector->makeGauge("State_Accounting", "Connected_duration")) + , syncing_duration(collector->makeGauge("State_Accounting", "Syncing_duration")) + , tracking_duration(collector->makeGauge("State_Accounting", "Tracking_duration")) + , full_duration(collector->makeGauge("State_Accounting", "Full_duration")) + , disconnected_transitions( collector->makeGauge("State_Accounting", "Disconnected_transitions")) - , connectedTransitions( + , connected_transitions( collector->makeGauge("State_Accounting", "Connected_transitions")) - , syncingTransitions(collector->makeGauge("State_Accounting", "Syncing_transitions")) - , trackingTransitions(collector->makeGauge("State_Accounting", "Tracking_transitions")) - , fullTransitions(collector->makeGauge("State_Accounting", "Full_transitions")) + , syncing_transitions(collector->makeGauge("State_Accounting", "Syncing_transitions")) + , tracking_transitions(collector->makeGauge("State_Accounting", "Tracking_transitions")) + , full_transitions(collector->makeGauge("State_Accounting", "Full_transitions")) { } beast::insight::Hook hook; - beast::insight::Gauge disconnectedDuration; - beast::insight::Gauge connectedDuration; - beast::insight::Gauge syncingDuration; - beast::insight::Gauge trackingDuration; - beast::insight::Gauge fullDuration; + beast::insight::Gauge disconnected_duration; + beast::insight::Gauge connected_duration; + beast::insight::Gauge syncing_duration; + beast::insight::Gauge tracking_duration; + beast::insight::Gauge full_duration; - beast::insight::Gauge disconnectedTransitions; - beast::insight::Gauge connectedTransitions; - beast::insight::Gauge syncingTransitions; - beast::insight::Gauge trackingTransitions; - beast::insight::Gauge fullTransitions; + beast::insight::Gauge disconnected_transitions; + beast::insight::Gauge connected_transitions; + beast::insight::Gauge syncing_transitions; + beast::insight::Gauge tracking_transitions; + beast::insight::Gauge full_transitions; }; std::mutex statsMutex_; // Mutex to lock stats_ @@ -893,19 +893,19 @@ private: //------------------------------------------------------------------------------ -static std::array const kStateNames{ +static std::array const kSTATE_NAMES{ {"disconnected", "connected", "syncing", "tracking", "full"}}; -std::array const NetworkOPsImp::kStates = kStateNames; +std::array const NetworkOPsImp::kSTATES = kSTATE_NAMES; -std::array const NetworkOPsImp::StateAccounting::kStates = { - {json::StaticString(kStateNames[0]), - json::StaticString(kStateNames[1]), - json::StaticString(kStateNames[2]), - json::StaticString(kStateNames[3]), - json::StaticString(kStateNames[4])}}; +std::array const NetworkOPsImp::StateAccounting::kSTATES = { + {json::StaticString(kSTATE_NAMES[0]), + json::StaticString(kSTATE_NAMES[1]), + json::StaticString(kSTATE_NAMES[2]), + json::StaticString(kSTATE_NAMES[3]), + json::StaticString(kSTATE_NAMES[4])}}; -static auto const kGenesisAccountId = +static auto const kGENESIS_ACCOUNT_ID = calcAccountID(generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")).first); //------------------------------------------------------------------------------ @@ -954,20 +954,20 @@ NetworkOPsImp::isFull() std::string NetworkOPsImp::getHostId(bool forAdmin) { - static std::string const kHostname = boost::asio::ip::host_name(); + static std::string const kHOSTNAME = boost::asio::ip::host_name(); if (forAdmin) - return kHostname; + return kHOSTNAME; // For non-admin uses hash the node public key into a // single RFC1751 word: - static std::string const kShroudedHostId = [this]() { + static std::string const kSHROUDED_HOST_ID = [this]() { auto const& id = registry_.get().getApp().nodeIdentity(); return RFC1751::getWordFromBlob(id.first.data(), id.first.size()); }(); - return kShroudedHostId; + return kSHROUDED_HOST_ID; } void @@ -990,7 +990,7 @@ NetworkOPsImp::setTimer( // Only start the timer if waitHandlerCounter_ is not yet joined. if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this, onExpire, onError](boost::system::error_code const& e) { - if ((e.value() == boost::system::errc::success) && (!jobQueue_.isStopped())) + if ((e.value() == boost::system::errc::success) && (!job_queue_.isStopped())) { onExpire(); } @@ -1017,7 +1017,7 @@ NetworkOPsImp::setHeartbeatTimer() heartbeatTimer_, consensus_.parms().ledgerGRANULARITY, [this]() { - jobQueue_.addJob(JtNetopTimer, "NetHeart", [this]() { processHeartbeatTimer(); }); + job_queue_.addJob(JtNetopTimer, "NetHeart", [this]() { processHeartbeatTimer(); }); }, [this]() { setHeartbeatTimer(); }); } @@ -1031,7 +1031,7 @@ NetworkOPsImp::setClusterTimer() clusterTimer_, 10s, [this]() { - jobQueue_.addJob(JtNetopCluster, "NetCluster", [this]() { processClusterTimer(); }); + job_queue_.addJob(JtNetopCluster, "NetCluster", [this]() { processClusterTimer(); }); }, [this]() { setClusterTimer(); }); } @@ -1194,7 +1194,7 @@ NetworkOPsImp::strOperatingMode(OperatingMode const mode, bool const admin) cons } } - return kStates[static_cast(mode)]; + return kSTATES[static_cast(mode)]; } void @@ -1247,7 +1247,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) auto tx = std::make_shared(trans, reason, registry_.get().getApp()); - jobQueue_.addJob(JtTransaction, "SubmitTxn", [this, tx]() { + job_queue_.addJob(JtTransaction, "SubmitTxn", [this, tx]() { auto t = tx; processTransaction(t, false, false, FailHard::No); }); @@ -1312,7 +1312,7 @@ NetworkOPsImp::processTransaction( bool bLocal, FailHard failType) { - auto ev = jobQueue_.makeLoadEvent(JtTxnProc, "ProcessTXN"); + auto ev = job_queue_.makeLoadEvent(JtTxnProc, "ProcessTXN"); // preProcessTransaction can change our pointer if (!preProcessTransaction(transaction)) @@ -1344,7 +1344,7 @@ NetworkOPsImp::doTransactionAsync( if (dispatchState_ == DispatchState::None) { - if (jobQueue_.addJob(JtBatch, "TxBatchAsync", [this]() { transactionBatch(); })) + if (job_queue_.addJob(JtBatch, "TxBatchAsync", [this]() { transactionBatch(); })) { dispatchState_ = DispatchState::Scheduled; } @@ -1389,7 +1389,7 @@ NetworkOPsImp::doTransactionSyncBatch( if (!transactions_.empty()) { // More transactions need to be applied, but by another job. - if (jobQueue_.addJob(JtBatch, "TxBatchSync", [this]() { transactionBatch(); })) + if (job_queue_.addJob(JtBatch, "TxBatchSync", [this]() { transactionBatch(); })) { dispatchState_ = DispatchState::Scheduled; } @@ -1401,7 +1401,7 @@ NetworkOPsImp::doTransactionSyncBatch( void NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) { - auto ev = jobQueue_.makeLoadEvent(JtTxnProc, "ProcessTXNSet"); + auto ev = job_queue_.makeLoadEvent(JtTxnProc, "ProcessTXNSet"); std::vector> candidates; candidates.reserve(set.size()); for (auto const& [_, tx] : set) @@ -1569,7 +1569,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) std::size_t count = 0; for (auto txNext = ledgerMaster_.popAcctTransaction(txCur); - txNext && count < kMaxPoppedTransactions; + txNext && count < kMAX_POPPED_TRANSACTIONS; txNext = ledgerMaster_.popAcctTransaction(txCur), ++count) { if (!batchLock.owns_lock()) @@ -1618,7 +1618,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // 1. It was submitted locally. (Note that this flag is only // true on the initial submission.) // 2. The transaction has a LastLedgerSequence, and the - // LastLedgerSequence is fewer than LocalTxs::kHoldLedgers + // LastLedgerSequence is fewer than LocalTxs::kHOLD_LEDGERS // (5) ledgers into the future. (Remember that an // unseated optional compares as less than all seated // values, so it has to be checked explicitly first.) @@ -1629,7 +1629,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // the other conditions, so don't hold it again. Time's // up!) // - if (e.local || (ledgersLeft && ledgersLeft <= LocalTxs::kHoldLedgers) || + if (e.local || (ledgersLeft && ledgersLeft <= LocalTxs::kHOLD_LEDGERS) || registry_.get().getHashRouter().setFlags( e.transaction->getID(), HashRouterFlags::HELD)) { @@ -1733,7 +1733,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) json::Value NetworkOPsImp::getOwnerInfo(std::shared_ptr lpLedger, AccountID const& account) { - json::Value jvObjects(json::ValueType::Object); + json::Value jvObjects(json::ObjectValue); auto root = keylet::ownerDir(account); auto sleNode = lpLedger->read(keylet::page(root)); if (sleNode) @@ -1751,19 +1751,18 @@ NetworkOPsImp::getOwnerInfo(std::shared_ptr lpLedger, AccountID { case ltOFFER: if (!jvObjects.isMember(jss::offers)) - jvObjects[jss::offers] = json::Value(json::ValueType::Array); + jvObjects[jss::offers] = json::Value(json::ArrayValue); - jvObjects[jss::offers].append(sleCur->getJson(JsonOptions::Values::None)); + jvObjects[jss::offers].append(sleCur->getJson(JsonOptions::KNone)); break; case ltRIPPLE_STATE: if (!jvObjects.isMember(jss::ripple_lines)) { - jvObjects[jss::ripple_lines] = json::Value(json::ValueType::Array); + jvObjects[jss::ripple_lines] = json::Value(json::ArrayValue); } - jvObjects[jss::ripple_lines].append( - sleCur->getJson(JsonOptions::Values::None)); + jvObjects[jss::ripple_lines].append(sleCur->getJson(JsonOptions::KNone)); break; case ltACCOUNT_ROOT: @@ -2114,7 +2113,7 @@ NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) // We now have an additional transaction set // Inform peers we have this set protocol::TMHaveTransactionSet msg; - msg.set_hash(map->getHash().asUInt256().begin(), 256 / 8); + msg.set_hash(map->getHash().asUint256().begin(), 256 / 8); msg.set_status(protocol::tsHAVE); registry_.get().getOverlay().foreach( SendAlways(std::make_shared(msg, protocol::mtHAVE_SET))); @@ -2196,7 +2195,7 @@ NetworkOPsImp::pubManifest(Manifest const& mo) if (!streamMaps_[SManifests].empty()) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); jvObj[jss::type] = "manifestReceived"; jvObj[jss::master_key] = toBase58(TokenType::NodePublic, mo.masterKey); @@ -2258,9 +2257,9 @@ NetworkOPsImp::ServerFeeSummary::operator!=(NetworkOPsImp::ServerFeeSummary cons static std::uint32_t trunc32(std::uint64_t v) { - constexpr std::uint64_t kMax32 = std::numeric_limits::max(); + constexpr std::uint64_t kMAX32 = std::numeric_limits::max(); - return std::min(kMax32, v); + return std::min(kMAX32, v); }; void @@ -2274,7 +2273,7 @@ NetworkOPsImp::pubServer() if (!streamMaps_[SServer].empty()) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); ServerFeeSummary f{ registry_.get().getOpenLedger().current()->fees().base, @@ -2292,7 +2291,7 @@ NetworkOPsImp::pubServer() auto const loadFactor = std::max( safeCast(f.loadFactorServer), mulDiv(f.em->openLedgerFeeLevel, f.loadBaseServer, f.em->referenceFeeLevel) - .value_or(xrpl::kMuldivMax)); + .value_or(xrpl::kMULDIV_MAX)); jvObj[jss::load_factor] = trunc32(loadFactor); jvObj[jss::load_factor_fee_escalation] = f.em->openLedgerFeeLevel.jsonClipped(); @@ -2334,7 +2333,7 @@ NetworkOPsImp::pubConsensus(ConsensusPhase phase) auto& streamMap = streamMaps_[SConsensusPhase]; if (!streamMap.empty()) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); jvObj[jss::type] = "consensusPhase"; jvObj[jss::consensus] = to_string(phase); @@ -2361,7 +2360,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (!streamMaps_[SValidations].empty()) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); auto const signerPublic = val->getSignerPublic(); @@ -2396,7 +2395,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (val->isFieldPresent(sfAmendments)) { - jvObj[jss::amendments] = json::Value(json::ValueType::Array); + jvObj[jss::amendments] = json::Value(json::ArrayValue); for (auto const& amendment : val->getFieldV256(sfAmendments)) jvObj[jss::amendments].append(to_string(amendment)); } @@ -2433,7 +2432,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) // for consumers supporting different API versions MultiApiJson multiObj{jvObj}; multiObj.visit( - RPC::kApiVersion<1>, // + RPC::kAPI_VERSION<1>, // [](json::Value& jvTx) { // Type conversion for older API versions to string if (jvTx.isMember(jss::ledger_index)) @@ -2571,7 +2570,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str // We will always relay trusted validations; if configured, we will // also relay all untrusted validations. - return registry_.get().getApp().config().relayUntrustedValidations == 1 || val->isTrusted(); + return registry_.get().getApp().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); } json::Value @@ -2583,14 +2582,14 @@ NetworkOPsImp::getConsensusInfo() json::Value NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { - json::Value info = json::ValueType::Object; + json::Value info = json::ObjectValue; // System-level warnings { - json::Value warnings{json::ValueType::Array}; + json::Value warnings{json::ArrayValue}; if (isAmendmentBlocked()) { - json::Value& w = warnings.append(json::ValueType::Object); + json::Value& w = warnings.append(json::ObjectValue); w[jss::id] = WarnRpcAmendmentBlocked; w[jss::message] = "This server is amendment blocked, and must be updated to be " @@ -2598,7 +2597,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } if (isUNLBlocked()) { - json::Value& w = warnings.append(json::ValueType::Object); + json::Value& w = warnings.append(json::ObjectValue); w[jss::id] = WarnRpcExpiredValidatorList; w[jss::message] = "This server has an expired validator list. validators.txt " @@ -2607,7 +2606,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } if (admin && isAmendmentWarned()) { - json::Value& w = warnings.append(json::ValueType::Object); + json::Value& w = warnings.append(json::ObjectValue); w[jss::id] = WarnRpcUnsupportedMajority; w[jss::message] = "One or more unsupported amendments have reached majority. " @@ -2616,7 +2615,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (auto const expected = registry_.get().getAmendmentTable().firstUnsupportedExpected()) { - auto& d = w[jss::details] = json::ValueType::Object; + auto& d = w[jss::details] = json::ObjectValue; d[jss::expected_date] = expected->time_since_epoch().count(); d[jss::expected_date_UTC] = to_string(*expected); } @@ -2631,8 +2630,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!registry_.get().getApp().config().serverDomain.empty()) - info[jss::server_domain] = registry_.get().getApp().config().serverDomain; + if (!registry_.get().getApp().config().SERVER_DOMAIN.empty()) + info[jss::server_domain] = registry_.get().getApp().config().SERVER_DOMAIN; info[jss::build_version] = BuildInfo::getVersionString(); @@ -2652,7 +2651,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) // Note: By default the node size is "tiny". When parsing it's an error if the final // NODE_SIZE is over 4 so below code should be safe. // NOLINTNEXTLINE(bugprone-switch-missing-default-case) - switch (registry_.get().getApp().config().nodeSize) + switch (registry_.get().getApp().config().NODE_SIZE) { case 0: info[jss::node_size] = "tiny"; @@ -2687,7 +2686,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } else { - auto& x = (info[jss::validator_list] = json::ValueType::Object); + auto& x = (info[jss::validator_list] = json::ObjectValue); x[jss::count] = static_cast(registry_.get().getValidators().count()); @@ -2721,7 +2720,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (!xrpl::git::getCommitHash().empty() || !xrpl::git::getBuildBranch().empty()) { - auto& x = (info[jss::git] = json::ValueType::Object); + auto& x = (info[jss::git] = json::ObjectValue); if (!xrpl::git::getCommitHash().empty()) x[jss::hash] = xrpl::git::getCommitHash(); if (!xrpl::git::getBuildBranch().empty()) @@ -2748,7 +2747,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { info[jss::counters] = registry_.get().getPerfLog().countersJson(); - json::Value nodestore(json::ValueType::Object); + json::Value nodestore(json::ObjectValue); registry_.get().getNodeStore().getCountsJson(nodestore); info[jss::counters][jss::nodestore] = nodestore; info[jss::current_activities] = registry_.get().getPerfLog().currentJson(); @@ -2769,7 +2768,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::peers] = json::UInt(registry_.get().getOverlay().size()); - json::Value lastClose = json::ValueType::Object; + json::Value lastClose = json::ObjectValue; lastClose[jss::proposers] = json::UInt(consensus_.prevProposers()); if (human) @@ -2787,7 +2786,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) // info[jss::consensus] = consensus_.getJson(); if (admin) - info[jss::load] = jobQueue_.getJson(); + info[jss::load] = job_queue_.getJson(); if (auto const netid = registry_.get().getOverlay().networkID()) info[jss::network_id] = static_cast(*netid); @@ -2804,7 +2803,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) escalationMetrics.openLedgerFeeLevel, loadBaseServer, escalationMetrics.referenceFeeLevel) - .value_or(xrpl::kMuldivMax); + .value_or(xrpl::kMULDIV_MAX); auto const loadFactor = std::max(safeCast(loadFactorServer), loadFactorFeeEscalation); @@ -2873,7 +2872,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (lpClosed) { XRPAmount const baseFee = lpClosed->fees().base; - json::Value l(json::ValueType::Object); + json::Value l(json::ObjectValue); l[jss::seq] = json::UInt(lpClosed->header().seq); l[jss::hash] = to_string(lpClosed->header().hash); @@ -2895,11 +2894,11 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) std::abs(closeOffset.count()) >= 60) l[jss::close_time_offset] = static_cast(closeOffset.count()); - static constexpr std::chrono::seconds kHighAgeThreshold{1000000}; + constexpr std::chrono::seconds kHIGH_AGE_THRESHOLD{1000000}; if (ledgerMaster_.haveValidated()) { auto const age = ledgerMaster_.getValidatedLedgerAge(); - l[jss::age] = json::UInt(age < kHighAgeThreshold ? age.count() : 0); + l[jss::age] = json::UInt(age < kHIGH_AGE_THRESHOLD ? age.count() : 0); } else { @@ -2909,7 +2908,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { using namespace std::chrono_literals; auto age = closeTime - lCloseTime; - l[jss::age] = json::UInt(age < kHighAgeThreshold ? age.count() : 0); + l[jss::age] = json::UInt(age < kHIGH_AGE_THRESHOLD ? age.count() : 0); } } } @@ -2943,31 +2942,31 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) std::to_string(registry_.get().getOverlay().getPeerDisconnectCharges()); // This array must be sorted in increasing order. - static constexpr std::array kProtocols{ + static constexpr std::array kPROTOCOLS{ "http", "https", "peer", "ws", "ws2", "wss", "wss2"}; - static_assert(std::ranges::is_sorted(kProtocols)); + static_assert(std::ranges::is_sorted(kPROTOCOLS)); { - json::Value ports{json::ValueType::Array}; + json::Value ports{json::ArrayValue}; for (auto const& port : registry_.get().getServerHandler().setup().ports) { // Don't publish admin ports for non-admin users if (!admin && - !(port.adminNetsV4.empty() && port.adminNetsV6.empty() && port.adminUser.empty() && - port.adminPassword.empty())) + !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() && + port.admin_user.empty() && port.admin_password.empty())) continue; std::vector proto; // NOLINTNEXTLINE(modernize-use-ranges) std::set_intersection( std::begin(port.protocol), std::end(port.protocol), - std::begin(kProtocols), - std::end(kProtocols), + std::begin(kPROTOCOLS), + std::end(kPROTOCOLS), std::back_inserter(proto)); if (!proto.empty()) { - auto& jv = ports.append(json::Value(json::ValueType::Object)); + auto& jv = ports.append(json::Value(json::ObjectValue)); jv[jss::port] = std::to_string(port.port); - jv[jss::protocol] = json::Value{json::ValueType::Array}; + jv[jss::protocol] = json::Value{json::ArrayValue}; for (auto const& p : proto) jv[jss::protocol].append(p); } @@ -2979,9 +2978,9 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) auto const optPort = grpcSection.get("port"); if (optPort && grpcSection.get("ip")) { - auto& jv = ports.append(json::Value(json::ValueType::Object)); + auto& jv = ports.append(json::Value(json::ObjectValue)); jv[jss::port] = *optPort; - jv[jss::protocol] = json::Value{json::ValueType::Array}; + jv[jss::protocol] = json::Value{json::ArrayValue}; jv[jss::protocol].append("grpc"); } } @@ -3016,7 +3015,7 @@ NetworkOPsImp::pubProposedTransaction( if (transaction->isFlag(tfInnerBatchTxn)) return; - MultiApiJson const jvObj = transJson(transaction, result, false, ledger, std::nullopt); + MultiApiJson jvObj = transJson(transaction, result, false, ledger, std::nullopt); { std::scoped_lock const sl(subLock_); @@ -3070,7 +3069,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) if (!streamMaps_[SLedger].empty()) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); jvObj[jss::type] = "ledgerClosed"; jvObj[jss::ledger_index] = lpAccepted->header().seq; @@ -3081,7 +3080,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) jvObj[jss::network_id] = registry_.get().getNetworkIDService().getNetworkID(); if (!lpAccepted->rules().enabled(featureXRPFees)) - jvObj[jss::fee_ref] = kFeeUnitsDeprecated; + jvObj[jss::fee_ref] = kFEE_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(); @@ -3131,11 +3130,11 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) } { - static bool kFirstTime = true; - if (kFirstTime) + static bool kFIRST_TIME = true; + if (kFIRST_TIME) { // First validated ledger, start delayed SubAccountHistory - kFirstTime = false; + kFIRST_TIME = false; for (auto& outer : subAccountHistory_) { for (auto& inner : outer.second) @@ -3170,14 +3169,14 @@ NetworkOPsImp::reportFeeChange() // only schedule the job if something has changed if (f != lastFeeSummary_) { - jobQueue_.addJob(JtClientFeeChange, "PubFee", [this]() { pubServer(); }); + job_queue_.addJob(JtClientFeeChange, "PubFee", [this]() { pubServer(); }); } } void NetworkOPsImp::reportConsensusStateChange(ConsensusPhase phase) { - jobQueue_.addJob(JtClientConsensus, "PubCons", [this, phase]() { pubConsensus(phase); }); + job_queue_.addJob(JtClientConsensus, "PubCons", [this, phase]() { pubConsensus(phase); }); } inline void @@ -3201,7 +3200,7 @@ NetworkOPsImp::transJson( std::shared_ptr const& ledger, std::optional> meta) { - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); std::string sToken; std::string sHuman; @@ -3211,11 +3210,11 @@ 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::Values::DisableApiPriorV2, false); + jvObj[jss::transaction] = transaction->getJson(JsonOptions::KDisableApiPriorV2, false); if (meta) { - jvObj[jss::meta] = meta->get().getJson(JsonOptions::Values::None); + jvObj[jss::meta] = meta->get().getJson(JsonOptions::KNone); RPC::insertDeliveredAmount(jvObj[jss::meta], *ledger, transaction, meta->get()); RPC::insertNFTSyntheticInJson(jvObj, transaction, meta->get()); RPC::insertMPTokenIssuanceID(jvObj[jss::meta], transaction, meta->get()); @@ -3308,7 +3307,7 @@ NetworkOPsImp::pubValidatedTransaction( // Create two different Json objects, for different API versions auto const metaRef = std::ref(transaction.getMeta()); auto const trResult = transaction.getResult(); - MultiApiJson const jvObj = transJson(stTxn, trResult, true, ledger, metaRef); + MultiApiJson jvObj = transJson(stTxn, trResult, true, ledger, metaRef); { std::scoped_lock const sl(subLock_); @@ -3669,7 +3668,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) * genesis account: first tx is the one with seq 1 * other account: first tx is the one created the account */ - if (accountId == kGenesisAccountId) + if (accountId == kGENESIS_ACCOUNT_ID) { auto stx = tx->getSTransaction(); if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) @@ -3749,7 +3748,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) int feeChargeCount = 0; if (auto sptr = subInfo.sinkWptr.lock(); sptr) { - sptr->getConsumer().charge(Resource::kFeeMediumBurdenRpc); + sptr->getConsumer().charge(Resource::kFEE_MEDIUM_BURDEN_RPC); ++feeChargeCount; } else @@ -3894,7 +3893,7 @@ NetworkOPsImp::subAccountHistoryStart( << ", no need to add AccountHistory job."; return; } - if (accountId == kGenesisAccountId) + if (accountId == kGENESIS_ACCOUNT_ID) { if (auto const sleAcct = ledger->read(accountKeylet); sleAcct) { @@ -4060,7 +4059,7 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, json::Value& jvResult) jvResult[jss::ledger_time] = json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); if (!lpClosed->rules().enabled(featureXRPFees)) - jvResult[jss::fee_ref] = kFeeUnitsDeprecated; + jvResult[jss::fee_ref] = kFEE_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(); @@ -4293,7 +4292,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::ValueType::Array)); + json::Value& jvOffers = (jvResult[jss::offers] = json::Value(json::ArrayValue)); std::unordered_map umBalance; uint256 const uBookBase = getBookBase(book); @@ -4316,7 +4315,7 @@ NetworkOPsImp::getBookPage( bool bDone = false; bool bDirectAdvance = true; - SLE::const_pointer sleOfferDir; + std::shared_ptr sleOfferDir; uint256 offerIndex; unsigned int uBookEntry = 0; STAmount saDirRate; @@ -4405,7 +4404,7 @@ NetworkOPsImp::getBookPage( AuthHandling::ZeroIfUnauthorized, viewJ); - if (saOwnerFunds < beast::kZero) + if (saOwnerFunds < beast::kZERO) { // Treat negative funds as zero. @@ -4414,13 +4413,13 @@ NetworkOPsImp::getBookPage( } } - json::Value jvOffer = sleOffer->getJson(JsonOptions::Values::None); + json::Value jvOffer = sleOffer->getJson(JsonOptions::KNone); STAmount saTakerGetsFunded; STAmount saOwnerFundsLimit = saOwnerFunds; - Rate offerRate = kParityRate; + Rate offerRate = kPARITY_RATE; - if (rate != kParityRate + if (rate != kPARITY_RATE // Have a transfer fee. && uTakerID != book.out.getIssuer() // Not taking offers of own IOUs. @@ -4449,7 +4448,7 @@ NetworkOPsImp::getBookPage( .setJson(jvOffer[jss::taker_pays_funded]); } - STAmount const saOwnerPays = (kParityRate == offerRate) + STAmount const saOwnerPays = (kPARITY_RATE == offerRate) ? saTakerGetsFunded : std::min(saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); @@ -4478,8 +4477,8 @@ NetworkOPsImp::getBookPage( } } - // jvResult[jss::marker] = json::Value(json::ValueType::Array); - // jvResult[jss::nodes] = json::Value(json::ValueType::Array); + // jvResult[jss::marker] = json::Value(json::arrayValue); + // jvResult[jss::nodes] = json::Value(json::arrayValue); } #else @@ -4497,7 +4496,7 @@ NetworkOPsImp::getBookPage( json::Value const& jvMarker, json::Value& jvResult) { - auto& jvOffers = (jvResult[jss::offers] = json::Value(json::ValueType::Array)); + auto& jvOffers = (jvResult[jss::offers] = json::Value(json::arrayValue)); std::map umBalance; @@ -4549,7 +4548,7 @@ NetworkOPsImp::getBookPage( uOfferOwnerID, book.out.currency, book.out.account, - FreezeHandling::ZeroIfFrozen); + FreezeHandling::fhZERO_IF_FROZEN); if (saOwnerFunds.isNegative()) { @@ -4560,7 +4559,7 @@ NetworkOPsImp::getBookPage( } } - json::Value jvOffer = sleOffer->getJson(JsonOptions::Values::None); + json::Value jvOffer = sleOffer->getJson(JsonOptions::KNone); STAmount saTakerGetsFunded; STAmount saOwnerFundsLimit = saOwnerFunds; @@ -4611,8 +4610,8 @@ NetworkOPsImp::getBookPage( } } - // jvResult[jss::marker] = json::Value(json::ValueType::Array); - // jvResult[jss::nodes] = json::Value(json::ValueType::Array); + // jvResult[jss::marker] = json::Value(json::arrayValue); + // jvResult[jss::nodes] = json::Value(json::arrayValue); } #endif @@ -4626,25 +4625,26 @@ NetworkOPsImp::collectMetrics() counters[static_cast(mode)].dur += current; std::scoped_lock const lock(statsMutex_); - stats_.disconnectedDuration.set( + stats_.disconnected_duration.set( counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); - stats_.connectedDuration.set( + stats_.connected_duration.set( counters[static_cast(OperatingMode::CONNECTED)].dur.count()); - stats_.syncingDuration.set( + stats_.syncing_duration.set( counters[static_cast(OperatingMode::SYNCING)].dur.count()); - stats_.trackingDuration.set( + stats_.tracking_duration.set( counters[static_cast(OperatingMode::TRACKING)].dur.count()); - stats_.fullDuration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); + stats_.full_duration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); - stats_.disconnectedTransitions.set( + stats_.disconnected_transitions.set( counters[static_cast(OperatingMode::DISCONNECTED)].transitions); - stats_.connectedTransitions.set( + stats_.connected_transitions.set( counters[static_cast(OperatingMode::CONNECTED)].transitions); - stats_.syncingTransitions.set( + stats_.syncing_transitions.set( counters[static_cast(OperatingMode::SYNCING)].transitions); - stats_.trackingTransitions.set( + stats_.tracking_transitions.set( counters[static_cast(OperatingMode::TRACKING)].transitions); - stats_.fullTransitions.set(counters[static_cast(OperatingMode::FULL)].transitions); + stats_.full_transitions.set( + counters[static_cast(OperatingMode::FULL)].transitions); } void @@ -4674,13 +4674,13 @@ NetworkOPsImp::StateAccounting::json(json::Value& obj) const std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; - obj[jss::state_accounting] = json::ValueType::Object; + obj[jss::state_accounting] = json::ObjectValue; for (std::size_t i = static_cast(OperatingMode::DISCONNECTED); i <= static_cast(OperatingMode::FULL); ++i) { - obj[jss::state_accounting][kStates[i]] = json::ValueType::Object; - auto& state = obj[jss::state_accounting][kStates[i]]; + obj[jss::state_accounting][kSTATES[i]] = json::ObjectValue; + auto& state = obj[jss::state_accounting][kSTATES[i]]; state[jss::transitions] = std::to_string(counters[i].transitions); state[jss::duration_us] = std::to_string(counters[i].dur.count()); } diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 3f4bd6280f..6fa1fbda61 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -116,7 +116,7 @@ SHAMapStoreImp::SHAMapStoreImp( section.set("cache_mb", std::to_string(config.getValueFor(SizedItem::HashNodeDbCache))); } - if (!section.exists("filter_bits") && (config.nodeSize >= 2)) + if (!section.exists("filter_bits") && (config.NODE_SIZE >= 2)) section.set("filter_bits", "10"); } @@ -141,22 +141,22 @@ SHAMapStoreImp::SHAMapStoreImp( getIfExists(section, "advisory_delete", advisoryDelete_); auto const minInterval = - config.standalone() ? kMinimumDeletionIntervalSa : kMinimumDeletionInterval; + config.standalone() ? kMINIMUM_DELETION_INTERVAL_SA : kMINIMUM_DELETION_INTERVAL; if (deleteInterval_ < minInterval) { Throw( "online_delete must be at least " + std::to_string(minInterval)); } - if (config.ledgerHistory > deleteInterval_) + if (config.LEDGER_HISTORY > deleteInterval_) { Throw( "online_delete must not be less than ledger_history " "(currently " + - std::to_string(config.ledgerHistory) + ")"); + std::to_string(config.LEDGER_HISTORY) + ")"); } - stateDb_.init(config, dbName_); + state_db_.init(config, dbName_); dbPaths(); } } @@ -165,34 +165,18 @@ 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_ != 0u) { - SavedState state = stateDb_.getState(); + SavedState state = state_db_.getState(); auto writableBackend = makeBackendRotating(state.writableDb); auto archiveBackend = makeBackendRotating(state.archiveDb); if (state.writableDb.empty()) { state.writableDb = writableBackend->getName(); state.archiveDb = archiveBackend->getName(); - stateDb_.setState(state); + state_db_.setState(state); } // Create NodeStore with two backends to allow online deletion of @@ -203,7 +187,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) std::move(writableBackend), std::move(archiveBackend), nscfg, - app_.getJournal(kNodeStoreName)); + app_.getJournal(kNODE_STORE_NAME)); fdRequired_ += dbr->fdRequired(); dbRotating_ = dbr.get(); db.reset(dynamic_cast(dbr.release())); @@ -215,7 +199,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) scheduler_, readThreads, nscfg, - app_.getJournal(kNodeStoreName)); + app_.getJournal(kNODE_STORE_NAME)); fdRequired_ += db->fdRequired(); } return db; @@ -253,7 +237,7 @@ SHAMapStoreImp::copyNode(std::uint64_t& nodeCount, SHAMapTreeNode const& node) { // Copy a single record from node to dbRotating_ dbRotating_->fetchNodeObject( - node.getHash().asUInt256(), 0, NodeStore::FetchType::Synchronous, true); + node.getHash().asUint256(), 0, NodeStore::FetchType::Synchronous, true); if ((++nodeCount % checkHealthInterval_) == 0u) { if (healthWait() == HealthResult::Stopping) @@ -267,14 +251,12 @@ void SHAMapStoreImp::run() { beast::setCurrentThreadName("SHAMapStore"); - LedgerIndex lastRotated = stateDb_.getState().lastRotated; + LedgerIndex lastRotated = state_db_.getState().lastRotated; netOPs_ = &app_.getOPs(); ledgerMaster_ = &app_.getLedgerMaster(); - fullBelowCache_ = &(*app_.getNodeFamily().getFullBelowCache()); - treeNodeCache_ = &(*app_.getNodeFamily().getTreeNodeCache()); if (advisoryDelete_) - canDelete_ = stateDb_.getCanDelete(); + canDelete_ = state_db_.getCanDelete(); while (true) { @@ -304,7 +286,7 @@ SHAMapStoreImp::run() if (lastRotated == 0u) { lastRotated = validatedSeq; - stateDb_.setLastRotated(lastRotated); + state_db_.setLastRotated(lastRotated); } bool const readyToRotate = validatedSeq >= lastRotated + deleteInterval_ && @@ -372,7 +354,7 @@ SHAMapStoreImp::run() savedState.writableDb = writableName; savedState.archiveDb = archiveName; savedState.lastRotated = lastRotated; - stateDb_.setState(savedState); + state_db_.setState(savedState); clearCaches(validatedSeq); }); @@ -401,7 +383,7 @@ SHAMapStoreImp::dbPaths() boost::filesystem::create_directories(dbPath); } - SavedState state = stateDb_.getState(); + SavedState state = state_db_.getState(); { auto update = [&dbPath](std::string& sPath) { @@ -421,7 +403,7 @@ SHAMapStoreImp::dbPaths() if (update(state.writableDb)) { update(state.archiveDb); - stateDb_.setState(state); + state_db_.setState(state); } } @@ -500,7 +482,7 @@ SHAMapStoreImp::makeBackendRotating(std::string path) section, megabytes(app_.config().getValueFor(SizedItem::BurstSize, std::nullopt)), scheduler_, - app_.getJournal(kNodeStoreName))}; + app_.getJournal(kNODE_STORE_NAME))}; backend->open(); return backend; } @@ -560,16 +542,16 @@ SHAMapStoreImp::clearCaches(LedgerIndex validatedSeq) // 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. - fullBelowCache_->clear(); + 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 diff --git a/src/xrpld/app/misc/SHAMapStoreImp.h b/src/xrpld/app/misc/SHAMapStoreImp.h index 1803c15e71..c205d2dd90 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.h +++ b/src/xrpld/app/misc/SHAMapStoreImp.h @@ -7,8 +7,6 @@ #include #include #include -#include -#include #include #include @@ -59,16 +57,16 @@ private: // check health/stop status as records are copied std::uint64_t const checkHealthInterval_ = 1000; // minimum # of ledgers to maintain for health of network - static std::uint32_t const kMinimumDeletionInterval = 256; + static std::uint32_t const kMINIMUM_DELETION_INTERVAL = 256; // minimum # of ledgers required for standalone mode. - static std::uint32_t const kMinimumDeletionIntervalSa = 8; + static std::uint32_t const kMINIMUM_DELETION_INTERVAL_SA = 8; // minimum ledger to maintain online. std::atomic minimumOnline_; NodeStore::Scheduler& scheduler_; beast::Journal const journal_; NodeStore::DatabaseRotating* dbRotating_ = nullptr; - SavedStateDB stateDb_; + SavedStateDB state_db_; std::thread thread_; bool stop_ = false; bool healthy_ = true; @@ -95,10 +93,8 @@ private: // as of run() or before NetworkOPs* netOPs_ = nullptr; LedgerMaster* ledgerMaster_ = nullptr; - FullBelowCache* fullBelowCache_ = nullptr; - TreeNodeCache* treeNodeCache_ = nullptr; - static constexpr auto kNodeStoreName = "NodeStore"; + static constexpr auto kNODE_STORE_NAME = "NodeStore"; public: SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal); @@ -117,7 +113,7 @@ public: { if (advisoryDelete_) canDelete_ = seq; - return stateDb_.setCanDelete(seq); + return state_db_.setCanDelete(seq); } bool @@ -131,7 +127,7 @@ public: LedgerIndex getLastRotated() override { - return stateDb_.getState().lastRotated; + return state_db_.getState().lastRotated; } // All ledgers before and including this are unprotected diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index d3caec55cf..4cd73acaec 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -40,7 +40,7 @@ class TxQ { public: /// Fee level for single-signed reference transaction. - static constexpr FeeLevel64 kBaseLevel{256}; + static constexpr FeeLevel64 kBASE_LEVEL{256}; /** Structure used to customize @ref TxQ behavior. @@ -76,7 +76,7 @@ public: std::uint32_t retrySequencePercent = 25; /// Minimum value of the escalation multiplier, regardless /// of the prior ledger's median fee level. - FeeLevel64 minimumEscalationMultiplier = kBaseLevel * 500; + FeeLevel64 minimumEscalationMultiplier = kBASE_LEVEL * 500; /// Minimum number of transactions to allow into the ledger /// before escalation, regardless of the prior ledger's size. std::uint32_t minimumTxnInLedger = 32; @@ -288,7 +288,7 @@ public: /** Return the next sequence that would go in the TxQ for an account. */ SeqProxy - nextQueuableSeq(SLE::const_ref sleAccount) const; + nextQueuableSeq(std::shared_ptr const& sleAccount) const; /** Returns fee metrics in reference fee level units. */ @@ -342,7 +342,9 @@ public: private: // Implementation for nextQueuableSeq(). The passed lock must be held. SeqProxy - nextQueuableSeqImpl(SLE::const_ref sleAccount, std::scoped_lock const&) const; + nextQueuableSeqImpl( + std::shared_ptr const& sleAccount, + std::scoped_lock const&) const; /** Track and use the fee escalation metrics of the @@ -510,7 +512,7 @@ private: their `retriesRemaining` forced down as part of the penalty. */ - int retriesRemaining{kRetriesAllowed}; + int retriesRemaining{kRETRIES_ALLOWED}; /// Flags provided to `apply`. If the transaction is later /// attempted with different flags, it will need to be /// `preflight`ed again. @@ -546,7 +548,7 @@ private: that the queue doesn't fill up with stale transactions which prevent lower fee level transactions from queuing. */ - static constexpr int kRetriesAllowed = 10; + static constexpr int kRETRIES_ALLOWED = 10; /** The hash of the parent ledger. @@ -759,7 +761,7 @@ private: /** parentHash_ used for logging only */ - LedgerHash parentHash_{beast::kZero}; + LedgerHash parentHash_{beast::kZERO}; /** Most queue operations are done under the master lock, but use this mutex for the RPC "fee" command, which isn't. @@ -780,7 +782,7 @@ private: STTx const&, ApplyFlags const, OpenView const&, - SLE::const_ref sleAccount, + std::shared_ptr const& sleAccount, AccountMap::iterator const&, std::optional const&, std::scoped_lock const& lock); @@ -829,13 +831,13 @@ template XRPAmount toDrops(FeeLevel const& level, XRPAmount baseFee) { - return mulDiv(level, baseFee, TxQ::kBaseLevel).value_or(XRPAmount(STAmount::kMaxNativeN)); + return mulDiv(level, baseFee, TxQ::kBASE_LEVEL).value_or(XRPAmount(STAmount::kMAX_NATIVE_N)); } inline FeeLevel64 toFeeLevel(XRPAmount const& drops, XRPAmount const& baseFee) { - return mulDiv(drops, TxQ::kBaseLevel, baseFee) + return mulDiv(drops, TxQ::kBASE_LEVEL, baseFee) .value_or(FeeLevel64(std::numeric_limits::max())); } diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index dcd7a24499..5f051fe527 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -246,12 +246,12 @@ class ValidatorList hash_set negativeUNL_; // Currently supported versions of publisher list format - static constexpr std::uint32_t kSupportedListVersions[]{1, 2}; + static constexpr std::uint32_t kSUPPORTED_LIST_VERSIONS[]{1, 2}; // In the initial release, to prevent potential abuse and attacks, any VL // collection with more than 5 entries will be considered malformed. - static constexpr std::size_t kMaxSupportedBlobs = 5; + static constexpr std::size_t kMAX_SUPPORTED_BLOBS = 5; // Prefix of the file name used to store cache files. - static std::string const kFilePrefix; + static std::string const kFILE_PREFIX; public: ValidatorList( @@ -360,7 +360,7 @@ public: std::string const& rawManifest, std::map const& blobInfos, std::vector& messages, - std::size_t maxSize = kMaximumMessageSize); + std::size_t maxSize = kMAXIMUM_MESSAGE_SIZE); /** Apply multiple published lists of public keys, then broadcast it to all peers that have not seen it or sent it. diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index 55f060baf1..c4d2545217 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -96,10 +96,10 @@ private: Application& app_; beast::Journal const j_; - // If both mutex are to be locked at the same time, `sitesMutex_` must be - // locked before `stateMutex_` or we may deadlock. - std::mutex mutable sitesMutex_; - std::mutex mutable stateMutex_; + // If both mutex are to be locked at the same time, `sites_mutex_` must be + // locked before `state_mutex_` or we may deadlock. + std::mutex mutable sites_mutex_; + std::mutex mutable state_mutex_; std::condition_variable cv_; std::weak_ptr work_; diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 65771f6aa3..56b97d3f7e 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -24,7 +24,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include #include @@ -49,7 +49,7 @@ namespace xrpl { static std::vector> parseSection(Section const& section) { - static boost::regex const kRe1( + static boost::regex const kRE1( "^" // start of line "(?:\\s*)" // whitespace (optional) "([abcdefABCDEF0-9]{64})" // @@ -64,7 +64,7 @@ parseSection(Section const& section) { boost::smatch match; - if (!boost::regex_match(line, match, kRe1)) + if (!boost::regex_match(line, match, kRE1)) Throw("Invalid entry '" + line + "' in [" + section.name() + "]"); uint256 id; @@ -176,9 +176,9 @@ public: // from that validator. So flapping due to that validator being off // line will happen less frequently than every 24 hours. using namespace std::chrono_literals; - static constexpr NetClock::duration kExpiresAfter = 24h; + static constexpr NetClock::duration kEXPIRES_AFTER = 24h; - auto const newTimeout = closeTime + kExpiresAfter; + auto const newTimeout = closeTime + kEXPIRES_AFTER; // Walk all validations and replace previous votes from trusted // validators with these newest votes. @@ -330,8 +330,8 @@ public: threshold_ = std::max( 1L, static_cast( - (trustedValidations_ * kAmendmentMajorityCalcThreshold.num) / - kAmendmentMajorityCalcThreshold.den)); + (trustedValidations_ * kAMENDMENT_MAJORITY_CALC_THRESHOLD.num) / + kAMENDMENT_MAJORITY_CALC_THRESHOLD.den)); } [[nodiscard]] bool @@ -983,17 +983,13 @@ AmendmentTableImpl::injectJson( json::Value AmendmentTableImpl::getJson(bool isAdmin) const { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); { std::scoped_lock const lock(mutex_); for (auto const& e : amendmentMap_) { injectJson( - ret[to_string(e.first)] = json::ValueType::Object, - e.first, - e.second, - isAdmin, - lock); + ret[to_string(e.first)] = json::ObjectValue, e.first, e.second, isAdmin, lock); } } return ret; @@ -1002,14 +998,14 @@ AmendmentTableImpl::getJson(bool isAdmin) const json::Value AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const { - json::Value ret = json::ValueType::Object; + json::Value ret = json::ObjectValue; { std::scoped_lock const lock(mutex_); AmendmentState const* a = get(amendmentID, lock); if (a != nullptr) { - json::Value& jAmendment = (ret[to_string(amendmentID)] = json::ValueType::Object); + json::Value& jAmendment = (ret[to_string(amendmentID)] = json::ObjectValue); injectJson(jAmendment, amendmentID, *a, isAdmin, lock); } } diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 425a5723fb..2975a5f622 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -20,7 +20,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include @@ -150,14 +150,12 @@ json::Value Transaction::getJson(JsonOptions options, bool binary) const { // Note, we explicitly suppress `include_date` option here - json::Value ret(transaction_->getJson( - options & ~static_cast(JsonOptions::Values::IncludeDate), - binary)); + json::Value ret(transaction_->getJson(options & ~JsonOptions::KIncludeDate, binary)); // NOTE Binary STTx::getJson output might not be a JSON object if (ret.isObject() && (ledgerIndex_ != 0u)) { - if (!(options & JsonOptions::Values::DisableApiPriorV2)) + if (!(options & JsonOptions::KDisableApiPriorV2)) { // Behaviour before API version 2 ret[jss::inLedger] = ledgerIndex_; @@ -167,7 +165,7 @@ Transaction::getJson(JsonOptions options, bool binary) const // `ledger_index` elements (taking precedence over include_date) ret[jss::ledger_index] = ledgerIndex_; - if (options & JsonOptions::Values::IncludeDate) + if (options & JsonOptions::KIncludeDate) { auto ct = app_.getLedgerMaster().getCloseTimeBySeq(ledgerIndex_); if (ct) diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index c12632875d..8b478f964e 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -77,7 +77,7 @@ getFeeLevelPaid(ReadView const& view, STTx const& tx) return FeeLevel64(0); } - return mulDiv(effectiveFeePaid, TxQ::kBaseLevel, baseFee) + return mulDiv(effectiveFeePaid, TxQ::kBASE_LEVEL, baseFee) .value_or(FeeLevel64(std::numeric_limits::max())); } @@ -93,7 +93,7 @@ static FeeLevel64 increase(FeeLevel64 level, std::uint32_t increasePercent) { return mulDiv(level, 100 + increasePercent, 100) - .value_or(static_cast(xrpl::kMuldivMax)); + .value_or(static_cast(xrpl::kMULDIV_MAX)); } ////////////////////////////////////////////////////////////////////////// @@ -130,15 +130,15 @@ TxQ::FeeMetrics::update( // upperLimit must be >= minimumTxnCount_ or std::clamp can give // unexpected results auto const upperLimit = std::max( - mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::kMuldivMax), minimumTxnCount_); + mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::kMULDIV_MAX), minimumTxnCount_); txnsExpected_ = std::clamp( - mulDiv(size, cutPct, 100).value_or(xrpl::kMuldivMax), minimumTxnCount_, upperLimit); + mulDiv(size, cutPct, 100).value_or(xrpl::kMULDIV_MAX), minimumTxnCount_, upperLimit); recentTxnCounts_.clear(); } else if (size > txnsExpected_ || size > targetTxnCount_) { recentTxnCounts_.push_back(mulDiv(size, 100 + setup.normalConsensusIncreasePercent, 100) - .value_or(xrpl::kMuldivMax)); + .value_or(xrpl::kMULDIV_MAX)); auto const iter = std::ranges::max_element(recentTxnCounts_); BOOST_ASSERT(iter != recentTxnCounts_.end()); auto const next = [&] { @@ -150,7 +150,7 @@ TxQ::FeeMetrics::update( // current size limit, use a limit that is // 90% of the way from max_element to the // current size limit. - return ((txnsExpected_ * 9) + *iter) / 10; + return (txnsExpected_ * 9 + *iter) / 10; }(); // Ledgers are processing in a timely manner, // so keep the limit high, but don't let it @@ -194,15 +194,15 @@ TxQ::FeeMetrics::scaleFeeLevel(Snapshot const& snapshot, OpenView const& view) // Compute escalated fee level // Don't care about the overflow flag return mulDiv(multiplier, current * current, target * target) - .value_or(static_cast(xrpl::kMuldivMax)); + .value_or(static_cast(xrpl::kMULDIV_MAX)); } - return kBaseLevel; + return kBASE_LEVEL; } namespace detail { -static constexpr std::pair +constexpr static std::pair sumOfFirstSquares(std::size_t xIn) { // sum(n = 1->x) : n * n = x(x + 1)(2x + 1) / 6 @@ -218,7 +218,7 @@ sumOfFirstSquares(std::size_t xIn) // in a ledger, this is the least of our problems. if (x >= (1 << 21)) return {false, std::numeric_limits::max()}; - return {true, (x * (x + 1) * ((2 * x) + 1)) / 6}; + return {true, (x * (x + 1) * (2 * x + 1)) / 6}; } // Unit tests for sumOfSquares() @@ -387,7 +387,7 @@ TxQ::canBeHeld( STTx const& tx, ApplyFlags const flags, OpenView const& view, - SLE::const_ref sleAccount, + std::shared_ptr const& sleAccount, AccountMap::iterator const& accountIter, std::optional const& replacementIter, std::scoped_lock const& lock) @@ -395,7 +395,7 @@ TxQ::canBeHeld( // PreviousTxnID is deprecated and should never be used. // AccountTxnID is not supported by the transaction // queue yet, but should be added in the future. - // TapFailHard transactions are never held + // tapFAIL_HARD transactions are never held if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || ((flags & TapFailHard) != 0u)) return telCAN_NOT_QUEUE; @@ -744,9 +744,6 @@ TxQ::apply( if (auto directApplied = tryDirectApply(app, view, tx, flags, j)) return *directApplied; - if ((flags & TapDryRun) != 0u) - return {telCAN_NOT_QUEUE, false}; - // If we get past tryDirectApply() without returning then we expect // one of the following to occur: // @@ -764,7 +761,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::kTicket(account, txSeqProx))) + if (txSeqProx.isTicket() && !view.exists(keylet::kTICKET(account, txSeqProx))) { if (txSeqProx.value() < acctSeqProx.value()) { @@ -1030,8 +1027,8 @@ TxQ::apply( // Sum fees and spending for all of the queued transactions // so we know how much to remove from the account balance // for the trial preclaim. - XRPAmount potentialSpend = beast::kZero; - XRPAmount totalFee = beast::kZero; + XRPAmount potentialSpend = beast::kZERO; + XRPAmount totalFee = beast::kZERO; for (auto iter = txIter->first; iter != txIter->end; ++iter) { // If we're replacing this transaction don't include @@ -1154,7 +1151,7 @@ TxQ::apply( return {pcresult.ter, false}; // Too low of a fee should get caught by preclaim - XRPL_ASSERT(feeLevelPaid >= kBaseLevel, "xrpl::TxQ::apply : minimum fee"); + XRPL_ASSERT(feeLevelPaid >= kBASE_LEVEL, "xrpl::TxQ::apply : minimum fee"); JLOG(j_.trace()) << "Transaction " << transactionID << " from account " << account << " has fee level of " << feeLevelPaid << " needs at least " @@ -1179,10 +1176,10 @@ TxQ::apply( conditions change, but don't waste the effort to clear). */ if (txSeqProx.isSeq() && txIter && multiTxn.has_value() && - txIter->first->second.retriesRemaining == MaybeTx::kRetriesAllowed && - feeLevelPaid > requiredFeeLevel && requiredFeeLevel > kBaseLevel) + txIter->first->second.retriesRemaining == MaybeTx::kRETRIES_ALLOWED && + feeLevelPaid > requiredFeeLevel && requiredFeeLevel > kBASE_LEVEL) { - OpenView sandbox(kOpenLedger, &view, view.rules()); + OpenView sandbox(kOPEN_LEDGER, &view, view.rules()); auto result = tryClearAccountQueueUpThruTx( app, @@ -1249,7 +1246,7 @@ TxQ::apply( if (lastRIter->feeLevel > feeLevelPaid || endAccount.transactions.size() == 1) return lastRIter->feeLevel; - constexpr FeeLevel64 kMax{std::numeric_limits::max()}; + constexpr FeeLevel64 kMAX{std::numeric_limits::max()}; auto endTotal = std::accumulate( endAccount.transactions.begin(), endAccount.transactions.end(), @@ -1258,8 +1255,8 @@ TxQ::apply( // Check for overflow. auto next = txn.second.feeLevel / endAccount.transactions.size(); auto mod = txn.second.feeLevel % endAccount.transactions.size(); - if (total.first >= kMax - next || total.second >= kMax - mod) - return {kMax, FeeLevel64{0}}; + if (total.first >= kMAX - next || total.second >= kMAX - mod) + return {kMAX, FeeLevel64{0}}; return {total.first + next, total.second + mod}; }); @@ -1576,7 +1573,7 @@ TxQ::accept(Application& app, OpenView& view) // // Acquires a lock and calls the implementation. SeqProxy -TxQ::nextQueuableSeq(SLE::const_ref sleAccount) const +TxQ::nextQueuableSeq(std::shared_ptr const& sleAccount) const { std::scoped_lock const lock(mutex_); return nextQueuableSeqImpl(sleAccount, lock); @@ -1589,7 +1586,9 @@ TxQ::nextQueuableSeq(SLE::const_ref sleAccount) const // sequence number, that is not used by a transaction in the queue, must // be found and returned. SeqProxy -TxQ::nextQueuableSeqImpl(SLE::const_ref sleAccount, std::scoped_lock const&) const +TxQ::nextQueuableSeqImpl( + std::shared_ptr const& sleAccount, + std::scoped_lock const&) const { // If the account is not in the ledger or a non-account was passed // then return zero. We have no idea. @@ -1748,9 +1747,9 @@ TxQ::getMetrics(OpenView const& view) const result.txQMaxSize = maxSize_; result.txInLedger = view.txCount(); result.txPerLedger = snapshot.txnsExpected; - result.referenceFeeLevel = kBaseLevel; + result.referenceFeeLevel = kBASE_LEVEL; result.minProcessingFeeLevel = - isFull() ? byFee_.rbegin()->feeLevel + FeeLevel64{1} : kBaseLevel; + isFull() ? byFee_.rbegin()->feeLevel + FeeLevel64{1} : kBASE_LEVEL; result.medFeeLevel = snapshot.escalationMultiplier; result.openLedgerFeeLevel = FeeMetrics::scaleFeeLevel(snapshot, view); @@ -1773,7 +1772,7 @@ TxQ::getTxRequiredFeeAndSeq(OpenView const& view, std::shared_ptr co std::uint32_t const accountSeq = sle ? (*sle)[sfSequence] : 0; std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value(); return { - .fee = mulDiv(fee, baseFee, kBaseLevel) + .fee = mulDiv(fee, baseFee, kBASE_LEVEL) .value_or(XRPAmount(std::numeric_limits::max())), .accountSeq = accountSeq, .availableSeq = availableSeq}; @@ -1826,9 +1825,9 @@ TxQ::doRPC(Application& app) const auto const metrics = getMetrics(*view); - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); - auto& levels = ret[jss::levels] = json::ValueType::Object; + auto& levels = ret[jss::levels] = json::ObjectValue; ret[jss::ledger_current_index] = view->header().seq; ret[jss::expected_ledger_size] = std::to_string(metrics.txPerLedger); diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 57b65814e1..1576d398f8 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -130,7 +130,7 @@ ValidatorList::MessageWithHash::MessageWithHash( { } -std::string const ValidatorList::kFilePrefix = "cache."; +std::string const ValidatorList::kFILE_PREFIX = "cache."; ValidatorList::ValidatorList( ManifestCache& validatorManifests, @@ -291,7 +291,7 @@ ValidatorList::load( boost::filesystem::path ValidatorList::getCacheFileName(ValidatorList::scoped_lock const&, PublicKey const& pubKey) const { - return dataPath_ / (kFilePrefix + strHex(pubKey)); + return dataPath_ / (kFILE_PREFIX + strHex(pubKey)); } // static @@ -312,7 +312,7 @@ ValidatorList::buildFileData( std::optional forceVersion, beast::Journal j) { - json::Value value(json::ValueType::Object); + json::Value value(json::ObjectValue); XRPL_ASSERT( pubCollection.rawVersion == 2 || pubCollection.remaining.empty(), @@ -336,11 +336,11 @@ ValidatorList::buildFileData( break; } case 2: { - json::Value blobs(json::ValueType::Array); + json::Value blobs(json::ArrayValue); auto add = [&blobs, &outerManifest = pubCollection.rawManifest](PublisherList const& pubList) { - auto& blob = blobs.append(json::ValueType::Object); + auto& blob = blobs.append(json::ObjectValue); blob[jss::blob] = pubList.rawBlob; blob[jss::signature] = pubList.rawSignature; if (pubList.rawManifest && *pubList.rawManifest != outerManifest) @@ -359,7 +359,7 @@ ValidatorList::buildFileData( } default: JLOG(j.trace()) << "Invalid VL version provided: " << effectiveVersion; - value = json::ValueType::Null; + value = json::NullValue; } return value; @@ -420,7 +420,7 @@ ValidatorList::parseBlobs(std::uint32_t version, json::Value const& body) case 2: default: { if (!body.isMember(jss::blobs_v2) || !body[jss::blobs_v2].isArray() || - body[jss::blobs_v2].size() > kMaxSupportedBlobs || + body[jss::blobs_v2].size() > kMAX_SUPPORTED_BLOBS || // If any of the v1 fields are present, the VL is malformed body.isMember(jss::blob) || body.isMember(jss::signature)) return {}; @@ -462,7 +462,7 @@ ValidatorList::parseBlobs(protocol::TMValidatorList const& body) std::vector ValidatorList::parseBlobs(protocol::TMValidatorListCollection const& body) { - if (body.blobs_size() > kMaxSupportedBlobs) + if (body.blobs_size() > kMAX_SUPPORTED_BLOBS) return {}; std::vector result; result.reserve(body.blobs_size()); @@ -536,7 +536,7 @@ splitMessageParts( smallMsg.set_manifest(blob.manifest()); XRPL_ASSERT( - Message::totalSize(smallMsg) <= kMaximumMessageSize, + Message::totalSize(smallMsg) <= kMAXIMUM_MESSAGE_SIZE, "xrpl::splitMessageParts : maximum message size"); messages.emplace_back( @@ -593,7 +593,7 @@ buildValidatorListMessage( msg.set_version(version); XRPL_ASSERT( - Message::totalSize(msg) <= kMaximumMessageSize, + Message::totalSize(msg) <= kMAXIMUM_MESSAGE_SIZE, "xrpl::buildValidatorListMessage(ValidatorBlobInfo) : maximum " "message size"); messages.emplace_back( @@ -659,7 +659,7 @@ ValidatorList::buildValidatorListMessages( std::string const& rawManifest, std::map const& blobInfos, std::vector& messages, - std::size_t maxSize /*= kMaximumMessageSize*/) + std::size_t maxSize /*= kMAXIMUM_MESSAGE_SIZE*/) { XRPL_ASSERT( !blobInfos.empty(), @@ -978,8 +978,8 @@ ValidatorList::applyLists( std::string siteUri, std::optional const& hash /* = {} */) { - if (std::count(std::begin(kSupportedListVersions), std::end(kSupportedListVersions), version) != - 1) + if (std::count( + std::begin(kSUPPORTED_LIST_VERSIONS), std::end(kSUPPORTED_LIST_VERSIONS), version) != 1) return PublisherListStats{ListDisposition::UnsupportedVersion}; std::scoped_lock const lock{mutex_}; @@ -1605,14 +1605,14 @@ ValidatorList::expires() const json::Value ValidatorList::getJson() const { - json::Value res(json::ValueType::Object); + json::Value res(json::ObjectValue); std::shared_lock const readLock{mutex_}; res[jss::validation_quorum] = static_cast(quorum_); { - auto& x = (res[jss::validator_list] = json::ValueType::Object); + auto& x = (res[jss::validator_list] = json::ObjectValue); x[jss::count] = static_cast(count(readLock)); @@ -1647,16 +1647,16 @@ ValidatorList::getJson() const } // Validator keys listed in the local config file - json::Value& jLocalStaticKeys = (res[jss::local_static_keys] = json::ValueType::Array); + 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::ValueType::Array); + json::Value& jPublisherLists = (res[jss::publisher_lists] = json::ArrayValue); for (auto const& [publicKey, pubCollection] : publisherLists_) { - json::Value& curr = jPublisherLists.append(json::ValueType::Object); + json::Value& curr = jPublisherLists.append(json::ObjectValue); curr[jss::pubkey_publisher] = strHex(publicKey); curr[jss::available] = pubCollection.status == PublisherStatus::Available; @@ -1669,7 +1669,7 @@ ValidatorList::getJson() const } if (publisherList.validFrom != TimeKeeper::time_point{}) target[jss::effective] = to_string(publisherList.validFrom); - json::Value& keys = (target[jss::list] = json::ValueType::Array); + json::Value& keys = (target[jss::list] = json::ArrayValue); for (auto const& key : publisherList.list) { keys.append(toBase58(TokenType::NodePublic, key)); @@ -1684,13 +1684,13 @@ ValidatorList::getJson() const } } - json::Value remaining(json::ValueType::Array); + json::Value remaining(json::ArrayValue); for (auto const& [sequence, future] : pubCollection.remaining) { using namespace std::chrono_literals; (void)sequence; - json::Value& r = remaining.append(json::ValueType::Object); + json::Value& r = remaining.append(json::ObjectValue); appendList(future, r); // Race conditions can happen, so make this check "fuzzy" XRPL_ASSERT( @@ -1702,14 +1702,14 @@ ValidatorList::getJson() const } // Trusted validator keys - json::Value& jValidatorKeys = (res[jss::trusted_validator_keys] = json::ValueType::Array); + json::Value& jValidatorKeys = (res[jss::trusted_validator_keys] = json::ArrayValue); for (auto const& k : trustedMasterKeys_) { jValidatorKeys.append(toBase58(TokenType::NodePublic, k)); } // signing keys - json::Value& jSigningKeys = (res[jss::signing_keys] = json::ValueType::Object); + json::Value& jSigningKeys = (res[jss::signing_keys] = json::ObjectValue); validatorManifests_.forEachManifest([&jSigningKeys, this](Manifest const& manifest) { auto it = keyListings_.find(manifest.masterKey); if (it != keyListings_.end() && manifest.signingKey) @@ -1722,7 +1722,7 @@ ValidatorList::getJson() const // Negative UNL if (!negativeUNL_.empty()) { - json::Value& jNegativeUNL = (res[jss::NegativeUNL] = json::ValueType::Array); + json::Value& jNegativeUNL = (res[jss::NegativeUNL] = json::ArrayValue); for (auto const& k : negativeUNL_) { jNegativeUNL.append(toBase58(TokenType::NodePublic, k)); diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 76fd078174..57734ef956 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -44,9 +44,9 @@ namespace xrpl { -constexpr auto kDefaultRefreshInterval = std::chrono::minutes{5}; -constexpr auto kErrorRetryInterval = std::chrono::seconds{30}; -unsigned constexpr short kMaxRedirects = 3; +auto constexpr kDEFAULT_REFRESH_INTERVAL = std::chrono::minutes{5}; +auto constexpr kERROR_RETRY_INTERVAL = std::chrono::seconds{30}; +unsigned short constexpr kMAX_REDIRECTS = 3; ValidatorSite::Site::Resource::Resource(std::string inUri) : uri{std::move(inUri)} { @@ -92,7 +92,7 @@ ValidatorSite::Site::Resource::Resource(std::string inUri) : uri{std::move(inUri ValidatorSite::Site::Site(std::string uri) : loadedResource{std::make_shared(std::move(uri))} , startingResource{loadedResource} - , refreshInterval{kDefaultRefreshInterval} + , refreshInterval{kDEFAULT_REFRESH_INTERVAL} , nextRefresh{clock_type::now()} { @@ -114,7 +114,7 @@ ValidatorSite::ValidatorSite( ValidatorSite::~ValidatorSite() { - std::unique_lock lock{stateMutex_}; + std::unique_lock lock{state_mutex_}; if (timer_.expiry() > clock_type::time_point{}) { if (!stopping_) @@ -141,7 +141,7 @@ ValidatorSite::load(std::vector const& siteURIs) { JLOG(j_.debug()) << "Loading configured validator list sites"; - std::scoped_lock const lock{sitesMutex_}; + std::scoped_lock const lock{sites_mutex_}; return load(siteURIs, lock); } @@ -178,8 +178,8 @@ ValidatorSite::load( void ValidatorSite::start() { - std::scoped_lock const l0{sitesMutex_}; - std::scoped_lock const l1{stateMutex_}; + std::scoped_lock const l0{sites_mutex_}; + std::scoped_lock const l1{state_mutex_}; if (timer_.expiry() == clock_type::time_point{}) setTimer(l0, l1); } @@ -187,14 +187,14 @@ ValidatorSite::start() void ValidatorSite::join() { - std::unique_lock lock{stateMutex_}; + std::unique_lock lock{state_mutex_}; cv_.wait(lock, [&] { return !pending_; }); } void ValidatorSite::stop() { - std::unique_lock lock{stateMutex_}; + std::unique_lock lock{state_mutex_}; stopping_ = true; // work::cancel() must be called before the // cv wait in order to kick any asio async operations @@ -246,7 +246,7 @@ ValidatorSite::makeRequest( sites_[siteIdx].activeResource = resource; std::shared_ptr sp; auto timeoutCancel = [this]() { - std::scoped_lock const lockState{stateMutex_}; + std::scoped_lock const lockState{state_mutex_}; // docs indicate cancel_one() can throw, but this // should be reconsidered if it changes to noexcept try @@ -312,7 +312,7 @@ ValidatorSite::makeRequest( sp->run(); // start a timer for the request, which shouldn't take more // than requestTimeout_ to complete - std::scoped_lock const lockState{stateMutex_}; + std::scoped_lock const lockState{state_mutex_}; timer_.expires_after(requestTimeout_); timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { this->onRequestTimeout(siteIdx, ec); @@ -326,7 +326,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) return; { - std::scoped_lock const lockSite{sitesMutex_}; + std::scoped_lock const lockSite{sites_mutex_}; // In some circumstances, both this function and the response // handler (onSiteFetch or onTextFetch) can get queued and // processed. In all observed cases, the response handler @@ -343,7 +343,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) "already been processed"; } - std::scoped_lock const lockState{stateMutex_}; + std::scoped_lock const lockState{state_mutex_}; if (auto sp = work_.lock()) sp->cancel(); } @@ -362,7 +362,7 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) try { - std::scoped_lock const lock{sitesMutex_}; + std::scoped_lock const lock{sites_mutex_}; sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; sites_[siteIdx].redirCount = 0; // the WorkSSL client ctor can throw if SSL init fails @@ -512,7 +512,7 @@ ValidatorSite::processRedirect( throw std::runtime_error{"missing location"}; } - if (sites_[siteIdx].redirCount == kMaxRedirects) + if (sites_[siteIdx].redirCount == kMAX_REDIRECTS) { JLOG(j_.warn()) << "Exceeded max redirects for validator list at " << sites_[siteIdx].loadedResource->uri; @@ -545,7 +545,7 @@ ValidatorSite::onSiteFetch( detail::response_type const& res, std::size_t siteIdx) { - std::scoped_lock lockSites{sitesMutex_}; + std::scoped_lock lockSites{sites_mutex_}; { if (endpoint != endpoint_type{}) sites_[siteIdx].lastRequestEndpoint = endpoint; @@ -558,7 +558,7 @@ ValidatorSite::onSiteFetch( .disposition = ListDisposition::Invalid, .message = errMsg}); if (retry) - sites_[siteIdx].nextRefresh = clock_type::now() + kErrorRetryInterval; + sites_[siteIdx].nextRefresh = clock_type::now() + kERROR_RETRY_INTERVAL; // See if there's a copy saved locally from last time we // saw the list. @@ -617,7 +617,7 @@ ValidatorSite::onSiteFetch( sites_[siteIdx].activeResource.reset(); } - std::scoped_lock const lockState{stateMutex_}; + std::scoped_lock const lockState{state_mutex_}; fetching_ = false; if (!stopping_) setTimer(lockSites, lockState); @@ -630,7 +630,7 @@ ValidatorSite::onTextFetch( std::string const& res, std::size_t siteIdx) { - std::scoped_lock const lockSites{sitesMutex_}; + std::scoped_lock const lockSites{sites_mutex_}; { try { @@ -657,7 +657,7 @@ ValidatorSite::onTextFetch( sites_[siteIdx].activeResource.reset(); } - std::scoped_lock const lockState{stateMutex_}; + std::scoped_lock const lockState{state_mutex_}; fetching_ = false; if (!stopping_) setTimer(lockSites, lockState); @@ -670,13 +670,13 @@ ValidatorSite::getJson() const using namespace std::chrono; using Int = json::Value::Int; - json::Value jrr(json::ValueType::Object); - json::Value& jSites = (jrr[jss::validator_sites] = json::ValueType::Array); + json::Value jrr(json::ObjectValue); + json::Value& jSites = (jrr[jss::validator_sites] = json::ArrayValue); { - std::scoped_lock const lock{sitesMutex_}; + std::scoped_lock const lock{sites_mutex_}; for (Site const& site : sites_) { - json::Value& v = jSites.append(json::ValueType::Object); + json::Value& v = jSites.append(json::ObjectValue); std::stringstream uri; uri << site.loadedResource->uri; if (site.loadedResource != site.startingResource) diff --git a/src/xrpld/app/misc/detail/WorkSSL.cpp b/src/xrpld/app/misc/detail/WorkSSL.cpp index e1b864e81f..0a8d53b1a2 100644 --- a/src/xrpld/app/misc/detail/WorkSSL.cpp +++ b/src/xrpld/app/misc/detail/WorkSSL.cpp @@ -30,9 +30,9 @@ WorkSSL::WorkSSL( callback_type cb) : WorkBase(host, path, port, ios, lastEndpoint, lastStatus, cb) , context_( - config.sslVerifyDir, - config.sslVerifyFile, - config.sslVerify, + config.SSL_VERIFY_DIR, + config.SSL_VERIFY_FILE, + config.SSL_VERIFY, j, boost::asio::ssl::context::tlsv12_client) , stream_(socket_, context_.context()) diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 1fd3136420..8530fb2e65 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -39,7 +39,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include @@ -75,7 +75,7 @@ namespace xrpl::detail { static std::string toString(TableType type) { - static_assert(kTableTypeCount == 3, "Need to modify switch statement if enum is modified"); + static_assert(kTABLE_TYPE_COUNT == 3, "Need to modify switch statement if enum is modified"); switch (type) { @@ -87,7 +87,7 @@ toString(TableType type) return "AccountTransactions"; // LCOV_EXCL_START default: - UNREACHABLE("xrpl::detail::toString : invalid TableType"); + UNREACHABLE("xrpl::detail::to_string : invalid TableType"); return "Unknown"; // LCOV_EXCL_STOP } @@ -102,7 +102,7 @@ makeLedgerDBs( { // ledger database auto lgr{std::make_unique( - setup, kLgrDbName, setup.lgrPragma, kLgrDbInit, checkpointerSetup, j)}; + setup, kLGR_DB_NAME, setup.lgrPragma, kLGR_DB_INIT, checkpointerSetup, j)}; lgr->getSession() << boost::str( boost::format("PRAGMA cache_size=-%d;") % kilobytes(config.getValueFor(SizedItem::LgrDbCache))); @@ -111,7 +111,7 @@ makeLedgerDBs( { // transaction database auto tx{std::make_unique( - setup, kTxDbName, setup.txPragma, kTxDbInit, checkpointerSetup, j)}; + setup, kTX_DB_NAME, setup.txPragma, kTX_DB_INIT, checkpointerSetup, j)}; tx->getSession() << boost::str( boost::format("PRAGMA cache_size=-%d;") % kilobytes(config.getValueFor(SizedItem::TxnDbCache))); @@ -230,7 +230,7 @@ saveValidatedLedger( // LCOV_EXCL_STOP } - if (ledger->header().accountHash != ledger->stateMap().getHash().asUInt256()) + if (ledger->header().accountHash != ledger->stateMap().getHash().asUint256()) { // LCOV_EXCL_START JLOG(j.fatal()) << "sAL: " << ledger->header().accountHash @@ -241,7 +241,7 @@ saveValidatedLedger( } XRPL_ASSERT( - ledger->header().txHash == ledger->txMap().getHash().asUInt256(), + ledger->header().txHash == ledger->txMap().getHash().asUint256(), "xrpl::detail::saveValidatedLedger : transaction hash match"); // Save the ledger header in the hashed object store @@ -274,15 +274,16 @@ saveValidatedLedger( } { - static boost::format kDeleteLedger("DELETE FROM Ledgers WHERE LedgerSeq = %u;"); - static boost::format kDeleteTranS1("DELETE FROM Transactions WHERE LedgerSeq = %u;"); - static boost::format kDeleteTranS2("DELETE FROM AccountTransactions WHERE LedgerSeq = %u;"); - static boost::format kDeleteAcctTrans( + static boost::format kDELETE_LEDGER("DELETE FROM Ledgers WHERE LedgerSeq = %u;"); + static boost::format kDELETE_TRANS1("DELETE FROM Transactions WHERE LedgerSeq = %u;"); + static boost::format kDELETE_TRANS2( + "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;"); + static boost::format kDELETE_ACCT_TRANS( "DELETE FROM AccountTransactions WHERE TransID = '%s';"); { auto db = ldgDB.checkoutDb(); - *db << boost::str(kDeleteLedger % seq); + *db << boost::str(kDELETE_LEDGER % seq); } if (app.config().useTxTables()) @@ -299,8 +300,8 @@ saveValidatedLedger( soci::transaction tr(*db); - *db << boost::str(kDeleteTranS1 % seq); - *db << boost::str(kDeleteTranS2 % seq); + *db << boost::str(kDELETE_TRANS1 % seq); + *db << boost::str(kDELETE_TRANS2 % seq); std::string const ledgerSeq(std::to_string(seq)); @@ -311,7 +312,7 @@ saveValidatedLedger( std::string const txnId(to_string(transactionID)); std::string const txnSeq(std::to_string(acceptedLedgerTx->getTxnSeq())); - *db << boost::str(kDeleteAcctTrans % transactionID); + *db << boost::str(kDELETE_ACCT_TRANS % transactionID); auto const& accts = acceptedLedgerTx->getAffected(); @@ -357,7 +358,7 @@ saveValidatedLedger( // It's okay for pseudo transactions to not affect any // accounts. But otherwise... JLOG(j.warn()) << "Transaction in ledger " << seq << " affects no accounts"; - JLOG(j.warn()) << sleTxn->getJson(JsonOptions::Values::None); + JLOG(j.warn()) << sleTxn->getJson(JsonOptions::KNone); } *db @@ -377,7 +378,7 @@ saveValidatedLedger( } { - static std::string const kAddLedger( + static std::string const kADD_LEDGER( R"sql(INSERT OR REPLACE INTO Ledgers (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime, CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash) @@ -400,7 +401,7 @@ saveValidatedLedger( auto const accountHash = to_string(ledger->header().accountHash); auto const txHash = to_string(ledger->header().txHash); - *db << kAddLedger, soci::use(hash), soci::use(seq), soci::use(parentHash), + *db << kADD_LEDGER, soci::use(hash), soci::use(seq), soci::use(parentHash), soci::use(drops), soci::use(closeTime), soci::use(parentCloseTime), soci::use(closeTimeResolution), soci::use(closeFlags), soci::use(accountHash), soci::use(txHash); @@ -696,8 +697,8 @@ transactionsSQL( bool count, beast::Journal j) { - static constexpr std::uint32_t kNonbinaryPageLength = 200; - static constexpr std::uint32_t kBinaryPageLength = 500; + constexpr std::uint32_t kNONBINARY_PAGE_LENGTH = 200; + constexpr std::uint32_t kBINARY_PAGE_LENGTH = 500; std::uint32_t numberOfResults = 0; @@ -707,12 +708,12 @@ transactionsSQL( } else if (options.limit == UINT32_MAX) { - numberOfResults = binary ? kBinaryPageLength : kNonbinaryPageLength; + numberOfResults = binary ? kBINARY_PAGE_LENGTH : kNONBINARY_PAGE_LENGTH; } else if (!options.bUnlimited) { numberOfResults = - std::min(binary ? kBinaryPageLength : kNonbinaryPageLength, options.limit); + std::min(binary ? kBINARY_PAGE_LENGTH : kNONBINARY_PAGE_LENGTH, options.limit); } else { @@ -1047,7 +1048,7 @@ accountTxPage( std::optional newmarker; - static std::string const kPrefix( + static std::string const kPREFIX( R"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq, Status,RawTxn,TxnMeta FROM AccountTransactions INNER JOIN Transactions @@ -1064,7 +1065,7 @@ accountTxPage( if (findLedger == 0) { sql = boost::str( - boost::format(kPrefix + (R"(AccountTransactions.LedgerSeq BETWEEN %u AND %u + boost::format(kPREFIX + (R"(AccountTransactions.LedgerSeq BETWEEN %u AND %u ORDER BY AccountTransactions.LedgerSeq %s, AccountTransactions.TxnSeq %s LIMIT %u;)")) % @@ -1302,7 +1303,7 @@ dbHasSpace(soci::session& session, Config const& config, beast::Journal j) if (config.useTxTables()) { DatabaseCon::Setup const dbSetup = setupDatabaseCon(config); - boost::filesystem::path const dbPath = dbSetup.dataDir / kTxDbName; + boost::filesystem::path const dbPath = dbSetup.dataDir / kTX_DB_NAME; boost::system::error_code ec; std::optional dbSize = boost::filesystem::file_size(dbPath, ec); if (ec) @@ -1311,23 +1312,23 @@ dbHasSpace(soci::session& session, Config const& config, beast::Journal j) dbSize.reset(); } - static auto const kPageSize = [&] { + static auto const kPAGE_SIZE = [&] { std::uint32_t ps = 0; session << "PRAGMA page_size;", soci::into(ps); return ps; }(); - static auto const kMaxPages = [&] { + static auto const kMAX_PAGES = [&] { std::uint32_t mp = 0; session << "PRAGMA max_page_count;", soci::into(mp); return mp; }(); std::uint32_t pageCount = 0; session << "PRAGMA page_count;", soci::into(pageCount); - std::uint32_t const freePages = kMaxPages - pageCount; - std::uint64_t const freeSpace = safeCast(freePages) * kPageSize; + std::uint32_t const freePages = kMAX_PAGES - pageCount; + std::uint64_t const freeSpace = safeCast(freePages) * kPAGE_SIZE; JLOG(j.info()) << "Transaction DB pathname: " << dbPath.string() << "; file size: " << dbSize.value_or(-1) << " bytes" - << "; SQLite page size: " << kPageSize << " bytes" + << "; SQLite page size: " << kPAGE_SIZE << " bytes" << "; Free pages: " << freePages << "; Free space: " << freeSpace << " bytes; " << "Note that this does not take into account available disk " diff --git a/src/xrpld/app/rdb/backend/detail/Node.h b/src/xrpld/app/rdb/backend/detail/Node.h index 8267bb1a82..f5beb230b1 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.h +++ b/src/xrpld/app/rdb/backend/detail/Node.h @@ -9,7 +9,7 @@ namespace xrpl::detail { /* Need to change TableTypeCount if TableType is modified. */ enum class TableType { Ledgers, Transactions, AccountTransactions }; -constexpr int kTableTypeCount = 3; +constexpr int kTABLE_TYPE_COUNT = 3; struct DatabasePairValid { diff --git a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp index fd1298516f..a50d17bf2b 100644 --- a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp +++ b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp @@ -420,7 +420,7 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) if (!useTxTables_) return {}; - static std::uint32_t const kPageLength(200); + static std::uint32_t const kPAGE_LENGTH(200); auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; @@ -436,7 +436,7 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) { auto db = checkoutTransaction(); auto newmarker = - detail::oldestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPageLength) + detail::oldestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPAGE_LENGTH) .first; return {ret, newmarker}; } @@ -450,7 +450,7 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) if (!useTxTables_) return {}; - static std::uint32_t const kPageLength(200); + static std::uint32_t const kPAGE_LENGTH(200); auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; @@ -466,7 +466,7 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) { auto db = checkoutTransaction(); auto newmarker = - detail::newestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPageLength) + detail::newestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPAGE_LENGTH) .first; return {ret, newmarker}; } @@ -480,7 +480,7 @@ SQLiteDatabase::oldestAccountTxPageB(AccountTxPageOptions const& options) if (!useTxTables_) return {}; - static std::uint32_t const kPageLength(500); + static std::uint32_t const kPAGE_LENGTH(500); auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); MetaTxsList ret; @@ -494,7 +494,7 @@ SQLiteDatabase::oldestAccountTxPageB(AccountTxPageOptions const& options) { auto db = checkoutTransaction(); auto newmarker = - detail::oldestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPageLength) + detail::oldestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPAGE_LENGTH) .first; return {ret, newmarker}; } @@ -508,7 +508,7 @@ SQLiteDatabase::newestAccountTxPageB(AccountTxPageOptions const& options) if (!useTxTables_) return {}; - static std::uint32_t const kPageLength(500); + static std::uint32_t const kPAGE_LENGTH(500); auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); MetaTxsList ret; @@ -522,7 +522,7 @@ SQLiteDatabase::newestAccountTxPageB(AccountTxPageOptions const& options) { auto db = checkoutTransaction(); auto newmarker = - detail::newestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPageLength) + detail::newestAccountTxPage(*db, onUnsavedLedger, onTransaction, options, kPAGE_LENGTH) .first; return {ret, newmarker}; } @@ -641,10 +641,10 @@ SQLiteDatabase::SQLiteDatabase(ServiceRegistry& registry, Config const& config, setup, DatabaseCon::CheckpointerSetup{.jobQueue = &jobQueue, .registry = registry_})) { - static constexpr std::string_view kError = "Failed to create ledger databases"; + std::string_view constexpr kERROR = "Failed to create ledger databases"; - JLOG(j_.fatal()) << kError; - Throw(kError.data()); + JLOG(j_.fatal()) << kERROR; + Throw(kERROR.data()); } } diff --git a/src/xrpld/app/rdb/detail/PeerFinder.cpp b/src/xrpld/app/rdb/detail/PeerFinder.cpp index 2481b63d2b..7227c65663 100644 --- a/src/xrpld/app/rdb/detail/PeerFinder.cpp +++ b/src/xrpld/app/rdb/detail/PeerFinder.cpp @@ -9,7 +9,7 @@ #include #include -#include // IWYU pragma: keep +#include #include #include diff --git a/src/xrpld/consensus/Consensus.cpp b/src/xrpld/consensus/Consensus.cpp index d529ab2e44..5498f7cf79 100644 --- a/src/xrpld/consensus/Consensus.cpp +++ b/src/xrpld/consensus/Consensus.cpp @@ -35,7 +35,7 @@ shouldCloseLedger( << ", timeSincePrevClose: " << timeSincePrevClose.count() << "ms" << ", openTime: " << openTime.count() << "ms" << ", idleInterval: " << idleInterval.count() << "ms" - << ", ledgerMIN_CLOSE: " << parms.ledgerMinClose.count() << "ms" + << ", ledgerMIN_CLOSE: " << parms.ledgerMIN_CLOSE.count() << "ms" << ". "; using namespace std::chrono_literals; if ((prevRoundTime < -1s) || (prevRoundTime > 10min) || (timeSincePrevClose > 10min)) @@ -67,7 +67,7 @@ shouldCloseLedger( } // Preserve minimum ledger open time - if (openTime < parms.ledgerMinClose) + if (openTime < parms.ledgerMIN_CLOSE) { JLOG(j.debug()) << "Must wait minimum time before closing"; CLOG(clog) << "not closing because under ledgerMIN_CLOSE. "; @@ -175,12 +175,12 @@ checkConsensus( << " agree=" << currentAgree << " validated=" << currentFinished << " time=" << currentAgreeTime.count() << "/" << previousAgreeTime.count() << " proposing? " << proposing - << " minimum duration to reach consensus: " << parms.ledgerMinConsensus.count() + << " minimum duration to reach consensus: " << parms.ledgerMIN_CONSENSUS.count() << "ms" - << " max consensus time " << parms.ledgerMaxConsensus.count() << "ms" - << " minimum consensus percentage: " << parms.minConsensusPct << ". "; + << " max consensus time " << parms.ledgerMAX_CONSENSUS.count() << "ms" + << " minimum consensus percentage: " << parms.minCONSENSUS_PCT << ". "; - if (currentAgreeTime <= parms.ledgerMinConsensus) + if (currentAgreeTime <= parms.ledgerMIN_CONSENSUS) { CLOG(clog) << "Not reached. "; return ConsensusState::No; @@ -190,7 +190,7 @@ checkConsensus( { // Less than 3/4 of the last ledger's proposers are present; don't // rush: we may need more time. - if (currentAgreeTime < (previousAgreeTime + parms.ledgerMinConsensus)) + if (currentAgreeTime < (previousAgreeTime + parms.ledgerMIN_CONSENSUS)) { JLOG(j.trace()) << "too fast, not enough proposers"; CLOG(clog) << "Too fast, not enough proposers. Not reached. "; @@ -204,8 +204,8 @@ checkConsensus( currentAgree, currentProposers, proposing, - parms.minConsensusPct, - currentAgreeTime > parms.ledgerMaxConsensus, + parms.minCONSENSUS_PCT, + currentAgreeTime > parms.ledgerMAX_CONSENSUS, stalled, clog)) { @@ -221,8 +221,8 @@ checkConsensus( currentFinished, currentProposers, false, - parms.minConsensusPct, - currentAgreeTime > parms.ledgerMaxConsensus, + parms.minCONSENSUS_PCT, + currentAgreeTime > parms.ledgerMAX_CONSENSUS, false, clog)) { @@ -232,9 +232,9 @@ checkConsensus( } std::chrono::milliseconds const maxAgreeTime = - previousAgreeTime * parms.ledgerAbandonConsensusFactor; + previousAgreeTime * parms.ledgerABANDON_CONSENSUS_FACTOR; if (currentAgreeTime > - std::clamp(maxAgreeTime, parms.ledgerMaxConsensus, parms.ledgerAbandonConsensus)) + std::clamp(maxAgreeTime, parms.ledgerMAX_CONSENSUS, parms.ledgerABANDON_CONSENSUS)) { JLOG(j.warn()) << "consensus taken too long"; CLOG(clog) << "Consensus taken too long. "; diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 131db30ce0..e5c06bd1c8 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -549,7 +549,7 @@ private: // How long has this round been open ConsensusTimer openTime_; - NetClock::duration closeResolution_ = kLedgerDefaultTimeResolution; + NetClock::duration closeResolution_ = kLEDGER_DEFAULT_TIME_RESOLUTION; ConsensusParms::AvalancheState closeTimeAvalancheState_ = ConsensusParms::AvalancheState::Init; @@ -625,7 +625,7 @@ Consensus::startRound( if (firstRound_) { // take our initial view of closeTime_ from the seed ledger - prevRoundTime_ = adaptor_.parms().ledgerIdleInterval; + prevRoundTime_ = adaptor_.parms().ledgerIDLE_INTERVAL; prevCloseTime_ = prevLedger.closeTime(); firstRound_ = false; } @@ -932,7 +932,7 @@ Consensus::getJson(bool full) const using std::to_string; using Int = json::Value::Int; - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret["proposing"] = (mode_.get() == ConsensusMode::Proposing); ret["proposers"] = static_cast(currPeerPositions_.size()); @@ -968,7 +968,7 @@ Consensus::getJson(bool full) const if (!currPeerPositions_.empty()) { - json::Value ppj(json::ValueType::Object); + json::Value ppj(json::ObjectValue); for (auto const& [nodeId, peerPos] : currPeerPositions_) { @@ -979,7 +979,7 @@ Consensus::getJson(bool full) const if (!acquired_.empty()) { - json::Value acq(json::ValueType::Array); + json::Value acq(json::ArrayValue); for (auto const& at : acquired_) { acq.append(to_string(at.first)); @@ -989,7 +989,7 @@ Consensus::getJson(bool full) const if (result_ && !result_->disputes.empty()) { - json::Value dsj(json::ValueType::Object); + json::Value dsj(json::ObjectValue); for (auto const& [txId, dispute] : result_->disputes) { dsj[to_string(txId)] = dispute.getJson(); @@ -999,7 +999,7 @@ Consensus::getJson(bool full) const if (!rawCloseTimes_.peers.empty()) { - json::Value ctj(json::ValueType::Object); + json::Value ctj(json::ObjectValue); for (auto const& ct : rawCloseTimes_.peers) { ctj[std::to_string(ct.first.time_since_epoch().count())] = ct.second; @@ -1009,7 +1009,7 @@ Consensus::getJson(bool full) const if (!deadNodes_.empty()) { - json::Value dnj(json::ValueType::Array); + json::Value dnj(json::ArrayValue); for (auto const& dn : deadNodes_) { dnj.append(to_string(dn)); @@ -1169,9 +1169,9 @@ Consensus::phaseOpen(std::unique_ptr const& clog) } auto const idleInterval = std::max( - adaptor_.parms().ledgerIdleInterval, 2 * previousLedger_.closeTimeResolution()); + adaptor_.parms().ledgerIDLE_INTERVAL, 2 * previousLedger_.closeTimeResolution()); CLOG(clog) << "idle interval set to " << idleInterval.count() << "ms based on " - << "ledgerIDLE_INTERVAL: " << adaptor_.parms().ledgerIdleInterval.count() + << "ledgerIDLE_INTERVAL: " << adaptor_.parms().ledgerIDLE_INTERVAL.count() << ", previous ledger close time resolution: " << previousLedger_.closeTimeResolution().count() << "ms. "; @@ -1218,7 +1218,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) << "roundTime: " << result_->roundTime.read().count() << ", " // NOLINTEND(bugprone-unchecked-optional-access) - << "max consensus time: " << parms.ledgerMaxConsensus.count() << ", " + << "max consensus time: " << parms.ledgerMAX_CONSENSUS.count() << ", " << "validators: " << totalValidators << ", " << "laggards: " << laggards << ", " << "offline: " << offline << ", " @@ -1227,7 +1227,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) if ((ahead == 0u) || (laggards == 0u) || (totalValidators == 0u) || !adaptor_.validator() || !adaptor_.haveValidated() || // NOLINTNEXTLINE(bugprone-unchecked-optional-access) result_ set as shouldPause called - result_->roundTime.read() > parms.ledgerMaxConsensus) + result_->roundTime.read() > parms.ledgerMAX_CONSENSUS) { j_.debug() << "not pausing (early)" << vars.str(); CLOG(clog) << "Not pausing (early). "; @@ -1249,7 +1249,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) * 3: >=95% * 4: =100% */ - static constexpr std::size_t kMaxPausePhase = 4; + constexpr static std::size_t kMAX_PAUSE_PHASE = 4; /** * No particular threshold guarantees consensus. Lower thresholds @@ -1270,7 +1270,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) * else out of the scope of this delay mechanism is wrong with the * network. */ - std::size_t const phase = (ahead - 1) % (kMaxPausePhase + 1); + std::size_t const phase = (ahead - 1) % (kMAX_PAUSE_PHASE + 1); // validators that remain after the laggards() function are considered // offline, and should be considered as laggards for purposes of @@ -1282,7 +1282,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) if (laggards + offline > totalValidators - quorum) willPause = true; break; - case kMaxPausePhase: + case kMAX_PAUSE_PHASE: // No tolerance. willPause = true; break; @@ -1297,7 +1297,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) float const nonLaggards = totalValidators - (laggards + offline); float const quorumRatio = static_cast(quorum) / totalValidators; float const allowedDissent = 1.0f - quorumRatio; - float const phaseFactor = static_cast(phase) / kMaxPausePhase; + float const phaseFactor = static_cast(phase) / kMAX_PAUSE_PHASE; if (nonLaggards / totalValidators < quorumRatio + (allowedDissent * phaseFactor)) { @@ -1337,17 +1337,17 @@ Consensus::phaseEstablish(std::unique_ptr const& clo result_->proposers = currPeerPositions_.size(); convergePercent_ = result_->roundTime.read() * 100 / - std::max(prevRoundTime_, parms.avMinConsensusTime); + std::max(prevRoundTime_, parms.avMIN_CONSENSUS_TIME); CLOG(clog) << "convergePercent_ " << convergePercent_ << " is based on round duration so far: " << result_->roundTime.read().count() << "ms, " << "previous round duration: " << prevRoundTime_.count() << "ms, " - << "avMIN_CONSENSUS_TIME: " << parms.avMinConsensusTime.count() << "ms. "; + << "avMIN_CONSENSUS_TIME: " << parms.avMIN_CONSENSUS_TIME.count() << "ms. "; // Give everyone a chance to take an initial position - if (result_->roundTime.read() < parms.ledgerMinConsensus) + if (result_->roundTime.read() < parms.ledgerMIN_CONSENSUS) { - CLOG(clog) << "ledgerMIN_CONSENSUS not reached: " << parms.ledgerMinConsensus.count() + CLOG(clog) << "ledgerMIN_CONSENSUS not reached: " << parms.ledgerMIN_CONSENSUS.count() << "ms. "; return; } @@ -1542,7 +1542,7 @@ Consensus::updateOurPositions(std::unique_ptr const& int threshVote = participantsNeeded(participants, neededWeight); // Threshold to declare consensus - int const threshConsensus = participantsNeeded(participants, parms.avCtConsensusPct); + int const threshConsensus = participantsNeeded(participants, parms.avCT_CONSENSUS_PCT); std::stringstream ss; ss << "Proposers:" << currPeerPositions_.size() << " nw:" << neededWeight @@ -1696,9 +1696,9 @@ Consensus::haveConsensus(std::unique_ptr const& clog // Consensus has taken far too long. Drop out of the round. if (result_->state == ConsensusState::Expired) { - static auto const kMinimumCounter = parms.avalancheCutoffs.size() * parms.avMinRounds; + static auto const kMINIMUM_COUNTER = parms.avalancheCutoffs.size() * parms.avMIN_ROUNDS; std::stringstream ss; - if (establishCounter_ < kMinimumCounter) + if (establishCounter_ < kMINIMUM_COUNTER) { // If each round of phaseEstablish takes a very long time, we may // "expire" before we've given consensus enough time at each @@ -1708,7 +1708,7 @@ Consensus::haveConsensus(std::unique_ptr const& clog // amount of time. ss << "Consensus time has expired in round " << establishCounter_ - << "; continue until round " << kMinimumCounter << ". " + << "; continue until round " << kMINIMUM_COUNTER << ". " << json::Compact{getJson(false)}; JLOG(j_.error()) << ss.str(); CLOG(clog) << ss.str() << ". "; diff --git a/src/xrpld/consensus/ConsensusParms.h b/src/xrpld/consensus/ConsensusParms.h index e6dd7f046e..88a6318b3c 100644 --- a/src/xrpld/consensus/ConsensusParms.h +++ b/src/xrpld/consensus/ConsensusParms.h @@ -28,7 +28,7 @@ struct ConsensusParms This is a safety to protect against very old validations and the time it takes to adjust the close time accuracy window. */ - std::chrono::seconds const validationValidWall = std::chrono::minutes{5}; + std::chrono::seconds const validationVALID_WALL = std::chrono::minutes{5}; /** Duration a validation remains current after first observed. @@ -36,14 +36,14 @@ struct ConsensusParms first saw it. This provides faster recovery in very rare cases where the number of validations produced by the network is lower than normal */ - std::chrono::seconds const validationValidLocal = std::chrono::minutes{3}; + std::chrono::seconds const validationVALID_LOCAL = std::chrono::minutes{3}; /** Duration pre-close in which validations are acceptable. The number of seconds before a close time that we consider a validation acceptable. This protects against extreme clock errors */ - std::chrono::seconds const validationValidEarly = std::chrono::minutes{3}; + std::chrono::seconds const validationVALID_EARLY = std::chrono::minutes{3}; //! How long we consider a proposal fresh std::chrono::seconds const proposeFRESHNESS = std::chrono::seconds{20}; @@ -56,13 +56,13 @@ struct ConsensusParms // millisecond resolution. //! The percentage threshold above which we can declare consensus. - std::size_t const minConsensusPct = 80; + std::size_t const minCONSENSUS_PCT = 80; //! The duration a ledger may remain idle before closing - std::chrono::milliseconds const ledgerIdleInterval = std::chrono::seconds{15}; + std::chrono::milliseconds const ledgerIDLE_INTERVAL = std::chrono::seconds{15}; //! The number of seconds we wait minimum to ensure participation - std::chrono::milliseconds const ledgerMinConsensus = std::chrono::milliseconds{1950}; + std::chrono::milliseconds const ledgerMIN_CONSENSUS = std::chrono::milliseconds{1950}; /** The maximum amount of time to spend pausing for laggards. * @@ -70,16 +70,16 @@ struct ConsensusParms * validators don't appear to be offline that are merely waiting for * laggards. */ - std::chrono::milliseconds const ledgerMaxConsensus = std::chrono::seconds{15}; + std::chrono::milliseconds const ledgerMAX_CONSENSUS = std::chrono::seconds{15}; //! Minimum number of seconds to wait to ensure others have computed the LCL - std::chrono::milliseconds const ledgerMinClose = std::chrono::seconds{2}; + std::chrono::milliseconds const ledgerMIN_CLOSE = std::chrono::seconds{2}; //! How often we check state or change positions std::chrono::milliseconds const ledgerGRANULARITY = std::chrono::seconds{1}; //! How long to wait before completely abandoning consensus - std::size_t const ledgerAbandonConsensusFactor = 10; + std::size_t const ledgerABANDON_CONSENSUS_FACTOR = 10; /** * Maximum amount of time to give a consensus round @@ -87,7 +87,7 @@ struct ConsensusParms * Does not include the time to build the LCL, so there is no reason for a * round to go this long, regardless of how big the ledger is. */ - std::chrono::milliseconds const ledgerAbandonConsensus = std::chrono::seconds{120}; + std::chrono::milliseconds const ledgerABANDON_CONSENSUS = std::chrono::seconds{120}; /** The minimum amount of time to consider the previous round to have taken. @@ -99,7 +99,7 @@ struct ConsensusParms twice the interval between proposals (0.7s) divided by the interval between mid and late consensus ([85-50]/100). */ - std::chrono::milliseconds const avMinConsensusTime = std::chrono::seconds{5}; + std::chrono::milliseconds const avMIN_CONSENSUS_TIME = std::chrono::seconds{5}; //------------------------------------------------------------------------------ // Avalanche tuning @@ -136,16 +136,16 @@ struct ConsensusParms }; //! Percentage of nodes required to reach agreement on ledger close time - std::size_t const avCtConsensusPct = 75; + std::size_t const avCT_CONSENSUS_PCT = 75; //! Number of rounds before certain actions can happen. // (Moving to the next avalanche level, considering that votes are stalled // without consensus.) - std::size_t const avMinRounds = 2; + std::size_t const avMIN_ROUNDS = 2; //! Number of rounds before a stuck vote is considered unlikely to change //! because voting stalled - std::size_t const avStalledRounds = 4; + std::size_t const avSTALLED_ROUNDS = 4; }; inline std::pair> diff --git a/src/xrpld/consensus/ConsensusProposal.h b/src/xrpld/consensus/ConsensusProposal.h index d16679bfb5..ebfe61711a 100644 --- a/src/xrpld/consensus/ConsensusProposal.h +++ b/src/xrpld/consensus/ConsensusProposal.h @@ -26,7 +26,7 @@ namespace xrpl { As consensus proceeds, peers may change their position on the transaction, or choose to abstain. Each successive proposal includes a strictly monotonically increasing number (or, if a peer is choosing to abstain, - the special value `kSeqLeave`). + the special value `kSEQ_LEAVE`). Refer to @ref Consensus for requirements of the template arguments. @@ -42,10 +42,10 @@ public: using NodeID = NodeId; //< Sequence value when a peer initially joins consensus - static std::uint32_t const kSeqJoin = 0; + static std::uint32_t const kSEQ_JOIN = 0; //< Sequence number when a peer wants to bow out and leave consensus - static std::uint32_t const kSeqLeave = 0xffffffff; + static std::uint32_t const kSEQ_LEAVE = 0xffffffff; /** Constructor @@ -95,7 +95,7 @@ public: /** Get the sequence number of this proposal - Starting with an initial sequence number of `kSeqJoin`, successive + Starting with an initial sequence number of `kSEQ_JOIN`, successive proposals from a peer will increase the sequence number. @return the sequence number @@ -126,14 +126,14 @@ public: bool isInitial() const { - return proposeSeq_ == kSeqJoin; + return proposeSeq_ == kSEQ_JOIN; } //! Get whether this node left the consensus process bool isBowOut() const { - return proposeSeq_ == kSeqLeave; + return proposeSeq_ == kSEQ_LEAVE; } //! Get whether this position is stale relative to the provided cutoff @@ -160,7 +160,7 @@ public: position_ = newPosition; closeTime_ = newCloseTime; time_ = now; - if (proposeSeq_ != kSeqLeave) + if (proposeSeq_ != kSEQ_LEAVE) ++proposeSeq_; } @@ -175,7 +175,7 @@ public: { signingHash_.reset(); time_ = now; - proposeSeq_ = kSeqLeave; + proposeSeq_ = kSEQ_LEAVE; } std::string @@ -195,7 +195,7 @@ public: { using std::to_string; - json::Value ret = json::ValueType::Object; + json::Value ret = json::ObjectValue; ret[jss::previous_ledger] = to_string(prevLedger()); if (!isBowOut()) diff --git a/src/xrpld/consensus/DisputedTx.h b/src/xrpld/consensus/DisputedTx.h index 1c0c069f54..795f399d1f 100644 --- a/src/xrpld/consensus/DisputedTx.h +++ b/src/xrpld/consensus/DisputedTx.h @@ -79,20 +79,20 @@ public: // enough, so there's room for change. Check the times in case the state // machine is altered to allow states to loop. if (nextCutoff.consensusTime > currentCutoff.consensusTime || - avalancheCounter_ < p.avMinRounds) + avalancheCounter_ < p.avMIN_ROUNDS) return false; // We've haven't had this vote for minimum rounds yet. Things could // change. - if (proposing && currentVoteCounter_ < p.avMinRounds) + if (proposing && currentVoteCounter_ < p.avMIN_ROUNDS) return false; // If we or any peers have changed a vote in several rounds, then // things could still change. But if _either_ has not changed in that // long, we're unlikely to change our vote any time soon. (This prevents // a malicious peer from flip-flopping a vote to prevent consensus.) - if (peersUnchanged < p.avStalledRounds && - (proposing && currentVoteCounter_ < p.avStalledRounds)) + if (peersUnchanged < p.avSTALLED_ROUNDS && + (proposing && currentVoteCounter_ < p.avSTALLED_ROUNDS)) return false; // Does this transaction have more than 80% agreement @@ -108,7 +108,7 @@ public: int const weight = support / total; // Returns true if the tx has more than minCONSENSUS_PCT (80) percent // agreement. Either voting for _or_ voting against the tx. - bool const stalled = weight > p.minConsensusPct || weight < (100 - p.minConsensusPct); + bool const stalled = weight > p.minCONSENSUS_PCT || weight < (100 - p.minCONSENSUS_PCT); if (stalled) { @@ -276,7 +276,7 @@ DisputedTx::updateVote(int percentTime, bool proposing, ConsensusPar // Proposing or not, we need to keep track of which state we've reached so // we can determine if the vote has stalled. auto const [requiredPct, newState] = - getNeededWeight(p, avalancheState_, percentTime, ++avalancheCounter_, p.avMinRounds); + getNeededWeight(p, avalancheState_, percentTime, ++avalancheCounter_, p.avMIN_ROUNDS); if (newState) { avalancheState_ = *newState; @@ -286,7 +286,7 @@ DisputedTx::updateVote(int percentTime, bool proposing, ConsensusPar if (proposing) // give ourselves full weight { // This is basically the percentage of nodes voting 'yes' (including us) - weight = ((yays_ * 100) + (ourVote_ ? 100 : 0)) / (nays_ + yays_ + 1); + weight = (yays_ * 100 + (ourVote_ ? 100 : 0)) / (nays_ + yays_ + 1); newPosition = weight > requiredPct; } @@ -320,7 +320,7 @@ DisputedTx::getJson() const { using std::to_string; - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret["yays"] = yays_; ret["nays"] = nays_; @@ -328,7 +328,7 @@ DisputedTx::getJson() const if (!votes_.empty()) { - json::Value votes(json::ValueType::Object); + json::Value votes(json::ObjectValue); for (auto const& [nodeId, vote] : votes_) votes[to_string(nodeId)] = vote; ret["votes"] = std::move(votes); diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index 9d76c7f283..022219f822 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -232,7 +232,7 @@ struct Node res["branchSupport"] = branchSupport; if (!children.empty()) { - json::Value& cs = (res["children"] = json::ValueType::Array); + json::Value& cs = (res["children"] = json::ArrayValue); for (auto const& child : children) { cs.append(child->getJson()); @@ -779,7 +779,7 @@ public: { json::Value res; res["trie"] = root_->getJson(); - res["seq_support"] = json::ValueType::Object; + res["seq_support"] = json::ObjectValue; for (auto const& [seq, sup] : seqSupport_) res["seq_support"][to_string(seq)] = sup; return res; diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index 7be578060e..825d0f6076 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -33,7 +33,7 @@ struct ValidationParms This is a safety to protect against very old validations and the time it takes to adjust the close time accuracy window. */ - std::chrono::seconds validationCurrentWall = std::chrono::minutes{5}; + std::chrono::seconds validationCURRENT_WALL = std::chrono::minutes{5}; /** Duration a validation remains current after first observed. @@ -41,14 +41,14 @@ struct ValidationParms first saw it. This provides faster recovery in very rare cases where the number of validations produced by the network is lower than normal */ - std::chrono::seconds validationCurrentLocal = std::chrono::minutes{3}; + std::chrono::seconds validationCURRENT_LOCAL = std::chrono::minutes{3}; /** Duration pre-close in which validations are acceptable. The number of seconds before a close time that we consider a validation acceptable. This protects against extreme clock errors */ - std::chrono::seconds validationCurrentEarly = std::chrono::minutes{3}; + std::chrono::seconds validationCURRENT_EARLY = std::chrono::minutes{3}; /** Duration a set of validations for a given ledger hash remain valid @@ -56,7 +56,7 @@ struct ValidationParms hash can expire. This keeps validations for recent ledgers available for a reasonable interval. */ - std::chrono::seconds validationSetExpires = std::chrono::minutes{10}; + std::chrono::seconds validationSET_EXPIRES = std::chrono::minutes{10}; /** How long we consider a validation fresh. * @@ -98,7 +98,7 @@ public: bool operator()(time_point now, Seq s, ValidationParms const& p) { - if (now > (when_ + p.validationSetExpires)) + if (now > (when_ + p.validationSET_EXPIRES)) seq_ = Seq{0}; if (s <= seq_) return false; @@ -139,9 +139,9 @@ isCurrent( // promoted from unsigned 32 bit to signed 64 bit prior // to computation. - return (signTime > (now - p.validationCurrentEarly)) && - (signTime < (now + p.validationCurrentWall)) && - ((seenTime == NetClock::time_point{}) || (seenTime < (now + p.validationCurrentLocal))); + return (signTime > (now - p.validationCURRENT_EARLY)) && + (signTime < (now + p.validationCURRENT_WALL)) && + ((seenTime == NetClock::time_point{}) || (seenTime < (now + p.validationCURRENT_LOCAL))); } /** Status of validation we received */ @@ -610,7 +610,7 @@ public: auto const diff = std::max(seqit->second.signTime(), val.signTime()) - std::min(seqit->second.signTime(), val.signTime()); - if (diff > parms_.validationCurrentWall && + if (diff > parms_.validationCURRENT_WALL && val.signTime() > seqit->second.signTime()) seqit->second = val; } @@ -702,12 +702,12 @@ public: { // We only need to refresh the keep range when it's just about // to expire. Track the next time we need to refresh. - static std::chrono::steady_clock::time_point kRefreshTime; - if (auto const now = byLedger_.clock().now(); kRefreshTime <= now) + static std::chrono::steady_clock::time_point kREFRESH_TIME; + if (auto const now = byLedger_.clock().now(); kREFRESH_TIME <= now) { // The next refresh time is shortly before the expiration // time from now. - kRefreshTime = now + parms_.validationSetExpires - parms_.validationFRESHNESS; + kREFRESH_TIME = now + parms_.validationSET_EXPIRES - parms_.validationFRESHNESS; for (auto i = byLedger_.begin(); i != byLedger_.end(); ++i) { @@ -732,8 +732,8 @@ public: } } - beast::expire(byLedger_, parms_.validationSetExpires); - beast::expire(bySequence_, parms_.validationSetExpires); + beast::expire(byLedger_, parms_.validationSET_EXPIRES); + beast::expire(bySequence_, parms_.validationSET_EXPIRES); } JLOG(j.debug()) << "Validations sets sweep lock duration " << std::chrono::duration_cast( diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index a18b68a508..10fbadaae7 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -48,13 +48,13 @@ A default-constructed Setup contains recommended values. struct FeeSetup { /** The cost of a reference transaction in drops. */ - XRPAmount referenceFee{10}; + XRPAmount reference_fee{10}; /** The account reserve requirement in drops. */ - XRPAmount accountReserve{10 * kDropsPerXrp}; + XRPAmount account_reserve{10 * kDROPS_PER_XRP}; /** The per-owned item reserve requirement in drops. */ - XRPAmount ownerReserve{2 * kDropsPerXrp}; + XRPAmount owner_reserve{2 * kDROPS_PER_XRP}; /* (Remember to update the example cfg files when changing any of these * values.) */ @@ -63,7 +63,7 @@ struct FeeSetup [[nodiscard]] Fees toFees() const { - return Fees{referenceFee, accountReserve, ownerReserve}; + return Fees{reference_fee, account_reserve, owner_reserve}; } }; @@ -76,30 +76,30 @@ class Config : public BasicConfig { public: // Settings related to the configuration file location and directories - static char const* const kConfigFileName; - static char const* const kConfigLegacyName; - static char const* const kDatabaseDirName; - static char const* const kValidatorsFileName; + static char const* const kCONFIG_FILE_NAME; + static char const* const kCONFIG_LEGACY_NAME; + static char const* const kDATABASE_DIR_NAME; + static char const* const kVALIDATORS_FILE_NAME; /** Returns the full path and filename of the debug log file. */ [[nodiscard]] boost::filesystem::path getDebugLogFile() const; private: - boost::filesystem::path configFile_; + boost::filesystem::path CONFIG_FILE_; public: - boost::filesystem::path configDir; + boost::filesystem::path CONFIG_DIR; private: - boost::filesystem::path debugLogfile_; + boost::filesystem::path DEBUG_LOGFILE_; void load(); beast::Journal const j_; - bool quiet_ = false; // Minimize logging verbosity. - bool silent_ = false; // No output to console after startup. + bool QUIET_ = false; // Minimize logging verbosity. + bool SILENT_ = false; // No output to console after startup. /** Operate in stand-alone mode. In stand alone mode: @@ -109,9 +109,9 @@ private: - If no ledger is loaded, the default ledger with the root account is created. */ - bool runStandalone_ = false; + bool RUN_STANDALONE_ = false; - bool useTxTables_ = true; + bool USE_TX_TABLES_ = true; /** Determines if the server will sign a tx, given an account's secret seed. @@ -126,45 +126,45 @@ private: public: bool doImport = false; - bool elbSupport = false; + bool ELB_SUPPORT = false; // Entries from [ips] config stanza - std::vector ips; + std::vector IPS; // Entries from [ips_fixed] config stanza - std::vector ipsFixed; + std::vector IPS_FIXED; - StartUpType startUp = StartUpType::Normal; + StartUpType START_UP = StartUpType::Normal; - bool startValid = false; + bool START_VALID = false; - std::string startLedger; + std::string START_LEDGER; - std::optional trapTxHash; + std::optional TRAP_TX_HASH; // Network parameters - uint32_t networkId = 0; + uint32_t NETWORK_ID = 0; // Note: The following parameters do not relate to the UNL or trust at all // Minimum number of nodes to consider the network present - std::size_t networkQuorum = 1; + std::size_t NETWORK_QUORUM = 1; // Peer networking parameters // 1 = relay, 0 = do not relay (but process), -1 = drop completely (do NOT // process) - int relayUntrustedValidations = 1; - int relayUntrustedProposals = 0; + int RELAY_UNTRUSTED_VALIDATIONS = 1; + int RELAY_UNTRUSTED_PROPOSALS = 0; // True to ask peers not to relay current IP. - bool peerPrivate = false; + bool PEER_PRIVATE = false; // peers_max is a legacy configuration, which is going to be replaced // with individual inbound peers peers_in_max and outbound peers // peers_out_max configuration. for now we support both the legacy and // the new configuration. if peers_max is configured then peers_in_max and // peers_out_max are ignored. - std::size_t peersMax = 0; - std::size_t peersOutMax = 0; - std::size_t peersInMax = 0; + std::size_t PEERS_MAX = 0; + std::size_t PEERS_OUT_MAX = 0; + std::size_t PEERS_IN_MAX = 0; // Path searching: these were reasonable default values at some point but // further research is needed to decide if they still are @@ -178,110 +178,110 @@ public: // Servers operating as validators disable path finding by // default by setting the `PATH_SEARCH_MAX` option to 0 // unless it is explicitly set in the configuration file. - int pathSearchOld = 2; - int pathSearch = 2; - int pathSearchFast = 2; - int pathSearchMax = 3; + int PATH_SEARCH_OLD = 2; + int PATH_SEARCH = 2; + int PATH_SEARCH_FAST = 2; + int PATH_SEARCH_MAX = 3; // Validation - std::optional validationQuorum; // validations to consider ledger authoritative + std::optional VALIDATION_QUORUM; // validations to consider ledger authoritative - FeeSetup fees; + FeeSetup FEES; // Node storage configuration - std::uint32_t ledgerHistory = 256; - std::uint32_t fetchDepth = 1000000000; + std::uint32_t LEDGER_HISTORY = 256; + std::uint32_t FETCH_DEPTH = 1000000000; // Tunable that adjusts various parameters, typically associated // with hardware parameters (RAM size and CPU cores). The default // is 'tiny'. - std::size_t nodeSize = 0; + std::size_t NODE_SIZE = 0; - bool sslVerify = true; - std::string sslVerifyFile; - std::string sslVerifyDir; + bool SSL_VERIFY = true; + std::string SSL_VERIFY_FILE; + std::string SSL_VERIFY_DIR; // Compression - bool compression = false; + bool COMPRESSION = false; // Enable the experimental Ledger Replay functionality - bool ledgerReplay = false; + bool LEDGER_REPLAY = false; // Work queue limits - int maxTransactions = 250; - static constexpr int kMaxJobQueueTx = 1000; - static constexpr int kMinJobQueueTx = 100; + int MAX_TRANSACTIONS = 250; + static constexpr int kMAX_JOB_QUEUE_TX = 1000; + static constexpr int kMIN_JOB_QUEUE_TX = 100; // Amendment majority time - std::chrono::seconds amendmentMajorityTime = kDefaultAmendmentMajorityTime; + std::chrono::seconds AMENDMENT_MAJORITY_TIME = kDEFAULT_AMENDMENT_MAJORITY_TIME; // Thread pool configuration (0 = choose for me) - int workers = 0; // jobqueue thread count. default: upto 6 - int ioWorkers = 0; // io svc thread count. default: 2 - int prefetchWorkers = 0; // prefetch thread count. default: 4 + int WORKERS = 0; // jobqueue thread count. default: upto 6 + int IO_WORKERS = 0; // io svc thread count. default: 2 + int PREFETCH_WORKERS = 0; // prefetch thread count. default: 4 // Can only be set in code, specifically unit tests - bool forceMultiThread = false; + bool FORCE_MULTI_THREAD = false; // Normally the sweep timer is automatically deduced based on the node // size, but we allow admins to explicitly set it in the config. - std::optional sweepInterval; + std::optional SWEEP_INTERVAL; // Reduce-relay - Experimental parameters to control p2p routing algorithms // Enable base squelching of duplicate validation/proposal messages - bool vpReduceRelayBaseSquelchEnable = false; + bool VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = false; ///////////////////// !!TEMPORARY CODE BLOCK!! //////////////////////// // Temporary squelching config for the peers selected as a source of // // validator messages. The config must be removed once squelching is // // made the default routing algorithm // - std::size_t vpReduceRelaySquelchMaxSelectedPeers = 5; + std::size_t VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = 5; ///////////////// END OF TEMPORARY CODE BLOCK ///////////////////// // Transaction reduce-relay feature - bool txReduceRelayEnable = false; + bool TX_REDUCE_RELAY_ENABLE = false; // If tx reduce-relay feature is disabled // and this flag is enabled then some // tx-related metrics is collected. It // is ignored if tx reduce-relay feature is // enabled. It is used in debugging to compare // metrics with the feature disabled/enabled. - bool txReduceRelayMetrics = false; + bool TX_REDUCE_RELAY_METRICS = false; // Minimum peers a server should have before // selecting random peers - std::size_t txReduceRelayMinPeers = 20; + std::size_t TX_REDUCE_RELAY_MIN_PEERS = 20; // Percentage of peers with the tx reduce-relay feature enabled // to relay to out of total active peers - std::size_t txRelayPercentage = 25; + std::size_t TX_RELAY_PERCENTAGE = 25; // These override the command line client settings - std::optional rpcIp; + std::optional rpc_ip; std::unordered_set> features; - std::string serverDomain; + std::string SERVER_DOMAIN; // How long can a peer remain in the "unknown" state - std::chrono::seconds maxUnknownTime{600}; + std::chrono::seconds MAX_UNKNOWN_TIME{600}; // How long can a peer remain in the "diverged" state - std::chrono::seconds maxDivergedTime{300}; + std::chrono::seconds MAX_DIVERGED_TIME{300}; // Enable the beta API version - bool betaRpcApi = false; + bool BETA_RPC_API = false; // First, attempt to load the latest ledger directly from disk. - bool fastLoad = false; + bool FAST_LOAD = false; // When starting xrpld with existing database it do not know it has those // ledgers locally until the server naturally tries to backfill. This makes // is difficult to test some functionality (in particular performance // testing sidechains). With this variable the user is able to force xrpld // to consider the ledger range to be present. It should be used for testing // only. - std::optional> forcedLedgerRangePresent; + std::optional> FORCED_LEDGER_RANGE_PRESENT; - std::optional validatorListThreshold; + std::optional VALIDATOR_LIST_THRESHOLD; public: Config(); @@ -305,23 +305,23 @@ public: [[nodiscard]] bool quiet() const { - return quiet_; + return QUIET_; } [[nodiscard]] bool silent() const { - return silent_; + return SILENT_; } [[nodiscard]] bool standalone() const { - return runStandalone_; + return RUN_STANDALONE_; } [[nodiscard]] bool useTxTables() const { - return useTxTables_; + return USE_TX_TABLES_; } [[nodiscard]] bool diff --git a/src/xrpld/core/TimeKeeper.h b/src/xrpld/core/TimeKeeper.h index 8eb13e75c0..a21f5aa6e8 100644 --- a/src/xrpld/core/TimeKeeper.h +++ b/src/xrpld/core/TimeKeeper.h @@ -18,7 +18,7 @@ private: adjust(std::chrono::system_clock::time_point when) { return time_point( - std::chrono::duration_cast(when.time_since_epoch() - kEpochOffset)); + std::chrono::duration_cast(when.time_since_epoch() - kEPOCH_OFFSET)); } public: diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index 6eedc43edd..11ee43e9cc 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -114,7 +114,7 @@ namespace xrpl { // clang-format off // The configurable node sizes are "tiny", "small", "medium", "large", "huge" inline constexpr std::array>, 13> -kSizedItems +kSIZED_ITEMS {{ // FIXME: We should document each of these items, explaining exactly // what they control and whether there exists an explicit @@ -143,7 +143,7 @@ static_assert( []() constexpr -> bool { std::underlying_type_t idx = 0; - for (auto const& i : kSizedItems) + for (auto const& i : kSIZED_ITEMS) { if (static_cast>(i.first) != idx) return false; @@ -248,10 +248,10 @@ getSingleSection( // //------------------------------------------------------------------------------ -char const* const Config::kConfigFileName = "xrpld.cfg"; -char const* const Config::kConfigLegacyName = "rippled.cfg"; -char const* const Config::kDatabaseDirName = "db"; -char const* const Config::kValidatorsFileName = "validators.txt"; +char const* const Config::kCONFIG_FILE_NAME = "xrpld.cfg"; +char const* const Config::kCONFIG_LEGACY_NAME = "rippled.cfg"; +char const* const Config::kDATABASE_DIR_NAME = "db"; +char const* const Config::kVALIDATORS_FILE_NAME = "validators.txt"; [[nodiscard]] static std::string getEnvVar(char const* name) @@ -272,11 +272,11 @@ Config::Config() void Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) { - XRPL_ASSERT(nodeSize == 0, "xrpl::Config::setupControl : node size not set"); + XRPL_ASSERT(NODE_SIZE == 0, "xrpl::Config::setupControl : node size not set"); - quiet_ = bQuiet || bSilent; - silent_ = bSilent; - runStandalone_ = bStandalone; + QUIET_ = bQuiet || bSilent; + SILENT_ = bSilent; + RUN_STANDALONE_ = bStandalone; // We try to autodetect the appropriate node size by checking available // RAM and CPU resources. We default to "tiny" for standalone mode. @@ -284,7 +284,7 @@ Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) { // First, check against 'minimum' RAM requirements per node size: auto const& threshold = - kSizedItems[std::underlying_type_t(SizedItem::RamSizeGb)]; + kSIZED_ITEMS[std::underlying_type_t(SizedItem::RamSizeGb)]; auto ns = std::ranges::find_if(threshold.second, [this](std::size_t limit) { return (limit == 0) || (ramSize_ < limit); @@ -293,15 +293,15 @@ Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) XRPL_ASSERT(ns != threshold.second.end(), "xrpl::Config::setupControl : valid node size"); if (ns != threshold.second.end()) - nodeSize = std::distance(threshold.second.begin(), ns); + NODE_SIZE = std::distance(threshold.second.begin(), ns); // Adjust the size based on the number of hardware threads of // execution available to us: if (auto const hc = std::thread::hardware_concurrency(); hc != 0) - nodeSize = std::min(hc / 2, nodeSize); + NODE_SIZE = std::min(hc / 2, NODE_SIZE); } - XRPL_ASSERT(nodeSize <= 4, "xrpl::Config::setupControl : node size is set"); + XRPL_ASSERT(NODE_SIZE <= 4, "xrpl::Config::setupControl : node size is set"); } void @@ -319,10 +319,10 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand if (!strConf.empty()) { // --conf= : everything is relative that file. - configFile_ = strConf; - configDir = boost::filesystem::absolute(configFile_); - configDir.remove_filename(); - dataDir = configDir / kDatabaseDirName; + CONFIG_FILE_ = strConf; + CONFIG_DIR = boost::filesystem::absolute(CONFIG_FILE_); + CONFIG_DIR.remove_filename(); + dataDir = CONFIG_DIR / kDATABASE_DIR_NAME; } else { @@ -331,13 +331,13 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand // Check if either of the config files exist in the current working // directory, in which case the databases will be stored in a // subdirectory. - configDir = boost::filesystem::current_path(); - dataDir = configDir / kDatabaseDirName; - configFile_ = configDir / kConfigFileName; - if (boost::filesystem::exists(configFile_)) + CONFIG_DIR = boost::filesystem::current_path(); + dataDir = CONFIG_DIR / kDATABASE_DIR_NAME; + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_FILE_NAME; + if (boost::filesystem::exists(CONFIG_FILE_)) break; - configFile_ = configDir / kConfigLegacyName; - if (boost::filesystem::exists(configFile_)) + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_LEGACY_NAME; + if (boost::filesystem::exists(CONFIG_FILE_)) break; // Check if the home directory is set, and optionally the XDG config @@ -362,22 +362,22 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand // Check if either of the config files exist in the XDG config // dir. dataDir = strXdgDataHome + "/" + systemName(); - configDir = strXdgConfigHome + "/" + systemName(); - configFile_ = configDir / kConfigFileName; - if (boost::filesystem::exists(configFile_)) + CONFIG_DIR = strXdgConfigHome + "/" + systemName(); + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_FILE_NAME; + if (boost::filesystem::exists(CONFIG_FILE_)) break; - configFile_ = configDir / kConfigLegacyName; - if (boost::filesystem::exists(configFile_)) + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_LEGACY_NAME; + if (boost::filesystem::exists(CONFIG_FILE_)) break; } // As a last resort, check the system config directory. - dataDir = "/var/lib/" + systemName(); - configDir = "/etc/" + systemName(); - configFile_ = configDir / kConfigFileName; - if (boost::filesystem::exists(configFile_)) + dataDir = "/var/opt/" + systemName(); + CONFIG_DIR = "/etc/opt/" + systemName(); + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_FILE_NAME; + if (boost::filesystem::exists(CONFIG_FILE_)) break; - configFile_ = configDir / kConfigLegacyName; + CONFIG_FILE_ = CONFIG_DIR / kCONFIG_LEGACY_NAME; } while (false); } @@ -390,7 +390,7 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand { dataDir = boost::filesystem::path(dbPath); } - else if (runStandalone_) + else if (RUN_STANDALONE_) { dataDir.clear(); } @@ -407,16 +407,17 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand legacy("database_path", boost::filesystem::absolute(dataDir).string()); } - HTTPClient::initializeSSLContext(this->sslVerifyDir, this->sslVerifyFile, this->sslVerify, j_); + HTTPClient::initializeSSLContext( + this->SSL_VERIFY_DIR, this->SSL_VERIFY_FILE, this->SSL_VERIFY, j_); - if (runStandalone_) - ledgerHistory = 0; + if (RUN_STANDALONE_) + LEDGER_HISTORY = 0; Section const ledgerTxTablesSection = section("ledger_tx_tables"); - getIfExists(ledgerTxTablesSection, "use_tx_tables", useTxTables_); + getIfExists(ledgerTxTablesSection, "use_tx_tables", USE_TX_TABLES_); Section const& nodeDbSection{section(ConfigSection::nodeDatabase())}; - getIfExists(nodeDbSection, "fast_load", fastLoad); + getIfExists(nodeDbSection, "fast_load", FAST_LOAD); } // 0 ports are allowed for unit tests, but still not allowed to be present in @@ -453,16 +454,16 @@ Config::load() // NOTE: this writes to cerr because we want cout to be reserved // for the writing of the json response (so that stdout can be part of a // pipeline, for instance) - if (!quiet_) - std::cerr << "Loading: " << configFile_ << "\n"; + if (!QUIET_) + std::cerr << "Loading: " << CONFIG_FILE_ << "\n"; boost::system::error_code ec; - auto const fileContents = getFileContents(ec, configFile_); + auto const fileContents = getFileContents(ec, CONFIG_FILE_); if (ec) { - std::cerr << "Failed to read '" << configFile_ << "'." << ec.value() << ": " << ec.message() - << std::endl; + std::cerr << "Failed to read '" << CONFIG_FILE_ << "'." << ec.value() << ": " + << ec.message() << std::endl; return; } @@ -478,10 +479,10 @@ Config::loadFromString(std::string const& fileContents) build(secConfig); if (auto s = getIniFileSection(secConfig, SECTION_IPS)) - ips = *s; + IPS = *s; if (auto s = getIniFileSection(secConfig, SECTION_IPS_FIXED)) - ipsFixed = *s; + IPS_FIXED = *s; // if the user has specified ip:port then replace : with a space. { @@ -501,8 +502,8 @@ Config::loadFromString(std::string const& fileContents) } }; - replaceColons(ipsFixed); - replaceColons(ips); + replaceColons(IPS_FIXED); + replaceColons(IPS); } { @@ -520,47 +521,47 @@ Config::loadFromString(std::string const& fileContents) { if (strTemp == "main") { - networkId = 0; + NETWORK_ID = 0; } else if (strTemp == "testnet") { - networkId = 1; + NETWORK_ID = 1; } else if (strTemp == "devnet") { - networkId = 2; + NETWORK_ID = 2; } else { - networkId = beast::lexicalCastThrow(strTemp); + NETWORK_ID = beast::lexicalCastThrow(strTemp); } } if (getSingleSection(secConfig, SECTION_PEER_PRIVATE, strTemp, j_)) - peerPrivate = beast::lexicalCastThrow(strTemp); + PEER_PRIVATE = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PEERS_MAX, strTemp, j_)) { - peersMax = beast::lexicalCastThrow(strTemp); + PEERS_MAX = beast::lexicalCastThrow(strTemp); } else { - std::optional peersInMaxOpt{}; + std::optional peersInMax{}; if (getSingleSection(secConfig, SECTION_PEERS_IN_MAX, strTemp, j_)) { - peersInMaxOpt = beast::lexicalCastThrow(strTemp); - if (*peersInMaxOpt > 1000) + peersInMax = beast::lexicalCastThrow(strTemp); + if (*peersInMax > 1000) { Throw("Invalid value specified in [" SECTION_PEERS_IN_MAX "] section; the value must be less or equal than 1000"); } } - std::optional peersOutMaxOpt{}; + std::optional peersOutMax{}; if (getSingleSection(secConfig, SECTION_PEERS_OUT_MAX, strTemp, j_)) { - peersOutMaxOpt = beast::lexicalCastThrow(strTemp); - if (*peersOutMaxOpt < 10 || *peersOutMaxOpt > 1000) + peersOutMax = beast::lexicalCastThrow(strTemp); + if (*peersOutMax < 10 || *peersOutMax > 1000) { Throw("Invalid value specified in [" SECTION_PEERS_OUT_MAX "] section; the value must be in range 10-1000"); @@ -568,17 +569,17 @@ Config::loadFromString(std::string const& fileContents) } // if one section is configured then the other must be configured too - if ((peersInMaxOpt && !peersOutMaxOpt) || (peersOutMaxOpt && !peersInMaxOpt)) + if ((peersInMax && !peersOutMax) || (peersOutMax && !peersInMax)) { Throw("Both sections [" SECTION_PEERS_IN_MAX "]" "and [" SECTION_PEERS_OUT_MAX "] must be configured"); } - if (peersInMaxOpt && peersOutMaxOpt) + if (peersInMax && peersOutMax) { - peersInMax = *peersInMaxOpt; - peersOutMax = *peersOutMaxOpt; + PEERS_IN_MAX = *peersInMax; + PEERS_OUT_MAX = *peersOutMax; } } @@ -586,27 +587,27 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "tiny")) { - nodeSize = 0; + NODE_SIZE = 0; } else if (boost::iequals(strTemp, "small")) { - nodeSize = 1; + NODE_SIZE = 1; } else if (boost::iequals(strTemp, "medium")) { - nodeSize = 2; + NODE_SIZE = 2; } else if (boost::iequals(strTemp, "large")) { - nodeSize = 3; + NODE_SIZE = 3; } else if (boost::iequals(strTemp, "huge")) { - nodeSize = 4; + NODE_SIZE = 4; } else { - nodeSize = std::min(4, beast::lexicalCastThrow(strTemp)); + NODE_SIZE = std::min(4, beast::lexicalCastThrow(strTemp)); } } @@ -614,27 +615,27 @@ Config::loadFromString(std::string const& fileContents) signingEnabled_ = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_ELB_SUPPORT, strTemp, j_)) - elbSupport = beast::lexicalCastThrow(strTemp); + ELB_SUPPORT = beast::lexicalCastThrow(strTemp); - getSingleSection(secConfig, SECTION_SSL_VERIFY_FILE, sslVerifyFile, j_); - getSingleSection(secConfig, SECTION_SSL_VERIFY_DIR, sslVerifyDir, j_); + getSingleSection(secConfig, SECTION_SSL_VERIFY_FILE, SSL_VERIFY_FILE, j_); + getSingleSection(secConfig, SECTION_SSL_VERIFY_DIR, SSL_VERIFY_DIR, j_); if (getSingleSection(secConfig, SECTION_SSL_VERIFY, strTemp, j_)) - sslVerify = beast::lexicalCastThrow(strTemp); + SSL_VERIFY = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_RELAY_VALIDATIONS, strTemp, j_)) { if (boost::iequals(strTemp, "all")) { - relayUntrustedValidations = 1; + RELAY_UNTRUSTED_VALIDATIONS = 1; } else if (boost::iequals(strTemp, "trusted")) { - relayUntrustedValidations = 0; + RELAY_UNTRUSTED_VALIDATIONS = 0; } else if (boost::iequals(strTemp, "drop_untrusted")) { - relayUntrustedValidations = -1; + RELAY_UNTRUSTED_VALIDATIONS = -1; } else { @@ -647,15 +648,15 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "all")) { - relayUntrustedProposals = 1; + RELAY_UNTRUSTED_PROPOSALS = 1; } else if (boost::iequals(strTemp, "trusted")) { - relayUntrustedProposals = 0; + RELAY_UNTRUSTED_PROPOSALS = 0; } else if (boost::iequals(strTemp, "drop_untrusted")) { - relayUntrustedProposals = -1; + RELAY_UNTRUSTED_PROPOSALS = -1; } else { @@ -671,28 +672,28 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_NETWORK_QUORUM, strTemp, j_)) - networkQuorum = beast::lexicalCastThrow(strTemp); + NETWORK_QUORUM = beast::lexicalCastThrow(strTemp); - fees = setupFeeVote(section("voting")); + FEES = setupFeeVote(section("voting")); /* [fee_default] is documented in the example config files as useful for * things like offline transaction signing. Until that's completely * deprecated, allow it to override the [voting] section. */ if (getSingleSection(secConfig, SECTION_FEE_DEFAULT, strTemp, j_)) - fees.referenceFee = beast::lexicalCastThrow(strTemp); + FEES.reference_fee = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_LEDGER_HISTORY, strTemp, j_)) { if (boost::iequals(strTemp, "full")) { - ledgerHistory = std::numeric_limits::max(); + LEDGER_HISTORY = std::numeric_limits::max(); } else if (boost::iequals(strTemp, "none")) { - ledgerHistory = 0; + LEDGER_HISTORY = 0; } else { - ledgerHistory = beast::lexicalCastThrow(strTemp); + LEDGER_HISTORY = beast::lexicalCastThrow(strTemp); } } @@ -700,42 +701,42 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "none")) { - fetchDepth = 0; + FETCH_DEPTH = 0; } else if (boost::iequals(strTemp, "full")) { - fetchDepth = std::numeric_limits::max(); + FETCH_DEPTH = std::numeric_limits::max(); } else { - fetchDepth = beast::lexicalCastThrow(strTemp); + FETCH_DEPTH = beast::lexicalCastThrow(strTemp); } - fetchDepth = std::max(fetchDepth, 10); + FETCH_DEPTH = std::max(FETCH_DEPTH, 10); } // By default, validators don't have pathfinding enabled, unless it is // explicitly requested by the server's admin. if (exists(SECTION_VALIDATION_SEED) || exists(SECTION_VALIDATOR_TOKEN)) - pathSearchMax = 0; + PATH_SEARCH_MAX = 0; if (getSingleSection(secConfig, SECTION_PATH_SEARCH_OLD, strTemp, j_)) - pathSearchOld = beast::lexicalCastThrow(strTemp); + PATH_SEARCH_OLD = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH, strTemp, j_)) - pathSearch = beast::lexicalCastThrow(strTemp); + PATH_SEARCH = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH_FAST, strTemp, j_)) - pathSearchFast = beast::lexicalCastThrow(strTemp); + PATH_SEARCH_FAST = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH_MAX, strTemp, j_)) - pathSearchMax = beast::lexicalCastThrow(strTemp); + PATH_SEARCH_MAX = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_DEBUG_LOGFILE, strTemp, j_)) - debugLogfile_ = strTemp; + DEBUG_LOGFILE_ = strTemp; if (getSingleSection(secConfig, SECTION_SWEEP_INTERVAL, strTemp, j_)) { - sweepInterval = beast::lexicalCastThrow(strTemp); + SWEEP_INTERVAL = beast::lexicalCastThrow(strTemp); - if (sweepInterval < 10 || sweepInterval > 600) + if (SWEEP_INTERVAL < 10 || SWEEP_INTERVAL > 600) { Throw("Invalid " SECTION_SWEEP_INTERVAL ": must be between 10 and 600 inclusive"); @@ -744,9 +745,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_WORKERS, strTemp, j_)) { - workers = beast::lexicalCastThrow(strTemp); + WORKERS = beast::lexicalCastThrow(strTemp); - if (workers < 1 || workers > 1024) + if (WORKERS < 1 || WORKERS > 1024) { Throw("Invalid " SECTION_WORKERS ": must be between 1 and 1024 inclusive."); @@ -755,9 +756,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_IO_WORKERS, strTemp, j_)) { - ioWorkers = beast::lexicalCastThrow(strTemp); + IO_WORKERS = beast::lexicalCastThrow(strTemp); - if (ioWorkers < 1 || ioWorkers > 1024) + if (IO_WORKERS < 1 || IO_WORKERS > 1024) { Throw("Invalid " SECTION_IO_WORKERS ": must be between 1 and 1024 inclusive."); @@ -766,9 +767,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_PREFETCH_WORKERS, strTemp, j_)) { - prefetchWorkers = beast::lexicalCastThrow(strTemp); + PREFETCH_WORKERS = beast::lexicalCastThrow(strTemp); - if (prefetchWorkers < 1 || prefetchWorkers > 1024) + if (PREFETCH_WORKERS < 1 || PREFETCH_WORKERS > 1024) { Throw("Invalid " SECTION_PREFETCH_WORKERS ": must be between 1 and 1024 inclusive."); @@ -776,10 +777,10 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_COMPRESSION, strTemp, j_)) - compression = beast::lexicalCastThrow(strTemp); + COMPRESSION = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_LEDGER_REPLAY, strTemp, j_)) - ledgerReplay = beast::lexicalCastThrow(strTemp); + LEDGER_REPLAY = beast::lexicalCastThrow(strTemp); if (exists(SECTION_REDUCE_RELAY)) { @@ -802,15 +803,15 @@ Config::loadFromString(std::string const& fileContents) if (sec.exists("vp_base_squelch_enable")) { - vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_base_squelch_enable", false); + VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.valueOr("vp_base_squelch_enable", false); } else if (sec.exists("vp_enable")) { - vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_enable", false); + VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.valueOr("vp_enable", false); } else { - vpReduceRelayBaseSquelchEnable = false; + VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = false; } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// @@ -818,8 +819,9 @@ Config::loadFromString(std::string const& fileContents) // Temporary squelching config for the peers selected as a source of // // validator messages. The config must be removed once squelching is // // made the default routing algorithm. // - vpReduceRelaySquelchMaxSelectedPeers = sec.valueOr("vp_base_squelch_max_selected_peers", 5); - if (vpReduceRelaySquelchMaxSelectedPeers < 3) + VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = + sec.valueOr("vp_base_squelch_max_selected_peers", 5); + if (VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS < 3) { Throw("Invalid " SECTION_REDUCE_RELAY " vp_base_squelch_max_selected_peers must be " @@ -827,11 +829,11 @@ Config::loadFromString(std::string const& fileContents) } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// - txReduceRelayEnable = sec.valueOr("tx_enable", false); - txReduceRelayMetrics = sec.valueOr("tx_metrics", false); - txReduceRelayMinPeers = sec.valueOr("tx_min_peers", 20); - txRelayPercentage = sec.valueOr("tx_relay_percentage", 25); - if (txRelayPercentage < 10 || txRelayPercentage > 100 || txReduceRelayMinPeers < 10) + TX_REDUCE_RELAY_ENABLE = sec.valueOr("tx_enable", false); + TX_REDUCE_RELAY_METRICS = sec.valueOr("tx_metrics", false); + TX_REDUCE_RELAY_MIN_PEERS = sec.valueOr("tx_min_peers", 20); + TX_RELAY_PERCENTAGE = sec.valueOr("tx_relay_percentage", 25); + if (TX_RELAY_PERCENTAGE < 10 || TX_RELAY_PERCENTAGE > 100 || TX_REDUCE_RELAY_MIN_PEERS < 10) { Throw("Invalid " SECTION_REDUCE_RELAY ", tx_min_peers must be greater than or equal to 10" @@ -842,8 +844,8 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_MAX_TRANSACTIONS, strTemp, j_)) { - maxTransactions = - std::clamp(beast::lexicalCastThrow(strTemp), kMinJobQueueTx, kMaxJobQueueTx); + MAX_TRANSACTIONS = + std::clamp(beast::lexicalCastThrow(strTemp), kMIN_JOB_QUEUE_TX, kMAX_JOB_QUEUE_TX); } if (getSingleSection(secConfig, SECTION_SERVER_DOMAIN, strTemp, j_)) @@ -855,7 +857,7 @@ Config::loadFromString(std::string const& fileContents) ": the domain name does not appear to meet the requirements."); } - serverDomain = strTemp; + SERVER_DOMAIN = strTemp; } if (exists(SECTION_OVERLAY)) @@ -867,7 +869,7 @@ Config::loadFromString(std::string const& fileContents) try { if (auto val = sec.get("max_unknown_time")) - maxUnknownTime = seconds{beast::lexicalCastThrow(*val)}; + MAX_UNKNOWN_TIME = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { @@ -875,7 +877,7 @@ Config::loadFromString(std::string const& fileContents) ": must be of the form '' representing seconds."); } - if (maxUnknownTime < seconds{300} || maxUnknownTime > seconds{1800}) + if (MAX_UNKNOWN_TIME < seconds{300} || MAX_UNKNOWN_TIME > seconds{1800}) { Throw( "Invalid value 'max_unknown_time' in " SECTION_OVERLAY @@ -885,7 +887,7 @@ Config::loadFromString(std::string const& fileContents) try { if (auto val = sec.get("max_diverged_time")) - maxDivergedTime = seconds{beast::lexicalCastThrow(*val)}; + MAX_DIVERGED_TIME = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { @@ -893,7 +895,7 @@ Config::loadFromString(std::string const& fileContents) ": must be of the form '' representing seconds."); } - if (maxDivergedTime < seconds{60} || maxDivergedTime > seconds{900}) + if (MAX_DIVERGED_TIME < seconds{60} || MAX_DIVERGED_TIME > seconds{900}) { Throw("Invalid value 'max_diverged_time' in " SECTION_OVERLAY ": the time must be between 60 and 900 seconds, inclusive."); @@ -915,22 +917,22 @@ Config::loadFromString(std::string const& fileContents) if (boost::iequals(match[2], "minutes")) { - amendmentMajorityTime = minutes(duration); + AMENDMENT_MAJORITY_TIME = minutes(duration); } else if (boost::iequals(match[2], "hours")) { - amendmentMajorityTime = hours(duration); + AMENDMENT_MAJORITY_TIME = hours(duration); } else if (boost::iequals(match[2], "days")) { - amendmentMajorityTime = days(duration); + AMENDMENT_MAJORITY_TIME = days(duration); } else if (boost::iequals(match[2], "weeks")) { - amendmentMajorityTime = weeks(duration); + AMENDMENT_MAJORITY_TIME = weeks(duration); } - if (amendmentMajorityTime < minutes(15)) + if (AMENDMENT_MAJORITY_TIME < minutes(15)) { Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME ", the minimum amount of time an amendment must hold a " @@ -939,10 +941,10 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_BETA_RPC_API, strTemp, j_)) - betaRpcApi = beast::lexicalCastThrow(strTemp); + BETA_RPC_API = beast::lexicalCastThrow(strTemp); // Do not load trusted validator configuration for standalone mode - if (!runStandalone_) + if (!RUN_STANDALONE_) { // If a file was explicitly specified, then throw if the // path is malformed or if the file does not exist or is @@ -964,8 +966,8 @@ Config::loadFromString(std::string const& fileContents) "]"); } - if (!validatorsFile.is_absolute() && !configDir.empty()) - validatorsFile = configDir / validatorsFile; + if (!validatorsFile.is_absolute() && !CONFIG_DIR.empty()) + validatorsFile = CONFIG_DIR / validatorsFile; if (!boost::filesystem::exists(validatorsFile)) { @@ -984,9 +986,9 @@ Config::loadFromString(std::string const& fileContents) validatorsFile.string()); } } - else if (!configDir.empty()) + else if (!CONFIG_DIR.empty()) { - validatorsFile = configDir / kValidatorsFileName; + validatorsFile = CONFIG_DIR / kVALIDATORS_FILE_NAME; if (!validatorsFile.empty()) { @@ -1059,7 +1061,7 @@ Config::loadFromString(std::string const& fileContents) } } - validatorListThreshold = [&]() -> std::optional { + VALIDATOR_LIST_THRESHOLD = [&]() -> std::optional { auto const& listThreshold = section(SECTION_VALIDATOR_LIST_THRESHOLD); if (listThreshold.lines().empty()) { @@ -1117,14 +1119,14 @@ Config::loadFromString(std::string const& fileContents) // This doesn't properly belong here, but check to make sure that the // value specified for network_quorum is achievable: { - auto pm = peersMax; + auto pm = PEERS_MAX; // FIXME this apparently magic value is actually defined as a constant // elsewhere (see defaultMaxPeers) but we handle this check here. if (pm == 0) pm = 21; - if (networkQuorum > pm) + if (NETWORK_QUORUM > pm) { Throw( "The minimum number of required peers (network_quorum) exceeds " @@ -1136,13 +1138,13 @@ Config::loadFromString(std::string const& fileContents) boost::filesystem::path Config::getDebugLogFile() const { - auto logFile = debugLogfile_; + auto logFile = DEBUG_LOGFILE_; if (!logFile.empty() && !logFile.is_absolute()) { // Unless an absolute path for the log file is specified, the // path is relative to the config file directory. - logFile = boost::filesystem::absolute(logFile, configDir); + logFile = boost::filesystem::absolute(logFile, CONFIG_DIR); } if (!logFile.empty()) @@ -1171,9 +1173,9 @@ int Config::getValueFor(SizedItem item, std::optional node) const { auto const index = static_cast>(item); - XRPL_ASSERT(index < kSizedItems.size(), "xrpl::Config::getValueFor : valid index input"); + XRPL_ASSERT(index < kSIZED_ITEMS.size(), "xrpl::Config::getValueFor : valid index input"); XRPL_ASSERT(!node || *node <= 4, "xrpl::Config::getValueFor : unset or valid node"); - return kSizedItems.at(index).second.at(node.value_or(nodeSize)); + return kSIZED_ITEMS.at(index).second.at(node.value_or(NODE_SIZE)); } FeeSetup @@ -1184,14 +1186,14 @@ setupFeeVote(Section const& section) std::uint64_t temp = 0; if (set(temp, "reference_fee", section) && temp <= std::numeric_limits::max()) - setup.referenceFee = temp; + setup.reference_fee = temp; } { std::uint32_t temp = 0; if (set(temp, "account_reserve", section)) - setup.accountReserve = temp; + setup.account_reserve = temp; if (set(temp, "owner_reserve", section)) - setup.ownerReserve = temp; + setup.owner_reserve = temp; } return setup; } @@ -1201,7 +1203,7 @@ setupDatabaseCon(Config const& c, std::optional j) { DatabaseCon::Setup setup; - setup.startUp = c.startUp; + setup.startUp = c.START_UP; setup.standAlone = c.standalone(); setup.dataDir = c.legacy("database_path"); if (!setup.standAlone && setup.dataDir.empty()) @@ -1255,7 +1257,7 @@ setupDatabaseCon(Config const& c, std::optional j) boost::iequals(journalMode, "wal")) { result->emplace_back( - boost::str(boost::format(kCommonDbPragmaJournal) % journalMode)); + boost::str(boost::format(kCOMMON_DB_PRAGMA_JOURNAL) % journalMode)); } else { @@ -1276,7 +1278,8 @@ setupDatabaseCon(Config const& c, std::optional j) if (higherRisk || boost::iequals(synchronous, "normal") || boost::iequals(synchronous, "full") || boost::iequals(synchronous, "extra")) { - result->emplace_back(boost::str(boost::format(kCommonDbPragmaSync) % synchronous)); + result->emplace_back( + boost::str(boost::format(kCOMMON_DB_PRAGMA_SYNC) % synchronous)); } else { @@ -1297,7 +1300,7 @@ setupDatabaseCon(Config const& c, std::optional j) if (higherRisk || boost::iequals(tempStore, "default") || boost::iequals(tempStore, "file")) { - result->emplace_back(boost::str(boost::format(kCommonDbPragmaTemp) % tempStore)); + result->emplace_back(boost::str(boost::format(kCOMMON_DB_PRAGMA_TEMP) % tempStore)); } else { @@ -1305,7 +1308,7 @@ setupDatabaseCon(Config const& c, std::optional j) } } - if (showRiskWarning && j && c.ledgerHistory > kSqliteTuningCutoff) + if (showRiskWarning && j && c.LEDGER_HISTORY > kSQLITE_TUNING_CUTOFF) { JLOG(j->warn()) << "reducing the data integrity guarantees from the " "default [sqlite] behavior is not recommended for " diff --git a/src/xrpld/overlay/Compression.h b/src/xrpld/overlay/Compression.h index fb58bd128a..91417913e3 100644 --- a/src/xrpld/overlay/Compression.h +++ b/src/xrpld/overlay/Compression.h @@ -5,8 +5,8 @@ namespace xrpl::compression { -constexpr std::size_t kHeaderBytes = 6; -constexpr std::size_t kHeaderBytesCompressed = 10; +std::size_t constexpr kHEADER_BYTES = 6; +std::size_t constexpr kHEADER_BYTES_COMPRESSED = 10; // All values other than 'none' must have the high bit. The low order four bits // must be 0. diff --git a/src/xrpld/overlay/Message.h b/src/xrpld/overlay/Message.h index cd21ca40c6..7c2701d443 100644 --- a/src/xrpld/overlay/Message.h +++ b/src/xrpld/overlay/Message.h @@ -11,7 +11,7 @@ namespace xrpl { -constexpr std::size_t kMaximumMessageSize = megabytes(64); +constexpr std::size_t kMAXIMUM_MESSAGE_SIZE = megabytes(64); // VFALCO NOTE If we forward declare Message and write out shared_ptr // instead of using the in-class type alias, we can remove the @@ -80,7 +80,7 @@ private: std::vector buffer_; std::vector bufferCompressed_; std::size_t category_; - std::once_flag onceFlag_; + std::once_flag once_flag_; std::optional validatorKey_; /** Set the payload header diff --git a/src/xrpld/overlay/Overlay.h b/src/xrpld/overlay/Overlay.h index ef97ea7f24..80430293d8 100644 --- a/src/xrpld/overlay/Overlay.h +++ b/src/xrpld/overlay/Overlay.h @@ -47,7 +47,6 @@ public: std::uint32_t crawlOptions = 0; std::optional networkID; bool vlEnabled = true; - bool verifyEndpoints = true; }; using PeerSequence = std::vector>; diff --git a/src/xrpld/overlay/ReduceRelayCommon.h b/src/xrpld/overlay/ReduceRelayCommon.h index 2389c21f0e..4105003315 100644 --- a/src/xrpld/overlay/ReduceRelayCommon.h +++ b/src/xrpld/overlay/ReduceRelayCommon.h @@ -13,27 +13,27 @@ namespace xrpl::reduce_relay { // where max_squelch is // min(max(MAX_UNSQUELCH_EXPIRE_DEFAULT, SQUELCH_PER_PEER * number_of_peers), // MAX_UNSQUELCH_EXPIRE_PEERS) -static constexpr auto kMinUnsquelchExpire = std::chrono::seconds{300}; -static constexpr auto kMaxUnsquelchExpireDefault = std::chrono::seconds{600}; -static constexpr auto kSquelchPerPeer = std::chrono::seconds(10); -static constexpr auto kMaxUnsquelchExpirePeers = std::chrono::seconds{3600}; +static constexpr auto kMIN_UNSQUELCH_EXPIRE = std::chrono::seconds{300}; +static constexpr auto kMAX_UNSQUELCH_EXPIRE_DEFAULT = std::chrono::seconds{600}; +static constexpr auto kSQUELCH_PER_PEER = std::chrono::seconds(10); +static constexpr auto kMAX_UNSQUELCH_EXPIRE_PEERS = std::chrono::seconds{3600}; // No message received threshold before identifying a peer as idled -static constexpr auto kIdled = std::chrono::seconds{8}; +static constexpr auto kIDLED = std::chrono::seconds{8}; // Message count threshold to start selecting peers as the source // of messages from the validator. We add peers who reach -// kMinMessageThreshold to considered pool once kMaxSelectedPeers -// reach kMaxMessageThreshold. -static constexpr uint16_t kMinMessageThreshold = 19; -static constexpr uint16_t kMaxMessageThreshold = 20; +// kMIN_MESSAGE_THRESHOLD to considered pool once kMAX_SELECTED_PEERS +// reach kMAX_MESSAGE_THRESHOLD. +static constexpr uint16_t kMIN_MESSAGE_THRESHOLD = 19; +static constexpr uint16_t kMAX_MESSAGE_THRESHOLD = 20; // Max selected peers to choose as the source of messages from validator -static constexpr uint16_t kMaxSelectedPeers = 5; +static constexpr uint16_t kMAX_SELECTED_PEERS = 5; // Wait before reduce-relay feature is enabled on boot up to let // the server establish peer connections -static constexpr auto kWaitOnBootup = std::chrono::minutes{10}; +static constexpr auto kWAIT_ON_BOOTUP = std::chrono::minutes{10}; // Maximum size of the aggregated transaction hashes per peer. // Once we get to high tps throughput, this cap will prevent // TMTransactions from exceeding the current protocol message // size limit of 64MB. -static constexpr std::size_t kMaxTxQueueSize = 10000; +static constexpr std::size_t kMAX_TX_QUEUE_SIZE = 10000; } // namespace xrpl::reduce_relay diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index 0600265500..26be3946c1 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -104,10 +104,10 @@ private: /** Update peer info. If the message is from a new * peer or from a previously expired squelched peer then switch * the peer's and slot's state to Counting. If time of last - * selection round is > 2 * kMaxUnsquelchExpireDefault then switch the + * selection round is > 2 * kMAX_UNSQUELCH_EXPIRE_DEFAULT then switch the * slot's state to Counting. If the number of messages for the peer is > - * kMinMessageThreshold then add peer to considered peers pool. If the - * number of considered peers who reached kMaxMessageThreshold is + * kMIN_MESSAGE_THRESHOLD then add peer to considered peers pool. If the + * number of considered peers who reached kMAX_MESSAGE_THRESHOLD is * maxSelectedPeers_ then randomly select maxSelectedPeers_ from * considered peers, and call squelch handler for each peer, which is not * selected and not already in Squelched state. Set the state for those @@ -181,9 +181,9 @@ private: void deleteIdlePeer(PublicKey const& validator); - /** Get random squelch duration between kMinUnsquelchExpire and - * min(max(kMaxUnsquelchExpireDefault, kSquelchPerPeer * npeers), - * kMaxUnsquelchExpirePeers) + /** Get random squelch duration between kMIN_UNSQUELCH_EXPIRE and + * min(max(kMAX_UNSQUELCH_EXPIRE_DEFAULT, kSQUELCH_PER_PEER * npeers), + * kMAX_UNSQUELCH_EXPIRE_PEERS) * @param npeers number of peers that can be squelched in the Slot */ std::chrono::seconds @@ -210,10 +210,10 @@ private: std::unordered_map peers_; // peer's data // pool of peers considered as the source of messages - // from validator - peers that reached kMinMessageThreshold + // from validator - peers that reached kMIN_MESSAGE_THRESHOLD std::unordered_set considered_; - // number of peers that reached kMaxMessageThreshold + // number of peers that reached kMAX_MESSAGE_THRESHOLD std::uint16_t reachedThreshold_{0}; // last time peers were selected, used to age the slot @@ -239,7 +239,7 @@ Slot::deleteIdlePeer(PublicKey const& validator) auto& peer = it->second; auto id = it->first; ++it; - if (now - peer.lastMessage > kIdled) + if (now - peer.lastMessage > kIDLED) { JLOG(journal_.trace()) << "deleteIdlePeer: " << Slice(validator) << " " << id << " idled " @@ -297,12 +297,12 @@ Slot::update( if (state_ != SlotState::Counting || peer.state == PeerState::Squelched) return; - if (++peer.count > kMinMessageThreshold) + if (++peer.count > kMIN_MESSAGE_THRESHOLD) considered_.insert(id); - if (peer.count == (kMaxMessageThreshold + 1)) + if (peer.count == (kMAX_MESSAGE_THRESHOLD + 1)) ++reachedThreshold_; - if (now - lastSelected_ > 2 * kMaxUnsquelchExpireDefault) + if (now - lastSelected_ > 2 * kMAX_UNSQUELCH_EXPIRE_DEFAULT) { JLOG(journal_.trace()) << "update: resetting due to inactivity " << Slice(validator) << " " << id << " " << duration_cast(now - lastSelected_).count(); @@ -333,7 +333,7 @@ Slot::update( << "update: peer not found " << Slice(validator) << " " << id; continue; } - if (now - itPeers->second.lastMessage < kIdled) + if (now - itPeers->second.lastMessage < kIDLED) selected.insert(id); } @@ -389,13 +389,13 @@ std::chrono::seconds Slot::getSquelchDuration(std::size_t npeers) { using namespace std::chrono; - auto m = std::max(kMaxUnsquelchExpireDefault, seconds{kSquelchPerPeer * npeers}); - if (m > kMaxUnsquelchExpirePeers) + auto m = std::max(kMAX_UNSQUELCH_EXPIRE_DEFAULT, seconds{kSQUELCH_PER_PEER * npeers}); + if (m > kMAX_UNSQUELCH_EXPIRE_PEERS) { - m = kMaxUnsquelchExpirePeers; + m = kMAX_UNSQUELCH_EXPIRE_PEERS; JLOG(journal_.warn()) << "getSquelchDuration: unexpected squelch duration " << npeers; } - return seconds{xrpl::randInt(kMinUnsquelchExpire / 1s, m / 1s)}; + return seconds{xrpl::randInt(kMIN_UNSQUELCH_EXPIRE / 1s, m / 1s)}; } template @@ -428,7 +428,7 @@ Slot::deletePeer(PublicKey const& validator, id_t id, bool erase) } else if (considered_.contains(id)) { - if (it->second.count > kMaxMessageThreshold) + if (it->second.count > kMAX_MESSAGE_THRESHOLD) --reachedThreshold_; considered_.erase(id); } @@ -544,8 +544,8 @@ public: : handler_(handler) , logs_(registry.getLogs()) , journal_(registry.getJournal("Slots")) - , baseSquelchEnabled_(config.vpReduceRelayBaseSquelchEnable) - , maxSelectedPeers_(config.vpReduceRelaySquelchMaxSelectedPeers) + , baseSquelchEnabled_(config.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) + , maxSelectedPeers_(config.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS) { } ~Slots() = default; @@ -557,14 +557,14 @@ public: return baseSquelchEnabled_ && reduceRelayReady(); } - /** Check if reduce_relay::kWaitOnBootup time passed since startup */ + /** Check if reduce_relay::kWAIT_ON_BOOTUP time passed since startup */ bool reduceRelayReady() { if (!reduceRelayReady_) { reduceRelayReady_ = reduce_relay::epoch(ClockType::now()) > - reduce_relay::kWaitOnBootup; + reduce_relay::kWAIT_ON_BOOTUP; } return reduceRelayReady_; @@ -708,7 +708,7 @@ template bool Slots::addPeerMessage(uint256 const& key, id_t id) { - beast::expire(peersWithMessage, reduce_relay::kIdled); + beast::expire(peersWithMessage, reduce_relay::kIDLED); if (key.isNonZero()) { @@ -782,7 +782,7 @@ Slots::deleteIdlePeers() for (auto it = slots_.begin(); it != slots_.end();) { it->second.deleteIdlePeer(it->first); - if (now - it->second.getLastSelected() > kMaxUnsquelchExpireDefault) + if (now - it->second.getLastSelected() > kMAX_UNSQUELCH_EXPIRE_DEFAULT) { JLOG(journal_.trace()) << "deleteIdlePeers: deleting idle slot " << Slice(it->first); it = slots_.erase(it); diff --git a/src/xrpld/overlay/Squelch.h b/src/xrpld/overlay/Squelch.h index b509f293c2..21a1b228a1 100644 --- a/src/xrpld/overlay/Squelch.h +++ b/src/xrpld/overlay/Squelch.h @@ -56,7 +56,7 @@ Squelch::addSquelch( PublicKey const& validator, std::chrono::seconds const& squelchDuration) { - if (squelchDuration >= kMinUnsquelchExpire && squelchDuration <= kMaxUnsquelchExpirePeers) + if (squelchDuration >= kMIN_UNSQUELCH_EXPIRE && squelchDuration <= kMAX_UNSQUELCH_EXPIRE_PEERS) { squelched_[validator] = ClockType::now() + squelchDuration; return true; diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index 295f4f5497..c83478ce1e 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -29,17 +28,19 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include #include -#include +#include #include #include @@ -51,7 +52,7 @@ ConnectAttempt::ConnectAttempt( endpoint_type remoteEndpoint, Resource::Consumer usage, shared_context const& context, - Peer::id_t id, + std::uint32_t id, std::shared_ptr const& slot, beast::Journal journal, OverlayImpl& overlay) @@ -64,6 +65,7 @@ ConnectAttempt::ConnectAttempt( , usage_(usage) , strand_(boost::asio::make_strand(ioContext)) , timer_(ioContext) + , stepTimer_(ioContext) , streamPtr_( std::make_unique( socket_type(std::forward(ioContext)), @@ -76,9 +78,10 @@ ConnectAttempt::ConnectAttempt( ConnectAttempt::~ConnectAttempt() { + // slot_ will be null if we successfully connected + // and transferred ownership to a PeerImp if (slot_ != nullptr) overlay_.peerFinder().onClosed(slot_); - JLOG(journal_.trace()) << "~ConnectAttempt"; } void @@ -89,17 +92,30 @@ ConnectAttempt::stop() boost::asio::post(strand_, std::bind(&ConnectAttempt::stop, shared_from_this())); return; } - if (socket_.is_open()) - { - JLOG(journal_.debug()) << "Stop"; - } - close(); + + if (!socket_.is_open()) + return; + + JLOG(journal_.debug()) << "stop: Stop"; + + shutdown(); } void ConnectAttempt::run() { - setTimer(); + if (!strand_.running_in_this_thread()) + { + boost::asio::post(strand_, std::bind(&ConnectAttempt::run, shared_from_this())); + return; + } + + JLOG(journal_.debug()) << "run: connecting to " << remoteEndpoint_; + + ioPending_ = true; + + // Allow up to connectTimeout_ seconds to establish remote peer connection + setTimer(ConnectionStep::TcpConnect); stream_.next_layer().async_connect( remoteEndpoint_, @@ -110,6 +126,73 @@ ConnectAttempt::run() //------------------------------------------------------------------------------ +void +ConnectAttempt::shutdown() +{ + XRPL_ASSERT( + strand_.running_in_this_thread(), "xrpl::ConnectAttempt::shutdown: strand in this thread"); + + if (!socket_.is_open()) + return; + + shutdown_ = true; + boost::beast::get_lowest_layer(stream_).cancel(); + + tryAsyncShutdown(); +} + +void +ConnectAttempt::tryAsyncShutdown() +{ + XRPL_ASSERT( + strand_.running_in_this_thread(), + "xrpl::ConnectAttempt::tryAsyncShutdown : strand in this thread"); + + if (!shutdown_ || currentStep_ == ConnectionStep::ShutdownStarted) + return; + + if (ioPending_) + return; + + // gracefully shutdown the SSL socket, performing a shutdown handshake + if (currentStep_ != ConnectionStep::TcpConnect && currentStep_ != ConnectionStep::TlsHandshake) + { + setTimer(ConnectionStep::ShutdownStarted); + stream_.async_shutdown(bind_executor( + strand_, + std::bind(&ConnectAttempt::onShutdown, shared_from_this(), std::placeholders::_1))); + return; + } + + close(); +} + +void +ConnectAttempt::onShutdown(error_code ec) +{ + cancelTimer(); + + if (ec) + { + // - eof: the stream was cleanly closed + // - operation_aborted: an expired timer (slow shutdown) + // - stream_truncated: the tcp connection closed (no handshake) it could + // occur if a peer does not perform a graceful disconnect + // - broken_pipe: the peer is gone + // - application data after close notify: benign SSL shutdown condition + bool const shouldLog = + (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && + ec.message().find("application data after close notify") == std::string::npos); + + if (shouldLog) + { + JLOG(journal_.debug()) << "onShutdown: " << ec.message(); + } + } + + close(); +} + void ConnectAttempt::close() { @@ -118,50 +201,93 @@ ConnectAttempt::close() if (!socket_.is_open()) return; - try - { - timer_.cancel(); - socket_.close(); - } - catch (boost::system::system_error const&) // NOLINT(bugprone-empty-catch) - { - // ignored - } + cancelTimer(); - JLOG(journal_.debug()) << "Closed"; + error_code ec; + socket_.close(ec); // NOLINT(bugprone-unused-return-value) } void ConnectAttempt::fail(std::string const& reason) { JLOG(journal_.debug()) << reason; - close(); + shutdown(); } void ConnectAttempt::fail(std::string const& name, error_code ec) { JLOG(journal_.debug()) << name << ": " << ec.message(); - close(); + shutdown(); } void -ConnectAttempt::setTimer() +ConnectAttempt::setTimer(ConnectionStep step) { - try + currentStep_ = step; + + // Set global timer (only if not already set) + if (timer_.expiry() == std::chrono::steady_clock::time_point{}) { - timer_.expires_after(std::chrono::seconds(15)); - } - catch (boost::system::system_error const& e) - { - JLOG(journal_.error()) << "setTimer: " << e.code(); - return; + try + { + timer_.expires_after(kCONNECT_TIMEOUT); + timer_.async_wait( + boost::asio::bind_executor( + strand_, + std::bind( + &ConnectAttempt::onTimer, shared_from_this(), std::placeholders::_1))); + } + catch (std::exception const& ex) + { + JLOG(journal_.error()) << "setTimer (global): " << ex.what(); + close(); + return; + } } - timer_.async_wait( - boost::asio::bind_executor( - strand_, - std::bind(&ConnectAttempt::onTimer, shared_from_this(), std::placeholders::_1))); + // Set step-specific timer + try + { + std::chrono::seconds stepTimeout; + switch (step) + { + case ConnectionStep::TcpConnect: + stepTimeout = StepTimeouts::kTCP_CONNECT; + break; + case ConnectionStep::TlsHandshake: + stepTimeout = StepTimeouts::kTLS_HANDSHAKE; + break; + case ConnectionStep::HttpWrite: + stepTimeout = StepTimeouts::kHTTP_WRITE; + break; + case ConnectionStep::HttpRead: + stepTimeout = StepTimeouts::kHTTP_READ; + break; + case ConnectionStep::ShutdownStarted: + stepTimeout = StepTimeouts::kTLS_SHUTDOWN; + break; + case ConnectionStep::Complete: + case ConnectionStep::Init: + return; // No timer needed for init or complete step + } + + // call to expires_after cancels previous timer + stepTimer_.expires_after(stepTimeout); + stepTimer_.async_wait( + boost::asio::bind_executor( + strand_, + std::bind(&ConnectAttempt::onTimer, shared_from_this(), std::placeholders::_1))); + + JLOG(journal_.trace()) << "setTimer: " << stepToString(step) + << " timeout=" << stepTimeout.count() << "s"; + } + catch (std::exception const& ex) + { + JLOG(journal_.error()) << "setTimer (step " << stepToString(step) << "): " << ex.what(); + close(); + return; + } } void @@ -170,6 +296,7 @@ ConnectAttempt::cancelTimer() try { timer_.cancel(); + stepTimer_.cancel(); } catch (boost::system::system_error const&) // NOLINT(bugprone-empty-catch) { @@ -194,18 +321,40 @@ ConnectAttempt::onTimer(error_code ec) close(); return; } - fail("Timeout"); + + // Determine which timer expired by checking their expiry times + auto const now = std::chrono::steady_clock::now(); + bool const globalExpired = (timer_.expiry() <= now); + bool const stepExpired = (stepTimer_.expiry() <= now); + + if (globalExpired) + { + JLOG(journal_.debug()) << "onTimer: Global timeout; step: " << stepToString(currentStep_); + } + else if (stepExpired) + { + JLOG(journal_.debug()) << "onTimer: Step timeout; step: " << stepToString(currentStep_); + } + else + { + JLOG(journal_.warn()) << "onTimer: Unexpected timer callback"; + } + + close(); } void ConnectAttempt::onConnect(error_code ec) { - cancelTimer(); + ioPending_ = false; if (ec) { if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; + } fail("onConnect", ec); return; @@ -222,7 +371,15 @@ ConnectAttempt::onConnect(error_code ec) return; } - setTimer(); + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + + ioPending_ = true; + + setTimer(ConnectionStep::TlsHandshake); stream_.set_verify_mode(boost::asio::ssl::verify_none); stream_.async_handshake( @@ -235,14 +392,15 @@ ConnectAttempt::onConnect(error_code ec) void ConnectAttempt::onHandshake(error_code ec) { - cancelTimer(); - if (!socket_.is_open()) - return; + ioPending_ = false; if (ec) { if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; + } fail("onHandshake", ec); return; @@ -255,26 +413,29 @@ ConnectAttempt::onHandshake(error_code ec) return; } + setTimer(ConnectionStep::HttpWrite); + + // check if we connected to ourselves if (!overlay_.peerFinder().onConnected( slot_, beast::IPAddressConversion::fromAsio(localEndpoint))) { - fail("Duplicate connection"); + fail("Self connection"); return; } auto const sharedValue = makeSharedValue(*streamPtr_, journal_); if (!sharedValue) { - close(); // makeSharedValue logs - return; + shutdown(); + return; // makeSharedValue logs } req_ = makeRequest( !overlay_.peerFinder().config().peerPrivate, - app_.config().compression, - app_.config().ledgerReplay, - app_.config().txReduceRelayEnable, - app_.config().vpReduceRelayBaseSquelchEnable); + app_.config().COMPRESSION, + app_.config().LEDGER_REPLAY, + app_.config().TX_REDUCE_RELAY_ENABLE, + app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); buildHandshake( req_, @@ -284,7 +445,14 @@ ConnectAttempt::onHandshake(error_code ec) remoteEndpoint_.address(), app_); - setTimer(); + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + + ioPending_ = true; + boost::beast::http::async_write( stream_, req_, @@ -296,20 +464,30 @@ ConnectAttempt::onHandshake(error_code ec) void ConnectAttempt::onWrite(error_code ec) { - cancelTimer(); - - if (!socket_.is_open()) - return; + ioPending_ = false; if (ec) { if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; + } fail("onWrite", ec); return; } + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + + ioPending_ = true; + + setTimer(ConnectionStep::HttpRead); + boost::beast::http::async_read( stream_, readBuf_, @@ -323,24 +501,21 @@ void ConnectAttempt::onRead(error_code ec) { cancelTimer(); - - if (!socket_.is_open()) - return; + ioPending_ = false; + currentStep_ = ConnectionStep::Complete; if (ec) { - if (ec == boost::asio::error::operation_aborted) - return; - if (ec == boost::asio::error::eof) { JLOG(journal_.debug()) << "EOF"; - setTimer(); - stream_.async_shutdown( - boost::asio::bind_executor( - strand_, - std::bind( - &ConnectAttempt::onShutdown, shared_from_this(), std::placeholders::_1))); + shutdown(); + return; + } + + if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; } @@ -348,73 +523,85 @@ ConnectAttempt::onRead(error_code ec) return; } + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + processResponse(); } -void -ConnectAttempt::onShutdown(error_code ec) -{ - cancelTimer(); - if (!ec) - { - close(); - return; - } - - if (ec != boost::asio::error::eof) - { - fail("onShutdown", ec); - return; - } - close(); -} - //-------------------------------------------------------------------------- void ConnectAttempt::processResponse() { - if (response_.result() == boost::beast::http::status::service_unavailable) - { - json::Value json; - json::Reader r; - std::string s; - s.reserve(boost::asio::buffer_size(response_.body().data())); - for (auto const buffer : response_.body().data()) - { - s.append(static_cast(buffer.data()), boost::asio::buffer_size(buffer)); - } - auto const success = r.parse(s, json); - if (success) - { - if (json.isObject() && json.isMember("peer-ips")) - { - json::Value const& ips = json["peer-ips"]; - if (ips.isArray()) - { - std::vector eps; - eps.reserve(ips.size()); - for (auto const& v : ips) - { - if (v.isString()) - { - error_code ec; - auto const ep = parseEndpoint(v.asString(), ec); - if (!ec) - eps.push_back(ep); - } - } - overlay_.peerFinder().onRedirects(remoteEndpoint_, eps); - } - } - } - } - if (!OverlayImpl::isPeerUpgrade(response_)) { - JLOG(journal_.info()) << "Unable to upgrade to peer protocol: " << response_.result() - << " (" << response_.reason() << ")"; - close(); + // A peer may respond with service_unavailable and a list of alternative + // peers to connect to, a differing status code is unexpected + if (response_.result() != boost::beast::http::status::service_unavailable) + { + JLOG(journal_.warn()) << "Unable to upgrade to peer protocol: " << response_.result() + << " (" << response_.reason() << ")"; + shutdown(); + return; + } + + // Parse response body to determine if this is a redirect or other + // service unavailable + std::string responseBody; + responseBody.reserve(boost::asio::buffer_size(response_.body().data())); + for (auto const buffer : response_.body().data()) + { + responseBody.append( + static_cast(buffer.data()), boost::asio::buffer_size(buffer)); + } + + json::Value json; + json::Reader reader; + auto const isValidJson = reader.parse(responseBody, json); + + // Check if this is a redirect response (contains peer-ips field) + auto const isRedirect = isValidJson && json.isObject() && json.isMember("peer-ips"); + + if (!isRedirect) + { + JLOG(journal_.warn()) << "processResponse: " << remoteEndpoint_ + << " failed to upgrade to peer protocol: " << response_.result() + << " (" << response_.reason() << ")"; + + shutdown(); + return; + } + + json::Value const& peerIps = json["peer-ips"]; + if (!peerIps.isArray()) + { + fail("processResponse: invalid peer-ips format"); + return; + } + + // Extract and validate peer endpoints + std::vector redirectEndpoints; + redirectEndpoints.reserve(peerIps.size()); + + for (auto const& ipValue : peerIps) + { + if (!ipValue.isString()) + continue; + + error_code ec; + auto const endpoint = parseEndpoint(ipValue.asString(), ec); + if (!ec) + redirectEndpoints.push_back(endpoint); + } + + // Notify PeerFinder about the redirect redirectEndpoints may be empty + overlay_.peerFinder().onRedirects(remoteEndpoint_, redirectEndpoints); + + fail("processResponse: failed to connect to peer: redirected"); return; } @@ -438,8 +625,8 @@ ConnectAttempt::processResponse() auto const sharedValue = makeSharedValue(*streamPtr_, journal_); if (!sharedValue) { - close(); // makeSharedValue logs - return; + shutdown(); + return; // makeSharedValue logs } try @@ -454,9 +641,8 @@ ConnectAttempt::processResponse() usage_.setPublicKey(publicKey); - JLOG(journal_.info()) << "Public Key: " << toBase58(TokenType::NodePublic, publicKey); - JLOG(journal_.debug()) << "Protocol: " << to_string(*negotiatedProtocol); + JLOG(journal_.info()) << "Public Key: " << toBase58(TokenType::NodePublic, publicKey); auto const member = app_.getCluster().member(publicKey); if (member) @@ -464,11 +650,21 @@ ConnectAttempt::processResponse() JLOG(journal_.info()) << "Cluster name: " << *member; } - auto const result = - overlay_.peerFinder().activate(slot_, publicKey, static_cast(member)); + auto const result = overlay_.peerFinder().activate(slot_, publicKey, member.has_value()); if (result != PeerFinder::Result::Success) { - fail("Outbound " + std::string(to_string(result))); + std::stringstream ss; + ss << "Outbound Connect Attempt " << remoteEndpoint_ << " " << to_string(result); + fail(ss.str()); + return; + } + + if (!socket_.is_open()) + return; + + if (shutdown_) + { + tryAsyncShutdown(); return; } diff --git a/src/xrpld/overlay/detail/ConnectAttempt.h b/src/xrpld/overlay/detail/ConnectAttempt.h index aba224d5c7..70ce7912ba 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.h +++ b/src/xrpld/overlay/detail/ConnectAttempt.h @@ -1,13 +1,42 @@ #pragma once -#include #include -#include +#include namespace xrpl { -/** Manages an outbound connection attempt. */ +/** + * @class ConnectAttempt + * @brief Manages outbound peer connection attempts with comprehensive timeout + * handling + * + * The ConnectAttempt class handles the complete lifecycle of establishing an + * outbound connection to a peer in the XRPL network. It implements a + * sophisticated dual-timer system that provides both global timeout protection + * and per-step timeout diagnostics. + * + * The connection establishment follows these steps: + * 1. **TCP Connect**: Establish basic network connection + * 2. **TLS Handshake**: Negotiate SSL/TLS encryption + * 3. **HTTP Write**: Send peer handshake request + * 4. **HTTP Read**: Receive and validate peer response + * 5. **Complete**: Connection successfully established + * + * Uses a hybrid timeout approach: + * - **Global Timer**: Hard limit (20s) for entire connection process + * - **Step Timers**: Individual timeouts for each connection phase + * + * - All errors result in connection termination + * + * All operations are serialized using boost::asio::strand to ensure thread + * safety. The class is designed to be used exclusively within the ASIO event + * loop. + * + * @note This class should not be used directly. It is managed by OverlayImpl + * as part of the peer discovery and connection management system. + * + */ class ConnectAttempt : public OverlayImpl::Child, public std::enable_shared_from_this { @@ -16,29 +45,95 @@ private: using endpoint_type = boost::asio::ip::tcp::endpoint; using request_type = boost::beast::http::request; using response_type = boost::beast::http::response; - using socket_type = boost::asio::ip::tcp::socket; using middle_type = boost::beast::tcp_stream; using stream_type = boost::beast::ssl_stream; using shared_context = std::shared_ptr; + /** + * @enum ConnectionStep + * @brief Represents the current phase of the connection establishment + * process + * + * Used for tracking progress and providing detailed timeout diagnostics. + * Each step has its own timeout value defined in StepTimeouts. + */ + enum class ConnectionStep { + Init, // Initial state, nothing started + TcpConnect, // Establishing TCP connection to remote peer + TlsHandshake, // Performing SSL/TLS handshake + HttpWrite, // Sending HTTP upgrade request + HttpRead, // Reading HTTP upgrade response + Complete, // Connection successfully established + ShutdownStarted // Connection shutdown has started + }; + + // A timeout for connection process, greater than all step timeouts + static constexpr std::chrono::seconds kCONNECT_TIMEOUT{25}; + + /** + * @struct StepTimeouts + * @brief Defines timeout values for each connection step + * + * These timeouts are designed to detect slow individual phases while + * allowing the global timeout to enforce the overall time limit. + */ + struct StepTimeouts + { + // TCP connection timeout + static constexpr std::chrono::seconds kTCP_CONNECT{8}; + // SSL handshake timeout + static constexpr std::chrono::seconds kTLS_HANDSHAKE{8}; + // HTTP write timeout + static constexpr std::chrono::seconds kHTTP_WRITE{3}; + // HTTP read timeout + static constexpr std::chrono::seconds kHTTP_READ{3}; + // SSL shutdown timeout + static constexpr std::chrono::seconds kTLS_SHUTDOWN{2}; + }; + + // Core application and networking components Application& app_; - std::uint32_t const id_; + Peer::id_t const id_; beast::WrappedSink sink_; beast::Journal const journal_; endpoint_type remoteEndpoint_; Resource::Consumer usage_; + boost::asio::strand strand_; boost::asio::basic_waitable_timer timer_; - std::unique_ptr streamPtr_; + boost::asio::basic_waitable_timer stepTimer_; + + std::unique_ptr streamPtr_; // SSL stream (owned) socket_type& socket_; stream_type& stream_; boost::beast::multi_buffer readBuf_; + response_type response_; std::shared_ptr slot_; request_type req_; + bool shutdown_ = false; // Shutdown has been initiated + bool ioPending_ = false; // Async I/O operation in progress + ConnectionStep currentStep_ = ConnectionStep::Init; + public: + /** + * @brief Construct a new ConnectAttempt object + * + * @param app Application context providing configuration and services + * @param ioContext ASIO I/O context for async operations + * @param remoteEndpoint Target peer endpoint to connect to + * @param usage Resource usage tracker for rate limiting + * @param context Shared SSL context for encryption + * @param id Unique peer identifier for this connection attempt + * @param slot PeerFinder slot representing this connection + * @param journal Logging interface for diagnostics + * @param overlay Parent overlay manager + * + * @note The constructor only initializes the object. Call run() to begin + * the actual connection attempt. + */ ConnectAttempt( Application& app, boost::asio::io_context& ioContext, @@ -52,38 +147,111 @@ public: ~ConnectAttempt() override; + /** + * @brief Stop the connection attempt + * + * This method is thread-safe and can be called from any thread. + */ void stop() override; + /** + * @brief Begin the connection attempt + * + * This method is thread-safe and posts to the strand if needed. + */ void run(); private: + /** + * @brief Set timers for the specified connection step + * + * @param step The connection step to set timers for + * + * Sets both the step-specific timer and the global timer (if not already + * set). + */ void - close(); - void - fail(std::string const& reason); - void - fail(std::string const& name, error_code ec); - void - setTimer(); + setTimer(ConnectionStep step); + + /** + * @brief Cancel both global and step timers + * + * Used during cleanup and when connection completes successfully. + * Exceptions from timer cancellation are safely ignored. + */ void cancelTimer(); + + /** + * @brief Handle timer expiration events + * + * @param ec Error code from timer operation + * + * Determines which timer expired (global vs step) and logs appropriate + * diagnostic information before terminating the connection. + */ void onTimer(error_code ec); + + // Connection phase handlers void - onConnect(error_code ec); + onConnect(error_code ec); // TCP connection completion handler void - onHandshake(error_code ec); + onHandshake(error_code ec); // TLS handshake completion handler void - onWrite(error_code ec); + onWrite(error_code ec); // HTTP write completion handler void - onRead(error_code ec); + onRead(error_code ec); // HTTP read completion handler + + // Error and cleanup handlers void - onShutdown(error_code ec); + fail(std::string const& reason); // Fail with custom reason + void + fail(std::string const& name, error_code ec); // Fail with system error + void + shutdown(); // Initiate graceful shutdown + void + tryAsyncShutdown(); // Attempt async SSL shutdown + void + onShutdown(error_code ec); // SSL shutdown completion handler + void + close(); // Force close socket + + /** + * @brief Process the HTTP upgrade response from peer + * + * Validates the peer's response, extracts protocol information, + * verifies handshake, and either creates a PeerImp or handles + * redirect responses. + */ void processResponse(); + static std::string + stepToString(ConnectionStep step) + { + switch (step) + { + case ConnectionStep::Init: + return "Init"; + case ConnectionStep::TcpConnect: + return "TcpConnect"; + case ConnectionStep::TlsHandshake: + return "TlsHandshake"; + case ConnectionStep::HttpWrite: + return "HttpWrite"; + case ConnectionStep::HttpRead: + return "HttpRead"; + case ConnectionStep::Complete: + return "Complete"; + case ConnectionStep::ShutdownStarted: + return "ShutdownStarted"; + } + return "Unknown"; + }; + template static boost::asio::ip::tcp::endpoint parseEndpoint(std::string const& s, boost::system::error_code& ec) diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index 39fd93f1d4..af0585f8ad 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -88,13 +88,13 @@ makeFeaturesRequestHeader( { std::stringstream str; if (comprEnabled) - str << kFeatureCompr << "=lz4" << kDelimFeature; + str << kFEATURE_COMPR << "=lz4" << kDELIM_FEATURE; if (ledgerReplayEnabled) - str << kFeatureLedgerReplay << "=1" << kDelimFeature; + str << kFEATURE_LEDGER_REPLAY << "=1" << kDELIM_FEATURE; if (txReduceRelayEnabled) - str << kFeatureTxrr << "=1" << kDelimFeature; + str << kFEATURE_TXRR << "=1" << kDELIM_FEATURE; if (vpReduceRelayEnabled) - str << kFeatureVprr << "=1" << kDelimFeature; + str << kFEATURE_VPRR << "=1" << kDELIM_FEATURE; return str.str(); } @@ -107,14 +107,14 @@ makeFeaturesResponseHeader( bool vpReduceRelayEnabled) { std::stringstream str; - if (comprEnabled && isFeatureValue(headers, kFeatureCompr, "lz4")) - str << kFeatureCompr << "=lz4" << kDelimFeature; - if (ledgerReplayEnabled && featureEnabled(headers, kFeatureLedgerReplay)) - str << kFeatureLedgerReplay << "=1" << kDelimFeature; - if (txReduceRelayEnabled && featureEnabled(headers, kFeatureTxrr)) - str << kFeatureTxrr << "=1" << kDelimFeature; - if (vpReduceRelayEnabled && featureEnabled(headers, kFeatureVprr)) - str << kFeatureVprr << "=1" << kDelimFeature; + if (comprEnabled && isFeatureValue(headers, kFEATURE_COMPR, "lz4")) + str << kFEATURE_COMPR << "=lz4" << kDELIM_FEATURE; + if (ledgerReplayEnabled && featureEnabled(headers, kFEATURE_LEDGER_REPLAY)) + str << kFEATURE_LEDGER_REPLAY << "=1" << kDELIM_FEATURE; + if (txReduceRelayEnabled && featureEnabled(headers, kFEATURE_TXRR)) + str << kFEATURE_TXRR << "=1" << kDELIM_FEATURE; + if (vpReduceRelayEnabled && featureEnabled(headers, kFEATURE_VPRR)) + str << kFEATURE_VPRR << "=1" << kDELIM_FEATURE; return str.str(); } @@ -132,20 +132,20 @@ makeFeaturesResponseHeader( this topic, see https://github.com/openssl/openssl/issues/5509 and https://github.com/XRPLF/rippled/issues/2413. */ -static std::optional> +static std::optional> hashLastMessage(SSL const* ssl, size_t (*get)(const SSL*, void*, size_t)) { - static constexpr std::size_t kSslMinimumFinishedLength = 12; + constexpr std::size_t kSSL_MINIMUM_FINISHED_LENGTH = 12; unsigned char buf[1024]; size_t const len = get(ssl, buf, sizeof(buf)); - if (len < kSslMinimumFinishedLength) + if (len < kSSL_MINIMUM_FINISHED_LENGTH) return std::nullopt; sha512_hasher const h; - BaseUInt<512> cookie; + BaseUint<512> cookie; SHA512(buf, len, cookie.data()); return cookie; } @@ -171,7 +171,7 @@ makeSharedValue(stream_type& ssl, beast::Journal journal) // Both messages hash to the same value and the cookie // is 0. Don't allow this. - if (result == beast::kZero) + if (result == beast::kZERO) { JLOG(journal.error()) << "Cookie generation: identical finished messages"; return std::nullopt; @@ -209,8 +209,8 @@ buildHandshake( h.insert("Instance-Cookie", std::to_string(app.instanceID())); - if (!app.config().serverDomain.empty()) - h.insert("Server-Domain", app.config().serverDomain); + if (!app.config().SERVER_DOMAIN.empty()) + h.insert("Server-Domain", app.config().SERVER_DOMAIN); if (beast::IP::isPublic(remoteIp)) h.insert("Remote-IP", remoteIp.to_string()); @@ -408,10 +408,10 @@ makeResponse( "X-Protocol-Ctl", makeFeaturesResponseHeader( req, - app.config().compression, - app.config().ledgerReplay, - app.config().txReduceRelayEnable, - app.config().vpReduceRelayBaseSquelchEnable)); + app.config().COMPRESSION, + app.config().LEDGER_REPLAY, + app.config().TX_REDUCE_RELAY_ENABLE, + app.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE)); buildHandshake(resp, sharedValue, networkID, publicIp, remoteIp, app); diff --git a/src/xrpld/overlay/detail/Handshake.h b/src/xrpld/overlay/detail/Handshake.h index 3cbaa118da..77a346477f 100644 --- a/src/xrpld/overlay/detail/Handshake.h +++ b/src/xrpld/overlay/detail/Handshake.h @@ -115,15 +115,15 @@ makeResponse( // value: \S+ // compression feature -static constexpr char kFeatureCompr[] = "compr"; +static constexpr char kFEATURE_COMPR[] = "compr"; // validation/proposal reduce-relay base squelch feature -static constexpr char kFeatureVprr[] = "vprr"; +static constexpr char kFEATURE_VPRR[] = "vprr"; // transaction reduce-relay feature -static constexpr char kFeatureTxrr[] = "txrr"; +static constexpr char kFEATURE_TXRR[] = "txrr"; // ledger replay -static constexpr char kFeatureLedgerReplay[] = "ledgerreplay"; -static constexpr char kDelimFeature[] = ";"; -static constexpr char kDelimValue[] = ","; +static constexpr char kFEATURE_LEDGER_REPLAY[] = "ledgerreplay"; +static constexpr char kDELIM_FEATURE[] = ";"; +static constexpr char kDELIM_VALUE[] = ","; /** Get feature's header value @param headers request/response header diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 120b34c78c..30f4c281ed 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -31,12 +31,12 @@ Message::Message( XRPL_ASSERT(messageBytes, "xrpl::Message::Message : non-empty message input"); - buffer_.resize(kHeaderBytes + messageBytes); + buffer_.resize(kHEADER_BYTES + messageBytes); setHeader(buffer_.data(), messageBytes, type, Algorithm::None, 0); if (messageBytes != 0) - message.SerializeToArray(buffer_.data() + kHeaderBytes, messageBytes); + message.SerializeToArray(buffer_.data() + kHEADER_BYTES, messageBytes); XRPL_ASSERT( getBufferSize() == totalSize(message), @@ -58,14 +58,14 @@ Message::messageSize(::google::protobuf::Message const& message) std::size_t Message::totalSize(::google::protobuf::Message const& message) { - return messageSize(message) + compression::kHeaderBytes; + return messageSize(message) + compression::kHEADER_BYTES; } void Message::compress() { using namespace xrpl::compression; - auto const messageBytes = buffer_.size() - kHeaderBytes; + auto const messageBytes = buffer_.size() - kHEADER_BYTES; auto type = getType(buffer_.data()); @@ -104,19 +104,19 @@ Message::compress() if (compressible) { - auto payload = static_cast(buffer_.data() + kHeaderBytes); + auto payload = static_cast(buffer_.data() + kHEADER_BYTES); auto compressedSize = xrpl::compression::compress( payload, messageBytes, [&](std::size_t inSize) { // size of required compressed buffer - bufferCompressed_.resize(inSize + kHeaderBytesCompressed); - return (bufferCompressed_.data() + kHeaderBytesCompressed); + bufferCompressed_.resize(inSize + kHEADER_BYTES_COMPRESSED); + return (bufferCompressed_.data() + kHEADER_BYTES_COMPRESSED); }); - if (compressedSize < (messageBytes - (kHeaderBytesCompressed - kHeaderBytes))) + if (compressedSize < (messageBytes - (kHEADER_BYTES_COMPRESSED - kHEADER_BYTES))) { - bufferCompressed_.resize(kHeaderBytesCompressed + compressedSize); + bufferCompressed_.resize(kHEADER_BYTES_COMPRESSED + compressedSize); // NOLINTNEXTLINE(readability-suspicious-call-argument) setHeader(bufferCompressed_.data(), compressedSize, type, Algorithm::LZ4, messageBytes); } @@ -203,7 +203,7 @@ Message::getBuffer(Compressed tryCompressed) if (tryCompressed == Compressed::Off) return buffer_; - std::call_once(onceFlag_, &Message::compress, this); + std::call_once(once_flag_, &Message::compress, this); if (!bufferCompressed_.empty()) { diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index b31f54058a..e21d00a1e7 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -92,11 +92,15 @@ namespace xrpl { namespace CrawlOptions { -static constexpr auto kDisabled = 0; -static constexpr auto kOverlay = (1 << 0); -static constexpr auto kServerInfo = (1 << 1); -static constexpr auto kServerCounts = (1 << 2); -static constexpr auto kUNL = (1 << 3); +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + Disabled = 0, + Overlay = (1 << 0), + ServerInfo = (1 << 1), + ServerCounts = (1 << 2), + Unl = (1 << 3) +}; } // namespace CrawlOptions //------------------------------------------------------------------------------ @@ -112,7 +116,7 @@ OverlayImpl::Child::~Child() //------------------------------------------------------------------------------ -OverlayImpl::Timer::Timer(OverlayImpl& overlay) : Child(overlay), timer(overlay_.ioContext_) +OverlayImpl::Timer::Timer(OverlayImpl& overlay) : Child(overlay), timer(overlay_.io_context_) { } @@ -150,10 +154,10 @@ OverlayImpl::Timer::onTimer(error_code ec) overlay_.peerFinder_->oncePerSecond(); overlay_.sendEndpoints(); overlay_.autoConnect(); - if (overlay_.app_.config().txReduceRelayEnable) + if (overlay_.app_.config().TX_REDUCE_RELAY_ENABLE) overlay_.sendTxQueue(); - if ((++overlay_.timerCount_ % Tuning::kCheckIdlePeers) == 0) + if ((++overlay_.timer_count_ % Tuning::CheckIdlePeers) == 0) overlay_.deleteIdlePeers(); asyncWait(); @@ -171,9 +175,9 @@ OverlayImpl::OverlayImpl( BasicConfig const& config, beast::insight::Collector::ptr const& collector) : app_(app) - , ioContext_(ioContext) - , work_(std::in_place, boost::asio::make_work_guard(ioContext_)) - , strand_(boost::asio::make_strand(ioContext_)) + , io_context_(ioContext) + , work_(std::in_place, boost::asio::make_work_guard(io_context_)) + , strand_(boost::asio::make_strand(io_context_)) , setup_(std::move(setup)) , journal_(app_.getJournal("Overlay")) , serverHandler_(serverHandler) @@ -186,7 +190,7 @@ OverlayImpl::OverlayImpl( config, collector)) , resolver_(resolver) - , nextId_(1) + , next_id_(1) , slots_(app, *this, app.config()) , stats_( std::bind(&OverlayImpl::collectMetrics, this), @@ -209,7 +213,7 @@ OverlayImpl::onHandoff( http_request_type&& request, endpoint_type remoteEndpoint) { - auto const id = nextId_++; + auto const id = next_id_++; auto peerJournal = app_.getJournal("Peer"); beast::WrappedSink sink(peerJournal.sink(), makePrefix(id)); beast::Journal const journal(sink); @@ -259,7 +263,7 @@ OverlayImpl::onHandoff( { handoff.moved = false; handoff.response = makeRedirectResponse(slot, request, remoteEndpoint.address()); - handoff.keepAlive = beast::rfc2616::isKeepAlive(request); + handoff.keep_alive = beast::rfc2616::isKeepAlive(request); return handoff; } } @@ -271,7 +275,7 @@ OverlayImpl::onHandoff( handoff.moved = false; handoff.response = makeErrorResponse( slot, request, remoteEndpoint.address(), "Unable to agree on a protocol version"); - handoff.keepAlive = false; + handoff.keep_alive = false; return handoff; } @@ -282,7 +286,7 @@ OverlayImpl::onHandoff( handoff.moved = false; handoff.response = makeErrorResponse(slot, request, remoteEndpoint.address(), "Incorrect security cookie"); - handoff.keepAlive = false; + handoff.keep_alive = false; return handoff; } @@ -311,7 +315,7 @@ OverlayImpl::onHandoff( << "Peer " << remoteEndpoint << " redirected, " << to_string(result); handoff.moved = false; handoff.response = makeRedirectResponse(slot, request, remoteEndpoint.address()); - handoff.keepAlive = false; + handoff.keep_alive = false; return handoff; } } @@ -351,7 +355,7 @@ OverlayImpl::onHandoff( peerFinder_->onClosed(slot); handoff.moved = false; handoff.response = makeErrorResponse(slot, request, remoteEndpoint.address(), e.what()); - handoff.keepAlive = false; + handoff.keep_alive = false; return handoff; } } @@ -392,9 +396,9 @@ OverlayImpl::makeRedirectResponse( } msg.insert("Content-Type", "application/json"); msg.insert(boost::beast::http::field::connection, "close"); - msg.body() = json::ValueType::Object; + msg.body() = json::ObjectValue; { - json::Value& ips = (msg.body()["peer-ips"] = json::ValueType::Array); + json::Value& ips = (msg.body()["peer-ips"] = json::ArrayValue); for (auto const& _ : peerFinder_->redirect(slot)) ips.append(_.address.toString()); } @@ -444,11 +448,11 @@ OverlayImpl::connect(beast::IP::Endpoint const& remoteEndpoint) auto const p = std::make_shared( app_, - ioContext_, + io_context_, beast::IPAddressConversion::toAsioEndpoint(remoteEndpoint), usage, setup_.context, - nextId_++, + next_id_++, slot, app_.getJournal("Peer"), *this); @@ -471,14 +475,14 @@ OverlayImpl::addActive(std::shared_ptr const& peer) { auto const result = peers_.emplace(peer->slot(), peer); - XRPL_ASSERT(result.second, "xrpl::OverlayImpl::addActive : peer is inserted"); + XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer is inserted"); (void)result.second; } { auto const result = ids_.emplace( std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer)); - XRPL_ASSERT(result.second, "xrpl::OverlayImpl::addActive : peer ID is inserted"); + XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer ID is inserted"); (void)result.second; } @@ -508,15 +512,14 @@ OverlayImpl::start() app_.config(), serverHandler_.setup().overlay.port(), app_.getValidationPublicKey().has_value(), - setup_.ipLimit, - setup_.verifyEndpoints); + setup_.ipLimit); peerFinder_->setConfig(config); peerFinder_->start(); // Populate our boot cache: if there are no entries in [ips] then we use // the entries in [ips_fixed]. - auto bootstrapIps = app_.config().ips.empty() ? app_.config().ipsFixed : app_.config().ips; + auto bootstrapIps = app_.config().IPS.empty() ? app_.config().IPS_FIXED : app_.config().IPS; // If nothing is specified, default to several well-known high-capacity // servers to serve as bootstrap: @@ -544,7 +547,7 @@ OverlayImpl::start() { if (addr.port() == 0) { - ips.push_back(to_string(addr.atPort(kDefaultPeerPort))); + ips.push_back(to_string(addr.atPort(kDEFAULT_PEER_PORT))); } else { @@ -558,10 +561,10 @@ OverlayImpl::start() }); // Add the ips_fixed from the xrpld.cfg file - if (!app_.config().standalone() && !app_.config().ipsFixed.empty()) + if (!app_.config().standalone() && !app_.config().IPS_FIXED.empty()) { resolver_.resolve( - app_.config().ipsFixed, + app_.config().IPS_FIXED, [this](std::string const& name, std::vector const& addresses) { std::vector ips; ips.reserve(addresses.size()); @@ -570,7 +573,7 @@ OverlayImpl::start() { if (addr.port() == 0) { - ips.emplace_back(addr.address(), kDefaultPeerPort); + ips.emplace_back(addr.address(), kDEFAULT_PEER_PORT); } else { @@ -746,10 +749,10 @@ OverlayImpl::getOverlayInfo() const { using namespace std::chrono; json::Value jv; - auto& av = jv[jss::active] = json::Value(json::ValueType::Array); + auto& av = jv[jss::active] = json::Value(json::ArrayValue); forEach([&](std::shared_ptr const& sp) { - auto& pv = av.append(json::Value(json::ValueType::Object)); + auto& pv = av.append(json::Value(json::ObjectValue)); pv[jss::public_key] = base64Encode(sp->getNodePublic().data(), sp->getNodePublic().size()); pv[jss::type] = sp->slot()->inbound() ? jss::in : jss::out; pv[jss::uptime] = static_cast(duration_cast(sp->uptime()).count()); @@ -862,7 +865,7 @@ OverlayImpl::json() bool OverlayImpl::processCrawl(http_request_type const& req, Handoff& handoff) { - if (req.target() != "/crawl" || setup_.crawlOptions == CrawlOptions::kDisabled) + if (req.target() != "/crawl" || setup_.crawlOptions == CrawlOptions::Disabled) return false; boost::beast::http::response msg; @@ -873,19 +876,19 @@ OverlayImpl::processCrawl(http_request_type const& req, Handoff& handoff) msg.insert("Connection", "close"); msg.body()["version"] = json::Value(2u); - if ((setup_.crawlOptions & CrawlOptions::kOverlay) != 0u) + if ((setup_.crawlOptions & CrawlOptions::Overlay) != 0u) { msg.body()["overlay"] = getOverlayInfo(); } - if ((setup_.crawlOptions & CrawlOptions::kServerInfo) != 0u) + if ((setup_.crawlOptions & CrawlOptions::ServerInfo) != 0u) { msg.body()["server"] = getServerInfo(); } - if ((setup_.crawlOptions & CrawlOptions::kServerCounts) != 0u) + if ((setup_.crawlOptions & CrawlOptions::ServerCounts) != 0u) { msg.body()["counts"] = getServerCounts(); } - if ((setup_.crawlOptions & CrawlOptions::kUNL) != 0u) + if ((setup_.crawlOptions & CrawlOptions::Unl) != 0u) { msg.body()["unl"] = getUnlInfo(); } @@ -900,9 +903,9 @@ OverlayImpl::processValidatorList(http_request_type const& req, Handoff& handoff { // If the target is in the form "/vl/", // return the most recent validator list for that key. - constexpr std::string_view kPrefix("/vl/"); + constexpr std::string_view kPREFIX("/vl/"); - if (!req.target().starts_with(kPrefix) || !setup_.vlEnabled) + if (!req.target().starts_with(kPREFIX) || !setup_.vlEnabled) return false; std::uint32_t version = 1; @@ -917,14 +920,14 @@ OverlayImpl::processValidatorList(http_request_type const& req, Handoff& handoff msg.result(status); msg.insert("Content-Length", "0"); - msg.body() = json::ValueType::Null; + msg.body() = json::NullValue; msg.prepare_payload(); handoff.response = std::make_shared(msg); return true; }; - std::string_view key = req.target().substr(kPrefix.size()); + std::string_view key = req.target().substr(kPREFIX.size()); if (auto slash = key.find('/'); slash != std::string_view::npos) { @@ -986,7 +989,7 @@ OverlayImpl::processHealth(http_request_type const& req, Handoff& handoff) auto health = HealthState::Healthy; auto setHealth = [&health](HealthState state) { health = std::max(health, state); }; - msg.body()[jss::info] = json::ValueType::Object; + msg.body()[jss::info] = json::ObjectValue; if (lastValidatedLedgerAge >= 7 || lastValidatedLedgerAge < 0) { msg.body()[jss::info][jss::validated_ledger] = lastValidatedLedgerAge; @@ -1257,7 +1260,7 @@ OverlayImpl::relay( if (!relay) { - if (!app_.config().txReduceRelayEnable) + if (!app_.config().TX_REDUCE_RELAY_ENABLE) return; peers = getActivePeers(toSkip, total, disabled, enabledInSkip); @@ -1270,13 +1273,13 @@ OverlayImpl::relay( auto& txn = tx->get(); auto const sm = std::make_shared(txn, protocol::mtTRANSACTION); peers = getActivePeers(toSkip, total, disabled, enabledInSkip); - auto const minRelay = app_.config().txReduceRelayMinPeers + disabled; + auto const minRelay = app_.config().TX_REDUCE_RELAY_MIN_PEERS + disabled; - if (!app_.config().txReduceRelayEnable || total <= minRelay) + if (!app_.config().TX_REDUCE_RELAY_ENABLE || total <= minRelay) { for (auto const& p : peers) p->send(sm); - if (app_.config().txReduceRelayEnable || app_.config().txReduceRelayMetrics) + if (app_.config().TX_REDUCE_RELAY_ENABLE || app_.config().TX_REDUCE_RELAY_METRICS) txMetrics_.addMetrics(total, toSkip.size(), 0); return; } @@ -1284,8 +1287,8 @@ OverlayImpl::relay( // We have more peers than the minimum (disabled + minimum enabled), // relay to all disabled and some randomly selected enabled that // do not have the transaction. - auto const enabledTarget = app_.config().txReduceRelayMinPeers + - ((total - minRelay) * app_.config().txRelayPercentage / 100); + auto const enabledTarget = app_.config().TX_REDUCE_RELAY_MIN_PEERS + + ((total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100); txMetrics_.addMetrics(enabledTarget, toSkip.size(), disabled); @@ -1511,7 +1514,7 @@ OverlayImpl::deleteIdlePeers() //------------------------------------------------------------------------------ Overlay::Setup -setupOverlay(BasicConfig const& config, beast::Journal j) +setupOverlay(BasicConfig const& config) { Overlay::Setup setup; @@ -1529,17 +1532,9 @@ setupOverlay(BasicConfig const& config, beast::Journal j) { boost::system::error_code ec; setup.publicIp = boost::asio::ip::make_address(ip, ec); - if (ec || !beast::IP::isPublic(setup.publicIp)) + if (ec || beast::IP::isPrivate(setup.publicIp)) Throw("Configured public IP is invalid"); } - - set(setup.verifyEndpoints, true, "verify_endpoints", section); - if (!setup.verifyEndpoints) - { - JLOG(j.warn()) << "Endpoint verification is disabled. This is a " - "security risk and should only be used for " - "testing."; - } } { @@ -1571,19 +1566,19 @@ setupOverlay(BasicConfig const& config, beast::Journal j) { if (get(section, "overlay", true)) { - setup.crawlOptions |= CrawlOptions::kOverlay; + setup.crawlOptions |= CrawlOptions::Overlay; } if (get(section, "server", true)) { - setup.crawlOptions |= CrawlOptions::kServerInfo; + setup.crawlOptions |= CrawlOptions::ServerInfo; } if (get(section, "counts", false)) { - setup.crawlOptions |= CrawlOptions::kServerCounts; + setup.crawlOptions |= CrawlOptions::ServerCounts; } if (get(section, "unl", true)) { - setup.crawlOptions |= CrawlOptions::kUNL; + setup.crawlOptions |= CrawlOptions::Unl; } } } diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 6fcc2df854..65c93a5845 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -80,7 +80,7 @@ private: }; Application& app_; - boost::asio::io_context& ioContext_; + boost::asio::io_context& io_context_; std::optional> work_; boost::asio::strand strand_; mutable std::recursive_mutex mutex_; // VFALCO use std::mutex @@ -96,8 +96,8 @@ private: hash_map, std::weak_ptr> peers_; hash_map> ids_; Resolver& resolver_; - std::atomic nextId_; - int timerCount_{0}; + std::atomic next_id_; + int timer_count_{0}; std::atomic jqTransOverflow_{0}; std::atomic peerDisconnects_{0}; std::atomic peerDisconnectsCharges_{0}; diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 325f8ba038..fa65cb604a 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -74,7 +74,7 @@ #include #include #include -#include +#include #include @@ -105,10 +105,13 @@ namespace xrpl { namespace { /** The threshold above which we treat a peer connection as high latency */ -constexpr std::chrono::milliseconds kPeerHighLatency{300}; +std::chrono::milliseconds constexpr kPEER_HIGH_LATENCY{300}; /** How often we PING the peer to check for latency and sendq probe */ -constexpr std::chrono::seconds kPeerTimerInterval{60}; +std::chrono::seconds constexpr kPEER_TIMER_INTERVAL{60}; + +/** The timeout for a shutdown timer */ +std::chrono::seconds constexpr kSHUTDOWN_TIMER_INTERVAL{5}; } // namespace @@ -150,25 +153,27 @@ PeerImp::PeerImp( , creationTime_(clock_type::now()) , squelch_(app_.getJournal("Squelch")) , usage_(consumer) - , fee_{.fee = Resource::kFeeTrivialPeer, .context = ""} + , fee_{.fee = Resource::kFEE_TRIVIAL_PEER, .context = ""} , slot_(slot) , request_(std::move(request)) , headers_(request_) , compressionEnabled_( - peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().compression) + peerFeatureEnabled(headers_, kFEATURE_COMPR, "lz4", app_.config().COMPRESSION) ? Compressed::On : Compressed::Off) , txReduceRelayEnabled_( - peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().txReduceRelayEnable)) + peerFeatureEnabled(headers_, kFEATURE_TXRR, app_.config().TX_REDUCE_RELAY_ENABLE)) , ledgerReplayEnabled_( - peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().ledgerReplay)) + peerFeatureEnabled(headers_, kFEATURE_LEDGER_REPLAY, app_.config().LEDGER_REPLAY)) , ledgerReplayMsgHandler_(app, app.getLedgerReplayer()) { - JLOG(journal_.info()) - << "compression enabled " << (compressionEnabled_ == Compressed::On) - << " vp reduce-relay base squelch enabled " - << peerFeatureEnabled(headers_, kFeatureVprr, app_.config().vpReduceRelayBaseSquelchEnable) - << " tx reduce-relay enabled " << txReduceRelayEnabled_; + JLOG(journal_.info()) << "compression enabled " << (compressionEnabled_ == Compressed::On) + << " vp reduce-relay base squelch enabled " + << peerFeatureEnabled( + headers_, + kFEATURE_VPRR, + app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) + << " tx reduce-relay enabled " << txReduceRelayEnabled_; } PeerImp::~PeerImp() @@ -188,7 +193,7 @@ PeerImp::~PeerImp() // Helper function to check for valid uint256 values in protobuf buffers static bool -stringIsUInt256Sized(std::string const& pBuffStr) +stringIsUint256Sized(std::string const& pBuffStr) { return pBuffStr.size() == uint256::size(); } @@ -207,7 +212,7 @@ PeerImp::run() return ret; if (auto const s = base64Decode(value); s.size() == uint256::size()) - return uint256::fromRaw(s); + return uint256{s}; return std::nullopt; }; @@ -267,7 +272,13 @@ PeerImp::stop() if (!socket_.is_open()) return; - close(); + // The rationale for using different severity levels is that + // outbound connections are under our control and may be logged + // at a higher level, but inbound connections are more numerous and + // uncontrolled so to prevent log flooding the severity is reduced. + JLOG(journal_.debug()) << "stop: Stop"; + + shutdown(); } //------------------------------------------------------------------------------ @@ -280,13 +291,17 @@ PeerImp::send(std::shared_ptr const& m) post(strand_, std::bind(&PeerImp::send, shared_from_this(), m)); return; } - if (gracefulClose_) - return; - if (detaching_) - return; + if (!socket_.is_open()) return; + // we are in progress of closing the connection + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + auto validator = m->getValidatorKey(); if (validator && !squelch_.expireSquelch(*validator)) { @@ -307,14 +322,14 @@ PeerImp::send(std::shared_ptr const& m) auto sendqSize = sendQueue_.size(); - if (sendqSize < Tuning::kTargetSendQueue) + if (sendqSize < Tuning::TargetSendQueue) { // To detect a peer that does not read from their // side of the connection, we expect a peer to have // a small senq periodically largeSendq_ = 0; } - else if (auto sink = journal_.debug(); sink && (sendqSize % Tuning::kSendQueueLogFreq) == 0) + else if (auto sink = journal_.debug(); sink && (sendqSize % Tuning::SendQueueLogFreq) == 0) { std::string const n = name(); sink << n << " sendq: " << sendqSize; @@ -325,6 +340,7 @@ PeerImp::send(std::shared_ptr const& m) if (sendqSize != 0) return; + writePending_ = true; boost::asio::async_write( stream_, boost::asio::buffer(sendQueue_.front()->getBuffer(compressionEnabled_)), @@ -366,7 +382,7 @@ PeerImp::addTxQueue(uint256 const& hash) return; } - if (txQueue_.size() == reduce_relay::kMaxTxQueueSize) + if (txQueue_.size() == reduce_relay::kMAX_TX_QUEUE_SIZE) { JLOG(pJournal_.warn()) << "addTxQueue exceeds the cap"; sendTxQueue(); @@ -429,7 +445,7 @@ PeerImp::getVersion() const json::Value PeerImp::json() { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::public_key] = toBase58(TokenType::NodePublic, publicKey_); ret[jss::address] = remoteAddress_.toString(); @@ -499,7 +515,7 @@ PeerImp::json() lastStatus = lastStatus_; } - if (closedLedgerHash != beast::kZero) + if (closedLedgerHash != beast::kZERO) ret[jss::ledger] = to_string(closedLedgerHash); if (lastStatus.has_newstatus()) @@ -531,7 +547,7 @@ PeerImp::json() } } - ret[jss::metrics] = json::Value(json::ValueType::Object); + ret[jss::metrics] = json::Value(json::ObjectValue); ret[jss::metrics][jss::total_bytes_recv] = std::to_string(metrics_.recv.totalBytes()); ret[jss::metrics][jss::total_bytes_sent] = std::to_string(metrics_.sent.totalBytes()); ret[jss::metrics][jss::avg_bps_recv] = std::to_string(metrics_.recv.averageBytes()); @@ -607,20 +623,16 @@ PeerImp::hasRange(std::uint32_t uMin, std::uint32_t uMax) //------------------------------------------------------------------------------ void -PeerImp::close() +PeerImp::fail(std::string const& name, error_code ec) { - XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::close : strand in this thread"); + XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::fail : strand in this thread"); + if (!socket_.is_open()) return; - detaching_ = true; // DEPRECATED + JLOG(journal_.warn()) << name << ": " << ec.message(); - cancelTimer(); - error_code ec; - socket_.close(ec); // NOLINT(bugprone-unused-return-value) - - overlay_.incPeerDisconnect(); - JLOG((inbound_ ? journal_.debug() : journal_.info())) << "close: Closed"; + shutdown(); } void @@ -634,69 +646,121 @@ PeerImp::fail(std::string const& reason) (void (Peer::*)(std::string const&))&PeerImp::fail, shared_from_this(), reason)); return; } - if (journal_.active(beast::Severity::Warning) && socket_.is_open()) + + if (!socket_.is_open()) + return; + + // Call to name() locks, log only if the message will be outputted + if (journal_.active(beast::severities::KWarning)) { std::string const n = name(); JLOG(journal_.warn()) << n << " failed: " << reason; } - close(); + + shutdown(); } void -PeerImp::fail(std::string const& name, error_code ec) -{ - XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::fail : strand in this thread"); - if (!socket_.is_open()) - return; - - JLOG(journal_.warn()) << name << ": " << ec.message(); - - close(); -} - -void -PeerImp::gracefulClose() +PeerImp::tryAsyncShutdown() { XRPL_ASSERT( - strand_.running_in_this_thread(), "xrpl::PeerImp::gracefulClose : strand in this thread"); - XRPL_ASSERT(socket_.is_open(), "xrpl::PeerImp::gracefulClose : socket is open"); - XRPL_ASSERT(!gracefulClose_, "xrpl::PeerImp::gracefulClose : socket is not closing"); - gracefulClose_ = true; - if (!sendQueue_.empty()) + strand_.running_in_this_thread(), + "xrpl::PeerImp::tryAsyncShutdown : strand in this thread"); + + if (!shutdown_ || shutdownStarted_) return; - setTimer(); + + if (readPending_ || writePending_) + return; + + shutdownStarted_ = true; + + setTimer(kSHUTDOWN_TIMER_INTERVAL); + + // gracefully shutdown the SSL socket, performing a shutdown handshake stream_.async_shutdown(bind_executor( strand_, std::bind(&PeerImp::onShutdown, shared_from_this(), std::placeholders::_1))); } void -PeerImp::setTimer() +PeerImp::shutdown() { - try - { - timer_.expires_after(kPeerTimerInterval); - } - catch (boost::system::system_error const& e) - { - JLOG(journal_.error()) << "setTimer: " << e.code(); + XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::shutdown: strand in this thread"); + + if (!socket_.is_open() || shutdown_) return; - } - timer_.async_wait(bind_executor( - strand_, std::bind(&PeerImp::onTimer, shared_from_this(), std::placeholders::_1))); + + shutdown_ = true; + + boost::beast::get_lowest_layer(stream_).cancel(); + + tryAsyncShutdown(); } -// convenience for ignoring the error code void -PeerImp::cancelTimer() noexcept +PeerImp::onShutdown(error_code ec) +{ + cancelTimer(); + if (ec) + { + // - eof: the stream was cleanly closed + // - operation_aborted: an expired timer (slow shutdown) + // - stream_truncated: the tcp connection closed (no handshake) it could + // occur if a peer does not perform a graceful disconnect + // - broken_pipe: the peer is gone + bool const shouldLog = + (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && + ec.message().find("application data after close notify") == std::string::npos); + + if (shouldLog) + { + JLOG(journal_.debug()) << "onShutdown: " << ec.message(); + } + } + + close(); +} + +void +PeerImp::close() +{ + XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::close : strand in this thread"); + + if (!socket_.is_open()) + return; + + cancelTimer(); + + error_code ec; + socket_.close(ec); // NOLINT(bugprone-unused-return-value) + + overlay_.incPeerDisconnect(); + + // The rationale for using different severity levels is that + // outbound connections are under our control and may be logged + // at a higher level, but inbound connections are more numerous and + // uncontrolled so to prevent log flooding the severity is reduced. + JLOG((inbound_ ? journal_.debug() : journal_.info())) << "close: Closed"; +} + +//------------------------------------------------------------------------------ + +void +PeerImp::setTimer(std::chrono::seconds interval) { try { - timer_.cancel(); + timer_.expires_after(interval); } - catch (boost::system::system_error const&) // NOLINT(bugprone-empty-catch) + catch (std::exception const& ex) { - // ignored + JLOG(journal_.error()) << "setTimer: " << ex.what(); + shutdown(); + return; } + + timer_.async_wait(bind_executor( + strand_, std::bind(&PeerImp::onTimer, shared_from_this(), std::placeholders::_1))); } //------------------------------------------------------------------------------ @@ -712,11 +776,14 @@ PeerImp::makePrefix(std::string const& fingerprint) void PeerImp::onTimer(error_code const& ec) { + XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::PeerImp::onTimer : strand in this thread"); + if (!socket_.is_open()) return; if (ec) { + // do not initiate shutdown, timers are frequently cancelled if (ec == boost::asio::error::operation_aborted) return; @@ -726,7 +793,16 @@ PeerImp::onTimer(error_code const& ec) return; } - if (largeSendq_++ >= Tuning::kSendqIntervals) + // the timer expired before the shutdown completed + // force close the connection + if (shutdown_) + { + JLOG(journal_.debug()) << "onTimer: shutdown timer expired"; + close(); + return; + } + + if (largeSendq_++ >= Tuning::SendqIntervals) { fail("Large send queue"); return; @@ -741,8 +817,8 @@ PeerImp::onTimer(error_code const& ec) duration = clock_type::now() - trackingTime_; } - if ((t == Tracking::Diverged && (duration > app_.config().maxDivergedTime)) || - (t == Tracking::Unknown && (duration > app_.config().maxUnknownTime))) + if ((t == Tracking::Diverged && (duration > app_.config().MAX_DIVERGED_TIME)) || + (t == Tracking::Unknown && (duration > app_.config().MAX_UNKNOWN_TIME))) { overlay_.peerFinder().onFailure(slot_); fail("Not useful"); @@ -766,32 +842,20 @@ PeerImp::onTimer(error_code const& ec) send(std::make_shared(message, protocol::mtPING)); - setTimer(); + setTimer(kPEER_TIMER_INTERVAL); } void -PeerImp::onShutdown(error_code ec) +PeerImp::cancelTimer() noexcept { - cancelTimer(); - - if (ec) + try { - // - eof: the stream was cleanly closed - // - operation_aborted: an expired timer (slow shutdown) - // - stream_truncated: the tcp connection closed (no handshake) it could - // occur if a peer does not perform a graceful disconnect - // - broken_pipe: the peer is gone - bool const shouldLog = - (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && - ec.message().find("application data after close notify") == std::string::npos); - - if (shouldLog) - { - JLOG(journal_.debug()) << "onShutdown: " << ec.message(); - } + timer_.cancel(); + } + catch (std::exception const& ex) + { + JLOG(journal_.error()) << "cancelTimer: " << ex.what(); } - - close(); } //------------------------------------------------------------------------------ @@ -800,6 +864,15 @@ PeerImp::doAccept() { XRPL_ASSERT(readBuffer_.size() == 0, "xrpl::PeerImp::doAccept : empty read buffer"); + JLOG(journal_.debug()) << "doAccept"; + + // a shutdown was initiated before the handshake, there is nothing to do + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + auto const sharedValue = makeSharedValue(*streamPtr_, journal_); // This shouldn't fail since we already computed @@ -810,7 +883,7 @@ PeerImp::doAccept() return; } - JLOG(journal_.info()) << "Protocol: " << to_string(protocol_); + JLOG(journal_.debug()) << "Protocol: " << to_string(protocol_); if (auto member = app_.getCluster().member(publicKey_)) { @@ -850,15 +923,16 @@ PeerImp::doAccept() error_code ec, std::size_t bytesTransferred) { if (!socket_.is_open()) return; + if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); + return; + } if (ec) { - if (ec == boost::asio::error::operation_aborted) - return; - fail("onWriteResponse", ec); return; } - if (writeBuffer->size() == bytesTransferred) { doProtocolStart(); @@ -889,6 +963,13 @@ PeerImp::domain() const void PeerImp::doProtocolStart() { + // a shutdown was initiated before the handshare, there is nothing to do + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + onReadMessage(error_code(), 0); // Send all the validator lists that have been loaded @@ -920,31 +1001,45 @@ PeerImp::doProtocolStart() if (auto m = overlay_.getManifestsMessage()) send(m); - setTimer(); + setTimer(kPEER_TIMER_INTERVAL); } // Called repeatedly with protocol message data void PeerImp::onReadMessage(error_code ec, std::size_t bytesTransferred) { + XRPL_ASSERT( + strand_.running_in_this_thread(), "xrpl::PeerImp::onReadMessage : strand in this thread"); + + readPending_ = false; + if (!socket_.is_open()) return; if (ec) { - if (ec == boost::asio::error::operation_aborted) - return; - if (ec == boost::asio::error::eof) { - JLOG(journal_.info()) << "EOF"; - gracefulClose(); + JLOG(journal_.debug()) << "EOF"; + shutdown(); + return; + } + + if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; } fail("onReadMessage", ec); return; } + // we started shutdown, no reason to process further data + if (shutdown_) + { + tryAsyncShutdown(); + return; + } if (auto stream = journal_.trace()) { @@ -956,7 +1051,7 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytesTransferred) readBuffer_.commit(bytesTransferred); - auto hint = Tuning::kReadBufferBytes; + auto hint = Tuning::kREAD_BUFFER_BYTES; while (readBuffer_.size() > 0) { @@ -969,26 +1064,37 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytesTransferred) 350ms, journal_); + if (!socket_.is_open()) + return; + + // the error_code is produced by invokeProtocolMessage + // it could be due to a bad message if (ec) { fail("onReadMessage", ec); return; } - if (!socket_.is_open()) - return; - - if (gracefulClose_) - return; - if (bytesConsumed == 0) break; + readBuffer_.consume(bytesConsumed); } + // check if a shutdown was initiated while processing messages + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + + readPending_ = true; + + XRPL_ASSERT(!shutdownStarted_, "xrpl::PeerImp::onReadMessage : shutdown started"); + // Timeout on writes only stream_.async_read_some( - readBuffer_.prepare(std::max(Tuning::kReadBufferBytes, hint)), + readBuffer_.prepare(std::max(Tuning::kREAD_BUFFER_BYTES, hint)), bind_executor( strand_, std::bind( @@ -1001,17 +1107,26 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytesTransferred) void PeerImp::onWriteMessage(error_code ec, std::size_t bytesTransferred) { + XRPL_ASSERT( + strand_.running_in_this_thread(), "xrpl::PeerImp::onWriteMessage : strand in this thread"); + + writePending_ = false; + if (!socket_.is_open()) return; if (ec) { if (ec == boost::asio::error::operation_aborted) + { + tryAsyncShutdown(); return; + } fail("onWriteMessage", ec); return; } + if (auto stream = journal_.trace()) { stream << "onWriteMessage: " @@ -1022,8 +1137,18 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytesTransferred) XRPL_ASSERT(!sendQueue_.empty(), "xrpl::PeerImp::onWriteMessage : non-empty send buffer"); sendQueue_.pop(); + + if (shutdown_) + { + tryAsyncShutdown(); + return; + } + if (!sendQueue_.empty()) { + writePending_ = true; + XRPL_ASSERT(!shutdownStarted_, "xrpl::PeerImp::onWriteMessage : shutdown started"); + // Timeout on writes only boost::asio::async_write( stream_, @@ -1037,13 +1162,6 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytesTransferred) std::placeholders::_2))); return; } - - if (gracefulClose_) - { - stream_.async_shutdown(bind_executor( - strand_, std::bind(&PeerImp::onShutdown, shared_from_this(), std::placeholders::_1))); - return; - } } //------------------------------------------------------------------------------ @@ -1068,7 +1186,7 @@ PeerImp::onMessageBegin( { auto const name = protocolMessageName(type); loadEvent_ = app_.getJobQueue().makeLoadEvent(JtPeer, name); - fee_ = {.fee = Resource::kFeeTrivialPeer, .context = name}; + fee_ = {.fee = Resource::kFEE_TRIVIAL_PEER, .context = name}; auto const category = TrafficCount::categorize(*m, static_cast(type), true); @@ -1090,7 +1208,7 @@ PeerImp::onMessageBegin( // LEDGER_DATA category == TrafficCount::Category::GlTscShare || category == TrafficCount::Category::GlTscGet) && - (txReduceRelayEnabled() || app_.config().txReduceRelayMetrics)) + (txReduceRelayEnabled() || app_.config().TX_REDUCE_RELAY_METRICS)) { overlay_.addTxMetrics(static_cast(type), static_cast(size)); } @@ -1112,12 +1230,12 @@ PeerImp::onMessage(std::shared_ptr const& m) if (s == 0) { - fee_.update(Resource::kFeeUselessData, "empty"); + fee_.update(Resource::kFEE_USELESS_DATA, "empty"); return; } if (s > 100) - fee_.update(Resource::kFeeModerateBurdenPeer, "oversize"); + fee_.update(Resource::kFEE_MODERATE_BURDEN_PEER, "oversize"); app_.getJobQueue().addJob(JtManifest, "RcvManifests", [this, that = shared_from_this(), m]() { overlay_.onManifests(m, that); @@ -1130,7 +1248,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (m->type() == protocol::TMPing::ptPING) { // We have received a ping request, reply with a pong - fee_.update(Resource::kFeeModerateBurdenPeer, "ping request"); + fee_.update(Resource::kFEE_MODERATE_BURDEN_PEER, "ping request"); m->set_type(protocol::TMPing::ptPONG); send(std::make_shared(*m, protocol::mtPING)); return; @@ -1171,7 +1289,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // VFALCO NOTE I think we should drop the peer immediately if (!cluster()) { - fee_.update(Resource::kFeeUselessData, "unknown cluster"); + fee_.update(Resource::kFEE_USELESS_DATA, "unknown cluster"); return; } @@ -1246,7 +1364,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // implication for the protocol. if (m->endpoints_v2().size() >= 1024) { - fee_.update(Resource::kFeeUselessData, "endpoints too large"); + fee_.update(Resource::kFEE_USELESS_DATA, "endpoints too large"); return; } @@ -1283,7 +1401,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (malformed > 0) { fee_.update( - Resource::kFeeInvalidData * malformed, + Resource::kFEE_INVALID_DATA * malformed, std::to_string(malformed) + " malformed endpoints"); } @@ -1344,20 +1462,20 @@ PeerImp::handleTransaction( { JLOG(pJournal_.warn()) << "Ignoring Network relayed Tx containing " "tfInnerBatchTxn (handleTransaction)."; - fee_.update(Resource::kFeeModerateBurdenPeer, "inner batch txn"); + fee_.update(Resource::kFEE_MODERATE_BURDEN_PEER, "inner batch txn"); return; } // LCOV_EXCL_STOP HashRouterFlags flags = HashRouterFlags::UNDEFINED; - static constexpr std::chrono::seconds kTxInterval = 10s; + constexpr std::chrono::seconds kTX_INTERVAL = 10s; - if (!app_.getHashRouter().shouldProcess(txID, id_, flags, kTxInterval)) + if (!app_.getHashRouter().shouldProcess(txID, id_, flags, kTX_INTERVAL)) { // we have seen this transaction recently if (any(flags & HashRouterFlags::BAD)) { - fee_.update(Resource::kFeeUselessData, "known bad"); + fee_.update(Resource::kFEE_USELESS_DATA, "known bad"); JLOG(pJournal_.debug()) << "Ignoring known bad tx " << txID; } @@ -1400,7 +1518,7 @@ PeerImp::handleTransaction( { JLOG(pJournal_.trace()) << "No new transactions until synchronized"; } - else if (app_.getJobQueue().getJobCount(JtTransaction) > app_.config().maxTransactions) + else if (app_.getJobQueue().getJobCount(JtTransaction) > app_.config().MAX_TRANSACTIONS) { overlay_.incJqTransOverflow(); JLOG(pJournal_.info()) << "Transaction queue is full"; @@ -1431,7 +1549,7 @@ void PeerImp::onMessage(std::shared_ptr const& m) { auto badData = [&](std::string const& msg) { - fee_.update(Resource::kFeeInvalidData, "get_ledger " + msg); + fee_.update(Resource::kFEE_INVALID_DATA, "get_ledger " + msg); JLOG(pJournal_.warn()) << "TMGetLedger: " << msg; }; auto const itype{m->itype()}; @@ -1472,7 +1590,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } // Verify ledger hash - if (m->has_ledgerhash() && !stringIsUInt256Sized(m->ledgerhash())) + if (m->has_ledgerhash() && !stringIsUint256Sized(m->ledgerhash())) { badData("Invalid ledger hash"); return; @@ -1522,7 +1640,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // Verify query depth if (m->has_querydepth()) { - if (m->querydepth() > Tuning::kMaxQueryDepth || itype == protocol::liBASE) + if (m->querydepth() > Tuning::MaxQueryDepth || itype == protocol::liBASE) { badData("Invalid query depth"); return; @@ -1543,11 +1661,11 @@ PeerImp::onMessage(std::shared_ptr const& m) JLOG(pJournal_.trace()) << "onMessage, TMProofPathRequest"; if (!ledgerReplayEnabled_) { - fee_.update(Resource::kFeeMalformedRequest, "proof_path_request disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "proof_path_request disabled"); return; } - fee_.update(Resource::kFeeModerateBurdenPeer, "received a proof path request"); + fee_.update(Resource::kFEE_MODERATE_BURDEN_PEER, "received a proof path request"); std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(JtReplayReq, "RcvProofPReq", [weak, m]() { if (auto peer = weak.lock()) @@ -1557,11 +1675,11 @@ PeerImp::onMessage(std::shared_ptr const& m) { if (reply.error() == protocol::TMReplyError::reBAD_REQUEST) { - peer->charge(Resource::kFeeMalformedRequest, "proof_path_request"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "proof_path_request"); } else { - peer->charge(Resource::kFeeRequestNoReply, "proof_path_request"); + peer->charge(Resource::kFEE_REQUEST_NO_REPLY, "proof_path_request"); } } else @@ -1577,13 +1695,13 @@ PeerImp::onMessage(std::shared_ptr const& m) { if (!ledgerReplayEnabled_) { - fee_.update(Resource::kFeeMalformedRequest, "proof_path_response disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "proof_path_response disabled"); return; } if (!ledgerReplayMsgHandler_.processProofPathResponse(m)) { - fee_.update(Resource::kFeeInvalidData, "proof_path_response"); + fee_.update(Resource::kFEE_INVALID_DATA, "proof_path_response"); } } @@ -1593,11 +1711,11 @@ PeerImp::onMessage(std::shared_ptr const& m) JLOG(pJournal_.trace()) << "onMessage, TMReplayDeltaRequest"; if (!ledgerReplayEnabled_) { - fee_.update(Resource::kFeeMalformedRequest, "replay_delta_request disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "replay_delta_request disabled"); return; } - fee_.fee = Resource::kFeeModerateBurdenPeer; + fee_.fee = Resource::kFEE_MODERATE_BURDEN_PEER; std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(JtReplayReq, "RcvReplDReq", [weak, m]() { if (auto peer = weak.lock()) @@ -1607,11 +1725,11 @@ PeerImp::onMessage(std::shared_ptr const& m) { if (reply.error() == protocol::TMReplyError::reBAD_REQUEST) { - peer->charge(Resource::kFeeMalformedRequest, "replay_delta_request"); + peer->charge(Resource::kFEE_MALFORMED_REQUEST, "replay_delta_request"); } else { - peer->charge(Resource::kFeeRequestNoReply, "replay_delta_request"); + peer->charge(Resource::kFEE_REQUEST_NO_REPLY, "replay_delta_request"); } } else @@ -1627,13 +1745,13 @@ PeerImp::onMessage(std::shared_ptr const& m) { if (!ledgerReplayEnabled_) { - fee_.update(Resource::kFeeMalformedRequest, "replay_delta_response disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "replay_delta_response disabled"); return; } if (!ledgerReplayMsgHandler_.processReplayDeltaResponse(m)) { - fee_.update(Resource::kFeeInvalidData, "replay_delta_response"); + fee_.update(Resource::kFEE_INVALID_DATA, "replay_delta_response"); } } @@ -1641,12 +1759,12 @@ void PeerImp::onMessage(std::shared_ptr const& m) { auto badData = [&](std::string const& msg) { - fee_.update(Resource::kFeeInvalidData, msg); + fee_.update(Resource::kFEE_INVALID_DATA, msg); JLOG(pJournal_.warn()) << "TMLedgerData: " << msg; }; // Verify ledger hash - if (!stringIsUInt256Sized(m->ledgerhash())) + if (!stringIsUint256Sized(m->ledgerhash())) { badData("Invalid ledger hash"); return; @@ -1692,7 +1810,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } // Verify ledger nodes. - if (m->nodes_size() <= 0 || m->nodes_size() > Tuning::kHardMaxReplyNodes) + if (m->nodes_size() <= 0 || m->nodes_size() > Tuning::HardMaxReplyNodes) { badData("Invalid Ledger/TXset nodes " + std::to_string(m->nodes_size())); return; @@ -1713,7 +1831,7 @@ PeerImp::onMessage(std::shared_ptr const& m) return; } - uint256 const ledgerHash = uint256::fromRaw(m->ledgerhash()); + uint256 const ledgerHash{m->ledgerhash()}; // Otherwise check if received data for a candidate transaction set if (m->type() == protocol::liTS_CANDIDATE) @@ -1745,14 +1863,14 @@ PeerImp::onMessage(std::shared_ptr const& m) (publicKeyType(makeSlice(set.nodepubkey())) != KeyType::Secp256k1)) { JLOG(pJournal_.warn()) << "Proposal: malformed"; - fee_.update(Resource::kFeeInvalidSignature, " signature can't be longer than 72 bytes"); + fee_.update(Resource::kFEE_INVALID_SIGNATURE, " signature can't be longer than 72 bytes"); return; } - if (!stringIsUInt256Sized(set.currenttxhash()) || !stringIsUInt256Sized(set.previousledger())) + if (!stringIsUint256Sized(set.currenttxhash()) || !stringIsUint256Sized(set.previousledger())) { JLOG(pJournal_.warn()) << "Proposal: malformed"; - fee_.update(Resource::kFeeMalformedRequest, "bad hashes"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "bad hashes"); return; } @@ -1771,12 +1889,12 @@ PeerImp::onMessage(std::shared_ptr const& m) overlay_.reportInboundTraffic( TrafficCount::Category::ProposalUntrusted, Message::messageSize(*m)); - if (app_.config().relayUntrustedProposals == -1) + if (app_.config().RELAY_UNTRUSTED_PROPOSALS == -1) return; } - uint256 const proposeHash = uint256::fromRaw(set.currenttxhash()); - uint256 const prevLedger = uint256::fromRaw(set.previousledger()); + uint256 const proposeHash{set.currenttxhash()}; + uint256 const prevLedger{set.previousledger()}; NetClock::time_point const closeTime{NetClock::duration{set.closetime()}}; @@ -1788,7 +1906,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { // Count unique messages (Slots has it's own 'HashRouter'), which a peer // receives within IDLED seconds since the message has been relayed. - if (relayed && (stopwatch().now() - *relayed) < reduce_relay::kIdled) + if (relayed && (stopwatch().now() - *relayed) < reduce_relay::kIDLED) overlay_.updateSlotAndSquelch(suppression, publicKey, id_, protocol::mtPROPOSE_LEDGER); // report duplicate proposal messages @@ -1883,7 +2001,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { uint256 closedLedgerHash{}; - bool const peerChangedLedgers{m->has_ledgerhash() && stringIsUInt256Sized(m->ledgerhash())}; + bool const peerChangedLedgers{m->has_ledgerhash() && stringIsUint256Sized(m->ledgerhash())}; { // Operations on closedLedgerHash_ and previousLedgerHash_ must be @@ -1900,7 +2018,7 @@ PeerImp::onMessage(std::shared_ptr const& m) closedLedgerHash_.zero(); } - if (m->has_ledgerhashprevious() && stringIsUInt256Sized(m->ledgerhashprevious())) + if (m->has_ledgerhashprevious() && stringIsUint256Sized(m->ledgerhashprevious())) { previousLedgerHash_ = m->ledgerhashprevious(); addLedger(previousLedgerHash_, sl); @@ -1937,7 +2055,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } app_.getOPs().pubPeerStatus([m, this]() -> json::Value { - json::Value j = json::ValueType::Object; + json::Value j = json::ObjectValue; if (m->has_newstatus()) { @@ -2034,13 +2152,13 @@ PeerImp::checkTracking(std::uint32_t seq1, std::uint32_t seq2) { int const diff = std::max(seq1, seq2) - std::min(seq1, seq2); - if (diff < Tuning::kConvergedLedgerLimit) + if (diff < Tuning::ConvergedLedgerLimit) { // The peer's ledger sequence is close to the validation's tracking_ = Tracking::Converged; } - if ((diff > Tuning::kDivergedLedgerLimit) && (tracking_.load() != Tracking::Diverged)) + if ((diff > Tuning::DivergedLedgerLimit) && (tracking_.load() != Tracking::Diverged)) { // The peer's ledger sequence is way off the validation's std::scoped_lock const sl(recentLock_); @@ -2053,13 +2171,13 @@ PeerImp::checkTracking(std::uint32_t seq1, std::uint32_t seq2) void PeerImp::onMessage(std::shared_ptr const& m) { - if (!stringIsUInt256Sized(m->hash())) + if (!stringIsUint256Sized(m->hash())) { - fee_.update(Resource::kFeeMalformedRequest, "bad hash"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "bad hash"); return; } - uint256 const hash = uint256::fromRaw(m->hash()); + uint256 const hash{m->hash()}; if (m->status() == protocol::tsHAVE) { @@ -2067,7 +2185,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (std::ranges::find(recentTxSets_, hash) != recentTxSets_.end()) { - fee_.update(Resource::kFeeUselessData, "duplicate (tsHAVE)"); + fee_.update(Resource::kFEE_USELESS_DATA, "duplicate (tsHAVE)"); return; } @@ -2088,7 +2206,7 @@ PeerImp::onValidatorListMessage( { JLOG(pJournal_.warn()) << "Ignored malformed " << messageType; // This shouldn't ever happen with a well-behaved peer - fee_.update(Resource::kFeeHeavyBurdenPeer, "no blobs"); + fee_.update(Resource::kFEE_HEAVY_BURDEN_PEER, "no blobs"); return; } @@ -2102,7 +2220,7 @@ PeerImp::onValidatorListMessage( // Charging this fee here won't hurt the peer in the normal // course of operation (ie. refresh every 5 minutes), but // will add up if the peer is misbehaving. - fee_.update(Resource::kFeeUselessData, "duplicate"); + fee_.update(Resource::kFEE_USELESS_DATA, "duplicate"); return; } @@ -2192,27 +2310,28 @@ PeerImp::onValidatorListMessage( // Charging this fee here won't hurt the peer in the normal // course of operation (ie. refresh every 5 minutes), but // will add up if the peer is misbehaving. - fee_.update(Resource::kFeeUselessData, " duplicate (same_sequence or known_sequence)"); + fee_.update( + Resource::kFEE_USELESS_DATA, " duplicate (same_sequence or known_sequence)"); break; case ListDisposition::Stale: // There are very few good reasons for a peer to send an // old list, particularly more than once. - fee_.update(Resource::kFeeInvalidData, "expired"); + fee_.update(Resource::kFEE_INVALID_DATA, "expired"); break; case ListDisposition::Untrusted: // Charging this fee here won't hurt the peer in the normal // course of operation (ie. refresh every 5 minutes), but // will add up if the peer is misbehaving. - fee_.update(Resource::kFeeUselessData, "untrusted"); + fee_.update(Resource::kFEE_USELESS_DATA, "untrusted"); break; case ListDisposition::Invalid: // This shouldn't ever happen with a well-behaved peer - fee_.update(Resource::kFeeInvalidSignature, "invalid list disposition"); + fee_.update(Resource::kFEE_INVALID_SIGNATURE, "invalid list disposition"); break; case ListDisposition::UnsupportedVersion: // During a version transition, this may be legitimate. // If it happens frequently, that's probably bad. - fee_.update(Resource::kFeeInvalidData, "version"); + fee_.update(Resource::kFEE_INVALID_DATA, "version"); break; // LCOV_EXCL_START default: @@ -2280,7 +2399,7 @@ PeerImp::onMessage(std::shared_ptr const& m) JLOG(pJournal_.debug()) << "ValidatorList: received validator list from peer using " << "protocol version " << to_string(protocol_) << " which shouldn't support this feature."; - fee_.update(Resource::kFeeUselessData, "unsupported peer"); + fee_.update(Resource::kFEE_USELESS_DATA, "unsupported peer"); return; } onValidatorListMessage( @@ -2290,7 +2409,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { JLOG(pJournal_.warn()) << "ValidatorList: Exception, " << e.what(); using namespace std::string_literals; - fee_.update(Resource::kFeeInvalidData, e.what()); + fee_.update(Resource::kFEE_INVALID_DATA, e.what()); } } @@ -2304,7 +2423,7 @@ PeerImp::onMessage(std::shared_ptr const& m JLOG(pJournal_.debug()) << "ValidatorListCollection: received validator list from peer " << "using protocol version " << to_string(protocol_) << " which shouldn't support this feature."; - fee_.update(Resource::kFeeUselessData, "unsupported peer"); + fee_.update(Resource::kFEE_USELESS_DATA, "unsupported peer"); return; } if (m->version() < 2) @@ -2313,7 +2432,7 @@ PeerImp::onMessage(std::shared_ptr const& m << "ValidatorListCollection: received invalid validator list " "version " << m->version() << " from peer using protocol version " << to_string(protocol_); - fee_.update(Resource::kFeeInvalidData, "wrong version"); + fee_.update(Resource::kFEE_INVALID_DATA, "wrong version"); return; } onValidatorListMessage( @@ -2323,7 +2442,7 @@ PeerImp::onMessage(std::shared_ptr const& m { JLOG(pJournal_.warn()) << "ValidatorListCollection: Exception, " << e.what(); using namespace std::string_literals; - fee_.update(Resource::kFeeInvalidData, e.what()); + fee_.update(Resource::kFEE_INVALID_DATA, e.what()); } } @@ -2333,7 +2452,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (m->validation().size() < 50) { JLOG(pJournal_.warn()) << "Validation: Too small"; - fee_.update(Resource::kFeeMalformedRequest, "too small"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "too small"); return; } @@ -2360,7 +2479,7 @@ PeerImp::onMessage(std::shared_ptr const& m) val->getSeenTime())) { JLOG(pJournal_.trace()) << "Validation: Not current"; - fee_.update(Resource::kFeeUselessData, "not current"); + fee_.update(Resource::kFEE_USELESS_DATA, "not current"); return; } @@ -2378,7 +2497,7 @@ PeerImp::onMessage(std::shared_ptr const& m) overlay_.reportInboundTraffic( TrafficCount::Category::ValidationUntrusted, Message::messageSize(*m)); - if (app_.config().relayUntrustedValidations == -1) + if (app_.config().RELAY_UNTRUSTED_VALIDATIONS == -1) return; } @@ -2391,7 +2510,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // Count unique messages (Slots has it's own 'HashRouter'), which a // peer receives within IDLED seconds since the message has been // relayed. - if (relayed && (stopwatch().now() - *relayed) < reduce_relay::kIdled) + if (relayed && (stopwatch().now() - *relayed) < reduce_relay::kIDLED) { overlay_.updateSlotAndSquelch( key, val->getSignerPublic(), id_, protocol::mtVALIDATION); @@ -2429,7 +2548,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { JLOG(pJournal_.warn()) << "Exception processing validation: " << e.what(); using namespace std::string_literals; - fee_.update(Resource::kFeeMalformedRequest, e.what()); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, e.what()); } } @@ -2444,7 +2563,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (packet.query()) { // this is a query - if (sendQueue_.size() >= Tuning::kDropSendQueue) + if (sendQueue_.size() >= Tuning::DropSendQueue) { JLOG(pJournal_.debug()) << "GetObject: Large send queue"; return; @@ -2461,7 +2580,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (!txReduceRelayEnabled()) { JLOG(pJournal_.error()) << "TMGetObjectByHash: tx reduce-relay is disabled"; - fee_.update(Resource::kFeeMalformedRequest, "disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "disabled"); return; } @@ -2481,24 +2600,24 @@ PeerImp::onMessage(std::shared_ptr const& m) if (packet.has_ledgerhash()) { - if (!stringIsUInt256Sized(packet.ledgerhash())) + if (!stringIsUint256Sized(packet.ledgerhash())) { - fee_.update(Resource::kFeeMalformedRequest, "ledger hash"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "ledger hash"); return; } reply.set_ledgerhash(packet.ledgerhash()); } - fee_.update(Resource::kFeeModerateBurdenPeer, " received a get object by hash request"); + fee_.update(Resource::kFEE_MODERATE_BURDEN_PEER, " received a get object by hash request"); // This is a very minimal implementation for (int i = 0; i < packet.objects_size(); ++i) { auto const& obj = packet.objects(i); - if (obj.has_hash() && stringIsUInt256Sized(obj.hash())) + if (obj.has_hash() && stringIsUint256Sized(obj.hash())) { - uint256 const hash = uint256::fromRaw(obj.hash()); + uint256 const hash{obj.hash()}; // VFALCO TODO Move this someplace more sensible so we dont // need to inject the NodeStore interfaces. std::uint32_t const seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0}; @@ -2516,10 +2635,10 @@ PeerImp::onMessage(std::shared_ptr const& m) // Check if by adding this object, reply has reached its // limit - if (reply.objects_size() >= Tuning::kHardMaxReplyNodes) + if (reply.objects_size() >= Tuning::HardMaxReplyNodes) { fee_.update( - Resource::kFeeModerateBurdenPeer, + Resource::kFEE_MODERATE_BURDEN_PEER, "Reply limit reached. Truncating reply."); break; } @@ -2542,7 +2661,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { protocol::TMIndexedObject const& obj = packet.objects(i); - if (obj.has_hash() && stringIsUInt256Sized(obj.hash())) + if (obj.has_hash() && stringIsUint256Sized(obj.hash())) { if (obj.has_ledgerseq()) { @@ -2568,7 +2687,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (pLDo) { - uint256 const hash = uint256::fromRaw(obj.hash()); + uint256 const hash{obj.hash()}; app_.getLedgerMaster().addFetchPack( hash, std::make_shared(obj.data().begin(), obj.data().end())); @@ -2591,7 +2710,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (!txReduceRelayEnabled()) { JLOG(pJournal_.error()) << "TMHaveTransactions: tx reduce-relay is disabled"; - fee_.update(Resource::kFeeMalformedRequest, "disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "disabled"); return; } @@ -2613,14 +2732,14 @@ PeerImp::handleHaveTransactions(std::shared_ptr co for (std::uint32_t i = 0; i < m->hashes_size(); i++) { - if (!stringIsUInt256Sized(m->hashes(i))) + if (!stringIsUint256Sized(m->hashes(i))) { JLOG(pJournal_.error()) << "TMHaveTransactions with invalid hash size"; - fee_.update(Resource::kFeeMalformedRequest, "hash size"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "hash size"); return; } - uint256 hash = uint256::fromRaw(m->hashes(i)); + uint256 hash(m->hashes(i)); auto txn = app_.getMasterTransaction().fetchFromCache(hash); @@ -2654,7 +2773,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (!txReduceRelayEnabled()) { JLOG(pJournal_.error()) << "TMTransactions: tx reduce-relay is disabled"; - fee_.update(Resource::kFeeMalformedRequest, "disabled"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "disabled"); return; } @@ -2684,14 +2803,14 @@ PeerImp::onMessage(std::shared_ptr const& m) if (!m->has_validatorpubkey()) { - fee_.update(Resource::kFeeInvalidData, "squelch no pubkey"); + fee_.update(Resource::kFEE_INVALID_DATA, "squelch no pubkey"); return; } auto validator = m->validatorpubkey(); auto const slice{makeSlice(validator)}; if (!publicKeyType(slice)) { - fee_.update(Resource::kFeeInvalidData, "squelch bad pubkey"); + fee_.update(Resource::kFEE_INVALID_DATA, "squelch bad pubkey"); return; } PublicKey const key(slice); @@ -2710,7 +2829,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } else if (!squelch_.addSquelch(key, std::chrono::seconds{duration})) { - fee_.update(Resource::kFeeInvalidData, "squelch duration"); + fee_.update(Resource::kFEE_INVALID_DATA, "squelch duration"); } JLOG(pJournal_.debug()) << "onMessage: TMSquelch " << slice << " " << id() << " " << duration; @@ -2745,16 +2864,16 @@ PeerImp::doFetchPack(std::shared_ptr const& packet) return; } - if (!stringIsUInt256Sized(packet->ledgerhash())) + if (!stringIsUint256Sized(packet->ledgerhash())) { JLOG(pJournal_.warn()) << "FetchPack hash size malformed"; - fee_.update(Resource::kFeeMalformedRequest, "hash size"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "hash size"); return; } - fee_.fee = Resource::kFeeHeavyBurdenPeer; + fee_.fee = Resource::kFEE_HEAVY_BURDEN_PEER; - uint256 const hash = uint256::fromRaw(packet->ledgerhash()); + uint256 const hash{packet->ledgerhash()}; std::weak_ptr const weak = shared_from_this(); auto elapsed = UptimeClock::now(); @@ -2772,10 +2891,10 @@ PeerImp::doTransactions(std::shared_ptr const& pack JLOG(pJournal_.trace()) << "received TMGetObjectByHash requesting tx " << packet->objects_size(); - if (packet->objects_size() > reduce_relay::kMaxTxQueueSize) + if (packet->objects_size() > reduce_relay::kMAX_TX_QUEUE_SIZE) { JLOG(pJournal_.error()) << "doTransactions, invalid number of hashes"; - fee_.update(Resource::kFeeMalformedRequest, "too big"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "too big"); return; } @@ -2783,13 +2902,13 @@ PeerImp::doTransactions(std::shared_ptr const& pack { auto const& obj = packet->objects(i); - if (!stringIsUInt256Sized(obj.hash())) + if (!stringIsUint256Sized(obj.hash())) { - fee_.update(Resource::kFeeMalformedRequest, "hash size"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "hash size"); return; } - uint256 hash = uint256::fromRaw(obj.hash()); + uint256 hash(obj.hash()); auto txn = app_.getMasterTransaction().fetchFromCache(hash); @@ -2797,7 +2916,7 @@ PeerImp::doTransactions(std::shared_ptr const& pack { JLOG(pJournal_.error()) << "doTransactions, transaction not found " << Slice(hash.data(), hash.size()); - fee_.update(Resource::kFeeMalformedRequest, "tx not found"); + fee_.update(Resource::kFEE_MALFORMED_REQUEST, "tx not found"); return; } @@ -2848,7 +2967,7 @@ PeerImp::checkTransaction( { JLOG(pJournal_.warn()) << "Ignoring Network relayed Tx containing " "tfInnerBatchTxn (checkSignature)."; - charge(Resource::kFeeModerateBurdenPeer, "inner batch txn"); + charge(Resource::kFEE_MODERATE_BURDEN_PEER, "inner batch txn"); return; } // LCOV_EXCL_STOP @@ -2860,7 +2979,7 @@ PeerImp::checkTransaction( JLOG(pJournal_.info()) << "Marking transaction " << stx->getTransactionID() << "as BAD because it's expired"; app_.getHashRouter().setFlags(stx->getTransactionID(), HashRouterFlags::BAD); - charge(Resource::kFeeUselessData, "expired tx"); + charge(Resource::kFEE_USELESS_DATA, "expired tx"); return; } @@ -2891,7 +3010,7 @@ PeerImp::checkTransaction( if (!batch) { JLOG(pJournal_.debug()) << "Charging for pseudo-transaction tx " << tx->getID(); - charge(Resource::kFeeUselessData, "pseudo tx"); + charge(Resource::kFEE_USELESS_DATA, "pseudo tx"); } return; @@ -2913,7 +3032,7 @@ PeerImp::checkTransaction( // Probably not necessary to set HashRouterFlags::BAD, but // doesn't hurt. app_.getHashRouter().setFlags(stx->getTransactionID(), HashRouterFlags::BAD); - charge(Resource::kFeeInvalidSignature, "check transaction signature failure"); + charge(Resource::kFEE_INVALID_SIGNATURE, "check transaction signature failure"); return; } } @@ -2932,7 +3051,7 @@ PeerImp::checkTransaction( JLOG(pJournal_.debug()) << "Exception checking transaction: " << reason; } app_.getHashRouter().setFlags(stx->getTransactionID(), HashRouterFlags::BAD); - charge(Resource::kFeeInvalidSignature, "tx (impossible)"); + charge(Resource::kFEE_INVALID_SIGNATURE, "tx (impossible)"); return; } @@ -2944,7 +3063,7 @@ PeerImp::checkTransaction( JLOG(pJournal_.warn()) << "Exception in " << __func__ << ": " << ex.what(); app_.getHashRouter().setFlags(stx->getTransactionID(), HashRouterFlags::BAD); using namespace std::string_literals; - charge(Resource::kFeeInvalidData, "tx "s + ex.what()); + charge(Resource::kFEE_INVALID_DATA, "tx "s + ex.what()); } } @@ -2963,7 +3082,7 @@ PeerImp::checkPropose( { std::string const desc{"Proposal fails sig check"}; JLOG(pJournal_.warn()) << desc; - charge(Resource::kFeeInvalidSignature, desc); + charge(Resource::kFEE_INVALID_SIGNATURE, desc); return; } @@ -2975,7 +3094,7 @@ PeerImp::checkPropose( } else { - relay = app_.config().relayUntrustedProposals == 1 || cluster(); + relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster(); } if (relay) @@ -3007,7 +3126,7 @@ PeerImp::checkValidation( { std::string const desc{"Validation forwarded by peer is invalid"}; JLOG(pJournal_.debug()) << desc; - charge(Resource::kFeeInvalidSignature, desc); + charge(Resource::kFEE_INVALID_SIGNATURE, desc); return; } @@ -3032,7 +3151,7 @@ PeerImp::checkValidation( { JLOG(pJournal_.trace()) << "Exception processing validation: " << ex.what(); using namespace std::string_literals; - charge(Resource::kFeeMalformedRequest, "validation "s + ex.what()); + charge(Resource::kFEE_MALFORMED_REQUEST, "validation "s + ex.what()); } } @@ -3100,7 +3219,7 @@ PeerImp::sendLedgerBase( ledgerData.add_nodes()->set_nodedata(s.getDataPtr(), s.getLength()); auto const& stateMap{ledger->stateMap()}; - if (stateMap.getHash() != beast::kZero) + if (stateMap.getHash() != beast::kZERO) { // Return account state root node if possible Serializer root(768); @@ -3108,10 +3227,10 @@ PeerImp::sendLedgerBase( stateMap.serializeRoot(root); ledgerData.add_nodes()->set_nodedata(root.getDataPtr(), root.getLength()); - if (ledger->header().txHash != beast::kZero) + if (ledger->header().txHash != beast::kZERO) { auto const& txMap{ledger->txMap()}; - if (txMap.getHash() != beast::kZero) + if (txMap.getHash() != beast::kZERO) { // Return TX root node if possible root.erase(); @@ -3135,7 +3254,7 @@ PeerImp::getLedger(std::shared_ptr const& m) if (m->has_ledgerhash()) { // Attempt to find ledger by hash - uint256 const ledgerHash = uint256::fromRaw(m->ledgerhash()); + uint256 const ledgerHash{m->ledgerhash()}; ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash); if (!ledger) { @@ -3189,7 +3308,7 @@ PeerImp::getLedger(std::shared_ptr const& m) { // Do not resource charge a peer responding to a relay if (!m->has_requestcookie()) - charge(Resource::kFeeMalformedRequest, "get_ledger ledgerSeq"); + charge(Resource::kFEE_MALFORMED_REQUEST, "get_ledger ledgerSeq"); ledger.reset(); JLOG(pJournal_.warn()) << "getLedger: Invalid ledger sequence " << ledgerSeq; @@ -3214,7 +3333,7 @@ PeerImp::getTxSet(std::shared_ptr const& m) const { JLOG(pJournal_.trace()) << "getTxSet: TX set"; - uint256 const txSetHash = uint256::fromRaw(m->ledgerhash()); + uint256 const txSetHash{m->ledgerhash()}; std::shared_ptr shaMap{app_.getInboundTransactions().getSet(txSetHash, false)}; if (!shaMap) { @@ -3246,7 +3365,7 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) { // Do not resource charge a peer responding to a relay if (!m->has_requestcookie()) - charge(Resource::kFeeModerateBurdenPeer, "received a get ledger request"); + charge(Resource::kFEE_MODERATE_BURDEN_PEER, "received a get ledger request"); std::shared_ptr ledger; std::shared_ptr sharedMap; @@ -3273,7 +3392,7 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) } else { - if (sendQueue_.size() >= Tuning::kDropSendQueue) + if (sendQueue_.size() >= Tuning::DropSendQueue) { JLOG(pJournal_.debug()) << "processLedgerRequest: Large send queue"; return; @@ -3335,13 +3454,13 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) std::vector> data; for (int i = 0; - i < m->nodeids_size() && ledgerData.nodes_size() < Tuning::kSoftMaxReplyNodes; + i < m->nodeids_size() && ledgerData.nodes_size() < Tuning::SoftMaxReplyNodes; ++i) { auto const shaMapNodeId{deserializeSHAMapNodeID(m->nodeids(i))}; data.clear(); - data.reserve(Tuning::kSoftMaxReplyNodes); + data.reserve(Tuning::SoftMaxReplyNodes); try { @@ -3353,7 +3472,7 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) for (auto const& d : data) { - if (ledgerData.nodes_size() >= Tuning::kHardMaxReplyNodes) + if (ledgerData.nodes_size() >= Tuning::HardMaxReplyNodes) break; protocol::TMLedgerNode* node{ledgerData.add_nodes()}; node->set_nodeid(d.first.getRawString()); @@ -3417,24 +3536,24 @@ PeerImp::getScore(bool haveItem) const { // Random component of score, used to break ties and avoid // overloading the "best" peer - static int const kSpRandomMax = 9999; + static int const kSP_RANDOM_MAX = 9999; // Score for being very likely to have the thing we are // look for; should be roughly spRandomMax - static int const kSpHaveItem = 10000; + static int const kSP_HAVE_ITEM = 10000; // Score reduction for each millisecond of latency; should // be roughly spRandomMax divided by the maximum reasonable // latency - static int const kSpLatency = 30; + static int const kSP_LATENCY = 30; // Penalty for unknown latency; should be roughly spRandomMax - static int const kSpNoLatency = 8000; + static int const kSP_NO_LATENCY = 8000; - int score = randInt(kSpRandomMax); + int score = randInt(kSP_RANDOM_MAX); if (haveItem) - score += kSpHaveItem; + score += kSP_HAVE_ITEM; std::optional latency; { @@ -3444,11 +3563,11 @@ PeerImp::getScore(bool haveItem) const if (latency) { - score -= latency->count() * kSpLatency; + score -= latency->count() * kSP_LATENCY; } else { - score -= kSpNoLatency; + score -= kSP_NO_LATENCY; } return score; @@ -3458,7 +3577,7 @@ bool PeerImp::isHighLatency() const { std::scoped_lock const sl(recentLock_); - return latency_ >= kPeerHighLatency; + return latency_ >= kPEER_HIGH_LATENCY; } void diff --git a/src/xrpld/overlay/detail/PeerImp.h b/src/xrpld/overlay/detail/PeerImp.h index f5d87371be..676057ad82 100644 --- a/src/xrpld/overlay/detail/PeerImp.h +++ b/src/xrpld/overlay/detail/PeerImp.h @@ -30,6 +30,68 @@ namespace xrpl { struct ValidatorBlobInfo; class SHAMap; +/** + * @class PeerImp + * @brief This class manages established peer-to-peer connections, handles + message exchange, monitors connection health, and graceful shutdown. + * + + * The PeerImp shutdown mechanism is a multi-stage process + * designed to ensure graceful connection termination while handling ongoing + * I/O operations safely. The shutdown can be initiated from multiple points + * and follows a deterministic state machine. + * + * The shutdown process can be triggered from several entry points: + * - **External requests**: `stop()` method called by overlay management + * - **Error conditions**: `fail(error_code)` or `fail(string)` on protocol + * violations + * - **Timer expiration**: Various timeout scenarios (ping timeout, large send + * queue) + * - **Connection health**: Peer tracking divergence or unknown state timeouts + * + * The shutdown follows this progression: + * + * Normal Operation → shutdown() → tryAsyncShutdown() → onShutdown() → close() + * ↓ ↓ ↓ ↓ + * Set shutdown_ SSL graceful Timer cancel Socket close + * Cancel timer shutdown start & cleanup & metrics + * 5s safety timer Set shutdownStarted_ update + * + * Two primary flags coordinate the shutdown process: + * - `shutdown_`: Set when shutdown is requested + * - `shutdownStarted_`: Set when SSL shutdown begins + * + * The shutdown mechanism carefully coordinates with ongoing read/write + * operations: + * + * **Read Operations (`onReadMessage`)**: + * - Checks `shutdown_` flag after processing each message batch + * - If shutdown initiated during processing, calls `tryAsyncShutdown()` + * + * **Write Operations (`onWriteMessage`)**: + * - Checks `shutdown_` flag before queuing new writes + * - Calls `tryAsyncShutdown()` when shutdown flag detected + * + * Multiple timers require coordination during shutdown: + * 1. **Peer Timer**: Regular ping/pong timer cancelled immediately in + * `shutdown()` + * 2. **Shutdown Timer**: 5-second safety timer ensures shutdown completion + * 3. **Operation Cancellation**: All pending async operations are cancelled + * + * The shutdown implements fallback mechanisms: + * - **Graceful Path**: SSL shutdown → Socket close → Cleanup + * - **Forced Path**: If SSL shutdown fails or times out, proceeds to socket + * close + * - **Safety Timer**: 5-second timeout prevents hanging shutdowns + * + * All shutdown operations are serialized through the boost::asio::strand to + * ensure thread safety. The strand guarantees that shutdown state changes + * and I/O operation callbacks are executed sequentially. + * + * @note This class requires careful coordination between async operations, + * timer management, and shutdown procedures to ensure no resource leaks + * or hanging connections in high-throughput networking scenarios. + */ class PeerImp : public Peer, public std::enable_shared_from_this, public OverlayImpl::Child { public: @@ -59,6 +121,8 @@ private: socket_type& socket_; stream_type& stream_; boost::asio::strand strand_; + + // Multi-purpose timer for peer activity monitoring and shutdown safety waitable_timer timer_; // Updated at each stage of the connection process to reflect @@ -75,7 +139,6 @@ private: std::atomic tracking_; clock_type::time_point trackingTime_; - bool detaching_ = false; // Node public key of peer. PublicKey const publicKey_; std::string name_; @@ -127,7 +190,7 @@ private: struct ChargeWithContext { - Resource::Charge fee = Resource::kFeeTrivialPeer; + Resource::Charge fee = Resource::kFEE_TRIVIAL_PEER; std::string context{}; // NOLINT(readability-redundant-member-init) void @@ -153,7 +216,19 @@ private: http_response_type response_; boost::beast::http::fields const& headers_; std::queue> sendQueue_; - bool gracefulClose_ = false; + + // Primary shutdown flag set when shutdown is requested + bool shutdown_ = false; + + // SSL shutdown coordination flag + bool shutdownStarted_ = false; + + // Indicates a read operation is currently pending + bool readPending_ = false; + + // Indicates a write operation is currently pending + bool writePending_ = false; + int largeSendq_ = 0; std::unique_ptr loadEvent_; // The highest sequence of each PublisherList that has @@ -401,9 +476,6 @@ public: bool isHighLatency() const override; - void - fail(std::string const& reason); - bool compressionEnabled() const override { @@ -417,32 +489,129 @@ public: } private: - void - close(); - + /** + * @brief Handles a failure associated with a specific error code. + * + * This function is called when an operation fails with an error code. It + * logs the warning message and gracefully shutdowns the connection. + * + * The function will do nothing if the connection is already closed or if a + * shutdown is already in progress. + * + * @param name The name of the operation that failed (e.g., "read", + * "write"). + * @param ec The error code associated with the failure. + * @note This function must be called from within the object's strand. + */ void fail(std::string const& name, error_code ec); + /** + * @brief Handles a failure described by a reason string. + * + * This overload is used for logical errors or protocol violations not + * associated with a specific error code. It logs a warning with the + * given reason, then initiates a graceful shutdown. + * + * The function will do nothing if the connection is already closed or if a + * shutdown is already in progress. + * + * @param reason A descriptive string explaining the reason for the failure. + * @note This function must be called from within the object's strand. + */ void - gracefulClose(); + fail(std::string const& reason); + /** @brief Initiates the peer disconnection sequence. + * + * This is the primary entry point to start closing a peer connection. It + * marks the peer for shutdown and cancels any outstanding asynchronous + * operations. This cancellation allows the graceful shutdown to proceed + * once the handlers for the cancelled operations have completed. + * + * @note This method must be called on the peer's strand. + */ void - setTimer(); + shutdown(); + /** @brief Attempts to perform a graceful SSL shutdown if conditions are + * met. + * + * This helper function checks if the peer is in a state where a graceful + * SSL shutdown can be performed (i.e., shutdown has been requested and no + * I/O operations are currently in progress). + * + * @note This method must be called on the peer's strand. + */ + void + tryAsyncShutdown(); + + /** + * @brief Handles the completion of the asynchronous SSL shutdown. + * + * This function is the callback for the `async_shutdown` operation started + * in `shutdown()`. Its first action is to cancel the timer. It + * then inspects the error code to determine the outcome. + * + * Regardless of the result, this function proceeds to call `close()` to + * ensure the underlying socket is fully closed. + * + * @param ec The error code resulting from the `async_shutdown` operation. + */ + void + onShutdown(error_code ec); + + /** + * @brief Forcibly closes the underlying socket connection. + * + * This function provides the final, non-graceful shutdown of the peer + * connection. It ensures any pending timers are cancelled and then + * immediately closes the TCP socket, bypassing the SSL shutdown handshake. + * + * After closing, it notifies the overlay manager of the disconnection. + * + * @note This function must be called from within the object's strand. + */ + void + close(); + + /** + * @brief Sets and starts the peer timer. + * + * This function starts timer, which is used to detect inactivity + * and prevent stalled connections. It sets the timer to expire after the + * predefined `peerTimerInterval`. + * + * @note This function will terminate the connection in case of any errors. + */ + void + setTimer(std::chrono::seconds interval); + + /** + * @brief Handles the expiration of the peer activity timer. + * + * This callback is invoked when the timer set by `setTimer` expires. It + * watches the peer connection, checking for various timeout and health + * conditions. + * + * @param ec The error code associated with the timer's expiration. + * `operation_aborted` is expected if the timer was cancelled. + */ + void + onTimer(error_code const& ec); + + /** + * @brief Cancels any pending wait on the peer activity timer. + * + * This function is called to stop the timer. It gracefully manages any + * errors that might occur during the cancellation process. + */ void cancelTimer() noexcept; static std::string makePrefix(std::string const& fingerprint); - // Called when the timer wait completes - void - onTimer(boost::system::error_code const& ec); - - // Called when SSL shutdown completes - void - onShutdown(error_code ec); - void doAccept(); @@ -665,28 +834,30 @@ PeerImp::PeerImp( , creationTime_(clock_type::now()) , squelch_(app_.getJournal("Squelch")) , usage_(usage) - , fee_{.fee = Resource::kFeeTrivialPeer} + , fee_{.fee = Resource::kFEE_TRIVIAL_PEER} , slot_(std::move(slot)) , response_(std::move(response)) , headers_(response_) , compressionEnabled_( - peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().compression) + peerFeatureEnabled(headers_, kFEATURE_COMPR, "lz4", app_.config().COMPRESSION) ? Compressed::On : Compressed::Off) , txReduceRelayEnabled_( - peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().txReduceRelayEnable)) + peerFeatureEnabled(headers_, kFEATURE_TXRR, app_.config().TX_REDUCE_RELAY_ENABLE)) , ledgerReplayEnabled_( - peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().ledgerReplay)) + peerFeatureEnabled(headers_, kFEATURE_LEDGER_REPLAY, app_.config().LEDGER_REPLAY)) , ledgerReplayMsgHandler_(app, app.getLedgerReplayer()) { readBuffer_.commit( boost::asio::buffer_copy(readBuffer_.prepare(boost::asio::buffer_size(buffers)), buffers)); - JLOG(journal_.info()) - << "compression enabled " << (compressionEnabled_ == Compressed::On) - << " vp reduce-relay base squelch enabled " - << peerFeatureEnabled(headers_, kFeatureVprr, app_.config().vpReduceRelayBaseSquelchEnable) - << " tx reduce-relay enabled " << txReduceRelayEnabled_ << " on " << remoteAddress_ << " " - << id_; + JLOG(journal_.info()) << "compression enabled " << (compressionEnabled_ == Compressed::On) + << " vp reduce-relay base squelch enabled " + << peerFeatureEnabled( + headers_, + kFEATURE_VPRR, + app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) + << " tx reduce-relay enabled " << txReduceRelayEnabled_ << " on " + << remoteAddress_ << " " << id_; } template diff --git a/src/xrpld/overlay/detail/PeerReservationTable.cpp b/src/xrpld/overlay/detail/PeerReservationTable.cpp index 2ca85c3fd7..ec0f914dd6 100644 --- a/src/xrpld/overlay/detail/PeerReservationTable.cpp +++ b/src/xrpld/overlay/detail/PeerReservationTable.cpp @@ -18,7 +18,7 @@ namespace xrpl { auto PeerReservation::toJson() const -> json::Value { - json::Value result{json::ValueType::Object}; + json::Value result{json::ObjectValue}; result[jss::node] = toBase58(TokenType::NodePublic, nodeId); if (!description.empty()) { diff --git a/src/xrpld/overlay/detail/PeerSet.cpp b/src/xrpld/overlay/detail/PeerSet.cpp index 463b68bb6c..6dda492315 100644 --- a/src/xrpld/overlay/detail/PeerSet.cpp +++ b/src/xrpld/overlay/detail/PeerSet.cpp @@ -167,9 +167,9 @@ public: [[nodiscard]] std::set const& getPeerIds() const override { - static std::set const kEmptyPeers; + static std::set const kEMPTY_PEERS; JLOG(j_.error()) << "DummyPeerSet getPeerIds should not be called"; - return kEmptyPeers; + return kEMPTY_PEERS; } private: diff --git a/src/xrpld/overlay/detail/ProtocolMessage.h b/src/xrpld/overlay/detail/ProtocolMessage.h index b1a30bad10..0550cf68e0 100644 --- a/src/xrpld/overlay/detail/ProtocolMessage.h +++ b/src/xrpld/overlay/detail/ProtocolMessage.h @@ -98,19 +98,19 @@ struct MessageHeader @note This is the sum of sizes of the header and the payload. */ - std::uint32_t totalWireSize = 0; + std::uint32_t total_wire_size = 0; /** The size of the header associated with this message. */ - std::uint32_t headerSize = 0; + std::uint32_t header_size = 0; /** The size of the payload on the wire. */ - std::uint32_t payloadWireSize = 0; + std::uint32_t payload_wire_size = 0; /** Uncompressed message size if the message is compressed. */ - std::uint32_t uncompressedSize = 0; + std::uint32_t uncompressed_size = 0; /** The type of the message. */ - std::uint16_t messageType = 0; + std::uint16_t message_type = 0; /** Indicates which compression algorithm the payload is compressed with. * Currently only lz4 is supported. If None then the message is not @@ -159,10 +159,10 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st // - 32 bits are the uncompressed data size if (*iter & 0x80) { - hdr.headerSize = kHeaderBytesCompressed; + hdr.header_size = kHEADER_BYTES_COMPRESSED; // not enough bytes to parse the header - if (size < hdr.headerSize) + if (size < hdr.header_size) { ec = make_error_code(boost::system::errc::success); return std::nullopt; @@ -183,18 +183,18 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st } for (int i = 0; i != 4; ++i) - hdr.payloadWireSize = (hdr.payloadWireSize << 8) + *iter++; + hdr.payload_wire_size = (hdr.payload_wire_size << 8) + *iter++; // clear the top four bits (the compression bits). - hdr.payloadWireSize &= 0x0FFFFFFF; + hdr.payload_wire_size &= 0x0FFFFFFF; - hdr.totalWireSize = hdr.headerSize + hdr.payloadWireSize; + hdr.total_wire_size = hdr.header_size + hdr.payload_wire_size; for (int i = 0; i != 2; ++i) - hdr.messageType = (hdr.messageType << 8) + *iter++; + hdr.message_type = (hdr.message_type << 8) + *iter++; for (int i = 0; i != 4; ++i) - hdr.uncompressedSize = (hdr.uncompressedSize << 8) + *iter++; + hdr.uncompressed_size = (hdr.uncompressed_size << 8) + *iter++; return hdr; } @@ -204,9 +204,9 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st // - 26 bits are the payload size if ((*iter & 0xFC) == 0) { - hdr.headerSize = kHeaderBytes; + hdr.header_size = kHEADER_BYTES; - if (size < hdr.headerSize) + if (size < hdr.header_size) { ec = make_error_code(boost::system::errc::success); return std::nullopt; @@ -215,13 +215,13 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st hdr.algorithm = Algorithm::None; for (int i = 0; i != 4; ++i) - hdr.payloadWireSize = (hdr.payloadWireSize << 8) + *iter++; + hdr.payload_wire_size = (hdr.payload_wire_size << 8) + *iter++; - hdr.uncompressedSize = hdr.payloadWireSize; - hdr.totalWireSize = hdr.headerSize + hdr.payloadWireSize; + hdr.uncompressed_size = hdr.payload_wire_size; + hdr.total_wire_size = hdr.header_size + hdr.payload_wire_size; for (int i = 0; i != 2; ++i) - hdr.messageType = (hdr.messageType << 8) + *iter++; + hdr.message_type = (hdr.message_type << 8) + *iter++; return hdr; } @@ -240,18 +240,18 @@ parseMessageContent(MessageHeader const& header, Buffers const& buffers) auto m = std::make_shared(); ZeroCopyInputStream stream(buffers); - stream.Skip(header.headerSize); + stream.Skip(header.header_size); if (header.algorithm != compression::Algorithm::None) { std::vector payload; - payload.resize(header.uncompressedSize); + payload.resize(header.uncompressed_size); auto const payloadSize = xrpl::compression::decompress( stream, - header.payloadWireSize, + header.payload_wire_size, payload.data(), - header.uncompressedSize, + header.uncompressed_size, header.algorithm); if (payloadSize == 0 || !m->ParseFromArray(payload.data(), payloadSize)) @@ -279,13 +279,13 @@ invoke(MessageHeader const& header, Buffers const& buffers, Handler& handler) using namespace xrpl::compression; handler.onMessageBegin( - header.messageType, + header.message_type, m, - header.payloadWireSize, - header.uncompressedSize, + header.payload_wire_size, + header.uncompressed_size, header.algorithm != Algorithm::None); handler.onMessage(m); - handler.onMessageEnd(header.messageType, m); + handler.onMessageEnd(header.message_type, m); return true; } @@ -329,8 +329,8 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin // whose size exceeds this may result in the connection being dropped. A // larger message size may be supported in the future or negotiated as // part of a protocol upgrade. - if (header->payloadWireSize > kMaximumMessageSize || - header->uncompressedSize > kMaximumMessageSize) + if (header->payload_wire_size > kMAXIMUM_MESSAGE_SIZE || + header->uncompressed_size > kMAXIMUM_MESSAGE_SIZE) { result.second = make_error_code(boost::system::errc::message_size); return result; @@ -345,15 +345,15 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin // We don't have the whole message yet. This isn't an error but we have // nothing to do. - if (header->totalWireSize > size) + if (header->total_wire_size > size) { - hint = header->totalWireSize - size; + hint = header->total_wire_size - size; return result; } bool success = false; - switch (header->messageType) + switch (header->message_type) { case protocol::mtMANIFESTS: success = detail::invoke(*header, buffers, handler); @@ -420,12 +420,12 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin success = detail::invoke(*header, buffers, handler); break; default: - handler.onMessageUnknown(header->messageType); + handler.onMessageUnknown(header->message_type); success = true; break; } - result.first = header->totalWireSize; + result.first = header->total_wire_size; if (!success) result.second = make_error_code(boost::system::errc::bad_message); diff --git a/src/xrpld/overlay/detail/ProtocolVersion.cpp b/src/xrpld/overlay/detail/ProtocolVersion.cpp index 62660b0e01..86525068f8 100644 --- a/src/xrpld/overlay/detail/ProtocolVersion.cpp +++ b/src/xrpld/overlay/detail/ProtocolVersion.cpp @@ -25,7 +25,7 @@ namespace xrpl { it may not contain any duplicates!) */ -constexpr ProtocolVersion const kSupportedProtocolList[]{ +constexpr ProtocolVersion const kSUPPORTED_PROTOCOL_LIST[]{ {2, 1}, {2, 2}, }; @@ -36,7 +36,7 @@ constexpr ProtocolVersion const kSupportedProtocolList[]{ static_assert( []() constexpr -> bool { auto const len = - std::distance(std::begin(kSupportedProtocolList), std::end(kSupportedProtocolList)); + std::distance(std::begin(kSUPPORTED_PROTOCOL_LIST), std::end(kSUPPORTED_PROTOCOL_LIST)); // There should be at least one protocol we're willing to speak. if (len == 0) @@ -48,7 +48,7 @@ static_assert( { for (auto i = 0; i != len - 1; ++i) { - if (kSupportedProtocolList[i] >= kSupportedProtocolList[i + 1]) + if (kSUPPORTED_PROTOCOL_LIST[i] >= kSUPPORTED_PROTOCOL_LIST[i + 1]) return false; } } @@ -125,7 +125,7 @@ negotiateProtocolVersion(std::vector const& versions) [&result](ProtocolVersion const& v) { result = v; }; std::ranges::set_intersection( - versions, kSupportedProtocolList, boost::make_function_output_iterator(pickVersion)); + versions, kSUPPORTED_PROTOCOL_LIST, boost::make_function_output_iterator(pickVersion)); return result; } @@ -141,9 +141,9 @@ negotiateProtocolVersion(boost::beast::string_view const& versions) std::string const& supportedProtocolVersions() { - static std::string const kSupported = []() { + static std::string const kSUPPORTED = []() { std::string ret; - for (auto const& v : kSupportedProtocolList) + for (auto const& v : kSUPPORTED_PROTOCOL_LIST) { if (!ret.empty()) ret += ", "; @@ -153,13 +153,13 @@ supportedProtocolVersions() return ret; }(); - return kSupported; + return kSUPPORTED; } bool isProtocolSupported(ProtocolVersion const& v) { - return std::end(kSupportedProtocolList) != std::ranges::find(kSupportedProtocolList, v); + return std::end(kSUPPORTED_PROTOCOL_LIST) != std::ranges::find(kSUPPORTED_PROTOCOL_LIST, v); } } // namespace xrpl diff --git a/src/xrpld/overlay/detail/TrafficCount.cpp b/src/xrpld/overlay/detail/TrafficCount.cpp index bdce9e68f0..4dc99e3e37 100644 --- a/src/xrpld/overlay/detail/TrafficCount.cpp +++ b/src/xrpld/overlay/detail/TrafficCount.cpp @@ -8,7 +8,7 @@ namespace xrpl { -std::unordered_map const kTypeLookup = { +std::unordered_map const kTYPE_LOOKUP = { {protocol::mtPING, TrafficCount::Category::Base}, {protocol::mtSTATUS_CHANGE, TrafficCount::Category::Base}, {protocol::mtMANIFESTS, TrafficCount::Category::Manifests}, @@ -33,7 +33,7 @@ TrafficCount::categorize( protocol::MessageType type, bool inbound) { - if (auto item = kTypeLookup.find(type); item != kTypeLookup.end()) + if (auto item = kTYPE_LOOKUP.find(type); item != kTYPE_LOOKUP.end()) return item->second; if (type == protocol::mtHAVE_SET) diff --git a/src/xrpld/overlay/detail/TrafficCount.h b/src/xrpld/overlay/detail/TrafficCount.h index cb77c2359f..233f06b70f 100644 --- a/src/xrpld/overlay/detail/TrafficCount.h +++ b/src/xrpld/overlay/detail/TrafficCount.h @@ -226,7 +226,7 @@ public: static std::string toString(Category cat) { - static std::unordered_map const kCategoryMap = { + static std::unordered_map const kCATEGORY_MAP = { {Category::Base, "overhead"}, {Category::Cluster, "overhead_cluster"}, {Category::Overlay, "overhead_overlay"}, @@ -284,7 +284,7 @@ public: {Category::RequestedTransactions, "requested_transactions"}, {Category::Total, "total"}}; - if (auto it = kCategoryMap.find(cat); it != kCategoryMap.end()) + if (auto it = kCATEGORY_MAP.find(cat); it != kCATEGORY_MAP.end()) return it->second; return "unknown"; diff --git a/src/xrpld/overlay/detail/Tuning.h b/src/xrpld/overlay/detail/Tuning.h index a0f57ec3d7..c54fa24498 100644 --- a/src/xrpld/overlay/detail/Tuning.h +++ b/src/xrpld/overlay/detail/Tuning.h @@ -1,40 +1,47 @@ #pragma once +#include + namespace xrpl::Tuning { -/** How many ledgers off a server can be and we will - still consider it converged */ -static constexpr auto kConvergedLedgerLimit = 24; +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + /** How many ledgers off a server can be and we will + still consider it converged */ + ConvergedLedgerLimit = 24, -/** How many ledgers off a server has to be before we - consider it diverged */ -static constexpr auto kDivergedLedgerLimit = 128; + /** How many ledgers off a server has to be before we + consider it diverged */ + DivergedLedgerLimit = 128, -/** The soft cap on the number of ledger entries in a single reply. */ -static constexpr auto kSoftMaxReplyNodes = 8192; + /** The soft cap on the number of ledger entries in a single reply. */ + SoftMaxReplyNodes = 8192, -/** The hard cap on the number of ledger entries in a single reply. */ -static constexpr auto kHardMaxReplyNodes = 12288; + /** The hard cap on the number of ledger entries in a single reply. */ + HardMaxReplyNodes = 12288, -/** How many timer intervals a sendq has to stay large before we disconnect */ -static constexpr auto kSendqIntervals = 4; + /** How many timer intervals a sendq has to stay large before we disconnect + */ + SendqIntervals = 4, -/** How many messages on a send queue before we refuse queries */ -static constexpr auto kDropSendQueue = 192; + /** How many messages on a send queue before we refuse queries */ + DropSendQueue = 192, -/** How many messages we consider reasonable sustained on a send queue */ -static constexpr auto kTargetSendQueue = 128; + /** How many messages we consider reasonable sustained on a send queue */ + TargetSendQueue = 128, -/** How often to log send queue size */ -static constexpr auto kSendQueueLogFreq = 64; + /** How often to log send queue size */ + SendQueueLogFreq = 64, -/** How often we check for idle peers (seconds) */ -static constexpr auto kCheckIdlePeers = 4; + /** How often we check for idle peers (seconds) */ + CheckIdlePeers = 4, -/** The maximum number of levels to search */ -static constexpr auto kMaxQueryDepth = 3; + /** The maximum number of levels to search */ + MaxQueryDepth = 3, +}; /** Size of buffer used to read from the socket. */ -constexpr std::size_t kReadBufferBytes = 16384; +std::size_t constexpr kREAD_BUFFER_BYTES = 16384; } // namespace xrpl::Tuning diff --git a/src/xrpld/overlay/detail/TxMetrics.cpp b/src/xrpld/overlay/detail/TxMetrics.cpp index d2597cb19f..c1a336b11e 100644 --- a/src/xrpld/overlay/detail/TxMetrics.cpp +++ b/src/xrpld/overlay/detail/TxMetrics.cpp @@ -77,13 +77,13 @@ SingleMetrics::addMetrics(std::uint32_t val) { using namespace std::chrono_literals; accum += val; - n++; + N++; auto const timeElapsed = clock_type::now() - intervalStart; auto const timeElapsedInSecs = std::chrono::duration_cast(timeElapsed); if (timeElapsedInSecs >= 1s) { - auto const avg = accum / (perTimeUnit ? timeElapsedInSecs.count() : n); + auto const avg = accum / (perTimeUnit ? timeElapsedInSecs.count() : N); rollingAvgAggregate.push_back(avg); auto const total = @@ -92,7 +92,7 @@ SingleMetrics::addMetrics(std::uint32_t val) intervalStart = clock_type::now(); accum = 0; - n = 0; + N = 0; } } @@ -101,7 +101,7 @@ TxMetrics::json() const { std::scoped_lock const l(mutex); - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::txr_tx_cnt] = std::to_string(tx.m1.rollingAvg); ret[jss::txr_tx_sz] = std::to_string(tx.m2.rollingAvg); diff --git a/src/xrpld/overlay/detail/TxMetrics.h b/src/xrpld/overlay/detail/TxMetrics.h index 50df7a65cc..7b8b4bae1b 100644 --- a/src/xrpld/overlay/detail/TxMetrics.h +++ b/src/xrpld/overlay/detail/TxMetrics.h @@ -29,7 +29,7 @@ struct SingleMetrics clock_type::time_point intervalStart{clock_type::now()}; std::uint64_t accum{0}; std::uint64_t rollingAvg{0}; - std::uint32_t n{0}; + std::uint32_t N{0}; bool perTimeUnit{true}; boost::circular_buffer rollingAvgAggregate{30, 0ull}; /** Add metrics value diff --git a/src/xrpld/overlay/make_Overlay.h b/src/xrpld/overlay/make_Overlay.h index acd477deec..94d1110f4b 100644 --- a/src/xrpld/overlay/make_Overlay.h +++ b/src/xrpld/overlay/make_Overlay.h @@ -10,7 +10,7 @@ namespace xrpl { Overlay::Setup -setupOverlay(BasicConfig const& config, beast::Journal j); +setupOverlay(BasicConfig const& config); /** Creates the implementation of Overlay. */ std::unique_ptr diff --git a/src/xrpld/peerfinder/PeerfinderManager.h b/src/xrpld/peerfinder/PeerfinderManager.h index f88b1b637c..072750efe7 100644 --- a/src/xrpld/peerfinder/PeerfinderManager.h +++ b/src/xrpld/peerfinder/PeerfinderManager.h @@ -27,7 +27,7 @@ struct Config This includes both inbound and outbound, but does not include fixed peers. */ - std::size_t maxPeers{Tuning::kDefaultMaxPeers}; + std::size_t maxPeers{Tuning::DefaultMaxPeers}; /** The number of automatic outbound connections to maintain. Outbound connections are only maintained if autoConnect @@ -59,9 +59,6 @@ struct Config /** Limit how many incoming connections we allow per IP */ int ipLimit{0}; - /** `true` if we want to verify endpoints in TMEndpoints messages */ - bool verifyEndpoints = true; - //-------------------------------------------------------------------------- /** Create a configuration with default values. */ @@ -84,8 +81,6 @@ struct Config * @param port server's listening port * @param validationPublicKey true if validation public key is not empty * @param ipLimit limit of incoming connections per IP - * @param verifyEndpoints `true` if we want to verify endpoints in - * TMEndpoints messages * @return PeerFinder::Config */ static Config @@ -93,11 +88,10 @@ struct Config xrpl::Config const& config, std::uint16_t port, bool validationPublicKey, - int ipLimit, - bool verifyEndpoints); + int ipLimit); friend bool - operator==(Config const& lhs, Config const& rhs) = default; + operator==(Config const& lhs, Config const& rhs); }; //------------------------------------------------------------------------------ diff --git a/src/xrpld/peerfinder/detail/Bootcache.cpp b/src/xrpld/peerfinder/detail/Bootcache.cpp index a0a753530b..140d0f01c6 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.cpp +++ b/src/xrpld/peerfinder/detail/Bootcache.cpp @@ -110,13 +110,13 @@ Bootcache::insert(beast::IP::Endpoint const& endpoint) bool Bootcache::insertStatic(beast::IP::Endpoint const& endpoint) { - auto result(map_.insert(value_type(endpoint, kStaticValence))); + auto result(map_.insert(value_type(endpoint, kSTATIC_VALENCE))); - if (!result.second && (result.first->right.valence() < kStaticValence)) + if (!result.second && (result.first->right.valence() < kSTATIC_VALENCE)) { // An existing entry has too low a valence, replace it map_.erase(result.first); - result = map_.insert(value_type(endpoint, kStaticValence)); + result = map_.insert(value_type(endpoint, kSTATIC_VALENCE)); } if (result.second) @@ -143,7 +143,7 @@ Bootcache::onSuccess(beast::IP::Endpoint const& endpoint) ++entry.valence(); map_.erase(result.first); result = map_.insert(value_type(endpoint, entry)); - XRPL_ASSERT(result.second, "xrpl::PeerFinder::Bootcache::onSuccess : endpoint inserted"); + XRPL_ASSERT(result.second, "xrpl::PeerFinder::Bootcache::on_success : endpoint inserted"); } Entry const& entry(result.first->right); JLOG(journal_.info()) << beast::Leftw(18) << "Bootcache connect " << endpoint << " with " @@ -166,7 +166,7 @@ Bootcache::onFailure(beast::IP::Endpoint const& endpoint) --entry.valence(); map_.erase(result.first); result = map_.insert(value_type(endpoint, entry)); - XRPL_ASSERT(result.second, "xrpl::PeerFinder::Bootcache::onFailure : endpoint inserted"); + XRPL_ASSERT(result.second, "xrpl::PeerFinder::Bootcache::on_failure : endpoint inserted"); } Entry const& entry(result.first->right); auto const n(std::abs(entry.valence())); @@ -199,11 +199,11 @@ Bootcache::onWrite(beast::PropertyStream::Map& map) void Bootcache::prune() { - if (size() <= Tuning::kBootcacheSize) + if (size() <= Tuning::BootcacheSize) return; // Calculate the amount to remove - auto count((size() * Tuning::kBootcachePrunePercent) / 100); + auto count((size() * Tuning::BootcachePrunePercent) / 100); decltype(count) pruned(0); // Work backwards because bimap doesn't handle @@ -240,7 +240,7 @@ Bootcache::update() store_.save(list); // Reset the flag and cooldown timer needsUpdate_ = false; - whenUpdate_ = clock_.now() + Tuning::kBootcacheCooldownTime; + whenUpdate_ = clock_.now() + Tuning::kBOOTCACHE_COOLDOWN_TIME; } // Checks the clock and calls update if we are off the cooldown. diff --git a/src/xrpld/peerfinder/detail/Bootcache.h b/src/xrpld/peerfinder/detail/Bootcache.h index 01ee2cad33..c061f37595 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.h +++ b/src/xrpld/peerfinder/detail/Bootcache.h @@ -97,7 +97,7 @@ private: bool needsUpdate_{false}; public: - static constexpr int kStaticValence = 32; + static constexpr int kSTATIC_VALENCE = 32; using iterator = boost::transform_iterator; diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index 67b8370996..e859b09d21 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -42,18 +42,18 @@ public: return true; if (s.inbound()) - return inActive_ < inMax_; + return in_active_ < in_max_; - return outActive_ < outMax_; + return out_active_ < out_max_; } /** Returns the number of attempts needed to bring us to the max. */ [[nodiscard]] std::size_t attemptsNeeded() const { - if (attempts_ >= Tuning::kMaxConnectAttempts) + if (attempts_ >= Tuning::MaxConnectAttempts) return 0; - return Tuning::kMaxConnectAttempts - attempts_; + return Tuning::MaxConnectAttempts - attempts_; } /** Returns the number of outbound connection attempts. */ @@ -67,7 +67,7 @@ public: [[nodiscard]] int outMax() const { - return outMax_; + return out_max_; } /** Returns the number of outbound peers assigned an open slot. @@ -76,7 +76,7 @@ public: [[nodiscard]] int outActive() const { - return outActive_; + return out_active_; } /** Returns the number of fixed connections. */ @@ -90,7 +90,7 @@ public: [[nodiscard]] std::size_t fixedActive() const { - return fixedActive_; + return fixed_active_; } //-------------------------------------------------------------------------- @@ -99,9 +99,9 @@ public: void onConfig(Config const& config) { - outMax_ = config.outPeers; + out_max_ = config.outPeers; if (config.wantIncoming) - inMax_ = config.inPeers; + in_max_ = config.inPeers; } /** Returns the number of accepted connections that haven't handshaked. */ @@ -129,21 +129,21 @@ public: [[nodiscard]] int inMax() const { - return inMax_; + return in_max_; } /** Returns the number of inbound peers assigned an open slot. */ [[nodiscard]] int inboundActive() const { - return inActive_; + return in_active_; } /** Returns the total number of active peers excluding fixed peers. */ [[nodiscard]] int totalActive() const { - return inActive_ + outActive_; + return in_active_ + out_active_; } /** Returns the number of unused inbound slots. @@ -152,8 +152,8 @@ public: [[nodiscard]] int inboundSlotsFree() const { - if (inActive_ < inMax_) - return inMax_ - inActive_; + if (in_active_ < in_max_) + return in_max_ - in_active_; return 0; } @@ -163,8 +163,8 @@ public: [[nodiscard]] int outboundSlotsFree() const { - if (outActive_ < outMax_) - return outMax_ - outActive_; + if (out_active_ < out_max_) + return out_max_ - out_active_; return 0; } @@ -181,7 +181,7 @@ public: // // Fixed peers do not count towards the active outgoing total. - return outMax_ <= 0; + return out_max_ <= 0; } /** Output statistics. */ @@ -191,9 +191,9 @@ public: map["accept"] = acceptCount(); map["connect"] = connectCount(); map["close"] = closingCount(); - map["in"] << inActive_ << "/" << inMax_; - map["out"] << outActive_ << "/" << outMax_; - map["fixed"] = fixedActive_; + map["in"] << in_active_ << "/" << in_max_; + map["out"] << out_active_ << "/" << out_max_; + map["fixed"] = fixed_active_; map["reserved"] = reserved_; map["total"] = active_; } @@ -203,7 +203,7 @@ public: stateString() const { std::stringstream ss; - ss << outActive_ << "/" << outMax_ << " out, " << inActive_ << "/" << inMax_ << " in, " + ss << out_active_ << "/" << out_max_ << " out, " << in_active_ << "/" << in_max_ << " in, " << connectCount() << " connecting, " << closingCount() << " closing"; return ss.str(); } @@ -262,16 +262,16 @@ private: case Slot::State::Active: if (s.fixed()) - adjustCounter(fixedActive_, dir); + adjustCounter(fixed_active_, dir); if (!s.fixed() && !s.reserved()) { if (s.inbound()) { - adjustCounter(inActive_, dir); + adjustCounter(in_active_, dir); } else { - adjustCounter(outActive_, dir); + adjustCounter(out_active_, dir); } } adjustCounter(active_, dir); @@ -297,22 +297,22 @@ private: std::size_t active_{0}; /** Total number of inbound slots. */ - std::size_t inMax_{0}; + std::size_t in_max_{0}; /** Number of inbound slots assigned to active peers. */ - std::size_t inActive_{0}; + std::size_t in_active_{0}; /** Maximum desired outbound slots. */ - std::size_t outMax_{0}; + std::size_t out_max_{0}; /** Active outbound slots. */ - std::size_t outActive_{0}; + std::size_t out_active_{0}; /** Fixed connections. */ std::size_t fixed_{0}; /** Active fixed connections. */ - std::size_t fixedActive_{0}; + std::size_t fixed_active_{0}; /** Reserved connections. */ std::size_t reserved_{0}; diff --git a/src/xrpld/peerfinder/detail/Endpoint.cpp b/src/xrpld/peerfinder/detail/Endpoint.cpp index 15de5cd153..ab9cd66809 100644 --- a/src/xrpld/peerfinder/detail/Endpoint.cpp +++ b/src/xrpld/peerfinder/detail/Endpoint.cpp @@ -10,7 +10,7 @@ namespace xrpl::PeerFinder { Endpoint::Endpoint(beast::IP::Endpoint ep, std::uint32_t hops) - : hops(std::min(hops, Tuning::kMaxHops + 1)), address(std::move(ep)) + : hops(std::min(hops, Tuning::kMAX_HOPS + 1)), address(std::move(ep)) { } diff --git a/src/xrpld/peerfinder/detail/Fixed.h b/src/xrpld/peerfinder/detail/Fixed.h index 61df9caddb..c334b9ac99 100644 --- a/src/xrpld/peerfinder/detail/Fixed.h +++ b/src/xrpld/peerfinder/detail/Fixed.h @@ -25,8 +25,8 @@ public: void failure(clock_type::time_point const& now) { - failures_ = std::min(failures_ + 1, Tuning::kConnectionBackoff.size() - 1); - when_ = now + std::chrono::minutes(Tuning::kConnectionBackoff[failures_]); + failures_ = std::min(failures_ + 1, Tuning::kCONNECTION_BACKOFF.size() - 1); + when_ = now + std::chrono::minutes(Tuning::kCONNECTION_BACKOFF[failures_]); } /** Updates metadata to reflect a successful connection. */ diff --git a/src/xrpld/peerfinder/detail/Handouts.h b/src/xrpld/peerfinder/detail/Handouts.h index 19a367f8c1..f4c7483e3f 100644 --- a/src/xrpld/peerfinder/detail/Handouts.h +++ b/src/xrpld/peerfinder/detail/Handouts.h @@ -23,7 +23,7 @@ template std::size_t handoutOne(Target& t, HopContainer& h) { - XRPL_ASSERT(!t.full(), "xrpl::PeerFinder::detail::handoutOne : target is not full"); + XRPL_ASSERT(!t.full(), "xrpl::PeerFinder::detail::handout_one : target is not full"); for (auto it = h.begin(); it != h.end(); ++it) { auto const& e = *it; @@ -88,7 +88,7 @@ public: [[nodiscard]] bool full() const { - return list_.size() >= Tuning::kRedirectEndpointCount; + return list_.size() >= Tuning::kREDIRECT_ENDPOINT_COUNT; } [[nodiscard]] SlotImp::ptr const& @@ -117,7 +117,7 @@ private: template RedirectHandouts::RedirectHandouts(SlotImp::ptr slot) : slot_(std::move(slot)) { - list_.reserve(Tuning::kRedirectEndpointCount); + list_.reserve(Tuning::kREDIRECT_ENDPOINT_COUNT); } template @@ -131,7 +131,7 @@ RedirectHandouts::tryInsert(Endpoint const& ep) // addresses in a peer HTTP handshake instead of // the tmENDPOINTS message. // - if (ep.hops > Tuning::kMaxHops) + if (ep.hops > Tuning::kMAX_HOPS) return false; // Don't send them our address @@ -172,7 +172,7 @@ public: [[nodiscard]] bool full() const { - return list_.size() >= Tuning::kNumberOfEndpoints; + return list_.size() >= Tuning::kNUMBER_OF_ENDPOINTS; } void @@ -201,7 +201,7 @@ private: template SlotHandouts::SlotHandouts(SlotImp::ptr slot) : slot_(std::move(slot)) { - list_.reserve(Tuning::kNumberOfEndpoints); + list_.reserve(Tuning::kNUMBER_OF_ENDPOINTS); } template @@ -211,7 +211,7 @@ SlotHandouts::tryInsert(Endpoint const& ep) if (full()) return false; - if (ep.hops > Tuning::kMaxHops) + if (ep.hops > Tuning::kMAX_HOPS) return false; if (slot_->recent.filter(ep.address, ep.hops)) diff --git a/src/xrpld/peerfinder/detail/Livecache.h b/src/xrpld/peerfinder/detail/Livecache.h index 84efcb7bd1..063fb622cf 100644 --- a/src/xrpld/peerfinder/detail/Livecache.h +++ b/src/xrpld/peerfinder/detail/Livecache.h @@ -202,8 +202,8 @@ public: // but not given out (since they would exceed maxHops). They // are used for automatic connection attempts. // - using Histogram = std::array; - using lists_type = std::array; + using Histogram = std::array; + using lists_type = std::array; template struct Transform @@ -371,7 +371,7 @@ Livecache::expire() { std::size_t n(0); typename cache_type::time_point const expired( - cache_.clock().now() - Tuning::kLiveCacheSecondsToLive); + cache_.clock().now() - Tuning::kLIVE_CACHE_SECONDS_TO_LIVE); for (auto iter(cache_.chronological.begin()); iter != cache_.chronological.end() && iter.when() <= expired;) { @@ -398,7 +398,7 @@ Livecache::insert(Endpoint const& ep) // when redirecting. // XRPL_ASSERT( - ep.hops <= (Tuning::kMaxHops + 1), + ep.hops <= (Tuning::kMAX_HOPS + 1), "xrpl::PeerFinder::Livecache::insert : maximum input hops"); auto result = cache_.emplace(ep.address, ep); Element& e(result.first->second); @@ -439,7 +439,7 @@ void Livecache::onWrite(beast::PropertyStream::Map& map) { typename cache_type::time_point const expired( - cache_.clock().now() - Tuning::kLiveCacheSecondsToLive); + cache_.clock().now() - Tuning::kLIVE_CACHE_SECONDS_TO_LIVE); map["size"] = size(); map["hist"] = hops.histogram(); beast::PropertyStream::Set set("entries", map); @@ -498,8 +498,8 @@ void Livecache::HopsT::insert(Element& e) { XRPL_ASSERT( - e.endpoint.hops <= Tuning::kMaxHops + 1, - "xrpl::PeerFinder::Livecache::HopsT::insert : maximum input hops"); + e.endpoint.hops <= Tuning::kMAX_HOPS + 1, + "xrpl::PeerFinder::Livecache::hops_t::insert : maximum input hops"); // This has security implications without a shuffle lists_[e.endpoint.hops].push_front(e); ++hist_[e.endpoint.hops]; @@ -510,8 +510,8 @@ void Livecache::HopsT::reinsert(Element& e, std::uint32_t numHops) { XRPL_ASSERT( - numHops <= Tuning::kMaxHops + 1, - "xrpl::PeerFinder::Livecache::HopsT::reinsert : maximum hops input"); + numHops <= Tuning::kMAX_HOPS + 1, + "xrpl::PeerFinder::Livecache::hops_t::reinsert : maximum hops input"); auto& list = lists_[e.endpoint.hops]; list.erase(list.iterator_to(e)); diff --git a/src/xrpld/peerfinder/detail/Logic.h b/src/xrpld/peerfinder/detail/Logic.h index 3ebe0cf2f4..89e7336a33 100644 --- a/src/xrpld/peerfinder/detail/Logic.h +++ b/src/xrpld/peerfinder/detail/Logic.h @@ -633,7 +633,7 @@ public: result.emplace_back(slot, list); } - whenBroadcast = now + Tuning::kSecondsPerMessage; + whenBroadcast = now + Tuning::kSECONDS_PER_MESSAGE; } return result; @@ -652,7 +652,7 @@ public: entry.second->expire(); // Expire the recent attempts table - beast::expire(squelches, Tuning::kRecentAttemptDuration); + beast::expire(squelches, Tuning::kRECENT_ATTEMPT_DURATION); bootcache.periodicActivity(); } @@ -669,7 +669,7 @@ public: Endpoint& ep(*iter); // Enforce hop limit - if (ep.hops > Tuning::kMaxHops) + if (ep.hops > Tuning::kMAX_HOPS) { JLOG(journal.debug()) << beast::Leftw(18) << "Endpoints drop " << ep.address << " for excess hops " << ep.hops; @@ -696,7 +696,7 @@ public: } // Discard invalid addresses - if (config_.verifyEndpoints && !isValidAddress(ep.address)) + if (!isValidAddress(ep.address)) { JLOG(journal.debug()) << beast::Leftw(18) << "Endpoints drop " << ep.address << " as invalid"; @@ -731,10 +731,10 @@ public: beast::Journal const journal{sink}; // If we're sent too many endpoints, sample them at random: - if (list.size() > Tuning::kNumberOfEndpointsMax) + if (list.size() > Tuning::kNUMBER_OF_ENDPOINTS_MAX) { std::shuffle(list.begin(), list.end(), defaultPrng()); - list.resize(Tuning::kNumberOfEndpointsMax); + list.resize(Tuning::kNUMBER_OF_ENDPOINTS_MAX); } JLOG(journal.trace()) << "Endpoints contained " << list.size() @@ -745,12 +745,12 @@ public: // The object must exist in our table XRPL_ASSERT( slots.contains(slot->remoteEndpoint()), - "xrpl::PeerFinder::Logic::onEndpoints : valid slot input"); + "xrpl::PeerFinder::Logic::on_endpoints : valid slot input"); // Must be handshaked! XRPL_ASSERT( slot->state() == Slot::State::Active, - "xrpl::PeerFinder::Logic::onEndpoints : valid slot state"); + "xrpl::PeerFinder::Logic::on_endpoints : valid slot state"); clock_type::time_point const now(clock.now()); @@ -762,7 +762,7 @@ public: for (auto const& ep : list) { - XRPL_ASSERT(ep.hops, "xrpl::PeerFinder::Logic::onEndpoints : nonzero hops"); + XRPL_ASSERT(ep.hops, "xrpl::PeerFinder::Logic::on_endpoints : nonzero hops"); slot->recent.insert(ep.address, ep.hops); @@ -816,7 +816,7 @@ public: bootcache.insert(ep.address); } - slot->whenAcceptEndpoints = now + Tuning::kSecondsPerMessage; + slot->whenAcceptEndpoints = now + Tuning::kSECONDS_PER_MESSAGE; } //-------------------------------------------------------------------------- @@ -1088,8 +1088,6 @@ public: { if (isUnspecified(address)) return false; - if (isLoopback(address)) - return false; if (!isPublic(address)) return false; if (address.port() == 0) @@ -1207,7 +1205,7 @@ Logic::onRedirects( { std::scoped_lock const _(lock); std::size_t n = 0; - for (; first != last && n < Tuning::kMaxRedirects; ++first, ++n) + for (; first != last && n < Tuning::MaxRedirects; ++first, ++n) bootcache.insert(beast::IPAddressConversion::fromAsio(*first)); if (n > 0) { diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index fcf30fa4f4..ed9bba0ee4 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -15,10 +15,20 @@ Config::Config() : outPeers(calcOutPeers()) { } +bool +operator==(Config const& lhs, Config const& rhs) +{ + return lhs.autoConnect == rhs.autoConnect && lhs.peerPrivate == rhs.peerPrivate && + lhs.wantIncoming == rhs.wantIncoming && lhs.inPeers == rhs.inPeers && + lhs.maxPeers == rhs.maxPeers && lhs.outPeers == rhs.outPeers && + lhs.features == rhs.features && lhs.ipLimit == rhs.ipLimit && + lhs.listeningPort == rhs.listeningPort; +} + std::size_t Config::calcOutPeers() const { - return std::max((maxPeers * Tuning::kOutPercent + 50) / 100, std::size_t(Tuning::kMinOutCount)); + return std::max((maxPeers * Tuning::OutPercent + 50) / 100, std::size_t(Tuning::MinOutCount)); } void @@ -31,8 +41,8 @@ Config::applyTuning() // IP addresses. ipLimit = 2; - if (inPeers > Tuning::kDefaultMaxPeers) - ipLimit += std::min(5, static_cast(inPeers / Tuning::kDefaultMaxPeers)); + if (inPeers > Tuning::DefaultMaxPeers) + ipLimit += std::min(5, static_cast(inPeers / Tuning::DefaultMaxPeers)); } // We don't allow a single IP to consume all incoming slots, @@ -50,7 +60,6 @@ Config::onWrite(beast::PropertyStream::Map& map) const map["port"] = listeningPort; map["features"] = features; map["ip_limit"] = ipLimit; - map["verify_endpoints"] = verifyEndpoints; } Config @@ -58,22 +67,21 @@ Config::makeConfig( xrpl::Config const& cfg, std::uint16_t port, bool validationPublicKey, - int ipLimit, - bool verifyEndpoints) + int ipLimit) { PeerFinder::Config config; - config.peerPrivate = cfg.peerPrivate; + config.peerPrivate = cfg.PEER_PRIVATE; // Servers with peer privacy don't want to allow incoming connections config.wantIncoming = (!config.peerPrivate) && (port != 0); - if ((cfg.peersOutMax == 0u) && (cfg.peersInMax == 0u)) + if ((cfg.PEERS_OUT_MAX == 0u) && (cfg.PEERS_IN_MAX == 0u)) { - if (cfg.peersMax != 0) - config.maxPeers = cfg.peersMax; + if (cfg.PEERS_MAX != 0) + config.maxPeers = cfg.PEERS_MAX; - config.maxPeers = std::max(config.maxPeers, Tuning::kMinOutCount); + config.maxPeers = std::max(config.maxPeers, Tuning::MinOutCount); config.outPeers = config.calcOutPeers(); // Calculate the number of outbound peers we want. If we dont want @@ -94,8 +102,8 @@ Config::makeConfig( } else { - config.outPeers = cfg.peersOutMax; - config.inPeers = cfg.peersInMax; + config.outPeers = cfg.PEERS_OUT_MAX; + config.inPeers = cfg.PEERS_IN_MAX; config.maxPeers = 0; } @@ -108,11 +116,10 @@ Config::makeConfig( // if it's a private peer or we are running as standalone // automatic connections would defeat the purpose. - config.autoConnect = !cfg.standalone() && !cfg.peerPrivate; + config.autoConnect = !cfg.standalone() && !cfg.PEER_PRIVATE; config.listeningPort = port; config.features = ""; config.ipLimit = ipLimit; - config.verifyEndpoints = verifyEndpoints; // Enforce business rules config.applyTuning(); diff --git a/src/xrpld/peerfinder/detail/SlotImp.cpp b/src/xrpld/peerfinder/detail/SlotImp.cpp index a54ddb56e7..b941f54b48 100644 --- a/src/xrpld/peerfinder/detail/SlotImp.cpp +++ b/src/xrpld/peerfinder/detail/SlotImp.cpp @@ -23,9 +23,9 @@ SlotImp::SlotImp( , fixed_(fixed) , reserved_(false) , state_(State::Accept) - , remoteEndpoint_(std::move(remoteEndpoint)) - , localEndpoint_(localEndpoint) - , listeningPort_(kUnknownPort) + , remote_endpoint_(std::move(remoteEndpoint)) + , local_endpoint_(localEndpoint) + , listening_port_(kUNKNOWN_PORT) , checked(false) , canAccept(false) , connectivityCheckInProgress(false) @@ -38,8 +38,8 @@ SlotImp::SlotImp(beast::IP::Endpoint remoteEndpoint, bool fixed, clock_type& clo , fixed_(fixed) , reserved_(false) , state_(State::Connect) - , remoteEndpoint_(std::move(remoteEndpoint)) - , listeningPort_(kUnknownPort) + , remote_endpoint_(std::move(remoteEndpoint)) + , listening_port_(kUNKNOWN_PORT) , checked(true) , canAccept(true) , connectivityCheckInProgress(false) @@ -131,7 +131,7 @@ SlotImp::RecentT::filter(beast::IP::Endpoint const& ep, std::uint32_t hops) void SlotImp::RecentT::expire() { - beast::expire(cache_, Tuning::kLiveCacheSecondsToLive); + beast::expire(cache_, Tuning::kLIVE_CACHE_SECONDS_TO_LIVE); } } // namespace xrpl::PeerFinder diff --git a/src/xrpld/peerfinder/detail/SlotImp.h b/src/xrpld/peerfinder/detail/SlotImp.h index 0cf4d7a3c8..b198c93e5d 100644 --- a/src/xrpld/peerfinder/detail/SlotImp.h +++ b/src/xrpld/peerfinder/detail/SlotImp.h @@ -52,19 +52,19 @@ public: beast::IP::Endpoint const& remoteEndpoint() const override { - return remoteEndpoint_; + return remote_endpoint_; } std::optional const& localEndpoint() const override { - return localEndpoint_; + return local_endpoint_; } std::optional const& publicKey() const override { - return publicKey_; + return public_key_; } std::string @@ -76,8 +76,8 @@ public: std::optional listeningPort() const override { - std::uint32_t const value = listeningPort_; - if (value == kUnknownPort) + std::uint32_t const value = listening_port_; + if (value == kUNKNOWN_PORT) return std::nullopt; return value; } @@ -85,25 +85,25 @@ public: void setListeningPort(std::uint16_t port) { - listeningPort_ = port; + listening_port_ = port; } void localEndpoint(beast::IP::Endpoint const& endpoint) { - localEndpoint_ = endpoint; + local_endpoint_ = endpoint; } void remoteEndpoint(beast::IP::Endpoint const& endpoint) { - remoteEndpoint_ = endpoint; + remote_endpoint_ = endpoint; } void publicKey(PublicKey const& key) { - publicKey_ = key; + public_key_ = key; } void @@ -160,12 +160,12 @@ private: bool const fixed_; bool reserved_; State state_; - beast::IP::Endpoint remoteEndpoint_; - std::optional localEndpoint_; - std::optional publicKey_; + beast::IP::Endpoint remote_endpoint_; + std::optional local_endpoint_; + std::optional public_key_; - static constexpr std::int32_t kUnknownPort = -1; - std::atomic listeningPort_; + static std::int32_t constexpr kUNKNOWN_PORT = -1; + std::atomic listening_port_; public: // DEPRECATED public data members diff --git a/src/xrpld/peerfinder/detail/StoreSqdb.h b/src/xrpld/peerfinder/detail/StoreSqdb.h index 19cdd774b7..13338cbd73 100644 --- a/src/xrpld/peerfinder/detail/StoreSqdb.h +++ b/src/xrpld/peerfinder/detail/StoreSqdb.h @@ -15,7 +15,12 @@ private: soci::session sqlDb_; public: - static constexpr auto kCurrentSchemaVersion = 4; // on-database format version + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) + enum { + // This determines the on-database format of the data + CurrentSchemaVersion = 4 + }; explicit StoreSqdb(beast::Journal journal = beast::Journal{beast::Journal::getNullSink()}) : journal_(journal) @@ -68,7 +73,7 @@ public: void update() { - updatePeerFinderDB(sqlDb_, kCurrentSchemaVersion, journal_); + updatePeerFinderDB(sqlDb_, CurrentSchemaVersion, journal_); } private: diff --git a/src/xrpld/peerfinder/detail/Tuning.h b/src/xrpld/peerfinder/detail/Tuning.h index b4781495b8..4fc57a69a0 100644 --- a/src/xrpld/peerfinder/detail/Tuning.h +++ b/src/xrpld/peerfinder/detail/Tuning.h @@ -6,39 +6,48 @@ /** @{ */ namespace xrpl::PeerFinder::Tuning { -//--------------------------------------------------------- -// -// Automatic Connection Policy -// -//--------------------------------------------------------- +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + //--------------------------------------------------------- + // + // Automatic Connection Policy + // + //--------------------------------------------------------- -/** Time to wait between making batches of connection attempts */ -static constexpr auto kSecondsPerConnect = 10; + /** Time to wait between making batches of connection attempts */ + SecondsPerConnect = 10 -/** Maximum number of simultaneous connection attempts. */ -static constexpr auto kMaxConnectAttempts = 20; + /** Maximum number of simultaneous connection attempts. */ + , + MaxConnectAttempts = 20 -/** The percentage of total peer slots that are outbound. - The number of outbound peers will be the larger of the - minOutCount and outPercent * Config::maxPeers specially - rounded. -*/ -static constexpr auto kOutPercent = 15; + /** The percentage of total peer slots that are outbound. + The number of outbound peers will be the larger of the + minOutCount and outPercent * Config::maxPeers specially + rounded. + */ + , + OutPercent = 15 -/** A hard minimum on the number of outgoing connections. - This is enforced outside the Logic, so that the unit test - can use any settings it wants. -*/ -static constexpr auto kMinOutCount = 10; + /** A hard minimum on the number of outgoing connections. + This is enforced outside the Logic, so that the unit test + can use any settings it wants. + */ + , + MinOutCount = 10 -/** The default value of Config::maxPeers. */ -static constexpr auto kDefaultMaxPeers = 21; + /** The default value of Config::maxPeers. */ + , + DefaultMaxPeers = 21 -/** Max redirects we will accept from one connection. - Redirects are limited for security purposes, to prevent - the address caches from getting flooded. -*/ -static constexpr auto kMaxRedirects = 30; + /** Max redirects we will accept from one connection. + Redirects are limited for security purposes, to prevent + the address caches from getting flooded. + */ + , + MaxRedirects = 30 +}; //------------------------------------------------------------------------------ // @@ -46,7 +55,7 @@ static constexpr auto kMaxRedirects = 30; // //------------------------------------------------------------------------------ -static std::array const kConnectionBackoff{{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}}; +static std::array const kCONNECTION_BACKOFF{{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}}; //------------------------------------------------------------------------------ // @@ -54,17 +63,22 @@ static std::array const kConnectionBackoff{{1, 1, 2, 3, 5, 8, 13, 21, 3 // //------------------------------------------------------------------------------ -// Threshold of cache entries above which we trim. -static constexpr auto kBootcacheSize = 1000; +// Need to be named before converting +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum { + // Threshold of cache entries above which we trim. + BootcacheSize = 1000 -// The percentage of addresses we prune when we trim the cache. -static constexpr auto kBootcachePrunePercent = 10; + // The percentage of addresses we prune when we trim the cache. + , + BootcachePrunePercent = 10 +}; // The cool down wait between database updates // Ideally this should be larger than the time it takes a full // peer to send us a set of addresses and then disconnect. // -static std::chrono::seconds const kBootcacheCooldownTime(60); +static std::chrono::seconds const kBOOTCACHE_COOLDOWN_TIME(60); //------------------------------------------------------------------------------ // @@ -73,29 +87,29 @@ static std::chrono::seconds const kBootcacheCooldownTime(60); //------------------------------------------------------------------------------ // Drop incoming messages with hops greater than this number -constexpr std::uint32_t kMaxHops = 6; +std::uint32_t constexpr kMAX_HOPS = 6; // How many Endpoint to send in each mtENDPOINTS -constexpr std::uint32_t kNumberOfEndpoints = 2 * kMaxHops; +std::uint32_t constexpr kNUMBER_OF_ENDPOINTS = 2 * kMAX_HOPS; // The most Endpoint we will accept in mtENDPOINTS -constexpr std::uint32_t kNumberOfEndpointsMax = - std::max(kNumberOfEndpoints * 2, 64); +std::uint32_t constexpr kNUMBER_OF_ENDPOINTS_MAX = + std::max(kNUMBER_OF_ENDPOINTS * 2, 64); // Number of addresses we provide when redirecting. -constexpr std::uint32_t kRedirectEndpointCount = 10; +std::uint32_t constexpr kREDIRECT_ENDPOINT_COUNT = 10; // How often we send or accept mtENDPOINTS messages per peer // (we use a prime number of purpose) -constexpr std::chrono::seconds kSecondsPerMessage(151); +std::chrono::seconds constexpr kSECONDS_PER_MESSAGE(151); // How long an Endpoint will stay in the cache // This should be a small multiple of the broadcast frequency -constexpr std::chrono::seconds kLiveCacheSecondsToLive(30); +std::chrono::seconds constexpr kLIVE_CACHE_SECONDS_TO_LIVE(30); // How much time to wait before trying an outgoing address again. // Note that we ignore the port for purposes of comparison. -constexpr std::chrono::seconds kRecentAttemptDuration(60); +std::chrono::seconds constexpr kRECENT_ATTEMPT_DURATION(60); } // namespace xrpl::PeerFinder::Tuning /** @} */ diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index 60b6efc0a9..d50a4ab863 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -72,7 +72,7 @@ PerfLogImp::Counters::Counters(std::set const& labels, JobTypes con json::Value PerfLogImp::Counters::countersJson() const { - json::Value rpcobj(json::ValueType::Object); + json::Value rpcobj(json::ObjectValue); // totalRpc represents all rpc methods. All that started, finished, etc. Rpc totalRpc; for (auto const& proc : rpc) @@ -88,7 +88,7 @@ PerfLogImp::Counters::countersJson() const value = proc.second.value; } - json::Value p(json::ValueType::Object); + json::Value p(json::ObjectValue); p[jss::started] = std::to_string(value.started); totalRpc.started += value.started; p[jss::finished] = std::to_string(value.finished); @@ -102,7 +102,7 @@ PerfLogImp::Counters::countersJson() const if (totalRpc.started != 0u) { - json::Value totalRpcJson(json::ValueType::Object); + json::Value totalRpcJson(json::ObjectValue); totalRpcJson[jss::started] = std::to_string(totalRpc.started); totalRpcJson[jss::finished] = std::to_string(totalRpc.finished); totalRpcJson[jss::errored] = std::to_string(totalRpc.errored); @@ -110,7 +110,7 @@ PerfLogImp::Counters::countersJson() const rpcobj[jss::total] = totalRpcJson; } - json::Value jobQueueObj(json::ValueType::Object); + json::Value jobQueueObj(json::ObjectValue); // totalJq represents all jobs. All enqueued, started, finished, etc. Jq totalJq; for (auto const& proc : jq) @@ -126,7 +126,7 @@ PerfLogImp::Counters::countersJson() const value = proc.second.value; } - json::Value j(json::ValueType::Object); + json::Value j(json::ObjectValue); j[jss::queued] = std::to_string(value.queued); totalJq.queued += value.queued; j[jss::started] = std::to_string(value.started); @@ -142,7 +142,7 @@ PerfLogImp::Counters::countersJson() const if (totalJq.queued != 0u) { - json::Value totalJqJson(json::ValueType::Object); + json::Value totalJqJson(json::ObjectValue); totalJqJson[jss::queued] = std::to_string(totalJq.queued); totalJqJson[jss::started] = std::to_string(totalJq.started); totalJqJson[jss::finished] = std::to_string(totalJq.finished); @@ -151,7 +151,7 @@ PerfLogImp::Counters::countersJson() const jobQueueObj[jss::total] = totalJqJson; } - json::Value counters(json::ValueType::Object); + json::Value counters(json::ObjectValue); // Be kind to reporting tools and let them expect rpc and jq objects // even if empty. counters[jss::rpc] = rpcobj; @@ -164,7 +164,7 @@ PerfLogImp::Counters::currentJson() const { auto const present = steady_clock::now(); - json::Value jobsArray(json::ValueType::Array); + json::Value jobsArray(json::ArrayValue); auto const jobs = [this] { std::scoped_lock const lock(jobsMutex); return this->jobs; @@ -174,14 +174,14 @@ PerfLogImp::Counters::currentJson() const { if (j.first == JtInvalid) continue; - json::Value jobj(json::ValueType::Object); + json::Value jobj(json::ObjectValue); jobj[jss::job] = JobTypes::name(j.first); jobj[jss::duration_us] = std::to_string(std::chrono::duration_cast(present - j.second).count()); jobsArray.append(jobj); } - json::Value methodsArray(json::ValueType::Array); + json::Value methodsArray(json::ArrayValue); std::vector methods; { std::scoped_lock const lock(methodsMutex); @@ -191,14 +191,14 @@ PerfLogImp::Counters::currentJson() const } for (auto m : methods) { - json::Value methodobj(json::ValueType::Object); + json::Value methodobj(json::ObjectValue); methodobj[jss::method] = m.first; methodobj[jss::duration_us] = std::to_string(std::chrono::duration_cast(present - m.second).count()); methodsArray.append(methodobj); } - json::Value current(json::ValueType::Object); + json::Value current(json::ObjectValue); current[jss::jobs] = jobsArray; current[jss::methods] = methodsArray; return current; @@ -277,7 +277,7 @@ PerfLogImp::report() return; lastLog_ = present; - json::Value report(json::ValueType::Object); + json::Value report(json::ObjectValue); report[jss::time] = to_string(std::chrono::floor(present)); { std::scoped_lock const lock{counters_.jobsMutex}; @@ -285,7 +285,7 @@ PerfLogImp::report() } report[jss::hostid] = hostname_; report[jss::counters] = counters_.countersJson(); - report[jss::nodestore] = json::ValueType::Object; + report[jss::nodestore] = json::ObjectValue; app_.getNodeStore().getCountsJson(report[jss::nodestore]); report[jss::current_activities] = counters_.currentJson(); app_.getOPs().stateAccounting(report); diff --git a/src/xrpld/rpc/BookChanges.h b/src/xrpld/rpc/BookChanges.h index 45c3cf2e4b..f80de30b09 100644 --- a/src/xrpld/rpc/BookChanges.h +++ b/src/xrpld/rpc/BookChanges.h @@ -108,15 +108,15 @@ computeBookChanges(std::shared_ptr const& lpAccepted) STAmount second = noswap ? deltaPays : deltaGets; // defensively programmed, should (probably) never happen - if (second == beast::kZero) + if (second == beast::kZERO) continue; STAmount const rate = divide(first, second, noIssue()); - if (first < beast::kZero) + if (first < beast::kZERO) first = -first; - if (second < beast::kZero) + if (second < beast::kZERO) second = -second; std::stringstream ss; @@ -164,7 +164,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) } } - json::Value jvObj(json::ValueType::Object); + json::Value jvObj(json::ObjectValue); jvObj[jss::type] = "bookChanges"; // retrieve validated information from LedgerHeader class @@ -174,7 +174,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) jvObj[jss::ledger_time] = json::Value::UInt(lpAccepted->header().closeTime.time_since_epoch().count()); - jvObj[jss::changes] = json::ValueType::Array; + jvObj[jss::changes] = json::ArrayValue; auto volToStr = [](STAmount const& vol) { return vol.asset().visit( @@ -188,7 +188,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) for (auto const& entry : tally) { - json::Value& inner = jvObj[jss::changes].append(json::ValueType::Object); + json::Value& inner = jvObj[jss::changes].append(json::ObjectValue); STAmount const volA = std::get<0>(entry.second); STAmount const volB = std::get<1>(entry.second); diff --git a/src/xrpld/rpc/CTID.h b/src/xrpld/rpc/CTID.h index 781cd85e29..6c7e95a246 100644 --- a/src/xrpld/rpc/CTID.h +++ b/src/xrpld/rpc/CTID.h @@ -30,11 +30,11 @@ namespace xrpl::RPC { inline std::optional encodeCTID(uint32_t ledgerSeq, uint32_t txnIndex, uint32_t networkID) noexcept { - static constexpr uint32_t kMaxLedgerSeq = 0x0FFF'FFFF; - static constexpr uint32_t kMaxTxnIndex = 0xFFFF; - static constexpr uint32_t kMaxNetworkId = 0xFFFF; + constexpr uint32_t kMAX_LEDGER_SEQ = 0x0FFF'FFFF; + constexpr uint32_t kMAX_TXN_INDEX = 0xFFFF; + constexpr uint32_t kMAX_NETWORK_ID = 0xFFFF; - if (ledgerSeq > kMaxLedgerSeq || txnIndex > kMaxTxnIndex || networkID > kMaxNetworkId) + if (ledgerSeq > kMAX_LEDGER_SEQ || txnIndex > kMAX_TXN_INDEX || networkID > kMAX_NETWORK_ID) return std::nullopt; uint64_t const ctidValue = ((0xC000'0000ULL + static_cast(ledgerSeq)) << 32) | @@ -68,8 +68,8 @@ decodeCTID(T const ctid) noexcept if (ctidString.size() != 16) return std::nullopt; - static boost::regex const kHexRegex("^[0-9A-Fa-f]{16}$"); - if (!boost::regex_match(ctidString, kHexRegex)) + static boost::regex const kHEX_REGEX("^[0-9A-Fa-f]{16}$"); + if (!boost::regex_match(ctidString, kHEX_REGEX)) return std::nullopt; try @@ -94,9 +94,9 @@ decodeCTID(T const ctid) noexcept } // Validate CTID prefix. - static constexpr uint64_t kCtidPrefixMask = 0xF000'0000'0000'0000ULL; - static constexpr uint64_t kCtidPrefix = 0xC000'0000'0000'0000ULL; - if ((ctidValue & kCtidPrefixMask) != kCtidPrefix) + constexpr uint64_t kCTID_PREFIX_MASK = 0xF000'0000'0000'0000ULL; + constexpr uint64_t kCTID_PREFIX = 0xC000'0000'0000'0000ULL; + if ((ctidValue & kCTID_PREFIX_MASK) != kCTID_PREFIX) return std::nullopt; uint32_t const ledgerSeq = static_cast((ctidValue >> 32) & 0x0FFF'FFFF); diff --git a/src/xrpld/rpc/ServerHandler.h b/src/xrpld/rpc/ServerHandler.h index 0aac05ea44..6b4cc34cc5 100644 --- a/src/xrpld/rpc/ServerHandler.h +++ b/src/xrpld/rpc/ServerHandler.h @@ -46,8 +46,8 @@ public: std::uint16_t port = 0; std::string user; std::string password; - std::string adminUser; - std::string adminPassword; + std::string admin_user; + std::string admin_password; }; // Configuration when acting in client role @@ -72,9 +72,9 @@ private: Setup setup_; Endpoints endpoints_; JobQueue& jobQueue_; - beast::insight::Counter rpcRequests_; - beast::insight::Event rpcSize_; - beast::insight::Event rpcTime_; + beast::insight::Counter rpc_requests_; + beast::insight::Event rpc_size_; + beast::insight::Event rpc_time_; std::mutex mutex_; std::condition_variable condition_; bool stopped_{false}; diff --git a/src/xrpld/rpc/detail/AccountAssets.cpp b/src/xrpld/rpc/detail/AccountAssets.cpp index 67b9174fe3..5bc4360a0e 100644 --- a/src/xrpld/rpc/detail/AccountAssets.cpp +++ b/src/xrpld/rpc/detail/AccountAssets.cpp @@ -32,7 +32,7 @@ accountSourceAssets( auto& saBalance = rspEntry.getBalance(); // Filter out non - if (saBalance > beast::kZero + if (saBalance > beast::kZERO // Have IOUs to send. || (rspEntry.getLimitPeer() // Peer extends credit. diff --git a/src/xrpld/rpc/detail/AssetCache.cpp b/src/xrpld/rpc/detail/AssetCache.cpp index 0976290d4c..a0743a2303 100644 --- a/src/xrpld/rpc/detail/AssetCache.cpp +++ b/src/xrpld/rpc/detail/AssetCache.cpp @@ -124,7 +124,7 @@ AssetCache::getMPTs(xrpl::AccountID const& account) std::vector mpts; // Get issued/authorized tokens - forEachItem(*ledger_, account, [&](SLE::const_ref sle) { + forEachItem(*ledger_, account, [&](std::shared_ptr const& sle) { if (sle->getType() == ltMPTOKEN_ISSUANCE) { auto const mptID = makeMptID(sle->getFieldU32(sfSequence), account); diff --git a/src/xrpld/rpc/detail/AssetCache.h b/src/xrpld/rpc/detail/AssetCache.h index dd53620cdf..9112d78715 100644 --- a/src/xrpld/rpc/detail/AssetCache.h +++ b/src/xrpld/rpc/detail/AssetCache.h @@ -56,10 +56,10 @@ private: { AccountID account; LineDirection direction; - std::size_t hashValue; + std::size_t hash_value; AccountKey(AccountID const& account, LineDirection direction, std::size_t hash) - : account(account), direction(direction), hashValue(hash) + : account(account), direction(direction), hash_value(hash) { } @@ -71,14 +71,14 @@ private: bool operator==(AccountKey const& lhs) const { - return hashValue == lhs.hashValue && account == lhs.account && + return hash_value == lhs.hash_value && account == lhs.account && direction == lhs.direction; } [[nodiscard]] std::size_t getHash() const { - return hashValue; + return hash_value; } struct Hash diff --git a/src/xrpld/rpc/detail/DeliveredAmount.cpp b/src/xrpld/rpc/detail/DeliveredAmount.cpp index 8d8aac33bf..32554e8b5f 100644 --- a/src/xrpld/rpc/detail/DeliveredAmount.cpp +++ b/src/xrpld/rpc/detail/DeliveredAmount.cpp @@ -100,7 +100,7 @@ insertDeliveredAmount( auto amt = getDeliveredAmount(getLedgerIndex, getCloseTime, serializedTx, transactionMeta); if (amt) { - meta[jss::delivered_amount] = amt->getJson(JsonOptions::Values::IncludeDate); + meta[jss::delivered_amount] = amt->getJson(JsonOptions::KIncludeDate); } else { @@ -167,7 +167,7 @@ insertDeliveredAmount( if (amt) { - meta[jss::delivered_amount] = amt->getJson(JsonOptions::Values::IncludeDate); + meta[jss::delivered_amount] = amt->getJson(JsonOptions::KIncludeDate); } else { diff --git a/src/xrpld/rpc/detail/Handler.cpp b/src/xrpld/rpc/detail/Handler.cpp index 23eb8fdeec..6b04f24094 100644 --- a/src/xrpld/rpc/detail/Handler.cpp +++ b/src/xrpld/rpc/detail/Handler.cpp @@ -28,7 +28,7 @@ byRef(Function const& f) { return [f](JsonContext& context, json::Value& result) { result = f(context); - if (result.type() != json::ValueType::Object) + if (result.type() != json::ObjectValue) { // LCOV_EXCL_START UNREACHABLE("xrpl::RPC::byRef : result is object"); @@ -75,296 +75,287 @@ handlerFrom() HandlerImpl::maxApiVer}; } -Handler const kHandlerArray[]{ +Handler const kHANDLER_ARRAY[]{ // Some handlers not specified here are added to the table via addHandler() // Request-response methods {.name = "account_info", .valueMethod = byRef(&doAccountInfo), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_currencies", .valueMethod = byRef(&doAccountCurrencies), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_lines", .valueMethod = byRef(&doAccountLines), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_channels", .valueMethod = byRef(&doAccountChannels), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_nfts", .valueMethod = byRef(&doAccountNFTs), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_objects", .valueMethod = byRef(&doAccountObjects), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_offers", .valueMethod = byRef(&doAccountOffers), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "account_tx", .valueMethod = byRef(&doAccountTx), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "amm_info", .valueMethod = byRef(&doAMMInfo), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "blacklist", .valueMethod = byRef(&doBlackList), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "book_changes", .valueMethod = byRef(&doBookChanges), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "book_offers", .valueMethod = byRef(&doBookOffers), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "can_delete", .valueMethod = byRef(&doCanDelete), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "channel_authorize", .valueMethod = byRef(&doChannelAuthorize), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "channel_verify", .valueMethod = byRef(&doChannelVerify), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "connect", .valueMethod = byRef(&doConnect), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "consensus_info", .valueMethod = byRef(&doConsensusInfo), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "deposit_authorized", .valueMethod = byRef(&doDepositAuthorized), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "feature", .valueMethod = byRef(&doFeature), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "fee", .valueMethod = byRef(&doFee), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "fetch_info", .valueMethod = byRef(&doFetchInfo), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "gateway_balances", .valueMethod = byRef(&doGatewayBalances), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "get_counts", .valueMethod = byRef(&doGetCounts), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "get_aggregate_price", .valueMethod = byRef(&doGetAggregatePrice), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "ledger_accept", .valueMethod = byRef(&doLedgerAccept), .role = Role::ADMIN, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "ledger_cleaner", .valueMethod = byRef(&doLedgerCleaner), .role = Role::ADMIN, - .condition = Condition::NeedsNetworkConnection}, + .condition = NeedsNetworkConnection}, {.name = "ledger_closed", .valueMethod = byRef(&doLedgerClosed), .role = Role::USER, - .condition = Condition::NeedsClosedLedger}, + .condition = NeedsClosedLedger}, {.name = "ledger_current", .valueMethod = byRef(&doLedgerCurrent), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "ledger_data", .valueMethod = byRef(&doLedgerData), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "ledger_entry", .valueMethod = byRef(&doLedgerEntry), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "ledger_header", .valueMethod = byRef(&doLedgerHeader), .role = Role::USER, - .condition = Condition::NoCondition, + .condition = NoCondition, .minApiVer = 1, .maxApiVer = 1}, {.name = "ledger_request", .valueMethod = byRef(&doLedgerRequest), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "log_level", .valueMethod = byRef(&doLogLevel), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "logrotate", .valueMethod = byRef(&doLogRotate), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "manifest", .valueMethod = byRef(&doManifest), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "nft_buy_offers", .valueMethod = byRef(&doNFTBuyOffers), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "nft_sell_offers", .valueMethod = byRef(&doNFTSellOffers), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "noripple_check", .valueMethod = byRef(&doNoRippleCheck), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "owner_info", .valueMethod = byRef(&doOwnerInfo), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "peers", .valueMethod = byRef(&doPeers), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "path_find", .valueMethod = byRef(&doPathFind), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, - {.name = "ping", - .valueMethod = byRef(&doPing), - .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NeedsCurrentLedger}, + {.name = "ping", .valueMethod = byRef(&doPing), .role = Role::USER, .condition = NoCondition}, {.name = "print", .valueMethod = byRef(&doPrint), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, // { "profile", byRef (&doProfile), Role::USER, // NEEDS_CURRENT_LEDGER }, {.name = "random", .valueMethod = byRef(&doRandom), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "peer_reservations_add", .valueMethod = byRef(&doPeerReservationsAdd), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "peer_reservations_del", .valueMethod = byRef(&doPeerReservationsDel), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "peer_reservations_list", .valueMethod = byRef(&doPeerReservationsList), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "ripple_path_find", .valueMethod = byRef(&doRipplePathFind), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "server_definitions", .valueMethod = byRef(&doServerDefinitions), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "server_info", .valueMethod = byRef(&doServerInfo), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "server_state", .valueMethod = byRef(&doServerState), .role = Role::USER, - .condition = Condition::NoCondition}, - {.name = "sign", - .valueMethod = byRef(&doSign), - .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, + {.name = "sign", .valueMethod = byRef(&doSign), .role = Role::USER, .condition = NoCondition}, {.name = "sign_for", .valueMethod = byRef(&doSignFor), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "simulate", .valueMethod = byRef(&doSimulate), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, - {.name = "stop", - .valueMethod = byRef(&doStop), - .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NeedsCurrentLedger}, + {.name = "stop", .valueMethod = byRef(&doStop), .role = Role::ADMIN, .condition = NoCondition}, {.name = "submit", .valueMethod = byRef(&doSubmit), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "submit_multisigned", .valueMethod = byRef(&doSubmitMultiSigned), .role = Role::USER, - .condition = Condition::NeedsCurrentLedger}, + .condition = NeedsCurrentLedger}, {.name = "transaction_entry", .valueMethod = byRef(&doTransactionEntry), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "tx", .valueMethod = byRef(&doTxJson), .role = Role::USER, - .condition = Condition::NeedsNetworkConnection}, + .condition = NeedsNetworkConnection}, {.name = "tx_history", .valueMethod = byRef(&doTxHistory), .role = Role::USER, - .condition = Condition::NoCondition, + .condition = NoCondition, .minApiVer = 1, .maxApiVer = 1}, {.name = "tx_reduce_relay", .valueMethod = byRef(&doTxReduceRelay), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "unl_list", .valueMethod = byRef(&doUnlList), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "validation_create", .valueMethod = byRef(&doValidationCreate), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "validators", .valueMethod = byRef(&doValidators), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "validator_list_sites", .valueMethod = byRef(&doValidatorListSites), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "validator_info", .valueMethod = byRef(&doValidatorInfo), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "vault_info", .valueMethod = byRef(&doVaultInfo), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "wallet_propose", .valueMethod = byRef(&doWalletPropose), .role = Role::ADMIN, - .condition = Condition::NoCondition}, + .condition = NoCondition}, // Event methods {.name = "subscribe", .valueMethod = byRef(&doSubscribe), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, {.name = "unsubscribe", .valueMethod = byRef(&doUnsubscribe), .role = Role::USER, - .condition = Condition::NoCondition}, + .condition = NoCondition}, }; class HandlerTable @@ -382,7 +373,7 @@ private: { XRPL_ASSERT(minVer <= maxVer, "xrpl::RPC::HandlerTable : valid API version range"); XRPL_ASSERT( - maxVer <= RPC::kApiMaximumValidVersion, + maxVer <= RPC::kAPI_MAXIMUM_VALID_VERSION, "xrpl::RPC::HandlerTable : valid max API version"); return std::any_of( @@ -418,15 +409,15 @@ public: static HandlerTable const& instance() { - static HandlerTable const kHandlerTable(kHandlerArray); - return kHandlerTable; + static HandlerTable const kHANDLER_TABLE(kHANDLER_ARRAY); + return kHANDLER_TABLE; } [[nodiscard]] Handler const* getHandler(unsigned version, bool betaEnabled, std::string const& name) const { - if (version < RPC::kApiMinimumSupportedVersion || - version > (betaEnabled ? RPC::kApiBetaVersion : RPC::kApiMaximumSupportedVersion)) + if (version < RPC::kAPI_MINIMUM_SUPPORTED_VERSION || + version > (betaEnabled ? RPC::kAPI_BETA_VERSION : RPC::kAPI_MAXIMUM_SUPPORTED_VERSION)) return nullptr; auto const range = table_.equal_range(name); @@ -455,8 +446,8 @@ private: addHandler() { static_assert(HandlerImpl::minApiVer <= HandlerImpl::maxApiVer); - static_assert(HandlerImpl::maxApiVer <= RPC::kApiMaximumValidVersion); - static_assert(RPC::kApiMinimumSupportedVersion <= HandlerImpl::minApiVer); + static_assert(HandlerImpl::maxApiVer <= RPC::kAPI_MAXIMUM_VALID_VERSION); + static_assert(RPC::kAPI_MINIMUM_SUPPORTED_VERSION <= HandlerImpl::minApiVer); if (overlappingApiVersion( table_.equal_range(HandlerImpl::name), diff --git a/src/xrpld/rpc/detail/Handler.h b/src/xrpld/rpc/detail/Handler.h index 140f421ed3..1e1db7bb99 100644 --- a/src/xrpld/rpc/detail/Handler.h +++ b/src/xrpld/rpc/detail/Handler.h @@ -15,7 +15,9 @@ class Object; namespace xrpl::RPC { // Under what condition can we call this RPC? -enum class Condition { +// Bitwise flags +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) +enum Condition { NoCondition = 0, NeedsNetworkConnection = 1, NeedsCurrentLedger = 1 << 1, @@ -32,19 +34,19 @@ struct Handler Role role; RPC::Condition condition; - unsigned minApiVer = kApiMinimumSupportedVersion; - unsigned maxApiVer = kApiMaximumValidVersion; + unsigned minApiVer = kAPI_MINIMUM_SUPPORTED_VERSION; + unsigned maxApiVer = kAPI_MAXIMUM_VALID_VERSION; }; Handler const* getHandler(unsigned int version, bool betaEnabled, std::string const&); -/** Return a json::ValueType::Object with a single entry. */ +/** Return a json::objectValue with a single entry. */ template json::Value makeObjectValue(Value const& value, json::StaticString const& field = jss::message) { - json::Value result(json::ValueType::Object); + json::Value result(json::ObjectValue); result[field] = value; return result; } @@ -57,17 +59,17 @@ template ErrorCodeI conditionMet(Condition conditionRequired, T& context) { - if (context.app.getOPs().isAmendmentBlocked() && (conditionRequired != Condition::NoCondition)) + if (context.app.getOPs().isAmendmentBlocked() && (conditionRequired != NoCondition)) { return RpcAmendmentBlocked; } - if (context.app.getOPs().isUNLBlocked() && (conditionRequired != Condition::NoCondition)) + if (context.app.getOPs().isUNLBlocked() && (conditionRequired != NoCondition)) { return RpcExpiredValidatorList; } - if ((conditionRequired != Condition::NoCondition) && + if ((conditionRequired != NoCondition) && (context.netOps.getOperatingMode() < OperatingMode::SYNCING)) { JLOG(context.j.info()) << "Insufficient network mode for RPC: " @@ -78,9 +80,9 @@ conditionMet(Condition conditionRequired, T& context) return RpcNotSynced; } - if (!context.app.config().standalone() && conditionRequired != Condition::NoCondition) + if (!context.app.config().standalone() && conditionRequired != NoCondition) { - if (context.ledgerMaster.getValidatedLedgerAge() > Tuning::kMaxValidatedLedgerAge) + if (context.ledgerMaster.getValidatedLedgerAge() > Tuning::kMAX_VALIDATED_LEDGER_AGE) { if (context.apiVersion == 1) return RpcNoCurrent; @@ -100,7 +102,7 @@ conditionMet(Condition conditionRequired, T& context) } } - if ((conditionRequired != Condition::NoCondition) && !context.ledgerMaster.getClosedLedger()) + if ((conditionRequired != NoCondition) && !context.ledgerMaster.getClosedLedger()) { if (context.apiVersion == 1) return RpcNoClosed; diff --git a/src/xrpld/rpc/detail/LegacyPathFind.cpp b/src/xrpld/rpc/detail/LegacyPathFind.cpp index 0bfa19a1f4..83c7c30549 100644 --- a/src/xrpld/rpc/detail/LegacyPathFind.cpp +++ b/src/xrpld/rpc/detail/LegacyPathFind.cpp @@ -21,13 +21,13 @@ LegacyPathFind::LegacyPathFind(bool isAdmin, Application& app) } auto const& jobCount = app.getJobQueue().getJobCountGE(JtClient); - if (jobCount > Tuning::kMaxPathfindJobCount || app.getFeeTrack().isLoadedLocal()) + if (jobCount > Tuning::kMAX_PATHFIND_JOB_COUNT || app.getFeeTrack().isLoadedLocal()) return; while (true) { int prevVal = inProgress.load(); - if (prevVal >= Tuning::kMaxPathfindsInProgress) + if (prevVal >= Tuning::kMAX_PATHFINDS_IN_PROGRESS) return; if (inProgress.compare_exchange_strong( diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index 06507319f7..46069ce3bb 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -59,7 +59,7 @@ PathRequest::PathRequest( , owner_(owner) , wpSubscriber_(subscriber) , consumer_(subscriber->getConsumer()) - , jvStatus_(json::ValueType::Object) + , jvStatus_(json::ObjectValue) , lastIndex_(0) , inProgress_(false) , iLevel_(0) @@ -82,7 +82,7 @@ PathRequest::PathRequest( , owner_(owner) , fCompletion_(completion) , consumer_(consumer) - , jvStatus_(json::ValueType::Object) + , jvStatus_(json::ObjectValue) , lastIndex_(0) , inProgress_(false) , iLevel_(0) @@ -101,16 +101,16 @@ PathRequest::~PathRequest() return; std::string fast, full; - if (quickReply_ != steady_clock::time_point{}) + if (quick_reply_ != steady_clock::time_point{}) { fast = " fast:"; - fast += std::to_string(duration_cast(quickReply_ - created_).count()); + fast += std::to_string(duration_cast(quick_reply_ - created_).count()); fast += "ms"; } - if (fullReply_ != steady_clock::time_point{}) + if (full_reply_ != steady_clock::time_point{}) { full = " full:"; - full += std::to_string(duration_cast(fullReply_ - created_).count()); + full += std::to_string(duration_cast(full_reply_ - created_).count()); full += "ms"; } stream << iIdentifier_ << " complete:" << fast << full @@ -180,7 +180,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) if (!raSrcAccount_ || !raDstAccount_) return false; - if (!convertAll_ && (saSendMax_ || saDstAmount_ <= beast::kZero)) + if (!convert_all_ && (saSendMax_ || saDstAmount_ <= beast::kZERO)) { // If send max specified, dst amt must be -1. jvStatus_ = rpcError(RpcDstAmtMalformed); @@ -198,7 +198,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) auto const sleDest = lrLedger->read(keylet::account(*raDstAccount_)); - json::Value& jvDestCur = (jvStatus_[jss::destination_currencies] = json::ValueType::Array); + json::Value& jvDestCur = (jvStatus_[jss::destination_currencies] = json::ArrayValue); if (!sleDest) { @@ -210,7 +210,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) return false; } - if (!convertAll_ && saDstAmount_ < STAmount(lrLedger->fees().reserve)) + if (!convert_all_ && saDstAmount_ < STAmount(lrLedger->fees().reserve)) { // Payment must meet reserve. jvStatus_ = rpcError(RpcDstAmtMalformed); @@ -219,7 +219,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) } else { - bool const disallowXRP(sleDest->isFlag(lsfDisallowXRP)); + bool const disallowXRP((sleDest->getFlags() & lsfDisallowXRP) != 0u); auto const destAssets = accountDestAssets(*raDstAccount_, crCache, !disallowXRP); @@ -312,9 +312,9 @@ PathRequest::parseJson(json::Value const& jvParams) return PFR_PJ_INVALID; } - convertAll_ = saDstAmount_ == STAmount(saDstAmount_.asset(), 1u, 0, true); + convert_all_ = saDstAmount_ == STAmount(saDstAmount_.asset(), 1u, 0, true); - if (!validAsset(saDstAmount_.asset()) || (!convertAll_ && saDstAmount_ <= beast::kZero)) + if (!validAsset(saDstAmount_.asset()) || (!convert_all_ && saDstAmount_ <= beast::kZERO)) { jvStatus_ = rpcError(RpcDstAmtMalformed); return PFR_PJ_INVALID; @@ -323,7 +323,7 @@ PathRequest::parseJson(json::Value const& jvParams) if (jvParams.isMember(jss::send_max)) { // Send_max requires destination amount to be -1. - if (!convertAll_) + if (!convert_all_) { jvStatus_ = rpcError(RpcDstAmtMalformed); return PFR_PJ_INVALID; @@ -332,7 +332,7 @@ PathRequest::parseJson(json::Value const& jvParams) saSendMax_.emplace(); if (!amountFromJsonNoThrow(*saSendMax_, jvParams[jss::send_max]) || !validAsset(saSendMax_->asset()) || - (*saSendMax_ <= beast::kZero && + (*saSendMax_ <= beast::kZERO && *saSendMax_ != STAmount(saSendMax_->asset(), 1u, 0, true))) { jvStatus_ = rpcError(RpcSendmaxMalformed); @@ -344,7 +344,7 @@ PathRequest::parseJson(json::Value const& jvParams) { json::Value const& jvSrcCurrencies = jvParams[jss::source_currencies]; if (!jvSrcCurrencies.isArray() || jvSrcCurrencies.size() == 0 || - jvSrcCurrencies.size() > RPC::Tuning::kMaxSrcCur) + jvSrcCurrencies.size() > RPC::Tuning::kMAX_SRC_CUR) { jvStatus_ = rpcError(RpcSrcCurMalformed); return PFR_PJ_INVALID; @@ -523,7 +523,7 @@ PathRequest::getPathFinder( // NOLINTEND(bugprone-unchecked-optional-access) if (pathfinder->findPaths(level, continueCallback)) { - pathfinder->computePathRanks(kMaxPaths, continueCallback); + pathfinder->computePathRanks(kMAX_PATHS, continueCallback); } else { @@ -556,7 +556,7 @@ PathRequest::findPaths( [&](TAsset const& a) { if (!sameAccount || a != saDstAmount_.asset()) { - if (sourceAssets.size() >= RPC::Tuning::kMaxAutoSrcCur) + if (sourceAssets.size() >= RPC::Tuning::kMAX_AUTO_SRC_CUR) return false; if constexpr (std::is_same_v) { @@ -577,7 +577,7 @@ PathRequest::findPaths( } } - auto const dstAmount = convertAmount(saDstAmount_, convertAll_); + auto const dstAmount = convertAmount(saDstAmount_, convert_all_); hash_map> currencyMap; for (auto const& asset : sourceAssets) { @@ -596,7 +596,7 @@ PathRequest::findPaths( STPath fullLiquidityPath; auto ps = pathfinder->getBestPaths( - kMaxPaths, fullLiquidityPath, context_[asset], asset.getIssuer(), continueCallback); + kMAX_PATHS, fullLiquidityPath, context_[asset], asset.getIssuer(), continueCallback); context_[asset] = ps; auto const& sourceAccount = [&] { @@ -622,7 +622,7 @@ PathRequest::findPaths( JLOG(journal_.debug()) << iIdentifier_ << " Paths found, calling rippleCalc"; path::RippleCalc::Input rcInput; - if (convertAll_) + if (convert_all_) rcInput.partialPaymentAllowed = true; auto sandbox = std::make_unique(&*cache->getLedger(), TapNone); auto rc = path::RippleCalc::rippleCalculate( @@ -639,7 +639,7 @@ PathRequest::findPaths( app_, &rcInput); - if (!convertAll_ && !fullLiquidityPath.empty() && + if (!convert_all_ && !fullLiquidityPath.empty() && (rc.result() == terNO_LINE || rc.result() == tecPATH_PARTIAL)) { JLOG(journal_.debug()) << iIdentifier_ << " Trying with an extra path element"; @@ -673,22 +673,19 @@ PathRequest::findPaths( if (rc.result() == tesSUCCESS) { - json::Value jvEntry(json::ValueType::Object); + json::Value jvEntry(json::ObjectValue); if (rc.actualAmountIn.holds()) rc.actualAmountIn.get().account = sourceAccount; - jvEntry[jss::source_amount] = rc.actualAmountIn.getJson(JsonOptions::Values::None); - jvEntry[jss::paths_computed] = ps.getJson(JsonOptions::Values::None); + jvEntry[jss::source_amount] = rc.actualAmountIn.getJson(JsonOptions::KNone); + jvEntry[jss::paths_computed] = ps.getJson(JsonOptions::KNone); - if (convertAll_) - { - jvEntry[jss::destination_amount] = - rc.actualAmountOut.getJson(JsonOptions::Values::None); - } + if (convert_all_) + jvEntry[jss::destination_amount] = rc.actualAmountOut.getJson(JsonOptions::KNone); if (hasCompletion()) { // Old ripple_path_find API requires this - jvEntry[jss::paths_canonical] = json::ValueType::Array; + jvEntry[jss::paths_canonical] = json::ArrayValue; } jvArray.append(jvEntry); @@ -725,12 +722,12 @@ PathRequest::doUpdate( return jvStatus_; } - json::Value newStatus = json::ValueType::Object; + json::Value newStatus = json::ObjectValue; if (hasCompletion()) { // Old ripple_path_find API gives destination_currencies - auto& destAssets = (newStatus[jss::destination_currencies] = json::ValueType::Array); + auto& destAssets = (newStatus[jss::destination_currencies] = json::ArrayValue); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) isValid() ensures both are set auto const assets = accountDestAssets(*raDstAccount_, cache, true); for (auto const& asset : assets) @@ -741,7 +738,7 @@ PathRequest::doUpdate( newStatus[jss::source_account] = toBase58(*raSrcAccount_); newStatus[jss::destination_account] = toBase58(*raDstAccount_); // NOLINTEND(bugprone-unchecked-optional-access) - newStatus[jss::destination_amount] = saDstAmount_.getJson(JsonOptions::Values::None); + newStatus[jss::destination_amount] = saDstAmount_.getJson(JsonOptions::KNone); newStatus[jss::full_reply] = !fast; if (jvId_) @@ -754,39 +751,39 @@ PathRequest::doUpdate( // first pass if (loaded || fast) { - iLevel_ = app_.config().pathSearchFast; + iLevel_ = app_.config().PATH_SEARCH_FAST; } else { - iLevel_ = app_.config().pathSearch; + iLevel_ = app_.config().PATH_SEARCH; } } - else if ((iLevel_ == app_.config().pathSearchFast) && !fast) + else if ((iLevel_ == app_.config().PATH_SEARCH_FAST) && !fast) { // leaving fast pathfinding - iLevel_ = app_.config().pathSearch; - if (loaded && (iLevel_ > app_.config().pathSearchFast)) + iLevel_ = app_.config().PATH_SEARCH; + if (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST)) --iLevel_; } else if (bLastSuccess_) { // decrement, if possible - if (iLevel_ > app_.config().pathSearch || - (loaded && (iLevel_ > app_.config().pathSearchFast))) + if (iLevel_ > app_.config().PATH_SEARCH || + (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST))) --iLevel_; } else { // adjust as needed - if (!loaded && (iLevel_ < app_.config().pathSearchMax)) + if (!loaded && (iLevel_ < app_.config().PATH_SEARCH_MAX)) ++iLevel_; - if (loaded && (iLevel_ > app_.config().pathSearchFast)) + if (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST)) --iLevel_; } JLOG(journal_.debug()) << iIdentifier_ << " processing at level " << iLevel_; - json::Value jvArray = json::ValueType::Array; + json::Value jvArray = json::ArrayValue; if (findPaths(cache, iLevel_, jvArray, continueCallback)) { bLastSuccess_ = jvArray.size() != 0; @@ -798,15 +795,15 @@ PathRequest::doUpdate( newStatus = rpcError(RpcInternal); } - if (fast && quickReply_ == steady_clock::time_point{}) + if (fast && quick_reply_ == steady_clock::time_point{}) { - quickReply_ = steady_clock::now(); - owner_.reportFast(duration_cast(quickReply_ - created_)); + quick_reply_ = steady_clock::now(); + owner_.reportFast(duration_cast(quick_reply_ - created_)); } - else if (!fast && fullReply_ == steady_clock::time_point{}) + else if (!fast && full_reply_ == steady_clock::time_point{}) { - fullReply_ = steady_clock::now(); - owner_.reportFull(duration_cast(fullReply_ - created_)); + full_reply_ = steady_clock::now(); + owner_.reportFull(duration_cast(full_reply_ - created_)); } { diff --git a/src/xrpld/rpc/detail/PathRequest.h b/src/xrpld/rpc/detail/PathRequest.h index de8c10de0e..b74d4c6ade 100644 --- a/src/xrpld/rpc/detail/PathRequest.h +++ b/src/xrpld/rpc/detail/PathRequest.h @@ -140,7 +140,7 @@ private: std::optional domain_; - bool convertAll_{}; + bool convert_all_{}; std::recursive_mutex indexLock_; LedgerIndex lastIndex_; @@ -152,10 +152,10 @@ private: int const iIdentifier_; std::chrono::steady_clock::time_point const created_; - std::chrono::steady_clock::time_point quickReply_; - std::chrono::steady_clock::time_point fullReply_; + std::chrono::steady_clock::time_point quick_reply_; + std::chrono::steady_clock::time_point full_reply_; - static unsigned int const kMaxPaths = 4; + static unsigned int const kMAX_PATHS = 4; }; } // namespace xrpl diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index daa50cfb07..9a34cf44f1 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -94,14 +94,14 @@ namespace { // This is an arbitrary cutoff, and it might cause us to miss other // good paths with this arbitrary cut off. -constexpr std::size_t kPathfinderMaxCompletePaths = 1000; +constexpr std::size_t kPATHFINDER_MAX_COMPLETE_PATHS = 1000; struct AccountCandidate { int priority; AccountID account; - static int const kHighPriority = 10000; + static int const kHIGH_PRIORITY = 10000; }; bool @@ -226,7 +226,7 @@ Pathfinder::Pathfinder( , srcPathAsset_(uSrcPathAsset) , srcIssuer_(uSrcIssuer) , srcAmount_(amountFromPathAsset(uSrcPathAsset, uSrcIssuer, uSrcAccount)) - , convertAll_(convertAllCheck(dstAmount_)) + , convert_all_(convertAllCheck(dstAmount_)) , domain_(domain) , ledger_(cache->getLedger()) , rLCache_(cache) @@ -242,7 +242,7 @@ bool Pathfinder::findPaths(int searchLevel, std::function const& continueCallback) { JLOG(j_.trace()) << "findPaths start"; - if (dstAmount_ == beast::kZero) + if (dstAmount_ == beast::kZERO) { // No need to send zero money. JLOG(j_.debug()) << "Destination amount was zero."; @@ -367,7 +367,7 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue JLOG(j_.trace()) << "findPaths trying payment type " << paymentType; addPathsForType(costedPath.type, continueCallback); - if (completePaths_.size() > kPathfinderMaxCompletePaths) + if (completePaths_.size() > kPATHFINDER_MAX_COMPLETE_PATHS) break; } } @@ -398,7 +398,7 @@ Pathfinder::getPathLiquidity( try { // Compute a path that provides at least the minimum liquidity. - if (convertAll_) + if (convert_all_) rcInput.partialPaymentAllowed = true; auto rc = path::RippleCalc::rippleCalculate( @@ -418,7 +418,7 @@ Pathfinder::getPathLiquidity( qualityOut = getRate(rc.actualAmountOut, rc.actualAmountIn); amountOut = rc.actualAmountOut; - if (!convertAll_) + if (!convert_all_) { // Now try to compute the remaining liquidity. rcInput.partialPaymentAllowed = true; @@ -443,7 +443,7 @@ Pathfinder::getPathLiquidity( catch (std::exception const& e) { JLOG(j_.info()) << "checkpath: exception (" << e.what() << ") " - << path.getJson(JsonOptions::Values::None); + << path.getJson(JsonOptions::KNone); return tefEXCEPTION; } } @@ -451,7 +451,7 @@ Pathfinder::getPathLiquidity( void Pathfinder::computePathRanks(int maxPaths, std::function const& continueCallback) { - remainingAmount_ = convertAmount(dstAmount_, convertAll_); + remainingAmount_ = convertAmount(dstAmount_, convert_all_); // Must subtract liquidity in default path from remaining amount. try @@ -536,7 +536,7 @@ Pathfinder::rankPaths( rankedPaths.reserve(paths.size()); auto const saMinDstAmount = [&]() -> STAmount { - if (!convertAll_) + if (!convert_all_) { // Ignore paths that move only very small amounts. return smallestUsefulAmount(dstAmount_, maxPaths); @@ -561,12 +561,12 @@ Pathfinder::rankPaths( if (!isTesSuccess(resultCode)) { JLOG(j_.debug()) << "findPaths: dropping : " << transToken(resultCode) << ": " - << currentPath.getJson(JsonOptions::Values::None); + << currentPath.getJson(JsonOptions::KNone); } else { JLOG(j_.debug()) << "findPaths: quality: " << uQuality << ": " - << currentPath.getJson(JsonOptions::Values::None); + << currentPath.getJson(JsonOptions::KNone); rankedPaths.push_back({uQuality, currentPath.size(), liquidity, i}); } @@ -581,7 +581,7 @@ Pathfinder::rankPaths( std::ranges::sort( rankedPaths, [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { // 1) Higher quality (lower cost) is better - if (!convertAll_ && a.quality != b.quality) + if (!convert_all_ && a.quality != b.quality) return a.quality < b.quality; // 2) More liquidity (higher volume) is better @@ -713,16 +713,15 @@ Pathfinder::getBestPaths( // We found an extra path that can move the whole amount. fullLiquidityPath = (startsWithIssuer ? removeIssuer(path) : path); JLOG(j_.debug()) << "Found extra full path: " - << fullLiquidityPath.getJson(JsonOptions::Values::None); + << fullLiquidityPath.getJson(JsonOptions::KNone); } else { - JLOG(j_.debug()) << "Skipping a non-filling path: " - << path.getJson(JsonOptions::Values::None); + JLOG(j_.debug()) << "Skipping a non-filling path: " << path.getJson(JsonOptions::KNone); } } - if (remaining > beast::kZero) + if (remaining > beast::kZERO) { XRPL_ASSERT( fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : second empty path result"); @@ -730,7 +729,7 @@ Pathfinder::getBestPaths( } else { - JLOG(j_.debug()) << "findPaths: RESULTS: " << bestPaths.getJson(JsonOptions::Values::None); + JLOG(j_.debug()) << "findPaths: RESULTS: " << bestPaths.getJson(JsonOptions::KNone); } return bestPaths; } @@ -795,7 +794,7 @@ Pathfinder::getPathsOut( { } else if ( - rspEntry.getBalance() <= beast::kZero && + rspEntry.getBalance() <= beast::kZERO && (!rspEntry.getLimitPeer() || -rspEntry.getBalance() >= rspEntry.getLimitPeer() || (bAuthRequired && !rspEntry.getAuth()))) @@ -910,26 +909,26 @@ Pathfinder::addPathsForType( break; case NodeType::Accounts: - addLinks(parentPaths, pathsOut, kAfAddAccounts, continueCallback); + addLinks(parentPaths, pathsOut, kAF_ADD_ACCOUNTS, continueCallback); break; case NodeType::Books: - addLinks(parentPaths, pathsOut, kAfAddBooks, continueCallback); + addLinks(parentPaths, pathsOut, kAF_ADD_BOOKS, continueCallback); break; case NodeType::XrpBook: - addLinks(parentPaths, pathsOut, kAfAddBooks | kAfObXrp, continueCallback); + addLinks(parentPaths, pathsOut, kAF_ADD_BOOKS | kAF_OB_XRP, continueCallback); break; case NodeType::DestBook: - addLinks(parentPaths, pathsOut, kAfAddBooks | kAfObLast, continueCallback); + addLinks(parentPaths, pathsOut, kAF_ADD_BOOKS | kAF_OB_LAST, continueCallback); break; case NodeType::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, kAfAddAccounts | kAfAcLast, continueCallback); + addLinks(parentPaths, pathsOut, kAF_ADD_ACCOUNTS | kAF_AC_LAST, continueCallback); break; } @@ -952,7 +951,7 @@ Pathfinder::isNoRipple( auto const flag((toAccount > fromAccount) ? lsfHighNoRipple : lsfLowNoRipple); - return sleRipple && sleRipple->isFlag(flag); + return sleRipple && ((sleRipple->getFieldU32(sfFlags) & flag) != 0u); } // Does this path end on an account-to-account link whose last account has @@ -1011,9 +1010,9 @@ Pathfinder::addLink( JLOG(j_.trace()) << "addLink< flags=" << addFlags << " onXRP=" << bOnXRP << " completePaths size=" << completePaths_.size(); - JLOG(j_.trace()) << currentPath.getJson(JsonOptions::Values::None); + JLOG(j_.trace()) << currentPath.getJson(JsonOptions::KNone); - if ((addFlags & kAfAddAccounts) != 0u) + if ((addFlags & kAF_ADD_ACCOUNTS) != 0u) { // add accounts if (bOnXRP) @@ -1021,7 +1020,7 @@ Pathfinder::addLink( if (dstAmount_.native() && !currentPath.empty()) { // non-default path to XRP destination JLOG(j_.trace()) << "complete path found ax: " - << currentPath.getJson(JsonOptions::Values::None); + << currentPath.getJson(JsonOptions::KNone); addUniquePath(completePaths_, currentPath); } } @@ -1032,19 +1031,19 @@ Pathfinder::addLink( if (sleEnd) { - bool const bRequireAuth(sleEnd->isFlag(lsfRequireAuth)); + bool const bRequireAuth((sleEnd->getFieldU32(sfFlags) & lsfRequireAuth) != 0u); bool const bIsEndAsset(uEndPathAsset == dstAmount_.asset()); bool const bIsNoRippleOut(isNoRippleOut(currentPath)); - bool const bDestOnly((addFlags & kAfAcLast) != 0u); + bool const bDestOnly((addFlags & kAF_AC_LAST) != 0u); AccountCandidates candidates; auto forAssets = [&](AssetType const& assets) { candidates.reserve(assets.size()); - static constexpr bool kIsLine = + static bool constexpr kIS_LINE = std::is_same_v>; - static constexpr bool kIsMpt = + static bool constexpr kIS_MPT = std::is_same_v>; for (auto const& asset : assets) @@ -1052,14 +1051,14 @@ Pathfinder::addLink( if (continueCallback && !continueCallback()) return; auto const& acct = [&]() constexpr { - if constexpr (kIsLine) + if constexpr (kIS_LINE) return asset.getAccountIDPeer(); // Unlike trustline, MPT is not bidirectional - if constexpr (kIsMpt) + if constexpr (kIS_MPT) return getMPTIssuer(asset); }(); auto const direction = [&]() constexpr -> LineDirection { - if constexpr (kIsLine) + if constexpr (kIS_LINE) return asset.getDirectionPeer(); // incoming for MPT since MPT doesn't support // rippling (see LineDirection comments) @@ -1080,27 +1079,27 @@ Pathfinder::addLink( } auto const correctAsset = [&]() { - if constexpr (kIsLine) + if constexpr (kIS_LINE) { return uEndPathAsset.get() == asset.getLimit().template get().currency; } - if constexpr (kIsMpt) + if constexpr (kIS_MPT) { return uEndPathAsset.get() == asset.getMptID(); } }(); auto checkAsset = [&]() { - if constexpr (kIsLine) + if constexpr (kIS_LINE) { return ( - (asset.getBalance() <= beast::kZero && + (asset.getBalance() <= beast::kZERO && (!asset.getLimitPeer() || -asset.getBalance() >= asset.getLimitPeer() || (bRequireAuth && !asset.getAuth()))) || (bIsNoRippleOut && asset.getNoRipple())); } - if constexpr (kIsMpt) + if constexpr (kIS_MPT) { return asset.isZeroBalance() || asset.isMaxedOut() || requireAuth(*ledger_, MPTIssue{asset}, acct); @@ -1123,16 +1122,15 @@ Pathfinder::addLink( // this is a complete path if (!currentPath.empty()) { - JLOG(j_.trace()) - << "complete path found ae: " - << currentPath.getJson(JsonOptions::Values::None); + JLOG(j_.trace()) << "complete path found ae: " + << currentPath.getJson(JsonOptions::KNone); addUniquePath(completePaths_, currentPath); } } else if (!bDestOnly) { // this is a high-priority candidate - candidates.push_back({AccountCandidate::kHighPriority, acct}); + candidates.push_back({AccountCandidate::kHIGH_PRIORITY, acct}); } } else if (acct == srcAccount_) @@ -1212,10 +1210,10 @@ Pathfinder::addLink( } } } - if ((addFlags & kAfAddBooks) != 0u) + if ((addFlags & kAF_ADD_BOOKS) != 0u) { // add order books - if ((addFlags & kAfObXrp) != 0u) + if ((addFlags & kAF_OB_XRP) != 0u) { // to XRP only if (!bOnXRP && @@ -1229,7 +1227,7 @@ Pathfinder::addLink( } else { - bool const bDestOnly = (addFlags & kAfObLast) != 0; + bool const bDestOnly = (addFlags & kAF_OB_LAST) != 0; auto books = app_.getOrderBookDB().getBooksByTakerPays( assetFromPathAsset(uEndPathAsset, uEndIssuer), domain_); JLOG(j_.trace()) << books.size() << " books found from this currency/issuer"; @@ -1256,7 +1254,7 @@ Pathfinder::addLink( // destination is XRP, add account and path is // complete JLOG(j_.trace()) << "complete path found bx: " - << currentPath.getJson(JsonOptions::Values::None); + << currentPath.getJson(JsonOptions::KNone); addUniquePath(completePaths_, newPath); } else @@ -1302,7 +1300,7 @@ Pathfinder::addLink( { // with the destination account, this path is // complete JLOG(j_.trace()) << "complete path found ba: " - << currentPath.getJson(JsonOptions::Values::None); + << currentPath.getJson(JsonOptions::KNone); addUniquePath(completePaths_, newPath); } else diff --git a/src/xrpld/rpc/detail/Pathfinder.h b/src/xrpld/rpc/detail/Pathfinder.h index 36caab308e..ba1fc453b3 100644 --- a/src/xrpld/rpc/detail/Pathfinder.h +++ b/src/xrpld/rpc/detail/Pathfinder.h @@ -178,7 +178,7 @@ private: /** The amount remaining from srcAccount_ after the default liquidity has been removed. */ STAmount remainingAmount_; - bool convertAll_; + bool convert_all_; std::optional domain_; std::shared_ptr ledger_; @@ -196,19 +196,19 @@ private: beast::Journal const j_; // Add ripple paths - static std::uint32_t const kAfAddAccounts = 0x001; + static std::uint32_t const kAF_ADD_ACCOUNTS = 0x001; // Add order books - static std::uint32_t const kAfAddBooks = 0x002; + static std::uint32_t const kAF_ADD_BOOKS = 0x002; // Add order book to XRP only - static std::uint32_t const kAfObXrp = 0x010; + static std::uint32_t const kAF_OB_XRP = 0x010; // Must link to destination currency - static std::uint32_t const kAfObLast = 0x040; + static std::uint32_t const kAF_OB_LAST = 0x040; // Destination account only - static std::uint32_t const kAfAcLast = 0x080; + static std::uint32_t const kAF_AC_LAST = 0x080; }; } // namespace xrpl diff --git a/src/xrpld/rpc/detail/PathfinderUtils.h b/src/xrpld/rpc/detail/PathfinderUtils.h index a703127148..ff47de3217 100644 --- a/src/xrpld/rpc/detail/PathfinderUtils.h +++ b/src/xrpld/rpc/detail/PathfinderUtils.h @@ -10,10 +10,10 @@ largestAmount(STAmount const& amt) return amt.asset().visit( [&](Issue const& issue) -> STAmount { if (issue.native()) - return kInitialXrp; - return STAmount(amt.asset(), STAmount::kMaxValue, STAmount::kMaxOffset); + return kINITIAL_XRP; + return STAmount(amt.asset(), STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); }, - [&](MPTIssue const&) { return STAmount(amt.asset(), kMaxMpTokenAmount, 0); }); + [&](MPTIssue const&) { return STAmount(amt.asset(), kMAX_MP_TOKEN_AMOUNT, 0); }); } inline STAmount diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index f405ffe4de..98cb7ee9ba 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -128,13 +128,13 @@ private: // optionally followed by a forward slash and some other characters // (the issuer). // https://www.boost.org/doc/libs/1_82_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html - static boost::regex const kReCurIss("\\`([][:alnum:]<>(){}[|?!@#$%^&*]{3})(?:/(.+))?\\'"); + static boost::regex const kRE_CUR_ISS("\\`([][:alnum:]<>(){}[|?!@#$%^&*]{3})(?:/(.+))?\\'"); boost::smatch smMatch; - if (boost::regex_match(strCurrencyIssuer, smMatch, kReCurIss)) + if (boost::regex_match(strCurrencyIssuer, smMatch, kRE_CUR_ISS)) { - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); std::string const strCurrency = smMatch[1]; std::string const strIssuer = smMatch[2]; @@ -176,7 +176,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseAsIs(json::Value const& jvParams) { - json::Value v(json::ValueType::Object); + json::Value v(json::ObjectValue); if (jvParams.isArray() && (jvParams.size() > 0)) v[jss::params] = jvParams; @@ -188,10 +188,10 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseInternal(json::Value const& jvParams) { - json::Value v(json::ValueType::Object); + json::Value v(json::ObjectValue); v[jss::internal_command] = jvParams[0u]; - json::Value params(json::ValueType::Array); + json::Value params(json::ArrayValue); for (unsigned i = 1; i < jvParams.size(); ++i) params.append(jvParams[i]); @@ -207,7 +207,7 @@ private: { if (jvParams.size() == 1) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); std::string const strPk = jvParams[0u].asString(); if (!validPublicKey(strPk, TokenType::NodePublic)) @@ -226,7 +226,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseFetchInfo(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); unsigned int const iParams = jvParams.size(); if (iParams != 0) @@ -241,7 +241,7 @@ private: // NOLINTNEXTLINE(readability-make-member-function-const) parseAccountTransactions(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); unsigned int iParams = jvParams.size(); auto const account = parseBase58(jvParams[0u].asString()); @@ -317,7 +317,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseBookOffers(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); json::Value jvTakerPays = jvParseCurrencyIssuer(jvParams[0u].asString()); json::Value jvTakerGets = jvParseCurrencyIssuer(jvParams[1u].asString()); @@ -384,7 +384,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseCanDelete(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() == 0u) return jvRequest; @@ -407,7 +407,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseConnect(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); std::string ip = jvParams[0u].asString(); if (jvParams.size() == 2) { @@ -436,7 +436,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseDepositAuthorized(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); jvRequest[jss::source_account] = jvParams[0u].asString(); jvRequest[jss::destination_account] = jvParams[1u].asString(); @@ -446,7 +446,7 @@ private: // 8 credentials max if ((jvParams.size() >= 4) && (jvParams.size() <= 11)) { - jvRequest[jss::credentials] = json::Value(json::ValueType::Array); + jvRequest[jss::credentials] = json::Value(json::ArrayValue); for (uint32_t i = 3; i < jvParams.size(); ++i) jvRequest[jss::credentials].append(jvParams[i].asString()); } @@ -467,7 +467,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseFeature(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() > 0) jvRequest[jss::feature] = jvParams[0u].asString(); @@ -501,7 +501,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseGetCounts(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() != 0u) jvRequest[jss::min_count] = jvParams[0u].asUInt(); @@ -524,7 +524,7 @@ private: if (reader.parse(jvParams[2u].asString(), txJSON)) { // sign_for txJSON. - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::account] = jvParams[0u].asString(); jvRequest[jss::secret] = jvParams[1u].asString(); @@ -600,7 +600,7 @@ private: { if (jv.isObject()) { - json::Value jv1{json::ValueType::Object}; + json::Value jv1{json::ObjectValue}; if (jv.isMember(jss::params)) { auto const& params = jv[jss::params]; @@ -614,7 +614,7 @@ private: return jv1; } // else jv.isArray() - json::Value jv1{json::ValueType::Array}; + json::Value jv1{json::ArrayValue}; for (json::UInt j = 0; j < jv.size(); ++j) { if (jv[j].isMember(jss::params)) @@ -645,7 +645,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedger(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() == 0u) { @@ -675,7 +675,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedgerId(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); std::string const strLedger = jvParams[0u].asString(); @@ -696,7 +696,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedgerEntry(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::index] = jvParams[0u].asString(); @@ -714,7 +714,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLogLevel(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() == 1) { @@ -763,7 +763,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseChannelAuthorize(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); unsigned int index = 0; @@ -792,7 +792,7 @@ private: index++; } - if (!jvParams[index].isString() || !toUInt64(jvParams[index].asString())) + if (!jvParams[index].isString() || !toUint64(jvParams[index].asString())) return rpcError(RpcChannelAmtMalformed); jvRequest[jss::amount] = jvParams[index]; @@ -812,7 +812,7 @@ private: if (!validPublicKey(strPk)) return rpcError(RpcPublicMalformed); - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); jvRequest[jss::public_key] = strPk; { @@ -823,7 +823,7 @@ private: } jvRequest[jss::channel_id] = jvParams[1u].asString(); - if (!jvParams[2u].isString() || !toUInt64(jvParams[2u].asString())) + if (!jvParams[2u].isString() || !toUint64(jvParams[2u].asString())) return rpcError(RpcChannelAmtMalformed); jvRequest[jss::amount] = jvParams[2u]; @@ -838,7 +838,7 @@ private: { std::array accFields{{jss::account, acc2Field}}; auto const nParams = jvParams.size(); - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); for (auto i = 0; i < nParams; ++i) { // This was non-const. see comment below @@ -885,7 +885,7 @@ private: return rpcError(RpcActMalformed); // Get info on account. - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); jvRequest[jss::account] = strIdent; @@ -900,11 +900,11 @@ private: parseVault(json::Value const& jvParams) { std::string const strVaultID = jvParams[0u].asString(); - uint256 id = beast::kZero; + uint256 id = beast::kZERO; if (!id.parseHex(strVaultID)) return rpcError(RpcInvalidParams); - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); jvRequest[jss::vault_id] = strVaultID; if (jvParams.size() > 1) @@ -942,7 +942,7 @@ private: parseRipplePathFind(json::Value const& jvParams) { json::Reader reader; - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; bool const bLedger = 2 == jvParams.size(); JLOG(j_.trace()) << "RPC json: " << jvParams[0u]; @@ -970,7 +970,7 @@ private: { json::Value txJSON; json::Reader reader; - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; if (reader.parse(jvParams[0u].asString(), txJSON)) { @@ -1017,7 +1017,7 @@ private: { // Submitting tx_blob - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::tx_blob] = jvParams[0u].asString(); @@ -1026,7 +1026,7 @@ private: if ((jvParams.size() >= 2 || bOffline) && reader.parse(jvParams[1u].asString(), txJSON)) { // Signing or submitting tx_json. - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::secret] = jvParams[0u].asString(); jvRequest[jss::tx_json] = txJSON; @@ -1056,7 +1056,7 @@ private: json::Reader reader; if (reader.parse(jvParams[0u].asString(), txJSON)) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::tx_json] = txJSON; return jvRequest; } @@ -1078,7 +1078,7 @@ private: if (txHash.length() != 64) return rpcError(RpcInvalidParams); - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::tx_hash] = txHash; jvParseLedger(jvRequest, jvParams[1u].asString()); @@ -1096,7 +1096,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseTx(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; if (jvParams.size() == 2 || jvParams.size() == 4) { @@ -1129,7 +1129,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseTxHistory(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; jvRequest[jss::start] = jvParams[0u].asUInt(); @@ -1146,7 +1146,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseValidationCreate(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; if (jvParams.size() != 0u) jvRequest[jss::secret] = jvParams[0u].asString(); @@ -1161,7 +1161,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseWalletPropose(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; if (jvParams.size() != 0u) jvRequest[jss::passphrase] = jvParams[0u].asString(); @@ -1180,7 +1180,7 @@ private: unsigned int index = 0; unsigned int const size = jvParams.size(); - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; std::string param = jvParams[index++].asString(); if (param.empty()) @@ -1207,7 +1207,7 @@ private: if (index < size) { - json::Value& hotWallets = (jvRequest["hotwallet"] = json::ValueType::Array); + json::Value& hotWallets = (jvRequest["hotwallet"] = json::ArrayValue); while (index < size) hotWallets.append(jvParams[index++].asString()); } @@ -1220,7 +1220,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseServerDefinitions(json::Value const& jvParams) { - json::Value jvRequest{json::ValueType::Object}; + json::Value jvRequest{json::ObjectValue}; if (jvParams.size() == 1) { @@ -1235,7 +1235,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseServerInfo(json::Value const& jvParams) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); if (jvParams.size() == 1 && jvParams[0u].asString() == "counters") jvRequest[jss::counters] = true; return jvRequest; @@ -1269,7 +1269,7 @@ public: int maxParams; }; - static constexpr Command kCommands[] = { + static constexpr Command kCOMMANDS[] = { // Request-response methods // - Returns an error, or the request. // - To modify the method, provide a new method in the request. @@ -1483,7 +1483,7 @@ public: auto const count = jvParams.size(); - for (auto const& command : kCommands) + for (auto const& command : kCOMMANDS) { if (strMethod == command.name) { @@ -1585,7 +1585,7 @@ struct RPCCallImp if (!jvReply) Throw("expected reply to have result, error and id properties"); - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); jvResult["result"] = jvReply; @@ -1624,15 +1624,15 @@ rpcCmdToJson( unsigned int apiVersion, beast::Journal j) { - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); RPCParser rpParser(apiVersion, j); - json::Value jvRpcParams(json::ValueType::Array); + json::Value jvRpcParams(json::ArrayValue); for (int i = 1; i != args.size(); i++) jvRpcParams.append(args[i]); - retParams = json::Value(json::ValueType::Object); + retParams = json::Value(json::ObjectValue); retParams[jss::method] = args[0]; retParams[jss::params] = jvRpcParams; @@ -1676,11 +1676,11 @@ rpcClient( int nRet = RpcSuccess; json::Value jvOutput; - json::Value jvRequest(json::ValueType::Object); + json::Value jvRequest(json::ObjectValue); try { - json::Value jvRpc = json::Value(json::ValueType::Object); + json::Value jvRpc = json::Value(json::ObjectValue); jvRequest = rpcCmdToJson(args, jvRpc, apiVersion, logs.journal("RPCParser")); if (jvRequest.isMember(jss::error)) @@ -1702,19 +1702,19 @@ rpcClient( // line client works without a config file } - if (config.rpcIp) + if (config.rpc_ip) { - setup.client.ip = config.rpcIp->address().to_string(); - setup.client.port = config.rpcIp->port(); + setup.client.ip = config.rpc_ip->address().to_string(); + setup.client.port = config.rpc_ip->port(); } - json::Value jvParams(json::ValueType::Array); + json::Value jvParams(json::ArrayValue); - if (!setup.client.adminUser.empty()) - jvRequest["admin_user"] = setup.client.adminUser; + if (!setup.client.admin_user.empty()) + jvRequest["admin_user"] = setup.client.admin_user; - if (!setup.client.adminPassword.empty()) - jvRequest["admin_password"] = setup.client.adminPassword; + if (!setup.client.admin_password.empty()) + jvRequest["admin_password"] = setup.client.admin_password; if (jvRequest.isObject()) { @@ -1818,7 +1818,7 @@ namespace RPCCall { int fromCommandLine(Config const& config, std::vector const& vCmd, Logs& logs) { - auto const result = rpcClient(vCmd, config, logs, RPC::kApiCommandLineVersion); + auto const result = rpcClient(vCmd, config, logs, RPC::kAPI_COMMAND_LINE_VERSION); std::cout << result.second.toStyledString(); @@ -1860,10 +1860,10 @@ fromNetwork( // Number of bytes to try to receive if no // Content-Length header received - constexpr auto kRpcReplyMaxBytes = megabytes(256); + constexpr auto kRPC_REPLY_MAX_BYTES = megabytes(256); using namespace std::chrono_literals; - static constexpr auto kRpcWebhookTimeout = 30s; + auto constexpr kRPC_WEBHOOK_TIMEOUT = 30s; HTTPClient::request( bSSL, @@ -1879,8 +1879,8 @@ fromNetwork( std::placeholders::_1, std::placeholders::_2, j), - kRpcReplyMaxBytes, - kRpcWebhookTimeout, + kRPC_REPLY_MAX_BYTES, + kRPC_WEBHOOK_TIMEOUT, std::bind( &RPCCallImp::onResponse, callbackFuncP, diff --git a/src/xrpld/rpc/detail/RPCHandler.cpp b/src/xrpld/rpc/detail/RPCHandler.cpp index 7e30b81fa6..fb99aa682a 100644 --- a/src/xrpld/rpc/detail/RPCHandler.cpp +++ b/src/xrpld/rpc/detail/RPCHandler.cpp @@ -114,7 +114,7 @@ fillHandler(JsonContext& context, Handler const*& result) { // Count all jobs at jtCLIENT priority or higher. int const jobCount = context.app.getJobQueue().getJobCountGE(JtClient); - if (jobCount > Tuning::kMaxJobQueueClients) + if (jobCount > Tuning::kMAX_JOB_QUEUE_CLIENTS) { JLOG(context.j.debug()) << "Too busy for command: " << jobCount; return RpcTooBusy; @@ -135,7 +135,7 @@ fillHandler(JsonContext& context, Handler const*& result) JLOG(context.j.trace()) << "COMMAND:" << strCommand; JLOG(context.j.trace()) << "REQUEST:" << context.params; - auto handler = getHandler(context.apiVersion, context.app.config().betaRpcApi, strCommand); + auto handler = getHandler(context.apiVersion, context.app.config().BETA_RPC_API, strCommand); if (handler == nullptr) return RpcUnknownCommand; @@ -157,9 +157,9 @@ template Status callMethod(JsonContext& context, Method method, std::string const& name, Object& result) { - static std::atomic kRequestId{0}; + static std::atomic kREQUEST_ID{0}; auto& perfLog = context.app.getPerfLog(); - std::uint64_t const curId = ++kRequestId; + std::uint64_t const curId = ++kREQUEST_ID; try { perfLog.rpcStart(name, curId); @@ -179,8 +179,8 @@ callMethod(JsonContext& context, Method method, std::string const& name, Object& perfLog.rpcError(name, curId); JLOG(context.j.info()) << "Caught throw: " << e.what(); - if (context.loadType == Resource::kFeeReferenceRpc) - context.loadType = Resource::kFeeExceptionRpc; + if (context.loadType == Resource::kFEE_REFERENCE_RPC) + context.loadType = Resource::kFEE_EXCEPTION_RPC; injectError(RpcInternal, result); return RpcInternal; diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index 7ab2468b75..84ecd4e607 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -45,7 +46,7 @@ namespace xrpl::RPC { std::uint64_t -getStartHint(SLE::const_ref sle, AccountID const& accountID) +getStartHint(std::shared_ptr const& sle, AccountID const& accountID) { if (sle->getType() == ltRIPPLE_STATE) { @@ -66,7 +67,10 @@ getStartHint(SLE::const_ref sle, AccountID const& accountID) } bool -isRelatedToAccount(ReadView const& ledger, SLE::const_ref sle, AccountID const& accountID) +isRelatedToAccount( + ReadView const& ledger, + std::shared_ptr const& sle, + AccountID const& accountID) { if (sle->getType() == ltRIPPLE_STATE) { @@ -160,7 +164,7 @@ getSeedFromRPC(json::Value const& params, json::Value& error) using string_to_seed_t = std::function(std::string const&)>; using seed_match_t = std::pair; - static seed_match_t const kSeedTypes[]{ + static seed_match_t const kSEED_TYPES[]{ {jss::passphrase.cStr(), [](std::string const& s) { return parseGenericSeed(s); }}, {jss::seed.cStr(), [](std::string const& s) { return parseBase58(s); }}, {jss::seed_hex.cStr(), [](std::string const& s) { @@ -173,7 +177,7 @@ getSeedFromRPC(json::Value const& params, json::Value& error) // Identify which seed type is in use. seed_match_t const* seedType = nullptr; int count = 0; - for (auto const& t : kSeedTypes) + for (auto const& t : kSEED_TYPES) { if (params.isMember(t.first)) { @@ -215,13 +219,13 @@ keypairForSignature(json::Value const& params, json::Value& error, unsigned int bool const hasKeyType = params.isMember(jss::key_type); // All of the secret types we allow, but only one at a time. - static char const* const kSecretTypes[]{ + static char const* const kSECRET_TYPES[]{ jss::passphrase.cStr(), jss::secret.cStr(), jss::seed.cStr(), jss::seed_hex.cStr()}; // Identify which secret type is in use. char const* secretType = nullptr; int count = 0; - for (auto t : kSecretTypes) + for (auto t : kSECRET_TYPES) { if (params.isMember(t)) { @@ -347,7 +351,7 @@ chooseLedgerEntryType(json::Value const& params) std::pair result{RPC::Status::kOK, ltANY}; if (params.isMember(jss::type)) { - static constexpr auto kTypes = + static constexpr auto kTYPES = std::to_array>({ #pragma push_macro("LEDGER_ENTRY") #undef LEDGER_ENTRY @@ -374,10 +378,10 @@ chooseLedgerEntryType(json::Value const& params) // against the canonical name (case-insensitive) or the RPC name // (case-sensitive). auto const filter = p.asString(); - auto const iter = std::ranges::find_if(kTypes, [&filter](decltype(kTypes.front())& t) { + auto const iter = std::ranges::find_if(kTYPES, [&filter](decltype(kTYPES.front())& t) { return boost::iequals(std::get<0>(t), filter) || std::get<1>(t) == filter; }); - if (iter == kTypes.end()) + if (iter == kTYPES.end()) { result.first = RPC::Status{RpcInvalidParams, "Invalid field 'type'."}; XRPL_ASSERT( diff --git a/src/xrpld/rpc/detail/RPCHelpers.h b/src/xrpld/rpc/detail/RPCHelpers.h index bbc101a072..cdebd592c7 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.h +++ b/src/xrpld/rpc/detail/RPCHelpers.h @@ -33,7 +33,7 @@ struct JsonContext; * @return A 64-bit unsigned integer representing the start hint for traversal. */ std::uint64_t -getStartHint(SLE::const_ref sle, AccountID const& accountID); +getStartHint(std::shared_ptr const& sle, AccountID const& accountID); /** * @brief Tests if a ledger entry (SLE) is owned by the specified account. @@ -47,7 +47,10 @@ getStartHint(SLE::const_ref sle, AccountID const& accountID); * @return true if the SLE is owned by the account, false otherwise. */ bool -isRelatedToAccount(ReadView const& ledger, SLE::const_ref sle, AccountID const& accountID); +isRelatedToAccount( + ReadView const& ledger, + std::shared_ptr const& sle, + AccountID const& accountID); /** * @brief Parses an array of account IDs from a JSON value. @@ -149,7 +152,7 @@ std::optional> keypairForSignature( json::Value const& params, json::Value& error, - unsigned int apiVersion = kApiVersionIfUnspecified); + unsigned int apiVersion = kAPI_VERSION_IF_UNSPECIFIED); /** Parse subscribe/unsubscribe parameters */ diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 4d0d10a66b..f8ab42f499 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -36,7 +36,7 @@ isValidatedOld(LedgerMaster& ledgerMaster, bool standalone) if (standalone) return false; - return ledgerMaster.getValidatedLedgerAge() > Tuning::kMaxValidatedLedgerAge; + return ledgerMaster.getValidatedLedgerAge() > Tuning::kMAX_VALIDATED_LEDGER_AGE; } template @@ -304,9 +304,9 @@ getLedger(T& ledger, LedgerShortcut shortcut, Context const& context) return {RpcNotSynced, "notSynced"}; } - static auto const kMinSequenceGap = 10; + static auto const kMIN_SEQUENCE_GAP = 10; - if (ledger->header().seq + kMinSequenceGap < context.ledgerMaster.getValidLedgerIndex()) + if (ledger->header().seq + kMIN_SEQUENCE_GAP < context.ledgerMaster.getValidLedgerIndex()) { ledger.reset(); if (context.apiVersion == 1) @@ -342,7 +342,7 @@ getLedger<>(std::shared_ptr&, uint256 const&, Context const&); // In the absence of the "ledger_hash" or "ledger_index" parameters, the code // assumes that "ledger_index" has the value "current". // -// Returns a json::ValueType::Object. If there was an error, it will be in that +// Returns a json::objectValue. If there was an error, it will be in that // return value. Otherwise, the object contains the field "validated" and // optionally the fields "ledger_hash", "ledger_index" and // "ledger_current_index", if they are defined. @@ -401,18 +401,18 @@ getOrAcquireLedger(RPC::JsonContext const& context) if (hasHash) { - auto const& jsonHash = context.params.get(jss::ledger_hash, json::ValueType::Null); + auto const& jsonHash = context.params.get(jss::ledger_hash, json::NullValue); if (!jsonHash.isString() || !ledgerHash.parseHex(jsonHash.asString())) return Unexpected(RPC::expectedFieldError(jss::ledger_hash, "hex string")); } else { - auto const& jsonIndex = context.params.get(jss::ledger_index, json::ValueType::Null); + auto const& jsonIndex = context.params.get(jss::ledger_index, json::NullValue); if (!jsonIndex.isInt() && !jsonIndex.isUInt()) return Unexpected(RPC::expectedFieldError(jss::ledger_index, "number")); // We need a validated ledger to get the hash from the sequence - if (ledgerMaster.getValidatedLedgerAge() > RPC::Tuning::kMaxValidatedLedgerAge) + if (ledgerMaster.getValidatedLedgerAge() > RPC::Tuning::kMAX_VALIDATED_LEDGER_AGE) { if (context.apiVersion == 1) return Unexpected(rpcError(RpcNoCurrent)); @@ -471,7 +471,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) neededHash = hashOfSeq(*ledger, ledgerIndex, j); } XRPL_ASSERT(neededHash, "xrpl::RPC::getOrAcquireLedger : nonzero needed hash"); - ledgerHash = neededHash ? *neededHash : beast::kZero; // kludge + ledgerHash = neededHash ? *neededHash : beast::kZERO; // kludge } // Try to get the desired ledger diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index 92e9849939..56291ab34b 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -39,7 +39,7 @@ public: std::string strPassword, ServiceRegistry& registry) : RPCSub(source) - , ioContext_(ioContext) + , io_context_(ioContext) , jobQueue_(jobQueue) , url_(strUrl) , username_(std::move(strUsername)) @@ -159,7 +159,7 @@ private: JLOG(j_.info()) << "RPCCall::fromNetwork: " << ip_; RPCCall::fromNetwork( - ioContext_, + io_context_, ip_, port_, username_, @@ -180,7 +180,7 @@ private: } private: - boost::asio::io_context& ioContext_; + boost::asio::io_context& io_context_; JobQueue& jobQueue_; std::string url_; diff --git a/src/xrpld/rpc/detail/Role.cpp b/src/xrpld/rpc/detail/Role.cpp index 68c5fcc484..998eea15c9 100644 --- a/src/xrpld/rpc/detail/Role.cpp +++ b/src/xrpld/rpc/detail/Role.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include @@ -28,14 +27,14 @@ bool passwordUnrequiredOrSentCorrect(Port const& port, json::Value const& params) { XRPL_ASSERT( - !(port.adminNetsV4.empty() && port.adminNetsV6.empty()), + !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty()), "xrpl::passwordUnrequiredOrSentCorrect : non-empty admin nets"); - bool const passwordRequired = (!port.adminUser.empty() || !port.adminPassword.empty()); + bool const passwordRequired = (!port.admin_user.empty() || !port.admin_password.empty()); return !passwordRequired || ((params["admin_password"].isString() && - params["admin_password"].asString() == port.adminPassword) && - (params["admin_user"].isString() && params["admin_user"].asString() == port.adminUser)); + params["admin_password"].asString() == port.admin_password) && + (params["admin_user"].isString() && params["admin_user"].asString() == port.admin_user)); } bool @@ -80,7 +79,7 @@ ipAllowed( bool isAdmin(Port const& port, json::Value const& params, beast::IP::Address const& remoteIp) { - return ipAllowed(remoteIp, port.adminNetsV4, port.adminNetsV6) && + return ipAllowed(remoteIp, port.admin_nets_v4, port.admin_nets_v6) && passwordUnrequiredOrSentCorrect(port, params); } @@ -98,7 +97,7 @@ requestRole( if (required == Role::ADMIN) return Role::FORBID; - if (ipAllowed(remoteIp.address(), port.secureGatewayNetsV4, port.secureGatewayNetsV6)) + if (ipAllowed(remoteIp.address(), port.secure_gateway_nets_v4, port.secure_gateway_nets_v6)) { if (!user.empty()) return Role::IDENTIFIED; @@ -253,46 +252,32 @@ forwardedFor(http_request_type const& request) // Look for the Forwarded field in the request. if (auto it = request.find(boost::beast::http::field::forwarded); it != request.end()) { - auto asciiToLower = [](char c) -> char { + auto asciiTolower = [](char c) -> char { return ((static_cast(c) - 65U) < 26) ? c + 'a' - 'A' : c; }; - // Look for the first (case insensitive) "for=" at a directive - // boundary (start of value, or preceded by , ; or OWS). - static constexpr std::string_view kForStr{"for="}; - auto const atFieldBoundary = [begin = it->value().begin()](auto p) { - return p == begin || p[-1] == ';' || p[-1] == ',' || p[-1] == ' ' || p[-1] == '\t'; - }; - auto found = it->value().begin(); - while (true) - { - found = std::search( - found, - it->value().end(), - kForStr.begin(), - kForStr.end(), - [&asciiToLower](char c1, char c2) { return asciiToLower(c1) == asciiToLower(c2); }); + // Look for the first (case insensitive) "for=" + static std::string const kFOR_STR{"for="}; + char const* found = std::search( + it->value().begin(), + it->value().end(), + kFOR_STR.begin(), + kFOR_STR.end(), + [&asciiTolower](char c1, char c2) { return asciiTolower(c1) == asciiTolower(c2); }); - if (found == it->value().end()) - return {}; + if (found == it->value().end()) + return {}; - if (atFieldBoundary(found)) - break; - - ++found; - } - - std::advance(found, kForStr.size()); + found += kFOR_STR.size(); // We found a "for=". Scan for the end of the IP address. - auto const end = it->value().end(); - std::size_t const pos = [&found, &end]() { - std::size_t const pos = - std::string_view(found, std::distance(found, end)).find_first_of(",;"); - if (pos != std::string_view::npos) + std::size_t const pos = [&found, &it]() { + auto const remaining = static_cast(it->value().end() - found); + if (std::size_t const pos = std::string_view(found, remaining).find_first_of(",;"); + pos != std::string_view::npos) return pos; - return static_cast(std::distance(found, end)); + return remaining; }(); return extractIpAddrFromField({found, pos}); diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 0bdece3ec3..e81fc37cc5 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -139,9 +139,9 @@ ServerHandler::ServerHandler( , jobQueue_(jobQueue) { auto const& group(cm.group("rpc")); - rpcRequests_ = group->makeCounter("requests"); - rpcSize_ = group->makeEvent("size"); - rpcTime_ = group->makeEvent("time"); + rpc_requests_ = group->makeCounter("requests"); + rpc_size_ = group->makeEvent("size"); + rpc_time_ = group->makeEvent("time"); } ServerHandler::~ServerHandler() @@ -337,9 +337,10 @@ ServerHandler::onWSMessage( { json::Value jv; auto const size = boost::asio::buffer_size(buffers); - if (size > RPC::Tuning::kMaxRequestSize || !json::Reader{}.parse(jv, buffers) || !jv.isObject()) + if (size > RPC::Tuning::kMAX_REQUEST_SIZE || !json::Reader{}.parse(jv, buffers) || + !jv.isObject()) { - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); jvResult[jss::type] = jss::error; jvResult[jss::error] = "jsonInvalid"; jvResult[jss::value] = buffersToString(buffers); @@ -425,12 +426,12 @@ ServerHandler::processSession( } // Requests without "command" are invalid. - json::Value jr(json::ValueType::Object); - Resource::Charge loadType = Resource::kFeeReferenceRpc; + json::Value jr(json::ObjectValue); + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; try { - auto apiVersion = RPC::getAPIVersionNumber(jv, app_.config().betaRpcApi); - if (apiVersion == RPC::kApiInvalidVersion || + auto apiVersion = RPC::getAPIVersionNumber(jv, app_.config().BETA_RPC_API); + if (apiVersion == RPC::kAPI_INVALID_VERSION || (!jv.isMember(jss::command) && !jv.isMember(jss::method)) || (jv.isMember(jss::command) && !jv[jss::command].isString()) || (jv.isMember(jss::method) && !jv[jss::method].isString()) || @@ -439,8 +440,8 @@ ServerHandler::processSession( { jr[jss::type] = jss::response; jr[jss::status] = jss::error; - jr[jss::error] = apiVersion == RPC::kApiInvalidVersion ? jss::invalid_API_version - : jss::missingCommand; + jr[jss::error] = apiVersion == RPC::kAPI_INVALID_VERSION ? jss::invalid_API_version + : jss::missingCommand; jr[jss::request] = jv; if (jv.isMember(jss::id)) jr[jss::id] = jv[jss::id]; @@ -451,13 +452,13 @@ ServerHandler::processSession( if (jv.isMember(jss::api_version)) jr[jss::api_version] = jv[jss::api_version]; - is->getConsumer().charge(Resource::kFeeMalformedRpc); + is->getConsumer().charge(Resource::kFEE_MALFORMED_RPC); return jr; } auto required = RPC::roleRequired( apiVersion, - app_.config().betaRpcApi, + app_.config().BETA_RPC_API, jv.isMember(jss::command) ? jv[jss::command].asString() : jv[jss::method].asString()); auto role = requestRole( required, @@ -467,7 +468,7 @@ ServerHandler::processSession( is->user()); if (Role::FORBID == role) { - loadType = Resource::kFeeMalformedRpc; + loadType = Resource::kFEE_MALFORMED_RPC; jr[jss::result] = rpcError(RpcForbidden); } else @@ -584,18 +585,18 @@ ServerHandler::processSession( static json::Value makeJsonError(json::Int code, json::Value&& message) { - json::Value sub{json::ValueType::Object}; + json::Value sub{json::ObjectValue}; sub["code"] = code; sub["message"] = std::move(message); - json::Value r{json::ValueType::Object}; + json::Value r{json::ObjectValue}; r["error"] = sub; return r; } -constexpr json::Int kMethodNotFound = -32601; -constexpr json::Int kServerOverloaded = -32604; -constexpr json::Int kForbidden = -32605; -constexpr json::Int kWrongVersion = -32606; +json::Int constexpr kMETHOD_NOT_FOUND = -32601; +json::Int constexpr kSERVER_OVERLOADED = -32604; +json::Int constexpr kFORBIDDEN = -32605; +json::Int constexpr kWRONG_VERSION = -32606; void ServerHandler::processRequest( @@ -612,7 +613,7 @@ ServerHandler::processRequest( json::Value jsonOrig; { json::Reader reader; - if ((request.size() > RPC::Tuning::kMaxRequestSize) || !reader.parse(request, jsonOrig) || + if ((request.size() > RPC::Tuning::kMAX_REQUEST_SIZE) || !reader.parse(request, jsonOrig) || !jsonOrig || !jsonOrig.isObject()) { httpReply( @@ -637,7 +638,7 @@ ServerHandler::processRequest( size = jsonOrig[jss::params].size(); } - json::Value reply(batch ? json::ValueType::Array : json::ValueType::Object); + json::Value reply(batch ? json::ArrayValue : json::ObjectValue); auto const start(std::chrono::high_resolution_clock::now()); for (unsigned i = 0; i < size; ++i) { @@ -645,37 +646,37 @@ ServerHandler::processRequest( if (!jsonRPC.isObject()) { - json::Value r(json::ValueType::Object); + json::Value r(json::ObjectValue); r[jss::request] = jsonRPC; - r[jss::error] = makeJsonError(kMethodNotFound, "Method not found"); + r[jss::error] = makeJsonError(kMETHOD_NOT_FOUND, "Method not found"); reply.append(r); continue; } - unsigned apiVersion = RPC::kApiVersionIfUnspecified; + unsigned apiVersion = RPC::kAPI_VERSION_IF_UNSPECIFIED; if (jsonRPC.isMember(jss::params) && jsonRPC[jss::params].isArray() && jsonRPC[jss::params].size() > 0 && jsonRPC[jss::params][0u].isObject()) { apiVersion = RPC::getAPIVersionNumber( - jsonRPC[jss::params][json::UInt(0)], app_.config().betaRpcApi); + jsonRPC[jss::params][json::UInt(0)], app_.config().BETA_RPC_API); } - if (apiVersion == RPC::kApiVersionIfUnspecified && batch) + if (apiVersion == RPC::kAPI_VERSION_IF_UNSPECIFIED && batch) { // for batch request, api_version may be at a different level - apiVersion = RPC::getAPIVersionNumber(jsonRPC, app_.config().betaRpcApi); + apiVersion = RPC::getAPIVersionNumber(jsonRPC, app_.config().BETA_RPC_API); } - if (apiVersion == RPC::kApiInvalidVersion) + if (apiVersion == RPC::kAPI_INVALID_VERSION) { if (!batch) { httpReply(400, jss::invalid_API_version.cStr(), output, rpcJ); return; } - json::Value r(json::ValueType::Object); + json::Value r(json::ObjectValue); r[jss::request] = jsonRPC; - r[jss::error] = makeJsonError(kWrongVersion, jss::invalid_API_version.cStr()); + r[jss::error] = makeJsonError(kWRONG_VERSION, jss::invalid_API_version.cStr()); reply.append(r); continue; } @@ -686,7 +687,7 @@ ServerHandler::processRequest( if (jsonRPC.isMember(jss::method) && jsonRPC[jss::method].isString()) { required = RPC::roleRequired( - apiVersion, app_.config().betaRpcApi, jsonRPC[jss::method].asString()); + apiVersion, app_.config().BETA_RPC_API, jsonRPC[jss::method].asString()); } if (jsonRPC.isMember(jss::params) && jsonRPC[jss::params].isArray() && @@ -697,7 +698,7 @@ ServerHandler::processRequest( } else { - role = requestRole(required, port, json::ValueType::Object, remoteIPAddress, user); + role = requestRole(required, port, json::ObjectValue, remoteIPAddress, user); } Resource::Consumer usage; @@ -717,7 +718,7 @@ ServerHandler::processRequest( return; } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kServerOverloaded, "Server is overloaded"); + r[jss::error] = makeJsonError(kSERVER_OVERLOADED, "Server is overloaded"); reply.append(r); continue; } @@ -725,28 +726,28 @@ ServerHandler::processRequest( if (role == Role::FORBID) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); if (!batch) { httpReply(403, "Forbidden", output, rpcJ); return; } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kForbidden, "Forbidden"); + r[jss::error] = makeJsonError(kFORBIDDEN, "Forbidden"); reply.append(r); continue; } if (!jsonRPC.isMember(jss::method) || jsonRPC[jss::method].isNull()) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); if (!batch) { httpReply(400, "Null method", output, rpcJ); return; } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kMethodNotFound, "Null method"); + r[jss::error] = makeJsonError(kMETHOD_NOT_FOUND, "Null method"); reply.append(r); continue; } @@ -754,14 +755,14 @@ ServerHandler::processRequest( json::Value const& method = jsonRPC[jss::method]; if (!method.isString()) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); if (!batch) { httpReply(400, "method is not string", output, rpcJ); return; } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kMethodNotFound, "method is not string"); + r[jss::error] = makeJsonError(kMETHOD_NOT_FOUND, "method is not string"); reply.append(r); continue; } @@ -769,14 +770,14 @@ ServerHandler::processRequest( std::string const strMethod = method.asString(); if (strMethod.empty()) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); if (!batch) { httpReply(400, "method is empty", output, rpcJ); return; } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kMethodNotFound, "method is empty"); + r[jss::error] = makeJsonError(kMETHOD_NOT_FOUND, "method is empty"); reply.append(r); continue; } @@ -793,11 +794,11 @@ ServerHandler::processRequest( params = jsonRPC[jss::params]; if (!params) { - params = json::Value(json::ValueType::Object); + params = json::Value(json::ObjectValue); } else if (!params.isArray() || params.size() != 1) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); httpReply(400, "params unparsable", output, rpcJ); return; } @@ -806,7 +807,7 @@ ServerHandler::processRequest( params = std::move(params[0u]); if (!params.isObjectOrNull()) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); httpReply(400, "params unparsable", output, rpcJ); return; } @@ -822,7 +823,7 @@ ServerHandler::processRequest( { if (!params[jss::ripplerpc].isString()) { - usage.charge(Resource::kFeeMalformedRpc); + usage.charge(Resource::kFEE_MALFORMED_RPC); if (!batch) { httpReply(400, "ripplerpc is not a string", output, rpcJ); @@ -830,7 +831,7 @@ ServerHandler::processRequest( } json::Value r = jsonRPC; - r[jss::error] = makeJsonError(kMethodNotFound, "ripplerpc is not a string"); + r[jss::error] = makeJsonError(kMETHOD_NOT_FOUND, "ripplerpc is not a string"); reply.append(r); continue; } @@ -853,7 +854,7 @@ ServerHandler::processRequest( params[jss::command] = strMethod; JLOG(journal_.trace()) << "doRpcCommand:" << strMethod << ":" << params; - Resource::Charge loadType = Resource::kFeeReferenceRpc; + Resource::Charge loadType = Resource::kFEE_REFERENCE_RPC; RPC::JsonContext context{ {.j = journal_, @@ -894,7 +895,7 @@ ServerHandler::processRequest( if (usage.warn()) result[jss::warning] = jss::load; - json::Value r(json::ValueType::Object); + json::Value r(json::ObjectValue); if (ripplerpc >= "2.0") { if (result.isMember(jss::error)) @@ -993,24 +994,24 @@ ServerHandler::processRequest( auto response = to_string(reply); - rpcTime_.notify( + rpc_time_.notify( std::chrono::duration_cast( std::chrono::high_resolution_clock::now() - start)); - ++rpcRequests_; - rpcSize_.notify(beast::insight::Event::value_type{response.size()}); + ++rpc_requests_; + rpc_size_.notify(beast::insight::Event::value_type{response.size()}); response += '\n'; if (auto stream = journal_.debug()) { - static int const kMaxSize = 10000; - if (response.size() <= kMaxSize) + static int const kMAX_SIZE = 10000; + if (response.size() <= kMAX_SIZE) { stream << "Reply: " << response; } else { - stream << "Reply: " << response.substr(0, kMaxSize); + stream << "Reply: " << response.substr(0, kMAX_SIZE); } } @@ -1060,13 +1061,13 @@ ServerHandler::Setup::makeContexts() { if (p.secure()) { - if (p.sslKey.empty() && p.sslCert.empty() && p.sslChain.empty()) + if (p.ssl_key.empty() && p.ssl_cert.empty() && p.ssl_chain.empty()) { - p.context = makeSslContext(p.sslCiphers); + p.context = makeSslContext(p.ssl_ciphers); } else { - p.context = makeSslContextAuthed(p.sslKey, p.sslCert, p.sslChain, p.sslCiphers); + p.context = makeSslContextAuthed(p.ssl_key, p.ssl_cert, p.ssl_chain, p.ssl_ciphers); } } else @@ -1106,19 +1107,19 @@ toPort(ParsedPort const& parsed, std::ostream& log) p.user = parsed.user; p.password = parsed.password; - p.adminUser = parsed.adminUser; - p.adminPassword = parsed.adminPassword; - p.sslKey = parsed.sslKey; - p.sslCert = parsed.sslCert; - p.sslChain = parsed.sslChain; - p.sslCiphers = parsed.sslCiphers; - p.pmdOptions = parsed.pmdOptions; - p.wsQueueLimit = parsed.wsQueueLimit; + p.admin_user = parsed.admin_user; + p.admin_password = parsed.admin_password; + p.ssl_key = parsed.ssl_key; + p.ssl_cert = parsed.ssl_cert; + p.ssl_chain = parsed.ssl_chain; + p.ssl_ciphers = parsed.ssl_ciphers; + p.pmd_options = parsed.pmd_options; + p.ws_queue_limit = parsed.ws_queue_limit; p.limit = parsed.limit; - p.adminNetsV4 = parsed.adminNetsV4; - p.adminNetsV6 = parsed.adminNetsV6; - p.secureGatewayNetsV4 = parsed.secureGatewayNetsV4; - p.secureGatewayNetsV6 = parsed.secureGatewayNetsV6; + p.admin_nets_v4 = parsed.admin_nets_v4; + p.admin_nets_v6 = parsed.admin_nets_v6; + p.secure_gateway_nets_v4 = parsed.secure_gateway_nets_v4; + p.secure_gateway_nets_v6 = parsed.secure_gateway_nets_v6; return p; } @@ -1221,8 +1222,8 @@ setupClient(ServerHandler::Setup& setup) setup.client.port = iter->port; setup.client.user = iter->user; setup.client.password = iter->password; - setup.client.adminUser = iter->adminUser; - setup.client.adminPassword = iter->adminPassword; + setup.client.admin_user = iter->admin_user; + setup.client.admin_password = iter->admin_password; } // Fill out the overlay portion of the Setup diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 86d895fa1b..c6ceeee65f 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include #include @@ -55,7 +54,6 @@ #include #include -#include #include #include #include @@ -165,7 +163,7 @@ public: static ErrorCodeI acctMatchesPubKey( - SLE::const_pointer accountState, + std::shared_ptr accountState, AccountID const& accountID, PublicKey const& publicKey) { @@ -312,7 +310,7 @@ checkPayment( std::nullopt, domain, app); - if (pf.findPaths(app.config().pathSearchOld)) + if (pf.findPaths(app.config().PATH_SEARCH_OLD)) { // 4 is the maximum paths pf.computePathRanks(4); @@ -324,10 +322,10 @@ checkPayment( auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSign: build_path: " - << result.getJson(JsonOptions::Values::None); + << result.getJson(JsonOptions::KNone); if (!result.empty()) - txJson[jss::Paths] = result.getJson(JsonOptions::Values::None); + txJson[jss::Paths] = result.getJson(JsonOptions::KNone); } } return json::Value(); @@ -382,7 +380,7 @@ checkTxJsonFields( } // Check for current ledger. - if (verify && !config.standalone() && (validatedLedgerAge > Tuning::kMaxValidatedLedgerAge)) + if (verify && !config.standalone() && (validatedLedgerAge > Tuning::kMAX_VALIDATED_LEDGER_AGE)) { if (apiVersion == 1) { @@ -407,25 +405,6 @@ checkTxJsonFields( return ret; } -static Expected -checkNetworkID(json::Value const& txJson, uint32_t appNetworkId) -{ - if (appNetworkId > 1024) - { - if (!txJson.isMember(jss::NetworkID)) - { - return Unexpected( - RPC::makeError(RpcInvalidParams, RPC::missingFieldMessage("tx_json.NetworkID"))); - } - if (!txJson[jss::NetworkID].isIntegral() || txJson[jss::NetworkID].asUInt() != appNetworkId) - { - return Unexpected( - RPC::makeError(RpcInvalidParams, RPC::invalidFieldMessage("tx_json.NetworkID"))); - } - } - return Expected(); -} - //------------------------------------------------------------------------------ // A move-only struct that makes it easy to return either a json::Value or a @@ -508,7 +487,7 @@ transactionPreProcessImpl( validatedLedgerAge, app.config(), app.getFeeTrack(), - getAPIVersionNumber(params, app.config().betaRpcApi)); + getAPIVersionNumber(params, app.config().BETA_RPC_API)); if (RPC::containsError(txJsonResult)) return std::move(txJsonResult); @@ -519,7 +498,7 @@ transactionPreProcessImpl( if (!verify && !txJson.isMember(jss::Sequence)) return RPC::missingFieldError("tx_json.Sequence"); - SLE::const_pointer sle; + std::shared_ptr sle; if (verify) sle = app.getOpenLedger().current()->read(keylet::account(srcAddressID)); @@ -781,12 +760,12 @@ transactionFormatResultImpl(Transaction::pointer tpTrans, unsigned apiVersion) { if (apiVersion > 1) { - jvResult[jss::tx_json] = tpTrans->getJson(JsonOptions::Values::DisableApiPriorV2); + jvResult[jss::tx_json] = tpTrans->getJson(JsonOptions::KDisableApiPriorV2); jvResult[jss::hash] = to_string(tpTrans->getID()); } else { - jvResult[jss::tx_json] = tpTrans->getJson(JsonOptions::Values::None); + jvResult[jss::tx_json] = tpTrans->getJson(JsonOptions::KNone); } RPC::insertDeliverMax( @@ -846,16 +825,16 @@ getTxFee(Application const& app, Config const& config, json::Value tx) if (tx.isMember(jss::Signers)) { if (!tx[jss::Signers].isArray()) - return config.fees.referenceFee; + return config.FEES.reference_fee; - if (tx[jss::Signers].size() > STTx::kMaxMultiSigners) - return config.fees.referenceFee; + if (tx[jss::Signers].size() > STTx::kMAX_MULTI_SIGNERS) + return config.FEES.reference_fee; // check multi-signed signers for (auto& signer : tx[jss::Signers]) { if (!signer.isMember(jss::Signer) || !signer[jss::Signer].isObject()) - return config.fees.referenceFee; + return config.FEES.reference_fee; if (!signer[jss::Signer].isMember(jss::SigningPubKey)) { // autofill SigningPubKey @@ -872,7 +851,7 @@ getTxFee(Application const& app, Config const& config, json::Value tx) STParsedJSONObject parsed(std::string(jss::tx_json), tx); if (!parsed.object.has_value()) { - return config.fees.referenceFee; + return config.FEES.reference_fee; } try @@ -880,13 +859,13 @@ getTxFee(Application const& app, Config const& config, json::Value tx) STTx const& stTx = STTx(std::move(parsed.object.value())); std::string reason; if (!passesLocalChecks(stTx, reason)) - return config.fees.referenceFee; + return config.FEES.reference_fee; return calculateBaseFee(*app.getOpenLedger().current(), stTx); } catch (std::exception& e) { - return config.fees.referenceFee; + return config.FEES.reference_fee; } } @@ -945,8 +924,8 @@ checkFee( if (!doAutoFill) return RPC::missingFieldError("tx_json.Fee"); - int mult = Tuning::kDefaultAutoFillFeeMultiplier; - int div = Tuning::kDefaultAutoFillFeeDivisor; + int mult = Tuning::kDEFAULT_AUTO_FILL_FEE_MULTIPLIER; + int div = Tuning::kDEFAULT_AUTO_FILL_FEE_DIVISOR; if (request.isMember(jss::fee_mult_max)) { if (request[jss::fee_mult_max].isInt()) @@ -993,7 +972,7 @@ checkFee( //------------------------------------------------------------------------------ -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSign( json::Value jvRequest, @@ -1027,7 +1006,7 @@ transactionSign( return transactionFormatResultImpl(txn.second, apiVersion); } -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSubmit( json::Value jvRequest, @@ -1150,7 +1129,7 @@ sortAndValidateSigners(STArray& signers, AccountID const& signingForID) } // namespace detail -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSignFor( json::Value jvRequest, @@ -1186,16 +1165,8 @@ transactionSignFor( if (!txJson.isObject()) return RPC::objectFieldError(jss::tx_json); - if (auto checkResult = - detail::checkNetworkID(txJson, app.getNetworkIDService().getNetworkID()); - !checkResult) - { - return std::move(checkResult).error(); - } - - // If the tx_json.SigningPubKey field is missing, insert an empty one, - // in order for the `checkMultiSignFields` to not return an error - // for non-multisign transactions. + // If the tx_json.SigningPubKey field is missing, + // insert an empty one. if (!txJson.isMember(sfSigningPubKey.getJsonName())) txJson[sfSigningPubKey.getJsonName()] = ""; } @@ -1222,7 +1193,8 @@ transactionSignFor( signForParams.validMultiSign(), "xrpl::RPC::transactionSignFor : valid multi-signature"); { - SLE::const_pointer const accountState = ledger->read(keylet::account(*signerAccountID)); + std::shared_ptr const accountState = + ledger->read(keylet::account(*signerAccountID)); // Make sure the account and secret belong together. auto const err = acctMatchesPubKey(accountState, *signerAccountID, signForParams.getPublicKey()); @@ -1254,9 +1226,7 @@ transactionSignFor( signers.emplaceBack(std::move(signer)); // The array must be sorted and validated. - // For delegated transactions, the delegate account is - // the one forbidden from appearing in its own Signers array. - auto err = sortAndValidateSigners(signers, sttx->getFeePayer()); + auto err = sortAndValidateSigners(signers, (*sttx)[sfAccount]); if (RPC::containsError(err)) return err; } @@ -1271,7 +1241,7 @@ transactionSignFor( return transactionFormatResultImpl(txn.second, apiVersion); } -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSubmitMultiSigned( json::Value jvRequest, @@ -1304,12 +1274,12 @@ transactionSubmitMultiSigned( validatedLedgerAge, app.config(), app.getFeeTrack(), - getAPIVersionNumber(jvRequest, app.config().betaRpcApi)); + getAPIVersionNumber(jvRequest, app.config().BETA_RPC_API)); if (RPC::containsError(txJsonResult)) return std::move(txJsonResult); - SLE::const_pointer const sle = ledger->read(keylet::account(srcAddressID)); + std::shared_ptr const sle = ledger->read(keylet::account(srcAddressID)); if (!sle) { @@ -1423,9 +1393,7 @@ transactionSubmitMultiSigned( } // The array must be sorted and validated. - // For delegated transactions, getFeePayer() returns sfDelegate, - // that account is the one forbidden from appearing in its own Signers array. - auto err = sortAndValidateSigners(signers, stTx->getFeePayer()); + auto err = sortAndValidateSigners(signers, srcAddressID); if (RPC::containsError(err)) return err; diff --git a/src/xrpld/rpc/detail/TransactionSign.h b/src/xrpld/rpc/detail/TransactionSign.h index 1fd9e87b54..3d6f41ba30 100644 --- a/src/xrpld/rpc/detail/TransactionSign.h +++ b/src/xrpld/rpc/detail/TransactionSign.h @@ -25,8 +25,8 @@ getCurrentNetworkFee( TxQ const& txQ, Application const& app, json::Value const& tx, - int mult = Tuning::kDefaultAutoFillFeeMultiplier, - int div = Tuning::kDefaultAutoFillFeeDivisor); + int mult = Tuning::kDEFAULT_AUTO_FILL_FEE_MULTIPLIER, + int div = Tuning::kDEFAULT_AUTO_FILL_FEE_DIVISOR); /** Fill in the fee on behalf of the client. This is called when the client does not explicitly specify the fee. @@ -84,7 +84,7 @@ getProcessTxnFn(NetworkOPs& netOPs) }; } -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSign( json::Value params, // Passed by value so it can be modified locally. @@ -94,7 +94,7 @@ transactionSign( std::chrono::seconds validatedLedgerAge, Application& app); -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSubmit( json::Value params, // Passed by value so it can be modified locally. @@ -105,7 +105,7 @@ transactionSubmit( Application& app, ProcessTransactionFn const& processTransaction); -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSignFor( json::Value params, // Passed by value so it can be modified locally. @@ -115,7 +115,7 @@ transactionSignFor( std::chrono::seconds validatedLedgerAge, Application& app); -/** Returns a json::ValueType::Object. */ +/** Returns a json::objectValue. */ json::Value transactionSubmitMultiSigned( json::Value params, // Passed by value so it can be modified locally. diff --git a/src/xrpld/rpc/detail/TrustLine.cpp b/src/xrpld/rpc/detail/TrustLine.cpp index 77a2b36d56..4d0393bfed 100644 --- a/src/xrpld/rpc/detail/TrustLine.cpp +++ b/src/xrpld/rpc/detail/TrustLine.cpp @@ -9,12 +9,13 @@ #include #include +#include #include #include namespace xrpl { -TrustLineBase::TrustLineBase(SLE::const_ref sle, AccountID const& viewAccount) +TrustLineBase::TrustLineBase(std::shared_ptr const& sle, AccountID const& viewAccount) : key_(sle->key()) , lowLimit_(sle->getFieldAmount(sfLowLimit)) , highLimit_(sle->getFieldAmount(sfHighLimit)) @@ -29,14 +30,14 @@ TrustLineBase::TrustLineBase(SLE::const_ref sle, AccountID const& viewAccount) json::Value TrustLineBase::getJson(int) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret["low_id"] = to_string(lowLimit_.getIssuer()); ret["high_id"] = to_string(highLimit_.getIssuer()); return ret; } std::optional -PathFindTrustLine::makeItem(AccountID const& accountID, SLE::const_ref sle) +PathFindTrustLine::makeItem(AccountID const& accountID, std::shared_ptr const& sle) { if (!sle || sle->getType() != ltRIPPLE_STATE) return {}; @@ -52,11 +53,14 @@ getTrustLineItems( LineDirection direction = LineDirection::Outgoing) { std::vector items; - forEachItem(view, accountID, [&items, &accountID, &direction](SLE::const_ref 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(); @@ -74,7 +78,7 @@ PathFindTrustLine::getItems( return detail::getTrustLineItems(accountID, view, direction); } -RPCTrustLine::RPCTrustLine(SLE::const_ref 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)) @@ -84,7 +88,7 @@ RPCTrustLine::RPCTrustLine(SLE::const_ref sle, AccountID const& viewAccount) } std::optional -RPCTrustLine::makeItem(AccountID const& accountID, SLE::const_ref sle) +RPCTrustLine::makeItem(AccountID const& accountID, std::shared_ptr const& sle) { if (!sle || sle->getType() != ltRIPPLE_STATE) return {}; diff --git a/src/xrpld/rpc/detail/TrustLine.h b/src/xrpld/rpc/detail/TrustLine.h index 7a0a01d744..72d4d44ae3 100644 --- a/src/xrpld/rpc/detail/TrustLine.h +++ b/src/xrpld/rpc/detail/TrustLine.h @@ -39,7 +39,7 @@ public: protected: // This class should not be instantiated directly. Use one of the derived // classes. - TrustLineBase(SLE::const_ref sle, AccountID const& viewAccount); + TrustLineBase(std::shared_ptr const& sle, AccountID const& viewAccount); ~TrustLineBase() = default; TrustLineBase(TrustLineBase const&) = default; @@ -175,7 +175,7 @@ public: PathFindTrustLine() = delete; static std::optional - makeItem(AccountID const& accountID, SLE::const_ref sle); + makeItem(AccountID const& accountID, std::shared_ptr const& sle); static std::vector getItems(AccountID const& accountID, ReadView const& view, LineDirection direction); @@ -190,7 +190,7 @@ class RPCTrustLine final : public TrustLineBase, public CountedObject const& sle, AccountID const& viewAccount); [[nodiscard]] Rate const& getQualityIn() const @@ -205,7 +205,7 @@ public: } static std::optional - makeItem(AccountID const& accountID, SLE::const_ref sle); + makeItem(AccountID const& accountID, std::shared_ptr const& sle); static std::vector getItems(AccountID const& accountID, ReadView const& view); diff --git a/src/xrpld/rpc/detail/Tuning.h b/src/xrpld/rpc/detail/Tuning.h index 12c09bcb15..45c164efbe 100644 --- a/src/xrpld/rpc/detail/Tuning.h +++ b/src/xrpld/rpc/detail/Tuning.h @@ -11,58 +11,57 @@ struct LimitRange }; /** Limits for the account_lines command. */ -static constexpr LimitRange kAccountLines = {.rmin = 10, .rDefault = 200, .rmax = 400}; +static LimitRange constexpr kACCOUNT_LINES = {.rmin = 10, .rDefault = 200, .rmax = 400}; /** Limits for the account_channels command. */ -static constexpr LimitRange kAccountChannels = {.rmin = 10, .rDefault = 200, .rmax = 400}; +static LimitRange constexpr kACCOUNT_CHANNELS = {.rmin = 10, .rDefault = 200, .rmax = 400}; /** Limits for the account_objects command. */ -static constexpr LimitRange kAccountObjects = {.rmin = 10, .rDefault = 200, .rmax = 400}; +static LimitRange constexpr kACCOUNT_OBJECTS = {.rmin = 10, .rDefault = 200, .rmax = 400}; /** Limits for the account_offers command. */ -static constexpr LimitRange kAccountOffers = {.rmin = 10, .rDefault = 200, .rmax = 400}; +static LimitRange constexpr kACCOUNT_OFFERS = {.rmin = 10, .rDefault = 200, .rmax = 400}; /** Limits for the account_tx command. */ -static constexpr LimitRange kAccountTx = {.rmin = 10, .rDefault = 200, .rmax = 400}; +static LimitRange constexpr kACCOUNT_TX = {.rmin = 10, .rDefault = 200, .rmax = 400}; /** Limits for the book_offers command. */ -static constexpr LimitRange kBookOffers = {.rmin = 1, .rDefault = 60, .rmax = 100}; +static LimitRange constexpr kBOOK_OFFERS = {.rmin = 1, .rDefault = 60, .rmax = 100}; /** Limits for the no_ripple_check command. */ -static constexpr LimitRange kNoRippleCheck = {.rmin = 10, .rDefault = 300, .rmax = 400}; +static LimitRange constexpr kNO_RIPPLE_CHECK = {.rmin = 10, .rDefault = 300, .rmax = 400}; /** Limits for the account_nftokens command, in pages. */ -static constexpr LimitRange kAccountNfTokens = {.rmin = 20, .rDefault = 100, .rmax = 400}; +static LimitRange constexpr kACCOUNT_NF_TOKENS = {.rmin = 20, .rDefault = 100, .rmax = 400}; /** Limits for the nft_buy_offers & nft_sell_offers commands. */ -static constexpr LimitRange kNftOffers = {.rmin = 50, .rDefault = 250, .rmax = 500}; +static LimitRange constexpr kNFT_OFFERS = {.rmin = 50, .rDefault = 250, .rmax = 500}; -static constexpr int kDefaultAutoFillFeeMultiplier = 10; -static constexpr int kDefaultAutoFillFeeDivisor = 1; -static constexpr int kMaxPathfindsInProgress = 2; -static constexpr int kMaxPathfindJobCount = 50; -static constexpr int kMaxJobQueueClients = 500; -constexpr auto kMaxValidatedLedgerAge = std::chrono::minutes{2}; -static constexpr int kMaxRequestSize = 1000000; +static int constexpr kDEFAULT_AUTO_FILL_FEE_MULTIPLIER = 10; +static int constexpr kDEFAULT_AUTO_FILL_FEE_DIVISOR = 1; +static int constexpr kMAX_PATHFINDS_IN_PROGRESS = 2; +static int constexpr kMAX_PATHFIND_JOB_COUNT = 50; +static int constexpr kMAX_JOB_QUEUE_CLIENTS = 500; +auto constexpr kMAX_VALIDATED_LEDGER_AGE = std::chrono::minutes{2}; +static int constexpr kMAX_REQUEST_SIZE = 1000000; /** Maximum number of pages in one response from a binary LedgerData request. */ -static constexpr int kBinaryPageLength = 2048; +static int constexpr kBINARY_PAGE_LENGTH = 2048; /** Maximum number of pages in one response from a Json LedgerData request. */ -static constexpr int kJsonPageLength = 256; +static int constexpr kJSON_PAGE_LENGTH = 256; /** Maximum number of pages in a LedgerData response. */ -constexpr int -pageLength(bool isBinary) +int constexpr pageLength(bool isBinary) { - return isBinary ? kBinaryPageLength : kJsonPageLength; + return isBinary ? kBINARY_PAGE_LENGTH : kJSON_PAGE_LENGTH; } /** Maximum number of source currencies allowed in a path find request. */ -static constexpr int kMaxSrcCur = 18; +static int constexpr kMAX_SRC_CUR = 18; /** Maximum number of auto source currencies in a path find request. */ -static constexpr int kMaxAutoSrcCur = 88; +static int constexpr kMAX_AUTO_SRC_CUR = 88; } // namespace xrpl::RPC::Tuning /** @} */ diff --git a/src/xrpld/rpc/detail/WSInfoSub.h b/src/xrpld/rpc/detail/WSInfoSub.h index c224b93e0e..336f35957f 100644 --- a/src/xrpld/rpc/detail/WSInfoSub.h +++ b/src/xrpld/rpc/detail/WSInfoSub.h @@ -24,8 +24,8 @@ public: auto const& h = ws->request(); if (ipAllowed( beast::IPAddressConversion::fromAsio(ws->remoteEndpoint()).address(), - ws->port().secureGatewayNetsV4, - ws->port().secureGatewayNetsV6)) + ws->port().secure_gateway_nets_v4, + ws->port().secure_gateway_nets_v6)) { auto it = h.find("X-User"); if (it != h.end()) diff --git a/src/xrpld/rpc/handlers/ChannelVerify.cpp b/src/xrpld/rpc/handlers/ChannelVerify.cpp index 64f616e829..082188f8dc 100644 --- a/src/xrpld/rpc/handlers/ChannelVerify.cpp +++ b/src/xrpld/rpc/handlers/ChannelVerify.cpp @@ -58,7 +58,7 @@ doChannelVerify(RPC::JsonContext& context) return rpcError(RpcChannelMalformed); std::optional const optDrops = - params[jss::amount].isString() ? toUInt64(params[jss::amount].asString()) : std::nullopt; + params[jss::amount].isString() ? toUint64(params[jss::amount].asString()) : std::nullopt; if (!optDrops) return rpcError(RpcChannelAmtMalformed); diff --git a/src/xrpld/rpc/handlers/VaultInfo.cpp b/src/xrpld/rpc/handlers/VaultInfo.cpp index 2c00205131..59795736ed 100644 --- a/src/xrpld/rpc/handlers/VaultInfo.cpp +++ b/src/xrpld/rpc/handlers/VaultInfo.cpp @@ -22,7 +22,7 @@ parseVault(json::Value const& params, json::Value& jvResult) auto const hasOwner = params.isMember(jss::owner); auto const hasSeq = params.isMember(jss::seq); - uint256 uNodeIndex = beast::kZero; + uint256 uNodeIndex = beast::kZERO; if (hasVaultId && !hasOwner && !hasSeq) { if (!uNodeIndex.parseHex(params[jss::vault_id].asString())) @@ -42,7 +42,7 @@ parseVault(json::Value const& params, json::Value& jvResult) } if (!(params[jss::seq].isInt() || params[jss::seq].isUInt()) || params[jss::seq].asDouble() <= 0.0 || - params[jss::seq].asDouble() > double(json::Value::kMaxUInt)) + params[jss::seq].asDouble() > double(json::Value::kMAX_U_INT)) { RPC::injectError(RpcInvalidParams, jvResult); return std::nullopt; @@ -69,8 +69,8 @@ doVaultInfo(RPC::JsonContext& context) if (!lpLedger) return jvResult; - auto const uNodeIndex = parseVault(context.params, jvResult).value_or(beast::kZero); - if (uNodeIndex == beast::kZero) + auto const uNodeIndex = parseVault(context.params, jvResult).value_or(beast::kZERO); + if (uNodeIndex == beast::kZERO) { jvResult[jss::error] = "malformedRequest"; return jvResult; @@ -87,9 +87,9 @@ doVaultInfo(RPC::JsonContext& context) } json::Value& vault = jvResult[jss::vault]; - vault = sleVault->getJson(JsonOptions::Values::None); + vault = sleVault->getJson(JsonOptions::KNone); auto& share = vault[jss::shares]; - share = sleIssuance->getJson(JsonOptions::Values::None); + share = sleIssuance->getJson(JsonOptions::KNone); jvResult[jss::vault] = vault; return jvResult; diff --git a/src/xrpld/rpc/handlers/account/AccountChannels.cpp b/src/xrpld/rpc/handlers/account/AccountChannels.cpp index 8a5c7dc6e3..52c6b3148f 100644 --- a/src/xrpld/rpc/handlers/account/AccountChannels.cpp +++ b/src/xrpld/rpc/handlers/account/AccountChannels.cpp @@ -38,7 +38,7 @@ namespace xrpl { void addChannel(json::Value& jsonLines, SLE const& line) { - json::Value& jDst(jsonLines.append(json::ValueType::Object)); + json::Value& jDst(jsonLines.append(json::ObjectValue)); jDst[jss::channel_id] = to_string(line.key()); jDst[jss::account] = to_string(line[sfAccount]); jDst[jss::destination_account] = to_string(line[sfDestination]); @@ -108,19 +108,19 @@ doAccountChannels(RPC::JsonContext& context) return rpcError(RpcActMalformed); unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kAccountChannels, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kACCOUNT_CHANNELS, context)) return *err; - json::Value jsonChannels{json::ValueType::Array}; + json::Value jsonChannels{json::ArrayValue}; struct VisitData { - std::vector items; + std::vector> items; AccountID const& accountID; std::optional const& raDstAccount; }; VisitData visitData = {.items = {}, .accountID = accountID, .raDstAccount = raDstAccount}; visitData.items.reserve(limit); - uint256 startAfter = beast::kZero; + uint256 startAfter = beast::kZERO; std::uint64_t startHint = 0; if (params.isMember(jss::marker)) @@ -170,7 +170,8 @@ doAccountChannels(RPC::JsonContext& context) startAfter, startHint, limit + 1, - [&visitData, &accountID, &count, &limit, &marker, &nextHint](SLE::const_ref sleCur) { + [&visitData, &accountID, &count, &limit, &marker, &nextHint]( + std::shared_ptr const& sleCur) { if (!sleCur) { // LCOV_EXCL_START @@ -213,7 +214,7 @@ doAccountChannels(RPC::JsonContext& context) for (auto const& item : visitData.items) addChannel(jsonChannels, *item); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; result[jss::channels] = std::move(jsonChannels); return result; } diff --git a/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp b/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp index 058c10e224..1ea629c5ff 100644 --- a/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp +++ b/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp @@ -72,11 +72,11 @@ doAccountCurrencies(RPC::JsonContext& context) send.erase(badCurrency()); receive.erase(badCurrency()); - json::Value& sendCurrencies = (result[jss::send_currencies] = json::ValueType::Array); + json::Value& sendCurrencies = (result[jss::send_currencies] = json::ArrayValue); for (auto const& c : send) sendCurrencies.append(to_string(c)); - json::Value& recvCurrencies = (result[jss::receive_currencies] = json::ValueType::Array); + json::Value& recvCurrencies = (result[jss::receive_currencies] = json::ArrayValue); for (auto const& c : receive) recvCurrencies.append(to_string(c)); diff --git a/src/xrpld/rpc/handlers/account/AccountInfo.cpp b/src/xrpld/rpc/handlers/account/AccountInfo.cpp index d0f45cbc6f..69b0fb2879 100644 --- a/src/xrpld/rpc/handlers/account/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/account/AccountInfo.cpp @@ -49,7 +49,7 @@ namespace xrpl { void injectSLE(json::Value& jv, SLE const& sle) { - jv = sle.getJson(JsonOptions::Values::None); + jv = sle.getJson(JsonOptions::KNone); if (sle.getType() == ltACCOUNT_ROOT) { if (sle.isFieldPresent(sfEmailHash)) @@ -121,7 +121,7 @@ doAccountInfo(RPC::JsonContext& context) } auto const accountID{id.value()}; - static constexpr std::array, 9> kLsFlags{ + static constexpr std::array, 9> kLS_FLAGS{ {{"defaultRipple", lsfDefaultRipple}, {"depositAuth", lsfDepositAuth}, {"disableMasterKey", lsfDisableMaster}, @@ -133,17 +133,17 @@ doAccountInfo(RPC::JsonContext& context) {"requireDestinationTag", lsfRequireDestTag}}}; static constexpr std::array, 4> - kDisallowIncomingFlags{ + kDISALLOW_INCOMING_FLAGS{ {{"disallowIncomingNFTokenOffer", lsfDisallowIncomingNFTokenOffer}, {"disallowIncomingCheck", lsfDisallowIncomingCheck}, {"disallowIncomingPayChan", lsfDisallowIncomingPayChan}, {"disallowIncomingTrustline", lsfDisallowIncomingTrustline}}}; - static constexpr std::pair kAllowTrustLineClawbackFlag{ - "allowTrustLineClawback", lsfAllowTrustLineClawback}; + static constexpr std::pair + kALLOW_TRUST_LINE_CLAWBACK_FLAG{"allowTrustLineClawback", lsfAllowTrustLineClawback}; - static constexpr std::pair kAllowTrustLineLockingFlag{ - "allowTrustLineLocking", lsfAllowTrustLineLocking}; + static constexpr std::pair + kALLOW_TRUST_LINE_LOCKING_FLAG{"allowTrustLineLocking", lsfAllowTrustLineLocking}; auto const sleAccepted = ledger->read(keylet::account(accountID)); if (sleAccepted) @@ -158,27 +158,27 @@ doAccountInfo(RPC::JsonContext& context) return result; } - json::Value jvAccepted(json::ValueType::Object); + json::Value jvAccepted(json::ObjectValue); injectSLE(jvAccepted, *sleAccepted); result[jss::account_data] = jvAccepted; - json::Value acctFlags{json::ValueType::Object}; - for (auto const& lsf : kLsFlags) + json::Value acctFlags{json::ObjectValue}; + for (auto const& lsf : kLS_FLAGS) acctFlags[lsf.first.data()] = sleAccepted->isFlag(lsf.second); - for (auto const& lsf : kDisallowIncomingFlags) + for (auto const& lsf : kDISALLOW_INCOMING_FLAGS) acctFlags[lsf.first.data()] = sleAccepted->isFlag(lsf.second); if (ledger->rules().enabled(featureClawback)) { - acctFlags[kAllowTrustLineClawbackFlag.first.data()] = - sleAccepted->isFlag(kAllowTrustLineClawbackFlag.second); + acctFlags[kALLOW_TRUST_LINE_CLAWBACK_FLAG.first.data()] = + sleAccepted->isFlag(kALLOW_TRUST_LINE_CLAWBACK_FLAG.second); } if (ledger->rules().enabled(featureTokenEscrow)) { - acctFlags[kAllowTrustLineLockingFlag.first.data()] = - sleAccepted->isFlag(kAllowTrustLineLockingFlag.second); + acctFlags[kALLOW_TRUST_LINE_LOCKING_FLAG.first.data()] = + sleAccepted->isFlag(kALLOW_TRUST_LINE_LOCKING_FLAG.second); } result[jss::account_flags] = std::move(acctFlags); @@ -218,13 +218,13 @@ doAccountInfo(RPC::JsonContext& context) { // We put the SignerList in an array because of an anticipated // future when we support multiple signer lists on one account. - json::Value jvSignerList = json::ValueType::Array; + json::Value jvSignerList = json::ArrayValue; // This code will need to be revisited if in the future we support // multiple SignerLists on one account. auto const sleSigners = ledger->read(keylet::signers(accountID)); if (sleSigners) - jvSignerList.append(sleSigners->getJson(JsonOptions::Values::None)); + jvSignerList.append(sleSigners->getJson(JsonOptions::KNone)); // Documentation states this is returned as part of the account_info // response, but previously the code put it under account_data. We @@ -242,7 +242,7 @@ doAccountInfo(RPC::JsonContext& context) // Return queue info if that is requested if (queue) { - json::Value jvQueueData = json::ValueType::Object; + json::Value jvQueueData = json::ObjectValue; auto const txs = context.app.getTxQ().getAccountTxs(accountID); if (!txs.empty()) @@ -250,7 +250,7 @@ doAccountInfo(RPC::JsonContext& context) jvQueueData[jss::txn_count] = static_cast(txs.size()); auto& jvQueueTx = jvQueueData[jss::transactions]; - jvQueueTx = json::ValueType::Array; + jvQueueTx = json::ArrayValue; std::uint32_t seqCount = 0; std::uint32_t ticketCount = 0; @@ -266,7 +266,7 @@ doAccountInfo(RPC::JsonContext& context) SeqProxy prevSeqProxy = SeqProxy::sequence(0); for (auto const& tx : txs) { - json::Value jvTx = json::ValueType::Object; + json::Value jvTx = json::ObjectValue; if (tx.seqProxy.isSeq()) { diff --git a/src/xrpld/rpc/handlers/account/AccountLines.cpp b/src/xrpld/rpc/handlers/account/AccountLines.cpp index e69f70ca5a..7d0d4daa5a 100644 --- a/src/xrpld/rpc/handlers/account/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/account/AccountLines.cpp @@ -40,7 +40,7 @@ addLine(json::Value& jsonLines, RPCTrustLine const& line) STAmount const& saBalance(line.getBalance()); STAmount const& saLimit(line.getLimit()); STAmount const& saLimitPeer(line.getLimitPeer()); - json::Value& jPeer(jsonLines.append(json::ValueType::Object)); + json::Value& jPeer(jsonLines.append(json::ObjectValue)); jPeer[jss::account] = to_string(line.getAccountIDPeer()); // Amount reported is positive if current account holds other @@ -121,7 +121,7 @@ doAccountLines(RPC::JsonContext& context) } unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kAccountLines, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kACCOUNT_LINES, context)) return *err; // this flag allows the requester to ask incoming trustlines in default @@ -129,7 +129,7 @@ doAccountLines(RPC::JsonContext& context) bool const ignoreDefault = params.isMember(jss::ignore_default) && params[jss::ignore_default].asBool(); - json::Value& jsonLines(result[jss::lines] = json::ValueType::Array); + json::Value& jsonLines(result[jss::lines] = json::ArrayValue); struct VisitData { std::vector items; @@ -144,7 +144,7 @@ doAccountLines(RPC::JsonContext& context) .raPeerAccount = raPeerAccount, .ignoreDefault = ignoreDefault, .foundCount = 0}; - uint256 startAfter = beast::kZero; + uint256 startAfter = beast::kZERO; std::uint64_t startHint = 0; if (params.isMember(jss::marker)) @@ -195,7 +195,8 @@ doAccountLines(RPC::JsonContext& context) startAfter, startHint, limit + 1, - [&visitData, &count, &marker, &limit, &nextHint](SLE::const_ref sleCur) { + [&visitData, &count, &marker, &limit, &nextHint]( + std::shared_ptr const& sleCur) { if (!sleCur) { // LCOV_EXCL_START @@ -218,11 +219,11 @@ doAccountLines(RPC::JsonContext& context) { if (sleCur->getFieldAmount(sfLowLimit).getIssuer() == visitData.accountID) { - ignore = !sleCur->isFlag(lsfLowReserve); + ignore = !(sleCur->getFieldU32(sfFlags) & lsfLowReserve); } else { - ignore = !sleCur->isFlag(lsfHighReserve); + ignore = !(sleCur->getFieldU32(sfFlags) & lsfHighReserve); } } @@ -259,7 +260,7 @@ doAccountLines(RPC::JsonContext& context) for (auto const& item : visitData.items) addLine(jsonLines, item); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return result; } diff --git a/src/xrpld/rpc/handlers/account/AccountNFTs.cpp b/src/xrpld/rpc/handlers/account/AccountNFTs.cpp index 0eb91206f3..077001e543 100644 --- a/src/xrpld/rpc/handlers/account/AccountNFTs.cpp +++ b/src/xrpld/rpc/handlers/account/AccountNFTs.cpp @@ -58,7 +58,7 @@ doAccountNFTs(RPC::JsonContext& context) return rpcError(RpcActNotFound); unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kAccountNfTokens, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kACCOUNT_NF_TOKENS, context)) return *err; uint256 marker; @@ -81,12 +81,12 @@ doAccountNFTs(RPC::JsonContext& context) Keylet(ltNFTOKEN_PAGE, ledger->succ(first.key, last.key.next()).value_or(last.key))); std::uint32_t cnt = 0; - auto& nfts = (result[jss::account_nfts] = json::ValueType::Array); + auto& nfts = (result[jss::account_nfts] = json::ArrayValue); // Continue iteration from the current page: bool pastMarker = marker.isZero(); bool markerFound = false; - uint256 const maskedMarker = marker & nft::kPageMask; + uint256 const maskedMarker = marker & nft::kPAGE_MASK; while (cp) { auto arr = cp->getFieldArray(sfNFTokens); @@ -105,7 +105,7 @@ doAccountNFTs(RPC::JsonContext& context) // in that case then we need to compare against the full // 256 bits. uint256 const nftokenID = o[sfNFTokenID]; - uint256 const maskedNftokenID = nftokenID & nft::kPageMask; + uint256 const maskedNftokenID = nftokenID & nft::kPAGE_MASK; if (!pastMarker) { @@ -128,7 +128,7 @@ doAccountNFTs(RPC::JsonContext& context) pastMarker = true; { - json::Value& obj = nfts.append(o.getJson(JsonOptions::Values::None)); + json::Value& obj = nfts.append(o.getJson(JsonOptions::KNone)); // Pull out the components of the nft ID. obj[sfFlags.jsonName] = nft::getFlags(nftokenID); @@ -161,7 +161,7 @@ doAccountNFTs(RPC::JsonContext& context) return RPC::invalidFieldError(jss::marker); result[jss::account] = toBase58(accountID); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return result; } diff --git a/src/xrpld/rpc/handlers/account/AccountObjects.cpp b/src/xrpld/rpc/handlers/account/AccountObjects.cpp index 08a7fbe44a..c930333d91 100644 --- a/src/xrpld/rpc/handlers/account/AccountObjects.cpp +++ b/src/xrpld/rpc/handlers/account/AccountObjects.cpp @@ -59,78 +59,83 @@ getAccountObjects( // iterate NFT pages if the filter says so AND dirIndex == 0 bool iterateNFTPages = (!typeFilter.has_value() || typeMatchesFilter(typeFilter.value(), ltNFTOKEN_PAGE)) && - dirIndex.isZero(); + dirIndex == beast::kZERO; Keylet const firstNFTPage = keylet::nftpageMin(account); // we need to check the marker to see if it is an NFTTokenPage index. - if (iterateNFTPages && entryIndex.isNonZero()) + if (iterateNFTPages && entryIndex != beast::kZERO) { // if it is we will try to iterate the pages up to the limit // and then change over to the owner directory - if (firstNFTPage.key != (entryIndex & ~nft::kPageMask)) + if (firstNFTPage.key != (entryIndex & ~nft::kPAGE_MASK)) iterateNFTPages = false; } - auto& jvObjects = (jvResult[jss::account_objects] = json::ValueType::Array); + auto& jvObjects = (jvResult[jss::account_objects] = json::ArrayValue); // this is a mutable version of limit, used to seamlessly switch // to iterating directory entries when nftokenpages are exhausted - uint32_t limitLeft = limit; + uint32_t mlimit = limit; // iterate NFTokenPages preferentially if (iterateNFTPages) { Keylet const first = - entryIndex.isZero() ? firstNFTPage : Keylet{ltNFTOKEN_PAGE, entryIndex}; + entryIndex == beast::kZERO ? firstNFTPage : Keylet{ltNFTOKEN_PAGE, entryIndex}; Keylet const last = keylet::nftpageMax(account); - auto currentKey = ledger.succ(first.key, last.key.next()).value_or(last.key); + // current key + uint256 ck = ledger.succ(first.key, last.key.next()).value_or(last.key); - auto currentPage = ledger.read(Keylet{ltNFTOKEN_PAGE, currentKey}); + // current page + auto cp = ledger.read(Keylet{ltNFTOKEN_PAGE, ck}); - while (currentPage) + while (cp) { - jvObjects.append(currentPage->getJson(JsonOptions::Values::None)); - auto const npm = (*currentPage)[~sfNextPageMin]; + jvObjects.append(cp->getJson(JsonOptions::KNone)); + auto const npm = (*cp)[~sfNextPageMin]; if (npm) { - currentPage = ledger.read(Keylet(ltNFTOKEN_PAGE, *npm)); + cp = ledger.read(Keylet(ltNFTOKEN_PAGE, *npm)); } else { - currentPage = nullptr; + cp = nullptr; } - if (--limitLeft == 0 && currentPage) + if (--mlimit == 0) { - jvResult[jss::limit] = limit; - jvResult[jss::marker] = std::string("0,") + to_string(currentKey); - return true; + if (cp) + { + jvResult[jss::limit] = limit; + jvResult[jss::marker] = std::string("0,") + to_string(ck); + return true; + } } if (!npm) break; - currentKey = *npm; + ck = *npm; } // if execution reaches here then we're about to transition // to iterating the root directory (and the conventional // behaviour of this RPC function.) Therefore we should // zero entryIndex so as not to terribly confuse things. - entryIndex = beast::kZero; + entryIndex = beast::kZERO; } auto const root = keylet::ownerDir(account); - auto startEntryFound = false; + auto found = false; if (dirIndex.isZero()) { dirIndex = root.key; - startEntryFound = true; + found = true; } auto dir = ledger.read({ltDIR_NODE, dirIndex}); @@ -139,8 +144,8 @@ getAccountObjects( // it's possible the user had nftoken pages but no // directory entries. If there's no nftoken page, we will // give empty array for account_objects. - if (limitLeft >= limit) - jvResult[jss::account_objects] = json::ValueType::Array; + if (mlimit >= limit) + jvResult[jss::account_objects] = json::ArrayValue; // non-zero dirIndex validity was checked in the beginning of this // function; by this point, it should be zero. This function returns @@ -151,46 +156,46 @@ getAccountObjects( return true; } - std::uint32_t itemsAdded = 0; + std::uint32_t i = 0; for (;;) { - auto const& dirEntries = dir->getFieldV256(sfIndexes); - auto entryIter = dirEntries.begin(); + auto const& entries = dir->getFieldV256(sfIndexes); + auto iter = entries.begin(); - if (!startEntryFound) + if (!found) { - entryIter = std::find(entryIter, dirEntries.end(), entryIndex); - if (entryIter == dirEntries.end()) + iter = std::find(iter, entries.end(), entryIndex); + if (iter == entries.end()) return false; - startEntryFound = true; + found = true; } // it's possible that the returned NFTPages exactly filled the // response. Check for that condition. - if (itemsAdded == limitLeft && limitLeft < limit && entryIter != dirEntries.end()) + if (i == mlimit && mlimit < limit) { jvResult[jss::limit] = limit; - jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*entryIter); + jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*iter); return true; } - for (; entryIter != dirEntries.end(); ++entryIter) + for (; iter != entries.end(); ++iter) { - auto const sleNode = ledger.read(keylet::child(*entryIter)); + auto const sleNode = ledger.read(keylet::child(*iter)); if (!typeFilter.has_value() || typeMatchesFilter(typeFilter.value(), sleNode->getType())) { - jvObjects.append(sleNode->getJson(JsonOptions::Values::None)); + jvObjects.append(sleNode->getJson(JsonOptions::KNone)); } - if (++itemsAdded == limitLeft) + if (++i == mlimit) { - if (++entryIter != dirEntries.end()) + if (++iter != entries.end()) { jvResult[jss::limit] = limit; - jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*entryIter); + jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*iter); return true; } @@ -207,14 +212,13 @@ getAccountObjects( if (!dir) return true; - if (itemsAdded == limitLeft) + if (i == mlimit) { - auto const& currentDirEntries = dir->getFieldV256(sfIndexes); - if (!currentDirEntries.empty()) + auto const& e = dir->getFieldV256(sfIndexes); + if (!e.empty()) { jvResult[jss::limit] = limit; - jvResult[jss::marker] = - to_string(dirIndex) + ',' + to_string(*currentDirEntries.begin()); + jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*e.begin()); } return true; @@ -257,7 +261,7 @@ doAccountObjects(RPC::JsonContext& context) { json::StaticString name; LedgerEntryType type; - } static constexpr kDeletionBlockers[] = { + } static constexpr kDELETION_BLOCKERS[] = { {.name = jss::check, .type = ltCHECK}, {.name = jss::escrow, .type = ltESCROW}, {.name = jss::nft_page, .type = ltNFTOKEN_PAGE}, @@ -274,9 +278,9 @@ doAccountObjects(RPC::JsonContext& context) }; typeFilter.emplace(); - typeFilter->reserve(std::size(kDeletionBlockers)); + typeFilter->reserve(std::size(kDELETION_BLOCKERS)); - for (auto [name, type] : kDeletionBlockers) + for (auto [name, type] : kDELETION_BLOCKERS) { if (params.isMember(jss::type) && name != params[jss::type]) { @@ -306,7 +310,7 @@ doAccountObjects(RPC::JsonContext& context) } unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kAccountObjects, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kACCOUNT_OBJECTS, context)) return *err; uint256 dirIndex; @@ -333,7 +337,7 @@ doAccountObjects(RPC::JsonContext& context) return RPC::invalidFieldError(jss::marker); result[jss::account] = toBase58(accountID); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return result; } diff --git a/src/xrpld/rpc/handlers/account/AccountOffers.cpp b/src/xrpld/rpc/handlers/account/AccountOffers.cpp index 4829ff56b1..6314dc8ec2 100644 --- a/src/xrpld/rpc/handlers/account/AccountOffers.cpp +++ b/src/xrpld/rpc/handlers/account/AccountOffers.cpp @@ -33,10 +33,10 @@ namespace xrpl { void -appendOfferJson(SLE::const_ref offer, json::Value& offers) +appendOfferJson(std::shared_ptr const& offer, json::Value& offers) { STAmount const dirRate = amountFromQuality(getQuality(offer->getFieldH256(sfBookDirectory))); - json::Value& obj(offers.append(json::ValueType::Object)); + json::Value& obj(offers.append(json::ObjectValue)); offer->getFieldAmount(sfTakerPays).setJson(obj[jss::taker_pays]); offer->getFieldAmount(sfTakerGets).setJson(obj[jss::taker_gets]); obj[jss::seq] = offer->getFieldU32(sfSequence); @@ -83,12 +83,12 @@ doAccountOffers(RPC::JsonContext& context) return rpcError(RpcActNotFound); unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kAccountOffers, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kACCOUNT_OFFERS, context)) return *err; - json::Value& jsonOffers(result[jss::offers] = json::ValueType::Array); - std::vector offers; - uint256 startAfter = beast::kZero; + json::Value& jsonOffers(result[jss::offers] = json::ArrayValue); + std::vector> offers; + uint256 startAfter = beast::kZERO; std::uint64_t startHint = 0; if (params.isMember(jss::marker)) @@ -138,7 +138,8 @@ doAccountOffers(RPC::JsonContext& context) startAfter, startHint, limit + 1, - [&offers, &count, &marker, &limit, &nextHint, &accountID](SLE::const_ref sle) { + [&offers, &count, &marker, &limit, &nextHint, &accountID]( + std::shared_ptr const& sle) { if (!sle) { // LCOV_EXCL_START @@ -176,7 +177,7 @@ doAccountOffers(RPC::JsonContext& context) for (auto const& offer : offers) appendOfferJson(offer, jsonOffers); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return result; } diff --git a/src/xrpld/rpc/handlers/account/AccountTx.cpp b/src/xrpld/rpc/handlers/account/AccountTx.cpp index 6c6d2bb6fd..7c8e45f523 100644 --- a/src/xrpld/rpc/handlers/account/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/account/AccountTx.cpp @@ -211,7 +211,7 @@ getLedgerRange(RPC::Context& context, std::optional const& ledg std::pair doAccountTxHelp(RPC::Context& context, AccountTxArgs const& args) { - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; AccountTxResult result; @@ -293,7 +293,7 @@ populateJsonResponse( response[jss::ledger_index_min] = result.ledgerRange.min; response[jss::ledger_index_max] = result.ledgerRange.max; - json::Value& jvTxns = (response[jss::transactions] = json::ValueType::Array); + json::Value& jvTxns = (response[jss::transactions] = json::ArrayValue); if (auto txnsData = std::get_if(&result.transactions)) { @@ -303,18 +303,14 @@ populateJsonResponse( { if (txn) { - json::Value& jvObj = jvTxns.append(json::ValueType::Object); + json::Value& jvObj = jvTxns.append(json::ObjectValue); jvObj[jss::validated] = true; auto const jsonTx = (context.apiVersion > 1 ? jss::tx_json : jss::tx); if (context.apiVersion > 1) { jvObj[jsonTx] = txn->getJson( - static_cast( - JsonOptions::Values::IncludeDate) | - static_cast( - JsonOptions::Values::DisableApiPriorV2), - false); + JsonOptions::KIncludeDate | JsonOptions::KDisableApiPriorV2, false); jvObj[jss::hash] = to_string(txn->getID()); jvObj[jss::ledger_index] = txn->getLedger(); jvObj[jss::ledger_hash] = @@ -326,14 +322,14 @@ populateJsonResponse( } else { - jvObj[jsonTx] = txn->getJson(JsonOptions::Values::IncludeDate); + jvObj[jsonTx] = txn->getJson(JsonOptions::KIncludeDate); } auto const& sttx = txn->getSTransaction(); RPC::insertDeliverMax(jvObj[jsonTx], sttx->getTxnType(), context.apiVersion); if (txnMeta) { - jvObj[jss::meta] = txnMeta->getJson(JsonOptions::Values::IncludeDate); + jvObj[jss::meta] = txnMeta->getJson(JsonOptions::KIncludeDate); insertDeliveredAmount(jvObj[jss::meta], context, txn, *txnMeta); RPC::insertNFTSyntheticInJson(jvObj, sttx, *txnMeta); RPC::insertMPTokenIssuanceID(jvObj[jss::meta], sttx, *txnMeta); @@ -355,7 +351,7 @@ populateJsonResponse( for (auto const& binaryData : std::get(result.transactions)) { - json::Value& jvObj = jvTxns.append(json::ValueType::Object); + json::Value& jvObj = jvTxns.append(json::ObjectValue); jvObj[jss::tx_blob] = strHex(std::get<0>(binaryData)); auto const jsonMeta = (context.apiVersion > 1 ? jss::meta_blob : jss::meta); @@ -367,7 +363,7 @@ populateJsonResponse( if (result.marker) { - response[jss::marker] = json::ValueType::Object; + response[jss::marker] = json::ObjectValue; response[jss::marker][jss::ledger] = result.marker->ledgerSeq; response[jss::marker][jss::seq] = result.marker->txnSeq; } @@ -410,7 +406,7 @@ doAccountTx(RPC::JsonContext& context) return RPC::invalidFieldError(jss::forward); } - if (auto const err = RPC::readLimitField(args.limit, RPC::Tuning::kAccountTx, context)) + if (auto const err = RPC::readLimitField(args.limit, RPC::Tuning::kACCOUNT_TX, context)) return *err; args.binary = params.isMember(jss::binary) && params[jss::binary].asBool(); @@ -440,8 +436,8 @@ doAccountTx(RPC::JsonContext& context) { auto& token = params[jss::marker]; if (!token.isMember(jss::ledger) || !token.isMember(jss::seq) || - !token[jss::ledger].isConvertibleTo(json::ValueType::UInt) || - !token[jss::seq].isConvertibleTo(json::ValueType::UInt)) + !token[jss::ledger].isConvertibleTo(json::ValueType::UintValue) || + !token[jss::seq].isConvertibleTo(json::ValueType::UintValue)) { RPC::Status const status{ RpcInvalidParams, diff --git a/src/xrpld/rpc/handlers/account/GatewayBalances.cpp b/src/xrpld/rpc/handlers/account/GatewayBalances.cpp index bd1681172c..7b6d6ca07b 100644 --- a/src/xrpld/rpc/handlers/account/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/account/GatewayBalances.cpp @@ -72,7 +72,7 @@ doGatewayBalances(RPC::JsonContext& context) if (!id) return rpcError(RpcActMalformed); auto const accountID{id.value()}; - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; result[jss::account] = toBase58(accountID); @@ -144,7 +144,7 @@ doGatewayBalances(RPC::JsonContext& context) // Traverse the cold wallet's trust lines { - forEachItem(*ledger, accountID, [&](SLE::const_ref sle) { + forEachItem(*ledger, accountID, [&](std::shared_ptr const& sle) { if (sle->getType() == ltESCROW) { auto const& escrow = sle->getFieldAmount(sfAmount); @@ -153,7 +153,7 @@ doGatewayBalances(RPC::JsonContext& context) return; auto& bal = locked[escrow.get().currency]; - if (bal == beast::kZero) + if (bal == beast::kZERO) { // This is needed to set the currency code correctly bal = escrow; @@ -170,7 +170,8 @@ doGatewayBalances(RPC::JsonContext& context) // On overflow return the largest valid STAmount. // Very large sums of STAmount are approximations // anyway. - bal = STAmount(bal.get(), STAmount::kMaxValue, STAmount::kMaxOffset); + bal = + STAmount(bal.get(), STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); } } } @@ -209,7 +210,7 @@ doGatewayBalances(RPC::JsonContext& context) { // normal negative balance, obligation to customer auto& bal = sums[rs->getBalance().get().currency]; - if (bal == beast::kZero) + if (bal == beast::kZERO) { // This is needed to set the currency code correctly bal = -rs->getBalance(); @@ -226,7 +227,7 @@ doGatewayBalances(RPC::JsonContext& context) // On overflow return the largest valid STAmount. // Very large sums of STAmount are approximations // anyway. - bal = STAmount(bal.asset(), STAmount::kMaxValue, STAmount::kMaxOffset); + bal = STAmount(bal.asset(), STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET); } } } diff --git a/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp index d8bb65aba9..2f4c90e4e7 100644 --- a/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp @@ -75,7 +75,7 @@ doNoRippleCheck(RPC::JsonContext& context) } unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kNoRippleCheck, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kNO_RIPPLE_CHECK, context)) return *err; bool transactions = false; @@ -99,7 +99,7 @@ doNoRippleCheck(RPC::JsonContext& context) json::Value dummy; // NOLINT(misc-const-correctness) json::Value& jvTransactions = - transactions ? (result[jss::transactions] = json::ValueType::Array) : dummy; + transactions ? (result[jss::transactions] = json::ArrayValue) : dummy; auto id = parseBase58(params[jss::account].asString()); if (!id) @@ -114,9 +114,9 @@ doNoRippleCheck(RPC::JsonContext& context) std::uint32_t seq = sle->getFieldU32(sfSequence); - json::Value& problems = (result["problems"] = json::ValueType::Array); + json::Value& problems = (result["problems"] = json::ArrayValue); - bool const bDefaultRipple = sle->isFlag(lsfDefaultRipple); + bool const bDefaultRipple = (sle->getFieldU32(sfFlags) & lsfDefaultRipple) != 0u; if (bDefaultRipple && !roleGateway) { @@ -130,57 +130,60 @@ doNoRippleCheck(RPC::JsonContext& context) problems.append("You should immediately set your default ripple flag"); if (transactions) { - json::Value& tx = jvTransactions.append(json::ValueType::Object); + json::Value& tx = jvTransactions.append(json::ObjectValue); tx["TransactionType"] = jss::AccountSet; tx["SetFlag"] = 8; fillTransaction(context, tx, accountID, seq, *ledger); } } - forEachItemAfter(*ledger, accountID, uint256(), 0, limit, [&](SLE::const_ref ownedItem) { - if (ownedItem->getType() == ltRIPPLE_STATE) - { - bool const bLow = accountID == ownedItem->getFieldAmount(sfLowLimit).getIssuer(); - - bool const bNoRipple = ownedItem->isFlag(bLow ? lsfLowNoRipple : lsfHighNoRipple); - - std::string problem; - bool needFix = false; - if (bNoRipple && roleGateway) + forEachItemAfter( + *ledger, accountID, uint256(), 0, limit, [&](std::shared_ptr const& ownedItem) { + if (ownedItem->getType() == ltRIPPLE_STATE) { - problem = "You should clear the no ripple flag on your "; - needFix = true; - } - else if (!roleGateway && !bNoRipple) - { - problem = "You should probably set the no ripple flag on your "; - needFix = true; - } - if (needFix) - { - AccountID const peer = - ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit).getIssuer(); - STAmount const peerLimit = - ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit); - problem += to_string(peerLimit.get().currency); - problem += " line to "; - problem += to_string(peerLimit.getIssuer()); - problems.append(problem); + bool const bLow = accountID == ownedItem->getFieldAmount(sfLowLimit).getIssuer(); - STAmount limitAmount(ownedItem->getFieldAmount(bLow ? sfLowLimit : sfHighLimit)); - limitAmount.get().account = peer; + bool const bNoRipple = + ownedItem->getFieldU32(sfFlags) & (bLow ? lsfLowNoRipple : lsfHighNoRipple); - json::Value& tx = jvTransactions.append(json::ValueType::Object); - tx["TransactionType"] = jss::TrustSet; - tx["LimitAmount"] = limitAmount.getJson(JsonOptions::Values::None); - tx["Flags"] = bNoRipple ? tfClearNoRipple : tfSetNoRipple; - fillTransaction(context, tx, accountID, seq, *ledger); + std::string problem; + bool needFix = false; + if (bNoRipple && roleGateway) + { + problem = "You should clear the no ripple flag on your "; + needFix = true; + } + else if (!roleGateway && !bNoRipple) + { + problem = "You should probably set the no ripple flag on your "; + needFix = true; + } + if (needFix) + { + AccountID const peer = + ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit).getIssuer(); + STAmount const peerLimit = + ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit); + problem += to_string(peerLimit.get().currency); + problem += " line to "; + problem += to_string(peerLimit.getIssuer()); + problems.append(problem); - return true; + STAmount limitAmount( + ownedItem->getFieldAmount(bLow ? sfLowLimit : sfHighLimit)); + limitAmount.get().account = peer; + + json::Value& tx = jvTransactions.append(json::ObjectValue); + tx["TransactionType"] = jss::TrustSet; + tx["LimitAmount"] = limitAmount.getJson(JsonOptions::KNone); + tx["Flags"] = bNoRipple ? tfClearNoRipple : tfSetNoRipple; + fillTransaction(context, tx, accountID, seq, *ledger); + + return true; + } } - } - return false; - }); + return false; + }); return result; } diff --git a/src/xrpld/rpc/handlers/admin/UnlList.cpp b/src/xrpld/rpc/handlers/admin/UnlList.cpp index c3835c7ae0..58a5bd3c25 100644 --- a/src/xrpld/rpc/handlers/admin/UnlList.cpp +++ b/src/xrpld/rpc/handlers/admin/UnlList.cpp @@ -14,11 +14,11 @@ namespace xrpl { json::Value doUnlList(RPC::JsonContext& context) { - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); context.app.getValidators().forEachListed( [&unl = obj[jss::unl]](PublicKey const& publicKey, bool trusted) { - json::Value node(json::ValueType::Object); + json::Value node(json::ObjectValue); node[jss::pubkey_validator] = toBase58(TokenType::NodePublic, publicKey); node[jss::trusted] = trusted; diff --git a/src/xrpld/rpc/handlers/admin/data/CanDelete.cpp b/src/xrpld/rpc/handlers/admin/data/CanDelete.cpp index 9ec1157e66..ae67f1f0dd 100644 --- a/src/xrpld/rpc/handlers/admin/data/CanDelete.cpp +++ b/src/xrpld/rpc/handlers/admin/data/CanDelete.cpp @@ -24,7 +24,7 @@ doCanDelete(RPC::JsonContext& context) if (!context.app.getSHAMapStore().advisoryDelete()) return RPC::makeError(RpcNotEnabled); - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); if (context.params.isMember(jss::can_delete)) { diff --git a/src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp b/src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp index de1e4439cf..4b15dbdcaf 100644 --- a/src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp +++ b/src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp @@ -15,7 +15,7 @@ namespace xrpl { json::Value doLedgerRequest(RPC::JsonContext& context) { - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; auto res = RPC::getOrAcquireLedger(context); if (!res.has_value()) diff --git a/src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp b/src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp index 0849bad944..4ef16c4f97 100644 --- a/src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp +++ b/src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp @@ -32,7 +32,7 @@ validationSeed(json::Value const& params) json::Value doValidationCreate(RPC::JsonContext& context) { - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); auto seed = validationSeed(context.params); diff --git a/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp b/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp index c783319049..3d670b9818 100644 --- a/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp +++ b/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp @@ -126,7 +126,7 @@ walletPropose(json::Value const& params) auto const publicKey = generateKeyPair(*keyType, *seed).first; - json::Value obj(json::ValueType::Object); + json::Value obj(json::ObjectValue); auto const seed1751 = seedAs1751(*seed); auto const seedHex = strHex(*seed); diff --git a/src/xrpld/rpc/handlers/admin/log/LogLevel.cpp b/src/xrpld/rpc/handlers/admin/log/LogLevel.cpp index 1ff5aa1a27..a18fd8cc89 100644 --- a/src/xrpld/rpc/handlers/admin/log/LogLevel.cpp +++ b/src/xrpld/rpc/handlers/admin/log/LogLevel.cpp @@ -19,13 +19,13 @@ json::Value doLogLevel(RPC::JsonContext& context) { // log_level - if (not context.params.isMember(jss::severity)) + if (!context.params.isMember(jss::severity)) { // get log severities - json::Value ret(json::ValueType::Object); - json::Value lev(json::ValueType::Object); + json::Value ret(json::ObjectValue); + json::Value lev(json::ObjectValue); - lev[jss::base] = Logs::toString(context.app.getLogs().threshold()); + lev[jss::base] = Logs::toString(Logs::fromSeverity(context.app.getLogs().threshold())); std::vector> const logTable( context.app.getLogs().partitionSeverities()); for (auto const& [k, v] : logTable) @@ -35,17 +35,18 @@ doLogLevel(RPC::JsonContext& context) return ret; } - auto const severity = Logs::fromString(context.params[jss::severity].asString()); + LogSeverity const sv(Logs::fromString(context.params[jss::severity].asString())); - if (not severity.has_value()) + if (sv == LSInvalid) return rpcError(RpcInvalidParams); + auto severity = Logs::toSeverity(sv); // log_level severity - if (not context.params.isMember(jss::partition)) + if (!context.params.isMember(jss::partition)) { // set base log threshold - context.app.getLogs().threshold(*severity); - return json::ValueType::Object; + context.app.getLogs().threshold(severity); + return json::ObjectValue; } // log_level partition severity base? @@ -56,14 +57,14 @@ doLogLevel(RPC::JsonContext& context) if (boost::iequals(partition, "base")) { - context.app.getLogs().threshold(*severity); + context.app.getLogs().threshold(severity); } else { - context.app.getLogs().get(partition).threshold(*severity); + context.app.getLogs().get(partition).threshold(severity); } - return json::ValueType::Object; + return json::ObjectValue; } return rpcError(RpcInvalidParams); diff --git a/src/xrpld/rpc/handlers/admin/peer/Connect.cpp b/src/xrpld/rpc/handlers/admin/peer/Connect.cpp index 568dcdaa26..cfa79eeb82 100644 --- a/src/xrpld/rpc/handlers/admin/peer/Connect.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/Connect.cpp @@ -32,7 +32,7 @@ doConnect(RPC::JsonContext& context) return RPC::missingFieldError(jss::ip); if (context.params.isMember(jss::port) && - !context.params[jss::port].isConvertibleTo(json::ValueType::Int)) + !context.params[jss::port].isConvertibleTo(json::IntValue)) { return rpcError(RpcInvalidParams); } @@ -45,7 +45,7 @@ doConnect(RPC::JsonContext& context) } else { - iPort = kDefaultPeerPort; + iPort = kDEFAULT_PEER_PORT; } auto const ipStr = context.params[jss::ip].asString(); diff --git a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp index 23b0d094b4..b437d17c6a 100644 --- a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp @@ -59,7 +59,7 @@ doPeerReservationsAdd(RPC::JsonContext& context) auto const previous = context.app.getPeerReservations().insertOrAssign( PeerReservation{.nodeId = nodeId, .description = desc}); - json::Value result{json::ValueType::Object}; + json::Value result{json::ObjectValue}; if (previous) { result[jss::previous] = previous->toJson(); diff --git a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp index 40042a0390..374170b135 100644 --- a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp @@ -31,7 +31,7 @@ doPeerReservationsDel(RPC::JsonContext& context) auto const previous = context.app.getPeerReservations().erase(nodeId); - json::Value result{json::ValueType::Object}; + json::Value result{json::ObjectValue}; if (previous) { result[jss::previous] = previous->toJson(); diff --git a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp index 95da4c8567..a9323340f9 100644 --- a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp @@ -12,8 +12,8 @@ doPeerReservationsList(RPC::JsonContext& context) auto const& reservations = context.app.getPeerReservations().list(); // Enumerate the reservations in context.app.getPeerReservations() // as a json::Value. - json::Value result{json::ValueType::Object}; - json::Value& jaReservations = result[jss::reservations] = json::ValueType::Array; + json::Value result{json::ObjectValue}; + json::Value& jaReservations = result[jss::reservations] = json::ArrayValue; for (auto const& reservation : reservations) { jaReservations.append(reservation.toJson()); diff --git a/src/xrpld/rpc/handlers/admin/peer/Peers.cpp b/src/xrpld/rpc/handlers/admin/peer/Peers.cpp index ab14325f0e..41132826e4 100644 --- a/src/xrpld/rpc/handlers/admin/peer/Peers.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/Peers.cpp @@ -19,7 +19,7 @@ namespace xrpl { json::Value doPeers(RPC::JsonContext& context) { - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); jvResult[jss::peers] = context.app.getOverlay().json(); @@ -47,7 +47,7 @@ doPeers(RPC::JsonContext& context) auto const now = context.app.getTimeKeeper().now(); auto const self = context.app.nodeIdentity().first; - json::Value& cluster = (jvResult[jss::cluster] = json::ValueType::Object); + json::Value& cluster = (jvResult[jss::cluster] = json::ObjectValue); std::uint32_t const ref = context.app.getFeeTrack().getLoadBase(); context.app.getCluster().forEach([&cluster, now, ref, &self](ClusterNode const& node) { diff --git a/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp b/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp index be3ce13d45..d9b6cfb2eb 100644 --- a/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp +++ b/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp @@ -68,7 +68,7 @@ doChannelAuthorize(RPC::JsonContext& context) return rpcError(RpcChannelMalformed); std::optional const optDrops = - params[jss::amount].isString() ? toUInt64(params[jss::amount].asString()) : std::nullopt; + params[jss::amount].isString() ? toUint64(params[jss::amount].asString()) : std::nullopt; if (!optDrops) return rpcError(RpcChannelAmtMalformed); diff --git a/src/xrpld/rpc/handlers/admin/signing/Sign.cpp b/src/xrpld/rpc/handlers/admin/signing/Sign.cpp index 781e160f54..6953dfd3d8 100644 --- a/src/xrpld/rpc/handlers/admin/signing/Sign.cpp +++ b/src/xrpld/rpc/handlers/admin/signing/Sign.cpp @@ -22,7 +22,7 @@ doSign(RPC::JsonContext& context) return RPC::makeError(RpcNotSupported, "Signing is not supported by this server."); } - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; NetworkOPs::FailHard const failType = NetworkOPs::doFailHard( context.params.isMember(jss::fail_hard) && context.params[jss::fail_hard].asBool()); diff --git a/src/xrpld/rpc/handlers/admin/signing/SignFor.cpp b/src/xrpld/rpc/handlers/admin/signing/SignFor.cpp index 35274d51f4..102cea08b4 100644 --- a/src/xrpld/rpc/handlers/admin/signing/SignFor.cpp +++ b/src/xrpld/rpc/handlers/admin/signing/SignFor.cpp @@ -23,7 +23,7 @@ doSignFor(RPC::JsonContext& context) return RPC::makeError(RpcNotSupported, "Signing is not supported by this server."); } - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; auto const failHard = context.params[jss::fail_hard].asBool(); auto const failType = NetworkOPs::doFailHard(failHard); diff --git a/src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp b/src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp index 341980ba6d..d55d4bb206 100644 --- a/src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp +++ b/src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp @@ -9,7 +9,7 @@ namespace xrpl { json::Value doConsensusInfo(RPC::JsonContext& context) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::info] = context.netOps.getConsensusInfo(); diff --git a/src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp b/src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp index 16e4789025..5cf05ee00f 100644 --- a/src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp +++ b/src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp @@ -9,7 +9,7 @@ namespace xrpl { json::Value doFetchInfo(RPC::JsonContext& context) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); if (context.params.isMember(jss::clear) && context.params[jss::clear].asBool()) { diff --git a/src/xrpld/rpc/handlers/admin/status/GetCounts.cpp b/src/xrpld/rpc/handlers/admin/status/GetCounts.cpp index 789c6dcf17..83a2aa2127 100644 --- a/src/xrpld/rpc/handlers/admin/status/GetCounts.cpp +++ b/src/xrpld/rpc/handlers/admin/status/GetCounts.cpp @@ -47,7 +47,7 @@ getCountsJson(Application& app, int minObjectCount) { auto objectCounts = CountedObjects::getInstance().getCounts(minObjectCount); - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); for (auto const& [k, v] : objectCounts) { diff --git a/src/xrpld/rpc/handlers/ledger/Ledger.cpp b/src/xrpld/rpc/handlers/ledger/Ledger.cpp index 1b096002bd..2b6116da27 100644 --- a/src/xrpld/rpc/handlers/ledger/Ledger.cpp +++ b/src/xrpld/rpc/handlers/ledger/Ledger.cpp @@ -80,13 +80,10 @@ LedgerHandler::check() if (!queue.has_value()) return queue.error(); - options_ = (*full ? static_cast(LedgerFill::Options::Full) : 0) | - (*expand ? static_cast(LedgerFill::Options::Expand) : 0) | - (*transactions ? static_cast(LedgerFill::Options::DumpTxrp) : 0) | - (*accounts ? static_cast(LedgerFill::Options::DumpState) : 0) | - (*binary ? static_cast(LedgerFill::Options::Binary) : 0) | - (*ownerFunds ? static_cast(LedgerFill::Options::OwnerFunds) : 0) | - (*queue ? static_cast(LedgerFill::Options::DumpQueue) : 0); + options_ = (*full ? LedgerFill::Full : 0) | (*expand ? LedgerFill::Expand : 0) | + (*transactions ? LedgerFill::DumpTxrp : 0) | (*accounts ? LedgerFill::DumpState : 0) | + (*binary ? LedgerFill::Binary : 0) | (*ownerFunds ? LedgerFill::OwnerFunds : 0) | + (*queue ? LedgerFill::DumpQueue : 0); bool const needsLedger = params.isMember(jss::ledger) || params.isMember(jss::ledger_hash) || params.isMember(jss::ledger_index); @@ -106,7 +103,8 @@ LedgerHandler::check() { return RpcTooBusy; } - context_.loadType = binary ? Resource::kFeeMediumBurdenRpc : Resource::kFeeHeavyBurdenRpc; + context_.loadType = + binary ? Resource::kFEE_MEDIUM_BURDEN_RPC : Resource::kFEE_HEAVY_BURDEN_RPC; } if (*queue) @@ -136,19 +134,19 @@ LedgerHandler::writeResult(json::Value& value) { auto& master = context_.app.getLedgerMaster(); { - auto& closed = value[jss::closed] = json::ValueType::Object; + auto& closed = value[jss::closed] = json::ObjectValue; addJson(closed, {*master.getClosedLedger(), &context_, 0}); } { - auto& open = value[jss::open] = json::ValueType::Object; + auto& open = value[jss::open] = json::ObjectValue; addJson(open, {*master.getCurrentLedger(), &context_, 0}); } } - json::Value warnings{json::ValueType::Array}; + json::Value warnings{json::ArrayValue}; if (context_.params.isMember(jss::type)) { - json::Value& w = warnings.append(json::ValueType::Object); + json::Value& w = warnings.append(json::ObjectValue); w[jss::id] = WarnRpcFieldsDeprecated; w[jss::message] = "Some fields from your request are deprecated. Please check the " diff --git a/src/xrpld/rpc/handlers/ledger/Ledger.h b/src/xrpld/rpc/handlers/ledger/Ledger.h index 719e635170..2ac9b99a06 100644 --- a/src/xrpld/rpc/handlers/ledger/Ledger.h +++ b/src/xrpld/rpc/handlers/ledger/Ledger.h @@ -40,13 +40,13 @@ public: // NOLINTBEGIN(readability-identifier-naming) static constexpr char name[] = "ledger"; - static constexpr unsigned minApiVer = RPC::kApiMinimumSupportedVersion; + static constexpr unsigned minApiVer = RPC::kAPI_MINIMUM_SUPPORTED_VERSION; - static constexpr unsigned maxApiVer = RPC::kApiMaximumValidVersion; + static constexpr unsigned maxApiVer = RPC::kAPI_MAXIMUM_VALID_VERSION; static constexpr Role role = Role::USER; - static constexpr Condition condition = Condition::NoCondition; + static constexpr Condition condition = NoCondition; // NOLINTEND(readability-identifier-naming) private: diff --git a/src/xrpld/rpc/handlers/ledger/LedgerData.cpp b/src/xrpld/rpc/handlers/ledger/LedgerData.cpp index 64ab30374b..f450c88dab 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerData.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerData.cpp @@ -82,8 +82,8 @@ doLedgerData(RPC::JsonContext& context) if (!isMarker) { // Return base ledger data on first query - jvResult[jss::ledger] = getJson(LedgerFill( - *lpLedger, &context, isBinary ? static_cast(LedgerFill::Options::Binary) : 0)); + jvResult[jss::ledger] = + getJson(LedgerFill(*lpLedger, &context, isBinary ? LedgerFill::Options::Binary : 0)); } auto [rpcStatus, type] = RPC::chooseLedgerEntryType(params); @@ -94,9 +94,9 @@ doLedgerData(RPC::JsonContext& context) return jvResult; } json::Value& nodes = jvResult[jss::state]; - if (nodes.type() == json::ValueType::Null) + if (nodes.type() == json::NullValue) { - nodes = json::Value(json::ValueType::Array); + nodes = json::Value(json::ArrayValue); } auto e = lpLedger->sles.end(); @@ -115,13 +115,13 @@ doLedgerData(RPC::JsonContext& context) { if (isBinary) { - json::Value& entry = nodes.append(json::ValueType::Object); + json::Value& entry = nodes.append(json::ObjectValue); entry[jss::data] = serializeHex(*sle); entry[jss::index] = to_string(sle->key()); } else { - json::Value& entry = nodes.append(sle->getJson(JsonOptions::Values::None)); + json::Value& entry = nodes.append(sle->getJson(JsonOptions::KNone)); entry[jss::index] = to_string(sle->key()); } } diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp index 9a9119d2ba..a5fcee7a5e 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp @@ -203,7 +203,7 @@ parseCredential( return Unexpected(issuer.error()); auto const credType = LedgerEntryHelpers::requiredHexBlob( - cred, jss::credential_type, kMaxCredentialTypeLength, "malformedRequest"); + cred, jss::credential_type, kMAX_CREDENTIAL_TYPE_LENGTH, "malformedRequest"); if (!credType) return Unexpected(credType.error()); @@ -244,7 +244,7 @@ parseAuthorizeCredentials(json::Value const& jv) } std::uint32_t const n = jv.size(); - if (n > kMaxCredentialsArraySize) + if (n > kMAX_CREDENTIALS_ARRAY_SIZE) { return Unexpected( LedgerEntryHelpers::malformedError( @@ -283,7 +283,10 @@ parseAuthorizeCredentials(json::Value const& jv) return Unexpected(issuer.error()); auto const credentialType = LedgerEntryHelpers::requiredHexBlob( - jo, jss::credential_type, kMaxCredentialTypeLength, "malformedAuthorizedCredentials"); + jo, + jss::credential_type, + kMAX_CREDENTIAL_TYPE_LENGTH, + "malformedAuthorizedCredentials"); if (!credentialType) return Unexpected(credentialType.error()); @@ -374,7 +377,7 @@ parseDirectoryNode( } if (params.isMember(jss::sub_index) && - (!params[jss::sub_index].isConvertibleTo(json::ValueType::UInt) || + (!params[jss::sub_index].isConvertibleTo(json::UintValue) || params[jss::sub_index].isBool())) { return LedgerEntryHelpers::invalidFieldError("malformedRequest", jss::sub_index, "number"); @@ -833,7 +836,7 @@ struct LedgerEntry json::Value doLedgerEntry(RPC::JsonContext& context) { - static auto kLedgerEntryParsers = std::to_array({ + static auto kLEDGER_ENTRY_PARSERS = std::to_array({ #pragma push_macro("LEDGER_ENTRY") #undef LEDGER_ENTRY @@ -856,7 +859,7 @@ doLedgerEntry(RPC::JsonContext& context) auto const hasMoreThanOneMember = [&]() { int count = 0; - for (auto const& ledgerEntry : kLedgerEntryParsers) + for (auto const& ledgerEntry : kLEDGER_ENTRY_PARSERS) { if (context.params.isMember(ledgerEntry.fieldName)) { @@ -885,7 +888,7 @@ doLedgerEntry(RPC::JsonContext& context) try { bool found = false; - for (auto const& ledgerEntry : kLedgerEntryParsers) + for (auto const& ledgerEntry : kLEDGER_ENTRY_PARSERS) { if (context.params.isMember(ledgerEntry.fieldName)) { @@ -967,7 +970,7 @@ doLedgerEntry(RPC::JsonContext& context) } else { - jvResult[jss::node] = sleNode->getJson(JsonOptions::Values::None); + jvResult[jss::node] = sleNode->getJson(JsonOptions::KNone); } return jvResult; diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h index e8e295ca2c..a5b83e8501 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h @@ -17,7 +17,7 @@ namespace xrpl::LedgerEntryHelpers { inline Unexpected missingFieldError(json::StaticString const field, std::optional err = std::nullopt) { - json::Value json = json::ValueType::Object; + json::Value json = json::ObjectValue; json[jss::error] = err.value_or("malformedRequest"); json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::missingFieldMessage(std::string(field.cStr())); @@ -27,7 +27,7 @@ missingFieldError(json::StaticString const field, std::optional err inline Unexpected invalidFieldError(std::string const& err, json::StaticString const field, std::string const& type) { - json::Value json = json::ValueType::Object; + json::Value json = json::ObjectValue; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::expectedFieldMessage(field, type); @@ -37,7 +37,7 @@ invalidFieldError(std::string const& err, json::StaticString const field, std::s inline Unexpected malformedError(std::string const& err, std::string const& message) { - json::Value json = json::ValueType::Object; + json::Value json = json::ObjectValue; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = message; diff --git a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp index b9f4a42880..73dfb178bc 100644 --- a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp @@ -57,7 +57,7 @@ toIso8601(NetClock::time_point tp) return date::format( "%Y-%Om-%dT%H:%M:%OS%z", date::sys_time( - system_clock::time_point{tp.time_since_epoch() + kEpochOffset})); + system_clock::time_point{tp.time_since_epoch() + kEPOCH_OFFSET})); } json::Value @@ -76,7 +76,7 @@ doAMMInfo(RPC::JsonContext& context) std::optional accountID; Asset asset1; Asset asset2; - SLE::const_pointer amm; + std::shared_ptr amm; }; auto getValuesFromContextParams = [&]() -> Expected { @@ -85,13 +85,13 @@ doAMMInfo(RPC::JsonContext& context) std::optional asset2; std::optional ammID; - static constexpr auto kInvalid = [](json::Value const& params) -> bool { + constexpr auto kINVALID = [](json::Value const& params) -> bool { return (params.isMember(jss::asset) != params.isMember(jss::asset2)) || (params.isMember(jss::asset) == params.isMember(jss::amm_account)); }; // NOTE, identical check for apVersion >= 3 below - if (context.apiVersion < 3 && kInvalid(params)) + if (context.apiVersion < 3 && kINVALID(params)) return Unexpected(RpcInvalidParams); if (params.isMember(jss::asset)) @@ -139,7 +139,7 @@ doAMMInfo(RPC::JsonContext& context) } // NOTE, identical check for apVersion < 3 above - if (context.apiVersion >= 3 && kInvalid(params)) + if (context.apiVersion >= 3 && kINVALID(params)) return Unexpected(RpcInvalidParams); XRPL_ASSERT( @@ -194,7 +194,7 @@ doAMMInfo(RPC::JsonContext& context) lptAMMBalance.setJson(ammResult[jss::lp_token]); ammResult[jss::trading_fee] = (*amm)[sfTradingFee]; ammResult[jss::account] = to_string(ammAccountID); - json::Value voteSlots(json::ValueType::Array); + json::Value voteSlots(json::ArrayValue); if (amm->isFieldPresent(sfVoteSlots)) { for (auto const& voteEntry : amm->getFieldArray(sfVoteSlots)) @@ -219,7 +219,7 @@ doAMMInfo(RPC::JsonContext& context) json::Value auction; auto const timeSlot = ammAuctionTimeSlot( ledger->header().parentCloseTime.time_since_epoch().count(), auctionSlot); - auction[jss::time_interval] = timeSlot ? *timeSlot : kAuctionSlotTimeIntervals; + auction[jss::time_interval] = timeSlot ? *timeSlot : kAUCTION_SLOT_TIME_INTERVALS; auctionSlot[sfPrice].setJson(auction[jss::price]); auction[jss::discounted_fee] = auctionSlot[sfDiscountedFee]; auction[jss::account] = to_string(auctionSlot.getAccountID(sfAccount)); diff --git a/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp index 5d031c2c74..2c9c53620c 100644 --- a/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp +++ b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp @@ -242,25 +242,25 @@ doBookOffers(RPC::JsonContext& context) } unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kBookOffers, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kBOOK_OFFERS, context)) return *err; bool const bProof(context.params.isMember(jss::proof)); json::Value const jvMarker( context.params.isMember(jss::marker) ? context.params[jss::marker] - : json::Value(json::ValueType::Null)); + : json::Value(json::NullValue)); context.netOps.getBookPage( lpLedger, {book.in, book.out, domain}, - takerID ? *takerID : beast::kZero, + takerID ? *takerID : beast::kZERO, bProof, limit, jvMarker, jvResult); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return jvResult; } diff --git a/src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp index 343d539277..7e9f891e7f 100644 --- a/src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp +++ b/src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp @@ -86,11 +86,11 @@ doDepositAuthorized(RPC::JsonContext& context) return result; } - bool const reqAuth = sleDest->isFlag(lsfDepositAuth) && (srcAcct != dstAcct); + bool const reqAuth = ((sleDest->getFlags() & lsfDepositAuth) != 0u) && (srcAcct != dstAcct); bool const credentialsPresent = params.isMember(jss::credentials); std::set> sorted; - std::vector lifeExtender; + std::vector> lifeExtender; if (credentialsPresent) { auto const& creds(params[jss::credentials]); @@ -101,7 +101,7 @@ doDepositAuthorized(RPC::JsonContext& context) RPC::expectedFieldMessage( jss::credentials, "is non-empty array of CredentialID(hash256)")); } - if (creds.size() > kMaxCredentialsArraySize) + if (creds.size() > kMAX_CREDENTIALS_ARRAY_SIZE) { return RPC::makeError( RpcInvalidParams, RPC::expectedFieldMessage(jss::credentials, "array too long")); @@ -128,20 +128,20 @@ doDepositAuthorized(RPC::JsonContext& context) jss::credentials, "an array of CredentialID(hash256)")); } - SLE::const_pointer sleCred = ledger->read(keylet::credential(credH)); + std::shared_ptr sleCred = ledger->read(keylet::credential(credH)); if (!sleCred) { RPC::injectError(RpcBadCredentials, "credentials don't exist", result); return result; } - if (!sleCred->isFlag(lsfAccepted)) + if ((sleCred->getFlags() & lsfAccepted) == 0u) { RPC::injectError(RpcBadCredentials, "credentials aren't accepted", result); return result; } - if (credentials::checkExpired(*sleCred, ledger->header().parentCloseTime)) + if (credentials::checkExpired(sleCred, ledger->header().parentCloseTime)) { RPC::injectError(RpcBadCredentials, "credentials are expired", result); return result; diff --git a/src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp index 6a75277b1b..1d34ca21b2 100644 --- a/src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp +++ b/src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp @@ -48,10 +48,11 @@ using Prices = static void iteratePriceData( RPC::JsonContext& context, - SLE::const_ref sle, + std::shared_ptr const& sle, std::function const& f) { - static constexpr std::uint8_t kMaxHistory = 3; + using Meta = std::shared_ptr; + constexpr std::uint8_t kMAX_HISTORY = 3; bool isNew = false; std::uint8_t history = 0; @@ -72,7 +73,7 @@ iteratePriceData( // for the Oracle is not found in the inner loop STObject const* prevChain = nullptr; - std::shared_ptr meta = nullptr; + Meta meta = nullptr; while (true) { if (prevChain == chain) @@ -81,7 +82,7 @@ iteratePriceData( if ((oracle == nullptr) || f(*oracle) || isNew) return; - if (++history > kMaxHistory) + if (++history > kMAX_HISTORY) return; uint256 const prevTx = chain->getFieldH256(sfPreviousTxnID); @@ -92,8 +93,6 @@ iteratePriceData( return; // LCOV_EXCL_LINE meta = ledger->txRead(prevTx).second; - if (!meta) - return; prevChain = chain; for (STObject const& node : meta->getFieldArray(sfAffectedNodes)) @@ -153,11 +152,11 @@ doGetAggregatePrice(RPC::JsonContext& context) json::Value result; auto const& params(context.params); - static constexpr std::uint16_t kMaxOracles = 200; + constexpr std::uint16_t kMAX_ORACLES = 200; if (!params.isMember(jss::oracles)) return RPC::missingFieldError(jss::oracles); if (!params[jss::oracles].isArray() || params[jss::oracles].size() == 0 || - params[jss::oracles].size() > kMaxOracles) + params[jss::oracles].size() > kMAX_ORACLES) { RPC::injectError(RpcOracleMalformed, result); return result; @@ -216,7 +215,7 @@ doGetAggregatePrice(RPC::JsonContext& context) return result; } if (params.isMember(jss::trim) && - (std::get(trim) == 0 || std::get(trim) > kMaxTrim)) + (std::get(trim) == 0 || std::get(trim) > kMAX_TRIM)) { RPC::injectError(RpcInvalidParams, result); return result; @@ -342,11 +341,11 @@ doGetAggregatePrice(RPC::JsonContext& context) auto const middle = size / 2; if ((size % 2) == 0) { - static STAmount const kTwo{noIssue(), 2, 0}; + static STAmount const kTWO{noIssue(), 2, 0}; auto it = itAdvance(prices.right.begin(), middle - 1); auto const& a1 = it->first; auto const& a2 = (++it)->first; - return divide(a1 + a2, kTwo, noIssue()); + return divide(a1 + a2, kTWO, noIssue()); } return itAdvance(prices.right.begin(), middle)->first; }(); diff --git a/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h b/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h index 8529ec2d2c..ed68ae3ac1 100644 --- a/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h +++ b/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h @@ -17,9 +17,12 @@ namespace xrpl { inline void -appendNftOfferJson(Application const& app, SLE::const_ref offer, json::Value& offers) +appendNftOfferJson( + Application const& app, + std::shared_ptr const& offer, + json::Value& offers) { - json::Value& obj(offers.append(json::ValueType::Object)); + json::Value& obj(offers.append(json::ObjectValue)); obj[jss::nft_offer_index] = to_string(offer->key()); obj[jss::flags] = (*offer)[sfFlags]; @@ -45,7 +48,7 @@ inline json::Value enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const& directory) { unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::kNftOffers, context)) + if (auto err = readLimitField(limit, RPC::Tuning::kNFT_OFFERS, context)) return *err; std::shared_ptr ledger; @@ -59,9 +62,9 @@ enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const json::Value result; result[jss::nft_id] = to_string(nftId); - json::Value& jsonOffers(result[jss::offers] = json::ValueType::Array); + json::Value& jsonOffers(result[jss::offers] = json::ArrayValue); - std::vector offers; + std::vector> offers; unsigned int reserve(limit); uint256 startAfter; std::uint64_t startHint = 0; @@ -94,7 +97,12 @@ enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const } if (!forEachItemAfter( - *ledger, directory, startAfter, startHint, reserve, [&offers](SLE::const_ref offer) { + *ledger, + directory, + startAfter, + startHint, + reserve, + [&offers](std::shared_ptr const& offer) { if (offer->getType() == ltNFTOKEN_OFFER) { offers.emplace_back(offer); @@ -117,7 +125,7 @@ enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const for (auto const& offer : offers) appendNftOfferJson(context.app, offer, jsonOffers); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; return result; } diff --git a/src/xrpld/rpc/handlers/orderbook/PathFind.cpp b/src/xrpld/rpc/handlers/orderbook/PathFind.cpp index 3a6b52ee98..da338dfcc8 100644 --- a/src/xrpld/rpc/handlers/orderbook/PathFind.cpp +++ b/src/xrpld/rpc/handlers/orderbook/PathFind.cpp @@ -15,7 +15,7 @@ namespace xrpl { json::Value doPathFind(RPC::JsonContext& context) { - if (context.app.config().pathSearchMax == 0) + if (context.app.config().PATH_SEARCH_MAX == 0) return rpcError(RpcNotSupported); auto lpLedger = context.ledgerMaster.getClosedLedger(); @@ -34,7 +34,7 @@ doPathFind(RPC::JsonContext& context) if (sSubCommand == "create") { - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; context.infoSub->clearRequest(); return context.app.getPathRequestManager().makePathRequest( context.infoSub, lpLedger, context.params); diff --git a/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp b/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp index b7edfb6dbe..316f26fa32 100644 --- a/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp +++ b/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp @@ -23,10 +23,10 @@ namespace xrpl { json::Value doRipplePathFind(RPC::JsonContext& context) { - if (context.app.config().pathSearchMax == 0) + if (context.app.config().PATH_SEARCH_MAX == 0) return rpcError(RpcNotSupported); - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; std::shared_ptr lpLedger; json::Value jvResult; @@ -37,7 +37,7 @@ doRipplePathFind(RPC::JsonContext& context) // No ledger specified, use pathfinding defaults // and dispatch to pathfinding engine if (context.app.getLedgerMaster().getValidatedLedgerAge() > - RPC::Tuning::kMaxValidatedLedgerAge) + RPC::Tuning::kMAX_VALIDATED_LEDGER_AGE) { if (context.apiVersion == 1) return rpcError(RpcNoNetwork); diff --git a/src/xrpld/rpc/handlers/server_info/Feature.cpp b/src/xrpld/rpc/handlers/server_info/Feature.cpp index bd7198b61c..4de07297d4 100644 --- a/src/xrpld/rpc/handlers/server_info/Feature.cpp +++ b/src/xrpld/rpc/handlers/server_info/Feature.cpp @@ -47,7 +47,7 @@ doFeature(RPC::JsonContext& context) features[to_string(h)][jss::majority] = t.time_since_epoch().count(); } - json::Value jvReply = json::ValueType::Object; + json::Value jvReply = json::ObjectValue; jvReply[jss::features] = features; return jvReply; } diff --git a/src/xrpld/rpc/handlers/server_info/Fee.cpp b/src/xrpld/rpc/handlers/server_info/Fee.cpp index 1fe5476d50..a3847d743a 100644 --- a/src/xrpld/rpc/handlers/server_info/Fee.cpp +++ b/src/xrpld/rpc/handlers/server_info/Fee.cpp @@ -11,7 +11,7 @@ json::Value doFee(RPC::JsonContext& context) { auto result = context.app.getTxQ().doRPC(context.app); - if (result.type() == json::ValueType::Object) + if (result.type() == json::ObjectValue) return result; // LCOV_EXCL_START diff --git a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp index aa23a7af26..ca887bb0c8 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp @@ -78,7 +78,7 @@ ServerDefinitions::translate(std::string const& inp) return replace("UINT", "UInt"); } - static std::unordered_map const kReplacements{ + static std::unordered_map const kREPLACEMENTS{ {"OBJECT", "STObject"}, {"ARRAY", "STArray"}, {"ACCOUNT", "AccountID"}, @@ -89,7 +89,7 @@ ServerDefinitions::translate(std::string const& inp) {"XCHAIN_BRIDGE", "XChainBridge"}, }; - if (auto const& it = kReplacements.find(inp); it != kReplacements.end()) + if (auto const& it = kREPLACEMENTS.find(inp); it != kREPLACEMENTS.end()) { return std::string(it->second); } @@ -122,14 +122,14 @@ ServerDefinitions::translate(std::string const& inp) return out; }; -ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} +ServerDefinitions::ServerDefinitions() : defs_{json::ObjectValue} { // populate SerializedTypeID names and values - defs_[jss::TYPES] = json::ValueType::Object; + defs_[jss::TYPES] = json::ObjectValue; defs_[jss::TYPES]["Done"] = -1; std::map typeMap{{-1, "Done"}}; - for (auto const& [rawName, typeValue] : kSTypeMap) + for (auto const& [rawName, typeValue] : kS_TYPE_MAP) { std::string const typeName = translate(std::string(rawName).substr(4) /* remove STI_ */); defs_[jss::TYPES][typeName] = typeValue; @@ -137,7 +137,7 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate LedgerEntryType names and values - defs_[jss::LEDGER_ENTRY_TYPES] = json::ValueType::Object; + defs_[jss::LEDGER_ENTRY_TYPES] = json::ObjectValue; defs_[jss::LEDGER_ENTRY_TYPES][jss::Invalid] = -1; for (auto const& f : LedgerFormats::getInstance()) @@ -146,14 +146,26 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate SField serialization data - defs_[jss::FIELDS] = json::ValueType::Array; + defs_[jss::FIELDS] = json::ArrayValue; uint32_t i = 0; + { + json::Value a = json::ArrayValue; + a[0U] = "Generic"; + json::Value v = json::ObjectValue; + v[jss::nth] = 0; + v[jss::isVLEncoded] = false; + v[jss::isSerialized] = false; + v[jss::isSigningField] = false; + v[jss::type] = "Unknown"; + a[1U] = v; + defs_[jss::FIELDS][i++] = a; + } { - json::Value a = json::ValueType::Array; + json::Value a = json::ArrayValue; a[0U] = "Invalid"; - json::Value v = json::ValueType::Object; + json::Value v = json::ObjectValue; v[jss::nth] = -1; v[jss::isVLEncoded] = false; v[jss::isSerialized] = false; @@ -164,9 +176,9 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } { - json::Value a = json::ValueType::Array; + json::Value a = json::ArrayValue; a[0U] = "ObjectEndMarker"; - json::Value v = json::ValueType::Object; + json::Value v = json::ObjectValue; v[jss::nth] = 1; v[jss::isVLEncoded] = false; v[jss::isSerialized] = true; @@ -177,9 +189,9 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } { - json::Value a = json::ValueType::Array; + json::Value a = json::ArrayValue; a[0U] = "ArrayEndMarker"; - json::Value v = json::ValueType::Object; + json::Value v = json::ObjectValue; v[jss::nth] = 1; v[jss::isVLEncoded] = false; v[jss::isSerialized] = true; @@ -190,9 +202,9 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } { - json::Value a = json::ValueType::Array; + json::Value a = json::ArrayValue; a[0U] = "taker_gets_funded"; - json::Value v = json::ValueType::Object; + json::Value v = json::ObjectValue; v[jss::nth] = 258; v[jss::isVLEncoded] = false; v[jss::isSerialized] = false; @@ -203,9 +215,9 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } { - json::Value a = json::ValueType::Array; + json::Value a = json::ArrayValue; a[0U] = "taker_pays_funded"; - json::Value v = json::ValueType::Object; + json::Value v = json::ObjectValue; v[jss::nth] = 259; v[jss::isVLEncoded] = false; v[jss::isSerialized] = false; @@ -215,28 +227,21 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} defs_[jss::FIELDS][i++] = a; } - // copy into a sorted map to ensure deterministic output order (sorted by fieldCode) - static std::map const kSortedFields( - xrpl::SField::getKnownCodeToField().begin(), xrpl::SField::getKnownCodeToField().end()); - - for (auto const& [code, field] : kSortedFields) + for (auto const& [code, field] : xrpl::SField::getKnownCodeToField()) { if (field->fieldName.empty()) continue; - json::Value innerObj = json::ValueType::Object; + json::Value innerObj = json::ObjectValue; - int32_t const type = field->fieldType; + uint32_t type = field->fieldType; innerObj[jss::nth] = field->fieldValue; // whether the field is variable-length encoded this means that the length is included // before the content innerObj[jss::isVLEncoded] = - (type == STI_VL || type == STI_ACCOUNT || type == STI_VECTOR256); - static_assert( - STI_VL == 7U && STI_ACCOUNT == 8U && STI_VECTOR256 == 19U, - "STI_VL, STI_ACCOUNT, STI_VECTOR256 must be 7, 8, 19 respectively"); + (type == 7U /* Blob */ || type == 8U /* AccountID */ || type == 19U /* Vector256 */); // whether the field is included in serialization innerObj[jss::isSerialized] = @@ -249,7 +254,7 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} innerObj[jss::type] = typeMap[type]; - json::Value innerArray = json::ValueType::Array; + json::Value innerArray = json::ArrayValue; innerArray[0U] = field->fieldName; innerArray[1U] = innerObj; @@ -257,7 +262,7 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate TER code names and values - defs_[jss::TRANSACTION_RESULTS] = json::ValueType::Object; + defs_[jss::TRANSACTION_RESULTS] = json::ObjectValue; for (auto const& [code, terInfo] : transResults()) { @@ -265,7 +270,7 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate TxType names and values - defs_[jss::TRANSACTION_TYPES] = json::ValueType::Object; + defs_[jss::TRANSACTION_TYPES] = json::ObjectValue; defs_[jss::TRANSACTION_TYPES][jss::Invalid] = -1; for (auto const& f : TxFormats::getInstance()) { @@ -273,13 +278,13 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate TxFormats - defs_[jss::TRANSACTION_FORMATS] = json::ValueType::Object; + defs_[jss::TRANSACTION_FORMATS] = json::ObjectValue; - defs_[jss::TRANSACTION_FORMATS][jss::common] = json::ValueType::Array; + defs_[jss::TRANSACTION_FORMATS][jss::common] = json::ArrayValue; auto txCommonFields = std::set(); for (auto const& element : TxFormats::getCommonFields()) { - json::Value elementObj = json::ValueType::Object; + json::Value elementObj = json::ObjectValue; elementObj[jss::name] = element.sField().getName(); elementObj[jss::optionality] = element.style(); defs_[jss::TRANSACTION_FORMATS][jss::common].append(elementObj); @@ -289,12 +294,12 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} for (auto const& format : TxFormats::getInstance()) { auto const& soTemplate = format.getSOTemplate(); - json::Value templateArray = json::ValueType::Array; + json::Value templateArray = json::ArrayValue; for (auto const& element : soTemplate) { if (txCommonFields.contains(element.sField().getName())) continue; // skip common fields, already added - json::Value elementObj = json::ValueType::Object; + json::Value elementObj = json::ObjectValue; elementObj[jss::name] = element.sField().getName(); elementObj[jss::optionality] = element.style(); templateArray.append(elementObj); @@ -303,12 +308,12 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} } // populate LedgerFormats - defs_[jss::LEDGER_ENTRY_FORMATS] = json::ValueType::Object; - defs_[jss::LEDGER_ENTRY_FORMATS][jss::common] = json::ValueType::Array; + defs_[jss::LEDGER_ENTRY_FORMATS] = json::ObjectValue; + defs_[jss::LEDGER_ENTRY_FORMATS][jss::common] = json::ArrayValue; auto ledgerCommonFields = std::set(); for (auto const& element : LedgerFormats::getCommonFields()) { - json::Value elementObj = json::ValueType::Object; + json::Value elementObj = json::ObjectValue; elementObj[jss::name] = element.sField().getName(); elementObj[jss::optionality] = element.style(); defs_[jss::LEDGER_ENTRY_FORMATS][jss::common].append(elementObj); @@ -317,12 +322,12 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} for (auto const& format : LedgerFormats::getInstance()) { auto const& soTemplate = format.getSOTemplate(); - json::Value templateArray = json::ValueType::Array; + json::Value templateArray = json::ArrayValue; for (auto const& element : soTemplate) { if (ledgerCommonFields.contains(element.sField().getName())) continue; // skip common fields, already added - json::Value elementObj = json::ValueType::Object; + json::Value elementObj = json::ObjectValue; elementObj[jss::name] = element.sField().getName(); elementObj[jss::optionality] = element.style(); templateArray.append(elementObj); @@ -330,10 +335,10 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} defs_[jss::LEDGER_ENTRY_FORMATS][format.getName()] = templateArray; } - defs_[jss::TRANSACTION_FLAGS] = json::ValueType::Object; + defs_[jss::TRANSACTION_FLAGS] = json::ObjectValue; for (auto const& [name, value] : getAllTxFlags()) { - json::Value txObj = json::ValueType::Object; + json::Value txObj = json::ObjectValue; for (auto const& [flagName, flagValue] : value) { txObj[flagName] = flagValue; @@ -341,10 +346,10 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} defs_[jss::TRANSACTION_FLAGS][name] = txObj; } - defs_[jss::LEDGER_ENTRY_FLAGS] = json::ValueType::Object; + defs_[jss::LEDGER_ENTRY_FLAGS] = json::ObjectValue; for (auto const& [name, value] : getAllLedgerFlags()) { - json::Value ledgerObj = json::ValueType::Object; + json::Value ledgerObj = json::ObjectValue; for (auto const& [flagName, flagValue] : value) { ledgerObj[flagName] = flagValue; @@ -352,7 +357,7 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} defs_[jss::LEDGER_ENTRY_FLAGS][name] = ledgerObj; } - defs_[jss::ACCOUNT_SET_FLAGS] = json::ValueType::Object; + defs_[jss::ACCOUNT_SET_FLAGS] = json::ObjectValue; for (auto const& [name, value] : getAsfFlagMap()) { defs_[jss::ACCOUNT_SET_FLAGS][name] = value; @@ -369,8 +374,8 @@ ServerDefinitions::ServerDefinitions() : defs_{json::ValueType::Object} ServerDefinitions const& getDefinitions() { - static ServerDefinitions const kDefs{}; - return kDefs; + static ServerDefinitions const kDEFS{}; + return kDEFS; } } // namespace detail @@ -396,7 +401,7 @@ doServerDefinitions(RPC::JsonContext& context) auto const& defs = detail::getDefinitions(); if (defs.hashMatches(hash)) { - json::Value jv = json::ValueType::Object; + json::Value jv = json::ObjectValue; jv[jss::hash] = to_string(hash); return jv; } diff --git a/src/xrpld/rpc/handlers/server_info/ServerInfo.cpp b/src/xrpld/rpc/handlers/server_info/ServerInfo.cpp index aaad9d2b02..af401cd22f 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerInfo.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerInfo.cpp @@ -11,7 +11,7 @@ namespace xrpl { json::Value doServerInfo(RPC::JsonContext& context) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::info] = context.netOps.getServerInfo( true, diff --git a/src/xrpld/rpc/handlers/server_info/ServerState.cpp b/src/xrpld/rpc/handlers/server_info/ServerState.cpp index acf4e9eb43..a3730ca703 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerState.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerState.cpp @@ -10,7 +10,7 @@ namespace xrpl { json::Value doServerState(RPC::JsonContext& context) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); ret[jss::state] = context.netOps.getServerInfo( false, diff --git a/src/xrpld/rpc/handlers/server_info/Version.h b/src/xrpld/rpc/handlers/server_info/Version.h index 1868df5d40..04c9d0f75c 100644 --- a/src/xrpld/rpc/handlers/server_info/Version.h +++ b/src/xrpld/rpc/handlers/server_info/Version.h @@ -8,7 +8,7 @@ class VersionHandler { public: explicit VersionHandler(JsonContext& c) - : apiVersion_(c.apiVersion), betaEnabled_(c.app.config().betaRpcApi) + : apiVersion_(c.apiVersion), betaEnabled_(c.app.config().BETA_RPC_API) { } @@ -27,13 +27,13 @@ public: // NOLINTBEGIN(readability-identifier-naming) static constexpr char const* name = "version"; - static constexpr unsigned minApiVer = RPC::kApiMinimumSupportedVersion; + static constexpr unsigned minApiVer = RPC::kAPI_MINIMUM_SUPPORTED_VERSION; - static constexpr unsigned maxApiVer = RPC::kApiMaximumValidVersion; + static constexpr unsigned maxApiVer = RPC::kAPI_MAXIMUM_VALID_VERSION; static constexpr Role role = Role::USER; - static constexpr Condition condition = Condition::NoCondition; + static constexpr Condition condition = NoCondition; // NOLINTEND(readability-identifier-naming) private: diff --git a/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp index 93840bb6d6..dee88533af 100644 --- a/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp +++ b/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp @@ -30,7 +30,7 @@ json::Value doSubscribe(RPC::JsonContext& context) { InfoSub::pointer ispSub; - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); if (!context.infoSub && !context.params.isMember(jss::url)) { @@ -197,7 +197,7 @@ doSubscribe(RPC::JsonContext& context) if (!context.app.config().useTxTables()) return rpcError(RpcNotEnabled); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; auto const& req = context.params[jss::account_history_tx_stream]; if (!req.isMember(jss::account) || !req[jss::account].isString()) return rpcError(RpcInvalidParams); @@ -285,13 +285,13 @@ doSubscribe(RPC::JsonContext& context) if ((j.isMember(jss::snapshot) && j[jss::snapshot].asBool()) || (j.isMember(jss::state_now) && j[jss::state_now].asBool())) { - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; std::shared_ptr lpLedger = context.app.getLedgerMaster().getPublishedLedger(); if (lpLedger) { - json::Value const jvMarker = json::Value(json::ValueType::Null); - json::Value jvOffers(json::ValueType::Object); + json::Value const jvMarker = json::Value(json::NullValue); + json::Value jvOffers(json::ObjectValue); auto add = [&](json::StaticString field) { context.netOps.getBookPage( @@ -299,7 +299,7 @@ doSubscribe(RPC::JsonContext& context) field == jss::asks ? reversed(book) : book, takerID ? *takerID : noAccount(), false, - RPC::Tuning::kBookOffers.rDefault, + RPC::Tuning::kBOOK_OFFERS.rDefault, jvMarker, jvOffers); diff --git a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp index 36dae615b3..580f213ec4 100644 --- a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp +++ b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp @@ -21,7 +21,7 @@ json::Value doUnsubscribe(RPC::JsonContext& context) { InfoSub::pointer ispSub; - json::Value jvResult(json::ValueType::Object); + json::Value jvResult(json::ObjectValue); bool removeUrl{false}; if (!context.infoSub && !context.params.isMember(jss::url)) diff --git a/src/xrpld/rpc/handlers/transaction/Simulate.cpp b/src/xrpld/rpc/handlers/transaction/Simulate.cpp index 676f0318a2..a119ea94f6 100644 --- a/src/xrpld/rpc/handlers/transaction/Simulate.cpp +++ b/src/xrpld/rpc/handlers/transaction/Simulate.cpp @@ -61,7 +61,7 @@ getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) return Unexpected( RPC::makeError(RpcSrcActMalformed, RPC::invalidFieldMessage("tx.Account"))); } - SLE::const_pointer const sle = + std::shared_ptr const sle = context.app.getOpenLedger().current()->read(keylet::account(*srcAddressID)); if (!hasTicketSeq && !sle) { @@ -194,7 +194,7 @@ getTxJsonFromParams(json::Value const& params) try { SerialIter sitTrans(makeSlice(*unHexed)); - txJson = STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); + txJson = STObject(std::ref(sitTrans), kSF_GENERIC).getJson(JsonOptions::KNone); } catch (std::runtime_error const&) { @@ -276,7 +276,7 @@ simulateTxn(RPC::JsonContext& context, std::shared_ptr transaction) } else { - jvResult[jss::meta] = result.metadata->getJson(JsonOptions::Values::None); + jvResult[jss::meta] = result.metadata->getJson(JsonOptions::KNone); RPC::insertDeliveredAmount( jvResult[jss::meta], view, transaction->getSTransaction(), *result.metadata); RPC::insertNFTSyntheticInJson( @@ -293,7 +293,7 @@ simulateTxn(RPC::JsonContext& context, std::shared_ptr transaction) } else { - jvResult[jss::tx_json] = transaction->getJson(JsonOptions::Values::None); + jvResult[jss::tx_json] = transaction->getJson(JsonOptions::KNone); } return jvResult; @@ -306,7 +306,7 @@ simulateTxn(RPC::JsonContext& context, std::shared_ptr transaction) json::Value doSimulate(RPC::JsonContext& context) { - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; json::Value txJson; // the tx as a JSON @@ -344,7 +344,7 @@ doSimulate(RPC::JsonContext& context) } catch (std::exception& e) { - json::Value jvResult = json::ValueType::Object; + json::Value jvResult = json::ObjectValue; jvResult[jss::error] = "invalidTransaction"; jvResult[jss::error_exception] = e.what(); return jvResult; @@ -365,7 +365,7 @@ doSimulate(RPC::JsonContext& context) // LCOV_EXCL_START this is just in case, so xrpld doesn't crash catch (std::exception const& e) { - json::Value jvResult = json::ValueType::Object; + json::Value jvResult = json::ObjectValue; jvResult[jss::error] = "internalSimulate"; jvResult[jss::error_exception] = e.what(); return jvResult; diff --git a/src/xrpld/rpc/handlers/transaction/Submit.cpp b/src/xrpld/rpc/handlers/transaction/Submit.cpp index f0c4cb2391..d3ce5c3fc0 100644 --- a/src/xrpld/rpc/handlers/transaction/Submit.cpp +++ b/src/xrpld/rpc/handlers/transaction/Submit.cpp @@ -44,7 +44,7 @@ getFailHard(RPC::JsonContext const& context) json::Value doSubmit(RPC::JsonContext& context) { - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; if (!context.params.isMember(jss::tx_blob)) { @@ -141,7 +141,7 @@ doSubmit(RPC::JsonContext& context) try { - jvResult[jss::tx_json] = transaction->getJson(JsonOptions::Values::None); + jvResult[jss::tx_json] = transaction->getJson(JsonOptions::KNone); jvResult[jss::tx_blob] = strHex(transaction->getSTransaction()->getSerializer().peekData()); if (temUNCERTAIN != transaction->getResult()) diff --git a/src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp b/src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp index cc04ed073e..80ec0c6702 100644 --- a/src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp +++ b/src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp @@ -15,7 +15,7 @@ namespace xrpl { json::Value doSubmitMultiSigned(RPC::JsonContext& context) { - context.loadType = Resource::kFeeHeavyBurdenRpc; + context.loadType = Resource::kFEE_HEAVY_BURDEN_RPC; auto const failHard = context.params[jss::fail_hard].asBool(); auto const failType = NetworkOPs::doFailHard(failHard); diff --git a/src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp b/src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp index bb68226334..c951053c51 100644 --- a/src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp +++ b/src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp @@ -33,7 +33,7 @@ doTransactionEntry(RPC::JsonContext& context) { jvResult[jss::error] = "fieldNotFoundTransaction"; } - else if (jvResult.get(jss::ledger_hash, json::ValueType::Null).isNull()) + else if (jvResult.get(jss::ledger_hash, json::NullValue).isNull()) { // We don't work on ledger current. @@ -60,7 +60,7 @@ doTransactionEntry(RPC::JsonContext& context) { if (context.apiVersion > 1) { - jvResult[jss::tx_json] = sttx->getJson(JsonOptions::Values::DisableApiPriorV2); + jvResult[jss::tx_json] = sttx->getJson(JsonOptions::KDisableApiPriorV2); jvResult[jss::hash] = to_string(sttx->getTransactionID()); if (!lpLedger->open()) @@ -81,14 +81,14 @@ doTransactionEntry(RPC::JsonContext& context) } else { - jvResult[jss::tx_json] = sttx->getJson(JsonOptions::Values::None); + jvResult[jss::tx_json] = sttx->getJson(JsonOptions::KNone); } RPC::insertDeliverMax(jvResult[jss::tx_json], sttx->getTxnType(), context.apiVersion); auto const jsonMeta = (context.apiVersion > 1 ? jss::meta : jss::metadata); if (stobj) - jvResult[jsonMeta] = stobj->getJson(JsonOptions::Values::None); + jvResult[jsonMeta] = stobj->getJson(JsonOptions::KNone); // 'accounts' // 'engine_...' // 'ledger_...' diff --git a/src/xrpld/rpc/handlers/transaction/Tx.cpp b/src/xrpld/rpc/handlers/transaction/Tx.cpp index c065bc268e..cddda6d2c2 100644 --- a/src/xrpld/rpc/handlers/transaction/Tx.cpp +++ b/src/xrpld/rpc/handlers/transaction/Tx.cpp @@ -77,12 +77,12 @@ doTxHelp(RPC::Context& context, TxArgs args) if (args.ledgerRange) { - static constexpr uint16_t kMaxRange = 1000; + constexpr uint16_t kMAX_RANGE = 1000; if (args.ledgerRange->second < args.ledgerRange->first) return {result, RpcInvalidLgrRange}; - if (args.ledgerRange->second - args.ledgerRange->first > kMaxRange) + if (args.ledgerRange->second - args.ledgerRange->first > kMAX_RANGE) return {result, RpcExcessiveLgrRange}; range = ClosedInterval(args.ledgerRange->first, args.ledgerRange->second); @@ -190,7 +190,7 @@ populateJsonResponse( { if (error.toErrorCode() == RpcTxnNotFound && result.searchedAll != TxSearched::Unknown) { - response = json::Value(json::ValueType::Object); + response = json::Value(json::ObjectValue); response[jss::searched_all] = (result.searchedAll == TxSearched::All); error.inject(response); } @@ -205,16 +205,15 @@ populateJsonResponse( auto const& sttx = result.txn->getSTransaction(); if (context.apiVersion > 1) { - static constexpr auto kOptionsJson = - static_cast(JsonOptions::Values::IncludeDate) | - static_cast(JsonOptions::Values::DisableApiPriorV2); + constexpr auto kOPTIONS_JSON = + JsonOptions::KIncludeDate | JsonOptions::KDisableApiPriorV2; if (args.binary) { - response[jss::tx_blob] = result.txn->getJson(kOptionsJson, true); + response[jss::tx_blob] = result.txn->getJson(kOPTIONS_JSON, true); } else { - response[jss::tx_json] = result.txn->getJson(kOptionsJson); + response[jss::tx_json] = result.txn->getJson(kOPTIONS_JSON); RPC::insertDeliverMax( response[jss::tx_json], sttx->getTxnType(), context.apiVersion); } @@ -234,7 +233,7 @@ populateJsonResponse( } else { - response = result.txn->getJson(JsonOptions::Values::IncludeDate, args.binary); + response = result.txn->getJson(JsonOptions::KIncludeDate, args.binary); if (!args.binary) RPC::insertDeliverMax(response, sttx->getTxnType(), context.apiVersion); } @@ -252,7 +251,7 @@ populateJsonResponse( auto& meta = *m; if (meta) { - response[jss::meta] = meta->getJson(JsonOptions::Values::None); + response[jss::meta] = meta->getJson(JsonOptions::KNone); insertDeliveredAmount(response[jss::meta], context, result.txn, *meta); RPC::insertNFTSyntheticInJson(response, sttx, *meta); RPC::insertMPTokenIssuanceID(response[jss::meta], sttx, *meta); diff --git a/src/xrpld/rpc/handlers/transaction/TxHistory.cpp b/src/xrpld/rpc/handlers/transaction/TxHistory.cpp index a45046773c..b7333d0115 100644 --- a/src/xrpld/rpc/handlers/transaction/TxHistory.cpp +++ b/src/xrpld/rpc/handlers/transaction/TxHistory.cpp @@ -21,7 +21,7 @@ doTxHistory(RPC::JsonContext& context) if (!context.app.config().useTxTables()) return rpcError(RpcNotEnabled); - context.loadType = Resource::kFeeMediumBurdenRpc; + context.loadType = Resource::kFEE_MEDIUM_BURDEN_RPC; if (!context.params.isMember(jss::start)) return rpcError(RpcInvalidParams); @@ -39,7 +39,7 @@ doTxHistory(RPC::JsonContext& context) for (auto const& t : trans) { - json::Value txJson = t->getJson(JsonOptions::Values::None); + json::Value txJson = t->getJson(JsonOptions::KNone); RPC::insertDeliverMax(txJson, t->getSTransaction()->getTxnType(), context.apiVersion); txs.append(txJson); } diff --git a/src/xrpld/rpc/handlers/utility/Ping.cpp b/src/xrpld/rpc/handlers/utility/Ping.cpp index 0d34b9e0fc..428b16ddd4 100644 --- a/src/xrpld/rpc/handlers/utility/Ping.cpp +++ b/src/xrpld/rpc/handlers/utility/Ping.cpp @@ -13,7 +13,7 @@ struct JsonContext; json::Value doPing(RPC::JsonContext& context) { - json::Value ret(json::ValueType::Object); + json::Value ret(json::ObjectValue); switch (context.role) { case Role::ADMIN: diff --git a/src/xrpld/rpc/json_body.h b/src/xrpld/rpc/json_body.h index 4520a8bf39..9f881cacbc 100644 --- a/src/xrpld/rpc/json_body.h +++ b/src/xrpld/rpc/json_body.h @@ -56,7 +56,7 @@ struct JsonBody class writer // NOLINT(readability-identifier-naming) -- Boost.Beast body concept name { - std::string bodyString_; + std::string body_string_; public: using const_buffers_type = boost::asio::const_buffer; @@ -65,7 +65,7 @@ struct JsonBody explicit writer( boost::beast::http::header const& fields, value_type const& value) - : bodyString_(to_string(value)) + : body_string_(to_string(value)) { } @@ -81,7 +81,7 @@ struct JsonBody get(boost::beast::error_code& ec) { ec.assign(0, ec.category()); - return {{const_buffers_type{bodyString_.data(), bodyString_.size()}, false}}; + return {{const_buffers_type{body_string_.data(), body_string_.size()}, false}}; } }; }; diff --git a/src/xrpld/shamap/NodeFamily.cpp b/src/xrpld/shamap/NodeFamily.cpp index a1668e80b2..aab36b7ca3 100644 --- a/src/xrpld/shamap/NodeFamily.cpp +++ b/src/xrpld/shamap/NodeFamily.cpp @@ -30,8 +30,8 @@ NodeFamily::NodeFamily(Application& app, CollectorManager& cm) stopwatch(), app.getJournal("NodeFamilyFulLBelowCache"), cm.collector(), - kFullBelowTargetSize, - kFullBelowExpiration)) + kFULL_BELOW_TARGET_SIZE, + kFULL_BELOW_EXPIRATION)) , tnCache_( std::make_shared( "Node family tree node cache",