Try to (very carefully!) recover wallet.dat if there is a problem.
| 1075 | // Try to (very carefully!) recover wallet.dat if there is a problem. |
| 1076 | // |
| 1077 | bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) |
| 1078 | { |
| 1079 | // Recovery procedure: |
| 1080 | // move wallet.dat to wallet.timestamp.bak |
| 1081 | // Call Salvage with fAggressive=true to |
| 1082 | // get as much data as possible. |
| 1083 | // Rewrite salvaged data to wallet.dat |
| 1084 | // Set -rescan so any missing transactions will be |
| 1085 | // found. |
| 1086 | int64_t now = GetTime(); |
| 1087 | std::string newFilename = strprintf("wallet.%d.bak", now); |
| 1088 | |
| 1089 | int result = dbenv.dbenv->dbrename(NULL, filename.c_str(), NULL, |
| 1090 | newFilename.c_str(), DB_AUTO_COMMIT); |
| 1091 | if (result == 0) |
| 1092 | LogPrintf("Renamed %s to %s\n", filename, newFilename); |
| 1093 | else { |
| 1094 | LogPrintf("Failed to rename %s to %s\n", filename, newFilename); |
| 1095 | return false; |
| 1096 | } |
| 1097 | |
| 1098 | std::vector<CDBEnv::KeyValPair> salvagedData; |
| 1099 | bool allOK = dbenv.Salvage(newFilename, true, salvagedData); |
| 1100 | if (salvagedData.empty()) { |
| 1101 | LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); |
| 1102 | return false; |
| 1103 | } |
| 1104 | LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); |
| 1105 | |
| 1106 | bool fSuccess = allOK; |
| 1107 | boost::scoped_ptr<Db> pdbCopy(new Db(dbenv.dbenv, 0)); |
| 1108 | int ret = pdbCopy->open(NULL, // Txn pointer |
| 1109 | filename.c_str(), // Filename |
| 1110 | "main", // Logical db name |
| 1111 | DB_BTREE, // Database type |
| 1112 | DB_CREATE, // Flags |
| 1113 | 0); |
| 1114 | if (ret > 0) { |
| 1115 | LogPrintf("Cannot create database file %s\n", filename); |
| 1116 | return false; |
| 1117 | } |
| 1118 | CWallet dummyWallet; |
| 1119 | CWalletScanState wss; |
| 1120 | |
| 1121 | DbTxn* ptxn = dbenv.TxnBegin(); |
| 1122 | for (CDBEnv::KeyValPair& row : salvagedData) { |
| 1123 | if (fOnlyKeys) { |
| 1124 | CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); |
| 1125 | CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); |
| 1126 | string strType, strErr; |
| 1127 | bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, |
| 1128 | wss, strType, strErr); |
| 1129 | if (!IsKeyType(strType) && strType != "hdpubkey") |
| 1130 | continue; |
| 1131 | if (!fReadOK) { |
| 1132 | LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); |
| 1133 | continue; |
| 1134 | } |