LCOV - code coverage report
Current view: top level - src/wallet - dump.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 0.0 % 185 0
Test Date: 2026-11-23 06:11:08 Functions: 0.0 % 7 0
Branches: 0.0 % 324 0

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2020-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <wallet/dump.h>
       6                 :             : 
       7                 :             : #include <common/args.h>
       8                 :             : #include <streams.h>
       9                 :             : #include <util/fs.h>
      10                 :             : #include <util/fs_helpers.h>
      11                 :             : #include <util/translation.h>
      12                 :             : #include <wallet/wallet.h>
      13                 :             : #include <wallet/walletdb.h>
      14                 :             : 
      15                 :             : #include <algorithm>
      16                 :             : #include <fstream>
      17                 :             : #include <memory>
      18                 :             : #include <string>
      19                 :             : #include <utility>
      20                 :             : #include <vector>
      21                 :             : 
      22                 :             : namespace wallet {
      23                 :             : static const std::string DUMP_MAGIC = "BITCOIN_CORE_WALLET_DUMP";
      24                 :             : uint32_t DUMP_VERSION = 1;
      25                 :             : 
      26                 :           0 : bool DumpWallet(const ArgsManager& args, WalletDatabase& db, bilingual_str& error)
      27                 :             : {
      28                 :             :     // Get the dumpfile
      29   [ #  #  #  # ]:           0 :     std::string dump_filename = args.GetArg("-dumpfile", "");
      30         [ #  # ]:           0 :     if (dump_filename.empty()) {
      31         [ #  # ]:           0 :         error = _("No dump file provided. To use dump, -dumpfile=<filename> must be provided.");
      32                 :           0 :         return false;
      33                 :             :     }
      34                 :             : 
      35         [ #  # ]:           0 :     fs::path path = fs::PathFromString(dump_filename);
      36         [ #  # ]:           0 :     path = fs::absolute(path);
      37   [ #  #  #  # ]:           0 :     if (fs::exists(path)) {
      38   [ #  #  #  # ]:           0 :         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));
      39                 :           0 :         return false;
      40                 :             :     }
      41   [ #  #  #  # ]:           0 :     AutoFile dump_file{fsbridge::fopen(path, "w")};
      42         [ #  # ]:           0 :     if (dump_file.IsNull()) {
      43   [ #  #  #  # ]:           0 :         error = strprintf(_("Unable to open %s for writing"), fs::PathToString(path));
      44                 :           0 :         return false;
      45                 :             :     }
      46                 :             : 
      47         [ #  # ]:           0 :     HashWriter hasher{};
      48                 :             : 
      49         [ #  # ]:           0 :     std::unique_ptr<DatabaseBatch> batch = db.MakeBatch();
      50                 :             : 
      51                 :           0 :     struct DumpWalletError {
      52                 :             :         bilingual_str message;
      53                 :             :     };
      54                 :           0 :     auto throw_error = [](bilingual_str message) {
      55                 :           0 :         throw DumpWalletError{std::move(message)};
      56                 :             :     };
      57                 :           0 :     auto throw_write_error = [&] {
      58   [ #  #  #  # ]:           0 :         throw_error(strprintf(_("Unable to write complete dump file %s."), fs::PathToString(path)));
      59                 :           0 :     };
      60                 :           0 :     auto write = [&](const std::string& line) {
      61                 :           0 :         try {
      62         [ #  # ]:           0 :             dump_file.write(MakeByteSpan(line));
      63         [ -  - ]:           0 :         } catch (const std::ios_base::failure&) {
      64                 :           0 :             throw_write_error();
      65                 :           0 :         }
      66                 :           0 :     };
      67                 :           0 :     auto write_record = [&](const std::string& line) {
      68                 :           0 :         write(line);
      69         [ #  # ]:           0 :         hasher << std::span{line};
      70                 :           0 :     };
      71                 :             : 
      72                 :           0 :     try {
      73         [ #  # ]:           0 :         std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
      74         [ #  # ]:           0 :         if (!cursor) {
      75         [ #  # ]:           0 :             throw_error(_("Error: Couldn't create cursor into database"));
      76                 :             :         }
      77                 :             : 
      78                 :             :         // Write out a magic string with version
      79         [ #  # ]:           0 :         std::string line = strprintf("%s,%u\n", DUMP_MAGIC, DUMP_VERSION);
      80         [ #  # ]:           0 :         write_record(line);
      81                 :             : 
      82                 :             :         // Write out the file format
      83         [ #  # ]:           0 :         std::string format = db.Format();
      84                 :             :         // BDB files that are opened using BerkeleyRODatabase have its format as "bdb_ro"
      85                 :             :         // We want to override that format back to "bdb"
      86         [ #  # ]:           0 :         if (format == "bdb_ro") {
      87         [ #  # ]:           0 :             format = "bdb";
      88                 :             :         }
      89         [ #  # ]:           0 :         line = strprintf("%s,%s\n", "format", format);
      90         [ #  # ]:           0 :         write_record(line);
      91                 :             : 
      92                 :             :         // Read the records
      93                 :           0 :         while (true) {
      94                 :           0 :             DataStream ss_key{};
      95                 :           0 :             DataStream ss_value{};
      96         [ #  # ]:           0 :             DatabaseCursor::Status status = cursor->Next(ss_key, ss_value);
      97         [ #  # ]:           0 :             if (status == DatabaseCursor::Status::DONE) {
      98                 :             :                 break;
      99         [ #  # ]:           0 :             } else if (status == DatabaseCursor::Status::FAIL) {
     100         [ #  # ]:           0 :                 throw_error(_("Error reading next record from wallet database"));
     101                 :             :             }
     102   [ #  #  #  # ]:           0 :             std::string key_str = HexStr(ss_key);
     103   [ #  #  #  # ]:           0 :             std::string value_str = HexStr(ss_value);
     104         [ #  # ]:           0 :             line = strprintf("%s,%s\n", key_str, value_str);
     105         [ #  # ]:           0 :             write_record(line);
     106                 :           0 :         }
     107                 :             : 
     108                 :             :         // Write the hash
     109   [ #  #  #  #  :           0 :         line = strprintf("checksum,%s\n", HexStr(hasher.GetHash()));
                   #  # ]
     110         [ #  # ]:           0 :         write(line);
     111   [ #  #  #  # ]:           0 :         if (!dump_file.Commit()) throw_write_error();
     112   [ #  #  #  # ]:           0 :         if (dump_file.fclose() != 0) throw_write_error();
     113   [ #  #  #  # ]:           0 :         DirectoryCommit(path.parent_path());
     114         [ #  # ]:           0 :     } catch (const DumpWalletError& e) {
     115         [ -  - ]:           0 :         error = e.message;
     116                 :             :         // Remove the dumpfile on failure
     117         [ -  - ]:           0 :         (void)dump_file.fclose();
     118         [ -  - ]:           0 :         fs::remove(path);
     119                 :           0 :         return false;
     120                 :           0 :     }
     121                 :             : 
     122                 :           0 :     return true;
     123                 :           0 : }
     124                 :             : 
     125                 :             : // The standard wallet deleter function blocks on the validation interface
     126                 :             : // queue, which doesn't exist for the bitcoin-wallet. Define our own
     127                 :             : // deleter here.
     128                 :           0 : static void WalletToolReleaseWallet(CWallet* wallet)
     129                 :             : {
     130                 :           0 :     wallet->WalletLogPrintf("Releasing wallet");
     131                 :           0 :     wallet->Close();
     132         [ #  # ]:           0 :     delete wallet;
     133                 :           0 : }
     134                 :             : 
     135                 :           0 : bool CreateFromDump(const ArgsManager& args, const std::string& name, const fs::path& wallet_path, bilingual_str& error)
     136                 :             : {
     137         [ #  # ]:           0 :     if (name.empty()) {
     138                 :           0 :         tfm::format(std::cerr, "Wallet name cannot be empty\n");
     139                 :           0 :         return false;
     140                 :             :     }
     141                 :             : 
     142                 :             :     // Get the dumpfile
     143   [ #  #  #  # ]:           0 :     std::string dump_filename = args.GetArg("-dumpfile", "");
     144         [ #  # ]:           0 :     if (dump_filename.empty()) {
     145         [ #  # ]:           0 :         error = _("No dump file provided. To use createfromdump, -dumpfile=<filename> must be provided.");
     146                 :           0 :         return false;
     147                 :             :     }
     148                 :             : 
     149         [ #  # ]:           0 :     fs::path dump_path = fs::PathFromString(dump_filename);
     150         [ #  # ]:           0 :     dump_path = fs::absolute(dump_path);
     151   [ #  #  #  # ]:           0 :     if (!fs::exists(dump_path)) {
     152   [ #  #  #  # ]:           0 :         error = strprintf(_("Dump file %s does not exist."), fs::PathToString(dump_path));
     153                 :           0 :         return false;
     154                 :             :     }
     155         [ #  # ]:           0 :     std::ifstream dump_file{dump_path.std_path()};
     156                 :             : 
     157                 :             :     // Compute the checksum
     158         [ #  # ]:           0 :     HashWriter hasher{};
     159                 :           0 :     uint256 checksum;
     160                 :             : 
     161                 :             :     // Check the magic and version
     162         [ #  # ]:           0 :     std::string magic_key;
     163         [ #  # ]:           0 :     std::getline(dump_file, magic_key, ',');
     164         [ #  # ]:           0 :     std::string version_value;
     165         [ #  # ]:           0 :     std::getline(dump_file, version_value, '\n');
     166         [ #  # ]:           0 :     if (magic_key != DUMP_MAGIC) {
     167         [ #  # ]:           0 :         error = strprintf(_("Error: Dumpfile identifier record is incorrect. Got \"%s\", expected \"%s\"."), magic_key, DUMP_MAGIC);
     168         [ #  # ]:           0 :         dump_file.close();
     169                 :             :         return false;
     170                 :             :     }
     171                 :             :     // Check the version number (value of first record)
     172         [ #  # ]:           0 :     const auto ver{ToIntegral<uint32_t>(version_value)};
     173         [ #  # ]:           0 :     if (!ver) {
     174         [ #  # ]:           0 :         error = strprintf(_("Error: Unable to parse version %u as a uint32_t"), version_value);
     175         [ #  # ]:           0 :         dump_file.close();
     176                 :             :         return false;
     177                 :             :     }
     178         [ #  # ]:           0 :     if (*ver != DUMP_VERSION) {
     179         [ #  # ]:           0 :         error = strprintf(_("Error: Dumpfile version is not supported. This version of bitcoin-wallet only supports version 1 dumpfiles. Got dumpfile with version %s"), version_value);
     180         [ #  # ]:           0 :         dump_file.close();
     181                 :             :         return false;
     182                 :             :     }
     183         [ #  # ]:           0 :     std::string magic_hasher_line = strprintf("%s,%s\n", magic_key, version_value);
     184   [ #  #  #  # ]:           0 :     hasher << std::span{magic_hasher_line};
     185                 :             : 
     186                 :             :     // Get the stored file format
     187         [ #  # ]:           0 :     std::string format_key;
     188         [ #  # ]:           0 :     std::getline(dump_file, format_key, ',');
     189         [ #  # ]:           0 :     std::string format_value;
     190         [ #  # ]:           0 :     std::getline(dump_file, format_value, '\n');
     191         [ #  # ]:           0 :     if (format_key != "format") {
     192         [ #  # ]:           0 :         error = strprintf(_("Error: Dumpfile format record is incorrect. Got \"%s\", expected \"format\"."), format_key);
     193         [ #  # ]:           0 :         dump_file.close();
     194                 :             :         return false;
     195                 :             :     }
     196                 :             :     // Make sure that the dump was created from a sqlite database only as that is the only
     197                 :             :     // type of database that we still support.
     198                 :             :     // Other formats such as BDB should not be loaded into a sqlite database since they also
     199                 :             :     // use a different type of wallet entirely which is no longer compatible with this software.
     200         [ #  # ]:           0 :     if (format_value != "sqlite") {
     201         [ #  # ]:           0 :         error = strprintf(_("Error: Dumpfile specifies an unsupported database format (%s). Only sqlite database dumps are supported"), format_value);
     202                 :           0 :         return false;
     203                 :             :     }
     204         [ #  # ]:           0 :     std::string format_hasher_line = strprintf("%s,%s\n", format_key, format_value);
     205   [ #  #  #  # ]:           0 :     hasher << std::span{format_hasher_line};
     206                 :             : 
     207         [ #  # ]:           0 :     DatabaseOptions options;
     208                 :           0 :     DatabaseStatus status;
     209         [ #  # ]:           0 :     ReadDatabaseArgs(args, options);
     210                 :           0 :     options.require_create = true;
     211                 :           0 :     options.require_format = DatabaseFormat::SQLITE;
     212         [ #  # ]:           0 :     std::unique_ptr<WalletDatabase> database = MakeDatabase(wallet_path, options, status, error);
     213         [ #  # ]:           0 :     if (!database) return false;
     214                 :             : 
     215                 :             :     // dummy chain interface
     216                 :           0 :     bool ret = true;
     217   [ #  #  #  #  :           0 :     std::shared_ptr<CWallet> wallet(new CWallet(/*chain=*/nullptr, name, std::move(database)), WalletToolReleaseWallet);
             #  #  #  # ]
     218                 :           0 :     {
     219                 :             :         // Get the database handle
     220                 :           0 :         WalletDatabase& db = wallet->GetDatabase();
     221         [ #  # ]:           0 :         std::unique_ptr<DatabaseBatch> batch = db.MakeBatch();
     222         [ #  # ]:           0 :         batch->TxnBegin();
     223                 :             : 
     224                 :             :         // Read the records from the dump file and write them to the database
     225         [ #  # ]:           0 :         while (dump_file.good()) {
     226         [ #  # ]:           0 :             std::string key;
     227         [ #  # ]:           0 :             std::getline(dump_file, key, ',');
     228         [ #  # ]:           0 :             std::string value;
     229         [ #  # ]:           0 :             std::getline(dump_file, value, '\n');
     230                 :             : 
     231         [ #  # ]:           0 :             if (key == "checksum") {
     232   [ #  #  #  # ]:           0 :                 std::vector<unsigned char> parsed_checksum = ParseHex(value);
     233   [ #  #  #  # ]:           0 :                 if (parsed_checksum.size() != checksum.size()) {
     234   [ #  #  #  # ]:           0 :                     error = Untranslated("Error: Checksum is not the correct size");
     235                 :           0 :                     ret = false;
     236                 :           0 :                     break;
     237                 :             :                 }
     238                 :           0 :                 std::copy(parsed_checksum.begin(), parsed_checksum.end(), checksum.begin());
     239                 :             :                 break;
     240                 :           0 :             }
     241                 :             : 
     242         [ #  # ]:           0 :             std::string line = strprintf("%s,%s\n", key, value);
     243   [ #  #  #  # ]:           0 :             hasher << std::span{line};
     244                 :             : 
     245   [ #  #  #  # ]:           0 :             if (key.empty() || value.empty()) {
     246                 :           0 :                 continue;
     247                 :             :             }
     248                 :             : 
     249   [ #  #  #  #  :           0 :             if (!IsHex(key)) {
                   #  # ]
     250         [ #  # ]:           0 :                 error = strprintf(_("Error: Got key that was not hex: %s"), key);
     251                 :           0 :                 ret = false;
     252                 :           0 :                 break;
     253                 :             :             }
     254   [ #  #  #  #  :           0 :             if (!IsHex(value)) {
                   #  # ]
     255         [ #  # ]:           0 :                 error = strprintf(_("Error: Got value that was not hex: %s"), value);
     256                 :           0 :                 ret = false;
     257                 :           0 :                 break;
     258                 :             :             }
     259                 :             : 
     260   [ #  #  #  # ]:           0 :             std::vector<unsigned char> k = ParseHex(key);
     261   [ #  #  #  # ]:           0 :             std::vector<unsigned char> v = ParseHex(value);
     262   [ #  #  #  #  :           0 :             if (!batch->Write(std::span{k}, std::span{v})) {
             #  #  #  # ]
     263         [ #  # ]:           0 :                 error = strprintf(_("Error: Unable to write record to new wallet"));
     264                 :           0 :                 ret = false;
     265                 :           0 :                 break;
     266                 :             :             }
     267                 :           0 :         }
     268                 :             : 
     269         [ #  # ]:           0 :         if (ret) {
     270         [ #  # ]:           0 :             uint256 comp_checksum = hasher.GetHash();
     271         [ #  # ]:           0 :             if (checksum.IsNull()) {
     272         [ #  # ]:           0 :                 error = _("Error: Missing checksum");
     273                 :           0 :                 ret = false;
     274         [ #  # ]:           0 :             } else if (checksum != comp_checksum) {
     275   [ #  #  #  #  :           0 :                 error = strprintf(_("Error: Dumpfile checksum does not match. Computed %s, expected %s"), HexStr(comp_checksum), HexStr(checksum));
                   #  # ]
     276                 :           0 :                 ret = false;
     277                 :             :             }
     278                 :             :         }
     279                 :             : 
     280                 :           0 :         if (ret) {
     281         [ #  # ]:           0 :             batch->TxnCommit();
     282                 :             :         } else {
     283         [ #  # ]:           0 :             batch->TxnAbort();
     284                 :             :         }
     285                 :             : 
     286         [ #  # ]:           0 :         batch.reset();
     287                 :             : 
     288         [ #  # ]:           0 :         dump_file.close();
     289                 :           0 :     }
     290                 :             :     // On failure, gather the paths to remove
     291         [ #  # ]:           0 :     std::vector<fs::path> paths_to_remove = wallet->GetDatabase().Files();
     292   [ #  #  #  # ]:           0 :     if (!name.empty()) paths_to_remove.push_back(wallet_path);
     293                 :             : 
     294                 :           0 :     wallet.reset(); // The pointer deleter will close the wallet for us.
     295                 :             : 
     296                 :             :     // Remove the wallet dir if we have a failure
     297         [ #  # ]:           0 :     if (!ret) {
     298         [ #  # ]:           0 :         for (const auto& p : paths_to_remove) {
     299         [ #  # ]:           0 :             fs::remove(p);
     300                 :             :         }
     301                 :             :     }
     302                 :             : 
     303                 :           0 :     return ret;
     304         [ #  # ]:           0 : }
     305                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1