From f09f5a7b9504c91726f759c40e01f1dea80fa115 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:23:20 -0500 Subject: [PATCH 1/7] init: close the notarizations DB in Shutdown() Shutdown() deleted pcoinsTip, pcoinsdbview and pblocktree but never pnotarizations, so notarizations/LOCK was the one LevelDB lock still held after "Shutdown: done". It was only released when the process was torn down, after the static datadir .lock had already been released. A successor started in that window took .lock, blocks/index and chainstate and then failed to open notarizations/LOCK (EAGAIN), which the open fallback "fixed" by moving the live notarizations DB aside and wiping it. Delete it under cs_main next to pblocktree, and null the pointer after the delete in the block-index load loop so a throwing reopen can never leave it dangling for Shutdown() to delete twice. Every user of pnotarizations now treats NULL as an empty DB (GetBlockNotarizations, GetBackNotarization, ScanNotarizationsDB, ConnectNotarizations, DisconnectNotarizations; crosschain.cpp, rpc/crosschain.cpp, hush_nSPV_fullnode.h and hush_dailysnapshot only reach it through those), so a straggler after Shutdown() cannot dereference it. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 8 ++++++++ src/main.cpp | 4 ++++ src/notarizationdb.cpp | 11 ++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..34403e3c1 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -274,6 +274,13 @@ void Shutdown() delete pblocktree; pblocktree = NULL; } + // Close the notarizations DB with the other LevelDBs. It used to be left open until process + // teardown, which made notarizations/LOCK the one LevelDB lock still held after "Shutdown: done" + // (and after the datadir .lock was released), so a quickly restarted successor failed to open it. + if (pnotarizations != NULL) { + delete pnotarizations; + pnotarizations = NULL; + } } #ifdef ENABLE_WALLET if (pwalletMain) @@ -2080,6 +2087,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) delete pcoinscatcher; delete pblocktree; delete pnotarizations; + pnotarizations = NULL; // Shutdown() deletes it, so never leave it dangling if a reopen below throws pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); diff --git a/src/main.cpp b/src/main.cpp index db0af063b..f71435fed 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2980,6 +2980,8 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO void ConnectNotarizations(const CBlock &block, int height) { + if (pnotarizations == NULL) // closed by Shutdown() + return; NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height); if (notarizations.size() > 0) { CDBBatch batch = CDBBatch(*pnotarizations); @@ -2992,6 +2994,8 @@ void ConnectNotarizations(const CBlock &block, int height) void DisconnectNotarizations(const CBlock &block) { + if (pnotarizations == NULL) // closed by Shutdown() + return; NotarizationsInBlock nibs; if (GetBlockNotarizations(block.GetHash(), nibs)) { CDBBatch batch = CDBBatch(*pnotarizations); diff --git a/src/notarizationdb.cpp b/src/notarizationdb.cpp index 478d00583..26641cbaf 100644 --- a/src/notarizationdb.cpp +++ b/src/notarizationdb.cpp @@ -9,7 +9,10 @@ #include "main.h" #include -NotarizationDB *pnotarizations; +// Owned by init: opened in AppInit2() and closed (set back to NULL) in Shutdown(), so that +// notarizations/LOCK is released together with the other LevelDB locks. Every accessor treats NULL +// as an empty DB, so a straggler after Shutdown() cannot dereference it. +NotarizationDB *pnotarizations = NULL; NotarizationDB::NotarizationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "notarizations", nCacheSize, fMemory, fWipe, false, 64) { } NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) { @@ -55,11 +58,15 @@ NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) { } bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) { + if (pnotarizations == NULL) + return false; return pnotarizations->Read(blockHash, nibs); } bool GetBackNotarization(uint256 notarizationHash, Notarization &n) { + if (pnotarizations == NULL) + return false; return pnotarizations->Read(notarizationHash, n); } @@ -86,6 +93,8 @@ void EraseBackNotarizations(const NotarizationsInBlock notarizations, CDBBatch & // Scan notarizationsdb backwards for blocks containing a notarization // for given symbol. Return height of matched notarization or 0. int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) { + if (pnotarizations == NULL) + return 0; if (height < 0 || height > chainActive.Height()) return false; From cbd5f8dce45902deb0972fc6730fb6d3ca0f6bb1 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:26:20 -0500 Subject: [PATCH 2/7] init: do not rename the main thread in Shutdown() Shutdown() called RenameThread("hush-shutoff") on the main thread. On Linux that sets /proc//comm, i.e. the process name, so for the whole shutdown (wallet flush, chainstate flush, LevelDB closes) the node no longer matched 'pgrep -x dragonxd' / pidof while it still held the datadir and LevelDB locks. pgrep-based restart scripts took that as "exited" and relaunched it early; on regtest pgrep stopped matching about 1 s after 'stop' in 10/10 runs while the old process was alive. Keep the process name until exit. Worker threads keep their own names. Nothing depends on "hush-shutoff": no hit in src/, qa/, contrib/ or util/, and the ObsidianDragon GUI only works around the rename by also checking the exe link. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 34403e3c1..776699fa9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -211,9 +211,9 @@ void Shutdown() /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. - static char shutoffstr[128]; - sprintf(shutoffstr,"%s-shutoff","hush"); - RenameThread(shutoffstr); + // Do not RenameThread() here: Shutdown() runs on the main thread, whose name is the process name + // (/proc//comm). Renaming it made 'pgrep -x dragonxd' stop matching a node that was still + // shutting down and holding its locks, so pgrep-based restart scripts relaunched it too early. mempool.AddTransactionsUpdated(1); if(fDebug) { From a7adcbc954bd187977ab4687d16b19bf11b4ba78 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:42:30 -0500 Subject: [PATCH 3/7] 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 --- src/init.cpp | 112 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 93 insertions(+), 19 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 776699fa9..2fca612f4 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -79,6 +79,7 @@ #include #include #include +#include #include #include #include @@ -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 /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) { From 4d7de7a0ebc72ba0d2c8c1cdd632e604a7db350c Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:44:43 -0500 Subject: [PATCH 4/7] init: do not leave chain DB pointers dangling in the block-index load loop The load loop deleted pcoinsTip, pcoinsdbview, pcoinscatcher and pblocktree before reopening them without resetting the pointers. If a reopen throws (e.g. a corrupt or unopenable blocks/index), the outer handler reports "Error opening block database", AppInit2() returns false and Shutdown() then calls FlushStateToDisk() on, and deletes, the already freed objects: a use-after-free and double delete on the exit path. Null each pointer right after its delete, as the previous commit already did for pnotarizations. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 2fca612f4..aa23fbbe9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2174,12 +2174,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) do { try { UnloadBlockIndex(); - delete pcoinsTip; - delete pcoinsdbview; - delete pcoinscatcher; - delete pblocktree; - delete pnotarizations; - pnotarizations = NULL; // Shutdown() deletes it, so never leave it dangling if a reopen below throws + // Shutdown() deletes (and pcoinsTip: flushes) whatever is non-NULL here, so never leave + // a pointer dangling if one of the reopens below throws. + delete pcoinsTip; pcoinsTip = NULL; + delete pcoinsdbview; pcoinsdbview = NULL; + delete pcoinscatcher; pcoinscatcher = NULL; + delete pblocktree; pblocktree = NULL; + delete pnotarizations; pnotarizations = NULL; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); From 8f70f494b3bd4a380badcb096c3f57e0c5e90218 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:10:21 -0500 Subject: [PATCH 5/7] init: do not call the notarizations DB corrupt on one post-failure probe OpenNotarizationDB() decided between "LOCK held" and "corrupt" with a lock probe taken after DB::Open had already failed. If the holder (an older dragonxd finishing its exit, the very upgrade-restart case the lock-aware fallback exists for) released notarizations/LOCK between the failed open and the probe, the probe found the lock free and a healthy DB was moved aside and replaced by an empty one. CDBWrapper throws a generic "Database I/O error", so the error text cannot tell the two cases apart either. Only treat the DB as unreadable when an open fails although the probe just before that open found the lock free: on a free probe, open once more, and move aside only if that attempt fails too. A held probe still gets the single bounded wait and then the in-memory fallback. The probe now returns the leveldb::Status of its LockFile call, and the log reports it ("Resource temporarily unavailable" versus, say, "Permission denied") instead of the generic open error alone, worded as "could not be taken" since a non-ok probe is not always another holder. Any non-ok probe still counts as held, so it never moves or wipes. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 87 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 51 insertions(+), 36 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index aa23fbbe9..5b4d5cae1 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -131,67 +131,82 @@ static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30; /** - * Is /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. + * Try to take /LOCK with LevelDB's own Env::LockFile, i.e. the same lock DB::Open takes, and + * release it at once. ok() means the lock is free (a missing LOCK file cannot be held). Anything else + * means it could not be taken: usually another process holds it ("Resource temporarily unavailable"), + * but it may also be e.g. a permission error. The caller treats every non-ok status as held, and so + * never moves or wipes the directory on its strength. */ -static bool LevelDBLockHeld(const boost::filesystem::path& dbdir) +static leveldb::Status ProbeLevelDBLock(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; + return leveldb::Status::OK(); leveldb::Env* env = leveldb::Env::Default(); leveldb::FileLock* lock = NULL; - if (!env->LockFile(lockpath.string(), &lock).ok()) - return true; - env->UnlockFile(lock); - return false; + leveldb::Status status = env->LockFile(lockpath.string(), &lock); + if (status.ok()) + env->UnlockFile(lock); + return status; } /** * 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 + * - LOCK cannot be taken (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. + * The lock is probed only after an open fails, so a holder that exits between the failed open and the + * probe makes the probe report "free" for a DB that is fine. The DB is therefore treated as corrupt only + * when an open fails although the probe just before that open found the lock free. */ 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); + bool fWaited = false; // the bounded wait for the lock has been used up + bool fProbedFree = false; // the probe right before the last open attempt found the lock free + int nWaited = 0; + while (true) { + try { + NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); + if (fWaited) LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, nWaited); - return pdb; - } catch (const std::exception& e) { - strError = e.what(); + else if (fProbedFree) + LogPrintf("%s: notarizations DB opened on retry (notarizations/LOCK was released after the first attempt)\n", __func__); + return pdb; + } catch (const std::exception& e) { + strError = e.what(); + } + if (fProbedFree) + break; // failed with the lock free beforehand: genuinely unreadable + + leveldb::Status lockStatus = ProbeLevelDBLock(ndir); + if (!lockStatus.ok()) { + if (!fWaited) { + LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK could not be taken (%s); waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n", + __func__, strError, lockStatus.ToString(), NOTARIZATION_LOCK_WAIT_SECONDS); + fWaited = true; + while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested()) { + MilliSleep(1000); + nWaited++; + lockStatus = ProbeLevelDBLock(ndir); + if (lockStatus.ok()) + break; + } + } + if (!lockStatus.ok()) { + LogPrintf("%s: notarizations/LOCK still could not be taken after %d s (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n", + __func__, nWaited, lockStatus.ToString()); + return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); } } - 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. + // The lock is free now: open once more before calling the DB corrupt. + fProbedFree = true; } LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError); From 2bc4a70eb867c0e53864b54b77ae3eacceef5d33 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:21:55 -0500 Subject: [PATCH 6/7] init: bound the notarizations LOCK wait by wall-clock time The wait for another process to release notarizations/LOCK counted 1 s sleeps, so the time spent probing and a loaded machine stretched the "up to 30 s" to 33-34 s. Wait against a GetTimeMillis() deadline instead, and report the measured elapsed time in the "released after" and "still could not be taken after" lines. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 5b4d5cae1..77a496853 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -170,12 +170,12 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) std::string strError; bool fWaited = false; // the bounded wait for the lock has been used up bool fProbedFree = false; // the probe right before the last open attempt found the lock free - int nWaited = 0; + int64_t nWaitStart = 0; while (true) { try { NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); if (fWaited) - LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, nWaited); + LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, (GetTimeMillis() - nWaitStart) / 1000); else if (fProbedFree) LogPrintf("%s: notarizations DB opened on retry (notarizations/LOCK was released after the first attempt)\n", __func__); return pdb; @@ -191,9 +191,10 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK could not be taken (%s); waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n", __func__, strError, lockStatus.ToString(), NOTARIZATION_LOCK_WAIT_SECONDS); fWaited = true; - while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested()) { - MilliSleep(1000); - nWaited++; + nWaitStart = GetTimeMillis(); + const int64_t nDeadline = nWaitStart + NOTARIZATION_LOCK_WAIT_SECONDS * 1000LL; + while (GetTimeMillis() < nDeadline && !ShutdownRequested()) { + MilliSleep(std::min(1000, std::max(1, nDeadline - GetTimeMillis()))); lockStatus = ProbeLevelDBLock(ndir); if (lockStatus.ok()) break; @@ -201,7 +202,7 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) } if (!lockStatus.ok()) { LogPrintf("%s: notarizations/LOCK still could not be taken after %d s (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n", - __func__, nWaited, lockStatus.ToString()); + __func__, (GetTimeMillis() - nWaitStart) / 1000, lockStatus.ToString()); return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); } } From ced37555c44b6432f17ea4197bfe0c9bd4fa4cb3 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:32:01 -0500 Subject: [PATCH 7/7] init: recreate a data-less notarizations DB in place, not aside Every unreadable notarizations DB was moved aside under a new timestamped notarizations.corrupt-* name. For a failure that persists across starts rather than real corruption (disk full: DB::Open creates the directory and LOCK, then fails), each start moved another empty directory aside, and the copies piled up without limit. When the directory holds no data, i.e. no non-empty .ldb/.sst table or .log write-ahead log, there is nothing to keep: recreate the DB in place instead (falling back to an in-memory DB as before if that fails). A directory that cannot be listed counts as holding data, and any DB with records is still moved aside, never deleted. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/init.cpp b/src/init.cpp index 77a496853..778e1a3c9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -151,6 +151,33 @@ static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir) return status; } +/** + * Does hold any LevelDB data, i.e. a non-empty table (.ldb/.sst) or write-ahead log (.log)? + * CURRENT, MANIFEST-*, LOCK and the LOG/LOG.old info logs carry no records. When in doubt (the + * directory cannot be listed) say yes, so the caller keeps a copy. + */ +static bool LevelDBDirHasData(const boost::filesystem::path& dbdir) +{ + boost::system::error_code ec; + if (!boost::filesystem::exists(dbdir, ec)) + return ec ? true : false; + boost::filesystem::directory_iterator it(dbdir, ec), end; + if (ec) + return true; + for (; it != end; it.increment(ec)) { + if (ec) + return true; + const std::string ext = it->path().extension().string(); + if (ext != ".ldb" && ext != ".sst" && ext != ".log") + continue; + boost::system::error_code sizeEc; + const uintmax_t size = boost::filesystem::file_size(it->path(), sizeEc); + if (sizeEc || size > 0) + return true; + } + 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"): @@ -159,7 +186,9 @@ static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir) * 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. + * create a fresh one. A directory holding no data is recreated in place instead, so a persistent + * failure (e.g. disk full) does not add another empty copy on every start. If even that fails, fall + * back to an in-memory DB. * The lock is probed only after an open fails, so a holder that exits between the failed open and the * probe makes the probe report "free" for a DB that is fine. The DB is therefore treated as corrupt only * when an open fails although the probe just before that open found the lock free. @@ -210,6 +239,16 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) fProbedFree = true; } + if (!LevelDBDirHasData(ndir)) { + LogPrintf("%s: notarizations DB failed to open (%s) and holds no data; recreating it in place (non-fatal)\n", __func__, strError); + 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); + } + } + 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.