util: write JSON atomically in WriteJson #35763

Open
kevkevinpal wants to merge 2 commits from banlist-atomic-write-json-unsafe into master AGit
kevkevinpal commented 2026-07-21 12:47:38 +00:00 (Migrated from github.com)

Summary

Follow-up to https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299

  • Renamed common::WriteSettings to common::WriteJson.
  • WriteJson writes to path + ".tmp" and RenameOver()s into place, so a failed or interrupted write cannot leave a truncated destination. Both settings.json and banlist.json use this helper.
  • Added a unit test for the write/read roundtrip, that the .tmp is gone after success, that rename failure is detected, and that a second failed write overwrites the same .tmp rather than creating another.
## Summary Follow-up to https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299 - Renamed `common::WriteSettings` to `common::WriteJson`. - `WriteJson` writes to `path + ".tmp"` and `RenameOver()`s into place, so a failed or interrupted write cannot leave a truncated destination. Both `settings.json` and `banlist.json` use this helper. - Added a unit test for the write/read roundtrip, that the `.tmp` is gone after success, that rename failure is detected, and that a second failed write overwrites the same `.tmp` rather than creating another.
DrahtBot commented 2026-07-21 12:47:46 +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
ACK winterrdog, ryanofsky
Stale ACK Herb-ops

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:

  • #34520 (refactor: Add nodiscard to functions returning bool+mutable ref by maflcko)

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/35763 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35763.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35763#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 | | ---- | --------- | | ACK | [winterrdog](https://github.com/bitcoin/bitcoin/pull/35763#pullrequestreview-5882961360), [ryanofsky](https://github.com/bitcoin/bitcoin/pull/35763#pullrequestreview-5890638406) | | Stale ACK | [Herb-ops](https://github.com/bitcoin/bitcoin/pull/35763#issuecomment-5103784773) | 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: * [#34520](https://github.com/bitcoin/bitcoin/pull/34520) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34520.svg"></sub> (refactor: Add [[nodiscard]] to functions returning bool+mutable ref by maflcko) 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-->
winterrdog commented 2026-07-21 17:42:12 +00:00 (Migrated from github.com)

Concept ACK

Thanks for picking these up.

cc: @sys-dev @ryanofsky

Concept ACK Thanks for picking these up. cc: @sys-dev @ryanofsky
Herb-ops commented 2026-07-28 11:52:57 +00:00 (Migrated from github.com)

ACK 07ec5af152b5bcff1b74decb9c7b729dff6c2283, with two non-blocking observations:

The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test.

The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers.

ACK 07ec5af152b5bcff1b74decb9c7b729dff6c2283, with two non-blocking observations: The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test. The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers.
winterrdog commented 2026-07-28 22:14:37 +00:00 (Migrated from github.com)

The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test.

The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers.

these need attention. so, i think they are blocking

> The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test. > > The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers. these need attention. so, i think they are blocking
winterrdog commented 2026-07-28 22:36:30 +00:00 (Migrated from github.com)

while going through this, another thought came to mind. right now WriteJsonUnsafe writes directly to whatever path it is given and relies on the caller to do the tmp-file + RenameOver() step. both current callers (args.cpp and addrdb.cpp) do this correctly, but that guarantee only lives in a comment. nothing stops a future caller from accidentally writing straight to a live file

i was wondering if it is worth making this a bit harder to misuse. two possible approaches came to mind

approach A: add WriteJsonAtomic alongside WriteJsonUnsafe

keep the low-level helper as-is, but add a wrapper that handles the tmp-file + rename step:

// settings.h
bool WriteJsonUnsafe(const fs::path& path,
                     const std::map<std::string, SettingsValue>& values,
                     std::vector<std::string>& errors);

bool WriteJsonAtomic(const fs::path& dest_path,
                     const std::map<std::string, SettingsValue>& values,
                     std::vector<std::string>& errors);


// settings.cpp
bool WriteJsonAtomic(const fs::path& dest_path,
                     const std::map<std::string, SettingsValue>& values,
                     std::vector<std::string>& errors)
{
    const fs::path path_tmp{dest_path + ".tmp"};
    if (!WriteJsonUnsafe(path_tmp, values, errors)) {
        return false;
    }
    return RenameOver(path_tmp, dest_path);
}

callers become:

// either this
if (!WriteJsonUnsafe(path_tmp, values, errors)) return false;
if (!RenameOver(path_tmp, path)) return false;

// or this
if (!WriteJsonAtomic(path, values, errors)) return false;

this keeps the current API intact while giving callers a safe helper for the common case. existing callers with custom tmp-file handling can keep using WriteJsonUnsafe, while new callers can just use WriteJsonAtomic. the downside is that the footgun is still there. WriteJsonUnsafe is still publicly available, so a future caller can still accidentally bypass the atomic write path. it also means carrying two helpers that are closely related

approach B: make the helper always write atomically

this is quite similar to the idea @sys-dev suggested here.

instead of exposing both APIs, make the helper always write to a tmp file and rename it:

// settings.h
bool WriteJson(const fs::path& dest_path,
               const std::map<std::string, SettingsValue>& values,
               std::vector<std::string>& errors);
// settings.cpp
bool WriteJson(const fs::path& dest_path,
               const std::map<std::string, SettingsValue>& values,
               std::vector<std::string>& errors)
{
    SettingsValue out(SettingsValue::VOBJ);
    for (const auto& [key, value] : values) out.pushKVEnd(key, value);

    const fs::path path_tmp{dest_path + ".tmp"};

    std::ofstream file{path_tmp.std_path()};
    // ...error handling lives here...
    file << out.write(/*prettyIndent=*/4, /*indentLevel=*/1) << std::endl;

    return RenameOver(path_tmp, dest_path);
}

this makes the safe path the only path. every caller gets atomic writes by default, so it is no longer possible to accidentally write directly to a live file. the tradeoff is that every caller now gets .tmp + RenameOver() semantics, even if a future use case genuinely just wants "write these bytes to this exact path" (for example, a one-off dump or export). it also bakes the tmp-file naming scheme into the helper itself


my thinking: i lean toward approach B unless there is already a use case for exposing the raw write helper. it feels a bit simpler, and it removes the footgun instead of just documenting it. that said, i could easily be missing a future use case where writing directly to the given path is the better choice

any thoughts ?

while going through this, another thought came to mind. right now `WriteJsonUnsafe` writes directly to whatever path it is given and relies on the caller to do the tmp-file + `RenameOver()` step. both current callers (`args.cpp` and `addrdb.cpp`) do this correctly, but that guarantee only lives in a comment. nothing stops a future caller from _accidentally_ writing straight to a live file i was wondering if it is worth making this a bit harder to misuse. two possible approaches came to mind <details><summary><b>approach A: add <code>WriteJsonAtomic</code> alongside <code>WriteJsonUnsafe</code></b></summary> keep the low-level helper as-is, but add a wrapper that handles the tmp-file + rename step: ```cpp // settings.h bool WriteJsonUnsafe(const fs::path& path, const std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors); bool WriteJsonAtomic(const fs::path& dest_path, const std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors); // settings.cpp bool WriteJsonAtomic(const fs::path& dest_path, const std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors) { const fs::path path_tmp{dest_path + ".tmp"}; if (!WriteJsonUnsafe(path_tmp, values, errors)) { return false; } return RenameOver(path_tmp, dest_path); } ``` callers become: ```cpp // either this if (!WriteJsonUnsafe(path_tmp, values, errors)) return false; if (!RenameOver(path_tmp, path)) return false; // or this if (!WriteJsonAtomic(path, values, errors)) return false; ``` this keeps the current API intact while giving callers a safe helper for the common case. existing callers with custom tmp-file handling can keep using `WriteJsonUnsafe`, while new callers can just use `WriteJsonAtomic`. the downside is that the footgun is still there. `WriteJsonUnsafe` is still publicly available, so a future caller can still accidentally bypass the atomic write path. it also means carrying two helpers that are closely related </details> <details><summary><b>approach B: make the helper always write atomically</b></summary> *this is quite similar to the idea @sys-dev suggested [here](https://github.com/bitcoin/bitcoin/pull/35384#discussion_r3329176108).* instead of exposing both APIs, make the helper always write to a tmp file and rename it: ```cpp // settings.h bool WriteJson(const fs::path& dest_path, const std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors); ``` ```cpp // settings.cpp bool WriteJson(const fs::path& dest_path, const std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors) { SettingsValue out(SettingsValue::VOBJ); for (const auto& [key, value] : values) out.pushKVEnd(key, value); const fs::path path_tmp{dest_path + ".tmp"}; std::ofstream file{path_tmp.std_path()}; // ...error handling lives here... file << out.write(/*prettyIndent=*/4, /*indentLevel=*/1) << std::endl; return RenameOver(path_tmp, dest_path); } ``` this makes the safe path the only path. every caller gets atomic writes by default, so it is no longer possible to accidentally write directly to a live file. the tradeoff is that every caller now gets `.tmp` + `RenameOver()` semantics, even if a future use case genuinely just wants "_write these bytes to this exact path_" (for example, a one-off dump or export). it also bakes the tmp-file naming scheme into the helper itself </details> --- **my thinking:** i lean toward approach B unless there is already a use case for exposing the raw write helper. it feels a bit simpler, and it removes the footgun instead of just documenting it. that said, i could easily be missing a future use case where writing directly to the given path is the better choice any thoughts ?
kevkevinpal commented 2026-09-07 14:26:06 +00:00 (Migrated from github.com)

@Herb-ops @winterrdog, can you review this again?

@Herb-ops @winterrdog, can you review this again?
winterrdog (Migrated from github.com) reviewed 2026-09-07 19:18:51 +00:00
winterrdog (Migrated from github.com) left a comment

approach ACK


now, we can update the PR title & description to match what the current code
actually does. they still mention WriteJsonUnsafe and callers doing the
atomic rename, while the current implementation is self-contained and handles
the "temp write + RenameOver()" itself

approach ACK --- now, we can update the PR title & description to match what the current code actually does. they still mention `WriteJsonUnsafe` and callers doing the atomic rename, while the current implementation is self-contained and handles the "temp write + `RenameOver()`" itself
winterrdog (Migrated from github.com) reviewed 2026-09-07 19:21:21 +00:00
Lines 156-168
winterrdog (Migrated from github.com) commented 2026-09-07 19:21:21 +00:00

premise: cleaning up path_tmp in case one of the error paths
is explored

currently, WriteJson() returns false but leaves the .tmp file behind.
the new test (write_uses_rename) actually has to manually remove
banlist_atomic.json.tmp after exercising the error paths, so it looks
like we can leave stale temp files around in cases like persistent permission
problems, an antivirus file lock on Windows, or repeated rename failures,
these temp files are most likely to accumulate indefinitely

would a best-effort fs::remove(path_tmp) on the failure path make sense
here, or do you prefer leaving the temp file around?

if implemented, one of the tradeoffs i can easily think of is the loss of
forensic evidence when debugging persistent failures.

any thoughts ?

**premise**: cleaning up `path_tmp` in case one of the error paths is explored currently, `WriteJson()` returns `false` but leaves the `.tmp` file behind. the new test (`write_uses_rename`) actually has to manually remove `banlist_atomic.json.tmp` after exercising the error paths, so it looks like we can leave stale temp files around in cases like persistent permission problems, an antivirus file lock on Windows, or repeated rename failures, these temp files are most likely to accumulate indefinitely would a _best-effort_ `fs::remove(path_tmp)` on the failure path make sense here, or do you prefer leaving the temp file around? if implemented, one of the tradeoffs i can easily think of is the loss of forensic evidence when debugging persistent failures. any thoughts ?
kevkevinpal (Migrated from github.com) reviewed 2026-09-07 21:25:51 +00:00
Lines 156-168
kevkevinpal (Migrated from github.com) commented 2026-09-07 21:25:51 +00:00

I prefer leaving it.

The tmp name is stable (path + ".tmp"), so a later attempt opens the same file and overwrites it. You get at most one leftover per destination, not an accumulating set. That matches the old settings.json write, which also left the .tmp on rename failure.

The fs::remove(...tmp) in the test is just fixture cleanup.


I can amend the commit to add a test that asserts we don't create endless tmp files

I prefer leaving it. The tmp name is stable (path + ".tmp"), so a later attempt opens the same file and overwrites it. You get at most one leftover per destination, not an accumulating set. That matches the old settings.json write, which also left the .tmp on rename failure. The fs::remove(...tmp) in the test is just fixture cleanup. --- I can amend the commit to add a test that asserts we don't create endless tmp files
kevkevinpal (Migrated from github.com) reviewed 2026-09-07 21:30:07 +00:00
Lines 156-168
kevkevinpal (Migrated from github.com) commented 2026-09-07 21:30:07 +00:00
Added this test https://github.com/bitcoin/bitcoin/pull/35763/changes/0260a681e1f15d57b0ddf57b8bb539d8ac3dc577#diff-8e202c9cf7b0629a40c224318626d23656c0366a1f4b98f8a34ed62f7691a161R73-R81 @winterrdog let me know if this looks good to you
winterrdog (Migrated from github.com) reviewed 2026-09-08 18:37:04 +00:00
winterrdog (Migrated from github.com) commented 2026-09-08 18:33:22 +00:00

:( this has dragged on for quite some time. the approach and code work fine but i spotted an API naming issue that i think is worth discussing.

currently, WriteSettings was renamed to WriteJson, but ReadSettings kept its old name. so we now have a WriteJson / ReadSettings pair that operates on the same kind of data, but has different names (asymmetry)

so, i see 3 potential directions:

A. keep the ReadSettings / WriteSettings pair

probably the simplest fix for this PR. these functions are not really generic JSON helpers anyway: they assume a flat map<string, SettingsValue> and handle the _warning_ key. the downside is that having WriteSettings write to something like banlist.json feels a little odd

B. rename both to a ReadJson / WriteJson pair

this fixes the asymmetry with a small change. the downside is that WriteJson sounds more generic than it actually is, because it would still have settings-specific behavior like adding the _warning_ key.

C. extract the generic JSON functionality from the settings functionality into separate functions

for example, have generic ReadJsonFile / WriteJsonFile helpers underneath, then keep ReadSettings / WriteSettings as thin wrappers for the settings-specific behavior.

this seems like the cleanest long-term design if we expect more JSON-backed files to use this code, but probably more work than this PR expected.


any thoughts on this ?

:( this has dragged on for quite some time. the approach and code work fine but i spotted an API naming issue that i think is worth discussing. currently, `WriteSettings` was renamed to `WriteJson`, but [`ReadSettings`](https://github.com/bitcoin/bitcoin/blob/0260a681e1f15d57b0ddf57b8bb539d8ac3dc577/src/common/settings.cpp#L73) kept its old name. so we now have a `WriteJson` / `ReadSettings` pair that operates on the same kind of data, but has different names (asymmetry) so, i see 3 potential directions: **A. keep the ****`ReadSettings`**** / ****`WriteSettings`**** pair** probably the simplest fix for this PR. these functions are not really generic JSON helpers anyway: they assume a flat `map<string, SettingsValue>` and handle the `_warning_` key. the downside is that having `WriteSettings` write to something like `banlist.json` feels a little odd **B. rename both to a ****`ReadJson`**** / ****`WriteJson`**** pair** this fixes the asymmetry with a small change. the downside is that `WriteJson` sounds more generic than it actually is, because it would still have settings-specific behavior like adding the `_warning_` key. **C. extract the generic JSON functionality from the settings functionality into separate functions** for example, have generic `ReadJsonFile` / `WriteJsonFile` helpers underneath, then keep `ReadSettings` / `WriteSettings` as thin wrappers for the settings-specific behavior. this seems like the cleanest long-term design if we expect more JSON-backed files to use this code, but probably more work than this PR expected. --- any thoughts on this ?
Lines 156-168
winterrdog (Migrated from github.com) commented 2026-09-08 18:37:00 +00:00

The tmp name is stable (path + ".tmp"), so a later attempt opens the same file and overwrites it.

makes sense. i concur

let me know if this looks good to you

yes! good, it is

> The tmp name is stable (path + ".tmp"), so a later attempt opens the same file and overwrites it. makes sense. i concur > let me know if this looks good to you yes! good, it is
kevkevinpal (Migrated from github.com) reviewed 2026-09-10 22:12:56 +00:00
kevkevinpal (Migrated from github.com) commented 2026-09-10 22:12:56 +00:00

Thank you for the review, and yeah, I agree that it's strange to have them different like that. I pushed ed55f14 to do path A.

We can do a follow-up for C if we want after this is merged.

Thank you for the review, and yeah, I agree that it's strange to have them different like that. I pushed [ed55f14](https://github.com/bitcoin/bitcoin/pull/35763/commits/ed55f14404baabc9eaff68d25e50e167a2fafc8f) to do path A. We can do a follow-up for C if we want after this is merged.
winterrdog (Migrated from github.com) reviewed 2026-09-17 17:15:31 +00:00
winterrdog (Migrated from github.com) commented 2026-09-17 17:15:31 +00:00

do a follow-up for C if we want

that is fine. we can do that

> do a follow-up for C if we want that is fine. we can do that
winterrdog (Migrated from github.com) reviewed 2026-09-17 17:23:19 +00:00
winterrdog (Migrated from github.com) left a comment

tACK ed55f14404

successfully built and tested on FreeBSD 15.0/clang++-19.1.7/x86_64. the changes herein LGTM as well

tACK ed55f14404baabc9eaff68d25e50e167a2fafc8f successfully built and tested on FreeBSD `15.0`/`clang++-19.1.7`/`x86_64`. the changes herein LGTM as well
First-time contributor

🔵 Suggestion · Failure test does not check preservation of the previous banlist

The test deletes the valid banlist before forcing failure, so it never checks that a failed update leaves the last good banlist readable.

Location: src/test/banman_tests.cpp:69 (head).

🔵 Suggestion · PR description claims a WriteJson rename absent from the patch

The PR title and description refer to WriteJson, but the helper and both callers still use common::WriteSettings.

Location: src/common/settings.h:48 (head).

🔵 Suggestion · Atomic banlist replacement changes operator-managed file layouts

Replacement changes symlink, file bind-mount and custom-permission behavior for banlist.json; documenting these upgrade effects would help, although no affected deployment was identified and the platform-specific failure was not experimentally observed.

Location: src/common/settings.cpp:153 (head).

🔵 Suggestion · Use different data to test repeated failed writes

Both failed writes in the rename-failure block (src/test/banman_tests.cpp:71-72) pass the same bans_write. The block checks only that banlist_atomic.json.tmp exists and that exactly one .tmp file is present, never what the file contains. A regression that appended to the existing temp file instead of truncating it would still pass. So the PR description's claim that the test shows a second failed write overwrites the same .tmp is only half checked: the test confirms the name is reused, not that the contents are replaced.

Location: src/test/banman_tests.cpp:71 (head).

Review coverage was incomplete.


Reviewed: 9f2077dc09c9 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:f3e06854f254c480580a263b00f5c6aaa804717e751da362d6c3a17a8fae78d3:eaa37ea1cdada8fdd806ab11180fd9e0f01062422d9d8c5ea7dcfd80d5014b95 --> <!-- ralph-base:791173ae952bb07716531dd01a78d70dc3b7c038 --> <!-- ralph-head:9f2077dc09c98e093e15c605ef292669ef409f1d --> <!-- ralph-case:af7dbd779a04a0bea2dd081148e5569bc4b673a23269453bfe524259af0ba45e --> **🔵 Suggestion · Failure test does not check preservation of the previous banlist** The test deletes the valid banlist before forcing failure, so it never checks that a failed update leaves the last good banlist readable. Location: [`src/test/banman_tests.cpp:69`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/9f2077dc09c98e093e15c605ef292669ef409f1d/src/test/banman_tests.cpp#L69>) (head). **🔵 Suggestion · PR description claims a `WriteJson` rename absent from the patch** The PR title and description refer to `WriteJson`, but the helper and both callers still use `common::WriteSettings`. Location: [`src/common/settings.h:48`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/9f2077dc09c98e093e15c605ef292669ef409f1d/src/common/settings.h#L48>) (head). **🔵 Suggestion · Atomic banlist replacement changes operator-managed file layouts** Replacement changes symlink, file bind-mount and custom-permission behavior for `banlist.json`; documenting these upgrade effects would help, although no affected deployment was identified and the platform-specific failure was not experimentally observed. Location: [`src/common/settings.cpp:153`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/9f2077dc09c98e093e15c605ef292669ef409f1d/src/common/settings.cpp#L153>) (head). **🔵 Suggestion · Use different data to test repeated failed writes** Both failed writes in the rename-failure block (`src/test/banman_tests.cpp:71-72`) pass the same `bans_write`. The block checks only that `banlist_atomic.json.tmp` exists and that exactly one `.tmp` file is present, never what the file contains. A regression that appended to the existing temp file instead of truncating it would still pass. So the PR description's claim that the test shows a second failed write overwrites the same `.tmp` is only half checked: the test confirms the name is reused, not that the contents are replaced. Location: [`src/test/banman_tests.cpp:71`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/9f2077dc09c98e093e15c605ef292669ef409f1d/src/test/banman_tests.cpp#L71>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`9f2077dc09c9`](<https://git.fish.foo/bitcoin/bitcoin/commit/9f2077dc09c98e093e15c605ef292669ef409f1d>) · [Review report](<https://review.fish.foo/report/35763-9f2077dc09c98e093e15c605ef292669ef409f1d-2586-3.html>) · [Previous reports](<https://review.fish.foo/traces/35763/>) [permalink](<https://review.fish.foo/report/35763-9f2077dc09c98e093e15c605ef292669ef409f1d-2586-3.html>)
ryanofsky (Migrated from github.com) approved these changes 2026-11-05 18:38:08 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK ed55f14404. Thanks for following up on #35384 and for the test of the rename failure path.

Code review ACK ed55f14404baabc9eaff68d25e50e167a2fafc8f. Thanks for following up on #35384 and for the test of the rename failure path.
Lines 151-157
ryanofsky (Migrated from github.com) commented 2026-11-05 18:20:33 +00:00

In commit "util: atomically write banlist.json and settings.json" (ed55f14404)

Nit: now that the function is called WriteSettings again, this function's behavior doesn't change, so the restructuring here could be dropped to keep the diff to the files that actually change. Fine either way.

In commit "util: atomically write banlist.json and settings.json" (ed55f14404baabc9eaff68d25e50e167a2fafc8f) Nit: now that the function is called `WriteSettings` again, this function's behavior doesn't change, so the restructuring here could be dropped to keep the diff to the files that actually change. Fine either way.
ryanofsky (Migrated from github.com) commented 2026-11-05 18:35:13 +00:00

In commit "util: atomically write banlist.json and settings.json" (ed55f14404)

This ended up different from what I suggested in https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299, and from an earlier version of this PR: keep WriteSettings a low-level function that writes the path it is given, rename it to make clear it is unsafe to use without RenameOver, and have callers do the rename. I still slightly prefer that, because I like functions that do one thing well, and once a write function also manages the temporary file it has to make choices for every caller (how the temporary file is named, whether to fsync) that some callers might want to make differently. But I don't see a problem with the current approach, and it is simpler for the two callers that exist now, so please go with whichever makes more sense to you.

In commit "util: atomically write banlist.json and settings.json" (ed55f14404baabc9eaff68d25e50e167a2fafc8f) This ended up different from what I suggested in https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299, and from an earlier version of this PR: keep `WriteSettings` a low-level function that writes the path it is given, rename it to make clear it is unsafe to use without `RenameOver`, and have callers do the rename. I still slightly prefer that, because I like functions that do one thing well, and once a write function also manages the temporary file it has to make choices for every caller (how the temporary file is named, whether to fsync) that some callers might want to make differently. But I don't see a problem with the current approach, and it is simpler for the two callers that exist now, so please go with whichever makes more sense to you.
ryanofsky (Migrated from github.com) commented 2026-11-05 18:20:30 +00:00

In commit "util: atomically write banlist.json and settings.json" (ed55f14404)

The commit message should say what behavior changes. It is only a title now, and since the commit also moves code around (the .tmp handling moves from WriteSettingsFile into WriteSettings, GetSettingsPath loses its temp parameter, CBanDB::Write is restructured), the diff makes it hard to see what the actual change is: banlist.json used to be written in place and is now written through a temporary file, while settings.json is written the same way as before. I'd suggest something like:

util: write banlist.json through a temporary file

Before this change, CBanDB::Write() passed banlist.json directly to
common::WriteSettings(), which truncates the file and then writes it.
If the node crashed during the write, or the write failed because the
disk was full, banlist.json could be left empty or partly written. On
the next startup the ban list would fail to load and all bans would be
dropped.

settings.json did not have this problem, because
ArgsManager::WriteSettingsFile() wrote settings.json.tmp and renamed it
over settings.json.

Move the .tmp file and RenameOver() step from WriteSettingsFile() into
WriteSettings(), so banlist.json is written the same way. If writing
banlist.json fails now, the previous banlist.json is kept and
banlist.json.tmp is left behind, to be overwritten by the next write.

settings.json is written the same way as before. The only change there
is the wording of write errors, which now say "JSON file" instead of
"settings file".

It would be even easier to review as two commits: first a small commit that changes CBanDB::Write to write banlist.json.tmp and call RenameOver itself, with the new test, so the behavior change is a few lines on its own; then a refactoring commit that moves the .tmp handling into WriteSettings and removes it from both callers, with no behavior change other than the error wording.

The PR title and description also still say WriteJson, and they go into the merge commit, so they should be updated to match too.

In commit "util: atomically write banlist.json and settings.json" (ed55f14404baabc9eaff68d25e50e167a2fafc8f) The commit message should say what behavior changes. It is only a title now, and since the commit also moves code around (the `.tmp` handling moves from `WriteSettingsFile` into `WriteSettings`, `GetSettingsPath` loses its `temp` parameter, `CBanDB::Write` is restructured), the diff makes it hard to see what the actual change is: `banlist.json` used to be written in place and is now written through a temporary file, while `settings.json` is written the same way as before. I'd suggest something like: ``` util: write banlist.json through a temporary file Before this change, CBanDB::Write() passed banlist.json directly to common::WriteSettings(), which truncates the file and then writes it. If the node crashed during the write, or the write failed because the disk was full, banlist.json could be left empty or partly written. On the next startup the ban list would fail to load and all bans would be dropped. settings.json did not have this problem, because ArgsManager::WriteSettingsFile() wrote settings.json.tmp and renamed it over settings.json. Move the .tmp file and RenameOver() step from WriteSettingsFile() into WriteSettings(), so banlist.json is written the same way. If writing banlist.json fails now, the previous banlist.json is kept and banlist.json.tmp is left behind, to be overwritten by the next write. settings.json is written the same way as before. The only change there is the wording of write errors, which now say "JSON file" instead of "settings file". ``` It would be even easier to review as two commits: first a small commit that changes `CBanDB::Write` to write `banlist.json.tmp` and call `RenameOver` itself, with the new test, so the behavior change is a few lines on its own; then a refactoring commit that moves the `.tmp` handling into `WriteSettings` and removes it from both callers, with no behavior change other than the error wording. The PR title and description also still say `WriteJson`, and they go into the merge commit, so they should be updated to match too.
Lines 52-56
ryanofsky (Migrated from github.com) commented 2026-11-05 18:20:31 +00:00

In commit "util: atomically write banlist.json and settings.json" (ed55f14404)

Non-blocking: this protects against the process being killed or failing partway through the write, but since nothing calls fsync before the rename, a power loss can still leave an empty file on some filesystems (SerializeFileDB in addrdb.cpp calls Commit() before renaming for that reason). Not something this PR needs to fix, but the comment could be more specific so callers don't assume more:

//! Write a settings file by writing to a temporary `.tmp` file next to `path`
//! and using RenameOver() to replace the destination. This avoids leaving a
//! truncated or empty file if the process is interrupted while writing. The
//! file is not synced to disk, so this does not protect against power loss.
In commit "util: atomically write banlist.json and settings.json" (ed55f14404baabc9eaff68d25e50e167a2fafc8f) Non-blocking: this protects against the process being killed or failing partway through the write, but since nothing calls fsync before the rename, a power loss can still leave an empty file on some filesystems ([`SerializeFileDB`](https://github.com/bitcoin/bitcoin/blob/ed55f14404baabc9eaff68d25e50e167a2fafc8f/src/addrdb.cpp#L76-L94) in `addrdb.cpp` calls `Commit()` before renaming for that reason). Not something this PR needs to fix, but the comment could be more specific so callers don't assume more: ```cpp //! Write a settings file by writing to a temporary `.tmp` file next to `path` //! and using RenameOver() to replace the destination. This avoids leaving a //! truncated or empty file if the process is interrupted while writing. The //! file is not synced to disk, so this does not protect against power loss. ```
ryanofsky (Migrated from github.com) commented 2026-11-05 18:20:34 +00:00

In commit "util: atomically write banlist.json and settings.json" (ed55f14404)

Nit: entry here shadows the CBanEntry entry declared at the top of the test, which made this a little confusing to read.

        for (const auto& dir_entry : fs::directory_iterator(banlist_path.parent_path())) {
            const std::string name{fs::PathToString(dir_entry.path().filename())};
In commit "util: atomically write banlist.json and settings.json" (ed55f14404baabc9eaff68d25e50e167a2fafc8f) Nit: `entry` here shadows the `CBanEntry entry` declared at the top of the test, which made this a little confusing to read. ```suggestion for (const auto& dir_entry : fs::directory_iterator(banlist_path.parent_path())) { const std::string name{fs::PathToString(dir_entry.path().filename())}; ```
sedited commented 2026-11-12 13:20:46 +00:00 (Migrated from github.com)

@kevkevinpal do you want to take ryanofsky's suggestions?

@kevkevinpal do you want to take ryanofsky's suggestions?
kevkevinpal commented 2026-11-12 14:01:58 +00:00 (Migrated from github.com)

ryanofsky

Yes, this completely slipped my mind. Will address it right now

> ryanofsky Yes, this completely slipped my mind. Will address it right now
kevkevinpal (Migrated from github.com) reviewed 2026-11-12 17:45:19 +00:00
kevkevinpal (Migrated from github.com) commented 2026-11-12 17:45:19 +00:00

Thanks, this is now addressed in 4a0f4916f6

Thanks, this is now addressed in 4a0f4916f60d31ec38afea3c141e7c8f53ffa46b
kevkevinpal (Migrated from github.com) reviewed 2026-11-12 17:45:20 +00:00
Lines 52-56
kevkevinpal (Migrated from github.com) commented 2026-11-12 17:45:20 +00:00

Thanks, this is now addressed in 9f2077dc09

Thanks, this is now addressed in 9f2077dc09c98e093e15c605ef292669ef409f1d
kevkevinpal (Migrated from github.com) reviewed 2026-11-12 17:45:22 +00:00
Lines 151-157
kevkevinpal (Migrated from github.com) commented 2026-11-12 17:45:22 +00:00

Thanks, this is now addressed in 9f2077dc09

Thanks, this is now addressed in 9f2077dc09c98e093e15c605ef292669ef409f1d
kevkevinpal (Migrated from github.com) reviewed 2026-11-12 17:45:24 +00:00
kevkevinpal (Migrated from github.com) commented 2026-11-12 17:45:24 +00:00

Thanks, this is now addressed in 4a0f4916f6

Thanks, this is now addressed in 4a0f4916f60d31ec38afea3c141e7c8f53ffa46b
winterrdog (Migrated from github.com) reviewed 2026-11-12 22:25:33 +00:00
winterrdog (Migrated from github.com) left a comment

reACK 9f2077dc09

successfully built and tested on FreeBSD 15.0/clang++-19.1.7/x86_64.

generally, the new changes bring in more clarity which is good for future maintenance

reACK 9f2077dc09c98e093e15c605ef292669ef409f1d successfully built and tested on FreeBSD `15.0`/`clang++-19.1.7`/`x86_64`. generally, the new changes bring in more clarity which is good for future maintenance
ryanofsky (Migrated from github.com) approved these changes 2026-11-13 13:37:49 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK 9f2077dc09. banlist.json is now written through a temporary file and RenameOver(), like settings.json, so a crash or full disk during the write can no longer leave it truncated.

Thanks for the updates and the clear commit messages. Remaining comments are minor: the PR title and description still describe the earlier WriteJson version (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563027281), the commits could be simpler, with a minimal fix in the first commit and no second commit (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563653108), and there is a possible follow-up about how a corrupt banlist.json is handled (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011).

Code review ACK 9f2077dc09c98e093e15c605ef292669ef409f1d. `banlist.json` is now written through a temporary file and `RenameOver()`, like `settings.json`, so a crash or full disk during the write can no longer leave it truncated. Thanks for the updates and the clear commit messages. Remaining comments are minor: the PR title and description still describe the earlier `WriteJson` version (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563027281), the commits could be simpler, with a minimal fix in the first commit and no second commit (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563653108), and there is a possible follow-up about how a corrupt `banlist.json` is handled (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011).
Lines 157-172
ryanofsky (Migrated from github.com) commented 2026-11-13 13:19:44 +00:00

In commit "util: write banlist.json through a temporary file" (4a0f4916f6)

The second commit reverts the changes this commit makes to CBanDB::Write, so across the PR addrdb.cpp doesn't change at all. That would seem more reasonable if the change being reverted were minimal, but this commit also restructures the function to return early on failure instead of on success, which the fix doesn't need.

Ideally I'd like to see (1) this commit reduced to a minimal bugfix without the restructuring, something like:

 bool CBanDB::Write(const banmap_t& banSet)
 {
+    const fs::path banlist_tmp{m_banlist_json + ".tmp"};
     std::vector<std::string> errors;
-    if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
-        return true;
+    if (common::WriteSettings(banlist_tmp, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
+        if (RenameOver(banlist_tmp, m_banlist_json)) return true;
+        errors.emplace_back(strprintf("Failed renaming JSON file %s to %s", fs::PathToString(banlist_tmp), fs::PathToString(m_banlist_json)));
     }

and (2) the second commit dropped, which would also match the design I'd prefer (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563641406). But I'm also happy to see this merged as-is, or in any other form that fixes the bug.

In commit "util: write banlist.json through a temporary file" (4a0f4916f60d31ec38afea3c141e7c8f53ffa46b) The second commit [reverts the changes](https://github.com/bitcoin/bitcoin/pull/35763/changes/9f2077dc09c98e093e15c605ef292669ef409f1d#diff-a86c3e4f3b8f46384cbbbc5104be50f5637a030ffeb52a83bd207abeb0e72fab) this commit makes to `CBanDB::Write`, so across the PR `addrdb.cpp` doesn't change at all. That would seem more reasonable if the change being reverted were minimal, but this commit also restructures the function to return early on failure instead of on success, which the fix doesn't need. Ideally I'd like to see (1) this commit reduced to a minimal bugfix without the restructuring, something like: ```diff bool CBanDB::Write(const banmap_t& banSet) { + const fs::path banlist_tmp{m_banlist_json + ".tmp"}; std::vector<std::string> errors; - if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { - return true; + if (common::WriteSettings(banlist_tmp, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { + if (RenameOver(banlist_tmp, m_banlist_json)) return true; + errors.emplace_back(strprintf("Failed renaming JSON file %s to %s", fs::PathToString(banlist_tmp), fs::PathToString(m_banlist_json))); } ``` and (2) the second commit dropped, which would also match the design I'd prefer (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563641406). But I'm also happy to see this merged as-is, or in any other form that fixes the bug.
ryanofsky (Migrated from github.com) commented 2026-11-13 13:09:29 +00:00

In commit "refactor: move .tmp handling into common::WriteSettings" (9f2077dc09)

Note: not for this PR, but a possible follow-up. The PR makes a truncated banlist.json less likely, but the way the truncated file is handled still seems unsafe to me. A truncated settings.json fails to parse and is reported as an error at startup. A truncated banlist.json fails to parse the same way, but CBanDB::Read only logs a warning, and BanMan::LoadBanlist resets to an empty banlist, which the BanMan constructor immediately writes over the corrupt file. So the bans are lost, and the file that would show what happened is gone.

In commit "refactor: move .tmp handling into common::WriteSettings" (9f2077dc09c98e093e15c605ef292669ef409f1d) Note: not for this PR, but a possible follow-up. The PR makes a truncated `banlist.json` less likely, but the way the truncated file is handled still seems unsafe to me. A truncated `settings.json` fails to parse and is [reported as an error](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/common/init.cpp#L100-L104) at startup. A truncated `banlist.json` fails to parse the same way, but `CBanDB::Read` [only logs a warning](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/addrdb.cpp#L168-L173), and [`BanMan::LoadBanlist`](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/banman.cpp#L41-L45) resets to an empty banlist, which the `BanMan` constructor [immediately writes](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/banman.cpp#L20-L21) over the corrupt file. So the bans are lost, and the file that would show what happened is gone.
ryanofsky (Migrated from github.com) commented 2026-11-13 13:08:52 +00:00

re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4484447375

once a write function also manages the temporary file it has to make choices for every caller

A small example of this is error messages. Because WriteSettings is now shared by two kinds of files, this PR changes its errors from "settings file" to "JSON file", which is less clear for settings.json. ReadSettings has the opposite problem: its parse error talks about a settings file and says removing it "will reset settings to default values", which is wrong for banlist.json (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011). This PR doesn't change ReadSettings, so it doesn't make that harder to fix, but in both cases the caller is what knows which file it is (CBanDB::Read already adds "Cannot load banlist" to the message) and what happens if it is removed. I think messages are easier to get right if low-level functions just read and write JSON and callers add the context as I originally suggested https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299. Still not a blocker for me.

re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4484447375 > once a write function also manages the temporary file it has to make choices for every caller A small example of this is error messages. Because `WriteSettings` is now shared by two kinds of files, this PR changes its errors from "settings file" to "JSON file", which is less clear for `settings.json`. `ReadSettings` has the opposite problem: its [parse error](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/common/settings.cpp#L90-L91) talks about a settings file and says removing it "will reset settings to default values", which is wrong for `banlist.json` (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011). This PR doesn't change `ReadSettings`, so it doesn't make that harder to fix, but in both cases the caller is what knows which file it is (`CBanDB::Read` already [adds](https://github.com/bitcoin/bitcoin/blob/9f2077dc09c98e093e15c605ef292669ef409f1d/src/addrdb.cpp#L168-L171) "Cannot load banlist" to the message) and what happens if it is removed. I think messages are easier to get right if low-level functions just read and write JSON and callers add the context as I originally suggested https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299. Still not a blocker for me.
ryanofsky (Migrated from github.com) commented 2026-11-13 12:03:52 +00:00

re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4554141085

The PR title and description also still say WriteJson, and they go into the merge commit, so they should be updated to match too.

Thanks, the two commits are easier to review now. The PR title and description still describe the earlier version though (WriteJson, renaming WriteSettings).

re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4554141085 > The PR title and description also still say `WriteJson`, and they go into the merge commit, so they should be updated to match too. Thanks, the two commits are easier to review now. The PR title and description still describe the earlier version though (`WriteJson`, renaming `WriteSettings`).
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!35763
No description provided.