Skip to content

Commit

Permalink
test: wip: add tests for verifier in cmd-socketio-server
Browse files Browse the repository at this point in the history
tests

Closes: hyperledger-cacti#123
Signed-off-by: Michal Bajer <michal.bajer@fujitsu.com>
  • Loading branch information
outSH committed Nov 22, 2021
1 parent 4beab22 commit 38b2dbf
Show file tree
Hide file tree
Showing 8 changed files with 918 additions and 78 deletions.
2 changes: 2 additions & 0 deletions packages/cactus-cmd-socketio-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
"@types/jest": "^26.0.19",
"@typescript-eslint/eslint-plugin": "^4.31.1",
"@typescript-eslint/parser": "^4.31.1",
"@types/socket.io": "^2.0.4",
"@types/socket.io-client": "^1.4.36",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,15 @@ export class ConfigUtil {
* @return {object} Merged objects
*/
private static mergeObjects(target: object, source: object): object {
const isObject = (obj) =>
const isObject = (obj: unknown) =>
obj && typeof obj === "object" && !Array.isArray(obj);
const mergeObject = Object.assign({}, target);
if (isObject(target) && isObject(source)) {
for (const [sourceKey, sourceValue] of Object.entries(source)) {
const targetValue = target[sourceKey];
const targetValue = (target as { [key: string]: any })[sourceKey];
if (isObject(sourceValue) && target.hasOwnProperty(sourceKey)) {
mergeObject[sourceKey] = ConfigUtil.mergeObjects(
targetValue,
sourceValue
);
(mergeObject as { [key: string]: any })[sourceKey] =
ConfigUtil.mergeObjects(targetValue, sourceValue);
} else {
Object.assign(mergeObject, { [sourceKey]: sourceValue });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function makeApiInfoList(targetApiInfo: any): ApiInfo[] {
}

// store on socket
const socketArray = [];
const socketArray: any[] = [];

// Returns the index of socketArray as a return value
export function addSocket(socket: any): number {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import {
deleteAndDisconnectSocke,
} from "./DriverCommon";
import { LedgerOperation } from "../business-logic-plugin/LedgerOperation";
import { Socket } from "dgram";
import { ConfigUtil } from "../routing-interface/util/ConfigUtil";
import { VerifierAuthentication } from "./VerifierAuthentication";
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

const io = require("socket.io-client");
import io from "socket.io-client";
import { Socket } from "socket.io-client";

const fs = require("fs");
const path = require("path");
Expand All @@ -44,24 +44,35 @@ type VALIDATOR_TYPE = typeof VALIDATOR_TYPE[keyof typeof VALIDATOR_TYPE]; // 'so
// abolish template-trade
// const validatorRregistryConf: any = yaml.safeLoad(fs.readFileSync("/etc/cactus/validator-registry.yaml", 'utf8'));

type LedgerInfoT = {
validatorID: string;
validatorType: string;
validatorURL: string;
validatorKeyPath: string;
apiInfo: object;
};

export class Verifier implements IVerifier {
validatorID = "";
validatorType = "";
validatorUrl = "";
validatorKeyPath = "";
apiInfo: {} = null;
apiInfo: object = {};
counterReqID = 1;
// TODO - why not Map()?
eventListenerHash: { [key: string]: VerifierEventListener } = {}; // Listeners for events from Ledger
static mapUrlSocket: Map<string, Socket> = new Map();
static mapUrlSocket: Map<string, SocketIOClient.Socket> = new Map();
checkValidator: (key: string, data: string) => Promise<any> =
VerifierAuthentication.verify;

constructor(ledgerInfo: string) {
// TODO: Configure the Verifier based on the connection information
const ledgerInfoObj: {} = JSON.parse(ledgerInfo);
this.validatorID = ledgerInfoObj["validatorID"];
this.validatorType = ledgerInfoObj["validatorType"];
this.validatorUrl = ledgerInfoObj["validatorURL"];
this.validatorKeyPath = ledgerInfoObj["validatorKeyPath"];
this.apiInfo = ledgerInfoObj["apiInfo"];
const ledgerInfoObj = JSON.parse(ledgerInfo) as LedgerInfoT;
this.validatorID = ledgerInfoObj.validatorID;
this.validatorType = ledgerInfoObj.validatorType;
this.validatorUrl = ledgerInfoObj.validatorURL;
this.validatorKeyPath = ledgerInfoObj.validatorKeyPath;
this.apiInfo = ledgerInfoObj.apiInfo;

if (VALIDATOR_TYPE.SOCKET === this.validatorType) {
// create socket instance assosiated with validatorUrl if it has not created yet
Expand All @@ -74,7 +85,7 @@ export class Verifier implements IVerifier {
logger.debug(`socketOptions = ${JSON.stringify(socketOptions)}`);
Verifier.mapUrlSocket.set(
this.validatorID,
io(this.validatorUrl, socketOptions)
io(this.validatorUrl, socketOptions),
);
}
}
Expand All @@ -84,13 +95,13 @@ export class Verifier implements IVerifier {
public sendAsyncRequest(
contract: object,
method: object,
args: object
args: object,
): Promise<void> {
return new Promise((resolve, reject) => {
logger.debug(
`call: sendAsyncRequest, contract = ${JSON.stringify(
contract
)}, method = ${JSON.stringify(method)}, args = ${args}`
contract,
)}, method = ${JSON.stringify(method)}, args = ${args}`,
);
try {
// verifier comunicate with socket
Expand Down Expand Up @@ -130,11 +141,14 @@ export class Verifier implements IVerifier {
private requestLedgerOperationNeo(
contract: object,
method: object,
args: object
args: object,
): void {
logger.debug("call : requestLedgerOperation");
try {
const socket = Verifier.mapUrlSocket.get(this.validatorID);
if (socket === undefined) {
throw Error(`No socket for validator with ID ${this.validatorID}`);
}

const requestData: {} = {
contract: contract,
Expand All @@ -153,17 +167,18 @@ export class Verifier implements IVerifier {
public sendSyncRequest(
contract: object,
method: object,
args: object
args: object,
): Promise<any> {
return new Promise((resolve, reject) => {
logger.debug("call : sendSyncRequest");
try {
logger.debug(
`##in sendSyncRequest, contract = ${JSON.stringify(
contract
)}, method = ${JSON.stringify(method)}, args = ${JSON.stringify(
args
)}, `
"##in sendSyncRequest, contract:",
contract,
"method:",
method,
"args:",
args,
);
let responseFlag = false;

Expand All @@ -173,6 +188,10 @@ export class Verifier implements IVerifier {

// Preparing socket
const socket = Verifier.mapUrlSocket.get(this.validatorID);
if (socket === undefined) {
throw Error(`No socket for validator with ID ${this.validatorID}`);
}

socket.on("connect_error", (err: object) => {
logger.error("##connect_error:", err);
// end communication
Expand All @@ -191,24 +210,23 @@ export class Verifier implements IVerifier {
reject(err);
});
socket.on("response", (result: any) => {
logger.debug(`#[recv]response, res: ${result}`);
logger.debug("#[recv]response, res:", result);
if (reqID === result.id) {
responseFlag = true;

VerifierAuthentication.verify(
this.validatorKeyPath,
result.resObj.data
)
this.checkValidator(this.validatorKeyPath, result.resObj.data)
.then((decodedData) => {
const resultObj = {
status: result.resObj.status,
data: decodedData.result,
};
logger.debug(`resultObj = ${resultObj}`);
logger.debug("resultObj =", resultObj);
// Result reply
resolve(resultObj);
})
.catch((err) => {
responseFlag = false; // otherwise hangs when checkValidator failed
// TODO - will hang if checkValidator takes to long
logger.error(err);
});
}
Expand All @@ -221,19 +239,19 @@ export class Verifier implements IVerifier {
args: args,
reqID: reqID,
};
logger.debug(`requestData : ${requestData}`);
logger.debug("requestData:", requestData);
socket.emit("request2", requestData);
logger.debug("set timeout");

// Time-out setting
setTimeout(() => {
if (responseFlag === false) {
logger.debug("requestTimeout reqID : " + reqID);
logger.debug("requestTimeout reqID:", reqID);
resolve({ status: 504, amount: 0 });
}
}, config.verifier.syncFunctionTimeoutMillisecond);
} catch (err) {
logger.error(`##Error: sendSyncRequest, ${err}`);
logger.error("##Error: sendSyncRequest:", err);
reject(err);
}
});
Expand All @@ -242,16 +260,16 @@ export class Verifier implements IVerifier {
private requestLedgerOperationHttp(
contract: object,
method: object,
args: object
args: object,
): Promise<void> {
return new Promise((resolve, reject) => {
try {
logger.debug(
`##in requestLedgerOperationHttp, contract = ${JSON.stringify(
contract
contract,
)}, method = ${JSON.stringify(method)}, args = ${JSON.stringify(
args
)}`
args,
)}`,
);
const eventListenerHash = this.eventListenerHash;
const validatorID = this.validatorID;
Expand All @@ -273,23 +291,23 @@ export class Verifier implements IVerifier {
for (const key in eventListenerHash) {
logger.debug(
`key : ${key}, eventListenerHash[key] : ${JSON.stringify(
eventListenerHash[key]
)}`
eventListenerHash[key],
)}`,
);
eventListener = eventListenerHash[key];
eventListener.onEvent(event);
}
} else {
logger.debug(
`##requestLedgerOperationHttp eventListener does not exist`
`##requestLedgerOperationHttp eventListener does not exist`,
);
}
logger.debug(`##after onEvent()`);

// resolve(responseObj);
} catch (err) {
logger.error(
`##Error: requestLedgerOperationHttp#httpReq.onload, ${err}`
`##Error: requestLedgerOperationHttp#httpReq.onload, ${err}`,
);
}
};
Expand All @@ -298,12 +316,19 @@ export class Verifier implements IVerifier {
};

logger.debug(`validatorUrl: ${this.validatorUrl}`);
httpReq.open("POST", this.validatorUrl + method["command"]);
httpReq.open(
"POST",
this.validatorUrl + (method as { [key: string]: string })["command"],
);
// httpReq.setRequestHeader('content-type', 'application/json');
httpReq.setRequestHeader("Content-Type", "application/json");
// httpReq.send(args['args']);
logger.debug(`args['args']: ${JSON.stringify(args["args"])}`);
httpReq.send(JSON.stringify(args["args"]));
logger.debug(
`args['args']: ${JSON.stringify(
(args as { [key: string]: any })["args"],
)}`,
);
httpReq.send(JSON.stringify((args as { [key: string]: any })["args"]));

resolve();
} catch (err) {
Expand All @@ -328,7 +353,7 @@ export class Verifier implements IVerifier {
public startMonitor(
id: string,
options: Object,
eventListener: VerifierEventListener
eventListener: VerifierEventListener,
): Promise<void> {
return new Promise((resolve, reject) => {
logger.debug("call : startMonitor");
Expand All @@ -337,10 +362,13 @@ export class Verifier implements IVerifier {

if (Object.keys(this.eventListenerHash).length > 0) {
logger.debug(
`##in startMonitor, validatorUrl = ${this.validatorUrl}`
`##in startMonitor, validatorUrl = ${this.validatorUrl}`,
);

const socket = Verifier.mapUrlSocket.get(this.validatorID);
if (socket === undefined) {
throw Error(`No socket for validator with ID ${this.validatorID}`);
}

socket.on("connect_error", (err: object) => {
logger.error("##connect_error:", err);
Expand Down Expand Up @@ -368,19 +396,16 @@ export class Verifier implements IVerifier {
logger.debug(
`##eventReceived Object.keys(this.eventListenerHash).length : ${
Object.keys(this.eventListenerHash).length
}`
}`,
);
if (Object.keys(this.eventListenerHash).length > 0) {
VerifierAuthentication.verify(
this.validatorKeyPath,
res.blockData
)
this.checkValidator(this.validatorKeyPath, res.blockData)
.then((decodedData) => {
const resultObj = {
status: res.status,
blockData: decodedData.blockData,
};
logger.debug(`resultObj = ${resultObj}`);
logger.debug("resultObj =", resultObj);
const event = new LedgerEvent();
event.verifierId = this.validatorID;
logger.debug(`##event.verifierId: ${event.verifierId}`);
Expand All @@ -389,7 +414,7 @@ export class Verifier implements IVerifier {
const eventListener = this.eventListenerHash[key];
if (eventListener != null) {
logger.debug(
`##set eventListener: ${eventListener}, ${this.constructor.name}, ${this.validatorID}`
`##set eventListener: ${eventListener}, ${this.constructor.name}, ${this.validatorID}`,
);
eventListener.onEvent(event);
} else {
Expand Down Expand Up @@ -438,7 +463,10 @@ export class Verifier implements IVerifier {
}
if (Object.keys(this.eventListenerHash).length === 0) {
const socket = Verifier.mapUrlSocket.get(this.validatorID);
logger.debug("##emit: startMonitor");
if (socket === undefined) {
throw Error(`No socket for validator with ID ${this.validatorID}`);
}
logger.debug("##emit: stopMonitor");
socket.emit("stopMonitor");
}
} catch (err) {
Expand All @@ -448,10 +476,12 @@ export class Verifier implements IVerifier {

private setEventListener(
appId: string,
eventListener: VerifierEventListener | null
eventListener: VerifierEventListener | null,
): void {
logger.debug(`##call : setEventListener`);
this.eventListenerHash[appId] = eventListener;
if (eventListener) {
this.eventListenerHash[appId] = eventListener;
}
return;
}

Expand Down
Loading

0 comments on commit 38b2dbf

Please sign in to comment.