Compare commits

..

3 Commits

Author SHA1 Message Date
Mayukha Vadari
40992c70eb Merge branch 'develop' into mvadari/rpc-framework 2026-05-13 12:14:10 -04:00
Mayukha Vadari
81da046d12 fix clang-tidy issues 2026-05-13 12:12:13 -04:00
Mayukha Vadari
a5a7f1c3f6 feat: Experimental attempt at RPC validation framework 2026-05-13 12:11:13 -04:00
800 changed files with 11077 additions and 17706 deletions

View File

@@ -171,7 +171,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,23 +179,22 @@ 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)$"

0
.github/scripts/levelization/generate.py vendored Executable file → Normal file
View File

View File

@@ -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

View File

@@ -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."

View File

@@ -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
@@ -126,15 +101,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 +123,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 +136,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"
@@ -251,7 +218,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:
@@ -355,19 +332,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")
)

View File

@@ -127,8 +127,7 @@
"distro_version": "9",
"compiler_name": "gcc",
"compiler_version": "12",
"image_sha": "4c086b9",
"package": true
"image_sha": "4c086b9"
},
{
"distro_name": "rhel",
@@ -170,8 +169,7 @@
"distro_version": "jammy",
"compiler_name": "gcc",
"compiler_version": "12",
"image_sha": "4c086b9",
"package": true
"image_sha": "4c086b9"
},
{
"distro_name": "ubuntu",

View File

@@ -1,101 +0,0 @@
name: Build Nix Docker image
on:
push:
branches:
- develop
paths:
- ".github/workflows/build-nix-image.yml"
- "docker/nix.Dockerfile"
- "flake.nix"
- "flake.lock"
- "nix/**"
pull_request:
paths:
- ".github/workflows/build-nix-image.yml"
- "docker/nix.Dockerfile"
- "flake.nix"
- "flake.lock"
- "nix/**"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
defaults:
run:
shell: bash
env:
UBUNTU_VERSION: "20.04"
RHEL_VERSION: "9"
DEBIAN_VERSION: "bookworm"
jobs:
build:
name: Build and push Nix image (${{ matrix.distro }})
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
matrix:
include:
- distro: nixos
- distro: ubuntu
- distro: rhel
- distro: debian
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Determine base image
id: vars
run: |
case "${{ matrix.distro }}" in
nixos)
echo "base_image=nixos/nix:latest" >> $GITHUB_OUTPUT
;;
ubuntu)
echo "base_image=ubuntu:${UBUNTU_VERSION}" >> $GITHUB_OUTPUT
;;
rhel)
echo "base_image=registry.access.redhat.com/ubi${RHEL_VERSION}/ubi:latest" >> $GITHUB_OUTPUT
;;
debian)
echo "base_image=debian:${DEBIAN_VERSION}" >> $GITHUB_OUTPUT
;;
esac
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
- name: Login to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata
id: meta
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0
with:
images: ghcr.io/xrplf/ci/nix-${{ matrix.distro }}
tags: |
type=sha,prefix=sha-,format=short
type=raw,value=latest
- name: Build and push
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
with:
context: .
file: docker/nix.Dockerfile
platforms: linux/amd64
push: ${{ github.event_name == 'push' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: BASE_IMAGE=${{ steps.vars.outputs.base_image }}

View File

@@ -11,4 +11,4 @@ on:
jobs:
check_title:
if: ${{ github.event.pull_request.draft != true }}
uses: XRPLF/actions/.github/workflows/check-pr-title.yml@291206777251b4d493641b5afbdf7c23009d2988
uses: XRPLF/actions/.github/workflows/check-pr-title.yml@a5d8dd35be543365e90a11358447130c8763871d

View File

@@ -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
@@ -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
@@ -179,7 +168,6 @@ jobs:
- check-rename
- clang-tidy
- build-test
- package
- upload-recipe
- notify-clio
runs-on: ubuntu-latest

View File

@@ -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

View File

@@ -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

View File

@@ -181,7 +181,7 @@ jobs:
- name: Build the binary
working-directory: ${{ env.BUILD_DIR }}
env:
BUILD_NPROC: ${{ steps.nproc.outputs.nproc }}
BUILD_NPROC: ${{ runner.os == 'Linux' && '16' || steps.nproc.outputs.nproc }}
BUILD_TYPE: ${{ inputs.build_type }}
CMAKE_TARGET: ${{ inputs.cmake_target }}
run: |

View File

@@ -176,7 +176,7 @@ jobs:
- name: Create issue
if: ${{ steps.run_clang_tidy.outcome != 'success' && inputs.create_issue_on_failure }}
uses: XRPLF/actions/create-issue@36d450d12d301e8410c1b7936e5de70c291cbe36
uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c
with:
title: "Clang-tidy check failed"
body_file: ${{ env.ISSUE_FILE }}

View File

@@ -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

View File

@@ -70,11 +70,7 @@ repos:
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:

View File

@@ -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:

View File

@@ -23,11 +23,7 @@ include(CompilationEnv)
if(is_gcc)
# GCC-specific fixes
add_compile_options(
-Wno-unknown-pragmas
-Wno-subobject-linkage
-Wno-error=deprecated-declarations
)
add_compile_options(-Wno-unknown-pragmas -Wno-subobject-linkage)
# -Wno-subobject-linkage can be removed when we upgrade GCC version to at least 13.3
elseif(is_clang)
# Clang-specific fixes
@@ -85,11 +81,7 @@ if(only_docs)
endif()
include(deps/Boost)
find_package(OpenSSL 3.5.6 REQUIRED)
set_target_properties(
OpenSSL::SSL
PROPERTIES INTERFACE_COMPILE_DEFINITIONS OPENSSL_NO_SSL2
)
add_subdirectory(external/antithesis-sdk)
find_package(date REQUIRED)
find_package(ed25519 REQUIRED)
@@ -142,7 +134,6 @@ endif()
include(XrplCore)
include(XrplProtocolAutogen)
include(XrplInstall)
include(XrplPackaging)
include(XrplValidatorKeys)
if(tests)

View File

@@ -168,13 +168,7 @@ def main():
if not os.environ.get("TIDY"):
return 0
repo_root = Path(
subprocess.check_output(
["git", "rev-parse", "--show-toplevel"],
cwd=Path(__file__).parent,
text=True,
).strip()
)
repo_root = Path(__file__).parent.parent
files = staged_files(repo_root)
if not files:
return 0

View File

@@ -28,7 +28,7 @@
# https://vl.ripple.com
# https://unl.xrplf.org
# http://127.0.0.1:8000
# file:///etc/xrpld/vl.txt
# file:///etc/opt/xrpld/vl.txt
#
# [validator_list_keys]
#

View File

@@ -527,17 +527,6 @@
#
# The current default (which is subject to change) is 300 seconds.
#
# verify_endpoints = <0 | 1>
#
# 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
#
@@ -1466,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 = ::

View File

@@ -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
)

View File

@@ -10,7 +10,7 @@
"rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86",
"re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1774398111.888",
"protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12",
"openssl/3.5.6#13f8f30151479797ca8a7c014856f849%1775635548.661",
"openssl/3.6.2#4789bbf131b77d0515d15e094c8f697f%1778071755.506",
"nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1775040983.408",
"lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914",
"libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492",
@@ -58,9 +58,6 @@
],
"lz4/[>=1.9.4 <2]": [
"lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504"
],
"sqlite3/3.44.2": [
"sqlite3/3.49.1"
]
},
"config_requires": []

View File

@@ -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

View File

@@ -4,8 +4,6 @@ from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout
from conan import ConanFile
import subprocess
class Xrpl(ConanFile):
name = "xrpl"
@@ -33,7 +31,7 @@ class Xrpl(ConanFile):
"grpc/1.78.1",
"libarchive/3.8.7",
"nudb/2.0.9",
"openssl/3.5.6",
"openssl/3.6.2",
"secp256k1/0.7.1",
"soci/4.0.3",
"zlib/1.3.2",

View File

@@ -63,7 +63,6 @@ words:
- Bougalis
- Britto
- Btrfs
- Buildx
- canonicality
- changespq
- checkme
@@ -99,15 +98,12 @@ words:
- desync
- desynced
- determ
- disablerepo
- distro
- doxyfile
- dxrpl
- enabled
- enablerepo
- endmacro
- exceptioned
- EXPECT_STREQ
- Falco
- fcontext
- finalizers
@@ -165,7 +161,6 @@ words:
- Merkle
- Metafuncton
- misprediction
- missingok
- mptbalance
- MPTDEX
- mptflags
@@ -197,9 +192,7 @@ words:
- NOLINT
- NOLINTNEXTLINE
- nonxrp
- noreplace
- noripple
- notifempty
- nudb
- nullptr
- nunl
@@ -219,7 +212,6 @@ words:
- preauthorize
- preauthorizes
- preclaim
- preun
- protobuf
- protos
- ptrs
@@ -254,14 +246,12 @@ words:
- sfields
- shamap
- shamapitem
- shlibs
- sidechain
- SIGGOOD
- sle
- sles
- soci
- socidb
- SRPMS
- sslws
- statsd
- STATSDCOLLECTOR
@@ -289,8 +279,8 @@ words:
- txn
- txns
- txs
- ubsan
- UBSAN
- ubsan
- umant
- unacquired
- unambiguity
@@ -327,6 +317,7 @@ words:
- xbridge
- xchain
- ximinez
- EXPECT_STREQ
- XMACRO
- xrpkuwait
- xrpl
@@ -334,4 +325,3 @@ words:
- xrplf
- xxhash
- xxhasher
- CGNAT

View File

@@ -1,66 +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}
# 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"
RUN <<EOF
ccache --version
clang-format --version
cmake --version
conan --version
g++ --version
gcc --version
gcovr --version
git --version
make --version
mold --version
ninja --version
perl --version
pkg-config --version
pre-commit --version
python3 --version
run-clang-tidy --help
vim --version
EOF

26
flake.lock generated
View File

@@ -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-glibc231": {
"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-glibc231": "nixpkgs-glibc231"
"nixpkgs": "nixpkgs"
}
}
},

View File

@@ -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-glibc231 = {
url = "github:NixOS/nixpkgs/9cd98386a38891d1074fc18036b842dc4416f562";
flake = false;
};
};
outputs =
{ nixpkgs, nixpkgs-glibc231, ... }:
{ nixpkgs, ... }:
let
forEachSystem = import ./nix/utils.nix { inherit nixpkgs nixpkgs-glibc231; };
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);
};
}

View File

@@ -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
{

View File

@@ -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.

View File

@@ -567,14 +567,14 @@ template <class T>
bool
SharedWeakUnion<T>::isStrong() const
{
return (tp_ & kTagMask) == 0u;
return (tp_ & kTAG_MASK) == 0u;
}
template <class T>
bool
SharedWeakUnion<T>::isWeak() const
{
return (tp_ & kTagMask) != 0u;
return (tp_ & kTAG_MASK) != 0u;
}
template <class T>
@@ -641,7 +641,7 @@ template <class T>
T*
SharedWeakUnion<T>::unsafeGetRawPtr() const
{
return reinterpret_cast<T*>(tp_ & kPtrMask);
return reinterpret_cast<T*>(tp_ & kPTR_MASK);
}
template <class T>
@@ -650,7 +650,7 @@ SharedWeakUnion<T>::unsafeSetRawPtr(T* p, RefStrength rs)
{
tp_ = reinterpret_cast<std::uintptr_t>(p);
if (tp_ && rs == RefStrength::Weak)
tp_ |= kTagMask;
tp_ |= kTAG_MASK;
}
template <class T>

View File

@@ -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<FieldType> refCounts_{kStrongDelta};
mutable std::atomic<FieldType> 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<CountType>((kOne << kStrongCountNumBits) - 1);
static constexpr CountType kMaxWeakValue =
static_cast<CountType>((kOne << kWeakCountNumBits) - 1);
static constexpr CountType kMAX_STRONG_VALUE =
static_cast<CountType>((kONE << kSTRONG_COUNT_NUM_BITS) - 1);
static constexpr CountType kMAX_WEAK_VALUE =
static_cast<CountType>((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<CountType>(v & kStrongMask)}
, weak{static_cast<CountType>((v & kWeakMask) >> kStrongCountNumBits)}
, partialDestroyStartedBit{v & kPartialDestroyStartedMask}
, partialDestroyFinishedBit{v & kPartialDestroyFinishedMask}
: strong{static_cast<CountType>(v & kSTRONG_MASK)}
, weak{static_cast<CountType>((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<IntrusiveRefCounts::FieldType>(weak)
<< IntrusiveRefCounts::kStrongCountNumBits) |
<< IntrusiveRefCounts::kSTRONG_COUNT_NUM_BITS) |
static_cast<IntrusiveRefCounts::FieldType>(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");

View File

@@ -55,8 +55,8 @@ template <class = void>
boost::thread_specific_ptr<detail::LocalValues>&
getLocalValues()
{
static boost::thread_specific_ptr<detail::LocalValues> kTsp(&detail::LocalValues::cleanup);
return kTsp;
static boost::thread_specific_ptr<detail::LocalValues> kTSP(&detail::LocalValues::cleanup);
return kTSP;
}
} // namespace detail

View File

@@ -191,7 +191,7 @@ public:
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;
static constexpr auto kMAXIMUM_MESSAGE_CHARACTERS = 12 * 1024;
static void
format(

View File

@@ -214,12 +214,12 @@ class Number
public:
// The range for the exponent when normalized
static constexpr int kMinExponent = -32768;
static constexpr int kMaxExponent = 32768;
constexpr static int kMIN_EXPONENT = -32768;
constexpr static int kMAX_EXPONENT = 32768;
static constexpr internalrep kMaxRep = std::numeric_limits<rep>::max();
static_assert(kMaxRep == 9'223'372'036'854'775'807);
static_assert(-kMaxRep == std::numeric_limits<rep>::min() + 1);
constexpr static internalrep kMAX_REP = std::numeric_limits<rep>::max();
static_assert(kMAX_REP == 9'223'372'036'854'775'807);
static_assert(-kMAX_REP == std::numeric_limits<rep>::min() + 1);
// May need to make unchecked private
struct Unchecked
@@ -409,26 +409,26 @@ 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
static constexpr Number
constexpr static Number
oneSmall();
/// oneLarge is needed because the ranges are private
static constexpr Number
constexpr static Number
oneLarge();
// And one is needed because it needs to choose between oneSmall and
@@ -445,25 +445,25 @@ private:
static thread_local RoundingMode mode;
// The available ranges for mantissa
static constexpr MantissaRange kSmallRange{MantissaRange::MantissaScale::Small};
static_assert(isPowerOfTen(kSmallRange.min));
static_assert(kSmallRange.min == 1'000'000'000'000'000LL);
static_assert(kSmallRange.max == 9'999'999'999'999'999LL);
static_assert(kSmallRange.log == 15);
static_assert(kSmallRange.min < kMaxRep);
static_assert(kSmallRange.max < kMaxRep);
static constexpr MantissaRange kLargeRange{MantissaRange::MantissaScale::Large};
static_assert(isPowerOfTen(kLargeRange.min));
static_assert(kLargeRange.min == 1'000'000'000'000'000'000ULL);
static_assert(kLargeRange.max == internalrep(9'999'999'999'999'999'999ULL));
static_assert(kLargeRange.log == 18);
static_assert(kLargeRange.min < kMaxRep);
static_assert(kLargeRange.max > kMaxRep);
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<MantissaRange const> kRange;
static thread_local std::reference_wrapper<MantissaRange const> kRANGE;
void
normalize();
@@ -471,7 +471,7 @@ private:
/** 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 <class T>
@@ -521,7 +521,7 @@ 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{})
@@ -552,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;
@@ -573,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;
@@ -671,29 +671,29 @@ 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 <Integral64 T>

View File

@@ -57,10 +57,10 @@ template <class T>
std::shared_ptr<T> const&
SharedWeakCachePointer<T>::getStrong() const
{
static std::shared_ptr<T> const kEmpty;
static std::shared_ptr<T> const kEMPTY;
if (auto p = std::get_if<std::shared_ptr<T>>(&combo_))
return *p;
return kEmpty;
return kEMPTY;
}
template <class T>

View File

@@ -7,11 +7,9 @@
#include <boost/utility/string_view.hpp>
#include <array>
#include <concepts>
#include <cstdint>
#include <optional>
#include <string>
#include <type_traits>
namespace xrpl {
@@ -28,39 +26,28 @@ namespace xrpl {
std::string
sqlBlobLiteral(Blob const& blob);
namespace detail {
template <typename T>
concept SomeChar = std::same_as<std::remove_cvref_t<T>, int8_t> ||
std::same_as<std::remove_cvref_t<T>, char> || std::same_as<std::remove_cvref_t<T>, uint8_t>;
inline constexpr std::array<std::optional<int>, 256> const kDigitLookupTable = []() {
std::array<std::optional<int>, 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<int>
hexCharToInt(SomeChar auto hexChar)
{
return kDigitLookupTable[static_cast<uint8_t>(hexChar)];
}
} // namespace detail
template <class Iterator>
std::optional<Blob>
strUnHex(std::size_t strSize, Iterator begin, Iterator end)
{
static constexpr std::array<int, 256> const kDIGIT_LOOKUP_TABLE = []() {
std::array<int, 256> 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<unsigned char>(*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<unsigned char>((*cHigh << 4) | *cLow));
out.push_back(static_cast<unsigned char>((cHigh << 4) | cLow));
}
return {std::move(out)};

View File

@@ -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};

View File

@@ -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<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
getCacheSize() const
{
std::scoped_lock const lock(mutex_);
return cacheCount_;
return cache_count_;
}
template <
@@ -139,7 +139,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{
std::scoped_lock const lock(mutex_);
cache_.clear();
cacheCount_ = 0;
cache_count_ = 0;
}
template <
@@ -157,7 +157,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{
std::scoped_lock const lock(mutex_);
cache_.clear();
cacheCount_ = 0;
cache_count_ = 0;
hits_ = 0;
misses_ = 0;
}
@@ -213,21 +213,21 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{
std::scoped_lock const lock(mutex_);
if (targetSize_ == 0 || (static_cast<int>(cache_.size()) <= targetSize_))
if (target_size_ == 0 || (static_cast<int>(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<std::thread> workers;
@@ -242,7 +242,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
for (std::thread& worker : workers)
worker.join();
cacheCount_ -= allRemovals;
cache_count_ -= allRemovals;
}
// At this point allStuffToSweep will go out of scope outside the lock
// and decrement the reference count on each strong pointer.
@@ -280,7 +280,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (entry.isCached())
{
--cacheCount_;
--cache_count_;
entry.ptr.convertToWeak();
ret = true;
}
@@ -317,7 +317,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(clock_.now(), data));
++cacheCount_;
++cache_count_;
return false;
}
@@ -366,12 +366,12 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
data = cachedData;
}
++cacheCount_;
++cache_count_;
return true;
}
entry.ptr = data;
++cacheCount_;
++cache_count_;
return false;
}
@@ -477,7 +477,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
auto [it, inserted] = cache_.emplace(
std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now));
if (!inserted)
it->second.lastAccess = now;
it->second.last_access = now;
return inserted;
}
@@ -626,7 +626,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (entry.isCached())
{
// independent of cache size, so not counted as a hit
++cacheCount_;
++cache_count_;
entry.touch(clock_.now());
return entry.ptr.getStrong();
}
@@ -658,7 +658,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (total != 0)
hitRate = (hits_ * 100) / total;
}
stats_.hitRate.set(hitRate);
stats_.hit_rate.set(hitRate);
}
}
@@ -706,7 +706,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
++cit;
}
}
else if (cit->second.lastAccess <= whenExpire)
else if (cit->second.last_access <= whenExpire)
{
// strong, expired
++cacheRemovals;
@@ -773,12 +773,12 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
auto cit = partition.begin();
while (cit != partition.end())
{
if (cit->second.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);
}

View File

@@ -30,8 +30,8 @@ public:
now(); // seconds since xrpld program start
private:
static std::atomic<rep> kNow;
static std::atomic<bool> kStop;
static std::atomic<rep> kNOW;
static std::atomic<bool> kSTOP;
struct UpdateThread : private std::thread
{

View File

@@ -73,12 +73,12 @@ class BaseUInt
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<std::uint32_t, kWidth> data_;
std::array<std::uint32_t, kWIDTH> data_;
public:
//--------------------------------------------------------------------------
@@ -86,8 +86,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 +121,7 @@ public:
iterator
end()
{
return data() + kBytes;
return data() + kBYTES;
}
[[nodiscard]] const_iterator
begin() const
@@ -131,7 +131,7 @@ public:
[[nodiscard]] const_iterator
end() const
{
return data() + kBytes;
return data() + kBYTES;
}
[[nodiscard]] const_iterator
cbegin() const
@@ -141,7 +141,7 @@ public:
[[nodiscard]] const_iterator
cend() const
{
return data() + kBytes;
return data() + kBYTES;
}
/** Value hashing function.
@@ -167,7 +167,7 @@ private:
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.
@@ -336,7 +336,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,7 +348,7 @@ public:
bool
operator!() const
{
return *this == beast::kZero;
return *this == beast::kZERO;
}
constexpr BaseUInt
@@ -356,7 +356,7 @@ public:
{
BaseUInt ret;
for (int i = 0; i < kWidth; i++)
for (int i = 0; i < kWIDTH; i++)
ret.data_[i] = ~data_[i];
return ret;
@@ -365,7 +365,7 @@ public:
BaseUInt&
operator=(std::uint64_t uHost)
{
*this = beast::kZero;
*this = beast::kZERO;
// NOLINTBEGIN(cppcoreguidelines-pro-type-member-init)
union
{
@@ -375,15 +375,15 @@ 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)
{
for (int i = 0; i < kWidth; i++)
for (int i = 0; i < kWIDTH; i++)
data_[i] ^= b.data_[i];
return *this;
@@ -392,7 +392,7 @@ public:
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;
@@ -401,7 +401,7 @@ public:
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;
@@ -411,7 +411,7 @@ public:
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)
@@ -434,7 +434,7 @@ public:
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);
@@ -475,7 +475,7 @@ public:
{
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]);
@@ -526,10 +526,10 @@ public:
return parseHex(std::string_view{str});
}
static constexpr std::size_t
constexpr static std::size_t
size()
{
return kBytes;
return kBYTES;
}
BaseUInt<Bits, Tag>&
@@ -543,17 +543,17 @@ 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;
}
};
@@ -639,7 +639,7 @@ template <std::size_t Bits, class Tag>
inline std::string
toShortString(BaseUInt<Bits, Tag> const& a)
{
static_assert(BaseUInt<Bits, Tag>::kBytes > 4, "For 4 bytes or less, use a native type");
static_assert(BaseUInt<Bits, Tag>::kBYTES > 4, "For 4 bytes or less, use a native type");
return strHex(a.cbegin(), a.cbegin() + 4) + "...";
}

View File

@@ -30,10 +30,10 @@ using weeks = std::chrono::duration<int, std::ratio_multiply<days::period, std::
= seconds(946684800)
*/
static constexpr std::chrono::seconds kEpochOffset =
constexpr static std::chrono::seconds kEPOCH_OFFSET =
date::sys_days{date::year{2000} / 1 / 1} - date::sys_days{date::year{1970} / 1 / 1};
static_assert(kEpochOffset.count() == 946684800);
static_assert(kEPOCH_OFFSET.count() == 946684800);
class NetClock
{
@@ -60,7 +60,7 @@ to_string(NetClock::time_point tp)
{
// 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC
using namespace std::chrono;
return to_string(system_clock::time_point{tp.time_since_epoch() + kEpochOffset});
return to_string(system_clock::time_point{tp.time_since_epoch() + kEPOCH_OFFSET});
}
template <class 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<NetClock::duration::period, std::ratio<1>>);
return toStringIso(date::sys_time<NetClock::duration>{tp.time_since_epoch() + kEpochOffset});
return toStringIso(date::sys_time<NetClock::duration>{tp.time_since_epoch() + kEPOCH_OFFSET});
}
/** A clock for measuring elapsed time.

View File

@@ -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

View File

@@ -5,7 +5,7 @@
#include <optional>
namespace xrpl {
constexpr auto kMuldivMax = std::numeric_limits<std::uint64_t>::max();
auto constexpr kMULDIV_MAX = std::numeric_limits<std::uint64_t>::max();
/** Return value*mul/div accurately.
Computes the result of the multiplication and division in

View File

@@ -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<std::uint64_t> 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<std::uint64_t> distribution{1};
seed = distribution(kSeeder);
seed = distribution(kSEEDER);
}
return beast::xor_shift_engine{seed};
}();
return kEngine;
return kENGINE;
}
/** Return a uniformly distributed random integer.

View File

@@ -22,9 +22,9 @@ safeCast(Src s) noexcept
{
static_assert(
std::is_signed_v<Dest> || std::is_unsigned_v<Src>, "Cannot cast signed to unsigned");
constexpr unsigned kNotSame = std::is_signed_v<Dest> != std::is_signed_v<Src>;
constexpr unsigned kNOT_SAME = std::is_signed_v<Dest> != std::is_signed_v<Src>;
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<Dest>(s);
}

View File

@@ -24,20 +24,20 @@ namespace xrpl {
template <class EF>
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<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exitFunction_{std::forward<EF>(rhs.exitFunction_)}
, executeOnDestruction_{rhs.executeOnDestruction_}
: exit_function_{std::forward<EF>(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<std::remove_cv_t<EFP>, ScopeExit> &&
std::is_constructible_v<EF, EFP>>* = 0) noexcept
: exitFunction_{std::forward<EFP>(f)}
: exit_function_{std::forward<EFP>(f)}
{
static_assert(std::is_nothrow_constructible_v<EF, decltype(std::forward<EFP>(f))>);
}
@@ -59,7 +59,7 @@ public:
void
release() noexcept
{
executeOnDestruction_ = false;
execute_on_destruction_ = false;
}
};
@@ -69,22 +69,22 @@ ScopeExit(EF) -> ScopeExit<EF>;
template <class EF>
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<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exitFunction_{std::forward<EF>(rhs.exitFunction_)}
, executeOnDestruction_{rhs.executeOnDestruction_}
, uncaughtOnCreation_{rhs.uncaughtOnCreation_}
: exit_function_{std::forward<EF>(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<std::remove_cv_t<EFP>, ScopeFail> &&
std::is_constructible_v<EF, EFP>>* = 0) noexcept
: exitFunction_{std::forward<EFP>(f)}
: exit_function_{std::forward<EFP>(f)}
{
static_assert(std::is_nothrow_constructible_v<EF, decltype(std::forward<EFP>(f))>);
}
@@ -106,7 +106,7 @@ public:
void
release() noexcept
{
executeOnDestruction_ = false;
execute_on_destruction_ = false;
}
};
@@ -116,22 +116,22 @@ ScopeFail(EF) -> ScopeFail<EF>;
template <class EF>
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<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exitFunction_{std::forward<EF>(rhs.exitFunction_)}
, executeOnDestruction_{rhs.executeOnDestruction_}
, uncaughtOnCreation_{rhs.uncaughtOnCreation_}
: exit_function_{std::forward<EF>(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<std::remove_cv_t<EFP>, ScopeSuccess> &&
std::is_constructible_v<EF, EFP>>* =
0) noexcept(std::is_nothrow_constructible_v<EF, EFP> || std::is_nothrow_constructible_v<EF, EFP&>)
: exitFunction_{std::forward<EFP>(f)}
: exit_function_{std::forward<EFP>(f)}
{
}
void
release() noexcept
{
executeOnDestruction_ = false;
execute_on_destruction_ = false;
}
};

View File

@@ -83,8 +83,8 @@ template <class Facade, class Clock = Facade>
AbstractClock<Facade>&
getAbstractClock()
{
static detail::AbstractClockWrapper<Facade, Clock> kClock;
return kClock;
static detail::AbstractClockWrapper<Facade, Clock> kCLOCK;
return kCLOCK;
}
} // namespace beast

View File

@@ -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 <std::size_t N>
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));
}

View File

@@ -53,7 +53,7 @@ inline void
maybeReverseBytes(T& t, Hasher&)
{
maybeReverseBytes(
t, std::integral_constant<bool, Hasher::kEndian != boost::endian::order::native>{});
t, std::integral_constant<bool, Hasher::kENDIAN != boost::endian::order::native>{});
}
} // namespace detail
@@ -154,7 +154,7 @@ struct IsContiguouslyHashable
: public std::integral_constant<
bool,
IsUniquelyRepresented<T>::value &&
(sizeof(T) == 1 || HashAlgorithm::kEndian == boost::endian::order::native)>
(sizeof(T) == 1 || HashAlgorithm::kENDIAN == boost::endian::order::native)>
{
explicit IsContiguouslyHashable() = default;
};

View File

@@ -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<std::uint8_t, kInternalBufferSize> buffer_{};
alignas(64) std::array<std::uint8_t, kINTERNAL_BUFFER_SIZE> buffer_{};
std::span<std::uint8_t> readBuffer_;
std::span<std::uint8_t> 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&

View File

@@ -62,7 +62,7 @@ private:
{
using run_time = std::pair<std::string, typename clock_type::duration>;
static constexpr auto kMaxTop = 10;
static constexpr auto kMAX_TOP = 10;
std::size_t suites = 0;
std::size_t cases = 0;
@@ -77,8 +77,8 @@ private:
std::ostream& os_;
Results results_;
SuiteResults suiteResults_;
CaseResults caseResults_;
SuiteResults suite_results_;
CaseResults case_results_;
public:
Reporter(Reporter const&) = delete;
@@ -146,11 +146,11 @@ Reporter<Unused>::Results::add(SuiteResults const& r)
});
if (iter != top.end())
{
if (top.size() == kMaxTop)
if (top.size() == kMAX_TOP)
top.resize(top.size() - 1);
top.emplace(iter, r.name, elapsed);
}
else if (top.size() < kMaxTop)
else if (top.size() < kMAX_TOP)
{
top.emplace_back(r.name, elapsed);
}
@@ -196,22 +196,22 @@ template <class Unused>
void
Reporter<Unused>::onSuiteBegin(SuiteInfo const& info)
{
suiteResults_ = SuiteResults{info.fullName()};
suite_results_ = SuiteResults{info.fullName()};
}
template <class Unused>
void
Reporter<Unused>::onSuiteEnd()
{
results_.add(suiteResults_);
results_.add(suite_results_);
}
template <class Unused>
void
Reporter<Unused>::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 +219,23 @@ template <class Unused>
void
Reporter<Unused>::onCaseEnd()
{
suiteResults_.add(caseResults_);
suite_results_.add(case_results_);
}
template <class Unused>
void
Reporter<Unused>::onPass()
{
++caseResults_.total;
++case_results_.total;
}
template <class Unused>
void
Reporter<Unused>::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;
}

View File

@@ -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. */

View File

@@ -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 <typename T>
bool
operator==(Zero, T const& t)
{
return t == kZero;
return t == kZERO;
}
template <typename T>
bool
operator!=(Zero, T const& t)
{
return t != kZero;
return t != kZERO;
}
template <typename T>
bool
operator<(Zero, T const& t)
{
return t > kZero;
return t > kZERO;
}
template <typename T>
bool
operator>(Zero, T const& t)
{
return t < kZero;
return t < kZERO;
}
template <typename T>
bool
operator>=(Zero, T const& t)
{
return t <= kZero;
return t <= kZERO;
}
template <typename T>
bool
operator<=(Zero, T const& t)
{
return t >= kZero;
return t >= kZERO;
}
} // namespace beast

View File

@@ -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<std::uint8_t*>(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);
}
}

View File

@@ -26,14 +26,12 @@ public:
result_type
operator()();
static constexpr result_type
min()
static result_type constexpr min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type
max()
static result_type constexpr max()
{
return std::numeric_limits<result_type>::max();
}

View File

@@ -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

View File

@@ -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

View File

@@ -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 {};

View File

@@ -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 <class F>
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>(f)](boost::coroutines2::coroutine<void>::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<std::mutex> lk(mutexRun_);
std::unique_lock<std::mutex> lk(mutex_run_);
cv_.wait(lk, [this]() { return !running_; });
}

View File

@@ -127,7 +127,7 @@ private:
std::function<void()> job_;
std::shared_ptr<LoadEvent> loadEvent_;
std::string name_;
clock_type::time_point queueTime_;
clock_type::time_point queue_time_;
};
using JobCounter = ClosureCounter<void>;

View File

@@ -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<void>::push_type* yield_{};
boost::coroutines2::coroutine<void>::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_;

View File

@@ -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&

View File

@@ -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 <typename Type>

View File

@@ -67,7 +67,7 @@ public:
[[nodiscard]] std::string
getFormattedErrorMessages() const;
static constexpr unsigned kNestLimit{25};
static constexpr unsigned kNEST_LIMIT{25};
private:
enum class TokenType {

View File

@@ -102,8 +102,8 @@ operator!=(StaticString x, std::string const& y)
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> 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::kMIN_INT - Value::kMAX_INT]
* - unsigned integer (range: 0 - Value::kMAX_UINT)
* - double
* - UTF-8 string
* - boolean
@@ -138,10 +138,10 @@ public:
using Int = json::Int;
using ArrayIndex = UInt;
static Value const kNull;
static constexpr Int kMinInt = std::numeric_limits<Int>::min();
static constexpr Int kMaxInt = std::numeric_limits<Int>::max();
static constexpr UInt kMaxUInt = std::numeric_limits<UInt>::max();
static Value const kNULL;
static constexpr Int kMIN_INT = std::numeric_limits<Int>::min();
static constexpr Int kMAX_INT = std::numeric_limits<Int>::max();
static constexpr UInt kMAX_UINT = std::numeric_limits<UInt>::max();
private:
class CZString
@@ -472,7 +472,7 @@ operator>=(Value const& x, Value const& y)
class ValueAllocator
{
public:
static constexpr auto kUnknown = (unsigned)-1;
static constexpr auto kUNKNOWN = (unsigned)-1;
virtual ~ValueAllocator() = default;
@@ -481,7 +481,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 = kUNKNOWN) = 0;
virtual void
releaseStringValue(char* value) = 0;
};

View File

@@ -9,7 +9,7 @@ class BookDirs
private:
ReadView const* view_ = nullptr;
uint256 const root_;
uint256 const nextQuality_;
uint256 const next_quality_;
uint256 const key_;
std::shared_ptr<SLE const> sle_ = nullptr;
unsigned int entry_ = 0;
@@ -67,15 +67,15 @@ private:
friend class BookDirs;
const_iterator(ReadView const& view, uint256 const& root, uint256 const& dirKey)
: view_(&view), root_(root), key_(dirKey), 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_;
uint256 cur_key_;
std::shared_ptr<SLE const> sle_;
unsigned int entry_ = 0;
uint256 index_;

View File

@@ -24,7 +24,7 @@ struct CreateGenesisT
{
explicit CreateGenesisT() = default;
};
extern CreateGenesisT const kCreateGenesis;
extern CreateGenesisT const kCREATE_GENESIS;
/** Holds a ledger.

View File

@@ -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;
}

View File

@@ -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<boost::container::pmr::monotonic_buffer_resource> monotonicResource_;
std::unique_ptr<boost::container::pmr::monotonic_buffer_resource> monotonic_resource_;
txs_map txs_;
Rules rules_;
LedgerHeader header_;
@@ -139,7 +139,7 @@ public:
std::shared_ptr<void const> hold = nullptr);
OpenView(OpenLedgerT, Rules const& rules, std::shared_ptr<ReadView const> const& base)
: OpenView(kOpenLedger, &*base, rules, base)
: OpenView(kOPEN_LEDGER, &*base, rules, base)
{
}

View File

@@ -57,7 +57,7 @@ isVaultPseudoAccountFrozen(
ReadView const& view,
AccountID const& account,
MPTIssue const& mptShare,
std::uint8_t depth);
int depth);
[[nodiscard]] bool
isLPTokenFrozen(

View File

@@ -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<boost::container::pmr::monotonic_buffer_resource>(
kInitialBufferSize)}
, items_{monotonicResource_.get()} {};
: monotonic_resource_{std::make_unique<boost::container::pmr::monotonic_buffer_resource>(
kINITIAL_BUFFER_SIZE)}
, items_{monotonic_resource_.get()} {};
RawStateTable(RawStateTable const& rhs)
: monotonicResource_{std::make_unique<boost::container::pmr::monotonic_buffer_resource>(
kInitialBufferSize)}
, items_{rhs.items_, monotonicResource_.get()}
: monotonic_resource_{std::make_unique<boost::container::pmr::monotonic_buffer_resource>(
kINITIAL_BUFFER_SIZE)}
, items_{rhs.items_, monotonic_resource_.get()}
, dropsDestroyed_{rhs.dropsDestroyed_} {};
RawStateTable(RawStateTable&&) = default;
@@ -101,7 +101,7 @@ private:
boost::container::pmr::polymorphic_allocator<std::pair<key_type const, SleAction>>>;
// monotonic_resource_ must outlive `items_`. Make a pointer so it may be
// easily moved.
std::unique_ptr<boost::container::pmr::monotonic_buffer_resource> monotonicResource_;
std::unique_ptr<boost::container::pmr::monotonic_buffer_resource> monotonic_resource_;
items_t items_;
XRPAmount dropsDestroyed_{0};

View File

@@ -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);

View File

@@ -70,21 +70,21 @@ escrowUnlockApplyHelper<Issue>(
initialBalance.get<Issue>().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<Issue>(
// 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 =
@@ -211,7 +211,7 @@ escrowUnlockApplyHelper<MPTIssue>(
// 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);

View File

@@ -4,43 +4,13 @@
#include <xrpl/protocol/Rules.h>
#include <xrpl/protocol/st.h>
#include <string_view>
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,
@@ -356,7 +311,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)

View File

@@ -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<AccountID> 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

View File

@@ -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);
}

View File

@@ -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<AccountID> 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);
//------------------------------------------------------------------------------
//

View File

@@ -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(

View File

@@ -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_;
};

View File

@@ -83,6 +83,10 @@ public:
virtual Status
fetch(uint256 const& hash, std::shared_ptr<NodeObject>* pObject) = 0;
/** Fetch a batch synchronously. */
virtual std::pair<std::vector<std::shared_ptr<NodeObject>>, Status>
fetchBatch(std::vector<uint256> const& hashes) = 0;
/** Store a single object.
Depending on the implementation this may happen immediately
or deferred using a scheduled task.

View File

@@ -29,7 +29,7 @@ enum class NodeObjectType : std::uint32_t {
class NodeObject : public CountedObject<NodeObject>
{
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

View File

@@ -9,13 +9,13 @@ 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;
static constexpr auto kBATCH_WRITE_PREALLOCATION_SIZE = 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;
static constexpr auto kBATCH_WRITE_LIMIT_SIZE = 65536;
/** Return codes from Backend operations. */
enum class Status {

View File

@@ -67,6 +67,9 @@ public:
backend_->sync();
}
std::vector<std::shared_ptr<NodeObject>>
fetchBatch(std::vector<uint256> const& hashes);
void
asyncFetch(
uint256 const& hash,

View File

@@ -55,7 +55,7 @@ lz4Compress(void const* in, std::size_t inSize, BufferFactory&& bf)
using std::runtime_error;
using namespace nudb::detail;
std::pair<void const*, std::size_t> result;
std::array<std::uint8_t, varint_traits<std::size_t>::kMax> vi{};
std::array<std::uint8_t, varint_traits<std::size_t>::kMAX> vi{};
auto const n = writeVarint(vi.data(), inSize);
auto const outMax = LZ4_compressBound(inSize);
std::uint8_t* out = reinterpret_cast<std::uint8_t*>(bf(n + outMax));
@@ -254,12 +254,12 @@ nodeobjectCompress(void const* in, std::size_t inSize, BufferFactory&& bf)
}
}
std::array<std::uint8_t, varint_traits<std::size_t>::kMax> vi{};
std::array<std::uint8_t, varint_traits<std::size_t>::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<void const*, std::size_t> 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<std::logic_error>("nodeobject codec: unknown=" + std::to_string(kCodecType));
Throw<std::logic_error>("nodeobject codec: unknown=" + std::to_string(kCODEC_TYPE));
};
return result;
}

View File

@@ -25,7 +25,7 @@ struct varint_traits<T, true>
{
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,

View File

@@ -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)

View File

@@ -69,7 +69,7 @@ toIssuer(AccountID&, std::string const&);
inline bool
isXRP(AccountID const& c)
{
return c == beast::kZero;
return c == beast::kZERO;
}
// DEPRECATED

View File

@@ -96,9 +96,9 @@ inline MPTAmount
toAmount<MPTAmount>(STAmount const& amt)
{
XRPL_ASSERT(
amt.holds<MPTIssue>() && amt.mantissa() <= kMaxMpTokenAmount && amt.exponent() == 0,
amt.holds<MPTIssue>() && amt.mantissa() <= kMAX_MP_TOKEN_AMOUNT && amt.exponent() == 0,
"xrpl::toAmount<MPTAmount> : maximum mantissa");
if (amt.mantissa() > kMaxMpTokenAmount || amt.exponent() != 0)
if (amt.mantissa() > kMAX_MP_TOKEN_AMOUNT || amt.exponent() != 0)
Throw<std::runtime_error>("toAmount<MPTAmount>: 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<T, T>;
static_assert(kAlwaysFalse, "Unsupported type for toAmount");
constexpr bool kALWAYS_FALSE = !std::is_same_v<T, T>;
static_assert(kALWAYS_FALSE, "Unsupported type for toAmount");
}
}
@@ -178,30 +178,30 @@ toMaxAmount(Asset const& asset)
{
if constexpr (std::is_same_v<IOUAmount, T>)
{
return IOUAmount(STAmount::kMaxValue, STAmount::kMaxOffset);
return IOUAmount(STAmount::kMAX_VALUE, STAmount::kMAX_OFFSET);
}
else if constexpr (std::is_same_v<XRPAmount, T>)
{
return XRPAmount(static_cast<std::int64_t>(STAmount::kMaxNativeN));
return XRPAmount(static_cast<std::int64_t>(STAmount::kMAX_NATIVE_N));
}
else if constexpr (std::is_same_v<MPTAmount, T>)
{
return MPTAmount(kMaxMpTokenAmount);
return MPTAmount(kMAX_MP_TOKEN_AMOUNT);
}
else if constexpr (std::is_same_v<STAmount, T>)
{
return asset.visit(
[](Issue const& issue) {
if (isXRP(issue))
return STAmount(issue, static_cast<std::int64_t>(STAmount::kMaxNativeN));
return STAmount(issue, STAmount::kMaxValue, STAmount::kMaxOffset);
return STAmount(issue, static_cast<std::int64_t>(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<T, T>;
static_assert(kAlwaysFalse, "Unsupported type for toMaxAmount");
constexpr bool kALWAYS_FALSE = !std::is_same_v<T, T>;
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<T, T>;
static_assert(kAlwaysFalse, "Unsupported type for getIssue");
constexpr bool kALWAYS_FALSE = !std::is_same_v<T, T>;
static_assert(kALWAYS_FALSE, "Unsupported type for getIssue");
}
}
@@ -260,8 +260,8 @@ get(STAmount const& a)
}
else
{
constexpr bool kAlwaysFalse = !std::is_same_v<T, T>;
static_assert(kAlwaysFalse, "Unsupported type for get");
constexpr bool kALWAYS_FALSE = !std::is_same_v<T, T>;
static_assert(kALWAYS_FALSE, "Unsupported type for get");
}
}

View File

@@ -35,49 +35,49 @@ namespace xrpl {
namespace RPC {
template <unsigned int Version>
static constexpr std::integral_constant<unsigned, Version> kApiVersion = {};
constexpr static std::integral_constant<unsigned, Version> 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;
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 <unsigned MinVer, unsigned MaxVer, typename Fn, typename... Args>
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<unsigned int, MinVer>{}, std::forward<Args>(args)...);
fn(std::integral_constant<unsigned int, MaxVer>{}, std::forward<Args>(args)...);
}
{
static constexpr auto kSize = MaxVer + 1 - MinVer;
constexpr auto kSIZE = MaxVer + 1 - MinVer;
[&]<std::size_t... Offset>(std::index_sequence<Offset...>) {
// NOLINTBEGIN(bugprone-use-after-move)
(((void)fn(
std::integral_constant<unsigned int, MinVer + Offset>{}, std::forward<Args>(args)...)),
...);
// NOLINTEND(bugprone-use-after-move)
}(std::make_index_sequence<kSize>{});
}(std::make_index_sequence<kSIZE>{});
}
template <typename Fn, typename... Args>
void
forAllApiVersions(Fn const& fn, Args&&... args)
requires requires {
forApiVersions<RPC::kApiMinimumSupportedVersion, RPC::kApiMaximumValidVersion>(
forApiVersions<RPC::kAPI_MINIMUM_SUPPORTED_VERSION, RPC::kAPI_MAXIMUM_VALID_VERSION>(
fn, std::forward<Args>(args)...);
}
{
forApiVersions<RPC::kApiMinimumSupportedVersion, RPC::kApiMaximumValidVersion>(
forApiVersions<RPC::kAPI_MINIMUM_SUPPORTED_VERSION, RPC::kAPI_MAXIMUM_VALID_VERSION>(
fn, std::forward<Args>(args)...);
}

View File

@@ -148,10 +148,10 @@ public:
};
template <ValidIssueType TIss>
constexpr bool kIsIssueV = std::is_same_v<TIss, Issue>;
constexpr bool kIS_ISSUE_V = std::is_same_v<TIss, Issue>;
template <ValidIssueType TIss>
constexpr bool kIsMptissueV = std::is_same_v<TIss, MPTIssue>;
constexpr bool kIS_MPTISSUE_V = std::is_same_v<TIss, MPTIssue>;
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<TLhs> && kIsMptissueV<TRhs>)
else if constexpr (kIS_ISSUE_V<TLhs> && kIS_MPTISSUE_V<TRhs>)
{
return std::weak_ordering::greater;
}

View File

@@ -140,8 +140,8 @@ private:
using issue_hasher = std::hash<xrpl::Issue>;
using mptissue_hasher = std::hash<xrpl::MPTIssue>;
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<xrpl::Asset>;
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;
}

View File

@@ -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. */

View File

@@ -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 <xrpl/protocol/detail/features.macro>
);
@@ -184,9 +184,9 @@ bitsetIndexToFeature(size_t i);
std::string
featureToName(uint256 const& f);
class FeatureBitset : private std::bitset<detail::kNumFeatures>
class FeatureBitset : private std::bitset<detail::kNUM_FEATURES>
{
using base = std::bitset<detail::kNumFeatures>;
using base = std::bitset<detail::kNUM_FEATURES>;
template <class... Fs>
void

View File

@@ -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.

View File

@@ -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)

View File

@@ -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<KeyletDesc<AccountID const&>, 6> const kDirectAccountKeylets{
std::array<KeyletDesc<AccountID const&>, 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},

View File

@@ -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

View File

@@ -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

View File

@@ -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&

Some files were not shown because too many files have changed in this diff Show More