Skip to content

Commit

Permalink
feat(validator): go-ethereum validator including execSyncFunction
Browse files Browse the repository at this point in the history
Signed-off-by: Takuma TAKEUCHI <takeuchi.takuma@fujitsu.com>
  • Loading branch information
takeutak committed Nov 24, 2020
1 parent 869933b commit 9e520d0
Show file tree
Hide file tree
Showing 53 changed files with 2,211 additions and 2 deletions.
6 changes: 5 additions & 1 deletion examples/cartrade/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
## Premise
- Launch two Validators (For Ethereum and Fabric)
- for Ethereum:
- `/packages/ledger-plugin/go-ethereum/validator`
- `/packages/ledger-plugin/go-ethereum-ts/validator`
- "validatorUrl": `https://localhost:5050`,
1. cd `/packages/ledger-plugin/go-ethereum-ts/validator/src`
1. npm install
1. npm run build
1. npm run start
- for Fabric:
- `/packages/ledger-plugin/fabric/validator`
- "validatorUrl": `https://localhost:5040`,
Expand Down
4 changes: 4 additions & 0 deletions examples/cartrade/config/usersetting.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@
"rejectUnauthorized": false,
"reconnection": false,
"timeout": 20000
},
"verifier": {
"maxCounterRequestID":100,
"syncFunctionTimeoutMillisecond":5000
}
}
2 changes: 1 addition & 1 deletion examples/cartrade/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@hyperledger/cactus",
"name": "@hyperledger-labs/cactus",
"private": true,
"scripts": {
"run-ci": "./tools/ci.sh",
Expand Down
2 changes: 2 additions & 0 deletions packages/business-logic-plugin/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import bodyParser = require('body-parser');
import indexRouter from '../routing-interface/routes/index';
import loginRouter from '../routing-interface/routes/login';
import tradesRouter from '../routing-interface/routes/trades';
import balanceRouter from '../routing-interface/routes/balance';

const app: express.Express = express();

Expand All @@ -31,6 +32,7 @@ app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/api/v1/bl/login/', loginRouter);
app.use('/api/v1/bl/trades/', tradesRouter);
app.use('/api/v1/bl/balance/', balanceRouter);

// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: NextFunction) => {
Expand Down
4 changes: 4 additions & 0 deletions packages/config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@
"rejectUnauthorized": false,
"reconnection": false,
"timeout": 20000
},
"verifier": {
"maxCounterRequestID":100,
"syncFunctionTimeoutMillisecond":5000
}
}
78 changes: 78 additions & 0 deletions packages/ledger-plugin/VerifierBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export class VerifierBase implements Verifier {
validatorID: string = "";
validatorUrl: string = "";
apiInfo: {} = null;
counterReqID: number = 1;
eventListener: VerifierEventListener | null = null; // Listener for events from Ledger

constructor(ledgerInfo: string) {
Expand All @@ -43,6 +44,7 @@ export class VerifierBase implements Verifier {
return makeApiInfoList(this.apiInfo);
};

// NOTE: This function will be deleted due to the updating of API functions
requestLedgerOperation(param: LedgerOperation): void {
logger.debug('call : requestLedgerOperation');
try {
Expand All @@ -69,6 +71,75 @@ export class VerifierBase implements Verifier {
throw err;
}
};

execSyncFunction(param: LedgerOperation): Promise<any> {
return new Promise((resolve, reject) => {
logger.debug('call : execSyncFunction');
try {
logger.debug(`##in execSyncFunction, LedgerOperation = ${JSON.stringify(param)}`);
let responseFlag: boolean = false;

const reqID = this.genarateReqID();
logger.debug(`##execSyncFunction, reqID = ${reqID}`);

const socketOptions: {} = {
rejectUnauthorized: config.socketOptions.rejectUnauthorized,
reconnection: config.socketOptions.reconnection,
timeout: config.socketOptions.timeout,
};
logger.debug(`socketOptions = ${JSON.stringify(socketOptions)}`);
const socket: Socket = io(this.validatorUrl, socketOptions);
socket.on("connect_error", (err: object) => {
logger.error("##connect_error:", err);
// end communication
socket.disconnect();
reject(err);
});
socket.on("connect_timeout", (err: object) => {
logger.error("####Error:", err);
// end communication
socket.disconnect();
reject(err);
});
socket.on("error", (err: object) => {
logger.error("####Error:", err);
socket.disconnect();
reject(err);
});
socket.on("response", (result: any) => {
logger.debug("#[recv]response, res: " + json2str(result));
if (reqID === result.id) {
responseFlag = true;
logger.debug(`##execSyncFunction: resObj: ${JSON.stringify(result.resObj)}`);
resolve(result.resObj);
}
});

const apiType: string = param.apiType;
//const progress: string = param.progress;
let data: {} = param.data;
data["reqID"] = reqID;
const requestData: {} = {
func: apiType,
args: data
};
logger.debug('requestData : ' + JSON.stringify(requestData));
socket.emit('request', requestData);
logger.debug('set timeout');

setTimeout(() => {
if (responseFlag === false) {
logger.debug('requestTimeout reqID : ' + reqID);
resolve({"status":504, "amount":0});
}
}, config.verifier.syncFunctionTimeoutMillisecond);
}
catch (err) {
logger.error(`##Error: execSyncFunction, ${err}`);
reject(err);
}
});
}

startMonitor(): Promise<LedgerEvent> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -173,6 +244,13 @@ export class VerifierBase implements Verifier {
this.eventListener = eventListener;
return;
};

genarateReqID(): string {
if (this.counterReqID > config.verifier.maxCounterRequestID) {
this.counterReqID = 1;
}
return `${this.validatorID}_${this.counterReqID++}`;
}

// Validator -> Verifier
// NOTE: The following methods are not implemented this time
Expand Down
1 change: 1 addition & 0 deletions packages/ledger-plugin/go-ethereum-ts/validator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist/
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
core/node_modules/
core/package-lock.json
dependent/node_modules/
dependent/package-lock.json
core/npm-debug.log

17 changes: 17 additions & 0 deletions packages/ledger-plugin/go-ethereum-ts/validator/src/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!--
Copyright 2019-2020 Fujitsu Laboratories Ltd.
SPDX-License-Identifier: Apache-2.0
README.md
-->
# BIF-trial(Validator)

## Assumption
- geth1(geth-docker) is running
- Specify the geth1 URL to connect to with "validatorUrl" in "config/default.js"

## Run
<pre>
cd core
node ./bin/www.js
</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 2019-2020 Fujitsu Laboratories Ltd.
# SPDX-License-Identifier: Apache-2.0
FROM hyperledger/fabric-ccenv:x86_64-1.0.4
#ENV http_proxy $HTTP_PROXY
#ENV https_proxy $HTTP_PROXY
#ENV HTTP_PROXY $HTTP_PROXY
#ENV HTTPS_PROXY $HTTP_PROXY
#ENV NO_PROXY "rest-server,ec1-connector,ec2-connector,geth1,geth2"
RUN apt update
RUN apt-get install -y screen
RUN apt-get install -y npm
#RUN npm -g config set proxy $HTTP_PROXY
RUN npm -g install n
RUN n --version
RUN n 8.9.0
RUN npm -g install express
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import * as shell from 'shelljs';
shell.cp('-R', 'core/CA/', '../dist/core');
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-----BEGIN CERTIFICATE-----
MIIBdTCCARoCCQC/F+Mh551QzDAKBggqhkjOPQQDAjBCMQswCQYDVQQGEwJKUDEQ
MA4GA1UECAwHZXNqbXMxMjEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkg
THRkMB4XDTE4MDYyNzA3MjIzNVoXDTI4MDYyNDA3MjIzNVowQjELMAkGA1UEBhMC
SlAxEDAOBgNVBAgMB2Vzam1zMTIxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMg
UHR5IEx0ZDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDPpSD2w0zrqJKraGD1b
5Jq2sDuacThSUqi7fvz8oyrWtuKDjZ15zIaSOtak6XRxFh9V9Gokdg5GNbW/pTZc
TuowCgYIKoZIzj0EAwIDSQAwRgIhAKH6ERsyd5bpEMIkY4clPqguwDWoTLk2VKq6
ONEhUqotAiEA4yJxGmZpFdRScG2gDUIF2VDeX+XfHdJI2J41hyW9/zI=
-----END CERTIFICATE-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-----BEGIN CERTIFICATE REQUEST-----
MIH9MIGkAgEAMEIxCzAJBgNVBAYTAkpQMRAwDgYDVQQIDAdlc2ptczEyMSEwHwYD
VQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjO
PQMBBwNCAAQz6Ug9sNM66iSq2hg9W+SatrA7mnE4UlKou378/KMq1rbig42decyG
kjrWpOl0cRYfVfRqJHYORjW1v6U2XE7qoAAwCgYIKoZIzj0EAwIDSAAwRQIgCUA1
B5mZK7Hx79J1xBb0MGwuoUkt4bGPXbHqWEMZXQMCIQCRgadPkrNw56+pT5MVxA5K
vV6xTgmxUYrYnpkR4tptqQ==
-----END CERTIFICATE REQUEST-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEICIlCfK3zMTFzUgdaj01LAHjJmHlbg6Xql9+i70iPz5EoAoGCCqGSM49
AwEHoUQDQgAEM+lIPbDTOuokqtoYPVvkmrawO5pxOFJSqLt+/PyjKta24oONnXnM
hpI61qTpdHEWH1X0aiR2DkY1tb+lNlxO6g==
-----END EC PRIVATE KEY-----
46 changes: 46 additions & 0 deletions packages/ledger-plugin/go-ethereum-ts/validator/src/core/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2019-2020 Fujitsu Laboratories Ltd.
* SPDX-License-Identifier: Apache-2.0
*
* app.js
*/

/* Summary:
*
*/

import { NextFunction, Request, Response } from 'express';
import createError = require('http-errors');
import express = require('express');
import cookieParser = require('cookie-parser');
import bodyParser = require('body-parser');

const app: express.Express = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: NextFunction) => {
next(createError(404));
});

// error handler
app.use((err: { message: string, status?: number }, req: Request, res: Response, next: NextFunction) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// set erreor response
const errorResponse: {} = {
"statusCode": err.status || 500,
"message": err.message
};

// render the error page
res.status(err.status || 500);
res.send(errorResponse);
});

export default app;
Loading

0 comments on commit 9e520d0

Please sign in to comment.