| 248 | } |
| 249 | |
| 250 | bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename) |
| 251 | { |
| 252 | std::string filename; |
| 253 | BerkeleyEnvironment* env = GetWalletEnv(file_path, filename); |
| 254 | |
| 255 | // Recovery procedure: |
| 256 | // move wallet file to walletfilename.timestamp.bak |
| 257 | // Call Salvage with fAggressive=true to |
| 258 | // get as much data as possible. |
| 259 | // Rewrite salvaged data to fresh wallet file |
| 260 | // Set -rescan so any missing transactions will be |
| 261 | // found. |
| 262 | int64_t now = GetTime(); |
| 263 | newFilename = strprintf("%s.%d.bak", filename, now); |
| 264 | |
| 265 | int result = env->dbenv->dbrename(nullptr, filename.c_str(), nullptr, |
| 266 | newFilename.c_str(), DB_AUTO_COMMIT); |
| 267 | if (result == 0) |
| 268 | LogPrintf("Renamed %s to %s\n", filename, newFilename); |
| 269 | else |
| 270 | { |
| 271 | LogPrintf("Failed to rename %s to %s\n", filename, newFilename); |
| 272 | return false; |
| 273 | } |
| 274 | |
| 275 | std::vector<BerkeleyEnvironment::KeyValPair> salvagedData; |
| 276 | bool fSuccess = env->Salvage(newFilename, true, salvagedData); |
| 277 | if (salvagedData.empty()) |
| 278 | { |
| 279 | LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); |
| 280 | return false; |
| 281 | } |
| 282 | LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); |
| 283 | |
| 284 | std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0); |
| 285 | int ret = pdbCopy->open(nullptr, // Txn pointer |
| 286 | filename.c_str(), // Filename |
| 287 | "main", // Logical db name |
| 288 | DB_BTREE, // Database type |
| 289 | DB_CREATE, // Flags |
| 290 | 0); |
| 291 | if (ret > 0) { |
| 292 | LogPrintf("Cannot create database file %s\n", filename); |
| 293 | pdbCopy->close(0); |
| 294 | return false; |
| 295 | } |
| 296 | |
| 297 | DbTxn* ptxn = env->TxnBegin(); |
| 298 | for (BerkeleyEnvironment::KeyValPair& row : salvagedData) |
| 299 | { |
| 300 | if (recoverKVcallback) |
| 301 | { |
| 302 | CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); |
| 303 | CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); |
| 304 | if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue)) |
| 305 | continue; |
| 306 | } |
| 307 | Dbt datKey(&row.first[0], row.first.size()); |