Merge bitcoin/bitcoin#35492: wallet: fail dump on incomplete writes
What changed, and why it matters
This change fixes a bug in the `bitcoin-wallet dump` command. Previously, if writing the dump file failed partway through (for example, because the disk was full), the tool could still report success and leave behind an incomplete, misleading file. Now the tool checks every write and close operation, reports failure, and deletes the partial file. This is a reliability and data-integrity improvement rather than a remote attack vector.
Treat as a low-severity reliability/data-integrity fix. Backport to maintained branches if wallet dump integrity is considered important. No urgent deployment required for security reasons, but users relying on `bitcoin-wallet dump` for backups benefit from the corrected failure handling.
Security signals we found
Incomplete/truncated wallet dump could be mistaken for a complete backup, leading to data loss or incorrect wallet recovery
Tool previously returned success despite write failures, violating fail-safe expectations for sensitive key material
Patch removes the partial dump file on failure, preventing misleading artifacts
New functional test uses RLIMIT_FSIZE to verify failure path and cleanup
Evidence from the diff
DumpWallet() in src/wallet/dump.cpp previously used std::ofstream and only checked open() success. It did not verify that subsequent writes or close() succeeded, so a full disk, I/O error, or other write failure could produce a truncated dump while the tool returned true and printed the private-key warning. The patch replaces std::ofstream with AutoFile (which throws on write failure and provides Commit()/fclose()), wraps the dump logic in a try/catch, calls Commit() and fclose(), removes the partial file on any failure, and adds a functional test that enforces a 512-byte file-size limit to simulate an incomplete write.
Changed components
src/wallet/dump.cpptest/functional/tool_wallet.pybitcoin-wallet CLI tool (dump subcommand)Inspect captured patch +73 / −43
### src/wallet/dump.cpp
@@ -5,7 +5,9 @@
#include <wallet/dump.h>
#include <common/args.h>
+#include <streams.h>
#include <util/fs.h>
+#include <util/fs_helpers.h>
#include <util/translation.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
@@ -36,9 +38,8 @@ bool DumpWallet(const ArgsManager& args, WalletDatabase& db, bilingual_str& erro
error = strprintf(_("File %s already exists. If you are sure this is what you want, move it out of the way first."), fs::PathToString(path));
return false;
}
- std::ofstream dump_file;
- dump_file.open(path.std_path());
- if (dump_file.fail()) {
+ AutoFile dump_file{fsbridge::fopen(path, "w")};
+ if (dump_file.IsNull()) {
error = strprintf(_("Unable to open %s for writing"), fs::PathToString(path));
return false;
}
@@ -47,66 +48,78 @@ bool DumpWallet(const ArgsManager& args, WalletDatabase& db, bilingual_str& erro
std::unique_ptr<DatabaseBatch> batch = db.MakeBatch();
- bool ret = true;
- std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
- if (!cursor) {
- error = _("Error: Couldn't create cursor into database");
- ret = false;
- }
+ struct DumpWalletError {
+ bilingual_str message;
+ };
+ auto throw_error = [](bilingual_str message) {
+ throw DumpWalletError{std::move(message)};
+ };
+ auto throw_write_error = [&] {
+ throw_error(strprintf(_("Unable to write complete dump file %s."), fs::PathToString(path)));
+ };
+ auto write = [&](const std::string& line) {
+ try {
+ dump_file.write(MakeByteSpan(line));
+ } catch (const std::ios_base::failure&) {
+ throw_write_error();
+ }
+ };
+ auto write_record = [&](const std::string& line) {
+ write(line);
+ hasher << std::span{line};
+ };
+
+ try {
+ std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
+ if (!cursor) {
+ throw_error(_("Error: Couldn't create cursor into database"));
+ }
- // Write out a magic string with version
- std::string line = strprintf("%s,%u\n", DUMP_MAGIC, DUMP_VERSION);
- dump_file.write(line.data(), line.size());
- hasher << std::span{line};
-
- // Write out the file format
- std::string format = db.Format();
- // BDB files that are opened using BerkeleyRODatabase have its format as "bdb_ro"
- // We want to override that format back to "bdb"
- if (format == "bdb_ro") {
- format = "bdb";
- }
- line = strprintf("%s,%s\n", "format", format);
- dump_file.write(line.data(), line.size());
- hasher << std::span{line};
+ // Write out a magic string with version
+ std::string line = strprintf("%s,%u\n", DUMP_MAGIC, DUMP_VERSION);
+ write_record(line);
- if (ret) {
+ // Write out the file format
+ std::string format = db.Format();
+ // BDB files that are opened using BerkeleyRODatabase have its format as "bdb_ro"
+ // We want to override that format back to "bdb"
+ if (format == "bdb_ro") {
+ format = "bdb";
+ }
+ line = strprintf("%s,%s\n", "format", format);
+ write_record(line);
// Read the records
while (true) {
DataStream ss_key{};
DataStream ss_value{};
DatabaseCursor::Status status = cursor->Next(ss_key, ss_value);
if (status == DatabaseCursor::Status::DONE) {
- ret = true;
break;
} else if (status == DatabaseCursor::Status::FAIL) {
- error = _("Error reading next record from wallet database");
- ret = false;
- break;
+ throw_error(_("Error reading next record from wallet database"));
}
std::string key_str = HexStr(ss_key);
std::string value_str = HexStr(ss_value);
line = strprintf("%s,%s\n", key_str, value_str);
- dump_file.write(line.data(), line.size());
- hasher << std::span{line};
+ write_record(line);
}
- }
- cursor.reset();
- batch.reset();
-
- if (ret) {
// Write the hash
- tfm::format(dump_file, "checksum,%s\n", HexStr(hasher.GetHash()));
- dump_file.close();
- } else {
+ line = strprintf("checksum,%s\n", HexStr(hasher.GetHash()));
+ write(line);
+ if (!dump_file.Commit()) throw_write_error();
+ if (dump_file.fclose() != 0) throw_write_error();
+ DirectoryCommit(path.parent_path());
+ } catch (const DumpWalletError& e) {
+ error = e.message;
// Remove the dumpfile on failure
- dump_file.close();
+ (void)dump_file.fclose();
fs::remove(path);
+ return false;
}
- return ret;
+ return true;
}
// The standard wallet deleter function blocks on the validation interface
### test/functional/tool_wallet.py
@@ -29,10 +29,10 @@ def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_wallet_tool()
- def bitcoin_wallet_process(self, *args):
+ def bitcoin_wallet_process(self, *args, **kwargs):
default_args = ['-datadir={}'.format(self.nodes[0].datadir_path), '-chain=%s' % self.chain]
- return subprocess.Popen(self.get_binaries().wallet_argv() + default_args + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ return subprocess.Popen(self.get_binaries().wallet_argv() + default_args + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kwargs)
def assert_raises_tool_error(self, error, *args):
p = self.bitcoin_wallet_process(*args)
@@ -272,6 +272,23 @@ def test_dump_createfromdump(self):
self.log.info('Checking that a dumpfile cannot be overwritten')
self.assert_raises_tool_error('File {} already exists. If you are sure this is what you want, move it out of the way first.'.format(wallet_dump), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'dump')
+ if os.name == 'posix':
+ self.log.info('Checking that incomplete dumps fail and are removed')
+
+ def limit_dump_size():
+ import resource
+ import signal
+ signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
+ resource.setrlimit(resource.RLIMIT_FSIZE, (512, 512))
+
+ limited_dump = self.nodes[0].datadir_path / "wallet-limited.dump"
+ p = self.bitcoin_wallet_process('-wallet=todump', '-dumpfile={}'.format(limited_dump), 'dump', preexec_fn=limit_dump_size)
+ stdout, stderr = p.communicate()
+ assert_equal(stdout, '')
+ assert_equal(p.poll(), 1)
+ assert "Unable to write complete dump file {}.".format(limited_dump) in stderr.strip()
+ assert not limited_dump.exists()
+
self.log.info('Checking createfromdump arguments')
self.assert_raises_tool_error('No dump file provided. To use createfromdump, -dumpfile=<filename> must be provided.', '-wallet=todump', 'createfromdump')
non_exist_dump = self.nodes[0].datadir_path / "wallet.nodump"Why this scored 43/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.