Try to (very carefully!) recover wallet.dat if there is a problem.
| 210 | // Try to (very carefully!) recover wallet.dat if there is a problem. |
| 211 | // |
| 212 | bool CWalletDB::Recover(CDBEnv& dbenv, string filename, bool fOnlyKeys) { |
| 213 | // Recovery procedure: |
| 214 | // move wallet.dat to wallet.timestamp.bak |
| 215 | // Call Salvage with fAggressive=true to |
| 216 | // get as much data as possible. |
| 217 | // Rewrite salvaged data to wallet.dat |
| 218 | // Set -rescan so any missing transactions will be |
| 219 | // found. |
| 220 | int64_t now = GetTime(); |
| 221 | string newFilename = strprintf("wallet.%d.bak", now); |
| 222 | |
| 223 | int32_t result = dbenv.dbenv->dbrename(nullptr, filename.c_str(), nullptr, newFilename.c_str(), DB_AUTO_COMMIT); |
| 224 | if (result == 0) { |
| 225 | LogPrint(BCLog::INFO, "Renamed %s to %s\n", filename, newFilename); |
| 226 | } else { |
| 227 | LogPrint(BCLog::INFO, "Failed to rename %s to %s\n", filename, newFilename); |
| 228 | return false; |
| 229 | } |
| 230 | |
| 231 | vector<CDBEnv::KeyValPair> salvagedData; |
| 232 | bool allOK = dbenv.Salvage(newFilename, true, salvagedData); |
| 233 | if (salvagedData.empty()) { |
| 234 | LogPrint(BCLog::INFO, "Salvage(aggressive) found no records in %s.\n", newFilename); |
| 235 | return false; |
| 236 | } |
| 237 | LogPrint(BCLog::INFO, "Salvage(aggressive) found %u records\n", salvagedData.size()); |
| 238 | |
| 239 | bool fSuccess = allOK; |
| 240 | boost::scoped_ptr<Db> pdbCopy(new Db(dbenv.dbenv, 0)); |
| 241 | int32_t ret = pdbCopy->open(nullptr, // Txn pointer |
| 242 | filename.c_str(), // Filename |
| 243 | "main", // Logical db name |
| 244 | DB_BTREE, // Database type |
| 245 | DB_CREATE, // Flags |
| 246 | 0); |
| 247 | if (ret > 0) { |
| 248 | LogPrint(BCLog::INFO, "Cannot create database file %s\n", filename); |
| 249 | return false; |
| 250 | } |
| 251 | DbTxn* ptxn = dbenv.TxnBegin(); |
| 252 | for (auto& row : salvagedData) { |
| 253 | if (fOnlyKeys) { |
| 254 | CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); |
| 255 | CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); |
| 256 | string strType, strErr; |
| 257 | bool fReadOK = ReadKeyValue(nullptr, ssKey, ssValue, strType, strErr, -1); |
| 258 | if (strType != "keystore") |
| 259 | continue; |
| 260 | if (!fReadOK) { |
| 261 | LogPrint(BCLog::INFO, "WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); |
| 262 | continue; |
| 263 | } |
| 264 | } |
| 265 | Dbt datKey(&row.first[0], row.first.size()); |
| 266 | Dbt datValue(&row.second[0], row.second.size()); |
| 267 | int32_t ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); |
| 268 | if (ret2 > 0) |
| 269 | fSuccess = false; |