Skip to content

Commit

Permalink
feat(LedgerPlugin): add monitoring features on Ledger Plugin Validato…
Browse files Browse the repository at this point in the history
…r for Hyperledger Sawtooth

Signed-off-by: Takuma TAKEUCHI <takeuchi.takuma@fujitsu.com>
  • Loading branch information
takeutak committed Jan 26, 2021
1 parent bcf4a30 commit 958876b
Show file tree
Hide file tree
Showing 21 changed files with 1,177 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/ledger-plugin/sawtooth/validator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist/
6 changes: 6 additions & 0 deletions packages/ledger-plugin/sawtooth/validator/src/.gitignore
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
dependent/ValidatorAuthentication.ts
16 changes: 16 additions & 0 deletions packages/ledger-plugin/sawtooth/validator/src/build/Dockerfile
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,3 @@
import * as shell from 'shelljs';
shell.cp('-R', 'core/CA/', '../dist/core');
shell.cp('-R', 'core/validatorKey/', '../dist/core');
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import * as shell from 'shelljs';
shell.cp('../../../ValidatorAuthentication.ts', './dependent');
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/sawtooth/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;
276 changes: 276 additions & 0 deletions packages/ledger-plugin/sawtooth/validator/src/core/bin/www.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
#!/usr/bin/env node

/*
* Copyright 2019-2020 Fujitsu Laboratories Ltd.
* SPDX-License-Identifier: Apache-2.0
*
* www.js
*/

/* Summary:
* Connector: a part independent of end-chains
*/

/**
* Module dependencies.
*/

import app from '../app';
const debug = require('debug')('connector:server');
import https = require('https');
import { config } from '../config/default';
import fs = require('fs');

// Log settings
import { getLogger } from "log4js";
const logger = getLogger('connector_main[' + process.pid + ']');
logger.level = config.logLevel;

// implementation class of a part dependent of end-chains (server plugin)
//import { ServerPlugin } from '../../dependent/ServerPlugin';
//const Splug = new ServerPlugin();

// destination dependency (MONITOR) implementation class
import { ServerMonitorPlugin } from '../../dependent/ServerMonitorPlugin';
const Smonitor = new ServerMonitorPlugin();

/**
* Get port from environment and store in Express.
*/

const sslport = normalizePort(process.env.PORT || config.sslParam.port);
app.set('port', sslport);

// Specify private key and certificate
const sslParam = {
key: fs.readFileSync(config.sslParam.key),
cert: fs.readFileSync(config.sslParam.cert)
};

/**
* Create HTTPS server.
*/

const server = https.createServer(sslParam, app); // Start as an https server.
const io = require('socket.io')(server);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(sslport, function(){
console.log('listening on *:' + sslport);
});
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
const port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTPS server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

const bind = typeof sslport === 'string'
? 'Pipe ' + sslport
: 'Port ' + sslport;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTPS server "listening" event.
*/

function onListening() {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

io.on('connection', function(client) {
logger.info('Client ' + client.id + ' connected.');

/**
* request: The server plugin's request to execute a function
* @param {JSON} data: Request Body (following format)
* JSON: {
* "func": (string) Function name ,// For example : "transferNumericAsset"
* "args": (Object) argument// for example , {"from" : "xxx" , "to" : "yyy" , "value" : "10,000"}
* }
**/
/*
client.on('request', function(data) {
const func = data.func;
const args = data.args;
console.log('##[HL-BC] Invoke smart contract to transfer asset(D1)');
logger.info('*** REQUEST ***');
logger.info('Client ID :' + client.id);
logger.info('Data :' + JSON.stringify(data));
// Check for the existence of the specified function and call it if it exists.
if (Splug.isExistFunction(func)) {
// Can be called with Server plugin function name.
Splug[func](args)
.then((respObj) => {
logger.info('*** RESPONSE ***');
logger.info('Client ID :' + client.id);
logger.info('Response :' + JSON.stringify(respObj));
client.emit("response", respObj);
})
.catch((errObj) => {
logger.error('*** ERROR ***');
logger.error('Client ID :' + client.id);
logger.error('Detail :' + JSON.stringify(errObj));
client.emit("connector_error", errObj);
});
} else {
// No such function
const emsg = "Function " + func + " not found!";
logger.error(emsg);
const retObj = {
"status" : 504,
"errorDetail" : emsg
};
client.emit("connector_error", retObj);
}
});
// TODO: "request2" -> "request"
client.on('request2', function(data) {
const methodType = data.method.type;
// const args = data.args;
const args = {};
args["contract"] = data.contract;
args["method"] = data.method;
args["args"] = data.args;
if (data.reqID !== undefined) {
logger.info(`##add reqID: ${data.reqID}`);
args["reqID"] = data.reqID;
}
console.log('##[HL-BC] Invoke smart contract to transfer asset(D1)');
logger.info('*** REQUEST ***');
logger.info('Client ID :' + client.id);
logger.info('Data :' + JSON.stringify(data));
// Check for the existence of the specified function and call it if it exists.
if (methodType === "web3Eth") {
// Can be called with Server plugin function name.
Splug.web3Eth(args)
.then((respObj) => {
logger.info('*** RESPONSE ***');
logger.info('Client ID :' + client.id);
logger.info('Response :' + JSON.stringify(respObj));
client.emit("response", respObj);
})
.catch((errObj) => {
logger.error('*** ERROR ***');
logger.error('Client ID :' + client.id);
logger.error('Detail :' + JSON.stringify(errObj));
client.emit("connector_error", errObj);
});
} else if (methodType === "contract") {
// Can be called with Server plugin function name.
Splug.contract(args)
.then((respObj) => {
logger.info('*** RESPONSE ***');
logger.info('Client ID :' + client.id);
logger.info('Response :' + JSON.stringify(respObj));
client.emit("response", respObj);
})
.catch((errObj) => {
logger.error('*** ERROR ***');
logger.error('Client ID :' + client.id);
logger.error('Detail :' + JSON.stringify(errObj));
client.emit("connector_error", errObj);
});
} else {
// No such function
const emsg = "method.type " + methodType + " not found!";
logger.error(emsg);
const retObj = {
"status" : 504,
"errorDetail" : emsg
};
client.emit("connector_error", retObj);
}
});
*/

/**
* startMonitor: starting block generation event monitoring
**/
client.on('startMonitor', function(data) {
// Callback to receive monitoring results
const cb = function(callbackData) {
let emitType = "";
if(callbackData.status == 200) {
emitType = "eventReceived";
logger.info('event data callbacked.');
} else {
emitType = "monitor_error";
}
client.emit(emitType, callbackData);
}

Smonitor.startMonitor(client.id, data.filterKey, cb);
});

/**
* stopMonitor: block generation events monitoring stopping
**/
/*
// I think it is more common to stop from the disconnect described later, but I will prepare for it.
client.on('stopMonitor', function(reason) {
Smonitor.stopMonitor(client.id);
});
client.on('disconnect', function(reason) {
// Unexpected disconnect as well as explicit disconnect request can be received here
logger.info('Client ' + client.id + ' disconnected.');
logger.info('Reason :' + reason);
// Stop monitoring if disconnected client is for event monitoring
Smonitor.stopMonitor(client.id);
});
*/

});

Loading

0 comments on commit 958876b

Please sign in to comment.