diff --git a/index.js b/index.js deleted file mode 100644 index 6d7bd24367583ef28c4e5bc0718e49985c73fe16..0000000000000000000000000000000000000000 --- a/index.js +++ /dev/null @@ -1,490 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const cli_1 = require("./app/cli"); -const stream = require("stream"); -const server_1 = require("./server"); -const path = require('path'); -const _ = require('underscore'); -const directory = require('./app/lib/system/directory'); -const constants = require('./app/lib/constants'); -const logger = require('./app/lib/logger').NewLogger('duniter'); -const configDependency = require('./app/modules/config'); -const wizardDependency = require('./app/modules/wizard'); -const resetDependency = require('./app/modules/reset'); -const checkConfDependency = require('./app/modules/check-config'); -const exportBcDependency = require('./app/modules/export-bc'); -const reapplyDependency = require('./app/modules/reapply'); -const revertDependency = require('./app/modules/revert'); -const daemonDependency = require('./app/modules/daemon'); -const pSignalDependency = require('./app/modules/peersignal'); -const routerDependency = require('./app/modules/router'); -const pluginDependency = require('./app/modules/plugin'); -const proverDependency = require('./app/modules/prover').ProverDependency; -class Stacks { - static quickRun(...args) { - return __awaiter(this, void 0, void 0, function* () { - const deps = Array.from(args).map((f, index) => { - const canonicalPath = path.resolve(f); - return { - name: 'duniter-quick-module-' + index, - required: require(canonicalPath) - }; - }); - const stack = Stacks.autoStack(deps); - let res; - try { - res = yield stack.executeStack(Stacks.quickRunGetArgs()); - } - catch (e) { - console.error(e); - } - Stacks.onRunDone(); - return res; - }); - } - static quickRunGetArgs() { - return process.argv.slice(); - } - static onRunDone() { - return Stacks.todoOnRunDone(); - } - static autoStack(priorityModules) { - const duniterModules = []; - let duniterDeps = []; - try { - const pjson = require(path.resolve('./package.json')); - // Look for compliant packages - const prodDeps = Object.keys(pjson.dependencies || {}); - const devDeps = Object.keys(pjson.devDependencies || {}); - duniterDeps = prodDeps.concat(devDeps); - } - catch (e) { } - for (const dep of duniterDeps) { - try { - const required = require(dep); - if (required.duniter) { - duniterModules.push({ - name: dep, - required - }); - } - } - catch (e) { } - } - // The final stack - return new Stack((priorityModules || []).concat(PRODUCTION_DEPENDENCIES).concat(duniterModules)); - } -} -Stacks.todoOnRunDone = () => process.exit(); -const MINIMAL_DEPENDENCIES = [ - { name: 'duniter-config', required: configDependency } -]; -const DEFAULT_DEPENDENCIES = MINIMAL_DEPENDENCIES.concat([ - { name: 'duniter-wizard', required: wizardDependency }, - { name: 'duniter-reset', required: resetDependency }, - { name: 'duniter-chkconf', required: checkConfDependency }, - { name: 'duniter-exportbc', required: exportBcDependency }, - { name: 'duniter-reapply', required: reapplyDependency }, - { name: 'duniter-revert', required: revertDependency }, - { name: 'duniter-daemon', required: daemonDependency }, - { name: 'duniter-psignal', required: pSignalDependency }, - { name: 'duniter-router', required: routerDependency }, - { name: 'duniter-plugin', required: pluginDependency }, - { name: 'duniter-prover', required: proverDependency } -]); -const PRODUCTION_DEPENDENCIES = DEFAULT_DEPENDENCIES.concat([]); -module.exports = function (home, memory, overConf) { - return new server_1.Server(home, memory, overConf); -}; -module.exports.statics = { - logger: logger, - /** - * Creates a new stack with minimal registrations only. - */ - minimalStack: () => new Stack(MINIMAL_DEPENDENCIES), - /** - * Creates a new stack with core registrations only. - */ - simpleStack: () => new Stack(DEFAULT_DEPENDENCIES), - /** - * Creates a new stack pre-registered with compliant modules found in package.json - */ - autoStack: (...args) => { - return Stacks.autoStack.apply(null, args); - }, - quickRun: (path) => { - return Stacks.quickRun(path); - }, - setOnRunDone: (f) => { - return Stacks.todoOnRunDone = f; - } -}; -class Stack { - constructor(dependencies) { - this.dependencies = dependencies; - this.definitions = []; - this.streams = { - input: [], - process: [], - output: [], - neutral: [] - }; - this.cli = cli_1.ExecuteCommand(); - this.configLoadingCallbacks = []; - this.configBeforeSaveCallbacks = []; - this.resetDataHooks = []; - this.resetConfigHooks = []; - this.INPUT = new InputStream(); - this.PROCESS = new ProcessStream(); - this.loaded = {}; - this.wizardTasks = {}; - // We register the initial dependencies right now. Others can be added thereafter. - for (const dep of dependencies) { - this.registerDependency(dep.required, dep.name); - } - } - // Part of modules API - getModule(name) { - return this.loaded[name]; - } - registerDependency(requiredObject, name) { - if (name && this.loaded[name]) { - // Do not try to load it twice - return; - } - this.loaded[name] = requiredObject; - const def = requiredObject.duniter; - this.definitions.push(def); - for (const opt of (def.cliOptions || [])) { - this.cli.addOption(opt.value, opt.desc, opt.parser); - } - for (const command of (def.cli || [])) { - this.cli.addCommand({ - name: command.name, - desc: command.desc - }, (...args) => this.processCommand.apply(this, [command].concat(args))); - } - /** - * Configuration injection - * ----------------------- - */ - if (def.config) { - if (def.config.onLoading) { - this.configLoadingCallbacks.push(def.config.onLoading); - } - // Before the configuration is saved, the module can make some injection/cleaning - if (def.config.beforeSave) { - this.configBeforeSaveCallbacks.push(def.config.beforeSave); - } - } - /** - * Reset data/config injection - * ----------------------- - */ - if (def.onReset) { - if (def.onReset.data) { - this.resetDataHooks.push(def.onReset.data); - } - // Before the configuration is saved, the module can make some injection/cleaning - if (def.onReset.config) { - this.resetConfigHooks.push(def.onReset.config); - } - } - /** - * Wizard injection - * ----------------------- - */ - if (def.wizard) { - const tasks = Object.keys(def.wizard); - for (const name of tasks) { - this.wizardTasks[name] = def.wizard[name]; - } - } - } - ; - processCommand(...args) { - return __awaiter(this, void 0, void 0, function* () { - const command = args[0]; - const program = args[1]; - const params = args.slice(2); - params.pop(); // Don't need the command argument - const dbName = program.mdb; - const dbHome = program.home; - const home = directory.getHome(dbName, dbHome); - if (command.logs === false) { - logger.mute(); - } - // Add log files for this instance (non-memory instances only) - if (!program.memory) { - logger.addHomeLogs(home, program.loglevel); - } - const server = new server_1.Server(home, program.memory === true, commandLineConf(program)); - // If ever the process gets interrupted - let isSaving = false; - process.on('SIGINT', () => __awaiter(this, void 0, void 0, function* () { - if (!isSaving) { - isSaving = true; - // Save DB - try { - yield server.disconnect(); - process.exit(); - } - catch (e) { - logger.error(e); - process.exit(3); - } - } - })); - // Config or Data reset hooks - server.resetDataHook = () => __awaiter(this, void 0, void 0, function* () { - for (const callback of this.resetDataHooks) { - yield callback(server.conf, program, logger, server.dal.confDAL); - } - }); - server.resetConfigHook = () => __awaiter(this, void 0, void 0, function* () { - for (const callback of this.resetConfigHooks) { - yield callback(server.conf, program, logger, server.dal.confDAL); - } - }); - // Initialize server (db connection, ...) - try { - server.onPluggedFSHook = () => __awaiter(this, void 0, void 0, function* () { - // Register the configuration hook for loading phase (overrides the loaded data) - server.dal.loadConfHook = (conf) => __awaiter(this, void 0, void 0, function* () { - // Loading injection - for (const callback of this.configLoadingCallbacks) { - yield callback(conf, program, logger, server.dal.confDAL); - } - }); - // Register the configuration hook for saving phase (overrides the saved data) - server.dal.saveConfHook = (conf) => __awaiter(this, void 0, void 0, function* () { - const clonedConf = _.clone(conf); - for (const callback of this.configBeforeSaveCallbacks) { - yield callback(clonedConf, program, logger, server.dal.confDAL); - } - return clonedConf; - }); - }); - yield server.plugFileSystem(); - const conf = yield server.loadConf(); - // Eventually change the log level - // Add log files for this instance (non-memory instances only) - if (!program.memory) { - logger.addHomeLogs(home, conf.loglevel); - } - // Auto-configuration default - yield configure(program, server, server.conf || {}); - // Autosave conf - try { - yield server.dal.saveConf(conf); - logger.debug("Configuration saved."); - } - catch (e) { - logger.error("Configuration could not be saved: " + e); - throw Error(e); - } - const daemon = server.getDaemon(); - if (command.preventIfRunning && daemon.status()) { - throw 'Your node is currently running. Please stop it and relaunch your command.'; - } - // First possible class of commands: post-config - if (command.onConfiguredExecute) { - return yield command.onConfiguredExecute(server, conf, program, params, this.wizardTasks, this); - } - // Second possible class of commands: post-service - yield server.initDAL(conf); - /** - * Service injection - * ----------------- - */ - for (const def of this.definitions) { - if (def.service) { - // To feed data coming from some I/O (network, disk, other module, ...) - if (def.service.input) { - this.streams.input.push(def.service.input(server, conf, logger)); - } - // To handle data this has been submitted by INPUT stream - if (def.service.process) { - this.streams.process.push(def.service.process(server, conf, logger)); - } - // To handle data this has been validated by PROCESS stream - if (def.service.output) { - this.streams.output.push(def.service.output(server, conf, logger)); - } - // Special service which does not stream anything particular (ex.: piloting the `server` object) - if (def.service.neutral) { - this.streams.neutral.push(def.service.neutral(server, conf, logger)); - } - } - } - // All inputs write to global INPUT stream - for (const module of this.streams.input) - module.pipe(this.INPUT); - // All processes read from global INPUT stream - for (const module of this.streams.process) - this.INPUT.pipe(module); - // All processes write to global PROCESS stream - for (const module of this.streams.process) - module.pipe(this.PROCESS); - // All ouputs read from global PROCESS stream - for (const module of this.streams.output) - this.PROCESS.pipe(module); - return yield command.onDatabaseExecute(server, conf, program, params, - // Start services and streaming between them - () => __awaiter(this, void 0, void 0, function* () { - const modules = this.streams.input.concat(this.streams.process).concat(this.streams.output).concat(this.streams.neutral); - yield Promise.all(modules.map((module) => module.startService())); - }), - // Stop services and streaming between them - () => __awaiter(this, void 0, void 0, function* () { - const modules = this.streams.input.concat(this.streams.process).concat(this.streams.output).concat(this.streams.neutral); - // Any streaming module must implement a `stopService` method - yield Promise.all(modules.map((module) => module.stopService())); - // // Stop reading inputs - // for (const module of streams.input) module.unpipe(); - // Stop reading from global INPUT - // INPUT.unpipe(); - // for (const module of streams.process) module.unpipe(); - // // Stop reading from global PROCESS - // PROCESS.unpipe(); - }), this); - } - catch (e) { - server.disconnect(); - throw e; - } - }); - } - executeStack(argv) { - // Trace these errors - process.on('unhandledRejection', (reason) => { - logger.error('Unhandled rejection: ' + reason); - logger.error(reason); - }); - // Executes the command - return this.cli.execute(argv); - } -} -function commandLineConf(program, conf = {}) { - conf = conf || {}; - conf.sync = conf.sync || {}; - const cli = { - currency: program.currency, - cpu: program.cpu, - server: { - port: program.port, - }, - db: { - mport: program.mport, - mdb: program.mdb, - home: program.home - }, - logs: { - http: program.httplogs, - nohttp: program.nohttplogs - }, - endpoints: [], - rmEndpoints: [], - isolate: program.isolate, - forksize: program.forksize, - nofork: program.nofork, - timeout: program.timeout - }; - // Update conf - if (cli.currency) - conf.currency = cli.currency; - if (cli.server.port) - conf.port = cli.server.port; - if (cli.cpu) - conf.cpu = Math.max(0.01, Math.min(1.0, cli.cpu)); - if (cli.logs.http) - conf.httplogs = true; - if (cli.logs.nohttp) - conf.httplogs = false; - if (cli.db.mport) - conf.mport = cli.db.mport; - if (cli.db.home) - conf.home = cli.db.home; - if (cli.db.mdb) - conf.mdb = cli.db.mdb; - if (cli.isolate) - conf.isolate = cli.isolate; - if (cli.timeout) - conf.timeout = cli.timeout; - if (cli.forksize != null) - conf.forksize = cli.forksize; - return conf; -} -function configure(program, server, conf) { - return __awaiter(this, void 0, void 0, function* () { - if (typeof server == "string" || typeof conf == "string") { - throw constants.ERRORS.CLI_CALLERR_CONFIG; - } - // Try to add an endpoint if provided - if (program.addep) { - if (conf.endpoints.indexOf(program.addep) === -1) { - conf.endpoints.push(program.addep); - } - // Remove it from "to be removed" list - const indexInRemove = conf.rmEndpoints.indexOf(program.addep); - if (indexInRemove !== -1) { - conf.rmEndpoints.splice(indexInRemove, 1); - } - } - // Try to remove an endpoint if provided - if (program.remep) { - if (conf.rmEndpoints.indexOf(program.remep) === -1) { - conf.rmEndpoints.push(program.remep); - } - // Remove it from "to be added" list - const indexInToAdd = conf.endpoints.indexOf(program.remep); - if (indexInToAdd !== -1) { - conf.endpoints.splice(indexInToAdd, 1); - } - } - }); -} -/** - * InputStream is a special stream this filters what passes in. - * Only DUP-like documents should be treated by the processing tools, to avoid JSON injection and save CPU cycles. - * @constructor - */ -class InputStream extends stream.Transform { - constructor() { - super({ objectMode: true }); - } - _write(str, enc, done) { - if (typeof str === 'string') { - // Keep only strings - const matches = str.match(/Type: (.*)\n/); - if (matches && matches[1].match(/(Block|Membership|Identity|Certification|Transaction|Peer)/)) { - const type = matches[1].toLowerCase(); - this.push({ type, doc: str }); - } - } - done && done(); - } - ; -} -class ProcessStream extends stream.Transform { - constructor() { - super({ objectMode: true }); - } - _write(obj, enc, done) { - // Never close the stream - if (obj !== undefined && obj !== null) { - this.push(obj); - } - done && done(); - } - ; -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/server.js b/server.js deleted file mode 100644 index 143f5d22ed0c3996e1972cdb55a1a9df3c0b1723..0000000000000000000000000000000000000000 --- a/server.js +++ /dev/null @@ -1,503 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const IdentityService_1 = require("./app/service/IdentityService"); -const MembershipService_1 = require("./app/service/MembershipService"); -const PeeringService_1 = require("./app/service/PeeringService"); -const BlockchainService_1 = require("./app/service/BlockchainService"); -const TransactionsService_1 = require("./app/service/TransactionsService"); -const ConfDTO_1 = require("./app/lib/dto/ConfDTO"); -const fileDAL_1 = require("./app/lib/dal/fileDAL"); -const DuniterBlockchain_1 = require("./app/lib/blockchain/DuniterBlockchain"); -const SqlBlockchain_1 = require("./app/lib/blockchain/SqlBlockchain"); -const stream = require("stream"); -const path = require('path'); -const _ = require('underscore'); -const archiver = require('archiver'); -const unzip = require('unzip2'); -const fs = require('fs'); -const daemonize = require("daemonize2"); -const parsers = require('duniter-common').parsers; -const constants = require('./app/lib/constants'); -const jsonpckg = require('./package.json'); -const keyring = require('duniter-common').keyring; -const directory = require('./app/lib/system/directory'); -const rawer = require('duniter-common').rawer; -const logger = require('./app/lib/logger').NewLogger('server'); -class Server extends stream.Duplex { - constructor(home, memoryOnly, overrideConf) { - super({ objectMode: true }); - this.overrideConf = overrideConf; - this.home = home; - this.conf = ConfDTO_1.ConfDTO.mock(); - this.version = jsonpckg.version; - this.logger = logger; - this.rawer = rawer; - this.paramsP = directory.getHomeParams(memoryOnly, home); - this.MerkleService = require("./app/lib/helpers/merkle"); - this.IdentityService = new IdentityService_1.IdentityService(); - this.MembershipService = new MembershipService_1.MembershipService(); - this.PeeringService = new PeeringService_1.PeeringService(this); - this.BlockchainService = new BlockchainService_1.BlockchainService(this); - this.TransactionsService = new TransactionsService_1.TransactionService(); - // Create document mapping - this.documentsMapping = { - 'identity': { action: (obj) => this.IdentityService.submitIdentity(obj), parser: parsers.parseIdentity }, - 'certification': { action: (obj) => this.IdentityService.submitCertification(obj), parser: parsers.parseCertification }, - 'revocation': { action: (obj) => this.IdentityService.submitRevocation(obj), parser: parsers.parseRevocation }, - 'membership': { action: (obj) => this.MembershipService.submitMembership(obj), parser: parsers.parseMembership }, - 'peer': { action: (obj) => this.PeeringService.submitP(obj), parser: parsers.parsePeer }, - 'transaction': { action: (obj) => this.TransactionsService.processTx(obj), parser: parsers.parseTransaction }, - 'block': { action: (obj) => this.BlockchainService.submitBlock(obj, true, constants.NO_FORK_ALLOWED), parser: parsers.parseBlock } - }; - } - // Unused, but made mandatory by Duplex interface - _read() { } - _write(obj, enc, writeDone) { - return this.submit(obj, false, () => writeDone); - } - /** - * Facade method to control what is pushed to the stream (we don't want it to be closed) - * @param obj An object to be pushed to the stream. - */ - streamPush(obj) { - if (obj) { - this.push(obj); - } - } - getBcContext() { - return this.BlockchainService.getContext(); - } - plugFileSystem() { - return __awaiter(this, void 0, void 0, function* () { - logger.debug('Plugging file system...'); - const params = yield this.paramsP; - this.dal = new fileDAL_1.FileDAL(params); - yield this.onPluggedFSHook(); - }); - } - unplugFileSystem() { - return __awaiter(this, void 0, void 0, function* () { - logger.debug('Unplugging file system...'); - yield this.dal.close(); - }); - } - loadConf(useDefaultConf = false) { - return __awaiter(this, void 0, void 0, function* () { - logger.debug('Loading conf...'); - this.conf = yield this.dal.loadConf(this.overrideConf, useDefaultConf); - // Default values - this.conf.remoteipv6 = this.conf.remoteipv6 === undefined ? this.conf.ipv6 : this.conf.remoteipv6; - this.conf.remoteport = this.conf.remoteport === undefined ? this.conf.port : this.conf.remoteport; - this.conf.c = this.conf.c === undefined ? constants.CONTRACT.DEFAULT.C : this.conf.c; - this.conf.dt = this.conf.dt === undefined ? constants.CONTRACT.DEFAULT.DT : this.conf.dt; - this.conf.ud0 = this.conf.ud0 === undefined ? constants.CONTRACT.DEFAULT.UD0 : this.conf.ud0; - this.conf.stepMax = this.conf.stepMax === undefined ? constants.CONTRACT.DEFAULT.STEPMAX : this.conf.stepMax; - this.conf.sigPeriod = this.conf.sigPeriod === undefined ? constants.CONTRACT.DEFAULT.SIGPERIOD : this.conf.sigPeriod; - this.conf.msPeriod = this.conf.msPeriod === undefined ? constants.CONTRACT.DEFAULT.MSPERIOD : this.conf.msPeriod; - this.conf.sigStock = this.conf.sigStock === undefined ? constants.CONTRACT.DEFAULT.SIGSTOCK : this.conf.sigStock; - this.conf.sigWindow = this.conf.sigWindow === undefined ? constants.CONTRACT.DEFAULT.SIGWINDOW : this.conf.sigWindow; - this.conf.sigValidity = this.conf.sigValidity === undefined ? constants.CONTRACT.DEFAULT.SIGVALIDITY : this.conf.sigValidity; - this.conf.msValidity = this.conf.msValidity === undefined ? constants.CONTRACT.DEFAULT.MSVALIDITY : this.conf.msValidity; - this.conf.sigQty = this.conf.sigQty === undefined ? constants.CONTRACT.DEFAULT.SIGQTY : this.conf.sigQty; - this.conf.idtyWindow = this.conf.idtyWindow === undefined ? constants.CONTRACT.DEFAULT.IDTYWINDOW : this.conf.idtyWindow; - this.conf.msWindow = this.conf.msWindow === undefined ? constants.CONTRACT.DEFAULT.MSWINDOW : this.conf.msWindow; - this.conf.xpercent = this.conf.xpercent === undefined ? constants.CONTRACT.DEFAULT.X_PERCENT : this.conf.xpercent; - this.conf.percentRot = this.conf.percentRot === undefined ? constants.CONTRACT.DEFAULT.PERCENTROT : this.conf.percentRot; - this.conf.powDelay = this.conf.powDelay === undefined ? constants.CONTRACT.DEFAULT.POWDELAY : this.conf.powDelay; - this.conf.avgGenTime = this.conf.avgGenTime === undefined ? constants.CONTRACT.DEFAULT.AVGGENTIME : this.conf.avgGenTime; - this.conf.dtDiffEval = this.conf.dtDiffEval === undefined ? constants.CONTRACT.DEFAULT.DTDIFFEVAL : this.conf.dtDiffEval; - this.conf.medianTimeBlocks = this.conf.medianTimeBlocks === undefined ? constants.CONTRACT.DEFAULT.MEDIANTIMEBLOCKS : this.conf.medianTimeBlocks; - this.conf.rootoffset = this.conf.rootoffset === undefined ? 0 : this.conf.rootoffset; - this.conf.forksize = this.conf.forksize === undefined ? constants.BRANCHES.DEFAULT_WINDOW_SIZE : this.conf.forksize; - // 1.3.X: the msPeriod = msWindow - this.conf.msPeriod = this.conf.msPeriod === undefined ? this.conf.msWindow : this.conf.msPeriod; - // Default keypair - if (!this.conf.pair || !this.conf.pair.pub || !this.conf.pair.sec) { - // Create a random key - this.conf.pair = keyring.randomKey().json(); - } - // Extract key pair - this.keyPair = keyring.Key(this.conf.pair.pub, this.conf.pair.sec); - this.sign = this.keyPair.sign; - // Blockchain object - this.blockchain = new DuniterBlockchain_1.DuniterBlockchain(new SqlBlockchain_1.SQLBlockchain(this.dal), this.dal); - // Update services - this.IdentityService.setConfDAL(this.conf, this.dal); - this.MembershipService.setConfDAL(this.conf, this.dal); - this.PeeringService.setConfDAL(this.conf, this.dal, this.keyPair); - this.BlockchainService.setConfDAL(this.conf, this.dal, this.keyPair); - this.TransactionsService.setConfDAL(this.conf, this.dal); - return this.conf; - }); - } - initWithDAL() { - return __awaiter(this, void 0, void 0, function* () { - yield this.plugFileSystem(); - yield this.loadConf(); - yield this.initDAL(); - return this; - }); - } - submit(obj, isInnerWrite = false, done = null) { - return __awaiter(this, void 0, void 0, function* () { - if (!obj.documentType) { - throw 'Document type not given'; - } - try { - const action = this.documentsMapping[obj.documentType].action; - let res; - if (typeof action == 'function') { - // Handle the incoming object - res = yield action(obj); - } - else { - throw 'Unknown document type \'' + obj.documentType + '\''; - } - if (res) { - // Only emit valid documents - this.emit(obj.documentType, _.clone(res)); - this.streamPush(_.clone(res)); - } - if (done) { - isInnerWrite ? done(null, res) : done(); - } - return res; - } - catch (err) { - if (err && !err.uerr) { - // Unhandled error, display it - logger.debug('Document write error: ', err); - } - if (done) { - isInnerWrite ? done(err, null) : done(); - } - else { - throw err; - } - } - }); - } - submitP(obj, isInnerWrite) { - return this.submit(obj, isInnerWrite); - } - initDAL(conf = null) { - return __awaiter(this, void 0, void 0, function* () { - yield this.dal.init(this.conf); - // Maintenance - let head_1 = yield this.dal.bindexDAL.head(1); - if (head_1) { - // Case 1: b_index < block - yield this.dal.blockDAL.exec('DELETE FROM block WHERE NOT fork AND number > ' + head_1.number); - // Case 2: b_index > block - const current = yield this.dal.blockDAL.getCurrent(); - const nbBlocksToRevert = (head_1.number - current.number); - for (let i = 0; i < nbBlocksToRevert; i++) { - yield this.revert(); - } - } - }); - } - recomputeSelfPeer() { - return this.PeeringService.generateSelfPeer(this.conf, 0); - } - getCountOfSelfMadePoW() { - return this.BlockchainService.getCountOfSelfMadePoW(); - } - isServerMember() { - return this.BlockchainService.isMember(); - } - checkConfig() { - if (!this.conf.pair) { - throw new Error('No keypair was given.'); - } - } - resetHome() { - return __awaiter(this, void 0, void 0, function* () { - const params = yield this.paramsP; - const myFS = params.fs; - const rootPath = params.home; - const existsDir = yield myFS.exists(rootPath); - if (existsDir) { - yield myFS.removeTree(rootPath); - } - }); - } - resetAll(done) { - return __awaiter(this, void 0, void 0, function* () { - yield this.resetDataHook(); - yield this.resetConfigHook(); - const files = ['stats', 'cores', 'current', directory.DUNITER_DB_NAME, directory.DUNITER_DB_NAME + '.db', directory.DUNITER_DB_NAME + '.log', directory.WOTB_FILE, 'export.zip', 'import.zip', 'conf']; - const dirs = ['blocks', 'blockchain', 'ud_history', 'branches', 'certs', 'txs', 'cores', 'sources', 'links', 'ms', 'identities', 'peers', 'indicators', 'leveldb']; - return this.resetFiles(files, dirs, done); - }); - } - resetData(done = null) { - return __awaiter(this, void 0, void 0, function* () { - yield this.resetDataHook(); - const files = ['stats', 'cores', 'current', directory.DUNITER_DB_NAME, directory.DUNITER_DB_NAME + '.db', directory.DUNITER_DB_NAME + '.log', directory.WOTB_FILE]; - const dirs = ['blocks', 'ud_history', 'branches', 'certs', 'txs', 'cores', 'sources', 'links', 'ms', 'identities', 'peers', 'indicators', 'leveldb']; - yield this.resetFiles(files, dirs, done); - }); - } - resetConf(done) { - return __awaiter(this, void 0, void 0, function* () { - yield this.resetConfigHook(); - const files = ['conf']; - const dirs = []; - return this.resetFiles(files, dirs, done); - }); - } - resetStats(done) { - const files = ['stats']; - const dirs = ['ud_history']; - return this.resetFiles(files, dirs, done); - } - resetPeers(done) { - return this.dal.resetPeers(); - } - exportAllDataAsZIP() { - return __awaiter(this, void 0, void 0, function* () { - const params = yield this.paramsP; - const rootPath = params.home; - const myFS = params.fs; - const archive = archiver('zip'); - if (yield myFS.exists(path.join(rootPath, 'indicators'))) { - archive.directory(path.join(rootPath, 'indicators'), '/indicators', undefined, { name: 'indicators' }); - } - const files = ['duniter.db', 'stats.json', 'wotb.bin']; - for (const file of files) { - if (yield myFS.exists(path.join(rootPath, file))) { - archive.file(path.join(rootPath, file), { name: file }); - } - } - archive.finalize(); - return archive; - }); - } - importAllDataFromZIP(zipFile) { - return __awaiter(this, void 0, void 0, function* () { - const params = yield this.paramsP; - yield this.resetData(); - const output = unzip.Extract({ path: params.home }); - fs.createReadStream(zipFile).pipe(output); - return new Promise((resolve, reject) => { - output.on('error', reject); - output.on('close', resolve); - }); - }); - } - cleanDBData() { - return __awaiter(this, void 0, void 0, function* () { - yield this.dal.cleanCaches(); - this.dal.wotb.resetWoT(); - const files = ['stats', 'cores', 'current', directory.DUNITER_DB_NAME, directory.DUNITER_DB_NAME + '.db', directory.DUNITER_DB_NAME + '.log']; - const dirs = ['blocks', 'ud_history', 'branches', 'certs', 'txs', 'cores', 'sources', 'links', 'ms', 'identities', 'peers', 'indicators', 'leveldb']; - return this.resetFiles(files, dirs); - }); - } - resetFiles(files, dirs, done = null) { - return __awaiter(this, void 0, void 0, function* () { - try { - const params = yield this.paramsP; - const myFS = params.fs; - const rootPath = params.home; - for (const fName of files) { - // JSON file? - const existsJSON = yield myFS.exists(rootPath + '/' + fName + '.json'); - if (existsJSON) { - const theFilePath = rootPath + '/' + fName + '.json'; - yield myFS.remove(theFilePath); - if (yield myFS.exists(theFilePath)) { - throw Error('Failed to delete file "' + theFilePath + '"'); - } - } - else { - // Normal file? - const normalFile = path.join(rootPath, fName); - const existsFile = yield myFS.exists(normalFile); - if (existsFile) { - yield myFS.remove(normalFile); - if (yield myFS.exists(normalFile)) { - throw Error('Failed to delete file "' + normalFile + '"'); - } - } - } - } - for (const dirName of dirs) { - const existsDir = yield myFS.exists(rootPath + '/' + dirName); - if (existsDir) { - yield myFS.removeTree(rootPath + '/' + dirName); - if (yield myFS.exists(rootPath + '/' + dirName)) { - throw Error('Failed to delete folder "' + rootPath + '/' + dirName + '"'); - } - } - } - done && done(); - } - catch (e) { - done && done(e); - throw e; - } - }); - } - disconnect() { - return Promise.resolve(this.dal && this.dal.close()); - } - revert() { - return this.BlockchainService.revertCurrentBlock(); - } - revertTo(number) { - return __awaiter(this, void 0, void 0, function* () { - const current = yield this.BlockchainService.current(); - for (let i = 0, count = current.number - number; i < count; i++) { - yield this.BlockchainService.revertCurrentBlock(); - } - if (current.number <= number) { - logger.warn('Already reached'); - } - }); - } - reapplyTo(number) { - return __awaiter(this, void 0, void 0, function* () { - const current = yield this.BlockchainService.current(); - if (current.number == number) { - logger.warn('Already reached'); - } - else { - for (let i = 0, count = number - current.number; i < count; i++) { - yield this.BlockchainService.applyNextAvailableFork(); - } - } - }); - } - singleWritePromise(obj) { - return this.submit(obj); - } - writeRaw(raw, type) { - return __awaiter(this, void 0, void 0, function* () { - const parser = this.documentsMapping[type] && this.documentsMapping[type].parser; - const obj = parser.syncWrite(raw, logger); - return yield this.singleWritePromise(obj); - }); - } - /***************** - * DAEMONIZATION - ****************/ - /** - * Get the daemon handle. Eventually give arguments to launch a new daemon. - * @param overrideCommand The new command to launch. - * @param insteadOfCmd The current command to be replaced by `overrideCommand` command. - * @returns {*} The daemon handle. - */ - getDaemon(overrideCommand, insteadOfCmd) { - const mainModule = process.argv[1]; - const cwd = path.resolve(mainModule, '../..'); - const argv = this.getCommand(overrideCommand, insteadOfCmd); - return daemonize.setup({ - main: mainModule, - name: directory.INSTANCE_NAME, - pidfile: path.join(directory.INSTANCE_HOME, "app.pid"), - argv, - cwd - }); - } - /** - * Return current script full command arguments except the two firsts (which are node executable + js file). - * If the two optional `cmd` and `insteadOfCmd` parameters are given, replace `insteadOfCmd`'s value by `cmd` in - * the script arguments. - * - * Ex: - * * process.argv: ['/usr/bin/node', '/opt/duniter/sources/bin/duniter', 'restart', '--mdb', 'g1'] - * - * Then `getCommand('direct_start', 'restart') will return: - * - * * ['direct_start', '--mdb', 'g1'] - * - * This new array is what will be given to a *fork* of current script, resulting in a new process with: - * - * * process.argv: ['/usr/bin/node', '/opt/duniter/sources/bin/duniter', 'direct_start', '--mdb', 'g1'] - * - * @param cmd - * @param insteadOfCmd - * @returns {*} - */ - getCommand(cmd, insteadOfCmd) { - if (insteadOfCmd) { - // Return the same command args, except the command `insteadOfCmd` which is replaced by `cmd` - return process.argv.slice(2).map((arg) => { - if (arg == insteadOfCmd) { - return cmd; - } - else { - return arg; - } - }); - } - else { - // Return the exact same args (generally for stop/status commands) - return process.argv.slice(2); - } - } - /** - * Retrieve the last linesQuantity lines from the log file. - * @param linesQuantity - */ - getLastLogLines(linesQuantity) { - return this.dal.getLogContent(linesQuantity); - } - /***************** - * MODULES PLUGS - ****************/ - /** - * Default endpoint. To be overriden by a module to specify another endpoint value (for ex. BMA). - */ - getMainEndpoint() { - return Promise.resolve('DEFAULT_ENDPOINT'); - } - /** - * Default WoT incoming data for new block. To be overriden by a module. - */ - generatorGetJoinData() { - return Promise.resolve({}); - } - /** - * Default WoT incoming certifications for new block, filtering wrong certs. To be overriden by a module. - */ - generatorComputeNewCerts() { - return Promise.resolve({}); - } - /** - * Default WoT transforming method for certs => links. To be overriden by a module. - */ - generatorNewCertsToLinks() { - return Promise.resolve({}); - } - /** - * Default hook on file system plugging. To be overriden by module system. - */ - onPluggedFSHook() { - return Promise.resolve({}); - } - /** - * Default hook on data reset. To be overriden by module system. - */ - resetDataHook() { - return Promise.resolve({}); - } - /** - * Default hook on data reset. To be overriden by module system. - */ - resetConfigHook() { - return Promise.resolve({}); - } -} -exports.Server = Server; -//# sourceMappingURL=server.js.map \ No newline at end of file