diff --git a/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts b/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts deleted file mode 100644 index f666637341..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts +++ /dev/null @@ -1,217 +0,0 @@ -import type { Request } from "express"; -import { getLogger } from "log4js"; -import { RequestInfo } from "./RequestInfo"; - -import { TradeInfo } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TradeInfo"; -import { transactionManagement } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/routes/index"; -import { verifierFactory } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/routes/index"; -import { BusinessLogicBase } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/business-logic-plugin/BusinessLogicBase"; -import { Verifier } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/Verifier"; -import { LedgerEvent } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/LedgerPlugin"; -import { json2str } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon"; - -const fs = require("fs"); -const yaml = require("js-yaml"); - -const config: any = yaml.safeLoad( - fs.readFileSync("/etc/cactus/default.yaml", "utf8"), -); - -// Setup logger -const moduleName = "BusinessLogicCheckEthereumValidator"; -const logger = getLogger(`${moduleName}`); -logger.level = config.logLevel; - -export class BusinessLogicCheckEthereumValidator extends BusinessLogicBase { - businessLogicID: string; - - constructor(businessLogicID: string) { - super(); - this.businessLogicID = businessLogicID; - } - - startTransaction(req: Request, businessLogicID: string, tradeID: string) { - logger.debug(` ##startTransaction(): called startTransaction()`); - - const requestInfo: RequestInfo = new RequestInfo(); - requestInfo.setBusinessLogicID(businessLogicID); - requestInfo.setTradeID(tradeID); - - const tradeInfo: TradeInfo = new TradeInfo( - requestInfo.businessLogicID, - requestInfo.tradeID, - ); - - this.startMonitor(tradeInfo); - } - - startMonitor(tradeInfo: TradeInfo) { - logger.debug( - `##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}`, - ); - - const validator = this.getValidator(tradeInfo); - - if (config.monitorMode === true) { - logger.debug(`##startMonitor(): Creating validator with Monitor Mode`); - } else { - logger.debug(`##startMonitor(): Creating validator without Monitor Mode`) - } - - const verifier = this.getVerifier(validator); - - this.sendTestRequest(verifier); - } - - private getValidator(tradeInfo: TradeInfo) { - logger.debug(`##getValidator(): Getting validator with tradeInfo: ${tradeInfo}`); - const validator = JSON.parse( - transactionManagement.getValidatorToUse(tradeInfo.businessLogicID), - ); - const ethValidator = validator["validatorID"][0]; - return ethValidator; - } - - private getVerifier(validator: any) { - logger.debug(`getVerifier(): Getting Verifier with validator: ${validator}`); - - const verifier = verifierFactory.getVerifier( - validator, - moduleName, - {}, - config.monitorMode - ); - - return verifier; - } - - stopMonitor(tradeInfo: TradeInfo) { - logger.debug(`##calling stopMonitor()`); - - // get validator - const validator = this.getValidator(tradeInfo); - // get verifier - const verifier = this.getVerifier(validator); - // stop monitoring - verifier.stopMonitor(moduleName); - } - - sendTestRequest(verifier: Verifier) { - const contract = {}; - const method = { command: "getBalance", type: "web3Eth" }; - const accountEthereum = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; - const args = { args: [accountEthereum] }; - - logger.debug(`##sendTestRequest(): calling verifier.sendSyncRequest()`); - verifier - .sendSyncRequest(contract, method, args) - .then((response) => { - if (response.status == 504 && response.data === undefined) { - logger.error(`##sendTestRequest(): Could not establish connection to ethereum ledger`); - } else { - logger.info(`##sendTestRequest(): Successfully connected to ethereum ledger`); - } - return { status: response.status, data: response.data }; - }) - .catch((err) => { - logger.error(err); - }); - } - - onEvent(ledgerEvent: LedgerEvent, targetIndex: number): void { - logger.debug(`##onEvent(): ${json2str(ledgerEvent)}`); - - const tx = this.getTransactionFromEvent(ledgerEvent, targetIndex); - if (tx == null) { - logger.error(`##onEvent(): invalid event: ${json2str(ledgerEvent)}`); - return; - } - - try { - const txId = tx["hash"]; - const status = ledgerEvent.data["status"]; - logger.debug(`##onEvent(): txId = ${txId}`); - logger.debug(`##onEvent(): status = ${status}`); - - if (status !== 200) { - logger.error( - `##onEvent(): error event, status: ${status}, txId: ${txId}` - ); - return; - } - } catch (err) { - logger.error(`##onEvent(): err: ${err}, event: ${json2str(ledgerEvent)}`); - } - } - - getTxIDFromEvent(event: LedgerEvent, targetIndex: number): string | null { - const tx = this.getTransactionFromEvent(event, targetIndex); - console.log(tx) - if (tx == null) { - logger.warn(`##getTxIDFromEvent(): skip(not found tx)`); - return null; - } - - try { - const txId = tx["hash"]; - if (typeof txId !== "string") { - logger.warn( - `##getTxIDFromEvent(): skip(invalid block, not found txId.), event: ${json2str( - event - )}` - ); - return null; - } - - logger.debug(`##getTxIDFromEvent(): txId: ${txId}`); - return txId; - } catch (err) { - logger.error( - `##getTxIDFromEvent(): err: ${err}, event: ${json2str(event)}` - ); - return null; - } - } - - getEventDataNum(ledgerEvent: LedgerEvent): number { - logger.debug( - `##getEventDataNum(), ledgerEvent.verifierId: ${ledgerEvent.verifierId}` - ); - const event = ledgerEvent.data; - let retEventNum = 0; - - try { - const validatorID = config.checkEthereumValidator.connector.validatorID; - - retEventNum = event["blockData"]["transactions"].length; - logger.debug( - `##getEventDataNum(): retEventNum: ${retEventNum}, verifierId: ${ledgerEvent.verifierId}` - ); - return retEventNum; - } catch (err) { - logger.error( - `##getEventDataNum(): invalid even, err: ${err}, event: ${event}` - ); - return 0; - } - } - - getTransactionFromEvent( - event: LedgerEvent, - targetIndex: number - ): object | null { - try { - const retTransaction = event.data["blockData"]["transactions"][targetIndex]; - logger.debug( - `##getTransactionFromEvent(), retTransaction: ${retTransaction}` - ); - console.log(retTransaction) - return retTransaction; - } catch (err) { - logger.error( - `##getTransactionFromEvent(): invalid even, err:${err}, event:${event}` - ); - } - } -} - diff --git a/examples/cactus-check-connection-ethereum-validator/CHANGELOG.md b/examples/cactus-check-connection-ethereum-validator/CHANGELOG.md deleted file mode 100644 index 9e044dd947..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/CHANGELOG.md +++ /dev/null @@ -1,46 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [2.0.0-alpha.2](https://github.com/hyperledger/cacti/compare/v2.0.0-alpha.1...v2.0.0-alpha.2) (2023-09-27) - -### Bug Fixes - -* **security:** the CVE-2022-2421 - upgrade socket.io-parser to >=4.2.1 ([9172172](https://github.com/hyperledger/cacti/commit/917217227a3fa53a00429f047cd6318862e6ab8d)), closes [#2229](https://github.com/hyperledger/cacti/issues/2229) [#2228](https://github.com/hyperledger/cacti/issues/2228) - -# [2.0.0-alpha.1](https://github.com/hyperledger/cacti/compare/v2.0.0-alpha-prerelease...v2.0.0-alpha.1) (2023-05-19) - -**Note:** Version bump only for package check-connection-ethereum-validator - -# [2.0.0-alpha-prerelease](https://github.com/hyperledger/cacti/compare/v1.2.0...v2.0.0-alpha-prerelease) (2023-05-11) - -**Note:** Version bump only for package check-connection-ethereum-validator - -# [1.2.0](https://github.com/hyperledger/cacti/compare/v1.1.3...v1.2.0) (2023-03-28) - -**Note:** Version bump only for package check-connection-ethereum-validator - -## [1.1.2](https://github.com/hyperledger/cactus/compare/v1.1.1...v1.1.2) (2022-11-11) - -**Note:** Version bump only for package check-connection-ethereum-validator - -## [1.1.1](https://github.com/hyperledger/cactus/compare/v1.1.0...v1.1.1) (2022-11-03) - -**Note:** Version bump only for package check-connection-ethereum-validator - -# [1.1.0](https://github.com/hyperledger/cactus/compare/v1.0.0...v1.1.0) (2022-10-17) - -### Bug Fixes - -* resolve some CodeQL warnings ([824f5c8](https://github.com/hyperledger/cactus/commit/824f5c80ce5efbd9765699fdd635ab1d7f29cea2)) - -# [1.0.0](https://github.com/hyperledger/cactus/compare/v1.0.0-rc.3...v1.0.0) (2022-03-16) - -### Bug Fixes - -* **cmd-api-server:** upgrade socket.io - CVE-2022-21676 ([8e1c69e](https://github.com/hyperledger/cactus/commit/8e1c69e7b8ab5e4ccc31a0ec183a9777ccc22cdc)), closes [#1914](https://github.com/hyperledger/cactus/issues/1914) - -### Features - -* **cactus-api-client:** common verifier-factory ([2f70a64](https://github.com/hyperledger/cactus/commit/2f70a6473f30446859427335f2d3602bddca636d)), closes [#1878](https://github.com/hyperledger/cactus/issues/1878) diff --git a/examples/cactus-check-connection-ethereum-validator/README.MD b/examples/cactus-check-connection-ethereum-validator/README.MD deleted file mode 100644 index 7b2f6932fc..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/README.MD +++ /dev/null @@ -1,211 +0,0 @@ -# cactus-check-connection-ethereum-validator - -Business Logic Plugin for checking communication with ethereum ledger via cactus-plugin-ledger-connector-go-ethereum-socketio - -------------------------------------------------------------------------- -## 1. Setup - -Before booting, prepare the directory on your server for storing config files - - sudo mkdir /etc/cactus - sudo chmod 777 /etc/cactus - - -#### Start docker environment for Go-Ethereum testnet - - cd cactus/tools/docker/geth-testnet - ./script-start-docker.sh - -#### Build all necessary packages - -In main cactus directory run - - npm run configure - -#### Launch ethereum connector - -1. Install npm packages and build them - ``` - cd cactus/packages/cactus-plugin-ledger-connector-go-ethereum-socketio - npm install - npm run build - ``` - -2. Create symbolic link to node_modules - ``` - npm run init-ethereum - ``` - -3. Create docker image - ``` - docker-compose -f docker-compose.yaml build - ``` - -4. Launch container - ``` - docker-compose -f docker-compose.yaml up - ``` - -#### Launch socket server and BLP - -1. Install and build npm packages on cactus-cmd-socketio-server - ``` - cd cactus/packages/cactus-cmd-socketio-server - npm install - npm run build - ``` - -2. Install and build npm packages on cactus/examples/cactus-check-connection-ethereum-validator - ``` - cd cactus/examples/cactus-check-connection-ethereum-validator - npm install - npm run build - ``` - -3. Create the symbolic link to node_modules. - ``` - cd cactus/examples/cactus-check-connection-ethereum-validator - npm run init-check-connection-ethereum-validator - ``` - -4. Launch BLP - ``` - cd cactus/examples/cactus-check-connection-ethereum-validator - npm run start - ``` - -### Setup tool -Alternative way of setup blp is to use setup tool located in `tools` directory: - - cactus/examples/cactus-check-connection-ethereum-validator/tools/ - - -Full setup of blp with needed environment is made with 4 following steps: - -##### 1. Setup environment: -This step consists of: - -- checking `/etc/cactus` directory for availability -- checking permissions on above directory and changes them to proper ones -- starting ethereum testnet -- running `npm run configure` in main cactus directory - -In `tools` directory run command `./setup.sh -s env` - -##### 2. Setup connector -This step consists of: - -- building Ethereum connector -- running Ethereum connector - -1. Open new terminal window -2. In `tools` directory run command: `./setup.sh -s connector` - -##### 3. build socket.io server -1. Open new terminal window -2. In `tools` directory run command: `./setup.sh -s build_socketio_server` - -##### 4. Setup BLP -This step consists of: - -- building cactus-check-connection-ethereum-validator BLP -- running cactus-check-connection-ethereum-validator BLP - -In `tools` directory run command: `./setup.sh -s blp` - -##### To check help run: - - ./setup.sh help -------------------------------------------------------------------------- - -## 2. How to use - -Application checks connection by getting balance on ethereum ledger -Source test account address is: - - 06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97 - -Destination test account address is: - - 9d624f7995e8bd70251f8265f2f9f2b49f169c55 - - -To execute BLP run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"jLn76rgB"}' - - -To check balance (async request) on Ethereum ledger run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/getBalance -XPOST -H "Content-Type: application/json" -d '{"account": "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "requestType": "async"}' - -To check balance (sync request) on Ethereum ledger run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/getBalance -XPOST -H "Content-Type: application/json" -d '{"account": "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "requestType": "sync"}' - -To transfer assets between two Ethereum accounts (async request) run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/transferAssets -XPOST -H "Content-Type: application/json" -d '{"srcAccount": "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "destAccount": "9d624f7995e8bd70251f8265f2f9f2b49f169c55", "amount": "10", "requestType": "async"}' - -To transfer assets between two Ethereum accounts (sync request) run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/transferAssets -XPOST -H "Content-Type: application/json" -d '{"srcAccount": "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "destAccount": "9d624f7995e8bd70251f8265f2f9f2b49f169c55", "amount": "10", "requestType": "sync"}' - -BLP starts by default with Monitor Mode active, but it can be changed by switching monitorMode flag in: - - /etc/cactus/default.yaml - -To stop Monitor Mode manually run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/stopMonitor - -To start Monitor Mode manually run: - - curl localhost:5034/api/v1/bl/check-ethereum-validator/startMonitor - -------------------------------------------------------------------------- -## 3. Testing - -#### Test cases - -check-connection-to-ledger.test.ts: - 1. Check if all services (ledger, connector and BLP) are available - 2. Check if containers (ledger, connector) are up and running - 3. Check connection to BLP and received response - 4. Check connection BLP -> connector -> ledger (sync/async) - 5. Make sample transaction between two Ethereum accounts (sync/async) - -check-config-files.ts: - 1. Check and validate default.yaml - 2. Check and validate usersetting.yaml - -#### How to run - -For testing purpose test suite is getting ip address from /etc/cactus/usersetting.yaml -Change value hostName in above file before running test suite - -To run testsuites: - -1. In cactus/jest.config.js comment lines: - - ``` - ./examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts, - ./examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts, - ``` -2. In main cactus directory run: - ``` - npx jest examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts - npm jest examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts - ``` -You can also use setup script located in `tools` directory: - - cactus/examples/cactus-check-connection-ethereum-validator/tools/ - -To run single test suite run one of the following commands: - - ./test-runner.sh -t test_connection - ./test-runner.sh -t test_configs - -All available tests can be run with command: - - ./test-runner.sh -t all \ No newline at end of file diff --git a/examples/cactus-check-connection-ethereum-validator/RequestInfo.ts b/examples/cactus-check-connection-ethereum-validator/RequestInfo.ts deleted file mode 100644 index 1113c7cce4..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/RequestInfo.ts +++ /dev/null @@ -1,12 +0,0 @@ -export class RequestInfo { - businessLogicID: string = null; - tradeID: string = null; - - setBusinessLogicID(businessLogicID: string) { - this.businessLogicID = businessLogicID; - } - - setTradeID(tradeID: string) { - this.tradeID = tradeID; - } -} diff --git a/examples/cactus-check-connection-ethereum-validator/TestEthereumVerifier.ts b/examples/cactus-check-connection-ethereum-validator/TestEthereumVerifier.ts deleted file mode 100644 index 58ab1f8351..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/TestEthereumVerifier.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { Verifier } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/Verifier"; -import { ConfigUtil } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/util/ConfigUtil"; -import { verifierFactory } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/routes/index"; -import { IVerifierEventListener } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/LedgerPlugin"; - -const config: any = ConfigUtil.getConfig(); -import { getLogger } from "log4js"; -import { VerifierFactory } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/VerifierFactory"; -const moduleName = "TestEthereumBalance"; -const logger = getLogger(`${moduleName}`); -logger.level = config.logLevel; - -export class TestEthereumVerifier { - private verifierEthereum: Verifier; - private validatorId: string; - private appId: string; - private monitorOptions: object; - private monitorMode: boolean; - - constructor() { - this.verifierEthereum = null; - this.validatorId = "84jUisrs"; - this.appId = "BusinessLogicCheckEthereumValidator"; - this.monitorOptions = {}; - this.monitorMode = false; - } - - private createVerifierWithoutMonitoring(): void { - logger.debug("create verifierEthereum"); - - this.verifierEthereum = verifierFactory.getVerifier( - this.validatorId, - this.appId, - this.monitorOptions, - this.monitorMode, - ); - } - - sendAsyncRequest( - contract: object, - method: { type: string; command: string }, - args: object, - ): Promise { - return new Promise((resolve, reject) => { - this.verifierEthereum - .sendAsyncRequest(contract, method, args) - .then(() => { - logger.debug(`Successfully sent async request to: ${method.command}`); - resolve(true); - }) - .catch((err) => { - logger.error(err); - reject(err); - }); - }); - } - - sendSyncRequest( - contract: object, - method: { type: string; command: string }, - args: object, - ): Promise { - return new Promise((resolve, reject) => { - this.verifierEthereum - .sendSyncRequest(contract, method, args) - .then((result) => { - let response = {}; - if (method.command === "getBalance") { - response = { - status: result.status, - amount: parseFloat(result.data), - }; - } else { - response = { - status: result.status, - data: result.data, - }; - } - resolve(response); - }) - .catch((err) => { - logger.error(err); - reject(err); - }); - }); - } - - getBalance(account: string, requestType: string): any { - this.createVerifierWithoutMonitoring(); - - const contract = {}; - const method = { type: "web3Eth", command: "getBalance" }; - const args = { args: [account] }; - - logger.debug(`Sending ${requestType} request for ETH balance...`); - if (requestType === "async") { - return this.sendAsyncRequest(contract, method, args); - } else { - return this.sendSyncRequest(contract, method, args); - } - } - - transferAsset( - srcAccount: string, - destAccount: string, - amount: string, - requestType: string, - ) { - this.createVerifierWithoutMonitoring(); - - const contract = {}; - const method = { type: "web3Eth", command: "sendTransaction" }; - const args = { - args: [ - { - from: srcAccount, - to: destAccount, - value: amount, - }, - ], - }; - - logger.debug(`Sending ${requestType} request for moving ETH assets...`); - - if (requestType === "async") { - return this.sendAsyncRequest(contract, method, args); - } else { - return this.sendSyncRequest(contract, method, args); - } - } - - stopMonitor() { - logger.debug(`StartingMonitor`); - - this.createVerifierWithoutMonitoring(); - logger.debug(`Stopping Monitor`); - const blpMonitorModuleName = "BusinessLogicCheckEthereumValidator"; - - this.verifierEthereum.stopMonitor(blpMonitorModuleName); - } - - startMonitor() { - logger.debug(`StartingMonitor`); - - const blpMonitorModuleName = "BusinessLogicCheckEthereumValidator"; - const verifier = verifierFactory.getVerifier( - this.validatorId, - blpMonitorModuleName, - this.monitorOptions, - true, - ); - let eventListener: IVerifierEventListener; - - verifier.startMonitor(blpMonitorModuleName, {}, eventListener); - } -} diff --git a/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts b/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts deleted file mode 100644 index 2a7854bc3f..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Router, NextFunction, Request, Response } from "express"; -import { getLogger } from "log4js"; -import { TransactionManagement } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TransactionManagement"; -import { RIFError } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RIFError"; -import { ConfigUtil } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/util/ConfigUtil"; -import { TestEthereumVerifier } from "./TestEthereumVerifier"; -import escapeHtml from "escape-html"; - -const config: any = ConfigUtil.getConfig(); -const moduleName = "check-ethereum-validator"; -const logger = getLogger(`${moduleName}`); -logger.level = config.logLevel; - -const router: Router = Router(); -export const transactionManagement: TransactionManagement = new TransactionManagement(); - -function isRifError(err: any, res: Response): boolean { - if (err instanceof RIFError) { - logger.error(`RIFError caught, ${err.statusCode}, ${err.message}`); - res.status(err.statusCode); - res.send(escapeHtml(err.message)); - return true; - } - logger.error(`Error caught: ${err.statusCode}, ${err.message}`); - return false; -} - -function checkRequestType(requestType: string): string | boolean { - - if (requestType === undefined) { - logger.error(`Unspecified type of request in request body. Use `); - return false; - } - if (requestType.localeCompare("async") !== 0 && requestType.localeCompare("sync") !== 0) { - logger.error(`Wrong request type specified in request: ${requestType}. Use `); - return false; - } - return requestType; -} - -router.post("/", (req: Request, res: Response, next: NextFunction) => { - try { - logger.info("check-ethereum-validator()"); - const tradeID: string = transactionManagement.startBusinessLogic(req); - const result = { tradeID: tradeID }; - res.status(200).json(result); - } catch (err) { - if (isRifError(err, res)) return; - next(err); - } -}); - -const testEthereumVerifier: TestEthereumVerifier = new TestEthereumVerifier(); - -router.post("/getBalance", (req: Request, res: Response, next: NextFunction) => { - logger.info("check-ethereum-validator()"); - - const requestType = checkRequestType(req.body.requestType); - - if (requestType === false) { - return res.end(); - } - - logger.debug(`Sending ${requestType} request on 'getBalance' endpoint`); - - try { - testEthereumVerifier.getBalance(req.body.account, - requestType.toString()) - .then((result: any) => { - logger.debug(JSON.stringify(result)); - res.status(200).json(result); - }) - .catch((err: any) => { - logger.error(err); - }); - } catch (err) { - if (isRifError(err, res)) return; - next(err); - } - -}); - -router.post("/transferAssets", (req: Request, res: Response, next: NextFunction) => { - - logger.info("check-ethereum-validator()"); - - const requestType = checkRequestType(req.body.requestType); - - if (requestType === false) { - return res.end(); - } - - logger.debug(`Sending ${req.body.requestType} request on 'transferAsset' endpoint`); - - try { - testEthereumVerifier.transferAsset(req.body.srcAccount, - req.body.destAccount, - req.body.amount, - req.body.requestType) - .then((result: any) => { - logger.debug(JSON.stringify(result)); - res.status(200).json(result); - }) - .catch((err) => { - logger.error(err); - }); - } catch (err) { - if (isRifError(err, res)) return; - next(err); - } -}); - - -router.get("/stopMonitor", (req: Request, res: Response, next: NextFunction) => { - - logger.info("check-ethereum-validator()"); - - try { - testEthereumVerifier.stopMonitor() - res.status(200).json(true); - } catch (err) { - if (isRifError(err, res)) return; - next(err); - } -}); - -router.get("/startMonitor", (req: Request, res: Response, next: NextFunction) => { - - logger.info("check-ethereum-validator()"); - - try { - testEthereumVerifier.startMonitor() - res.status(200).json(true); - } catch (err) { - if (isRifError(err, res)) return; - next(err); - } -}); - -export default router; diff --git a/examples/cactus-check-connection-ethereum-validator/config/BLP_config.ts b/examples/cactus-check-connection-ethereum-validator/config/BLP_config.ts deleted file mode 100644 index 6c68b9ad4a..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/config/BLP_config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { BusinessLogicPlugin } from "../../../packages/cactus-cmd-socketio-server/src/main/typescript/business-logic-plugin/BusinessLogicPlugin"; -import { BusinessLogicCheckEthereumValidator } from "../BusinessLogicCheckEthereumValidator"; - -export function getTargetBLPInstance( - businessLogicID: string, -): BusinessLogicPlugin | null { - switch (businessLogicID) { - case "jLn76rgB": - return new BusinessLogicCheckEthereumValidator(businessLogicID); - default: - return null; - } -} diff --git a/examples/cactus-check-connection-ethereum-validator/config/default.yaml b/examples/cactus-check-connection-ethereum-validator/config/default.yaml deleted file mode 100644 index ec39924a65..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/config/default.yaml +++ /dev/null @@ -1,8 +0,0 @@ -checkEthereumValidator: - connector: - validatorID: 84jUisrs - chainName: geth1 - -logLevel: debug - -monitorMode: true \ No newline at end of file diff --git a/examples/cactus-check-connection-ethereum-validator/config/usersetting.yaml b/examples/cactus-check-connection-ethereum-validator/config/usersetting.yaml deleted file mode 100644 index ace67b3cad..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/config/usersetting.yaml +++ /dev/null @@ -1,24 +0,0 @@ -blpRegistry: - - - businessLogicID: jLn76rgB - validatorID: [84jUisrs] - -logLevel: debug - -applicationHostInfo: - hostName: http://aaa.bbb.ccc.ddd - hostPort: 5034 - -appRouters: - - - path: /api/v1/bl/check-ethereum-validator/ - routerJs: ../../../../../../examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.js - -verifier: - maxCounterRequestID: 100 - syncFunctionTimeoutMillisecond: 5000 - -socketOptions: - rejectUnauthorized: false - reconnection: false - timeout: 20000 \ No newline at end of file diff --git a/examples/cactus-check-connection-ethereum-validator/copyBLPConfig.ts b/examples/cactus-check-connection-ethereum-validator/copyBLPConfig.ts deleted file mode 100644 index 4ca06790b4..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/copyBLPConfig.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as shell from "shelljs"; - -shell.cp( - "../../dist/examples/cactus-check-connection-ethereum-validator/config/BLP_config.js", - "../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/business-logic-plugin/", -); diff --git a/examples/cactus-check-connection-ethereum-validator/copyStaticAssets.ts b/examples/cactus-check-connection-ethereum-validator/copyStaticAssets.ts deleted file mode 100644 index ca8a0715d0..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/copyStaticAssets.ts +++ /dev/null @@ -1,4 +0,0 @@ -import * as shell from "shelljs"; - -shell.cp("-R", "config/default.yaml", "/etc/cactus/"); -shell.cp("-R", "config/usersetting.yaml", "/etc/cactus/"); diff --git a/examples/cactus-check-connection-ethereum-validator/package.json b/examples/cactus-check-connection-ethereum-validator/package.json deleted file mode 100644 index 179c2f5639..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@hyperledger/cactus-examples-check-connection-ethereum-validator", - "version": "2.0.0-alpha.2", - "private": true, - "license": "Apache-2.0", - "scripts": { - "build": "npm run build-ts && npm run copy-static-assets && npm run copy-blp-config && npm run replace-blp-config-path", - "build-ts": "tsc -p ./tsconfig.json", - "copy-blp-config": "ts-node copyBLPConfig.ts", - "copy-static-assets": "ts-node copyStaticAssets.ts", - "debug": "nodemon --inspect ../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/www.js", - "init-check-connection-ethereum-validator": "ln -s ../examples/cactus-check-connection-ethereum-validator/node_modules ../../dist/node_modules", - "replace-blp-config-path": "ts-node replaceBLPConfigPath.ts", - "start": "node ../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/www.js", - "tslint": "tslint -c tslint.json -p tsconfig.json './*.ts'" - }, - "dependencies": { - "escape-html": "1.0.3", - "express": "4.18.2", - "js-yaml": "4.1.0", - "log4js": "6.9.1", - "shelljs": "0.8.5", - "socket.io": "4.5.4" - }, - "devDependencies": { - "@hyperledger/cactus-common": "2.0.0-alpha.2", - "@types/escape-html": "1.0.1", - "@types/express": "4.17.20", - "@types/js-yaml": "4.0.8", - "@types/node": "15.14.9", - "@types/shelljs": "0.8.14" - }, - "engines": { - "node": ">=18", - "npm": ">=8" - } -} diff --git a/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts b/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts deleted file mode 100644 index 55213da67f..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts +++ /dev/null @@ -1,18 +0,0 @@ -const fs = require("fs"); - -const targetFile = - "../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/business-logic-plugin/BLP_config.js"; -const srcStr = '"../BusinessLogicCheckEthereumValidator"'; -const distStr = - '"../../../../../../examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator"'; - -fs.readFile(targetFile, "utf8", (readErr, data) => { - if (readErr) { - return console.log(readErr); - } - const result = data.replace(srcStr, distStr); - - fs.writeFile(targetFile, result, "utf8", (writeErr) => { - if (writeErr) return console.log(writeErr); - }); -}); diff --git a/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts b/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts deleted file mode 100644 index 6ac2aa9d2c..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { - Logger, - LoggerProvider, - LogLevelDesc, -} from "@hyperledger/cactus-common"; - -const logLevel: LogLevelDesc = "TRACE"; -const logger: Logger = LoggerProvider.getOrCreate({ - label: "preflight-check", - level: logLevel, -}); - -const fs = require("fs"); -const yaml = require("js-yaml"); - -const configLocation = "/etc/cactus"; -const encoding = "utf8"; - -function getYamlFileContent(fileName: string): any { - logger.debug(`Reading ${fileName} file`); - const fileContent = yaml.safeLoad( - fs.readFileSync(`${configLocation}/${fileName}.yaml`, encoding), - ); - return fileContent; -} - -function checkExistenceOfFile(fileName: string): boolean { - const path = `${configLocation}/${fileName}.yaml`; - - if (fs.existsSync(path)) { - return true; - } else { - return false; - } -} -describe("Config files check tests", () => { - test("Check if all config files exists", () => { - expect(checkExistenceOfFile("default")).toBe(true); - expect(checkExistenceOfFile("usersetting")).toBe(true); - }); - - test("Check default.yaml integrity", () => { - const defaultYaml = getYamlFileContent("default"); - logger.debug(`default.yaml file content:\n${defaultYaml}`); - - logger.debug(`Check keys in tested config file`); - expect(Object.keys(defaultYaml)).toContain("checkEthereumValidator"); - expect(Object.keys(defaultYaml)).toContain("logLevel"); - expect(Object.keys(defaultYaml.checkEthereumValidator)).toContain( - "connector", - ); - expect(Object.keys(defaultYaml.checkEthereumValidator.connector)).toContain( - "validatorID", - ); - expect(Object.keys(defaultYaml.checkEthereumValidator.connector)).toContain( - "chainName", - ); - - logger.debug(`Check values in tested config file`); - expect(defaultYaml.checkEthereumValidator.connector.validatorID).toBe( - "84jUisrs", - ); - expect( - typeof defaultYaml.checkEthereumValidator.connector.validatorID, - ).toBe("string"); - - expect(defaultYaml.checkEthereumValidator.connector.chainName).toBe( - "geth1", - ); - expect(typeof defaultYaml.checkEthereumValidator.connector.chainName).toBe( - "string", - ); - - expect(typeof defaultYaml.logLevel).toBe("string"); - }); - - test("Check usersetting.yaml integrity", () => { - const usersettingYaml = getYamlFileContent("usersetting"); - logger.debug(`default.yaml file content:\n${usersettingYaml}`); - - logger.debug(`Check keys in tested config file`); - expect(Object.keys(usersettingYaml)).toContain("blpRegistry"); - expect(Object.keys(usersettingYaml.blpRegistry[0])).toContain( - "businessLogicID", - ); - expect(Object.keys(usersettingYaml.blpRegistry[0])).toContain( - "validatorID", - ); - - expect(Object.keys(usersettingYaml)).toContain("logLevel"); - - expect(Object.keys(usersettingYaml)).toContain("applicationHostInfo"); - expect(Object.keys(usersettingYaml.applicationHostInfo)).toContain( - "hostName", - ); - expect(Object.keys(usersettingYaml.applicationHostInfo)).toContain( - "hostPort", - ); - - expect(Object.keys(usersettingYaml)).toContain("appRouters"); - expect(Object.keys(usersettingYaml.appRouters[0])).toContain("path"); - expect(Object.keys(usersettingYaml.appRouters[0])).toContain("routerJs"); - - expect(Object.keys(usersettingYaml)).toContain("verifier"); - expect(Object.keys(usersettingYaml.verifier)).toContain( - "maxCounterRequestID", - ); - expect(Object.keys(usersettingYaml.verifier)).toContain( - "syncFunctionTimeoutMillisecond", - ); - - expect(Object.keys(usersettingYaml)).toContain("socketOptions"); - expect(Object.keys(usersettingYaml.socketOptions)).toContain( - "rejectUnauthorized", - ); - expect(Object.keys(usersettingYaml.socketOptions)).toContain( - "reconnection", - ); - expect(Object.keys(usersettingYaml.socketOptions)).toContain("timeout"); - - logger.debug(`Check values in tested config file`); - expect(usersettingYaml.blpRegistry[0].businessLogicID).toBe("jLn76rgB"); - expect(usersettingYaml.blpRegistry[0].validatorID[0]).toBe("84jUisrs"); - - expect( - usersettingYaml.logLevel === "error" || - usersettingYaml.logLevel === "warn" || - usersettingYaml.logLevel === "info" || - usersettingYaml.logLevel === "debug" || - usersettingYaml.logLevel === "trace", - ).toBe(true); - - const ipRegex = - /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; - expect( - usersettingYaml.applicationHostInfo.hostName.replace("http://", ""), - ).toMatch(ipRegex); - - expect(typeof usersettingYaml.applicationHostInfo.hostPort).toBe("number"); - expect(usersettingYaml.applicationHostInfo.hostPort).toBe(5034); - - expect(typeof usersettingYaml.verifier.maxCounterRequestID).toBe("number"); - expect(usersettingYaml.verifier.maxCounterRequestID).toBe(100); - expect(typeof usersettingYaml.verifier.syncFunctionTimeoutMillisecond).toBe( - "number", - ); - - expect(typeof usersettingYaml.socketOptions.rejectUnauthorized).toBe( - "boolean", - ); - expect(typeof usersettingYaml.socketOptions.reconnection).toBe("boolean"); - expect(typeof usersettingYaml.socketOptions.timeout).toBe("number"); - }); -}); diff --git a/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts b/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts deleted file mode 100644 index ae6416e216..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts +++ /dev/null @@ -1,392 +0,0 @@ -import { - Logger, - LoggerProvider, - LogLevelDesc, -} from "@hyperledger/cactus-common"; - -const logLevel: LogLevelDesc = "TRACE"; -const logger: Logger = LoggerProvider.getOrCreate({ - label: "test-check-connection-to-ethereum-ledger", - level: logLevel, -}); - -const http = require("http"); -const net = require("net"); -const fs = require("fs"); -const yaml = require("js-yaml"); - -function getConfigData(): any { - const config: any = yaml.safeLoad( - fs.readFileSync("/etc/cactus/usersetting.yaml", "utf8"), - ); - const hostName: string = config.applicationHostInfo.hostName.replace( - "http://", - "", - ); - const hostPort: string = config.applicationHostInfo.hostPort; - - logger.info(`BLP hostname from usersetting file in /etc/cactus: ${hostName}`); - logger.info(`BLP port from usersetting file in /etc/cactus: ${hostPort}`); - return { hostname: hostName, port: hostPort }; -} - -function createOptionObj( - path: string, - method: string, - postData: string, -): Record { - const configData = getConfigData(); - const options = { - hostname: configData.hostname, - port: configData.port, - path: path, - method: method, - headers: { - "Content-Type": "application/json", - "Content-Length": Buffer.byteLength(postData), - }, - }; - return options; -} - -function pingService(hostName: string, port: number): Promise { - return new Promise((resolve) => { - const sock = new net.Socket(); - sock.setTimeout(120); - sock.on("connect", function () { - logger.debug(`${hostName}:${port} is up.`); - sock.destroy(); - resolve(true); - }); - sock.on("error", function (error: any) { - logger.error(`${hostName}:${port} is down: ${error.message}`); - resolve(false); - }); - sock.connect(port, hostName); - }); -} - -function sendRequest( - options: Record, - postData: string, -): Promise { - return new Promise((resolve, reject) => { - const request = http - .request(options, (response: any) => { - response.setEncoding("utf8"); - let body = ""; - const statusCode = response.statusCode; - response.on("data", (chunk: any) => (body += chunk)); - response.on("end", () => resolve([body, statusCode])); - }) - .on("error", reject); - - request.write(postData); - request.end(); - }); -} - -function checkContainerStatus(containerName: string): Promise { - const { exec } = require("child_process"); - - const checkRunningCmd = "docker container inspect -f '{{.State.Running}}'"; - - return new Promise((resolve) => { - exec(`${checkRunningCmd} ${containerName}`, (err: any, out: any) => { - logger.debug(`Output from docker command: err: ${err}, out: ${out}`); - - if (out.replace("\n", "") == "true") { - logger.info(`Container: ${containerName} is up and running!`); - resolve(true); - } else { - logger.error(`Container: ${containerName} is down!`); - resolve(false); - } - }); - }); -} - -describe("Environment check tests", () => { - test("Check if all required services are accessible", async () => { - const config = getConfigData(); - const ethereumLedgerPort = 8545; - const ethereumConnectorPort = 5050; - - logger.debug(`Check connection to BLP (${config.hostname}:${config.port})`); - expect(await pingService(config.hostname, config.port)).toBeTrue(); - - logger.debug( - `Check connection to Ethereum Connector (${config.hostname}:${ethereumConnectorPort})`, - ); - expect( - await pingService(config.hostname, ethereumConnectorPort), - ).toBeTrue(); - - logger.debug( - `Check connection to Ethereum Ledger (${config.hostname}:${ethereumLedgerPort})`, - ); - expect(await pingService(config.hostname, ethereumLedgerPort)).toBeTrue(); - }); - - test("Check if containers started successfully", async () => { - logger.debug(`Check ethereum ledger container`); - const ethereumLedgerContainerName = "geth1"; - expect(await checkContainerStatus(ethereumLedgerContainerName)).toBeTrue(); - - logger.debug(`Check ethereum connector container`); - const ethereumConnectorContainerName = - "hyperledger-cactus-plugin-ledger-connector-go-ethereum-socketio"; - expect( - await checkContainerStatus(ethereumConnectorContainerName), - ).toBeTrue(); - }); - - test("Check connection to BLP and validate response", async () => { - const postData = JSON.stringify({ - businessLogicID: "jLn76rgB", - }); - const path = "/api/v1/bl/check-ethereum-validator"; - const options = createOptionObj(path, "POST", postData); - - const response = await sendRequest(options, postData); - logger.debug(`Received response: [${response}]`); - - logger.debug(`Check status code from API`); - expect(response[1]).toBe(200); - - logger.debug(`Check if response is not empty`); - expect(response[0]).not.toBe(""); - - let jsonResponse: any; - try { - jsonResponse = JSON.parse(response[0]); - } catch (error) { - logger.error(`There was a problem with parsing response`); - } - - logger.debug(`Check if parsed response contains proper keys`); - expect(Object.keys(jsonResponse)).toContain("tradeID"); - - logger.debug(`Check if value assigned to tradeID key is not empty`); - expect(jsonResponse.tradeID).not.toEqual(""); - }); -}); - -describe("Ledger operation tests", () => { - test("Get balance from ledger (read test )", async () => { - const account = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; - const path = "/api/v1/bl/check-ethereum-validator/getBalance"; - - logger.info("Checking ASYNC request..."); - - let postData = JSON.stringify({ - account: account, - requestType: "async", - }); - - let options = createOptionObj(path, "POST", postData); - - let response = await sendRequest(options, postData); - logger.debug(`Received response: [${response}]`); - - // check status code - logger.debug(`Check status code from API`); - expect(response[1]).toBe(200); - - // check response content - logger.debug(`Check response content`); - expect(response[0]).toBe("true"); - - logger.info("Checking SYNC request"); - - postData = JSON.stringify({ - account: account, - requestType: "sync", - }); - - options = createOptionObj(path, "POST", postData); - response = await sendRequest(options, postData); - logger.debug(`Received response: [${response}]`); - - // check status code from API - logger.debug(`Check status code from API`); - expect(response[1]).toBe(200); - - // check if response is not empty - expect(response[0]).not.toBe(""); - - let jsonResponse: any; - try { - jsonResponse = JSON.parse(response[0]); - } catch (error) { - logger.error(`There was a problem with parsing response`); - } - - logger.debug(`Check if parsed response contains proper keys`); - expect(Object.keys(jsonResponse)).toContain("status"); - expect(Object.keys(jsonResponse)).toContain("amount"); - - logger.debug(`Check if values assigned keys are not empty`); - expect(jsonResponse.status).not.toEqual(""); - expect(jsonResponse.amount).not.toEqual(""); - - logger.debug( - `Check if status code retrieved from connector is between 200-300`, - ); - expect(jsonResponse.status >= 200).toBeTruthy(); - expect(jsonResponse.status).toBeLessThan(300); - - logger.debug(`Check if balance is not negative number`); - expect(jsonResponse.amount >= 0).toBeTruthy(); - }); - - async function getCurrentBalanceOnAccount(account: string): Promise { - const getCurrentBalancePath = - "/api/v1/bl/check-ethereum-validator/getBalance"; - - const postData = JSON.stringify({ - account: account, - requestType: "sync", - }); - - const options = createOptionObj(getCurrentBalancePath, "POST", postData); - - const srcCheckBalanceResponse = await sendRequest(options, postData); - - let srcCheckBalanceJsonResponse: any; - try { - srcCheckBalanceJsonResponse = JSON.parse(srcCheckBalanceResponse[0]); - } catch (error) { - logger.error(`There was a problem with parsing response`); - } - - return srcCheckBalanceJsonResponse.amount; - } - - test("Make sample transaction (write test )", async () => { - const srcAccount = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; - const destAccount = "9d624f7995e8bd70251f8265f2f9f2b49f169c55"; - const transferAmount = "150"; - const path = "/api/v1/bl/check-ethereum-validator/transferAssets"; - - logger.info("Checking ASYNC request..."); - - let postData = JSON.stringify({ - srcAccount: srcAccount, - destAccount: destAccount, - amount: transferAmount, - requestType: "async", - }); - - let options = createOptionObj(path, "POST", postData); - - // Get current balances on accounts before sending request - let srcBalanceBeforeTransaction = - await getCurrentBalanceOnAccount(srcAccount); - let destBalanceBeforeTransaction = - await getCurrentBalanceOnAccount(destAccount); - logger.debug(`Balances before transaction:\nsource account:${srcBalanceBeforeTransaction} - \ndestination account: ${destBalanceBeforeTransaction}`); - - // Make request - let response = await sendRequest(options, postData); - logger.debug(`Received response: [${response}]`); - - // Check status code - logger.debug(`Check status code from API`); - expect(response[1]).toBe(200); - - // Check response content - logger.debug(`Check response content`); - expect(response[0]).toBe("true"); - - // Wait for 20s to complete transfer - const foo = true; - await new Promise((r) => setTimeout(r, 60000)); - expect(foo).toBeDefined(); - - // Check balances after transaction - let srcBalanceAfterTransaction = - await getCurrentBalanceOnAccount(srcAccount); - let destBalanceAfterTransaction = - await getCurrentBalanceOnAccount(destAccount); - - // Check if differences from before and after transaction are correct - - expect(srcBalanceBeforeTransaction - srcBalanceAfterTransaction).toBe( - parseInt(transferAmount), - ); - expect(destBalanceAfterTransaction - destBalanceBeforeTransaction).toBe( - parseInt(transferAmount), - ); - logger.debug("Assets have been successfully moved between accounts"); - - logger.info("Checking SYNC request..."); - - postData = JSON.stringify({ - srcAccount: srcAccount, - destAccount: destAccount, - amount: transferAmount, - requestType: "sync", - }); - - options = createOptionObj(path, "POST", postData); - - // Get current balances on accounts before sending request - srcBalanceBeforeTransaction = await getCurrentBalanceOnAccount(srcAccount); - destBalanceBeforeTransaction = - await getCurrentBalanceOnAccount(destAccount); - logger.debug(`Balances before transaction:\nsource account:${srcBalanceBeforeTransaction} - destination account: ${destBalanceBeforeTransaction}`); - - // Make request - response = await sendRequest(options, postData); - logger.debug(`Received response: [${response}]`); - - // Check status code - logger.debug(`Check status code from API`); - expect(response[1]).toBe(200); - - // Check response content - logger.debug(`Check response content`); - let jsonResponse: any; - try { - jsonResponse = JSON.parse(response[0]); - } catch (error) { - logger.error(`There was a problem with parsing response`); - } - - logger.debug(`Check if parsed response contains proper keys`); - expect(Object.keys(jsonResponse)).toContain("status"); - expect(Object.keys(jsonResponse)).toContain("data"); - - logger.debug("Check content of response"); - logger.debug(`Check if values assigned keys are not empty`); - expect(jsonResponse.status).not.toEqual(""); - expect(jsonResponse.data).not.toEqual(""); - - logger.debug( - `Check if status code retrieved from connector is between 200-300`, - ); - expect(jsonResponse.status >= 200).toBeTruthy(); - expect(jsonResponse.status).toBeLessThan(300); - - // Wait for 20s to complete transfer - await new Promise((r) => setTimeout(r, 60000)); - expect(foo).toBeDefined(); - - // Check balances after transaction - srcBalanceAfterTransaction = await getCurrentBalanceOnAccount(srcAccount); - destBalanceAfterTransaction = await getCurrentBalanceOnAccount(destAccount); - - // Check if differences from before and after transaction are correct - - expect(srcBalanceBeforeTransaction - srcBalanceAfterTransaction).toBe( - parseInt(transferAmount), - ); - expect(destBalanceAfterTransaction - destBalanceBeforeTransaction).toBe( - parseInt(transferAmount), - ); - logger.debug("Assets have been successfully moved between accounts"); - }); -}); diff --git a/examples/cactus-check-connection-ethereum-validator/tools/setup.sh b/examples/cactus-check-connection-ethereum-validator/tools/setup.sh deleted file mode 100755 index 36fb6b0ee9..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/tools/setup.sh +++ /dev/null @@ -1,218 +0,0 @@ -#!/bin/bash - -ROOT_DIR=`realpath ../../..` - -# --------------------------- SWITCHES --------------------------- - -function main_switch(){ - case $1 in - -s) - setup "$2" - ;; - help) - echo "-----------------------------------------------------------------------------------" - echo "Usage for setup: $0 {-s} {setup step}" - echo "Setup steps: - - check_cactus_dir - checks if /etc/cactus dir exists - - check_cactus_permissions - checks if /etc/cactus has correct permissions - - start_eth_env - starts Ethereum environment - - configure_topdir - runs in cactus topdir - - build_connector - builds ethereum go connector - - start_connector - launches ethereum go connector - - build_socketio_server - builds socketio server - - build_blp - builds cactus-check-connection-ethereum-validator BLP - - start_blp - launches cactus-check-connection-ethereum-validator BLP - - rebuild_blp - rebuilds cactus-check-connection-ethereum-validator BLP - - connector - runs full setup of connector (install + build) - - env - runs full setup of environment (check_cactus_dir + check_cactus_permissions + start_eth_env - + configure_topdir) - - blp - runs full seyup of blp (install + build) - " - echo "-----------------------------------------------------------------------------------" - ;; - *) - echo "Wrong parameter provided - Use <$0 help> for more info" - ;; - esac -} - -function setup(){ - case $1 in - check_cactus_dir) - check_cactus_dir - ;; - check_cactus_permissions) - check_cactus_permissions - ;; - start_eth_env) - start_docker_ethereum_env - ;; - configure_topdir) - configure_topdir - ;; - build_connector) - build_connector - ;; - start_connector) - start_connector - ;; - build_socketio_server) - build_socketio_server - ;; - build_blp) - build_blp - ;; - start_blp) - start_blp - ;; - rebuild_blp) - rebuild_blp - ;; - connector) - setup_connector - ;; - blp) - setup_blp - ;; - env) - setup_env - ;; - *) - echo "Wrong parameter provided - Allowed parameters: - {check_cactus_dir|check_cactus_permissions| - start_eth_env|configure_topdir|build_connector|start_connector| - build_socketio_server|build_blp|start_blp|rebuild_blp|connector|env|blp}" - ;; - esac -} - -# --------------------------- SETUP FUNCTIONS --------------------------- - -function check_cactus_dir(){ - echo "Check if directory /etc/cactus exists" - if [[ -d "/etc/cactus" ]] - then - echo "Directory /etc/cactus already exists" - else - sudo mkdir /etc/cactus - fi -} - -function check_cactus_permissions(){ - echo "Check if directory /etc/cactus has correct permissions" - if [ "$(stat -c '%a' /etc/cactus)" == "777" ] - then - echo "Directory /etc/cactus has proper permissions" - else - sudo chmod 777 /etc/cactus - fi -} - -function start_docker_ethereum_env(){ - echo "Start docker env for Go-Ethereum testnet" - cd ${ROOT_DIR}/tools/docker/geth-testnet - ./script-start-docker.sh -} - -function configure_topdir(){ - echo "Build all necessary packages from topdir" - cd ${ROOT_DIR} - npm run configure -} - -function build_connector(){ - echo "Build ethereum connector" - cd ${ROOT_DIR}/packages/cactus-plugin-ledger-connector-go-ethereum-socketio - install_and_build - npm run init-ethereum - docker-compose -f docker-compose.yaml build - -} - -function start_connector(){ - echo "Launch ethereum connector" - connector_dir_name="cactus-plugin-ledger-connector-go-ethereum-socketio" - docker-compose -f ${ROOT_DIR}/packages/${connector_dir_name}/docker-compose.yaml up -} - -function build_socketio_server(){ - echo "Launch socketio server" - cd ${ROOT_DIR}/packages/cactus-cmd-socketio-server - install_and_build -} - -function build_blp(){ - echo "Build BLP" - cd ${ROOT_DIR}/examples/cactus-check-connection-ethereum-validator - install_and_build - npm run init-check-connection-ethereum-validator -} - -function start_blp(){ - echo "Launch BLP" - cd ${ROOT_DIR}/examples/cactus-check-connection-ethereum-validator - npm run start -} - -function rebuild_blp(){ - echo "Rebuild BLP" - node_modules="${ROOT_DIR}/examples/cactus-check-connection-ethereum-validator/node_modules" - package_lock="${ROOT_DIR}/examples/cactus-check-connection-ethereum-validator/package-lock.json" - echo "Are you sure you want to delete (y|n): - $node_modules - $package_lock" - read user_input - if [ "$user_input" = "y" ] - then - rm -rf "$node_modules" - rm -f "$package_lock" - elif [ "$user_input" = "n" ] - then - echo "Aborting..." - return - else - echo "Wrong input. Required {y|n}" - fi - - if [ ! -d "$node_modules" ] && [ ! -f "$package_lock" ] - then - echo "Directory node_modules and package-lock.json successfully deleted" - fi - echo "Building BLP" - cd ${ROOT_DIR}/examples/cactus-check-connection-ethereum-validator - install_and_build - npm run init-check-connection-ethereum-validator -} - -function setup_env(){ - echo "Running full setup of env" - check_cactus_dir - check_cactus_permissions - start_docker_ethereum_env - configure_topdir -} - -function setup_connector(){ - echo "Running full setup of connector" - build_connector - start_connector -} - -function setup_blp(){ - echo "Running full setup of blp" - build_blp - start_blp -} - -# --------------------------- HELPER FUNCTIONS --------------------------- - -function install_and_build(){ - npm install - npm run build -} - -# --------------------------- MAIN EXECUTION --------------------------- - -main_switch "$1" "$2" \ No newline at end of file diff --git a/examples/cactus-check-connection-ethereum-validator/tools/test-runner.sh b/examples/cactus-check-connection-ethereum-validator/tools/test-runner.sh deleted file mode 100755 index b504c4637e..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/tools/test-runner.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash - -ROOT_DIR=`realpath ../../..` - -# --------------------------- SWITCHES --------------------------- - -function main_switch(){ - case $1 in - -t) - tests "$2" - ;; - help) - echo "-----------------------------------------------------------------------------------" - echo "Usage for test-runner: $0 {-t} {test_connection|test_configs|all}" - echo "Parameters: - - test_connection - executes set of tests to check connection between all components - - test_configs - executes set of tests to validate config files in /etc/cactus - - all - executes all available tests for current BLP" - echo "-----------------------------------------------------------------------------------" - ;; - *) - echo "Wrong parameter provided - Use <$0 help> for more info" - ;; - esac -} - -function tests(){ - case $1 in - test_connection) - test_connection - ;; - test_configs) - test_configs - ;; - all) - all - ;; - *) - echo "Wrong test provided. Available: {test_connection|test_configs|all}" - ;; - esac -} - -# --------------------------- TEST FUNCTIONS --------------------------- - -function test_connection(){ - cd $ROOT_DIR - npx jest examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts -} - -function test_configs(){ - cd $ROOT_DIR - npx jest examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts -} - -function all(){ - test_connection - test_configs -} - -# --------------------------- MAIN EXECUTION --------------------------- - -main_switch "$1" "$2" \ No newline at end of file diff --git a/examples/cactus-check-connection-ethereum-validator/tsconfig.json b/examples/cactus-check-connection-ethereum-validator/tsconfig.json deleted file mode 100644 index c6aabfe8e9..0000000000 --- a/examples/cactus-check-connection-ethereum-validator/tsconfig.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "compilerOptions": { - /* Basic Options */ - "incremental": true, /* Enable incremental compilation */ - "target": "ES2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ - "module": "CommonJS", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - "lib": [ - "es2015", - "es2016", - "es2017", - "dom" - ], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationDir": "dist/types", - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - // "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - // "outDir": "./dist/lib/", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - // "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - "strictNullChecks": false, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - "strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - "resolveJsonModule": true, /* When true allows the importing of json files in Typescript code */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - "typeRoots": [ - "./node_modules/@types", - "./typings" - ], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - /* Advanced Options */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "outDir": "../../dist" - }, - "include": [ - "./*.ts", - "./config/*.ts" - ], - "exclude": [ - "copyStaticAssets.ts", - "copyBLPConfig.ts", - "replaceBLPConfigPath.ts" - ] - } - \ No newline at end of file diff --git a/jest.config.js b/jest.config.js index ac56d303c0..4bb1c5947e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -131,7 +131,5 @@ module.exports = { `./examples/cactus-example-carbon-accounting-backend/src/test/typescript/integration/admin-enroll-v1-endpoint.test.ts`, `./examples/cactus-example-supply-chain-backend/src/test/typescript/integration/supply-chain-backend-api-calls.test.ts`, `./examples/cactus-example-supply-chain-backend/src/test/typescript/integration/supply-chain-cli-via-npm-script.test.ts`, - `./examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts`, - `./examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-config-files.test.ts`, ], }; diff --git a/yarn.lock b/yarn.lock index 3a9114e90c..2a042d933d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7236,25 +7236,6 @@ __metadata: languageName: unknown linkType: soft -"@hyperledger/cactus-examples-check-connection-ethereum-validator@workspace:examples/cactus-check-connection-ethereum-validator": - version: 0.0.0-use.local - resolution: "@hyperledger/cactus-examples-check-connection-ethereum-validator@workspace:examples/cactus-check-connection-ethereum-validator" - dependencies: - "@hyperledger/cactus-common": 2.0.0-alpha.2 - "@types/escape-html": 1.0.1 - "@types/express": 4.17.20 - "@types/js-yaml": 4.0.8 - "@types/node": 15.14.9 - "@types/shelljs": 0.8.14 - escape-html: 1.0.3 - express: 4.18.2 - js-yaml: 4.1.0 - log4js: 6.9.1 - shelljs: 0.8.5 - socket.io: 4.5.4 - languageName: unknown - linkType: soft - "@hyperledger/cactus-plugin-consortium-manual@2.0.0-alpha.2, @hyperledger/cactus-plugin-consortium-manual@workspace:packages/cactus-plugin-consortium-manual": version: 0.0.0-use.local resolution: "@hyperledger/cactus-plugin-consortium-manual@workspace:packages/cactus-plugin-consortium-manual" @@ -13108,13 +13089,6 @@ __metadata: languageName: node linkType: hard -"@types/js-yaml@npm:4.0.8": - version: 4.0.8 - resolution: "@types/js-yaml@npm:4.0.8" - checksum: a5a77a5a1eac7e7fb667156c251c2b947ca4ddfdda570726369dd50bd5b2b1d0da2d0fb4273d1b10aa1782406d7b3da8923d957df4fb89dbfa1db06f43297de2 - languageName: node - linkType: hard - "@types/json-schema@npm:*, @types/json-schema@npm:^7.0.6, @types/json-schema@npm:^7.0.7, @types/json-schema@npm:^7.0.8": version: 7.0.9 resolution: "@types/json-schema@npm:7.0.9" @@ -13809,16 +13783,6 @@ __metadata: languageName: node linkType: hard -"@types/shelljs@npm:0.8.14": - version: 0.8.14 - resolution: "@types/shelljs@npm:0.8.14" - dependencies: - "@types/glob": ~7.2.0 - "@types/node": "*" - checksum: d49ed5e5494e30a9d22c0d1104af8587a748da8ff372a6bb0aadf4329b4ae88360238473841f444a8eb067b8478829e55570c627c94f50ea45489bd36e99e567 - languageName: node - linkType: hard - "@types/sockjs@npm:^0.3.33": version: 0.3.33 resolution: "@types/sockjs@npm:0.3.33"