diff --git a/doc/managing-wallets.md b/doc/managing-wallets.md index ce2bb7327144..1b17a9fd401d 100644 --- a/doc/managing-wallets.md +++ b/doc/managing-wallets.md @@ -106,7 +106,15 @@ This means that a single backup is enough to recover the coins at any time. It i Non-HD wallets must be backed up every 1000 keys used since the previous backup, or even more often to maintain the metadata. -### 1.6 Restoring the Wallet From a Backup +### 1.6 Automatic Backups + +For legacy wallets, Dash Core automatically creates a backup in the `backups` directory inside the data directory on every startup and whenever the keypool is replenished. Each file is named after the wallet with the backup time appended, e.g. `wallet.dat.2026-08-02-14-30`. + +Older backups are pruned as new ones are made. The most recent `-createwalletbackups` backups (default: 10, max: 20) are always kept. Beyond those, at most one backup is kept from each widening age range — 1-2 hours old, 2-4 hours, 4-8 hours, and so on, each range twice as long as the one before (512-1024 hours is about 3-6 weeks) — up to `-maxwalletbackups` files in total (default: 30); if that cap is reached, the most recent ranges are the ones kept. This preserves restore points going back months, even for a wallet that writes many backups a day while mixing, while keeping the size of the `backups` directory predictable. Several backups made within the same hour do not each get their own range: beyond the most recent `-createwalletbackups`, only the oldest backup in each range is kept. The backup just written is never pruned, and if the system clock has been set back, backups dated later than it are left untouched until the clock catches up with them. A clock set far forward makes all existing backups look old at once, so those beyond the most recent `-createwalletbackups` can collapse into one or two ranges. + +Setting either option to `0` disables automatic backups, in which case existing backups are left untouched. Renaming a backup also excludes it from pruning, which is a simple way to keep one indefinitely. + +### 1.7 Restoring the Wallet From a Backup To restore a wallet, the `restorewallet` RPC or the `Restore Wallet` GUI menu item (`File` -> `Restore Wallet…`) must be used. diff --git a/doc/release-notes-7005.md b/doc/release-notes-7005.md new file mode 100644 index 000000000000..b3e166a704a2 --- /dev/null +++ b/doc/release-notes-7005.md @@ -0,0 +1,21 @@ +Wallet +------ + +- Automatic wallet backups now keep older restore points instead of only + the most recent ones. The newest `-createwalletbackups` backups are + still always kept (default: 10; the maximum is raised from 10 to 20). + Beyond those, at most one backup is kept from each exponentially + widening age range (1-2 hours old, 2-4 hours, 4-8 hours, and so on), up + to a total of `-maxwalletbackups` files (default: 30). By default this keeps up + to 30 files per wallet instead of 10; set `-maxwalletbackups=10` to + keep the previous footprint. A backup's age is read from the timestamp + in its filename, so a renamed backup is never pruned. See section 1.6 + of `doc/managing-wallets.md` for details. (#7005) + +Updated settings +---------------- + +- New option `-maxwalletbackups=` sets the maximum total number of + automatic wallet backups to keep (default: 30). `0` disables automatic + backups, as does `-createwalletbackups=0`; existing backups are left + untouched while automatic backups are disabled. (#7005) diff --git a/src/common/system.cpp b/src/common/system.cpp index f718d27501d1..d237a975420c 100644 --- a/src/common/system.cpp +++ b/src/common/system.cpp @@ -34,7 +34,7 @@ const std::string gCoinJoinName = "CoinJoin"; /** nWalletBackups: - 1..10 - number of automatic backups to keep + 1..20 - number of most recent automatic backups to keep 0 - disabled by command-line -1 - disabled because of some error during run-time -2 - disabled because wallet was locked and we were not able to replenish keypool diff --git a/src/dummywallet.cpp b/src/dummywallet.cpp index d02cf96adbe0..e0a88804a2f0 100644 --- a/src/dummywallet.cpp +++ b/src/dummywallet.cpp @@ -50,6 +50,7 @@ void DummyWalletInit::AddWalletOptions(ArgsManager& argsman) const "-keypool=", "-maxapsfee=", "-maxtxfee=", + "-maxwalletbackups=", "-signer=", "-spendzeroconfchange", "-wallet=", diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp index bee31c7e1788..46fd7930673a 100644 --- a/src/wallet/init.cpp +++ b/src/wallet/init.cpp @@ -63,7 +63,8 @@ void WalletInit::AddWalletOptions(ArgsManager& argsman) const { argsman.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting many (possibly all) or none, instead of selecting on a per-output basis. Privacy is improved as addresses are mostly swept with fewer transactions and outputs are aggregated in clean change addresses. It may result in higher fees due to less optimal coin selection caused by this added limitation and possibly a larger-than-necessary number of inputs being used. Always enabled for wallets with \"avoid_reuse\" enabled, otherwise default: %u.", DEFAULT_AVOIDPARTIALSPENDS), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); argsman.AddArg("-consolidatefeerate=", strprintf("The maximum feerate (in %s/kvB) at which transaction building may use more inputs than strictly necessary so that the wallet's UTXO pool can be reduced (default: %s).", CURRENCY_UNIT, FormatMoney(DEFAULT_CONSOLIDATE_FEERATE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); - argsman.AddArg("-createwalletbackups=", strprintf("Number of automatic wallet backups (default: %u)", nWalletBackups), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); + argsman.AddArg("-createwalletbackups=", strprintf("Number of most recent automatic wallet backups to keep, 0 to disable (default: %u, max: %u). Older backups are additionally kept at exponentially spaced intervals, see doc/managing-wallets.md.", DEFAULT_N_WALLET_BACKUPS, MAX_N_WALLET_BACKUPS), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); + argsman.AddArg("-maxwalletbackups=", strprintf("Maximum total number of automatic wallet backups to keep, 0 to disable (default: %u)", DEFAULT_MAX_WALLET_BACKUPS), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); argsman.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); #if HAVE_SYSTEM argsman.AddArg("-instantsendnotify=", "Execute command when a wallet InstantSend transaction is successfully locked. %s in cmd is replaced by TxID and %w is replaced by wallet name. %w is not currently implemented on Windows. On systems where %w is supported, it should NOT be quoted because this would break shell escaping used to invoke the command.", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); @@ -226,7 +227,7 @@ void WalletInit::InitCoinJoinSettings(CCoinJoinClientManager& mgr) const void WalletInit::InitAutoBackup() const { - CWallet::InitAutoBackup(); + CWallet::InitAutoBackup(gArgs); } } // namespace wallet diff --git a/src/wallet/test/CMakeLists.txt b/src/wallet/test/CMakeLists.txt index 44a9f471ddaf..67e56d638e5c 100644 --- a/src/wallet/test/CMakeLists.txt +++ b/src/wallet/test/CMakeLists.txt @@ -8,6 +8,7 @@ target_sources(test_bitcoin PRIVATE init_test_fixture.cpp wallet_test_fixture.cpp + backup_tests.cpp bip39_tests.cpp coinjoin_tests.cpp coinselector_tests.cpp diff --git a/src/wallet/test/backup_tests.cpp b/src/wallet/test/backup_tests.cpp new file mode 100644 index 000000000000..c15ec96eb7af --- /dev/null +++ b/src/wallet/test/backup_tests.cpp @@ -0,0 +1,214 @@ +// Copyright (c) 2026 The Dash Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace wallet { + +namespace { +using BackupTime = std::chrono::system_clock::time_point; +using Backups = std::multimap; + +//! Fixtures are anchored on a fixed date so that age-range boundaries are exact +//! rather than dependent on when the test happens to run. +constexpr std::chrono::sys_days BACKUP_ANCHOR{std::chrono::year{2026} / 8 / 4}; + +//! Filename AutoBackupWallet() writes for a backup taken at `time`. +fs::path BackupPath(BackupTime time) +{ + return fs::u8path("wallet.dat" + FormatBackupFileTime(std::chrono::floor(time))); +} + +//! A backup taken `days_ago` days before the anchor; `minute` tells apart several taken that day. +Backups::value_type Backup(int days_ago, int minute = 0) +{ + const BackupTime time{BACKUP_ANCHOR - std::chrono::days{days_ago} + std::chrono::minutes{minute}}; + return {time, BackupPath(time)}; +} + +Backups DailyBackups(int count) +{ + Backups backups; + for (int i = 0; i < count; ++i) + backups.insert(Backup(i)); + return backups; +} + +std::set Paths(const Backups& backups) +{ + std::set paths; + for (const auto& [time, path] : backups) + paths.insert(path); + return paths; +} + +//! Names of the backups that survive pruning with `backup_time` as the backup just written. +std::set Kept(const Backups& backups, BackupTime backup_time, int keep_recent, int max_backups) +{ + std::set kept{Paths(backups)}; + for (const auto& path : GetBackupsToDelete(backups, backup_time, keep_recent, max_backups)) { + BOOST_CHECK_EQUAL(kept.erase(path), 1U); + } + return kept; +} +} // namespace + +BOOST_FIXTURE_TEST_SUITE(backup_tests, BasicTestingSetup) + +BOOST_AUTO_TEST_CASE(retention_by_count_and_age) +{ + // Nothing is deleted while the count window isn't full. + BOOST_CHECK(GetBackupsToDelete(DailyBackups(10), BACKUP_ANCHOR, 10, 50).empty()); + + // Backups less than an hour older than the newest fall in no age range, so beyond + // the count window they are dropped. + Backups backups; + for (int minute = 0; minute < 11; ++minute) + backups.insert(Backup(0, minute)); + auto expected{Paths(backups)}; + expected.erase(Backup(0, 0).second); + BOOST_CHECK(Kept(backups, backups.rbegin()->first, 10, 50) == expected); + + // 100 daily backups: the last 10 by count, then days 10, 21, 42, 85 and 99 as the + // oldest in [128,256), [256,512), [512,1024), [1024,2048) and [2048,4096) hours. + backups = DailyBackups(100); + expected = Paths({Backup(0), Backup(1), Backup(2), Backup(3), Backup(4), Backup(5), Backup(6), Backup(7), Backup(8), + Backup(9), Backup(10), Backup(21), Backup(42), Backup(85), Backup(99)}); + BOOST_CHECK(Kept(backups, BACKUP_ANCHOR, 10, 50) == expected); + + // -maxwalletbackups below that drops the widest ranges first, and equal to the count + // window degrades to keeping the most recent backups only. + expected.erase(Backup(42).second); + expected.erase(Backup(85).second); + expected.erase(Backup(99).second); + BOOST_CHECK(Kept(backups, BACKUP_ANCHOR, 10, 12) == expected); + BOOST_CHECK(Kept(backups, BACKUP_ANCHOR, 10, 10) == Paths(DailyBackups(10))); + + // The count window is positional: after 60 idle days the new backup pushes out only + // one of the old ones, and of the rest the oldest stays for the [1024,2048) hour range. + backups.clear(); + for (int minute = 0; minute < 15; ++minute) + backups.insert(Backup(60, minute)); + backups.insert(Backup(0)); + expected = Paths({Backup(0), Backup(60, 0)}); + for (int minute = 6; minute < 15; ++minute) + expected.insert(Backup(60, minute).second); + BOOST_CHECK(Kept(backups, BACKUP_ANCHOR, 10, 50) == expected); + + // Disabled (0) or failed (negative) automatic backups delete nothing. + for (int keep_recent : {0, -1, -2}) { + BOOST_CHECK(GetBackupsToDelete(backups, BACKUP_ANCHOR, keep_recent, 30).empty()); + } + BOOST_CHECK(GetBackupsToDelete(backups, BACKUP_ANCHOR, 10, 0).empty()); +} + +BOOST_AUTO_TEST_CASE(clock_moved_backward) +{ + // 40 daily backups written with a correct clock, then the clock jumps back 20 days + // and a new backup is written half an hour after the existing day-20 one. + Backups backups{DailyBackups(40)}; + const auto just_written{Backup(20, 30)}; + backups.insert(just_written); + + // Ranked by filename time alone, the new backup would fall behind the 20 later-dated + // files, out of the count window, and be deleted as a non-oldest member of its range. + // Instead those 20 are left alone and the rest is pruned as if the new backup were the + // newest: it and days 20-28 fill the count window, and days 30 and 39 are the oldest + // in the [128,256) and [256,512) hour ranges before it. + auto expected{Paths(backups)}; + for (int day : {29, 31, 32, 33, 34, 35, 36, 37, 38}) + expected.erase(Backup(day).second); + BOOST_CHECK(Kept(backups, just_written.first, 10, 50) == expected); +} + +BOOST_AUTO_TEST_CASE(frequent_backups_keep_history) +{ + // A wallet that mixes all day can write more backups a day than the count window + // holds. Replay the pruning AutoBackupWallet() does after each backup over 60 days of + // one backup every 72 minutes (20 a day). + Backups backups; + const BackupTime first_backup{BACKUP_ANCHOR - std::chrono::days{60}}; + auto backup_time{first_backup}; + for (int i = 0; i < 20 * 60; ++i, backup_time += std::chrono::minutes{72}) { + backups.insert({backup_time, BackupPath(backup_time)}); + for (const auto& path : GetBackupsToDelete(backups, backup_time, 10, 30)) { + std::erase_if(backups, [&](const auto& entry) { return entry.second == path; }); + } + BOOST_REQUIRE_LE(backups.size(), 30U); + } + + // Restore points older than the last 10 backups (12 hours) survive, back to the first. + const auto newest{backups.rbegin()->first}; + const auto older_than{[&](std::chrono::hours age) { + return std::count_if(backups.begin(), backups.end(), + [&](const auto& entry) { return newest - entry.first >= age; }); + }}; + BOOST_CHECK_GE(older_than(std::chrono::days{1}), 4); + BOOST_CHECK_GE(older_than(std::chrono::days{7}), 3); + BOOST_CHECK(backups.begin()->first == first_backup); +} + +BOOST_AUTO_TEST_CASE(init_auto_backup_clamping) +{ + const int orig_backups{nWalletBackups}; + const int orig_max_backups{CWallet::nMaxWalletBackups}; + + const auto check{[](const std::vector& argv, int expected_backups, int expected_max_backups) { + ArgsManager args; + args.AddArg("-createwalletbackups=", "", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); + args.AddArg("-maxwalletbackups=", "", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET); + std::vector argv_full{"ignored"}; + argv_full.insert(argv_full.end(), argv.begin(), argv.end()); + std::string error; + BOOST_REQUIRE(args.ParseParameters(argv_full.size(), argv_full.data(), error)); + CWallet::InitAutoBackup(args); + BOOST_CHECK_EQUAL(nWalletBackups, expected_backups); + BOOST_CHECK_EQUAL(CWallet::nMaxWalletBackups, expected_max_backups); + }}; + + check({}, DEFAULT_N_WALLET_BACKUPS, DEFAULT_MAX_WALLET_BACKUPS); + check({"-createwalletbackups=100"}, MAX_N_WALLET_BACKUPS, DEFAULT_MAX_WALLET_BACKUPS); + check({"-createwalletbackups=-5"}, 0, DEFAULT_MAX_WALLET_BACKUPS); + check({"-createwalletbackups=15", "-maxwalletbackups=12"}, 12, 12); + check({"-maxwalletbackups=0"}, 0, 0); + check({"-maxwalletbackups=-1"}, 0, 0); + + nWalletBackups = orig_backups; + CWallet::nMaxWalletBackups = orig_max_backups; +} + +BOOST_AUTO_TEST_CASE(parse_backup_file_time) +{ + using namespace std::chrono; + + const auto parsed{ParseBackupFileTime(fs::u8path("wallet.dat.2026-08-02-14-30"))}; + BOOST_REQUIRE(parsed.has_value()); + const sys_seconds time{sys_days{year{2026} / 8 / 2} + hours{14} + minutes{30}}; + BOOST_CHECK(*parsed == time); + // What AutoBackupWallet() writes, seconds dropped, is what the parser accepts. + BOOST_CHECK_EQUAL(FormatBackupFileTime(time + seconds{59}), ".2026-08-02-14-30"); + + for (const char* name : {"wallet.dat", "wallet.dat.bak", "wallet.dat.2026-08-02", "wallet.dat.2026-08-02-14-3x", + "wallet.dat.2026-13-02-14-30", "wallet.dat.2026-02-30-14-30", "wallet.dat.2026-08-02-24-30", + "wallet.dat.2026-08-02-14-60", "wallet.dat.2500-01-01-00-00"}) { + BOOST_CHECK_MESSAGE(!ParseBackupFileTime(fs::u8path(name)).has_value(), name); + } +} + +BOOST_AUTO_TEST_SUITE_END() + +} // namespace wallet diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 18719bce0f55..fe6a96d62d47 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -88,11 +88,11 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -113,6 +113,8 @@ static isminetype InputIsMine(const CWallet& wallet, const CTxIn& txin) EXCLUSIV return ISMINE_NO; } +int CWallet::nMaxWalletBackups = DEFAULT_MAX_WALLET_BACKUPS; + bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name) { common::SettingsValue setting_value = chain.getRwSetting("wallet"); @@ -3911,13 +3913,87 @@ void CWallet::postInitProcess() WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this)); } -void CWallet::InitAutoBackup() +std::vector GetBackupsToDelete(const std::multimap& backups, + std::chrono::system_clock::time_point backup_time, int keep_recent, + int max_backups) { - if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) + if (keep_recent <= 0 || max_backups <= 0) return {}; + const auto recent{static_cast(keep_recent)}; + + // Newest first, skipping backups dated after the one just written. + const std::vector> candidates( + std::make_reverse_iterator(backups.upper_bound(backup_time)), backups.rend()); + if (candidates.size() <= recent) return {}; + const auto newest{candidates[0].first}; + + // std::bit_width() maps an age in hours onto its range, and the last entry seen in a + // range is its oldest. Ranges start at an hour rather than a day so that a wallet + // writing more backups a day than the count window holds still carries some past a day. + std::map oldest_per_range; + for (size_t i = recent; i < candidates.size(); ++i) { + const auto age_hours{std::chrono::duration_cast(newest - candidates[i].first).count()}; + if (age_hours < 1) continue; + oldest_per_range[std::bit_width(static_cast(age_hours))] = i; + } + // If the cap leaves room for fewer ranges than are populated, keep the most recent ones. + const auto max_ranges{static_cast(std::max(max_backups - keep_recent, 0))}; + std::set keep; + for (const auto& [range, index] : oldest_per_range) { + if (keep.size() >= max_ranges) break; + keep.insert(index); + } + + std::vector to_delete; + for (size_t i = recent; i < candidates.size(); ++i) { + if (!keep.contains(i)) to_delete.push_back(candidates[i].second); + } + return to_delete; +} + +std::string FormatBackupFileTime(std::chrono::sys_seconds time) +{ + const auto days{std::chrono::floor(time)}; + const std::chrono::year_month_day ymd{days}; + const std::chrono::hh_mm_ss hms{time - days}; + return strprintf(".%04i-%02u-%02u-%02i-%02i", signed{ymd.year()}, unsigned{ymd.month()}, unsigned{ymd.day()}, hms.hours().count(), hms.minutes().count()); +} + +std::optional ParseBackupFileTime(const fs::path& backup_file) +{ + const std::string ext{fs::PathToString(backup_file.extension())}; + if (ext.size() != 17 || ext[0] != '.' || ext[5] != '-' || ext[8] != '-' || ext[11] != '-' || ext[14] != '-') { + return std::nullopt; + } + const auto to_int = [&ext](size_t pos, size_t len) -> std::optional { + int value{0}; + for (size_t i = pos; i < pos + len; ++i) { + if (!IsDigit(ext[i])) return std::nullopt; + value = value * 10 + (ext[i] - '0'); + } + return value; + }; + const auto year{to_int(1, 4)}, month{to_int(6, 2)}, day{to_int(9, 2)}, hour{to_int(12, 2)}, minute{to_int(15, 2)}; + if (!year || !month || !day || !hour || !minute) return std::nullopt; + // Bound the year so the time_point and differences between backup times stay representable. + if (*year < 1970 || *year > 2200 || *hour > 23 || *minute > 59) return std::nullopt; + const std::chrono::year_month_day ymd{std::chrono::year{*year}, std::chrono::month{static_cast(*month)}, + std::chrono::day{static_cast(*day)}}; + if (!ymd.ok()) return std::nullopt; + return std::chrono::sys_days{ymd} + std::chrono::hours{*hour} + std::chrono::minutes{*minute}; +} + +void CWallet::InitAutoBackup(const ArgsManager& args) +{ + if (args.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) return; - nWalletBackups = gArgs.GetIntArg("-createwalletbackups", 10); - nWalletBackups = std::max(0, std::min(10, nWalletBackups)); + nWalletBackups = args.GetIntArg("-createwalletbackups", DEFAULT_N_WALLET_BACKUPS); + nWalletBackups = std::max(0, std::min(MAX_N_WALLET_BACKUPS, nWalletBackups)); + + nMaxWalletBackups = args.GetIntArg("-maxwalletbackups", DEFAULT_MAX_WALLET_BACKUPS); + nMaxWalletBackups = std::max(0, nMaxWalletBackups); + + nWalletBackups = std::min(nWalletBackups, nMaxWalletBackups); } bool CWallet::BackupWallet(const std::string& strDest) const @@ -3980,13 +4056,8 @@ bool CWallet::AutoBackupWallet(const fs::path& wallet_path, bilingual_str& error } // Create backup of the ... - std::string dateTimeStr = [&]() { - const std::chrono::sys_seconds secs{GetTime()}; - const auto days{std::chrono::floor(secs)}; - const std::chrono::year_month_day ymd{days}; - const std::chrono::hh_mm_ss hms{secs - days}; - return strprintf(".%04i-%02u-%02u-%02i-%02i", signed{ymd.year()}, unsigned{ymd.month()}, unsigned{ymd.day()}, hms.hours().count(), hms.minutes().count()); - }(); + const std::chrono::sys_seconds secs{GetTime()}; + const std::string dateTimeStr{FormatBackupFileTime(secs)}; if (wallet_path.empty()) { // ... opened wallet @@ -4036,35 +4107,29 @@ bool CWallet::AutoBackupWallet(const fs::path& wallet_path, bilingual_str& error } } - // Keep only the last 10 backups, including the new one of course - std::multimap folder_set; - // Build map of backup files for current(!) wallet sorted by last write time - fs::path currentFile; + // Age comes from the timestamp in each filename rather than the filesystem mtime, which + // isn't preserved by all filesystems, cloud-sync tools or cross-device copies. + std::multimap folder_set; for (const auto& entry : fs::directory_iterator(backupsDir)) { // Only check regular files - if (entry.is_regular_file()) { - currentFile = entry.path().filename(); - // Only add the backups for the current wallet, e.g. wallet.dat.* - if (fs::PathToString(entry.path().stem()) == strWalletName) { - folder_set.insert(decltype(folder_set)::value_type(fs::last_write_time(entry.path()), entry)); - } - } - } - - // Loop backward through backup files and keep the N newest ones (1 <= N <= 10) - int counter{0}; - for (const auto& [entry_time, entry] : folder_set | std::views::reverse) { - counter++; - if (counter > nWalletBackups) { - // More than nWalletBackups backups: delete oldest one(s) - try { - fs::remove(entry); - WalletLogPrintf("Old backup deleted: %s\n", fs::PathToString(entry)); - } catch(fs::filesystem_error &error) { - warnings.push_back(strprintf(_("Failed to delete backup, error: %s"), fsbridge::get_filesystem_error_message(error))); - WalletLogPrintf("%s\n", Join(warnings, Untranslated("\n")).original); - return false; - } + if (!entry.is_regular_file()) continue; + // Only add the backups for the current wallet, e.g. wallet.dat.* + if (fs::PathToString(entry.path().stem()) != strWalletName) continue; + if (const auto backup_time{ParseBackupFileTime(entry.path())}) { + folder_set.insert({*backup_time, entry.path()}); + } + } + + // The filename only carries minutes, so compare at that precision. + for (const auto& path : GetBackupsToDelete(folder_set, std::chrono::floor(secs), + nWalletBackups, nMaxWalletBackups)) { + try { + fs::remove(path); + WalletLogPrintf("Old backup deleted: %s\n", fs::PathToString(path)); + } catch(fs::filesystem_error &error) { + warnings.push_back(strprintf(_("Failed to delete backup, error: %s"), fsbridge::get_filesystem_error_message(error))); + WalletLogPrintf("%s\n", Join(warnings, Untranslated("\n")).original); + return false; } } @@ -4487,7 +4552,7 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnl if(nWalletBackups == -2) { TopUpKeyPool(); WalletLogPrintf("Keypool replenished, re-initializing automatic backups.\n"); - nWalletBackups = gArgs.GetIntArg("-createwalletbackups", 10); + InitAutoBackup(gArgs); } return true; } diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index b6fb1df9ca35..917730e4a57a 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -61,6 +62,7 @@ #include +class ArgsManager; class CKey; class CKeyID; class CPubKey; @@ -115,6 +117,36 @@ void NotifyWalletLoading(WalletContext& context, const std::shared_ptr& void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr& wallet); std::unique_ptr MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error); +//! Wallet backup configuration defaults +static constexpr int DEFAULT_MAX_WALLET_BACKUPS = 30; +static constexpr int DEFAULT_N_WALLET_BACKUPS = 10; +static constexpr int MAX_N_WALLET_BACKUPS = 20; + +/** + * Pick which automatic backups to delete: keeps the newest keep_recent by count, plus the + * oldest backup in each exponential age range in hours relative to the newest backup + * ([1,2), [2,4), [4,8), ...), for at most max_backups files in total; if that cap binds, + * the most recent ranges win. Deletes nothing if either limit is not positive, which is + * how the global nWalletBackups reports disabled or failed backups. + * + * backup_time is when the backup that triggered pruning was written. Backups dated after + * it, which only a clock that moved backward can produce, are never deleted and take no + * part in retention, so the backup just written is always the newest one and is kept. + */ +std::vector GetBackupsToDelete(const std::multimap& backups, + std::chrono::system_clock::time_point backup_time, int keep_recent, + int max_backups); + +//! Suffix AutoBackupWallet() appends to a backup's filename: ".YYYY-MM-DD-HH-MM" in UTC. +std::string FormatBackupFileTime(std::chrono::sys_seconds time); + +/** + * Read back the timestamp from a backup filename (e.g. "wallet.dat.2026-08-02-14-30"), or + * std::nullopt if the name isn't in that format, which is also how retention tells its + * own files apart from anything else in the backups directory. + */ +std::optional ParseBackupFileTime(const fs::path& backup_file); + //! -paytxfee default constexpr CAmount DEFAULT_PAY_TX_FEE = 0; //! -fallbackfee default @@ -625,6 +657,8 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati std::set setLockedCoins GUARDED_BY(cs_wallet); int64_t nKeysLeftSinceAutoBackup; + //! -maxwalletbackups; process-wide like the nWalletBackups global it caps. + static int nMaxWalletBackups; /** Registered interfaces::Chain::Notifications handler. */ std::unique_ptr m_chain_notifications_handler; @@ -1106,7 +1140,7 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati void postInitProcess(); /* AutoBackup functionality */ - static void InitAutoBackup(); + static void InitAutoBackup(const ArgsManager& args); bool AutoBackupWallet(const fs::path& wallet_path, bilingual_str& error_string, std::vector& warnings); bool BackupWallet(const std::string& strDest) const; diff --git a/test/util/data/non-backported.txt b/test/util/data/non-backported.txt index 24212bbd2fe1..162ec1bd85c2 100644 --- a/test/util/data/non-backported.txt +++ b/test/util/data/non-backported.txt @@ -112,5 +112,6 @@ src/wallet/coinjoin.* src/wallet/hdchain.* src/wallet/platformkeys.* src/wallet/platformtypes.h +src/wallet/test/backup_tests.cpp src/wallet/test/platformkeys_tests.cpp src/hash_x11.h