From 4938e5dd78f0b6c65702970c82101242105c4893 Mon Sep 17 00:00:00 2001 From: Benoit Lavenier <benoit.lavenier@e-is.pro> Date: Mon, 5 Jun 2023 13:34:35 +0200 Subject: [PATCH] fix(ts) Prepare for node 16+ upgrade (e.g. set Promise type) --- app/cli.ts | 4 +- app/lib/blockchain/DuniterBlockchain.ts | 6 +- app/lib/blockchain/Switcher.ts | 5 +- app/lib/common-libs/constants.ts | 30 ++++++--- app/lib/common-libs/manual-promise.ts | 13 ++-- app/lib/common-libs/timeout-promise.ts | 4 +- app/lib/dal/drivers/LevelDBDriver.ts | 4 +- app/lib/dal/drivers/SQLiteDriver.ts | 4 +- app/lib/dal/fileDAL.ts | 44 +++++-------- app/lib/dal/indexDAL/abstract/DividendDAO.ts | 4 +- app/lib/dal/indexDAL/abstract/GenericDAO.ts | 1 - app/lib/dal/indexDAL/abstract/PeerDAO.ts | 1 - app/lib/dal/indexDAL/abstract/SIndexDAO.ts | 4 +- app/lib/dal/indexDAL/abstract/TxsDAO.ts | 5 +- app/lib/dal/indexDAL/abstract/WalletDAO.ts | 1 - .../dal/indexDAL/leveldb/LevelDBBlockchain.ts | 6 +- app/lib/dal/indexDAL/leveldb/LevelDBCindex.ts | 6 +- .../dal/indexDAL/leveldb/LevelDBDividend.ts | 10 +-- app/lib/dal/indexDAL/leveldb/LevelDBIindex.ts | 12 ++-- app/lib/dal/indexDAL/leveldb/LevelDBMindex.ts | 6 +- app/lib/dal/indexDAL/leveldb/LevelDBSindex.ts | 17 ++--- app/lib/dal/indexDAL/leveldb/LevelDBTable.ts | 9 ++- .../indexers/LevelMIndexExpiresOnIndexer.ts | 6 +- .../indexers/LevelMIndexRevokesOnIndexer.ts | 6 +- app/lib/dal/indexDAL/sqlite/SqliteDividend.ts | 10 +-- app/lib/dal/indexDAL/sqlite/SqliteIIndex.ts | 6 +- app/lib/dal/indexDAL/sqlite/SqliteMIndex.ts | 6 +- app/lib/dal/indexDAL/sqlite/SqlitePeers.ts | 14 ++-- app/lib/dal/indexDAL/sqlite/SqliteSIndex.ts | 10 +-- app/lib/dal/indexDAL/sqlite/SqliteTable.ts | 42 ++++++++---- app/lib/dal/sqliteDAL/MetaDAL.ts | 4 +- app/lib/dto/CertificationDTO.ts | 6 +- app/lib/dto/ConfDTO.ts | 7 +- app/lib/dto/TransactionDTO.ts | 7 +- app/lib/indexer.ts | 18 +++-- app/lib/rules/global_rules.ts | 7 +- app/lib/rules/local_rules.ts | 32 +-------- app/lib/streams/multicaster.ts | 2 +- app/lib/system/directory.ts | 4 +- app/lib/wizard.ts | 2 +- app/modules/bma/index.ts | 8 ++- app/modules/bma/lib/constants.ts | 9 ++- app/modules/bma/lib/controllers/blockchain.ts | 12 ++-- app/modules/bma/lib/controllers/wot.ts | 47 +++++++------ app/modules/bma/lib/upnp.ts | 2 +- app/modules/config.ts | 5 +- app/modules/crawler/index.ts | 21 +++--- app/modules/crawler/lib/crawler.ts | 9 +-- app/modules/crawler/lib/req2fwd.ts | 2 +- app/modules/crawler/lib/sync.ts | 2 +- .../crawler/lib/sync/BMARemoteContacter.ts | 4 +- .../crawler/lib/sync/FsSyncDownloader.ts | 6 +- .../crawler/lib/sync/IRemoteContacter.ts | 4 +- .../crawler/lib/sync/P2PSyncDownloader.ts | 29 +++++--- .../crawler/lib/sync/RemoteSynchronizer.ts | 9 ++- .../crawler/lib/sync/WS2PRemoteContacter.ts | 4 +- .../crawler/lib/sync/p2p/p2p-candidate.ts | 11 ++-- .../crawler/lib/sync/v2/ValidatorStream.ts | 2 +- app/modules/daemon.ts | 14 ++-- app/modules/export-bc.ts | 3 +- app/modules/keypair/index.ts | 13 ++-- app/modules/keypair/lib/scrypt.ts | 37 ++++++----- app/modules/plugin.ts | 16 ++--- app/modules/prover/index.ts | 66 +++++++++---------- app/modules/prover/lib/blockGenerator.ts | 27 ++++---- app/modules/prover/lib/permanentProver.ts | 53 ++++++++------- app/modules/prover/lib/proof.ts | 12 ++-- app/modules/prover/lib/prover.ts | 2 +- app/modules/reapply.ts | 3 +- app/modules/reset.ts | 3 +- app/modules/revert.ts | 6 +- app/modules/upnp-provider.ts | 4 +- app/modules/wizard.ts | 3 +- app/modules/ws2p/lib/WS2PCluster.ts | 44 ++++--------- app/modules/ws2p/lib/WS2PConnection.ts | 17 ++--- app/modules/ws2p/lib/WS2PServer.ts | 2 +- .../ws2p/lib/impl/WS2PReqMapperByServer.ts | 6 +- app/service/BlockchainService.ts | 8 +-- app/service/IdentityService.ts | 17 +++-- app/service/MembershipService.ts | 5 +- app/service/PeeringService.ts | 10 ++- test/fast/modules/ws2p/single_write.ts | 4 +- test/fast/prover/prover-pow-1-cluster.ts | 2 +- .../fork-resolution/register-fork-blocks.ts | 2 +- test/integration/misc/http-api.ts | 2 +- .../proof-of-work/continuous-proof.ts | 6 +- test/integration/tools/test-until.ts | 2 +- test/integration/tools/toolbox.ts | 12 ++-- 88 files changed, 468 insertions(+), 504 deletions(-) diff --git a/app/cli.ts b/app/cli.ts index f0bb646c8..ca3e8db1c 100644 --- a/app/cli.ts +++ b/app/cli.ts @@ -34,10 +34,10 @@ export const ExecuteCommand = () => { // Callback for command rejection let onReject: any = () => - Promise.reject(Error("Uninitilized rejection throw")); + Promise.reject(Error("Uninitialized rejection throw")); // Command execution promise - const currentCommand = new Promise((resolve, reject) => { + const currentCommand = new Promise<void>((resolve, reject) => { onResolve = resolve; onReject = reject; }); diff --git a/app/lib/blockchain/DuniterBlockchain.ts b/app/lib/blockchain/DuniterBlockchain.ts index 063a09505..2dee3c829 100644 --- a/app/lib/blockchain/DuniterBlockchain.ts +++ b/app/lib/blockchain/DuniterBlockchain.ts @@ -520,10 +520,8 @@ export class DuniterBlockchain { await dal.iindexDAL.removeBlock(blockstamp); await dal.cindexDAL.removeBlock(blockstamp); await dal.sindexDAL.removeBlock(blockstamp); - const { - createdUDsDestroyedByRevert, - consumedUDsRecoveredByRevert, - } = await dal.dividendDAL.revertUDs(number); + const { createdUDsDestroyedByRevert, consumedUDsRecoveredByRevert } = + await dal.dividendDAL.revertUDs(number); // Then: normal updates const previousBlock = await dal.getFullBlockOf(number - 1); diff --git a/app/lib/blockchain/Switcher.ts b/app/lib/blockchain/Switcher.ts index ebeb59acc..d8387a7bc 100644 --- a/app/lib/blockchain/Switcher.ts +++ b/app/lib/blockchain/Switcher.ts @@ -170,9 +170,8 @@ export class Switcher<T extends SwitchBlock> { previousHash ); if (previous) { - knownForkBlocks[ - BlockDTO.fromJSONObject(previous).blockstamp - ] = true; + knownForkBlocks[BlockDTO.fromJSONObject(previous).blockstamp] = + true; const alreadyKnownInvalidBlock = this.invalidForks.indexOf( [previous.number, previous.hash].join("-") diff --git a/app/lib/common-libs/constants.ts b/app/lib/common-libs/constants.ts index 91266e0aa..0cda34dbb 100755 --- a/app/lib/common-libs/constants.ts +++ b/app/lib/common-libs/constants.ts @@ -54,16 +54,26 @@ const CONDITIONS = CSV_INTEGER + "\\))))*"; const CONDITION_SIG_PUBKEY = "SIG\\((" + PUBKEY + ")\\)"; -const BMA_REGEXP = /^BASIC_MERKLED_API( ([a-z_][a-z0-9-_.]*))?( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))( (\/.+))?$/; -const BMAS_REGEXP = /^BMAS( ([a-z_][a-z0-9-_.]*))?( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))( (\/.+))?$/; -const BMATOR_REGEXP = /^BMATOR( ([a-z0-9]{16})\.onion)( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))$/; -const WS2P_REGEXP = /^WS2P (?:[1-9][0-9]* )?([a-f0-9]{8}) ([a-z_][a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+) ([0-9]+)(?: (.+))?$/; -const WS2P_V2_REGEXP = /^WS2P ([1-9][0-9]*) ([a-f0-9]{8}) ([a-z_][a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+) ([0-9]+)(?: (.+))?$/; -const WS2PTOR_REGEXP = /^WS2PTOR (?:[1-9][0-9]* )?([a-f0-9]{8}) ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion) ([0-9]+)(?: (.+))?$/; -const WS2PTOR_V2_REGEXP = /^WS2PTOR ([1-9][0-9]*) ([a-f0-9]{8}) ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion) ([0-9]+)(?: (.+))?$/; -const WS_FULL_ADDRESS_ONION_REGEX = /^(?:wss?:\/\/)(?:www\.)?([0-9a-z]{16}\.onion)(:[0-9]+)?$/; -const IPV4_REGEXP = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/; -const IPV6_REGEXP = /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/; +const BMA_REGEXP = + /^BASIC_MERKLED_API( ([a-z_][a-z0-9-_.]*))?( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))( (\/.+))?$/; +const BMAS_REGEXP = + /^BMAS( ([a-z_][a-z0-9-_.]*))?( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))( (\/.+))?$/; +const BMATOR_REGEXP = + /^BMATOR( ([a-z0-9]{16})\.onion)( ([0-9.]+))?( ([0-9a-f:]+))?( ([0-9]+))$/; +const WS2P_REGEXP = + /^WS2P (?:[1-9][0-9]* )?([a-f0-9]{8}) ([a-z_][a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+) ([0-9]+)(?: (.+))?$/; +const WS2P_V2_REGEXP = + /^WS2P ([1-9][0-9]*) ([a-f0-9]{8}) ([a-z_][a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+) ([0-9]+)(?: (.+))?$/; +const WS2PTOR_REGEXP = + /^WS2PTOR (?:[1-9][0-9]* )?([a-f0-9]{8}) ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion) ([0-9]+)(?: (.+))?$/; +const WS2PTOR_V2_REGEXP = + /^WS2PTOR ([1-9][0-9]*) ([a-f0-9]{8}) ([a-z0-9-_.]*|[0-9.]+|[0-9a-f:]+.onion) ([0-9]+)(?: (.+))?$/; +const WS_FULL_ADDRESS_ONION_REGEX = + /^(?:wss?:\/\/)(?:www\.)?([0-9a-z]{16}\.onion)(:[0-9]+)?$/; +const IPV4_REGEXP = + /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/; +const IPV6_REGEXP = + /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/; const HOST_ONION_REGEX = /^(?:www\.)?([0-9a-z]{16}\.onion)$/; const MAXIMUM_LEN_OF_COMPACT_TX = 100; diff --git a/app/lib/common-libs/manual-promise.ts b/app/lib/common-libs/manual-promise.ts index 24d6382aa..ff2a9c761 100644 --- a/app/lib/common-libs/manual-promise.ts +++ b/app/lib/common-libs/manual-promise.ts @@ -12,14 +12,11 @@ export interface ManualPromise<T> extends Querable<T> { * @returns {ManualPromise<T>} */ export function newManualPromise<T>() { - let resolveCb: (data: T) => void = () => {}; - let rejectCb: (error: Error) => void = () => {}; - const p = new Promise((res, rej) => { - resolveCb = res; - rejectCb = rej; + let q: ManualPromise<T>; + const p = new Promise<T>((resolve, reject) => { + q.resolve = resolve; + q.reject = reject; }); - const q: ManualPromise<T> = querablePromise(p); - q.resolve = resolveCb; - q.reject = rejectCb; + q = querablePromise(p); return q; } diff --git a/app/lib/common-libs/timeout-promise.ts b/app/lib/common-libs/timeout-promise.ts index eab7d91f9..08c6cce2b 100644 --- a/app/lib/common-libs/timeout-promise.ts +++ b/app/lib/common-libs/timeout-promise.ts @@ -12,7 +12,7 @@ // GNU Affero General Public License for more details. export function newRejectTimeoutPromise(timeout: number) { - return new Promise((res, rej) => { + return new Promise<void>((res, rej) => { setTimeout(rej, timeout); }); } @@ -21,7 +21,7 @@ export function newResolveTimeoutPromise<T>( timeout: number, value: T ): Promise<T> { - return new Promise((res) => { + return new Promise<T>((res) => { setTimeout(() => res(value), timeout); }); } diff --git a/app/lib/dal/drivers/LevelDBDriver.ts b/app/lib/dal/drivers/LevelDBDriver.ts index 7959c3f1e..0fd4c0344 100644 --- a/app/lib/dal/drivers/LevelDBDriver.ts +++ b/app/lib/dal/drivers/LevelDBDriver.ts @@ -20,7 +20,7 @@ import * as memdown from "memdown"; export const LevelDBDriver = { newMemoryInstance: (): Promise<LevelUp> => { const impl: any = memdown.default(); - return new Promise((res, rej) => { + return new Promise<LevelUp<any>>((res, rej) => { const db: LevelUp = levelup.default(impl, undefined, (err: Error) => { if (err) return rej(err); res(db); @@ -30,7 +30,7 @@ export const LevelDBDriver = { newFileInstance: (path: string): Promise<LevelUp> => { const impl: any = leveldown.default(path); - return new Promise((res, rej) => { + return new Promise<LevelUp<any>>((res, rej) => { const db: LevelUp = levelup.default(impl, undefined, (err: Error) => { if (err) return rej(err); res(db); diff --git a/app/lib/dal/drivers/SQLiteDriver.ts b/app/lib/dal/drivers/SQLiteDriver.ts index 15a437ef5..0cc970038 100644 --- a/app/lib/dal/drivers/SQLiteDriver.ts +++ b/app/lib/dal/drivers/SQLiteDriver.ts @@ -41,7 +41,7 @@ export class SQLiteDriver { // Force case sensitiveness on LIKE operator const sql = "PRAGMA case_sensitive_like=ON"; - await new Promise<any>((resolve, reject) => + await new Promise<void>((resolve, reject) => sqlite.exec(sql, (err: any) => { if (err) return reject( @@ -115,7 +115,7 @@ export class SQLiteDriver { if (process.platform === "win32") { db.open; // For an unknown reason, we need this line. } - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { this.logger.debug('Closing SQLite database "%s"...', this.path); db.on("close", () => { this.logger.info('Database "%s" closed.', this.path); diff --git a/app/lib/dal/fileDAL.ts b/app/lib/dal/fileDAL.ts index b680bf9f4..4e7f2fb00 100644 --- a/app/lib/dal/fileDAL.ts +++ b/app/lib/dal/fileDAL.ts @@ -499,9 +499,7 @@ export class FileDAL implements ServerDAO { return true; } - async getGlobalIdentityByHashForHashingAndSig( - hash: string - ): Promise<{ + async getGlobalIdentityByHashForHashingAndSig(hash: string): Promise<{ pubkey: string; uid: string; buid: string; @@ -523,9 +521,7 @@ export class FileDAL implements ServerDAO { return pending; } - async getGlobalIdentityByHashForLookup( - hash: string - ): Promise<{ + async getGlobalIdentityByHashForLookup(hash: string): Promise<{ pubkey: string; uid: string; buid: string; @@ -551,9 +547,7 @@ export class FileDAL implements ServerDAO { return pending; } - async getGlobalIdentityByHashForJoining( - hash: string - ): Promise<{ + async getGlobalIdentityByHashForJoining(hash: string): Promise<{ pubkey: string; uid: string; buid: string; @@ -568,9 +562,10 @@ export class FileDAL implements ServerDAO { if (!idty) { return null; } - const membership = (await this.mindexDAL.getReducedMSForImplicitRevocation( - idty.pub - )) as FullMindexEntry; + const membership = + (await this.mindexDAL.getReducedMSForImplicitRevocation( + idty.pub + )) as FullMindexEntry; return { pubkey: idty.pub, uid: idty.uid, @@ -604,9 +599,7 @@ export class FileDAL implements ServerDAO { }; } - async getGlobalIdentityByHashForRevocation( - hash: string - ): Promise<{ + async getGlobalIdentityByHashForRevocation(hash: string): Promise<{ pub: string; uid: string; created_on: string; @@ -623,9 +616,10 @@ export class FileDAL implements ServerDAO { if (!idty) { return null; } - const membership = (await this.mindexDAL.getReducedMSForImplicitRevocation( - idty.pub - )) as FullMindexEntry; + const membership = + (await this.mindexDAL.getReducedMSForImplicitRevocation( + idty.pub + )) as FullMindexEntry; return { pub: idty.pub, uid: idty.uid, @@ -708,9 +702,7 @@ export class FileDAL implements ServerDAO { return await this.iindexDAL.getFromPubkeyOrUid(search); } - async getWrittenIdtyByPubkeyForHashingAndIsMember( - pub: string - ): Promise<{ + async getWrittenIdtyByPubkeyForHashingAndIsMember(pub: string): Promise<{ uid: string; created_on: string; pub: string; @@ -719,9 +711,7 @@ export class FileDAL implements ServerDAO { return await this.iindexDAL.getFromPubkey(pub); } - async getWrittenIdtyByPubkeyForRevocationCheck( - pubkey: string - ): Promise<{ + async getWrittenIdtyByPubkeyForRevocationCheck(pubkey: string): Promise<{ pub: string; uid: string; created_on: string; @@ -744,9 +734,7 @@ export class FileDAL implements ServerDAO { }; } - async getWrittenIdtyByPubkeyForCertificationCheck( - pubkey: string - ): Promise<{ + async getWrittenIdtyByPubkeyForCertificationCheck(pubkey: string): Promise<{ pub: string; uid: string; created_on: string; @@ -1605,7 +1593,7 @@ export class FileDAL implements ServerDAO { } getLogContent(linesQuantity: number) { - return new Promise((resolve, reject) => { + return new Promise<string[]>((resolve, reject) => { try { let lines: string[] = [], i = 0; diff --git a/app/lib/dal/indexDAL/abstract/DividendDAO.ts b/app/lib/dal/indexDAL/abstract/DividendDAO.ts index 906537889..aa97e9c83 100644 --- a/app/lib/dal/indexDAL/abstract/DividendDAO.ts +++ b/app/lib/dal/indexDAL/abstract/DividendDAO.ts @@ -60,9 +60,7 @@ export interface DividendDAO extends GenericDAO<DividendEntry> { getWrittenOnUDs(number: number): Promise<SimpleUdEntryForWallet[]>; - revertUDs( - number: number - ): Promise<{ + revertUDs(number: number): Promise<{ createdUDsDestroyedByRevert: SimpleUdEntryForWallet[]; consumedUDsRecoveredByRevert: SimpleUdEntryForWallet[]; }>; diff --git a/app/lib/dal/indexDAL/abstract/GenericDAO.ts b/app/lib/dal/indexDAL/abstract/GenericDAO.ts index e9057917c..f3f9651e6 100644 --- a/app/lib/dal/indexDAL/abstract/GenericDAO.ts +++ b/app/lib/dal/indexDAL/abstract/GenericDAO.ts @@ -1,7 +1,6 @@ import { Initiable } from "../../sqliteDAL/Initiable"; export interface GenericDAO<T> extends Initiable { - /** * Make a generic find with some ordering. * @param criterion Criterion object, LokiJS's find object format. diff --git a/app/lib/dal/indexDAL/abstract/PeerDAO.ts b/app/lib/dal/indexDAL/abstract/PeerDAO.ts index a3f6e3f23..b85f893e5 100644 --- a/app/lib/dal/indexDAL/abstract/PeerDAO.ts +++ b/app/lib/dal/indexDAL/abstract/PeerDAO.ts @@ -2,7 +2,6 @@ import { DBPeer } from "../../../db/DBPeer"; import { Initiable } from "../../sqliteDAL/Initiable"; export interface PeerDAO extends Initiable { - listAll(): Promise<DBPeer[]>; withUPStatus(): Promise<DBPeer[]>; diff --git a/app/lib/dal/indexDAL/abstract/SIndexDAO.ts b/app/lib/dal/indexDAL/abstract/SIndexDAO.ts index ee312da7d..d41e6d612 100644 --- a/app/lib/dal/indexDAL/abstract/SIndexDAO.ts +++ b/app/lib/dal/indexDAL/abstract/SIndexDAO.ts @@ -23,9 +23,7 @@ export interface SIndexDAO extends ReduceableDAO<SindexEntry> { getTxSource(identifier: string, pos: number): Promise<FullSindexEntry | null>; - getAvailableForPubkey( - pubkey: string - ): Promise< + getAvailableForPubkey(pubkey: string): Promise< { amount: number; base: number; diff --git a/app/lib/dal/indexDAL/abstract/TxsDAO.ts b/app/lib/dal/indexDAL/abstract/TxsDAO.ts index fc91a739d..4090cfa1e 100644 --- a/app/lib/dal/indexDAL/abstract/TxsDAO.ts +++ b/app/lib/dal/indexDAL/abstract/TxsDAO.ts @@ -4,7 +4,6 @@ import { SandBox } from "../../sqliteDAL/SandBox"; import { DBTx } from "../../../db/DBTx"; export interface TxsDAO extends GenericDAO<DBTx> { - disableCheckConstraints(): Promise<void>; enableCheckConstraints(): Promise<void>; @@ -29,9 +28,7 @@ export interface TxsDAO extends GenericDAO<DBTx> { addPending(dbTx: DBTx): Promise<DBTx>; - getTxHistoryByPubkey( - pubkey: string - ): Promise<{ + getTxHistoryByPubkey(pubkey: string): Promise<{ sent: DBTx[]; received: DBTx[]; sending: DBTx[]; diff --git a/app/lib/dal/indexDAL/abstract/WalletDAO.ts b/app/lib/dal/indexDAL/abstract/WalletDAO.ts index 4b9f7e96b..00e047aba 100644 --- a/app/lib/dal/indexDAL/abstract/WalletDAO.ts +++ b/app/lib/dal/indexDAL/abstract/WalletDAO.ts @@ -2,7 +2,6 @@ import { Initiable } from "../../sqliteDAL/Initiable"; import { DBWallet } from "../../../db/DBWallet"; export interface WalletDAO extends Initiable { - /** * Saves a wallet. * @param {DBWallet} wallet diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBBlockchain.ts b/app/lib/dal/indexDAL/leveldb/LevelDBBlockchain.ts index e0101e8bb..f9d062b47 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBBlockchain.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBBlockchain.ts @@ -19,8 +19,10 @@ import { LevelIndexBlockJoiners } from "./indexers/block/LevelIndexBlockJoiners" import { LevelIndexBlockActives } from "./indexers/block/LevelIndexBlockActives"; import { LevelIndexBlockLeavers } from "./indexers/block/LevelIndexBlockLeavers"; -export class LevelDBBlockchain extends LevelDBTable<DBBlock> - implements BlockchainDAO { +export class LevelDBBlockchain + extends LevelDBTable<DBBlock> + implements BlockchainDAO +{ private forks: LevelDBTable<DBBlock>; private indexOfIdentities: LevelIndexBlock; private indexOfCertifications: LevelIndexBlock; diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBCindex.ts b/app/lib/dal/indexDAL/leveldb/LevelDBCindex.ts index bfa05669f..4f0f3a457 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBCindex.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBCindex.ts @@ -19,8 +19,10 @@ export interface LevelDBCindexEntry { issued: CindexEntry[]; } -export class LevelDBCindex extends LevelDBTable<LevelDBCindexEntry> - implements CIndexDAO { +export class LevelDBCindex + extends LevelDBTable<LevelDBCindexEntry> + implements CIndexDAO +{ private indexForExpiresOn: LevelDBTable<string[]>; private indexForWrittenOn: LevelDBTable<string[]>; diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBDividend.ts b/app/lib/dal/indexDAL/leveldb/LevelDBDividend.ts index 161ddca38..ef5a88207 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBDividend.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBDividend.ts @@ -18,8 +18,10 @@ interface Consumption { pub: string; } -export class LevelDBDividend extends LevelDBTable<DividendEntry> - implements DividendDAO { +export class LevelDBDividend + extends LevelDBTable<DividendEntry> + implements DividendDAO +{ private indexForTrimming: LevelDBTable<string[]>; private hasIndexed = false; @@ -208,9 +210,7 @@ export class LevelDBDividend extends LevelDBTable<DividendEntry> ); } - async revertUDs( - number: number - ): Promise<{ + async revertUDs(number: number): Promise<{ createdUDsDestroyedByRevert: SimpleUdEntryForWallet[]; consumedUDsRecoveredByRevert: SimpleUdEntryForWallet[]; }> { diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBIindex.ts b/app/lib/dal/indexDAL/leveldb/LevelDBIindex.ts index fd5010024..d34b45aad 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBIindex.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBIindex.ts @@ -19,8 +19,10 @@ import { LevelIIndexKickIndexer } from "./indexers/LevelIIndexKickIndexer"; import { DataErrors } from "../../../common-libs/errors"; import { OldTransformers } from "../common/OldTransformer"; -export class LevelDBIindex extends LevelDBTable<IindexEntry[]> - implements IIndexDAO { +export class LevelDBIindex + extends LevelDBTable<IindexEntry[]> + implements IIndexDAO +{ private indexForHash: LevelIIndexHashIndexer; private indexForUid: LevelIIndexUidIndexer; private indexForKick: LevelIIndexKickIndexer; @@ -218,9 +220,9 @@ export class LevelDBIindex extends LevelDBTable<IindexEntry[]> return null; } const entries = await this.get(pub); - return OldTransformers.iindexEntityOrNull(entries) as Promise< - FullIindexEntry - >; + return OldTransformers.iindexEntityOrNull( + entries + ) as Promise<FullIindexEntry>; } async getFullFromPubkey(pub: string): Promise<FullIindexEntry> { diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBMindex.ts b/app/lib/dal/indexDAL/leveldb/LevelDBMindex.ts index dcadf4ad7..e825150e2 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBMindex.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBMindex.ts @@ -16,8 +16,10 @@ import { MIndexDAO } from "../abstract/MIndexDAO"; import { LevelMIndexRevokesOnIndexer } from "./indexers/LevelMIndexRevokesOnIndexer"; import { LevelMIndexExpiresOnIndexer } from "./indexers/LevelMIndexExpiresOnIndexer"; -export class LevelDBMindex extends LevelDBTable<MindexEntry[]> - implements MIndexDAO { +export class LevelDBMindex + extends LevelDBTable<MindexEntry[]> + implements MIndexDAO +{ private indexForExpiresOn: LevelMIndexExpiresOnIndexer; private indexForRevokesOn: LevelMIndexRevokesOnIndexer; private indexForWrittenOn: LevelDBWrittenOnIndexer<MindexEntry>; diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBSindex.ts b/app/lib/dal/indexDAL/leveldb/LevelDBSindex.ts index f81e4f9d2..b58aa9aa3 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBSindex.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBSindex.ts @@ -14,8 +14,10 @@ import { pint } from "../../../common-libs/pint"; import { arrayPruneAllCopy } from "../../../common-libs/array-prune"; import { CommonConstants } from "../../../common-libs/constants"; -export class LevelDBSindex extends LevelDBTable<SindexEntry> - implements SIndexDAO { +export class LevelDBSindex + extends LevelDBTable<SindexEntry> + implements SIndexDAO +{ private indexForTrimming: LevelDBTable<string[]>; private indexForConsumed: LevelDBTable<string[]>; private indexForConditions: LevelDBTable<string[]>; @@ -124,9 +126,7 @@ export class LevelDBSindex extends LevelDBTable<SindexEntry> return reduced.filter((r) => !r.consumed); } - async getAvailableForPubkey( - pubkey: string - ): Promise< + async getAvailableForPubkey(pubkey: string): Promise< { amount: number; base: number; @@ -537,9 +537,10 @@ export class LevelDBSindex extends LevelDBTable<SindexEntry> if (!condition) return pubKeys; let match: RegExpExecArray | null; while ( - (match = CommonConstants.TRANSACTION.OUTPUT_CONDITION_SIG_PUBKEY.exec( - condition - )) !== null + (match = + CommonConstants.TRANSACTION.OUTPUT_CONDITION_SIG_PUBKEY.exec( + condition + )) !== null ) { pubKeys.push(match[1]); condition = condition.substring(match.index + match[0].length); diff --git a/app/lib/dal/indexDAL/leveldb/LevelDBTable.ts b/app/lib/dal/indexDAL/leveldb/LevelDBTable.ts index 9b23982b1..f9d018a11 100644 --- a/app/lib/dal/indexDAL/leveldb/LevelDBTable.ts +++ b/app/lib/dal/indexDAL/leveldb/LevelDBTable.ts @@ -12,7 +12,6 @@ export class LevelDBTable<T> { cleanCache(): void {} - async close() { await this.db.close(); } @@ -73,7 +72,7 @@ export class LevelDBTable<T> { public async count(options?: AbstractIteratorOptions) { let count = 0; - await new Promise((res) => { + await new Promise<void>((res) => { this.db .createReadStream(options) .on("data", () => count++) @@ -86,7 +85,7 @@ export class LevelDBTable<T> { callback: (entry: T) => void, options?: AbstractIteratorOptions ) { - await new Promise((res) => { + await new Promise<void>((res) => { this.db .createReadStream(options) .on("data", (data) => callback(JSON.parse(String(data.value)))) @@ -98,7 +97,7 @@ export class LevelDBTable<T> { callback: (entry: { key: string; value: T }) => void, options?: AbstractIteratorOptions ) { - await new Promise((res) => { + await new Promise<void>((res) => { this.db .createReadStream(options) .on("data", (data) => @@ -116,7 +115,7 @@ export class LevelDBTable<T> { options?: AbstractIteratorOptions ) { const ops: Promise<void>[] = []; - await new Promise((res) => { + await new Promise<void>((res) => { this.db .createReadStream(options) .on("data", (data) => diff --git a/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexExpiresOnIndexer.ts b/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexExpiresOnIndexer.ts index ddefe40a1..f2ba81927 100644 --- a/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexExpiresOnIndexer.ts +++ b/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexExpiresOnIndexer.ts @@ -88,9 +88,9 @@ export class LevelMIndexExpiresOnIndexer extends LevelDBDataIndex< }) ); // Case 2: REVERT expired = put back the value of `expires_on` - const values: MindexEntry[] = Underscore.values( - newStateByPub - ).map((entries) => reduce(entries)); + const values: MindexEntry[] = Underscore.values(newStateByPub).map( + (entries) => reduce(entries) + ); const byExpiresOnForExpired = reduceGroupBy(values, "expires_on"); await Promise.all( Underscore.keys(byExpiresOnForExpired).map(async (expiresOn) => diff --git a/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexRevokesOnIndexer.ts b/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexRevokesOnIndexer.ts index cc34691e8..29192fa4d 100644 --- a/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexRevokesOnIndexer.ts +++ b/app/lib/dal/indexDAL/leveldb/indexers/LevelMIndexRevokesOnIndexer.ts @@ -88,9 +88,9 @@ export class LevelMIndexRevokesOnIndexer extends LevelDBDataIndex< }) ); // Case 2: revocation REVERT - const values: MindexEntry[] = Underscore.values( - newStateByPub - ).map((entries) => reduce(entries)); + const values: MindexEntry[] = Underscore.values(newStateByPub).map( + (entries) => reduce(entries) + ); const byExpiredOn = reduceGroupBy(values, "revoked_on"); await Promise.all( Underscore.keys(byExpiredOn).map(async (revokesOn) => diff --git a/app/lib/dal/indexDAL/sqlite/SqliteDividend.ts b/app/lib/dal/indexDAL/sqlite/SqliteDividend.ts index d64cc48b3..77f83cab4 100644 --- a/app/lib/dal/indexDAL/sqlite/SqliteDividend.ts +++ b/app/lib/dal/indexDAL/sqlite/SqliteDividend.ts @@ -12,8 +12,10 @@ import { import { DividendDaoHandler } from "../common/DividendDaoHandler"; import { DataErrors } from "../../../common-libs/errors"; -export class SqliteDividend extends SqliteTable<DividendEntry> - implements DividendDAO { +export class SqliteDividend + extends SqliteTable<DividendEntry> + implements DividendDAO +{ constructor(getSqliteDB: (dbName: string) => Promise<SQLiteDriver>) { super( "dividend", @@ -201,9 +203,7 @@ export class SqliteDividend extends SqliteTable<DividendEntry> ); } - async revertUDs( - number: number - ): Promise<{ + async revertUDs(number: number): Promise<{ createdUDsDestroyedByRevert: SimpleUdEntryForWallet[]; consumedUDsRecoveredByRevert: SimpleUdEntryForWallet[]; }> { diff --git a/app/lib/dal/indexDAL/sqlite/SqliteIIndex.ts b/app/lib/dal/indexDAL/sqlite/SqliteIIndex.ts index a50fdb041..7c3c24537 100644 --- a/app/lib/dal/indexDAL/sqlite/SqliteIIndex.ts +++ b/app/lib/dal/indexDAL/sqlite/SqliteIIndex.ts @@ -15,8 +15,10 @@ import { SqlNullableFieldDefinition, } from "./SqlFieldDefinition"; -export class SqliteIIndex extends SqliteTable<IindexEntry> - implements IIndexDAO { +export class SqliteIIndex + extends SqliteTable<IindexEntry> + implements IIndexDAO +{ constructor(getSqliteDB: (dbName: string) => Promise<SQLiteDriver>) { super( "iindex", diff --git a/app/lib/dal/indexDAL/sqlite/SqliteMIndex.ts b/app/lib/dal/indexDAL/sqlite/SqliteMIndex.ts index 0d8b60d2b..eb1a81ab0 100644 --- a/app/lib/dal/indexDAL/sqlite/SqliteMIndex.ts +++ b/app/lib/dal/indexDAL/sqlite/SqliteMIndex.ts @@ -10,8 +10,10 @@ import { SqlNullableFieldDefinition, } from "./SqlFieldDefinition"; -export class SqliteMIndex extends SqliteTable<MindexEntry> - implements MIndexDAO { +export class SqliteMIndex + extends SqliteTable<MindexEntry> + implements MIndexDAO +{ private readonly p2: Promise<SQLiteDriver>; private d2: SqliteNodeIOManager<{ pub: string; diff --git a/app/lib/dal/indexDAL/sqlite/SqlitePeers.ts b/app/lib/dal/indexDAL/sqlite/SqlitePeers.ts index 50ce41093..a265628b0 100644 --- a/app/lib/dal/indexDAL/sqlite/SqlitePeers.ts +++ b/app/lib/dal/indexDAL/sqlite/SqlitePeers.ts @@ -48,12 +48,14 @@ export class SqlitePeers extends SqliteTable<DBPeer> implements PeerDAO { cleanCache(): void {} async countNonWoTPeers(): Promise<number> { - return (( - await this.driver.sqlRead( - "SELECT COUNT(*) as _count FROM peers WHERE nonWoT", - [] - ) - )[0] as any)["_count"]; + return ( + ( + await this.driver.sqlRead( + "SELECT COUNT(*) as _count FROM peers WHERE nonWoT", + [] + ) + )[0] as any + )["_count"]; } deleteNonWotPeersWhoseLastContactIsAbove(threshold: number): Promise<void> { diff --git a/app/lib/dal/indexDAL/sqlite/SqliteSIndex.ts b/app/lib/dal/indexDAL/sqlite/SqliteSIndex.ts index fd27cead1..5fbdfe8ab 100644 --- a/app/lib/dal/indexDAL/sqlite/SqliteSIndex.ts +++ b/app/lib/dal/indexDAL/sqlite/SqliteSIndex.ts @@ -14,8 +14,10 @@ import { } from "./SqlFieldDefinition"; import { SIndexDAO } from "../abstract/SIndexDAO"; -export class SqliteSIndex extends SqliteTable<SindexEntry> - implements SIndexDAO { +export class SqliteSIndex + extends SqliteTable<SindexEntry> + implements SIndexDAO +{ constructor(getSqliteDB: (dbName: string) => Promise<SQLiteDriver>) { super( "sindex", @@ -169,9 +171,7 @@ export class SqliteSIndex extends SqliteTable<SindexEntry> ); } - async getAvailableForPubkey( - pubkey: string - ): Promise< + async getAvailableForPubkey(pubkey: string): Promise< { amount: number; base: number; diff --git a/app/lib/dal/indexDAL/sqlite/SqliteTable.ts b/app/lib/dal/indexDAL/sqlite/SqliteTable.ts index d2c39b33b..a9c5a1f87 100644 --- a/app/lib/dal/indexDAL/sqlite/SqliteTable.ts +++ b/app/lib/dal/indexDAL/sqlite/SqliteTable.ts @@ -43,8 +43,9 @@ export class SqliteTable<T> { generateCreateTable() { let sql = `CREATE TABLE IF NOT EXISTS ${this.name} (`; const fields = this.keys() - .map((fieldName) => { - const f = this.fields[fieldName] as SqlFieldDefinition; + .map((key) => { + const fieldName = String(key); + const f = this.fields[key] as SqlFieldDefinition; switch (f.type) { case "BOOLEAN": return `\n${fieldName} BOOLEAN${f.nullable ? " NULL" : ""}`; @@ -80,7 +81,9 @@ export class SqliteTable<T> { return this.keys() .filter((key) => this.fields[key]?.indexed) .map((fieldName) => { - return `CREATE INDEX IF NOT EXISTS idx_${this.name}_${fieldName} ON ${this.name} (${fieldName});\n`; + return `CREATE INDEX IF NOT EXISTS idx_${this.name}_${String( + fieldName + )} ON ${this.name} (${String(fieldName)});\n`; }) .join(""); } @@ -101,12 +104,14 @@ export class SqliteTable<T> { ) { const valuesOfRecord = fieldsToUpdate .map( - (fieldName) => `${fieldName} = ${this.getFieldValue(fieldName, record)}` + (fieldName) => + `${String(fieldName)} = ${this.getFieldValue(fieldName, record)}` ) .join(","); const conditionsOfRecord = whereFields .map( - (fieldName) => `${fieldName} = ${this.getFieldValue(fieldName, record)}` + (fieldName) => + `${String(fieldName)} = ${this.getFieldValue(fieldName, record)}` ) .join(","); await driver.sqlWrite( @@ -206,18 +211,27 @@ export class SqliteTable<T> { } async count() { - return (( - await this.driver.sqlRead(`SELECT COUNT(*) as max FROM ${this.name}`, []) - )[0] as any).max; + return ( + ( + await this.driver.sqlRead( + `SELECT COUNT(*) as max FROM ${this.name}`, + [] + ) + )[0] as any + ).max; } async countBy(fieldName: keyof T, fieldValue: any): Promise<number> { - return (( - await this.driver.sqlRead( - `SELECT COUNT(*) as max FROM ${this.name} WHERE ${fieldName} = ?`, - [fieldValue] - ) - )[0] as any).max; + return ( + ( + await this.driver.sqlRead( + `SELECT COUNT(*) as max FROM ${this.name} WHERE ${String( + fieldName + )} = ?`, + [fieldValue] + ) + )[0] as any + ).max; } /** diff --git a/app/lib/dal/sqliteDAL/MetaDAL.ts b/app/lib/dal/sqliteDAL/MetaDAL.ts index 53caf5519..82dfe8b49 100644 --- a/app/lib/dal/sqliteDAL/MetaDAL.ts +++ b/app/lib/dal/sqliteDAL/MetaDAL.ts @@ -195,9 +195,7 @@ export class MetaDAL extends AbstractSQLite<DBMeta> { 25: async () => {}, // Drop old table 'txs' (replaced by a file 'txs.db') - 26: "BEGIN;" + - "DROP TABLE IF EXISTS txs;" + - "COMMIT;", + 26: "BEGIN;" + "DROP TABLE IF EXISTS txs;" + "COMMIT;", // Add columns 'issuer' and 'recipient' in transaction table - see issue #1442 27: async () => { diff --git a/app/lib/dto/CertificationDTO.ts b/app/lib/dto/CertificationDTO.ts index 047206d56..1c35b7395 100644 --- a/app/lib/dto/CertificationDTO.ts +++ b/app/lib/dto/CertificationDTO.ts @@ -39,8 +39,10 @@ export class ShortCertificationDTO { } } -export class CertificationDTO extends ShortCertificationDTO - implements Cloneable { +export class CertificationDTO + extends ShortCertificationDTO + implements Cloneable +{ clone(): any { return CertificationDTO.fromJSONObject(this); } diff --git a/app/lib/dto/ConfDTO.ts b/app/lib/dto/ConfDTO.ts index 7d5d82474..40b46016e 100644 --- a/app/lib/dto/ConfDTO.ts +++ b/app/lib/dto/ConfDTO.ts @@ -68,8 +68,8 @@ export interface CurrencyConfDTO { export interface KeypairConfDTO { pair: Keypair; oldPair: Keypair | null; - salt: string; - passwd: string; + salt?: string; + passwd?: string; } export interface NetworkConfDTO { @@ -119,7 +119,8 @@ export class ConfDTO NetworkConfDTO, BranchingDTO, WS2PConfDTO, - PowDTO { + PowDTO +{ constructor( public loglevel: string, public currency: string, diff --git a/app/lib/dto/TransactionDTO.ts b/app/lib/dto/TransactionDTO.ts index e10747033..43f93dd9a 100644 --- a/app/lib/dto/TransactionDTO.ts +++ b/app/lib/dto/TransactionDTO.ts @@ -170,9 +170,10 @@ export class TransactionDTO implements Cloneable { const recipients: string[] = []; while ( output && - (match = CommonConstants.TRANSACTION.OUTPUT_CONDITION_SIG_PUBKEY.exec( - output - )) !== null + (match = + CommonConstants.TRANSACTION.OUTPUT_CONDITION_SIG_PUBKEY.exec( + output + )) !== null ) { const pub = match[1] as string; if (!res.includes(pub) && !recipients.includes(pub)) { diff --git a/app/lib/indexer.ts b/app/lib/indexer.ts index c691672f4..0386ee3b8 100644 --- a/app/lib/indexer.ts +++ b/app/lib/indexer.ts @@ -917,8 +917,9 @@ export class Indexer { await Promise.all( mindex.map(async (ENTRY: MindexEntry) => { if (!ENTRY.revoked_on) { - const created_on = reduce(await dal.mindexDAL.reducable(ENTRY.pub)) - .created_on; + const created_on = reduce( + await dal.mindexDAL.reducable(ENTRY.pub) + ).created_on; if (created_on != null) { ENTRY.numberFollowing = number(ENTRY.created_on) > number(created_on); @@ -1470,10 +1471,8 @@ export class Indexer { (entry) => entry.issuer == HEAD.issuer ); nbPersonalBlocksInFrame = count(blocksOfIssuer); - const blocksPerIssuerInFrame = uniq( - issuersInFrame - ).map((issuer: string) => - count(Underscore.where(blocksInFrame, { issuer })) + const blocksPerIssuerInFrame = uniq(issuersInFrame).map( + (issuer: string) => count(Underscore.where(blocksInFrame, { issuer })) ); medianOfBlocksInFrame = Math.max(1, median(blocksPerIssuerInFrame)); if (nbPersonalBlocksInFrame == 0) { @@ -2091,9 +2090,8 @@ export class Indexer { Math.pow(10, HEAD.unitBase) ) { // console.log('GARBAGE ACCOUNT on B#%s %s! (has %s units left)', HEAD.number, account, balance + variations) - const globalAccountEntries = await dal.sindexDAL.getAvailableForConditions( - account - ); + const globalAccountEntries = + await dal.sindexDAL.getAvailableForConditions(account); // localAccountEntries.forEach(e => console.log('local: %s %s %s', e.identifier, e.pos, e.amount)) // globalAccountEntries.forEach(e => console.log('global: %s %s %s', e.identifier, e.pos, e.amount)) for (const src of localAccountEntries.concat(globalAccountEntries)) { @@ -2436,7 +2434,7 @@ export function reduceForDBTrimming<T extends { writtenOn: number }>( export function reduce<T>(records: T[]): T { return records.reduce((obj: T, record) => { - const keys = Object.keys(record) as (keyof T)[]; + const keys = Underscore.keys<T>(record); for (const k of keys) { if (record[k] !== undefined && record[k] !== null) { obj[k] = record[k]; diff --git a/app/lib/rules/global_rules.ts b/app/lib/rules/global_rules.ts index c168807bf..822c7021c 100644 --- a/app/lib/rules/global_rules.ts +++ b/app/lib/rules/global_rules.ts @@ -93,9 +93,10 @@ export const GLOBAL_RULES_FUNCTIONS = { // Because the window rule does not apply on initial certifications if (current && idty.buid != constants.SPECIAL_BLOCK) { // From DUP 0.5: we fully check the blockstamp - const basedBlock = (await dal.getAbsoluteValidBlockInForkWindowByBlockstamp( - idty.buid - )) || { medianTime: 0 }; + const basedBlock = + (await dal.getAbsoluteValidBlockInForkWindowByBlockstamp( + idty.buid + )) || { medianTime: 0 }; // Check if writable let duration = current.medianTime - basedBlock.medianTime; if (duration > conf.idtyWindow) { diff --git a/app/lib/rules/local_rules.ts b/app/lib/rules/local_rules.ts index ea5f8a578..aeb68937a 100644 --- a/app/lib/rules/local_rules.ts +++ b/app/lib/rules/local_rules.ts @@ -34,37 +34,11 @@ const constants = CommonConstants; const maxAcceleration = require("./helpers").maxAcceleration; const INVALID_G1_BLOCKS = new Set([ - 15144, - 31202, - 85448, - 87566, - 90830, - 109327, - 189835, - 199172, - 221274, - 253582, + 15144, 31202, 85448, 87566, 90830, 109327, 189835, 199172, 221274, 253582, ]); const INVALID_GT_BLOCKS = new Set([ - 24316, - 62067, - 62551, - 93288, - 173118, - 183706, - 196196, - 246027, - 247211, - 263207, - 307038, - 328741, - 335914, - 377316, - 395714, - 396024, - 407913, - 422366, - 496751, + 24316, 62067, 62551, 93288, 173118, 183706, 196196, 246027, 247211, 263207, + 307038, 328741, 335914, 377316, 395714, 396024, 407913, 422366, 496751, ]); export const LOCAL_RULES_FUNCTIONS = { diff --git a/app/lib/streams/multicaster.ts b/app/lib/streams/multicaster.ts index 5afd88cd1..2dd59e92d 100644 --- a/app/lib/streams/multicaster.ts +++ b/app/lib/streams/multicaster.ts @@ -267,7 +267,7 @@ export class Multicaster extends stream.Transform { if (!peer.isReachable()) { return Promise.resolve(); } - return new Promise((resolve, reject) => { + return new Promise<any>((resolve, reject) => { const postReq = request.post( { uri: protocol(peer.getPort()) + "://" + peer.getURL() + uri, diff --git a/app/lib/system/directory.ts b/app/lib/system/directory.ts index b8fec8b43..3e8e445d6 100644 --- a/app/lib/system/directory.ts +++ b/app/lib/system/directory.ts @@ -95,8 +95,8 @@ class QioFileSystem implements FileSystem { } } else { // Use NodeJS streams for faster writing - let wstream = fs.createWriteStream(file); - await new Promise(async (res, rej) => { + const wstream = fs.createWriteStream(file); + await new Promise<void>(async (res, rej) => { // When done, return wstream.on("close", (err: any) => { if (err) return rej(err); diff --git a/app/lib/wizard.ts b/app/lib/wizard.ts index 1c38b02e1..3ef480391 100644 --- a/app/lib/wizard.ts +++ b/app/lib/wizard.ts @@ -33,7 +33,7 @@ export class Wizard { } function doTasks(todos: string[], conf: ConfDTO) { - return new Promise((res, rej) => { + return new Promise<void>((res, rej) => { async.forEachSeries( todos, function (task: any, callback: any) { diff --git a/app/modules/bma/index.ts b/app/modules/bma/index.ts index 92d66a56b..8a9372f76 100644 --- a/app/modules/bma/index.ts +++ b/app/modules/bma/index.ts @@ -89,7 +89,11 @@ export const BmaDependency = { }, config: { - onLoading: async (conf: NetworkConfDTO, program: any, logger: any) => { + onLoading: async ( + conf: Partial<NetworkConfDTO>, + program: any, + logger: any + ) => { // If the usage of BMA hasn't been defined yet if (conf.nobma === undefined) { // Do we have an existing BMA conf? @@ -186,7 +190,7 @@ export const BmaDependency = { } }, - beforeSave: async (conf: NetworkConfDTO, program: any) => { + beforeSave: async (conf: Partial<NetworkConfDTO>, program: any) => { if (!conf.ipv4) delete conf.ipv4; if (!conf.ipv6) delete conf.ipv6; if (!conf.remoteipv4) delete conf.remoteipv4; diff --git a/app/modules/bma/lib/constants.ts b/app/modules/bma/lib/constants.ts index adb86d061..90d707c83 100644 --- a/app/modules/bma/lib/constants.ts +++ b/app/modules/bma/lib/constants.ts @@ -17,13 +17,16 @@ export const BMAConstants = { BMA_PORTS_END: 10999, DEFAULT_PORT: 10901, - IPV4_REGEXP: /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/, - IPV6_REGEXP: /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/, + IPV4_REGEXP: + /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/, + IPV6_REGEXP: + /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/, HOST_ONION_REGEX: CommonConstants.HOST_ONION_REGEX, PORT_START: 15000, UPNP_INTERVAL: 300, UPNP_TTL: 600, - PUBLIC_KEY: /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$/, + PUBLIC_KEY: + /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$/, SHA256_HASH: /^[A-F0-9]{64}$/, ERRORS: { diff --git a/app/modules/bma/lib/controllers/blockchain.ts b/app/modules/bma/lib/controllers/blockchain.ts index 36f7443b2..b6ff1da0c 100644 --- a/app/modules/bma/lib/controllers/blockchain.ts +++ b/app/modules/bma/lib/controllers/blockchain.ts @@ -188,9 +188,10 @@ export class BlockchainBinding extends AbstractController { async hardship(req: any): Promise<HttpHardship> { let nextBlockNumber = 0; const search = await ParametersService.getSearchP(req); - const idty = await this.server.dal.getWrittenIdtyByPubkeyOrUidForIsMemberAndPubkey( - search - ); + const idty = + await this.server.dal.getWrittenIdtyByPubkeyOrUidForIsMemberAndPubkey( + search + ); if (!idty) { throw BMAConstants.ERRORS.NO_MATCHING_IDENTITY; } @@ -222,9 +223,8 @@ export class BlockchainBinding extends AbstractController { ); const difficulties = []; for (const issuer of issuers) { - const member = await this.server.dal.getWrittenIdtyByPubkeyForUidAndPubkey( - issuer - ); + const member = + await this.server.dal.getWrittenIdtyByPubkeyForUidAndPubkey(issuer); const difficulty = await this.server .getBcContext() .getIssuerPersonalizedDifficulty(member.pub); diff --git a/app/modules/bma/lib/controllers/wot.ts b/app/modules/bma/lib/controllers/wot.ts index 73422c518..858ae8ffb 100644 --- a/app/modules/bma/lib/controllers/wot.ts +++ b/app/modules/bma/lib/controllers/wot.ts @@ -58,9 +58,10 @@ export class WOTBinding extends AbstractController { ); const validCerts = []; for (const cert of certs) { - const member = await this.server.dal.getWrittenIdtyByPubkeyForUidAndIsMemberAndWasMember( - cert.from - ); + const member = + await this.server.dal.getWrittenIdtyByPubkeyForUidAndIsMemberAndWasMember( + cert.from + ); if (member) { cert.uids = [member.uid]; cert.isMember = member.member; @@ -138,9 +139,10 @@ export class WOTBinding extends AbstractController { search )) as FullIindexEntry; } else { - idty = (await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( - search - )) as FullIindexEntry; + idty = + (await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( + search + )) as FullIindexEntry; } const certs = await this.server.dal.certsToTarget( idty.pub, @@ -148,9 +150,10 @@ export class WOTBinding extends AbstractController { ); const theCerts: HttpCertification[] = []; for (const cert of certs) { - const certifier = await this.server.dal.getWrittenIdtyByPubkeyForUidAndMemberAndCreatedOn( - cert.from - ); + const certifier = + await this.server.dal.getWrittenIdtyByPubkeyForUidAndMemberAndCreatedOn( + cert.from + ); if (certifier) { let certBlock = await this.server.dal.getBlockWeHaveItForSure( cert.block_number @@ -196,9 +199,8 @@ export class WOTBinding extends AbstractController { } else { identities = await this.IdentityService.searchIdentities(search); } - const all: HttpIdentityRequirement[] = await this.BlockchainService.requirementsOfIdentities( - identities - ); + const all: HttpIdentityRequirement[] = + await this.BlockchainService.requirementsOfIdentities(identities); if (!all || !all.length) { throw BMAConstants.ERRORS.NO_IDTY_MATCHING_PUB_OR_UID; } @@ -250,16 +252,18 @@ export class WOTBinding extends AbstractController { search )) as FullIindexEntry; } else { - idty = (await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( - search - )) as FullIindexEntry; + idty = + (await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( + search + )) as FullIindexEntry; } const certs = await this.server.dal.certsFrom(idty.pub); const theCerts: HttpCertification[] = []; for (const cert of certs) { - const certified = await this.server.dal.getWrittenIdtyByPubkeyForUidAndMemberAndCreatedOn( - cert.to - ); + const certified = + await this.server.dal.getWrittenIdtyByPubkeyForUidAndMemberAndCreatedOn( + cert.to + ); if (certified) { let certBlock = await this.server.dal.getBlockWeHaveItForSure( cert.block_number @@ -296,9 +300,10 @@ export class WOTBinding extends AbstractController { async identityOf(req: any): Promise<HttpSimpleIdentity> { let search = await ParametersService.getSearchP(req); - const idty = await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( - search - ); + const idty = + await this.server.dal.getWrittenIdtyByPubkeyOrUIdForHashingAndIsMember( + search + ); if (!idty) { throw constants.ERRORS.NO_MEMBER_MATCHING_PUB_OR_UID; } diff --git a/app/modules/bma/lib/upnp.ts b/app/modules/bma/lib/upnp.ts index 3c5eecb98..50910d13b 100644 --- a/app/modules/bma/lib/upnp.ts +++ b/app/modules/bma/lib/upnp.ts @@ -35,7 +35,7 @@ export const Upnp = async function ( await Q.nbind(client.externalIp, client)(); } catch (err) { if (err && err.message == "timeout") { - throw 'No UPnP gateway found: your node won\'t be reachable from the Internet. Use --noupnp option to avoid this message.'; + throw "No UPnP gateway found: your node won't be reachable from the Internet. Use --noupnp option to avoid this message."; } throw err; } finally { diff --git a/app/modules/config.ts b/app/modules/config.ts index 6776cd045..59075431c 100644 --- a/app/modules/config.ts +++ b/app/modules/config.ts @@ -93,10 +93,9 @@ module.exports = { const aggregates = Underscore.uniq( lines .map((l) => l.match(/: (\[\w+\](\[\w+\])*)/)) - .filter((l) => l) - .map((l: string[]) => l[1]) + .filter((l) => !!l) + .map((l) => l && (l[1] as unknown as string)) ); - console.log(aggregates); const results = aggregates.map((a: string) => { return { name: a, diff --git a/app/modules/crawler/index.ts b/app/modules/crawler/index.ts index 0ae24bd36..3ee33828a 100644 --- a/app/modules/crawler/index.ts +++ b/app/modules/crawler/index.ts @@ -109,8 +109,7 @@ export const CrawlerDependency = { }, { value: "--cautious", - desc: - "Check blocks validity during sync (overrides --nocautious option).", + desc: "Check blocks validity during sync (overrides --nocautious option).", }, { value: "--nopeers", desc: "Do not retrieve peers during sync." }, { @@ -119,8 +118,7 @@ export const CrawlerDependency = { }, { value: "--localsync", - desc: - "Allow to synchronize on nodes with local network IP address for `sync` command", + desc: "Allow to synchronize on nodes with local network IP address for `sync` command", }, { value: "--nosources", @@ -138,16 +136,14 @@ export const CrawlerDependency = { }, { value: "--minsig <minsig>", - desc: - "Minimum pending signatures count for `crawl-lookup`. Default is 5.", + desc: "Minimum pending signatures count for `crawl-lookup`. Default is 5.", }, ], cli: [ { name: "sync [source] [to]", - desc: - "Synchronize blockchain from a remote Duniter node. [source] is [host][:port]. [to] defaults to remote current block number.", + desc: "Synchronize blockchain from a remote Duniter node. [source] is [host][:port]. [to] defaults to remote current block number.", preventIfRunning: true, onConfiguredExecute: async (server: Server) => { await server.resetData(); @@ -531,7 +527,8 @@ export const CrawlerDependency = { logger.info("Looking at %s...", source); try { const fromHost = await connect(peer); - let current: DBBlock | null = await server.dal.getCurrentBlockOrNull(); + let current: DBBlock | null = + await server.dal.getCurrentBlockOrNull(); if (from) { current = { number: from - 1 } as any; } @@ -585,8 +582,7 @@ export const CrawlerDependency = { }, }, { - name: - "import-lookup [search] [fromhost] [fromport] [frompath] [tohost] [toport] [topath]", + name: "import-lookup [search] [fromhost] [fromport] [frompath] [tohost] [toport] [topath]", desc: "Exchange peerings with another node", onDatabaseExecute: async ( server: Server, @@ -751,8 +747,7 @@ export const CrawlerDependency = { }, { name: "crawl-lookup <toHost> <toPort> [<fromHost> [<fromPort>]]", - desc: - "Make a full network scan and rebroadcast every WoT pending document (identity, certification, membership)", + desc: "Make a full network scan and rebroadcast every WoT pending document (identity, certification, membership)", onDatabaseExecute: async ( server: Server, conf: ConfDTO, diff --git a/app/modules/crawler/lib/crawler.ts b/app/modules/crawler/lib/crawler.ts index b46420a9b..46bb4ce3a 100644 --- a/app/modules/crawler/lib/crawler.ts +++ b/app/modules/crawler/lib/crawler.ts @@ -553,10 +553,11 @@ export class BlockCrawler { return block; } async applyMainBranch(block: BlockDTO): Promise<boolean> { - const existing = await server.dal.getAbsoluteBlockByNumberAndHash( - block.number, - block.hash - ); + const existing = + await server.dal.getAbsoluteBlockByNumberAndHash( + block.number, + block.hash + ); if (!existing) { let addedBlock = await server.writeBlock( block, diff --git a/app/modules/crawler/lib/req2fwd.ts b/app/modules/crawler/lib/req2fwd.ts index 14bee1a63..befe13ec8 100644 --- a/app/modules/crawler/lib/req2fwd.ts +++ b/app/modules/crawler/lib/req2fwd.ts @@ -63,7 +63,7 @@ export const req2fwd = async ( for (const received of idty.pendingCerts) { const cid = [received.from, iid].join("-"); if (!certs[cid]) { - await new Promise((res) => setTimeout(res, 300)); + await new Promise<void>((res) => setTimeout(res, 300)); certs[cid] = received; const rawCert = rawer.getOfficialCertification({ currency: "g1", diff --git a/app/modules/crawler/lib/sync.ts b/app/modules/crawler/lib/sync.ts index de68f7920..9054bcad8 100644 --- a/app/modules/crawler/lib/sync.ts +++ b/app/modules/crawler/lib/sync.ts @@ -214,7 +214,7 @@ export class Synchroniser extends stream.Duplex { this.watcher ); - await new Promise((res, rej) => { + await new Promise<void>((res, rej) => { milestonesStream .pipe(download) .pipe(localIndexer) diff --git a/app/modules/crawler/lib/sync/BMARemoteContacter.ts b/app/modules/crawler/lib/sync/BMARemoteContacter.ts index 9e08866d6..75f45bf03 100644 --- a/app/modules/crawler/lib/sync/BMARemoteContacter.ts +++ b/app/modules/crawler/lib/sync/BMARemoteContacter.ts @@ -37,9 +37,7 @@ export class BMARemoteContacter implements IRemoteContacter { return this.contacter.getBlocks(count, from); } - getMilestones( - page: number - ): Promise<{ + getMilestones(page: number): Promise<{ chunkSize: number; totalPages: number; currentPage: number; diff --git a/app/modules/crawler/lib/sync/FsSyncDownloader.ts b/app/modules/crawler/lib/sync/FsSyncDownloader.ts index f948c0f14..d3fbe25db 100644 --- a/app/modules/crawler/lib/sync/FsSyncDownloader.ts +++ b/app/modules/crawler/lib/sync/FsSyncDownloader.ts @@ -5,8 +5,10 @@ import * as path from "path"; import { CommonConstants } from "../../../../lib/common-libs/constants"; import { ASyncDownloader } from "./ASyncDownloader"; -export class FsSyncDownloader extends ASyncDownloader - implements ISyncDownloader { +export class FsSyncDownloader + extends ASyncDownloader + implements ISyncDownloader +{ private ls: Promise<string[]>; private ttas: number[] = []; diff --git a/app/modules/crawler/lib/sync/IRemoteContacter.ts b/app/modules/crawler/lib/sync/IRemoteContacter.ts index 85e8ff267..aacf72151 100644 --- a/app/modules/crawler/lib/sync/IRemoteContacter.ts +++ b/app/modules/crawler/lib/sync/IRemoteContacter.ts @@ -30,9 +30,7 @@ export interface IRemoteContacter { milestonesPerPage: number; }>; - getMilestones( - page: number - ): Promise<{ + getMilestones(page: number): Promise<{ chunkSize: number; totalPages: number; currentPage: number; diff --git a/app/modules/crawler/lib/sync/P2PSyncDownloader.ts b/app/modules/crawler/lib/sync/P2PSyncDownloader.ts index a677cdb4b..8c2a3c1e6 100644 --- a/app/modules/crawler/lib/sync/P2PSyncDownloader.ts +++ b/app/modules/crawler/lib/sync/P2PSyncDownloader.ts @@ -16,8 +16,10 @@ import { ASyncDownloader } from "./ASyncDownloader"; import { P2pCandidate } from "./p2p/p2p-candidate"; import { CrawlerConstants } from "../constants"; -export class P2PSyncDownloader extends ASyncDownloader - implements ISyncDownloader { +export class P2PSyncDownloader + extends ASyncDownloader + implements ISyncDownloader +{ private PARALLEL_PER_CHUNK = 1; private MAX_DELAY_PER_DOWNLOAD = cliprogram.slow ? 2 * 60000 : 15000; private TOO_LONG_TIME_DOWNLOAD: string; @@ -136,7 +138,11 @@ export class P2PSyncDownloader extends ASyncDownloader * @param count The number of blocks to download. * @param chunkIndex The # of the chunk in local algorithm (logging purposes only) */ - private async p2pDownload(from: number, count: number, chunkIndex: number) { + private async p2pDownload( + from: number, + count: number, + chunkIndex: number + ): Promise<BlockDTO[]> { // if this chunk has already been downloaded before, we exclude its supplier node from the download list as it won't give correct answer now const lastSupplier = this.downloads[chunkIndex]; if (lastSupplier) { @@ -148,14 +154,17 @@ export class P2PSyncDownloader extends ASyncDownloader const candidates = await this.getP2Pcandidates(chunkIndex); // Book the nodes this.watcher.gettingChunk(chunkIndex, candidates); - return await this.raceOrCancelIfTimeout( + return await this.raceOrCancelIfTimeout<BlockDTO[]>( this.MAX_DELAY_PER_DOWNLOAD, candidates.map(async (node) => { try { this.handler[chunkIndex] = node; this.nbDownloading++; + console.debug( + "Getting chunk #" + chunkIndex + " on peer " + node.hostName + ); this.watcher.writeStatus( - "Getting chunck #" + + "Getting chunk #" + chunkIndex + "/" + (this.numberOfChunksToDownload - 1) + @@ -166,10 +175,10 @@ export class P2PSyncDownloader extends ASyncDownloader " on peer " + node.hostName ); - let blocks = await node.downloadBlocks(count, from); + let blocks = (await node.downloadBlocks(count, from)) || []; this.watcher.gotChunk(chunkIndex, node); this.watcher.writeStatus( - "GOT chunck #" + + "GOT chunk #" + chunkIndex + "/" + (this.numberOfChunksToDownload - 1) + @@ -226,7 +235,7 @@ export class P2PSyncDownloader extends ASyncDownloader throw Error(DataErrors[DataErrors.NO_NODE_FOUND_TO_DOWNLOAD_CHUNK]); } } - await new Promise((res) => setTimeout(res, 1000)); // Wait 1s before retrying + await new Promise<void>((res) => setTimeout(res, 1000)); // Wait 1s before retrying return this.downloadChunk(index); } } @@ -237,11 +246,11 @@ export class P2PSyncDownloader extends ASyncDownloader * @param races * @returns {Promise} */ - private raceOrCancelIfTimeout(timeout: number, races: any[]) { + private raceOrCancelIfTimeout<T = any>(timeout: number, races: Promise<T>[]) { return Promise.race( [ // Process the race, but cancel it if we don't get an anwser quickly enough - new Promise((resolve, reject) => { + new Promise<T>((resolve, reject) => { setTimeout(() => { reject(this.TOO_LONG_TIME_DOWNLOAD); }, timeout); diff --git a/app/modules/crawler/lib/sync/RemoteSynchronizer.ts b/app/modules/crawler/lib/sync/RemoteSynchronizer.ts index a39350128..a598bfd66 100644 --- a/app/modules/crawler/lib/sync/RemoteSynchronizer.ts +++ b/app/modules/crawler/lib/sync/RemoteSynchronizer.ts @@ -156,8 +156,8 @@ export class RemoteSynchronizer extends AbstractSynchronizer { if (access.isWS2P !== true) { try { endpoint = - [port == 443 ? "BMAS" : "BASIC_MERKLED_API", host, port].join(" ") + - (path ? (" " + path) : ""); + [port == 443 ? "BMAS" : "BASIC_MERKLED_API", host, port].join(" ") + + (path ? " " + path : ""); const contacter = await connect( PeerDTO.fromJSONObject({ endpoints: [endpoint], @@ -272,9 +272,8 @@ export class RemoteSynchronizer extends AbstractSynchronizer { if (!peers.length) { peers.push(DBPeer.fromPeerDTO(this.peer)); } - this.shuffledPeers = (this.noShufflePeers - ? peers - : Underscore.shuffle(peers) + this.shuffledPeers = ( + this.noShufflePeers ? peers : Underscore.shuffle(peers) ).filter((p) => !!p) as JSONDBPeer[]; } diff --git a/app/modules/crawler/lib/sync/WS2PRemoteContacter.ts b/app/modules/crawler/lib/sync/WS2PRemoteContacter.ts index cb0c7bfa7..cec278ca4 100644 --- a/app/modules/crawler/lib/sync/WS2PRemoteContacter.ts +++ b/app/modules/crawler/lib/sync/WS2PRemoteContacter.ts @@ -34,9 +34,7 @@ export class WS2PRemoteContacter implements IRemoteContacter { return this.requester.getBlock(number); } - getMilestones( - page: number - ): Promise<{ + getMilestones(page: number): Promise<{ chunkSize: number; totalPages: number; currentPage: number; diff --git a/app/modules/crawler/lib/sync/p2p/p2p-candidate.ts b/app/modules/crawler/lib/sync/p2p/p2p-candidate.ts index 65366d71e..9df30f665 100644 --- a/app/modules/crawler/lib/sync/p2p/p2p-candidate.ts +++ b/app/modules/crawler/lib/sync/p2p/p2p-candidate.ts @@ -83,11 +83,10 @@ export class P2pCandidate { return (this.api && this.api.hostName) || "NO_API"; } - async downloadBlocks(count: number, from: number) { + async downloadBlocks(count: number, from: number): Promise<BlockDTO[]> { const start = Date.now(); - let error: Error | undefined; this.reserved = false; - this.dlPromise = querablep( + const promise = querablep( (async () => { // We try to download the blocks let blocks: BlockDTO[] = []; @@ -110,6 +109,9 @@ export class P2pCandidate { break; } } + if (!blocks || blocks.length != count) { + throw new Error("Wrong number of blocks from " + this.hostName); + } this.responseTimes.push(Date.now() - start); // Only keep a flow of 5 ttas for the node if (this.responseTimes.length > 5) this.responseTimes.shift(); @@ -117,7 +119,8 @@ export class P2pCandidate { return blocks; })() ); - return this.dlPromise; + this.dlPromise = promise; + return promise; } private getRemoteAPIs() { diff --git a/app/modules/crawler/lib/sync/v2/ValidatorStream.ts b/app/modules/crawler/lib/sync/v2/ValidatorStream.ts index 9f2802eb5..26322bac6 100644 --- a/app/modules/crawler/lib/sync/v2/ValidatorStream.ts +++ b/app/modules/crawler/lib/sync/v2/ValidatorStream.ts @@ -74,7 +74,7 @@ export class ValidatorStream extends Readable { } } catch (e) { failures++; - await new Promise((res) => setTimeout(res, 3000)); + await new Promise<void>((res) => setTimeout(res, 3000)); if (failures >= 15) { NewLogger().error( "Could not get a validation from remote blockchain after %s trials. Stopping sync.", diff --git a/app/modules/daemon.ts b/app/modules/daemon.ts index 7604e6043..aae80b743 100644 --- a/app/modules/daemon.ts +++ b/app/modules/daemon.ts @@ -24,13 +24,11 @@ module.exports = { cliOptions: [ { value: "--loglevel <level>", - desc: - "Logs level, either [error,warning,info,debug,trace]. default to `info`.", + desc: "Logs level, either [error,warning,info,debug,trace]. default to `info`.", }, { value: "--sql-traces", - desc: - "Will log every SQL query that is executed. Requires --loglevel 'trace'.", + desc: "Will log every SQL query that is executed. Requires --loglevel 'trace'.", }, ], @@ -129,7 +127,7 @@ module.exports = { constants.NB_INITIAL_LINES_TO_SHOW ); // Never ending command - return new Promise((res) => null); + return new Promise<void>((res) => null); }, }, { @@ -159,7 +157,7 @@ module.exports = { logger.info(">> Server ready!"); - return new Promise(() => null); // Never ending + return new Promise<void>(() => null); // Never ending }, }, ], @@ -173,7 +171,7 @@ function ServerService(server: Server) { } function startDaemon(daemon: any) { - return new Promise((resolve, reject) => + return new Promise<void>((resolve, reject) => daemon.start((err: any) => { if (err) return reject(err); resolve(); @@ -182,7 +180,7 @@ function startDaemon(daemon: any) { } function stopDaemon(daemon: any) { - return new Promise((resolve, reject) => + return new Promise<void>((resolve, reject) => daemon.stop((err: any) => { err && console.error(err); if (err) return reject(err); diff --git a/app/modules/export-bc.ts b/app/modules/export-bc.ts index 5d3b91098..00b1c6e65 100644 --- a/app/modules/export-bc.ts +++ b/app/modules/export-bc.ts @@ -20,8 +20,7 @@ module.exports = { cli: [ { name: "export-bc [upto]", - desc: - "Exports the whole blockchain as JSON array, up to [upto] block number (excluded).", + desc: "Exports the whole blockchain as JSON array, up to [upto] block number (excluded).", logs: false, onDatabaseExecute: async ( server: Server, diff --git a/app/modules/keypair/index.ts b/app/modules/keypair/index.ts index a809f75fd..d6775e688 100644 --- a/app/modules/keypair/index.ts +++ b/app/modules/keypair/index.ts @@ -34,14 +34,12 @@ export const KeypairDependency = { }, { value: "--keyN <N>", - desc: - "Scrypt `N` CPU/memory cost parameter. Must be a power of 2. Defaults to 4096.", + desc: "Scrypt `N` CPU/memory cost parameter. Must be a power of 2. Defaults to 4096.", parser: parseInt, }, { value: "--keyr <r>", - desc: - "Scrypt `r` The blocksize parameter, which fine-tunes sequential memory read size and performance. Defaults to 16.", + desc: "Scrypt `r` The blocksize parameter, which fine-tunes sequential memory read size and performance. Defaults to 16.", parser: parseInt, }, { @@ -55,8 +53,7 @@ export const KeypairDependency = { }, { value: "--keyfile <filepath>", - desc: - "Force to use the keypair of the given YAML file. File must contain `pub:` and `sec:` fields.", + desc: "Force to use the keypair of the given YAML file. File must contain `pub:` and `sec:` fields.", }, ], @@ -156,7 +153,7 @@ export const KeypairDependency = { }, beforeSave: async ( - conf: KeypairConfDTO, + conf: Partial<KeypairConfDTO>, program: any, logger: any, confDAL: any @@ -172,7 +169,7 @@ export const KeypairDependency = { // We save the key in a separate file const keyring = - 'pub: "' + conf.pair.pub + '"\n' + 'sec: "' + conf.pair.sec + '"'; + 'pub: "' + conf.pair?.pub + '"\n' + 'sec: "' + conf.pair?.sec + '"'; await confDAL.coreFS.write("keyring.yml", keyring); // We never want to store salt, password or keypair in the conf.json file diff --git a/app/modules/keypair/lib/scrypt.ts b/app/modules/keypair/lib/scrypt.ts index 3135ecad6..8e35f8d32 100644 --- a/app/modules/keypair/lib/scrypt.ts +++ b/app/modules/keypair/lib/scrypt.ts @@ -32,24 +32,25 @@ export const Scrypt = async ( r = 16, p = 1 ) => { - const res: { pub: string; sec: string } = await new Promise( - (resolve, reject) => { - crypto.scrypt( - key, - salt, - SEED_LENGTH, - { N, r, p }, - (err: any, seed: Buffer) => { - if (err) return reject(err); - const pair = KeyPairBuilder.fromSeed(seed); - resolve({ - pub: pair.getPublicKey(), - sec: seedToSecretKey(seed), - }); - } - ); - } - ); + const res: { pub: string; sec: string } = await new Promise<{ + pub: string; + sec: string; + }>((resolve, reject) => { + crypto.scrypt( + key, + salt, + SEED_LENGTH, + { N, r, p }, + (err: any, seed: Buffer) => { + if (err) return reject(err); + const pair = KeyPairBuilder.fromSeed(seed); + resolve({ + pub: pair.getPublicKey(), + sec: seedToSecretKey(seed), + }); + } + ); + }); return res; }; diff --git a/app/modules/plugin.ts b/app/modules/plugin.ts index 06c60ff58..5ff2b8149 100644 --- a/app/modules/plugin.ts +++ b/app/modules/plugin.ts @@ -14,7 +14,7 @@ import { ConfDTO } from "../lib/dto/ConfDTO"; import { Server } from "../../server"; -"use strict"; +("use strict"); const fs = require("fs"); const path = require("path"); @@ -31,8 +31,7 @@ module.exports = { cli: [ { name: "plug [what]", - desc: - "Plugs in a duniter module to this Duniter codebase, making it available for the node.", + desc: "Plugs in a duniter module to this Duniter codebase, making it available for the node.", logs: false, onDatabaseExecute: async ( server: Server, @@ -55,8 +54,7 @@ module.exports = { }, { name: "unplug [what]", - desc: - "Plugs in a duniter module to this Duniter codebase, making it available for the node.", + desc: "Plugs in a duniter module to this Duniter codebase, making it available for the node.", logs: false, onDatabaseExecute: async ( server: Server, @@ -86,7 +84,7 @@ function npmInstall( npm: string | null = null, cwd: string | null = null ) { - return new Promise((res, rej) => { + return new Promise<void>((res, rej) => { const node = getNode(); npm = npm || getNPM(); cwd = cwd || getCWD(); @@ -117,7 +115,7 @@ function npmRemove( npm: string | null = null, cwd: string | null = null ) { - return new Promise((res, rej) => { + return new Promise<void>((res, rej) => { const node = getNode(); npm = npm || getNPM(); cwd = cwd || getCWD(); @@ -167,7 +165,7 @@ async function checkNPMAccess() { } async function getNPMAccess() { - const hasAccessToPackageJSON = await new Promise((res) => { + const hasAccessToPackageJSON = await new Promise<boolean>((res) => { fs.access( path.join(__dirname, "/../../package.json"), fs.constants.R_OK | fs.constants.W_OK, @@ -176,7 +174,7 @@ async function getNPMAccess() { } ); }); - const hasAccessToNodeModules = await new Promise((res) => { + const hasAccessToNodeModules = await new Promise<boolean>((res) => { fs.access( path.join(__dirname, "/../../node_modules"), fs.constants.R_OK | fs.constants.W_OK, diff --git a/app/modules/prover/index.ts b/app/modules/prover/index.ts index 80336f874..5451ee88c 100644 --- a/app/modules/prover/index.ts +++ b/app/modules/prover/index.ts @@ -50,7 +50,7 @@ export const ProverDependency = { conf.powSecurityRetryDelay = ProverConstants.POW_SECURITY_RETRY_DELAY; conf.powMaxHandicap = ProverConstants.POW_MAXIMUM_ACCEPTABLE_HANDICAP; }, - beforeSave: async (conf: ConfDTO) => { + beforeSave: async (conf: Partial<ConfDTO>) => { delete conf.powSecurityRetryDelay; delete conf.powMaxHandicap; }, @@ -59,15 +59,12 @@ export const ProverDependency = { service: { output: (server: Server) => { const generator = new BlockGenerator(server); - server.generatorGetJoinData = generator.getSinglePreJoinData.bind( - generator - ); - server.generatorComputeNewCerts = generator.computeNewCerts.bind( - generator - ); - server.generatorNewCertsToLinks = generator.newCertsToLinks.bind( - generator - ); + server.generatorGetJoinData = + generator.getSinglePreJoinData.bind(generator); + server.generatorComputeNewCerts = + generator.computeNewCerts.bind(generator); + server.generatorNewCertsToLinks = + generator.newCertsToLinks.bind(generator); return new Prover(server); }, }, @@ -75,15 +72,12 @@ export const ProverDependency = { methods: { hookServer: (server: Server) => { const generator = new BlockGenerator(server); - server.generatorGetJoinData = generator.getSinglePreJoinData.bind( - generator - ); - server.generatorComputeNewCerts = generator.computeNewCerts.bind( - generator - ); - server.generatorNewCertsToLinks = generator.newCertsToLinks.bind( - generator - ); + server.generatorGetJoinData = + generator.getSinglePreJoinData.bind(generator); + server.generatorComputeNewCerts = + generator.computeNewCerts.bind(generator); + server.generatorNewCertsToLinks = + generator.newCertsToLinks.bind(generator); }, prover: (server: Server) => new Prover(server), blockGenerator: (server: Server, prover: any) => @@ -119,8 +113,7 @@ export const ProverDependency = { }, { value: "--submit-local", - desc: - "With gen-* commands: the generated block is submitted to this node only.", + desc: "With gen-* commands: the generated block is submitted to this node only.", }, { value: "--nocheck-issuer", @@ -128,13 +121,11 @@ export const ProverDependency = { }, { value: "--submit-host <host>", - desc: - "With gen-* commands: the generated block is submitted to `submit-host` node.", + desc: "With gen-* commands: the generated block is submitted to `submit-host` node.", }, { value: "--submit-port <port>", - desc: - "With gen-* commands: the generated block is submitted to `submit-host` node with port `submit-port`.", + desc: "With gen-* commands: the generated block is submitted to `submit-host` node with port `submit-port`.", }, { value: "--at <medianTime>", @@ -155,8 +146,11 @@ export const ProverDependency = { ) => { const difficulty = params[0]; const generator = new BlockGeneratorWhichProves(server, null); - return generateAndSend(program, difficulty, server, () => () => - generator.nextBlock() + return generateAndSend( + program, + difficulty, + server, + () => () => generator.nextBlock() ); }, }, @@ -181,8 +175,11 @@ export const ProverDependency = { catched = true; do { try { - await generateAndSend(program, difficulty, server, () => () => - generator.nextBlock() + await generateAndSend( + program, + difficulty, + server, + () => () => generator.nextBlock() ); catched = false; } catch (e) { @@ -228,9 +225,12 @@ export const ProverDependency = { throw "Difficulty is required."; } const generator = new BlockGenerator(server); - return generateAndSend(program, difficulty, server, () => (): Promise< - BlockDTO - > => generator.manualRoot()); + return generateAndSend( + program, + difficulty, + server, + () => (): Promise<BlockDTO> => generator.manualRoot() + ); }, }, ], @@ -244,7 +244,7 @@ function generateAndSend( getGenerationMethod: any ) { const logger = server.logger; - return new Promise((resolve, reject) => { + return new Promise<any>((resolve, reject) => { if (!program.submitLocal) { if (!program.submitHost) { throw "Option --submit-host is required."; diff --git a/app/modules/prover/lib/blockGenerator.ts b/app/modules/prover/lib/blockGenerator.ts index 66c1aa751..81f8031ec 100644 --- a/app/modules/prover/lib/blockGenerator.ts +++ b/app/modules/prover/lib/blockGenerator.ts @@ -252,9 +252,8 @@ export class BlockGenerator { const identity = await this.dal.getGlobalIdentityByHashForIsMember( leave.idHash ); - const currentMembership = await this.dal.mindexDAL.getReducedMSForImplicitRevocation( - ms.issuer - ); + const currentMembership = + await this.dal.mindexDAL.getReducedMSForImplicitRevocation(ms.issuer); const currentMSN = currentMembership ? parseInt(currentMembership.created_on) : -1; @@ -430,9 +429,8 @@ export class BlockGenerator { joiners ); join.ms = ms; - const currentMembership = await this.dal.mindexDAL.getReducedMSForImplicitRevocation( - ms.issuer - ); + const currentMembership = + await this.dal.mindexDAL.getReducedMSForImplicitRevocation(ms.issuer); const currentMSN = currentMembership ? parseInt(currentMembership.created_on) : -1; @@ -593,14 +591,15 @@ export class BlockGenerator { const isMember = await this.dal.isMember(cert.from); const doubleSignature = !!~certifiers.indexOf(cert.from); if (isMember && !doubleSignature) { - const isValid = await GLOBAL_RULES_HELPERS.checkCertificationIsValidForBlock( - cert, - { number: current.number + 1, currency: current.currency }, - async () => - this.dal.getGlobalIdentityByHashForHashingAndSig(idHash), - this.conf, - this.dal - ); + const isValid = + await GLOBAL_RULES_HELPERS.checkCertificationIsValidForBlock( + cert, + { number: current.number + 1, currency: current.currency }, + async () => + this.dal.getGlobalIdentityByHashForHashingAndSig(idHash), + this.conf, + this.dal + ); if (isValid) { certifiers.push(cert.from); foundCerts.push(cert); diff --git a/app/modules/prover/lib/permanentProver.ts b/app/modules/prover/lib/permanentProver.ts index bf52ee7d7..c3b18dd64 100644 --- a/app/modules/prover/lib/permanentProver.ts +++ b/app/modules/prover/lib/permanentProver.ts @@ -20,6 +20,7 @@ import { parsers } from "../../../lib/common-libs/parsers/index"; import { Server } from "../../../../server"; import { Querable, querablep } from "../../../lib/common-libs/querable"; +import { BlockDTO } from "../../../lib/dto/BlockDTO"; export class PermanentProver { logger: any; @@ -29,12 +30,11 @@ export class PermanentProver { loops: number; private permanencePromise: Querable<void> | null = null; - - private blockchainChangedResolver: any = null; - private promiseOfWaitingBetween2BlocksOfOurs: any = null; - private lastComputedBlock: any = null; - private resolveContinuePromise: any = null; - private continuePromise: any = null; + private blockchainChangedResolver: ((value: void) => void) | null = null; + private promiseOfWaitingBetween2BlocksOfOurs: Promise<void> | null = null; + private lastComputedBlock: BlockDTO | null = null; + private resolveContinuePromise: ((value: boolean) => void) | null = null; + private continuePromise: Promise<boolean> | null = null; constructor(private server: Server) { this.logger = server.logger; @@ -44,7 +44,7 @@ export class PermanentProver { // Promises triggering the prooving lopp this.resolveContinuePromise = null; - this.continuePromise = new Promise( + this.continuePromise = new Promise<boolean>( (resolve) => (this.resolveContinuePromise = resolve) ); @@ -55,13 +55,13 @@ export class PermanentProver { if (!this.permanencePromise || this.permanencePromise.isFulfilled()) { this.startPermanence(); } - this.resolveContinuePromise(true); + this.resolveContinuePromise && this.resolveContinuePromise(true); } async startPermanence() { - let permanenceResolve = () => {}; + let permanenceResolve: (value: void) => void = () => {}; this.permanencePromise = querablep( - new Promise((res) => { + new Promise<void>((res) => { permanenceResolve = res; }) ); @@ -99,8 +99,8 @@ export class PermanentProver { this.checkTrialIsNotTooHigh(trial, current, selfPubkey); const lastIssuedByUs = current.issuer == selfPubkey; if (lastIssuedByUs && !this.promiseOfWaitingBetween2BlocksOfOurs) { - this.promiseOfWaitingBetween2BlocksOfOurs = new Promise((resolve) => - setTimeout(resolve, theConf.powDelay) + this.promiseOfWaitingBetween2BlocksOfOurs = new Promise<void>( + (resolve) => setTimeout(resolve, theConf.powDelay) ); this.logger.warn( "Waiting " + @@ -126,15 +126,15 @@ export class PermanentProver { let cancelAlreadyTriggered = false; // The canceller - (async () => { + setTimeout(async () => { // If the blockchain changes - await new Promise( + await new Promise<void>( (resolve) => (this.blockchainChangedResolver = resolve) ); cancelAlreadyTriggered = true; // Then cancel the generation await this.prover.cancel(); - })(); + }); let unsignedBlock = null, trial2 = 0; @@ -144,7 +144,8 @@ export class PermanentProver { await this.server.BlockchainService.pushFIFO( "generatingNextBlock", async () => { - const current = (await this.server.dal.getCurrentBlockOrNull()) as DBBlock; + const current = + (await this.server.dal.getCurrentBlockOrNull()) as DBBlock; const selfPubkey = this.server.keyPair.publicKey; if (!cancelAlreadyTriggered) { trial2 = await this.server @@ -165,11 +166,13 @@ export class PermanentProver { ); } try { - const obj = parsers.parseBlock.syncWrite( - dos2unix(this.lastComputedBlock.getRawSigned()) - ); + const obj = + this.lastComputedBlock && + parsers.parseBlock.syncWrite( + dos2unix(this.lastComputedBlock.getRawSigned()) + ); await this.server.writeBlock(obj); - await new Promise((res) => { + await new Promise<void>((res) => { this.server.once("bcEvent", () => res()); }); } catch (err) { @@ -201,7 +204,7 @@ export class PermanentProver { await Promise.race( waitingRaces.concat([ // The blockchain has changed! We or someone else found a proof, we must make a gnu one - new Promise( + new Promise<void>( (resolve) => (this.blockchainChangedResolver = () => { this.logger.warn("Blockchain changed!"); @@ -210,7 +213,7 @@ export class PermanentProver { ), // Security: if nothing happens for a while, trigger the whole process again - new Promise((resolve) => + new Promise<void>((resolve) => setTimeout(() => { if (!raceDone) { this.logger.warn( @@ -251,10 +254,10 @@ export class PermanentProver { } } - async stopEveryting() { + async stopEverything() { // First: avoid continuing the main loop - this.resolveContinuePromise(true); - this.continuePromise = new Promise( + this.resolveContinuePromise && this.resolveContinuePromise(true); + this.continuePromise = new Promise<boolean>( (resolve) => (this.resolveContinuePromise = resolve) ); // Second: stop any started proof diff --git a/app/modules/prover/lib/proof.ts b/app/modules/prover/lib/proof.ts index 2ce2942c5..5956d8eb4 100644 --- a/app/modules/prover/lib/proof.ts +++ b/app/modules/prover/lib/proof.ts @@ -248,9 +248,8 @@ export function createPowWorker() { if (!found) { // CPU speed recording if (turn > 0) { - cpuUsage = profiler.cpuUsageOverLastMilliseconds( - turnDuration - ); + cpuUsage = + profiler.cpuUsageOverLastMilliseconds(turnDuration); if ( cpuUsage > currentCPU + 0.005 || cpuUsage < currentCPU - 0.005 @@ -296,9 +295,8 @@ export function createPowWorker() { if (currentProofCheck === "") { askedStop = true; } else { - const [currentNumber, currentHash] = currentProofCheck.split( - "-" - ); + const [currentNumber, currentHash] = + currentProofCheck.split("-"); if ( block.number !== parseInt(currentNumber) + 1 || block.previousHash !== currentHash @@ -383,7 +381,7 @@ export function createPowWorker() { } function pSend(stuff: any) { - return new Promise(function (resolve, reject) { + return new Promise<void>(function (resolve, reject) { if (process.send) { process.send(stuff, function (error: any) { !error && resolve(); diff --git a/app/modules/prover/lib/prover.ts b/app/modules/prover/lib/prover.ts index c1adcbdea..dbdce3328 100644 --- a/app/modules/prover/lib/prover.ts +++ b/app/modules/prover/lib/prover.ts @@ -45,6 +45,6 @@ export class Prover extends stream.Transform { } async stopService() { - await this.permaProver.stopEveryting(); + await this.permaProver.stopEverything(); } } diff --git a/app/modules/reapply.ts b/app/modules/reapply.ts index 873120d5b..00827ba37 100644 --- a/app/modules/reapply.ts +++ b/app/modules/reapply.ts @@ -20,8 +20,7 @@ module.exports = { cli: [ { name: "reapply-to [number]", - desc: - "Reapply reverted blocks until block #[number] is reached. EXPERIMENTAL", + desc: "Reapply reverted blocks until block #[number] is reached. EXPERIMENTAL", preventIfRunning: true, onDatabaseExecute: async ( server: Server, diff --git a/app/modules/reset.ts b/app/modules/reset.ts index b14582eab..a12e2931a 100644 --- a/app/modules/reset.ts +++ b/app/modules/reset.ts @@ -24,8 +24,7 @@ module.exports = { cli: [ { name: "reset [config|data|peers|stats|all]", - desc: - "Reset configuration, data, peers, transactions or everything in the database", + desc: "Reset configuration, data, peers, transactions or everything in the database", preventIfRunning: true, onConfiguredExecute: async ( diff --git a/app/modules/revert.ts b/app/modules/revert.ts index 2c53bcfb2..6989c898c 100644 --- a/app/modules/revert.ts +++ b/app/modules/revert.ts @@ -19,8 +19,7 @@ module.exports = { cli: [ { name: "revert [count]", - desc: - "Revert (undo + remove) the top [count] blocks from the blockchain. EXPERIMENTAL", + desc: "Revert (undo + remove) the top [count] blocks from the blockchain. EXPERIMENTAL", preventIfRunning: true, onDatabaseExecute: async ( @@ -44,8 +43,7 @@ module.exports = { }, { name: "revert-to [number]", - desc: - "Revert (undo + remove) top blockchain blocks until block #[number] is reached. EXPERIMENTAL", + desc: "Revert (undo + remove) top blockchain blocks until block #[number] is reached. EXPERIMENTAL", onDatabaseExecute: async ( server: Server, conf: ConfDTO, diff --git a/app/modules/upnp-provider.ts b/app/modules/upnp-provider.ts index 7631e3196..6783bb937 100644 --- a/app/modules/upnp-provider.ts +++ b/app/modules/upnp-provider.ts @@ -43,7 +43,7 @@ export class UpnpProvider { async checkUPnPisAvailable() { try { - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { this.client.externalIp((err: any, res: any) => { if (err || !res) { reject(); @@ -179,7 +179,7 @@ export class UpnpProvider { } static async getUPnPMappings(client: any): Promise<any> { - return new Promise((resolve, reject) => { + return new Promise<any>((resolve, reject) => { client.getMappings((err: any, res: any) => { if (err) { reject(err); diff --git a/app/modules/wizard.ts b/app/modules/wizard.ts index f68f26447..1bfcc3bf0 100644 --- a/app/modules/wizard.ts +++ b/app/modules/wizard.ts @@ -29,8 +29,7 @@ module.exports = { cli: [ { - name: - "wizard [key|network|network-reconfigure|currency|pow|parameters]", + name: "wizard [key|network|network-reconfigure|currency|pow|parameters]", desc: "Launch the configuration wizard.", onConfiguredExecute: async ( diff --git a/app/modules/ws2p/lib/WS2PCluster.ts b/app/modules/ws2p/lib/WS2PCluster.ts index 854dfed12..812c32af6 100644 --- a/app/modules/ws2p/lib/WS2PCluster.ts +++ b/app/modules/ws2p/lib/WS2PCluster.ts @@ -168,34 +168,16 @@ export class WS2PCluster { if (!h.sigV2) { throw "HEAD_MESSAGE_WRONGLY_SIGNED"; } else { - const [ - , - , - , - pub, - blockstamp, - ws2pId, - , - , - , - , - ]: string[] = h.messageV2.split(":"); + const [, , , pub, blockstamp, ws2pId, , , , ,]: string[] = + h.messageV2.split(":"); this.headReceived(h, pub, [pub, ws2pId].join("-"), blockstamp); } } // HEAD v1 and HEAD v0 else if (h.message && h.sig) { if (h.message.match(WS2PConstants.HEAD_V1_REGEXP)) { - const [ - , - , - , - pub, - blockstamp, - ws2pId, - , - , - ]: string[] = h.message.split(":"); + const [, , , pub, blockstamp, ws2pId, , ,]: string[] = + h.message.split(":"); await this.headReceived( h, pub, @@ -343,9 +325,10 @@ export class WS2PCluster { } if (!exists) { // Do we have this block in the DB? - exists = !!(await this.server.dal.getAbsoluteBlockInForkWindowByBlockstamp( - blockstamp - )); + exists = + !!(await this.server.dal.getAbsoluteBlockInForkWindowByBlockstamp( + blockstamp + )); } // Update the last time it was checked this.blockstampsCache[blockstamp] = Date.now(); @@ -572,7 +555,7 @@ export class WS2PCluster { const canReachClearEndpoint = ProxiesConf.canReachClearEndpoint( this.server.conf.proxiesConf ); - const isMember = (await this.server.dal.isMember(this.server.conf.pair.pub)); + const isMember = await this.server.dal.isMember(this.server.conf.pair.pub); peers.sort((a, b) => { // Top priority at our own nodes if ( @@ -768,9 +751,7 @@ export class WS2PCluster { freeMemberRoom, freeMirorRoom, ]: string[] = messageV2.split(":"); - return isMember - ? freeMemberRoom - : freeMirorRoom; + return isMember ? freeMemberRoom : freeMirorRoom; } } } @@ -837,9 +818,8 @@ export class WS2PCluster { // Block received else if (data.joiners) { // Update the cache - this.blockstampsCache[ - [data.number, data.hash].join("-") - ] = Date.now(); + this.blockstampsCache[[data.number, data.hash].join("-")] = + Date.now(); } // HEAD changed diff --git a/app/modules/ws2p/lib/WS2PConnection.ts b/app/modules/ws2p/lib/WS2PConnection.ts index e186327f1..b7c88c4f7 100644 --- a/app/modules/ws2p/lib/WS2PConnection.ts +++ b/app/modules/ws2p/lib/WS2PConnection.ts @@ -528,7 +528,7 @@ export class WS2PConnection { try { await Promise.race([ connectionTimeout, - new Promise((resolve, reject) => { + new Promise<void>((resolve, reject) => { (async () => { await this.onWsOpened; try { @@ -685,10 +685,11 @@ export class WS2PConnection { // Request message else if (data.reqId && typeof data.reqId === "string") { try { - const answer = await this.messageHandler.answerToRequest( - data.body, - this - ); + const answer = + await this.messageHandler.answerToRequest( + data.body, + this + ); this.ws.send( JSON.stringify({ resId: data.reqId, body: answer }) ); @@ -737,7 +738,7 @@ export class WS2PConnection { async request(body: WS2PRequest) { await this.connectAsInitiator(); const uuid = nuuid.v4(); - return new Promise((resolve, reject) => { + return new Promise<void>((resolve, reject) => { this.nbRequestsCount++; this.ws.send( JSON.stringify({ @@ -761,7 +762,7 @@ export class WS2PConnection { extras, Promise.race([ // The answer - new Promise((res, rej) => { + new Promise<void>((res, rej) => { extras.resolve = res; extras.reject = () => { this.errorDetected(WS2P_ERR.REQUEST_FAILED); @@ -827,7 +828,7 @@ export class WS2PConnection { async pushData(type: WS2P_PUSH, key: string, data: any) { await this.connectAsInitiator(); - return new Promise((resolve, reject) => { + return new Promise<void>((resolve, reject) => { this.nbPushsToRemoteCount++; try { this.ws.send( diff --git a/app/modules/ws2p/lib/WS2PServer.ts b/app/modules/ws2p/lib/WS2PServer.ts index 5ebf238f6..fa66c2462 100644 --- a/app/modules/ws2p/lib/WS2PServer.ts +++ b/app/modules/ws2p/lib/WS2PServer.ts @@ -288,7 +288,7 @@ export class WS2PServer extends events.EventEmitter { async close() { await Promise.all(this.connections.map((c) => c.close())); - return new Promise((res, rej) => { + return new Promise<void>((res, rej) => { this.wss.close((err: any) => { if (err) return rej(err); res(); diff --git a/app/modules/ws2p/lib/impl/WS2PReqMapperByServer.ts b/app/modules/ws2p/lib/impl/WS2PReqMapperByServer.ts index b62efe936..1b69ae957 100644 --- a/app/modules/ws2p/lib/impl/WS2PReqMapperByServer.ts +++ b/app/modules/ws2p/lib/impl/WS2PReqMapperByServer.ts @@ -44,9 +44,9 @@ export class WS2PReqMapperByServer implements WS2PReqMapper { if (!current || current.number < from) { return []; } - return ( - await this.server.dal.getBlocksBetween(from, from + count - 1) - ).map((b: DBBlock) => BlockDTO.fromJSONObject(b)); + return (await this.server.dal.getBlocksBetween(from, from + count - 1)).map( + (b: DBBlock) => BlockDTO.fromJSONObject(b) + ); } getMilestones(page: number): Promise<HttpMilestonePage> { diff --git a/app/service/BlockchainService.ts b/app/service/BlockchainService.ts index 63c4d5c78..2a2ff5798 100644 --- a/app/service/BlockchainService.ts +++ b/app/service/BlockchainService.ts @@ -122,7 +122,8 @@ export class BlockchainService extends FIFOService { throw Error(DataErrors[DataErrors.CANNOT_REVERT_NO_CURRENT_BLOCK]); } for (let i = 0, count = current.number - number; i < count; i++) { - const reverted = await this.bcService.mainContext.revertCurrentBlock(); + const reverted = + await this.bcService.mainContext.revertCurrentBlock(); blocks.push(BlockDTO.fromJSONObject(reverted)); } if (current.number < number) { @@ -432,9 +433,8 @@ export class BlockchainService extends FIFOService { ); } // Expiration of current membershship - const currentMembership = await this.dal.mindexDAL.getReducedMSForImplicitRevocation( - pubkey - ); + const currentMembership = + await this.dal.mindexDAL.getReducedMSForImplicitRevocation(pubkey); const currentMSN = currentMembership ? parseInt(currentMembership.created_on) : -1; diff --git a/app/service/IdentityService.ts b/app/service/IdentityService.ts index f3173f885..6389958c9 100644 --- a/app/service/IdentityService.ts +++ b/app/service/IdentityService.ts @@ -30,7 +30,7 @@ import { MindexEntry } from "../lib/indexer"; import { DataErrors } from "../lib/common-libs/errors"; import { Tristamp } from "../lib/common/Tristamp"; -"use strict"; +("use strict"); const constants = require("../lib/constants"); const BY_ABSORPTION = true; @@ -164,9 +164,10 @@ export class IdentityService extends FIFOService { ) { throw constants.ERRORS.BLOCKSTAMP_DOES_NOT_MATCH_A_BLOCK; } else if (current) { - let basedBlock = await this.dal.getAbsoluteValidBlockInForkWindowByBlockstamp( - idty.buid - ); + let basedBlock = + await this.dal.getAbsoluteValidBlockInForkWindowByBlockstamp( + idty.buid + ); if (!basedBlock) { throw constants.ERRORS.BLOCKSTAMP_DOES_NOT_MATCH_A_BLOCK; } @@ -218,9 +219,8 @@ export class IdentityService extends FIFOService { obj.currency = this.conf.currency || obj.currency; const cert = CertificationDTO.fromJSONObject(obj); const targetHash = cert.getTargetHash(); - let possiblyNullIdty = await this.dal.getGlobalIdentityByHashForHashingAndSig( - targetHash - ); + let possiblyNullIdty = + await this.dal.getGlobalIdentityByHashForHashingAndSig(targetHash); let idtyAbsorbed = false; const idty: { pubkey: string; @@ -270,8 +270,7 @@ export class IdentityService extends FIFOService { if (cert.block_number == 0 && !basedBlock) { basedBlock = { number: 0, - hash: - "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", + hash: "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", medianTime: 0, }; } diff --git a/app/service/MembershipService.ts b/app/service/MembershipService.ts index d09af9f1d..f3486d4b0 100644 --- a/app/service/MembershipService.ts +++ b/app/service/MembershipService.ts @@ -54,9 +54,8 @@ export class MembershipService extends FIFOService { throw constants.ERRORS.WRONG_SIGNATURE_MEMBERSHIP; } // Get already existing Membership with same parameters - const mostRecentNumber = await this.dal.getMostRecentMembershipNumberForIssuer( - entry.issuer - ); + const mostRecentNumber = + await this.dal.getMostRecentMembershipNumberForIssuer(entry.issuer); const thisNumber = entry.number; if (mostRecentNumber == thisNumber) { throw constants.ERRORS.ALREADY_RECEIVED_MEMBERSHIP; diff --git a/app/service/PeeringService.ts b/app/service/PeeringService.ts index daec3e589..f61bed550 100755 --- a/app/service/PeeringService.ts +++ b/app/service/PeeringService.ts @@ -245,9 +245,8 @@ export class PeeringService { let savedPeer = PeerDTO.fromJSONObject(peerEntity).toDBPeer(); if (peerEntity.pubkey == this.selfPubkey) { const localEndpoints = await this.server.getEndpoints(); - const localNodeNotListed = !peerEntityOld.containsAllEndpoints( - localEndpoints - ); + const localNodeNotListed = + !peerEntityOld.containsAllEndpoints(localEndpoints); const current = localNodeNotListed && (await this.dal.getCurrentBlockOrNull()); if ( @@ -342,9 +341,8 @@ export class PeeringService { } // The number cannot be superior to current block minBlock = Math.min(minBlock, current ? current.number : minBlock); - const targetBlockstamp: - | string - | null = await this.server.dal.getBlockstampOf(minBlock); + const targetBlockstamp: string | null = + await this.server.dal.getBlockstampOf(minBlock); const p2: any = { version: constants.DOCUMENTS_VERSION, currency: currency, diff --git a/test/fast/modules/ws2p/single_write.ts b/test/fast/modules/ws2p/single_write.ts index 31d8d0905..667aedcc5 100644 --- a/test/fast/modules/ws2p/single_write.ts +++ b/test/fast/modules/ws2p/single_write.ts @@ -26,7 +26,7 @@ describe('WS2P Single Write limiter', () => { const source = new Readable() const protection = new WS2PSingleWriteStream(PROTECTION_DURATION) let nbDocs = 0 - await new Promise(res => { + await new Promise<void>(res => { source .pipe(protection) .pipe(es.mapSync(() => { @@ -56,4 +56,4 @@ class Readable extends stream.Readable { async _read() { } -} \ No newline at end of file +} diff --git a/test/fast/prover/prover-pow-1-cluster.ts b/test/fast/prover/prover-pow-1-cluster.ts index ea00618c0..3560bf861 100644 --- a/test/fast/prover/prover-pow-1-cluster.ts +++ b/test/fast/prover/prover-pow-1-cluster.ts @@ -111,7 +111,7 @@ describe('PoW Cluster', () => { } } }) - await new Promise(res => { + await new Promise<void>(res => { master.onInfoMessage = () => res() }) await master.cancelWork() diff --git a/test/integration/fork-resolution/register-fork-blocks.ts b/test/integration/fork-resolution/register-fork-blocks.ts index d448373d5..920d6f21b 100644 --- a/test/integration/fork-resolution/register-fork-blocks.ts +++ b/test/integration/fork-resolution/register-fork-blocks.ts @@ -176,7 +176,7 @@ describe("Fork blocks", function() { await s2.sharePeeringWith(s1) await s2.writeBlock(b4a) const b3c = await s3.commit({ time: now + 33 }) - await new Promise((res, rej) => { + await new Promise<void>((res, rej) => { const event = CommonConstants.DocumentError s2.on(event, (e:any) => { try { diff --git a/test/integration/misc/http-api.ts b/test/integration/misc/http-api.ts index 6ec11146c..1dcb732f6 100644 --- a/test/integration/misc/http-api.ts +++ b/test/integration/misc/http-api.ts @@ -350,7 +350,7 @@ function postBlock(server2:TestingServer) { }) .then(async (result:HttpBlock) => { const numberToReach = block.number - await new Promise((res) => { + await new Promise<void>((res) => { const interval = setInterval(async () => { const current = await server2.dal.getCurrentBlockOrNull() if (current && current.number == numberToReach) { diff --git a/test/integration/proof-of-work/continuous-proof.ts b/test/integration/proof-of-work/continuous-proof.ts index 1db5b4f28..63fba46cd 100644 --- a/test/integration/proof-of-work/continuous-proof.ts +++ b/test/integration/proof-of-work/continuous-proof.ts @@ -117,9 +117,9 @@ describe("Continous proof-of-work", function() { s2.startBlockComputation(); await s2.until('block', 15); await s2.stopBlockComputation(); - await [ + await Promise.all([ CrawlerDependency.duniter.methods.pullBlocks(s3._server), - new Promise(res => { + new Promise<void>(res => { s3.pipe(es.mapSync((e:any) => { if (e.number === 15) { res() @@ -129,7 +129,7 @@ describe("Continous proof-of-work", function() { }), s3.startBlockComputation() - ]; + ]); const current = await s3.get('/blockchain/current') await s3.stopBlockComputation(); current.number.should.be.aboveOrEqual(14) diff --git a/test/integration/tools/test-until.ts b/test/integration/tools/test-until.ts index 4c05899ea..eff7ba46b 100644 --- a/test/integration/tools/test-until.ts +++ b/test/integration/tools/test-until.ts @@ -18,7 +18,7 @@ const UNTIL_TIMEOUT = 115000; export function until(server:TestingServer, eventName:string, count:number) { let counted = 0; const max = count == undefined ? 1 : count; - return new Promise(function (resolve, reject) { + return new Promise<void>(function (resolve, reject) { let finished = false; server._server.on(eventName, function () { counted++; diff --git a/test/integration/tools/toolbox.ts b/test/integration/tools/toolbox.ts index 5dd1d545b..5c3b65dcf 100644 --- a/test/integration/tools/toolbox.ts +++ b/test/integration/tools/toolbox.ts @@ -260,7 +260,7 @@ export const NewTestingServer = (conf:any) => { } export const serverWaitBlock = async (server:Server, number:number) => { - await new Promise((res) => { + await new Promise<void>((res) => { const interval = setInterval(async () => { const current = await server.dal.getCurrentBlockOrNull() if (current && current.number == number) { @@ -276,7 +276,7 @@ export const waitToHaveBlock = async (server:Server, number:number) => { } export const waitForkResolution = async (server:Server, number:number) => { - await new Promise(res => { + await new Promise<void>(res => { server.pipe(es.mapSync((e:any) => { if (e.bcEvent === 'switched' && e.block.number === number) { res() @@ -288,7 +288,7 @@ export const waitForkResolution = async (server:Server, number:number) => { } export const waitForkWS2PConnection = async (server:Server, pubkey:string) => { - await new Promise(res => { + await new Promise<void>(res => { server.pipe(es.mapSync((e:any) => { if (e.ws2p === 'connected' && e.to.pubkey === pubkey) { res() @@ -300,7 +300,7 @@ export const waitForkWS2PConnection = async (server:Server, pubkey:string) => { } export const waitForkWS2PDisconnection = async (server:Server, pubkey:string) => { - await new Promise(res => { + await new Promise<void>((res) => { server.pipe(es.mapSync((e:any) => { if (e.ws2p === 'disconnected' && e.peer.pub === pubkey) { res() @@ -473,7 +473,7 @@ export class TestingServer { } push(chunk: any, encoding?: string) { - return this.server.push(chunk, encoding) + return this.server.push(chunk, encoding as BufferEncoding) } pipe(writable:stream.Writable) { @@ -562,7 +562,7 @@ export class TestingServer { async commitWaitError(options:any, expectedError:string) { const results = await Promise.all([ - new Promise(res => { + new Promise<void>((res) => { this.server.pipe(es.mapSync((e:any) => { if (e.blockResolutionError === expectedError) { res() -- GitLab