From 9b4f8b4b7ed6a22b9fa6a3b1d10210d21084cb5b Mon Sep 17 00:00:00 2001 From: moneromooo-monero Date: Thu, 17 Dec 2015 22:31:49 +0000 Subject: wallet: save to a temporary file, then rename This should avoid most of wallet cache corruption cases --- src/wallet/wallet2.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src/wallet/wallet2.cpp') diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 5a9b96bb8..8fc07db2c 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -48,6 +48,7 @@ using namespace epee; #include "cryptonote_protocol/blobdatatype.h" #include "mnemonics/electrum-words.h" #include "common/dns_utils.h" +#include "common/util.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" @@ -1283,8 +1284,20 @@ void wallet2::store() std::string buf; bool r = ::serialization::dump_binary(cache_file_data, buf); - r = r && epee::file_io_utils::save_string_to_file(m_wallet_file, buf); THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_wallet_file); + + // save to new file, rename main to old, rename new to main + // at all times, there should be a valid file on disk + const std::string new_file = m_wallet_file + ".new"; + const std::string old_file = m_wallet_file + ".old"; + r = epee::file_io_utils::save_string_to_file(new_file, buf); + THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, new_file); + boost::filesystem::remove(old_file); // probably does not exist + std::error_code e = tools::replace_file(m_wallet_file, old_file); + THROW_WALLET_EXCEPTION_IF(e, error::file_save_error, m_wallet_file, e); + e = tools::replace_file(new_file, m_wallet_file); + THROW_WALLET_EXCEPTION_IF(e, error::file_save_error, m_wallet_file, e); + boost::filesystem::remove(old_file); } //---------------------------------------------------------------------------------------------------- uint64_t wallet2::unlocked_balance() const -- cgit v1.2.3