From ae3c7840e886d75cc57ff7a6b928c90841cae27d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Moreau?= <cem.moreau@gmail.com> Date: Tue, 8 May 2018 22:01:01 +0200 Subject: [PATCH] [enh] Refactoring: migrated remaining .js files to .ts --- .gitignore | 71 +--- app/lib/common-libs/errors.ts | 1 + app/lib/computation/BlockchainContext.ts | 2 +- app/lib/dal/indexDAL/abstract/TxsDAO.ts | 4 + app/lib/logger.ts | 2 +- app/modules/crawler/index.ts | 2 +- app/modules/crawler/lib/crawler.ts | 4 +- app/modules/prover/lib/blockGenerator.ts | 2 +- app/modules/prover/lib/permanentProver.ts | 2 +- app/service/BlockchainService.ts | 19 +- test/dal/{source_dal.js => sources-dal.ts} | 40 +-- test/dal/{triming.js => triming-dal.ts} | 161 +++++---- test/data/{blocks.js => blocks-data.ts} | 2 +- test/{eslint.js => eslint-test.ts} | 2 +- test/fast/block_local.js | 124 ------- test/fast/cfs.js | 155 -------- .../{common/crypto.js => crypto/crypto.ts} | 37 +- .../randomKey.js => crypto/randomKey.ts} | 26 +- .../{block_format.js => misc/block-format.ts} | 16 +- test/fast/misc/block-local.ts | 122 +++++++ test/fast/misc/cfs.ts | 137 +++++++ test/fast/{database.js => misc/database.ts} | 68 ++-- test/fast/{entities.js => misc/entities.ts} | 6 +- test/fast/{merkle.js => misc/merkle.ts} | 11 +- .../bma/{ddos-test.js => bma-ddos-test.ts} | 0 .../{limiter-test.js => bma-limiter-test.ts} | 0 .../{module-test.js => bma-module-test.ts} | 76 ++-- .../{crypto.js => common-crypto-test.ts} | 36 +- .../{peering.js => common-peering-test.ts} | 8 +- .../{randomKey.js => common-random-key.ts} | 27 +- .../{tx_format.js => common-tx-format.ts} | 10 +- ...arbaging.js => crawler-peers-garbaging.ts} | 35 +- ...{crypto-test.js => keypair-crypto-test.ts} | 25 +- ...{module-test.js => keypair-module-test.ts} | 24 +- test/fast/protocol-brg107-udEffectiveTime.js | 53 --- test/fast/protocol-brg11-udTime.js | 53 --- test/fast/protocol-brg49-version.js | 47 --- test/fast/protocol-brg50-blocksize.js | 68 ---- test/fast/protocol-brg51-number.js | 80 ----- .../protocol-brg106-number.ts} | 26 +- .../protocol-brg107-udEffectiveTime.ts | 52 +++ test/fast/protocol/protocol-brg11-udTime.ts | 52 +++ .../protocol-brg13-dividend.ts} | 68 ++-- test/fast/protocol/protocol-brg49-version.ts | 46 +++ .../fast/protocol/protocol-brg50-blocksize.ts | 67 ++++ test/fast/protocol/protocol-brg51-number.ts | 79 +++++ ...w-1-cluster.ts => prover-pow-1-cluster.ts} | 13 +- ...pow-2-engine.js => prover-pow-2-engine.ts} | 45 ++- ...pow-3-prover.js => prover-pow-3-prover.ts} | 0 .../community-collapse.ts | 6 +- .../newcomers-shuffling.ts} | 61 ++-- .../start-generate-blocks.ts | 12 +- test/integration/branches/branches2.ts | 110 +++--- .../branches/branches_pending_data.ts | 7 +- test/integration/branches/branches_revert2.ts | 28 +- test/integration/branches/branches_switch.ts | 89 +++-- .../certification_chainability.ts | 6 +- .../register-fork-blocks.ts} | 193 +++++----- .../identity/identity-absorption.ts | 6 +- .../identity/identity-clean-test.ts | 20 +- test/integration/identity/identity-expiry.ts | 7 +- .../identity-implicit-revocation.ts} | 77 ++-- .../identity-kicking-by-certs.ts} | 87 +++-- test/integration/identity/identity-kicking.ts | 6 +- test/integration/identity/identity-lookup.ts | 10 +- .../identity/identity-revocation-test.ts | 6 +- .../identity-same-pubkey.ts} | 33 +- .../identity/identity-several-tests.ts | 132 +++---- test/integration/identity/identity-test.ts | 10 +- test/integration/misc/http-api.ts | 14 +- .../single-document-treatment.ts} | 70 ++-- test/integration/network/network-merkle.ts | 23 +- test/integration/network/network-peerings.ts | 41 +-- .../network/network-peers-same-pubkey.ts | 8 +- test/integration/network/network-update.ts | 5 +- .../peer-outdated.ts} | 94 +++-- .../continuous-proof.ts} | 104 +++--- .../proof-of-work.ts} | 87 +++-- .../{v0.4-times.js => protocol/v0.4-times.ts} | 30 +- .../v0.5-identity-blockstamp.ts} | 41 +-- .../v0.5-transactions.ts} | 32 +- .../v0.6-difficulties.ts} | 112 +++--- .../v1.0-double-dividend.ts} | 64 ++-- .../v1.0-g1-dividend-long-run.ts} | 48 ++- .../v1.0-g1-dividend.ts} | 72 ++-- .../v1.0-modules-api.ts} | 176 ++++----- .../v1.1-dividend.ts} | 69 ++-- test/integration/revoked_pubkey_replay.ts | 3 +- .../server-sandbox.ts} | 25 +- .../sources-property.ts} | 29 +- test/integration/tools/TestUser.ts | 2 +- test/integration/tools/commit.js | 69 ---- test/integration/tools/http-expect.ts | 83 +++++ test/integration/tools/http.js | 94 ----- test/integration/tools/node.js | 335 ------------------ .../{shutDownEngine.js => shutdown-engine.ts} | 12 +- .../tools/{sync.js => test-sync.ts} | 17 +- .../tools/{until.js => test-until.ts} | 16 +- test/integration/tools/toolbox.ts | 66 ++-- test/integration/tools/unit.js | 41 --- test/integration/transactions-chaining.ts | 20 +- test/integration/transactions-csv-cltv-sig.ts | 5 +- .../transactions/transaction-crosschain.ts | 28 +- .../transactions-pruning.ts} | 67 ++-- test/integration/wot/wotb.ts | 58 ++- .../{ => ws2p}/ws2p_client_limitations.ts | 6 +- test/integration/{ => ws2p}/ws2p_cluster.ts | 8 +- .../integration/{ => ws2p}/ws2p_connection.ts | 17 +- .../{ => ws2p}/ws2p_doc_sharing.ts | 6 +- test/integration/{ => ws2p}/ws2p_docpool.ts | 8 +- test/integration/{ => ws2p}/ws2p_exchange.ts | 16 +- test/integration/{ => ws2p}/ws2p_heads.ts | 6 +- test/integration/{ => ws2p}/ws2p_network.ts | 6 +- test/integration/{ => ws2p}/ws2p_pulling.ts | 10 +- .../{ => ws2p}/ws2p_server_limitations.ts | 6 +- 115 files changed, 2178 insertions(+), 2883 deletions(-) rename test/dal/{source_dal.js => sources-dal.ts} (66%) rename test/dal/{triming.js => triming-dal.ts} (63%) rename test/data/{blocks.js => blocks-data.ts} (99%) rename test/{eslint.js => eslint-test.ts} (97%) delete mode 100644 test/fast/block_local.js delete mode 100644 test/fast/cfs.js rename test/fast/{common/crypto.js => crypto/crypto.ts} (68%) rename test/fast/{common/randomKey.js => crypto/randomKey.ts} (63%) rename test/fast/{block_format.js => misc/block-format.ts} (92%) create mode 100644 test/fast/misc/block-local.ts create mode 100644 test/fast/misc/cfs.ts rename test/fast/{database.js => misc/database.ts} (62%) rename test/fast/{entities.js => misc/entities.ts} (88%) rename test/fast/{merkle.js => misc/merkle.ts} (91%) rename test/fast/modules/bma/{ddos-test.js => bma-ddos-test.ts} (100%) rename test/fast/modules/bma/{limiter-test.js => bma-limiter-test.ts} (100%) rename test/fast/modules/bma/{module-test.js => bma-module-test.ts} (67%) rename test/fast/modules/common/{crypto.js => common-crypto-test.ts} (61%) rename test/fast/modules/common/{peering.js => common-peering-test.ts} (93%) rename test/fast/modules/common/{randomKey.js => common-random-key.ts} (61%) rename test/fast/modules/common/{tx_format.js => common-tx-format.ts} (88%) rename test/fast/modules/crawler/{peers_garbaging.js => crawler-peers-garbaging.ts} (59%) rename test/fast/modules/keypair/{crypto-test.js => keypair-crypto-test.ts} (77%) rename test/fast/modules/keypair/{module-test.js => keypair-module-test.ts} (75%) delete mode 100644 test/fast/protocol-brg107-udEffectiveTime.js delete mode 100644 test/fast/protocol-brg11-udTime.js delete mode 100644 test/fast/protocol-brg49-version.js delete mode 100644 test/fast/protocol-brg50-blocksize.js delete mode 100644 test/fast/protocol-brg51-number.js rename test/fast/{protocol-brg106-number.js => protocol/protocol-brg106-number.ts} (88%) create mode 100644 test/fast/protocol/protocol-brg107-udEffectiveTime.ts create mode 100644 test/fast/protocol/protocol-brg11-udTime.ts rename test/fast/{protocol-brg13-dividend.js => protocol/protocol-brg13-dividend.ts} (54%) create mode 100644 test/fast/protocol/protocol-brg49-version.ts create mode 100644 test/fast/protocol/protocol-brg50-blocksize.ts create mode 100644 test/fast/protocol/protocol-brg51-number.ts rename test/fast/prover/{pow-1-cluster.ts => prover-pow-1-cluster.ts} (92%) rename test/fast/prover/{pow-2-engine.js => prover-pow-2-engine.ts} (75%) rename test/fast/prover/{pow-3-prover.js => prover-pow-3-prover.ts} (100%) rename test/integration/{blocks => block-generation}/community-collapse.ts (92%) rename test/integration/{newcomers-shuffling.js => block-generation/newcomers-shuffling.ts} (68%) rename test/integration/{blocks => block-generation}/start-generate-blocks.ts (95%) rename test/integration/{register-fork-blocks.js => fork-resolution/register-fork-blocks.ts} (59%) rename test/integration/{identity-implicit-revocation.js => identity/identity-implicit-revocation.ts} (63%) rename test/integration/{identity-kicking-by-certs.js => identity/identity-kicking-by-certs.ts} (64%) rename test/integration/{identity-same-pubkey.js => identity/identity-same-pubkey.ts} (83%) rename test/integration/{single-document-treatment.js => misc/single-document-treatment.ts} (69%) rename test/integration/{peer-outdated.js => network/peer-outdated.ts} (65%) rename test/integration/{continuous-proof.js => proof-of-work/continuous-proof.ts} (63%) rename test/integration/{proof-of-work.js => proof-of-work/proof-of-work.ts} (68%) rename test/integration/{v0.4-times.js => protocol/v0.4-times.ts} (69%) rename test/integration/{v0.5-identity-blockstamp.js => protocol/v0.5-identity-blockstamp.ts} (58%) rename test/integration/{v0.5-transactions.js => protocol/v0.5-transactions.ts} (65%) rename test/integration/{v0.6-difficulties.js => protocol/v0.6-difficulties.ts} (60%) rename test/integration/{v1.0-double-dividend.js => protocol/v1.0-double-dividend.ts} (63%) rename test/integration/{v1.0-g1-dividend-long-run.js => protocol/v1.0-g1-dividend-long-run.ts} (74%) rename test/integration/{v1.0-g1-dividend.js => protocol/v1.0-g1-dividend.ts} (71%) rename test/integration/{v1.0-modules-api.js => protocol/v1.0-modules-api.ts} (71%) rename test/integration/{v1.1-dividend.js => protocol/v1.1-dividend.ts} (76%) rename test/integration/{server-sandbox.js => sandbox/server-sandbox.ts} (94%) rename test/integration/{sources_property.js => sources/sources-property.ts} (71%) delete mode 100644 test/integration/tools/commit.js create mode 100644 test/integration/tools/http-expect.ts delete mode 100644 test/integration/tools/http.js delete mode 100644 test/integration/tools/node.js rename test/integration/tools/{shutDownEngine.js => shutdown-engine.ts} (74%) rename test/integration/tools/{sync.js => test-sync.ts} (70%) rename test/integration/tools/{until.js => test-until.ts} (79%) delete mode 100644 test/integration/tools/unit.js rename test/integration/{transactions-pruning.js => transactions/transactions-pruning.ts} (63%) rename test/integration/{ => ws2p}/ws2p_client_limitations.ts (98%) rename test/integration/{ => ws2p}/ws2p_cluster.ts (96%) rename test/integration/{ => ws2p}/ws2p_connection.ts (97%) rename test/integration/{ => ws2p}/ws2p_doc_sharing.ts (96%) rename test/integration/{ => ws2p}/ws2p_docpool.ts (92%) rename test/integration/{ => ws2p}/ws2p_exchange.ts (81%) rename test/integration/{ => ws2p}/ws2p_heads.ts (96%) rename test/integration/{ => ws2p}/ws2p_network.ts (95%) rename test/integration/{ => ws2p}/ws2p_pulling.ts (93%) rename test/integration/{ => ws2p}/ws2p_server_limitations.ts (98%) diff --git a/.gitignore b/.gitignore index d8b4d9684..9cf17be13 100644 --- a/.gitignore +++ b/.gitignore @@ -35,78 +35,11 @@ vagrant/duniter .nyc_output coverage/ -# TS migration -test/blockchain/*.js* -test/blockchain/*.d.ts -test/blockchain/lib/*.js* -test/blockchain/lib/*.d.ts /index.js* /index.d.ts /server.js* /server.d.ts app/**/*.js* app/**/*.d.ts -test/integration/revoked_pubkey_replay.js -test/integration/server-shutdown.js -test/integration/transactions-csv-cltv-sig.js -test/integration/ws2p*js -test/integration/*.js.map -test/integration/*.d.ts -test/integration/membership_chainability.js* -test/integration/membership_chainability.d.ts -test/integration/tools/toolbox.js* -test/integration/tools/toolbox.d.ts -test/integration/tools/TestUser.js* -test/integration/tools/TestUser.d.ts -test/integration/documents-currency.js* -test/integration/documents-currency.d.ts -test/integration/forwarding.js -test/integration/branches_switch.js -test/integration/branches2.js -test/integration/transactions-chaining.js -test/unit-tools.js* -test/unit-tools.d.ts -test/fast/modules/crawler/block_pulling.js* -test/fast/modules/crawler/block_pulling.d.ts -test/fast/fork*.js* -test/fast/fork*.d.ts -test/fast/proxies*.js* -test/fast/proxies*.d.ts -test/fast/modules/ws2p/*.js* -test/fast/modules/ws2p/*.d.ts -test/fast/modules/common/grammar.js* -test/fast/modules/common/grammar.d.ts -test/fast/prover/pow-1-cluster.d.ts -test/fast/prover/pow-1-cluster.js -test/fast/prover/pow-1-cluster.js.map -test/fast/protocol-local-rule-chained-tx-depth.js -test/fast/protocol-local-rule-chained-tx-depth.js.map -test/fast/protocol-local-rule-chained-tx-depth.d.ts -test/fast/dal/*-loki.d.ts -test/fast/dal/*-loki.js* -test/dal/loki.d.ts -test/dal/loki.js* -test/dal/blockchain-archive.d.ts -test/dal/blockchain-archive.js* -test/dal/basic-dal-tests.d.ts -test/dal/basic-dal-tests.js* - -# In test folders -test/integration/wot/*.d.ts -test/integration/wot/*.js* -test/integration/transactions/*.d.ts -test/integration/transactions/*.js* -test/integration/network/*.d.ts -test/integration/network/*.js* -test/integration/misc/*.d.ts -test/integration/misc/*.js* -test/integration/identity/*.d.ts -test/integration/identity/*.js* -test/integration/certification/*.d.ts -test/integration/certification/*.js* -test/integration/branches/*.d.ts -test/integration/branches/*.js* -test/integration/blocks/*.d.ts -test/integration/blocks/*.js* -test/fast/index/*.d.ts -test/fast/index/*.js* \ No newline at end of file +test/**/*.d.ts +test/**/*.js* \ No newline at end of file diff --git a/app/lib/common-libs/errors.ts b/app/lib/common-libs/errors.ts index 009a16032..2af726625 100644 --- a/app/lib/common-libs/errors.ts +++ b/app/lib/common-libs/errors.ts @@ -1,5 +1,6 @@ export enum DataErrors { + BLOCK_WASNT_COMMITTED, CANNOT_ARCHIVE_CHUNK_WRONG_SIZE, CORRUPTED_DATABASE, BLOCKCHAIN_NOT_INITIALIZED_YET, diff --git a/app/lib/computation/BlockchainContext.ts b/app/lib/computation/BlockchainContext.ts index cc5bb67ad..07deaee84 100644 --- a/app/lib/computation/BlockchainContext.ts +++ b/app/lib/computation/BlockchainContext.ts @@ -117,7 +117,7 @@ export class BlockchainContext { return DuniterBlockchain.checkBlock(block, withPoWAndSignature, this.conf, this.dal) } - private async addBlock(obj: BlockDTO, index: any = null, HEAD: DBHead | null = null): Promise<any> { + private async addBlock(obj: BlockDTO, index: any = null, HEAD: DBHead | null = null): Promise<BlockDTO> { const block = await DuniterBlockchain.pushTheBlock(obj, index, HEAD, this.conf, this.dal, this.logger) this.vHEAD_1 = this.vHEAD = null return block diff --git a/app/lib/dal/indexDAL/abstract/TxsDAO.ts b/app/lib/dal/indexDAL/abstract/TxsDAO.ts index fe425eb52..0f8961605 100644 --- a/app/lib/dal/indexDAL/abstract/TxsDAO.ts +++ b/app/lib/dal/indexDAL/abstract/TxsDAO.ts @@ -30,4 +30,8 @@ export interface TxsDAO extends GenericDAO<DBTx> { removeAll(): Promise<void> sandbox:SandBox<{ issuers: string[], output_base:number, output_amount:number }> + + getSandboxRoom(): Promise<number> + + setSandboxSize(size:number): void } diff --git a/app/lib/logger.ts b/app/lib/logger.ts index 4ef6b1be1..7a2f4e1f2 100644 --- a/app/lib/logger.ts +++ b/app/lib/logger.ts @@ -156,6 +156,6 @@ logger.addHomeLogs(Directory.INSTANCE_HOME) /** * Convenience function to get logger directly */ -export function NewLogger() { +export function NewLogger(name?:string) { return logger } diff --git a/app/modules/crawler/index.ts b/app/modules/crawler/index.ts index c27aa53a1..eb34d602a 100644 --- a/app/modules/crawler/index.ts +++ b/app/modules/crawler/index.ts @@ -35,7 +35,7 @@ export const CrawlerDependency = { contacter: (host:string, port:number, opts?:any) => new Contacter(host, port, opts), - pullBlocks: async (server:Server, pubkey:string) => { + pullBlocks: async (server:Server, pubkey = "") => { const crawler = new Crawler(server, server.conf, server.logger); return crawler.pullBlocks(server, pubkey); }, diff --git a/app/modules/crawler/lib/crawler.ts b/app/modules/crawler/lib/crawler.ts index de7c52db7..0a0acbfa8 100644 --- a/app/modules/crawler/lib/crawler.ts +++ b/app/modules/crawler/lib/crawler.ts @@ -51,7 +51,7 @@ export class Crawler extends stream.Transform implements DuniterService { this.sandboxCrawler = new SandboxCrawler(server, conf, logger) } - pullBlocks(server:Server, pubkey:string) { + pullBlocks(server:Server, pubkey = "") { return this.blockCrawler.pullBlocks(server, pubkey) } @@ -344,7 +344,7 @@ export class BlockCrawler { this.syncBlockFifo.kill(); } - pullBlocks(server:Server, pubkey:string) { + pullBlocks(server:Server, pubkey = "") { return this.syncBlock(server, pubkey) } diff --git a/app/modules/prover/lib/blockGenerator.ts b/app/modules/prover/lib/blockGenerator.ts index 0076a2857..3ca3f43ec 100644 --- a/app/modules/prover/lib/blockGenerator.ts +++ b/app/modules/prover/lib/blockGenerator.ts @@ -691,7 +691,7 @@ export class BlockGeneratorWhichProves extends BlockGenerator { super(server) } - async makeNextBlock(block:DBBlock|null, trial:number, manualValues:any = null) { + async makeNextBlock(block:DBBlock|null, trial?:number|null, manualValues:any = null) { const unsignedBlock = block || (await this.nextBlock(manualValues)) const trialLevel = trial || (await this.mainContext.getIssuerPersonalizedDifficulty(this.selfPubkey)) return this.prover.prove(unsignedBlock, trialLevel, (manualValues && manualValues.time) || null); diff --git a/app/modules/prover/lib/permanentProver.ts b/app/modules/prover/lib/permanentProver.ts index 411e873cc..5dad21437 100644 --- a/app/modules/prover/lib/permanentProver.ts +++ b/app/modules/prover/lib/permanentProver.ts @@ -209,7 +209,7 @@ export class PermanentProver { permanenceResolve() } - async blockchainChanged(gottenBlock:any) { + async blockchainChanged(gottenBlock?:any) { if (this.server && (!gottenBlock || !this.lastComputedBlock || gottenBlock.hash !== this.lastComputedBlock.hash)) { // Cancel any processing proof await this.prover.cancel() diff --git a/app/service/BlockchainService.ts b/app/service/BlockchainService.ts index bcd1859ac..af71c2658 100644 --- a/app/service/BlockchainService.ts +++ b/app/service/BlockchainService.ts @@ -223,9 +223,10 @@ export class BlockchainService extends FIFOService { }) } - async blockResolution() { - let added = true - while (added) { + async blockResolution(): Promise<BlockDTO|null> { + let lastAdded:BlockDTO|null = null + let added:BlockDTO|null + do { const current = await this.current() let potentials = [] if (current) { @@ -235,7 +236,7 @@ export class BlockchainService extends FIFOService { potentials = await this.dal.getPotentialRootBlocks() this.logger.info('Block resolution: %s potential blocks for root block...', potentials.length) } - added = false + added = null let i = 0 while (!added && i < potentials.length) { const dto = BlockDTO.fromJSONObject(potentials[i]) @@ -245,17 +246,16 @@ export class BlockchainService extends FIFOService { await this.dal.removeTxByHash(tx.hash); } } - const addedBlock = await this.mainContext.checkAndAddBlock(dto) - added = true + lastAdded = added = await this.mainContext.checkAndAddBlock(dto) this.push({ bcEvent: OtherConstants.BC_EVENT.HEAD_CHANGED, - block: addedBlock + block: added }) // Clear invalid forks' cache this.invalidForks.splice(0, this.invalidForks.length) } catch (e) { this.logger.error(e) - added = false + added = null const theError = e && (e.message || e) this.push({ blockResolutionError: theError @@ -263,7 +263,8 @@ export class BlockchainService extends FIFOService { } i++ } - } + } while (added) + return lastAdded } async forkResolution() { diff --git a/test/dal/source_dal.js b/test/dal/sources-dal.ts similarity index 66% rename from test/dal/source_dal.js rename to test/dal/sources-dal.ts index 0e618485a..58a45b06a 100644 --- a/test/dal/source_dal.js +++ b/test/dal/sources-dal.ts @@ -11,41 +11,39 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const co = require('co'); +import {FileDAL} from "../../app/lib/dal/fileDAL" +import {Directory} from "../../app/lib/system/directory" + const should = require('should'); -const FileDAL = require('../../app/lib/dal/fileDAL').FileDAL -const dir = require('../../app/lib/system/directory').Directory -const indexer = require('../../app/lib/indexer').Indexer -let dal; +let dal:FileDAL describe("Source DAL", function(){ - before(() => co(function *() { - dal = new FileDAL(yield dir.getHomeParams(true, 'db0')); - yield dal.init(); - })); + before(async () => { + dal = new FileDAL(await Directory.getHomeParams(true, 'db0')); + await dal.init({} as any) + }) - it('should be able to feed the sindex with unordered rows', () => co(function *() { - yield dal.sindexDAL.insertBatch([ + it('should be able to feed the sindex with unordered rows', async () => { + await dal.sindexDAL.insertBatch([ { op: 'UPDATE', tx: null, identifier: 'SOURCE_1', pos: 4, written_on: '139-H', writtenOn: 139, written_time: 4500, consumed: true, conditions: 'SIG(ABC)' }, { op: 'CREATE', tx: null, identifier: 'SOURCE_1', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false, conditions: 'SIG(ABC)' }, { op: 'CREATE', tx: null, identifier: 'SOURCE_2', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false, conditions: 'SIG(ABC)' }, { op: 'CREATE', tx: null, identifier: 'SOURCE_3', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false, conditions: 'SIG(DEF)' } - ]); - (yield dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(2); - (yield dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(4); + ] as any); + (await dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(2); + (await dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(4); // Source availability - const sourcesOfDEF = yield dal.sindexDAL.getAvailableForPubkey('DEF'); + const sourcesOfDEF = await dal.sindexDAL.getAvailableForPubkey('DEF'); sourcesOfDEF.should.have.length(1); - const sourcesOfABC = yield dal.sindexDAL.getAvailableForPubkey('ABC'); + const sourcesOfABC = await dal.sindexDAL.getAvailableForPubkey('ABC'); sourcesOfABC.should.have.length(1); - const source1 = yield dal.sindexDAL.getSource('SOURCE_1', 4); + const source1 = await dal.sindexDAL.getSource('SOURCE_1', 4) as any source1.should.have.property('consumed').equal(true); - const udSources = yield dal.sindexDAL.getUDSources('ABC'); + const udSources = await dal.sindexDAL.getUDSources('ABC'); udSources.should.have.length(2); udSources[0].should.have.property('consumed').equal(false); udSources[1].should.have.property('consumed').equal(true); - })); -}); + }) +}) diff --git a/test/dal/triming.js b/test/dal/triming-dal.ts similarity index 63% rename from test/dal/triming.js rename to test/dal/triming-dal.ts index ef00f241d..ada1d304f 100644 --- a/test/dal/triming.js +++ b/test/dal/triming-dal.ts @@ -11,132 +11,131 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const co = require('co'); +import {FileDAL} from "../../app/lib/dal/fileDAL" +import {Directory} from "../../app/lib/system/directory" +import {Indexer} from "../../app/lib/indexer" +import {simpleNodeWith2Users} from "../integration/tools/toolbox" + const should = require('should'); -const FileDAL = require('../../app/lib/dal/fileDAL').FileDAL -const dir = require('../../app/lib/system/directory').Directory -const indexer = require('../../app/lib/indexer').Indexer -const toolbox = require('../integration/tools/toolbox'); -let dal; +let dal:FileDAL describe("Triming", function(){ - before(() => co(function *() { - dal = new FileDAL(yield dir.getHomeParams(true, 'db0')); - yield dal.init(); - })); + before(async () => { + dal = new FileDAL(await Directory.getHomeParams(true, 'db0')); + await dal.init({} as any) + }) - it('should be able to feed the bindex', () => co(function *() { - yield dal.bindexDAL.insertBatch([ + it('should be able to feed the bindex', async () => { + await dal.bindexDAL.insertBatch([ { number: 121, version: 6, bsize: 0, hash: "HASH", issuer: "ISSUER", time: 0, membersCount: 3, issuersCount: 2, issuersFrame: 1, issuersFrameVar: 2, avgBlockSize: 0, medianTime: 1482500000, dividend: 100, mass: 300, massReeval: 300, unitBase: 2, powMin: 70, udTime: 0, udReevalTime: 0, diffNumber: 5, speed: 1.0 }, { number: 122, version: 6, bsize: 0, hash: "HASH", issuer: "ISSUER", time: 0, membersCount: 3, issuersCount: 2, issuersFrame: 1, issuersFrameVar: 2, avgBlockSize: 0, medianTime: 1482500000, dividend: 100, mass: 300, massReeval: 300, unitBase: 2, powMin: 70, udTime: 0, udReevalTime: 0, diffNumber: 5, speed: 1.0 }, { number: 123, version: 6, bsize: 0, hash: "HASH", issuer: "ISSUER", time: 0, membersCount: 3, issuersCount: 2, issuersFrame: 1, issuersFrameVar: 2, avgBlockSize: 0, medianTime: 1482500000, dividend: 100, mass: 300, massReeval: 300, unitBase: 2, powMin: 70, udTime: 0, udReevalTime: 0, diffNumber: 5, speed: 1.0 }, { number: 124, version: 6, bsize: 0, hash: "HASH", issuer: "ISSUER", time: 0, membersCount: 3, issuersCount: 2, issuersFrame: 1, issuersFrameVar: 2, avgBlockSize: 0, medianTime: 1482500000, dividend: 100, mass: 300, massReeval: 300, unitBase: 2, powMin: 70, udTime: 0, udReevalTime: 0, diffNumber: 5, speed: 1.0 }, { number: 125, version: 6, bsize: 0, hash: "HASH", issuer: "ISSUER", time: 0, membersCount: 3, issuersCount: 2, issuersFrame: 1, issuersFrameVar: 2, avgBlockSize: 0, medianTime: 1482500000, dividend: 100, mass: 300, massReeval: 300, unitBase: 2, powMin: 70, udTime: 0, udReevalTime: 0, diffNumber: 5, speed: 1.0 } - ]); - })); + ] as any); + }) - it('should have bindex head(1) = 125', () => co(function *() { - const head = yield dal.bindexDAL.head(1); + it('should have bindex head(1) = 125', async () => { + const head = await dal.bindexDAL.head(1); head.should.have.property('number').equal(125); - })); + }) - it('should have bindex range(1, 3) = 125, 124, 123', () => co(function *() { - const range = yield dal.bindexDAL.range(1,3); + it('should have bindex range(1, 3) = 125, 124, 123', async () => { + const range = await dal.bindexDAL.range(1,3); range.should.have.length(3); range[0].should.have.property('number').equal(125); range[1].should.have.property('number').equal(124); range[2].should.have.property('number').equal(123); - })); + }) - it('should be able to feed the iindex', () => co(function *() { - yield dal.iindexDAL.insertBatch([ + it('should be able to feed the iindex', async () => { + await dal.iindexDAL.insertBatch([ { op: 'CREATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', uid: 'cat', created_on: '121-H', written_on: '122-H', writtenOn: 122, member: true, wasMember: true, kick: false }, { op: 'UPDATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', uid: null, created_on: '121-H', written_on: '123-H', writtenOn: 123, member: null, wasMember: null, kick: true }, { op: 'UPDATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', uid: null, created_on: '121-H', written_on: '124-H', writtenOn: 124, member: false, wasMember: null, kick: false } - ]); - let lignes = yield dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); + ] as any); + let lignes = await dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); lignes.should.have.length(3); - indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); - })); + Indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); + }) - it('should be able to trim the iindex', () => co(function *() { + it('should be able to trim the iindex', async () => { // Triming - yield dal.trimIndexes(124); - const lignes = yield dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); + await dal.trimIndexes(124); + const lignes = await dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); lignes.should.have.length(2); - indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); - })); + Indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); + }) - it('triming again the iindex should have no effet', () => co(function *() { + it('triming again the iindex should have no effet', async () => { // Triming - yield dal.trimIndexes(124); - const lignes = yield dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); + await dal.trimIndexes(124); + const lignes = await dal.iindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); lignes.should.have.length(2); - indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); - })); + Indexer.DUP_HELPERS.reduce(lignes).should.have.property('member').equal(false); + }) - it('should be able to feed the mindex', () => co(function *() { - yield dal.mindexDAL.insertBatch([ + it('should be able to feed the mindex', async () => { + await dal.mindexDAL.insertBatch([ { op: 'CREATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', created_on: '121-H', written_on: '122-H', writtenOn: 122, expires_on: 1000, expired_on: null }, { op: 'UPDATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', created_on: '121-H', written_on: '123-H', writtenOn: 123, expires_on: 1200, expired_on: null }, { op: 'UPDATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', created_on: '121-H', written_on: '124-H', writtenOn: 124, expires_on: null, expired_on: null }, { op: 'UPDATE', pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', created_on: '121-H', written_on: '125-H', writtenOn: 125, expires_on: 1400, expired_on: null } - ]); - const lignes = yield dal.mindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); + ] as any); + const lignes = await dal.mindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); lignes.should.have.length(4); - indexer.DUP_HELPERS.reduce(lignes).should.have.property('expires_on').equal(1400); - })); + Indexer.DUP_HELPERS.reduce(lignes).should.have.property('expires_on').equal(1400); + }) - it('should be able to trim the mindex', () => co(function *() { + it('should be able to trim the mindex', async () => { // Triming - yield dal.trimIndexes(124); - const lignes = yield dal.mindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); + await dal.trimIndexes(124); + const lignes = await dal.mindexDAL.reducable('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); lignes.should.have.length(3); - indexer.DUP_HELPERS.reduce(lignes).should.have.property('expires_on').equal(1400); - })); + Indexer.DUP_HELPERS.reduce(lignes).should.have.property('expires_on').equal(1400); + }) - it('should be able to feed the cindex', () => co(function *() { - yield dal.cindexDAL.insertBatch([ + it('should be able to feed the cindex', async () => { + await dal.cindexDAL.insertBatch([ { op: 'CREATE', issuer: 'HgTT', receiver: 'DNan', created_on: '121-H', written_on: '126-H', writtenOn: 126, expires_on: 1000, expired_on: null }, { op: 'UPDATE', issuer: 'HgTT', receiver: 'DNan', created_on: '121-H', written_on: '126-H', writtenOn: 126, expires_on: null, expired_on: 3000 }, { op: 'CREATE', issuer: 'DNan', receiver: 'HgTT', created_on: '125-H', written_on: '126-H', writtenOn: 126, expires_on: null, expired_on: null } - ]); - (yield dal.cindexDAL.findRaw({ issuer: 'HgTT' })).should.have.length(2); - (yield dal.cindexDAL.findRaw({ issuer: 'DNan' })).should.have.length(1); - })); + ] as any); + (await dal.cindexDAL.findRaw({ issuer: 'HgTT' })).should.have.length(2); + (await dal.cindexDAL.findRaw({ issuer: 'DNan' })).should.have.length(1); + }) - it('should be able to trim the cindex', () => co(function *() { + it('should be able to trim the cindex', async () => { // Triming - yield dal.trimIndexes(127); - (yield dal.cindexDAL.findRaw({ issuer: 'HgTT' })).should.have.length(0); + await dal.trimIndexes(127); + (await dal.cindexDAL.findRaw({ issuer: 'HgTT' })).should.have.length(0); // { op: 'UPDATE', issuer: 'DNan', receiver: 'HgTT', created_on: '125-H', written_on: '126-H', writtenOn: 126, expires_on: 3600, expired_on: null },/**/ - (yield dal.cindexDAL.findRaw({ issuer: 'DNan' })).should.have.length(1); - })); + (await dal.cindexDAL.findRaw({ issuer: 'DNan' })).should.have.length(1); + }) - it('should be able to feed the sindex', () => co(function *() { - yield dal.sindexDAL.insertBatch([ + it('should be able to feed the sindex', async () => { + await dal.sindexDAL.insertBatch([ { op: 'CREATE', identifier: 'SOURCE_1', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false }, { op: 'UPDATE', identifier: 'SOURCE_1', pos: 4, written_on: '139-H', writtenOn: 139, written_time: 4500, consumed: true }, { op: 'CREATE', identifier: 'SOURCE_2', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false }, { op: 'CREATE', identifier: 'SOURCE_3', pos: 4, written_on: '126-H', writtenOn: 126, written_time: 2000, consumed: false } - ]); - (yield dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(2); - (yield dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(4); - })); + ] as any); + (await dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(2); + (await dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(4); + }) - it('should be able to trim the sindex', () => co(function *() { + it('should be able to trim the sindex', async () => { // Triming - yield dal.trimIndexes(140); - (yield dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(0); - (yield dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(2); - })); + await dal.trimIndexes(140); + (await dal.sindexDAL.findRaw({ identifier: 'SOURCE_1' })).should.have.length(0); + (await dal.sindexDAL.findRaw({ pos: 4 })).should.have.length(2); + }) - it('should be able to trim the bindex', () => co(function *() { + it('should be able to trim the bindex', async () => { // Triming - const server = (yield toolbox.simpleNodeWith2Users({ + const server = (await simpleNodeWith2Users({ forksize: 9, sigQty: 1, dtDiffEval: 2, @@ -144,13 +143,13 @@ describe("Triming", function(){ })).s1; // const s1 = server.s1; for (let i = 0; i < 13; i++) { - yield server.commit(); + await server.commit(); } - (yield server.dal.bindexDAL.head(1)).should.have.property('number').equal(12); - (yield server.dal.bindexDAL.head(13)).should.have.property('number').equal(0); - yield server.commit(); - should.not.exists(yield server.dal.bindexDAL.head(14)); // Trimed - - yield server.closeCluster() - })); -}); + (await server.dal.bindexDAL.head(1)).should.have.property('number').equal(12); + (await server.dal.bindexDAL.head(13)).should.have.property('number').equal(0); + await server.commit(); + should.not.exists(await server.dal.bindexDAL.head(14)); // Trimed + + await server.closeCluster() + }) +}) diff --git a/test/data/blocks.js b/test/data/blocks-data.ts similarity index 99% rename from test/data/blocks.js rename to test/data/blocks-data.ts index 17094232a..ccaa84559 100644 --- a/test/data/blocks.js +++ b/test/data/blocks-data.ts @@ -12,7 +12,7 @@ // GNU Affero General Public License for more details. -module.exports = { +export const BLOCK_TEST_DATA = { WRONG_SIGNATURE: "Version: 10\n" + "Type: Block\n" + diff --git a/test/eslint.js b/test/eslint-test.ts similarity index 97% rename from test/eslint.js rename to test/eslint-test.ts index c6714b15f..d0ae93ec6 100644 --- a/test/eslint.js +++ b/test/eslint-test.ts @@ -25,7 +25,7 @@ describe('Linting', () => { ]; // Specify style of output - const options = {}; + const options:any = {}; options.formatter = 'stylish'; // Run the tests diff --git a/test/fast/block_local.js b/test/fast/block_local.js deleted file mode 100644 index ed4d289e4..000000000 --- a/test/fast/block_local.js +++ /dev/null @@ -1,124 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const parsers = require('../../app/lib/common-libs/parsers').parsers -const indexer = require('../../app/lib/indexer').Indexer -const LOCAL_RULES = require('../../app/lib/rules/local_rules').LOCAL_RULES_FUNCTIONS -const ALIAS = require('../../app/lib/rules').ALIAS -const blocks = require('../data/blocks.js'); -const parser = parsers.parseBlock; -const BlockDTO = require('../../app/lib/dto/BlockDTO').BlockDTO - -const conf = { - - sigQty: 1, - powZeroMin: 1, - powPeriod: 18, - incDateMin: 10, - avgGenTime: 60, - medianTimeBlocks: 20, - dt: 100, - ud0: 100, - c: 0.1 -} - -describe("Block local coherence", function(){ - - it('a valid block should be well formatted', test(ALIAS.ALL_LOCAL_BUT_POW_AND_SIGNATURE, blocks.VALID_ROOT)); - - describe("should be rejected", function(){ - - it('if wrong signature block', test(LOCAL_RULES.checkBlockSignature, blocks.WRONG_SIGNATURE, 'Block\'s signature must match')); - it('if root block does not have Parameters', test(LOCAL_RULES.checkParameters, blocks.ROOT_WITHOUT_PARAMETERS, 'Parameters must be provided for root block')); - it('if proof-of-work does not match PoWMin field', test(LOCAL_RULES.checkProofOfWork, blocks.WRONG_PROOF_OF_WORK, 'Not a proof-of-work')); - it('if non-root has Parameters', test(LOCAL_RULES.checkParameters, blocks.NON_ROOT_WITH_PARAMETERS, 'Parameters must not be provided for non-root block')); - it('if root block has PreviousHash', test(LOCAL_RULES.checkPreviousHash, blocks.ROOT_WITH_PREVIOUS_HASH, 'PreviousHash must not be provided for root block')); - it('if root block has PreviousIssuer', test(LOCAL_RULES.checkPreviousIssuer, blocks.ROOT_WITH_PREVIOUS_ISSUER, 'PreviousIssuer must not be provided for root block')); - it('if non-root block does not have PreviousHash', test(LOCAL_RULES.checkPreviousHash, blocks.NON_ROOT_WITHOUT_PREVIOUS_HASH, 'PreviousHash must be provided for non-root block')); - it('if non-root block does not have PreviousIssuer', test(LOCAL_RULES.checkPreviousIssuer, blocks.NON_ROOT_WITHOUT_PREVIOUS_ISSUER, 'PreviousIssuer must be provided for non-root block')); - it('a V2 block with Dividend must have UnitBase field', test(LOCAL_RULES.checkUnitBase, blocks.UD_BLOCK_WIHTOUT_BASE, 'Document has unkown fields or wrong line ending format')); - it('a V3 root block must have UnitBase field', test(LOCAL_RULES.checkUnitBase, blocks.V3_ROOT_BLOCK_NOBASE, 'Document has unkown fields or wrong line ending format')); - it('a V3 root block must have UnitBase field equal 0', test(LOCAL_RULES.checkUnitBase, blocks.V3_ROOT_BLOCK_POSITIVE_BASE, 'UnitBase must equal 0 for root block')); - it('a block with wrong date (in past)', test(LOCAL_RULES.checkBlockTimes, blocks.WRONG_DATE_LOWER, 'A block must have its Time between MedianTime and MedianTime + 1440')); - it('a block with wrong date (in future, but too far)', test(LOCAL_RULES.checkBlockTimes, blocks.WRONG_DATE_HIGHER_BUT_TOO_HIGH, 'A block must have its Time between MedianTime and MedianTime + 1440')); - it('a root block with different time & medianTime should fail', test(LOCAL_RULES.checkBlockTimes, blocks.WRONG_ROOT_TIMES, 'Root block must have Time equal MedianTime')); - it('a block with good date', test(LOCAL_RULES.checkBlockTimes, blocks.GOOD_DATE_HIGHER)); - it('Block cannot contain wrongly signed identities', test(LOCAL_RULES.checkIdentitiesSignature, blocks.WRONGLY_SIGNED_IDENTITIES, 'Identity\'s signature must match')); - it('block with colliding uids in identities', test(LOCAL_RULES.checkIdentitiesUserIDConflict, blocks.COLLIDING_UIDS, 'Block must not contain twice same identity uid')); - it('a block with colliding pubkeys in identities', test(LOCAL_RULES.checkIdentitiesPubkeyConflict, blocks.COLLIDING_PUBKEYS, 'Block must not contain twice same identity pubkey')); - it('a block with identities not matchin joins', test(LOCAL_RULES.checkIdentitiesMatchJoin, blocks.WRONG_IDTY_MATCH_JOINS, 'Each identity must match a newcomer line with same userid and certts')); - it('Block cannot contain wrongly signed join', test(LOCAL_RULES.checkMembershipsSignature, blocks.WRONGLY_SIGNED_JOIN, 'Membership\'s signature must match')); - it('Block cannot contain wrongly signed active', test(LOCAL_RULES.checkMembershipsSignature, blocks.WRONGLY_SIGNED_ACTIVE, 'Membership\'s signature must match')); - it('Block cannot contain wrongly signed leave', test(LOCAL_RULES.checkMembershipsSignature, blocks.WRONGLY_SIGNED_LEAVE, 'Membership\'s signature must match')); - it('Block cannot contain a same pubkey more than once in joiners', test(LOCAL_RULES.checkPubkeyUnicity, blocks.MULTIPLE_JOINERS, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); - it('Block cannot contain a same pubkey more than once in actives', test(LOCAL_RULES.checkPubkeyUnicity, blocks.MULTIPLE_ACTIVES, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); - it('Block cannot contain a same pubkey more than once in leavers', test(LOCAL_RULES.checkPubkeyUnicity, blocks.MULTIPLE_LEAVES, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); - it('Block cannot contain a same pubkey more than once in excluded', test(LOCAL_RULES.checkPubkeyUnicity, blocks.MULTIPLE_EXCLUDED, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); - it('Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded', test(LOCAL_RULES.checkPubkeyUnicity, blocks.MULTIPLE_OVER_ALL, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); - it('Block cannot have revoked key in joiners,actives,leavers', test(LOCAL_RULES.checkMembershipUnicity, blocks.REVOKED_WITH_MEMBERSHIPS, 'Unicity constraint PUBLIC_KEY on MINDEX is not respected')); - it('Block cannot have revoked key duplicates', test(LOCAL_RULES.checkRevokedUnicity, blocks.REVOKED_WITH_DUPLICATES, 'A single revocation per member is allowed')); - it('Block revoked keys must be in excluded', test(LOCAL_RULES.checkRevokedAreExcluded, blocks.REVOKED_NOT_IN_EXCLUDED, 'A revoked member must be excluded')); - it('Block cannot contain 2 certifications from same issuer', test(LOCAL_RULES.checkCertificationOneByIssuer, blocks.MULTIPLE_CERTIFICATIONS_FROM_SAME_ISSUER, 'Block cannot contain two certifications from same issuer')); - it('Block cannot contain identical certifications', test(LOCAL_RULES.checkCertificationUnicity, blocks.IDENTICAL_CERTIFICATIONS, 'Block cannot contain identical certifications (A -> B)')); - it('Block cannot contain certifications concerning a leaver', test(LOCAL_RULES.checkCertificationIsntForLeaverOrExcluded, blocks.LEAVER_WITH_CERTIFICATIONS, 'Block cannot contain certifications concerning leavers or excluded members')); - it('Block cannot contain certifications concerning an excluded member', test(LOCAL_RULES.checkCertificationIsntForLeaverOrExcluded, blocks.EXCLUDED_WITH_CERTIFICATIONS, 'Block cannot contain certifications concerning leavers or excluded members')); - it('Block cannot contain transactions without issuers (1)', test(LOCAL_RULES.checkTxIssuers, blocks.TRANSACTION_WITHOUT_ISSUERS, 'A transaction must have at least 1 issuer')); - it('Block cannot contain transactions without issuers (2)', test(LOCAL_RULES.checkTxSources, blocks.TRANSACTION_WITHOUT_SOURCES, 'A transaction must have at least 1 source')); - it('Block cannot contain transactions without issuers (3)', test(LOCAL_RULES.checkTxRecipients, blocks.TRANSACTION_WITHOUT_RECIPIENT, 'A transaction must have at least 1 recipient')); - it('Block cannot contain transactions with identical sources in one transaction', test(LOCAL_RULES.checkTxSources, blocks.TRANSACTION_WITH_DUPLICATED_SOURCE_SINGLE_TX, 'It cannot exist 2 identical sources for transactions inside a given block')); - it('Block cannot contain transactions with identical sources in a pack of transactions', test(LOCAL_RULES.checkTxSources, blocks.TRANSACTION_WITH_DUPLICATED_SOURCE_MULTIPLE_TX, 'It cannot exist 2 identical sources for transactions inside a given block')); - it('Block cannot contain transactions with empty output conditions', test(LOCAL_RULES.checkTxRecipients, blocks.TRANSACTION_WITH_EMPTY_TX_CONDITIONS, 'Empty conditions are forbidden')); - it('Block cannot contain transactions with wrong total', test(LOCAL_RULES.checkTxAmounts, blocks.TRANSACTION_WRONG_TOTAL, 'Transaction inputs sum must equal outputs sum')); - it('Block cannot contain transactions with wrong base transformation', test(LOCAL_RULES.checkTxAmounts, blocks.TRANSACTION_WRONG_TRANSFORM, 'Transaction output base amount does not equal previous base deltas')); - it('Block cannot contain transactions with unexisting lower base in sources', test(LOCAL_RULES.checkTxAmounts, blocks.TRANSACTION_WRONG_TRANSFORM_LOW_BASE, 'Transaction output base amount does not equal previous base deltas')); - it('Block cannot contain transactions with more than 100 lines', test(LOCAL_RULES.checkTxLen, blocks.TRANSACTION_TOO_LONG, 'A transaction has a maximum size of 100 lines')); - it('Block cannot contain transactions with a too large output', test(LOCAL_RULES.checkTxLen, blocks.OUTPUT_TOO_LONG, 'A transaction output has a maximum size of 2000 characters')); - it('Block cannot contain transactions with a too large unlock', test(LOCAL_RULES.checkTxLen, blocks.UNLOCK_TOO_LONG, 'A transaction unlock has a maximum size of 2000 characters')); - it('Block cannot be refused with a good V3 transaction', test(LOCAL_RULES.checkTxAmounts, blocks.TRANSACTION_V3_GOOD_AMOUNTS)); - it('Block cannot contain transactions with wrong signatures', test(LOCAL_RULES.checkTxSignature, blocks.TRANSACTION_WITH_WRONG_SIGNATURES, 'Signature from a transaction must match')); - }); - -}); - - -function test (rule, raw, expectedMessage) { - return () => co(function *() { - try { - let obj = parser.syncWrite(raw); - let block = BlockDTO.fromJSONObject(obj); - let index = indexer.localIndex(block, conf) - yield rule(block, conf, index); // conf parameter is not always used - if (expectedMessage) { - throw 'Test should have thrown an error'; - } - } catch (e) { - if (!expectedMessage) { - console.error(e.stack || e); - } - if (e.uerr) { - // This is a controlled error - e.uerr.message.should.equal(expectedMessage); - } else if (e) { - // This is a controlled error - e.message.should.equal(expectedMessage); - } else { - // throw Error(e) - // Display non wrapped errors (wrapped error is an error in constants.js) - // console.error(e.stack || e); - } - } - }); -} diff --git a/test/fast/cfs.js b/test/fast/cfs.js deleted file mode 100644 index 518c4a11a..000000000 --- a/test/fast/cfs.js +++ /dev/null @@ -1,155 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; - -var assert = require('assert'); -var should = require('should'); -var co = require('co'); -var CFSCore = require('../../app/lib/dal/fileDALs/CFSCore').CFSCore; -const mockFS = require('../../app/lib/system/directory').MemFS({ - 'B5_a': { - "A.json": '{ "text": "Content of A from B5_a" }' - }, - 'B4': { - 'B.json': '{ "text": "Content of B" }' - }, - 'B3': { - 'A.json': '{ "text": "Content of A from B3" }', - 'C.json': '{ "text": "Content of C from B3" }' - }, - 'OTHER': { - 'X.json': '{ "text": "Content of X" }' - } -}); - -describe("CFS", () => { - - var coreB3 = new CFSCore('/B3', mockFS); - var coreB4 = new CFSCore('/B4', mockFS); - var coreB5 = new CFSCore('/B5_a', mockFS); - - var rootCore = new CFSCore('/OTHER', mockFS); - - // ------------ Direct READ ------------ - - it('should have the content of A.json from B5', () => { - return co(function *() { - var content = yield coreB5.readJSON('A.json'); - content.should.have.property('text').equal('Content of A from B5_a'); - }); - }); - - // WRITE of file /C.json - - it('should have the content of C.json modified from B5 (direct read)', () => { - return co(function *() { - yield coreB5.writeJSON('C.json', { text: 'Content of C from B5_a'}); - var content = yield coreB5.readJSON('C.json'); - content.should.have.property('text').equal('Content of C from B5_a'); - }); - }); - - // WRITE of file /D.json - - it('should have the content of D.json modified from B4 (direct read/write)', () => { - return co(function *() { - yield coreB4.writeJSON('D.json', { text: 'Content of D'}); - var content = yield coreB4.readJSON('D.json'); - content.should.have.property('text').equal('Content of D'); - }); - }); - - // REMOVE file /D.json - - it('should have the content of D.json modified from B5 (direct read/write)', () => { - return co(function *() { - var exists = yield coreB5.exists('D.json'); - var content = yield coreB5.read('D.json'); - assert.equal(exists, false); - assert.equal(content, null); - }); - }); - - // ------------ LIST ------------ - - it('should have G,H,I as files from /DIR', () => { - return co(function *() { - yield coreB3.makeTree('/DIR'); - yield coreB4.makeTree('/DIR'); - yield coreB5.makeTree('/DIR'); - yield coreB3.writeJSON('/DIR/G.json', { text: 'Content of DIR/I'}); - yield coreB4.writeJSON('/DIR/H.json', { text: 'Content of DIR/H'}); - yield coreB5.writeJSON('/DIR/I.json', { text: 'Content of DIR/G'}); - (yield coreB3.list('/DIR')).should.deepEqual(['G.json']); - (yield coreB4.list('/DIR')).should.deepEqual(['H.json']); - (yield coreB5.list('/DIR')).should.deepEqual(['I.json']); - }); - }); - - // WRITE of file /DIR2/I.json in B4 - - it('should have I as files from /DIR2', () => { - return co(function *() { - yield coreB3.makeTree('/DIR2'); - yield coreB3.writeJSON('/DIR2/I.json', { text: 'Content of DIR2/I in B4'}); - var files = yield coreB3.list('/DIR2'); - files.should.have.length(1); - files.should.deepEqual(['I.json']); - // Check its contents - var contents = yield coreB3.listJSON('/DIR2'); - contents.should.have.length(1); - contents.should.deepEqual([{ text: 'Content of DIR2/I in B4' }]); - }); - }); - - // REMOVE of file /DIR2/I.json in B5 - - it('should have no files from /DIR2 after file DELETION', () => { - return co(function *() { - yield coreB3.remove('/DIR2/I.json'); - var files = yield coreB3.list('/DIR2'); - files.should.have.length(0); - // Check its contents - var contents = yield coreB3.listJSON('/DIR2'); - contents.should.have.length(0); - }); - }); - - describe("Root core", () => { - - it('should have 1 file in /OTHER folder', () => { - return co(function *() { - var files = yield rootCore.list('/'); - files.should.have.length(1); - // Check its contents - var contents = yield rootCore.listJSON('/'); - contents.should.have.length(1); - contents.should.deepEqual([{ text: 'Content of X' }]); - }); - }); - - // REMOVE of file /OTHER/X.json in rootCore - - it('should have no files from /OTHER after file DELETION', () => { - return co(function *() { - yield rootCore.remove('/X.json'); - var files = yield rootCore.list('/'); - files.should.have.length(0); - // Check its contents - var contents = yield rootCore.listJSON('/'); - contents.should.have.length(0); - }); - }); - }); -}); diff --git a/test/fast/common/crypto.js b/test/fast/crypto/crypto.ts similarity index 68% rename from test/fast/common/crypto.js rename to test/fast/crypto/crypto.ts index 4c2ee4325..1b3e30095 100644 --- a/test/fast/common/crypto.js +++ b/test/fast/crypto/crypto.ts @@ -12,31 +12,27 @@ // GNU Affero General Public License for more details. "use strict"; -const should = require('should'); -const co = require('co'); -const nacl = require('tweetnacl'); -const base58 = require('../../../app/lib/common-libs/crypto/base58') -const naclUtil = require('../../../app/lib/common-libs/crypto/nacl-util') -const keyring = require('../../../app/lib/common-libs/crypto/keyring') +import {Base58decode, Base58encode} from "../../../app/lib/common-libs/crypto/base58" +import {decodeBase64, decodeUTF8, encodeBase64, encodeUTF8} from "../../../app/lib/common-libs/crypto/nacl-util" +import {KeyGen, verify} from "../../../app/lib/common-libs/crypto/keyring" -const Base58decode = base58.Base58decode -const Base58encode = base58.Base58encode +const should = require('should'); -const enc = naclUtil.encodeBase64 -const dec = naclUtil.decodeBase64 +const enc = encodeBase64 +const dec = decodeBase64 -let pub, sec, rawPub, rawSec; +let pub:Uint8Array, sec:Uint8Array, rawPub:string, rawSec:string describe('ed25519 tests:', function(){ - before(() => co(function*() { + before(async () => { // Generate the keypair - const keyPair = keyring.KeyGen('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); + const keyPair = KeyGen('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); pub = Base58decode(keyPair.publicKey); sec = Base58decode(keyPair.secretKey); rawPub = Base58encode(pub); rawSec = Base58encode(sec); - })); + }) //it('good signature from existing secret key should be verified', function(done){ // const keys = nacl.sign.scryptKeyPair.fromSecretKey(dec("TM0Imyj/ltqdtsNG7BFOD1uKMZ81q6Yk2oz27U+4pvs9QBfD6EOJWpK3CqdNG368nJgszy7ElozAzVXxKvRmDA==")); @@ -50,17 +46,16 @@ describe('ed25519 tests:', function(){ it('good signature from generated key should be verified', function(done){ const msg = "Some message to be signed"; - const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg); - const verified = keyring.verify(msg, sig, rawPub); + const sig = KeyGen(rawPub, rawSec).signSync(msg); + const verified = verify(msg, sig, rawPub); verified.should.equal(true); done(); }); it('wrong signature from generated key should NOT be verified', function(done){ const msg = "Some message to be signed"; - const cor = dec(enc(msg) + 'delta'); - const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg); - const verified = keyring.verify(cor, sig, rawPub); + const sig = KeyGen(rawPub, rawSec).signSync(msg); + const verified = verify(msg + 'delta', sig, rawPub); verified.should.equal(false); done(); }); @@ -73,7 +68,7 @@ describe('ed25519 tests:', function(){ "Block: 33291-0000088375C232A4DDAE171BB3D3C51347CB6DC8B7AA8BE4CD4DAEEADF26FEB8\n" + "Endpoints:\n" + "BASIC_MERKLED_API g1.duniter.org 10901\n" - const verified = keyring.verify(msg, "u8t1IoWrB/C7T+2rS0rKYJfjPG4FN/HkKGFiUO5tILIzjFDvxxQiVC+0o/Vaz805SMmqJvXqornI71U7//+wCg==", "3AF7bhGQRt6ymcBZgZTBMoDsEtSwruSarjNG8kDnaueX"); + const verified = verify(msg, "u8t1IoWrB/C7T+2rS0rKYJfjPG4FN/HkKGFiUO5tILIzjFDvxxQiVC+0o/Vaz805SMmqJvXqornI71U7//+wCg==", "3AF7bhGQRt6ymcBZgZTBMoDsEtSwruSarjNG8kDnaueX"); verified.should.equal(true); done(); }); @@ -87,7 +82,7 @@ describe('ed25519 tests:', function(){ "Endpoints:\n" + "BASIC_MERKLED_API g1.duniter.tednet.fr 37.187.0.204 8999\n" + "BMAS g1.duniter.tednet.fr 9000\n" - const verified = keyring.verify(msg, "ImvQDdpGv2M6CxSnBuseM/azJhBUGzWVgQhIvb5L2oGLm2GyLk/Sbi5wkb4IjbjbQfdRPdlcx5zxaHhvZCiWAA==", "Com8rJukCozHZyFao6AheSsfDQdPApxQRnz7QYFf64mm"); + const verified = verify(msg, "ImvQDdpGv2M6CxSnBuseM/azJhBUGzWVgQhIvb5L2oGLm2GyLk/Sbi5wkb4IjbjbQfdRPdlcx5zxaHhvZCiWAA==", "Com8rJukCozHZyFao6AheSsfDQdPApxQRnz7QYFf64mm"); verified.should.equal(true); done(); }); diff --git a/test/fast/common/randomKey.js b/test/fast/crypto/randomKey.ts similarity index 63% rename from test/fast/common/randomKey.js rename to test/fast/crypto/randomKey.ts index b2a59e1ed..c3a64cc91 100644 --- a/test/fast/common/randomKey.js +++ b/test/fast/crypto/randomKey.ts @@ -11,37 +11,31 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const co = require('co') -const should = require('should'); -const keyring = require('../../../app/lib/common-libs/crypto/keyring') -const naclUtil = require('../../../app/lib/common-libs/crypto/nacl-util') +import {Key, KeyGen, randomKey, verify} from "../../../app/lib/common-libs/crypto/keyring" -const enc = naclUtil.encodeBase64 -const dec = naclUtil.decodeBase64 +const should = require('should'); -let key; +let key:Key describe('Random keypair', function(){ - before(() => co(function*() { + before(async () => { // Generate the keypair - key = keyring.randomKey() - })); + key = randomKey() + }) it('good signature from generated key should be verified', function(done){ const msg = "Some message to be signed"; - const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg); - const verified = keyring.verify(msg, sig, key.publicKey); + const sig = KeyGen(key.publicKey, key.secretKey).signSync(msg); + const verified = verify(msg, sig, key.publicKey); verified.should.equal(true); done(); }); it('wrong signature from generated key should NOT be verified', function(done){ const msg = "Some message to be signed"; - const cor = dec(enc(msg) + 'delta'); - const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg); - const verified = keyring.verify(cor, sig, key.publicKey); + const sig = KeyGen(key.publicKey, key.secretKey).signSync(msg); + const verified = verify(msg + 'delta', sig, key.publicKey); verified.should.equal(false); done(); }); diff --git a/test/fast/block_format.js b/test/fast/misc/block-format.ts similarity index 92% rename from test/fast/block_format.js rename to test/fast/misc/block-format.ts index 345b6838b..eb9b7356e 100644 --- a/test/fast/block_format.js +++ b/test/fast/misc/block-format.ts @@ -11,9 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {parsers} from "../../../app/lib/common-libs/parsers/index" + const should = require('should'); -const parsers = require('../../app/lib/common-libs/parsers').parsers const raw = "Version: 10\n" + "Type: Block\n" + @@ -63,17 +63,9 @@ const raw = "Version: 10\n" + describe("Block format", function(){ - var parser = parsers.parseBlock; + const parser = parsers.parseBlock; - it('a valid block should be well formatted', () => parser.syncWrite(raw, { - trace: (msg, p1) => { - if (p1) { - console.log(msg, p1) - } else { - console.log(msg) - } - } - })); + it('a valid block should be well formatted', () => parser.syncWrite(raw)) describe("should be rejected", function(){ diff --git a/test/fast/misc/block-local.ts b/test/fast/misc/block-local.ts new file mode 100644 index 000000000..413aff68d --- /dev/null +++ b/test/fast/misc/block-local.ts @@ -0,0 +1,122 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {parsers} from "../../../app/lib/common-libs/parsers/index" +import {Indexer} from "../../../app/lib/indexer" +import {LOCAL_RULES_FUNCTIONS} from "../../../app/lib/rules/local_rules" +import {ALIAS} from "../../../app/lib/rules/index" +import {BLOCK_TEST_DATA} from "../../data/blocks-data" +import {BlockDTO} from "../../../app/lib/dto/BlockDTO" + +const should = require('should'); + +const conf = { + + sigQty: 1, + powZeroMin: 1, + powPeriod: 18, + incDateMin: 10, + avgGenTime: 60, + medianTimeBlocks: 20, + dt: 100, + ud0: 100, + c: 0.1 +} + +describe("Block local coherence", function(){ + + it('a valid block should be well formatted', test(ALIAS.ALL_LOCAL_BUT_POW_AND_SIGNATURE, BLOCK_TEST_DATA.VALID_ROOT)); + + describe("should be rejected", function(){ + + it('if wrong signature block', test(LOCAL_RULES_FUNCTIONS.checkBlockSignature, BLOCK_TEST_DATA.WRONG_SIGNATURE, 'Block\'s signature must match')); + it('if root block does not have Parameters', test(LOCAL_RULES_FUNCTIONS.checkParameters, BLOCK_TEST_DATA.ROOT_WITHOUT_PARAMETERS, 'Parameters must be provided for root block')); + it('if proof-of-work does not match PoWMin field', test(LOCAL_RULES_FUNCTIONS.checkProofOfWork, BLOCK_TEST_DATA.WRONG_PROOF_OF_WORK, 'Not a proof-of-work')); + it('if non-root has Parameters', test(LOCAL_RULES_FUNCTIONS.checkParameters, BLOCK_TEST_DATA.NON_ROOT_WITH_PARAMETERS, 'Parameters must not be provided for non-root block')); + it('if root block has PreviousHash', test(LOCAL_RULES_FUNCTIONS.checkPreviousHash, BLOCK_TEST_DATA.ROOT_WITH_PREVIOUS_HASH, 'PreviousHash must not be provided for root block')); + it('if root block has PreviousIssuer', test(LOCAL_RULES_FUNCTIONS.checkPreviousIssuer, BLOCK_TEST_DATA.ROOT_WITH_PREVIOUS_ISSUER, 'PreviousIssuer must not be provided for root block')); + it('if non-root block does not have PreviousHash', test(LOCAL_RULES_FUNCTIONS.checkPreviousHash, BLOCK_TEST_DATA.NON_ROOT_WITHOUT_PREVIOUS_HASH, 'PreviousHash must be provided for non-root block')); + it('if non-root block does not have PreviousIssuer', test(LOCAL_RULES_FUNCTIONS.checkPreviousIssuer, BLOCK_TEST_DATA.NON_ROOT_WITHOUT_PREVIOUS_ISSUER, 'PreviousIssuer must be provided for non-root block')); + it('a V2 block with Dividend must have UnitBase field', test(LOCAL_RULES_FUNCTIONS.checkUnitBase, BLOCK_TEST_DATA.UD_BLOCK_WIHTOUT_BASE, 'Document has unkown fields or wrong line ending format')); + it('a V3 root block must have UnitBase field', test(LOCAL_RULES_FUNCTIONS.checkUnitBase, BLOCK_TEST_DATA.V3_ROOT_BLOCK_NOBASE, 'Document has unkown fields or wrong line ending format')); + it('a V3 root block must have UnitBase field equal 0', test(LOCAL_RULES_FUNCTIONS.checkUnitBase, BLOCK_TEST_DATA.V3_ROOT_BLOCK_POSITIVE_BASE, 'UnitBase must equal 0 for root block')); + it('a block with wrong date (in past)', test(LOCAL_RULES_FUNCTIONS.checkBlockTimes, BLOCK_TEST_DATA.WRONG_DATE_LOWER, 'A block must have its Time between MedianTime and MedianTime + 1440')); + it('a block with wrong date (in future, but too far)', test(LOCAL_RULES_FUNCTIONS.checkBlockTimes, BLOCK_TEST_DATA.WRONG_DATE_HIGHER_BUT_TOO_HIGH, 'A block must have its Time between MedianTime and MedianTime + 1440')); + it('a root block with different time & medianTime should fail', test(LOCAL_RULES_FUNCTIONS.checkBlockTimes, BLOCK_TEST_DATA.WRONG_ROOT_TIMES, 'Root block must have Time equal MedianTime')); + it('a block with good date', test(LOCAL_RULES_FUNCTIONS.checkBlockTimes, BLOCK_TEST_DATA.GOOD_DATE_HIGHER)); + it('Block cannot contain wrongly signed identities', test(LOCAL_RULES_FUNCTIONS.checkIdentitiesSignature, BLOCK_TEST_DATA.WRONGLY_SIGNED_IDENTITIES, 'Identity\'s signature must match')); + it('block with colliding uids in identities', test(LOCAL_RULES_FUNCTIONS.checkIdentitiesUserIDConflict, BLOCK_TEST_DATA.COLLIDING_UIDS, 'Block must not contain twice same identity uid')); + it('a block with colliding pubkeys in identities', test(LOCAL_RULES_FUNCTIONS.checkIdentitiesPubkeyConflict, BLOCK_TEST_DATA.COLLIDING_PUBKEYS, 'Block must not contain twice same identity pubkey')); + it('a block with identities not matchin joins', test(LOCAL_RULES_FUNCTIONS.checkIdentitiesMatchJoin, BLOCK_TEST_DATA.WRONG_IDTY_MATCH_JOINS, 'Each identity must match a newcomer line with same userid and certts')); + it('Block cannot contain wrongly signed join', test(LOCAL_RULES_FUNCTIONS.checkMembershipsSignature, BLOCK_TEST_DATA.WRONGLY_SIGNED_JOIN, 'Membership\'s signature must match')); + it('Block cannot contain wrongly signed active', test(LOCAL_RULES_FUNCTIONS.checkMembershipsSignature, BLOCK_TEST_DATA.WRONGLY_SIGNED_ACTIVE, 'Membership\'s signature must match')); + it('Block cannot contain wrongly signed leave', test(LOCAL_RULES_FUNCTIONS.checkMembershipsSignature, BLOCK_TEST_DATA.WRONGLY_SIGNED_LEAVE, 'Membership\'s signature must match')); + it('Block cannot contain a same pubkey more than once in joiners', test(LOCAL_RULES_FUNCTIONS.checkPubkeyUnicity, BLOCK_TEST_DATA.MULTIPLE_JOINERS, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); + it('Block cannot contain a same pubkey more than once in actives', test(LOCAL_RULES_FUNCTIONS.checkPubkeyUnicity, BLOCK_TEST_DATA.MULTIPLE_ACTIVES, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); + it('Block cannot contain a same pubkey more than once in leavers', test(LOCAL_RULES_FUNCTIONS.checkPubkeyUnicity, BLOCK_TEST_DATA.MULTIPLE_LEAVES, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); + it('Block cannot contain a same pubkey more than once in excluded', test(LOCAL_RULES_FUNCTIONS.checkPubkeyUnicity, BLOCK_TEST_DATA.MULTIPLE_EXCLUDED, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); + it('Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded', test(LOCAL_RULES_FUNCTIONS.checkPubkeyUnicity, BLOCK_TEST_DATA.MULTIPLE_OVER_ALL, 'Block cannot contain a same pubkey more than once in joiners, actives, leavers and excluded')); + it('Block cannot have revoked key in joiners,actives,leavers', test(LOCAL_RULES_FUNCTIONS.checkMembershipUnicity, BLOCK_TEST_DATA.REVOKED_WITH_MEMBERSHIPS, 'Unicity constraint PUBLIC_KEY on MINDEX is not respected')); + it('Block cannot have revoked key duplicates', test(LOCAL_RULES_FUNCTIONS.checkRevokedUnicity, BLOCK_TEST_DATA.REVOKED_WITH_DUPLICATES, 'A single revocation per member is allowed')); + it('Block revoked keys must be in excluded', test(LOCAL_RULES_FUNCTIONS.checkRevokedAreExcluded, BLOCK_TEST_DATA.REVOKED_NOT_IN_EXCLUDED, 'A revoked member must be excluded')); + it('Block cannot contain 2 certifications from same issuer', test(LOCAL_RULES_FUNCTIONS.checkCertificationOneByIssuer, BLOCK_TEST_DATA.MULTIPLE_CERTIFICATIONS_FROM_SAME_ISSUER, 'Block cannot contain two certifications from same issuer')); + it('Block cannot contain identical certifications', test(LOCAL_RULES_FUNCTIONS.checkCertificationUnicity, BLOCK_TEST_DATA.IDENTICAL_CERTIFICATIONS, 'Block cannot contain identical certifications (A -> B)')); + it('Block cannot contain certifications concerning a leaver', test(LOCAL_RULES_FUNCTIONS.checkCertificationIsntForLeaverOrExcluded, BLOCK_TEST_DATA.LEAVER_WITH_CERTIFICATIONS, 'Block cannot contain certifications concerning leavers or excluded members')); + it('Block cannot contain certifications concerning an excluded member', test(LOCAL_RULES_FUNCTIONS.checkCertificationIsntForLeaverOrExcluded, BLOCK_TEST_DATA.EXCLUDED_WITH_CERTIFICATIONS, 'Block cannot contain certifications concerning leavers or excluded members')); + it('Block cannot contain transactions without issuers (1)', test(LOCAL_RULES_FUNCTIONS.checkTxIssuers, BLOCK_TEST_DATA.TRANSACTION_WITHOUT_ISSUERS, 'A transaction must have at least 1 issuer')); + it('Block cannot contain transactions without issuers (2)', test(LOCAL_RULES_FUNCTIONS.checkTxSources, BLOCK_TEST_DATA.TRANSACTION_WITHOUT_SOURCES, 'A transaction must have at least 1 source')); + it('Block cannot contain transactions without issuers (3)', test(LOCAL_RULES_FUNCTIONS.checkTxRecipients, BLOCK_TEST_DATA.TRANSACTION_WITHOUT_RECIPIENT, 'A transaction must have at least 1 recipient')); + it('Block cannot contain transactions with identical sources in one transaction', test(LOCAL_RULES_FUNCTIONS.checkTxSources, BLOCK_TEST_DATA.TRANSACTION_WITH_DUPLICATED_SOURCE_SINGLE_TX, 'It cannot exist 2 identical sources for transactions inside a given block')); + it('Block cannot contain transactions with identical sources in a pack of transactions', test(LOCAL_RULES_FUNCTIONS.checkTxSources, BLOCK_TEST_DATA.TRANSACTION_WITH_DUPLICATED_SOURCE_MULTIPLE_TX, 'It cannot exist 2 identical sources for transactions inside a given block')); + it('Block cannot contain transactions with empty output conditions', test(LOCAL_RULES_FUNCTIONS.checkTxRecipients, BLOCK_TEST_DATA.TRANSACTION_WITH_EMPTY_TX_CONDITIONS, 'Empty conditions are forbidden')); + it('Block cannot contain transactions with wrong total', test(LOCAL_RULES_FUNCTIONS.checkTxAmounts, BLOCK_TEST_DATA.TRANSACTION_WRONG_TOTAL, 'Transaction inputs sum must equal outputs sum')); + it('Block cannot contain transactions with wrong base transformation', test(LOCAL_RULES_FUNCTIONS.checkTxAmounts, BLOCK_TEST_DATA.TRANSACTION_WRONG_TRANSFORM, 'Transaction output base amount does not equal previous base deltas')); + it('Block cannot contain transactions with unexisting lower base in sources', test(LOCAL_RULES_FUNCTIONS.checkTxAmounts, BLOCK_TEST_DATA.TRANSACTION_WRONG_TRANSFORM_LOW_BASE, 'Transaction output base amount does not equal previous base deltas')); + it('Block cannot contain transactions with more than 100 lines', test(LOCAL_RULES_FUNCTIONS.checkTxLen, BLOCK_TEST_DATA.TRANSACTION_TOO_LONG, 'A transaction has a maximum size of 100 lines')); + it('Block cannot contain transactions with a too large output', test(LOCAL_RULES_FUNCTIONS.checkTxLen, BLOCK_TEST_DATA.OUTPUT_TOO_LONG, 'A transaction output has a maximum size of 2000 characters')); + it('Block cannot contain transactions with a too large unlock', test(LOCAL_RULES_FUNCTIONS.checkTxLen, BLOCK_TEST_DATA.UNLOCK_TOO_LONG, 'A transaction unlock has a maximum size of 2000 characters')); + it('Block cannot be refused with a good V3 transaction', test(LOCAL_RULES_FUNCTIONS.checkTxAmounts, BLOCK_TEST_DATA.TRANSACTION_V3_GOOD_AMOUNTS)); + it('Block cannot contain transactions with wrong signatures', test(LOCAL_RULES_FUNCTIONS.checkTxSignature, BLOCK_TEST_DATA.TRANSACTION_WITH_WRONG_SIGNATURES, 'Signature from a transaction must match')); + }); + +}); + + +function test (rule:any, raw:string, expectedMessage?:string) { + return async () => { + try { + let obj = parsers.parseBlock.syncWrite(raw); + let block = BlockDTO.fromJSONObject(obj); + let index = Indexer.localIndex(block, conf as any) + await rule(block, conf, index); // conf parameter is not always used + if (expectedMessage) { + throw 'Test should have thrown an error'; + } + } catch (e) { + if (!expectedMessage) { + console.error(e.stack || e); + } + if (e.uerr) { + // This is a controlled error + e.uerr.message.should.equal(expectedMessage); + } else if (e) { + // This is a controlled error + e.message.should.equal(expectedMessage); + } else { + // throw Error(e) + // Display non wrapped errors (wrapped error is an error in constants.js) + // console.error(e.stack || e); + } + } + } +} diff --git a/test/fast/misc/cfs.ts b/test/fast/misc/cfs.ts new file mode 100644 index 000000000..db937d26e --- /dev/null +++ b/test/fast/misc/cfs.ts @@ -0,0 +1,137 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {CFSCore} from "../../../app/lib/dal/fileDALs/CFSCore" +import {MemFS} from "../../../app/lib/system/directory" + +const assert = require('assert') +const should = require('should') + +const mockFS = MemFS({ + 'B5_a': { + "A.json": '{ "text": "Content of A from B5_a" }' + }, + 'B4': { + 'B.json': '{ "text": "Content of B" }' + }, + 'B3': { + 'A.json': '{ "text": "Content of A from B3" }', + 'C.json': '{ "text": "Content of C from B3" }' + }, + 'OTHER': { + 'X.json': '{ "text": "Content of X" }' + } +}); + +describe("CFS", () => { + + const coreB3 = new CFSCore('/B3', mockFS); + const coreB4 = new CFSCore('/B4', mockFS); + const coreB5 = new CFSCore('/B5_a', mockFS); + + const rootCore = new CFSCore('/OTHER', mockFS); + + // ------------ Direct READ ------------ + + it('should have the content of A.json from B5', async () => { + const content = await coreB5.readJSON('A.json'); + content.should.have.property('text').equal('Content of A from B5_a'); + }); + + // WRITE of file /C.json + + it('should have the content of C.json modified from B5 (direct read)', async () => { + await coreB5.writeJSON('C.json', { text: 'Content of C from B5_a'}); + const content = await coreB5.readJSON('C.json'); + content.should.have.property('text').equal('Content of C from B5_a'); + }); + + // WRITE of file /D.json + + it('should have the content of D.json modified from B4 (direct read/write)', async () => { + await coreB4.writeJSON('D.json', { text: 'Content of D'}); + const content = await coreB4.readJSON('D.json'); + content.should.have.property('text').equal('Content of D'); + }); + + // REMOVE file /D.json + + it('should have the content of D.json modified from B5 (direct read/write)', async () => { + const exists = await coreB5.exists('D.json'); + const content = await coreB5.read('D.json'); + assert.equal(exists, false); + assert.equal(content, null); + }); + + // ------------ LIST ------------ + + it('should have G,H,I as files from /DIR', async () => { + await coreB3.makeTree('/DIR'); + await coreB4.makeTree('/DIR'); + await coreB5.makeTree('/DIR'); + await coreB3.writeJSON('/DIR/G.json', { text: 'Content of DIR/I'}); + await coreB4.writeJSON('/DIR/H.json', { text: 'Content of DIR/H'}); + await coreB5.writeJSON('/DIR/I.json', { text: 'Content of DIR/G'}); + (await coreB3.list('/DIR')).should.deepEqual(['G.json']); + (await coreB4.list('/DIR')).should.deepEqual(['H.json']); + (await coreB5.list('/DIR')).should.deepEqual(['I.json']); + }); + + // WRITE of file /DIR2/I.json in B4 + + it('should have I as files from /DIR2', async () => { + await coreB3.makeTree('/DIR2'); + await coreB3.writeJSON('/DIR2/I.json', { text: 'Content of DIR2/I in B4'}); + const files = await coreB3.list('/DIR2'); + files.should.have.length(1); + files.should.deepEqual(['I.json']); + // Check its contents + const contents = await coreB3.listJSON('/DIR2'); + contents.should.have.length(1); + contents.should.deepEqual([{ text: 'Content of DIR2/I in B4' }]); + }); + + // REMOVE of file /DIR2/I.json in B5 + + it('should have no files from /DIR2 after file DELETION', async () => { + await coreB3.remove('/DIR2/I.json'); + const files = await coreB3.list('/DIR2'); + files.should.have.length(0); + // Check its contents + const contents = await coreB3.listJSON('/DIR2'); + contents.should.have.length(0); + }); + + describe("Root core", () => { + + it('should have 1 file in /OTHER folder', async () => { + const files = await rootCore.list('/'); + files.should.have.length(1); + // Check its contents + const contents = await rootCore.listJSON('/'); + contents.should.have.length(1); + contents.should.deepEqual([{ text: 'Content of X' }]); + }); + + // REMOVE of file /OTHER/X.json in rootCore + + it('should have no files from /OTHER after file DELETION', async () => { + await rootCore.remove('/X.json'); + const files = await rootCore.list('/'); + files.should.have.length(0); + // Check its contents + const contents = await rootCore.listJSON('/'); + contents.should.have.length(0); + }); + }); +}); diff --git a/test/fast/database.js b/test/fast/misc/database.ts similarity index 62% rename from test/fast/database.js rename to test/fast/misc/database.ts index fcf6c5e6d..aeda0ec89 100644 --- a/test/fast/database.js +++ b/test/fast/misc/database.ts @@ -11,12 +11,10 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {SQLiteDriver} from "../../../app/lib/dal/drivers/SQLiteDriver" -const co = require('co'); -const tmp = require('tmp'); -const should = require('should'); -const SQLiteDriver = require('../../app/lib/dal/drivers/SQLiteDriver').SQLiteDriver +const tmp = require('tmp') +const should = require('should') const MEMORY = ':memory:'; const FILE = tmp.fileSync().name + '.db'; // We add an suffix to avoid Windows-locking of the file by the `tmp` module @@ -41,38 +39,38 @@ describe("SQLite driver", function() { let rows; - it('should be openable and closable on will', () => co(function*() { + it('should be openable and closable on will', async () => { const driver = new SQLiteDriver(MEMORY) - yield driver.executeSql(CREATE_TABLE_SQL); - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.executeSql(CREATE_TABLE_SQL); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); try { // We close the memory database, it should not remember its state - yield driver.closeConnection(); - yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.closeConnection(); + await driver.executeAll(SELECT_FROM_TABLE, []); throw 'Should have thrown an exception'; } catch (err) { err.should.have.property('message').match(/SQLITE_ERROR: no such table: duniter/) } // But if we populate it again, it will work - yield driver.executeSql(CREATE_TABLE_SQL); - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.executeSql(CREATE_TABLE_SQL); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); try { // We explicitely ask for destruction - yield driver.destroyDatabase(); - yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.destroyDatabase(); + await driver.executeAll(SELECT_FROM_TABLE, []); throw 'Should have thrown an exception'; } catch (err) { err.should.have.property('message').match(/SQLITE_ERROR: no such table: duniter/) } // But if we populate it again, it will work - yield driver.executeSql(CREATE_TABLE_SQL); - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.executeSql(CREATE_TABLE_SQL); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); - })); + }) }); describe("File", function() { @@ -80,35 +78,35 @@ describe("SQLite driver", function() { const driver = new SQLiteDriver(FILE); let rows; - it('should be able to open a new one', () => co(function*() { - yield driver.executeSql(CREATE_TABLE_SQL); - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + it('should be able to open a new one', async () => { + await driver.executeSql(CREATE_TABLE_SQL); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); - yield driver.closeConnection(); - })); + await driver.closeConnection(); + }) - it('should be able to reopen the file', () => co(function*() { + it('should be able to reopen the file', async () => { // Reopens the file - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); - })); + }) - it('should be able to remove the file', () => co(function*() { + it('should be able to remove the file', async () => { try { // We explicitely ask for destruction - yield driver.destroyDatabase(); - yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.destroyDatabase(); + await driver.executeAll(SELECT_FROM_TABLE, []); throw 'Should have thrown an exception'; } catch (err) { err.should.have.property('message').match(/SQLITE_ERROR: no such table: duniter/) } - })); + }) - it('should be able to open the file after being removed', () => co(function*() { + it('should be able to open the file after being removed', async () => { // But if we populate it again, it will work - yield driver.executeSql(CREATE_TABLE_SQL); - rows = yield driver.executeAll(SELECT_FROM_TABLE, []); + await driver.executeSql(CREATE_TABLE_SQL); + rows = await driver.executeAll(SELECT_FROM_TABLE, []); rows.should.have.length(0); - })); - }); -}); + }) + }) +}) diff --git a/test/fast/entities.js b/test/fast/misc/entities.ts similarity index 88% rename from test/fast/entities.js rename to test/fast/misc/entities.ts index 4f5656354..542e7d541 100644 --- a/test/fast/entities.js +++ b/test/fast/misc/entities.ts @@ -11,9 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -let should = require('should'); -let BlockDTO = require('../../app/lib/dto/BlockDTO').BlockDTO +import {BlockDTO} from "../../../app/lib/dto/BlockDTO" + +const should = require('should'); describe('Entities', () => { diff --git a/test/fast/merkle.js b/test/fast/misc/merkle.ts similarity index 91% rename from test/fast/merkle.js rename to test/fast/misc/merkle.ts index b93e6823d..503ad947e 100644 --- a/test/fast/merkle.js +++ b/test/fast/misc/merkle.ts @@ -11,15 +11,14 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -var should = require('should'); -var assert = require('assert'); +import {MerkleDTO} from "../../../app/lib/dto/MerkleDTO" -var MerkleDTO = require('../../app/lib/dto/MerkleDTO').MerkleDTO +const should = require('should'); +const assert = require('assert'); describe("Merkle ['a', 'b', 'c', 'd', 'e']", function(){ - var m = new MerkleDTO(); + const m = new MerkleDTO() as any m.initialize(['a', 'b', 'c', 'd', 'e']); it('should have root 16E6BEB3E080910740A2923D6091618CAA9968AEAD8A52D187D725D199548E2C', function(){ @@ -53,7 +52,7 @@ describe("Merkle ['a', 'b', 'c', 'd', 'e']", function(){ describe("Merkle []", function(){ - var m = new MerkleDTO(); + const m = new MerkleDTO() as any m.initialize([]); it('should have root empty', function(){ diff --git a/test/fast/modules/bma/ddos-test.js b/test/fast/modules/bma/bma-ddos-test.ts similarity index 100% rename from test/fast/modules/bma/ddos-test.js rename to test/fast/modules/bma/bma-ddos-test.ts diff --git a/test/fast/modules/bma/limiter-test.js b/test/fast/modules/bma/bma-limiter-test.ts similarity index 100% rename from test/fast/modules/bma/limiter-test.js rename to test/fast/modules/bma/bma-limiter-test.ts diff --git a/test/fast/modules/bma/module-test.js b/test/fast/modules/bma/bma-module-test.ts similarity index 67% rename from test/fast/modules/bma/module-test.js rename to test/fast/modules/bma/bma-module-test.ts index 08c575773..4e85f3973 100644 --- a/test/fast/modules/bma/module-test.js +++ b/test/fast/modules/bma/bma-module-test.ts @@ -11,141 +11,139 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {BmaDependency} from "../../../../app/modules/bma/index" +import {KeypairDependency} from "../../../../app/modules/keypair/index" +import {Network} from "../../../../app/modules/bma/lib/network" + const assert = require('assert'); const should = require('should'); -const co = require('co'); -const duniterBMA = require('../../../../app/modules/bma/index').BmaDependency -const duniterKeypair = require('../../../../app/modules/keypair').KeypairDependency -const network = require('../../../../app/modules/bma/lib/network').Network const duniter = require('../../../../index') -const logger = require('../../../../app/lib/logger').NewLogger() const rp = require('request-promise'); const stack = duniter.statics.minimalStack(); -stack.registerDependency(duniterKeypair, 'duniter-keypair'); -stack.registerDependency(duniterBMA, 'duniter-bma'); +stack.registerDependency(KeypairDependency, 'duniter-keypair'); +stack.registerDependency(BmaDependency, 'duniter-bma'); describe('Module usage', () => { - it('/node/summary should answer', () => co(function*() { + it('/node/summary should answer', async () => { stack.registerDependency({ duniter: { cli: [{ name: 'test1', desc: 'Unit Test execution', - onDatabaseExecute: (server, conf, program, params, startServices) => co(function*() { - yield startServices(); - }) + onDatabaseExecute: async (server:any, conf:any, program:any, params:any, startServices:any) => { + await startServices(); + } }] } }, 'duniter-automated-test'); - yield stack.executeStack(['node', 'index.js', 'test1', + await stack.executeStack(['node', 'index.js', 'test1', '--memory', '--noupnp', '--ipv4', '127.0.0.1', '--port', '10400' ]); - const json = yield rp.get({ + const json = await rp.get({ url: 'http://127.0.0.1:10400/node/summary', json: true, timeout: 1000 }); should.exist(json); json.should.have.property('duniter').property('software').equal('duniter'); - })); + }) - it('remoteipv4 should NOT be filled if remote Host is declared', () => co(function*() { + it('remoteipv4 should NOT be filled if remote Host is declared', async () => { stack.registerDependency({ duniter: { cli: [{ name: 'test2', desc: 'Unit Test execution', - onConfiguredExecute: (server, conf, program, params, startServices) => co(function*() { + onConfiguredExecute: async (server:any, conf:any, program:any, params:any, startServices:any) => { conf.should.not.have.property('remoteipv4'); conf.should.have.property('remoteipv6').equal(undefined); conf.should.have.property('remotehost').equal('localhost'); - }) + } }] } }, 'duniter-automated-test'); - yield stack.executeStack(['node', 'index.js', 'test2', + await stack.executeStack(['node', 'index.js', 'test2', '--memory', '--ipv4', '127.0.0.1', '--remoteh', 'localhost', '--port', '10400' ]); - })); + }) - it('remoteipv4 should NOT be filled if remote IPv6 is declared', () => co(function*() { + it('remoteipv4 should NOT be filled if remote IPv6 is declared', async () => { stack.registerDependency({ duniter: { cli: [{ name: 'test3', desc: 'Unit Test execution', - onConfiguredExecute: (server, conf, program, params, startServices) => co(function*() { + onConfiguredExecute: async (server:any, conf:any, program:any, params:any, startServices:any) => { conf.should.not.have.property('remoteipv4'); conf.should.not.have.property('remotehost'); conf.should.have.property('remoteipv6').equal('::1'); - }) + } }] } }, 'duniter-automated-test'); - yield stack.executeStack(['node', 'index.js', 'test3', + await stack.executeStack(['node', 'index.js', 'test3', '--memory', '--ipv4', '127.0.0.1', '--ipv6', '::1', '--port', '10400' ]); - })); + }) - it('remoteipv4 should be NOT be auto-filled if manual remoteipv4 is declared', () => co(function*() { + it('remoteipv4 should be NOT be auto-filled if manual remoteipv4 is declared', async () => { stack.registerDependency({ duniter: { cli: [{ name: 'test4', desc: 'Unit Test execution', - onConfiguredExecute: (server, conf, program, params, startServices) => co(function*() { + onConfiguredExecute: async (server:any, conf:any, program:any, params:any, startServices:any) => { conf.should.not.have.property('remotehost'); conf.should.have.property('remoteipv6').equal(undefined); conf.should.have.property('remoteipv4').equal('192.168.0.1'); - }) + } }] } }, 'duniter-automated-test'); - yield stack.executeStack(['node', 'index.js', 'test4', + await stack.executeStack(['node', 'index.js', 'test4', '--memory', '--remote4', '192.168.0.1', '--ipv4', '127.0.0.1', '--port', '10400' ]); - })); + }) - it('remoteipv4 should be filled if no remote is declared, but local IPv4 is', () => co(function*() { + it('remoteipv4 should be filled if no remote is declared, but local IPv4 is', async () => { stack.registerDependency({ duniter: { cli: [{ name: 'test5', desc: 'Unit Test execution', - onConfiguredExecute: (server, conf, program, params, startServices) => co(function*() { + onConfiguredExecute: async (server:any, conf:any, program:any, params:any, startServices:any) => { conf.should.not.have.property('remotehost'); conf.should.have.property('remoteipv6').equal(undefined); conf.should.have.property('remoteipv4').equal('127.0.0.1'); - }) + } }] } }, 'duniter-automated-test'); - yield stack.executeStack(['node', 'index.js', 'test5', + await stack.executeStack(['node', 'index.js', 'test5', '--memory', '--ipv4', '127.0.0.1', '--port', '10400' ]); - })); + }) - it('default IPv6 should not be a local one', () => co(function*() { - const ipv6 = network.getBestLocalIPv6(); + it('default IPv6 should not be a local one', async () => { + const ipv6 = Network.getBestLocalIPv6(); if (ipv6) { ipv6.should.not.match(/fe80/); } - })); -}); + }) +}) diff --git a/test/fast/modules/common/crypto.js b/test/fast/modules/common/common-crypto-test.ts similarity index 61% rename from test/fast/modules/common/crypto.js rename to test/fast/modules/common/common-crypto-test.ts index 3a275f00f..092e8d1cb 100644 --- a/test/fast/modules/common/crypto.js +++ b/test/fast/modules/common/common-crypto-test.ts @@ -11,28 +11,23 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const should = require('should'); -const co = require('co'); -const nacl = require('tweetnacl'); -const base58 = require('../../../../app/lib/common-libs').base58 -const keyring = require('../../../../app/lib/common-libs/crypto/keyring'); +import {KeyGen, verify} from "../../../../app/lib/common-libs/crypto/keyring" +import {Base58decode, Base58encode} from "../../../../app/lib/common-libs/crypto/base58" -const enc = require('../../../../app/lib/common-libs/crypto/nacl-util').encodeBase64, - dec = require('../../../../app/lib/common-libs/crypto/nacl-util').decodeBase64 +const should = require('should'); -let pub, sec, rawPub, rawSec; +let pub:Uint8Array, sec:Uint8Array, rawPub:string, rawSec:string describe('ed25519 tests:', function(){ - before(() => co(function*() { + before(async () => { // Generate the keypair - const keyPair = keyring.KeyGen('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); - pub = base58.decode(keyPair.publicKey); - sec = base58.decode(keyPair.secretKey); - rawPub = base58.encode(pub); - rawSec = base58.encode(sec); - })); + const keyPair = KeyGen('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); + pub = Base58decode(keyPair.publicKey); + sec = Base58decode(keyPair.secretKey); + rawPub = Base58encode(pub); + rawSec = Base58encode(sec); + }) //it('good signature from existing secret key should be verified', function(done){ // const keys = nacl.sign.scryptKeyPair.fromSecretKey(dec("TM0Imyj/ltqdtsNG7BFOD1uKMZ81q6Yk2oz27U+4pvs9QBfD6EOJWpK3CqdNG368nJgszy7ElozAzVXxKvRmDA==")); @@ -46,17 +41,16 @@ describe('ed25519 tests:', function(){ it('good signature from generated key should be verified', function(done){ const msg = "Some message to be signed"; - const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg); - const verified = keyring.verify(msg, sig, rawPub); + const sig = KeyGen(rawPub, rawSec).signSync(msg); + const verified = verify(msg, sig, rawPub); verified.should.equal(true); done(); }); it('wrong signature from generated key should NOT be verified', function(done){ const msg = "Some message to be signed"; - const cor = dec(enc(msg) + 'delta'); - const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg); - const verified = keyring.verify(cor, sig, rawPub); + const sig = KeyGen(rawPub, rawSec).signSync(msg); + const verified = verify(msg + 'delta', sig, rawPub); verified.should.equal(false); done(); }); diff --git a/test/fast/modules/common/peering.js b/test/fast/modules/common/common-peering-test.ts similarity index 93% rename from test/fast/modules/common/peering.js rename to test/fast/modules/common/common-peering-test.ts index 954575e24..9f3c4cea6 100644 --- a/test/fast/modules/common/peering.js +++ b/test/fast/modules/common/common-peering-test.ts @@ -11,11 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {PeerDTO} from "../../../../app/lib/dto/PeerDTO" +import {parsers} from "../../../../app/lib/common-libs/parsers/index" + const should = require('should'); const assert = require('assert'); -const parsers = require('../../../../app/lib/common-libs/parsers').parsers -const PeerDTO = require('../../../../app/lib/dto/PeerDTO').PeerDTO const rawPeer = "" + "Version: 10\n" + @@ -32,7 +32,7 @@ describe('Peer', function(){ describe('of some key', function(){ - var pr; + let pr:any before(function(done) { pr = PeerDTO.fromJSONObject(parsers.parsePeer.syncWrite(rawPeer)) diff --git a/test/fast/modules/common/randomKey.js b/test/fast/modules/common/common-random-key.ts similarity index 61% rename from test/fast/modules/common/randomKey.js rename to test/fast/modules/common/common-random-key.ts index 0aabe14a2..172154b8d 100644 --- a/test/fast/modules/common/randomKey.js +++ b/test/fast/modules/common/common-random-key.ts @@ -11,38 +11,31 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const should = require('should'); -const co = require('co'); -const nacl = require('tweetnacl'); -const keyring = require('../../../../app/lib/common-libs/crypto/keyring'); - +import {Key, KeyGen, randomKey, verify} from "../../../../app/lib/common-libs/crypto/keyring" -const enc = require('../../../../app/lib/common-libs/crypto/nacl-util').encodeBase64, - dec = require('../../../../app/lib/common-libs/crypto/nacl-util').decodeBase64 +const should = require('should'); -let key; +let key:Key describe('Random keypair', function(){ - before(() => co(function*() { + before(async () => { // Generate the keypair - key = keyring.randomKey() - })); + key = randomKey() + }) it('good signature from generated key should be verified', function(done){ const msg = "Some message to be signed"; - const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg); - const verified = keyring.verify(msg, sig, key.publicKey); + const sig = KeyGen(key.publicKey, key.secretKey).signSync(msg); + const verified = verify(msg, sig, key.publicKey); verified.should.equal(true); done(); }); it('wrong signature from generated key should NOT be verified', function(done){ const msg = "Some message to be signed"; - const cor = dec(enc(msg) + 'delta'); - const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg); - const verified = keyring.verify(cor, sig, key.publicKey); + const sig = KeyGen(key.publicKey, key.secretKey).signSync(msg); + const verified = verify(msg + 'delta', sig, key.publicKey); verified.should.equal(false); done(); }); diff --git a/test/fast/modules/common/tx_format.js b/test/fast/modules/common/common-tx-format.ts similarity index 88% rename from test/fast/modules/common/tx_format.js rename to test/fast/modules/common/common-tx-format.ts index 5b0df732b..6c958119c 100644 --- a/test/fast/modules/common/tx_format.js +++ b/test/fast/modules/common/common-tx-format.ts @@ -11,11 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -var should = require('should'); -var parsers = require('../../../../app/lib/common-libs/parsers').parsers +import {parsers} from "../../../../app/lib/common-libs/parsers/index" -var raw = "Version: 10\n" + +const should = require('should'); + +const raw = "Version: 10\n" + "Type: Transaction\n" + "Currency: test_net\n" + "Blockstamp: 3-2A27BD040B16B7AF59DDD88890E616987F4DD28AA47B9ABDBBEE46257B88E945\n" + @@ -34,7 +34,7 @@ var raw = "Version: 10\n" + describe("Transaction format", function(){ - var parser = parsers.parseTransaction; + const parser = parsers.parseTransaction; it('a valid block should be well formatted', () => parser.syncWrite(raw)); diff --git a/test/fast/modules/crawler/peers_garbaging.js b/test/fast/modules/crawler/crawler-peers-garbaging.ts similarity index 59% rename from test/fast/modules/crawler/peers_garbaging.js rename to test/fast/modules/crawler/crawler-peers-garbaging.ts index 9e29d392a..9bb881fc8 100644 --- a/test/fast/modules/crawler/peers_garbaging.js +++ b/test/fast/modules/crawler/crawler-peers-garbaging.ts @@ -11,14 +11,13 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const should = require('should'); -const co = require('co'); +import {cleanLongDownPeers} from "../../../../app/modules/crawler/lib/garbager" +import {Server} from "../../../../server" -const garbager = require('../../../../app/modules/crawler/lib/garbager') +const should = require('should'); const duniter = require('../../../../index') -let stack +let stack:any describe('Peers garbaging', () => { @@ -33,23 +32,23 @@ describe('Peers garbaging', () => { name: 'garbage', desc: 'Garbage testing', logs: false, - onDatabaseExecute: (server, conf, program, params) => co(function*() { - yield server.dal.peerDAL.savePeer({ pubkey: 'A', version: 1, currency: 'c', first_down: null, statusTS: 1485000000000, block: '2393-H' }); - yield server.dal.peerDAL.savePeer({ pubkey: 'B', version: 1, currency: 'c', first_down: 1484827199999, statusTS: 1485000000000, block: '2393-H' }); - yield server.dal.peerDAL.savePeer({ pubkey: 'C', version: 1, currency: 'c', first_down: 1484827200000, statusTS: 1485000000000, block: '2393-H' }); - yield server.dal.peerDAL.savePeer({ pubkey: 'D', version: 1, currency: 'c', first_down: 1484820000000, statusTS: 1485000000000, block: '2393-H' }); - (yield server.dal.peerDAL.listAll()).should.have.length(4); + onDatabaseExecute: async (server:Server) => { + await server.dal.peerDAL.savePeer({ pubkey: 'A', version: 1, currency: 'c', first_down: null, statusTS: 1485000000000, block: '2393-H' } as any); + await server.dal.peerDAL.savePeer({ pubkey: 'B', version: 1, currency: 'c', first_down: 1484827199999, statusTS: 1485000000000, block: '2393-H' } as any); + await server.dal.peerDAL.savePeer({ pubkey: 'C', version: 1, currency: 'c', first_down: 1484827200000, statusTS: 1485000000000, block: '2393-H' } as any); + await server.dal.peerDAL.savePeer({ pubkey: 'D', version: 1, currency: 'c', first_down: 1484820000000, statusTS: 1485000000000, block: '2393-H' } as any); + (await server.dal.peerDAL.listAll()).should.have.length(4); const now = 1485000000000; - yield garbager.cleanLongDownPeers(server, now); - (yield server.dal.peerDAL.listAll()).should.have.length(2); - }) + await cleanLongDownPeers(server, now); + (await server.dal.peerDAL.listAll()).should.have.length(2); + } }] } } }]); }) - it('should be able to garbage some peers', () => co(function*() { - yield stack.executeStack(['node', 'b.js', '--memory', 'garbage']); - })); -}); + it('should be able to garbage some peers', async () => { + await stack.executeStack(['node', 'b.js', '--memory', 'garbage']); + }) +}) diff --git a/test/fast/modules/keypair/crypto-test.js b/test/fast/modules/keypair/keypair-crypto-test.ts similarity index 77% rename from test/fast/modules/keypair/crypto-test.js rename to test/fast/modules/keypair/keypair-crypto-test.ts index 3ea1686da..1424c649e 100644 --- a/test/fast/modules/keypair/crypto-test.js +++ b/test/fast/modules/keypair/keypair-crypto-test.ts @@ -11,28 +11,27 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {Scrypt} from "../../../../app/modules/keypair/lib/scrypt" + const should = require('should'); -const co = require('co'); -const scrypt = require('../../../../app/modules/keypair/lib/scrypt').Scrypt describe('Scrypt salt // key', () => { - it('abc // abc', () => co(function*() { - const pair = yield scrypt('abc', 'abc'); + it('abc // abc', async () => { + const pair = await Scrypt('abc', 'abc'); pair.should.have.property('pub').equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); pair.should.have.property('sec').equal('51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); - })); + }) - it('abc // def', () => co(function*() { - const pair = yield scrypt('abc', 'def'); + it('abc // def', async () => { + const pair = await Scrypt('abc', 'def'); pair.should.have.property('pub').equal('G2CBgZBPLe6FSFUgpx2Jf1Aqsgta6iib3vmDRA1yLiqU'); pair.should.have.property('sec').equal('58LDg8QLmF5pv6Dn9h7X4yFKfMTdP8fdAiWVcyDoTRJu454fwRihCLULH4MW37zncsg4ruoTGJPZneWk22QmG1w4'); - })); + }) - it('azerty // def', () => co(function*() { - const pair = yield scrypt('azerty', 'def'); + it('azerty // def', async () => { + const pair = await Scrypt('azerty', 'def'); pair.should.have.property('pub').equal('3dbw4NYVEm5mwTH6bFrqBhan1k39qNHubkQWdrw2C5AD'); pair.should.have.property('sec').equal('4kemdi17CPkkBPnjXiPFf6oBhdGiiqhCL3R4Tuafe9THK8mzBs1evHw5r9u3f8xts2zn6VCBJYVrRMzdaEaWn5Ch'); - })); -}); + }) +}) diff --git a/test/fast/modules/keypair/module-test.js b/test/fast/modules/keypair/keypair-module-test.ts similarity index 75% rename from test/fast/modules/keypair/module-test.js rename to test/fast/modules/keypair/keypair-module-test.ts index 7ea191e6e..2b5f5db65 100644 --- a/test/fast/modules/keypair/module-test.js +++ b/test/fast/modules/keypair/keypair-module-test.ts @@ -11,34 +11,32 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {KeypairDependency} from "../../../../app/modules/keypair/index" + const should = require('should'); -const co = require('co'); -const keypair = require('../../../../app/modules/keypair/index').KeypairDependency -const assert = require('assert'); const duniter = require('../../../../index') describe('Module usage', () => { - it('wrong options should throw', () => co(function*() { + it('wrong options should throw', async () => { let errMessage; try { const stack = duniter.statics.minimalStack(); - stack.registerDependency(keypair, 'duniter-keypair'); - yield stack.executeStack(['node', 'index.js', 'config', '--memory', '--keyN', '2048']); + stack.registerDependency(KeypairDependency, 'duniter-keypair'); + await stack.executeStack(['node', 'index.js', 'config', '--memory', '--keyN', '2048']); } catch (e) { errMessage = e.message; } should.exist(errMessage); should.equal(errMessage, 'Missing --salt and --passwd options along with --keyN|keyr|keyp option'); - })); + }) - it('no options on brand new node should generate random key', () => co(function*() { + it('no options on brand new node should generate random key', async () => { const stack = duniter.statics.minimalStack(); - stack.registerDependency(keypair, 'duniter-keypair'); - const res = yield stack.executeStack(['node', 'index.js', 'config', '--memory']); + stack.registerDependency(KeypairDependency, 'duniter-keypair'); + const res = await stack.executeStack(['node', 'index.js', 'config', '--memory']); // This is extremely very unlikely to happen res.pair.should.have.property('pub').not.equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); res.pair.should.have.property('sec').not.equal('51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'); - })); -}); + }) +}) diff --git a/test/fast/protocol-brg107-udEffectiveTime.js b/test/fast/protocol-brg107-udEffectiveTime.js deleted file mode 100644 index 80a724935..000000000 --- a/test/fast/protocol-brg107-udEffectiveTime.js +++ /dev/null @@ -1,53 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer - -describe("Protocol BR_G107 - udReevalTime", function(){ - - it('root block good udReevalTime', () => co(function*(){ - const conf = { udReevalTime0: 1500000000 }; - const HEAD_1 = null; - const HEAD = { number: 0 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udReevalTime.should.equal(conf.udReevalTime0); - })); - - it('block with medianTime < udReevalTime', () => co(function*(){ - const conf = { dt: 100, dtReeval: 20 }; - const HEAD_1 = { number: 59, udReevalTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000899 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime); - })); - - it('block with medianTime == udReevalTime', () => co(function*(){ - const conf = { dt: 100, dtReeval: 20 }; - const HEAD_1 = { number: 59, udReevalTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000900 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime + conf.dtReeval); - })); - - it('block with medianTime > udReevalTime', () => co(function*(){ - const conf = { dt: 100, dtReeval: 20 }; - const HEAD_1 = { number: 59, udReevalTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000901 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime + conf.dtReeval); - })); - -}); diff --git a/test/fast/protocol-brg11-udTime.js b/test/fast/protocol-brg11-udTime.js deleted file mode 100644 index 9899b5b50..000000000 --- a/test/fast/protocol-brg11-udTime.js +++ /dev/null @@ -1,53 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer - -describe("Protocol BR_G11 - udTime", function(){ - - it('root block good udTime', () => co(function*(){ - const conf = { udTime0: 1500000000 }; - const HEAD_1 = null; - const HEAD = { number: 0 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udTime.should.equal(conf.udTime0); - })); - - it('block with medianTime < udTime', () => co(function*(){ - const conf = { dt: 100 }; - const HEAD_1 = { number: 59, udTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000899 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udTime.should.equal(HEAD_1.udTime); - })); - - it('block with medianTime == udTime', () => co(function*(){ - const conf = { dt: 100 }; - const HEAD_1 = { number: 59, udTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000900 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); - })); - - it('block with medianTime > udTime', () => co(function*(){ - const conf = { dt: 100 }; - const HEAD_1 = { number: 59, udTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000901 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); - })); - -}); diff --git a/test/fast/protocol-brg49-version.js b/test/fast/protocol-brg49-version.js deleted file mode 100644 index 151134e3a..000000000 --- a/test/fast/protocol-brg49-version.js +++ /dev/null @@ -1,47 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer - -const FAIL = false; -const SUCCESS = true; - -describe("Protocol BR_G49 - Version", function(){ - - it('V13 following V12 should fail', () => co(function*(){ - const HEAD_1 = { number: 17, version: 13 }; - const HEAD = { number: 18, version: 12 }; - indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); - })); - - it('V14 following V12 should fail', () => co(function*(){ - const HEAD_1 = { number: 17, version: 14 }; - const HEAD = { number: 18, version: 12 }; - indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); - })); - - it('V13 following V14 should succeed', () => co(function*(){ - const HEAD_1 = { number: 17, version: 13 }; - const HEAD = { number: 18, version: 14 }; - indexer.ruleVersion(HEAD, HEAD_1).should.equal(SUCCESS); - })); - - it('V13 following V15 should fail', () => co(function*(){ - const HEAD_1 = { number: 17, version: 13 }; - const HEAD = { number: 18, version: 15 }; - indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); - })); -}); diff --git a/test/fast/protocol-brg50-blocksize.js b/test/fast/protocol-brg50-blocksize.js deleted file mode 100644 index 8d19f9e34..000000000 --- a/test/fast/protocol-brg50-blocksize.js +++ /dev/null @@ -1,68 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer - -const FAIL = false; -const SUCCESS = true; - -describe("Protocol BR_G50 - Block size", function(){ - - it('2 for an AVG(10) should succeed', () => co(function*(){ - const HEAD = { number: 24, bsize: 2, avgBlockSize: 10 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); - - it('400 for an AVG(10) should succeed', () => co(function*(){ - const HEAD = { number: 24, bsize: 400, avgBlockSize: 10 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); - - it('499 for an AVG(10) should succeed', () => co(function*(){ - const HEAD = { number: 24, bsize: 499, avgBlockSize: 10 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); - - it('500 for an AVG(10) should fail', () => co(function*(){ - const HEAD = { number: 24, bsize: 500, avgBlockSize: 10 }; - indexer.ruleBlockSize(HEAD).should.equal(FAIL); - })); - - it('500 for an AVG(454) should fail', () => co(function*(){ - const HEAD = { number: 24, bsize: 500, avgBlockSize: 454 }; - indexer.ruleBlockSize(HEAD).should.equal(FAIL); - })); - - it('500 for an AVG(455) should succeed', () => co(function*(){ - const HEAD = { number: 24, bsize: 500, avgBlockSize: 455 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); - - it('1100 for an AVG(1000) should fail', () => co(function*(){ - const HEAD = { number: 24, bsize: 1100, avgBlockSize: 1000 }; - indexer.ruleBlockSize(HEAD).should.equal(FAIL); - })); - - it('1100 for an AVG(1001) should succeed', () => co(function*(){ - const HEAD = { number: 24, bsize: 1100, avgBlockSize: 1001 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); - - it('1100 for block#0 should succeed', () => co(function*(){ - const HEAD = { number: 0, bsize: 1100, avgBlockSize: 0 }; - indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); - })); -}); diff --git a/test/fast/protocol-brg51-number.js b/test/fast/protocol-brg51-number.js deleted file mode 100644 index 465238ea4..000000000 --- a/test/fast/protocol-brg51-number.js +++ /dev/null @@ -1,80 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -const co = require('co'); -const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer - -const FAIL = false; -const SUCCESS = true; - -describe("Protocol BR_G51 - Number", function(){ - - it('1 following 1 should fail', () => co(function*(){ - const block = { number: 1 }; - const HEAD_1 = { number: 1 }; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(FAIL); - })); - - it('1 following 0 should succeed', () => co(function*(){ - const block = { number: 1 }; - const HEAD_1 = { number: 0 }; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); - })); - - it('0 following 0 should fail', () => co(function*(){ - const block = { number: 0 }; - const HEAD_1 = { number: 0 }; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(FAIL); - })); - - it('0 following nothing should succeed', () => co(function*(){ - const block = { number: 0 }; - const HEAD_1 = null; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); - })); - - it('4 following nothing should fail', () => co(function*(){ - const block = { number: 4 }; - const HEAD_1 = null; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(FAIL); - })); - - it('4 following 2 should fail', () => co(function*(){ - const block = { number: 4 }; - const HEAD_1 = { number: 2 }; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(FAIL); - })); - - it('4 following 3 should succeed', () => co(function*(){ - const block = { number: 4 }; - const HEAD_1 = { number: 3 }; - const HEAD = {}; - indexer.prepareNumber(HEAD, HEAD_1); - indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); - })); - -}); diff --git a/test/fast/protocol-brg106-number.js b/test/fast/protocol/protocol-brg106-number.ts similarity index 88% rename from test/fast/protocol-brg106-number.js rename to test/fast/protocol/protocol-brg106-number.ts index 334f18ab9..0af3d3f9c 100644 --- a/test/fast/protocol-brg106-number.js +++ b/test/fast/protocol/protocol-brg106-number.ts @@ -11,22 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; -const co = require('co'); +import {Map} from "../../../app/lib/common-libs/crypto/map" +import {Indexer} from "../../../app/lib/indexer" + const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer describe("Protocol BR_G106 - Garbaging", function(){ - it('An account with balance < 1,00 should be cleaned up', () => co(function*(){ - const balances = { + it('An account with balance < 1,00 should be cleaned up', async () => { + const balances:Map<{ balance: number }> = { pubkeyA: { balance: 103 }, pubkeyB: { balance: 11 + 22 + 68 }, // 101 pubkeyC: { balance: 100 }, pubkeyD: { balance: 0 }, pubkeyE: { balance: 0 } } - const sources = { + const sources:any = { pubkeyA: [ // 103 { amount: 103, base: 0, tx: 'A1', identifier: 'I1', pos: 0 } ], @@ -42,13 +42,13 @@ describe("Protocol BR_G106 - Garbaging", function(){ pubkeyE: [] } const dal = { - getWallet: (conditions) => Promise.resolve(balances[conditions]), + getWallet: (conditions:string) => Promise.resolve(balances[conditions]), sindexDAL: { - getAvailableForConditions: (conditions) => Promise.resolve(sources[conditions]) + getAvailableForConditions: (conditions:string) => Promise.resolve(sources[conditions]) } }; - const HEAD = { unitBase: 0 }; - const cleaning = yield indexer.ruleIndexGarbageSmallAccounts(HEAD, [ + const HEAD = { unitBase: 0 } as any + const cleaning = await Indexer.ruleIndexGarbageSmallAccounts(HEAD, [ // A sends 3 to D --> A keeps 100 { op: 'UPDATE', conditions: 'pubkeyA', amount: 103, base: 0, identifier: 'I1', pos: 0 }, { op: 'CREATE', conditions: 'pubkeyA', amount: 100, base: 0, identifier: 'I2', pos: 0 }, @@ -62,7 +62,7 @@ describe("Protocol BR_G106 - Garbaging", function(){ // C sends 100 to E --> C keeps 0 { op: 'UPDATE', conditions: 'pubkeyC', amount: 100, base: 0, identifier: 'I8', pos: 0 }, { op: 'CREATE', conditions: 'pubkeyE', amount: 100, base: 0, identifier: 'I9', pos: 0 } - ], dal); + ] as any, dal as any); cleaning.should.have.length(5); cleaning[0].should.have.property('identifier').equal('I3'); cleaning[0].should.have.property('amount').equal(3); @@ -98,5 +98,5 @@ describe("Protocol BR_G106 - Garbaging", function(){ cleaning[4].should.have.property('tx').equal(null); cleaning[4].should.have.property('consumed').equal(true); cleaning[4].should.have.property('op').equal('UPDATE'); - })); -}); + }) +}) diff --git a/test/fast/protocol/protocol-brg107-udEffectiveTime.ts b/test/fast/protocol/protocol-brg107-udEffectiveTime.ts new file mode 100644 index 000000000..43176bdc1 --- /dev/null +++ b/test/fast/protocol/protocol-brg107-udEffectiveTime.ts @@ -0,0 +1,52 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Indexer} from "../../../app/lib/indexer" + +const should = require('should'); + +describe("Protocol BR_G107 - udReevalTime", function(){ + + it('root block good udReevalTime', async () => { + const conf = { udReevalTime0: 1500000000 } as any + const HEAD_1 = null as any + const HEAD = { number: 0 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udReevalTime.should.equal(conf.udReevalTime0); + }) + + it('block with medianTime < udReevalTime', async () => { + const conf = { dt: 100, dtReeval: 20 } as any + const HEAD_1 = { number: 59, udReevalTime: 1500000900 } as any + const HEAD = { number: 60, medianTime: 1500000899 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime); + }) + + it('block with medianTime == udReevalTime', async () => { + const conf = { dt: 100, dtReeval: 20 } as any + const HEAD_1 = { number: 59, udReevalTime: 1500000900 } as any + const HEAD = { number: 60, medianTime: 1500000900 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime + conf.dtReeval); + }) + + it('block with medianTime > udReevalTime', async () => { + const conf = { dt: 100, dtReeval: 20 } as any + const HEAD_1 = { number: 59, udReevalTime: 1500000900 } as any + const HEAD = { number: 60, medianTime: 1500000901 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udReevalTime.should.equal(HEAD_1.udReevalTime + conf.dtReeval); + }) + +}); diff --git a/test/fast/protocol/protocol-brg11-udTime.ts b/test/fast/protocol/protocol-brg11-udTime.ts new file mode 100644 index 000000000..0125226de --- /dev/null +++ b/test/fast/protocol/protocol-brg11-udTime.ts @@ -0,0 +1,52 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Indexer} from "../../../app/lib/indexer" + +const should = require('should'); + +describe("Protocol BR_G11 - udTime", function(){ + + it('root block good udTime', async () => { + const conf = { udTime0: 1500000000 } as any + const HEAD_1 = null as any + const HEAD = { number: 0 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udTime.should.equal(conf.udTime0); + }) + + it('block with medianTime < udTime', async () => { + const conf = { dt: 100 } as any + const HEAD_1 = { number: 59, udTime: 1500000900 }as any + const HEAD = { number: 60, medianTime: 1500000899 }as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udTime.should.equal(HEAD_1.udTime); + }) + + it('block with medianTime == udTime', async () => { + const conf = { dt: 100 } as any + const HEAD_1 = { number: 59, udTime: 1500000900 }as any + const HEAD = { number: 60, medianTime: 1500000900 }as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); + }) + + it('block with medianTime > udTime', async () => { + const conf = { dt: 100 }as any + const HEAD_1 = { number: 59, udTime: 1500000900 }as any + const HEAD = { number: 60, medianTime: 1500000901 }as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf) + HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); + }) + +}) diff --git a/test/fast/protocol-brg13-dividend.js b/test/fast/protocol/protocol-brg13-dividend.ts similarity index 54% rename from test/fast/protocol-brg13-dividend.js rename to test/fast/protocol/protocol-brg13-dividend.ts index 66025d6ce..e5d31d917 100644 --- a/test/fast/protocol-brg13-dividend.js +++ b/test/fast/protocol/protocol-brg13-dividend.ts @@ -12,49 +12,49 @@ // GNU Affero General Public License for more details. "use strict"; -const co = require('co'); +import {Indexer} from "../../../app/lib/indexer" + const should = require('should'); -const indexer = require('../../app/lib/indexer').Indexer describe("Protocol BR_G13 - dividend", function(){ - it('root block has no dividend', () => co(function*(){ - const conf = { udTime0: 1500000000, dt: 100 }; - const HEAD_1 = null; - const HEAD = { number: 0 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - indexer.prepareDividend(HEAD, HEAD_1, conf); + it('root block has no dividend', async () => { + const conf = { udTime0: 1500000000, dt: 100 } as any + const HEAD_1 = null as any + const HEAD = { number: 0 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + Indexer.prepareDividend(HEAD, HEAD_1, conf); should.equal(HEAD.dividend, null); - })); - - it('block with medianTime < udTime has no dividend', () => co(function*(){ - const conf = { dt: 100 }; - const HEAD_1 = { number: 59, udTime: 1500000900 }; - const HEAD = { number: 60, medianTime: 1500000899 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - indexer.prepareDividend(HEAD, HEAD_1, conf); + }) + + it('block with medianTime < udTime has no dividend', async () => { + const conf = { dt: 100 } as any + const HEAD_1 = { number: 59, udTime: 1500000900 } as any + const HEAD = { number: 60, medianTime: 1500000899 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + Indexer.prepareDividend(HEAD, HEAD_1, conf); HEAD.udTime.should.equal(HEAD_1.udTime); should.equal(HEAD.dividend, null); - })); - - it('block with medianTime == udTime', () => co(function*(){ - const conf = { dt: 100, dtReeval: 100, c: 0.0488 }; - const HEAD_1 = { number: 59, udTime: 1500000900, udReevalTime: 1500000900, dividend: 100, mass: 18000, massReeval: 18000, unitBase: 1 }; - const HEAD = { number: 60, medianTime: 1500000900, membersCount: 3 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - indexer.prepareDividend(HEAD, HEAD_1, conf); + }) + + it('block with medianTime == udTime', async () => { + const conf = { dt: 100, dtReeval: 100, c: 0.0488 } as any + const HEAD_1 = { number: 59, udTime: 1500000900, udReevalTime: 1500000900, dividend: 100, mass: 18000, massReeval: 18000, unitBase: 1 } as any + const HEAD = { number: 60, medianTime: 1500000900, membersCount: 3 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + Indexer.prepareDividend(HEAD, HEAD_1, conf); HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); should.equal(HEAD.dividend, 102); - })); - - it('block with medianTime > udTime', () => co(function*(){ - const conf = { dt: 100, dtReeval: 100, c: 0.0488 }; - const HEAD_1 = { number: 59, udTime: 1500000900, udReevalTime: 1500000900, dividend: 100, mass: 18000, massReeval: 18000, unitBase: 1 }; - const HEAD = { number: 60, medianTime: 1500000901, membersCount: 3 }; - indexer.prepareUDTime(HEAD, HEAD_1, conf); - indexer.prepareDividend(HEAD, HEAD_1, conf); + }) + + it('block with medianTime > udTime', async () => { + const conf = { dt: 100, dtReeval: 100, c: 0.0488 } as any + const HEAD_1 = { number: 59, udTime: 1500000900, udReevalTime: 1500000900, dividend: 100, mass: 18000, massReeval: 18000, unitBase: 1 } as any + const HEAD = { number: 60, medianTime: 1500000901, membersCount: 3 } as any + Indexer.prepareUDTime(HEAD, HEAD_1, conf); + Indexer.prepareDividend(HEAD, HEAD_1, conf); HEAD.udTime.should.equal(HEAD_1.udTime + conf.dt); should.equal(HEAD.dividend, 102); - })); + }) -}); +}) diff --git a/test/fast/protocol/protocol-brg49-version.ts b/test/fast/protocol/protocol-brg49-version.ts new file mode 100644 index 000000000..44b0af7be --- /dev/null +++ b/test/fast/protocol/protocol-brg49-version.ts @@ -0,0 +1,46 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Indexer} from "../../../app/lib/indexer" + +const should = require('should'); + +const FAIL = false; +const SUCCESS = true; + +describe("Protocol BR_G49 - Version", function(){ + + it('V13 following V12 should fail', async () => { + const HEAD_1 = { number: 17, version: 13 } as any + const HEAD = { number: 18, version: 12 } as any + Indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); + }) + + it('V14 following V12 should fail', async () => { + const HEAD_1 = { number: 17, version: 14 } as any + const HEAD = { number: 18, version: 12 } as any + Indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); + }) + + it('V13 following V14 should succeed', async () => { + const HEAD_1 = { number: 17, version: 13 } as any + const HEAD = { number: 18, version: 14 } as any + Indexer.ruleVersion(HEAD, HEAD_1).should.equal(SUCCESS); + }) + + it('V13 following V15 should fail', async () => { + const HEAD_1 = { number: 17, version: 13 } as any + const HEAD = { number: 18, version: 15 } as any + Indexer.ruleVersion(HEAD, HEAD_1).should.equal(FAIL); + }) +}) diff --git a/test/fast/protocol/protocol-brg50-blocksize.ts b/test/fast/protocol/protocol-brg50-blocksize.ts new file mode 100644 index 000000000..3cdc44b5c --- /dev/null +++ b/test/fast/protocol/protocol-brg50-blocksize.ts @@ -0,0 +1,67 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Indexer} from "../../../app/lib/indexer" + +const should = require('should'); + +const FAIL = false; +const SUCCESS = true; + +describe("Protocol BR_G50 - Block size", function(){ + + it('2 for an AVG(10) should succeed', async () => { + const HEAD = { number: 24, bsize: 2, avgBlockSize: 10 } as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) + + it('400 for an AVG(10) should succeed', async () => { + const HEAD = { number: 24, bsize: 400, avgBlockSize: 10 } as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) + + it('499 for an AVG(10) should succeed', async () => { + const HEAD = { number: 24, bsize: 499, avgBlockSize: 10 } as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) + + it('500 for an AVG(10) should fail', async () => { + const HEAD = { number: 24, bsize: 500, avgBlockSize: 10 } as any + Indexer.ruleBlockSize(HEAD).should.equal(FAIL); + }) + + it('500 for an AVG(454) should fail', async () => { + const HEAD = { number: 24, bsize: 500, avgBlockSize: 454} as any + Indexer.ruleBlockSize(HEAD).should.equal(FAIL); + }) + + it('500 for an AVG(455) should succeed', async () => { + const HEAD = { number: 24, bsize: 500, avgBlockSize: 455} as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) + + it('1100 for an AVG(1000) should fail', async () => { + const HEAD = { number: 24, bsize: 1100, avgBlockSize: 1000} as any + Indexer.ruleBlockSize(HEAD).should.equal(FAIL); + }) + + it('1100 for an AVG(1001) should succeed', async () => { + const HEAD = { number: 24, bsize: 1100, avgBlockSize: 1001} as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) + + it('1100 for block#0 should succeed', async () => { + const HEAD = { number: 0, bsize: 1100, avgBlockSize: 0} as any + Indexer.ruleBlockSize(HEAD).should.equal(SUCCESS); + }) +}); diff --git a/test/fast/protocol/protocol-brg51-number.ts b/test/fast/protocol/protocol-brg51-number.ts new file mode 100644 index 000000000..5b55b44c6 --- /dev/null +++ b/test/fast/protocol/protocol-brg51-number.ts @@ -0,0 +1,79 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Indexer} from "../../../app/lib/indexer" + +const should = require('should'); + +const FAIL = false; +const SUCCESS = true; + +describe("Protocol BR_G51 - Number", function(){ + + it('1 following 1 should fail', async () => { + const block = { number: 1 } as any + const HEAD_1 = { number: 1 } as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(FAIL); + }) + + it('1 following 0 should succeed', async () => { + const block = { number: 1 } as any + const HEAD_1 = { number: 0 } as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); + }) + + it('0 following 0 should fail', async () => { + const block = { number: 0 } as any + const HEAD_1 = { number: 0 } as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(FAIL); + }) + + it('0 following nothing should succeed', async () => { + const block = { number: 0 } as any + const HEAD_1 = null as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); + }) + + it('4 following nothing should fail', async () => { + const block = { number: 4 } as any + const HEAD_1 = null as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(FAIL); + }) + + it('4 following 2 should fail', async () => { + const block = { number: 4 } as any + const HEAD_1 = { number: 2 } as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(FAIL); + }) + + it('4 following 3 should succeed', async () => { + const block = { number: 4 } as any + const HEAD_1 = { number: 3 } as any + const HEAD = {} as any + Indexer.prepareNumber(HEAD, HEAD_1); + Indexer.ruleNumber(block, HEAD).should.equal(SUCCESS); + }) + +}) diff --git a/test/fast/prover/pow-1-cluster.ts b/test/fast/prover/prover-pow-1-cluster.ts similarity index 92% rename from test/fast/prover/pow-1-cluster.ts rename to test/fast/prover/prover-pow-1-cluster.ts index 928e7243c..da63563cc 100644 --- a/test/fast/prover/pow-1-cluster.ts +++ b/test/fast/prover/prover-pow-1-cluster.ts @@ -13,7 +13,6 @@ import {Master} from "../../../app/modules/prover/lib/powCluster" -const co = require('co') require('should') const logger = require('../../../app/lib/logger').NewLogger() @@ -33,9 +32,9 @@ describe('PoW Cluster', () => { master.nbWorkers.should.equal(0) }) - it('should answer for a basic PoW in more than 50ms (cold)', () => co(function*(){ + it('should answer for a basic PoW in more than 50ms (cold)', async () => { const start = Date.now() - yield master.proveByWorkers({ + await master.proveByWorkers({ newPoW: { block: { number: 0 @@ -57,15 +56,15 @@ describe('PoW Cluster', () => { }) const delay = Date.now() - start delay.should.be.above(50) - })) + }) it('should have an non-empty cluster after a PoW was asked', () => { master.nbWorkers.should.above(0) }) - it('should answer within 50ms for a basic PoW (warm)', () => co(function*(){ + it('should answer within 50ms for a basic PoW (warm)', async () => { const start = Date.now() - yield master.proveByWorkers({ + await master.proveByWorkers({ newPoW: { block: { number: 0 @@ -87,7 +86,7 @@ describe('PoW Cluster', () => { }) const delay = Date.now() - start delay.should.be.below(50) - })) + }) it('should be able to stop all the cores on cancel', async () => { master.proveByWorkers({ diff --git a/test/fast/prover/pow-2-engine.js b/test/fast/prover/prover-pow-2-engine.ts similarity index 75% rename from test/fast/prover/pow-2-engine.js rename to test/fast/prover/prover-pow-2-engine.ts index 9f3e0aefe..403f822ef 100644 --- a/test/fast/prover/pow-2-engine.js +++ b/test/fast/prover/prover-pow-2-engine.ts @@ -11,23 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {PowEngine} from "../../../app/modules/prover/lib/engine" +import {NewLogger} from "../../../app/lib/logger" -const co = require('co'); const should = require('should'); -const PowEngine = require('../../../app/modules/prover/lib/engine').PowEngine -const logger = require('../../../app/lib/logger').NewLogger() +const logger = NewLogger() describe('PoW Engine', () => { - it('should be configurable', () => co(function*(){ - const e1 = new PowEngine({ nbCores: 1 }, logger); - (yield e1.setConf({ cpu: 0.2, prefix: '34' })).should.deepEqual({ cpu: 0.2, prefix: '34' }); - yield e1.shutDown() - })); + it('should be configurable', async () => { + const e1 = new PowEngine({ nbCores: 1 } as any, logger); + (await e1.setConf({ cpu: 0.2, prefix: '34' })).should.deepEqual({ cpu: 0.2, prefix: '34' }); + await e1.shutDown() + }) - it('should be able to make a proof', () => co(function*(){ - const e1 = new PowEngine({ nbCores: 1 }, logger); + it('should be able to make a proof', async () => { + const e1 = new PowEngine({ nbCores: 1 } as any, logger); const block = { number: 35 }; const zeros = 2; const highMark = 'A'; @@ -38,7 +37,7 @@ describe('PoW Engine', () => { const forcedTime = 1; const medianTimeBlocks = 20; const avgGenTime = 5 * 60; - const proof = yield e1.prove({ + const proof = await e1.prove({ newPoW: { block, zeros, @@ -66,12 +65,12 @@ describe('PoW Engine', () => { pow: '009A52E6E2E4EA7DE950A2DA673114FA55B070EBE350D75FF0C62C6AAE9A37E5' } }); - yield e1.shutDown() - })); + await e1.shutDown() + }) - it('should be able to stop a proof', () => co(function*(){ - const e1 = new PowEngine({ nbCores: 1 }, logger); - yield e1.forceInit() + it('should be able to stop a proof', async () => { + const e1 = new PowEngine({ nbCores: 1 } as any, logger); + await e1.forceInit() const block = { number: 26 }; const zeros = 10; // Requires hundreds of thousands of tries probably const highMark = 'A'; @@ -96,10 +95,10 @@ describe('PoW Engine', () => { } } ) - yield new Promise((res) => setTimeout(res, 10)) - yield e1.cancel() - // const proof = yield proofPromise; + await new Promise((res) => setTimeout(res, 10)) + await e1.cancel() + // const proof = await proofPromise; // should.not.exist(proof); - yield e1.shutDown() - })); -}); + await e1.shutDown() + }) +}) diff --git a/test/fast/prover/pow-3-prover.js b/test/fast/prover/prover-pow-3-prover.ts similarity index 100% rename from test/fast/prover/pow-3-prover.js rename to test/fast/prover/prover-pow-3-prover.ts diff --git a/test/integration/blocks/community-collapse.ts b/test/integration/block-generation/community-collapse.ts similarity index 92% rename from test/integration/blocks/community-collapse.ts rename to test/integration/block-generation/community-collapse.ts index cb376d803..6c9620538 100644 --- a/test/integration/blocks/community-collapse.ts +++ b/test/integration/block-generation/community-collapse.ts @@ -15,9 +15,9 @@ import {TestUser} from "../tools/TestUser" import {NewTestingServer, TestingServer} from "../tools/toolbox" import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectJSON} from "../tools/http-expect" -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); const rp = require('request-promise'); const MEMORY_MODE = true; @@ -73,7 +73,7 @@ describe("Community collapse", function() { }) it('should be handled', function() { - return httpTest.expectJSON(rp('http://127.0.0.1:9340/blockchain/block/2', { json: true }), { + return expectJSON(rp('http://127.0.0.1:9340/blockchain/block/2', { json: true }), { number: 2 }); }); diff --git a/test/integration/newcomers-shuffling.js b/test/integration/block-generation/newcomers-shuffling.ts similarity index 68% rename from test/integration/newcomers-shuffling.js rename to test/integration/block-generation/newcomers-shuffling.ts index 0a4438d02..3a62ef2b5 100644 --- a/test/integration/newcomers-shuffling.js +++ b/test/integration/block-generation/newcomers-shuffling.ts @@ -11,21 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" -const co = require('co'); -const assert = require('assert'); -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); +const assert = require('assert'); -let s1, cat, tac, toc, tic +let s1:TestingServer, cat:TestUser, tac:TestUser, toc:TestUser, tic:TestUser -describe("Newcomers shuffling", function() { +/** + * Thist test is a bit useless as is, because we don't check the fact that the newcomers enter in a random manner. + */ - before(() => co(function*() { +describe("Newcomers shuffling", function() { - s1 = toolbox.server({ + before(async () => { + + s1 = NewTestingServer({ pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' @@ -37,17 +38,17 @@ describe("Newcomers shuffling", function() { toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); tic = new TestUser('tic', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, { server: s1 }); - yield s1.prepareForNetwork(); + await s1.prepareForNetwork(); // Publishing identities - yield cat.createIdentity(); - yield tac.createIdentity(); - yield cat.cert(tac); - yield tac.cert(cat); - yield cat.join(); - yield tac.join(); - yield s1.commit() - })); + await cat.createIdentity(); + await tac.createIdentity(); + await cat.cert(tac); + await tac.cert(cat); + await cat.join(); + await tac.join(); + await s1.commit() + }) after(() => { return Promise.all([ @@ -55,16 +56,16 @@ describe("Newcomers shuffling", function() { ]) }) - it('toc and tic could join ', () => co(function*() { - yield toc.createIdentity(); - yield tic.createIdentity(); - yield toc.join(); - yield tic.join(); + it('toc and tic could join ', async () => { + await toc.createIdentity(); + await tic.createIdentity(); + await toc.join(); + await tic.join(); // same certifier for toc and tic - yield cat.cert(toc) - yield cat.cert(tic) + await cat.cert(toc) + await cat.cert(tic) // We do not known which one of toc or tic will be the first in! - yield s1.commit() - yield s1.commit() - })); -}); + await s1.commit() + await s1.commit() + }) +}) diff --git a/test/integration/blocks/start-generate-blocks.ts b/test/integration/block-generation/start-generate-blocks.ts similarity index 95% rename from test/integration/blocks/start-generate-blocks.ts rename to test/integration/block-generation/start-generate-blocks.ts index 583e9c972..04c52d83b 100644 --- a/test/integration/blocks/start-generate-blocks.ts +++ b/test/integration/block-generation/start-generate-blocks.ts @@ -19,14 +19,12 @@ import {NewTestingServer, serverWaitBlock, TestingServer} from "../tools/toolbox import {TestUser} from "../tools/TestUser" import {RouterDependency} from "../../../app/modules/router" import {ProverDependency} from "../../../app/modules/prover/index" +import {until} from "../tools/test-until" +import {sync} from "../tools/test-sync" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectJSON} from "../tools/http-expect" const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const until = require('../tools/until'); -const sync = require('../tools/sync'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectJSON = httpTest.expectJSON; const MEMORY_MODE = true; const commonConf = { @@ -100,7 +98,7 @@ describe("Generation", function() { await toc.join(); await s1.commit(); // Server 2 syncs block 0 - await sync(0, 0, s1, s2); + await sync(0, 0, s1._server, s2._server); // Let each node know each other let peer1 = await nodeS1.getPeer(); await nodeS2.postPeer(PeerDTO.fromJSONObject(peer1).getRawSigned()); diff --git a/test/integration/branches/branches2.ts b/test/integration/branches/branches2.ts index 4e12085b1..0654d7e83 100644 --- a/test/integration/branches/branches2.ts +++ b/test/integration/branches/branches2.ts @@ -16,21 +16,14 @@ import {BmaDependency} from "../../../app/modules/bma/index" import {OtherConstants} from "../../../app/lib/other_constants" import {NewLogger} from "../../../app/lib/logger" import {Underscore} from "../../../app/lib/common-libs/underscore" -import {waitForkResolution, waitToHaveBlock} from "../tools/toolbox" +import {NewTestingServer, TestingServer, waitForkResolution, waitToHaveBlock} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {CrawlerDependency} from "../../../app/modules/crawler/index" +import {sync} from "../tools/test-sync" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectHttpCode, expectJSON} from "../tools/http-expect" -const co = require('co'); -const duniter = require('../../../index'); -const bma = BmaDependency.duniter.methods.bma; const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const commit = require('../tools/commit'); -const sync = require('../tools/sync'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectJSON = httpTest.expectJSON; -const expectHttpCode = httpTest.expectHttpCode; if (OtherConstants.MUTE_LOGS_DURING_UNIT_TESTS) { NewLogger().mute(); @@ -53,18 +46,18 @@ const commonConf = { sigQty: 1 }; -let s1:any, s2:any, cat, toc +let s1:TestingServer, s2:TestingServer, cat:TestUser, toc:TestUser const now = Math.round(new Date().getTime() / 1000); describe("SelfFork", function() { - before(() => co(function *() { + before(async () => { - s1 = duniter( - '/bb4', - MEMORY_MODE, + s1 = NewTestingServer( Underscore.extend({ + name: 'bb4', + memory: MEMORY_MODE, port: '7781', pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', @@ -72,10 +65,10 @@ describe("SelfFork", function() { } }, commonConf)); - s2 = duniter( - '/bb5', - MEMORY_MODE, + s2 = NewTestingServer( Underscore.extend({ + name: 'bb5', + memory: MEMORY_MODE, port: '7782', pair: { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', @@ -86,51 +79,46 @@ describe("SelfFork", function() { cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); - const commitS1 = commit(s1); - const commitS2 = commit(s2, { - time: now + 37180 - }); - - yield s1.initWithDAL().then(bma).then((bmapi:any) => bmapi.openConnections()); - yield s2.initWithDAL().then(bma).then((bmapi:any) => bmapi.openConnections()); - s1.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s1.conf)) - s2.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s2.conf)) + await s1.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi:any) => bmapi.openConnections()); + await s2.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi:any) => bmapi.openConnections()); + s1._server.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s1.conf)) + s2._server.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s2.conf)) // Server 1 - yield cat.createIdentity(); - yield toc.createIdentity(); - yield toc.cert(cat); - yield cat.cert(toc); - yield cat.join(); - yield toc.join(); - - yield commitS1({ + await cat.createIdentity(); + await toc.createIdentity(); + await toc.cert(cat); + await cat.cert(toc); + await cat.join(); + await toc.join(); + + await s1.commit({ time: now }); - yield commitS1(); - yield commitS1(); - yield commitS1(); + await s1.commit(); + await s1.commit(); + await s1.commit(); // Server 2 - yield sync(0, 2, s1, s2); - yield waitToHaveBlock(s2, 2) - let s2p = yield s2.PeeringService.peer(); - - yield commitS2(); // <-- block#3 is a fork block, S2 is committing another one than S1 issued - yield commitS2(); - yield commitS2(); - yield commitS2(); - yield commitS2(); - yield commitS2(); - yield commitS2(); - - yield s1.writePeer(s2p); + await sync(0, 2, s1._server, s2._server); + await waitToHaveBlock(s2._server, 2) + let s2p = await s2.PeeringService.peer(); + + await s2.commit({ time: now + 37180 }); // <-- block#3 is a fork block, S2 is committing another one than S1 issued + await s2.commit({ time: now + 37180 }); + await s2.commit({ time: now + 37180 }); + await s2.commit({ time: now + 37180 }); + await s2.commit({ time: now + 37180 }); + await s2.commit({ time: now + 37180 }); + await s2.commit({ time: now + 37180 }); + + await s1.writePeer(s2p); // Forking S1 from S2 - yield Promise.all([ - waitForkResolution(s1, 9), - CrawlerDependency.duniter.methods.pullBlocks(s1, s2p.pubkey) + await Promise.all([ + waitForkResolution(s1._server, 9), + CrawlerDependency.duniter.methods.pullBlocks(s1._server, s2p.pubkey) ]) - })); + }) after(() => { return Promise.all([ @@ -253,9 +241,9 @@ describe("SelfFork", function() { }); }); - it('should have 1 branch', () => co(function*() { - const branches = yield s2.BlockchainService.branches(); + it('should have 1 branch', async () => { + const branches = await s2.BlockchainService.branches(); branches.should.have.length(1); - })); - }); -}); + }) + }) +}) diff --git a/test/integration/branches/branches_pending_data.ts b/test/integration/branches/branches_pending_data.ts index 1b8930d8e..ca29812f5 100644 --- a/test/integration/branches/branches_pending_data.ts +++ b/test/integration/branches/branches_pending_data.ts @@ -15,13 +15,10 @@ import {Underscore} from "../../../app/lib/common-libs/underscore" import {NewTestingServer, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer, expectJSON} from "../tools/http-expect" const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectJSON = httpTest.expectJSON; -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; const commonConf = { diff --git a/test/integration/branches/branches_revert2.ts b/test/integration/branches/branches_revert2.ts index 9eb046e4f..67dc35b6f 100644 --- a/test/integration/branches/branches_revert2.ts +++ b/test/integration/branches/branches_revert2.ts @@ -11,25 +11,19 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {TestingServer} from "../tools/toolbox" +import {NewTestingServer, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" import {ProverConstants} from "../../../app/modules/prover/lib/constants" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer, expectHttpCode, expectJSON} from "../tools/http-expect" -const duniter = require('../../../index'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const commit = require('../tools/commit'); -const shutDownEngine = require('../tools/shutDownEngine'); ProverConstants.CORES_MAXIMUM_USE_IN_PARALLEL = 1 BmaDependency.duniter.methods.noLimit(); // Disables the HTTP limiter -const expectJSON = httpTest.expectJSON; -const expectHttpCode = httpTest.expectHttpCode; -const expectAnswer = httpTest.expectAnswer; - const now = 1490000000; const MEMORY_MODE = true; @@ -48,10 +42,10 @@ describe("Revert two blocks", function() { before(async () => { - s1 = duniter( - '/bb11', - MEMORY_MODE, + s1 = NewTestingServer( Underscore.extend({ + name: 'bb11', + memory: MEMORY_MODE, port: '7712', pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', @@ -73,11 +67,11 @@ describe("Revert two blocks", function() { await cat.cert(toc); await cat.join(); await toc.join(); - await commit(s1)({ time: now }); - await commit(s1)({ time: now + 1 }); - await commit(s1)({ time: now + 1 }); + await s1.commit({ time: now }); + await s1.commit({ time: now + 1 }); + await s1.commit({ time: now + 1 }); await cat.sendP(51, toc); - await commit(s1)({ time: now + 1 }); + await s1.commit({ time: now + 1 }); }); after(() => { @@ -197,7 +191,7 @@ describe("Revert two blocks", function() { await s1.dal.txsDAL.removeAll() await cat.sendP(19, toc); await s1.dal.blockDAL.removeBlock('DELETE FROM block WHERE fork AND number = 3') - await commit(s1)({ time: now + 1 }); + await s1.commit({ time: now + 1 }); }) it('/block/0 should exist', function() { diff --git a/test/integration/branches/branches_switch.ts b/test/integration/branches/branches_switch.ts index b3ebebc49..94786b98c 100644 --- a/test/integration/branches/branches_switch.ts +++ b/test/integration/branches/branches_switch.ts @@ -14,19 +14,14 @@ import {Underscore} from "../../../app/lib/common-libs/underscore" import {BmaDependency} from "../../../app/modules/bma/index" import {CrawlerDependency} from "../../../app/modules/crawler/index" +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {sync} from "../tools/test-sync" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectJSON} from "../tools/http-expect" -const co = require('co'); -const duniter = require('../../../index'); -const bma = require('../../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('../tools/TestUser').TestUser const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const commit = require('../tools/commit'); -const sync = require('../tools/sync'); const cluster = require('cluster') -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectJSON = httpTest.expectJSON; const MEMORY_MODE = true; const commonConf = { @@ -38,18 +33,18 @@ const commonConf = { sigQty: 1 }; -let s1:any, s2:any, cat, toc +let s1:TestingServer, s2:TestingServer, cat:TestUser, toc:TestUser describe("Switch", function() { - before(() => co(function *() { + before(async () => { cluster.setMaxListeners(6) - s1 = duniter( - '/bb11', - MEMORY_MODE, + s1 = NewTestingServer( Underscore.extend({ + name: 'bb11', + memory: MEMORY_MODE, switchOnHeadAdvance: 0, port: '7788', pair: { @@ -60,10 +55,10 @@ describe("Switch", function() { sigQty: 1, dt: 1, ud0: 120 }, commonConf)); - s2 = duniter( - '/bb12', - MEMORY_MODE, + s2 = NewTestingServer( Underscore.extend({ + name: 'bb12', + memory: MEMORY_MODE, switchOnHeadAdvance: 0, port: '7789', pair: { @@ -75,41 +70,41 @@ describe("Switch", function() { cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); - yield s1.initWithDAL().then(bma).then((bmapi:any) => bmapi.openConnections()); - yield s2.initWithDAL().then(bma).then((bmapi:any) => bmapi.openConnections()); - s1.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s1.conf)) - s2.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s2.conf)) - yield cat.createIdentity(); - yield toc.createIdentity(); - yield toc.cert(cat); - yield cat.cert(toc); - yield cat.join(); - yield toc.join(); - yield commit(s1)(); - yield commit(s1)(); - yield commit(s1)(); - yield sync(0, 2, s1, s2); - - let s2p = yield s2.PeeringService.peer(); - - yield commit(s1)(); - yield commit(s1)(); - yield commit(s2)(); - yield commit(s2)(); - yield commit(s2)(); - yield commit(s2)(); - yield commit(s2)(); - yield commit(s2)(); - yield commit(s2)(); + await s1.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi:any) => bmapi.openConnections()); + await s2.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi:any) => bmapi.openConnections()); + s1._server.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s1.conf)) + s2._server.addEndpointsDefinitions(() => BmaDependency.duniter.methods.getMainEndpoint(s2.conf)) + await cat.createIdentity(); + await toc.createIdentity(); + await toc.cert(cat); + await cat.cert(toc); + await cat.join(); + await toc.join(); + await s1.commit(); + await s1.commit(); + await s1.commit(); + await sync(0, 2, s1._server, s2._server); + + let s2p = await s2.PeeringService.peer(); + + await s1.commit(); + await s1.commit(); + await s2.commit(); + await s2.commit(); + await s2.commit(); + await s2.commit(); + await s2.commit(); + await s2.commit(); + await s2.commit(); // So we now have: // S1 01234 // S2 `3456789 - yield s1.writePeer(s2p) + await s1.writePeer(s2p) // Forking S1 from S2 - yield CrawlerDependency.duniter.methods.pullBlocks(s1, s2p.pubkey); + await CrawlerDependency.duniter.methods.pullBlocks(s1._server, s2p.pubkey); // S1 should have switched to the other branch - })); + }) after(() => { cluster.setMaxListeners(3) diff --git a/test/integration/certification/certification_chainability.ts b/test/integration/certification/certification_chainability.ts index ca4955b04..d232c9d13 100644 --- a/test/integration/certification/certification_chainability.ts +++ b/test/integration/certification/certification_chainability.ts @@ -16,13 +16,11 @@ import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" import {NewTestingServer, TestingServer} from "../tools/toolbox" import {HttpBlock} from "../../../app/modules/bma/lib/dtos" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" const should = require('should'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; const commonConf = { diff --git a/test/integration/register-fork-blocks.js b/test/integration/fork-resolution/register-fork-blocks.ts similarity index 59% rename from test/integration/register-fork-blocks.js rename to test/integration/fork-resolution/register-fork-blocks.ts index 7e7d5d753..d976ad2cc 100644 --- a/test/integration/register-fork-blocks.js +++ b/test/integration/fork-resolution/register-fork-blocks.ts @@ -11,25 +11,24 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {CommonConstants} from "../../../app/lib/common-libs/constants" +import {BlockDTO} from "../../../app/lib/dto/BlockDTO" +import {HttpBranches} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const assert = require('assert'); -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); -const CommonConstants = require('../../app/lib/common-libs/constants').CommonConstants const now = 1500000000 const forksize = 10 -let s1, s2, s3, cat1, tac1, toc1 +let s1:TestingServer, s2:TestingServer, s3:TestingServer, cat1:TestUser, tac1:TestUser, toc1:TestUser describe("Fork blocks", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ // The common conf nbCores:1, @@ -45,7 +44,7 @@ describe("Fork blocks", function() { } }); - s2 = toolbox.server({ + s2 = NewTestingServer({ // Particular conf nbCores:1, @@ -58,7 +57,7 @@ describe("Fork blocks", function() { } }); - s3 = toolbox.server({ + s3 = NewTestingServer({ // Particular conf nbCores:1, @@ -75,21 +74,21 @@ describe("Fork blocks", function() { tac1 = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); toc1 = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); - yield s1.prepareForNetwork(); - yield s2.prepareForNetwork(); - yield s3.prepareForNetwork(); + await s1.prepareForNetwork(); + await s2.prepareForNetwork(); + await s3.prepareForNetwork(); // Publishing identities - yield cat1.createIdentity(); - yield tac1.createIdentity(); - yield toc1.createIdentity(); - yield cat1.cert(tac1); - yield tac1.cert(cat1); - yield tac1.cert(toc1); - yield cat1.join(); - yield tac1.join(); - yield toc1.join(); - })); + await cat1.createIdentity(); + await tac1.createIdentity(); + await toc1.createIdentity(); + await cat1.cert(tac1); + await tac1.cert(cat1); + await tac1.cert(toc1); + await cat1.join(); + await tac1.join(); + await toc1.join(); + }) after(() => { return Promise.all([ @@ -99,85 +98,85 @@ describe("Fork blocks", function() { ]) }) - it('should create a common blockchain', () => co(function*() { - const b0 = yield s1.commit({ time: now }) - const b1 = yield s1.commit({ time: now + 11 }) - const b2 = yield s1.commit({ time: now + 22 }) - yield s2.writeBlock(b0) - yield s2.writeBlock(b1) - yield s2.writeBlock(b2) - yield s3.writeBlock(b0) - yield s3.writeBlock(b1) - yield s3.writeBlock(b2) - yield s2.waitToHaveBlock(2) - yield s3.waitToHaveBlock(2) - })) - - it('should exist the same block on each node', () => co(function*() { - yield s1.expectJSON('/blockchain/current', { + it('should create a common blockchain', async () => { + const b0 = await s1.commit({ time: now }) + const b1 = await s1.commit({ time: now + 11 }) + const b2 = await s1.commit({ time: now + 22 }) + await s2.writeBlock(b0) + await s2.writeBlock(b1) + await s2.writeBlock(b2) + await s3.writeBlock(b0) + await s3.writeBlock(b1) + await s3.writeBlock(b2) + await s2.waitToHaveBlock(2) + await s3.waitToHaveBlock(2) + }) + + it('should exist the same block on each node', async () => { + await s1.expectJSON('/blockchain/current', { number: 2 }) - yield s2.expectJSON('/blockchain/current', { + await s2.expectJSON('/blockchain/current', { number: 2 }) - })) - - it('should be able to fork, and notify each node', () => co(function*() { - const b3a = yield s1.commit({ time: now + 33 }) - const b3b = yield s2.commit({ time: now + 33 }) - yield s1.writeBlock(b3b) - yield s2.writeBlock(b3a) - yield s1.waitToHaveBlock(3) - yield s2.waitToHaveBlock(3) - })) - - it('should exist a different third block on each node', () => co(function*() { - yield s1.expectJSON('/blockchain/current', { + }) + + it('should be able to fork, and notify each node', async () => { + const b3a = await s1.commit({ time: now + 33 }) + const b3b = await s2.commit({ time: now + 33 }) + await s1.writeBlock(b3b) + await s2.writeBlock(b3a) + await s1.waitToHaveBlock(3) + await s2.waitToHaveBlock(3) + }) + + it('should exist a different third block on each node', async () => { + await s1.expectJSON('/blockchain/current', { number: 3, hash: "74AB356F0E6CD9AA6F752E58FFCD65D5F8C95CDAA93576A40457CC3598C4E3D1" }) - yield s2.expectJSON('/blockchain/current', { + await s2.expectJSON('/blockchain/current', { number: 3, hash: "2C3555F4009461C81F7209EAAD7DA831D8451708D06BB1173CCB40746CD0641B" }) - })) + }) - it('should exist both branches on each node', () => co(function*() { - yield s1.expect('/blockchain/branches', (res) => { + it('should exist both branches on each node', async () => { + await s1.expect('/blockchain/branches', (res:HttpBranches) => { assert.equal(res.blocks.length, 2) assert.equal(res.blocks[0].number, 3) assert.equal(res.blocks[0].hash, '2C3555F4009461C81F7209EAAD7DA831D8451708D06BB1173CCB40746CD0641B') assert.equal(res.blocks[1].number, 3) assert.equal(res.blocks[1].hash, '74AB356F0E6CD9AA6F752E58FFCD65D5F8C95CDAA93576A40457CC3598C4E3D1') }) - yield s2.expect('/blockchain/branches', (res) => { + await s2.expect('/blockchain/branches', (res:HttpBranches) => { assert.equal(res.blocks.length, 2) assert.equal(res.blocks[0].number, 3) assert.equal(res.blocks[0].hash, '74AB356F0E6CD9AA6F752E58FFCD65D5F8C95CDAA93576A40457CC3598C4E3D1') assert.equal(res.blocks[1].number, 3) assert.equal(res.blocks[1].hash, '2C3555F4009461C81F7209EAAD7DA831D8451708D06BB1173CCB40746CD0641B') }) - })) - - let b4a, b5a, b6a, b7a, b8a - - it('should be able to grow S1\'s blockchain', () => co(function*() { - b4a = yield s1.commit({time: now + 44}) - b5a = yield s1.commit({time: now + 55}) - b6a = yield s1.commit({time: now + 66}) - b7a = yield s1.commit({time: now + 77}) - b8a = yield s1.commit({time: now + 88}) - yield s1.waitToHaveBlock(8) - })) - - it('should refuse known fork blocks', () => co(function*() { - yield s1.sharePeeringWith(s2) - yield s2.sharePeeringWith(s1) - yield s2.writeBlock(b4a) - const b3c = yield s3.commit({ time: now + 33 }) - yield new Promise((res, rej) => { + }) + + let b4a:BlockDTO, b5a:BlockDTO, b6a:BlockDTO, b7a:BlockDTO, b8a:BlockDTO + + it('should be able to grow S1\'s blockchain', async () => { + b4a = (await s1.commit({time: now + 44})) as BlockDTO + b5a = (await s1.commit({time: now + 55})) as BlockDTO + b6a = (await s1.commit({time: now + 66})) as BlockDTO + b7a = (await s1.commit({time: now + 77})) as BlockDTO + b8a = (await s1.commit({time: now + 88})) as BlockDTO + await s1.waitToHaveBlock(8) + }) + + it('should refuse known fork blocks', async () => { + await s1.sharePeeringWith(s2) + await s2.sharePeeringWith(s1) + await s2.writeBlock(b4a) + const b3c = await s3.commit({ time: now + 33 }) + await new Promise((res, rej) => { const event = CommonConstants.DocumentError - s2.on(event, (e) => { + s2.on(event, (e:any) => { try { assert.equal(e, 'Block already known') res() @@ -188,32 +187,32 @@ describe("Fork blocks", function() { // Trigger the third-party fork block writing s2.writeBlock(b3c) }) - })) - - it('should be able to make one fork grow enough to make one node switch', () => co(function*() { - yield s2.writeBlock(b5a) - yield s2.writeBlock(b6a) - yield s2.writeBlock(b7a) - yield s2.writeBlock(b8a) - yield Promise.all([ + }) + + it('should be able to make one fork grow enough to make one node switch', async () => { + await s2.writeBlock(b5a) + await s2.writeBlock(b6a) + await s2.writeBlock(b7a) + await s2.writeBlock(b8a) + await Promise.all([ s2.waitToHaveBlock(8), s2.waitForkResolution(8) ]) - })) + }) - it('should exist a same current block on each node', () => co(function*() { - yield s1.expectJSON('/blockchain/current', { + it('should exist a same current block on each node', async () => { + await s1.expectJSON('/blockchain/current', { number: 8, hash: "B8D2AA2A5556F7A2837FB4B881FCF50595F855D0BF8F71C0B432E27216BBA40B" }) - yield s2.expectJSON('/blockchain/current', { + await s2.expectJSON('/blockchain/current', { number: 8, hash: "B8D2AA2A5556F7A2837FB4B881FCF50595F855D0BF8F71C0B432E27216BBA40B" }) - })) + }) - it('should exist 2 branches on each node', () => co(function*() { - yield s1.expect('/blockchain/branches', (res) => { + it('should exist 2 branches on each node', async () => { + await s1.expect('/blockchain/branches', (res:HttpBranches) => { assert.equal(res.blocks.length, 3) assert.equal(res.blocks[0].number, 3) assert.equal(res.blocks[0].hash, '2C3555F4009461C81F7209EAAD7DA831D8451708D06BB1173CCB40746CD0641B') // This is s2 fork! @@ -222,7 +221,7 @@ describe("Fork blocks", function() { assert.equal(res.blocks[2].number, 8) assert.equal(res.blocks[2].hash, 'B8D2AA2A5556F7A2837FB4B881FCF50595F855D0BF8F71C0B432E27216BBA40B') }) - yield s2.expect('/blockchain/branches', (res) => { + await s2.expect('/blockchain/branches', (res:HttpBranches) => { assert.equal(res.blocks.length, 3) assert.equal(res.blocks[0].number, 3) assert.equal(res.blocks[0].hash, '2C3555F4009461C81F7209EAAD7DA831D8451708D06BB1173CCB40746CD0641B') // This is s2 fork! @@ -231,5 +230,5 @@ describe("Fork blocks", function() { assert.equal(res.blocks[2].number, 8) assert.equal(res.blocks[2].hash, 'B8D2AA2A5556F7A2837FB4B881FCF50595F855D0BF8F71C0B432E27216BBA40B') }) - })) -}); + }) +}) diff --git a/test/integration/identity/identity-absorption.ts b/test/integration/identity/identity-absorption.ts index bbaf24fff..4ee1051e0 100644 --- a/test/integration/identity/identity-absorption.ts +++ b/test/integration/identity/identity-absorption.ts @@ -16,13 +16,11 @@ import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" import {shouldFail} from "../../unit-tools" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" const duniter = require('../../../index'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; const commonConf = { diff --git a/test/integration/identity/identity-clean-test.ts b/test/integration/identity/identity-clean-test.ts index f311491a2..2a40b596c 100644 --- a/test/integration/identity/identity-clean-test.ts +++ b/test/integration/identity/identity-clean-test.ts @@ -11,19 +11,15 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {TestingServer} from "../tools/toolbox" +import {NewTestingServer, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpMembers} from "../../../app/modules/bma/lib/dtos" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" -const duniter = require('../../../index'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const commit = require('../tools/commit'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; const commonConf = { @@ -42,10 +38,10 @@ describe("Identities cleaned", function() { before(async () => { - s1 = duniter( - '/bb12', - MEMORY_MODE, + s1 = NewTestingServer( Underscore.extend({ + name: 'bb12', + memory: MEMORY_MODE, port: '7733', pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', @@ -58,8 +54,6 @@ describe("Identities cleaned", function() { toc = new TestUser('cat', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); - const commitS1 = commit(s1); - await s1.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi) => bmapi.openConnections()); await cat.createIdentity(); await tic.createIdentity(); @@ -76,7 +70,7 @@ describe("Identities cleaned", function() { await tic.cert(cat); await cat.join(); await tic.join(); - await commitS1(); + await s1.commit() // We have the following WoT (diameter 1): diff --git a/test/integration/identity/identity-expiry.ts b/test/integration/identity/identity-expiry.ts index 8b6f9a0e8..9085e381a 100644 --- a/test/integration/identity/identity-expiry.ts +++ b/test/integration/identity/identity-expiry.ts @@ -17,14 +17,11 @@ import {TestUser} from "../tools/TestUser" import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpRequirements} from "../../../app/modules/bma/lib/dtos" import {ProverDependency} from "../../../app/modules/prover/index" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer, expectError} from "../tools/http-expect" const should = require('should'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; -const expectError = httpTest.expectError; const MEMORY_MODE = true; const commonConf = { diff --git a/test/integration/identity-implicit-revocation.js b/test/integration/identity/identity-implicit-revocation.ts similarity index 63% rename from test/integration/identity-implicit-revocation.js rename to test/integration/identity/identity-implicit-revocation.ts index d3d98b9f5..728b31c89 100644 --- a/test/integration/identity-implicit-revocation.js +++ b/test/integration/identity/identity-implicit-revocation.ts @@ -11,26 +11,23 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {FullMindexEntry} from "../../../app/lib/indexer" +import {HttpBlock, HttpLookup} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const assert = require('assert'); const should = require('should'); -const duniter = require('../../index'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('./tools/TestUser').TestUser -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); const now = 1480000000; -let s1, cat, tac, tic +let s1:TestingServer, cat:TestUser, tac:TestUser, tic:TestUser describe("Implicit revocation", function() { - before(() => co(function *() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' @@ -45,31 +42,31 @@ describe("Implicit revocation", function() { tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); tic = new TestUser('tic', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, { server: s1 }); - yield s1.initDalBmaConnections(); - yield cat.createIdentity(); - yield tac.createIdentity(); - yield tic.createIdentity(); - yield cat.cert(tac); - yield tac.cert(tic); - yield tic.cert(cat); - yield cat.join(); - yield tac.join(); - yield tic.join(); - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 8 }); - yield s1.commit({ time: now + 9 }); - yield cat.join(); - yield tac.join(); - yield s1.commit({ time: now + 10 }); - yield s1.commit({ time: now + 10 }); - yield s1.commit({ time: now + 11 }); - yield s1.commit({ time: now + 15 }); - yield s1.commit({ time: now + 15 }); - yield cat.join(); - yield tac.join(); - yield s1.commit({ time: now + 20 }); - yield s1.commit({ time: now + 20 }); - })); + await s1.initDalBmaConnections(); + await cat.createIdentity(); + await tac.createIdentity(); + await tic.createIdentity(); + await cat.cert(tac); + await tac.cert(tic); + await tic.cert(cat); + await cat.join(); + await tac.join(); + await tic.join(); + await s1.commit({ time: now }); + await s1.commit({ time: now + 8 }); + await s1.commit({ time: now + 9 }); + await cat.join(); + await tac.join(); + await s1.commit({ time: now + 10 }); + await s1.commit({ time: now + 10 }); + await s1.commit({ time: now + 11 }); + await s1.commit({ time: now + 15 }); + await s1.commit({ time: now + 15 }); + await cat.join(); + await tac.join(); + await s1.commit({ time: now + 20 }); + await s1.commit({ time: now + 20 }); + }) after(() => { return Promise.all([ @@ -77,18 +74,18 @@ describe("Implicit revocation", function() { ]) }) - it('block#4 should have kicked tic', () => s1.expectThat('/blockchain/block/5', (res) => { + it('block#4 should have kicked tic', () => s1.expectThat('/blockchain/block/5', (res:HttpBlock) => { assert.deepEqual(res.excluded, [ 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV' ]); })); - it('should exist implicit revocation traces', () => co(function*() { - const ms = yield s1.dal.mindexDAL.getReducedMS('DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV') + it('should exist implicit revocation traces', async () => { + const ms = (await s1.dal.mindexDAL.getReducedMS('DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV')) as FullMindexEntry ms.should.have.property('revoked_on').equal(1480000020) - })); + }) - it('should answer that tic is revoked on API', () => s1.expectThat('/wot/lookup/tic', (res) => { + it('should answer that tic is revoked on API', () => s1.expectThat('/wot/lookup/tic', (res:HttpLookup) => { res.should.have.property('results').length(1); res.results[0].should.have.property('uids').length(1); res.results[0].uids[0].should.have.property('uid').equal('tic'); diff --git a/test/integration/identity-kicking-by-certs.js b/test/integration/identity/identity-kicking-by-certs.ts similarity index 64% rename from test/integration/identity-kicking-by-certs.js rename to test/integration/identity/identity-kicking-by-certs.ts index c9e2274c2..ecf3f4620 100644 --- a/test/integration/identity-kicking-by-certs.js +++ b/test/integration/identity/identity-kicking-by-certs.ts @@ -11,22 +11,21 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpBlock} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const assert = require('assert'); -const TestUser = require('./tools/TestUser').TestUser -const toolbox = require('./tools/toolbox'); const now = 1480000000; -let s1, cat, tac, tic, toc, tuc +let s1:TestingServer, cat:TestUser, tac:TestUser, tic:TestUser, toc:TestUser, tuc:TestUser describe("Identities kicking by certs", function() { - before(() => co(function *() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' @@ -44,41 +43,41 @@ describe("Identities kicking by certs", function() { toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); tuc = new TestUser('tuc', { pub: '3conGDUXdrTGbQPMQQhEC4Ubu1MCAnFrAYvUaewbUhtk', sec: '5ks7qQ8Fpkin7ycXpxQSxxjVhs8VTzpM3vEBMqM7NfC1ZiFJ93uQryDcoM93Mj77T6hDAABdeHZJDFnkDb35bgiU'}, { server: s1 }); - yield s1.initDalBmaConnections(); - yield cat.createIdentity(); - yield tac.createIdentity(); - yield toc.createIdentity(); - yield cat.cert(tac); - yield cat.cert(toc); - yield tac.cert(cat); - yield tac.cert(toc); - yield toc.cert(cat); - yield toc.cert(tac); - yield cat.join(); - yield tac.join(); - yield toc.join(); - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 3 }); - yield s1.commit({ time: now + 5 }); - yield tic.createIdentity(); - yield cat.cert(tic); - yield tac.cert(tic); - yield tic.join(); - yield tuc.createIdentity(); - yield s1.commit({ time: now + 8 }); - yield tic.cert(cat); - yield cat.cert(tuc); - yield tac.cert(tuc); - yield tuc.join(); - yield s1.commit({ time: now + 8 }); - yield tuc.cert(cat); - yield s1.commit({ time: now + 8 }); - yield s1.commit({ time: now + 8 }); - yield s1.commit({ time: now + 8 }); - yield cat.revoke(); - yield s1.commitWaitError({ time: now + 8, excluded: ['3conGDUXdrTGbQPMQQhEC4Ubu1MCAnFrAYvUaewbUhtk'] }, "ruleToBeKickedArePresent") - yield s1.commit({ time: now + 8 }); - })); + await s1.initDalBmaConnections(); + await cat.createIdentity(); + await tac.createIdentity(); + await toc.createIdentity(); + await cat.cert(tac); + await cat.cert(toc); + await tac.cert(cat); + await tac.cert(toc); + await toc.cert(cat); + await toc.cert(tac); + await cat.join(); + await tac.join(); + await toc.join(); + await s1.commit({ time: now }); + await s1.commit({ time: now + 3 }); + await s1.commit({ time: now + 5 }); + await tic.createIdentity(); + await cat.cert(tic); + await tac.cert(tic); + await tic.join(); + await tuc.createIdentity(); + await s1.commit({ time: now + 8 }); + await tic.cert(cat); + await cat.cert(tuc); + await tac.cert(tuc); + await tuc.join(); + await s1.commit({ time: now + 8 }); + await tuc.cert(cat); + await s1.commit({ time: now + 8 }); + await s1.commit({ time: now + 8 }); + await s1.commit({ time: now + 8 }); + await cat.revoke(); + await s1.commitWaitError({ time: now + 8, excluded: ['3conGDUXdrTGbQPMQQhEC4Ubu1MCAnFrAYvUaewbUhtk'] }, "ruleToBeKickedArePresent") + await s1.commit({ time: now + 8 }); + }) after(() => { return Promise.all([ @@ -86,14 +85,14 @@ describe("Identities kicking by certs", function() { ]) }) - it('block#7 should have kicked 2 member', () => s1.expectJSON('/blockchain/block/7', (res) => { + it('block#7 should have kicked 2 member', () => s1.expectJSON('/blockchain/block/7', (res:HttpBlock) => { assert.deepEqual(res.excluded, [ '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo' ]); })); - it('block#8 should have kicked 1 member', () => s1.expectJSON('/blockchain/block/8', (res) => { + it('block#8 should have kicked 1 member', () => s1.expectJSON('/blockchain/block/8', (res:HttpBlock) => { assert.deepEqual(res.excluded, [ 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd' ]); diff --git a/test/integration/identity/identity-kicking.ts b/test/integration/identity/identity-kicking.ts index aaede1f7e..dfccca03d 100644 --- a/test/integration/identity/identity-kicking.ts +++ b/test/integration/identity/identity-kicking.ts @@ -17,13 +17,11 @@ import {NewTestingServer, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {Underscore} from "../../../app/lib/common-libs/underscore" import {ProverDependency} from "../../../app/modules/prover/index" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" const should = require('should'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; const commonConf = { diff --git a/test/integration/identity/identity-lookup.ts b/test/integration/identity/identity-lookup.ts index c893fb9f8..574005094 100644 --- a/test/integration/identity/identity-lookup.ts +++ b/test/integration/identity/identity-lookup.ts @@ -16,10 +16,10 @@ import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpLookup, HttpMemberships} from "../../../app/modules/bma/lib/dtos" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); const MEMORY_MODE = true; const commonConf = { @@ -72,7 +72,7 @@ describe("Lookup identity grouping", () => { ]) }) - it('cat should have only 1 identity in 1 pubkey', () => httpTest.expectAnswer(rp('http://127.0.0.1:4452/wot/lookup/cat', { json: true }), (res:HttpLookup) => { + it('cat should have only 1 identity in 1 pubkey', () => expectAnswer(rp('http://127.0.0.1:4452/wot/lookup/cat', { json: true }), (res:HttpLookup) => { res.should.have.property('results').length(1); // cat pubkey res.results[0].should.have.property('pubkey').equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); @@ -82,7 +82,7 @@ describe("Lookup identity grouping", () => { res.results[0].uids[0].should.have.property('uid').equal('cat'); })); - it('tic should have only 2 identities in 1 pubkey', () => httpTest.expectAnswer(rp('http://127.0.0.1:4452/wot/lookup/tic', { json: true }), (res:HttpLookup) => { + it('tic should have only 2 identities in 1 pubkey', () => expectAnswer(rp('http://127.0.0.1:4452/wot/lookup/tic', { json: true }), (res:HttpLookup) => { // We want to have only 1 result for the 2 identities res.should.have.property('results').length(1); // because they share the same pubkey @@ -95,7 +95,7 @@ describe("Lookup identity grouping", () => { res.results[0].uids[1].should.have.property('uid').equal('tic2'); })); - it('should exist 2 pending memberships', () => httpTest.expectAnswer(rp('http://127.0.0.1:4452/wot/pending', { json: true }), (res:HttpMemberships) => { + it('should exist 2 pending memberships', () => expectAnswer(rp('http://127.0.0.1:4452/wot/pending', { json: true }), (res:HttpMemberships) => { res.should.have.property('memberships').length(2); res.memberships[0].should.have.property('pubkey').equal('DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV'); res.memberships[0].should.have.property('uid').equal('tic1'); diff --git a/test/integration/identity/identity-revocation-test.ts b/test/integration/identity/identity-revocation-test.ts index 1a60685f1..a624b1217 100644 --- a/test/integration/identity/identity-revocation-test.ts +++ b/test/integration/identity/identity-revocation-test.ts @@ -18,13 +18,11 @@ import {TestUser} from "../tools/TestUser" import {BmaDependency} from "../../../app/modules/bma/index" import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpLookup, HttpMembers} from "../../../app/modules/bma/lib/dtos" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer} from "../tools/http-expect" const should = require('should'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectAnswer = httpTest.expectAnswer; BmaDependency.duniter.methods.noLimit(); // Disables the HTTP limiter diff --git a/test/integration/identity-same-pubkey.js b/test/integration/identity/identity-same-pubkey.ts similarity index 83% rename from test/integration/identity-same-pubkey.js rename to test/integration/identity/identity-same-pubkey.ts index 1e1949422..e3e0fc2cc 100644 --- a/test/integration/identity-same-pubkey.js +++ b/test/integration/identity/identity-same-pubkey.ts @@ -11,22 +11,19 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {TestUser} from "../tools/TestUser" +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {HttpLookup} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); -let s1, cat1, cat2, catb +let s1:TestingServer, cat1:TestUser, cat2:TestUser, catb:TestUser describe("Identities with shared pubkey", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' @@ -37,18 +34,18 @@ describe("Identities with shared pubkey", function() { cat2 = new TestUser('cat2', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); catb = new TestUser('cat1', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); - yield s1.initDalBmaConnections(); + await s1.initDalBmaConnections(); - yield cat2.createIdentity(); + await cat2.createIdentity(); // Early certification, to have only one matching 'HgTT' key at this moment - yield catb.cert(cat2); + await catb.cert(cat2); // catb gets certified by 'HgTT' - yield cat1.createIdentity(); - yield catb.createIdentity(); - yield cat1.cert(catb); - })); + await cat1.createIdentity(); + await catb.createIdentity(); + await cat1.cert(catb); + }) after(() => { return Promise.all([ @@ -56,13 +53,13 @@ describe("Identities with shared pubkey", function() { ]) }) - it('should exit 2 pubkey result', () => s1.expect('/wot/lookup/cat', (res) => { + it('should exit 2 pubkey result', () => s1.expect('/wot/lookup/cat', (res:HttpLookup) => { res.results.should.have.length(2); res.results[0].should.have.property('pubkey').equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); res.results[1].should.have.property('pubkey').equal('2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc'); })); - it('pubkey HgTT should have signed 1 key', () => s1.expect('/wot/lookup/cat', (res) => { + it('pubkey HgTT should have signed 1 key', () => s1.expect('/wot/lookup/cat', (res:HttpLookup) => { res.results.should.have.length(2); res.results[0].should.have.property('signed').length(1); const pubkey_hgtt = res.results[0]; diff --git a/test/integration/identity/identity-several-tests.ts b/test/integration/identity/identity-several-tests.ts index 316be2f47..67621a0f1 100644 --- a/test/integration/identity/identity-several-tests.ts +++ b/test/integration/identity/identity-several-tests.ts @@ -16,108 +16,77 @@ import {BmaDependency} from "../../../app/modules/bma/index" import {HttpBlock, HttpLookup, HttpSigned, HttpSummary} from "../../../app/modules/bma/lib/dtos" import {NewTestingServer, TestingServer} from "../tools/toolbox" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {shutDownEngine} from "../tools/shutdown-engine" +import {shouldFail} from "../../unit-tools" +import {expectAnswer} from "../tools/http-expect" const should = require('should'); const assert = require('assert'); -const request = require('request'); const constants = require('../../../app/lib/constants'); -const node = require('../tools/node'); const jspckg = require('../../../package'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); const rp = require('request-promise'); -const expectAnswer = httpTest.expectAnswer; const MEMORY_MODE = true; BmaDependency.duniter.methods.noLimit(); // Disables the HTTP limiter describe("Integration", function() { - describe("Node 1", function() { + let node1:TestingServer, cat:TestUser, tac:TestUser, tic:TestUser, toc:TestUser - const node1 = node('db1', { upnp: false, currency: 'bb', ipv4: 'localhost', port: 9999, remoteipv4: 'localhost', remoteport: 9999, httplogs: false, + before(async () => { + node1 = NewTestingServer({ + name: 'db1', + memory: MEMORY_MODE, + currency: 'bb', ipv4: 'localhost', port: 9999, remoteipv4: 'localhost', remoteport: 9999, httplogs: false, rootoffset: 0, - sigQty: 1, + sigQty: 1, sigPeriod: 0, pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' } - }); + }) - const cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, node1); - const tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, node1); - const tic = new TestUser('tic', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, node1); - const toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, node1); + cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: node1 }) + tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: node1 }) + tic = new TestUser('tic', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, { server: node1 }) + toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: node1 }) + await node1.initWithDAL().then(BmaDependency.duniter.methods.bma).then((bmapi) => bmapi.openConnections()); + }) - before(function(done) { - node1.startTesting() - .then(function(){ - node1.before([])(done); - }); - }); + describe("Node 1", function() { describe("Testing technical API", function(){ - before(function(done) { - node1.before([])(done); - }); - after(node1.after()); - - it('/node/summary should give package.json version', node1.summary(function(summary:HttpSummary, done:any){ + it('/node/summary should give package.json version', () => node1.expectJSON('/node/summary', (summary:HttpSummary) => { should.exists(summary); should.exists(summary.duniter); should.exists(summary.duniter.software); should.exists(summary.duniter.version); assert.equal(summary.duniter.software, "duniter"); assert.equal(summary.duniter.version, jspckg.version); - done(); - })); - }); - - describe("Testing malformed documents", function(){ - - before(function(done) { - node1.before(function(node1) { - - const malformedTransaction = "Version: 2\n" + - "Type: Transaction\n" + - "Currency: null\n" + - "Issuers:\n" + - "G2CBgZBPLe6FSFUgpx2Jf1Aqsgta6iib3vmDRA1yLiqU\n" + - "Inputs:\n" + - "0:T:1536:539CB0E60CD5F55CF1BE96F067E73BF55C052112:1.0\n" + - "Outputs:Comment: mon comments\n"; - - - function sendRaw (raw:string) { - return function(done:any) { - post('/tx/process', { - "transaction": raw - }, done); - } - } + })) + }) - function post(uri:string, data:any, done:any) { - const postReq = request.post({ - "uri": 'http://' + [node1.server.conf.remoteipv4, node1.server.conf.remoteport].join(':') + uri, - "timeout": 1000 * 10 - }, function (err:any, res:any, body:any) { - done(err, res, body); - }); - postReq.form(data); + describe("Testing malformed documents", () => { + + it('should not have crashed because of wrong tx', async () => { + const malformedTransaction = "Version: 2\n" + + "Type: Transaction\n" + + "Currency: null\n" + + "Issuers:\n" + + "G2CBgZBPLe6FSFUgpx2Jf1Aqsgta6iib3vmDRA1yLiqU\n" + + "Inputs:\n" + + "0:T:1536:539CB0E60CD5F55CF1BE96F067E73BF55C052112:1.0\n" + + "Outputs:Comment: mon comments\n"; + + await shouldFail(node1.post('/tx/process', { + json: { + transaction: malformedTransaction } - return [ - sendRaw(malformedTransaction) - ]; - }(node1))(done); - }); - after(node1.after()); - - it('should not have crashed because of wrong tx', function(){ - assert.equal(true, true); - }); - }); + }), '400 - {"ucode":1106,"message":"Requires a transaction"}') + }) + }) describe("Lookup on", function(){ @@ -132,8 +101,6 @@ describe("Integration", function() { await cat.cert(tac); }); - after(node1.after()); - describe("identities collisions", () => { it("sending same identity should fail", async () => { @@ -161,54 +128,47 @@ describe("Integration", function() { describe("user cat", function(){ - it('should give only 1 result', node1.lookup('cat', function(res:HttpLookup, done:any){ + it('should give only 1 result', () => node1.expectJSON('/wot/lookup/cat', (res:HttpLookup) => { should.exists(res); assert.equal(res.results.length, 1); - done(); })); - it('should have sent 1 signature', node1.lookup('cat', function(res:HttpLookup, done:any){ + it('should have sent 1 signature', () => node1.expectJSON('/wot/lookup/cat', (res:HttpLookup) => { should.exists(res); assert.equal(res.results[0].signed.length, 1); should.exists(res.results[0].signed[0].isMember); should.exists(res.results[0].signed[0].wasMember); assert.equal(res.results[0].signed[0].isMember, false); assert.equal(res.results[0].signed[0].wasMember, false); - done(); })); }); describe("user tac", function(){ - it('should give only 1 result', node1.lookup('tac', function(res:HttpLookup, done:any){ + it('should give only 1 result', () => node1.expectJSON('/wot/lookup/tac', (res:HttpLookup) => { should.exists(res); assert.equal(res.results.length, 1); - done(); })); - it('should have 1 signature', node1.lookup('tac', function(res:HttpLookup, done:any){ + it('should have 1 signature', () => node1.expectJSON('/wot/lookup/tac', (res:HttpLookup) => { should.exists(res); assert.equal(res.results[0].uids[0].others.length, 1); - done(); })); - it('should have sent 0 signature', node1.lookup('tac', function(res:HttpLookup, done:any){ + it('should have sent 0 signature', () => node1.expectJSON('/wot/lookup/tac', (res:HttpLookup) => { should.exists(res); assert.equal(res.results[0].signed.length, 0); - done(); })); }); - it('toc should give only 1 result', node1.lookup('toc', function(res:HttpLookup, done:any){ + it('toc should give only 1 result', () => node1.expectJSON('/wot/lookup/toc', (res:HttpLookup) => { should.exists(res); assert.equal(res.results.length, 1); - done(); })); - it('tic should give only 1 result', node1.lookup('tic', function(res:HttpLookup, done:any){ + it('tic should give only 1 result', () => node1.expectJSON('/wot/lookup/tic', (res:HttpLookup) => { should.exists(res); assert.equal(res.results.length, 1); - done(); })); }); }); diff --git a/test/integration/identity/identity-test.ts b/test/integration/identity/identity-test.ts index 7580016c4..c1e0150bb 100644 --- a/test/integration/identity/identity-test.ts +++ b/test/integration/identity/identity-test.ts @@ -23,17 +23,15 @@ import { } from "../../../app/modules/bma/lib/dtos" import {Underscore} from "../../../app/lib/common-libs/underscore" import {ProverDependency} from "../../../app/modules/prover/index" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer, expectError} from "../tools/http-expect" const should = require('should'); const constants = require('../../../app/lib/constants'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); BmaDependency.duniter.methods.noLimit(); // Disables the HTTP limiter -const expectAnswer = httpTest.expectAnswer; - const MEMORY_MODE = true; const commonConf = { ipv4: '127.0.0.1', @@ -168,7 +166,7 @@ describe("Identities collision", function() { }); it('should have identity-of/aaa', function() { - return httpTest.expectError(404, "No member matching this pubkey or uid", rp('http://127.0.0.1:7799/wot/identity-of/aaa')); + return expectError(404, "No member matching this pubkey or uid", rp('http://127.0.0.1:7799/wot/identity-of/aaa')); }); it('should have certifiers-of/cat giving results', function() { @@ -414,7 +412,7 @@ describe("Identities collision", function() { }) // it('memberships of man3', function() { - // return httpTest.expectHttpCode(404, rp('http://127.0.0.1:7799/blockchain/memberships/man3')); + // return expectHttpCode(404, rp('http://127.0.0.1:7799/blockchain/memberships/man3')); // }); // // it('difficulties', function() { diff --git a/test/integration/misc/http-api.ts b/test/integration/misc/http-api.ts index aeac65248..c79f927dd 100644 --- a/test/integration/misc/http-api.ts +++ b/test/integration/misc/http-api.ts @@ -22,13 +22,13 @@ import {ProverDependency} from "../../../app/modules/prover/index" import {HttpBlock, HttpDifficulties} from "../../../app/modules/bma/lib/dtos" import {Underscore} from "../../../app/lib/common-libs/underscore" import {BlockDTO} from "../../../app/lib/dto/BlockDTO" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectAnswer, expectError} from "../tools/http-expect" const should = require('should'); const assert = require('assert'); const rp = require('request-promise'); const ws = require('ws'); -const http = require('../tools/http'); -const shutDownEngine = require('../tools/shutDownEngine'); ProverConstants.CORES_MAXIMUM_USE_IN_PARALLEL = 1 @@ -170,7 +170,7 @@ describe("HTTP API", function() { }) it('/block/88 should not exist', function() { - return http.expectError(404, rp('http://127.0.0.1:7777/blockchain/block/88')); + return expectError(404, rp('http://127.0.0.1:7777/blockchain/block/88')); }); it('/current should exist', function() { @@ -180,7 +180,7 @@ describe("HTTP API", function() { }); it('/membership should not accept wrong signature', function() { - return http.expectError(400, 'wrong signature for membership', rp.post('http://127.0.0.1:7777/blockchain/membership', { + return expectError(400, 'wrong signature for membership', rp.post('http://127.0.0.1:7777/blockchain/membership', { json: { membership: 'Version: 10\n' + 'Type: Membership\n' + @@ -196,7 +196,7 @@ describe("HTTP API", function() { }); it('/membership should not accept wrong signature 2', function() { - return http.expectError(400, 'Document has unkown fields or wrong line ending format', rp.post('http://127.0.0.1:7777/blockchain/membership', { + return expectError(400, 'Document has unkown fields or wrong line ending format', rp.post('http://127.0.0.1:7777/blockchain/membership', { json: { membership: 'Version: 2\n' + 'Type: Membership\n' + @@ -211,7 +211,7 @@ describe("HTTP API", function() { }); it('/membership should not accept wrong signature 3', function() { - return http.expectError(400, 'Document has unkown fields or wrong line ending format', rp.post('http://127.0.0.1:7777/blockchain/membership', { + return expectError(400, 'Document has unkown fields or wrong line ending format', rp.post('http://127.0.0.1:7777/blockchain/membership', { json: { membership: 'Version: 2\n' + 'Type: Membership\n' + @@ -227,7 +227,7 @@ describe("HTTP API", function() { }); it('/difficulties should have current block number + 1', function() { - return http.expectAnswer(rp('http://127.0.0.1:7777/blockchain/difficulties', { json: true }), function(res:HttpDifficulties) { + return expectAnswer(rp('http://127.0.0.1:7777/blockchain/difficulties', { json: true }), function(res:HttpDifficulties) { res.should.have.property('block').equal(5); res.should.have.property('levels').have.length(1); }); diff --git a/test/integration/single-document-treatment.js b/test/integration/misc/single-document-treatment.ts similarity index 69% rename from test/integration/single-document-treatment.js rename to test/integration/misc/single-document-treatment.ts index eeb185128..1f7350219 100644 --- a/test/integration/single-document-treatment.js +++ b/test/integration/misc/single-document-treatment.ts @@ -11,24 +11,20 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, serverWaitBlock, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" -const co = require('co'); const assert = require('assert'); -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); -const CommonConstants = require('../../app/lib/common-libs/constants').CommonConstants const now = 1500000000 -let s1, s2, cat, tac +let s1:TestingServer, s2:TestingServer, cat:TestUser, tac:TestUser describe("Single document treatment", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ // The common conf medianTimeBlocks: 1, avgGenTime: 11, @@ -40,7 +36,7 @@ describe("Single document treatment", function() { } }); - s2 = toolbox.server({ + s2 = NewTestingServer({ pair: { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE' @@ -50,17 +46,17 @@ describe("Single document treatment", function() { cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); - yield s1.prepareForNetwork(); - yield s2.prepareForNetwork(); + await s1.prepareForNetwork(); + await s2.prepareForNetwork(); // Publishing identities - yield cat.createIdentity(); - yield tac.createIdentity(); - yield cat.cert(tac); - yield tac.cert(cat); - yield cat.join(); - yield tac.join(); - })); + await cat.createIdentity(); + await tac.createIdentity(); + await cat.cert(tac); + await tac.cert(cat); + await cat.join(); + await tac.join(); + }) after(() => { return Promise.all([ @@ -69,29 +65,29 @@ describe("Single document treatment", function() { ]) }) - it('should create a common blockchain', () => co(function*() { - const b0 = yield s1.commit({ time: now }) - const b1 = yield s1.commit({ time: now + 11 }) - const b2 = yield s1.commit({ time: now + 22 }) - yield s2.writeBlock(b0) - yield s2.writeBlock(b1) - yield s2.writeBlock(b2) - yield toolbox.serverWaitBlock(s2, 2) - })) - - it('should exist the same block on each node', () => co(function*() { - yield s1.expectJSON('/blockchain/current', { + it('should create a common blockchain', async () => { + const b0 = await s1.commit({ time: now }) + const b1 = await s1.commit({ time: now + 11 }) + const b2 = await s1.commit({ time: now + 22 }) + await s2.writeBlock(b0) + await s2.writeBlock(b1) + await s2.writeBlock(b2) + await serverWaitBlock(s2._server, 2) + }) + + it('should exist the same block on each node', async () => { + await s1.expectJSON('/blockchain/current', { number: 2 }) - yield s2.expectJSON('/blockchain/current', { + await s2.expectJSON('/blockchain/current', { number: 2 }) - })) + }) - it('should refuse known fork blocks', () => co(function*() { - const p1 = yield s1.getPeer() + it('should refuse known fork blocks', async () => { + const p1 = await s1.getPeer() // Trigger the multiple writings in parallel - const res = yield Promise.all([ + const res = await Promise.all([ s2.writePeer(p1).then(p => p).catch(e => { assert.equal(e.uerr.message, "Document already under treatment"); return null }), s2.writePeer(p1).then(p => p).catch(e => { assert.equal(e.uerr.message, "Document already under treatment"); return null }), s2.writePeer(p1).then(p => p).catch(e => { assert.equal(e.uerr.message, "Document already under treatment"); return null }), @@ -107,6 +103,6 @@ describe("Single document treatment", function() { assert.equal(res[4], null) assert.equal(res[5], null) - })) + }) }) diff --git a/test/integration/network/network-merkle.ts b/test/integration/network/network-merkle.ts index 7bda67d16..ba6abfd97 100644 --- a/test/integration/network/network-merkle.ts +++ b/test/integration/network/network-merkle.ts @@ -13,13 +13,11 @@ import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpMerkleOfPeers} from "../../../app/modules/bma/lib/dtos" +import {NewTestingServer} from "../tools/toolbox" +import {BmaDependency} from "../../../app/modules/bma/index" +import {expectAnswer, expectHttpCode} from "../tools/http-expect" const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const node = require('../tools/node'); - -const expectHttpCode = httpTest.expectHttpCode; -const expectAnswer = httpTest.expectAnswer; const commonConf = { bmaWithCrawler: true, @@ -31,7 +29,8 @@ const commonConf = { sigQty: 1 }; -const s1 = node('bb33', Underscore.extend({ +const s1 = NewTestingServer(Underscore.extend({ + name: 'bb33', ipv4: '127.0.0.1', port: '20501', remoteport: '20501', @@ -44,7 +43,8 @@ const s1 = node('bb33', Underscore.extend({ sigQty: 1, dt: 0, ud0: 120 }, commonConf)); -const s2 = node('bb12', Underscore.extend({ +const s2 = NewTestingServer(Underscore.extend({ + name: 'bb12', port: '20502', remoteport: '20502', ws2p: { upnp: false }, @@ -57,10 +57,11 @@ const s2 = node('bb12', Underscore.extend({ describe("Network Merkle", function() { before(async () => { - await s1.startTesting(); - await s2.startTesting(); - let peer1 = await s1.peeringP(); - await s2.submitPeerP(peer1); + await s1.initDalBmaConnections() + await s2.initDalBmaConnections() + await s1._server.PeeringService.generateSelfPeer(s1._server.conf, 0) + await s2._server.PeeringService.generateSelfPeer(s1._server.conf, 0) + await s1.sharePeeringWith(s2) }) describe("Server 1 /network/peering", function() { diff --git a/test/integration/network/network-peerings.ts b/test/integration/network/network-peerings.ts index 2c135f644..a1a58f729 100644 --- a/test/integration/network/network-peerings.ts +++ b/test/integration/network/network-peerings.ts @@ -11,7 +11,7 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {NewTestingServer, serverWaitBlock, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {CrawlerDependency} from "../../../app/modules/crawler/index" import {Contacter} from "../../../app/modules/crawler/lib/contacter" @@ -19,15 +19,12 @@ import {PeerDTO} from "../../../app/lib/dto/PeerDTO" import {BmaDependency} from "../../../app/modules/bma/index" import {RouterDependency} from "../../../app/modules/router" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {sync} from "../tools/test-sync" +import {shutDownEngine} from "../tools/shutdown-engine" +import {expectJSON} from "../tools/http-expect" const should = require('should'); const rp = require('request-promise'); -const httpTest = require('../tools/http'); -const sync = require('../tools/sync'); -const toolbox = require('../tools/toolbox'); -const shutDownEngine = require('../tools/shutDownEngine'); - -const expectJSON = httpTest.expectJSON; const MEMORY_MODE = true; const commonConf = { @@ -120,42 +117,42 @@ describe("Network peering", function() { await tic.join(); await s1.commit(); // Server 2 syncs block 0 - await sync(0, 0, s1, s2); - await toolbox.serverWaitBlock(s1._server, 0) + await sync(0, 0, s1._server, s2._server); + await serverWaitBlock(s1._server, 0) // Server 3 syncs block 0 - await sync(0, 0, s1, s3); - await toolbox.serverWaitBlock(s3._server, 0) + await sync(0, 0, s1._server, s3._server); + await serverWaitBlock(s3._server, 0) await nodeS1.getPeer().then((peer) => nodeS2.postPeer(PeerDTO.fromJSONObject(peer).getRawSigned())).catch(e => console.error(e)) await nodeS2.getPeer().then((peer) => nodeS1.postPeer(PeerDTO.fromJSONObject(peer).getRawSigned())).catch(e => console.error(e)) await nodeS3.getPeer().then((peer) => nodeS1.postPeer(PeerDTO.fromJSONObject(peer).getRawSigned())).catch(e => console.error(e)) await s1.commit(); await Promise.all([ - toolbox.serverWaitBlock(s2._server, 1), - toolbox.serverWaitBlock(s3._server, 1) + serverWaitBlock(s2._server, 1), + serverWaitBlock(s3._server, 1) ]) // A block was successfully spread accross the network await s2.bma.closeConnections(); await s1.commit(); - await toolbox.serverWaitBlock(s3._server, 2) + await serverWaitBlock(s3._server, 2) // Server 2 syncs block number 2 (it did not have it) - await sync(2, 2, s1, s2); - await toolbox.serverWaitBlock(s2._server, 2) + await sync(2, 2, s1._server, s2._server); + await serverWaitBlock(s2._server, 2) await s2.recomputeSelfPeer(); await s2.bma.openConnections(); await new Promise((resolve) => setTimeout(resolve, 1000)); await Promise.all([ - toolbox.serverWaitBlock(s2._server, 4), - toolbox.serverWaitBlock(s3._server, 4), + serverWaitBlock(s2._server, 4), + serverWaitBlock(s3._server, 4), s1.commit().then(() => s1.commit()) ]) await Promise.all([ - toolbox.serverWaitBlock(s1._server, 5), - toolbox.serverWaitBlock(s2._server, 5), + serverWaitBlock(s1._server, 5), + serverWaitBlock(s2._server, 5), s3.commit() ]) await Promise.all([ - toolbox.serverWaitBlock(s1._server, 6), - toolbox.serverWaitBlock(s3._server, 6), + serverWaitBlock(s1._server, 6), + serverWaitBlock(s3._server, 6), s2.commit() ]) }) diff --git a/test/integration/network/network-peers-same-pubkey.ts b/test/integration/network/network-peers-same-pubkey.ts index 389a751bf..f6a35980a 100644 --- a/test/integration/network/network-peers-same-pubkey.ts +++ b/test/integration/network/network-peers-same-pubkey.ts @@ -17,10 +17,10 @@ import {PeerDTO} from "../../../app/lib/dto/PeerDTO" import {HttpPeer} from "../../../app/modules/bma/lib/dtos" import {RouterDependency} from "../../../app/modules/router" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {until} from "../tools/test-until" +import {sync} from "../tools/test-sync" const should = require('should'); -const sync = require('../tools/sync'); -const until = require('../tools/until'); const catKeyPair = { pair: { @@ -60,7 +60,7 @@ describe("Peer document", function() { await s1.recomputeSelfPeer(); // peer#1 await s1.commit(); // block#2 // // s2 syncs from s1 - await sync(0, 2, s1, s2); + await sync(0, 2, s1._server, s2._server); await serverWaitBlock(s1._server, 2) await Promise.all([ s1.get('/network/peering').then((peer:HttpPeer) => s2.post('/network/peering/peers', { peer: PeerDTO.fromJSONObject(peer).getRawSigned() })), // peer#2 @@ -72,7 +72,7 @@ describe("Peer document", function() { serverWaitBlock(s1._server, 3) ]) - await sync(0, 3, s1, s3); + await sync(0, 3, s1._server, s3._server); await serverWaitBlock(s3._server, 3) const peer1 = await s1.get('/network/peering'); diff --git a/test/integration/network/network-update.ts b/test/integration/network/network-update.ts index 53c5a9870..4c0a523d8 100644 --- a/test/integration/network/network-update.ts +++ b/test/integration/network/network-update.ts @@ -17,8 +17,7 @@ import {TestUser} from "../tools/TestUser" import {NewTestingServer, TestingServer} from "../tools/toolbox" import {Underscore} from "../../../app/lib/common-libs/underscore" import {RouterDependency} from "../../../app/modules/router" - -const sync = require('../tools/sync'); +import {sync} from "../tools/test-sync" const catKeyPair = { pair: { @@ -64,7 +63,7 @@ describe("Network updating", function() { await s1.commit(); // block#0 } // // s2 syncs from s1 - await sync(0, 31, s1, s2); + await sync(0, 31, s1._server, s2._server); const b2 = await s1.makeNext({}); await s1.postBlock(b2); diff --git a/test/integration/peer-outdated.js b/test/integration/network/peer-outdated.ts similarity index 65% rename from test/integration/peer-outdated.js rename to test/integration/network/peer-outdated.ts index d71f0b3cf..a83d9540e 100644 --- a/test/integration/peer-outdated.js +++ b/test/integration/network/peer-outdated.ts @@ -11,35 +11,33 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpPeer, HttpPeers} from "../../../app/modules/bma/lib/dtos" +import {PeerDTO} from "../../../app/lib/dto/PeerDTO" +import {RouterDependency} from "../../../app/modules/router" +import {Multicaster} from "../../../app/lib/streams/multicaster" +import {until} from "../tools/test-until" -const co = require('co'); const should = require('should'); const es = require('event-stream'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const until = require('./tools/until'); -const toolbox = require('./tools/toolbox'); -const Multicaster = require('../../app/lib/streams/multicaster').Multicaster -const PeerDTO = require('../../app/lib/dto/PeerDTO').PeerDTO -let s1, s2, cat, toc +let s1:TestingServer, s2:TestingServer, cat:TestUser, toc:TestUser describe("Peer document expiry", function() { - let peer1V1; + let peer1V1:HttpPeer - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP' } }); - s2 = toolbox.server({ + s2 = NewTestingServer({ pair: { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F' @@ -49,30 +47,28 @@ describe("Peer document expiry", function() { cat = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); toc = new TestUser('toc', { pub: 'DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo', sec: '64EYRvdPpTfLGGmaX5nijLXRqWXaVz8r1Z1GtaahXwVSJGQRn7tqkxLb288zwSYzELMEG5ZhXSBYSxsTsz1m9y8F'}, { server: s1 }); - const commitS1 = commit(s1); - - yield [s1, s2].reduce((p, server) => co(function*() { - yield p; - yield server.initDalBmaConnections() - require('../../app/modules/router').RouterDependency.duniter.methods.routeToNetwork(server); - }), Promise.resolve()); + await [s1, s2].reduce(async (p:Promise<any>, server:TestingServer) => { + await p; + await server.initDalBmaConnections() + RouterDependency.duniter.methods.routeToNetwork(server._server) + }, Promise.resolve()) // Server 1 - yield cat.createIdentity(); - yield toc.createIdentity(); - yield toc.cert(cat); - yield cat.cert(toc); - yield cat.join(); - yield toc.join(); - yield commitS1(); // block#0 - yield commitS1(); // block#1 - yield s1.recomputeSelfPeer(); // peer#1 - peer1V1 = yield s1.get('/network/peering'); - yield commitS1(); // block#2 - yield s1.recomputeSelfPeer(); // peer#2 - yield s2.syncFrom(s1, 0, 2); - yield s2.waitToHaveBlock(2) - })); + await cat.createIdentity(); + await toc.createIdentity(); + await toc.cert(cat); + await cat.cert(toc); + await cat.join(); + await toc.join(); + await s1.commit(); // block#0 + await s1.commit(); // block#1 + await s1.recomputeSelfPeer(); // peer#1 + peer1V1 = await s1.get('/network/peering'); + await s1.commit(); // block#2 + await s1.recomputeSelfPeer(); // peer#2 + await s2.syncFrom(s1._server, 0, 2); + await s2.waitToHaveBlock(2) + }) after(() => { return Promise.all([ @@ -81,50 +77,50 @@ describe("Peer document expiry", function() { ]) }) - it('sending back V1 peer document should return the latest known one', () => co(function*() { + it('sending back V1 peer document should return the latest known one', async () => { let res; try { - yield s1.post('/network/peering/peers', { peer: PeerDTO.fromJSONObject(peer1V1).getRawSigned() }); + await s1.post('/network/peering/peers', { peer: PeerDTO.fromJSONObject(peer1V1).getRawSigned() }); } catch (e) { res = e; } should.exist(res); res.should.have.property("error").property("peer").property("block").match(/^2-/); - })); + }) - it('routing V1 peer document should raise an "outdated" event', () => co(function*() { + it('routing V1 peer document should raise an "outdated" event', async () => { const caster = new Multicaster(); return new Promise((resolve) => { caster - .pipe(es.mapSync((obj) => { + .pipe(es.mapSync((obj:any) => { obj.should.have.property("outdated").equal(true); resolve(); })); caster.sendPeering(PeerDTO.fromJSONObject(peer1V1), PeerDTO.fromJSONObject(peer1V1)); }); - })); + }) it('mirror should have 3 known blocks', () => s2.expectJSON('/blockchain/current', { number: 2 })); - it('mirror should have 1 known peers', () => s2.expect('/network/peers', (res) => { + it('mirror should have 1 known peers', () => s2.expect('/network/peers', (res:HttpPeers) => { res.should.have.property("peers").length(1); res.peers[0].should.have.property("pubkey").equal('DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo'); })); - it('routing V1 peer document should inject newer peer', () => co(function*() { - yield [ + it('routing V1 peer document should inject newer peer', async () => { + await [ s2.writePeer(peer1V1), until(s2, 'peer', 2) ]; - })); + }) - it('mirror should now have 2 known peers', () => s2.expect('/network/peers', (res) => { + it('mirror should now have 2 known peers', () => s2.expect('/network/peers', (res:HttpPeers) => { res.should.have.property("peers").length(2); res.peers[0].should.have.property("pubkey").equal('DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo'); res.peers[0].should.have.property("block").match(/^0-/); res.peers[1].should.have.property("pubkey").equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); res.peers[1].should.have.property("block").match(/^2-/); - })); -}); + })) +}) diff --git a/test/integration/continuous-proof.js b/test/integration/proof-of-work/continuous-proof.ts similarity index 63% rename from test/integration/continuous-proof.js rename to test/integration/proof-of-work/continuous-proof.ts index ffe8615b3..539384131 100644 --- a/test/integration/continuous-proof.js +++ b/test/integration/proof-of-work/continuous-proof.ts @@ -11,24 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {TestUser} from "../tools/TestUser" +import {NewTestingServer, simpleNetworkOf2NodesAnd2Users, TestingServer} from "../tools/toolbox" +import {CrawlerDependency} from "../../../app/modules/crawler/index" -const co = require('co'); const es = require('event-stream'); const should = require('should'); -const TestUser = require('./tools/TestUser').TestUser -const toolbox = require('./tools/toolbox'); -const constants = require('../../app/lib/constants'); const NB_CORES_FOR_COMPUTATION = 1 // For simple tests. Can be changed to test multiple cores. -let s1, s2, s3, i1, i2 +let s1:TestingServer, s2:TestingServer, s3:TestingServer, i1:TestUser, i2:TestUser describe("Continous proof-of-work", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ cpu: 1, nbCores: NB_CORES_FOR_COMPUTATION, powDelay: 100, @@ -42,37 +40,37 @@ describe("Continous proof-of-work", function() { i1 = new TestUser('i1', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); i2 = new TestUser('i2', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, { server: s1 }); - yield s1.prepareForNetwork(); - yield i1.createIdentity(); - yield i2.createIdentity(); - yield i1.cert(i2); - yield i2.cert(i1); - yield i1.join(); - yield i2.join(); - yield s1.commit(); - yield s1.closeCluster(); - })); - - it('should automatically stop waiting if nothing happens', () => co(function*() { + await s1.prepareForNetwork(); + await i1.createIdentity(); + await i2.createIdentity(); + await i1.cert(i2); + await i2.cert(i1); + await i1.join(); + await i2.join(); + await s1.commit(); + await s1.closeCluster(); + }) + + it('should automatically stop waiting if nothing happens', async () => { s1.conf.powSecurityRetryDelay = 10; let start = Date.now(); s1.startBlockComputation(); // s1.permaProver.should.have.property('loops').equal(0); - yield s1.until('block', 1); + await s1.until('block', 1); // s1.permaProver.should.have.property('loops').equal(1); (start - Date.now()).should.be.belowOrEqual(1000); - yield s1.stopBlockComputation(); - yield new Promise((resolve) => setTimeout(resolve, 100)); + await s1.stopBlockComputation(); + await new Promise((resolve) => setTimeout(resolve, 100)); // s1.permaProver.should.have.property('loops').equal(2); s1.conf.powSecurityRetryDelay = 10 * 60 * 1000; - yield s1.revert(); + await s1.revert(); s1.permaProver.loops = 0; - yield s1.stopBlockComputation(); - })); + await s1.stopBlockComputation(); + }) - it('should be able to start generation and find a block', () => co(function*() { + it('should be able to start generation and find a block', async () => { s1.permaProver.should.have.property('loops').equal(0); - yield [ + await [ s1.startBlockComputation(), s1.until('block', 2) ]; @@ -81,48 +79,48 @@ describe("Continous proof-of-work", function() { // * 1 loop for making b#1 // * 1 loop by waiting between b#1 and b#2 // * 1 loop for making b#2 - yield new Promise((resolve) => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); // s1.permaProver.should.have.property('loops').equal(4); - yield s1.stopBlockComputation(); + await s1.stopBlockComputation(); // If we wait a bit, the loop should be ended - yield new Promise((resolve) => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); // s1.permaProver.should.have.property('loops').equal(5); - yield s1.stopBlockComputation(); - })); + await s1.stopBlockComputation(); + }) - it('should be able to cancel generation because of a blockchain switch', () => co(function*() { + it('should be able to cancel generation because of a blockchain switch', async () => { // s1.permaProver.should.have.property('loops').equal(5); s1.startBlockComputation(); - yield s1.until('block', 1); + await s1.until('block', 1); // * 1 loop for making b#3 - yield new Promise((resolve) => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); // s1.permaProver.should.have.property('loops').equal(6); - yield s1.permaProver.blockchainChanged(); - yield new Promise((resolve) => setTimeout(resolve, 100)); + await s1.permaProver.blockchainChanged(); + await new Promise((resolve) => setTimeout(resolve, 100)); // * 1 loop for waiting for b#4 but being interrupted s1.permaProver.should.have.property('loops').greaterThanOrEqual(5); - yield s1.stopBlockComputation(); + await s1.stopBlockComputation(); // If we wait a bit, the loop should be ended - yield new Promise((resolve) => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); s1.permaProver.should.have.property('loops').greaterThanOrEqual(6); - })); + }) - it('testing proof-of-work during a block pulling', () => co(function*() { - const res = yield toolbox.simpleNetworkOf2NodesAnd2Users({ + it('testing proof-of-work during a block pulling', async () => { + const res = await simpleNetworkOf2NodesAnd2Users({ nbCores: NB_CORES_FOR_COMPUTATION, powMin: 0 }), s2 = res.s1, s3 = res.s2; - yield s2.commit(); + await s2.commit(); s2.conf.cpu = 1.0; s2.startBlockComputation(); - yield s2.until('block', 15); - yield s2.stopBlockComputation(); - yield [ - require('../../app/modules/crawler').CrawlerDependency.duniter.methods.pullBlocks(s3), + await s2.until('block', 15); + await s2.stopBlockComputation(); + await [ + CrawlerDependency.duniter.methods.pullBlocks(s3._server), new Promise(res => { - s3.pipe(es.mapSync((e) => { + s3.pipe(es.mapSync((e:any) => { if (e.number === 15) { res() } @@ -132,9 +130,9 @@ describe("Continous proof-of-work", function() { }), s3.startBlockComputation() ]; - const current = yield s3.get('/blockchain/current') - yield s3.stopBlockComputation(); + const current = await s3.get('/blockchain/current') + await s3.stopBlockComputation(); current.number.should.be.aboveOrEqual(14) - yield s1.closeCluster() - })); + await s1.closeCluster() + }) }); diff --git a/test/integration/proof-of-work.js b/test/integration/proof-of-work/proof-of-work.ts similarity index 68% rename from test/integration/proof-of-work.js rename to test/integration/proof-of-work/proof-of-work.ts index dd43486b2..29b3a7306 100644 --- a/test/integration/proof-of-work.js +++ b/test/integration/proof-of-work/proof-of-work.ts @@ -11,14 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewLogger} from "../../../app/lib/logger" +import {BlockProver} from "../../../app/modules/prover/lib/blockProver" -const co = require('co'); const should = require('should'); -const toolbox = require('./tools/toolbox'); -const constants = require('../../app/lib/constants'); -const logger = require('../../app/lib/logger').NewLogger(); -const BlockProver = require('../../app/modules/prover/lib/blockProver').BlockProver +const logger = NewLogger(); /*** conf.medianTimeBlocks @@ -28,11 +25,11 @@ conf.cpu keyring from Key ***/ -const intermediateProofs = []; +const intermediateProofs:any[] = []; const NB_CORES_FOR_COMPUTATION = 1 // For simple tests. Can be changed to test multiple cores. const prover = new BlockProver({ - push: (data) => intermediateProofs.push(data), + push: (data:any) => intermediateProofs.push(data), conf: { nbCores: NB_CORES_FOR_COMPUTATION, cpu: 1.0, // 80%, @@ -42,7 +39,7 @@ const prover = new BlockProver({ } }, logger -}); +} as any); const now = 1474382274 * 1000; const MUST_START_WITH_A_ZERO = 16; @@ -50,8 +47,8 @@ const MUST_START_WITH_TWO_ZEROS = 32; describe("Proof-of-work", function() { - it('should be able to find an easy PoW', () => co(function*() { - let block = yield prover.prove({ + it('should be able to find an easy PoW', async () => { + let block = await prover.prove({ issuer: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', number: 2 }, MUST_START_WITH_TWO_ZEROS, now); @@ -59,29 +56,29 @@ describe("Proof-of-work", function() { intermediateProofs.length.should.be.greaterThan(0); intermediateProofs[intermediateProofs.length - 1].pow.should.have.property('found').equal(true); intermediateProofs[intermediateProofs.length - 1].pow.should.have.property('hash').equal(block.hash); - })); + }) // Too randomly successing test // it('should be able to cancel a proof-of-work on other PoW receival', () => co(function*() { // const now = 1474464489; - // const res = yield toolbox.simpleNetworkOf2NodesAnd2Users({ + // const res = await toolbox.simpleNetworkOf2NodesAnd2Users({ // powMin: 46 // }), s1 = res.s1, s2 = res.s2; - // yield s1.commit({ + // await s1.commit({ // time: now // 38 hits to find the proof (known by test) // }); - // yield s2.until('block', 1); - // yield s1.expectJSON('/blockchain/current', { number: 0 }); - // yield s2.expectJSON('/blockchain/current', { number: 0 }); - // yield s1.commit({ + // await s2.until('block', 1); + // await s1.expectJSON('/blockchain/current', { number: 0 }); + // await s2.expectJSON('/blockchain/current', { number: 0 }); + // await s1.commit({ // time: now + 13 // 521 hits to find the proof // }); - // yield s2.until('block', 1); - // yield s1.expectJSON('/blockchain/current', { number: 1 }); - // yield s2.expectJSON('/blockchain/current', { number: 1 }); + // await s2.until('block', 1); + // await s1.expectJSON('/blockchain/current', { number: 1 }); + // await s2.expectJSON('/blockchain/current', { number: 1 }); // s1.conf.cpu = 1.0; // s2.conf.cpu = 0.02; - // yield Promise.all([ + // await Promise.all([ // // // Make a concurrent trial // Promise.all([ @@ -90,7 +87,7 @@ describe("Proof-of-work", function() { // let s2commit = s2.commit({ time: now + 14 }); // 7320 hits to be found: very high, that's good because we need time for s1 to find the proof *before* s2 // // A little handicap for s1 which will find the proof almost immediately // setTimeout(() => s1.commit({ time: now + 10 }), 100); - // yield s2commit; + // await s2commit; // throw 's2 server should not have found the proof before s1'; // } catch (e) { // should.exist(e); @@ -103,62 +100,62 @@ describe("Proof-of-work", function() { // s1.until('block', 1), // s2.until('block', 1) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 2 }); - // yield s2.expectJSON('/blockchain/current', { number: 2 }); + // await s1.expectJSON('/blockchain/current', { number: 2 }); + // await s2.expectJSON('/blockchain/current', { number: 2 }); // // Both nodes should receive the same last block from s2 // s2.conf.cpu = 1.0; - // yield [ + // await [ // s1.until('block', 1), // s2.until('block', 1), // s2.commit({ time: now + 10 }) // ]; - // yield s1.expectJSON('/blockchain/current', { number: 3 }); - // yield s2.expectJSON('/blockchain/current', { number: 3 }); + // await s1.expectJSON('/blockchain/current', { number: 3 }); + // await s2.expectJSON('/blockchain/current', { number: 3 }); // })); // TODO: re-enable when algorithm is better // it('should be able to cancel a waiting on other PoW receival', () => co(function*() { // const now = 1474464481; - // const res = yield toolbox.simpleNetworkOf2NodesAnd2Users({ + // const res = await toolbox.simpleNetworkOf2NodesAnd2Users({ // powSecurityRetryDelay: 10 * 60 * 1000, // powMaxHandicap: 8, // percentRot: 1, // powMin: 35 // }), s1 = res.s1, s2 = res.s2; - // yield Promise.all([ + // await Promise.all([ // s1.commit({ time: now }), // // We wait until both nodes received the new block // s1.until('block', 1), // s2.until('block', 1) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 0 }); - // yield s2.expectJSON('/blockchain/current', { number: 0 }); - // yield Promise.all([ + // await s1.expectJSON('/blockchain/current', { number: 0 }); + // await s2.expectJSON('/blockchain/current', { number: 0 }); + // await Promise.all([ // s2.commit({ time: now }), // // We wait until both nodes received the new block // s1.until('block', 1), // s2.until('block', 1) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 1 }); - // yield s2.expectJSON('/blockchain/current', { number: 1 }); - // yield Promise.all([ + // await s1.expectJSON('/blockchain/current', { number: 1 }); + // await s2.expectJSON('/blockchain/current', { number: 1 }); + // await Promise.all([ // s1.commit({ time: now }), // // We wait until both nodes received the new block // s1.until('block', 1), // s2.until('block', 1) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 2, issuersCount: 1 }); - // yield s2.expectJSON('/blockchain/current', { number: 2, issuersCount: 1 }); - // yield Promise.all([ + // await s1.expectJSON('/blockchain/current', { number: 2, issuersCount: 1 }); + // await s2.expectJSON('/blockchain/current', { number: 2, issuersCount: 1 }); + // await Promise.all([ // s2.commit({ time: now }), // // We wait until both nodes received the new block // s1.until('block', 1), // s2.until('block', 1) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 3, issuersCount: 2 }); - // yield s2.expectJSON('/blockchain/current', { number: 3, issuersCount: 2 }); - // // yield s2.expectJSON('/blockchain/difficulties', { number: 3, issuersCount: 2 }); - // yield Promise.all([ + // await s1.expectJSON('/blockchain/current', { number: 3, issuersCount: 2 }); + // await s2.expectJSON('/blockchain/current', { number: 3, issuersCount: 2 }); + // // await s2.expectJSON('/blockchain/difficulties', { number: 3, issuersCount: 2 }); + // await Promise.all([ // // new Promise((resolve) => { // s1.startBlockComputation(); @@ -170,7 +167,7 @@ describe("Proof-of-work", function() { // s1.until('block', 2), // s2.until('block', 2) // ]); - // yield s1.expectJSON('/blockchain/current', { number: 5 }); - // yield s2.expectJSON('/blockchain/current', { number: 5 }); + // await s1.expectJSON('/blockchain/current', { number: 5 }); + // await s2.expectJSON('/blockchain/current', { number: 5 }); // })); }); diff --git a/test/integration/v0.4-times.js b/test/integration/protocol/v0.4-times.ts similarity index 69% rename from test/integration/v0.4-times.js rename to test/integration/protocol/v0.4-times.ts index e11ee84fe..723367d00 100644 --- a/test/integration/v0.4-times.js +++ b/test/integration/protocol/v0.4-times.ts @@ -13,11 +13,9 @@ "use strict"; -const co = require('co'); +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" + const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); const conf = { avgGenTime: 5000, @@ -25,15 +23,15 @@ const conf = { }; const now = 1475069096; -let s1; +let s1:TestingServer describe("Protocol 0.4 Times", function() { - before(() => co(function*() { - const res = yield toolbox.simpleNodeWith2Users(conf); + before(async () => { + const res = await simpleNodeWith2Users(conf); s1 = res.s1; - yield s1.commit({ time: now }); // We must issue a normal root block, because always medianTime(0) == time(0) - })); + await s1.commit({ time: now }); // We must issue a normal root block, because always medianTime(0) == time(0) + }) after(() => { return Promise.all([ @@ -41,16 +39,16 @@ describe("Protocol 0.4 Times", function() { ]) }) - it('a V4 block should not accept a time = medianTime + avgGenTime * 1.189', () => co(function*() { - yield s1.commit({ medianTime: now, time: Math.ceil(now + conf.avgGenTime * 1.189) }); - yield s1.revert(); - })); + it('a V4 block should not accept a time = medianTime + avgGenTime * 1.189', async () => { + await s1.commit({ medianTime: now, time: Math.ceil(now + conf.avgGenTime * 1.189) }); + await s1.revert(); + }) - it('a V4 block should not accept a time > medianTime + avgGenTime * 1.189', () => co(function*() { + it('a V4 block should not accept a time > medianTime + avgGenTime * 1.189', async () => { try { - yield s1.commitExpectError({ medianTime: now, time: Math.ceil(now + conf.avgGenTime * 1.189) + 1 }); + await s1.commitExpectError({ medianTime: now, time: Math.ceil(now + conf.avgGenTime * 1.189) + 1 }); } catch (e) { e.should.have.property('message').equal('A block must have its Time between MedianTime and MedianTime + 5945'); } - })); + }) }); diff --git a/test/integration/v0.5-identity-blockstamp.js b/test/integration/protocol/v0.5-identity-blockstamp.ts similarity index 58% rename from test/integration/v0.5-identity-blockstamp.js rename to test/integration/protocol/v0.5-identity-blockstamp.ts index 9016e87ab..28d3adde8 100644 --- a/test/integration/v0.5-identity-blockstamp.js +++ b/test/integration/protocol/v0.5-identity-blockstamp.ts @@ -11,13 +11,10 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {createUser, simpleNodeWith2otherUsers, simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); const conf = { avgGenTime: 5000, @@ -26,19 +23,19 @@ const conf = { const now = 1578540000; -let s1, s2, tuc; +let s1:TestingServer, s2:TestingServer, tuc:TestUser describe("Protocol 0.5 Identity blockstamp", function() { - before(() => co(function*() { + before(async () => { - const res1 = yield toolbox.simpleNodeWith2Users(conf); - const res2 = yield toolbox.simpleNodeWith2otherUsers(conf); + const res1 = await simpleNodeWith2Users(conf); + const res2 = await simpleNodeWith2otherUsers(conf); s1 = res1.s1; s2 = res2.s1; - tuc = yield toolbox.createUser('tuc', '3conGDUXdrTGbQPMQQhEC4Ubu1MCAnFrAYvUaewbUhtk', '5ks7qQ8Fpkin7ycXpxQSxxjVhs8VTzpM3vEBMqM7NfC1ZiFJ93uQryDcoM93Mj77T6hDAABdeHZJDFnkDb35bgiU', s1); - })); + tuc = await createUser('tuc', '3conGDUXdrTGbQPMQQhEC4Ubu1MCAnFrAYvUaewbUhtk', '5ks7qQ8Fpkin7ycXpxQSxxjVhs8VTzpM3vEBMqM7NfC1ZiFJ93uQryDcoM93Mj77T6hDAABdeHZJDFnkDb35bgiU', s1._server); + }) after(() => { return Promise.all([ @@ -47,23 +44,23 @@ describe("Protocol 0.5 Identity blockstamp", function() { ]) }) - it('should be able to create tuc on s1', () => co(function*() { - yield s1.commit({ time: now }); - yield s1.commit({ time: now }); - yield s2.commit({ time: now }); - yield s2.commit({ time: now }); - yield tuc.createIdentity(); - })); + it('should be able to create tuc on s1', async () => { + await s1.commit({ time: now }); + await s1.commit({ time: now }); + await s2.commit({ time: now }); + await s2.commit({ time: now }); + await tuc.createIdentity(); + }) - it('should not be able to create tuc on s2, using identity generated on s1', () => co(function*() { + it('should not be able to create tuc on s2, using identity generated on s1', async () => { try { - yield tuc.submitIdentity(tuc.getIdentityRaw(), s2); + await tuc.submitIdentity(tuc.getIdentityRaw(), s2); throw { message: 'Submitting wrong identity should have thrown an error' }; } catch (e) { if (!(typeof e == "string") || e.match(/Submitting wrong identity should have thrown an error/)) { throw e; } } - })); -}); + }) +}) diff --git a/test/integration/v0.5-transactions.js b/test/integration/protocol/v0.5-transactions.ts similarity index 65% rename from test/integration/v0.5-transactions.js rename to test/integration/protocol/v0.5-transactions.ts index c7e546b0d..836eaffb0 100644 --- a/test/integration/v0.5-transactions.js +++ b/test/integration/protocol/v0.5-transactions.ts @@ -11,13 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {BlockDTO} from "../../../app/lib/dto/BlockDTO" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); +const constants = require('../../../app/lib/constants'); const conf = { dt: 30, @@ -27,21 +25,21 @@ const conf = { const now = 1578540000; -let s1; +let s1:TestingServer describe("Protocol 0.5 Transaction version", function() { - before(() => co(function*() { + before(async () => { - const res1 = yield toolbox.simpleNodeWith2Users(conf); + const res1 = await simpleNodeWith2Users(conf); s1 = res1.s1; const cat = res1.cat; const tac = res1.tac; - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 100 }); - yield s1.commit({ time: now + 100 }); - yield cat.sendP(51, tac); - })); + await s1.commit({ time: now }); + await s1.commit({ time: now + 100 }); + await s1.commit({ time: now + 100 }); + await cat.sendP(51, tac); + }) after(() => { return Promise.all([ @@ -49,9 +47,9 @@ describe("Protocol 0.5 Transaction version", function() { ]) }) - it('should not have a block with v5 transaction, but v3', () => co(function*() { - const block = yield s1.commit({ time: now + 100 }); + it('should not have a block with v5 transaction, but v3', async () => { + const block = (await s1.commit({ time: now + 100 })) as BlockDTO should.exists(block.transactions[0]); block.transactions[0].version.should.equal(constants.TRANSACTION_VERSION); - })); -}); + }) +}) diff --git a/test/integration/v0.6-difficulties.js b/test/integration/protocol/v0.6-difficulties.ts similarity index 60% rename from test/integration/v0.6-difficulties.js rename to test/integration/protocol/v0.6-difficulties.ts index 983a12246..7b834dfae 100644 --- a/test/integration/v0.6-difficulties.js +++ b/test/integration/protocol/v0.6-difficulties.ts @@ -11,11 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {serverWaitBlock, simpleNetworkOf2NodesAnd2Users, TestingServer} from "../tools/toolbox" -const co = require('co'); const should = require('should'); -const toolbox = require('./tools/toolbox'); const conf = { avgGenTime: 5000, @@ -24,20 +22,20 @@ const conf = { const now = 1480937906; -let s1, s2; +let s1:TestingServer, s2:TestingServer describe("Protocol 0.6 Difficulties", function() { - before(() => co(function*() { + before(async () => { - const res = yield toolbox.simpleNetworkOf2NodesAnd2Users(conf); + const res = await simpleNetworkOf2NodesAnd2Users(conf); s1 = res.s1; s2 = res.s2; - yield [ + await Promise.all([ s1.commit({ time: now }), s2.until('block', 1) - ]; - })); + ]) + }) after(() => { return Promise.all([ @@ -46,69 +44,69 @@ describe("Protocol 0.6 Difficulties", function() { ]) }) - it('should be able to emit a block#1 by a different user', () => co(function*() { - yield [ + it('should be able to emit a block#1 by a different user', async () => { + await Promise.all([ s1.commit({ time: now }), // medianOfBlocksInFrame = MEDIAN([1]) = 1 - toolbox.serverWaitBlock(s1, 1), - toolbox.serverWaitBlock(s2, 1) - ]; - yield [ + serverWaitBlock(s1._server, 1), + serverWaitBlock(s2._server, 1) + ]) + await Promise.all([ s2.commit({ time: now }), // medianOfBlocksInFrame = MEDIAN([1]) = 1 - toolbox.serverWaitBlock(s1, 2), - toolbox.serverWaitBlock(s2, 2) - ]; - yield s1.expectJSON('/blockchain/current', { + serverWaitBlock(s1._server, 2), + serverWaitBlock(s2._server, 2) + ]) + await s1.expectJSON('/blockchain/current', { number: 2, issuer: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc' }); - yield s1.expectJSON('/blockchain/block/0', { + await s1.expectJSON('/blockchain/block/0', { number: 0, issuer: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd' }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 1]) = 1, personal_excess = 100%, level = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 1]) = 1, personal_excess = 100%, level = 4 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 2]) = 1.5, personal_excess = 3/1.5 = 100%, level = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([1, 2]) = 1.5, personal_excess = 2/1.5 = 33%, level = 1 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 3]) = 2, personal_excess = 4/2 = 100%, level = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // medianOfBlocksInFrame = MEDIAN([1, 3]) = 2, personal_excess = 2/2 = 0%, level = 0 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 4]) = 2.5, personal_excess = 5/2.5 = 100%, level = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // medianOfBlocksInFrame = MEDIAN([1, 4]) = 2.5, personal_excess = 2/2.5 = 0%, level = 0 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 5] ... = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 5] ... = 0 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 6] ... = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 6] ... = 0 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 7] ... = 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 7] ... = 0 - yield s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 1]) = 1, personal_excess = 100%, level = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 1]) = 1, personal_excess = 100%, level = 4 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 2]) = 1.5, personal_excess = 3/1.5 = 100%, level = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([1, 2]) = 1.5, personal_excess = 2/1.5 = 33%, level = 1 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 3]) = 2, personal_excess = 4/2 = 100%, level = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // medianOfBlocksInFrame = MEDIAN([1, 3]) = 2, personal_excess = 2/2 = 0%, level = 0 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // medianOfBlocksInFrame = MEDIAN([1, 4]) = 2.5, personal_excess = 5/2.5 = 100%, level = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // medianOfBlocksInFrame = MEDIAN([1, 4]) = 2.5, personal_excess = 2/2.5 = 0%, level = 0 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 5] ... = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 5] ... = 0 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 6] ... = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 6] ... = 0 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 4 }); // ... [1, 7] ... = 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 0 }); // ... [1, 7] ... = 0 + await s1.commit({ time: now }); /********************* * PowMin incremented ********************/ - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // medianOfBlocksInFrame = MEDIAN([1, 8]) = 4.5, personal_excess = 9/4.5 = 100%, level = 1 + 4 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([1, 8]) = 4.5, personal_excess = 1/4.5 = 0%, level = 1 + 0 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 9] ... = 5 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 9] ... = 1 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 10] ... = 5 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 10] ... = 1 - yield s1.commit({ time: now }); - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 11] ... = 5 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 11] ... = 1 - yield s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // medianOfBlocksInFrame = MEDIAN([1, 8]) = 4.5, personal_excess = 9/4.5 = 100%, level = 1 + 4 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([1, 8]) = 4.5, personal_excess = 1/4.5 = 0%, level = 1 + 0 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 9] ... = 5 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 9] ... = 1 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 10] ... = 5 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 10] ... = 1 + await s1.commit({ time: now }); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 5 }); // ... [1, 11] ... = 5 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // ... [1, 11] ... = 1 + await s1.commit({ time: now }); /********************* * Frame excluded `2LvDg21` ********************/ - yield s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([11]) = 11, personal_excess = 12/11 = 9%, level = 1 - yield s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([11]) = 11, personal_excess = 0/11 = 0%, level = 1 - })); -}); + await s1.expectJSON('/blockchain/hardship/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([11]) = 11, personal_excess = 12/11 = 9%, level = 1 + await s1.expectJSON('/blockchain/hardship/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', { level: 1 }); // medianOfBlocksInFrame = MEDIAN([11]) = 11, personal_excess = 0/11 = 0%, level = 1 + }) +}) diff --git a/test/integration/v1.0-double-dividend.js b/test/integration/protocol/v1.0-double-dividend.ts similarity index 63% rename from test/integration/v1.0-double-dividend.js rename to test/integration/protocol/v1.0-double-dividend.ts index da14d9066..20c830c86 100644 --- a/test/integration/v1.0-double-dividend.js +++ b/test/integration/protocol/v1.0-double-dividend.ts @@ -11,13 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpBlock} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); const now = 1480000000; @@ -31,7 +29,7 @@ const conf = { medianTimeBlocks: 1 // The medianTime always equals previous block's medianTime }; -let s1, cat, tac; +let s1:TestingServer, cat:TestUser, tac:TestUser describe("Protocol 1.0 Dividend Update", function() { @@ -45,23 +43,23 @@ describe("Protocol 1.0 Dividend Update", function() { * * effective dividend: this is the real dividend, which is a share of the theoretical one */ - before(() => co(function*() { + before(async () => { - const res1 = yield toolbox.simpleNodeWith2Users(conf); + const res1 = await simpleNodeWith2Users(conf); s1 = res1.s1; cat = res1.cat; // HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd tac = res1.tac; // 2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 3 }); - yield s1.commit({ time: now + 4 }); - yield s1.commit({ time: now + 5 }); - yield s1.commit({ time: now + 6 }); - yield s1.commit({ time: now + 8 }); - yield s1.commit({ time: now + 10 }); - yield s1.commit({ time: now + 12 }); - yield s1.commit({ time: now + 14 }); - yield s1.commit({ time: now + 16 }); - })); + await s1.commit({ time: now }); + await s1.commit({ time: now + 3 }); + await s1.commit({ time: now + 4 }); + await s1.commit({ time: now + 5 }); + await s1.commit({ time: now + 6 }); + await s1.commit({ time: now + 8 }); + await s1.commit({ time: now + 10 }); + await s1.commit({ time: now + 12 }); + await s1.commit({ time: now + 14 }); + await s1.commit({ time: now + 16 }); + }) after(() => { return Promise.all([ @@ -69,35 +67,35 @@ describe("Protocol 1.0 Dividend Update", function() { ]) }) - it('should have block#2 with no UD', () => s1.expectThat('/blockchain/block/2', (json) => { + it('should have block#2 with no UD', () => s1.expectThat('/blockchain/block/2', (json:HttpBlock) => { should.not.exist(json.dividend); })); - it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json) => { - json.dividend.should.equal(1000); + it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); - it('should have block#4 with no UD', () => s1.expectThat('/blockchain/block/4', (json) => { + it('should have block#4 with no UD', () => s1.expectThat('/blockchain/block/4', (json:HttpBlock) => { should.not.exist(json.dividend); })); - it('should have block#5 with UD 1000', () => s1.expectThat('/blockchain/block/5', (json) => { - json.dividend.should.equal(1000); + it('should have block#5 with UD 1000', () => s1.expectThat('/blockchain/block/5', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); - it('should have block#6 with UD 1000', () => s1.expectThat('/blockchain/block/6', (json) => { - json.dividend.should.equal(1000); + it('should have block#6 with UD 1000', () => s1.expectThat('/blockchain/block/6', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); - it('should have block#7 with UD 1000', () => s1.expectThat('/blockchain/block/7', (json) => { - json.dividend.should.equal(1000); + it('should have block#7 with UD 1000', () => s1.expectThat('/blockchain/block/7', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); - it('should have block#8 with UD 1000', () => s1.expectThat('/blockchain/block/8', (json) => { - json.dividend.should.equal(1000); + it('should have block#8 with UD 1000', () => s1.expectThat('/blockchain/block/8', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); - it('should have block#9 with UD 1000', () => s1.expectThat('/blockchain/block/9', (json) => { - json.dividend.should.equal(1000); + it('should have block#9 with UD 1000', () => s1.expectThat('/blockchain/block/9', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); })); }); diff --git a/test/integration/v1.0-g1-dividend-long-run.js b/test/integration/protocol/v1.0-g1-dividend-long-run.ts similarity index 74% rename from test/integration/v1.0-g1-dividend-long-run.js rename to test/integration/protocol/v1.0-g1-dividend-long-run.ts index 512ae506d..752f656b1 100644 --- a/test/integration/v1.0-g1-dividend-long-run.js +++ b/test/integration/protocol/v1.0-g1-dividend-long-run.ts @@ -11,13 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpBlock} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); const start = 1488985390; // 2016-03-08 16:03:10 UTC+0 const delayToUD = 1489057200 - start; // Delay to 2016-03-09 12:00:00 UTC+0 @@ -39,7 +37,7 @@ const conf = { avgGenTime: 3600 * 24 // 1 bloc a day }; -let s1, cat, tac; +let s1:TestingServer, cat:TestUser, tac:TestUser describe("Protocol 1.0 Ğ1 Dividend - long run", function() { @@ -50,19 +48,19 @@ describe("Protocol 1.0 Ğ1 Dividend - long run", function() { * Simulates the real dividends that would occur in the currency (simulating N) */ - before(() => co(function*() { + before(async () => { - const res1 = yield toolbox.simpleNodeWith2Users(conf); + const res1 = await simpleNodeWith2Users(conf); s1 = res1.s1; cat = res1.cat; // HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd tac = res1.tac; // 2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc - yield s1.commit({ time: start }); - yield s1.commit({ time: start + 1 }); - yield s1.commit({ time: start + delayToUD }); + await s1.commit({ time: start }); + await s1.commit({ time: start + 1 }); + await s1.commit({ time: start + delayToUD }); for (let i = 1; i < 20; i++) { - yield s1.commit({ time: (start + delayToUD) + aDay * i }); + await s1.commit({ time: (start + delayToUD) + aDay * i }); } - })); + }) after(() => { return Promise.all([ @@ -70,38 +68,38 @@ describe("Protocol 1.0 Ğ1 Dividend - long run", function() { ]) }) - it('should have block#0 has no UD', () => s1.expectThat('/blockchain/block/0', (json) => { + it('should have block#0 has no UD', () => s1.expectThat('/blockchain/block/0', (json:HttpBlock) => { should.not.exist(json.dividend); json.should.have.property('medianTime').equal(start); // 2016-03-08 16:03:10 UTC+0 })); - it('should have block#1 has no UD', () => s1.expectThat('/blockchain/block/1', (json) => { - json.dividend.should.equal(1000); + it('should have block#1 has no UD', () => s1.expectThat('/blockchain/block/1', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal(start); // 2016-03-08 16:03:10 UTC+0 })); - it('should have block#2 with UD 1000', () => s1.expectThat('/blockchain/block/2', (json) => { + it('should have block#2 with UD 1000', () => s1.expectThat('/blockchain/block/2', (json:HttpBlock) => { should.not.exist(json.dividend); json.should.have.property('medianTime').equal(start + 1); // 2016-03-08 16:03:11 UTC+0 })); - it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json) => { - json.dividend.should.equal(1000); + it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal(start + delayToUD); // 2016-03-09 12:00:00 UTC+0 })); - it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/4', (json) => { - json.dividend.should.equal(1000); + it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/4', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay); // 2016-03-10 12:00:00 UTC+0 })); - it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/15', (json) => { - json.dividend.should.equal(1000); + it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/15', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 12); // 2016-03-21 12:00:00 UTC+0 })); - it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/16', (json) => { - json.dividend.should.equal(1000); + it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/16', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 13); // 2016-03-22 12:00:00 UTC+0 })); }); diff --git a/test/integration/v1.0-g1-dividend.js b/test/integration/protocol/v1.0-g1-dividend.ts similarity index 71% rename from test/integration/v1.0-g1-dividend.js rename to test/integration/protocol/v1.0-g1-dividend.ts index 55991a1c7..3a15bfb8e 100644 --- a/test/integration/v1.0-g1-dividend.js +++ b/test/integration/protocol/v1.0-g1-dividend.ts @@ -11,13 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpBlock} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const constants = require('../../app/lib/constants'); -const toolbox = require('./tools/toolbox'); const start = 1488985390; // 2016-03-08 16:03:10 UTC+0 const delayToUD = 1489057200 - start; // Delay to 2016-03-09 12:00:00 UTC+0 @@ -36,7 +34,7 @@ const conf = { avgGenTime: 3600 * 24 // 1 bloc a day }; -let s1, cat, tac; +let s1:TestingServer, cat:TestUser, tac:TestUser describe("Protocol 1.0 Ğ1 Dividend", function() { @@ -47,19 +45,19 @@ describe("Protocol 1.0 Ğ1 Dividend", function() { * Simulates the real dividends that would occur in the currency (simulating N) */ - before(() => co(function*() { + before(async () => { - const res1 = yield toolbox.simpleNodeWith2Users(conf); + const res1 = await simpleNodeWith2Users(conf); s1 = res1.s1; cat = res1.cat; // HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd tac = res1.tac; // 2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc - yield s1.commit({ time: start }); - yield s1.commit({ time: start + 1 }); - yield s1.commit({ time: start + delayToUD }); + await s1.commit({ time: start }); + await s1.commit({ time: start + 1 }); + await s1.commit({ time: start + delayToUD }); for (let i = 1; i < 15; i++) { - yield s1.commit({ time: (start + delayToUD) + aDay * i }); + await s1.commit({ time: (start + delayToUD) + aDay * i }); } - })); + }) after(() => { return Promise.all([ @@ -67,70 +65,70 @@ describe("Protocol 1.0 Ğ1 Dividend", function() { ]) }) - it('should have block#0 has no UD', () => s1.expectThat('/blockchain/block/0', (json) => { + it('should have block#0 has no UD', () => s1.expectThat('/blockchain/block/0', (json:HttpBlock) => { should.not.exist(json.dividend); json.should.have.property('medianTime').equal(start); // 2016-03-08 16:03:10 UTC+0 })); - it('should have block#1 has no UD', () => s1.expectThat('/blockchain/block/1', (json) => { - json.dividend.should.equal(1000); + it('should have block#1 has no UD', () => s1.expectThat('/blockchain/block/1', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal(start); // 2016-03-08 16:03:10 UTC+0 })); - it('should have block#2 with UD 1000', () => s1.expectThat('/blockchain/block/2', (json) => { + it('should have block#2 with UD 1000', () => s1.expectThat('/blockchain/block/2', (json:HttpBlock) => { should.not.exist(json.dividend); json.should.have.property('medianTime').equal(start + 1); // 2016-03-08 16:03:11 UTC+0 })); - it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json) => { - json.dividend.should.equal(1000); + it('should have block#3 with UD 1000', () => s1.expectThat('/blockchain/block/3', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal(start + delayToUD); // 2016-03-09 12:00:00 UTC+0 })); - it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/4', (json) => { - json.dividend.should.equal(1000); + it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/4', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay); // 2016-03-10 12:00:00 UTC+0 })); - it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/5', (json) => { - json.dividend.should.equal(1000); + it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/5', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 2); // 2016-03-11 12:00:00 UTC+0 })); - it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/6', (json) => { - json.dividend.should.equal(1000); + it('should have block#4 with UD 1000', () => s1.expectThat('/blockchain/block/6', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 3); // 2016-03-12 12:00:00 UTC+0 })); // ... skip some blocks ... - it('should have block#11 with UD 1000', () => s1.expectThat('/blockchain/block/11', (json) => { - json.dividend.should.equal(1000); + it('should have block#11 with UD 1000', () => s1.expectThat('/blockchain/block/11', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 8); // 2016-03-17 12:00:00 UTC+0 })); - it('should have block#12 with UD 1000', () => s1.expectThat('/blockchain/block/12', (json) => { - json.dividend.should.equal(1000); + it('should have block#12 with UD 1000', () => s1.expectThat('/blockchain/block/12', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 9); // 2016-03-18 12:00:00 UTC+0 })); - it('should have block#13 with UD 1000', () => s1.expectThat('/blockchain/block/13', (json) => { - json.dividend.should.equal(1000); + it('should have block#13 with UD 1000', () => s1.expectThat('/blockchain/block/13', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 10); // 2016-03-19 12:00:00 UTC+0 })); - it('should have block#14 with UD 1000', () => s1.expectThat('/blockchain/block/14', (json) => { - json.dividend.should.equal(1000); + it('should have block#14 with UD 1000', () => s1.expectThat('/blockchain/block/14', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 11); // 2016-03-20 12:00:00 UTC+0 })); - it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/15', (json) => { - json.dividend.should.equal(1000); + it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/15', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 12); // 2016-03-21 12:00:00 UTC+0 })); - it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/16', (json) => { - json.dividend.should.equal(1000); + it('should have block#14 with UD 1000, even if dtReeval has been reached', () => s1.expectThat('/blockchain/block/16', (json:HttpBlock) => { + (json.dividend as any).should.equal(1000); json.should.have.property('medianTime').equal((start + delayToUD) + aDay * 13); // 2016-03-22 12:00:00 UTC+0 })); }); diff --git a/test/integration/v1.0-modules-api.js b/test/integration/protocol/v1.0-modules-api.ts similarity index 71% rename from test/integration/v1.0-modules-api.js rename to test/integration/protocol/v1.0-modules-api.ts index e884aa75c..28c2798a4 100644 --- a/test/integration/v1.0-modules-api.js +++ b/test/integration/protocol/v1.0-modules-api.ts @@ -11,28 +11,30 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import * as stream from "stream" +import {parsers} from "../../../app/lib/common-libs/parsers/index" +import {Server} from "../../../server" +import {ConfDTO} from "../../../app/lib/dto/ConfDTO" +import {KeypairDependency} from "../../../app/modules/keypair/index" +import {BmaDependency} from "../../../app/modules/bma/index" -const co = require('co'); const should = require('should'); const util = require('util'); const path = require('path'); -const stream = require('stream'); -const duniter = require('../../index'); -const parsers = require('../../app/lib/common-libs/parsers').parsers +const duniter = require('../../../index'); const querablep = require('querablep'); describe("v1.0 Module API", () => { - it('should be able to execute `hello` command with quickRun', () => co(function*() { + it('should be able to execute `hello` command with quickRun', async () => { duniter.statics.setOnRunDone(() => { /* Do not exit the process */ }) - const absolutePath = path.join(__dirname, './scenarios/hello-plugin.js') + const absolutePath = path.join(__dirname, '../scenarios/hello-plugin.js') process.argv = ['', absolutePath, 'hello-world', '--memory'] - const res = yield duniter.statics.quickRun(absolutePath) + const res = await duniter.statics.quickRun(absolutePath) res.should.equal('Hello world! from within Duniter.') - })) + }) - it('should be able to execute `hello` command', () => co(function*() { + it('should be able to execute `hello` command', async () => { const sStack = duniter.statics.simpleStack(); const aStack = duniter.statics.autoStack(); @@ -46,21 +48,21 @@ describe("v1.0 Module API", () => { cli: [{ name: 'hello', desc: 'Returns an "Hello, world" string after configuration phase.', - onConfiguredExecute: (server, conf, program, params) => co(function*(){ + onConfiguredExecute: async (server:Server, conf:ConfDTO, program:any, params:any) => { return "Hello, " + params[0] + ". You successfully sent arg '" + params[1] + "' along with opt1 = " + program.opt1 + " and option2 = " + program.option2 + "."; - }) + } }] } }; sStack.registerDependency(helloDependency, 'duniter-hello'); sStack.registerDependency(helloDependency, 'duniter-hello'); // Try to load it 2 times, should not throw an error - sStack.registerDependency(require('../../app/modules/keypair').KeypairDependency, 'duniter-keypair'); + sStack.registerDependency(KeypairDependency, 'duniter-keypair'); aStack.registerDependency(helloDependency, 'duniter-hello'); - (yield sStack.executeStack(['node', 'index.js', '--memory', 'hello', 'World', 'TEST', '--opt1', '--option2', '5'])).should.equal('Hello, World. You successfully sent arg \'TEST\' along with opt1 = true and option2 = 5.'); - (yield aStack.executeStack(['node', 'index.js', '--memory', 'hello', 'Zorld', 'ESSE', '--option2', 'd'])).should.equal('Hello, Zorld. You successfully sent arg \'ESSE\' along with opt1 = undefined and option2 = NaN.'); - })); + (await sStack.executeStack(['node', 'index.js', '--memory', 'hello', 'World', 'TEST', '--opt1', '--option2', '5'])).should.equal('Hello, World. You successfully sent arg \'TEST\' along with opt1 = true and option2 = 5.'); + (await aStack.executeStack(['node', 'index.js', '--memory', 'hello', 'Zorld', 'ESSE', '--option2', 'd'])).should.equal('Hello, Zorld. You successfully sent arg \'ESSE\' along with opt1 = undefined and option2 = NaN.'); + }) /*********************** * CONFIGURATION HOOKS @@ -68,13 +70,12 @@ describe("v1.0 Module API", () => { describe("Configuration hooks", () => { - let stack; - function run() { - const args = Array.from(arguments); + let stack:any + function run(...args:string[]) { return stack.executeStack(['node', 'index.js', '--mdb', 'modules_api_tests'].concat(args)); } - before(() => co(function*() { + before(async () => { stack = duniter.statics.simpleStack(); const configurationDependency = { @@ -84,7 +85,7 @@ describe("v1.0 Module API", () => { { value: '--superpasswd <passwd>', desc: 'A crypto password.' } ], config: { - onLoading: (conf, program) => co(function*(){ + onLoading: async (conf:any, program:any) => { // Always adds a parameter named "superkey" conf.superkey = { pub: 'publicPart', sec: 'secretPart' }; @@ -96,12 +97,11 @@ describe("v1.0 Module API", () => { if (program.superpasswd) { conf.superpasswd = program.superpasswd; } - }), - beforeSave: (conf, program) => co(function*(){ - + }, + beforeSave: async (conf:any) => { // We never want to store "superpasswd" delete conf.superpasswd; - }) + } } } }; @@ -110,52 +110,52 @@ describe("v1.0 Module API", () => { cli: [{ name: 'gimme-conf', desc: 'Returns the configuration object.', - onConfiguredExecute: (server, conf, program, params, startServices, stopServices) => co(function*() { + onConfiguredExecute: async (server:Server, conf:any) => { // Gimme the conf! return conf; - }) + } }] } }; - stack.registerDependency(require('../../app/modules/keypair').KeypairDependency, 'duniter-keypair'); + stack.registerDependency(KeypairDependency, 'duniter-keypair'); stack.registerDependency(configurationDependency, 'duniter-configuration'); stack.registerDependency(returnConfDependency, 'duniter-gimme-conf'); - })); + }) - it('verify that we get the CLI options', () => co(function*() { - const conf = yield run('gimme-conf', '--supersalt', 'NaCl'); + it('verify that we get the CLI options', async () => { + const conf = await run('gimme-conf', '--supersalt', 'NaCl'); conf.should.have.property('supersalt').equal('NaCl'); - })); + }) - it('verify that we get the saved options', () => co(function*() { + it('verify that we get the saved options', async () => { let conf; // We make an initial reset - yield run('reset', 'config'); - conf = yield run('gimme-conf'); + await run('reset', 'config'); + conf = await run('gimme-conf'); conf.should.have.property('superkey'); // Always loaded conf.should.not.have.property('supersalt'); // Nothing should have changed - conf = yield run('gimme-conf'); + conf = await run('gimme-conf'); conf.should.have.property('superkey'); // Always loaded conf.should.not.have.property('supersalt'); // Now we try to save the parameters - yield run('config', '--supersalt', 'NaCl2', '--superpasswd', 'megapasswd'); - conf = yield run('gimme-conf'); + await run('config', '--supersalt', 'NaCl2', '--superpasswd', 'megapasswd'); + conf = await run('gimme-conf'); conf.should.have.property('superkey'); // Always loaded conf.should.have.property('supersalt').equal('NaCl2'); conf.should.not.have.property('superpasswd'); // Yet we can have all options by giving them explicitely using options - conf = yield run('gimme-conf', '--superpasswd', 'megapasswd2'); + conf = await run('gimme-conf', '--superpasswd', 'megapasswd2'); conf.should.have.property('superkey'); conf.should.have.property('supersalt').equal('NaCl2'); conf.should.have.property('superpasswd').equal('megapasswd2'); - })); - }); + }) + }) /*********************** * SERVICE START/STOP @@ -163,32 +163,31 @@ describe("v1.0 Module API", () => { describe("Service triggers", () => { - let stack; - let fakeI; - let fakeP; - let fakeO; + let stack:any + let fakeI:FakeStream + let fakeP:FakeStream + let fakeO:FakeStream - function run() { - const args = Array.from(arguments); + function run(...args:string[]) { return stack.executeStack(['node', 'index.js', '--memory', '--ws2p-noupnp'].concat(args)); } - before(() => co(function*() { + before(async () => { stack = duniter.statics.simpleStack(); - fakeI = new FakeStream((that, data) => { + fakeI = new FakeStream((that:any, data:any) => { // Note: we never pass here if (typeof data == "string") { that.push(data); } }); - fakeP = new FakeStream((that, data) => { + fakeP = new FakeStream((that:any, data:any) => { if (typeof data == "object" && data.type == "transaction") { const tx = parsers.parseTransaction.syncWrite(data.doc); that.push(tx); } }); - fakeO = new FakeStream((that, data, enc, done) => { + fakeO = new FakeStream((that:any, data:any, enc:any, done:any) => { if (data.issuers) { that.resolveData(); } @@ -201,8 +200,8 @@ describe("v1.0 Module API", () => { cli: [{ name: 'hello-service', desc: 'Says hello to the world, at service phase. And feed INPUT with a transaction.', - onDatabaseExecute: (duniterServer, conf, program, programArgs, startServices, stopServices) => co(function*(){ - yield startServices(); + onDatabaseExecute: async (duniterServer:Server, conf:any, program:any, programArgs:any, startServices:any) => { + await startServices(); fakeI.push("Version: 10\n" + "Type: Transaction\n" + "Currency: test_net\n" + @@ -219,9 +218,9 @@ describe("v1.0 Module API", () => { "99000:0:SIG(HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk)\n" + "Comment: reessai\n" + "P6MxJ/2SdkvNDyIyWuOkTz3MUwsgsfo70j+rpWeQWcm6GdvKQsbplB8482Ar1HMz2q0h5V3tfMqjCuAeWVQ+Ag==\n"); - yield fakeO.outputed; + await fakeO.outputed; return fakeO.outputed; - }) + } }], service: { input: () => fakeI, @@ -235,10 +234,10 @@ describe("v1.0 Module API", () => { cli: [{ name: 'bye-service', desc: 'Says goodbye to the world, at service phase.', - onDatabaseExecute: (duniterServer, conf, program, programArgs, startServices, stopServices) => co(function*(){ - yield stopServices(); + onDatabaseExecute: async (duniterServer:any, conf:any, program:any, programArgs:any, startServices:any, stopServices:any) => { + await stopServices(); return Promise.resolve(); - }) + } }], service: { input: () => fakeI, @@ -248,20 +247,20 @@ describe("v1.0 Module API", () => { } }; - stack.registerDependency(require('../../app/modules/keypair').KeypairDependency, 'duniter-keypair'); - stack.registerDependency(require('../../app/modules/bma').BmaDependency, 'duniter-bma'); + stack.registerDependency(KeypairDependency, 'duniter-keypair'); + stack.registerDependency(BmaDependency, 'duniter-bma'); stack.registerDependency(dummyStartServiceDependency, 'duniter-dummy-start'); stack.registerDependency(dummyStopServiceDependency, 'duniter-dummy-stop'); - })); + }) - it('verify that services are started', () => co(function*() { + it('verify that services are started', async () => { fakeI.started.isResolved().should.equal(false); fakeP.started.isResolved().should.equal(false); fakeO.started.isResolved().should.equal(false); fakeI.stopped.isResolved().should.equal(false); fakeP.stopped.isResolved().should.equal(false); fakeO.stopped.isResolved().should.equal(false); - yield run('hello-service'); + await run('hello-service'); fakeO.outputed.isResolved().should.equal(true); // The transaction has successfully gone through the whole stream fakeI.started.isResolved().should.equal(true); fakeP.started.isResolved().should.equal(true); @@ -269,50 +268,57 @@ describe("v1.0 Module API", () => { fakeI.stopped.isResolved().should.equal(false); fakeP.stopped.isResolved().should.equal(false); fakeO.stopped.isResolved().should.equal(false); - })); + }) - it('verify that services are stopped', () => co(function*() { + it('verify that services are stopped', async () => { fakeI.stopped.isResolved().should.equal(false); fakeP.stopped.isResolved().should.equal(false); fakeO.stopped.isResolved().should.equal(false); fakeI.started.isResolved().should.equal(true); fakeP.started.isResolved().should.equal(true); fakeO.started.isResolved().should.equal(true); - yield run('bye-service'); + await run('bye-service'); fakeI.started.isResolved().should.equal(false); fakeP.started.isResolved().should.equal(false); fakeO.started.isResolved().should.equal(false); fakeI.stopped.isResolved().should.equal(true); fakeP.stopped.isResolved().should.equal(true); fakeO.stopped.isResolved().should.equal(true); - })); - }); + }) + }) -}); +}) -function FakeStream(onWrite) { +class FakeStream extends stream.Transform { - const that = this; - stream.Transform.call(this, { objectMode: true }); + private resolveStart:any = () => null; + private resolveStop:any = () => null; + public resolveData:any + public started:any + public stopped:any + public outputed:any - let resolveStart = () => null; - let resolveStop = () => null; + constructor(private onWrite:any) { + super({ objectMode: true }) - this._write = onWrite.bind(this, that); + this.started = querablep(new Promise(res => this.resolveStart = res)); + this.stopped = querablep(new Promise(res => this.resolveStop = res)); + } - this.started = querablep(new Promise(res => resolveStart = res)); - this.stopped = querablep(new Promise(res => resolveStop = res)); + _write(obj:any, enc:any, done:any) { + this.onWrite(this, obj, enc, done) + } - this.startService = () => co(function*() { - resolveStart(); - that.stopped = querablep(new Promise(res => resolveStop = res)); - }); + async startService() { + this.resolveStart(); + this.stopped = querablep(new Promise(res => this.resolveStop = res)); + } - this.stopService = () => co(function*() { - resolveStop(); - that.started = querablep(new Promise(res => resolveStart = res)); - }); + async stopService() { + this.resolveStop(); + this.started = querablep(new Promise(res => this.resolveStart = res)); + } } util.inherits(FakeStream, stream.Transform); diff --git a/test/integration/v1.1-dividend.js b/test/integration/protocol/v1.1-dividend.ts similarity index 76% rename from test/integration/v1.1-dividend.js rename to test/integration/protocol/v1.1-dividend.ts index 475593909..c4a6add28 100644 --- a/test/integration/v1.1-dividend.js +++ b/test/integration/protocol/v1.1-dividend.ts @@ -11,25 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpSources, HttpTxHistory} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); const now = 1484000000; -let s1, cat, tac, tic +let s1:TestingServer, cat:TestUser, tac:TestUser, tic:TestUser describe("Protocol 1.1 Dividend", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ c: 0.1, dt: 10, dtReeval: 10, @@ -47,26 +44,26 @@ describe("Protocol 1.1 Dividend", function() { tac = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); tic = new TestUser('tic', { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7'}, { server: s1 }); - yield s1.initDalBmaConnections(); + await s1.initDalBmaConnections(); - yield cat.createIdentity(); - yield tac.createIdentity(); - yield cat.cert(tac); - yield tac.cert(cat); - yield cat.join(); - yield tac.join(); - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 10 }); - yield s1.commit({ time: now + 10 * 2 }); - yield s1.commit({ time: now + 10 * 3 }); + await cat.createIdentity(); + await tac.createIdentity(); + await cat.cert(tac); + await tac.cert(cat); + await cat.join(); + await tac.join(); + await s1.commit({ time: now }); + await s1.commit({ time: now + 10 }); + await s1.commit({ time: now + 10 * 2 }); + await s1.commit({ time: now + 10 * 3 }); // tic joins - yield tic.createIdentity(); - yield cat.cert(tic); - yield tic.join(); - yield s1.commit({ time: now + 10 + 10 * 4 }); - yield s1.commit({ time: now + 10 + 10 * 5 }); - })); + await tic.createIdentity(); + await cat.cert(tic); + await tic.join(); + await s1.commit({ time: now + 10 + 10 * 4 }); + await s1.commit({ time: now + 10 + 10 * 5 }); + }) after(() => { return Promise.all([ @@ -74,7 +71,7 @@ describe("Protocol 1.1 Dividend", function() { ]) }) - it('should exit 2 dividends for cat', () => s1.expect('/tx/sources/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res) => { + it('should exit 2 dividends for cat', () => s1.expect('/tx/sources/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res:HttpSources) => { res.should.have.property('pubkey').equal('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd'); res.should.have.property('sources').length(4); res.sources[0].should.have.property('amount').equal(100); // UD(0) = ud0 => M(0) = 0 @@ -83,12 +80,12 @@ describe("Protocol 1.1 Dividend", function() { res.sources[3].should.have.property('amount').equal(103); // t = 3, M(t-1) = 402, N(t) = 3, UD(t) = UD(t-1) + c²*M(t-1)/N(t) = 101 + 0.01*400/3 = 103 (ceiled) => M(3) = M(2)+N(t-1)*DU(t-1) = 400+3*101 = 703 res.sources[0].should.have.property('base').equal(0); res.sources[1].should.have.property('base').equal(0); - })); + })) - it('should be able to send 300 units', () => co(function *() { - yield cat.send(105, tac); - yield s1.commit(); - yield s1.expect('/tx/sources/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', (res) => { + it('should be able to send 300 units', async () => { + await cat.sendMoney(105, tac); + await s1.commit(); + await s1.expect('/tx/sources/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', (res:HttpSources) => { res.should.have.property('pubkey').equal('2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc'); res.should.have.property('sources').length(6); res.sources[0].should.have.property('amount').equal(100); @@ -104,10 +101,10 @@ describe("Protocol 1.1 Dividend", function() { res.sources[4].should.have.property('type').equal('D'); res.sources[5].should.have.property('type').equal('T'); }) - })); + }) - it('should have a correct history', () => s1.expect('/tx/history/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', (res) => { + it('should have a correct history', () => s1.expect('/tx/history/2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', (res:HttpTxHistory) => { res.history.received[0].should.have.property('blockstamp').not.equal(null).not.equal(''); res.history.received[0].should.have.property('blockstampTime').not.equal(null).greaterThan(0); - })); -}); + })) +}) diff --git a/test/integration/revoked_pubkey_replay.ts b/test/integration/revoked_pubkey_replay.ts index 39583d8cd..cb94affda 100644 --- a/test/integration/revoked_pubkey_replay.ts +++ b/test/integration/revoked_pubkey_replay.ts @@ -19,7 +19,6 @@ const TestUser = require('./tools/TestUser').TestUser describe("Revoked pubkey replay", function() { const now = 1500000000 - const DONT_WAIT_FOR_BLOCKCHAIN_CHANGE = true let s1:TestingServer, cat:any, tic:any const conf = { nbCores: 1, sigQty: 1 } @@ -71,7 +70,7 @@ describe("Revoked pubkey replay", function() { it('should not try to include tic2 in a new block', async () => { await s1.commit() await tic.join() - const block = await s1.commit(null, DONT_WAIT_FOR_BLOCKCHAIN_CHANGE) + const block = await s1.justCommit() block.should.have.property('joiners').length(0) }) diff --git a/test/integration/server-sandbox.js b/test/integration/sandbox/server-sandbox.ts similarity index 94% rename from test/integration/server-sandbox.js rename to test/integration/sandbox/server-sandbox.ts index 732087dca..661098359 100644 --- a/test/integration/server-sandbox.js +++ b/test/integration/sandbox/server-sandbox.ts @@ -11,26 +11,23 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {CommonConstants} from "../../../app/lib/common-libs/constants" +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" const co = require('co'); const should = require('should'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); -const constants = require('../../app/lib/constants'); -const CommonConstants = require('../../app/lib/common-libs/constants').CommonConstants +const constants = require('../../../app/lib/constants'); const now = 1482300000; -let s1, s2, s3, i1, i2, i3, i4, i5, i6, i7, i7onS2, i8, i9, i10, i11, i12, i13, i14, i15, i16 +let s1:TestingServer, s2:TestingServer, s3:TestingServer, i1:TestUser, i2:TestUser, i3:TestUser, i4:TestUser, i5:TestUser, i6:TestUser, i7:TestUser, i7onS2:TestUser, i8:TestUser, i9:TestUser, i10:TestUser, i11:TestUser, i12:TestUser, i13:TestUser, i14:TestUser describe("Sandboxes", function() { before(() => co(function*() { - s1 = toolbox.server({ + s1 = NewTestingServer({ idtyWindow: 10, sigWindow: 10, msWindow: 10, @@ -42,14 +39,14 @@ describe("Sandboxes", function() { } }); - s2 = toolbox.server({ + s2 = NewTestingServer({ pair: { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', sec: '468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7' } }); - s3 = toolbox.server({ + s3 = NewTestingServer({ pair: { pub: 'H9dtBFmJohAwMNXSbfoL6xfRtmrqMw8WZnjXMHr4vEHX', sec: '2ANWb1qjjYRtT2TPFv1rBWA4EVfY7pqE4WqFUuzEgWG4vzcuvyUxMtyeBSf93M4V3g4MeEkELaj6NjA72jxnb4yF' @@ -127,8 +124,8 @@ describe("Sandboxes", function() { yield i3.createIdentity(); (yield s1.dal.idtyDAL.getSandboxRoom()).should.equal(1); yield s1.commit({ time: now }); - yield s2.syncFrom(s1, 0, 1); - yield s3.syncFrom(s1, 0, 1); + yield s2.syncFrom(s1._server, 0, 1); + yield s3.syncFrom(s1._server, 0, 1); })); it('should create i5(1)', () => co(function *() { @@ -301,6 +298,6 @@ describe("Sandboxes", function() { }); }); -function shouldThrow(promise) { +function shouldThrow<T>(promise:Promise<T>) { return promise.should.be.rejected(); } diff --git a/test/integration/sources_property.js b/test/integration/sources/sources-property.ts similarity index 71% rename from test/integration/sources_property.js rename to test/integration/sources/sources-property.ts index 737cd5053..eab71ca03 100644 --- a/test/integration/sources_property.js +++ b/test/integration/sources/sources-property.ts @@ -11,17 +11,12 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {simpleNodeWith2Users, TestingServer} from "../tools/toolbox" +import {TestUser} from "../tools/TestUser" +import {HttpBlock, HttpSources} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); const assert = require('assert'); -const constants = require('../../app/lib/constants'); -const bma = require('../../app/modules/bma').BmaDependency.duniter.methods.bma; -const toolbox = require('./tools/toolbox'); -const node = require('./tools/node'); -const unit = require('./tools/unit'); -const http = require('./tools/http'); const now = 1480000000; @@ -32,18 +27,18 @@ const conf = { medianTimeBlocks: 1 // Easy: medianTime(b) = time(b-1) }; -let s1, cat, tac +let s1:TestingServer, cat:TestUser, tac:TestUser describe("Sources property", function() { - before(() => co(function*() { - const res = yield toolbox.simpleNodeWith2Users(conf); + before(async () => { + const res = await simpleNodeWith2Users(conf); s1 = res.s1; cat = res.cat; tac = res.tac; - yield s1.commit({ time: now }); - yield s1.commit({ time: now + 1 }); - })); + await s1.commit({ time: now }); + await s1.commit({ time: now + 1 }); + }) after(() => { return Promise.all([ @@ -51,17 +46,17 @@ describe("Sources property", function() { ]) }) - it('it should exist block#1 with UD of 200', () => s1.expect('/blockchain/block/1', (block) => { + it('it should exist block#1 with UD of 200', () => s1.expect('/blockchain/block/1', (block:HttpBlock) => { should.exists(block); assert.equal(block.number, 1); assert.equal(block.dividend, 200); })); - it('it should exist sources for HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', () => s1.expect('/tx/sources/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res) => { + it('it should exist sources for HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', () => s1.expect('/tx/sources/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res:HttpSources) => { assert.equal(res.sources.length, 1) })); - it('it should NOT exist sources if we change one letter to uppercased version', () => s1.expect('/tx/sources/HGTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res) => { + it('it should NOT exist sources if we change one letter to uppercased version', () => s1.expect('/tx/sources/HGTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res:HttpSources) => { assert.equal(res.sources.length, 0) })); }); diff --git a/test/integration/tools/TestUser.ts b/test/integration/tools/TestUser.ts index cf76f7408..c4f8c6b35 100644 --- a/test/integration/tools/TestUser.ts +++ b/test/integration/tools/TestUser.ts @@ -64,7 +64,7 @@ export class TestUser { } } - public async createIdentity(useRoot?:boolean, fromServer?:any) { + public async createIdentity(useRoot?:boolean|null, fromServer?:any) { if (!this.pub) { this.init(() => {}) } diff --git a/test/integration/tools/commit.js b/test/integration/tools/commit.js deleted file mode 100644 index 91e05bccf..000000000 --- a/test/integration/tools/commit.js +++ /dev/null @@ -1,69 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; - -const Underscore = require('../../../app/lib/common-libs/underscore').Underscore; -var co = require('co'); -var rp = require('request-promise'); -var logger = require('../../../app/lib/logger').NewLogger('test'); -const until = require('./until') -const BlockProver = require('../../../app/modules/prover/lib/blockProver').BlockProver - -module.exports = function makeBlockAndPost(theServer, extraProps, noWait) { - return function(manualValues) { - if (extraProps) { - manualValues = manualValues || {}; - manualValues = Underscore.extend(manualValues, extraProps); - } - return co(function *() { - if (!theServer._utProver) { - theServer._utProver = new BlockProver(theServer) - theServer._utGenerator = require('../../../app/modules/prover').ProverDependency.duniter.methods.blockGenerator(theServer, theServer._utProver) - } - let proven = yield theServer._utGenerator.makeNextBlock(null, null, manualValues) - const numberToReach = proven.number - const block = yield postBlock(theServer)(proven) - yield new Promise((res) => { - if (noWait) { - return res(block) - } - const interval = setInterval(() => co(function*() { - const current = yield theServer.dal.getCurrentBlockOrNull() - if (current && current.number == numberToReach) { - res() - clearInterval(interval) - } - }), 1) - }) - return block - }); - }; -}; - -function postBlock(server) { - return function(block) { - logger.trace(block.getRawSigned()); - return post(server, '/blockchain/block')({ - block: typeof block == 'string' ? block : block.getRawSigned() - }); - }; -} - -function post(server, uri) { - return function(data) { - return rp.post('http://' + [server.conf.ipv4, server.conf.port].join(':') + uri, { - form: data - }); - }; -} diff --git a/test/integration/tools/http-expect.ts b/test/integration/tools/http-expect.ts new file mode 100644 index 000000000..19053cfbf --- /dev/null +++ b/test/integration/tools/http-expect.ts @@ -0,0 +1,83 @@ +// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 +// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +import {Underscore} from "../../../app/lib/common-libs/underscore" + +const should = require('should'); +const assert = require('assert'); + +export async function expectHttpCode(code:number, message:any, promise?:any) { + if (arguments.length == 2) { + promise = arguments[1]; + message = undefined; + } + try { + const res = await promise; + assert.equal(res.statusCode, code); + } catch (err) { + if (err.response) { + assert.equal(err.response.statusCode, code); + if (message) { + assert.equal(err.error || err.cause, message); + } + } + else throw err; + } +} + +export async function expectError(code:number, message:any, promise?:any) { + if (arguments.length == 2) { + promise = arguments[1]; + message = undefined; + } + try { + const res = await promise; + assert.equal(res.statusCode, code); + } catch (err) { + if (err.response) { + assert.equal(err.response.statusCode, code); + if (message) { + let errorObj = typeof err.error == "string" ? JSON.parse(err.error) : err.error; + assert.equal(errorObj.message, message); + } + } + else throw err; + } +} + +export async function expectJSON<T>(promise:Promise<T>, json:any) { + try { + const resJson = await promise; + Underscore.keys(json).forEach(function(key){ + resJson.should.have.property(key).equal(json[key]); + }); + } catch (err) { + if (err.response) { + assert.equal(err.response.statusCode, 200); + } + else throw err; + } +} + +export async function expectAnswer<T>(promise:Promise<T>, testFunc:any) { + try { + const res = await promise; + return testFunc(res); + } catch (err) { + if (err.response) { + console.error(err.error); + assert.equal(err.response.statusCode, 200); + } + else throw err; + } +} diff --git a/test/integration/tools/http.js b/test/integration/tools/http.js deleted file mode 100644 index c6f4e0b00..000000000 --- a/test/integration/tools/http.js +++ /dev/null @@ -1,94 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; - -const co = require('co'); -const should = require('should'); -const assert = require('assert'); -const Underscore = require('../../../app/lib/common-libs/underscore').Underscore; - -module.exports = { - - expectHttpCode: function expectHttpCode(code, message, promise) { - if (arguments.length == 2) { - promise = arguments[1]; - message = undefined; - } - return co(function*(){ - try { - const res = yield promise; - assert.equal(res.statusCode, code); - } catch (err) { - if (err.response) { - assert.equal(err.response.statusCode, code); - if (message) { - assert.equal(err.error || err.cause, message); - } - } - else throw err; - } - }); - }, - - expectError: function expectHttpCode(code, message, promise) { - if (arguments.length == 2) { - promise = arguments[1]; - message = undefined; - } - return co(function*(){ - try { - const res = yield promise; - assert.equal(res.statusCode, code); - } catch (err) { - if (err.response) { - assert.equal(err.response.statusCode, code); - if (message) { - let errorObj = typeof err.error == "string" ? JSON.parse(err.error) : err.error; - assert.equal(errorObj.message, message); - } - } - else throw err; - } - }); - }, - - expectJSON: async function expectJSON(promise, json) { - try { - const resJson = await promise; - Underscore.keys(json).forEach(function(key){ - resJson.should.have.property(key).equal(json[key]); - }); - } catch (err) { - if (err.response) { - assert.equal(err.response.statusCode, 200); - } - else throw err; - } - }, - - expectAnswer: function expectJSON(promise, testFunc) { - return co(function*(){ - try { - const res = yield promise; - return testFunc(res); - } catch (err) { - if (err.response) { - console.error(err.error); - assert.equal(err.response.statusCode, 200); - } - else throw err; - } - }); - } -}; diff --git a/test/integration/tools/node.js b/test/integration/tools/node.js deleted file mode 100644 index e4df8cda7..000000000 --- a/test/integration/tools/node.js +++ /dev/null @@ -1,335 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; -var co = require('co'); -const Underscore = require('../../../app/lib/common-libs/underscore').Underscore; -var async = require('async'); -var request = require('request'); -var contacter = require('../../../app/modules/crawler').CrawlerDependency.duniter.methods.contacter; -var duniter = require('../../../index'); -var multicaster = require('../../../app/lib/streams/multicaster'); -var ConfDTO = require('../../../app/lib/dto/ConfDTO').ConfDTO -var PeerDTO = require('../../../app/lib/dto/PeerDTO').PeerDTO -var http = require('./http'); -const bma = require('../../../app/modules/bma').BmaDependency.duniter.methods.bma; - -module.exports = function (dbName, options) { - return new Node(dbName, options); -}; - -module.exports.statics = { -}; - -var UNTIL_TIMEOUT = 20000; - -function Node (dbName, options) { - - var logger = require('../../../app/lib/logger').NewLogger(dbName); - var that = this; - var started = false; - that.server = null; - that.http = null; - - /** - * To be executed before tests - * @param scenarios Scenarios to execute: a suite of operations over a node (identities, certs, tx, blocks, ...). - * @returns {Function} Callback executed by unit test framework. - */ - this.before = function (scenarios) { - return function(done) { - async.waterfall([ - function (next) { - that.http = contacter(options.remoteipv4, options.remoteport); - that.executes(scenarios, next); - } - ], done); - }; - }; - - this.executes = function (scenarios, done) { - async.waterfall([ - function(next) { - async.forEachSeries(scenarios, function(useCase, callback) { - useCase(callback); - }, next); - } - ], done); - }; - - /** - * To be exectued after unit tests. Here: clean the database (removal) - * @returns {Function} Callback executed by unit test framework. - */ - this.after = function () { - return function (done) { - done(); - }; - }; - - /** - * Generates next block and submit it to local node. - * @returns {Function} - */ - this.commit = function(params) { - return function(done) { - async.waterfall([ - function(next) { - async.parallel({ - block: function(callback){ - co(function *() { - try { - const block2 = yield require('../../../app/modules/prover').ProverDependency.duniter.methods.generateTheNextBlock(that.server, params); - const trial2 = yield that.server.getBcContext().getIssuerPersonalizedDifficulty(that.server.keyPair.publicKey); - const block = yield require('../../../app/modules/prover').ProverDependency.duniter.methods.generateAndProveTheNext(that.server, block2, trial2, params); - callback(null, block); - } catch (e) { - callback(e); - } - }); - } - }, next); - }, - function(res, next) { - var block = res.block; - logger.debug(block.getRawSigned()); - post('/blockchain/block', { - "block": block.getRawSigned() - }, next); - } - ], function(err, res) { - done(err, res.body); - }); - }; - }; - - function post(uri, data, done) { - return new Promise((resolve, reject) => { - var postReq = request.post({ - "uri": 'http://' + [that.server.conf.remoteipv4, that.server.conf.remoteport].join(':') + uri, - "timeout": 1000 * 10, - "json": true - }, function (err, res, body) { - if (err) { - reject(err) - done && done(err) - } else { - resolve(res, body) - done && done(err, res, body) - } - }); - postReq.form(data); - }) - } - - this.startTesting = function(done) { - return new Promise(function(resolve, reject){ - if (started) return done(); - async.waterfall([ - function(next) { - service(next)(); - }, - function (server, next){ - // Launching server - that.server = server; - started = true; - server.PeeringService.generateSelfPeer(server.conf, 0) - .then(() => next()) - .catch(next) - }, - function (next) { - that.http = contacter(options.remoteipv4, options.remoteport); - next(); - } - ], function(err) { - err ? reject(err) : resolve(); - done && done(err); - }); - }); - }; - - function service(callback) { - return function () { - const stack = duniter.statics.simpleStack(); - stack.registerDependency({ - duniter: { - config: { - onLoading: (conf, program) => co(function*() { - const overConf = ConfDTO.complete(options); - Underscore.extend(conf, overConf); - }) - }, - service: { - process: (server) => Underscore.extend(server, { - startService: () => { - logger.debug('Server Servie Started!'); - } - }) - }, - cli: [{ - name: 'execute', - desc: 'Unit Test execution', - onDatabaseExecute: (server, conf, program, params, startServices) => co(function*() { - yield startServices(); - callback(null, server); - yield Promise.resolve((res) => null); // Never ending - }) - }] - } - }, 'duniter-automated-test'); - options.port = options.port || 10901; - options.ipv4 = options.ipv4 || "127.0.0.1"; - options.ipv6 = options.ipv6 || null; - options.remotehost = options.remotehost || null; - options.remoteipv4 = options.remoteipv4 || null; - options.remoteipv6 = options.remoteipv6 || null; - options.remoteport = options.remoteport || 10901; - const cliOptions = ['--ws2p-noupnp'] - if (options.port) { - cliOptions.push('--port') - cliOptions.push(options.port) - } - if (options.ipv4) { - cliOptions.push('--ipv4') - cliOptions.push(options.ipv4) - } - if (options.ipv6) { - cliOptions.push('--ipv6') - cliOptions.push(options.ipv6) - } - if (options.remotehost) { - cliOptions.push('--remoteh') - cliOptions.push(options.remotehost) - } - if (options.remoteipv4) { - cliOptions.push('--remote4') - cliOptions.push(options.remoteipv4) - } - if (options.remoteipv6) { - cliOptions.push('--remote6') - cliOptions.push(options.remoteipv6) - } - if (options.remoteport) { - cliOptions.push('--remotep') - cliOptions.push(options.remoteport) - } - - stack.registerDependency(require('../../../app/modules/keypair').KeypairDependency, 'duniter-keypair') - stack.registerDependency(require('../../../app/modules/bma').BmaDependency, 'duniter-bma') - stack.executeStack(['', '', '--mdb', dbName, '--memory', 'execute'].concat(cliOptions)); - }; - } - - /************************ - * TEST UTILITIES - ************************/ - - this.lookup = function(search, callback) { - return function(done) { - co(function*(){ - try { - const res = yield that.http.getLookup(search); - callback(res, done); - } catch (err) { - logger.error(err); - callback(null, done); - } - }); - }; - }; - - this.until = function (eventName, count) { - var counted = 0; - var max = count == undefined ? 1 : count; - return new Promise(function (resolve, reject) { - var finished = false; - that.server.on(eventName, function () { - counted++; - if (counted == max) { - if (!finished) { - finished = true; - resolve(); - } - } - }); - setTimeout(function() { - if (!finished) { - finished = true; - reject('Received ' + counted + '/' + count + ' ' + eventName + ' after ' + UNTIL_TIMEOUT + ' ms'); - } - }, UNTIL_TIMEOUT); - }); - }; - - this.block = function(number, callback) { - return function(done) { - co(function*(){ - try { - const res = yield that.http.getBlock(number); - callback(res, done); - } catch (err) { - logger.error(err); - callback(null, done); - } - }); - }; - }; - - this.summary = function(callback) { - return function(done) { - co(function*(){ - try { - const res = yield that.http.getSummary(); - callback(res, done); - } catch (err) { - logger.error(err); - callback(null, done); - } - }); - }; - }; - - this.peering = function(done) { - co(function*(){ - try { - const res = yield that.http.getPeer(); - done(null, res); - } catch (err) { - logger.error(err); - done(err); - } - }); - }; - - this.peeringP = () => that.http.getPeer(); - - this.submitPeer = function(peer, done) { - return post('/network/peering/peers', { - "peer": PeerDTO.fromJSONObject(peer).getRawSigned() - }, done); - }; - - this.submitPeerP = (peer) => new Promise((res, rej) => { - that.submitPeer(peer, (err, data) => { - if (err) return rej(err) - res(data) - }) - }) - - this.commitP = (params) => new Promise((res, rej) => { - this.commit(params)((err, data) => { - if (err) return rej(err) - res(data) - }) - }) -} diff --git a/test/integration/tools/shutDownEngine.js b/test/integration/tools/shutdown-engine.ts similarity index 74% rename from test/integration/tools/shutDownEngine.js rename to test/integration/tools/shutdown-engine.ts index ade3f2350..b58c37666 100644 --- a/test/integration/tools/shutDownEngine.js +++ b/test/integration/tools/shutdown-engine.ts @@ -11,11 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -const co = require('co') +import {TestingServer} from "./toolbox" -module.exports = (server) => co(function*() { - if (server._utProver) { - const farm = yield server._utProver.getWorker(); - return farm.shutDownEngine(); +export async function shutDownEngine(server:TestingServer) { + if ((server as any)._utProver) { + const farm = await (server as any)._utProver.getWorker() + return farm.shutDownEngine() } -}) +} diff --git a/test/integration/tools/sync.js b/test/integration/tools/test-sync.ts similarity index 70% rename from test/integration/tools/sync.js rename to test/integration/tools/test-sync.ts index de088fb00..5a3d13b74 100644 --- a/test/integration/tools/sync.js +++ b/test/integration/tools/test-sync.ts @@ -11,17 +11,16 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {Server} from "../../../server" -const co = require('co'); const Underscore = require('../../../app/lib/common-libs/underscore').Underscore; const rp = require('request-promise'); -module.exports = function makeBlockAndPost(fromBlock, toBlock, fromServer, toServer) { +export function sync(fromBlock:number, toBlock:number, fromServer:Server, toServer:Server) { // Sync blocks - return Underscore.range(fromBlock, toBlock + 1).reduce((p, number) => co(function*(){ - yield p; - const json = yield rp('http://' + fromServer.conf.ipv4 + ':' + fromServer.conf.port + '/blockchain/block/' + number, { json: true }); - yield toServer.writeBlock(json) - }), Promise.resolve()); -}; + return Underscore.range(fromBlock, toBlock + 1).reduce(async (p:Promise<any>, number:number) => { + await p; + const json = await rp('http://' + fromServer.conf.ipv4 + ':' + fromServer.conf.port + '/blockchain/block/' + number, { json: true }); + await toServer.writeBlock(json) + }, Promise.resolve()) +} diff --git a/test/integration/tools/until.js b/test/integration/tools/test-until.ts similarity index 79% rename from test/integration/tools/until.js rename to test/integration/tools/test-until.ts index 3d45be8f4..4c05899ea 100644 --- a/test/integration/tools/until.js +++ b/test/integration/tools/test-until.ts @@ -11,16 +11,16 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {TestingServer} from "./toolbox" -var UNTIL_TIMEOUT = 115000; +const UNTIL_TIMEOUT = 115000; -module.exports = function (server, eventName, count) { - var counted = 0; - var max = count == undefined ? 1 : count; +export function until(server:TestingServer, eventName:string, count:number) { + let counted = 0; + const max = count == undefined ? 1 : count; return new Promise(function (resolve, reject) { - var finished = false; - server.on(eventName, function () { + let finished = false; + server._server.on(eventName, function () { counted++; if (counted == max) { if (!finished) { @@ -36,4 +36,4 @@ module.exports = function (server, eventName, count) { } }, UNTIL_TIMEOUT); }); -}; +} diff --git a/test/integration/tools/toolbox.ts b/test/integration/tools/toolbox.ts index e2ed9285c..d79b97f8a 100644 --- a/test/integration/tools/toolbox.ts +++ b/test/integration/tools/toolbox.ts @@ -42,17 +42,19 @@ import {WS2PClient} from "../../../app/modules/ws2p/lib/WS2PClient" import {DBBlock} from "../../../app/lib/db/DBBlock" import {DBPeer} from "../../../app/lib/db/DBPeer" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {BmaDependency} from "../../../app/modules/bma/index" +import {NewLogger} from "../../../app/lib/logger" +import {BlockProver} from "../../../app/modules/prover/lib/blockProver" +import {DataErrors} from "../../../app/lib/common-libs/errors" +import {until} from "./test-until" +import {sync} from "./test-sync" +import {expectAnswer, expectError, expectJSON} from "./http-expect" const assert = require('assert'); const rp = require('request-promise'); const es = require('event-stream'); const WebSocketServer = require('ws').Server -const httpTest = require('../tools/http'); -const sync = require('../tools/sync'); -const commit = require('../tools/commit'); -const until = require('../tools/until'); -const bma = require('../../../app/modules/bma').BmaDependency.duniter.methods.bma; -const logger = require('../../../app/lib/logger').NewLogger('toolbox'); +const logger = NewLogger(); require('../../../app/modules/bma').BmaDependency.duniter.methods.noLimit(); // Disables the HTTP limiter @@ -311,7 +313,7 @@ export const waitForHeads = async (server:Server, nbHeads:number) => { export class TestingServer { private prover:Prover - private permaProver:PermanentProver + public permaProver:PermanentProver public bma:BmaApi constructor( @@ -431,7 +433,7 @@ export class TestingServer { async initDalBmaConnections() { await this.server.initWithDAL() - const bmapi = await bma(this.server) + const bmapi = await BmaDependency.duniter.methods.bma(this.server) this.bma = bmapi const res = await bmapi.openConnections() return res @@ -451,34 +453,53 @@ export class TestingServer { expect(uri:string, expectations:any) { - return typeof expectations == 'function' ? httpTest.expectAnswer(rp(this.url(uri), { json: true }), expectations) : httpTest.expectJSON(rp(this.url(uri), { json: true }), expectations); + return typeof expectations == 'function' ? expectAnswer(rp(this.url(uri), { json: true }), expectations) : expectJSON(rp(this.url(uri), { json: true }), expectations); } expectThat(uri:string, expectations:any) { - return httpTest.expectAnswer(rp(this.url(uri), { json: true }), expectations); + return expectAnswer(rp(this.url(uri), { json: true }), expectations); } expectJSON(uri:string, expectations:any) { - return httpTest.expectJSON(rp(this.url(uri), { json: true }), expectations); + return expectJSON(rp(this.url(uri), { json: true }), expectations); } expectError(uri:string, code:number, message = '') { - return httpTest.expectError(code, message, rp(this.url(uri), { json: true })); + return expectError(code, message, rp(this.url(uri), { json: true })); } - syncFrom(otherServer:Server, fromIncuded:number, toIncluded:number) { return sync(fromIncuded, toIncluded, otherServer, this.server); } - until(type:string, count:number) { - return until(this.server, type, count); + return until(this, type, count); + } + + async justCommit(options:any = null) { + const proven = await this.generateNext(options) + await this.server.writeBlock(proven, true, false) + return proven } - async commit(options:any = null, noWait = false) { - const raw = await commit(this.server, null, noWait)(options); - return JSON.parse(raw); + async commit(options:any = null) { + const proven = await this.generateNext(options) + await this.server.writeBlock(proven, true, true) // The resolution is done manually + const blocksResolved = await this.server.BlockchainService.blockResolution() + if (!blocksResolved) { + throw Error(DataErrors[DataErrors.BLOCK_WASNT_COMMITTED]) + } + return blocksResolved + } + + private generateNext(options:any) { + const server = this.server as any + // Brings a priver to the server + if (!server._utProver) { + server._utProver = new BlockProver(server) + server._utGenerator = ProverDependency.duniter.methods.blockGenerator(server, server._utProver) + } + return server._utGenerator.makeNextBlock(null, null, options) } async commitWaitError(options:any, expectedError:string) { @@ -491,8 +512,8 @@ export class TestingServer { })) }), (async () => { - const raw = await commit(this.server, null, true)(options); - return JSON.parse(raw); + const proven = await this.generateNext(options) + await this.server.writeBlock(proven, false) })() ]) return results[1] @@ -500,8 +521,7 @@ export class TestingServer { async commitExpectError(options:any) { try { - const raw = await commit(this.server)(options); - JSON.parse(raw); + await this.commit(options) throw { message: 'Commit operation should have thrown an error' }; } catch (e) { if (e.statusCode) { @@ -598,7 +618,7 @@ export class TestingServer { async prepareForNetwork() { await this.server.initWithDAL(); - const bmaAPI = await bma(this.server); + const bmaAPI = await BmaDependency.duniter.methods.bma(this.server); await bmaAPI.openConnections(); this.bma = bmaAPI; RouterDependency.duniter.methods.routeToNetwork(this.server) diff --git a/test/integration/tools/unit.js b/test/integration/tools/unit.js deleted file mode 100644 index f92646ce2..000000000 --- a/test/integration/tools/unit.js +++ /dev/null @@ -1,41 +0,0 @@ -// Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1 -// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -"use strict"; - -var should = require('should'); -var co = require('co'); - -module.exports = { - - shouldFail: (promise, message) => co(function *() { - try { - yield promise; - throw { "message": '{ "message": "Should have thrown an error" }' }; - } catch(e) { - e.should.have.property('message').equal(message); - } - }), - - shouldNotFail: (promise) => co(function *() { - try { - yield promise; - } catch(e) { - let err = e; - if (typeof e === 'string') { - err = JSON.parse(e.message); - } - should.not.exist(err); - } - }) -}; diff --git a/test/integration/transactions-chaining.ts b/test/integration/transactions-chaining.ts index 7b1142b2b..3511ddfd2 100644 --- a/test/integration/transactions-chaining.ts +++ b/test/integration/transactions-chaining.ts @@ -14,11 +14,11 @@ import {CommonConstants} from "../../app/lib/common-libs/constants" import {TestUser} from "./tools/TestUser" import {TestingServer} from "./tools/toolbox" +import {shouldNotFail} from "../unit-tools" const should = require('should'); const assert = require('assert'); const toolbox = require('./tools/toolbox'); -const unit = require('./tools/unit'); describe("Transaction chaining", () => { @@ -81,8 +81,8 @@ describe("Transaction chaining", () => { }); const tmp = CommonConstants.TRANSACTION_MAX_TRIES; CommonConstants.TRANSACTION_MAX_TRIES = 2; - await unit.shouldNotFail(toc.sendTX(tx1)); - await unit.shouldNotFail(toc.sendTX(tx2)); + await shouldNotFail(toc.sendTX(tx1)); + await shouldNotFail(toc.sendTX(tx2)); (await s1.get('/tx/sources/DKpQPUL4ckzXYdnDRvCRKAm1gNvSdmAXnTrJZ7LvM5Qo')).should.have.property('sources').length(1); // 1200 (await s1.get('/tx/sources/DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV')).should.have.property('sources').length(1); // 1200 await s1.commit({ time: now + 7210 }); // TX1 commited only @@ -110,13 +110,13 @@ describe("Transaction chaining", () => { let tx7 = await tic.prepareUTX(tx6, ['SIG(0)'], [{ qty: 1200, base: 0, lock: 'SIG(' + toc.pub + ')' }], { blockstamp, comment: "PING-PONG TX7" }); const tmp = CommonConstants.TRANSACTION_MAX_TRIES; CommonConstants.TRANSACTION_MAX_TRIES = 2; - await unit.shouldNotFail(toc.sendTX(tx1)); - await unit.shouldNotFail(toc.sendTX(tx2)); - await unit.shouldNotFail(toc.sendTX(tx3)); - await unit.shouldNotFail(toc.sendTX(tx4)); - await unit.shouldNotFail(toc.sendTX(tx5)); - await unit.shouldNotFail(toc.sendTX(tx6)); - await unit.shouldNotFail(toc.sendTX(tx7)); + await shouldNotFail(toc.sendTX(tx1)); + await shouldNotFail(toc.sendTX(tx2)); + await shouldNotFail(toc.sendTX(tx3)); + await shouldNotFail(toc.sendTX(tx4)); + await shouldNotFail(toc.sendTX(tx5)); + await shouldNotFail(toc.sendTX(tx6)); + await shouldNotFail(toc.sendTX(tx7)); await s1.commitWaitError({ dontCareAboutChaining: true }, 'The maximum transaction chaining length per block is 5') CommonConstants.TRANSACTION_MAX_TRIES = tmp; }) diff --git a/test/integration/transactions-csv-cltv-sig.ts b/test/integration/transactions-csv-cltv-sig.ts index 57e4ac69a..a9ada9607 100644 --- a/test/integration/transactions-csv-cltv-sig.ts +++ b/test/integration/transactions-csv-cltv-sig.ts @@ -18,7 +18,6 @@ import {Buid} from "../../app/lib/common-libs/buid" describe("Transaction: CSV+CLTV+1of2SIG", function() { const now = 1500000000 - const DONT_WAIT_FOR_BLOCKCHAIN_CHANGE = true let s1:TestingServer let cat:any let tac:any @@ -59,7 +58,7 @@ describe("Transaction: CSV+CLTV+1of2SIG", function() { }) txHash = hashf(tx) await cat.sendTX(tx) - const block = await s1.commit({ time: now }, DONT_WAIT_FOR_BLOCKCHAIN_CHANGE) + const block = await s1.justCommit({ time: now }) block.should.have.property('transactions').length(1) await s1.waitToHaveBlock(2) }) @@ -79,7 +78,7 @@ describe("Transaction: CSV+CLTV+1of2SIG", function() { blockstamp: Buid.format.buid(current) }) await tac.sendTX(tx) - const block = await s1.commit(null, DONT_WAIT_FOR_BLOCKCHAIN_CHANGE) + const block = await s1.justCommit(null) block.should.have.property('transactions').length(1) }) diff --git a/test/integration/transactions/transaction-crosschain.ts b/test/integration/transactions/transaction-crosschain.ts index 463e77f4e..2ea332e92 100644 --- a/test/integration/transactions/transaction-crosschain.ts +++ b/test/integration/transactions/transaction-crosschain.ts @@ -15,12 +15,12 @@ import {NewTestingServer, TestingServer} from "../tools/toolbox" import {TestUser} from "../tools/TestUser" import {Underscore} from "../../../app/lib/common-libs/underscore" import {HttpSources} from "../../../app/modules/bma/lib/dtos" +import {shouldFail, shouldNotFail} from "../../unit-tools" +import {expectAnswer} from "../tools/http-expect" const assert = require('assert'); const should = require('should'); const rp = require('request-promise'); -const unit = require('../tools/unit'); -const httpTest = require('../tools/http'); /** * Test Crosschain algorithm described at https://en.bitcoin.it/wiki/Atomic_cross-chain_trading @@ -163,8 +163,8 @@ describe("Crosschain transactions", function() { /** * Note: the ROLLBACK transactions have a locktime, and cannot be used before that delay. */ - await unit.shouldFail(ticM.sendTX(mtx4), 'Locktime not elapsed yet'); - await unit.shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); + await shouldFail(ticM.sendTX(mtx4), 'Locktime not elapsed yet'); + await shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); /** * Let's say TOC agrees & and start COMMIT. @@ -186,8 +186,8 @@ describe("Crosschain transactions", function() { * Now the transaction is fully COMMITTED! Look at rollback transactions: they will fail. */ - await unit.shouldFail(tocB.sendTX(btx2), 'Source already consumed'); - await unit.shouldFail(ticM.sendTX(mtx4), 'Source already consumed'); + await shouldFail(tocB.sendTX(btx2), 'Source already consumed'); + await shouldFail(ticM.sendTX(mtx4), 'Source already consumed'); }) it('toc should now have 0 BETA_BROUZOUF from Transaction sources due to COMMIT', () => { @@ -348,15 +348,15 @@ describe("Crosschain transactions", function() { /** * Note: the ROLLBACK transactions have a locktime, and cannot be used before that delay. */ - await unit.shouldFail(ticM.sendTX(mtx4), 'Locktime not elapsed yet'); - await unit.shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); + await shouldFail(ticM.sendTX(mtx4), 'Locktime not elapsed yet'); + await shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); // Increment the medianTime by 1 await sM.commit({ time: now + 12 }); await sB.commit({ time: now + 14 }); - await unit.shouldNotFail(ticM.sendTX(mtx4)); // tic can rollback early (24h in real case) if toc does not reveal X - await unit.shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); // This one has a longer locktime (48h in real case) + await shouldNotFail(ticM.sendTX(mtx4)); // tic can rollback early (24h in real case) if toc does not reveal X + await shouldFail(tocB.sendTX(btx2), 'Locktime not elapsed yet'); // This one has a longer locktime (48h in real case) // Rollback for TIC(M) should be done await sM.commit({ time: now + 12 }); @@ -364,7 +364,7 @@ describe("Crosschain transactions", function() { // Make the medianTime increment by 1 await sB.commit({ time: now + 14 }); - await unit.shouldNotFail(tocB.sendTX(btx2)); // toc can rollback now (48h has passed). He has not revealed X, so he is safe. + await shouldNotFail(tocB.sendTX(btx2)); // toc can rollback now (48h has passed). He has not revealed X, so he is safe. await sB.commit({ time: now + 14 }); /** @@ -377,8 +377,8 @@ describe("Crosschain transactions", function() { // Assuming X was revealed ... but actually it is not since TOCM did succeed to send the TX let btx6 = await ticB.prepareUTX(btx1, ['XHX(1872767826647264) SIG(0)'], [{ qty: 120, base: 0, lock: 'SIG(' + ticB.pub + ')' }], { comment: 'tic takes money on BETA_BROUZOUF', blockstamp: blockstampB }); - await unit.shouldFail(tocB.sendTX(btx6), 'Source already consumed'); - await unit.shouldFail(ticM.sendTX(mtx5), 'Source already consumed'); + await shouldFail(tocB.sendTX(btx6), 'Source already consumed'); + await shouldFail(ticM.sendTX(mtx5), 'Source already consumed'); }) it('toc should now have 120 BETA_BROUZOUF from Transaction sources due to rollback TX', () => checkHaveSources(tocB, 1, 120)); @@ -390,7 +390,7 @@ describe("Crosschain transactions", function() { }); function checkHaveSources(theUser:TestUser, sourcesCount:number, sourcesTotalAmount:number) { - return httpTest.expectAnswer(rp('http://' + theUser.node.server.conf.ipv4 + ':' + theUser.node.server.conf.port + '/tx/sources/' + theUser.pub, { json: true }), (res:HttpSources) => { + return expectAnswer(rp('http://' + theUser.node.server.conf.ipv4 + ':' + theUser.node.server.conf.port + '/tx/sources/' + theUser.pub, { json: true }), (res:HttpSources) => { const txRes = Underscore.where(res.sources, { type: 'T' }) txRes.should.have.length(sourcesCount); let sum = 0; diff --git a/test/integration/transactions-pruning.js b/test/integration/transactions/transactions-pruning.ts similarity index 63% rename from test/integration/transactions-pruning.js rename to test/integration/transactions/transactions-pruning.ts index 617d5c549..c680ab8c9 100644 --- a/test/integration/transactions-pruning.js +++ b/test/integration/transactions/transactions-pruning.ts @@ -11,23 +11,20 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -"use strict"; +import {TestUser} from "../tools/TestUser" +import {CommonConstants} from "../../../app/lib/common-libs/constants" +import {NewTestingServer, TestingServer} from "../tools/toolbox" +import {HttpBlock, HttpTxHistory} from "../../../app/modules/bma/lib/dtos" -const co = require('co'); const should = require('should'); -const TestUser = require('./tools/TestUser').TestUser -const commit = require('./tools/commit'); -const toolbox = require('./tools/toolbox'); -const constants = require('../../app/lib/constants'); -const CommonConstants = require('../../app/lib/common-libs/constants').CommonConstants -let s1, cat1, tac1 +let s1:TestingServer, cat1:TestUser, tac1:TestUser describe("Transactions pruning", function() { - before(() => co(function*() { + before(async () => { - s1 = toolbox.server({ + s1 = NewTestingServer({ currency: 'currency_one', dt: 600, pair: { @@ -39,25 +36,25 @@ describe("Transactions pruning", function() { cat1 = new TestUser('cat', { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', sec: '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP'}, { server: s1 }); tac1 = new TestUser('tac', { pub: '2LvDg21dVXvetTD9GdkPLURavLYEqP3whauvPWX4c2qc', sec: '2HuRLWgKgED1bVio1tdpeXrf7zuUszv1yPHDsDj7kcMC4rVSN9RC58ogjtKNfTbH1eFz7rn38U1PywNs3m6Q7UxE'}, { server: s1 }); - yield s1.prepareForNetwork(); + await s1.prepareForNetwork(); - const now = parseInt(Date.now() / 1000); + const now = parseInt(String(Date.now() / 1000)) // Publishing identities - yield cat1.createIdentity(); - yield tac1.createIdentity(); - yield cat1.cert(tac1); - yield tac1.cert(cat1); - yield cat1.join(); - yield tac1.join(); - yield s1.commit(); - yield s1.commit({ + await cat1.createIdentity(); + await tac1.createIdentity(); + await cat1.cert(tac1); + await tac1.cert(cat1); + await cat1.join(); + await tac1.join(); + await s1.commit(); + await s1.commit({ time: now + 1300 }); - yield s1.commit(); - yield cat1.send(20, tac1); - yield cat1.send(100, tac1); - })); + await s1.commit(); + await cat1.sendMoney(20, tac1) + await cat1.sendMoney(100, tac1) + }) after(() => { return Promise.all([ @@ -65,27 +62,27 @@ describe("Transactions pruning", function() { ]) }) - it('double spending transactions should both exist first', () => s1.expect('/tx/history/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res) => { + it('double spending transactions should both exist first', () => s1.expect('/tx/history/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res:HttpTxHistory) => { res.history.should.have.property('sending').length(2); })); - it('should only commit 1 tx', () => co(function*() { - yield s1.commit(); - yield s1.expect('/blockchain/block/2', (res) => { + it('should only commit 1 tx', async () => { + await s1.commit(); + await s1.expect('/blockchain/block/2', (res:HttpBlock) => { res.should.have.property('transactions').length(0); }); - yield s1.expect('/blockchain/block/3', (res) => { + await s1.expect('/blockchain/block/3', (res:HttpBlock) => { res.should.have.property('transactions').length(1); }); - })); + }) - it('double spending transaction should have been pruned', () => co(function*() { + it('double spending transaction should have been pruned', async () => { const tmp = CommonConstants.TRANSACTION_MAX_TRIES; CommonConstants.TRANSACTION_MAX_TRIES = 1; - yield s1.commit(); - yield s1.expect('/tx/history/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res) => { + await s1.commit(); + await s1.expect('/tx/history/HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', (res:HttpTxHistory) => { res.history.should.have.property('sending').length(0); }); CommonConstants.TRANSACTION_MAX_TRIES = tmp; - })); -}); + }) +}) diff --git a/test/integration/wot/wotb.ts b/test/integration/wot/wotb.ts index 7ea0074d4..4ace7d46a 100644 --- a/test/integration/wot/wotb.ts +++ b/test/integration/wot/wotb.ts @@ -12,15 +12,13 @@ // GNU Affero General Public License for more details. import {TestUser} from "../tools/TestUser" -import {TestingServer} from "../tools/toolbox" +import {NewTestingServer, TestingServer} from "../tools/toolbox" import {BmaDependency} from "../../../app/modules/bma/index" import {WoTBInstance} from "../../../app/lib/wot" import {Underscore} from "../../../app/lib/common-libs/underscore" +import {shutDownEngine} from "../tools/shutdown-engine" const should = require('should'); -const duniter = require('../../../index'); -const commit = require('../tools/commit'); -const shutDownEngine = require('../tools/shutDownEngine'); const MEMORY_MODE = true; const commonConf = { @@ -59,10 +57,10 @@ describe("WOTB module", () => { let wotb:WoTBInstance before(async () => { - s1 = duniter( - '/bb11', - MEMORY_MODE, + s1 = NewTestingServer( Underscore.extend({ + name: 'bb11', + memory: MEMORY_MODE, port: '9337', pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', @@ -72,10 +70,10 @@ describe("WOTB module", () => { sigQty: 1, dt: 1, ud0: 120 }, commonConf)); - s2 = duniter( - '/bb41', - MEMORY_MODE, + s2 = NewTestingServer( Underscore.extend({ + name: 'bb41', + memory: MEMORY_MODE, port: '9338', pair: { pub: 'HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', @@ -86,10 +84,10 @@ describe("WOTB module", () => { msValidity: 400 // Memberships expire after 400 second delay }, commonConf)); - s3 = duniter( - '/bb11', - MEMORY_MODE, + s3 = NewTestingServer( Underscore.extend({ + name: 'bb11', + memory: MEMORY_MODE, port: '9339', pair: { pub: 'DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV', @@ -123,10 +121,10 @@ describe("WOTB module", () => { await cat.cert(toc); await cat.join(); await toc.join(); - await commit(s1)({ + await s1.commit({ time: now + 500 }); - await commit(s1)({ + await s1.commit({ time: now + 500 }); }) @@ -160,7 +158,7 @@ describe("WOTB module", () => { await tic.createIdentity(); await toc.cert(tic); await tic.join(); - await commit(s1)(); + await s1.commit(); let itic = await s1.dal.getWrittenIdtyByUIDForWotbId("tic"); itic.should.have.property('wotb_id').equal(2); wotb.isEnabled(2).should.equal(true); @@ -197,26 +195,26 @@ describe("WOTB module", () => { await cat2.join(); await toc2.join(); await tic2.join(); - await commit(s2)({ + await s2.commit({ time: now }); // Should make MS expire for toc2 - await commit(s2)({ + await s2.commit({ time: now + 500 }); - await commit(s2)({ + await s2.commit({ time: now + 600 }); await cat2.join(); // Renew for not to be kicked! await tic2.join(); // Renew for not to be kicked! - await commit(s2)({ + await s2.commit({ time: now + 800 }); - await commit(s2)({ + await s2.commit({ time: now + 800 }); // Members excluded - await commit(s2)({ + await s2.commit({ time: now + 800 }); }); @@ -244,7 +242,7 @@ describe("WOTB module", () => { it('a leaver who joins back should be enabled', async () => { await toc2.join(); - await commit(s2)(); + await s2.commit(); wotb.isEnabled(0).should.equal(true); wotb.isEnabled(1).should.equal(true); wotb.isEnabled(2).should.equal(true); @@ -283,8 +281,8 @@ describe("WOTB module", () => { }) it('two first commits: the WoT is new and OK', async () => { - await commit(s3)({ time: now }); - await commit(s3)({ + await s3.commit({ time: now }); + await s3.commit({ time: now + 1200 }); /** @@ -301,14 +299,14 @@ describe("WOTB module", () => { }); it('third & fourth commits: toc should have joined', async () => { - await commit(s3)({ + await s3.commit({ time: now + 2400 }); // MedianTime is now +500 for next certs await toc3.createIdentity(); await toc3.join(); await tic3.cert(toc3); - await commit(s3)({ + await s3.commit({ time: now + 4000 }); // MedianTime is now +1000 for next certs @@ -328,7 +326,7 @@ describe("WOTB module", () => { it('fifth commit: cat still here, but not its certs', async () => { await toc3.cert(tic3); - await commit(s3)({ + await s3.commit({ time: now + 4000 }); /** @@ -346,7 +344,7 @@ describe("WOTB module", () => { }); it('sixth commit: cat is gone with its certs', async () => { - await commit(s3)({ + await s3.commit({ time: now + 2500 }); /** @@ -366,7 +364,7 @@ describe("WOTB module", () => { it('seventh commit: toc is gone, but not its cert to tic', async () => { await tic3.cert(cat3); await cat3.join(); - await commit(s3)({ + await s3.commit({ time: now + 5000 }); /** diff --git a/test/integration/ws2p_client_limitations.ts b/test/integration/ws2p/ws2p_client_limitations.ts similarity index 98% rename from test/integration/ws2p_client_limitations.ts rename to test/integration/ws2p/ws2p_client_limitations.ts index 06c6ac6a8..073d71f16 100644 --- a/test/integration/ws2p_client_limitations.ts +++ b/test/integration/ws2p/ws2p_client_limitations.ts @@ -19,9 +19,9 @@ import { TestingServer, waitForkWS2PConnection, waitForkWS2PDisconnection -} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') diff --git a/test/integration/ws2p_cluster.ts b/test/integration/ws2p/ws2p_cluster.ts similarity index 96% rename from test/integration/ws2p_cluster.ts rename to test/integration/ws2p/ws2p_cluster.ts index a7b9919ab..34a30d159 100644 --- a/test/integration/ws2p_cluster.ts +++ b/test/integration/ws2p/ws2p_cluster.ts @@ -18,10 +18,10 @@ import { simpleUser, TestingServer, waitForkWS2PConnection -} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" -import {TestUser} from './tools/TestUser'; +} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" +import {TestUser} from '../tools/TestUser'; const assert = require('assert') diff --git a/test/integration/ws2p_connection.ts b/test/integration/ws2p/ws2p_connection.ts similarity index 97% rename from test/integration/ws2p_connection.ts rename to test/integration/ws2p/ws2p_connection.ts index c62159d74..268e1b8e3 100644 --- a/test/integration/ws2p_connection.ts +++ b/test/integration/ws2p/ws2p_connection.ts @@ -17,17 +17,18 @@ import { WS2PPubkeyLocalAuth, WS2PPubkeyRemoteAuth, WS2PRemoteAuth -} from "../../app/modules/ws2p/lib/WS2PConnection" -import {Key, verify} from "../../app/lib/common-libs/crypto/keyring" -import {getNewTestingPort} from "./tools/toolbox" -import {WS2PMessageHandler} from "../../app/modules/ws2p/lib/impl/WS2PMessageHandler" -import {WS2PResponse} from "../../app/modules/ws2p/lib/impl/WS2PResponse" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" -import {assertThrows} from "../unit-tools" +} from "../../../app/modules/ws2p/lib/WS2PConnection" +import {Key, verify} from "../../../app/lib/common-libs/crypto/keyring" +import {getNewTestingPort} from "../tools/toolbox" +import {WS2PMessageHandler} from "../../../app/modules/ws2p/lib/impl/WS2PMessageHandler" +import {WS2PResponse} from "../../../app/modules/ws2p/lib/impl/WS2PResponse" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" +import {assertThrows} from "../../unit-tools" +import {NewLogger} from "../../../app/lib/logger" const assert = require('assert'); const WebSocketServer = require('ws').Server -const logger = require('../../app/lib/logger').NewLogger('ws2p') +const logger = NewLogger() const gtest = "gtest" describe('WS2P', () => { diff --git a/test/integration/ws2p_doc_sharing.ts b/test/integration/ws2p/ws2p_doc_sharing.ts similarity index 96% rename from test/integration/ws2p_doc_sharing.ts rename to test/integration/ws2p/ws2p_doc_sharing.ts index ff8e132b4..0de1ee131 100644 --- a/test/integration/ws2p_doc_sharing.ts +++ b/test/integration/ws2p/ws2p_doc_sharing.ts @@ -11,9 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {TestUser} from './tools/TestUser'; -import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "./tools/toolbox" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +import {TestUser} from '../tools/TestUser'; +import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "../tools/toolbox" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') diff --git a/test/integration/ws2p_docpool.ts b/test/integration/ws2p/ws2p_docpool.ts similarity index 92% rename from test/integration/ws2p_docpool.ts rename to test/integration/ws2p/ws2p_docpool.ts index c155be922..1e7c5dde7 100644 --- a/test/integration/ws2p_docpool.ts +++ b/test/integration/ws2p/ws2p_docpool.ts @@ -11,10 +11,10 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {ProverDependency} from "../../app/modules/prover/index" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {ProverDependency} from "../../../app/modules/prover/index" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') diff --git a/test/integration/ws2p_exchange.ts b/test/integration/ws2p/ws2p_exchange.ts similarity index 81% rename from test/integration/ws2p_exchange.ts rename to test/integration/ws2p/ws2p_exchange.ts index 90b43facb..490596c98 100644 --- a/test/integration/ws2p_exchange.ts +++ b/test/integration/ws2p/ws2p_exchange.ts @@ -11,14 +11,14 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {WS2PConnection} from "../../app/modules/ws2p/lib/WS2PConnection" -import {Key} from "../../app/lib/common-libs/crypto/keyring" -import {newWS2PBidirectionnalConnection} from "./tools/toolbox" -import {WS2PRequester} from "../../app/modules/ws2p/lib/WS2PRequester" -import {BlockDTO} from "../../app/lib/dto/BlockDTO" -import {WS2PMessageHandler} from "../../app/modules/ws2p/lib/impl/WS2PMessageHandler" -import {WS2PResponse} from "../../app/modules/ws2p/lib/impl/WS2PResponse" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +import {WS2PConnection} from "../../../app/modules/ws2p/lib/WS2PConnection" +import {Key} from "../../../app/lib/common-libs/crypto/keyring" +import {newWS2PBidirectionnalConnection} from "../tools/toolbox" +import {WS2PRequester} from "../../../app/modules/ws2p/lib/WS2PRequester" +import {BlockDTO} from "../../../app/lib/dto/BlockDTO" +import {WS2PMessageHandler} from "../../../app/modules/ws2p/lib/impl/WS2PMessageHandler" +import {WS2PResponse} from "../../../app/modules/ws2p/lib/impl/WS2PResponse" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert'); describe('WS2P exchange', () => { diff --git a/test/integration/ws2p_heads.ts b/test/integration/ws2p/ws2p_heads.ts similarity index 96% rename from test/integration/ws2p_heads.ts rename to test/integration/ws2p/ws2p_heads.ts index d5a2b9fc1..07fbd8e1c 100644 --- a/test/integration/ws2p_heads.ts +++ b/test/integration/ws2p/ws2p_heads.ts @@ -11,9 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {getNewTestingPort, simpleTestingConf, simpleTestingServer, simpleUser, TestingServer} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +import {getNewTestingPort, simpleTestingConf, simpleTestingServer, simpleUser, TestingServer} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') const should = require('should') diff --git a/test/integration/ws2p_network.ts b/test/integration/ws2p/ws2p_network.ts similarity index 95% rename from test/integration/ws2p_network.ts rename to test/integration/ws2p/ws2p_network.ts index 2d7a776a7..cd3163ec1 100644 --- a/test/integration/ws2p_network.ts +++ b/test/integration/ws2p/ws2p_network.ts @@ -11,9 +11,9 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {getNewTestingPort, simpleTestingConf, simpleTestingServer, simpleUser, TestingServer} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +import {getNewTestingPort, simpleTestingConf, simpleTestingServer, simpleUser, TestingServer} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') diff --git a/test/integration/ws2p_pulling.ts b/test/integration/ws2p/ws2p_pulling.ts similarity index 93% rename from test/integration/ws2p_pulling.ts rename to test/integration/ws2p/ws2p_pulling.ts index 8170c14fc..52f7aaaf4 100644 --- a/test/integration/ws2p_pulling.ts +++ b/test/integration/ws2p/ws2p_pulling.ts @@ -11,11 +11,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. -import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" -import {WS2PClient} from "../../app/modules/ws2p/lib/WS2PClient" -import {TestUser} from "./tools/TestUser" +import {simpleTestingConf, simpleTestingServer, simpleUser, simpleWS2PNetwork, TestingServer} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" +import {WS2PClient} from "../../../app/modules/ws2p/lib/WS2PClient" +import {TestUser} from "../tools/TestUser" const assert = require('assert') diff --git a/test/integration/ws2p_server_limitations.ts b/test/integration/ws2p/ws2p_server_limitations.ts similarity index 98% rename from test/integration/ws2p_server_limitations.ts rename to test/integration/ws2p/ws2p_server_limitations.ts index 88a15f9b1..36520b9c1 100644 --- a/test/integration/ws2p_server_limitations.ts +++ b/test/integration/ws2p/ws2p_server_limitations.ts @@ -19,9 +19,9 @@ import { TestingServer, waitForkWS2PConnection, waitForkWS2PDisconnection -} from "./tools/toolbox" -import {WS2PCluster} from "../../app/modules/ws2p/lib/WS2PCluster" -import {WS2PConstants} from "../../app/modules/ws2p/lib/constants" +} from "../tools/toolbox" +import {WS2PCluster} from "../../../app/modules/ws2p/lib/WS2PCluster" +import {WS2PConstants} from "../../../app/modules/ws2p/lib/constants" const assert = require('assert') -- GitLab