2019-07-21 16:59:47 +02:00
|
|
|
import * as fs from 'fs';
|
2020-09-21 23:07:47 +02:00
|
|
|
import * as cluster from 'cluster';
|
2020-02-26 11:49:53 +01:00
|
|
|
import memPool from './mempool';
|
2020-02-29 15:52:04 +01:00
|
|
|
import blocks from './blocks';
|
2019-07-21 16:59:47 +02:00
|
|
|
|
|
|
|
class DiskCache {
|
|
|
|
static FILE_NAME = './cache.json';
|
|
|
|
|
2020-02-26 11:49:53 +01:00
|
|
|
constructor() {
|
2020-09-29 18:13:22 +02:00
|
|
|
process.on('SIGINT', () => {
|
|
|
|
this.saveCacheToDisk();
|
|
|
|
process.exit(2);
|
|
|
|
});
|
|
|
|
|
|
|
|
process.on('SIGTERM', () => {
|
|
|
|
this.saveCacheToDisk();
|
|
|
|
process.exit(2);
|
|
|
|
});
|
2020-03-01 17:09:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
saveCacheToDisk() {
|
|
|
|
this.saveData(JSON.stringify({
|
|
|
|
mempool: memPool.getMempool(),
|
|
|
|
blocks: blocks.getBlocks(),
|
|
|
|
}));
|
|
|
|
console.log('Mempool and blocks data saved to disk cache');
|
2020-02-26 11:49:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
loadMempoolCache() {
|
|
|
|
const cacheData = this.loadData();
|
|
|
|
if (cacheData) {
|
2020-02-29 15:52:04 +01:00
|
|
|
console.log('Restoring mempool and blocks data from disk cache');
|
|
|
|
const data = JSON.parse(cacheData);
|
2020-09-29 18:13:22 +02:00
|
|
|
memPool.setMempool(data.mempool);
|
|
|
|
blocks.setBlocks(data.blocks);
|
2020-02-26 11:49:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private saveData(dataBlob: string) {
|
2019-07-21 16:59:47 +02:00
|
|
|
fs.writeFileSync(DiskCache.FILE_NAME, dataBlob, 'utf8');
|
|
|
|
}
|
|
|
|
|
2020-02-26 11:49:53 +01:00
|
|
|
private loadData(): string {
|
2019-07-21 16:59:47 +02:00
|
|
|
return fs.readFileSync(DiskCache.FILE_NAME, 'utf8');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new DiskCache();
|