diff --git a/backend/src/api/disk-cache.ts b/backend/src/api/disk-cache.ts index 71a3d9d53..7a38e7da0 100644 --- a/backend/src/api/disk-cache.ts +++ b/backend/src/api/disk-cache.ts @@ -17,6 +17,7 @@ class DiskCache { private static TMP_FILE_NAMES = config.MEMPOOL.CACHE_DIR + '/tmp-cache{number}.json'; private static FILE_NAME = config.MEMPOOL.CACHE_DIR + '/cache.json'; private static FILE_NAMES = config.MEMPOOL.CACHE_DIR + '/cache{number}.json'; + private static TMP_RBF_FILE_NAME = config.MEMPOOL.CACHE_DIR + '/tmp-rbfcache.json'; private static RBF_FILE_NAME = config.MEMPOOL.CACHE_DIR + '/rbfcache.json'; private static CHUNK_FILES = 25; private isWritingCache = false; @@ -103,14 +104,26 @@ class DiskCache { logger.warn('Error writing to cache file: ' + (e instanceof Error ? e.message : e)); this.isWritingCache = false; } + try { logger.debug('Writing rbf data to disk cache (async)...'); this.isWritingCache = true; - - await fsPromises.writeFile(DiskCache.RBF_FILE_NAME, JSON.stringify({ - rbfCacheSchemaVersion: this.rbfCacheSchemaVersion, - rbf: rbfCache.dump(), - }), { flag: 'w' }); + const rbfData = rbfCache.dump(); + if (sync) { + fs.writeFileSync(DiskCache.TMP_RBF_FILE_NAME, JSON.stringify({ + network: config.MEMPOOL.NETWORK, + rbfCacheSchemaVersion: this.rbfCacheSchemaVersion, + rbf: rbfData, + }), { flag: 'w' }); + fs.renameSync(DiskCache.TMP_RBF_FILE_NAME, DiskCache.RBF_FILE_NAME); + } else { + await fsPromises.writeFile(DiskCache.TMP_RBF_FILE_NAME, JSON.stringify({ + network: config.MEMPOOL.NETWORK, + rbfCacheSchemaVersion: this.rbfCacheSchemaVersion, + rbf: rbfData, + }), { flag: 'w' }); + await fsPromises.rename(DiskCache.TMP_RBF_FILE_NAME, DiskCache.RBF_FILE_NAME); + } logger.debug('Rbf data saved to disk cache'); this.isWritingCache = false; } catch (e) { @@ -214,9 +227,15 @@ class DiskCache { logger.notice('Rbf disk cache contains an outdated schema version. Clearing it and skipping the cache loading.'); return this.wipeRbfCache(); } + if (rbfData.network && rbfData.network !== config.MEMPOOL.NETWORK) { + logger.notice('Rbf disk cache contains data from a different network. Clearing it and skipping the cache loading.'); + return this.wipeRbfCache(); + } } - rbfCache.load(rbfData.rbf); + if (rbfData?.rbf) { + rbfCache.load(rbfData.rbf); + } } catch (e) { logger.warn('Failed to parse rbf cache. Skipping. Reason: ' + (e instanceof Error ? e.message : e)); }