Skip to content

util: write JSON atomically in WriteJson - #35763

Open
kevkevinpal wants to merge 2 commits into
bitcoin:masterfrom
kevkevinpal:banlist-atomic-write-json-unsafe
Open

kevkevinpal wants to merge 2 commits into
bitcoin:masterfrom
kevkevinpal:banlist-atomic-write-json-unsafe

Conversation

@kevkevinpal

@kevkevinpal kevkevinpal commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #35384 (comment)

  • 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

DrahtBot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

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.

@winterrdog

winterrdog commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Concept ACK

Thanks for picking these up.

cc: @sys-dev @ryanofsky

@Herb-ops

Copy link
Copy Markdown

ACK 07ec5af, 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

winterrdog commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

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

winterrdog commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

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 ?

@kevkevinpal
kevkevinpal force-pushed the banlist-atomic-write-json-unsafe branch from 07ec5af to e524b77 Compare August 2, 2026 22:12
@kevkevinpal
kevkevinpal force-pushed the banlist-atomic-write-json-unsafe branch from e524b77 to 0e67947 Compare September 7, 2026 14:24
@kevkevinpal

Copy link
Copy Markdown
Contributor Author

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

@winterrdog winterrdog left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/common/settings.cpp Resolved
@kevkevinpal kevkevinpal changed the title util: atomically write banlist.json and rename WriteSettings to WriteJsonUnsafe util: write JSON atomically in WriteJson Sep 7, 2026
@kevkevinpal
kevkevinpal force-pushed the banlist-atomic-write-json-unsafe branch from 0e67947 to 0260a68 Compare September 7, 2026 21:26
Comment thread src/common/settings.cpp Resolved
Comment thread src/common/settings.cpp Resolved

@winterrdog winterrdog left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK ed55f14

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

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/common/settings.h Resolved
Comment thread src/common/settings.h Resolved
Comment thread src/addrdb.cpp Resolved
Comment thread src/test/banman_tests.cpp Resolved
Comment thread src/common/settings.cpp
for (const auto& value : values) {
out.pushKVEnd(value.first, value.second);
}
const fs::path path_tmp{path + ".tmp"};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

This ended up different from what I suggested in #35384 (comment), 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #35763 (comment)

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 (#35763 (comment)). 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 #35384 (comment). Still not a blocker for me.

@sedited

sedited commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

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

@kevkevinpal

Copy link
Copy Markdown
Contributor Author

ryanofsky

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

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() writes settings.json.tmp and renames
it over settings.json.

Write banlist.json the same way: write banlist.json.tmp and use
RenameOver() to replace banlist.json. 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.
Both callers of common::WriteSettings(), ArgsManager::WriteSettingsFile()
for settings.json and CBanDB::Write() for banlist.json, now write a .tmp
file and use RenameOver() to replace the destination. Move that step
into WriteSettings() itself, remove it from both callers, and drop the
now unused temp parameter of ArgsManager::GetSettingsPath().

There is no behavior change, except that write errors for settings.json
now say "JSON file" instead of "settings file".
@kevkevinpal
kevkevinpal force-pushed the banlist-atomic-write-json-unsafe branch from ed55f14 to 9f2077d Compare November 12, 2026 14:37

@winterrdog winterrdog left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reACK 9f2077d

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

@DrahtBot
DrahtBot requested a review from ryanofsky November 12, 2026 22:25

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review ACK 9f2077d. 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 and can be ignored: the PR title and description still describe the earlier WriteJson version (#35763 (comment)), the commits could be simpler, with a minimal fix in the first commit and no second commit (#35763 (comment)), and there is a possible follow-up about how a corrupt banlist.json is handled (#35763 (comment)).

Comment thread src/common/settings.h Resolved
Comment thread src/common/settings.cpp
for (const auto& value : values) {
out.pushKVEnd(value.first, value.second);
}
const fs::path path_tmp{path + ".tmp"};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #35763 (comment)

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 (#35763 (comment)). 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 #35384 (comment). Still not a blocker for me.

Comment thread src/common/settings.cpp
Comment on lines 90 to 91
errors.emplace_back(strprintf("Settings file %s does not contain valid JSON. This may be caused by a crash, power loss, full disk, or storage error, "
"and can be fixed by removing the file, which will reset settings to default values.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

Comment thread src/addrdb.cpp
Comment on lines 142 to 157
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)) {
for (const auto& err : errors) {
LogError("%s\n", err);
}
return false;
}

for (const auto& err : errors) {
LogError("%s\n", err);
if (!RenameOver(banlist_tmp, m_banlist_json)) {
LogError("Failed renaming JSON file %s to %s\n", fs::PathToString(banlist_tmp), fs::PathToString(m_banlist_json));
return false;
}
return false;
return true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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 (#35763 (comment)). But I'm also happy to see this merged as-is, or in any other form that fixes the bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants