From 8d7ab85f47927b4fdca0787bb82ca62ee386ddff Mon Sep 17 00:00:00 2001 From: stepniowskip Date: Mon, 6 Dec 2021 14:50:39 +0100 Subject: [PATCH] test: ethereum BLP with connectivity check Add BLP that checks connectivity between ethereum ledger and connector Closes: #1628 Signed-off-by: stepniowskip --- .../BusinessLogicCheckEthereumValidator.ts | 89 ++++++++ .../README.MD | 120 +++++++++++ .../RequestInfo.ts | 12 ++ .../TestEthereumBalance.ts | 60 ++++++ .../check-ethereum-validator.ts | 62 ++++++ .../config/BLP_config.ts | 13 ++ .../config/default.yaml | 6 + .../config/usersetting.yaml | 24 +++ .../copyBLPConfig.ts | 6 + .../copyStaticAssets.ts | 4 + .../package.json | 20 ++ .../replaceBLPConfigPath.ts | 18 ++ .../check-connection-to-ledger.test.ts | 204 ++++++++++++++++++ .../tsconfig.json | 81 +++++++ jest.config.js | 1 + .../TransactionManagement.ts | 3 +- 16 files changed, 722 insertions(+), 1 deletion(-) create mode 100644 examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/README.MD create mode 100644 examples/cactus-check-connection-ethereum-validator/RequestInfo.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/TestEthereumBalance.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/config/BLP_config.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/config/default.yaml create mode 100644 examples/cactus-check-connection-ethereum-validator/config/usersetting.yaml create mode 100644 examples/cactus-check-connection-ethereum-validator/copyBLPConfig.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/copyStaticAssets.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/package.json create mode 100644 examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts create mode 100644 examples/cactus-check-connection-ethereum-validator/tsconfig.json diff --git a/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts b/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts new file mode 100644 index 0000000000..f417cc1687 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/BusinessLogicCheckEthereumValidator.ts @@ -0,0 +1,89 @@ +import { 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"; + +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("called startTransaction()"); + + const requestInfo: RequestInfo = new RequestInfo(); + requestInfo.setBusinessLogicID(businessLogicID); + requestInfo.setTradeID(tradeID); + + const tradeInfo: TradeInfo = new TradeInfo( + requestInfo.businessLogicID, + requestInfo.tradeID, + ); + + this.executeTransaction(tradeInfo); + } + + executeTransaction(tradeInfo: TradeInfo) { + logger.debug( + `##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}`, + ); + + const validator = JSON.parse( + transactionManagement.getValidatorToUse(tradeInfo.businessLogicID), + ); + const ethereumValidator = validator["validatorID"][0]; + const verifier = verifierFactory.getVerifier( + ethereumValidator, + moduleName, + {}, + false, + ); + + this.sendRequest(verifier); + } + + sendRequest(verifier: Verifier) { + const contract = {}; + const method = { command: "getBalance", type: "web3Eth" }; + const accountEthereum = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; + const args = { args: [accountEthereum] }; + + logger.debug(`##sendRequest(): calling verifier.sendSyncRequest()`); + verifier + .sendSyncRequest(contract, method, args) + .then((response) => { + logger.debug( + `got response: \n status code: ${response.status} \n Ethereum balance: ${response.data}`, + ); + if (response.status == 504 && response.data === undefined) { + logger.error(`Could not establish connection to ethereum ledger`); + } else { + logger.info(`Successfully connected to ethereum ledger`); + } + return { status: response.status, data: response.data }; + }) + .catch((err) => { + logger.error(err); + }); + } +} diff --git a/examples/cactus-check-connection-ethereum-validator/README.MD b/examples/cactus-check-connection-ethereum-validator/README.MD new file mode 100644 index 0000000000..c0cbe18e5a --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/README.MD @@ -0,0 +1,120 @@ +# cactus-check-connection-ethereum-validator + +Business Logic Plugin for checking communication with ethereum ledger via cactus-plugin-ledger-connector-go-ethereum-socketio + +### 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 + ``` + +### How to use + +Application checks connection by getting balance on ethereum ledger +Test account address is: + + 06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97 + + +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 on Ethereum ledger run: + + + curl localhost:5034/api/v1/bl/check-ethereum-validator/06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97 + + +# Testing + +### Test cases + +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 + +### 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 testsuite: + +1. In cactus/jest.config.js comment line: + + ``` + `./examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.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 + ``` \ 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 new file mode 100644 index 0000000000..1113c7cce4 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/RequestInfo.ts @@ -0,0 +1,12 @@ +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/TestEthereumBalance.ts b/examples/cactus-check-connection-ethereum-validator/TestEthereumBalance.ts new file mode 100644 index 0000000000..f05e88e9d2 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/TestEthereumBalance.ts @@ -0,0 +1,60 @@ +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"; + +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = "TestEthereumBalance"; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +export class TestEthereumBalance { + 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 createVerifier(): void { + logger.debug("create verifierEthereum"); + + this.verifierEthereum = verifierFactory.getVerifier( + this.validatorId, + this.appId, + this.monitorOptions, + this.monitorMode, + ); + } + + getBalance(account: string): Promise { + return new Promise((resolve, reject) => { + this.createVerifier(); + + const contract = {}; + const method = { type: "web3Eth", command: "getBalance" }; + const args = { args: [account] }; + + this.verifierEthereum + .sendSyncRequest(contract, method, args) + .then((result) => { + const response = { + status: result.status, + amount: parseFloat(result.data), + }; + resolve(response); + }) + .catch((err) => { + logger.error(err); + reject(err); + }); + }); + } +} diff --git a/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts b/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts new file mode 100644 index 0000000000..4d3518e21c --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/check-ethereum-validator.ts @@ -0,0 +1,62 @@ +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, + BadRequestError, +} 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 { TestEthereumBalance } from "./TestEthereumBalance"; + +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(err.message); + return true; + } + logger.error(`Error caught: ${err.statusCode}, ${err.message}`); + return false; +} + +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 testEthereumBalance: TestEthereumBalance = new TestEthereumBalance(); + +router.get("/:account", (req: Request, res: Response, next: NextFunction) => { + try { + logger.info("check-ethereum-validator()"); + testEthereumBalance + .getBalance(req.params.account) + .then((result) => { + logger.debug(JSON.stringify(result)); + res.status(200).json(result); + }) + .catch((err) => { + logger.error(err); + }); + } 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 new file mode 100644 index 0000000000..6c68b9ad4a --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/config/BLP_config.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..728e76d15c --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/config/default.yaml @@ -0,0 +1,6 @@ +checkEthereumValidator: + connector: + validatorID: 84jUisrs + chainName: geth1 + +logLevel: debug \ 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 new file mode 100644 index 0000000000..ace67b3cad --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/config/usersetting.yaml @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000000..4ca06790b4 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/copyBLPConfig.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..ca8a0715d0 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/copyStaticAssets.ts @@ -0,0 +1,4 @@ +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 new file mode 100644 index 0000000000..87d987803d --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/package.json @@ -0,0 +1,20 @@ +{ + "name": "check-connection-ethereum-validator", + "version": "1.0.0-rc.3", + "private": true, + "scripts": { + "start": "node ../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/www.js", + "debug": "nodemon --inspect ../../dist/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/www.js", + "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", + "tslint": "tslint -c tslint.json -p tsconfig.json './*.ts'", + "copy-static-assets": "ts-node copyStaticAssets.ts", + "copy-blp-config": "ts-node copyBLPConfig.ts", + "replace-blp-config-path": "ts-node replaceBLPConfigPath.ts", + "init-check-connection-ethereum-validator": "ln -s ../examples/cactus-check-connection-ethereum-validator/node_modules ../../dist/node_modules" + }, + "dependencies": { + "@types/node": "15.14.7", + "socket.io": "4.1.3" + } +} diff --git a/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts b/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts new file mode 100644 index 0000000000..55213da67f --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/replaceBLPConfigPath.ts @@ -0,0 +1,18 @@ +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-connection-to-ledger.test.ts b/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts new file mode 100644 index 0000000000..681f3c2b0b --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/src/test/typescript/integration/check-connection-to-ledger.test.ts @@ -0,0 +1,204 @@ +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): any { + 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) { + console.log(`${hostName}:${port} is down: ${error.message}`); + resolve(false); + }); + sock.connect(port, hostName); + }); +} + +function sendRequest(options: Record, postData: string): any { + 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): any { + 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); + } + }); + }); +} + +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(""); +}); + +test("Check if there is proper communication between ledger and connector", async () => { + const postData = ""; + const account = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; + const path = `/api/v1/bl/check-ethereum-validator/${account}`; + const options = createOptionObj(path, "GET", postData); + + const response = await sendRequest(options, postData); + logger.debug(`Received response: [${response}]`); + + // 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(); +}); diff --git a/examples/cactus-check-connection-ethereum-validator/tsconfig.json b/examples/cactus-check-connection-ethereum-validator/tsconfig.json new file mode 100644 index 0000000000..c6aabfe8e9 --- /dev/null +++ b/examples/cactus-check-connection-ethereum-validator/tsconfig.json @@ -0,0 +1,81 @@ +{ + "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 b922f98d5f..1489ba5f14 100644 --- a/jest.config.js +++ b/jest.config.js @@ -153,5 +153,6 @@ 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`, ], }; diff --git a/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TransactionManagement.ts b/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TransactionManagement.ts index 589f49bdaf..c4eef4bf46 100644 --- a/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TransactionManagement.ts +++ b/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TransactionManagement.ts @@ -51,7 +51,8 @@ export class TransactionManagement implements VerifierEventListener { if ( businessLogicID === "guks32pf" || businessLogicID === "h40Q9eMD" || - businessLogicID === "j71S9gLN" + businessLogicID === "j71S9gLN" || + businessLogicID === "jLn76rgB" ) { const blp = getTargetBLPInstance(businessLogicID); if (blp === null) {