xud
Version:
Exchange Union Daemon
199 lines • 9.75 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const Config_1 = __importDefault(require("../Config"));
const LndClient_1 = __importDefault(require("../lndclient/LndClient"));
const Logger_1 = __importStar(require("../Logger"));
const utils_1 = require("../utils/utils");
class Backup extends events_1.EventEmitter {
constructor() {
super(...arguments);
this.config = new Config_1.default();
this.fileWatchers = [];
this.lndClients = [];
/** A map of client names to a boolean indicating whether they have changed since the last backup. */
this.databaseChangedMap = new Map();
this.xudBackupTimer = setInterval(() => {
if (this.databaseChangedMap.get('xud') === true) {
const backupPath = this.getBackupPath('xud');
const content = this.readDatabase(this.config.dbpath);
this.writeBackup(backupPath, content);
this.databaseChangedMap.set('xud', false);
}
}, 180000);
this.start = (args) => __awaiter(this, void 0, void 0, function* () {
yield this.config.load(args);
this.backupDir = args.backupdir || utils_1.getDefaultBackupDir();
this.logger = new Logger_1.default({
context: Logger_1.Context.Backup,
level: this.config.loglevel,
filename: this.config.logpath,
instanceId: this.config.instanceid,
dateFormat: this.config.logdateformat,
});
if (!fs_1.default.existsSync(this.backupDir)) {
try {
fs_1.default.mkdirSync(this.backupDir);
}
catch (error) {
this.logger.error(`Could not create backup directory: ${error}`);
return;
}
}
this.startLndSubscriptions().catch((err) => {
this.logger.error(`Could not connect to LNDs: ${err}`);
});
// Start the XUD database filewatcher
this.startFilewatcher('xud', this.config.dbpath).catch(this.logger.error);
this.logger.info('Started backup daemon');
});
this.stop = () => {
if (this.checkLndTimer) {
clearInterval(this.checkLndTimer);
}
this.fileWatchers.forEach((watcher) => {
watcher.close();
});
for (const lndClient of this.lndClients) {
lndClient.close();
}
clearInterval(this.xudBackupTimer);
};
this.waitForLndConnected = (lndClient) => {
return new Promise((resolve) => {
if (lndClient.isConnected()) {
resolve();
}
else {
lndClient.on('connectionVerified', resolve);
}
});
};
this.startLndSubscriptions = () => __awaiter(this, void 0, void 0, function* () {
// Start the LND SCB subscriptions
const lndPromises = [];
const startLndSubscription = (currency) => __awaiter(this, void 0, void 0, function* () {
const config = this.config.lnd[currency];
// Ignore the LND client if it is disabled or not configured
if (!config.disable && Object.entries(config).length !== 0) {
const lndClient = new LndClient_1.default({
config,
currency,
logger: Logger_1.default.DISABLED_LOGGER,
});
this.lndClients.push(lndClient);
yield lndClient.init();
this.logger.info(`Waiting for lnd-${lndClient.currency}`);
yield this.waitForLndConnected(lndClient);
const backupPath = this.getBackupPath('lnd', lndClient.currency);
this.logger.verbose(`Writing initial ${lndClient.currency} LND channel backup to: ${backupPath}`);
const channelBackup = yield lndClient.exportAllChannelBackup();
this.writeBackup(backupPath, channelBackup);
lndClient.subscribeChannelBackups();
this.logger.info(`Listening to ${currency} LND channel backups`);
lndClient.on('channelBackup', (channelBackup) => {
this.logger.trace(`New ${lndClient.currency} channel backup`);
this.writeBackup(backupPath, channelBackup);
});
lndClient.on('channelBackupEnd', () => __awaiter(this, void 0, void 0, function* () {
this.logger.warn(`Lost subscription to ${lndClient.currency} channel backups - attempting to restore`);
// attempt to re-subscribe to lnd backups
yield this.waitForLndConnected(lndClient);
lndClient.subscribeChannelBackups();
this.logger.info(`Subscription to ${lndClient.currency} channel backups restored`);
}));
}
});
for (const currency in this.config.lnd) {
lndPromises.push(startLndSubscription(currency));
}
yield Promise.all(lndPromises);
});
this.startFilewatcher = (client, dbPath) => __awaiter(this, void 0, void 0, function* () {
const backupPath = this.getBackupPath(client);
if (fs_1.default.existsSync(dbPath)) {
this.logger.verbose(`Writing initial ${client} database backup to: ${backupPath}`);
const content = this.readDatabase(dbPath);
this.writeBackup(backupPath, content);
}
else {
this.logger.warn(`Could not find database file of ${client} at ${dbPath}, waiting for it to be created...`);
const dbDir = path_1.default.dirname(dbPath);
const dbFilename = path_1.default.basename(dbPath);
yield new Promise((resolve) => {
const dbCreateWatcher = fs_1.default.watch(dbDir, (_, filename) => {
if (filename === dbFilename) {
this.logger.info(`${client} database created at ${dbPath}`);
dbCreateWatcher.close();
resolve();
}
});
});
}
this.fileWatchers.push(fs_1.default.watch(dbPath, { persistent: true, recursive: false }, (event) => {
if (event === 'change') {
this.logger.trace(`${client} database changed`);
this.emit('changeDetected', client);
this.databaseChangedMap.set(client, true);
}
}));
this.logger.verbose(`Listening for changes to the ${client} database`);
});
this.readDatabase = (path) => {
const content = fs_1.default.readFileSync(path);
return content;
};
this.writeBackup = (backupPath, data) => {
try {
fs_1.default.writeFileSync(backupPath, data);
this.logger.trace(`new backup written to ${backupPath}`);
this.emit('newBackup', backupPath);
}
catch (error) {
this.logger.error(`Could not write backup file: ${error}`);
}
};
this.getBackupPath = (client, currency) => {
let clientName = client;
if (currency) {
clientName += `-${currency}`;
}
return path_1.default.join(this.backupDir, clientName);
};
}
}
exports.default = Backup;
//# sourceMappingURL=Backup.js.map