init: make the notarizations DB open fallback lock-aware

Any failure to open the notarizations DB used to be treated as
corruption: the previous notarizations.corrupt was remove_all()ed, the
live directory renamed over it and a fresh DB created. The common
failure is not corruption at all but "IO error: lock .../LOCK: Resource
temporarily unavailable" from a previous dragonxd that has not finished
exiting, and the fallback then destroyed both the live DB and the last
saved copy. A filesystem exception from remove_all()/rename() also
escaped into the outer handler and failed startup with a spurious
"Error opening block database".

Move the logic into OpenNotarizationDB():

 - if notarizations/LOCK is held (probed with leveldb's own
   Env::LockFile, i.e. the lock DB::Open takes), log once that we are
   waiting for a previous dragonxd, wait up to 30 s in 1 s steps
   (abandoned on a shutdown request) and retry; if it is still held,
   run this session on an in-memory notarizations DB and leave the
   on-disk one untouched;
 - only a DB that fails to open with the lock free is moved aside, now
   to a timestamped notarizations.corrupt-YYYYmmdd-HHMMSS name, so an
   earlier copy is never deleted;
 - a failed move-aside or recreate falls back to an in-memory DB
   instead of throwing: the DB is non-essential and regenerable and
   must never fail startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 10:42:30 -05:00
co-authored by Claude Opus 5.5
parent cbd5f8dce4
commit a7adcbc954
+93 -19
View File
@@ -79,6 +79,7 @@
#include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <leveldb/env.h>
#include <chrono>
#include <wolfssl/options.h>
#include <wolfssl/ssl.h>
@@ -125,6 +126,97 @@ static const char* DEFAULT_ASMAP_FILENAME="asmap.dat";
// in-memory cache the DB is opened with; the value here does not affect validation.
static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB
// How long AppInit2() waits for another process to release notarizations/LOCK before it gives up and
// runs on an in-memory notarizations DB.
static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30;
/**
* Is <dbdir>/LOCK held, by another process or by another open DB in this one? Probed with LevelDB's
* own Env::LockFile, i.e. the same lock DB::Open takes. A missing LOCK file cannot be held. Any other
* failure to take the lock counts as held: the caller then never moves or wipes the directory.
*/
static bool LevelDBLockHeld(const boost::filesystem::path& dbdir)
{
const boost::filesystem::path lockpath = dbdir / "LOCK";
boost::system::error_code ec;
if (!boost::filesystem::exists(lockpath, ec))
return false;
leveldb::Env* env = leveldb::Env::Default();
leveldb::FileLock* lock = NULL;
if (!env->LockFile(lockpath.string(), &lock).ok())
return true;
env->UnlockFile(lock);
return false;
}
/**
* Open the notarizations (dPoW) DB. It is non-essential and node-regenerable, so nothing here may fail
* startup (previously any open failure surfaced as a spurious "Error opening block database"):
* - LOCK held (typically a previous dragonxd that is still exiting): wait up to
* NOTARIZATION_LOCK_WAIT_SECONDS for it and retry; if it is still held, run this session on an
* in-memory DB and leave the on-disk one alone.
* - otherwise the DB is unreadable (seen: a torn snapshot, 0-byte log -> leveldb "Database I/O error"):
* move it aside under a timestamped notarizations.corrupt-* name, never deleting an earlier copy, and
* create a fresh one. If even that fails, fall back to an in-memory DB.
*/
static NotarizationDB* OpenNotarizationDB(bool fWipe)
{
const boost::filesystem::path ndir = GetDataDir() / "notarizations";
std::string strError;
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe);
} catch (const std::exception& e) {
strError = e.what();
}
if (LevelDBLockHeld(ndir)) {
LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK is held by another process; waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n",
__func__, strError, NOTARIZATION_LOCK_WAIT_SECONDS);
int nWaited = 0;
while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested() && LevelDBLockHeld(ndir)) {
MilliSleep(1000);
nWaited++;
}
if (!LevelDBLockHeld(ndir)) {
try {
NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe);
LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, nWaited);
return pdb;
} catch (const std::exception& e) {
strError = e.what();
}
}
if (LevelDBLockHeld(ndir)) {
LogPrintf("%s: notarizations/LOCK still held after %d s; using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, nWaited);
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
// The lock is free but the DB still does not open: treat it as corrupt.
}
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError);
// Move (do NOT delete) the old DB aside, so a transient open failure (fd exhaustion, disk full,
// permissions) cannot permanently destroy notarization history. Earlier copies are kept too.
try {
const std::string base = ndir.string() + ".corrupt-" + DateTimeStrFormat("%Y%m%d-%H%M%S", GetTime());
boost::filesystem::path aside(base);
for (int i = 1; boost::filesystem::exists(aside); i++)
aside = base + strprintf(".%d", i);
boost::filesystem::rename(ndir, aside);
LogPrintf("%s: moved the old notarizations DB to %s\n", __func__, aside.string());
} catch (const std::exception& e) {
LogPrintf("%s: could not move the notarizations DB aside (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
} catch (const std::exception& e) {
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
CClientUIInterface uiInterface; // global UI callback dispatcher (declared extern in ui_interface.h)
// Shutdown
@@ -2093,25 +2185,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
try {
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fReindex);
} catch (const std::exception& e) {
// The notarizations (dPoW) DB is non-essential and node-regenerable. It has been seen to
// snapshot/flush torn (0-byte log -> leveldb "Database I/O error" on reopen), which
// previously aborted startup with a spurious "Error opening block database" and forced a
// full resync. Wipe and recreate it instead of failing hard.
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __FUNCTION__, e.what());
// Move (do NOT delete) the old DB aside, so a transient open failure (fd
// exhaustion, disk full, permissions) cannot permanently destroy notarization
// history. If the recreate below also fails it propagates as fatal and the old
// data survives in notarizations.corrupt for recovery.
{
boost::filesystem::path ndir = GetDataDir() / "notarizations";
boost::filesystem::remove_all(ndir.string() + ".corrupt");
boost::filesystem::rename(ndir, ndir.string() + ".corrupt");
}
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
}
pnotarizations = OpenNotarizationDB(fReindex);
if (fReindex) {