Skip to content

Commit

Permalink
feat(examples): add example/cartrade applications
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 Aug 26, 2020
1 parent 5abe629 commit 769c087
Show file tree
Hide file tree
Showing 66 changed files with 2,994 additions and 0 deletions.
4 changes: 4 additions & 0 deletions examples/cartrade/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
package-lock.json
TransactionInfo.json
lint.log
76 changes: 76 additions & 0 deletions examples/cartrade/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# example-cartrade

## Premise
- Launch two Validators (For ethereim and fabric)
- for Ethereum:
- `/packages/ledger-plugin/go-ethereum/validator`
- "validatorUrl": `https://localhost:5050`,
- for Fabric:
- `/packages/ledger-plugin/fabric/validator`
- "validatorUrl": `https://localhost:5040`,

- The following drivers are operating normally (* It is also necessary to check the operation.).
- for Ethereum:
- `/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.js`
- for Fabric:
- `/packages/ledger-plugin/fabric/validator/unit-test/queryCar.js`
- `/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js`

## Boot method
1. cd `/examples/cartrade`
1. npm install
1. Modify the following information for your environment
- corrected escrow account information, etc. on `config/default.json`
- cartradeInfo.fabric.submitter.certificate (certificate for admin)
- cartradeInfo.fabric.submitter.pkey (admin private key)
- carriadeInfo.ethereum.fromAddressPkey (private key of fromAddress)
- cartradeInfo.ethereum.escrowAddress (Address of the escrow account)
- carriadeInfo.ethereum.escrowAddressPkey (secret key of the escrow account)
- applicationHostInfo.hostName (URL of the host on the Location header)
- applicationHostInfo.hostPort (The port number of Rounting-interface HTTP server)
1. npm run build
1. npm run start
- cartrade application boots on port 5034.

## How to use this application
- Run with curl, etc. Currently only POST is available.
- Examples of curl POSTs:.
- **transaction execution**
- `curl localhost:5034/api/v1/bl/trades/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"guks32pf","tradeParams":["0xec709e1774f0ce4aba47b52a499f9abaaa159f71", "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55", "user01", "user02", 50, "CAR1"],"authParams":["none"]}'`
- **Transaction Reference**
- `curl localhost:5034/api/v1/bl/trades/XXXXXXXXXXXXXX-XXX -XGET`
- **Login**
- `curl localhost:5034/api/v1/bl/login/ -XPOST -H "Content-Type: application/json" -d '{"userid":"user01","pwd":"hoge"}'`

- In the case of the above "transaction execution", the console log is the following:
```
[2020-08-21T19:55:24.207] [INFO] TransactionManagement - tradeID: 20200821195524-001
[2020-08-21T19:55:24.282] [INFO] BusinessLogicCartrade - firstTransaction txId : 0xafe7c812ab55c02feb691d2133bbba2c38abaf7f221794c3ca833a29708f4653
[2020-08-21T19:56:20.005] [INFO] BusinessLogicCartrade - ##INFO: underEscrow -> underTransfer, businessLogicID: guks32pf, tradeID: 20200821195524-001
[2020-08-21T19:56:20.608] [INFO] BusinessLogicCartrade - secondTransaction txId : 17c7577f73560ea5955f3151ed678833aa45d1252b34c6f933a7123757e82969
[2020-08-21T19:56:23.691] [INFO] BusinessLogicCartrade - ##INFO: underTransfer -> underSettlement, businessLogicID: guks32pf, tradeID: 20200821195524-001
[2020-08-21T19:56:23.703] [INFO] BusinessLogicCartrade - thirdTransaction txId : 0x61acb066349e24319afdf272b35429d198046e10f8fca3972f17a9e9a4dca75d
[2020-08-21T19:56:31.518] [INFO] BusinessLogicCartrade - ##INFO: completed cartrade, businessLogicID: guks32pf, tradeID: 20200821195524-001
```
- When the message `"##INFO: completed cartrade"` happens, the transaction is completed.

## How to confirm operation results
- How to check your account balance
- `/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.js`
- Example: `node validatorDriver_getNumericBalance.js`
- The balance of the account is displayed on the Validator's console.
- Example output
```
[2020-08-18T17:06:15.795] [INFO] connector_main[6710] - Response :{"status":200,"amount":1900}
```
- How to identify the owner of the car
- `/packages/ledger-plugin/fabric/validator/unit-test/queryCar.js`
- Example: `node queryCar.js CAR1`
- The owner of the car is displayed on the console.
- Example output
```
##queryCar Params: CAR1
Transaction has been evaluated, result is: {"colour":"red","make":"Ford","model":"Mustang","owner":"fuser02"}
```
- How to change the ownership of the car by hand
- ``/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js``
77 changes: 77 additions & 0 deletions examples/cartrade/config/default.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
{
"ledgerPluginInfo": [
{
"validatorId": "84jUisrs",
"validatorUrl": "https://localhost:5050",
"ledgerInfo": {
"ledgerAbstract": "Go-Ethereum Ledger"
}
},
{
"validatorId": "r9IS4dDf",
"validatorUrl": "https://localhost:5040",
"ledgerInfo": {
"ledgerAbstract": "Fabric Ledger"
}
}
],
"cartradeInfo": {
"fabric": {
"mspid": "Org1MSP",
"keystore": "./wallet/admin",
"connUserName": "user1",
"contractName": "fabcar",
"peers": [
{
"name": "peer0.org1.example.com",
"requests": "grpc://localhost:7051"
}
],
"orderer": {
"name": "orderer.example.com",
"url": "grpc://localhost:7050"
},
"ca": {
"name": "ca.example.com",
"url": "http://localhost:7054"
},
"submitter": {
"name": "admin",
"secret": "adminpw",
"certificate": "-----BEGIN CERTIFICATE-----\nMIICAjCCAaigAwIBAgIUYcAcX63XaN2Omym6hEXF+Kxzx2QwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwNzI3MTAzNDAwWhcNMjEwNzI3MTAz\nOTAwWjAhMQ8wDQYDVQQLEwZjbGllbnQxDjAMBgNVBAMTBWFkbWluMFkwEwYHKoZI\nzj0CAQYIKoZIzj0DAQcDQgAE0TjOYDQfDbAOU3wYNvxgeaTE/r88BieO5V4yu/6E\nJk4yBHscyaRCnrLZ9eqyFa5+3G5V0mA7hbTw48mdeMArsKNsMGowDgYDVR0PAQH/\nBAQDAgeAMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFBMOvw1wPpaBeZIpqc3AFbGs\nY0KMMCsGA1UdIwQkMCKAIEI5qg3NdtruuLoM2nAYUdFFBNMarRst3dusalc2Xkl8\nMAoGCCqGSM49BAMCA0gAMEUCIQDXvckX5bZ5mGPHpQ49aKSFsGJkwrX1BnW7DwA+\n4suQPQIgVGKIiQBQDGlOQHkt9lqno/yFiFZSjzZSS24LFIJNKU4=\n-----END CERTIFICATE-----\n",
"pkey": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgQ3pbxM94ZzHPEHW7\n5TQ1N/WfCLSgqY97dfyF34WiJz2hRANCAATROM5gNB8NsA5TfBg2/GB5pMT+vzwG\nJ47lXjK7/oQmTjIEexzJpEKestn16rIVrn7cblXSYDuFtPDjyZ14wCuw\n-----END PRIVATE KEY-----\n"
},
"channelName": "mychannel",
"chaincodeId": "fabcar"
},
"ethereum": {
"gethUrl": "http://localhost:8545",
"chainName": "geth1",
"networkId": 10,
"chainId": 10,
"network": "mainnet",
"hardfork": "petersburg",
"gas": 21000,
// private key for from address
"fromAddressPkey": "40d7e5931a6e0807d3ebd70518f635dbf575975d3bb564ff34c99be416067c89",
// escrow address
"escrowAddress": "0x36e146d5afab61ab125ee671708eeb380aea05b6",
// private key for escrow address
"escrowAddressPkey": "13a45756bc314465c4ae2ff0eb9ab58cf72453c04604d8fa14393eb25ce96d06"
}
},
// Log level (trace/debug/info/warn/error/fatal)
"logLevel": "debug",
// Application Host Info
"applicationHostInfo": {
// host name
"hostName": "http://foo.foo.foo:bar",
// port number
"hostPort": 5034
},
"socketOptions": {
"rejectUnauthorized": false,
"reconnection": false,
"timeout": 20000
}
}
9 changes: 9 additions & 0 deletions examples/cartrade/copyStaticAssets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* copyStaticAssets.ts
*/

import * as shell from 'shelljs';
shell.cp('-R', 'src/routing-interface/views', 'dist/routing-interface/views/');
39 changes: 39 additions & 0 deletions examples/cartrade/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "BLP",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node ./dist/routing-interface/www.js",
"debug": "nodemon --inspect ./dist/routing-interface/www.js",
"build": "npm run build-ts && npm run copy-static-assets",
"build-ts": "tsc",
"tslint.old": "tslint -c tslint.json -p tsconfig.json",
"tslint.old2": "tslint -c tslint.json -p tsconfig.json",
"tslint": "tslint -c tslint.json -p tsconfig.json './src/**/*.ts'",
"copy-static-assets": "ts-node copyStaticAssets.ts"
},
"dependencies": {
"@types/node": "^14.0.24",
"body-parser": "^1.19.0",
"config": "^1.26.1",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ethereumjs-common": "^1.5.1",
"ethereumjs-tx": "^2.1.2",
"express": "~4.16.1",
"fabric-ca-client": "~1.4.0",
"fabric-network": "~1.4.0",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"log4js": "^3.0.6",
"morgan": "~1.9.1",
"shelljs": "^0.8.4",
"socket.io": "^2.0.4",
"ts-node": "^8.10.2",
"web3": "^1.2.9"
},
"devDependencies": {
"tslint": "^6.1.2",
"typescript": "^3.9.3"
}
}
8 changes: 8 additions & 0 deletions examples/cartrade/public/stylesheets/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}

a {
color: #00B7FF;
}
50 changes: 50 additions & 0 deletions examples/cartrade/src/business-logic-plugin/BusinessLogicBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* BusinessLogicBase.ts
*/

import { RequestInfo } from '../routing-interface/RequestInfo';
import { BusinessLogicPlugin } from './BusinessLogicPlugin';
import { VerifierEventListener, LedgerEvent } from '../ledger-plugin/LedgerPlugin';
import { json2str } from '../ledger-plugin/DriverCommon'
import { TransactionInfo } from '../examples/cartrade/TransactionInfo';

import config = require('config');
import { getLogger } from "log4js";
const moduleName = 'BusinessLogicCartrade';
const logger = getLogger(`${moduleName}`);
logger.level = config.logLevel;

export class BusinessLogicBase implements BusinessLogicPlugin, VerifierEventListener {
eventFilter: object | null = null;

startTransaction(requestInfo: RequestInfo) {
// NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass)
}

executeNextTransaction(txInfo: object, txId: string): void {
// NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass)
}

onEvent(ledgerEvent: LedgerEvent): void {
// NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass)
}

getEventFilter(): object | null {
logger.debug(`##called getEventFilter: ${json2str(this.eventFilter)}`);
return this.eventFilter;
}

setEventFilter(filter: object): void {
logger.debug(`##called setEventFilter(before): ${json2str(this.eventFilter)}`);
this.eventFilter = filter;
logger.debug(`##called setEventFilter(after): ${json2str(this.eventFilter)}`);
}

isTargetEvent(ledgerEvent: LedgerEvent): boolean {
// NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass)
return false;
}
}
13 changes: 13 additions & 0 deletions examples/cartrade/src/business-logic-plugin/BusinessLogicPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* BusinessLogicPlugin.ts
*/

// import { TransactionInfoManagement } from './TransactionInfoManagement';
import { RequestInfo } from '../routing-interface/RequestInfo';

export interface BusinessLogicPlugin {
startTransaction(requestInfo: RequestInfo): void;
}
18 changes: 18 additions & 0 deletions examples/cartrade/src/business-logic-plugin/LedgerOperation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* LedgerOperation.ts
*/

export class LedgerOperation {
apiType: string;
progress: string;
data: {};

constructor(apiType: string, progress: string, data: {}) {
this.apiType = apiType;
this.progress = progress;
this.data = data;
}
}
57 changes: 57 additions & 0 deletions examples/cartrade/src/business-logic-plugin/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* app.ts
*/

import { Router, NextFunction, Request, Response } from 'express';

import * as createError from 'http-errors';
import * as express from 'express';
import * as path from 'path';
import * as cookieParser from 'cookie-parser';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';

import indexRouter from '../routing-interface/routes/index';
import loginRouter from '../routing-interface/routes/login';
import tradesRouter from '../routing-interface/routes/trades';
import usersRouter from '../routing-interface/routes/users';

const app: express.Express = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/', indexRouter);
app.use('/api/v1/bl/login/', loginRouter);
app.use('/api/v1/bl/trades/', tradesRouter);
app.use('/users', usersRouter);

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

// error handler
app.use((err: global.Error, 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 : {};

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

export default app;
6 changes: 6 additions & 0 deletions examples/cartrade/src/business-logic-plugin/typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare module global {
type Error = {
message: string;
status: number;
}
}
21 changes: 21 additions & 0 deletions examples/cartrade/src/config/BLP_config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2020 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* BLP_config.ts
*/

import { BusinessLogicPlugin } from '../business-logic-plugin/BusinessLogicPlugin';
import { BusinessLogicCartrade } from '../examples/cartrade/BusinessLogicCartrade';
// import { BusinessLogicCartrade } from '../examples/cartrade/BusinessLogicXxxxTrade';

export function getTargetBLPInstance(businessLogicID: string): BusinessLogicPlugin | null {
switch (businessLogicID) {
case "guks32pf":
return new BusinessLogicCartrade();
// case "***":
// return new BusinessLogic***Trace();
default:
return null;
}
}

0 comments on commit 769c087

Please sign in to comment.