WIP: [wip,nomerge,rfc] build: Require C++23 compiler #36033

Draft
maflcko wants to merge 13 commits from 2608-cpp23 into master AGit
maflcko commented 2026-08-20 09:06:27 +00:00 (Migrated from github.com)

C++23 for Bitcoin Core is mostly a "style update" on top of C++20. However, the workarounds to avoid C++23 keep accumulating and some parts of the code already use C++23 features, such as lambda attributes (github.com/bitcoin-core/libmultiprocess@bdd0cd6941).

I don't know when it is fine to switch, but at some point, I think it is fine to require a C++23 compiler, so that new stuff is unlocked. Of course this requires bumping the minimum required compiler versions:

  • GCC: 13
  • Clang: 19

There are some C++23 features that aren't implemented (such as <stacktrace> not really shipped in any vanilla stdlib today), or e.g. ranges::starts_with not implemented until libstdc++-16. But overall I think we are better off using C++23 without those few features instead of waiting longer?

C++23 for Bitcoin Core is mostly a "style update" on top of C++20. However, the workarounds to avoid C++23 keep accumulating and some parts of the code already use C++23 features, such as lambda attributes (https://github.com/bitcoin-core/libmultiprocess/commit/bdd0cd69418d189f62699d274a751cbf6d36bb43). I don't know when it is fine to switch, but at some point, I think it is fine to require a C++23 compiler, so that [new stuff](https://github.com/bitcoin/bitcoin/issues/34979#issuecomment-4448399166) is unlocked. Of course this requires bumping the minimum required compiler versions: * GCC: 13 * Clang: 19 There are some C++23 features that aren't implemented (such as `<stacktrace>` not really shipped in any vanilla stdlib today), or e.g. `ranges::starts_with` not implemented until libstdc++-16. But overall I think we are better off using C++23 without those few features instead of waiting longer?
DrahtBot commented 2026-08-20 09:06:34 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK l0rinc

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37018 (descriptor: fix InferScript creates invalid descriptors for invalid pubkeys by Eunovo)
  • #36994 (net: reduce ASMap lookup and address grouping costs by l0rinc)
  • #36980 (log: mask SENSITIVE rw_settings in LogArgs by enessubass)
  • #36976 (rpc: Use OBJ_NAMED_PARAMS in estimatesmartfee by maflcko)
  • #36858 (refactor: break the blockstorage/validation circular dependency by pzafonte)
  • #36856 (kernel: add manual pruning by pzafonte)
  • #36839 (build: explicitly disable cl.exe by bartoli)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36434 (http: support unix sockets by pinheadmz)
  • #36255 (Refactor CoinGrinder tests by murchandamus)
  • #36049 (streams: handle buffered write failures outside the destructor by l0rinc)
  • #35940 (net: add bip152hb permission to select BIP152 high-bandwidth peers by w0xlt)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #34132 (coins,dbwrapper: make database point-read failures fatal by l0rinc)
  • #29418 (rpc: provide per message stats for global traffic via new field in 'getnettotals' by vasild)
  • #27865 (wallet: Track no-longer-spendable TXOs separately by achow101)
  • #17783 (common: Disallow calling IsArgSet() on ALLOW_LIST options by ryanofsky)
  • #17580 (refactor: Add ALLOW_LIST flags and enforce usage in CheckArgFlags by ryanofsky)
  • #16545 (refactor: Implement missing error checking for ArgsManager flags by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36033 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36033.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36033#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [l0rinc](https://github.com/bitcoin/bitcoin/pull/36033#issuecomment-5372931579) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#37018](https://github.com/bitcoin/bitcoin/pull/37018) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37018.svg"></sub> (descriptor: fix `InferScript` creates invalid descriptors for invalid pubkeys by Eunovo) * [#36994](https://github.com/bitcoin/bitcoin/pull/36994) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36994.svg"></sub> (net: reduce ASMap lookup and address grouping costs by l0rinc) * [#36980](https://github.com/bitcoin/bitcoin/pull/36980) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36980.svg"></sub> (log: mask SENSITIVE rw_settings in LogArgs by enessubass) * [#36976](https://github.com/bitcoin/bitcoin/pull/36976) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36976.svg"></sub> (rpc: Use OBJ_NAMED_PARAMS in estimatesmartfee by maflcko) * [#36858](https://github.com/bitcoin/bitcoin/pull/36858) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36858.svg"></sub> (refactor: break the blockstorage/validation circular dependency by pzafonte) * [#36856](https://github.com/bitcoin/bitcoin/pull/36856) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36856.svg"></sub> (kernel: add manual pruning by pzafonte) * [#36839](https://github.com/bitcoin/bitcoin/pull/36839) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36839.svg"></sub> (build: explicitly disable cl.exe by bartoli) * [#36738](https://github.com/bitcoin/bitcoin/pull/36738) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36738.svg"></sub> (refactor: move block writes and pruning into BlockManager by pzafonte) * [#36434](https://github.com/bitcoin/bitcoin/pull/36434) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36434.svg"></sub> (http: support unix sockets by pinheadmz) * [#36255](https://github.com/bitcoin/bitcoin/pull/36255) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36255.svg"></sub> (Refactor CoinGrinder tests by murchandamus) * [#36049](https://github.com/bitcoin/bitcoin/pull/36049) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36049.svg"></sub> (streams: handle buffered write failures outside the destructor by l0rinc) * [#35940](https://github.com/bitcoin/bitcoin/pull/35940) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35940.svg"></sub> (net: add bip152hb permission to select BIP152 high-bandwidth peers by w0xlt) * [#35713](https://github.com/bitcoin/bitcoin/pull/35713) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35713.svg"></sub> (Remove boost as a unit test runner by rustaceanrob) * [#34132](https://github.com/bitcoin/bitcoin/pull/34132) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34132.svg"></sub> (coins,dbwrapper: make database point-read failures fatal by l0rinc) * [#29418](https://github.com/bitcoin/bitcoin/pull/29418) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29418.svg"></sub> (rpc: provide per message stats for global traffic via new field in 'getnettotals' by vasild) * [#27865](https://github.com/bitcoin/bitcoin/pull/27865) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/27865.svg"></sub> (wallet: Track no-longer-spendable TXOs separately by achow101) * [#17783](https://github.com/bitcoin/bitcoin/pull/17783) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/17783.svg"></sub> (common: Disallow calling IsArgSet() on ALLOW_LIST options by ryanofsky) * [#17580](https://github.com/bitcoin/bitcoin/pull/17580) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/17580.svg"></sub> (refactor: Add ALLOW_LIST flags and enforce usage in CheckArgFlags by ryanofsky) * [#16545](https://github.com/bitcoin/bitcoin/pull/16545) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/16545.svg"></sub> (refactor: Implement missing error checking for ArgsManager flags by ryanofsky) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2026-08-20 10:17:30 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task NetBSD Cross: https://github.com/bitcoin/bitcoin/actions/runs/32352184973/job/96373551351
LLM reason (✨ experimental): CI failed due to a C++ build error: std::ranges::views::zip is not available (no member named 'zip' in namespace 'std::ranges::views').

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `NetBSD Cross`: https://github.com/bitcoin/bitcoin/actions/runs/32352184973/job/96373551351</sub> <sub>LLM reason (✨ experimental): CI failed due to a C++ build error: `std::ranges::views::zip` is not available (`no member named 'zip' in namespace 'std::ranges::views'`).</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
l0rinc commented 2026-08-21 17:08:15 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
hebasto (Migrated from github.com) reviewed 2026-08-23 16:34:45 +00:00
hebasto (Migrated from github.com) left a comment

edede385cab47020124bba6db98d69319168afb5

iwyu incorrectly suggests to remove the util/expected include

This looks like IWYU's "Automatic re-export: function return values" heuristics in action.

edede385cab47020124bba6db98d69319168afb5 > iwyu incorrectly suggests to remove the util/expected include This looks like IWYU's ["Automatic re-export: function return values"](https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/WhatIsAUse.md#automatic-re-export-function-return-values) heuristics in action.
DrahtBot commented 2026-09-09 11:34:04 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-09-29 21:26:00 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
First-time contributor

Review failed because required verification did not complete.

Earlier concerns neither republished nor resolved: 4 major findings · 1 minor finding · 4 suggestions. See the Run archive linked from the Review report for their assessments.

Review coverage was incomplete.


Reviewed: 4a926d33b6c5 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:b8db55c205d385dbec975c3f1c25c817b3b37fd0 --> <!-- ralph-head:4a926d33b6c55ba4f696fed6850b5b9851fddf66 --> <!-- ralph-case:009b24cca1f92768a1f4f4fc1d5ac1a5d0479ede7ebc91dfd70f4c75ec817064 --> Review failed because required verification did not complete. Earlier concerns neither republished nor resolved: 4 major findings · 1 minor finding · 4 suggestions. See the Run archive linked from the Review report for their assessments. Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`4a926d33b6c5`](<https://git.fish.foo/bitcoin/bitcoin/commit/4a926d33b6c55ba4f696fed6850b5b9851fddf66>) · [Review report](<https://review.fish.foo/report/36033-4a926d33b6c55ba4f696fed6850b5b9851fddf66-3257-16.html>) · [Previous reports](<https://review.fish.foo/traces/36033/>) [permalink](<https://review.fish.foo/report/36033-4a926d33b6c55ba4f696fed6850b5b9851fddf66-3257-16.html>)
DrahtBot commented 2026-10-02 10:24:55 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-10-07 12:29:21 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-10-21 14:11:37 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-11-01 22:56:12 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-11-04 13:08:31 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
maflcko (Migrated from github.com) reviewed 2026-11-10 20:00:44 +00:00
maflcko (Migrated from github.com) commented 2026-11-10 20:00:44 +00:00
self-nit: Should `std::unreachable` be rejected? Here is a linter diff
    lint: Add std_unreachable linter

diff --git a/test/lint/test_runner/src/lint_cpp.rs b/test/lint/test_runner/src/lint_cpp.rs
index 5d279c7c77..e446aae748 100644
--- a/test/lint/test_runner/src/lint_cpp.rs
+++ b/test/lint/test_runner/src/lint_cpp.rs
@@ -211,2 +211,29 @@ Assertions with a falsy literal value should be replaced with AssertUnreachable(
 
+pub fn lint_std_unreachable() -> LintResult {
+    let found = git()
+        .args([
+            "grep",
+            "--line-number",
+            "--fixed-string",
+            "std::unreachable()",
+            "--",
+            "src/",
+        ])
+        .args(get_pathspecs_default_excludes())
+        .status()
+        .expect("command error")
+        .success();
+    if found {
+        // Reject all for now, but if there is an optimization use case in the future, an exclusion
+        // can be added, or this linter can be removed.
+        Err(r#"
+std::unreachable() invokes UB and should be replaced with AssertUnreachable().
+            "#
+        .trim()
+        .to_string())
+    } else {
+        Ok(())
+    }
+}
+
 pub fn lint_boost_assert() -> LintResult {
diff --git a/test/lint/test_runner/src/main.rs b/test/lint/test_runner/src/main.rs
index 22f3876948..3a884d410f 100644
--- a/test/lint/test_runner/src/main.rs
+++ b/test/lint/test_runner/src/main.rs
@@ -17,3 +17,3 @@ use lint_cpp::{
     lint_assert_falsy, lint_boost_assert, lint_includes_build_config, lint_remove_all,
-    lint_rpc_assert, lint_std_filesystem,
+    lint_rpc_assert, lint_std_filesystem, lint_std_unreachable,
 };
@@ -80,2 +80,7 @@ fn get_linter_list() -> Vec<&'static Linter> {
         },
+        &Linter {
+            description: "Check that std::unreachable() is not used",
+            name: "std_unreachable",
+            lint_fn: lint_std_unreachable
+        },
         &Linter {
<details><summary>self-nit: Should `std::unreachable` be rejected? Here is a linter diff</summary> ```diff lint: Add std_unreachable linter diff --git a/test/lint/test_runner/src/lint_cpp.rs b/test/lint/test_runner/src/lint_cpp.rs index 5d279c7c77..e446aae748 100644 --- a/test/lint/test_runner/src/lint_cpp.rs +++ b/test/lint/test_runner/src/lint_cpp.rs @@ -211,2 +211,29 @@ Assertions with a falsy literal value should be replaced with AssertUnreachable( +pub fn lint_std_unreachable() -> LintResult { + let found = git() + .args([ + "grep", + "--line-number", + "--fixed-string", + "std::unreachable()", + "--", + "src/", + ]) + .args(get_pathspecs_default_excludes()) + .status() + .expect("command error") + .success(); + if found { + // Reject all for now, but if there is an optimization use case in the future, an exclusion + // can be added, or this linter can be removed. + Err(r#" +std::unreachable() invokes UB and should be replaced with AssertUnreachable(). + "# + .trim() + .to_string()) + } else { + Ok(()) + } +} + pub fn lint_boost_assert() -> LintResult { diff --git a/test/lint/test_runner/src/main.rs b/test/lint/test_runner/src/main.rs index 22f3876948..3a884d410f 100644 --- a/test/lint/test_runner/src/main.rs +++ b/test/lint/test_runner/src/main.rs @@ -17,3 +17,3 @@ use lint_cpp::{ lint_assert_falsy, lint_boost_assert, lint_includes_build_config, lint_remove_all, - lint_rpc_assert, lint_std_filesystem, + lint_rpc_assert, lint_std_filesystem, lint_std_unreachable, }; @@ -80,2 +80,7 @@ fn get_linter_list() -> Vec<&'static Linter> { }, + &Linter { + description: "Check that std::unreachable() is not used", + name: "std_unreachable", + lint_fn: lint_std_unreachable + }, &Linter { ``` </details>
l0rinc (Migrated from github.com) reviewed 2026-11-25 15:24:44 +00:00
l0rinc (Migrated from github.com) left a comment

My inline comments cover build and IPC compatibility, the skipped-path regression in block import, test guards for expected, and optional C++23 cleanups.

I have added patches to illustrate those suggestions, but I don't think we should fix them all here - but it would make sense to add a small compile sample for each to demonstrate support across our infrastructure - then handle the exhaustive call-site migrations in separate PRs.

My inline comments cover build and IPC compatibility, the skipped-path regression in block import, test guards for `expected`, and optional C++23 cleanups. I have added patches to illustrate those suggestions, but I don't think we should fix them all here - but it would make sense to add a small compile sample for each to demonstrate support across our infrastructure - then handle the exhaustive call-site migrations in separate PRs.
l0rinc (Migrated from github.com) commented 2026-11-25 12:36:06 +00:00

aa80723 build: Require C++23 compiler:

GCC 12 and NetBSD's libstdc++ 12 fail on features this PR uses - maybe we could mention #36042 as a dependency.

> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: GCC 12 and NetBSD's libstdc++ 12 fail on features this PR uses - maybe we could mention #36042 as a dependency.
l0rinc (Migrated from github.com) commented 2026-11-25 12:36:47 +00:00

aa80723 build: Require C++23 compiler:

Cap'n Proto 0.9.2 headers fail with GCC 14 and Apple Clang in C++23. The libmultiprocess compatibility check could be updated separately to cover C++23. Here, requiring Cap'n Proto 1.0 when IPC is enabled would cover bundled and external libmultiprocess builds.

Example patch
diff --git a/CMakeLists.txt b/CMakeLists.txt
index a48902d3c3..7b67b25fd4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -256,6 +256,11 @@ if(WITH_ZMQ)
   find_package(ZeroMQ 4.0.0 MODULE REQUIRED)
 endif()
 
+if(ENABLE_IPC)
+  # Older Cap'n Proto headers fail with compilers that implement P2468R2.
+  find_package(CapnProto 1.0 CONFIG REQUIRED)
+endif()
+
 if(ENABLE_IPC AND WITH_EXTERNAL_LIBMULTIPROCESS)
   find_package(Libmultiprocess REQUIRED COMPONENTS Lib)
   find_package(LibmultiprocessNative REQUIRED COMPONENTS Bin
diff --git a/doc/dependencies.md b/doc/dependencies.md
index a0f71f579b..5e2a282b4e 100644
--- a/doc/dependencies.md
+++ b/doc/dependencies.md
@@ -37,7 +37,7 @@ with support for C++23 features including std::byteswap and std::views::zip.
 
 | Dependency | Releases | Minimum required |
 | --- | --- | --- |
-| [Cap'n Proto](../depends/packages/native_capnp.mk) ([IPC](multiprocess.md)) | [link](https://capnproto.org/) | [0.9.2](https://github.com/bitcoin/bitcoin/pull/36747) (1.0 with Clang) |
+| [Cap'n Proto](../depends/packages/native_capnp.mk) ([IPC](multiprocess.md)) | [link](https://capnproto.org/) | [1.0](https://github.com/bitcoin/bitcoin/pull/36033) |
 | [libmultiprocess](../depends/packages/native_libmultiprocess.mk) ([IPC](multiprocess.md)) | [link](https://github.com/bitcoin-core/libmultiprocess/tags) | [v14.0](https://github.com/bitcoin/bitcoin/pull/36817) |
 | Python (scripts, tests) | [link](https://www.python.org) | [3.10](https://github.com/bitcoin/bitcoin/pull/30527) |
 | [Qt](../depends/packages/qt.mk) (gui) | [link](https://download.qt.io/archive/qt/) | [6.2](https://github.com/bitcoin/bitcoin/pull/30997) |
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: Cap'n Proto 0.9.2 headers fail with GCC 14 and Apple Clang in C++23. The libmultiprocess compatibility check could be updated separately to cover C++23. Here, requiring Cap'n Proto 1.0 when IPC is enabled would cover bundled and external libmultiprocess builds. <details><summary>Example patch</summary> ```diff diff --git a/CMakeLists.txt b/CMakeLists.txt index a48902d3c3..7b67b25fd4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -256,6 +256,11 @@ if(WITH_ZMQ) find_package(ZeroMQ 4.0.0 MODULE REQUIRED) endif() +if(ENABLE_IPC) + # Older Cap'n Proto headers fail with compilers that implement P2468R2. + find_package(CapnProto 1.0 CONFIG REQUIRED) +endif() + if(ENABLE_IPC AND WITH_EXTERNAL_LIBMULTIPROCESS) find_package(Libmultiprocess REQUIRED COMPONENTS Lib) find_package(LibmultiprocessNative REQUIRED COMPONENTS Bin diff --git a/doc/dependencies.md b/doc/dependencies.md index a0f71f579b..5e2a282b4e 100644 --- a/doc/dependencies.md +++ b/doc/dependencies.md @@ -37,7 +37,7 @@ with support for C++23 features including std::byteswap and std::views::zip. | Dependency | Releases | Minimum required | | --- | --- | --- | -| [Cap'n Proto](../depends/packages/native_capnp.mk) ([IPC](multiprocess.md)) | [link](https://capnproto.org/) | [0.9.2](https://github.com/bitcoin/bitcoin/pull/36747) (1.0 with Clang) | +| [Cap'n Proto](../depends/packages/native_capnp.mk) ([IPC](multiprocess.md)) | [link](https://capnproto.org/) | [1.0](https://github.com/bitcoin/bitcoin/pull/36033) | | [libmultiprocess](../depends/packages/native_libmultiprocess.mk) ([IPC](multiprocess.md)) | [link](https://github.com/bitcoin-core/libmultiprocess/tags) | [v14.0](https://github.com/bitcoin/bitcoin/pull/36817) | | Python (scripts, tests) | [link](https://www.python.org) | [3.10](https://github.com/bitcoin/bitcoin/pull/30527) | | [Qt](../depends/packages/qt.mk) (gui) | [link](https://download.qt.io/archive/qt/) | [6.2](https://github.com/bitcoin/bitcoin/pull/30997) | ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:37:44 +00:00

aa80723 build: Require C++23 compiler:

After the C++23 switch, network, RPC, tests, and the chainstate demo still cast enums through their underlying types. std::to_underlying expresses those conversions directly.

Example patch
diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp
index fc611fcb78..4ae41c63fd 100644
--- a/src/bitcoin-chainstate.cpp
+++ b/src/bitcoin-chainstate.cpp
@@ -20,6 +20,7 @@
 #include <optional>
 #include <string>
 #include <string_view>
+#include <utility>
 #include <vector>
 
 using namespace btck;
@@ -130,7 +131,7 @@ public:
 
     void WarningUnsetHandler(Warning warning) override
     {
-        std::cout << "Warning unset: " << static_cast<std::underlying_type_t<Warning>>(warning) << std::endl;
+        std::cout << "Warning unset: " << std::to_underlying(warning) << std::endl;
     }
 
     void FlushErrorHandler(std::string_view error) override
diff --git a/src/net_permissions.h b/src/net_permissions.h
index f51d9b4a8f..95cb323d95 100644
--- a/src/net_permissions.h
+++ b/src/net_permissions.h
@@ -9,7 +9,7 @@
 #include <netbase.h>
 
 #include <string>
-#include <type_traits>
+#include <utility>
 #include <vector>
 
 struct bilingual_str;
@@ -48,8 +48,7 @@ enum class NetPermissionFlags : uint32_t {
 };
 constexpr NetPermissionFlags operator|(NetPermissionFlags a, NetPermissionFlags b)
 {
-    using t = std::underlying_type_t<NetPermissionFlags>;
-    return static_cast<NetPermissionFlags>(static_cast<t>(a) | static_cast<t>(b));
+    return static_cast<NetPermissionFlags>(std::to_underlying(a) | std::to_underlying(b));
 }
 
 class NetPermissions
@@ -59,8 +58,7 @@ public:
     static std::vector<std::string> ToStrings(NetPermissionFlags flags);
     static inline bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
     {
-        using t = std::underlying_type_t<NetPermissionFlags>;
-        return (static_cast<t>(flags) & static_cast<t>(f)) == static_cast<t>(f);
+        return (std::to_underlying(flags) & std::to_underlying(f)) == std::to_underlying(f);
     }
     static inline void AddFlag(NetPermissionFlags& flags, NetPermissionFlags f)
     {
@@ -74,8 +72,7 @@ public:
     static inline void ClearFlag(NetPermissionFlags& flags, NetPermissionFlags f)
     {
         assert(f == NetPermissionFlags::Implicit);
-        using t = std::underlying_type_t<NetPermissionFlags>;
-        flags = static_cast<NetPermissionFlags>(static_cast<t>(flags) & ~static_cast<t>(f));
+        flags = static_cast<NetPermissionFlags>(std::to_underlying(flags) & ~std::to_underlying(f));
     }
 };
 
diff --git a/src/netbase.h b/src/netbase.h
index 12f7110d04..6512f9de40 100644
--- a/src/netbase.h
+++ b/src/netbase.h
@@ -17,8 +17,8 @@
 #include <memory>
 #include <optional>
 #include <string>
-#include <type_traits>
 #include <unordered_set>
+#include <utility>
 #include <vector>
 
 extern int nConnectTimeout;
@@ -39,13 +39,11 @@ enum class ConnectionDirection {
     Both = (In | Out),
 };
 static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {
-    using underlying = std::underlying_type_t<ConnectionDirection>;
-    a = ConnectionDirection(underlying(a) | underlying(b));
+    a = ConnectionDirection(std::to_underlying(a) | std::to_underlying(b));
     return a;
 }
 static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {
-    using underlying = std::underlying_type_t<ConnectionDirection>;
-    return (underlying(a) & underlying(b));
+    return std::to_underlying(a) & std::to_underlying(b);
 }
 
 /**
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index 5590dd3581..648a02c635 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -60,7 +60,6 @@
 #include <stdexcept>
 #include <string>
 #include <string_view>
-#include <type_traits>
 #include <utility>
 #include <vector>
 
@@ -1020,7 +1019,7 @@ static RPCMethod getnodeaddresses()
     for (const CAddress& addr : vAddr) {
         UniValue obj(UniValue::VOBJ);
         obj.pushKV("time", TicksSinceEpoch<std::chrono::seconds>(addr.nTime));
-        obj.pushKV("services", static_cast<std::underlying_type_t<decltype(addr.nServices)>>(addr.nServices));
+        obj.pushKV("services", std::to_underlying(addr.nServices));
         obj.pushKV("address", addr.ToStringAddr());
         obj.pushKV("port", addr.GetPort());
         obj.pushKV("network", GetNetworkName(addr.GetNetClass()));
@@ -1238,7 +1237,7 @@ UniValue AddrmanEntryToJSON(const AddrInfo& info, const CConnman& connman)
         ret.pushKV("mapped_as", mapped_as);
     }
     ret.pushKV("port", info.GetPort());
-    ret.pushKV("services", static_cast<std::underlying_type_t<decltype(info.nServices)>>(info.nServices));
+    ret.pushKV("services", std::to_underlying(info.nServices));
     ret.pushKV("time", TicksSinceEpoch<std::chrono::seconds>(info.nTime));
     ret.pushKV("network", GetNetworkName(info.GetNetClass()));
     ret.pushKV("source", info.source.ToStringAddr());
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index 448bc191a6..4dba99bd17 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -51,8 +51,7 @@ const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hu
 std::string GetAllOutputTypes()
 {
     std::vector<std::string> ret;
-    using U = std::underlying_type_t<TxoutType>;
-    for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
+    for (auto i = std::to_underlying(TxoutType::NONSTANDARD); i <= std::to_underlying(TxoutType::WITNESS_UNKNOWN); ++i) {
         ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
     }
     return Join(ret, ", ");
diff --git a/src/test/util/common.h b/src/test/util/common.h
index aa2fc1896f..a6a051e26d 100644
--- a/src/test/util/common.h
+++ b/src/test/util/common.h
@@ -56,7 +56,7 @@ inline std::ostream& operator<<(std::ostream& os, const std::chrono::time_point<
 template <typename T> requires std::is_enum_v<T>
 inline std::ostream& operator<<(std::ostream& os, const T& e)
 {
-    return os << static_cast<std::underlying_type_t<T>>(e);
+    return os << std::to_underlying(e);
 }
 
 template <typename T>
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: After the C++23 switch, network, RPC, tests, and the chainstate demo still cast enums through their underlying types. `std::to_underlying` expresses those conversions directly. <details><summary>Example patch</summary> ```diff diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index fc611fcb78..4ae41c63fd 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -20,6 +20,7 @@ #include <optional> #include <string> #include <string_view> +#include <utility> #include <vector> using namespace btck; @@ -130,7 +131,7 @@ public: void WarningUnsetHandler(Warning warning) override { - std::cout << "Warning unset: " << static_cast<std::underlying_type_t<Warning>>(warning) << std::endl; + std::cout << "Warning unset: " << std::to_underlying(warning) << std::endl; } void FlushErrorHandler(std::string_view error) override diff --git a/src/net_permissions.h b/src/net_permissions.h index f51d9b4a8f..95cb323d95 100644 --- a/src/net_permissions.h +++ b/src/net_permissions.h @@ -9,7 +9,7 @@ #include <netbase.h> #include <string> -#include <type_traits> +#include <utility> #include <vector> struct bilingual_str; @@ -48,8 +48,7 @@ enum class NetPermissionFlags : uint32_t { }; constexpr NetPermissionFlags operator|(NetPermissionFlags a, NetPermissionFlags b) { - using t = std::underlying_type_t<NetPermissionFlags>; - return static_cast<NetPermissionFlags>(static_cast<t>(a) | static_cast<t>(b)); + return static_cast<NetPermissionFlags>(std::to_underlying(a) | std::to_underlying(b)); } class NetPermissions @@ -59,8 +58,7 @@ public: static std::vector<std::string> ToStrings(NetPermissionFlags flags); static inline bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f) { - using t = std::underlying_type_t<NetPermissionFlags>; - return (static_cast<t>(flags) & static_cast<t>(f)) == static_cast<t>(f); + return (std::to_underlying(flags) & std::to_underlying(f)) == std::to_underlying(f); } static inline void AddFlag(NetPermissionFlags& flags, NetPermissionFlags f) { @@ -74,8 +72,7 @@ public: static inline void ClearFlag(NetPermissionFlags& flags, NetPermissionFlags f) { assert(f == NetPermissionFlags::Implicit); - using t = std::underlying_type_t<NetPermissionFlags>; - flags = static_cast<NetPermissionFlags>(static_cast<t>(flags) & ~static_cast<t>(f)); + flags = static_cast<NetPermissionFlags>(std::to_underlying(flags) & ~std::to_underlying(f)); } }; diff --git a/src/netbase.h b/src/netbase.h index 12f7110d04..6512f9de40 100644 --- a/src/netbase.h +++ b/src/netbase.h @@ -17,8 +17,8 @@ #include <memory> #include <optional> #include <string> -#include <type_traits> #include <unordered_set> +#include <utility> #include <vector> extern int nConnectTimeout; @@ -39,13 +39,11 @@ enum class ConnectionDirection { Both = (In | Out), }; static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) { - using underlying = std::underlying_type_t<ConnectionDirection>; - a = ConnectionDirection(underlying(a) | underlying(b)); + a = ConnectionDirection(std::to_underlying(a) | std::to_underlying(b)); return a; } static inline bool operator&(ConnectionDirection a, ConnectionDirection b) { - using underlying = std::underlying_type_t<ConnectionDirection>; - return (underlying(a) & underlying(b)); + return std::to_underlying(a) & std::to_underlying(b); } /** diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp index 5590dd3581..648a02c635 100644 --- a/src/rpc/net.cpp +++ b/src/rpc/net.cpp @@ -60,7 +60,6 @@ #include <stdexcept> #include <string> #include <string_view> -#include <type_traits> #include <utility> #include <vector> @@ -1020,7 +1019,7 @@ static RPCMethod getnodeaddresses() for (const CAddress& addr : vAddr) { UniValue obj(UniValue::VOBJ); obj.pushKV("time", TicksSinceEpoch<std::chrono::seconds>(addr.nTime)); - obj.pushKV("services", static_cast<std::underlying_type_t<decltype(addr.nServices)>>(addr.nServices)); + obj.pushKV("services", std::to_underlying(addr.nServices)); obj.pushKV("address", addr.ToStringAddr()); obj.pushKV("port", addr.GetPort()); obj.pushKV("network", GetNetworkName(addr.GetNetClass())); @@ -1238,7 +1237,7 @@ UniValue AddrmanEntryToJSON(const AddrInfo& info, const CConnman& connman) ret.pushKV("mapped_as", mapped_as); } ret.pushKV("port", info.GetPort()); - ret.pushKV("services", static_cast<std::underlying_type_t<decltype(info.nServices)>>(info.nServices)); + ret.pushKV("services", std::to_underlying(info.nServices)); ret.pushKV("time", TicksSinceEpoch<std::chrono::seconds>(info.nTime)); ret.pushKV("network", GetNetworkName(info.GetNetClass())); ret.pushKV("source", info.source.ToStringAddr()); diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp index 448bc191a6..4dba99bd17 100644 --- a/src/rpc/util.cpp +++ b/src/rpc/util.cpp @@ -51,8 +51,7 @@ const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hu std::string GetAllOutputTypes() { std::vector<std::string> ret; - using U = std::underlying_type_t<TxoutType>; - for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) { + for (auto i = std::to_underlying(TxoutType::NONSTANDARD); i <= std::to_underlying(TxoutType::WITNESS_UNKNOWN); ++i) { ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i))); } return Join(ret, ", "); diff --git a/src/test/util/common.h b/src/test/util/common.h index aa2fc1896f..a6a051e26d 100644 --- a/src/test/util/common.h +++ b/src/test/util/common.h @@ -56,7 +56,7 @@ inline std::ostream& operator<<(std::ostream& os, const std::chrono::time_point< template <typename T> requires std::is_enum_v<T> inline std::ostream& operator<<(std::ostream& os, const T& e) { - return os << static_cast<std::underlying_type_t<T>>(e); + return os << std::to_underlying(e); } template <typename T> ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:38:03 +00:00

aa80723 build: Require C++23 compiler:

transaction_identifier::FromHex and two descriptor counts can use optional::transform after C++23. TapSatisfier::FromPKHBytes can construct optional<XOnlyPubKey> from optional<CPubKey> directly, and that cleanup could land earlier.

Example patch
diff --git a/src/primitives/transaction_identifier.h b/src/primitives/transaction_identifier.h
index 9479d2be51..5bcc4faeec 100644
--- a/src/primitives/transaction_identifier.h
+++ b/src/primitives/transaction_identifier.h
@@ -42,9 +42,7 @@ public:
     constexpr void SetNull() { m_wrapped.SetNull(); }
     static std::optional<transaction_identifier> FromHex(std::string_view hex)
     {
-        auto u{uint256::FromHex(hex)};
-        if (!u) return std::nullopt;
-        return FromUint256(*u);
+        return uint256::FromHex(hex).transform(FromUint256);
     }
     std::string GetHex() const { return m_wrapped.GetHex(); }
     std::string ToString() const { return m_wrapped.ToString(); }
diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp
index 4212a2bff7..b76d94860d 100644
--- a/src/script/descriptor.cpp
+++ b/src/script/descriptor.cpp
@@ -1505,8 +1505,7 @@ public:
     }
 
     std::optional<int64_t> MaxSatisfactionElems() const override {
-        if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
-        return {};
+        return m_subdescriptor_args[0]->MaxSatisfactionElems().transform([](auto sub_elems) { return 1 + sub_elems; });
     }
 
     std::unique_ptr<DescriptorImpl> Clone() const override
@@ -1546,8 +1545,7 @@ public:
     }
 
     std::optional<int64_t> MaxSatisfactionElems() const override {
-        if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
-        return {};
+        return m_subdescriptor_args[0]->MaxSatisfactionElems().transform([](auto sub_elems) { return 1 + sub_elems; });
     }
 
     std::unique_ptr<DescriptorImpl> Clone() const override
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index 924ff983b9..dcdb34b0d9 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -534,8 +534,7 @@ struct TapSatisfier: Satisfier<XOnlyPubKey> {
     //! Conversion from a raw xonly public key hash.
     template<typename I>
     std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
-        if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
-        return {};
+        return std::optional<XOnlyPubKey>{Satisfier::CPubFromPKHBytes(first, last)};
     }
 
     //! Satisfy a BIP340 signature check.
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: `transaction_identifier::FromHex` and two descriptor counts can use `optional::transform` after C++23. `TapSatisfier::FromPKHBytes` can construct `optional<XOnlyPubKey>` from `optional<CPubKey>` directly, and that cleanup could land earlier. <details><summary>Example patch</summary> ```diff diff --git a/src/primitives/transaction_identifier.h b/src/primitives/transaction_identifier.h index 9479d2be51..5bcc4faeec 100644 --- a/src/primitives/transaction_identifier.h +++ b/src/primitives/transaction_identifier.h @@ -42,9 +42,7 @@ public: constexpr void SetNull() { m_wrapped.SetNull(); } static std::optional<transaction_identifier> FromHex(std::string_view hex) { - auto u{uint256::FromHex(hex)}; - if (!u) return std::nullopt; - return FromUint256(*u); + return uint256::FromHex(hex).transform(FromUint256); } std::string GetHex() const { return m_wrapped.GetHex(); } std::string ToString() const { return m_wrapped.ToString(); } diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp index 4212a2bff7..b76d94860d 100644 --- a/src/script/descriptor.cpp +++ b/src/script/descriptor.cpp @@ -1505,8 +1505,7 @@ public: } std::optional<int64_t> MaxSatisfactionElems() const override { - if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems; - return {}; + return m_subdescriptor_args[0]->MaxSatisfactionElems().transform([](auto sub_elems) { return 1 + sub_elems; }); } std::unique_ptr<DescriptorImpl> Clone() const override @@ -1546,8 +1545,7 @@ public: } std::optional<int64_t> MaxSatisfactionElems() const override { - if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems; - return {}; + return m_subdescriptor_args[0]->MaxSatisfactionElems().transform([](auto sub_elems) { return 1 + sub_elems; }); } std::unique_ptr<DescriptorImpl> Clone() const override diff --git a/src/script/sign.cpp b/src/script/sign.cpp index 924ff983b9..dcdb34b0d9 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -534,8 +534,7 @@ struct TapSatisfier: Satisfier<XOnlyPubKey> { //! Conversion from a raw xonly public key hash. template<typename I> std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const { - if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey}; - return {}; + return std::optional<XOnlyPubKey>{Satisfier::CPubFromPKHBytes(first, last)}; } //! Satisfy a BIP340 signature check. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:38:15 +00:00

aa80723 build: Require C++23 compiler:

fold_left can take each fee vector directly with the existing CAmount{0} seed. This is a small optional cleanup.

Example patch
diff --git a/src/node/block_template_manager.cpp b/src/node/block_template_manager.cpp
index 4336cfd592..f9556de723 100644
--- a/src/node/block_template_manager.cpp
+++ b/src/node/block_template_manager.cpp
@@ -25,7 +25,7 @@
 #include <algorithm>
 #include <compare>
 #include <condition_variable>
-#include <numeric>
+#include <functional>
 #include <utility>
 #include <vector>
 
@@ -172,11 +172,11 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock(
 
             // Calculate the original template total fees if we haven't already
             if (current_fees == -1) {
-                current_fees = std::accumulate(block_template.vTxFees.begin(), block_template.vTxFees.end(), CAmount{0});
+                current_fees = std::ranges::fold_left(block_template.vTxFees, CAmount{0}, std::plus{});
             }
 
             // Check if fees increased enough to return the new template
-            const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
+            const CAmount new_fees = std::ranges::fold_left(new_tmpl->vTxFees, CAmount{0}, std::plus{});
             Assume(wait_options.fee_threshold != MAX_MONEY);
             if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl;
         }
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: `fold_left` can take each fee vector directly with the existing `CAmount{0}` seed. This is a small optional cleanup. <details><summary>Example patch</summary> ```diff diff --git a/src/node/block_template_manager.cpp b/src/node/block_template_manager.cpp index 4336cfd592..f9556de723 100644 --- a/src/node/block_template_manager.cpp +++ b/src/node/block_template_manager.cpp @@ -25,7 +25,7 @@ #include <algorithm> #include <compare> #include <condition_variable> -#include <numeric> +#include <functional> #include <utility> #include <vector> @@ -172,11 +172,11 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock( // Calculate the original template total fees if we haven't already if (current_fees == -1) { - current_fees = std::accumulate(block_template.vTxFees.begin(), block_template.vTxFees.end(), CAmount{0}); + current_fees = std::ranges::fold_left(block_template.vTxFees, CAmount{0}, std::plus{}); } // Check if fees increased enough to return the new template - const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0}); + const CAmount new_fees = std::ranges::fold_left(new_tmpl->vTxFees, CAmount{0}, std::plus{}); Assume(wait_options.fee_threshold != MAX_MONEY); if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:41:32 +00:00

aa80723 build: Require C++23 compiler:

The RISC-V link test still compiles and links its internal-header consumer as C++20. I'd update both flags to C++23 for this migration.

Example patch
diff --git a/ci/test/link-riscv.sh b/ci/test/link-riscv.sh
index 93bebfa8a9..bba7d5f1a9 100755
--- a/ci/test/link-riscv.sh
+++ b/ci/test/link-riscv.sh
@@ -17,7 +17,7 @@ LIBM=$("${GCC}" -print-file-name=libm.a)
 
 echo -e "#include <script/script_error.h>\n int main() { return ScriptErrorString(ScriptError_t::SCRIPT_ERR_UNKNOWN_ERROR).size() > 0; }" > test.cpp
 
-"${GXX}" -I "${BASE_ROOT_DIR}"/src -g -std=c++20 -c test.cpp -o test.o
+"${GXX}" -I "${BASE_ROOT_DIR}"/src -g -std=c++23 -c test.cpp -o test.o
 
 # Make the binary executable on linux for testing purposes
 echo -e ".section .text
@@ -52,7 +52,7 @@ echo -e "#include <sys/stat.h>
 
 "${GCC}" -g -c syscalls.c -o syscalls.o
 
-"${GXX}" -g -std=c++20 \
+"${GXX}" -g -std=c++23 \
     -nostdlib \
     "${CRTBEGIN}" \
     test.o \
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: The RISC-V link test still compiles and links its internal-header consumer as C++20. I'd update both flags to C++23 for this migration. <details><summary>Example patch</summary> ```diff diff --git a/ci/test/link-riscv.sh b/ci/test/link-riscv.sh index 93bebfa8a9..bba7d5f1a9 100755 --- a/ci/test/link-riscv.sh +++ b/ci/test/link-riscv.sh @@ -17,7 +17,7 @@ LIBM=$("${GCC}" -print-file-name=libm.a) echo -e "#include <script/script_error.h>\n int main() { return ScriptErrorString(ScriptError_t::SCRIPT_ERR_UNKNOWN_ERROR).size() > 0; }" > test.cpp -"${GXX}" -I "${BASE_ROOT_DIR}"/src -g -std=c++20 -c test.cpp -o test.o +"${GXX}" -I "${BASE_ROOT_DIR}"/src -g -std=c++23 -c test.cpp -o test.o # Make the binary executable on linux for testing purposes echo -e ".section .text @@ -52,7 +52,7 @@ echo -e "#include <sys/stat.h> "${GCC}" -g -c syscalls.c -o syscalls.o -"${GXX}" -g -std=c++20 \ +"${GXX}" -g -std=c++23 \ -nostdlib \ "${CRTBEGIN}" \ test.o \ ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:41:41 +00:00

aa80723 build: Require C++23 compiler:

Most hunks are ordinary C++20 cleanup and could land on master now. The NUMS_H lambda needs C++23, and the CMake probe should change to -std=c++23 only with this PR.

Example patch
diff --git a/cmake/module/TestAppendRequiredLibraries.cmake b/cmake/module/TestAppendRequiredLibraries.cmake
index 3ff857c6cd..1eec3f18e3 100644
--- a/cmake/module/TestAppendRequiredLibraries.cmake
+++ b/cmake/module/TestAppendRequiredLibraries.cmake
@@ -43,7 +43,7 @@ endfunction()
 # Clang, when building for 32-bit,
 # and linking against libstdc++, requires linking with
 # -latomic if using the C++ atomic library.
-# Can be tested with: clang++ -std=c++20 test.cpp -m32
+# Can be tested with: clang++ -std=c++23 test.cpp -m32
 #
 # Sourced from http://bugs.debian.org/797228
 function(test_append_atomic_library target)
diff --git a/src/prevector.h b/src/prevector.h
index e8a71bc9a0..05cdf09b41 100644
--- a/src/prevector.h
+++ b/src/prevector.h
@@ -30,8 +30,8 @@
  *    - T* indirect: a pointer to an array of capacity elements of type T
  *      (only the first _size are initialized).
  *
- *  The data type T must be movable by memmove/realloc(). Once we switch to C++,
- *  move constructors can be used instead.
+ *  The element type T must be trivially copyable because storage can be
+ *  relocated with memmove() or realloc().
  */
 template<unsigned int N, typename T, typename Size = uint32_t, typename Diff = int32_t>
 class prevector {
diff --git a/src/pubkey.cpp b/src/pubkey.cpp
index 0c2d975439..eba9ed0d78 100644
--- a/src/pubkey.cpp
+++ b/src/pubkey.cpp
@@ -194,7 +194,7 @@ int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned
  */
 constexpr XOnlyPubKey XOnlyPubKey::NUMS_H{
     // Use immediate lambda to work around GCC-14 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117966
-    []() consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(),
+    [] consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(),
 };
 
 std::vector<CPubKey> XOnlyPubKey::GetCPubKeys() const
diff --git a/src/random.h b/src/random.h
index f0c0dcee81..ba45a967b7 100644
--- a/src/random.h
+++ b/src/random.h
@@ -343,10 +343,10 @@ public:
 
     /** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
     template <StdChronoDuration Dur>
-    Dur randrange(std::common_type_t<Dur> range) noexcept
+    Dur randrange(std::type_identity_t<Dur> range) noexcept
     // Having the compiler infer the template argument from the function argument
     // is dangerous, because the desired return value generally has a different
-    // type than the function argument. So std::common_type is used to force the
+    // type than the function argument. So std::type_identity is used to force the
     // call site to specify the type of the return value.
     {
         return Dur{Impl().randrange(range.count())};
diff --git a/src/test/fuzz/util.h b/src/test/fuzz/util.h
index d85333fc38..dc706c63cb 100644
--- a/src/test/fuzz/util.h
+++ b/src/test/fuzz/util.h
@@ -164,9 +164,9 @@ template <typename WeakEnumType, size_t size>
 template <class Dur>
 // Having the compiler infer the template argument from the function argument
 // is dangerous, because the desired return value generally has a different
-// type than the function argument. So std::common_type is used to force the
+// type than the function argument. So std::type_identity is used to force the
 // call site to specify the type of the return value.
-[[nodiscard]] Dur ConsumeDuration(FuzzedDataProvider& fuzzed_data_provider, std::common_type_t<Dur> min, std::common_type_t<Dur> max) noexcept
+[[nodiscard]] Dur ConsumeDuration(FuzzedDataProvider& fuzzed_data_provider, std::type_identity_t<Dur> min, std::type_identity_t<Dur> max) noexcept
 {
     return Dur{fuzzed_data_provider.ConsumeIntegralInRange(min.count(), max.count())};
 }
diff --git a/src/test/miniminer_tests.cpp b/src/test/miniminer_tests.cpp
index c5048ceb45..c066a7feca 100644
--- a/src/test/miniminer_tests.cpp
+++ b/src/test/miniminer_tests.cpp
@@ -44,9 +44,8 @@ static inline bool sanity_check(const std::vector<CTransactionRef>& transactions
     for (const auto& [outpoint, fee] : bumpfees) {
         if (fee < 0) return false;
         if (fee == 0) continue;
-        auto outpoint_ = outpoint; // structured bindings can't be captured in C++17, so we need to use a variable
         const bool found = std::any_of(transactions.cbegin(), transactions.cend(), [&](const auto& tx) {
-            return outpoint_.hash == tx->GetHash() && outpoint_.n < tx->vout.size();
+            return outpoint.hash == tx->GetHash() && outpoint.n < tx->vout.size();
         });
         if (!found) return false;
     }
diff --git a/src/threadsafety.h b/src/threadsafety.h
index 35f3b81327..eda7efaedc 100644
--- a/src/threadsafety.h
+++ b/src/threadsafety.h
@@ -50,6 +50,6 @@
 #define SHARED_LOCKS_REQUIRED(...)
 #define NO_THREAD_SAFETY_ANALYSIS
 #define ASSERT_EXCLUSIVE_LOCK(...)
-#endif // __GNUC__
+#endif // __clang__
 
 #endif // BITCOIN_THREADSAFETY_H
diff --git a/src/util/vector.h b/src/util/vector.h
index aa545f224f..7869cf9f91 100644
--- a/src/util/vector.h
+++ b/src/util/vector.h
@@ -6,7 +6,6 @@
 #define BITCOIN_UTIL_VECTOR_H
 
 #include <functional>
-#include <initializer_list>
 #include <optional>
 #include <type_traits>
 #include <utility>
@@ -24,8 +23,7 @@ inline std::vector<std::common_type_t<Args...>> Vector(Args&&... args)
 {
     std::vector<std::common_type_t<Args...>> ret;
     ret.reserve(sizeof...(args));
-    // The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html
-    (void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...};
+    (ret.emplace_back(std::forward<Args>(args)), ...);
     return ret;
 }
 
@@ -62,7 +60,7 @@ inline void ClearShrink(V& v) noexcept
     // 3. v = {}; v.shrink_to_fit();
     // 4. v.clear(); v.shrink_to_fit();
     //
-    // (2) does not appear to release memory in glibc debug mode, even if v.shrink_to_fit()
+    // (2) does not appear to release memory in libstdc++ debug mode, even if v.shrink_to_fit()
     // follows. (3) and (4) rely on std::vector::shrink_to_fit, which is only a non-binding
     // request. Therefore, we use method (1).
 
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: Most hunks are ordinary C++20 cleanup and could land on master now. The `NUMS_H` lambda needs C++23, and the CMake probe should change to `-std=c++23` only with this PR. <details><summary>Example patch</summary> ```diff diff --git a/cmake/module/TestAppendRequiredLibraries.cmake b/cmake/module/TestAppendRequiredLibraries.cmake index 3ff857c6cd..1eec3f18e3 100644 --- a/cmake/module/TestAppendRequiredLibraries.cmake +++ b/cmake/module/TestAppendRequiredLibraries.cmake @@ -43,7 +43,7 @@ endfunction() # Clang, when building for 32-bit, # and linking against libstdc++, requires linking with # -latomic if using the C++ atomic library. -# Can be tested with: clang++ -std=c++20 test.cpp -m32 +# Can be tested with: clang++ -std=c++23 test.cpp -m32 # # Sourced from http://bugs.debian.org/797228 function(test_append_atomic_library target) diff --git a/src/prevector.h b/src/prevector.h index e8a71bc9a0..05cdf09b41 100644 --- a/src/prevector.h +++ b/src/prevector.h @@ -30,8 +30,8 @@ * - T* indirect: a pointer to an array of capacity elements of type T * (only the first _size are initialized). * - * The data type T must be movable by memmove/realloc(). Once we switch to C++, - * move constructors can be used instead. + * The element type T must be trivially copyable because storage can be + * relocated with memmove() or realloc(). */ template<unsigned int N, typename T, typename Size = uint32_t, typename Diff = int32_t> class prevector { diff --git a/src/pubkey.cpp b/src/pubkey.cpp index 0c2d975439..eba9ed0d78 100644 --- a/src/pubkey.cpp +++ b/src/pubkey.cpp @@ -194,7 +194,7 @@ int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned */ constexpr XOnlyPubKey XOnlyPubKey::NUMS_H{ // Use immediate lambda to work around GCC-14 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117966 - []() consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(), + [] consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(), }; std::vector<CPubKey> XOnlyPubKey::GetCPubKeys() const diff --git a/src/random.h b/src/random.h index f0c0dcee81..ba45a967b7 100644 --- a/src/random.h +++ b/src/random.h @@ -343,10 +343,10 @@ public: /** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */ template <StdChronoDuration Dur> - Dur randrange(std::common_type_t<Dur> range) noexcept + Dur randrange(std::type_identity_t<Dur> range) noexcept // Having the compiler infer the template argument from the function argument // is dangerous, because the desired return value generally has a different - // type than the function argument. So std::common_type is used to force the + // type than the function argument. So std::type_identity is used to force the // call site to specify the type of the return value. { return Dur{Impl().randrange(range.count())}; diff --git a/src/test/fuzz/util.h b/src/test/fuzz/util.h index d85333fc38..dc706c63cb 100644 --- a/src/test/fuzz/util.h +++ b/src/test/fuzz/util.h @@ -164,9 +164,9 @@ template <typename WeakEnumType, size_t size> template <class Dur> // Having the compiler infer the template argument from the function argument // is dangerous, because the desired return value generally has a different -// type than the function argument. So std::common_type is used to force the +// type than the function argument. So std::type_identity is used to force the // call site to specify the type of the return value. -[[nodiscard]] Dur ConsumeDuration(FuzzedDataProvider& fuzzed_data_provider, std::common_type_t<Dur> min, std::common_type_t<Dur> max) noexcept +[[nodiscard]] Dur ConsumeDuration(FuzzedDataProvider& fuzzed_data_provider, std::type_identity_t<Dur> min, std::type_identity_t<Dur> max) noexcept { return Dur{fuzzed_data_provider.ConsumeIntegralInRange(min.count(), max.count())}; } diff --git a/src/test/miniminer_tests.cpp b/src/test/miniminer_tests.cpp index c5048ceb45..c066a7feca 100644 --- a/src/test/miniminer_tests.cpp +++ b/src/test/miniminer_tests.cpp @@ -44,9 +44,8 @@ static inline bool sanity_check(const std::vector<CTransactionRef>& transactions for (const auto& [outpoint, fee] : bumpfees) { if (fee < 0) return false; if (fee == 0) continue; - auto outpoint_ = outpoint; // structured bindings can't be captured in C++17, so we need to use a variable const bool found = std::any_of(transactions.cbegin(), transactions.cend(), [&](const auto& tx) { - return outpoint_.hash == tx->GetHash() && outpoint_.n < tx->vout.size(); + return outpoint.hash == tx->GetHash() && outpoint.n < tx->vout.size(); }); if (!found) return false; } diff --git a/src/threadsafety.h b/src/threadsafety.h index 35f3b81327..eda7efaedc 100644 --- a/src/threadsafety.h +++ b/src/threadsafety.h @@ -50,6 +50,6 @@ #define SHARED_LOCKS_REQUIRED(...) #define NO_THREAD_SAFETY_ANALYSIS #define ASSERT_EXCLUSIVE_LOCK(...) -#endif // __GNUC__ +#endif // __clang__ #endif // BITCOIN_THREADSAFETY_H diff --git a/src/util/vector.h b/src/util/vector.h index aa545f224f..7869cf9f91 100644 --- a/src/util/vector.h +++ b/src/util/vector.h @@ -6,7 +6,6 @@ #define BITCOIN_UTIL_VECTOR_H #include <functional> -#include <initializer_list> #include <optional> #include <type_traits> #include <utility> @@ -24,8 +23,7 @@ inline std::vector<std::common_type_t<Args...>> Vector(Args&&... args) { std::vector<std::common_type_t<Args...>> ret; ret.reserve(sizeof...(args)); - // The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html - (void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...}; + (ret.emplace_back(std::forward<Args>(args)), ...); return ret; } @@ -62,7 +60,7 @@ inline void ClearShrink(V& v) noexcept // 3. v = {}; v.shrink_to_fit(); // 4. v.clear(); v.shrink_to_fit(); // - // (2) does not appear to release memory in glibc debug mode, even if v.shrink_to_fit() + // (2) does not appear to release memory in libstdc++ debug mode, even if v.shrink_to_fit() // follows. (3) and (4) rely on std::vector::shrink_to_fit, which is only a non-binding // request. Therefore, we use method (1). ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:42:51 +00:00

aa80723 build: Require C++23 compiler:

The keypath and descriptor parsers build string_views from both ends of existing character spans, and the descriptor test does the same. C++23 lets these four sites construct the view from the span directly.

Example patch
diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp
index b76d94860d..0767ce4f91 100644
--- a/src/script/descriptor.cpp
+++ b/src/script/descriptor.cpp
@@ -2447,7 +2447,7 @@ std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index
         auto threshold = Expr(expr);
         uint32_t thres;
         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
-        if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
+        if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold})}) {
             thres = *maybe_thres;
         } else {
             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
diff --git a/src/test/descriptor_tests.cpp b/src/test/descriptor_tests.cpp
index 45f63d81bd..35a85610ea 100644
--- a/src/test/descriptor_tests.cpp
+++ b/src/test/descriptor_tests.cpp
@@ -596,7 +596,7 @@ void CheckInferDescriptor(const std::string& script_hex, const std::string& expe
                         hardened = true;
                     }
                 }
-                const uint32_t p{*Assert(ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()}))};
+                const uint32_t p{*Assert(ToIntegral<uint32_t>(std::string_view{elem}))};
                 info.path.push_back(p | (((uint32_t)hardened) << 31));
             }
 
diff --git a/src/util/bip32.cpp b/src/util/bip32.cpp
index f576fc1c06..4edfaa71e0 100644
--- a/src/util/bip32.cpp
+++ b/src/util/bip32.cpp
@@ -17,7 +17,7 @@
 
 util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const char> elem)
 {
-    const std::string_view raw{elem.begin(), elem.end()};
+    const std::string_view raw{elem};
     if (elem.empty()) {
         return util::Unexpected{strprintf("Key path value '%s' is not valid", raw)};
     }
@@ -29,7 +29,7 @@ util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const
         is_hardened = true;
     }
 
-    const auto number{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
+    const auto number{ToIntegral<uint32_t>(std::string_view{elem})};
     if (!number) {
         return util::Unexpected{strprintf("Key path value '%s' is not a valid uint32", raw)};
     }
> [aa80723](https://github.com/bitcoin/bitcoin/pull/36033/changes/aa80723e89ee10a95c3b5dac949d97d4fe07efce) _build: Require C++23 compiler_: The keypath and descriptor parsers build `string_view`s from both ends of existing character spans, and the descriptor test does the same. C++23 lets these four sites construct the view from the span directly. <details><summary>Example patch</summary> ```diff diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp index b76d94860d..0767ce4f91 100644 --- a/src/script/descriptor.cpp +++ b/src/script/descriptor.cpp @@ -2447,7 +2447,7 @@ std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index auto threshold = Expr(expr); uint32_t thres; std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys - if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) { + if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold})}) { thres = *maybe_thres; } else { error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end())); diff --git a/src/test/descriptor_tests.cpp b/src/test/descriptor_tests.cpp index 45f63d81bd..35a85610ea 100644 --- a/src/test/descriptor_tests.cpp +++ b/src/test/descriptor_tests.cpp @@ -596,7 +596,7 @@ void CheckInferDescriptor(const std::string& script_hex, const std::string& expe hardened = true; } } - const uint32_t p{*Assert(ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()}))}; + const uint32_t p{*Assert(ToIntegral<uint32_t>(std::string_view{elem}))}; info.path.push_back(p | (((uint32_t)hardened) << 31)); } diff --git a/src/util/bip32.cpp b/src/util/bip32.cpp index f576fc1c06..4edfaa71e0 100644 --- a/src/util/bip32.cpp +++ b/src/util/bip32.cpp @@ -17,7 +17,7 @@ util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const char> elem) { - const std::string_view raw{elem.begin(), elem.end()}; + const std::string_view raw{elem}; if (elem.empty()) { return util::Unexpected{strprintf("Key path value '%s' is not valid", raw)}; } @@ -29,7 +29,7 @@ util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const is_hardened = true; } - const auto number{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})}; + const auto number{ToIntegral<uint32_t>(std::string_view{elem})}; if (!number) { return util::Unexpected{strprintf("Key path value '%s' is not a valid uint32", raw)}; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:35:00 +00:00

9b0aec1 compat: Use std::byteswap:

The three internal_bswap functions now only forward to std::byteswap.

Example patch
diff --git a/src/common/bip352.h b/src/common/bip352.h
index fd9e0e711d..b29b6be11e 100644
--- a/src/common/bip352.h
+++ b/src/common/bip352.h
@@ -7,7 +7,6 @@
 
 #include <addresstype.h>
 #include <attributes.h>
-#include <compat/byteswap.h>
 #include <key.h>
 #include <primitives/transaction.h>
 #include <pubkey.h>
@@ -15,6 +14,7 @@
 #include <util/expected.h>
 
 #include <array>
+#include <bit>
 #include <compare>
 #include <cstdint>
 #include <cstring>
@@ -62,7 +62,7 @@ struct BIP352Comparator {
         // sort of the outpoints, using the 36-byte serialization:
         // <txid, 32-bytes little-endian>:<vout, 4-bytes little-endian>
         if (a.hash != b.hash) return a.hash < b.hash;
-        return internal_bswap_32(a.n) < internal_bswap_32(b.n);
+        return std::byteswap(a.n) < std::byteswap(b.n);
     }
 };
 
diff --git a/src/compat/byteswap.h b/src/compat/byteswap.h
deleted file mode 100644
index f4c6542126..0000000000
--- a/src/compat/byteswap.h
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2014-present The Bitcoin Core developers
-// Distributed under the MIT software license, see the accompanying
-// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-#ifndef BITCOIN_COMPAT_BYTESWAP_H
-#define BITCOIN_COMPAT_BYTESWAP_H
-
-#include <bit>
-#include <cstdint>
-
-inline constexpr uint16_t internal_bswap_16(uint16_t x)
-{
-    return std::byteswap(x);
-}
-
-inline constexpr uint32_t internal_bswap_32(uint32_t x)
-{
-    return std::byteswap(x);
-}
-
-inline constexpr uint64_t internal_bswap_64(uint64_t x)
-{
-    return std::byteswap(x);
-}
-
-#endif // BITCOIN_COMPAT_BYTESWAP_H
diff --git a/src/compat/endian.h b/src/compat/endian.h
index 7941698b6f..cf99c02eca 100644
--- a/src/compat/endian.h
+++ b/src/compat/endian.h
@@ -5,69 +5,67 @@
 #ifndef BITCOIN_COMPAT_ENDIAN_H
 #define BITCOIN_COMPAT_ENDIAN_H
 
-#include <compat/byteswap.h>
-
 #include <bit>
 #include <cstdint>
 
 inline constexpr uint16_t htobe16_internal(uint16_t host_16bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_16(host_16bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_16bits);
         else return host_16bits;
 }
 inline constexpr uint16_t htole16_internal(uint16_t host_16bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_16(host_16bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_16bits);
         else return host_16bits;
 }
 inline constexpr uint16_t be16toh_internal(uint16_t big_endian_16bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_16(big_endian_16bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_16bits);
         else return big_endian_16bits;
 }
 inline constexpr uint16_t le16toh_internal(uint16_t little_endian_16bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_16(little_endian_16bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_16bits);
         else return little_endian_16bits;
 }
 inline constexpr uint32_t htobe32_internal(uint32_t host_32bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_32(host_32bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_32bits);
         else return host_32bits;
 }
 inline constexpr uint32_t htole32_internal(uint32_t host_32bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_32(host_32bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_32bits);
         else return host_32bits;
 }
 inline constexpr uint32_t be32toh_internal(uint32_t big_endian_32bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_32(big_endian_32bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_32bits);
         else return big_endian_32bits;
 }
 inline constexpr uint32_t le32toh_internal(uint32_t little_endian_32bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_32(little_endian_32bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_32bits);
         else return little_endian_32bits;
 }
 inline constexpr uint64_t htobe64_internal(uint64_t host_64bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_64(host_64bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_64bits);
         else return host_64bits;
 }
 inline constexpr uint64_t htole64_internal(uint64_t host_64bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_64(host_64bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_64bits);
         else return host_64bits;
 }
 inline constexpr uint64_t be64toh_internal(uint64_t big_endian_64bits)
 {
-    if constexpr (std::endian::native == std::endian::little) return internal_bswap_64(big_endian_64bits);
+    if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_64bits);
         else return big_endian_64bits;
 }
 inline constexpr uint64_t le64toh_internal(uint64_t little_endian_64bits)
 {
-    if constexpr (std::endian::native == std::endian::big) return internal_bswap_64(little_endian_64bits);
+    if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_64bits);
         else return little_endian_64bits;
 }
 
diff --git a/src/test/bswap_tests.cpp b/src/test/bswap_tests.cpp
index a2df1ea87c..6014bf07e0 100644
--- a/src/test/bswap_tests.cpp
+++ b/src/test/bswap_tests.cpp
@@ -2,7 +2,10 @@
 // Distributed under the MIT software license, see the accompanying
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 
-#include <compat/byteswap.h>
+#include <compat/endian.h>
+
+#include <bit>
+#include <cstdint>
 
 #include <boost/test/unit_test.hpp>
 
@@ -16,9 +19,13 @@ BOOST_AUTO_TEST_CASE(bswap_tests)
     uint16_t e1 = 0x3412;
     uint32_t e2 = 0xbc9a7856;
     uint64_t e3 = 0xbc9a78563412f0de;
-    BOOST_CHECK(internal_bswap_16(u1) == e1);
-    BOOST_CHECK(internal_bswap_32(u2) == e2);
-    BOOST_CHECK(internal_bswap_64(u3) == e3);
+    constexpr bool little_endian{std::endian::native == std::endian::little};
+    BOOST_CHECK(htobe16_internal(u1) == (little_endian ? e1 : u1));
+    BOOST_CHECK(htobe32_internal(u2) == (little_endian ? e2 : u2));
+    BOOST_CHECK(htobe64_internal(u3) == (little_endian ? e3 : u3));
+    BOOST_CHECK(htole16_internal(u1) == (little_endian ? u1 : e1));
+    BOOST_CHECK(htole32_internal(u2) == (little_endian ? u2 : e2));
+    BOOST_CHECK(htole64_internal(u3) == (little_endian ? u3 : e3));
 }
 
 BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/fuzz/dbwrapper.cpp b/src/test/fuzz/dbwrapper.cpp
index 42fd86bcde..fcae9ed33f 100644
--- a/src/test/fuzz/dbwrapper.cpp
+++ b/src/test/fuzz/dbwrapper.cpp
@@ -3,7 +3,6 @@
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 
 #include <dbwrapper.h>
-#include <compat/byteswap.h>
 #include <random.h>
 #include <sync.h>
 #include <test/fuzz/FuzzedDataProvider.h>
@@ -19,6 +18,7 @@
 #include <leveldb/helpers/memenv/memenv.h>
 
 #include <algorithm>
+#include <bit>
 #include <cstdint>
 #include <deque>
 #include <functional>
@@ -117,7 +117,7 @@ std::vector<uint8_t> MakeValue(uint16_t key, uint32_t size)
 /** Equivalent to leveldb::BytewiseComparator() on 2-byte little-endian
  *  serialized uint16_t keys, while keeping the oracle keyed by uint16_t. */
 struct LevelDBBytewiseU16Cmp {
-    bool operator()(uint16_t a, uint16_t b) const { return internal_bswap_16(a) < internal_bswap_16(b); }
+    bool operator()(uint16_t a, uint16_t b) const { return std::byteswap(a) < std::byteswap(b); }
 };
 
 /** key → value-size map ordered by LevelDB's bytewise comparator. */
diff --git a/src/wallet/migrate.cpp b/src/wallet/migrate.cpp
index 6e5f8a493b..1775fb42b0 100644
--- a/src/wallet/migrate.cpp
+++ b/src/wallet/migrate.cpp
@@ -2,7 +2,6 @@
 // Distributed under the MIT software license, see the accompanying
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 
-#include <compat/byteswap.h>
 #include <crypto/common.h>
 #include <streams.h>
 #include <util/log.h>
@@ -10,6 +9,7 @@
 #include <wallet/migrate.h>
 
 #include <array>
+#include <bit>
 #include <cstddef>
 #include <optional>
 #include <stdexcept>
@@ -135,7 +135,7 @@ public:
         uint32_t uint32_flags;
         s >> uint32_flags;
         if (other_endian) {
-            uint32_flags = internal_bswap_32(uint32_flags);
+            uint32_flags = std::byteswap(uint32_flags);
         }
         flags = static_cast<BTreeFlags>(uint32_flags);
 
@@ -152,23 +152,23 @@ public:
         s >> chksum;
 
         if (other_endian) {
-            lsn_file = internal_bswap_32(lsn_file);
-            lsn_offset = internal_bswap_32(lsn_offset);
-            page_num = internal_bswap_32(page_num);
-            magic = internal_bswap_32(magic);
-            version = internal_bswap_32(version);
-            pagesize = internal_bswap_32(pagesize);
-            free_list = internal_bswap_32(free_list);
-            last_page = internal_bswap_32(last_page);
-            partitions = internal_bswap_32(partitions);
-            key_count = internal_bswap_32(key_count);
-            record_count = internal_bswap_32(record_count);
-            unused2 = internal_bswap_32(unused2);
-            minkey = internal_bswap_32(minkey);
-            re_len = internal_bswap_32(re_len);
-            re_pad = internal_bswap_32(re_pad);
-            root = internal_bswap_32(root);
-            crypto_magic = internal_bswap_32(crypto_magic);
+            lsn_file = std::byteswap(lsn_file);
+            lsn_offset = std::byteswap(lsn_offset);
+            page_num = std::byteswap(page_num);
+            magic = std::byteswap(magic);
+            version = std::byteswap(version);
+            pagesize = std::byteswap(pagesize);
+            free_list = std::byteswap(free_list);
+            last_page = std::byteswap(last_page);
+            partitions = std::byteswap(partitions);
+            key_count = std::byteswap(key_count);
+            record_count = std::byteswap(record_count);
+            unused2 = std::byteswap(unused2);
+            minkey = std::byteswap(minkey);
+            re_len = std::byteswap(re_len);
+            re_pad = std::byteswap(re_pad);
+            root = std::byteswap(root);
+            crypto_magic = std::byteswap(crypto_magic);
         }
 
         // Page number must match
@@ -229,7 +229,7 @@ public:
         deleted = uint8_type & static_cast<uint8_t>(RecordType::DELETE_FLAG);
 
         if (other_endian) {
-            len = internal_bswap_16(len);
+            len = std::byteswap(len);
         }
     }
 };
@@ -280,8 +280,8 @@ public:
         s.read(std::as_writable_bytes(std::span(data.data(), data.size())));
 
         if (m_header.other_endian) {
-            page_num = internal_bswap_32(page_num);
-            records = internal_bswap_32(records);
+            page_num = std::byteswap(page_num);
+            records = std::byteswap(records);
         }
     }
 };
@@ -312,8 +312,8 @@ public:
         s >> item_len;
 
         if (m_header.other_endian) {
-            page_number = internal_bswap_32(page_number);
-            item_len = internal_bswap_32(item_len);
+            page_number = std::byteswap(page_number);
+            item_len = std::byteswap(item_len);
         }
     }
 };
@@ -357,13 +357,13 @@ public:
         type = static_cast<PageType>(uint8_type);
 
         if (other_endian) {
-            lsn_file = internal_bswap_32(lsn_file);
-            lsn_offset = internal_bswap_32(lsn_offset);
-            page_num = internal_bswap_32(page_num);
-            prev_page = internal_bswap_32(prev_page);
-            next_page = internal_bswap_32(next_page);
-            entries = internal_bswap_16(entries);
-            hf_offset = internal_bswap_16(hf_offset);
+            lsn_file = std::byteswap(lsn_file);
+            lsn_offset = std::byteswap(lsn_offset);
+            page_num = std::byteswap(page_num);
+            prev_page = std::byteswap(prev_page);
+            next_page = std::byteswap(next_page);
+            entries = std::byteswap(entries);
+            hf_offset = std::byteswap(hf_offset);
         }
 
         if (expected_page_num != page_num) {
@@ -399,7 +399,7 @@ public:
             uint16_t index;
             s >> index;
             if (m_header.other_endian) {
-                index = internal_bswap_16(index);
+                index = std::byteswap(index);
             }
             indexes.push_back(index);
             pos += sizeof(uint16_t);
@@ -489,7 +489,7 @@ public:
             uint16_t index;
             s >> index;
             if (m_header.other_endian) {
-                index = internal_bswap_16(index);
+                index = std::byteswap(index);
             }
             indexes.push_back(index);
             pos += sizeof(uint16_t);
@@ -575,8 +575,8 @@ void BerkeleyRODatabase::Open()
         SeekToPage(db_file, i, page_size);
         db_file >> file >> offset;
         if (outer_meta.other_endian) {
-            file = internal_bswap_32(file);
-            offset = internal_bswap_32(offset);
+            file = std::byteswap(file);
+            offset = std::byteswap(offset);
         }
         if (file != 0 || offset != 1) {
             throw std::runtime_error("LSNs are not reset, this database is not completely flushed. Please reopen then close the database with a version that has BDB support");
> [9b0aec1](https://github.com/bitcoin/bitcoin/pull/36033/changes/9b0aec18bd87a3a95ade4620668ace56f57498c3) _compat: Use std::byteswap_: The three `internal_bswap` functions now only forward to `std::byteswap`. <details><summary>Example patch</summary> ```patch diff --git a/src/common/bip352.h b/src/common/bip352.h index fd9e0e711d..b29b6be11e 100644 --- a/src/common/bip352.h +++ b/src/common/bip352.h @@ -7,7 +7,6 @@ #include <addresstype.h> #include <attributes.h> -#include <compat/byteswap.h> #include <key.h> #include <primitives/transaction.h> #include <pubkey.h> @@ -15,6 +14,7 @@ #include <util/expected.h> #include <array> +#include <bit> #include <compare> #include <cstdint> #include <cstring> @@ -62,7 +62,7 @@ struct BIP352Comparator { // sort of the outpoints, using the 36-byte serialization: // <txid, 32-bytes little-endian>:<vout, 4-bytes little-endian> if (a.hash != b.hash) return a.hash < b.hash; - return internal_bswap_32(a.n) < internal_bswap_32(b.n); + return std::byteswap(a.n) < std::byteswap(b.n); } }; diff --git a/src/compat/byteswap.h b/src/compat/byteswap.h deleted file mode 100644 index f4c6542126..0000000000 --- a/src/compat/byteswap.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2014-present The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_COMPAT_BYTESWAP_H -#define BITCOIN_COMPAT_BYTESWAP_H - -#include <bit> -#include <cstdint> - -inline constexpr uint16_t internal_bswap_16(uint16_t x) -{ - return std::byteswap(x); -} - -inline constexpr uint32_t internal_bswap_32(uint32_t x) -{ - return std::byteswap(x); -} - -inline constexpr uint64_t internal_bswap_64(uint64_t x) -{ - return std::byteswap(x); -} - -#endif // BITCOIN_COMPAT_BYTESWAP_H diff --git a/src/compat/endian.h b/src/compat/endian.h index 7941698b6f..cf99c02eca 100644 --- a/src/compat/endian.h +++ b/src/compat/endian.h @@ -5,69 +5,67 @@ #ifndef BITCOIN_COMPAT_ENDIAN_H #define BITCOIN_COMPAT_ENDIAN_H -#include <compat/byteswap.h> - #include <bit> #include <cstdint> inline constexpr uint16_t htobe16_internal(uint16_t host_16bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_16(host_16bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_16bits); else return host_16bits; } inline constexpr uint16_t htole16_internal(uint16_t host_16bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_16(host_16bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_16bits); else return host_16bits; } inline constexpr uint16_t be16toh_internal(uint16_t big_endian_16bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_16(big_endian_16bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_16bits); else return big_endian_16bits; } inline constexpr uint16_t le16toh_internal(uint16_t little_endian_16bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_16(little_endian_16bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_16bits); else return little_endian_16bits; } inline constexpr uint32_t htobe32_internal(uint32_t host_32bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_32(host_32bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_32bits); else return host_32bits; } inline constexpr uint32_t htole32_internal(uint32_t host_32bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_32(host_32bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_32bits); else return host_32bits; } inline constexpr uint32_t be32toh_internal(uint32_t big_endian_32bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_32(big_endian_32bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_32bits); else return big_endian_32bits; } inline constexpr uint32_t le32toh_internal(uint32_t little_endian_32bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_32(little_endian_32bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_32bits); else return little_endian_32bits; } inline constexpr uint64_t htobe64_internal(uint64_t host_64bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_64(host_64bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(host_64bits); else return host_64bits; } inline constexpr uint64_t htole64_internal(uint64_t host_64bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_64(host_64bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(host_64bits); else return host_64bits; } inline constexpr uint64_t be64toh_internal(uint64_t big_endian_64bits) { - if constexpr (std::endian::native == std::endian::little) return internal_bswap_64(big_endian_64bits); + if constexpr (std::endian::native == std::endian::little) return std::byteswap(big_endian_64bits); else return big_endian_64bits; } inline constexpr uint64_t le64toh_internal(uint64_t little_endian_64bits) { - if constexpr (std::endian::native == std::endian::big) return internal_bswap_64(little_endian_64bits); + if constexpr (std::endian::native == std::endian::big) return std::byteswap(little_endian_64bits); else return little_endian_64bits; } diff --git a/src/test/bswap_tests.cpp b/src/test/bswap_tests.cpp index a2df1ea87c..6014bf07e0 100644 --- a/src/test/bswap_tests.cpp +++ b/src/test/bswap_tests.cpp @@ -2,7 +2,10 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <compat/byteswap.h> +#include <compat/endian.h> + +#include <bit> +#include <cstdint> #include <boost/test/unit_test.hpp> @@ -16,9 +19,13 @@ BOOST_AUTO_TEST_CASE(bswap_tests) uint16_t e1 = 0x3412; uint32_t e2 = 0xbc9a7856; uint64_t e3 = 0xbc9a78563412f0de; - BOOST_CHECK(internal_bswap_16(u1) == e1); - BOOST_CHECK(internal_bswap_32(u2) == e2); - BOOST_CHECK(internal_bswap_64(u3) == e3); + constexpr bool little_endian{std::endian::native == std::endian::little}; + BOOST_CHECK(htobe16_internal(u1) == (little_endian ? e1 : u1)); + BOOST_CHECK(htobe32_internal(u2) == (little_endian ? e2 : u2)); + BOOST_CHECK(htobe64_internal(u3) == (little_endian ? e3 : u3)); + BOOST_CHECK(htole16_internal(u1) == (little_endian ? u1 : e1)); + BOOST_CHECK(htole32_internal(u2) == (little_endian ? u2 : e2)); + BOOST_CHECK(htole64_internal(u3) == (little_endian ? u3 : e3)); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/fuzz/dbwrapper.cpp b/src/test/fuzz/dbwrapper.cpp index 42fd86bcde..fcae9ed33f 100644 --- a/src/test/fuzz/dbwrapper.cpp +++ b/src/test/fuzz/dbwrapper.cpp @@ -3,7 +3,6 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <dbwrapper.h> -#include <compat/byteswap.h> #include <random.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> @@ -19,6 +18,7 @@ #include <leveldb/helpers/memenv/memenv.h> #include <algorithm> +#include <bit> #include <cstdint> #include <deque> #include <functional> @@ -117,7 +117,7 @@ std::vector<uint8_t> MakeValue(uint16_t key, uint32_t size) /** Equivalent to leveldb::BytewiseComparator() on 2-byte little-endian * serialized uint16_t keys, while keeping the oracle keyed by uint16_t. */ struct LevelDBBytewiseU16Cmp { - bool operator()(uint16_t a, uint16_t b) const { return internal_bswap_16(a) < internal_bswap_16(b); } + bool operator()(uint16_t a, uint16_t b) const { return std::byteswap(a) < std::byteswap(b); } }; /** key → value-size map ordered by LevelDB's bytewise comparator. */ diff --git a/src/wallet/migrate.cpp b/src/wallet/migrate.cpp index 6e5f8a493b..1775fb42b0 100644 --- a/src/wallet/migrate.cpp +++ b/src/wallet/migrate.cpp @@ -2,7 +2,6 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <compat/byteswap.h> #include <crypto/common.h> #include <streams.h> #include <util/log.h> @@ -10,6 +9,7 @@ #include <wallet/migrate.h> #include <array> +#include <bit> #include <cstddef> #include <optional> #include <stdexcept> @@ -135,7 +135,7 @@ public: uint32_t uint32_flags; s >> uint32_flags; if (other_endian) { - uint32_flags = internal_bswap_32(uint32_flags); + uint32_flags = std::byteswap(uint32_flags); } flags = static_cast<BTreeFlags>(uint32_flags); @@ -152,23 +152,23 @@ public: s >> chksum; if (other_endian) { - lsn_file = internal_bswap_32(lsn_file); - lsn_offset = internal_bswap_32(lsn_offset); - page_num = internal_bswap_32(page_num); - magic = internal_bswap_32(magic); - version = internal_bswap_32(version); - pagesize = internal_bswap_32(pagesize); - free_list = internal_bswap_32(free_list); - last_page = internal_bswap_32(last_page); - partitions = internal_bswap_32(partitions); - key_count = internal_bswap_32(key_count); - record_count = internal_bswap_32(record_count); - unused2 = internal_bswap_32(unused2); - minkey = internal_bswap_32(minkey); - re_len = internal_bswap_32(re_len); - re_pad = internal_bswap_32(re_pad); - root = internal_bswap_32(root); - crypto_magic = internal_bswap_32(crypto_magic); + lsn_file = std::byteswap(lsn_file); + lsn_offset = std::byteswap(lsn_offset); + page_num = std::byteswap(page_num); + magic = std::byteswap(magic); + version = std::byteswap(version); + pagesize = std::byteswap(pagesize); + free_list = std::byteswap(free_list); + last_page = std::byteswap(last_page); + partitions = std::byteswap(partitions); + key_count = std::byteswap(key_count); + record_count = std::byteswap(record_count); + unused2 = std::byteswap(unused2); + minkey = std::byteswap(minkey); + re_len = std::byteswap(re_len); + re_pad = std::byteswap(re_pad); + root = std::byteswap(root); + crypto_magic = std::byteswap(crypto_magic); } // Page number must match @@ -229,7 +229,7 @@ public: deleted = uint8_type & static_cast<uint8_t>(RecordType::DELETE_FLAG); if (other_endian) { - len = internal_bswap_16(len); + len = std::byteswap(len); } } }; @@ -280,8 +280,8 @@ public: s.read(std::as_writable_bytes(std::span(data.data(), data.size()))); if (m_header.other_endian) { - page_num = internal_bswap_32(page_num); - records = internal_bswap_32(records); + page_num = std::byteswap(page_num); + records = std::byteswap(records); } } }; @@ -312,8 +312,8 @@ public: s >> item_len; if (m_header.other_endian) { - page_number = internal_bswap_32(page_number); - item_len = internal_bswap_32(item_len); + page_number = std::byteswap(page_number); + item_len = std::byteswap(item_len); } } }; @@ -357,13 +357,13 @@ public: type = static_cast<PageType>(uint8_type); if (other_endian) { - lsn_file = internal_bswap_32(lsn_file); - lsn_offset = internal_bswap_32(lsn_offset); - page_num = internal_bswap_32(page_num); - prev_page = internal_bswap_32(prev_page); - next_page = internal_bswap_32(next_page); - entries = internal_bswap_16(entries); - hf_offset = internal_bswap_16(hf_offset); + lsn_file = std::byteswap(lsn_file); + lsn_offset = std::byteswap(lsn_offset); + page_num = std::byteswap(page_num); + prev_page = std::byteswap(prev_page); + next_page = std::byteswap(next_page); + entries = std::byteswap(entries); + hf_offset = std::byteswap(hf_offset); } if (expected_page_num != page_num) { @@ -399,7 +399,7 @@ public: uint16_t index; s >> index; if (m_header.other_endian) { - index = internal_bswap_16(index); + index = std::byteswap(index); } indexes.push_back(index); pos += sizeof(uint16_t); @@ -489,7 +489,7 @@ public: uint16_t index; s >> index; if (m_header.other_endian) { - index = internal_bswap_16(index); + index = std::byteswap(index); } indexes.push_back(index); pos += sizeof(uint16_t); @@ -575,8 +575,8 @@ void BerkeleyRODatabase::Open() SeekToPage(db_file, i, page_size); db_file >> file >> offset; if (outer_meta.other_endian) { - file = internal_bswap_32(file); - offset = internal_bswap_32(offset); + file = std::byteswap(file); + offset = std::byteswap(offset); } if (file != 0 || offset != 1) { throw std::runtime_error("LSNs are not reset, this database is not completely flushed. Please reopen then close the database with a version that has BDB support"); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:35:55 +00:00

dbcd3a9 refactor: Use std::views::zip in btck import blocks:

The zip loop reads a length before checking whether its path is null.

Example patch
diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index 34a180dfcd..6b212bd63a 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -51,7 +51,6 @@
 #include <list>
 #include <memory>
 #include <optional>
-#include <ranges>
 #include <span>
 #include <stdexcept>
 #include <string>
@@ -1370,11 +1369,9 @@ int btck_chainstate_manager_import_blocks(btck_ChainstateManager* chainman, cons
     try {
         std::vector<fs::path> import_files;
         import_files.reserve(block_file_paths_data_len);
-        for (auto [path, path_len] : std::views::zip(std::span{block_file_paths_data, block_file_paths_data_len},
-                                                     std::span{block_file_paths_lens, block_file_paths_data_len}))
-        {
-            if (path != nullptr) {
-                import_files.emplace_back(std::string{path, path_len}.c_str());
+        for (size_t i{0}; i < block_file_paths_data_len; ++i) {
+            if (const char* path{block_file_paths_data[i]}) {
+                import_files.emplace_back(std::string{path, block_file_paths_lens[i]}.c_str());
             }
         }
         auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h
index 9106f3d8d5..0c5924edf9 100644
--- a/src/kernel/bitcoinkernel.h
+++ b/src/kernel/bitcoinkernel.h
@@ -1400,9 +1400,10 @@ BITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT bt
  * is detected.
  *
  * @param[in] chainstate_manager        Non-null.
- * @param[in] block_file_paths_data     Nullable, array of block files described by their full filesystem paths.
- * @param[in] block_file_paths_lens     Nullable, array containing the lengths of each of the paths.
- * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_len arrays.
+ * @param[in] block_file_paths_data     Array of full filesystem paths. Null entries are skipped.
+ *                                      May be null if the length is zero.
+ * @param[in] block_file_paths_lens     Array of path lengths. May be null if there are no non-null paths.
+ * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_lens arrays, when provided.
  * @return                              0 if the import blocks call was completed successfully, non-zero otherwise.
  */
 BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_import_blocks(
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index 6c98b8ea05..c2c940d709 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -855,10 +855,12 @@ BOOST_AUTO_TEST_CASE(btck_chainman_tests)
     Logger logger{std::make_unique<TestLog>()};
     auto test_directory{TestDirectory{"chainman_test_bitcoin_kernel"}};
 
-    { // test with default context
+    { // A skipped path does not need a corresponding length.
         Context context{};
         ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")};
-        ChainMan chainman{context, chainman_opts};
+        UniqueHandle<btck_ChainstateManager, btck_chainstate_manager_destroy> chainman{btck_chainstate_manager_create(chainman_opts.get())};
+        const char* skipped_paths[]{nullptr};
+        BOOST_CHECK_EQUAL(btck_chainstate_manager_import_blocks(chainman.get(), skipped_paths, nullptr, std::size(skipped_paths)), 0);
     }
 
     { // test with default context options
> [dbcd3a9](https://github.com/bitcoin/bitcoin/pull/36033/changes/dbcd3a9bfd9f7e9dab602120bc3cdc550b0c276d) _refactor: Use std::views::zip in btck import blocks_: The zip loop reads a length before checking whether its path is null. <details><summary>Example patch</summary> ```diff diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp index 34a180dfcd..6b212bd63a 100644 --- a/src/kernel/bitcoinkernel.cpp +++ b/src/kernel/bitcoinkernel.cpp @@ -51,7 +51,6 @@ #include <list> #include <memory> #include <optional> -#include <ranges> #include <span> #include <stdexcept> #include <string> @@ -1370,11 +1369,9 @@ int btck_chainstate_manager_import_blocks(btck_ChainstateManager* chainman, cons try { std::vector<fs::path> import_files; import_files.reserve(block_file_paths_data_len); - for (auto [path, path_len] : std::views::zip(std::span{block_file_paths_data, block_file_paths_data_len}, - std::span{block_file_paths_lens, block_file_paths_data_len})) - { - if (path != nullptr) { - import_files.emplace_back(std::string{path, path_len}.c_str()); + for (size_t i{0}; i < block_file_paths_data_len; ++i) { + if (const char* path{block_file_paths_data[i]}) { + import_files.emplace_back(std::string{path, block_file_paths_lens[i]}.c_str()); } } auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman}; diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h index 9106f3d8d5..0c5924edf9 100644 --- a/src/kernel/bitcoinkernel.h +++ b/src/kernel/bitcoinkernel.h @@ -1400,9 +1400,10 @@ BITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT bt * is detected. * * @param[in] chainstate_manager Non-null. - * @param[in] block_file_paths_data Nullable, array of block files described by their full filesystem paths. - * @param[in] block_file_paths_lens Nullable, array containing the lengths of each of the paths. - * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_len arrays. + * @param[in] block_file_paths_data Array of full filesystem paths. Null entries are skipped. + * May be null if the length is zero. + * @param[in] block_file_paths_lens Array of path lengths. May be null if there are no non-null paths. + * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_lens arrays, when provided. * @return 0 if the import blocks call was completed successfully, non-zero otherwise. */ BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_import_blocks( diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp index 6c98b8ea05..c2c940d709 100644 --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -855,10 +855,12 @@ BOOST_AUTO_TEST_CASE(btck_chainman_tests) Logger logger{std::make_unique<TestLog>()}; auto test_directory{TestDirectory{"chainman_test_bitcoin_kernel"}}; - { // test with default context + { // A skipped path does not need a corresponding length. Context context{}; ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")}; - ChainMan chainman{context, chainman_opts}; + UniqueHandle<btck_ChainstateManager, btck_chainstate_manager_destroy> chainman{btck_chainstate_manager_create(chainman_opts.get())}; + const char* skipped_paths[]{nullptr}; + BOOST_CHECK_EQUAL(btck_chainstate_manager_import_blocks(chainman.get(), skipped_paths, nullptr, std::size(skipped_paths)), 0); } { // test with default context options ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:37:33 +00:00

dbcd3a9 refactor: Use std::views::zip in btck import blocks:

The block-import loop needs indexed access because null paths need no corresponding length. Elsewhere, five loops use an index only to pair entries from related containers.

Example patch
diff --git a/src/blockencodings.cpp b/src/blockencodings.cpp
index dbf4c05000..58defbadc6 100644
--- a/src/blockencodings.cpp
+++ b/src/blockencodings.cpp
@@ -16,6 +16,7 @@
 #include <util/log.h>
 #include <validation.h>
 
+#include <ranges>
 #include <unordered_map>
 
 CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce)
@@ -209,17 +210,17 @@ ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& c
         }
 
         Assume(txn_available.size() == tx_source.size());
-        for (size_t i = 0; i < txn_available.size(); i++) {
-            switch (tx_source[i]) {
+        for (auto [tx, source] : std::views::zip(txn_available, tx_source)) {
+            switch (source) {
                 case TxSource::MEMPOOL:
                     ++mempool_count;
-                    Assume(txn_available[i]);
-                    mempool_size += txn_available[i]->ComputeTotalSize();
+                    Assume(tx);
+                    mempool_size += tx->ComputeTotalSize();
                     break;
                 case TxSource::EXTRA:
                     ++extra_count;
-                    Assume(txn_available[i]);
-                    extra_size += txn_available[i]->ComputeTotalSize();
+                    Assume(tx);
+                    extra_size += tx->ComputeTotalSize();
                     break;
                 default:
                     break;
diff --git a/src/common/settings.cpp b/src/common/settings.cpp
index de59e800b4..63a9ac72ac 100644
--- a/src/common/settings.cpp
+++ b/src/common/settings.cpp
@@ -10,9 +10,11 @@
 #include <univalue.h>
 #include <util/fs.h>
 
+#include <cassert>
 #include <fstream>
 #include <iterator>
 #include <map>
+#include <ranges>
 #include <string>
 #include <utility>
 #include <vector>
@@ -104,10 +106,11 @@ bool ReadSettings(const fs::path& path, std::map<std::string, SettingsValue>& va
 
     const std::vector<std::string>& in_keys = in.getKeys();
     const std::vector<SettingsValue>& in_values = in.getValues();
-    for (size_t i = 0; i < in_keys.size(); ++i) {
-        auto inserted = values.emplace(in_keys[i], in_values[i]);
+    assert(in_keys.size() == in_values.size());
+    for (auto [key, value] : std::views::zip(in_keys, in_values)) {
+        auto inserted = values.emplace(key, value);
         if (!inserted.second) {
-            errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path)));
+            errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", key, fs::PathToString(path)));
             values.clear();
             break;
         }
diff --git a/src/netaddress.cpp b/src/netaddress.cpp
index 25c21bbd42..a1d8955fe7 100644
--- a/src/netaddress.cpp
+++ b/src/netaddress.cpp
@@ -19,6 +19,7 @@
 #include <cstdint>
 #include <ios>
 #include <iterator>
+#include <ranges>
 #include <string_view>
 #include <tuple>
 
@@ -1043,8 +1044,9 @@ bool CSubNet::Match(const CNetAddr &addr) const
     }
 
     assert(network.m_addr.size() == addr.m_addr.size());
-    for (size_t x = 0; x < addr.m_addr.size(); ++x) {
-        if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) {
+    assert(addr.m_addr.size() <= std::size(netmask));
+    for (auto [addr_byte, mask_byte, network_byte] : std::views::zip(addr.m_addr, netmask, network.m_addr)) {
+        if ((addr_byte & mask_byte) != network_byte) {
             return false;
         }
     }
diff --git a/src/util/sock.cpp b/src/util/sock.cpp
index 8d567b397a..ee3e6edd49 100644
--- a/src/util/sock.cpp
+++ b/src/util/sock.cpp
@@ -17,6 +17,7 @@
 #include <compare>
 #include <exception>
 #include <memory>
+#include <ranges>
 #include <stdexcept>
 #include <string>
 #include <utility>
@@ -183,20 +184,19 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per
     }
 
     assert(pfds.size() == events_per_sock.size());
-    size_t i{0};
-    for (auto& [sock, events] : events_per_sock) {
-        assert(sock->m_socket == static_cast<SOCKET>(pfds[i].fd));
+    for (auto [entry, pfd] : std::views::zip(events_per_sock, pfds)) {
+        auto& [sock, events] = entry;
+        assert(sock->m_socket == static_cast<SOCKET>(pfd.fd));
         events.occurred = 0;
-        if (pfds[i].revents & POLLIN) {
+        if (pfd.revents & POLLIN) {
             events.occurred |= RecvEvent;
         }
-        if (pfds[i].revents & POLLOUT) {
+        if (pfd.revents & POLLOUT) {
             events.occurred |= SendEvent;
         }
-        if (pfds[i].revents & (POLLERR | POLLHUP)) {
+        if (pfd.revents & (POLLERR | POLLHUP)) {
             events.occurred |= ErrorEvent;
         }
-        ++i;
     }
 
     return true;
diff --git a/src/wallet/rpc/backup.cpp b/src/wallet/rpc/backup.cpp
index dfd4727a0c..4bfec30b63 100644
--- a/src/wallet/rpc/backup.cpp
+++ b/src/wallet/rpc/backup.cpp
@@ -29,8 +29,10 @@
 
 #include <cstdint>
 #include <fstream>
-#include <tuple>
+#include <ranges>
 #include <string>
+#include <tuple>
+#include <utility>
 
 #include <univalue.h>
 
@@ -237,12 +239,10 @@ RPCMethod importdescriptors()
 
     // Translate each ImportResult into the per-input UniValue result. Inputs
     // that failed to parse already hold an error in results[] and are not
-    // part of `requests`, so use input_index to map each import_results[k]
-    // back to its slot.
+    // part of `requests`, so use input_index to map each result back to its slot.
     CHECK_NONFATAL(import_results.size() == requests.size());
-    for (size_t k = 0; k < requests.size(); ++k) {
-        UniValue& result = results[requests[k].input_index];
-        const ImportResult& import_result = import_results[k];
+    for (auto [request, import_result] : std::views::zip(std::as_const(requests), std::as_const(import_results))) {
+        UniValue& result = results[request.input_index];
         result = UniValue(UniValue::VOBJ);
         UniValue warnings(UniValue::VARR);
         if (import_result.has_error()) {
> [dbcd3a9](https://github.com/bitcoin/bitcoin/pull/36033/changes/dbcd3a9bfd9f7e9dab602120bc3cdc550b0c276d) _refactor: Use std::views::zip in btck import blocks_: The block-import loop needs indexed access because null paths need no corresponding length. Elsewhere, five loops use an index only to pair entries from related containers. <details><summary>Example patch</summary> ```diff diff --git a/src/blockencodings.cpp b/src/blockencodings.cpp index dbf4c05000..58defbadc6 100644 --- a/src/blockencodings.cpp +++ b/src/blockencodings.cpp @@ -16,6 +16,7 @@ #include <util/log.h> #include <validation.h> +#include <ranges> #include <unordered_map> CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce) @@ -209,17 +210,17 @@ ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& c } Assume(txn_available.size() == tx_source.size()); - for (size_t i = 0; i < txn_available.size(); i++) { - switch (tx_source[i]) { + for (auto [tx, source] : std::views::zip(txn_available, tx_source)) { + switch (source) { case TxSource::MEMPOOL: ++mempool_count; - Assume(txn_available[i]); - mempool_size += txn_available[i]->ComputeTotalSize(); + Assume(tx); + mempool_size += tx->ComputeTotalSize(); break; case TxSource::EXTRA: ++extra_count; - Assume(txn_available[i]); - extra_size += txn_available[i]->ComputeTotalSize(); + Assume(tx); + extra_size += tx->ComputeTotalSize(); break; default: break; diff --git a/src/common/settings.cpp b/src/common/settings.cpp index de59e800b4..63a9ac72ac 100644 --- a/src/common/settings.cpp +++ b/src/common/settings.cpp @@ -10,9 +10,11 @@ #include <univalue.h> #include <util/fs.h> +#include <cassert> #include <fstream> #include <iterator> #include <map> +#include <ranges> #include <string> #include <utility> #include <vector> @@ -104,10 +106,11 @@ bool ReadSettings(const fs::path& path, std::map<std::string, SettingsValue>& va const std::vector<std::string>& in_keys = in.getKeys(); const std::vector<SettingsValue>& in_values = in.getValues(); - for (size_t i = 0; i < in_keys.size(); ++i) { - auto inserted = values.emplace(in_keys[i], in_values[i]); + assert(in_keys.size() == in_values.size()); + for (auto [key, value] : std::views::zip(in_keys, in_values)) { + auto inserted = values.emplace(key, value); if (!inserted.second) { - errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path))); + errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", key, fs::PathToString(path))); values.clear(); break; } diff --git a/src/netaddress.cpp b/src/netaddress.cpp index 25c21bbd42..a1d8955fe7 100644 --- a/src/netaddress.cpp +++ b/src/netaddress.cpp @@ -19,6 +19,7 @@ #include <cstdint> #include <ios> #include <iterator> +#include <ranges> #include <string_view> #include <tuple> @@ -1043,8 +1044,9 @@ bool CSubNet::Match(const CNetAddr &addr) const } assert(network.m_addr.size() == addr.m_addr.size()); - for (size_t x = 0; x < addr.m_addr.size(); ++x) { - if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) { + assert(addr.m_addr.size() <= std::size(netmask)); + for (auto [addr_byte, mask_byte, network_byte] : std::views::zip(addr.m_addr, netmask, network.m_addr)) { + if ((addr_byte & mask_byte) != network_byte) { return false; } } diff --git a/src/util/sock.cpp b/src/util/sock.cpp index 8d567b397a..ee3e6edd49 100644 --- a/src/util/sock.cpp +++ b/src/util/sock.cpp @@ -17,6 +17,7 @@ #include <compare> #include <exception> #include <memory> +#include <ranges> #include <stdexcept> #include <string> #include <utility> @@ -183,20 +184,19 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per } assert(pfds.size() == events_per_sock.size()); - size_t i{0}; - for (auto& [sock, events] : events_per_sock) { - assert(sock->m_socket == static_cast<SOCKET>(pfds[i].fd)); + for (auto [entry, pfd] : std::views::zip(events_per_sock, pfds)) { + auto& [sock, events] = entry; + assert(sock->m_socket == static_cast<SOCKET>(pfd.fd)); events.occurred = 0; - if (pfds[i].revents & POLLIN) { + if (pfd.revents & POLLIN) { events.occurred |= RecvEvent; } - if (pfds[i].revents & POLLOUT) { + if (pfd.revents & POLLOUT) { events.occurred |= SendEvent; } - if (pfds[i].revents & (POLLERR | POLLHUP)) { + if (pfd.revents & (POLLERR | POLLHUP)) { events.occurred |= ErrorEvent; } - ++i; } return true; diff --git a/src/wallet/rpc/backup.cpp b/src/wallet/rpc/backup.cpp index dfd4727a0c..4bfec30b63 100644 --- a/src/wallet/rpc/backup.cpp +++ b/src/wallet/rpc/backup.cpp @@ -29,8 +29,10 @@ #include <cstdint> #include <fstream> -#include <tuple> +#include <ranges> #include <string> +#include <tuple> +#include <utility> #include <univalue.h> @@ -237,12 +239,10 @@ RPCMethod importdescriptors() // Translate each ImportResult into the per-input UniValue result. Inputs // that failed to parse already hold an error in results[] and are not - // part of `requests`, so use input_index to map each import_results[k] - // back to its slot. + // part of `requests`, so use input_index to map each result back to its slot. CHECK_NONFATAL(import_results.size() == requests.size()); - for (size_t k = 0; k < requests.size(); ++k) { - UniValue& result = results[requests[k].input_index]; - const ImportResult& import_result = import_results[k]; + for (auto [request, import_result] : std::views::zip(std::as_const(requests), std::as_const(import_results))) { + UniValue& result = results[request.input_index]; result = UniValue(UniValue::VOBJ); UniValue warnings(UniValue::VARR); if (import_result.has_error()) { ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:37:54 +00:00

cf8e2c6 refactor: clang-tidy readability-container-contains for C++23:

strHelp.contains('\n') scans for the newline before find scans again. I would keep the find position, use contains for the host-port colon and argsman error checks, and remove the redundant category-reset ternary (the newline and category changes can be pushed independently, the other contains edits need C++23).

Example patch
diff --git a/src/init/common.cpp b/src/init/common.cpp
index 897f2951e2..043a26e045 100644
--- a/src/init/common.cpp
+++ b/src/init/common.cpp
@@ -86,7 +86,7 @@ util::Result<void> SetLoggingCategories(const ArgsManager& args)
     const auto last_negated = std::find_if(categories.rbegin(), categories.rend(),
                                            [](const std::string& cat) { return cat == "0" || cat == "none"; });
 
-    const auto categories_to_process = (last_negated == categories.rend()) ? categories : std::ranges::subrange(last_negated.base(), categories.end());
+    const auto categories_to_process = std::ranges::subrange(last_negated.base(), categories.end());
 
     for (const auto& cat : categories_to_process) {
         if (!LogInstance().EnableCategory(cat)) {
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index 7ba403bd18..bb336e873a 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -105,8 +105,9 @@ std::string CRPCTable::help(std::string_view strCommand, const JSONRPCRequest& h
             std::string strHelp{e.what()};
             if (strCommand == "")
             {
-                if (strHelp.contains('\n'))
-                    strHelp = strHelp.substr(0, strHelp.find('\n'));
+                if (const auto newline{strHelp.find('\n')}; newline != std::string::npos) {
+                    strHelp.resize(newline);
+                }
 
                 if (category != pcmd->category)
                 {
diff --git a/src/test/argsman_tests.cpp b/src/test/argsman_tests.cpp
index c3e8b7e1a8..571df4e8ae 100644
--- a/src/test/argsman_tests.cpp
+++ b/src/test/argsman_tests.cpp
@@ -111,7 +111,7 @@ public:
 
         if (expect.error) {
             BOOST_CHECK(!success);
-            BOOST_CHECK_NE(error.find(expect.error), std::string::npos);
+            BOOST_CHECK(error.contains(expect.error));
         } else {
             BOOST_CHECK(success);
             BOOST_CHECK_EQUAL(error, "");
diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp
index 926ea7f436..15608faca9 100644
--- a/src/util/strencodings.cpp
+++ b/src/util/strencodings.cpp
@@ -75,7 +75,7 @@ bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut)
     // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
     bool fHaveColon = colon != in.npos;
     bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
-    bool fMultiColon{fHaveColon && colon != 0 && (in.find_last_of(':', colon - 1) != in.npos)};
+    bool fMultiColon{fHaveColon && in.substr(0, colon).contains(':')};
     if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
         if (const auto n{ToIntegral<uint16_t>(in.substr(colon + 1))}) {
             in = in.substr(0, colon);
> [cf8e2c6](https://github.com/bitcoin/bitcoin/pull/36033/changes/cf8e2c6bfe496665edecfb293b9838c5398d6027) _refactor: clang-tidy readability-container-contains for C++23_: `strHelp.contains('\n')` scans for the newline before `find` scans again. I would keep the `find` position, use `contains` for the host-port colon and argsman error checks, and remove the redundant category-reset ternary (the newline and category changes can be pushed independently, the other `contains` edits need C++23). <details><summary>Example patch</summary> ```diff diff --git a/src/init/common.cpp b/src/init/common.cpp index 897f2951e2..043a26e045 100644 --- a/src/init/common.cpp +++ b/src/init/common.cpp @@ -86,7 +86,7 @@ util::Result<void> SetLoggingCategories(const ArgsManager& args) const auto last_negated = std::find_if(categories.rbegin(), categories.rend(), [](const std::string& cat) { return cat == "0" || cat == "none"; }); - const auto categories_to_process = (last_negated == categories.rend()) ? categories : std::ranges::subrange(last_negated.base(), categories.end()); + const auto categories_to_process = std::ranges::subrange(last_negated.base(), categories.end()); for (const auto& cat : categories_to_process) { if (!LogInstance().EnableCategory(cat)) { diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 7ba403bd18..bb336e873a 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -105,8 +105,9 @@ std::string CRPCTable::help(std::string_view strCommand, const JSONRPCRequest& h std::string strHelp{e.what()}; if (strCommand == "") { - if (strHelp.contains('\n')) - strHelp = strHelp.substr(0, strHelp.find('\n')); + if (const auto newline{strHelp.find('\n')}; newline != std::string::npos) { + strHelp.resize(newline); + } if (category != pcmd->category) { diff --git a/src/test/argsman_tests.cpp b/src/test/argsman_tests.cpp index c3e8b7e1a8..571df4e8ae 100644 --- a/src/test/argsman_tests.cpp +++ b/src/test/argsman_tests.cpp @@ -111,7 +111,7 @@ public: if (expect.error) { BOOST_CHECK(!success); - BOOST_CHECK_NE(error.find(expect.error), std::string::npos); + BOOST_CHECK(error.contains(expect.error)); } else { BOOST_CHECK(success); BOOST_CHECK_EQUAL(error, ""); diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index 926ea7f436..15608faca9 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -75,7 +75,7 @@ bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut) // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator bool fHaveColon = colon != in.npos; bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe - bool fMultiColon{fHaveColon && colon != 0 && (in.find_last_of(':', colon - 1) != in.npos)}; + bool fMultiColon{fHaveColon && in.substr(0, colon).contains(':')}; if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) { if (const auto n{ToIntegral<uint16_t>(in.substr(colon + 1))}) { in = in.substr(0, colon); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:36:17 +00:00

b84d9ee util: Use std::expected:

The tests use BOOST_CHECK before accessing error() or value(), so a failed check continues into a wrong-state access. This is already true on master and can be fixed before the std::expected migration.

Example patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index f6df5aa9f6..8dbfdc46aa 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -168,7 +168,7 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part, TestChain100Setup)
 
     const auto expect_part{[&](size_t offset, size_t size) {
         auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};
-        BOOST_CHECK(res);
+        BOOST_REQUIRE(res);
         const auto& part{res.value()};
         BOOST_CHECK_EQUAL_COLLECTIONS(part.begin(), part.end(), block->begin() + offset, block->begin() + offset + size);
     }};
@@ -196,7 +196,7 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part_error, TestChain100Setup)
 
     const auto expect_part_error{[&](size_t offset, size_t size) {
         auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};
-        BOOST_CHECK(!res);
+        BOOST_REQUIRE(!res);
         BOOST_CHECK_EQUAL(res.error(), node::ReadRawError::BadPartRange);
     }};
 
diff --git a/src/test/mempool_fee_estimator_tests.cpp b/src/test/mempool_fee_estimator_tests.cpp
index d35ea419bd..b60a4683db 100644
--- a/src/test/mempool_fee_estimator_tests.cpp
+++ b/src/test/mempool_fee_estimator_tests.cpp
@@ -138,7 +138,7 @@ BOOST_AUTO_TEST_CASE(MempoolFeeRateEstimator)
         const std::string unloaded_err = strprintf("%s: Mempool not loaded yet, no fee rate estimate available",
                                                    FeeRateEstimatorTypeToString(FeeRateEstimatorType::MEMPOOL_POLICY));
         const auto result = mempool_estimator.EstimateFeeRate(/*conservative=*/true);
-        BOOST_CHECK(!result);
+        BOOST_REQUIRE(!result);
         BOOST_CHECK_EQUAL(result.error().reason, unloaded_err);
     }
     m_node.mempool->SetLoadTried(true);
@@ -149,7 +149,7 @@ BOOST_AUTO_TEST_CASE(MempoolFeeRateEstimator)
         const auto result = mempool_estimator.EstimateFeeRate(/*conservative=*/true);
         const std::string insufficient_err{strprintf("%s: Not enough recent block data for fee rate estimation",
                                                      FeeRateEstimatorTypeToString(FeeRateEstimatorType::MEMPOOL_POLICY))};
-        BOOST_CHECK(!result);
+        BOOST_REQUIRE(!result);
         BOOST_CHECK_EQUAL(result.error().reason, insufficient_err);
     }
     {
diff --git a/src/test/threadpool_tests.cpp b/src/test/threadpool_tests.cpp
index 4811d73215..b6a3010253 100644
--- a/src/test/threadpool_tests.cpp
+++ b/src/test/threadpool_tests.cpp
@@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error)
 
     // Never started: Inactive
     auto res = threadPool.Submit(fn_empty);
-    BOOST_CHECK(!res);
+    BOOST_REQUIRE(!res);
     BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");
 
     // Interrupted (workers still alive): Interrupted, and Start() must be rejected too
@@ -94,7 +94,7 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error)
     const auto blocking_tasks = BlockWorkers(threadPool, blocker, NUM_WORKERS_DEFAULT);
     threadPool.Interrupt();
     res = threadPool.Submit(fn_empty);
-    BOOST_CHECK(!res);
+    BOOST_REQUIRE(!res);
     BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "Interrupted");
     BOOST_CHECK_EXCEPTION(threadPool.Start(NUM_WORKERS_DEFAULT), std::runtime_error, HasReason("Thread pool has been interrupted or is stopping"));
     blocker.release(NUM_WORKERS_DEFAULT);
@@ -103,19 +103,19 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error)
     // Interrupted then stopped: Inactive
     threadPool.Stop();
     res = threadPool.Submit(fn_empty);
-    BOOST_CHECK(!res);
+    BOOST_REQUIRE(!res);
     BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");
 
     // Started then stopped: Inactive
     threadPool.Start(NUM_WORKERS_DEFAULT);
     threadPool.Stop();
     res = threadPool.Submit(fn_empty);
-    BOOST_CHECK(!res);
+    BOOST_REQUIRE(!res);
     BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");
 
     std::vector<std::function<void()>> tasks;
     const auto range_res{threadPool.Submit(std::move(tasks))};
-    BOOST_CHECK(!range_res);
+    BOOST_REQUIRE(!range_res);
     BOOST_CHECK_EQUAL(SubmitErrorString(range_res.error()), "No active workers");
 }
 
@@ -330,12 +330,12 @@ BOOST_AUTO_TEST_CASE(interrupt_blocks_new_submissions)
     threadPool.Interrupt();
 
     auto res = threadPool.Submit([]{});
-    BOOST_CHECK(!res);
+    BOOST_REQUIRE(!res);
     BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "Interrupted");
 
     std::vector<std::function<void()>> tasks;
     const auto range_res{threadPool.Submit(std::move(tasks))};
-    BOOST_CHECK(!range_res);
+    BOOST_REQUIRE(!range_res);
     BOOST_CHECK_EQUAL(SubmitErrorString(range_res.error()), "Interrupted");
 
     // Reset pool
> [b84d9ee](https://github.com/bitcoin/bitcoin/pull/36033/changes/b84d9ee7a0b3885fdc8846c535ef3d8dfd90d1e9) _util: Use std::expected_: The tests use `BOOST_CHECK` before accessing `error()` or `value()`, so a failed check continues into a wrong-state access. This is already true on master and can be fixed before the `std::expected` migration. <details><summary>Example patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index f6df5aa9f6..8dbfdc46aa 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -168,7 +168,7 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part, TestChain100Setup) const auto expect_part{[&](size_t offset, size_t size) { auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})}; - BOOST_CHECK(res); + BOOST_REQUIRE(res); const auto& part{res.value()}; BOOST_CHECK_EQUAL_COLLECTIONS(part.begin(), part.end(), block->begin() + offset, block->begin() + offset + size); }}; @@ -196,7 +196,7 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part_error, TestChain100Setup) const auto expect_part_error{[&](size_t offset, size_t size) { auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})}; - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(res.error(), node::ReadRawError::BadPartRange); }}; diff --git a/src/test/mempool_fee_estimator_tests.cpp b/src/test/mempool_fee_estimator_tests.cpp index d35ea419bd..b60a4683db 100644 --- a/src/test/mempool_fee_estimator_tests.cpp +++ b/src/test/mempool_fee_estimator_tests.cpp @@ -138,7 +138,7 @@ BOOST_AUTO_TEST_CASE(MempoolFeeRateEstimator) const std::string unloaded_err = strprintf("%s: Mempool not loaded yet, no fee rate estimate available", FeeRateEstimatorTypeToString(FeeRateEstimatorType::MEMPOOL_POLICY)); const auto result = mempool_estimator.EstimateFeeRate(/*conservative=*/true); - BOOST_CHECK(!result); + BOOST_REQUIRE(!result); BOOST_CHECK_EQUAL(result.error().reason, unloaded_err); } m_node.mempool->SetLoadTried(true); @@ -149,7 +149,7 @@ BOOST_AUTO_TEST_CASE(MempoolFeeRateEstimator) const auto result = mempool_estimator.EstimateFeeRate(/*conservative=*/true); const std::string insufficient_err{strprintf("%s: Not enough recent block data for fee rate estimation", FeeRateEstimatorTypeToString(FeeRateEstimatorType::MEMPOOL_POLICY))}; - BOOST_CHECK(!result); + BOOST_REQUIRE(!result); BOOST_CHECK_EQUAL(result.error().reason, insufficient_err); } { diff --git a/src/test/threadpool_tests.cpp b/src/test/threadpool_tests.cpp index 4811d73215..b6a3010253 100644 --- a/src/test/threadpool_tests.cpp +++ b/src/test/threadpool_tests.cpp @@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error) // Never started: Inactive auto res = threadPool.Submit(fn_empty); - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers"); // Interrupted (workers still alive): Interrupted, and Start() must be rejected too @@ -94,7 +94,7 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error) const auto blocking_tasks = BlockWorkers(threadPool, blocker, NUM_WORKERS_DEFAULT); threadPool.Interrupt(); res = threadPool.Submit(fn_empty); - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "Interrupted"); BOOST_CHECK_EXCEPTION(threadPool.Start(NUM_WORKERS_DEFAULT), std::runtime_error, HasReason("Thread pool has been interrupted or is stopping")); blocker.release(NUM_WORKERS_DEFAULT); @@ -103,19 +103,19 @@ BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error) // Interrupted then stopped: Inactive threadPool.Stop(); res = threadPool.Submit(fn_empty); - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers"); // Started then stopped: Inactive threadPool.Start(NUM_WORKERS_DEFAULT); threadPool.Stop(); res = threadPool.Submit(fn_empty); - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers"); std::vector<std::function<void()>> tasks; const auto range_res{threadPool.Submit(std::move(tasks))}; - BOOST_CHECK(!range_res); + BOOST_REQUIRE(!range_res); BOOST_CHECK_EQUAL(SubmitErrorString(range_res.error()), "No active workers"); } @@ -330,12 +330,12 @@ BOOST_AUTO_TEST_CASE(interrupt_blocks_new_submissions) threadPool.Interrupt(); auto res = threadPool.Submit([]{}); - BOOST_CHECK(!res); + BOOST_REQUIRE(!res); BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "Interrupted"); std::vector<std::function<void()>> tasks; const auto range_res{threadPool.Submit(std::move(tasks))}; - BOOST_CHECK(!range_res); + BOOST_REQUIRE(!range_res); BOOST_CHECK_EQUAL(SubmitErrorString(range_res.error()), "Interrupted"); // Reset pool ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 12:37:15 +00:00

cf8e2c6 refactor: clang-tidy readability-container-contains for C++23:

We already compile the bundled libmultiprocess as C++23. Its standalone build still supports C++20, so changing those tests to .contains() here would break it. Could the tidy job disable only readability-container-contains for the subtree?

> [cf8e2c6](https://github.com/bitcoin/bitcoin/pull/36033/changes/cf8e2c6bfe496665edecfb293b9838c5398d6027) _refactor: clang-tidy readability-container-contains for C++23_: We already compile the bundled libmultiprocess as C++23. Its standalone build still supports C++20, so changing those tests to `.contains()` here would break it. Could the tidy job disable only `readability-container-contains` for the subtree?
l0rinc (Migrated from github.com) commented 2026-11-25 12:37:23 +00:00

cf8e2c6 refactor: clang-tidy readability-container-contains for C++23:

ContainsNUL now only calls contains('\0'), so I'd inline that check at its callers and remove the standalone fuzz call. The other membership searches can use ranges::contains. loadwallet can reuse GetWallet too, and that part could land separately before the C++23 switch.

Example patch
diff --git a/src/base58.cpp b/src/base58.cpp
index d6157a8656..6cf3109f21 100644
--- a/src/base58.cpp
+++ b/src/base58.cpp
@@ -7,7 +7,6 @@
 #include <hash.h>
 #include <uint256.h>
 #include <util/strencodings.h>
-#include <util/string.h>
 
 #include <algorithm>
 #include <cassert>
@@ -16,8 +15,6 @@
 
 #include <limits>
 
-using util::ContainsNUL;
-
 /** All alphanumeric characters except for "0", "I", "O", and "l" */
 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
 static const int8_t mapBase58[256] = {
@@ -134,7 +131,7 @@ std::string EncodeBase58(std::span<const unsigned char> input)
 
 bool DecodeBase58(std::string_view str, std::vector<unsigned char>& vchRet, int max_ret_len)
 {
-    if (ContainsNUL(str)) {
+    if (str.contains('\0')) {
         return false;
     }
     return DecodeBase58Raw(str, vchRet, max_ret_len);
@@ -168,7 +165,7 @@ std::string EncodeBase58Check(std::span<const unsigned char> input)
 
 bool DecodeBase58Check(std::string_view str, std::vector<unsigned char>& vchRet, int max_ret)
 {
-    if (ContainsNUL(str)) {
+    if (str.contains('\0')) {
         return false;
     }
     return DecodeBase58CheckRaw(str, vchRet, max_ret);
diff --git a/src/net.cpp b/src/net.cpp
index 96d4812630..7ff1204092 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -358,7 +358,7 @@ bool IsLocal(const CService& addr)
 bool CConnman::AlreadyConnectedToHost(std::string_view host) const
 {
     LOCK(m_nodes_mutex);
-    return std::ranges::any_of(m_nodes, [&host](CNode* node) { return node->m_addr_name == host; });
+    return std::ranges::contains(m_nodes, host, &CNode::m_addr_name);
 }
 
 bool CConnman::AlreadyConnectedToAddressPort(const CService& addr_port) const
@@ -1809,7 +1809,7 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
 
     int nInbound = 0;
 
-    const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end();
+    const bool inbound_onion = std::ranges::contains(m_onion_binds, addr_bind);
 
     // Tor inbound connections do not reveal the peer's actual network address.
     // Therefore do not apply address-based whitelist permissions to them.
diff --git a/src/netaddress.cpp b/src/netaddress.cpp
index c89569142c..25c21bbd42 100644
--- a/src/netaddress.cpp
+++ b/src/netaddress.cpp
@@ -22,7 +22,6 @@
 #include <string_view>
 #include <tuple>
 
-using util::ContainsNUL;
 using util::HasPrefix;
 
 CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const
@@ -212,7 +211,7 @@ static void Checksum(std::span<const uint8_t> addr_pubkey, uint8_t (&checksum)[C
 
 bool CNetAddr::SetSpecial(std::string_view addr)
 {
-    if (ContainsNUL(addr)) {
+    if (addr.contains('\0')) {
         return false;
     }
 
diff --git a/src/netbase.cpp b/src/netbase.cpp
index 9c81cd249a..6ad70ca444 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -28,8 +28,6 @@
 #include <sys/un.h>
 #endif
 
-using util::ContainsNUL;
-
 // Settings
 static GlobalMutex g_proxyinfo_mutex;
 static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
@@ -144,7 +142,7 @@ std::vector<std::string> GetNetworkNames(bool append_unroutable)
 
 static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
 {
-    if (ContainsNUL(name)) return {};
+    if (name.contains('\0')) return {};
     {
         CNetAddr addr;
         // From our perspective, onion addresses are not hostnames but rather
@@ -173,7 +171,7 @@ static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int
 
 std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
 {
-    if (ContainsNUL(name)) return {};
+    if (name.contains('\0')) return {};
     std::string strHost = name;
     if (strHost.empty()) return {};
     if (strHost.front() == '[' && strHost.back() == ']') {
@@ -191,7 +189,7 @@ std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, D
 
 std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
 {
-    if (name.empty() || ContainsNUL(name)) {
+    if (name.empty() || name.contains('\0')) {
         return {};
     }
     uint16_t port{portDefault};
@@ -216,7 +214,7 @@ std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bo
 
 CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
 {
-    if (ContainsNUL(name)) {
+    if (name.contains('\0')) {
         return {};
     }
     // "1.2:345" will fail to resolve the ip, but will still set the port.
@@ -833,7 +831,7 @@ CSubNet LookupSubNet(const std::string& subnet_str)
 {
     CSubNet subnet;
     assert(!subnet.IsValid());
-    if (ContainsNUL(subnet_str)) {
+    if (subnet_str.contains('\0')) {
         return subnet;
     }
 
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index a9b152e653..7ba403bd18 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -716,7 +716,7 @@ bool IsDeprecatedRPCEnabled(const std::string& method)
 {
     const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
 
-    return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
+    return std::ranges::contains(enabled_methods, method);
 }
 
 UniValue JSONRPCExec(const JSONRPCRequest& jreq, bool catch_errors)
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index dbbf51077e..924ff983b9 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -132,7 +132,7 @@ std::vector<uint8_t> MutableTransactionSignatureCreator::CreateMuSig2Nonce(const
     auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
     if (it == sigdata.musig2_pubkeys.end()) return {};
     const std::vector<CPubKey>& pubkeys = it->second;
-    if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
+    if (!std::ranges::contains(pubkeys, part_pubkey)) return {};
 
     // Compute sighash
     std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
@@ -160,7 +160,7 @@ bool MutableTransactionSignatureCreator::CreateMuSig2PartialSig(const SigningPro
     auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
     if (it == sigdata.musig2_pubkeys.end()) return false;
     const std::vector<CPubKey>& pubkeys = it->second;
-    if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
+    if (!std::ranges::contains(pubkeys, part_pubkey)) return {};
 
     // Retrieve pubnonces
     auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
diff --git a/src/test/bip352_tests.cpp b/src/test/bip352_tests.cpp
index 36c8c79db5..a93341e742 100644
--- a/src/test/bip352_tests.cpp
+++ b/src/test/bip352_tests.cpp
@@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(bip352_send_and_receive_test_vectors)
                     expected_spks.push_back(tap);
                 }
                 match = std::all_of(sp_tr_dests->begin(), sp_tr_dests->end(), [&](const auto& entry) {
-                    return std::find(expected_spks.begin(), expected_spks.end(), entry.second) != expected_spks.end();
+                    return std::ranges::contains(expected_spks, entry.second);
                 });
                 if (match) break;
             }
diff --git a/src/test/fuzz/mini_miner.cpp b/src/test/fuzz/mini_miner.cpp
index 8848a0cddc..015b245d15 100644
--- a/src/test/fuzz/mini_miner.cpp
+++ b/src/test/fuzz/mini_miner.cpp
@@ -90,7 +90,7 @@ FUZZ_TARGET(mini_miner, .init = initialize_miner)
             // Add some random outpoint (will be interpreted as confirmed or not yet submitted
             // to mempool).
             auto outpoint = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
-            if (outpoint.has_value() && std::find(outpoints.begin(), outpoints.end(), *outpoint) == outpoints.end()) {
+            if (outpoint.has_value() && !std::ranges::contains(outpoints, *outpoint)) {
                 outpoints.push_back(*outpoint);
             }
         }
diff --git a/src/test/fuzz/rpc.cpp b/src/test/fuzz/rpc.cpp
index 349bcf59ba..8bd4323757 100644
--- a/src/test/fuzz/rpc.cpp
+++ b/src/test/fuzz/rpc.cpp
@@ -367,8 +367,8 @@ void initialize_rpc()
     rpc_testing_setup = InitializeRPCFuzzTestingSetup();
     const std::vector<std::string> supported_rpc_commands = rpc_testing_setup->GetRPCCommands();
     for (const std::string& rpc_command : supported_rpc_commands) {
-        const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end();
-        const bool not_safe_for_fuzzing = std::find(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end();
+        const bool safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_SAFE_FOR_FUZZING, rpc_command);
+        const bool not_safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING, rpc_command);
         if (!(safe_for_fuzzing || not_safe_for_fuzzing)) {
             std::cerr << "Error: RPC command \"" << rpc_command << "\" not found in RPC_COMMANDS_SAFE_FOR_FUZZING or RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n";
             std::terminate();
@@ -394,7 +394,7 @@ FUZZ_TARGET(rpc, .init = initialize_rpc)
     if (!g_limit_to_rpc_command.empty() && rpc_command != g_limit_to_rpc_command) {
         return;
     }
-    const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end();
+    const bool safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_SAFE_FOR_FUZZING, rpc_command);
     if (!safe_for_fuzzing) {
         return;
     }
diff --git a/src/test/fuzz/string.cpp b/src/test/fuzz/string.cpp
index 8e693326ca..f6bdb01404 100644
--- a/src/test/fuzz/string.cpp
+++ b/src/test/fuzz/string.cpp
@@ -41,7 +41,6 @@ using common::AmountErrMsg;
 using common::AmountHighWarn;
 using common::FeeModeFromString;
 using common::ResolveErrMsg;
-using util::ContainsNUL;
 using util::Join;
 using util::RemovePrefix;
 using util::SplitString;
@@ -101,7 +100,6 @@ FUZZ_TARGET(string)
     (void)TrimString(random_string_1);
     (void)TrimString(random_string_1, random_string_2);
     (void)UrlDecode(random_string_1);
-    (void)ContainsNUL(random_string_1);
     try {
         throw scriptnum_error{random_string_1};
     } catch (const std::runtime_error&) {
diff --git a/src/test/fuzz/system.cpp b/src/test/fuzz/system.cpp
index 7c73f8b9f8..60bfb02e75 100644
--- a/src/test/fuzz/system.cpp
+++ b/src/test/fuzz/system.cpp
@@ -97,7 +97,7 @@ FUZZ_TARGET(system, .init = initialize_system)
                     if (args_manager.GetArgFlags(hidden_argument) != std::nullopt) {
                         continue;
                     }
-                    if (std::find(hidden_arguments.begin(), hidden_arguments.end(), hidden_argument) != hidden_arguments.end()) {
+                    if (std::ranges::contains(hidden_arguments, hidden_argument)) {
                         continue;
                     }
                     hidden_arguments.push_back(hidden_argument);
diff --git a/src/test/fuzz/txgraph.cpp b/src/test/fuzz/txgraph.cpp
index ec9ab79291..a84f917981 100644
--- a/src/test/fuzz/txgraph.cpp
+++ b/src/test/fuzz/txgraph.cpp
@@ -271,7 +271,7 @@ struct SimTxGraph
         // deduplication as it'd rely on non-deterministic pointer comparison).
         arg.clear();
         for (auto ptr : ret) {
-            if (std::find(arg.begin(), arg.end(), ptr) == arg.end()) {
+            if (!std::ranges::contains(arg, ptr)) {
                 arg.push_back(ptr);
             }
         }
diff --git a/src/test/netbase_tests.cpp b/src/test/netbase_tests.cpp
index 7515c21a0f..ea36db5ee3 100644
--- a/src/test/netbase_tests.cpp
+++ b/src/test/netbase_tests.cpp
@@ -15,8 +15,9 @@
 #include <util/strencodings.h>
 #include <util/translation.h>
 
-#include <string>
+#include <algorithm>
 #include <numeric>
+#include <string>
 
 #include <boost/test/unit_test.hpp>
 
@@ -477,13 +478,13 @@ BOOST_AUTO_TEST_CASE(netpermissions_test)
 
     const auto strings = NetPermissions::ToStrings(NetPermissionFlags::All);
     BOOST_CHECK_EQUAL(strings.size(), 7U);
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "bloomfilter") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "forcerelay") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "relay") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "noban") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "mempool") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "download") != strings.end());
-    BOOST_CHECK(std::find(strings.begin(), strings.end(), "addr") != strings.end());
+    BOOST_CHECK(std::ranges::contains(strings, "bloomfilter"));
+    BOOST_CHECK(std::ranges::contains(strings, "forcerelay"));
+    BOOST_CHECK(std::ranges::contains(strings, "relay"));
+    BOOST_CHECK(std::ranges::contains(strings, "noban"));
+    BOOST_CHECK(std::ranges::contains(strings, "mempool"));
+    BOOST_CHECK(std::ranges::contains(strings, "download"));
+    BOOST_CHECK(std::ranges::contains(strings, "addr"));
 }
 
 BOOST_AUTO_TEST_CASE(netbase_dont_resolve_strings_with_embedded_nul_characters)
diff --git a/src/test/random_tests.cpp b/src/test/random_tests.cpp
index 213465fded..b99321905d 100644
--- a/src/test/random_tests.cpp
+++ b/src/test/random_tests.cpp
@@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(stdrandom_test)
         std::vector<int> test{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
         std::shuffle(test.begin(), test.end(), ctx);
         for (int j = 1; j <= 10; ++j) {
-            BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end());
+            BOOST_CHECK(std::ranges::contains(test, j));
         }
     }
 }
diff --git a/src/util/moneystr.cpp b/src/util/moneystr.cpp
index 7cd68c0da8..9528933ae4 100644
--- a/src/util/moneystr.cpp
+++ b/src/util/moneystr.cpp
@@ -13,7 +13,6 @@
 #include <cstdint>
 #include <optional>
 
-using util::ContainsNUL;
 using util::TrimString;
 
 std::string FormatMoney(const CAmount n)
@@ -44,7 +43,7 @@ std::string FormatMoney(const CAmount n)
 
 std::optional<CAmount> ParseMoney(const std::string& money_string)
 {
-    if (ContainsNUL(money_string)) {
+    if (money_string.contains('\0')) {
         return std::nullopt;
     }
     const std::string str = TrimString(money_string);
diff --git a/src/util/string.h b/src/util/string.h
index 2bfe176a7d..de67094f30 100644
--- a/src/util/string.h
+++ b/src/util/string.h
@@ -232,17 +232,6 @@ inline std::string MakeUnorderedList(const std::vector<std::string>& items)
     return Join(items, "\n", [](const std::string& item) { return "- " + item; });
 }
 
-/**
- * Check if a string contains any embedded NUL characters
- */
-[[nodiscard]] inline bool ContainsNUL(std::string_view str) noexcept
-{
-    for (auto c : str) {
-        if (c == 0) return true;
-    }
-    return false;
-}
-
 /**
  * Locale-independent version of std::to_string
  */
diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp
index 7a2bd99320..359d637238 100644
--- a/src/wallet/rpc/wallet.cpp
+++ b/src/wallet/rpc/wallet.cpp
@@ -24,7 +24,6 @@
 #include <wallet/wallet.h>
 #include <wallet/walletutil.h>
 
-#include <algorithm>
 #include <optional>
 #include <string_view>
 
@@ -265,11 +264,8 @@ static RPCMethod loadwallet()
     std::vector<bilingual_str> warnings;
     std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool());
 
-    {
-        LOCK(context.wallets_mutex);
-        if (std::any_of(context.wallets.begin(), context.wallets.end(), [&name](const auto& wallet) { return wallet->GetName() == name; })) {
-            throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded.");
-        }
+    if (GetWallet(context, name)) {
+        throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded.");
     }
 
     std::shared_ptr<CWallet> const wallet = LoadWallet(context, name, load_on_start, options, status, error, warnings);
diff --git a/src/wallet/transaction.h b/src/wallet/transaction.h
index 153aeea213..23438679c5 100644
--- a/src/wallet/transaction.h
+++ b/src/wallet/transaction.h
@@ -16,6 +16,7 @@
 #include <util/string.h>
 #include <wallet/types.h>
 
+#include <algorithm>
 #include <bitset>
 #include <cstdint>
 #include <map>
@@ -445,7 +446,7 @@ public:
     : m_wtx(wtx),
     m_output(output)
     {
-        Assume(std::ranges::find(wtx.GetTx()->vout, output) != wtx.GetTx()->vout.end());
+        Assume(std::ranges::contains(wtx.GetTx()->vout, output));
     }
 
     const CWalletTx& GetWalletTx() const { return m_wtx; }
> [cf8e2c6](https://github.com/bitcoin/bitcoin/pull/36033/changes/cf8e2c6bfe496665edecfb293b9838c5398d6027) _refactor: clang-tidy readability-container-contains for C++23_: `ContainsNUL` now only calls `contains('\0')`, so I'd inline that check at its callers and remove the standalone fuzz call. The other membership searches can use `ranges::contains`. `loadwallet` can reuse `GetWallet` too, and that part could land separately before the C++23 switch. <details><summary>Example patch</summary> ```diff diff --git a/src/base58.cpp b/src/base58.cpp index d6157a8656..6cf3109f21 100644 --- a/src/base58.cpp +++ b/src/base58.cpp @@ -7,7 +7,6 @@ #include <hash.h> #include <uint256.h> #include <util/strencodings.h> -#include <util/string.h> #include <algorithm> #include <cassert> @@ -16,8 +15,6 @@ #include <limits> -using util::ContainsNUL; - /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static const int8_t mapBase58[256] = { @@ -134,7 +131,7 @@ std::string EncodeBase58(std::span<const unsigned char> input) bool DecodeBase58(std::string_view str, std::vector<unsigned char>& vchRet, int max_ret_len) { - if (ContainsNUL(str)) { + if (str.contains('\0')) { return false; } return DecodeBase58Raw(str, vchRet, max_ret_len); @@ -168,7 +165,7 @@ std::string EncodeBase58Check(std::span<const unsigned char> input) bool DecodeBase58Check(std::string_view str, std::vector<unsigned char>& vchRet, int max_ret) { - if (ContainsNUL(str)) { + if (str.contains('\0')) { return false; } return DecodeBase58CheckRaw(str, vchRet, max_ret); diff --git a/src/net.cpp b/src/net.cpp index 96d4812630..7ff1204092 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -358,7 +358,7 @@ bool IsLocal(const CService& addr) bool CConnman::AlreadyConnectedToHost(std::string_view host) const { LOCK(m_nodes_mutex); - return std::ranges::any_of(m_nodes, [&host](CNode* node) { return node->m_addr_name == host; }); + return std::ranges::contains(m_nodes, host, &CNode::m_addr_name); } bool CConnman::AlreadyConnectedToAddressPort(const CService& addr_port) const @@ -1809,7 +1809,7 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock, int nInbound = 0; - const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end(); + const bool inbound_onion = std::ranges::contains(m_onion_binds, addr_bind); // Tor inbound connections do not reveal the peer's actual network address. // Therefore do not apply address-based whitelist permissions to them. diff --git a/src/netaddress.cpp b/src/netaddress.cpp index c89569142c..25c21bbd42 100644 --- a/src/netaddress.cpp +++ b/src/netaddress.cpp @@ -22,7 +22,6 @@ #include <string_view> #include <tuple> -using util::ContainsNUL; using util::HasPrefix; CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const @@ -212,7 +211,7 @@ static void Checksum(std::span<const uint8_t> addr_pubkey, uint8_t (&checksum)[C bool CNetAddr::SetSpecial(std::string_view addr) { - if (ContainsNUL(addr)) { + if (addr.contains('\0')) { return false; } diff --git a/src/netbase.cpp b/src/netbase.cpp index 9c81cd249a..6ad70ca444 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -28,8 +28,6 @@ #include <sys/un.h> #endif -using util::ContainsNUL; - // Settings static GlobalMutex g_proxyinfo_mutex; static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex); @@ -144,7 +142,7 @@ std::vector<std::string> GetNetworkNames(bool append_unroutable) static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function) { - if (ContainsNUL(name)) return {}; + if (name.contains('\0')) return {}; { CNetAddr addr; // From our perspective, onion addresses are not hostnames but rather @@ -173,7 +171,7 @@ static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function) { - if (ContainsNUL(name)) return {}; + if (name.contains('\0')) return {}; std::string strHost = name; if (strHost.empty()) return {}; if (strHost.front() == '[' && strHost.back() == ']') { @@ -191,7 +189,7 @@ std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, D std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function) { - if (name.empty() || ContainsNUL(name)) { + if (name.empty() || name.contains('\0')) { return {}; } uint16_t port{portDefault}; @@ -216,7 +214,7 @@ std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bo CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function) { - if (ContainsNUL(name)) { + if (name.contains('\0')) { return {}; } // "1.2:345" will fail to resolve the ip, but will still set the port. @@ -833,7 +831,7 @@ CSubNet LookupSubNet(const std::string& subnet_str) { CSubNet subnet; assert(!subnet.IsValid()); - if (ContainsNUL(subnet_str)) { + if (subnet_str.contains('\0')) { return subnet; } diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index a9b152e653..7ba403bd18 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -716,7 +716,7 @@ bool IsDeprecatedRPCEnabled(const std::string& method) { const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc"); - return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end(); + return std::ranges::contains(enabled_methods, method); } UniValue JSONRPCExec(const JSONRPCRequest& jreq, bool catch_errors) diff --git a/src/script/sign.cpp b/src/script/sign.cpp index dbbf51077e..924ff983b9 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -132,7 +132,7 @@ std::vector<uint8_t> MutableTransactionSignatureCreator::CreateMuSig2Nonce(const auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey); if (it == sigdata.musig2_pubkeys.end()) return {}; const std::vector<CPubKey>& pubkeys = it->second; - if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {}; + if (!std::ranges::contains(pubkeys, part_pubkey)) return {}; // Compute sighash std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion); @@ -160,7 +160,7 @@ bool MutableTransactionSignatureCreator::CreateMuSig2PartialSig(const SigningPro auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey); if (it == sigdata.musig2_pubkeys.end()) return false; const std::vector<CPubKey>& pubkeys = it->second; - if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {}; + if (!std::ranges::contains(pubkeys, part_pubkey)) return {}; // Retrieve pubnonces auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256()); diff --git a/src/test/bip352_tests.cpp b/src/test/bip352_tests.cpp index 36c8c79db5..a93341e742 100644 --- a/src/test/bip352_tests.cpp +++ b/src/test/bip352_tests.cpp @@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(bip352_send_and_receive_test_vectors) expected_spks.push_back(tap); } match = std::all_of(sp_tr_dests->begin(), sp_tr_dests->end(), [&](const auto& entry) { - return std::find(expected_spks.begin(), expected_spks.end(), entry.second) != expected_spks.end(); + return std::ranges::contains(expected_spks, entry.second); }); if (match) break; } diff --git a/src/test/fuzz/mini_miner.cpp b/src/test/fuzz/mini_miner.cpp index 8848a0cddc..015b245d15 100644 --- a/src/test/fuzz/mini_miner.cpp +++ b/src/test/fuzz/mini_miner.cpp @@ -90,7 +90,7 @@ FUZZ_TARGET(mini_miner, .init = initialize_miner) // Add some random outpoint (will be interpreted as confirmed or not yet submitted // to mempool). auto outpoint = ConsumeDeserializable<COutPoint>(fuzzed_data_provider); - if (outpoint.has_value() && std::find(outpoints.begin(), outpoints.end(), *outpoint) == outpoints.end()) { + if (outpoint.has_value() && !std::ranges::contains(outpoints, *outpoint)) { outpoints.push_back(*outpoint); } } diff --git a/src/test/fuzz/rpc.cpp b/src/test/fuzz/rpc.cpp index 349bcf59ba..8bd4323757 100644 --- a/src/test/fuzz/rpc.cpp +++ b/src/test/fuzz/rpc.cpp @@ -367,8 +367,8 @@ void initialize_rpc() rpc_testing_setup = InitializeRPCFuzzTestingSetup(); const std::vector<std::string> supported_rpc_commands = rpc_testing_setup->GetRPCCommands(); for (const std::string& rpc_command : supported_rpc_commands) { - const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end(); - const bool not_safe_for_fuzzing = std::find(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(); + const bool safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_SAFE_FOR_FUZZING, rpc_command); + const bool not_safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING, rpc_command); if (!(safe_for_fuzzing || not_safe_for_fuzzing)) { std::cerr << "Error: RPC command \"" << rpc_command << "\" not found in RPC_COMMANDS_SAFE_FOR_FUZZING or RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n"; std::terminate(); @@ -394,7 +394,7 @@ FUZZ_TARGET(rpc, .init = initialize_rpc) if (!g_limit_to_rpc_command.empty() && rpc_command != g_limit_to_rpc_command) { return; } - const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end(); + const bool safe_for_fuzzing = std::ranges::contains(RPC_COMMANDS_SAFE_FOR_FUZZING, rpc_command); if (!safe_for_fuzzing) { return; } diff --git a/src/test/fuzz/string.cpp b/src/test/fuzz/string.cpp index 8e693326ca..f6bdb01404 100644 --- a/src/test/fuzz/string.cpp +++ b/src/test/fuzz/string.cpp @@ -41,7 +41,6 @@ using common::AmountErrMsg; using common::AmountHighWarn; using common::FeeModeFromString; using common::ResolveErrMsg; -using util::ContainsNUL; using util::Join; using util::RemovePrefix; using util::SplitString; @@ -101,7 +100,6 @@ FUZZ_TARGET(string) (void)TrimString(random_string_1); (void)TrimString(random_string_1, random_string_2); (void)UrlDecode(random_string_1); - (void)ContainsNUL(random_string_1); try { throw scriptnum_error{random_string_1}; } catch (const std::runtime_error&) { diff --git a/src/test/fuzz/system.cpp b/src/test/fuzz/system.cpp index 7c73f8b9f8..60bfb02e75 100644 --- a/src/test/fuzz/system.cpp +++ b/src/test/fuzz/system.cpp @@ -97,7 +97,7 @@ FUZZ_TARGET(system, .init = initialize_system) if (args_manager.GetArgFlags(hidden_argument) != std::nullopt) { continue; } - if (std::find(hidden_arguments.begin(), hidden_arguments.end(), hidden_argument) != hidden_arguments.end()) { + if (std::ranges::contains(hidden_arguments, hidden_argument)) { continue; } hidden_arguments.push_back(hidden_argument); diff --git a/src/test/fuzz/txgraph.cpp b/src/test/fuzz/txgraph.cpp index ec9ab79291..a84f917981 100644 --- a/src/test/fuzz/txgraph.cpp +++ b/src/test/fuzz/txgraph.cpp @@ -271,7 +271,7 @@ struct SimTxGraph // deduplication as it'd rely on non-deterministic pointer comparison). arg.clear(); for (auto ptr : ret) { - if (std::find(arg.begin(), arg.end(), ptr) == arg.end()) { + if (!std::ranges::contains(arg, ptr)) { arg.push_back(ptr); } } diff --git a/src/test/netbase_tests.cpp b/src/test/netbase_tests.cpp index 7515c21a0f..ea36db5ee3 100644 --- a/src/test/netbase_tests.cpp +++ b/src/test/netbase_tests.cpp @@ -15,8 +15,9 @@ #include <util/strencodings.h> #include <util/translation.h> -#include <string> +#include <algorithm> #include <numeric> +#include <string> #include <boost/test/unit_test.hpp> @@ -477,13 +478,13 @@ BOOST_AUTO_TEST_CASE(netpermissions_test) const auto strings = NetPermissions::ToStrings(NetPermissionFlags::All); BOOST_CHECK_EQUAL(strings.size(), 7U); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "bloomfilter") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "forcerelay") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "relay") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "noban") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "mempool") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "download") != strings.end()); - BOOST_CHECK(std::find(strings.begin(), strings.end(), "addr") != strings.end()); + BOOST_CHECK(std::ranges::contains(strings, "bloomfilter")); + BOOST_CHECK(std::ranges::contains(strings, "forcerelay")); + BOOST_CHECK(std::ranges::contains(strings, "relay")); + BOOST_CHECK(std::ranges::contains(strings, "noban")); + BOOST_CHECK(std::ranges::contains(strings, "mempool")); + BOOST_CHECK(std::ranges::contains(strings, "download")); + BOOST_CHECK(std::ranges::contains(strings, "addr")); } BOOST_AUTO_TEST_CASE(netbase_dont_resolve_strings_with_embedded_nul_characters) diff --git a/src/test/random_tests.cpp b/src/test/random_tests.cpp index 213465fded..b99321905d 100644 --- a/src/test/random_tests.cpp +++ b/src/test/random_tests.cpp @@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(stdrandom_test) std::vector<int> test{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::shuffle(test.begin(), test.end(), ctx); for (int j = 1; j <= 10; ++j) { - BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end()); + BOOST_CHECK(std::ranges::contains(test, j)); } } } diff --git a/src/util/moneystr.cpp b/src/util/moneystr.cpp index 7cd68c0da8..9528933ae4 100644 --- a/src/util/moneystr.cpp +++ b/src/util/moneystr.cpp @@ -13,7 +13,6 @@ #include <cstdint> #include <optional> -using util::ContainsNUL; using util::TrimString; std::string FormatMoney(const CAmount n) @@ -44,7 +43,7 @@ std::string FormatMoney(const CAmount n) std::optional<CAmount> ParseMoney(const std::string& money_string) { - if (ContainsNUL(money_string)) { + if (money_string.contains('\0')) { return std::nullopt; } const std::string str = TrimString(money_string); diff --git a/src/util/string.h b/src/util/string.h index 2bfe176a7d..de67094f30 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -232,17 +232,6 @@ inline std::string MakeUnorderedList(const std::vector<std::string>& items) return Join(items, "\n", [](const std::string& item) { return "- " + item; }); } -/** - * Check if a string contains any embedded NUL characters - */ -[[nodiscard]] inline bool ContainsNUL(std::string_view str) noexcept -{ - for (auto c : str) { - if (c == 0) return true; - } - return false; -} - /** * Locale-independent version of std::to_string */ diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp index 7a2bd99320..359d637238 100644 --- a/src/wallet/rpc/wallet.cpp +++ b/src/wallet/rpc/wallet.cpp @@ -24,7 +24,6 @@ #include <wallet/wallet.h> #include <wallet/walletutil.h> -#include <algorithm> #include <optional> #include <string_view> @@ -265,11 +264,8 @@ static RPCMethod loadwallet() std::vector<bilingual_str> warnings; std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool()); - { - LOCK(context.wallets_mutex); - if (std::any_of(context.wallets.begin(), context.wallets.end(), [&name](const auto& wallet) { return wallet->GetName() == name; })) { - throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded."); - } + if (GetWallet(context, name)) { + throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded."); } std::shared_ptr<CWallet> const wallet = LoadWallet(context, name, load_on_start, options, status, error, warnings); diff --git a/src/wallet/transaction.h b/src/wallet/transaction.h index 153aeea213..23438679c5 100644 --- a/src/wallet/transaction.h +++ b/src/wallet/transaction.h @@ -16,6 +16,7 @@ #include <util/string.h> #include <wallet/types.h> +#include <algorithm> #include <bitset> #include <cstdint> #include <map> @@ -445,7 +446,7 @@ public: : m_wtx(wtx), m_output(output) { - Assume(std::ranges::find(wtx.GetTx()->vout, output) != wtx.GetTx()->vout.end()); + Assume(std::ranges::contains(wtx.GetTx()->vout, output)); } const CWalletTx& GetWalletTx() const { return m_wtx; } ``` </details>
maflcko (Migrated from github.com) reviewed 2026-11-26 10:16:39 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:16:39 +00:00
Sure, but then it should be done in all places? Ref: https://github.com/bitcoin/bitcoin/pull/36535#issuecomment-6186677574
maflcko (Migrated from github.com) reviewed 2026-11-26 10:16:44 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:16:44 +00:00

Hmm, I don't know the answer here. See also https://github.com/bitcoin/bitcoin/issues/34928. One one hand it is nice to just run tidy on everything as a belt-and-suspender. On the other hand, it is extra effort ...

Hmm, I don't know the answer here. See also https://github.com/bitcoin/bitcoin/issues/34928. One one hand it is nice to just run tidy on everything as a belt-and-suspender. On the other hand, it is extra effort ...
maflcko (Migrated from github.com) reviewed 2026-11-26 10:16:50 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:16:50 +00:00

This happens with C++20 on current master, so it needs to be an independent pull.

This happens with C++20 on current master, so it needs to be an independent pull.
maflcko (Migrated from github.com) reviewed 2026-11-26 10:16:59 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:16:59 +00:00

This happens on master, and I don't think this needs to be fixed in tests. If it was, it should be checked and enforced by tidy, not manually.

See also my rant https://github.com/bitcoin/bitcoin/pull/35139, but I don't think it'll go anywhere.

This happens on master, and I don't think this needs to be fixed in tests. If it was, it should be checked and enforced by tidy, not manually. See also my rant https://github.com/bitcoin/bitcoin/pull/35139, but I don't think it'll go anywhere.
maflcko (Migrated from github.com) reviewed 2026-11-26 10:17:08 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:17:08 +00:00

ok, but this seems unrelated to C++23? Maybe a separate pull can be created?

ok, but this seems unrelated to C++23? Maybe a separate pull can be created?
maflcko (Migrated from github.com) reviewed 2026-11-26 10:17:14 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 10:17:14 +00:00

Sure, this can be done right after merge of this one.

Sure, this can be done right after merge of this one.
maflcko commented 2026-11-26 10:19:09 +00:00 (Migrated from github.com)

thx, took some and replied to the others

thx, took some and replied to the others
l0rinc (Migrated from github.com) reviewed 2026-11-26 15:10:15 +00:00
l0rinc (Migrated from github.com) commented 2026-11-26 15:10:15 +00:00

I mean this is a behavior change as-is

I mean this is a behavior change as-is
maflcko (Migrated from github.com) reviewed 2026-11-26 15:58:20 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 15:58:20 +00:00

ok, I already dropped the commit in the last push. I guess using views::zip isn't worth it in normal code. Only exception could be the univalue iteration, but this can be done later inside the univalue lib.

ok, I already dropped the commit in the last push. I guess using `views::zip` isn't worth it in normal code. Only exception could be the univalue iteration, but this can be done later inside the univalue lib.
maflcko (Migrated from github.com) reviewed 2026-11-26 16:47:54 +00:00
maflcko (Migrated from github.com) commented 2026-11-26 16:47:54 +00:00
Closing for now. Let's continue in https://github.com/bitcoin/bitcoin/pull/36747#discussion_r4711280131
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36033
No description provided.