Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .cspell.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ words:
- keylet
- keylets
- keyvadb
- kuznetsss
- kwarg
- kwargs
- ledgerentry
Expand Down Expand Up @@ -203,6 +204,7 @@ words:
- multisign
- multisigned
- Nakamoto
- nbougalis
- nftid
- nftoffer
- nftoken
Expand Down
20 changes: 20 additions & 0 deletions .github/instructions/cpp.instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
applyTo: "**/*.h,**/*.hpp,**/*.cpp,**/*.ipp"
---

# C++

C++ code must follow [`docs/cpp/guidelines.md`](../../docs/cpp/guidelines.md),
and `XRPL_ASSERT` and `UNREACHABLE` contracts must follow
[`docs/cpp/antithesis.md`](../../docs/cpp/antithesis.md).

When writing code, follow these documents.

When reviewing a pull request:

- Check every C++ change against these documents, and report each violation
as a review comment that names the rule it breaks.
- Review only code the pull request adds or modifies; existing violations in
untouched code are out of scope.
- Do not comment on formatting or on anything clang-tidy reports; CI checks
those separately.
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ The legacy unit tests under `src/test/` are a custom framework (derived from Bea

## Lint/Format

See [CONTRIBUTING.md](./CONTRIBUTING.md#pre-commit-hooks) for `pre-commit` setup and [CONTRIBUTING.md](./CONTRIBUTING.md#clang-tidy) for `clang-tidy` (opt-in, needs local `clang-tidy` and generated headers).
See [CONTRIBUTING.md](./CONTRIBUTING.md#pre-commit-hooks) for `pre-commit` setup and [docs/cpp/clang-tidy.md](./docs/cpp/clang-tidy.md) for `clang-tidy` (opt-in, needs local `clang-tidy` and generated headers).

## Code Style

New file placement and header levelization: see [CONTRIBUTING.md](./CONTRIBUTING.md#before-making-a-pull-request). Braces, whitespace, member order, and other conventions: see [docs/CodingStyle.md](./docs/CodingStyle.md). `XRPL_ASSERT`/`UNREACHABLE` contracts: see [CONTRIBUTING.md](./CONTRIBUTING.md#contracts-and-instrumentation). Commit messages: see [CONTRIBUTING.md](./CONTRIBUTING.md#good-commit-messages). New public functions/methods need a Doxygen-style comment.
New file placement and header levelization: see [docs/cpp/guidelines.md](./docs/cpp/guidelines.md#source-layout). Braces, whitespace, member order, and other conventions: see [docs/CodingStyle.md](./docs/CodingStyle.md). `XRPL_ASSERT`/`UNREACHABLE` contracts: see [docs/cpp/antithesis.md](./docs/cpp/antithesis.md). Commit messages: see [CONTRIBUTING.md](./CONTRIBUTING.md#good-commit-messages). New public functions/methods need a Doxygen-style comment.

Comments should explain _why_, not _what_/_how_ — the code already shows that. Only describe what/how when the code itself would otherwise be confusing (a non-obvious workaround, a subtle invariant, a surprising constraint). Write new or changed comments as full sentences: start with a capital letter and end with a period.

Expand Down
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@

# The CI tooling team should review changes to the CI configuration.
/.github/ @XRPLF/ci-tooling
/docs/cpp/ @bthomee @godexsoft @kuznetsss @mathbunnyru @nbougalis @ximinez
240 changes: 9 additions & 231 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,21 +91,13 @@ If your test can be run offline, in under 60 seconds, then it can be an
automatic test run by `xrpld --unittest`.
Otherwise, it must be a manual test.

If you create new source files, they must be organized as follows:

- If the files are in any of the `libxrpl` modules, the headers (`.h`) must go
under `include/xrpl`, and source (`.cpp`) files must go under
`src/libxrpl`.
- All other non-test files must go under `src/xrpld`.
- New test source files should use `gtest` and go under `src/tests`, unless that isn't possible, in which case they should use our legacy test framework and go under `src/test`.
- All benchmark source files must go under `src/benchmarks`.
C++ code must follow the [C++ guidelines](./docs/cpp/guidelines.md),
including where new source files go and header levelization.

The source must be formatted according to the style guide below. The easiest
way to satisfy this is to install the [`pre-commit`](#pre-commit-hooks) hooks,
which format and lint your changes automatically on every commit.

Header includes must be [levelized](.github/scripts/levelization).

Changes should be usually squashed down into a single commit.
Some larger or more complicated change sets make more sense,
and are easier to review if organized into multiple logical commits.
Expand Down Expand Up @@ -226,9 +218,10 @@ at any time, so don't use it lightly.

# Style guide

This is a non-exhaustive list of recommended style guidelines. These are
not always strictly enforced and serve as a way to keep the codebase
coherent rather than a set of _thou shalt not_ commandments.
C++ coding guidelines live in [`docs/cpp/guidelines.md`](./docs/cpp/guidelines.md),
C++ formatting in [`docs/cpp/formatting.md`](./docs/cpp/formatting.md), and
`clang-tidy` in [`docs/cpp/clang-tidy.md`](./docs/cpp/clang-tidy.md).
This section covers the `pre-commit` hooks that enforce them.

## Pre-commit hooks

Expand All @@ -241,7 +234,7 @@ yourself. The version of each hook sourced from an external repository
(`clang-format`, `gersemi`, etc.) is pinned in that file, so running the hooks
locally uses exactly the same versions as CI. A few `local` hooks — most notably
`clang-tidy` and `cargo fmt` — run tools from your own environment; see
[Installing clang-tidy](#installing-clang-tidy) and
[Installing clang-tidy](./docs/cpp/clang-tidy.md#installing-clang-tidy) and
[Rust](./docs/build/environment.md#rust) for how to get those.

To get started, install `pre-commit` and enable the git hook scripts:
Expand All @@ -267,8 +260,8 @@ pre-commit run clang-format --all-files

The hooks configured in this repository include, among others:

- `clang-format` — C++/proto formatting (see [Formatting](#formatting))
- `clang-tidy` — C++ static analysis (see [Clang-tidy](#clang-tidy)); opt in with `TIDY=1`
- `clang-format` — C++/proto formatting (see [C++ formatting](./docs/cpp/formatting.md))
- `clang-tidy` — C++ static analysis (see [Clang-tidy](./docs/cpp/clang-tidy.md)); opt in with `TIDY=1`
- `fix-include-style`, `fix-pragma-once`, `check-doxygen-style` — C++ hygiene
- `gersemi` — CMake formatting
- `cargo fmt` — Rust formatting for the crates in `crates/`
Expand All @@ -278,190 +271,6 @@ The hooks configured in this repository include, among others:
The same hooks run in CI on every pull request, so running them locally before
you push helps you avoid CI failures.

## Formatting

All code must conform to `clang-format`, according to the settings in
[`.clang-format`](./.clang-format), unless the result would be unreasonably
difficult to read or maintain. The `clang-format` version is pinned in
[`.pre-commit-config.yaml`](./.pre-commit-config.yaml), so the
[`pre-commit`](#pre-commit-hooks) hook always formats with the same version as
CI. To demarcate lines that should be left as-is, surround them with comments
like this:

```
// clang-format off
...
// clang-format on
```

The easiest way to format your changes is to let the `pre-commit` hook run
automatically on commit, or to run it manually:

```bash
pre-commit run clang-format --all-files
```

You can also format individual files in place by running `clang-format -i <file>...`
from any directory within this project.

> [!NOTE]
> This uses whatever `clang-format` version is installed locally, which may
> differ from the pinned version used by `pre-commit` and CI, so the results
> can vary.

There is a Continuous Integration job that runs clang-format on pull requests. If the code doesn't comply, a patch file that corrects auto-fixable formatting issues is generated.

To download the patch file:

1. Next to `clang-format / check (pull_request) Failing after #s` -> click **Details** to open the details page.
2. Left menu -> click **Summary**
3. Scroll down to near the bottom-right under `Artifacts` -> click **clang-format.patch**
4. Download the zip file and extract it to your local git repository. Run `git apply [patch-file-name]`.
5. Commit and push.

## Clang-tidy

All code must pass `clang-tidy` checks according to the settings in [`.clang-tidy`](./.clang-tidy).

There is a Continuous Integration job that runs clang-tidy on pull requests. The CI will check:

- All changed C++ files (`.cpp`, `.h`, `.ipp`) when only code files are modified
- **All files in the repository** when the `.clang-tidy` configuration file is changed

This ensures that configuration changes don't introduce new warnings across the codebase.

### Installing clang-tidy

The [Nix development shell](./docs/build/nix.md) provides `clang-tidy` at the [tested version](./docs/build/environment.md#tested-compiler-versions).

### Running clang-tidy locally

Before running clang-tidy, you must generate the files it depends on (protobuf headers, and, when the project is configured with `-Drust=ON`, the cxxbridge headers from the Rust crates). Configure the project as described in [`BUILD.md`](./BUILD.md), then build the `tidy_prerequisites` target, which generates all of them:

```bash
cmake --build build --target tidy_prerequisites
```

#### Via pre-commit (recommended)

If you have already installed the [`pre-commit`](#pre-commit-hooks) hooks, you can run clang-tidy on your staged files using:

```
TIDY=1 pre-commit run clang-tidy
```

This runs clang-tidy locally with the same configuration/flags as CI, scoped to your staged C++ files. The `TIDY=1` environment variable is required to opt in — without it the hook is skipped.

You can also have clang-tidy run automatically on every `git commit` by setting `TIDY=1` in your shell environment:

```
export TIDY=1
```

With this set, the hook will run as part of `git commit` alongside the other pre-commit checks.

#### Manually

Then run clang-tidy on your local changes:

```
run-clang-tidy -p build -allow-no-checks include src tests
```

This will check all source files in the `include`, `src` and `tests` directories using the compile commands from your `build` directory.
Headers are checked on their own, which requires the `verify_headers` CMake option (ON by default).
If you wish to automatically fix whatever clang-tidy finds _and_ is capable of fixing, add `-fix -format` to the above command:

```
run-clang-tidy -p build -quiet -fix -format -allow-no-checks include src tests
```

`-format` reformats the fixed code with [`.clang-format`](./.clang-format); without it the fixes are inserted in LLVM style and the `clang-format` hook rewrites them afterwards.

## Contracts and instrumentation

We are using [Antithesis](https://antithesis.com/) for continuous fuzzing,
and keep a copy of [Antithesis C++ SDK](https://github.com/antithesishq/antithesis-sdk-cpp/)
in `external/antithesis-sdk`. One of the aims of fuzzing is to identify bugs
by finding external conditions which cause contracts violations inside `xrpld`.
The contracts are expressed as `XRPL_ASSERT` or `UNREACHABLE` (defined in
`include/xrpl/beast/utility/instrumentation.h`), which are effectively (outside
of Antithesis) wrappers for `assert(...)` with added name. The purpose of name
is to provide contracts with stable identity which does not rely on line numbers.

When `xrpld` is built with the Antithesis instrumentation enabled
(using `voidstar` CMake option) and ran on the Antithesis platform, the
contracts become
[test properties](https://antithesis.com/docs/using_antithesis/properties.html);
otherwise they are just like a regular `assert`.
To learn more about Antithesis, see
[How Antithesis Works](https://antithesis.com/docs/introduction/how_antithesis_works.html)
and [C++ SDK](https://antithesis.com/docs/using_antithesis/sdk/cpp/overview.html#)

We continue to use the old style `assert` or `assert(false)` in certain
locations, where the reporting of contract violations on the Antithesis
platform is either not possible or not useful.

For this reason:

- The locations where `assert` or `assert(false)` contracts should continue to be used:
- `constexpr` functions
- unit tests i.e. files under `src/test`
- unit tests-related modules (files under `beast/test` and `beast/unit_test`)
- Outside of the listed locations, do not use `assert`; use `XRPL_ASSERT` instead,
giving it unique name, with the short description of the contract.
- Outside of the listed locations, do not use `assert(false)`; use
`UNREACHABLE` instead, giving it unique name, with the description of the
condition being violated
- The contract name should start with a full name (including scope) of the
function, optionally a named lambda, followed by a colon `:` and a brief
(typically at most five words) description. `UNREACHABLE` contracts
can use slightly longer descriptions. If there are multiple overloads of the
function, use common sense to balance both brevity and unambiguity of the
function name. NOTE: the purpose of name is to provide stable means of
unique identification of every contract; for this reason try to avoid elements
which can change in some obvious refactors or when reinforcing the condition.
- Contract description typically (except for `UNREACHABLE`) should describe the
_expected_ condition, as in "I assert that _expected_ is true".
- Contract description for `UNREACHABLE` should describe the _unexpected_
situation which caused the line to have been reached.
- Example good name for an
`UNREACHABLE` macro `"json::operator==(Value, Value) : invalid type"`; example
good name for an `XRPL_ASSERT` macro `"json::Value::asCString : valid type"`.
- Example **bad** name
`"RFC1751::insert(char* s, int x, int start, int length) : length is greater than or equal zero"`
(missing namespace, unnecessary full function signature, description too verbose).
Good name: `"xrpl::RFC1751::insert : minimum length"`.
- In **few** well-justified cases a non-standard name can be used, in which case a
comment should be placed to explain the rationale (example in `contract.cpp`)
- Do **not** rename a contract without a good reason (e.g. the name no longer
reflects the location or the condition being checked)
- Do not use `std::unreachable`
- Do not put contracts where they can be violated by an external condition
(e.g. timing, data payload before mandatory validation etc.) as this creates
bogus bug reports (and causes crashes of Debug builds)
- Only use `UNREACHABLE` for paths that are truly impossible. Do not use it to
avoid writing a test for a path that is rare but reachable. When you exclude
an `UNREACHABLE` branch from coverage, wrap it in
`LCOV_EXCL_START`/`LCOV_EXCL_STOP`.
- For a condition that is rare but possible (e.g. a value from a peer that must
be positive, but a peer can send a negative one), handle it at runtime and use
`SOMETIMES` to tell the fuzzer to try to make it happen:

```cpp
bool isNegative = value.peek() < 0;
SOMETIMES(isNegative, "xrpl::Foo::bar : negative value");
if (isNegative)
{
JLOG(journal.debug()) << "...";
return false;
}
```

- See `include/xrpl/beast/utility/instrumentation.h` for the full list of
macros (`XRPL_ASSERT`, `XRPL_ASSERT_IF`, `ALWAYS`, `REACHABLE`, `SOMETIMES`,
`UNREACHABLE`) and when to use each.

## Unit Tests

To execute all unit tests:
Expand All @@ -483,37 +292,6 @@ Alternatively, if the unit test name finds an exact match, it will stop
doing partial matches, i.e. if a unit test with a title of `TestSuiteName`
exists, then no other unit test will be executed, apart from `TestSuiteName`.

## Avoid
Comment thread
kuznetsss marked this conversation as resolved.
Resolved

1. Proliferation of nearly identical code.
2. Proliferation of new files and classes.
3. Complex inheritance and complex OOP patterns.
4. Unmanaged memory allocation and raw pointers.
5. Macros and non-trivial templates (unless they add significant value).
6. Lambda patterns (unless these add significant value).
7. CPU or architecture-specific code unless there is a good reason to
include it, and where it is used, guard it with macros and provide
explanatory comments.
8. Importing new libraries unless there is a very good reason to do so.

## Seek to

9. Extend functionality of existing code rather than creating new code.
10. Prefer readability over terseness where important logic is
concerned.
11. Inline functions that are not used or are not likely to be used
elsewhere in the codebase.
12. Use clear and self-explanatory names for functions, variables,
structs and classes.
13. Use TitleCase for classes, structs, type aliases and filenames,
camelCase for function and variable names, lower case for namespaces and
folders. The exception is a type alias that generic code looks up by name
(`value_type`, `iterator`, `result_type`, and the rest of the standard
container, hash and clock members), which keeps its snake_case spelling;
`.clang-tidy` lists the names that are allowed.
14. Provide as many comments as you feel that a competent programmer
would need to understand what your code does.

# Maintainers

Maintainers are ecosystem participants with elevated access to the repository.
Expand Down
Loading
Loading