diff --git a/examples/cartrade/BusinessLogicCartrade.ts b/examples/cartrade/BusinessLogicCartrade.ts index 570a36b40b..c7ba47dabb 100644 --- a/examples/cartrade/BusinessLogicCartrade.ts +++ b/examples/cartrade/BusinessLogicCartrade.ts @@ -133,12 +133,14 @@ export class BusinessLogicCartrade extends BusinessLogicBase { const transactionData: TransactionData = new TransactionData("escrow", "ledger001", result.txId); this.transactionInfoManagement.setTransactionData(tradeInfo, transactionData); - // Set LedgerOperation + // Set Parameter logger.debug('firstTransaction data : ' + JSON.stringify(result.data)); - const ledgerOperation: LedgerOperation = new LedgerOperation("sendRawTransaction", "", result.data); + const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. + const method = {type: "web3Eth", command: "sendRawTransaction"}; + const args = {"args": [result.data["serializedTx"]]}; - // Run Verifier (Ethereum) - verifierEthereum.requestLedgerOperation(ledgerOperation); + // Run Verifier (Fabric) + verifierEthereum.requestLedgerOperationNeo(contract, method, args); }) .catch(err => { logger.error(err); @@ -175,7 +177,7 @@ export class BusinessLogicCartrade extends BusinessLogicBase { // Set Parameter //logger.debug('secondTransaction data : ' + JSON.stringify(result.data)); const contract = {"channelName": "mychannel"}; - const method = {"method": "sendSignedProposal"}; + const method = {"type": "sendSignedTransaction"}; const args = {"args": [result.data]}; // Run Verifier (Fabric) @@ -222,7 +224,18 @@ export class BusinessLogicCartrade extends BusinessLogicBase { const ledgerOperation: LedgerOperation = new LedgerOperation("sendRawTransaction", "", result.data); // Run Verifier (Ethereum) - verifierEthereum.requestLedgerOperation(ledgerOperation); + // verifierEthereum.requestLedgerOperation(ledgerOperation); + + // TODO: Neo!! + // Set Parameter + const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. + const method = {type: "web3Eth", command: "sendRawTransaction"}; + const args = {"args": [result.data["serializedTx"]]}; + + // Run Verifier (Fabric) + verifierEthereum.requestLedgerOperationNeo(contract, method, args); + + }) .catch(err => { logger.error(err); diff --git a/examples/cartrade/README.md b/examples/cartrade/README.md index c965e0850d..f1a6f4e353 100644 --- a/examples/cartrade/README.md +++ b/examples/cartrade/README.md @@ -1,10 +1,18 @@ # example-cartrade +## Prerequisites + +Before you begin, you need to check that you have all the prerequisites installed as follows: +- Docker (recommend: v17.06.2-ce or greater) +- Docker-compose (recommend: v1.14.0 or greater) +- node.js (recommend: v10.23.0 or greater) +- The ports 5034, 5040, 5050 are available (If they are already used, the following processes can be done by changing the port number setting) + ## Boot method 1. Before booting, please modify the following information for your environment - - applicationHostInfo.hostName (URL of the host on the Location header) on `/packages/config/default.json` - - applicationHostInfo.hostPort (The port number of Routing-interface http server) on `/packages/config/default.json` + - `applicationHostInfo.hostName` (IP address of the host on the Location header) on `/packages/config/default.json` + - `applicationHostInfo.hostPort` (The port number of Routing-interface http server, the default is 5034) on `/packages/config/default.json` 1. Start ledgers: - `./script-start-ledgers.sh` @@ -12,52 +20,45 @@ - `./script-build-all.sh` 1. Start validators and the cartrade app - Please open three consoles and execute the following:. - - Start the validator for Fabric: + - Start the validator for Fabric on the first console: `./script-start-validator-fabric.sh` - - Start the validator for Ethereum: + - Start the validator for Ethereum on the second console: `./script-start-validator-ethereum.sh` - - Start the cartrade app: + - Start the cartrade app on the third console: `./script-start-cartrade.sh` ## 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 +1. (Optional) Check the balance on Ethereum and the fabcar ownership on Fabric using the following script + - `./script-build-get-app.sh` (only the first time) + - `./script-get-app.sh` + - The result is as the following: ``` + [process] Execute an app for getting Balance on Ethereum + The balance of fromAccount: + BigNumber { s: 1, e: 4, c: [ 100000 ] } + The balance of toAccount: + BigNumber { s: 1, e: 1, c: [ 0 ] } + [process] Execute an app for getting ownership on Fabcar ##queryCar Params: CAR1 - Transaction has been evaluated, result is: {"colour":"red","make":"Ford","model":"Mustang","owner":"user02"} + Transaction has been evaluated, result is: {"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"} + ``` +1. Run the transaction execution using the following script + - `./script-post-cartrade-sample.sh` + - After this, the transactions are executed by order. When the following log appears on the above third console (the console of `./script-start-cartrade.sh`), the transactions are completed. ``` -- How to change the ownership of the car by hand - - ``/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js`` \ No newline at end of file + [INFO] BusinessLogicCartrade - ##INFO: completed cartrade, businessLogicID: guks32pf, tradeID: *******-001 + ``` +1. (Optional) Check the balance on Ethereum and the fabcar ownership on Fabric using the following script + - `./script-get-app.sh` + - The result is as the following. In the following case, 50 coins from fromAccount was transferred to toAccount, and the car ownership ("owner") was transferred. + ``` + [process] Execute an app for getting Balance on Ethereum + The balance of fromAccount: + BigNumber { s: 1, e: 4, c: [ 99950 ] } + The balance of toAccount: + BigNumber { s: 1, e: 1, c: [ 50 ] } + [process] Execute an app for getting ownership on Fabcar + ##queryCar Params: CAR1 + Transaction has been evaluated, result is: {"colour":"red","make":"Ford","model":"Mustang","owner":"Cathy"} + ``` \ No newline at end of file diff --git a/examples/cartrade/TransactionEthereum.ts b/examples/cartrade/TransactionEthereum.ts index f538fcf880..04368a71e5 100644 --- a/examples/cartrade/TransactionEthereum.ts +++ b/examples/cartrade/TransactionEthereum.ts @@ -49,13 +49,11 @@ export function makeRawTransaction(txParam: { fromAddress: string, fromAddressPk // const gasPrice: string = web3.eth.getGasPrice(); const latestNonce = getLatestNonce(txParam.fromAddress); - logger.debug(`#####(A) _nonce: ${_nonce}, latestNonce: ${latestNonce}`); logger.debug(`####makeRawTransaction(): fromAddress: ${txParam.fromAddress}, txnCount: ${web3.utils.toHex(txnCount)}, latestNonce: ${web3.utils.toHex(latestNonce)}`); if (txnCount <= latestNonce) { txnCount = latestNonce + 1; logger.debug(`####makeRawTransaction(): Adjust txnCount, fromAddress: ${txParam.fromAddress}, txnCount: ${web3.utils.toHex(txnCount)}, latestNonce: ${web3.utils.toHex(latestNonce)}`); } - logger.debug(`#####(B) _nonce: ${_nonce}, latestNonce: ${latestNonce}, txnCount: ${txnCount}`); setLatestNonce(txParam.fromAddress, txnCount); const privKey: Buffer = Buffer.from(txParam.fromAddressPkey, 'hex'); @@ -99,7 +97,6 @@ function getLatestNonce(fromAddress: string): number { if (mapFromAddressNonce.has(fromAddress)) { return mapFromAddressNonce.get(fromAddress); } - //return 0; return -1; } diff --git a/examples/cartrade/script-build-all.sh b/examples/cartrade/script-build-all.sh index 5c95a6431a..34b2cc5bea 100755 --- a/examples/cartrade/script-build-all.sh +++ b/examples/cartrade/script-build-all.sh @@ -1,16 +1,18 @@ +cd ../.. + ## Build validator for Fabric -cd ../../packages/ledger-plugin/fabric/validator/src/ +cd ./packages/ledger-plugin/fabric/validator/src ./script-build-validator.sh -cp -a ../../../../../examples/cartrade/build/wallet/ . -cd ../../../../../ +cp -a ../../../../../examples/cartrade/build/wallet . +cd ../../../../.. ## build validator for Ethereum -cd ./packages/ledger-plugin/go-ethereum/validator/src/ +cd ./packages/ledger-plugin/go-ethereum/validator/src ./script-build-validator.sh -cd ../../../../../ +cd ../../../../.. ## build packages -cd ./packages/ +cd ./packages ./script-build-packages.sh cd .. diff --git a/examples/cartrade/script-build-cartrade.sh b/examples/cartrade/script-build-cartrade.sh index 3fb57901ae..5f85d05487 100755 --- a/examples/cartrade/script-build-cartrade.sh +++ b/examples/cartrade/script-build-cartrade.sh @@ -1,4 +1,4 @@ ## Build a cartrade app echo "[process] Build a cartrade app" npm install -npm run build +npm run build \ No newline at end of file diff --git a/examples/cartrade/script-build-get-app.sh b/examples/cartrade/script-build-get-app.sh new file mode 100755 index 0000000000..c7cc039359 --- /dev/null +++ b/examples/cartrade/script-build-get-app.sh @@ -0,0 +1,7 @@ +## Build a getting app +echo "[process] Build an app for getting Balance on Ethereum" +cd script-test-getFunctions/go-ethereum +npm install +echo "[process] Build an app for getting ownership on Fabcar" +cd ../fabric +npm install \ No newline at end of file diff --git a/examples/cartrade/script-get-app.sh b/examples/cartrade/script-get-app.sh new file mode 100755 index 0000000000..6642f437f9 --- /dev/null +++ b/examples/cartrade/script-get-app.sh @@ -0,0 +1,7 @@ +## Execute a getting app +echo "[process] Execute an app for getting Balance on Ethereum" +cd script-test-getFunctions/go-ethereum +node getBalance.js +echo "[process] Execute an app for getting ownership on Fabcar" +cd ../fabric +node queryCar.js CAR1 \ No newline at end of file diff --git a/examples/cartrade/script-post-cartrade-sample.sh b/examples/cartrade/script-post-cartrade-sample.sh index 10b3572a51..f1513538db 100755 --- a/examples/cartrade/script-post-cartrade-sample.sh +++ b/examples/cartrade/script-post-cartrade-sample.sh @@ -1 +1 @@ -curl localhost:5034/api/v1/bl/trades/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"guks32pf","tradeParams":["0xec709e1774f0ce4aba47b52a499f9abaaa159f71", "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55", "user01", "user02", 50, "CAR1"],"authParams":["param"]}' \ No newline at end of file +curl localhost:5034/api/v1/bl/trades/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"guks32pf","tradeParams":["0x06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55", "Brad", "Cathy", 50, "CAR1"],"authParams":["none"]}' \ No newline at end of file diff --git a/examples/cartrade/script-start-cartrade.sh b/examples/cartrade/script-start-cartrade.sh index aaa5694a28..b955686730 100755 --- a/examples/cartrade/script-start-cartrade.sh +++ b/examples/cartrade/script-start-cartrade.sh @@ -1,4 +1,4 @@ -cd ../../ +cd ../.. ## Start cartrade app echo "[process] Start the routing interface and the cartrade app" diff --git a/examples/cartrade/script-start-ledgers.sh b/examples/cartrade/script-start-ledgers.sh index 83231a80dc..93c7196d45 100755 --- a/examples/cartrade/script-start-ledgers.sh +++ b/examples/cartrade/script-start-ledgers.sh @@ -1,8 +1,10 @@ -## Start docker environment for Fabric testnet -cd ../../tools/docker/fabric14-fabcar-testnet +cd ../.. + +## Start docker environment for Go-Ethereum testnet +cd ./tools/docker/geth-testnet ./script-start-docker.sh cd ../../.. -## Start docker environment for Go-Ethereum testnet -cd ../../tools/docker/geth-testnet +## Start docker environment for Fabric testnet +cd ./tools/docker/fabric14-fabcar-testnet ./script-start-docker.sh \ No newline at end of file diff --git a/examples/cartrade/script-start-validator-ethereum.sh b/examples/cartrade/script-start-validator-ethereum.sh index 33f2a76446..70df1f048e 100755 --- a/examples/cartrade/script-start-validator-ethereum.sh +++ b/examples/cartrade/script-start-validator-ethereum.sh @@ -1,4 +1,4 @@ -cd .. +cd ../.. echo "[process] Start the validator for Go-Ethereum" cd ./packages/ledger-plugin/go-ethereum/validator/src diff --git a/examples/cartrade/script-start-validator-fabric.sh b/examples/cartrade/script-start-validator-fabric.sh index eb24a34040..575cd167e1 100755 --- a/examples/cartrade/script-start-validator-fabric.sh +++ b/examples/cartrade/script-start-validator-fabric.sh @@ -1,4 +1,4 @@ -cd .. +cd ../.. echo "[process] Start the validator for Fabric" cd ./packages/ledger-plugin/fabric/validator/src diff --git a/examples/cartrade/script-stop-cartrade.sh b/examples/cartrade/script-stop-cartrade.sh new file mode 100755 index 0000000000..0849294110 --- /dev/null +++ b/examples/cartrade/script-stop-cartrade.sh @@ -0,0 +1,7 @@ +echo "[process] Stop the validators and the cartrade app" +# stop the validator for Ethereum +kill -9 $(lsof -t -i:5050) +# stop the validator for Fabric +kill -9 $(lsof -t -i:5040) +# stop the cartrade app +kill -9 $(lsof -t -i:5034) \ No newline at end of file diff --git a/examples/cartrade/script-test-getFunctions/fabric/config/connection.json b/examples/cartrade/script-test-getFunctions/fabric/config/connection.json new file mode 100644 index 0000000000..4991bc7794 --- /dev/null +++ b/examples/cartrade/script-test-getFunctions/fabric/config/connection.json @@ -0,0 +1,52 @@ +{ + "name": "basic-network", + "version": "1.0.0", + "client": { + "organization": "Org1", + "connection": { + "timeout": { + "peer": { + "endorser": "300" + }, + "orderer": "300" + } + } + }, + "channels": { + "mychannel": { + "orderers": [ + "orderer.example.com" + ], + "peers": { + "peer0.org1.example.com": {} + } + } + }, + "organizations": { + "Org1": { + "mspid": "Org1MSP", + "peers": [ + "peer0.org1.example.com" + ], + "certificateAuthorities": [ + "ca.example.com" + ] + } + }, + "orderers": { + "orderer.example.com": { + "url": "grpc://localhost:7050" + } + }, + "peers": { + "peer0.org1.example.com": { + "url": "grpc://localhost:7051" + } + }, + "certificateAuthorities": { + "ca.example.com": { + "url": "http://localhost:7054", + "caName": "ca.example.com" + } + } +} \ No newline at end of file diff --git a/examples/cartrade/script-test-getFunctions/fabric/package.json b/examples/cartrade/script-test-getFunctions/fabric/package.json new file mode 100644 index 0000000000..157f3401b1 --- /dev/null +++ b/examples/cartrade/script-test-getFunctions/fabric/package.json @@ -0,0 +1,11 @@ +{ + "name": "validatorDriver", + "version": "0.0.0", + "private": true, + "dependencies": { + "config": "^1.26.1", + "socket.io": "^2.0.4", + "fabric-ca-client": "~1.4.0", + "fabric-network": "~1.4.0" + } + } \ No newline at end of file diff --git a/packages/ledger-plugin/fabric/validator/unit-test/queryCar.js b/examples/cartrade/script-test-getFunctions/fabric/queryCar.js similarity index 97% rename from packages/ledger-plugin/fabric/validator/unit-test/queryCar.js rename to examples/cartrade/script-test-getFunctions/fabric/queryCar.js index 5283d070c9..7418edfa00 100644 --- a/packages/ledger-plugin/fabric/validator/unit-test/queryCar.js +++ b/examples/cartrade/script-test-getFunctions/fabric/queryCar.js @@ -5,12 +5,6 @@ * queryCar.js */ -//////// -// Usage -// TODO: -// -//////// - 'use strict'; const { FileSystemWallet, Gateway } = require('fabric-network'); @@ -73,4 +67,4 @@ async function main() { } } -main(); +main(); \ No newline at end of file diff --git a/examples/cartrade/script-test-getFunctions/go-ethereum/getBalance.js b/examples/cartrade/script-test-getFunctions/go-ethereum/getBalance.js new file mode 100644 index 0000000000..65a591190a --- /dev/null +++ b/examples/cartrade/script-test-getFunctions/go-ethereum/getBalance.js @@ -0,0 +1,11 @@ +const Web3 = require('web3'); +const web3 = new Web3(); +web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545")); +const fromAccount = "0x06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97" +const toAccount = "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55" +console.log("The balance of fromAccount:"); +var res = web3.eth.getBalance(fromAccount); +console.log(res); +console.log("The balance of toAccount:"); +var res = web3.eth.getBalance(toAccount); +console.log(res); \ No newline at end of file diff --git a/examples/cartrade/script-test-getFunctions/go-ethereum/package.json b/examples/cartrade/script-test-getFunctions/go-ethereum/package.json new file mode 100644 index 0000000000..deb393bd81 --- /dev/null +++ b/examples/cartrade/script-test-getFunctions/go-ethereum/package.json @@ -0,0 +1,12 @@ +{ + "dependencies": { + "fs": "^0.0.1-security", + "jsonfile": "^5.0.0", + "web3": "^0.20.7" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "license": "ISC" +} diff --git a/packages/business-logic-plugin/app.ts b/packages/business-logic-plugin/app.ts index 55e6ce9029..f5bc9d43ac 100644 --- a/packages/business-logic-plugin/app.ts +++ b/packages/business-logic-plugin/app.ts @@ -14,10 +14,12 @@ import cookieParser = require('cookie-parser'); import logger = require('morgan'); 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 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'; +import carsRouter from '../routing-interface/routes/cars'; +import assetRouter from '../routing-interface/routes/asset'; const app: express.Express = express(); @@ -30,9 +32,11 @@ 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('/api/v1/bl/login/', loginRouter); +app.use('/api/v1/bl/trades/', tradesRouter); app.use('/api/v1/bl/balance/', balanceRouter); +app.use('/api/v1/bl/cars/', carsRouter); +app.use('/api/v1/bl/asset/', assetRouter); // catch 404 and forward to error handler app.use((req: Request, res: Response, next: NextFunction) => { diff --git a/packages/config/contractInfo.json b/packages/config/contractInfo.json new file mode 100644 index 0000000000..3b0c557bbe --- /dev/null +++ b/packages/config/contractInfo.json @@ -0,0 +1,38 @@ +{ + "contractInfo": [ + { + "transactionHash": "0x8387ee93223da535a2cc0177d6f86df0a9dbf56f14573baf11d94cb9c9269fb1", + "address": "0x89d266156b47c69b8a6f3152c0c56b87b5dea427", + "abi": [ + { + "constant": false, + "inputs": [ + { + "name": "_addAsset", + "type": "uint256" + } + ], + "name": "addAsset", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "getAsset", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + } + ] + } + ] +} diff --git a/packages/config/default.json b/packages/config/default.json index 54967704b2..baa0651d17 100644 --- a/packages/config/default.json +++ b/packages/config/default.json @@ -7,7 +7,7 @@ ], "logLevel": "debug", "applicationHostInfo": { - "hostName": "http://xxx.xxxxx.xxx:xxxx", + "hostName": "http://xxx.xxx.xxx.xxx", "hostPort": 5034 }, "socketOptions": { diff --git a/packages/copyStaticAssets.ts b/packages/copyStaticAssets.ts index 9741ad5bb7..201d670264 100644 --- a/packages/copyStaticAssets.ts +++ b/packages/copyStaticAssets.ts @@ -12,4 +12,5 @@ import * as shell from 'shelljs'; // shell.cp('-R', 'src/routing-interface/views', 'dist/routing-interface/views/'); shell.cp('-R', 'config/default.json', '../dist/packages/config/'); shell.cp('-R', 'config/verifier-config.json', '../dist/packages/config/'); +shell.cp('-R', 'config/contractInfo.json', '../dist/packages/config/'); shell.cp('-R', 'config/usersetting.json', '../dist/packages/config/'); diff --git a/packages/ledger-plugin/VerifierBase.ts b/packages/ledger-plugin/VerifierBase.ts index a2e1ecc113..b350c970d6 100644 --- a/packages/ledger-plugin/VerifierBase.ts +++ b/packages/ledger-plugin/VerifierBase.ts @@ -44,7 +44,8 @@ export class VerifierBase implements Verifier { return makeApiInfoList(this.apiInfo); }; - // NOTE: This function will be deleted due to the updating of API functions + // NOTE: asynchronous command + // TODO: Method name confirmation requestLedgerOperation(param: LedgerOperation): void { logger.debug('call : requestLedgerOperation'); try { @@ -71,17 +72,46 @@ export class VerifierBase implements Verifier { throw err; } }; - + + // NOTE: asynchronous command (repaired version) + // TODO: Method name confirmation + requestLedgerOperationNeo(contract: object, method: object, args: object): void { + logger.debug('call : requestLedgerOperation'); + try { + const socketOptions: {} = { + rejectUnauthorized: config.socketOptions.rejectUnauthorized, // temporary avoidance since self-signed certificates are used + reconnection: config.socketOptions.reconnection, + timeout: config.socketOptions.timeout, + }; + logger.debug(`socketOptions = ${JSON.stringify(socketOptions)}`); + const socket: Socket = io(this.validatorUrl, socketOptions); + + const requestData: {} = { + contract: contract, + method: method, + args: args + }; + // logger.debug('requestData : ' + JSON.stringify(requestData)); + socket.emit('request2', requestData); + } catch (err) { + logger.error('requestLedgerOperation faild : ' + err); + throw err; + } + }; + + // NOTE: Synchronous command execSyncFunction(param: LedgerOperation): Promise { return new Promise((resolve, reject) => { logger.debug('call : execSyncFunction'); try { logger.debug(`##in execSyncFunction, LedgerOperation = ${JSON.stringify(param)}`); let responseFlag: boolean = false; - + + // reqID generation const reqID = this.genarateReqID(); logger.debug(`##execSyncFunction, reqID = ${reqID}`); - + + // Preparing socket const socketOptions: {} = { rejectUnauthorized: config.socketOptions.rejectUnauthorized, reconnection: config.socketOptions.reconnection, @@ -111,13 +141,15 @@ export class VerifierBase implements Verifier { if (reqID === result.id) { responseFlag = true; logger.debug(`##execSyncFunction: resObj: ${JSON.stringify(result.resObj)}`); + // Result reply resolve(result.resObj); } }); + // Call Validator const apiType: string = param.apiType; - //const progress: string = param.progress; - let data: {} = param.data; + // const progress: string = param.progress; + const data: {} = param.data; data["reqID"] = reqID; const requestData: {} = { func: apiType, @@ -126,7 +158,81 @@ export class VerifierBase implements Verifier { logger.debug('requestData : ' + JSON.stringify(requestData)); socket.emit('request', requestData); logger.debug('set timeout'); - + + // Time-out setting + 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); + } + }); + } + + // NOTE: Synchronous command (repaired version) + execSyncFunctionNeo(contract: object, method: object, args: object): Promise { + return new Promise((resolve, reject) => { + logger.debug('call : execSyncFunction'); + try { + logger.debug(`##in execSyncFunction, contract = ${JSON.stringify(contract)}, method = ${JSON.stringify(method)}, args = ${JSON.stringify(args)}, `); + let responseFlag: boolean = false; + + // reqID generation + const reqID = this.genarateReqID(); + logger.debug(`##execSyncFunction, reqID = ${reqID}`); + + // Preparing socket + 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)}`); + // Result reply + resolve(result.resObj); + } + }); + + // Call Validator + const requestData: {} = { + contract: contract, + method: method, + args: args, + reqID: reqID + }; + logger.debug('requestData : ' + JSON.stringify(requestData)); + socket.emit('request2', requestData); + logger.debug('set timeout'); + + // Time-out setting setTimeout(() => { if (responseFlag === false) { logger.debug('requestTimeout reqID : ' + reqID); @@ -244,9 +350,11 @@ export class VerifierBase implements Verifier { this.eventListener = eventListener; return; }; - + + // Request ID generation genarateReqID(): string { if (this.counterReqID > config.verifier.maxCounterRequestID) { + // Counter initialization this.counterReqID = 1; } return `${this.validatorID}_${this.counterReqID++}`; diff --git a/packages/ledger-plugin/fabric/validator/src/.gitignore b/packages/ledger-plugin/fabric/validator/src/.gitignore index 5b2ae41f99..3487209b7b 100644 --- a/packages/ledger-plugin/fabric/validator/src/.gitignore +++ b/packages/ledger-plugin/fabric/validator/src/.gitignore @@ -5,4 +5,4 @@ dependent/package-lock.json core/npm-debug.log dependent/wallet/ core/wallet/ - +wallet/ diff --git a/packages/ledger-plugin/fabric/validator/src/README.md b/packages/ledger-plugin/fabric/validator/src/README.md index 3c8bc09a32..f6301a428f 100644 --- a/packages/ledger-plugin/fabric/validator/src/README.md +++ b/packages/ledger-plugin/fabric/validator/src/README.md @@ -4,15 +4,13 @@ README.md --> -# Fabric-specific +# BIF-trial(Validator) ## Assumption -- A ledger (Hyperledger fabric node) to connect is already running -- Specify URL of the ledger node to connect to in "PluginConfig.js" +- fabric is running -## Execution -``` -./setup.sh +## Run +
 cd core
 node ./bin/www.js 
-```
\ No newline at end of file
+
diff --git a/packages/ledger-plugin/fabric/validator/src/copyStaticAssets.ts b/packages/ledger-plugin/fabric/validator/src/copyStaticAssets.ts new file mode 100644 index 0000000000..e8c9519ffa --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/copyStaticAssets.ts @@ -0,0 +1,3 @@ +import * as shell from 'shelljs'; +shell.cp('-R', 'core/CA/', '../dist/core'); +shell.cp('dependent/connection.json', '../dist/dependent'); diff --git a/packages/ledger-plugin/fabric/validator/src/core/app.js b/packages/ledger-plugin/fabric/validator/src/core/app.js deleted file mode 100644 index 77e35eb6e1..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/core/app.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * app.js - */ - -/* Summary: - * - */ - -var express = require('express'); -var cookieParser = require('cookie-parser'); -var bodyParser = require('body-parser'); - -var app = express(); - -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: false })); -app.use(cookieParser()); - -// catch 404 and forward to error handler -app.use(function(req, res, next) { - var err = new Error('Not Found'); - err.status = 404; - next(err); -}); - -// error handler -app.use(function(err, req, res, next) { - // 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); - console.log(err); - res.send(err); -}); - -module.exports = app; diff --git a/packages/ledger-plugin/fabric/validator/src/core/app.ts b/packages/ledger-plugin/fabric/validator/src/core/app.ts new file mode 100644 index 0000000000..5d9a6d66a2 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/core/app.ts @@ -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(function(req, res, next) { + 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(err); +}); + +export default app; diff --git a/packages/ledger-plugin/fabric/validator/src/core/bin/www.js b/packages/ledger-plugin/fabric/validator/src/core/bin/www.js deleted file mode 100644 index a78f7cbaea..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/core/bin/www.js +++ /dev/null @@ -1,208 +0,0 @@ -#!/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. - */ - -var app = require('../app'); -var debug = require('debug')('connector:server'); -var fs = require('fs'); -var https = require('https'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('connector_main[' + process.pid + ']'); -logger.level = config.logLevel; - -// implementation class of a part dependent of end-chains (server plugin) -var ServerPlugin = require('../../dependent/ServerPlugin.js'); -var Splug = new ServerPlugin(); -// destination dependency (MONITOR) implementation class -var ServerMonitorPlugin = require('../../dependent/ServerMonitorPlugin.js'); -var Smonitor = new ServerMonitorPlugin(); - -/** - * Get port from environment and store in Express. - */ - -var sslport = normalizePort(process.env.PORT || config.sslParam.port); -app.set('port', sslport); - -// Specify private key and certificate -var sslParam = { - key: fs.readFileSync(config.sslParam.key), - cert: fs.readFileSync(config.sslParam.cert) -}; - -/** - * Create HTTPS server. - */ - -var server = https.createServer(sslParam, app); // Start as an https server. -var 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) { - var 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; - } - - var 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() { - var addr = server.address(); - var 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) { - var func = data.func; - var 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((resp_obj) => { - logger.info('*** RESPONSE ***'); - logger.info('Client ID :' + client.id); - logger.info('Response :' + JSON.stringify(resp_obj)); - client.emit("response", resp_obj); - }) - .catch((err_obj) => { - logger.error('*** ERROR ***'); - logger.error('Client ID :' + client.id); - logger.error('Detail :' + JSON.stringify(err_obj)); - client.emit("connector_error", err_obj); - }); - } else { - // No such function - var emsg = "Function " + func + " not found!"; - logger.error(emsg); - var ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - client.emit("connector_error", ret_obj); - } - }); - - /** - * startMonitor: starting block generation event monitoring - **/ - client.on('startMonitor', function() { - // Callback to receive monitoring results - var cb = function(callbackData) { - var emit_type = ""; - if(callbackData.status == 200) { - emit_type = "eventReceived"; - logger.info('event data callbacked.'); - } else { - emit_type = "monitor_error"; - } - client.emit(emit_type, callbackData); - } - - Smonitor.startMonitor(client.id, 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); - }); - -}); - diff --git a/packages/ledger-plugin/fabric/validator/src/core/bin/www.ts b/packages/ledger-plugin/fabric/validator/src/core/bin/www.ts new file mode 100644 index 0000000000..d8e50620bd --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/core/bin/www.ts @@ -0,0 +1,273 @@ +#!/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) { + var 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; + if (data.reqID !== undefined) { + logger.info(`##add reqID: ${data.reqID}`); + args["reqID"] = data.reqID; + } + logger.info('##[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); + } + }); + + client.on('request2', function(data) { + const func = data.method.method; + 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; + } + logger.info('##[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 presence of a request ID. + if ((data.method.type === "evaluateTransaction") + || (data.method.type === "submitTransaction")) { + // Call a synchronous method. + Splug.contractTransaction(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 (data.method.type === "sendSignedTransaction") { + // Call an asynchronous method. + Splug.sendSignedProposal(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); + } + }); + + /** + * startMonitor: starting block generation event monitoring + **/ + client.on('startMonitor', function() { + // 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, 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); + }); + +}); + diff --git a/packages/ledger-plugin/fabric/validator/src/core/config/default.js b/packages/ledger-plugin/fabric/validator/src/core/config/default.js deleted file mode 100644 index c7f6ab2bbd..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/core/config/default.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * default.js - */ - -module.exports = { - // Defined value for the destination independent part. I don't think I can use it only at www, so I think I can write directly there. - // Destination dependent definition values should be in lib/PluginConfig.js. - "sslParam" : { - "port" : 5040, - //"port" : 5041, - "key" : './CA/connector.priv', - "cert" : './CA/connector.crt' - }, - // Log level (trace/debug/info/warn/error/fatal) - "logLevel" : "debug" -}; diff --git a/packages/ledger-plugin/fabric/validator/src/core/config/default.ts b/packages/ledger-plugin/fabric/validator/src/core/config/default.ts new file mode 100644 index 0000000000..ca4e21ffb1 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/core/config/default.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * default.js + */ + +export const config = { + // Defined value for the destination independent part. I don't think I can use it only at www, so I think I can write directly there. + // Destination dependent definition values should be in lib/PluginConfig.js. + "sslParam" : { + "port" : 5040, + //"port" : 5041, + //"port" : 5042, + "key" : './core/CA/connector.priv', + "cert" : './core/CA/connector.crt' + }, + // Log level (trace/debug/info/warn/error/fatal) + "logLevel" : "debug" +}; diff --git a/packages/ledger-plugin/fabric/validator/src/core/package.json b/packages/ledger-plugin/fabric/validator/src/core/package.json deleted file mode 100644 index 4cde14a5a5..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/core/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "connector", - "version": "0.0.0", - "private": true, - "scripts": { - "start": "node ./bin/www" - }, - "dependencies": { - "body-parser": "~1.17.1", - "config": "^1.26.1", - "cookie-parser": "~1.4.3", - "debug": "~4.1.1", - "express": "~4.15.2", - "log4js": "^3.0.6", - "morgan": "~1.8.1", - "serve-favicon": "~2.4.2", - "socket.io": "^2.0.4" - } -} diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.js b/packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.ts similarity index 90% rename from packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.js rename to packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.ts index a742297689..acd0e011c0 100644 --- a/packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.js +++ b/packages/ledger-plugin/fabric/validator/src/dependent/PluginConfig.ts @@ -11,7 +11,7 @@ * Definition value specific to the connection destination dependent part */ -module.exports = { +export const SplugConfig = { "fabric":{ "mspid": "Org1MSP", "keystore":"./wallet/admin", @@ -37,6 +37,7 @@ module.exports = { "secret":"adminpw" }, "channelName":"mychannel", - "chaincodeId":"easy_sample_ec1" + //"chaincodeId":"easy_sample_ec1" + "chaincodeId":"fabcar" } }; diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/PluginUtil.js b/packages/ledger-plugin/fabric/validator/src/dependent/PluginUtil.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/src/dependent/PluginUtil.js rename to packages/ledger-plugin/fabric/validator/src/dependent/PluginUtil.ts diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.js b/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.js deleted file mode 100644 index 1a2203832a..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.js +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerMonitorPlugin.js - */ - -/* - * Summary: - * Monitoring class of connection destination dependent part of linkage server - * Used when performing continuous monitoring. - * Processing that ends with reception of a single event is supported by implementing a unique function in ServerPlugin. - * Unlike ServerPlugin, it does not basically handle its own functions. - */ - - -// Basic package dependency declaration -var process = require('process'); -// IF declaration for fabric -var sdk = require('./fabricaccess.js'); -// config file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerMonitorPlugin[' + process.pid + ']'); -logger.level = config.logLevel; - - -/* - * ServerMonitorPlugin - * Server monitoring class definition - */ -var ServerMonitorPlugin = class { - - constructor() { - // Define settings specific to the dependent part - // Initializing filter during monitoring - this._filterTable = {}; - this._network = SplugConfig; //channelID, mspid, peer settings, etc. - this._eh = null; - } - - /* - * startMonitor - * Start monitoring - * @param {string} clientId : Client ID of the monitoring start request source - * @param {function} cb : Callback function that receives the monitoring result at any time - */ - startMonitor(clientId, cb) { - logger.info('*** START MONITOR ***'); - logger.info('Client ID :' + clientId); - var filter = this._filterTable[clientId]; - var network = this._network; - var channel = null; - - if (!filter) { - sdk.GetClientAndChannel() - .then((retobj) => { - channel = retobj.channel; //Set the returned channel - this._filterTable[clientId] = retobj.client; - return sdk.GetSubmitter(retobj.client) - }) - .then((submitter) => { - var peer = this._filterTable[clientId].newPeer(network.fabric.peers[0].requests); - this._eh = channel.newChannelEventHub(peer); - logger.info('Connecting the event hub'); - this._eh.registerBlockEvent((block) => { - var txlist = []; - logger.info('*** Block Event ***'); - console.log('##[HL-BC] Notify new block data(D2)'); - logger.info('chain id :' + network.fabric.channelName); - logger.info("blocknumber : " + block.header.number); - var len = block.data.data.length; - logger.info('data.data.length :' + len); - console.log('##[HL-BC] Validate transactions(D3)'); - console.log('##[HL-BC] digital sign on valid transaction(D4)'); - for (var i = 0; i < len; i++) { - var payload = block.data.data[i].payload; - var channel_header = payload.header.channel_header; - if (channel_header.type == 3) { //'ENDORSER_TRANSACTION' - var txid = channel_header.tx_id; - logger.info('transaction id :' + txid); - var transaction = payload.data; - var actionPayload = transaction.actions[0].payload; - var proposalPayload = actionPayload.chaincode_proposal_payload; - var invocationSpec = proposalPayload.input; - // Can obtain chaincode name and argument list (function name at the beginning) from invocationSpec - var ccid = invocationSpec.chaincode_spec.chaincode_id.name; - logger.info('chaincode id :' + ccid); - // Only notify transactions from the chaincode used in ServerPlugin - if (ccid == network.fabric.chaincodeId) { - var args = invocationSpec.chaincode_spec.input.args; - logger.info('args.length :' + args.length); - for (var j = 0; j < args.length; j++) { - // code must be specified for toString - args[j] = args[j].toString('utf8'); - logger.info('args[' + j + '] :' + args[j]); - } - var func = args[0]; - args.shift(); - - // Interpretation of response - var resp = actionPayload.action.proposal_response_payload.extension.response.payload; - logger.info('resp :' + resp); - - //The transaction data should include the following. - txlist.push({ - "chaincodeId":ccid, - "txId":txid, - "func":func, - "args":args - }); - } - } - } - logger.info('*** SEND BLOCK DATA ***'); - var ret_obj = { - "status" : 200, - "blockData" : txlist - }; - cb(ret_obj); - - }); - this._eh.connect(true); //fullBlock=true - }) - .catch((err) => { - logger.error(err); - var err_obj = { - "status" : 504, - "errorDetail" : err - }; - cb(err_obj); - }); - } else { - logger.info('target filter has already start watching.'); - } - } - - - /* - * stopMonitor - * Stop monitoring - * @param {string} clientId : Client ID of the monitoring stop request source - */ - stopMonitor(clientId) { - var filter = this._filterTable[clientId]; - - if (filter) { - // Stop filter & remove from table - if (this._eh == null) { - logger.error('EventHub does not exist'); - return; - } - if (this._eh.isconnected()) { - logger.info('Disconnecting the event hub'); - this._eh.disconnect(); - } - delete this._filterTable[clientId]; - } - } - -}; - -module.exports = ServerMonitorPlugin; diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.ts b/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.ts new file mode 100644 index 0000000000..4ba12d41a1 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/dependent/ServerMonitorPlugin.ts @@ -0,0 +1,168 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * ServerMonitorPlugin.js + */ + +/* + * Summary: + * Monitoring class of connection destination dependent part of linkage server + * Used when performing continuous monitoring. + * Processing that ends with reception of a single event is supported by implementing a unique function in ServerPlugin. + * Unlike ServerPlugin, it does not basically handle its own functions. + */ + + +// Basic package dependency declaration +var process = require('process'); +// IF declaration for fabric +var sdk = require('./fabricaccess.js'); +// config file +import { SplugConfig } from './PluginConfig'; +import { config } from '../core/config/default'; +// Log settings +import { getLogger } from "log4js"; +const logger = getLogger('ServerMonitorPlugin[' + process.pid + ']'); +logger.level = config.logLevel; + + +/* + * ServerMonitorPlugin + * Server monitoring class definition + */ +export class ServerMonitorPlugin { + + _filterTable: object; + _network; + _eh; + + constructor() { + // Define settings specific to the dependent part + // Initializing filter during monitoring + this._filterTable = {}; + this._network = SplugConfig; //channelID, mspid, peer settings, etc. + this._eh = null; + } + + /* + * startMonitor + * Start monitoring + * @param {string} clientId : Client ID of the monitoring start request source + * @param {function} cb : Callback function that receives the monitoring result at any time + */ + startMonitor(clientId, cb) { + logger.info('*** START MONITOR ***'); + logger.info('Client ID :' + clientId); + var filter = this._filterTable[clientId]; + var network = this._network; + var channel = null; + + if (!filter) { + sdk.GetClientAndChannel() + .then((retobj) => { + channel = retobj.channel; //Set the returned channel + this._filterTable[clientId] = retobj.client; + return sdk.GetSubmitter(retobj.client) + }) + .then((submitter) => { + var peer = this._filterTable[clientId].newPeer(network.fabric.peers[0].requests); + this._eh = channel.newChannelEventHub(peer); + logger.info('Connecting the event hub'); + this._eh.registerBlockEvent((block) => { + var txlist = []; + logger.info('*** Block Event ***'); + console.log('##[HL-BC] Notify new block data(D2)'); + logger.info('chain id :' + network.fabric.channelName); + logger.info("blocknumber : " + block.header.number); + var len = block.data.data.length; + logger.info('data.data.length :' + len); + console.log('##[HL-BC] Validate transactions(D3)'); + console.log('##[HL-BC] digital sign on valid transaction(D4)'); + for (var i = 0; i < len; i++) { + var payload = block.data.data[i].payload; + var channel_header = payload.header.channel_header; + if (channel_header.type == 3) { //'ENDORSER_TRANSACTION' + var txid = channel_header.tx_id; + logger.info('transaction id :' + txid); + var transaction = payload.data; + var actionPayload = transaction.actions[0].payload; + var proposalPayload = actionPayload.chaincode_proposal_payload; + var invocationSpec = proposalPayload.input; + // Can obtain chaincode name and argument list (function name at the beginning) from invocationSpec + var ccid = invocationSpec.chaincode_spec.chaincode_id.name; + logger.info('chaincode id :' + ccid); + // Only notify transactions from the chaincode used in ServerPlugin + if (ccid == network.fabric.chaincodeId) { + var args = invocationSpec.chaincode_spec.input.args; + logger.info('args.length :' + args.length); + for (var j = 0; j < args.length; j++) { + // code must be specified for toString + args[j] = args[j].toString('utf8'); + logger.info('args[' + j + '] :' + args[j]); + } + var func = args[0]; + args.shift(); + + // Interpretation of response + var resp = actionPayload.action.proposal_response_payload.extension.response.payload; + logger.info('resp :' + resp); + + //The transaction data should include the following. + txlist.push({ + "chaincodeId":ccid, + "txId":txid, + "func":func, + "args":args + }); + } + } + } + logger.info('*** SEND BLOCK DATA ***'); + var retObj = { + "status" : 200, + "blockData" : txlist + }; + cb(retObj); + + }); + this._eh.connect(true); //fullBlock=true + }) + .catch((err) => { + logger.error(err); + var errObj = { + "status" : 504, + "errorDetail" : err + }; + cb(errObj); + }); + } else { + logger.info('target filter has already start watching.'); + } + } + + + /* + * stopMonitor + * Stop monitoring + * @param {string} clientId : Client ID of the monitoring stop request source + */ + stopMonitor(clientId) { + var filter = this._filterTable[clientId]; + + if (filter) { + // Stop filter & remove from table + if (this._eh == null) { + logger.error('EventHub does not exist'); + return; + } + if (this._eh.isconnected()) { + logger.info('Disconnecting the event hub'); + this._eh.disconnect(); + } + delete this._filterTable[clientId]; + } + } + +}; + diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.js b/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.js deleted file mode 100644 index d3ffa5d73f..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.js +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerPlugin.js - */ - -/* - * Summary: - * Dependent part of the connection destination of the connector - * Define and implement the function independently according to the connection destination dependent part (adapter) on the core side. - */ - -'use strict'; - -// config file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// utility -var SplugUtil = require('./PluginUtil.js'); -// Read the library, SDK, etc. according to EC specifications as needed -var fabric = require('./fabricaccess.js'); - -/* - * ServerPlugin - * ServerPlugin class definition - */ -var ServerPlugin = class { - /* - * constructor - */ - constructor() { - // Define settings specific to the dependent part - } - - /* - * isExistFunction - * - * @param {String} funcName : The function name you want to determine. - * - * @return {Boolean} true : exist / false : not exist - * - * @desc Determines if the specified function exists in its class. - * Make sure that the support status of your class can be determined by your class. - * Functions that you do not want to call directly need to be devised such as implemented outside of this class like utilities. - */ - isExistFunction(funcName) { - if (this[funcName] != undefined) { - return true; - } else { - return false; - } - } - - /* - * changeCarOwner - * Change car owner - * - * @param {Object} args : JSON Object - * { - * "carId":, - * "newOwner": - * } - * @return {Object} JSON object - */ - changeCarOwner(args) { - return new Promise((resolve, reject) => { - logger.info("changeCarOwner start"); - var ret_obj = {}; - var carId = args["carId"]; - var newOwner = args["newOwner"]; - if (carId == undefined || newOwner == undefined) { - var emsg = "Insufficient parameters."; - logger.info(emsg); - ret_obj = { - "status": 504, - "errorDetail": emsg - }; - return reject(ret_obj); - } - var reqparam = { fcn: "changeCarOwner", args: [carId, newOwner] }; - // Block generation event monitoring target because it is performed from the operation request by the CC chain code - fabric.Invoke(reqparam, false) - .then((returnvalue) => { - if (returnvalue != null) { - ret_obj = { - "status": 200, - "data": returnvalue // Should contain the transaction ID - }; - return resolve(ret_obj); - } - }).catch(err => { - var emsg = err.toString().replace(/Error: /g, ""); - logger.error(emsg); - ret_obj = { - "status": 504, - "errorDetail": emsg - }; - return reject(ret_obj); - }); - }); - } - - /** - * Offline trading - * @param {object} args - * [0] signedCommitProposal - * [1] commitReq - * @return {Object} JSON object - */ - sendSignedProposal(args) { - return new Promise((resolve, reject) => { - logger.info("sendSignedProposal start"); - var ret_obj = {}; - // parameter check - logger.info("sendSignedProposal parameter check"); - var signedCommitProposal = args[0]; - var commitReq = args[1]; - if (signedCommitProposal == undefined || commitReq == undefined) { - var emsg = "Insufficient parameters."; - logger.info(emsg); - ret_obj = { - "status": 504, - "errorDetail": emsg - }; - return reject(ret_obj); - } - // call chainncode - fabric.InvokeSendSignedProposal(signedCommitProposal, commitReq) - .then((returnvalue) => { - if (returnvalue != null) { - ret_obj = { - "status": 200, - "data": returnvalue - }; - return resolve(ret_obj); - } - }).catch(err => { - var emsg = err.toString().replace(/Error: /g, ""); - logger.error(emsg); - ret_obj = { - "status": 504, - "errorDetail": emsg - }; - return reject(ret_obj); - }); - }); - } - -} /* class */ - -module.exports = ServerPlugin; - diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.ts b/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.ts new file mode 100644 index 0000000000..388fe3906f --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/dependent/ServerPlugin.ts @@ -0,0 +1,480 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * ServerPlugin.js + */ + +/* + * Summary: + * Dependent part of the connection destination of the connector + * Define and implement the function independently according to the connection destination dependent part (adapter) on the core side. + */ + +// config file +import { SplugConfig } from './PluginConfig'; +import { config } from '../core/config/default'; +// Log settings +import { getLogger } from "log4js"; +const logger = getLogger('ServerPlugin[' + process.pid + ']'); +logger.level = config.logLevel; +// utility +var SplugUtil = require('./PluginUtil.js'); +// Read the library, SDK, etc. according to EC specifications as needed +var fabric = require('./fabricaccess.js'); + +var FabricClient = require('fabric-client'); +var copService = require('fabric-ca-client'); +var path = require('path'); +const { FileSystemWallet, Gateway } = require('fabric-network'); +const fs = require('fs'); +const ccpPath = path.resolve(__dirname, 'connection.json'); +const ccpJSON = fs.readFileSync(ccpPath, 'utf8'); +const ccp = JSON.parse(ccpJSON); +const walletPath = path.resolve(__dirname, 'wallet'); +const connUserName = SplugConfig.fabric.connUserName; + +/* + * ServerPlugin + * ServerPlugin class definition + */ +export class ServerPlugin { + /* + * constructor + */ + constructor() { + // Define settings specific to the dependent part + } + + /* + * isExistFunction + * + * @param {String} funcName : The function name you want to determine. + * + * @return {Boolean} true : exist / false : not exist + * + * @desc Determines if the specified function exists in its class. + * Make sure that the support status of your class can be determined by your class. + * Functions that you do not want to call directly need to be devised such as implemented outside of this class like utilities. + */ + isExistFunction(funcName) { + if (this[funcName] != undefined) { + return true; + } else { + return false; + } + } + + /* + * contractTransaction(Sync) + * + * @param {Object} args : JSON Object + * { + * "contract": { + * "channelName": , + * "contractName": + * }, + * "args": { + * "args":[ + * , + * < : >, + * < : > + * ] + * }, + * "method": { + * "method": + * ] + * }, + * "reqID": // option + * } + * @return {Object} JSON object + */ + contractTransaction(args) { + return new Promise((resolve, reject) => { + logger.info("evaluateTransaction start"); + logger.debug(`##evaluateTransaction(A)`); + var retObj = {}; + var reqID = args['reqID']; + if (reqID === undefined) { + reqID = null; + } + logger.debug(`##evaluateTransaction(Aa): args: ${JSON.stringify(args.args.args)}, reqID: ${reqID}`); + var reqparam = { method: args.method, args: args.args.args, channelName: args.contract.channelName, contractName: args.contract.contractName }; + // Block generation event monitoring target because it is performed from the operation request by the CC chain code + InvokeSync(reqparam) + .then((returnvalue: any) => { + logger.debug(`##evaluateTransaction(B)`); + logger.debug(`##evaluateTransaction(B1), returnvalue: ${returnvalue}`); + if (returnvalue == null) { + logger.debug(`##evaluateTransaction(B2), returnvalue: null`); + } + else if (returnvalue == undefined) { + logger.debug(`##evaluateTransaction(B3), returnvalue: undefined`); + } + else if (returnvalue == "") { + logger.debug(`##evaluateTransaction(B4), returnvalue: empty string`); + } + if (returnvalue != null) { + logger.debug(`##evaluateTransaction(B5)`); + let objRetValue = {}; + if (returnvalue != "") { + logger.debug(`##evaluateTransaction(B6)`); + objRetValue = JSON.parse(returnvalue); + } + retObj = { + "resObj" : { + "status" : 200, + "data": [objRetValue] // car information. Return as an array. + } + }; + if (reqID !== null) { + retObj["id"] = reqID; + } + logger.debug(`##evaluateTransaction(C1c) retObj: ${retObj}`); + return resolve(retObj); + } + logger.debug(`##evaluateTransaction(C)`); + }).catch(err => { + logger.debug(`##evaluateTransaction(D)`); + var emsg = err.toString().replace(/Error: /g, ""); + logger.error(emsg); + retObj = { + "resObj" : { + "status": 504, + "errorDetail": emsg + } + }; + return reject(retObj); + }); + }); + } + + /** + * Offline trading + * @param {object} args : JSON Object + * { + * "contract": { + * "channelName":, + * }, + * "args": { + * "args":[ + * { + * "signedCommitProposal":, + * "commitReq": + * } + * ] + * }, + * "reqID": // option + * } + * @return {Object} JSON object + */ + sendSignedProposal(args) { + return new Promise((resolve, reject) => { + logger.info("sendSignedProposal start"); + var retObj = {}; + // parameter check + logger.info("sendSignedProposal parameter check"); + var channelName = args.contract.channelName; + var signedCommitProposal = args.args.args[0].signedCommitProposal; + var commitReq = args.args.args[0].commitReq; + logger.info(`##channelName = ${channelName}`); + logger.info(`##signedCommitProposal = ${signedCommitProposal}`); + logger.info(`##commitReq = ${commitReq}`); + if (signedCommitProposal == undefined || commitReq == undefined) { + var emsg = "Insufficient parameters."; + logger.info(emsg); + retObj = { + "status": 504, + "errorDetail": emsg + }; + return reject(retObj); + } + var reqparam = { + signedCommitProposal: signedCommitProposal, + commitReq: commitReq, + channelName: channelName + }; + // call chainncode + InvokeSendSignedProposal(reqparam) + .then((returnvalue) => { + if (returnvalue != null) { + retObj = { + "status": 200, + "data": returnvalue + }; + return resolve(retObj); + } + }).catch(err => { + var emsg = err.toString().replace(/Error: /g, ""); + logger.error(emsg); + retObj = { + "status": 504, + "errorDetail": emsg + }; + return reject(retObj); + }); + }); + } + +} /* class */ + + +/* + * Invoke function + * @param reqBody [json object] {fcn:, args:[arg1>,,,,]} + * @return [string] Success: Chain code execution result + * Failure: Chain code error or internal error +*/ +async function Invoke(reqBody) { + var txId = null; + var theUser = null; + var eventhubs = []; + var invokeResponse; //Return value from chain code + + try { + logger.info('##fablicaccess: Invoke start'); + + var fcn = reqBody.fcn; + var args = reqBody.args; + + // Create a new file system based wallet for managing identities. + //const walletPath = path.join(process.cwd(), 'wallet'); + const wallet = new FileSystemWallet(walletPath); + console.log(`Wallet path: ${walletPath}`); + + // Check to see if we've already enrolled the user. + const userExists = await wallet.exists(connUserName); + if (!userExists) { + //logger.error(`An identity for the user ${connUserName} does not exist in the wallet`); + const errMsg = `An identity for the user ${connUserName} does not exist in the wallet`; + logger.error(errMsg); + logger.error('Run the registerUser.js application before retrying'); + } + + // Create a new gateway for connecting to our peer node. + const gateway = new Gateway(); + await gateway.connect(ccp, { wallet, identity: connUserName, discovery: { enabled: false } }); + + // Get the network (channel) our contract is deployed to. + const network = await gateway.getNetwork(reqBody.channelName); + + // Get the contract from the network. + const contract = network.getContract(reqBody.contractName); + + // Submit the specified transaction. + logger.info(`##fablicaccess: Invoke Params: fcn=${fcn}, args0=${args[0]}, args1=${args[1]}`); + const transaction = contract.createTransaction(fcn); + + txId = transaction.getTransactionID().getTransactionID(); + logger.info('##fablicaccess: txId = ' + txId); + + const respData = await transaction.submit(args[0], args[1]); + + // const respData = await contract.submitTransaction(fcn, args[0], args[1]); + logger.info('Transaction has been submitted'); + + // Disconnect from the gateway. + await gateway.disconnect(); + + } catch (error) { + logger.error(`Failed to submit transaction: ${error}`); + } +} + +/* + * Invoke Sync function + * @param reqBody [json object] {fcn:, args:[arg1>,,,,], channelName:, contractName:} + * @return [string] Success: Chain code execution result + * Failure: Chain code error or internal error +*/ +async function InvokeSync(reqBody) { + return new Promise(async function (resolve, reject) { + try { + logger.info('##fablicaccess: InvokeSync start'); + logger.debug(`##InvokeSync(A)`); + + var type = reqBody.method.type; + var fcn = reqBody.method.command; + var args = reqBody.args; + + // Create a new file system based wallet for managing identities. + //const walletPath = path.join(process.cwd(), 'wallet'); + logger.debug(`##InvokeSync(B)`); + const wallet = new FileSystemWallet(walletPath); + console.log(`Wallet path: ${walletPath}`); + + // Check to see if we've already enrolled the user. + logger.debug(`##InvokeSync(C)`); + const userExists = await wallet.exists(connUserName); + if (!userExists) { + logger.debug(`##InvokeSync(C1)`); + //logger.error(`An identity for the user ${connUserName} does not exist in the wallet`); + const errMsg = `An identity for the user ${connUserName} does not exist in the wallet`; + logger.error(errMsg); + logger.error('Run the registerUser.js application before retrying'); + return reject(errMsg); + } + + // Create a new gateway for connecting to our peer node. + logger.debug(`##InvokeSync(D)`); + const gateway = new Gateway(); + await gateway.connect(ccp, { wallet, identity: connUserName, discovery: { enabled: false } }); + + // Get the network (channel) our contract is deployed to. + logger.debug(`##InvokeSync(E)`); + const network = await gateway.getNetwork(reqBody.channelName); + + // Get the contract from the network. + logger.debug(`##InvokeSync(F)`); + const contract = network.getContract(reqBody.contractName); + + // Submit the specified transaction. + logger.debug(`##InvokeSync(G)`); + logger.info(`##fablicaccess: InvokeSync Params: type=${type}, fcn=${fcn}, args0=${args[0]}, args1=${args[1]}, args2=${args[2]}`); + // const transaction = contract.createTransaction(fcn); + var result: any = null; + switch (args.length) { + case 0: + logger.debug(`##InvokeSync(G1): No args.`); + if (type === "evaluateTransaction") { + logger.debug(`##InvokeSync(G1): call evaluateTransaction`); + result = await contract.evaluateTransaction(fcn); + } else { + logger.debug(`##InvokeSync(G1): call submitTransaction`); + result = await contract.submitTransaction(fcn); + } + break; + case 1: + logger.debug(`##InvokeSync(G2): One arg.`); + if (type === "evaluateTransaction") { + logger.debug(`##InvokeSync(G1): call evaluateTransaction`); + result = await contract.evaluateTransaction(fcn, args[0]); + } else { + logger.debug(`##InvokeSync(G1): call submitTransaction`); + result = await contract.submitTransaction(fcn, args[0]); + } + break; + case 2: + logger.debug(`##InvokeSync(G3): Two args.`); + if (type === "evaluateTransaction") { + logger.debug(`##InvokeSync(G1): call evaluateTransaction`); + result = await contract.evaluateTransaction(fcn, args[0], args[1]); + } else { + logger.debug(`##InvokeSync(G1): call submitTransaction`); + result = await contract.submitTransaction(fcn, args[0], args[1]); + } + break; + case 3: + logger.debug(`##InvokeSync(G4): Three args.`); + if (type === "evaluateTransaction") { + logger.debug(`##InvokeSync(G1): call evaluateTransaction`); + result = await contract.evaluateTransaction(fcn, args[0], args[1], args[2]); + } else { + logger.debug(`##InvokeSync(G1): call submitTransaction`); + result = await contract.submitTransaction(fcn, args[0], args[1], args[2]); + } + break; + } + logger.info(`##fablicaccess: InvokeSync result: ${result}`); + console.log(`##fablicaccess: InvokeSync result: ${result}`); + + // Disconnect from the gateway. + logger.debug(`##InvokeSync(H)`); + await gateway.disconnect(); + + logger.debug(`##InvokeSync(I)`); + return resolve(result); + + } catch (error) { + logger.debug(`##InvokeSync(Z)`); + const errMsg = `Failed to submit transaction: ${error}`; + logger.error(errMsg); + return reject(errMsg); + } + }); +} + +/** + * setup TLS for this client + * @param {*} client + * @param {*} enrollmentID + * @param {*} secret + */ +async function TLSSetup(client, enrollmentID, secret) { + const tlsOptions = { + trustedRoots: [], + verify: false + }; + logger.info("tlssetup start"); + const caService = new copService(SplugConfig.fabric.ca.url, tlsOptions, SplugConfig.fabric.ca.name); + const req = { + enrollmentID: enrollmentID, + enrollmentSecret: secret, + profile: 'tls' + }; + const enrollment = await caService.enroll(req); + client.setTlsClientCertAndKey(enrollment.certificate, enrollment.key.toBytes()); +} + +/** + * Creating a channel object + * @param {string} channelName + */ +async function setupChannel(channelName) { + logger.info("setupChannel start"); + const client = new FabricClient(); + await TLSSetup(client, SplugConfig.fabric.submitter.name, SplugConfig.fabric.submitter.secret); + const channel = client.newChannel(channelName); + + for (var i = 0; i < SplugConfig.fabric.peers.length; i++) { + var peer = client.newPeer( + SplugConfig.fabric.peers[i].requests + ); + channel.addPeer(peer); + } + + const orderer = client.newOrderer( + SplugConfig.fabric.orderer.url + ); + channel.addOrderer(orderer); + logger.info("setupChannel end"); + return channel; +} + +/** + * Function for InvokeSendSignedProposal + * @param reqBody [json object] {signedCommitProposal:, commitReq:, channelName:} + * @return [string] Success: Chain code execution result + * Failure: Chain code error or internal error + */ +async function InvokeSendSignedProposal(reqBody) { + return new Promise(async function (resolve, reject) { + logger.info("InvokeSendSignedProposal start"); + + var invokeResponse; // Return value from chain code + var channel; // Channel + + try { + //channel object generation + if (channel == undefined) { + channel = await setupChannel(reqBody.channelName); + } + + const response = await channel.sendSignedTransaction({ + signedProposal: reqBody.signedCommitProposal, + request: reqBody.commitReq, + }); + logger.info("successfully send signedCommitProposal"); + logger.info("response : " + JSON.stringify(response)); + if (response.status === 'SUCCESS') { + invokeResponse = response; + return resolve(invokeResponse); + } else { + throw new Error('Failed to order the transaction. Error code: ' + response.status); + } + } catch (e) { + return reject(e); + } + }); +} + diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.js b/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.js deleted file mode 100644 index 8588686b7b..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.js +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * fabricaccess.js - */ - -/* - * Summary: - * Request processing library for fabric v1.4.0 - */ - - -//Dependent library -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -var path = require('path'); - -//fabric client dependent library -var Fabric_Client = require('fabric-client'); -var User = require('fabric-client/lib/User.js'); -var copService = require('fabric-ca-client'); - -// list of fabric-client objects -var clients = {} - -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('fabricaccess[' + process.pid + ']'); -logger.level = config.logLevel; - -const { FileSystemWallet, Gateway } = require('fabric-network'); -const fs = require('fs'); -//const path = require('path'); - -const ccpPath = path.resolve(__dirname, 'connection.json'); -const ccpJSON = fs.readFileSync(ccpPath, 'utf8'); -const ccp = JSON.parse(ccpJSON); - -const walletPath = path.resolve(__dirname, 'wallet'); -const connUserName = SplugConfig.fabric.connUserName; -const channelName = SplugConfig.fabric.channelName; -const contractName = SplugConfig.fabric.contractName; - -/* - * Invoke function - * @param reqBody [json object] {fcn:, args:[arg1>,,,,]} - * isWait [bool] true : returning a response after waiting for block generation - * @return [string] Success: Chain code execution result - * Failure: Chain code error or internal error -*/ -exports.Invoke = async function (reqBody, isWait) { - var tx_id = null; - var the_user = null; - var eventhubs = []; - var invokeResponse; //Return value from chain code - - try { - logger.info('##fablicaccess: Invoke start'); - - var fcn = reqBody.fcn; - var args = reqBody.args; - - // Create a new file system based wallet for managing identities. - //const walletPath = path.join(process.cwd(), 'wallet'); - const wallet = new FileSystemWallet(walletPath); - console.log(`Wallet path: ${walletPath}`); - - // Check to see if we've already enrolled the user. - const userExists = await wallet.exists(connUserName); - if (!userExists) { - //logger.error(`An identity for the user ${connUserName} does not exist in the wallet`); - const errMsg = `An identity for the user ${connUserName} does not exist in the wallet`; - logger.error(errMsg); - logger.error('Run the registerUser.js application before retrying'); - } - - // Create a new gateway for connecting to our peer node. - const gateway = new Gateway(); - await gateway.connect(ccp, { wallet, identity: connUserName, discovery: { enabled: false } }); - - // Get the network (channel) our contract is deployed to. - const network = await gateway.getNetwork(channelName); - - // Get the contract from the network. - const contract = network.getContract(contractName); - - // Submit the specified transaction. - logger.info(`##fablicaccess: Invoke Params: fcn=${fcn}, args0=${args[0]}, args1={args[1]}`); - const transaction = contract.createTransaction(fcn); - - tx_id = transaction.getTransactionID().getTransactionID(); - logger.info('##fablicaccess: tx_id = ' + tx_id); - - const respData = await transaction.submit(args[0], args[1]); - - // const respData = await contract.submitTransaction(fcn, args[0], args[1]); - logger.info('Transaction has been submitted'); - - // Disconnect from the gateway. - await gateway.disconnect(); - - } catch (error) { - logger.error(`Failed to submit transaction: ${error}`); - } -} - -/** - * setup TLS for this client - * @param {*} client - * @param {*} enrollmentID - * @param {*} secret - */ -async function TLSSetup(client, enrollmentID, secret) { - const tlsOptions = { - trustedRoots: [], - verify: false - }; - logger.info("tlssetup start"); - const caService = new copService(SplugConfig.fabric.ca.url, tlsOptions, SplugConfig.fabric.ca.name); - const req = { - enrollmentID: enrollmentID, - enrollmentSecret: secret, - profile: 'tls' - }; - const enrollment = await caService.enroll(req); - client.setTlsClientCertAndKey(enrollment.certificate, enrollment.key.toBytes()); -} - -/** - * Creating a channel object - * @param {string} channelName - */ -async function setupChannel(channelName) { - logger.info("setupChannel start"); - const client = new Fabric_Client(); - await TLSSetup(client, SplugConfig.fabric.submitter.name, SplugConfig.fabric.submitter.secret); - const channel = client.newChannel(channelName); - - for (var i = 0; i < SplugConfig.fabric.peers.length; i++) { - var peer = client.newPeer( - SplugConfig.fabric.peers[i].requests - ); - channel.addPeer(peer); - } - - const orderer = client.newOrderer( - SplugConfig.fabric.orderer.url - ); - channel.addOrderer(orderer); - logger.info("setupChannel end"); - return channel; -} - -/** - * Function for InvokeSendSignedProposal - * @param {*} signedCommitProposal - * @param {*} commitReq - * @return [string] Success: Chain code execution result - * Failure: Chain code error or internal error - */ -exports.InvokeSendSignedProposal = async function (signedCommitProposal, commitReq) { - return new Promise(async function (resolve, reject) { - logger.info("InvokeSendSignedProposal start"); - - var invokeResponse; // Return value from chain code - var channel; // Channel - - try { - //channel object generation - if (channel == undefined) { - channel = await setupChannel(SplugConfig.fabric.channelName); - } - - const response = await channel.sendSignedTransaction({ - signedProposal: signedCommitProposal, - request: commitReq, - }); - logger.info("successfully send signedCommitProposal"); - logger.info("response : " + JSON.stringify(response)); - if (response.status === 'SUCCESS') { - invokeResponse = response; - return resolve(invokeResponse); - } else { - throw new Error('Failed to order the transaction. Error code: ' + response.status); - } - } catch (e) { - return reject(e); - } - }); -} - -// Get user object to send Proposal to EP -function getSubmitter(cli) { - logger.info('##fabricaccess_getSubmitter'); - var caUrl = SplugConfig.fabric.ca.url; - var caName = SplugConfig.fabric.ca.name; - var submitter = SplugConfig.fabric.submitter; - return cli.getUserContext(submitter.name, true) - .then((user) => { - - return new Promise((resolve, reject) => { - - if (user && user.isEnrolled()) { - return resolve(user); - } - var member = new User(submitter.name); - var cryptoSuite = cli.getCryptoSuite(); - if (!cryptoSuite) { - var storePath = path.join(__dirname, SplugConfig.fabric.keystore); - cryptoSuite = Fabric_Client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore( - Fabric_Client.newCryptoKeyStore({ - path: storePath - }) - ); - cli.setCryptoSuite(cryptoSuite); - } - member.setCryptoSuite(cryptoSuite); - - var tlsOptions = { - trustedRoots: [], - verify: false - }; - var cop = new copService(caUrl, tlsOptions, caName, cryptoSuite); - return cop.enroll({ - enrollmentID: submitter.name, - enrollmentSecret: submitter.secret - }).then((enrollment) => { - return member.setEnrollment(enrollment.key, enrollment.certificate, SplugConfig.fabric.mspid); - }).then(() => { - return cli.setUserContext(member, false); - }).then(() => { - return resolve(member); - }).catch((err) => { - return reject(err); - }); - }); - }); -} - -// Export also for use with ServerMonitorPlugin -exports.GetSubmitter = function (cli) { - return getSubmitter(cli); -} - -// fabric-client and Channel object generation -function getClientAndChannel() { - logger.info('##fabricaccess_getClientAndChannel'); - var retObj = { client: null, channel: null }; - var channelName = SplugConfig.fabric.channelName; - // Since only one KVS can be set in the client, management in CA units as well as KVS path - var isNewClient = false; - var client = clients[SplugConfig.fabric.ca.name]; - if (!client) { - logger.info('create new fabric-client'); - client = new Fabric_Client(); - clients[SplugConfig.fabric.ca.name] = client; - isNewClient = true; - } - - var channel = null; - - // * If getChannel of v1.0 SDK does not exist, an exception is returned instead of null, so try ~ catch - // Therefore, the error from Client.js will always be output in the log for the first time, but it is not harmful - try { - channel = client.getChannel(channelName); - } catch (e) { - if (channel == null) { - logger.info('create new channel, name=' + channelName); - channel = client. - newChannel(channelName); - var orderer = client.newOrderer(SplugConfig.fabric.orderer.url); - channel.addOrderer(orderer); - // EP settings - for (var i = 0; i < SplugConfig.fabric.peers.length; i++) { - var peer = client.newPeer(SplugConfig.fabric.peers[i].requests); - channel.addPeer(peer); - } - } else { - // Exception when reflecting connection destination information difference - logger.error(e); - } - } - retObj.channel = channel; - - return new Promise((resolve, reject) => { - if (isNewClient) { - //var storePath = "/tmp/" + SplugConfig.fabric.keystore; - var storePath = SplugConfig.fabric.keystore; - var cryptoSuite = Fabric_Client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore( - Fabric_Client.newCryptoKeyStore({ - path: storePath - }) - ); - client.setCryptoSuite(cryptoSuite); - - // Generate enrollment information storage location - return Fabric_Client.newDefaultKeyValueStore({ - path: storePath - }) - .then((store) => { - // Set KeyValue Store - client.setStateStore(store); - retObj.client = client; - resolve(retObj); - }) - } else { - retObj.client = client; - resolve(retObj); - } - }); -} - -// Export also for use with ServerMonitorPlugin -exports.GetClientAndChannel = function () { - return getClientAndChannel(); -} \ No newline at end of file diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.ts b/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.ts new file mode 100644 index 0000000000..b36f84a9c2 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/dependent/fabricaccess.ts @@ -0,0 +1,157 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * fabricaccess.js + */ + +/* + * Summary: + * Request processing library for fabric v1.4.0 + */ + +//Dependent library +import { SplugConfig } from './PluginConfig'; +import { config } from '../core/config/default'; +var path = require('path'); + +//fabric client dependent library +var FabricClient = require('fabric-client'); +var User = require('fabric-client/lib/User.js'); +var copService = require('fabric-ca-client'); + +// list of fabric-client objects +var clients = {} + +// Log settings +import { getLogger } from "log4js"; +const logger = getLogger('fabricaccess[' + process.pid + ']'); +logger.level = config.logLevel; + +// Get user object to send Proposal to EP +function getSubmitter(cli) { + logger.info('##fabricaccess_getSubmitter'); + var caUrl = SplugConfig.fabric.ca.url; + var caName = SplugConfig.fabric.ca.name; + var submitter = SplugConfig.fabric.submitter; + return cli.getUserContext(submitter.name, true) + .then((user) => { + + return new Promise((resolve, reject) => { + + if (user && user.isEnrolled()) { + return resolve(user); + } + var member = new User(submitter.name); + var cryptoSuite = cli.getCryptoSuite(); + if (!cryptoSuite) { + var storePath = path.join(__dirname, SplugConfig.fabric.keystore); + cryptoSuite = FabricClient.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore( + FabricClient.newCryptoKeyStore({ + path: storePath + }) + ); + cli.setCryptoSuite(cryptoSuite); + } + member.setCryptoSuite(cryptoSuite); + + var tlsOptions = { + trustedRoots: [], + verify: false + }; + var cop = new copService(caUrl, tlsOptions, caName, cryptoSuite); + return cop.enroll({ + enrollmentID: submitter.name, + enrollmentSecret: submitter.secret + }).then((enrollment) => { + return member.setEnrollment(enrollment.key, enrollment.certificate, SplugConfig.fabric.mspid); + }).then(() => { + return cli.setUserContext(member, false); + }).then(() => { + return resolve(member); + }).catch((err) => { + return reject(err); + }); + }); + }); +} + +// Export also for use with ServerMonitorPlugin +exports.GetSubmitter = function (cli) { + return getSubmitter(cli); +} + +// fabric-client and Channel object generation +function getClientAndChannel() { + logger.info('##fabricaccess_getClientAndChannel'); + var retObj = { client: null, channel: null }; + var channelName = SplugConfig.fabric.channelName; + // Since only one KVS can be set in the client, management in CA units as well as KVS path + var isNewClient = false; + var client = clients[SplugConfig.fabric.ca.name]; + if (!client) { + logger.info('create new fabric-client'); + client = new FabricClient(); + clients[SplugConfig.fabric.ca.name] = client; + isNewClient = true; + } + + var channel = null; + + // * If getChannel of v1.0 SDK does not exist, an exception is returned instead of null, so try ~ catch + // Therefore, the error from Client.js will always be output in the log for the first time, but it is not harmful + try { + channel = client.getChannel(channelName); + } catch (e) { + if (channel == null) { + logger.info('create new channel, name=' + channelName); + channel = client. + newChannel(channelName); + var orderer = client.newOrderer(SplugConfig.fabric.orderer.url); + channel.addOrderer(orderer); + // EP settings + for (var i = 0; i < SplugConfig.fabric.peers.length; i++) { + var peer = client.newPeer(SplugConfig.fabric.peers[i].requests); + channel.addPeer(peer); + } + } else { + // Exception when reflecting connection destination information difference + logger.error(e); + } + } + retObj.channel = channel; + + return new Promise((resolve, reject) => { + if (isNewClient) { + //var storePath = "/tmp/" + SplugConfig.fabric.keystore; + var storePath = SplugConfig.fabric.keystore; + var cryptoSuite = FabricClient.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore( + FabricClient.newCryptoKeyStore({ + path: storePath + }) + ); + client.setCryptoSuite(cryptoSuite); + + // Generate enrollment information storage location + return FabricClient.newDefaultKeyValueStore({ + path: storePath + }) + .then((store) => { + // Set KeyValue Store + client.setStateStore(store); + retObj.client = client; + resolve(retObj); + }) + } else { + retObj.client = client; + resolve(retObj); + } + }); +} + +// Export also for use with ServerMonitorPlugin +exports.GetClientAndChannel = function () { + return getClientAndChannel(); +} \ No newline at end of file diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/package.json b/packages/ledger-plugin/fabric/validator/src/dependent/package.json deleted file mode 100644 index a3217a3f01..0000000000 --- a/packages/ledger-plugin/fabric/validator/src/dependent/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "dependent", - "version": "0.0.0", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { - "config": "^1.26.1", - "log4js": "^3.0.6", - "fabric-ca-client": "~1.4.0", - "fabric-network": "~1.4.0" - } -} diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/template/PluginConfig_template.js b/packages/ledger-plugin/fabric/validator/src/dependent/template/PluginConfig_template.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/src/dependent/template/PluginConfig_template.js rename to packages/ledger-plugin/fabric/validator/src/dependent/template/PluginConfig_template.ts diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/PluginUtil_template.ts b/packages/ledger-plugin/fabric/validator/src/dependent/template/PluginUtil_template.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/PluginUtil_template.ts rename to packages/ledger-plugin/fabric/validator/src/dependent/template/PluginUtil_template.ts diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/ServerMonitorPlugin_template.ts b/packages/ledger-plugin/fabric/validator/src/dependent/template/ServerMonitorPlugin_template.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/ServerMonitorPlugin_template.ts rename to packages/ledger-plugin/fabric/validator/src/dependent/template/ServerMonitorPlugin_template.ts diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/ServerPlugin_template.ts b/packages/ledger-plugin/fabric/validator/src/dependent/template/ServerPlugin_template.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/ServerPlugin_template.ts rename to packages/ledger-plugin/fabric/validator/src/dependent/template/ServerPlugin_template.ts diff --git a/packages/ledger-plugin/fabric/validator/src/package.json b/packages/ledger-plugin/fabric/validator/src/package.json new file mode 100644 index 0000000000..980c990d35 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/package.json @@ -0,0 +1,33 @@ +{ + "name": "connector", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ../dist/core/bin/www.js", + "debug": "nodemon --inspect ../dist/core/bin/www.js", + "build": "npm run build-ts && npm run copy-static-assets", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json", + "copy-static-assets": "ts-node copyStaticAssets.ts", + "init-fabric": "ln -s ../src/node_modules ../dist/node_modules" + }, + "dependencies": { + "@types/node": "^14.14.5", + "body-parser": "~1.17.1", + "config": "^1.26.1", + "cookie-parser": "~1.4.3", + "debug": "~4.1.1", + "express": "~4.15.2", + "log4js": "^3.0.6", + "morgan": "~1.8.1", + "serve-favicon": "~2.4.2", + "shelljs": "^0.8.4", + "socket.io": "^2.0.4", + "ts-node": "^9.0.0", + "fabric-ca-client": "~1.4.0", + "fabric-network": "~1.4.0" + }, + "devDependencies": { + "typescript": "^3.9.3" + } +} diff --git a/packages/ledger-plugin/fabric/validator/src/script-build-validator.sh b/packages/ledger-plugin/fabric/validator/src/script-build-validator.sh new file mode 100755 index 0000000000..9f0531b3ff --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/script-build-validator.sh @@ -0,0 +1,5 @@ +## Build a validator for Fabric +echo "[process] Build a validator for Fabric" +npm install +npm run build +npm run init-fabric # For making symbolic for node_modules, enough to be done only once. \ No newline at end of file diff --git a/packages/ledger-plugin/fabric/validator/src/script-start-validator.sh b/packages/ledger-plugin/fabric/validator/src/script-start-validator.sh new file mode 100755 index 0000000000..2f23c5368d --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/src/script-start-validator.sh @@ -0,0 +1,3 @@ +## Start a validator for Fabric +echo "[process] Start a validator for Fabric" +npm run start \ No newline at end of file diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/tsconfig.json b/packages/ledger-plugin/fabric/validator/src/tsconfig.json similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/tsconfig.json rename to packages/ledger-plugin/fabric/validator/src/tsconfig.json diff --git a/packages/ledger-plugin/fabric/validator/unit-test/PluginConfig.js b/packages/ledger-plugin/fabric/validator/unit-test/PluginConfig.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/unit-test/PluginConfig.js rename to packages/ledger-plugin/fabric/validator/unit-test/PluginConfig.ts diff --git a/packages/ledger-plugin/fabric/validator/unit-test/README.md b/packages/ledger-plugin/fabric/validator/unit-test/README.md deleted file mode 100644 index 67f2006247..0000000000 --- a/packages/ledger-plugin/fabric/validator/unit-test/README.md +++ /dev/null @@ -1,82 +0,0 @@ - - -# Validator Driver - -## The point of this document -This document describes the procedures for runnning fabric validator unit-test. - -## Assumption -- Validator for fabric ledger is already running - - ProcedureURL: https://github.com/hyperledger/cactus/blob/master/packages/ledger-plugin/fabric/validator/src/README.md -- The fabcar container is already running - - ProcedureURL: https://github.com/hyperledger/cactus/blob/master/packages/ledger-plugin/fabric/validator/unit-test/fabric-docker/README.md - -## How to unit-test fabric validator -- There are 2 unit-tests for fabric validator. -### step1: Get car information -- Target source: "queryCar.js" -- This script is for getting car information recorded in fabcar. - -1) Run -
-	node queryCar.js
- - - Sample output -
-		Transaction has been evaluated, result is: [{"Key":"CAR0", "Record":{"colour":"blue","make":"Toyota","model":"Prius","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"}},{"Key":"CAR2", "Record":{"colour":"green","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"colour":"yellow","make":"Volkswagen","model":"Passat","owner":"Max"}},{"Key":"CAR4", "Record":{"colour":"black","make":"Tesla","model":"S","owner":"Adriana"}},{"Key":"CAR5", "Record":{"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}},{"Key":"CAR6", "Record":{"colour":"white","make":"Chery","model":"S22L","owner":"Aarav"}},{"Key":"CAR7", "Record":{"colour":"violet","make":"Fiat","model":"Punto","owner":"Pari"}},{"Key":"CAR8", "Record":{"colour":"indigo","make":"Tata","model":"Nano","owner":"Valeria"}},{"Key":"CAR9", "Record":{"colour":"brown","make":"Holden","model":"Barina","owner":"Shotaro"}}]
- -### step2: Asset transfer -- Target source: "validatorDriver_signTransactionOffline.js" -- This script is for setting owner information. - -1) Check the private key of wallet/admin - - Get the filename which is replaced `-pub` with `-priv` in `unit-test/wallet/admin/`. -
-		$ find (fabric unit-test path)/wallet/admin/ -type f -name '*-pub' | sed -e "s/-pub\$/-priv/"
-		6adbd1d5df2852efc1447f91effadbc2c8b5f1c6577c644441905f05e9551018-priv
- - -2) Specify the parameters in the target source - - Before -
-		const privateKeyPath = walletPath + '/admin/39dff34541b3ebc034474ed3b68cde6477f319bd67d01bb771e99b6f7595b4cf-priv';
- - - After -
-		const privateKeyPath = walletPath + '/admin/< xxx-priv checked by step1 >';
- - -3) Run -
-	node validatorDriver_sendSignedTransaction.js 
- - - Sample output -
-		keita@keita-VirtualBox:~/cactusProject/cactus/packages/ledger-plugin/fabric/validator/unit-test$ node validatorDriver_signTransactionOffline.js 
-		validatorUrl: https://localhost:5040
-		##exec requestStartMonitor()
-		exec sendRequest()
-		#[send]requestData: {"func":"changeCarOwner","args":{"carId":"CAR101","newOwner":"Charlie"}}
-		setupChannel start
-		tlssetup start
-		#[recv]eventReceived, res: {"status":200,"blockData":[]}
-		{
-		  fcn: 'changeCarOwner',
-		  args: [ 'CAR101', 'Charlie' ],
-		  chaincodeId: 'fabcar',
-		  channelId: 'mychannel'
-		}
-		proposal end
-		##txId: 2a143227120188314fe2255ac22192f85ddb6af80a715f2f64f5d02ad052d8aa
-		signProposal start
-		successfully send signedProposal
-		Successfully build commit transaction proposal
-		signProposal start
-		Successfully build endorse transaction proposal
-		emit request
-		#[recv]eventReceived, res: {"status":200,"blockData":[]}
-		##exec requestStopMonitor()
\ No newline at end of file diff --git a/packages/ledger-plugin/fabric/validator/unit-test/copyStaticAssets.ts b/packages/ledger-plugin/fabric/validator/unit-test/copyStaticAssets.ts new file mode 100644 index 0000000000..7d1000099a --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/copyStaticAssets.ts @@ -0,0 +1,3 @@ +import * as shell from 'shelljs'; +shell.cp('config/connection.json', './dist/config'); +shell.cp('config/default.js', './dist/config'); diff --git a/packages/ledger-plugin/fabric/validator/unit-test/createCar.js b/packages/ledger-plugin/fabric/validator/unit-test/createCar.ts similarity index 94% rename from packages/ledger-plugin/fabric/validator/unit-test/createCar.js rename to packages/ledger-plugin/fabric/validator/unit-test/createCar.ts index bd64fd5faa..d1d144b951 100644 --- a/packages/ledger-plugin/fabric/validator/unit-test/createCar.js +++ b/packages/ledger-plugin/fabric/validator/unit-test/createCar.ts @@ -11,9 +11,11 @@ // //////// +{ 'use strict'; const { FileSystemWallet, Gateway } = require('fabric-network'); +//import { FileSystemWallet, Gateway } from 'fabric-network'; const fs = require('fs'); const path = require('path'); @@ -26,7 +28,7 @@ const walletPath = path.resolve(__dirname, 'wallet'); // ## Request for "createCar" -const key = 'CAR101'; +const key = 'CAR102'; const make = 'Toyota'; const model = 'Harrier'; const colour = 'Black'; @@ -35,7 +37,7 @@ const owner = 'Dave'; const userName = 'user1'; const channelName = 'mychannel'; -async function main() { +async function createCars() { try { // Create a new file system based wallet for managing identities. @@ -74,4 +76,5 @@ async function main() { } } -main(); +createCars(); +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/fabric-docker/README.md b/packages/ledger-plugin/fabric/validator/unit-test/fabric-docker/README.md index 6da60c9e0d..fa663345ae 100644 --- a/packages/ledger-plugin/fabric/validator/unit-test/fabric-docker/README.md +++ b/packages/ledger-plugin/fabric/validator/unit-test/fabric-docker/README.md @@ -26,22 +26,12 @@ Ensure that the next containers are started. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES - ec8289e32f06 dev-peer0.org1.example.com-fabcar-1.0-5c906e402ed29f20260ae42283216aa75549c571e2e380f3615826365d8269ba "chaincode -peer.add…" 2 hours ago Up 2 hours dev-peer0.org1.example.com-fabcar-1.0 + ec8289e32f06 dev-peer0.org1.example.com-fabcar-1.0-5c906e402ed29f20260ae42283216aa75549c571e2e380f3615826365d8269ba "chaincode -peer.add..." 2 hours ago Up 2 hours dev-peer0.org1.example.com-fabcar-1.0 a468d622234a hyperledger/fabric-tools "/bin/bash" 2 hours ago Up 2 hours cli 80e28ca9fbcf hyperledger/fabric-peer "peer node start" 2 hours ago Up 2 hours 0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp peer0.org1.example.com - 8391db445423 hyperledger/fabric-ca "sh -c 'fabric-ca-se…" 2 hours ago Up 2 hours 0.0.0.0:7054->7054/tcp ca.example.com + 8391db445423 hyperledger/fabric-ca "sh -c 'fabric-ca-se..." 2 hours ago Up 2 hours 0.0.0.0:7054->7054/tcp ca.example.com 3a06daddc298 hyperledger/fabric-orderer "orderer" 2 hours ago Up 2 hours 0.0.0.0:7050->7050/tcp orderer.example.com - b722f3d14f6e hyperledger/fabric-couchdb "tini -- /docker-ent…" 2 hours ago Up 2 hours 4369/tcp, 9100/tcp, 0.0.0.0:5984->5984/tcp couchdb - -#### Remarks - -According to the report from some contributor, in some environment the command `./startFabric.sh` fails, due to version incompatibility between fabric and couchdb. If you encounter the same situation, execute the following commands and re-execute this step: - - curl -sSL https://bit.ly/2ysbOFE | bash -s -- 1.4.0 1.4.0 - docker pull hyperledger/fabric-couchdb:0.4.14 - docker tag hyperledger/fabric-couchdb:0.4.14 hyperledger/fabric-couchdb:latest - - + b722f3d14f6e hyperledger/fabric-couchdb "tini -- /docker-ent..." 2 hours ago Up 2 hours 4369/tcp, 9100/tcp, 0.0.0.0:5984->5984/tcp couchdb ### 2) Registering an administrator user and general users @@ -86,3 +76,4 @@ Copy and extract wallet.tar to the following target directory: [Deployment Method] $ tar xvf wallet.tar + diff --git a/packages/ledger-plugin/fabric/validator/unit-test/package.json b/packages/ledger-plugin/fabric/validator/unit-test/package.json index fa65344211..df580dc962 100644 --- a/packages/ledger-plugin/fabric/validator/unit-test/package.json +++ b/packages/ledger-plugin/fabric/validator/unit-test/package.json @@ -2,10 +2,21 @@ "name": "validatorDriver", "version": "0.0.0", "private": true, + "scripts": { + "build": "npm run build-ts && npm run copy-static-assets", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json", + "copy-static-assets": "ts-node copyStaticAssets.ts" + }, "dependencies": { + "@types/node": "^14.14.5", "config": "^1.26.1", "socket.io": "^2.0.4", + "ts-node": "^9.0.0", "fabric-ca-client": "~1.4.0", "fabric-network": "~1.4.0" + }, + "devDependencies": { + "typescript": "^3.9.3" } } diff --git a/packages/ledger-plugin/fabric/validator/unit-test/queryCar.ts b/packages/ledger-plugin/fabric/validator/unit-test/queryCar.ts new file mode 100644 index 0000000000..ab25ab83b5 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/queryCar.ts @@ -0,0 +1,78 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * queryCar.js + */ + +//////// +// Usage +// TODO: +// +//////// + +{ +'use strict'; + +const { FileSystemWallet, Gateway } = require('fabric-network'); +const fs = require('fs'); +const path = require('path'); + +const ccpPath = path.resolve(__dirname, 'config', 'connection.json'); +const ccpJSON = fs.readFileSync(ccpPath, 'utf8'); +const ccp = JSON.parse(ccpJSON); + +// TODO: +const walletPath = path.resolve(__dirname, 'wallet'); + + +const userName = 'user1'; +const channelName = 'mychannel'; + +async function queryCars() { + try { + + // Create a new file system based wallet for managing identities. + const wallet = new FileSystemWallet(walletPath); + console.log(`Wallet path: ${walletPath}`); + + // Check to see if we've already enrolled the user. + const userExists = await wallet.exists(userName); + if (!userExists) { + console.log('An identity for the user "' + userName + '" does not exist in the wallet'); + console.log('Run the registerUser.js application before retrying'); + return; + } + + // Create a new gateway for connecting to our peer node. + const gateway = new Gateway(); + await gateway.connect(ccp, { wallet, identity: userName, discovery: { enabled: false } }); + + // Get the network (channel) our contract is deployed to. + const network = await gateway.getNetwork('mychannel'); + + // Get the contract from the network. + const contract = network.getContract('fabcar'); + + // Evaluate the specified transaction. + if (process.argv.length > 2) { + const key = process.argv[2]; + //console.log('##queryCar Params: ' + key); + console.log(`##queryCar Params: ${key}`); + const result = await contract.evaluateTransaction('queryCar', key); + console.log(`Transaction has been evaluated, result is: ${result.toString()}`); + } + else { + console.log('##queryAllCars: '); + const result = await contract.evaluateTransaction('queryAllCars'); + console.log(`Transaction has been evaluated, result is: ${result.toString()}`); + } + + } catch (error) { + console.error(`Failed to evaluate transaction: ${error}`); + process.exit(1); + } +} + +queryCars(); +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/signTransactionOffline.js b/packages/ledger-plugin/fabric/validator/unit-test/signTransactionOffline.js deleted file mode 100644 index 50cb18ea6a..0000000000 --- a/packages/ledger-plugin/fabric/validator/unit-test/signTransactionOffline.js +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * signTransactionOffline.js - */ - -//////// -// Usage -// TODO: -// -//////// - -/* Summary: - * Request library for fabric v1.4.0 (for offline signature) Processing library Testing library - * In this case, it is used only when transferring assets. -*/ - -// For reading keys and certificates -const fs = require('fs'); -const path = require('path'); - -//Constant definition -const config = require('./PluginConfig.js'); - -//Fabric node-sdk -const FabricCAService = require('fabric-ca-client'); -const Client = require('fabric-client'); - -//Cryptographic -const hash = require('fabric-client/lib/hash'); -const jsrsa = require('jsrsasign'); -const { KEYUTIL } = jsrsa; -const elliptic = require('elliptic'); -const EC = elliptic.ec; - -// TODO: -const walletPath = path.resolve(__dirname, 'wallet'); - -//Key and certificate issued by msp (User1@example.com) -const basic_network_path = "/home/kanazashi/workspace/fabric-samples/basic-network"; -const privateKeyPath0 = basic_network_path + '/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/keystore/c75bd6911aca808941c3557ee7c97e90f3952e379497dc55eb903f31b50abc83_sk'; -const privateKeyPem0 = fs.readFileSync(privateKeyPath0, 'utf8'); -const certPath0 = basic_network_path + '/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/signcerts/User1@org1.example.com-cert.pem'; -const certPem0 = fs.readFileSync(certPath0, 'utf8'); - -// Keys and certificates issued by Fabric-CA (STM administrator, general user) -const privateKeyPath = walletPath + '/admin/b4acea028a4641fc938b7eb9ed00fa21496ed5471656c3d80d9bb637bdc6ea3f-priv'; -const privateKeyPem = fs.readFileSync(privateKeyPath, 'utf8'); -const certPath = walletPath + '/admin/admin'; -const work = fs.readFileSync(certPath, 'utf8'); //For E-cert issued by Fabric-CA, parsing is required once -const certPem = JSON.parse(work).enrollment.identity.certificate; - -const mspId = config.fabric.mspid; - - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - - -// BEGIN Signature process===================================================================================== - -// this ordersForCurve comes from CryptoSuite_ECDSA_AES.js and will be part of the -// stand alone fabric-sig package in future. -const ordersForCurve = { - 'secp256r1': { - 'halfOrder': elliptic.curves.p256.n.shrn(1), - 'order': elliptic.curves.p256.n - }, - 'secp384r1': { - 'halfOrder': elliptic.curves.p384.n.shrn(1), - 'order': elliptic.curves.p384.n - } -}; - -// this function comes from CryptoSuite_ECDSA_AES.js and will be part of the -// stand alone fabric-sig package in future. -function _preventMalleability(sig, curveParams) { - const halfOrder = ordersForCurve[curveParams.name].halfOrder; - if (!halfOrder) { - throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name); - } - - // in order to guarantee 's' falls in the lower range of the order, as explained in the above link, - // first see if 's' is larger than half of the order, if so, it needs to be specially treated - if (sig.s.cmp(halfOrder) === 1) { // module 'bn.js', file lib/bn.js, method cmp() - // convert from BigInteger used by jsrsasign Key objects and bn.js used by elliptic Signature objects - const bigNum = ordersForCurve[curveParams.name].order; - sig.s = bigNum.sub(sig.s); - } - - return sig; -} - -/** - * this method is used for test at this moment. In future this - * would be a stand alone package that running at the browser/cellphone/PAD - * - * @param {string} privateKey PEM encoded private key - * @param {Buffer} proposalBytes proposal bytes - */ -function sign(privateKey, proposalBytes, algorithm, keySize) { - const hashAlgorithm = algorithm.toUpperCase(); - const hashFunction = hash[`${hashAlgorithm}_${keySize}`]; - const ecdsaCurve = elliptic.curves[`p${keySize}`]; - const ecdsa = new EC(ecdsaCurve); - const key = KEYUTIL.getKey(privateKey); - - const signKey = ecdsa.keyFromPrivate(key.prvKeyHex, 'hex'); - const digest = hashFunction(proposalBytes); - - let sig = ecdsa.sign(Buffer.from(digest, 'hex'), signKey); - sig = _preventMalleability(sig, key.ecparams); - - return Buffer.from(sig.toDER()); -} - -function signProposal(proposalBytes, privateKeyPem) { - console.log("signProposal start"); - - const signature = sign(privateKeyPem, proposalBytes, 'sha2', 256); - const signedProposal = { signature, proposal_bytes: proposalBytes }; - return signedProposal; -} - -// END Signature process========================================================================================= - - -// setup TLS for this client -async function TLSSetup(client, enrollmentID, secret) { - const tlsOptions = { - trustedRoots: [], - verify: false - }; - console.log("tlssetup start"); - const caService = new FabricCAService(config.fabric.ca.url, tlsOptions, config.fabric.ca.name); - const req = { - enrollmentID: enrollmentID, - enrollmentSecret: secret, - profile: 'tls' - }; - const enrollment = await caService.enroll(req); - client.setTlsClientCertAndKey(enrollment.certificate, enrollment.key.toBytes()); -} - - -//Creating a channel object -async function setupChannel(channelName) { - console.log("setupChannel start"); - const client = new Client(); - await TLSSetup(client, config.fabric.submitter.name, config.fabric.submitter.secret); - const channel = client.newChannel(channelName); - - //add peer to channel - //const peerTLSCertPath = path.resolve(__dirname, './crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tlscacerts/org1.example.com-cert.pem'); - //const peerPEMCert = fs.readFileSync(peerTLSCertPath, 'utf8'); - for (var i = 0; i < config.fabric.peers.length; i++) { - var peer = client.newPeer( - config.fabric.peers[i].requests - /*{ - pem: peerPEMCert, - 'ssl-target-name-override': 'peer0.org1.example.com', - } - */ - ); - channel.addPeer(peer); - } - - //add orderer to channel - /* - const ordererTLSCertPath = path.resolve(__dirname, './crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tlscacerts/example.com-cert.pem'); - const ordererPEMCert = fs.readFileSync(ordererTLSCertPath, 'utf8'); - */ - const orderer = client.newOrderer( - config.fabric.orderer.url - /*{ - pem: ordererPEMCert, - 'ssl-target-name-override': 'orderer.example.com', - } - */ - ); - channel.addOrderer(orderer); - // TODO: channel.initialize() should not require an signning identity - // await channel.initialize(); - return channel; -} - - -//Monitor for block commit monitoring -async function transactionMonitor(txId, eh, invokeResponse) { - return new Promise((resolve, reject) => { - const handle = setTimeout(() => { - console.log('Timeout - Failed to receive event for txId ' + txId); - eh.disconnect(); // shutdown - throw new Error('TIMEOUT - no event received'); - }, 60000); - - eh.registerTxEvent(txId, (txnid, code, block_num) => { - clearTimeout(handle); - console.log('Event has been seen with transaction code:' + code + ' for transaction id:' + txnid + ' for block_num:' + block_num); - resolve(invokeResponse); - }, (error) => { - clearTimeout(handle); - console.log('Failed to receive event replay for Event for transaction id ::' + txId); - reject(error); - }, { disconnect: true } - // Setting the disconnect to true as we do not want to use this - // ChannelEventHub after the event we are looking for comes in - ); - console.log('Successfully registered event for ' + txId); - - //Signature processing is also required when monitoring Event - // However, the key used for the signature here is that of the user (User1@example.com) issued by msp. - const unsignedEvent = eh.generateUnsignedRegistration({ - certificate: certPem0, - mspId, - }); - const signedProposal = signProposal(unsignedEvent, privateKeyPem0); - const signedEvent = { - signature: signedProposal.signature, - payload: signedProposal.proposal_bytes, - }; - eh.connect({ signedEvent }); - - console.log('Successfully called connect on ' + eh.getPeerAddr()); - }); -} - - -// The following three signatures are required when sending transactions and monitoring block commits. -// Endorsement, Commit -> Signed by STM user. Request a signature from the authorization/signature server. -// RegisterChannelEventHub -> Signed by msp user (User1@example.com) -async function Invoke(reqBody, isWait) { - // exports.Invoke = async function(reqBody, isWait){ - //var eventhubs = []; //For the time being, give up the eventhub connection of multiple peers. - var invokeResponse; //Return value from chain code - var channel; - var eh; //EventHub - - return new Promise(async function (resolve, reject) { - try { - //channel object generation - if (channel == undefined) { - channel = await setupChannel(config.fabric.channelName); - } - - /* - * Endorse step - */ - const transactionProposalReq = { - fcn: reqBody.fcn, //Chain code function name - args: reqBody.args, //Chaincode argument - chaincodeId: 'fabcar', - channelId: config.fabric.channelName, - }; - console.log(transactionProposalReq); - const { proposal, txId } = channel.generateUnsignedProposal(transactionProposalReq, config.fabric.mspid, certPem); - console.log("proposal end"); - console.log(`##txId=${txId.getTransactionID()}`); - const signedProposal = signProposal(proposal.toBuffer(), privateKeyPem); - console.log('Successfully build endorse transaction proposal'); - - var targets = []; - for (var i = 0; i < config.fabric.peers.length; i++) { - var peer = channel.getPeer(config.fabric.peers[i].requests.split("//")[1]); - targets.push(peer); - } - const sendSignedProposalReq = { signedProposal, targets }; - const proposalResponses = await channel.sendSignedProposal(sendSignedProposalReq); - console.log("successfully send signedProposal") - var all_good = true; - for (var i in proposalResponses) { - let one_good = false; - if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) { - if (proposalResponses[i].response.payload) { - invokeResponse = new String(proposalResponses[i].response.payload); - } - one_good = true; - } else { - console.log('transaction proposal was bad'); - var resStr = proposalResponses[0].toString(); - var errMsg = resStr.replace("Error: ", ""); - return reject(errMsg); - } - all_good = all_good & one_good; - } - //If the return value of invoke is an empty string, store txID - if (invokeResponse == "") { - invokeResponse = txId.getTransactionID(); - } - //Error if all peers do not return status 200 - if (!all_good) { - throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); - } - - /** - * End the endorse step. - * Start to commit the tx. - */ - const commitReq = { - proposalResponses, - proposal, - }; - const commitProposal = channel.generateUnsignedTransaction(commitReq); - console.log('Successfully build commit transaction proposal'); - - // sign this commit proposal at local - const signedCommitProposal = signProposal(commitProposal.toBuffer(), privateKeyPem); - - const response = await channel.sendSignedTransaction({ - signedProposal: signedCommitProposal, - request: commitReq, - }); - console.log("successfully send signedCommitProposal"); - console.log(response); - if (response.status === 'SUCCESS') { - if (!isWait) { - // If you do not want to wait for block generation, resolve here - return resolve(invokeResponse); - } - } else { - throw new Error('Failed to order the transaction. Error code: ' + response.status); - } - - /* - * Monitor block commit (EventHub generated. Currently one peer) - */ - //TODO: push to eventhubs - eh = channel.newChannelEventHub(peer); - const res = await transactionMonitor(txId.getTransactionID(), eh, invokeResponse); - console.log("block created"); - console.log(res); - //When waiting for block generation, resolve here - return resolve(res); - - } catch (e) { - // Disconnect from EventHub server - if (eh != undefined) { - if (eh.isconnected()) { - console.log('Disconnecting the event hub'); - eh.disconnect(); - } - console.error(e); - } else { - console.error(e); - } - return reject(e); - } - }); -} - -var ret_obj = {}; -var carId = "CAR12"; -var newOwner = 'Dave#_A'; -if (carId == undefined || newOwner == undefined) { - var emsg = "Insufficient parameters."; - logger.info(emsg); - return; -} -var reqparam = { fcn: "changeCarOwner", args: [carId, newOwner] }; - -Invoke(reqparam, true) - .then((returnvalue) => { - console.log('success : ' + returnvalue); - }).catch(err => { - console.log('failed : ' + err); - }); diff --git a/packages/ledger-plugin/fabric/validator/unit-test/tsconfig.json b/packages/ledger-plugin/fabric/validator/unit-test/tsconfig.json new file mode 100644 index 0000000000..928b357062 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist", + "sourceMap": false, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "ES2017", + "module": "CommonJS", + "typeRoots": [ + "node_modules/@types", + "./typings" + ], + "lib": [ + "es2017", + "dom" + ] + }, +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.js b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.js deleted file mode 100644 index 5642507d49..0000000000 --- a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.js +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * validatorDriver_changeCarOwner.js - */ - -//////// -// Usage -// TODO: -// -//////// - -// Validator test program.(socket.io client) -var io = require('socket.io-client'); -var config = require('config'); - -// Specify the server (Validator) of the communication destination -var validatorUrl = config.validatorUrl; -console.log('validatorUrl: ' + validatorUrl); -var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 -}; -var socket = io(validatorUrl, options); - -// ## Request for "changeCarOwner" -var carId = "CAR101"; -var newOwner = "Robert"; - -var func = "changeCarOwner"; -var args = { - carId : carId, - newOwner : newOwner -}; - -// function param -var requestData = { - func : func, - args : args -}; - - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - - -socket.on('connect_error', (err) => { - console.log('####connect_error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('connect_timeout', (err) => { - console.log('####Error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('error', (err) => { - console.log('####Error:', err); -}); - -socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); -}); - - -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); -} - -// request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); -} - - -function sendRequest() { - // - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); -} - -setTimeout(requestStartMonitor, 2000); // TODO: -setTimeout(sendRequest, 4000); diff --git a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.ts b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.ts new file mode 100644 index 0000000000..cc685c3d9b --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_changeCarOwner.ts @@ -0,0 +1,120 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * validatorDriver_changeCarOwner.js + */ + +//////// +// Usage +// TODO: +// +//////// + +{ + +// Validator test program.(socket.io client) +var io = require('socket.io-client'); +var config = require('config'); + +// Specify the server (Validator) of the communication destination +var validatorUrl = config.validatorUrl; +console.log('validatorUrl: ' + validatorUrl); +var options = { + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 +}; +var socket = io(validatorUrl, options); + +// ## Request for "changeCarOwner" +var carID = "CAR11"; +var newOwner = "Robert"; +var reqID = "req12345"; + +//var func = "changeCarOwner"; +//var args = { +// carId : carId, +// newOwner : newOwner +//}; + +const contract = {"channelName": "mychannel", "contractName": "fabcar"}; +const method = {type: "submitTransaction", command: "changeCarOwner"}; +const args = {"args": [carID, newOwner]}; + + +// function param +const requestData = { + contract: contract, + method: method, + args: args, + reqID: reqID +}; + + + +const json2str = (jsonObj) => { + try { + return JSON.stringify(jsonObj); + } + catch (error) { + return null; + } +} + + +socket.on('connect_error', (err) => { + console.log('####connect_error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('connect_timeout', (err) => { + console.log('####Error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('error', (err) => { + console.log('####Error:', err); +}); + +socket.on('eventReceived', function (res) { + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); +}); + + +const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); +} + +// request StartMonitor +const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); +} + + +const sendRequest = () => { + // + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + socket.emit('request2', requestData); +} + +setTimeout(requestStartMonitor, 2000); // TODO: +setTimeout(sendRequest, 4000); + +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryAllCars.ts b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryAllCars.ts new file mode 100644 index 0000000000..8842c556fb --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryAllCars.ts @@ -0,0 +1,111 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * validatorDriver_queryCar.js + */ + +//////// +// Usage +// TODO: +// +//////// + +{ + +// Validator test program.(socket.io client) +var io = require('socket.io-client'); +var config = require('config'); + +// Specify the server (Validator) of the communication destination +var validatorUrl = config.validatorUrl; +console.log('validatorUrl: ' + validatorUrl); +var options = { + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 +}; +var socket = io(validatorUrl, options); + +// ## Request for "changeCarOwner" +var reqID = "req12345"; + + +const contract = {"channelName": "mychannel", "contractName": "fabcar"}; +const method = {type: "evaluateTransaction", command: "queryAllCars"}; +const args = {"args": []}; + +// function param +const requestData = { + contract: contract, + method: method, + args: args, + reqID: reqID +}; + + +const json2str = (jsonObj) => { + try { + return JSON.stringify(jsonObj); + } + catch (error) { + return null; + } +} + + +socket.on('connect_error', (err) => { + console.log('####connect_error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('connect_timeout', (err) => { + console.log('####Error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('error', (err) => { + console.log('####Error:', err); +}); + +socket.on('eventReceived', function (res) { + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); +}); + + +const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); +} + +// request StartMonitor +const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); +} + + +const sendRequest = () => { + // + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + socket.emit('request2', requestData); +} + +setTimeout(requestStartMonitor, 2000); // TODO: +setTimeout(sendRequest, 4000); + +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryCar.ts b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryCar.ts new file mode 100644 index 0000000000..ec198631c3 --- /dev/null +++ b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_queryCar.ts @@ -0,0 +1,111 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * validatorDriver_queryCar.js + */ + +//////// +// Usage +// TODO: +// +//////// + +{ + +// Validator test program.(socket.io client) +var io = require('socket.io-client'); +var config = require('config'); + +// Specify the server (Validator) of the communication destination +var validatorUrl = config.validatorUrl; +console.log('validatorUrl: ' + validatorUrl); +var options = { + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 +}; +var socket = io(validatorUrl, options); + +// ## Request for "changeCarOwner" +var carID = "CAR11"; +var reqID = "req12345"; + +const contract = {"channelName": "mychannel", "contractName": "fabcar"}; +const method = {type: "evaluateTransaction", command: "queryCar"}; +const args = {"args": [carID]}; + +// function param +const requestData = { + contract: contract, + method: method, + args: args, + reqID: reqID +}; + + +const json2str = (jsonObj) => { + try { + return JSON.stringify(jsonObj); + } + catch (error) { + return null; + } +} + + +socket.on('connect_error', (err) => { + console.log('####connect_error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('connect_timeout', (err) => { + console.log('####Error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('error', (err) => { + console.log('####Error:', err); +}); + +socket.on('eventReceived', function (res) { + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); +}); + + +const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); +} + +// request StartMonitor +const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); +} + + +const sendRequest = () => { + // + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + socket.emit('request2', requestData); +} + +setTimeout(requestStartMonitor, 2000); // TODO: +setTimeout(sendRequest, 4000); + +} diff --git a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.ts similarity index 63% rename from packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js rename to packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.ts index 6fc6e858ec..d30b0fa5da 100644 --- a/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.js +++ b/packages/ledger-plugin/fabric/validator/unit-test/validatorDriver_signTransactionOffline.ts @@ -7,7 +7,7 @@ //////// // Usage -// TODO: +// TODO:XX // //////// @@ -16,6 +16,8 @@ * In this case, it is used only when transferring assets. */ +{ + // Validator test program.(socket.io client) var io = require('socket.io-client'); var config = require('config'); @@ -24,9 +26,9 @@ var config = require('config'); var validatorUrl = config.validatorUrl; console.log('validatorUrl: ' + validatorUrl); var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 }; var socket = io(validatorUrl, options); @@ -47,45 +49,36 @@ const { KEYUTIL } = jsrsa; const elliptic = require('elliptic'); const EC = elliptic.ec; -// TODO: -const walletPath = path.resolve(__dirname, 'wallet'); - -//Key and certificate issued by msp (User1@example.com) -//const basic_network_path = "./fabric-docker/basic-network"; -const basic_network_path = path.resolve(__dirname, 'fabric-docker/fabric-samples/basic-network'); -const privateKeyPath0 = basic_network_path + '/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/keystore/c75bd6911aca808941c3557ee7c97e90f3952e379497dc55eb903f31b50abc83_sk'; -const privateKeyPem0 = fs.readFileSync(privateKeyPath0, 'utf8'); -const certPath0 = basic_network_path + '/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/signcerts/User1@org1.example.com-cert.pem'; -const certPem0 = fs.readFileSync(certPath0, 'utf8'); - // Keys and certificates issued by Fabric-CA (STM administrator, general user) -const privateKeyPath = walletPath + '/admin/39dff34541b3ebc034474ed3b68cde6477f319bd67d01bb771e99b6f7595b4cf-priv'; -const privateKeyPem = fs.readFileSync(privateKeyPath, 'utf8'); -const certPath = walletPath + '/admin/admin'; -const work = fs.readFileSync(certPath, 'utf8'); //For E-cert issued by Fabric-CA, parsing is required once -const certPem = JSON.parse(work).enrollment.identity.certificate; +const privateKeyPem = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgQ3pbxM94ZzHPEHW7\n5TQ1N/WfCLSgqY97dfyF34WiJz2hRANCAATROM5gNB8NsA5TfBg2/GB5pMT+vzwG\nJ47lXjK7/oQmTjIEexzJpEKestn16rIVrn7cblXSYDuFtPDjyZ14wCuw\n-----END PRIVATE KEY-----\n"; + +const certPem = "-----BEGIN CERTIFICATE-----\nMIICAjCCAaigAwIBAgIUYcAcX63XaN2Omym6hEXF+Kxzx2QwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwNzI3MTAzNDAwWhcNMjEwNzI3MTAz\nOTAwWjAhMQ8wDQYDVQQLEwZjbGllbnQxDjAMBgNVBAMTBWFkbWluMFkwEwYHKoZI\nzj0CAQYIKoZIzj0DAQcDQgAE0TjOYDQfDbAOU3wYNvxgeaTE/r88BieO5V4yu/6E\nJk4yBHscyaRCnrLZ9eqyFa5+3G5V0mA7hbTw48mdeMArsKNsMGowDgYDVR0PAQH/\nBAQDAgeAMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFBMOvw1wPpaBeZIpqc3AFbGs\nY0KMMCsGA1UdIwQkMCKAIEI5qg3NdtruuLoM2nAYUdFFBNMarRst3dusalc2Xkl8\nMAoGCCqGSM49BAMCA0gAMEUCIQDXvckX5bZ5mGPHpQ49aKSFsGJkwrX1BnW7DwA+\n4suQPQIgVGKIiQBQDGlOQHkt9lqno/yFiFZSjzZSS24LFIJNKU4=\n-----END CERTIFICATE-----\n"; const mspId = config.fabric.mspid; // ## Request for "changeCarOwner" -var carId = "CAR101"; +var carId = "CAR11"; var newOwner = "Charlie"; +const contract = {"channelName": "mychannel"}; +const method = {"type": "sendSignedTransaction"}; +//const args = {"args": [carID]}; + var func = "changeCarOwner"; var args = { - carId : carId, - newOwner : newOwner + carId : carId, + newOwner : newOwner }; // function param var requestData = { - func : func, - args : args + func : func, + args : args }; -function json2str(jsonObj) { +const json2str = (jsonObj) => { try { return JSON.stringify(jsonObj); } @@ -95,7 +88,6 @@ function json2str(jsonObj) { } - // BEGIN Signature process===================================================================================== // this ordersForCurve comes from CryptoSuite_ECDSA_AES.js and will be part of the @@ -113,7 +105,7 @@ const ordersForCurve = { // this function comes from CryptoSuite_ECDSA_AES.js and will be part of the // stand alone fabric-sig package in future. -function _preventMalleability(sig, curveParams) { +const _preventMalleability = (sig, curveParams) => { const halfOrder = ordersForCurve[curveParams.name].halfOrder; if (!halfOrder) { throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name); @@ -137,7 +129,7 @@ function _preventMalleability(sig, curveParams) { * @param {string} privateKey PEM encoded private key * @param {Buffer} proposalBytes proposal bytes */ -function sign(privateKey, proposalBytes, algorithm, keySize) { +const sign = (privateKey, proposalBytes, algorithm, keySize) => { const hashAlgorithm = algorithm.toUpperCase(); const hashFunction = hash[`${hashAlgorithm}_${keySize}`]; const ecdsaCurve = elliptic.curves[`p${keySize}`]; @@ -153,10 +145,10 @@ function sign(privateKey, proposalBytes, algorithm, keySize) { return Buffer.from(sig.toDER()); } -function signProposal(proposalBytes, privateKeyPem) { +const signProposal = (proposalBytes, paramPrivateKeyPem) => { console.log("signProposal start"); - const signature = sign(privateKeyPem, proposalBytes, 'sha2', 256); + const signature = sign(paramPrivateKeyPem, proposalBytes, 'sha2', 256); const signedProposal = { signature, proposal_bytes: proposalBytes }; return signedProposal; } @@ -165,7 +157,7 @@ function signProposal(proposalBytes, privateKeyPem) { // setup TLS for this client -async function TLSSetup(client, enrollmentID, secret) { +const TLSSetup = async (client, enrollmentID, secret) => { const tlsOptions = { trustedRoots: [], verify: false @@ -183,7 +175,7 @@ async function TLSSetup(client, enrollmentID, secret) { //Creating a channel object -async function setupChannel(channelName) { +const setupChannel = async (channelName) => { console.log("setupChannel start"); const client = new Client(); await TLSSetup(client, config.fabric.submitter.name, config.fabric.submitter.secret); @@ -195,27 +187,27 @@ async function setupChannel(channelName) { for (var i = 0; i < config.fabric.peers.length; i++) { var peer = client.newPeer( config.fabric.peers[i].requests - /*{ - pem: peerPEMCert, - 'ssl-target-name-override': 'peer0.org1.example.com', - } - */ + /*{ + pem: peerPEMCert, + 'ssl-target-name-override': 'peer0.org1.example.com', + } + */ ); channel.addPeer(peer); } //add orderer to channel - /* - const ordererTLSCertPath = path.resolve(__dirname, './crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tlscacerts/example.com-cert.pem'); - const ordererPEMCert = fs.readFileSync(ordererTLSCertPath, 'utf8'); - */ + /* + const ordererTLSCertPath = path.resolve(__dirname, './crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tlscacerts/example.com-cert.pem'); + const ordererPEMCert = fs.readFileSync(ordererTLSCertPath, 'utf8'); + */ const orderer = client.newOrderer( config.fabric.orderer.url - /*{ - pem: ordererPEMCert, - 'ssl-target-name-override': 'orderer.example.com', - } - */ + /*{ + pem: ordererPEMCert, + 'ssl-target-name-override': 'orderer.example.com', + } + */ ); channel.addOrderer(orderer); // TODO: channel.initialize() should not require an signning identity @@ -224,51 +216,10 @@ async function setupChannel(channelName) { } -//Monitor for block commit monitoring -async function transactionMonitor(txId, eh, invokeResponse) { - return new Promise((resolve, reject) => { - const handle = setTimeout(() => { - console.log('Timeout - Failed to receive event for txId ' + txId); - eh.disconnect(); // shutdown - throw new Error('TIMEOUT - no event received'); - }, 60000); - - eh.registerTxEvent(txId, (txnid, code, block_num) => { - clearTimeout(handle); - console.log('Event has been seen with transaction code:' + code + ' for transaction id:' + txnid + ' for block_num:' + block_num); - resolve(invokeResponse); - }, (error) => { - clearTimeout(handle); - console.log('Failed to receive event replay for Event for transaction id ::' + txId); - reject(error); - }, { disconnect: true } - // Setting the disconnect to true as we do not want to use this - // ChannelEventHub after the event we are looking for comes in - ); - console.log('Successfully registered event for ' + txId); - - //Signature processing is also required when monitoring Event - // However, the key used for the signature here is that of the user (User1@example.com) issued by msp. - const unsignedEvent = eh.generateUnsignedRegistration({ - certificate: certPem0, - mspId, - }); - const signedProposal = signProposal(unsignedEvent, privateKeyPem0); - const signedEvent = { - signature: signedProposal.signature, - payload: signedProposal.proposal_bytes, - }; - eh.connect({ signedEvent }); - - console.log('Successfully called connect on ' + eh.getPeerAddr()); - }); -} - - // The following three signatures are required when sending transactions and monitoring block commits. // Endorsement, Commit -> Signed by STM user. Request a signature from the authorization/signature server. // RegisterChannelEventHub -> Signed by msp user (User1@example.com) -async function Invoke(reqBody, isWait) { +const Invoke = async (reqBody, isWait) => { // exports.Invoke = async function(reqBody, isWait){ //var eventhubs = []; //For the time being, give up the eventhub connection of multiple peers. var invokeResponse; //Return value from chain code @@ -282,12 +233,12 @@ async function Invoke(reqBody, isWait) { channel = await setupChannel(config.fabric.channelName); } - /* - * Endorse step - */ + /* + * Endorse step + */ const transactionProposalReq = { - fcn: reqBody.func, //Chain code function name - args: [reqBody.args.carId, reqBody.args.newOwner], //Chaincode argument + fcn: reqBody.func, //Chain code function name + args: [reqBody.args.carId, reqBody.args.newOwner], //Chaincode argument chaincodeId: 'fabcar', channelId: config.fabric.channelName, }; @@ -298,42 +249,42 @@ async function Invoke(reqBody, isWait) { const signedProposal = signProposal(proposal.toBuffer(), privateKeyPem); var targets = []; - for (var i = 0; i < config.fabric.peers.length; i++) { + for (let i = 0; i < config.fabric.peers.length; i++) { var peer = channel.getPeer(config.fabric.peers[i].requests.split("//")[1]); targets.push(peer); } const sendSignedProposalReq = { signedProposal, targets }; const proposalResponses = await channel.sendSignedProposal(sendSignedProposalReq); console.log("successfully send signedProposal") - var all_good = true; - for (var i in proposalResponses) { - let one_good = false; + var allGood = true; + for (let i in proposalResponses) { + let oneGood = false; if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) { if (proposalResponses[i].response.payload) { invokeResponse = new String(proposalResponses[i].response.payload); } - one_good = true; + oneGood = true; } else { console.log('transaction proposal was bad'); var resStr = proposalResponses[0].toString(); var errMsg = resStr.replace("Error: ", ""); return reject(errMsg); } - all_good = all_good & one_good; + allGood = (allGood && oneGood); } //If the return value of invoke is an empty string, store txID if (invokeResponse == "") { invokeResponse = txId.getTransactionID(); } //Error if all peers do not return status 200 - if (!all_good) { + if (!allGood) { throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); } - /** - * End the endorse step. - * Start to commit the tx. - */ + /** + * End the endorse step. + * Start to commit the tx. + */ const commitReq = { proposalResponses, proposal, @@ -345,11 +296,17 @@ async function Invoke(reqBody, isWait) { const signedCommitProposal = signProposal(commitProposal.toBuffer(), privateKeyPem); console.log('Successfully build endorse transaction proposal'); - var requestData = { - func : "sendSignedProposal", - args : [signedCommitProposal, commitReq] - }; - return resolve(requestData); + var retRequestData = { + contract: contract, + method: method, + args : { + args : [{ + signedCommitProposal: signedCommitProposal, + commitReq: commitReq + }] + } + }; + return resolve(retRequestData); } catch (e) { @@ -379,40 +336,40 @@ socket.on('error', (err) => { }); socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); }); -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); +const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); } // request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); +const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); } -function sendRequest() { - // - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - Invoke(requestData, true) +const sendRequest = () => { + // + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + Invoke(requestData, true) .then((returnvalue) => { //console.log('success : ' + json2str(returnvalue)); - console.log(`emit request`); - socket.emit('request', returnvalue); + console.log(`emit request2`); + socket.emit('request2', returnvalue); }).catch(err => { console.log('failed : ' + err); }); @@ -420,3 +377,5 @@ function sendRequest() { setTimeout(requestStartMonitor, 2000); // TODO: setTimeout(sendRequest, 4000); + +} diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/.gitignore b/packages/ledger-plugin/go-ethereum-ts/validator/src/.gitignore deleted file mode 100644 index fc89d99464..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -core/node_modules/ -core/package-lock.json -dependent/node_modules/ -dependent/package-lock.json -core/npm-debug.log - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/README.md b/packages/ledger-plugin/go-ethereum-ts/validator/src/README.md deleted file mode 100644 index 6dcd803567..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/README.md +++ /dev/null @@ -1,17 +0,0 @@ - -# BIF-trial(Validator) - -## Assumption -- geth1(geth-docker) is running -- Specify the geth1 URL to connect to with "validatorUrl" in "config/default.js" - -## Run -
-cd core
-node ./bin/www.js 
-
diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/build/Dockerfile b/packages/ledger-plugin/go-ethereum-ts/validator/src/build/Dockerfile deleted file mode 100644 index e5fb0f727a..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/build/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -# 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 diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.crt b/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.crt deleted file mode 100644 index 34773b65c3..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.crt +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBdTCCARoCCQC/F+Mh551QzDAKBggqhkjOPQQDAjBCMQswCQYDVQQGEwJKUDEQ -MA4GA1UECAwHZXNqbXMxMjEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkg -THRkMB4XDTE4MDYyNzA3MjIzNVoXDTI4MDYyNDA3MjIzNVowQjELMAkGA1UEBhMC -SlAxEDAOBgNVBAgMB2Vzam1zMTIxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMg -UHR5IEx0ZDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDPpSD2w0zrqJKraGD1b -5Jq2sDuacThSUqi7fvz8oyrWtuKDjZ15zIaSOtak6XRxFh9V9Gokdg5GNbW/pTZc -TuowCgYIKoZIzj0EAwIDSQAwRgIhAKH6ERsyd5bpEMIkY4clPqguwDWoTLk2VKq6 -ONEhUqotAiEA4yJxGmZpFdRScG2gDUIF2VDeX+XfHdJI2J41hyW9/zI= ------END CERTIFICATE----- diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.csr b/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.csr deleted file mode 100644 index e828a1414b..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.csr +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIH9MIGkAgEAMEIxCzAJBgNVBAYTAkpQMRAwDgYDVQQIDAdlc2ptczEyMSEwHwYD -VQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjO -PQMBBwNCAAQz6Ug9sNM66iSq2hg9W+SatrA7mnE4UlKou378/KMq1rbig42decyG -kjrWpOl0cRYfVfRqJHYORjW1v6U2XE7qoAAwCgYIKoZIzj0EAwIDSAAwRQIgCUA1 -B5mZK7Hx79J1xBb0MGwuoUkt4bGPXbHqWEMZXQMCIQCRgadPkrNw56+pT5MVxA5K -vV6xTgmxUYrYnpkR4tptqQ== ------END CERTIFICATE REQUEST----- diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.priv b/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.priv deleted file mode 100644 index 6faf76a31e..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/CA/connector.priv +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PARAMETERS----- -BggqhkjOPQMBBw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MHcCAQEEICIlCfK3zMTFzUgdaj01LAHjJmHlbg6Xql9+i70iPz5EoAoGCCqGSM49 -AwEHoUQDQgAEM+lIPbDTOuokqtoYPVvkmrawO5pxOFJSqLt+/PyjKta24oONnXnM -hpI61qTpdHEWH1X0aiR2DkY1tb+lNlxO6g== ------END EC PRIVATE KEY----- diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/bin/www.ts b/packages/ledger-plugin/go-ethereum-ts/validator/src/core/bin/www.ts deleted file mode 100644 index 844cd10039..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/bin/www.ts +++ /dev/null @@ -1,210 +0,0 @@ -#!/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); - } - }); - - /** - * startMonitor: starting block generation event monitoring - **/ - client.on('startMonitor', function() { - // 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, 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); - }); - -}); - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/config/default.ts b/packages/ledger-plugin/go-ethereum-ts/validator/src/core/config/default.ts deleted file mode 100644 index 6b3d314543..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/config/default.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * default.js - */ - -export const config = { -//module.exports = { - // Defined value for the destination independent part. I don't think I can use it only at www, so I think I can write directly there. - // Destination dependent definition values should be in lib/PluginConfig.js. - "sslParam" : { - "port" : 5050, - "key" : "./core/CA/connector.priv", - "cert" : "./core/CA/connector.crt" - }, - // Log level (trace/debug/info/warn/error/fatal) - "logLevel" : "debug" -} diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerMonitorPlugin.ts b/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerMonitorPlugin.ts deleted file mode 100644 index 75307e0661..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerMonitorPlugin.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerMonitorPlugin.js - */ - -/* - * Summary: - * Connector: monitoring class of a part dependent on end-chains - * Used in the case of monitoring continuously. - * Processing that ends with the acceptance of a single event is handled by a custom function implementation in server plugins. - * Unlike server plugins, it basically does not handle its own functions. - */ - -// configuration file -import { SplugConfig } from './PluginConfig'; -var config = require('config'); -// Log settings -import { getLogger } from "log4js"; -const logger = getLogger('ServerMonitorPlugin[' + process.pid + ']'); -//var log4js = require('log4js'); -//var logger = log4js.getLogger('ServerMonitorPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// Load libraries, SDKs, etc. according to specifications of endchains as needed -var Web3 = require('web3'); - -/* - * ServerMonitorPlugin - * Class definitions of server monitoring - */ -export class ServerMonitorPlugin { - - _filterTable: object; - - /* - * constructors - */ - constructor(){ - // Define dependent specific settings - // Initialize monitored filter - this._filterTable = {}; - } - - /* - * startMonitor - * Start Monitoring - * @param {string} clientId: Client ID from which monitoring start request was made - * @param {function} cb: A callback function that receives monitoring results at any time. - */ - startMonitor(clientId, cb) { - logger.info('*** START MONITOR ***'); - logger.info('Client ID :' + clientId); - // Implement handling to receive events from an end-chain and return them in a callback function - var filter = this._filterTable[clientId]; - if (!filter) { - logger.info('create new web3 filter and start watching.'); - try { - var web3 = new Web3(); - var provider = new web3.providers.HttpProvider(SplugConfig.provider); - web3.setProvider(provider); - filter = web3.eth.filter("latest"); - // filter should be managed by client ID - // (You should never watch multiple urls from the same client) - this._filterTable[clientId] = filter; - filter.watch(function (error, blockHash) { - if (!error) { - console.log('##[HL-BC] Notify new block data(D2)'); - var blockData = web3.eth.getBlock(blockHash, true); - var trLength = blockData.transactions.length; - logger.info(trLength + " transactions in block " + blockData.number); - console.log('##[HL-BC] Validate transactions(D3)'); - console.log('##[HL-BC] digital sign on valid transaction(D4)'); - if (trLength > 0) { - logger.info('*** SEND BLOCK DATA ***'); - // Notify only if transaction exists - var retObj = { - "status" : 200, - "blockData" : blockData - }; - cb(retObj); - } - } else { - let errObj = { - "status" : 504, - "errorDetail" : error - }; - cb(errObj); - } - }); - } catch (e) { - var emsg = e.toString().replace(/Error: /g , ""); - let errObj = { - "status" : 504, - "errorDetail" : emsg - }; - cb(errObj); - } - } else { - logger.info('target filter has already start watching.'); - } - } - - /* - * stopMonitor - * monitoring stop - * @param {string} clientId: Client ID from which monitoring stop request was made - */ - stopMonitor(clientId) { - // Implement a process to end EC monitoring - var filter = this._filterTable[clientId]; - if (filter) { - // Stop the filter & Remove it from table - logger.info('stop watching and remove filter.'); - filter.stopWatching(); - delete this._filterTable[clientId]; - } - } - -} /* class */ - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/package_template.json b/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/package_template.json deleted file mode 100644 index 289b20b1f1..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/package_template.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "dependent", - "version": "0.0.0", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - } -} diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/setup.sh b/packages/ledger-plugin/go-ethereum-ts/validator/src/setup.sh deleted file mode 100755 index 4a68744bbc..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/setup.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 - -cd ./core -npm install -cd ../dependent -npm install diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/.gitignore b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/.gitignore deleted file mode 100644 index b8ffe08f2c..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -package-lock.json - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/README.md b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/README.md deleted file mode 100644 index 001a24c2b7..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/README.md +++ /dev/null @@ -1,58 +0,0 @@ - -# BIF-trial(Validator Driver) - -## Assumption -- Validator1 (for Ethereum) is running -- geth1(geth-docker) is running -- Specify the validator URL to connect to with "validatorUrl" in "config/default.js" - -## a) Get balance -### Target source: validatorDriver_getNumericBalance.js - -1) Specify the parameters in the target source - - - referedAddress: Account ID to be displayed - -2) Run -
-node validatorDriver_getNumericBalance.js 
-
- -## b) Asset transfer -### Target source: validatorDriver_transferNumericAsset.js - -1) Specify the parameters in the target source - - - fromAddress: Transfer source account ID - - toAddress: Destination account ID - - amount: the value of the asset to be transferred - -2) Run -
-node validatorDriver_transferNumericAsset.js 
-
- -## c) Raw Transaction execution (Asset transfer) -### Target source: validatorDriver_sendRawTransaction.js - -1) Specify the parameters in the target source - - - fromAddress: Transfer source account ID - - fromAddressPkey: private key of Transfer source account - - toAddress: Destination account ID - - amount: the value of the asset to be transferred - -2) Run -
-node validatorDriver_sendRawTransaction.js 
-
- - -**NOTE** - -* You can check the balance with "validatorDriver_getNumericBalance.js". diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/config/default.js b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/config/default.js deleted file mode 100644 index 8b7080ca23..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/config/default.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * default.js - */ - -module.exports = { - // URL to validator - "validatorUrl" : 'https://localhost:5050', - "gethUrl" : 'http://localhost:8545', - - // forCustomChain - "chainName": 'geth1', - "networkId": 10, - "chainId": 10 - -}; diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/.gitignore b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/.gitignore deleted file mode 100644 index 53a9595130..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -data-ec1 -data-ec2 -genesis/genesis-ec1.json -genesis/genesis-ec2.json - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/README.md b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/README.md deleted file mode 100644 index cc027e713b..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/README.md +++ /dev/null @@ -1,102 +0,0 @@ - -# BIF-trial(geth-docker) - -## Explanation -- "geth-docker" is a module required to run "Validator" -- Immediately after applying -geth-docker, it is necessary to perform "a) initialization" -- How to start/stop will be explained follow - -## a) Initialization -### 1) Account creation -
-./init-account.sh
-
- -Please keep in your memo the addresses (ec1-accounts[0],[1],..,[4] and ec2-accounts[0],[1],..,[4]), - -* Sample output -
- make-account-ec1-accounts[0]
- Creating network "ecenv_default" with the default driver
- INFO [05-29|08:33:35.658] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {782646267c64d536983a64af9d9a5ab80e036989}
- 
- make-account-ec1-accounts[1]
- INFO [05-29|08:33:42.143] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {38f6d41b35d1af26865a0c13d41e8aa342e62e61}
- 
- make-account-ec1-accounts[2]
- INFO [05-29|08:33:48.534] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {895b383457a714e051357dfc36bb3b6ddf84f01f}
- 
- make-account-ec1-accounts[3]
- INFO [05-29|08:33:54.731] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {caf99b30857e0d29cd866e27fb39b2e7d2b2dc17}
- 
- make-account-ec1-accounts[4]
- INFO [05-29|08:34:01.282] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {1b75166f65a852216306af320783e4b22986d3e3}
- 
- make-account-ec2-accounts[0]
- INFO [05-29|08:34:08.021] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {8f2244f75a4c53684c5827ec19615dc89c2ad21c}
- 
- make-account-ec2-accounts[1]
- INFO [05-29|08:34:14.414] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {add19019ee1ea604b3fcb55a11b97d0fc81cc221}
- 
- make-account-ec2-accounts[2]
- INFO [05-29|08:34:21.292] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {ab66982e4eb732f0e17c56586e530f94ee9411ce}
- 
- make-account-ec2-accounts[3]
- INFO [05-29|08:34:27.947] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {4809b6329ef15bcd1b5b730e0f148ae751cfd9f6}
- 
- make-account-ec2-accounts[4]
- INFO [05-29|08:34:34.360] Maximum peer count                       ETH=25 LES=0 total=25
- Address: {421c9db39b64575c511f94990acfd4394dd5f1c3}
-
- -### 2) Editing initial block information -* Change the "ADDRESS" in genesis/genesis-ec1.json(and genesis-ec2.json) to the address for ec1-accounts[0]. - - * Specify ec1-accounts [0] account for "genesis / genesis-ec1.json" - * Specify ec2-accounts [0] account for "genesis / genesis-ec2.json" - -* Sample output - -
- "alloc"      : {
- 	"ADDRESS":
- 	{"balance":"100000000000000000000000000"}
- },
-                  |
-                  v
- "alloc"      : {
- 	"782646267c64d536983a64af9d9a5ab80e036989":
- 	{"balance":"100000000000000000000000000"}
- },
-
- -### 3) Initializing end-chains: -
-./init-chain.sh
-
- -## b) Launching geth-containers -
-./up.sh
-
- - -## c) Stop geth-containers -
-./down.sh
-
- diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/delete.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/delete.sh deleted file mode 100755 index e07cdc3ee5..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/delete.sh +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -docker-compose -f docker-init.yml down -docker-compose down -sudo rm -r ./data* -docker network rm ec1net -docker network rm ec2net diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-compose.yml b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-compose.yml deleted file mode 100644 index 02b0587a5a..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-compose.yml +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -version: '3' -services: - geth1: - container_name: geth1 - image: ethereum/client-go:v1.8.27 - volumes: - - "$PWD/data-ec1:/root/data" - - "$PWD/genesis/genesis-ec1.json:/root/data/genesis.json" # mount genesis.js from host - working_dir: /root - ports: - - "8545:8545" #uncomment this line to enable JSON-RPC access from outside of network - # - "30303:30303" - expose: - - "8545" # enable JSON-RPC access fron only inside of network - networks: - - ec1net - logging: - driver: "json-file" - options: - max-size: "10m" - max-file: "3" - # following parameters are given to geth - command: > - --rpc - --networkid 10 - --nodiscover - --datadir=/root/data - --rpcaddr "0.0.0.0" - --rpcport "8545" - --rpccorsdomain "*" - --rpcvhosts "*" - --rpcapi "eth,web3" - --unlock 0,1,2,3,4 - --password "/dev/null" - --gasprice 0 - --mine --minerthreads=1 - geth2: - container_name: geth2 - image: ethereum/client-go:v1.8.27 - volumes: - - "$PWD/data-ec2:/root/data" - - "$PWD/genesis/genesis-ec2.json:/root/data/genesis.json" # mount genesis.js from host - working_dir: /root - ports: - - "8546:8545" #uncomment this line to enable JSON-RPC access from outside of network - # - "30303:30303" - expose: - - "8545" # enable JSON-RPC access fron only inside of network - networks: - - ec2net - logging: - driver: "json-file" - options: - max-size: "10m" - max-file: "3" - # following parameters are given to geth - command: > - --rpc - --networkid 10 - --nodiscover - --datadir=/root/data - --rpcaddr "0.0.0.0" - --rpcport "8545" - --rpccorsdomain "*" - --rpcvhosts "*" - --rpcapi "eth,web3" - --unlock 0,1,2,3,4 - --password "/dev/null" - --gasprice 0 - --mine --minerthreads=1 -networks: - ec1net: - external: true - ec2net: - external: true diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-init.yml b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-init.yml deleted file mode 100644 index b7e5a6d1ad..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/docker-init.yml +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -version: '3' -services: - # ec1 - make-account-ec1: - container_name: make-account-ec1 - image: ethereum/client-go:v1.8.27 - tty: true - volumes: - - "$PWD/data-ec1:/root/data" - command: > - --datadir "/root/data" - account new --password /dev/null > /root/data/log.txt - init-chain-ec1: - container_name: init-chain-ec1 - image: ethereum/client-go:v1.8.27 - tty: true - volumes: - - "$PWD/data-ec1:/root/data" - - "$PWD/genesis/genesis-ec1.json:/root/data/genesis.json" - command: > - --datadir "/root/data" - init /root/data/genesis.json - # ec2 - make-account-ec2: - container_name: make-account-ec2 - image: ethereum/client-go:v1.8.27 - tty: true - volumes: - - "$PWD/data-ec2:/root/data" - command: > - --datadir "/root/data" - account new --password /dev/null > /root/data/log.txt - init-chain-ec2: - container_name: init-chain-ec2 - image: ethereum/client-go:v1.8.27 - tty: true - volumes: - - "$PWD/data-ec2:/root/data" - - "$PWD/genesis/genesis-ec2.json:/root/data/genesis.json" - command: > - --datadir "/root/data" - init /root/data/genesis.json diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/down.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/down.sh deleted file mode 100755 index b2f43f232e..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/down.sh +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -docker-compose -f docker-init.yml down -docker-compose down diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/genesis/template/genesis-template.json b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/genesis/template/genesis-template.json deleted file mode 100644 index 1d3401b722..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/genesis/template/genesis-template.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "config": { - "chainId": 10, - "homesteadBlock": 0, - "eip155Block": 0, - "eip158Block": 0 - }, - "alloc" : { - "ADDRESS": - {"balance":"100000000000000000000000000"} - }, - "coinbase" : "0x3333333333333333333333333333333333333333", - "difficulty" : "0x4000", - "extraData" : "", - "gasLimit" : "0x8000000", - "nonce" : "0x0000000000000042", - "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000", - "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000", - "timestamp" : "0x00" -} diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-account.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-account.sh deleted file mode 100755 index d3119eda18..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-account.sh +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -echo "make-account-ec1-accounts[0]" -docker-compose -f docker-init.yml run make-account-ec1 -cp ./genesis/template/genesis-template.json ./genesis/genesis-ec1.json -echo " " -echo "make-account-ec1-accounts[1]" -docker-compose -f docker-init.yml run make-account-ec1 -echo " " -echo "make-account-ec1-accounts[2]" -docker-compose -f docker-init.yml run make-account-ec1 -echo " " -echo "make-account-ec1-accounts[3]" -docker-compose -f docker-init.yml run make-account-ec1 -echo " " -echo "make-account-ec1-accounts[4]" -docker-compose -f docker-init.yml run make-account-ec1 -echo " " -echo "make-account-ec2-accounts[0]" -docker-compose -f docker-init.yml run make-account-ec2 -cp ./genesis/template/genesis-template.json ./genesis/genesis-ec2.json -echo " " -echo "make-account-ec2-accounts[1]" -docker-compose -f docker-init.yml run make-account-ec2 -echo " " -echo "make-account-ec2-accounts[2]" -docker-compose -f docker-init.yml run make-account-ec2 -echo " " -echo "make-account-ec2-accounts[3]" -docker-compose -f docker-init.yml run make-account-ec2 -echo " " -echo "make-account-ec2-accounts[4]" -docker-compose -f docker-init.yml run make-account-ec2 -echo " " diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-chain.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-chain.sh deleted file mode 100755 index 58ed9d76b2..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/init-chain.sh +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -docker-compose -f docker-init.yml run init-chain-ec1 -docker-compose -f docker-init.yml run init-chain-ec2 diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/logview.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/logview.sh deleted file mode 100755 index 806b11f3f8..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/logview.sh +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -docker-compose logs -f diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/up.sh b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/up.sh deleted file mode 100755 index c1bb37b0f3..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/geth-docker/up.sh +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2019-2020 Fujitsu Laboratories Ltd. -# SPDX-License-Identifier: Apache-2.0 -docker network create ec1net -docker network create ec2net -docker-compose up -d diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/package.json b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/package.json deleted file mode 100644 index 71d3f357c5..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "validatorDriver", - "version": "0.0.0", - "private": true, - "dependencies": { - "config": "^1.26.1", - "ethereumjs-common": "^1.5.1", - "ethereumjs-tx": "^2.1.2", - "web3": "^1.2.9", - "socket.io": "^2.0.4" - } -} diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_sendRawTransaction.js b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_sendRawTransaction.js deleted file mode 100644 index a65e3d1e7b..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_sendRawTransaction.js +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * validatorDriver_sendRawTransaction.js - */ - -//////// -// Usage -// 1) Set parameter to parameter variable -// [parameter variables of sendRawTransaction] fromAddress,fromAddressPkey,toAddress,amount,amount -// 2) execute -// -//////// - -// Validator test program.(socket.io client) -var io = require('socket.io-client'); -var config = require('config'); - -// Specify the server (Validator) of the communication destination -var validatorUrl = config.validatorUrl; -console.log('validatorUrl: ' + validatorUrl); -var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 -}; -var socket = io(validatorUrl, options); - -// for signing -var Common = require('ethereumjs-common').default; -var Tx = require('ethereumjs-tx').Transaction; -const Web3 = require('web3'); -var gethUrl = config.gethUrl; -console.log('gethUrl: ' + gethUrl); -const provider = new Web3.providers.HttpProvider(gethUrl); -const web3 = new Web3(provider); - -//ethereumjs-tx2.1.2_support -const customCommon = Common.forCustomChain( - 'mainnet', - { - name: config.chainName, - networkId: config.networkId, - chainId: config.chainId, - }, - 'petersburg', -) - -// for test -// ec1-accounts[0] Address: {686b88b469a06e663e9c1c448ae646e1d6031c73}, pkey: fe47fab697963b8ab1ed82817db727f6b2f7cf522584da89cea82958224f6540 -// ec1-accounts[1] Address: {9bece585f400a2714c99aff66a09814aa75de781}, pkey: ee00377add8fcc7509cde13b974e12d5d7032462689b5398c275ca271c5f2b92 -// ec1-accounts[2] Address: {7370b07a74c4fe2caadf38c6d5788aa77d3a8843}, pkey: 6a6c15c2d03f41f2de94027a5ddde7f6631b72cac8ea102f386ceafa93aab236 -// ec1-accounts[3] Address: {a075cfe69fae5160c4284ee778ea02d6fb4b8f74}, pkey: 34e3c7eaec470daaec0a104448103e685c9ae71f782efa9fc74f3fc0092676da -// ec1-accounts[4] Address: {b5431683f672782f0ebc74830047d824e7d3e05b}, pkey: 2925a764049f0041fb8681a0acc8502388066aaa7228cee5216d01ce4d4117f7 - -// ## Request Params -var fromAddress = "ec709e1774f0ce4aba47b52a499f9abaaa159f71"; -var fromAddressPkey = "40d7e5931a6e0807d3ebd70518f635dbf575975d3bb564ff34c99be416067c89"; -var toAddress = "36e146d5afab61ab125ee671708eeb380aea05b6"; -var amount = 50; - -var gas = 21000; - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - -function makeTxTransferNumericAsset() { - //web3_v1.2.9_support - web3.eth.getTransactionCount('0x' + fromAddress).then(_nance => { - var txnCount = _nance; - // NOTE: No need to count up. - - var gasPrice = web3.eth.gasPrice; - - var privKey = Buffer.from(fromAddressPkey, 'hex'); - console.log('##privKey=' + fromAddressPkey); - var rawTx = { - "nonce": web3.utils.toHex(txnCount), - "to": '0x' + toAddress, - "value": amount, - "gas": gas, - - } - console.log('txnCount=' + web3.utils.toHex(txnCount)); - console.log('##rawTx=' + json2str(rawTx)); - var tx = new Tx(rawTx, { common: customCommon },); - tx.sign(privKey); - var serializedTx = tx.serialize(); - var serializedTxHex = '0x' + serializedTx.toString('hex'); - console.log('##serializedTxHex=' + serializedTxHex); - - var func = "sendRawTransaction"; - - var args = { - serializedTx: serializedTxHex - }; - // function param - var requestData = { - func: func, - args: args - }; - - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); - }) -} - - -socket.on('connect_error', (err) => { - console.log('####connect_error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('connect_timeout', (err) => { - console.log('####Error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('error', (err) => { - console.log('####Error:', err); -}); - -socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); -}); - - -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); -} - -// request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); -} - - -setTimeout(requestStartMonitor, 2000); -setTimeout(makeTxTransferNumericAsset, 4000); diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_transferNumericAsset.js b/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_transferNumericAsset.js deleted file mode 100644 index 16d0f4f4f3..0000000000 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_transferNumericAsset.js +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * validatorDriver_transferNumericAsset.js - */ - -//////// -// Usage -// 1) Set parameter to parameter variable -// [parameter variables of transferNumericAsset] fromAddress,toAddress,amount -// 2) Specify the function to execute with "requestData" -// 3) execute -// -//////// - -// Validator test program.(socket.io client) -var io = require('socket.io-client'); -var config = require('config'); - -// Specify the server (Validator) of the communication destination -var validatorUrl = config.validatorUrl; -console.log('validatorUrl: ' + validatorUrl); -var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 -}; -var socket = io(validatorUrl, options); - -// for test -// ec1-accounts[0] Address: {686b88b469a06e663e9c1c448ae646e1d6031c73} -// ec1-accounts[1] Address: {9bece585f400a2714c99aff66a09814aa75de781} -// ec1-accounts[2] Address: {7370b07a74c4fe2caadf38c6d5788aa77d3a8843} -// ec1-accounts[3] Address: {a075cfe69fae5160c4284ee778ea02d6fb4b8f74} -// ec1-accounts[4] Address: {b5431683f672782f0ebc74830047d824e7d3e05b} - - -// ## Request for "transferNumericAsset" -var fromAddress = "686b88b469a06e663e9c1c448ae646e1d6031c73"; -var toAddress = "9bece585f400a2714c99aff66a09814aa75de781"; -var amount = 50; -var func2 = "transferNumericAsset"; -var args2 = { - fromAddress : fromAddress, - toAddress : toAddress, - amount : amount -}; - -// function param -var requestData = { - func : func2, // func1 or func2 - args : args2 // arg1 or arg2 -}; - - - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - - -socket.on('connect_error', (err) => { - console.log('####connect_error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('connect_timeout', (err) => { - console.log('####Error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('error', (err) => { - console.log('####Error:', err); -}); - -socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); -}); - - -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); -} - -// request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); -} - - -function sendRequest() { - // - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); -} - -setTimeout(requestStartMonitor, 2000); -setTimeout(sendRequest, 4000); diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/.gitignore b/packages/ledger-plugin/go-ethereum/validator/.gitignore similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/.gitignore rename to packages/ledger-plugin/go-ethereum/validator/.gitignore diff --git a/packages/ledger-plugin/go-ethereum/validator/src/README.md b/packages/ledger-plugin/go-ethereum/validator/src/README.md index 2985034c5a..6dcd803567 100644 --- a/packages/ledger-plugin/go-ethereum/validator/src/README.md +++ b/packages/ledger-plugin/go-ethereum/validator/src/README.md @@ -4,15 +4,14 @@ README.md --> -# Validator of Ethereum-speicific Ledger Plugin +# BIF-trial(Validator) ## Assumption -- A ledger (Ethereum node) to connect is already running -- Specify URL of the ledger node to connect to in "provider" of "PluginConfig.js" +- geth1(geth-docker) is running +- Specify the geth1 URL to connect to with "validatorUrl" in "config/default.js" -## Execution -``` -./setup.sh +## Run +
 cd core
 node ./bin/www.js 
-```
\ No newline at end of file
+
diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/copyStaticAssets.ts b/packages/ledger-plugin/go-ethereum/validator/src/copyStaticAssets.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/copyStaticAssets.ts rename to packages/ledger-plugin/go-ethereum/validator/src/copyStaticAssets.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/app.js b/packages/ledger-plugin/go-ethereum/validator/src/core/app.js deleted file mode 100644 index 77e35eb6e1..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/core/app.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * app.js - */ - -/* Summary: - * - */ - -var express = require('express'); -var cookieParser = require('cookie-parser'); -var bodyParser = require('body-parser'); - -var app = express(); - -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: false })); -app.use(cookieParser()); - -// catch 404 and forward to error handler -app.use(function(req, res, next) { - var err = new Error('Not Found'); - err.status = 404; - next(err); -}); - -// error handler -app.use(function(err, req, res, next) { - // 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); - console.log(err); - res.send(err); -}); - -module.exports = app; diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/core/app.ts b/packages/ledger-plugin/go-ethereum/validator/src/core/app.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/core/app.ts rename to packages/ledger-plugin/go-ethereum/validator/src/core/app.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.js b/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.js deleted file mode 100644 index 9896ea5606..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.js +++ /dev/null @@ -1,207 +0,0 @@ -#!/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. - */ - -var app = require('../app'); -var debug = require('debug')('connector:server'); -var fs = require('fs'); -var https = require('https'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('connector_main[' + process.pid + ']'); -logger.level = config.logLevel; - -// implementation class of a part dependent of end-chains (server plugin) -var ServerPlugin = require('../../dependent/ServerPlugin.js'); -var Splug = new ServerPlugin(); -// destination dependency (MONITOR) implementation class -var ServerMonitorPlugin = require('../../dependent/ServerMonitorPlugin.js'); -var Smonitor = new ServerMonitorPlugin(); - -/** - * Get port from environment and store in Express. - */ - -var sslport = normalizePort(process.env.PORT || config.sslParam.port); -app.set('port', sslport); - -// Specify private key and certificate -var sslParam = { - key: fs.readFileSync(config.sslParam.key), - cert: fs.readFileSync(config.sslParam.cert) -}; - -/** - * Create HTTPS server. - */ - -var server = https.createServer(sslParam, app); // Start as an https server. -var 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) { - var 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; - } - - var 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() { - var addr = server.address(); - var 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) { - var func = data.func; - var 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((resp_obj) => { - logger.info('*** RESPONSE ***'); - logger.info('Client ID :' + client.id); - logger.info('Response :' + JSON.stringify(resp_obj)); - client.emit("response", resp_obj); - }) - .catch((err_obj) => { - logger.error('*** ERROR ***'); - logger.error('Client ID :' + client.id); - logger.error('Detail :' + JSON.stringify(err_obj)); - client.emit("connector_error", err_obj); - }); - } else { - // No such function - var emsg = "Function " + func + " not found!"; - logger.error(emsg); - var ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - client.emit("connector_error", ret_obj); - } - }); - - /** - * startMonitor: starting block generation event monitoring - **/ - client.on('startMonitor', function() { - // Callback to receive monitoring results - var cb = function(callbackData) { - var emit_type = ""; - if(callbackData.status == 200) { - emit_type = "eventReceived"; - logger.info('event data callbacked.'); - } else { - emit_type = "monitor_error"; - } - client.emit(emit_type, callbackData); - } - - Smonitor.startMonitor(client.id, cb); - }); - - /** - * stopMonitor: block generation events monitoring stopping - **/ - 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); - }); - -}); - diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.ts b/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.ts new file mode 100644 index 0000000000..21f284e6f4 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/core/bin/www.ts @@ -0,0 +1,273 @@ +#!/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() { + // 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, 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); + }); + +}); + diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.js b/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.js deleted file mode 100644 index 501dee5301..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * default.js - */ - -module.exports = { - // Defined value for the destination independent part. - // Destination dependent definition values should be in lib/PluginConfig.js. - "sslParam" : { - "port" : 5050, - "key" : './CA/connector.priv', - "cert" : './CA/connector.crt' - }, - // Log level (trace/debug/info/warn/error/fatal) - "logLevel" : "debug" -}; diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.ts b/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.ts new file mode 100644 index 0000000000..04a4d2b513 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/core/config/default.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * default.js + */ + +export const config = { +//module.exports = { + // Defined value for the destination independent part. I don't think I can use it only at www, so I think I can write directly there. + // Destination dependent definition values should be in lib/PluginConfig.js. + "sslParam" : { + "port" : 5050, + "key" : "./core/CA/connector.priv", + "cert" : "./core/CA/connector.crt" + }, + // Log level (trace/debug/info/warn/error/fatal) + "logLevel" : "debug" +} diff --git a/packages/ledger-plugin/go-ethereum/validator/src/core/package.json b/packages/ledger-plugin/go-ethereum/validator/src/core/package.json deleted file mode 100644 index 4cde14a5a5..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/core/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "connector", - "version": "0.0.0", - "private": true, - "scripts": { - "start": "node ./bin/www" - }, - "dependencies": { - "body-parser": "~1.17.1", - "config": "^1.26.1", - "cookie-parser": "~1.4.3", - "debug": "~4.1.1", - "express": "~4.15.2", - "log4js": "^3.0.6", - "morgan": "~1.8.1", - "serve-favicon": "~2.4.2", - "socket.io": "^2.0.4" - } -} diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginConfig.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginConfig.js deleted file mode 100644 index 2563ec08d1..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginConfig.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * PluginConfig.js - */ - -/* - * Summary: - * Configuration file of cooperation server: a part dependent on end-chains - * Definition values specific to the connection dependent part, etc. - */ - -module.exports = { - // URL to operate and monitor - //"provider" : 'http://geth1:8545' - "provider" : 'http://localhost:8545' -}; diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/PluginConfig.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginConfig.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/PluginConfig.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginConfig.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginUtil.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginUtil.js deleted file mode 100644 index ed1fcd86a6..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginUtil.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * PluginUtil.js - */ - -/* - * Summary: - * Cooperation server: utility library dependent on endchains - * For example, implementing internal functions that should not be exposed as functions of server plugins. - */ - -/* - * convNum - * - * @param {String/Number} value: The scientific string or numeric value to be converted. For numbers, it is returned as is. - * @param {String/Number} default_value: The value to use if conversion was not possible. Text or number in scientific notation. Optional. - * - * @return {Number} The value converted to a number, or the default_value if the conversion failed. - * - * @desc exponentiation is also supported. The following formats are supported:. (value, default_value) - * 3.78*10^14 - * 3.78e14 - */ -exports.convNum = function(value, default_value) { - var retvalue = 0; - var def_value = 0; - - switch(typeof(default_value)) { - case "number": - def_value = default_value; - break; - case "string": - var def_value_str = default_value.replace(/\*10\^/g, "e"); - def_value = parseFloat(def_value_str); - break; - default: // undefined should also be included here. - // Fixed value because of cumbersome handling. - def_value = 0; - break; - } // switch(typeof(default_value)) - - if(def_value==NaN) { // number is guaranteed. - def_value = 0; - } - - switch(typeof(value)) { - case "number": - retvalue = value; - break; - case "string": - var value_str = value.replace(/\*10\^/g, "e"); - retvalue = parseFloat(value_str); - break; - default: - // Set default value. - retvalue = def_value; - break; - } // switch(typeof(value)) - - if(retvalue==NaN) { // number is guaranteed. - retvalue = def_value; - } - - return retvalue; -} - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/PluginUtil.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginUtil.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/PluginUtil.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/PluginUtil.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.js deleted file mode 100644 index f207e69985..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.js +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerMonitorPlugin.js - */ - -/* - * Summary: - * Connector: monitoring class of a part dependent on end-chains - * Used in the case of monitoring continuously. - * Processing that ends with the acceptance of a single event is handled by a custom function implementation in server plugins. - * Unlike server plugins, it basically does not handle its own functions. - */ - -// configuration file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerMonitorPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// Load libraries, SDKs, etc. according to specifications of endchains as needed -var Web3 = require('web3'); - -/* - * ServerMonitorPlugin - * Class definitions of server monitoring - */ -var ServerMonitorPlugin = class { - /* - * constructors - */ - constructor(){ - // Define dependent specific settings - // Initialize monitored filter - this._filterTable = {}; - } - - /* - * startMonitor - * Start Monitoring - * @param {string} clientId: Client ID from which monitoring start request was made - * @param {function} cb: A callback function that receives monitoring results at any time. - */ - startMonitor(clientId, cb) { - logger.info('*** START MONITOR ***'); - logger.info('Client ID :' + clientId); - // Implement handling to receive events from an end-chain and return them in a callback function - var filter = this._filterTable[clientId]; - if (!filter) { - logger.info('create new web3 filter and start watching.'); - try { - var web3 = new Web3(); - var provider = new web3.providers.HttpProvider(SplugConfig.provider); - web3.setProvider(provider); - filter = web3.eth.filter("latest"); - // filter should be managed by client ID - // (You should never watch multiple urls from the same client) - this._filterTable[clientId] = filter; - filter.watch(function (error, blockHash) { - if (!error) { - console.log('##[HL-BC] Notify new block data(D2)'); - var blockData = web3.eth.getBlock(blockHash, true); - var trLength = blockData.transactions.length; - logger.info(trLength + " transactions in block " + blockData.number); - console.log('##[HL-BC] Validate transactions(D3)'); - console.log('##[HL-BC] digital sign on valid transaction(D4)'); - if (trLength > 0) { - logger.info('*** SEND BLOCK DATA ***'); - // Notify only if transaction exists - var ret_obj = { - "status" : 200, - "blockData" : blockData - }; - cb(ret_obj); - } - } else { - var err_obj = { - "status" : 504, - "errorDetail" : error - }; - cb(err_obj); - } - }); - } catch (e) { - var emsg = e.toString().replace(/Error: /g , ""); - var err_obj = { - "status" : 504, - "errorDetail" : emsg - }; - cb(err_obj); - } - } else { - logger.info('target filter has already start watching.'); - } - } - - /* - * stopMonitor - * monitoring stop - * @param {string} clientId: Client ID from which monitoring stop request was made - */ - stopMonitor(clientId) { - // Implement a process to end EC monitoring - var filter = this._filterTable[clientId]; - if (filter) { - // Stop the filter & Remove it from table - logger.info('stop watching and remove filter.'); - filter.stopWatching(); - delete this._filterTable[clientId]; - } - } - -} /* class */ - -module.exports = ServerMonitorPlugin; - diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.ts new file mode 100644 index 0000000000..72abff1284 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerMonitorPlugin.ts @@ -0,0 +1,119 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * ServerMonitorPlugin.js + */ + +/* + * Summary: + * Connector: monitoring class of a part dependent on end-chains + * Used in the case of monitoring continuously. + * Processing that ends with the acceptance of a single event is handled by a custom function implementation in server plugins. + * Unlike server plugins, it basically does not handle its own functions. + */ + +// configuration file +import { SplugConfig } from './PluginConfig'; +import { config } from '../core/config/default'; +// Log settings +import { getLogger } from "log4js"; +const logger = getLogger('ServerMonitorPlugin[' + process.pid + ']'); +logger.level = config.logLevel; +// Load libraries, SDKs, etc. according to specifications of endchains as needed +var Web3 = require('web3'); + +/* + * ServerMonitorPlugin + * Class definitions of server monitoring + */ +export class ServerMonitorPlugin { + + _filterTable: object; + + /* + * constructors + */ + constructor(){ + // Define dependent specific settings + // Initialize monitored filter + this._filterTable = {}; + } + + /* + * startMonitor + * Start Monitoring + * @param {string} clientId: Client ID from which monitoring start request was made + * @param {function} cb: A callback function that receives monitoring results at any time. + */ + startMonitor(clientId, cb) { + logger.info('*** START MONITOR ***'); + logger.info('Client ID :' + clientId); + // Implement handling to receive events from an end-chain and return them in a callback function + var filter = this._filterTable[clientId]; + if (!filter) { + logger.info('create new web3 filter and start watching.'); + try { + var web3 = new Web3(); + var provider = new web3.providers.HttpProvider(SplugConfig.provider); + web3.setProvider(provider); + filter = web3.eth.filter("latest"); + // filter should be managed by client ID + // (You should never watch multiple urls from the same client) + this._filterTable[clientId] = filter; + filter.watch(function (error, blockHash) { + if (!error) { + console.log('##[HL-BC] Notify new block data(D2)'); + var blockData = web3.eth.getBlock(blockHash, true); + var trLength = blockData.transactions.length; + logger.info(trLength + " transactions in block " + blockData.number); + console.log('##[HL-BC] Validate transactions(D3)'); + console.log('##[HL-BC] digital sign on valid transaction(D4)'); + if (trLength > 0) { + logger.info('*** SEND BLOCK DATA ***'); + // Notify only if transaction exists + var retObj = { + "status" : 200, + "blockData" : blockData + }; + cb(retObj); + } + } else { + let errObj = { + "status" : 504, + "errorDetail" : error + }; + cb(errObj); + } + }); + } catch (e) { + var emsg = e.toString().replace(/Error: /g , ""); + let errObj = { + "status" : 504, + "errorDetail" : emsg + }; + cb(errObj); + } + } else { + logger.info('target filter has already start watching.'); + } + } + + /* + * stopMonitor + * monitoring stop + * @param {string} clientId: Client ID from which monitoring stop request was made + */ + stopMonitor(clientId) { + // Implement a process to end EC monitoring + var filter = this._filterTable[clientId]; + if (filter) { + // Stop the filter & Remove it from table + logger.info('stop watching and remove filter.'); + filter.stopWatching(); + delete this._filterTable[clientId]; + } + } + +} + diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.js deleted file mode 100644 index 4662adeb40..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.js +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerPlugin.js - */ - -/* - * Summary: - * Connector: a part dependent on endchains - * Define and implement the function according to the connection destination dependent part (ADAPTER) on the core side. - */ - -// configuration file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// utility -var SplugUtil = require('./PluginUtil.js'); -// Load libraries, SDKs, etc. according to specifications of endchains as needed -var Web3 = require('web3'); - - -/* - * ServerPlugin - * Class definition for server plugins - */ -var ServerPlugin = class { - /* - * constructors - */ - constructor(){ - // Define dependent specific settings - } - - /* - * isExistFunction - * - * @param {String} funcName: The function name to check. - * - * @return {Boolean} true: Yes./false: does not exist. - * - * @desc Return if end-chain specific funtion is implemented - * Scope of this function is in this class - * Functions that should not be called directly should be implemented outside this class like utilities. - */ - isExistFunction(funcName) { - if(this[funcName]!=undefined) { - return true; - } else { - return false; - } - } - - // Define an arbitrary function and implement it according to specifications of end-chains - /* - * getNumericBalance - * Get numerical balance - * - * @param {Object} args JSON Object - * { - * "referedAddress": - * } - * @return {Object} JSON object - */ - getNumericBalance(args) { - // * The Web3 API can be used synchronously, but each function is always an asynchronous specification because of the use of other APIs such as REST, - return new Promise((resolve, reject) => { - logger.info("getNumericBalance start"); - var ret_obj = {}; - if(args["referedAddress"]==undefined) { - var emsg = "JSON parse error!"; - logger.info(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - var ethargs = args["referedAddress"]; - // Handling exceptions to absorb the difference of interest. - try { - var web3 = new Web3(); - web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); - var balance = web3.eth.getBalance(ethargs); - var amount_val = balance.toNumber(); - - ret_obj = { - "status" : 200, - "amount" : amount_val - }; - return resolve(ret_obj); - } catch (e) { - var emsg = e.toString().replace(/Error: /g , ""); - logger.error(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - }); - } - - /* - * transferNumericAsset - * Transfer numerical asset - * - * @param {Object} args JSON Object - * { - * "fromAddress":, - * "toAddress":, - * "amount": - * } - * @return {Object} JSON object - */ - transferNumericAsset(args) { - return new Promise((resolve, reject) => { - logger.info("transferNumericAsset start"); - - var ret_obj = {}; - var send_args = {}; - var send_function = 'sendTransaction'; - - if((args["fromAddress"]==undefined)||(args["toAddress"]==undefined)|| - (args["amount"]==undefined)) { - var emsg = "JSON parse error!"; - logger.error(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - // Dealing with exponentiation strings. - var amount = SplugUtil.convNum(args["amount"], 0); - - // Create an argument object for sendTransaction. - send_args = { - "from" : args["fromAddress"], - "to" : args["toAddress"], - "value" : amount - }; - - - logger.info('send_func :' + send_function); - logger.info('send_args :' + JSON.stringify(send_args)); - - // Handle the exception once to absorb the difference of interest. - try { - var web3 = new Web3(); - web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); - var res = web3.eth[send_function](send_args); - - ret_obj = { - "status" : 200, - "txid" : res - }; - return resolve(ret_obj); - } catch (e) { - var emsg = e.toString().replace(/Error: /g , ""); - logger.error(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - }); - } - - /* - * sendRawTransaction - * send row trancastion - * - * @param {Object} args JSON Object - * { - * "serializedTx": - * } - * @return {Object} JSON object - */ - sendRawTransaction(args) { - return new Promise((resolve, reject) => { - logger.info("sendRawTransaction start"); - - var ret_obj = {}; - var send_args = {}; - var send_function = 'sendTransaction'; - - if(args["serializedTx"]==undefined) { - var emsg = "JSON parse error!"; - logger.error(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - - var serializedTx = args["serializedTx"]; - logger.info('serializedTx :' + serializedTx); - - // Handle the exception once to absorb the difference of interest. - try { - var web3 = new Web3(); - web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); - var res = web3.eth.sendRawTransaction(serializedTx); - - ret_obj = { - "status" : 200, - "txid" : res - }; - return resolve(ret_obj); - } catch (e) { - var emsg = e.toString().replace(/Error: /g , ""); - logger.error(emsg); - ret_obj = { - "status" : 504, - "errorDetail" : emsg - }; - return reject(ret_obj); - } - }); - } - -} /* class */ - -module.exports = ServerPlugin; - diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerPlugin.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.ts similarity index 53% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerPlugin.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.ts index 3ba0dccc0e..64fec4b826 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/ServerPlugin.ts +++ b/packages/ledger-plugin/go-ethereum/validator/src/dependent/ServerPlugin.ts @@ -13,10 +13,10 @@ // configuration file var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); +import { config } from '../core/config/default'; // Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerPlugin[' + process.pid + ']'); +import { getLogger } from "log4js"; +const logger = getLogger('ServerPlugin[' + process.pid + ']'); logger.level = config.logLevel; // utility var SplugUtil = require('./PluginUtil.js'); @@ -72,7 +72,12 @@ export class ServerPlugin { return new Promise((resolve, reject) => { logger.info("getNumericBalance start"); var retObj = {}; - if(args["referedAddress"]==undefined) { + + var referedAddress = args.args.args[0]; + var reqID = args['reqID']; + + + if(referedAddress === undefined) { let emsg = "JSON parse error!"; logger.info(emsg); retObj = { @@ -83,7 +88,7 @@ export class ServerPlugin { }; return reject(retObj); } - var ethargs = args["referedAddress"]; + var ethargs = referedAddress; // Handling exceptions to absorb the difference of interest. try { var web3 = new Web3(); @@ -97,8 +102,8 @@ export class ServerPlugin { } }; logger.debug("##getNumericBalance: add reqID"); - if (args["reqID"] !== undefined) { - retObj["id"] = args["reqID"]; + if (reqID !== undefined) { + retObj["id"] = reqID; } logger.debug(`##getNumericBalance: retObj: ${JSON.stringify(retObj)}`); return resolve(retObj); @@ -112,8 +117,8 @@ export class ServerPlugin { } }; logger.debug("##getNumericBalance: add reqID"); - if (args["reqID"] !== undefined) { - retObj["id"] = args["reqID"]; + if (reqID !== undefined) { + retObj["id"] = reqID; } logger.debug(`##getNumericBalance: retObj: ${JSON.stringify(retObj)}`); return reject(retObj); @@ -141,9 +146,12 @@ export class ServerPlugin { var retObj = {}; var sendArgs = {}; var sendFunction = 'sendTransaction'; + // const funcParam = args; + const funcParam = args.args.args[0]; + var reqID = args['reqID']; - if((args["fromAddress"]==undefined)||(args["toAddress"]==undefined)|| - (args["amount"]==undefined)) { + if((funcParam["fromAddress"]==undefined)||(funcParam["toAddress"]==undefined)|| + (funcParam["amount"]==undefined)) { let emsg = "JSON parse error!"; logger.error(emsg); retObj = { @@ -155,12 +163,12 @@ export class ServerPlugin { return reject(retObj); } // Dealing with exponentiation strings. - var amount = SplugUtil.convNum(args["amount"], 0); + var amount = SplugUtil.convNum(funcParam["amount"], 0); // Create an argument object for sendTransaction. sendArgs = { - "from" : args["fromAddress"], - "to" : args["toAddress"], + "from" : funcParam["fromAddress"], + "to" : funcParam["toAddress"], "value" : amount }; @@ -181,8 +189,8 @@ export class ServerPlugin { } }; logger.debug("##transferNumericAsset: add reqID"); - if (args["reqID"] !== undefined) { - retObj["reqID"] = args["reqID"]; + if (reqID !== undefined) { + retObj["reqID"] = reqID; } logger.debug(`##transferNumericAsset: retObj: ${JSON.stringify(retObj)}`); return resolve(retObj); @@ -196,8 +204,8 @@ export class ServerPlugin { } }; logger.debug("##transferNumericAsset: add reqID"); - if (args["reqID"] !== undefined) { - retObj["reqID"] = args["reqID"]; + if (reqID !== undefined) { + retObj["reqID"] = reqID; } logger.debug(`##transferNumericAsset: retObj: ${JSON.stringify(retObj)}`); return reject(retObj); @@ -217,13 +225,14 @@ export class ServerPlugin { */ sendRawTransaction(args) { return new Promise((resolve, reject) => { - logger.info("sendRawTransaction start"); + logger.info("sendRawTransaction(start"); var retObj = {}; var sendArgs = {}; var sendFunction = 'sendTransaction'; + const funcParam = args.args.args[0]; - if(args["serializedTx"]==undefined) { + if(funcParam["serializedTx"]==undefined) { let emsg = "JSON parse error!"; logger.error(emsg); retObj = { @@ -233,7 +242,7 @@ export class ServerPlugin { return reject(retObj); } - var serializedTx = args["serializedTx"]; + var serializedTx = funcParam["serializedTx"]; logger.info('serializedTx :' + serializedTx); // Handle the exception once to absorb the difference of interest. @@ -259,5 +268,157 @@ export class ServerPlugin { }); } + + /* + * web3Eth + * + * @param {Object} args JSON Object + * { + * "method":, + * "args":, + * "reqID": (option) + * } + * @return {Object} JSON object + */ + web3Eth(args) { + return new Promise((resolve, reject) => { + logger.info("web3Eth start"); + + let retObj = {}; + const sendFunction = args.method.command; + const sendArgs = args.args.args[0]; + const reqID = args['reqID']; + + logger.info('send_func :' + sendFunction); + logger.info('sendArgs :' + JSON.stringify(sendArgs)); + + // Handle the exception once to absorb the difference of interest. + try { + const web3 = new Web3(); + web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); + let result: any = null; + if (sendArgs !== undefined) { + result = web3.eth[sendFunction](sendArgs); + } else { + result = web3.eth[sendFunction](); + } + + retObj = { + "resObj" : { + "status" : 200, + "data" : result + } + }; + logger.debug("##web3Eth: add reqID"); + if (reqID !== undefined) { + retObj["id"] = reqID; + } + logger.debug(`##web3Eth: retObj: ${JSON.stringify(retObj)}`); + return resolve(retObj); + } catch (e) { + let emsg = e.toString().replace(/Error: /g , ""); + logger.error(emsg); + retObj = { + "resObj" : { + "status" : 504, + "errorDetail" : emsg + } + }; + logger.debug("##web3Eth: add reqID"); + if (reqID !== undefined) { + retObj["id"] = reqID; + } + logger.debug(`##web3Eth: retObj: ${JSON.stringify(retObj)}`); + return reject(retObj); + } + }); + } + + + /* + * contract + * + * @param {Object} args JSON Object + * { + * "contract":, + * "method":, + * "args":, + * "reqID": (option) + * } + * @return {Object} JSON object + */ + contract(args) { + return new Promise((resolve, reject) => { + logger.info("contract start"); + + let retObj = {}; + const sendCommand = args.method.command; + const sendFunction = args.method.function; + const sendArgs = args.args.args; + const reqID = args['reqID']; + + logger.info('sendCommand :' + sendCommand); + logger.info('sendFunction :' + sendFunction); + logger.info('sendArgs :' + JSON.stringify(sendArgs)); + + // Handle the exception once to absorb the difference of interest. + try { + const web3 = new Web3(); + web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); + const contract = web3.eth.contract(args.contract.abi).at(args.contract.address); + + let result: any = null; + switch (sendArgs.length) { + case 0: + logger.debug(`##contract: No args.`); + result = contract[sendCommand][sendFunction](); + break; + case 1: + logger.debug(`##contract: One arg.`); + result = contract[sendCommand][sendFunction](sendArgs[0]); + break; + case 2: + logger.debug(`##contract: Two args.`); + result = contract[sendCommand][sendFunction](sendArgs[0], sendArgs[1]); + break; + case 3: + logger.debug(`##contract: Three args.`); + result = contract[sendCommand][sendFunction](sendArgs[0], sendArgs[1], sendArgs[2]); + break; + } + logger.debug(`##contract: result: ${result}`); + + retObj = { + "resObj" : { + "status" : 200, + "data" : result + } + }; + logger.debug("##contract: add reqID"); + if (reqID !== undefined) { + retObj["id"] = reqID; + } + logger.debug(`##contract: retObj: ${JSON.stringify(retObj)}`); + return resolve(retObj); + } catch (e) { + let emsg = e.toString().replace(/Error: /g , ""); + logger.error(emsg); + retObj = { + "resObj" : { + "status" : 504, + "errorDetail" : emsg + } + }; + logger.debug("##contract: add reqID"); + if (reqID !== undefined) { + retObj["id"] = reqID; + } + logger.debug(`##contract: retObj: ${JSON.stringify(retObj)}`); + return reject(retObj); + } + }); + } + + } /* class */ diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getAccounts.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getAccounts.ts similarity index 95% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getAccounts.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getAccounts.ts index 1d6f6e62fc..da82c505da 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getAccounts.ts +++ b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getAccounts.ts @@ -8,7 +8,7 @@ // File for direct operation of geth // Account & balance checking import { SplugConfig } from './PluginConfig'; -import { Web3 } from 'web3'; +const Web3 = require('web3'); const web3 = new Web3(); web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); const accounts = web3.eth.accounts; diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getBlock.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getBlock.ts similarity index 93% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getBlock.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getBlock.ts index 8c6659dfd4..c78a5a6f97 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_getBlock.ts +++ b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_getBlock.ts @@ -8,7 +8,7 @@ // File for direct operation of geth // checking block information import { SplugConfig } from './PluginConfig'; -import { Web3 } from 'web3'; +const Web3 = require('web3'); const web3 = new Web3(); web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); const res = web3.eth.getBlock(0); // get 0th block information diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_sendTransaction.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_sendTransaction.ts similarity index 96% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_sendTransaction.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_sendTransaction.ts index b58473ef4a..c5f43b106c 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/geth_sendTransaction.ts +++ b/packages/ledger-plugin/go-ethereum/validator/src/dependent/geth_sendTransaction.ts @@ -8,7 +8,7 @@ // File for direct operation of geth // Asset Transfer import { SplugConfig } from './PluginConfig'; -import { Web3 } from 'web3'; +const Web3 = require('web3'); const web3 = new Web3(); web3.setProvider(new web3.providers.HttpProvider(SplugConfig.provider)); const accounts = web3.eth.accounts; diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/package.json b/packages/ledger-plugin/go-ethereum/validator/src/dependent/package.json deleted file mode 100644 index dbb14fa1e9..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "dependent", - "version": "0.0.0", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { - "config": "^1.26.1", - "log4js": "^3.0.6", - "web3": "^0.20.0" - } -} diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginConfig_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginConfig_template.js deleted file mode 100644 index c856214ebc..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginConfig_template.js +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * PluginConfig_template.js - */ - -/* - * Summary: - * Cooperation server: configuration file of a part dependent on end-chains - * Definition values specific to the connection dependent part, etc. - */ - -module.exports = { - // Nothing special -}; diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/PluginConfig_template.ts b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginConfig_template.ts similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/dependent/template/PluginConfig_template.ts rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginConfig_template.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginUtil_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginUtil_template.js deleted file mode 100644 index 3a8dc9ba4f..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginUtil_template.js +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * PluginUtil_template.js - */ - -/* - * Summary: - * Cooperation server: utility libraries of a part dependent on end-chains - * For example, implementing internal functions that should not be exposed as functions of ServerPlugin. - */ - -// Nothing special diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/template/PluginUtil_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginUtil_template.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/src/dependent/template/PluginUtil_template.js rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/template/PluginUtil_template.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerMonitorPlugin_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerMonitorPlugin_template.js deleted file mode 100644 index fbc640a6b0..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerMonitorPlugin_template.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerMonitorPlugin_template.js - */ - -/* - * Summary: - * Connector: monitoring class of a part dependent on end-chains - * Used in the case of monitoring continuously. - * Processing that ends with the acceptance of a single event is handled by a custom function implementation in server plugins. - * Unlike server plugins, it basically does not handle its own functions. - */ - -// configuration file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerMonitorPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// Load libraries, SDKs, etc. according to specifications of endchains as needed - -/* - * ServerMonitorPlugin - * Class definitions of server monitoring - */ -var ServerMonitorPlugin = class { - /* - * constructors - */ - constructor(){ - // Define dependent specific settings - } - - /* - * startMonitor - * Start Monitoring - * @param {string} clientId: Client ID from which monitoring start request was made - * @param {function} cb: A callback function that receives monitoring results at any time. - */ - startMonitor(clientId, cb) { - logger.info('*** START MONITOR ***'); - logger.info('Client ID :' + clientId); - // Implement handling to receive events from an endchain and return them in a callback function - - } - - /* - * stopMonitor - * monitoring stop - * @param {string} clientId: Client ID from which monitoring stop request was made - */ - stopMonitor(clientId) { - // Implement a process to end EC monitoring - } - -} /* class */ - -module.exports = ServerMonitorPlugin; - diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/template/ServerMonitorPlugin_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerMonitorPlugin_template.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/src/dependent/template/ServerMonitorPlugin_template.js rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerMonitorPlugin_template.ts diff --git a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerPlugin_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerPlugin_template.js deleted file mode 100644 index 36cded30a1..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerPlugin_template.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * ServerPlugin_template.js - */ - -/* - * Summary: - * Connector: a part dependent on endchains - * Define and implement the function according to the connection destination dependent part (ADAPTER) on the core side. - */ - -// configuration file -var SplugConfig = require('./PluginConfig.js'); -var config = require('config'); -// Log settings -var log4js = require('log4js'); -var logger = log4js.getLogger('ServerPlugin[' + process.pid + ']'); -logger.level = config.logLevel; -// utility -var SplugUtil = require('./PluginUtil.js'); -// Load libraries, SDKs, etc. according to specifications of endchains as needed - -/* - * ServerPlugin - * Class definition for server plugins - */ -var ServerPlugin = class { - /* - * constructors - */ - constructor(){ - // Define dependent specific settings - } - - /* - * isExistFunction - * - * @param {String} funcName: The function name to check. - * - * @return {Boolean} true: Yes./false: does not exist. - * - * @desc Return if end-chain specific funtion is implemented - * Scope of this function is in this class - * Functions that should not be called directly should be implemented outside this class like utilities. - */ - isExistFunction(funcName) { - if(this[funcName]!=undefined) { - return true; - } else { - return false; - } - } - - // Define an arbitrary function and implement it according to specifications of end-chains - - -} /* class */ - -module.exports = ServerPlugin; - diff --git a/packages/ledger-plugin/fabric/validator/src/dependent/template/ServerPlugin_template.js b/packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerPlugin_template.ts similarity index 100% rename from packages/ledger-plugin/fabric/validator/src/dependent/template/ServerPlugin_template.js rename to packages/ledger-plugin/go-ethereum/validator/src/dependent/template/ServerPlugin_template.ts diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/src/package.json b/packages/ledger-plugin/go-ethereum/validator/src/package.json similarity index 100% rename from packages/ledger-plugin/go-ethereum-ts/validator/src/package.json rename to packages/ledger-plugin/go-ethereum/validator/src/package.json diff --git a/packages/ledger-plugin/go-ethereum/validator/src/script-build-validator.sh b/packages/ledger-plugin/go-ethereum/validator/src/script-build-validator.sh new file mode 100755 index 0000000000..4c12854830 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/script-build-validator.sh @@ -0,0 +1,5 @@ +## Build a validator for Ethereum +echo "[process] Build a validator for Ethereum" +npm install +npm run build +npm run init-ethereum # For making symbolic for node_modules, enough to be done only once. \ No newline at end of file diff --git a/packages/ledger-plugin/go-ethereum/validator/src/script-start-validator.sh b/packages/ledger-plugin/go-ethereum/validator/src/script-start-validator.sh new file mode 100755 index 0000000000..fcac6695bf --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/script-start-validator.sh @@ -0,0 +1,3 @@ +## Start a validator for Ethereum +echo "[process] Start a validator for Ethereum" +npm run start \ No newline at end of file diff --git a/packages/ledger-plugin/go-ethereum/validator/src/tsconfig.json b/packages/ledger-plugin/go-ethereum/validator/src/tsconfig.json new file mode 100644 index 0000000000..0b59967292 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/src/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "../dist", + "sourceMap": false, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "ES2017", + "module": "CommonJS", + "typeRoots": [ + "node_modules/@types", + "./typings" + ], + "lib": [ + "es2017", + "dom" + ] + }, + "include": [ + "./core/*.ts", + "./core/bin/*.ts", + "./core/config/*.ts", + "./dependent/*.ts" + ], + "exclude": [ + "copyStaticAssets.ts" + ] +} diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/README.md b/packages/ledger-plugin/go-ethereum/validator/unit-test/README.md index 0280509920..001a24c2b7 100644 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/README.md +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/README.md @@ -4,37 +4,55 @@ README.md --> - -# Validator Driver +# BIF-trial(Validator Driver) ## Assumption -- Validator for Ethereum-version Ledger Plugin is already running -- The docker container "geth1" (geth-docker) is already running +- Validator1 (for Ethereum) is running +- geth1(geth-docker) is running - Specify the validator URL to connect to with "validatorUrl" in "config/default.js" -## (a) Get balance -- Target source: "validatorDriver_getNumericBalance.js" +## a) Get balance +### Target source: validatorDriver_getNumericBalance.js 1) Specify the parameters in the target source - - referedAddress: Account ID to be displayed + + - referedAddress: Account ID to be displayed 2) Run -
-	node validatorDriver_getNumericBalance.js 
-	
+
+node validatorDriver_getNumericBalance.js 
+
+ +## b) Asset transfer +### Target source: validatorDriver_transferNumericAsset.js + +1) Specify the parameters in the target source -## (b) Asset transfer + - fromAddress: Transfer source account ID + - toAddress: Destination account ID + - amount: the value of the asset to be transferred -- Target source: "validatorDriver_sendSignedTransaction.js" +2) Run +
+node validatorDriver_transferNumericAsset.js 
+
+ +## c) Raw Transaction execution (Asset transfer) +### Target source: validatorDriver_sendRawTransaction.js 1) Specify the parameters in the target source - - fromAddress: Transfer source account ID - - fromAddressPkey: private key of Transfer source account - - toAddress: Destination account ID - - amount: the value of the asset to be transferred + - fromAddress: Transfer source account ID + - fromAddressPkey: private key of Transfer source account + - toAddress: Destination account ID + - amount: the value of the asset to be transferred 2) Run -
-	node validatorDriver_sendSignedTransaction.js 
-	
+
+node validatorDriver_sendRawTransaction.js 
+
+ + +**NOTE** + +* You can check the balance with "validatorDriver_getNumericBalance.js". diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/config/default.js b/packages/ledger-plugin/go-ethereum/validator/unit-test/config/default.js index 77268051fd..8b7080ca23 100644 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/config/default.js +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/config/default.js @@ -6,7 +6,13 @@ */ module.exports = { - // URL to validator. Please write your IP address in the field of "YourIpAddress". - "validatorUrl" : 'https://YourIpAddress:5050', - "gethUrl" : 'http://localhost:8545' + // URL to validator + "validatorUrl" : 'https://localhost:5050', + "gethUrl" : 'http://localhost:8545', + + // forCustomChain + "chainName": 'geth1', + "networkId": 10, + "chainId": 10 + }; diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/copyStaticAssets.ts b/packages/ledger-plugin/go-ethereum/validator/unit-test/copyStaticAssets.ts new file mode 100644 index 0000000000..50378228f8 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/copyStaticAssets.ts @@ -0,0 +1,2 @@ +import * as shell from 'shelljs'; +shell.cp('config/default.js', './dist/config'); diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/geth-docker/README.md b/packages/ledger-plugin/go-ethereum/validator/unit-test/geth-docker/README.md index 9e20c28e6e..cc027e713b 100644 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/geth-docker/README.md +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/geth-docker/README.md @@ -4,11 +4,11 @@ README.md --> -# geth-docker +# BIF-trial(geth-docker) ## Explanation -- The docker container "geth-docker" is required to run the unit-test for Validator of Ethereum-specific Ledger Plugin -- Immediately after applying geth-docker, it is necessary to perform "a) initialization" +- "geth-docker" is a module required to run "Validator" +- Immediately after applying -geth-docker, it is necessary to perform "a) initialization" - How to start/stop will be explained follow ## a) Initialization @@ -16,10 +16,10 @@
 ./init-account.sh
 
-- NOTE: - - Please keep in your memo the addresses (ec1-accounts[0],[1],..,[4] and ec2-accounts[0],[1],..,[4]), -- Sample output +Please keep in your memo the addresses (ec1-accounts[0],[1],..,[4] and ec2-accounts[0],[1],..,[4]), + +* Sample output
  make-account-ec1-accounts[0]
  Creating network "ecenv_default" with the default driver
@@ -64,11 +64,13 @@
 
### 2) Editing initial block information -- Change the "ADDRESS" in genesis/genesis-ec1.json(and genesis-ec2.json) to the address for ec1-accounts[0]. - - Specify ec1-accounts [0] account for "genesis / genesis-ec1.json" - - Specify ec2-accounts [0] account for "genesis / genesis-ec2.json" +* Change the "ADDRESS" in genesis/genesis-ec1.json(and genesis-ec2.json) to the address for ec1-accounts[0]. + + * Specify ec1-accounts [0] account for "genesis / genesis-ec1.json" + * Specify ec2-accounts [0] account for "genesis / genesis-ec2.json" + +* Sample output -- Sample output
  "alloc"      : {
  	"ADDRESS":
@@ -92,13 +94,9 @@
 ./up.sh
 
+ ## c) Stop geth-containers
 ./down.sh
 
-## d) Stop geth-containers and delete their information -
-./delete.sh
-
- diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/package.json b/packages/ledger-plugin/go-ethereum/validator/unit-test/package.json index 85995cafc0..2bb031ce4d 100644 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/package.json +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/package.json @@ -2,10 +2,22 @@ "name": "validatorDriver", "version": "0.0.0", "private": true, + "scripts": { + "build": "npm run build-ts && npm run copy-static-assets", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json", + "copy-static-assets": "ts-node copyStaticAssets.ts" + }, "dependencies": { + "@types/node": "^14.14.5", "config": "^1.26.1", - "ethereumjs-tx": "^1.3.4", - "web3": "^0.20.0", + "ethereumjs-common": "^1.5.1", + "ethereumjs-tx": "^2.1.2", + "ts-node": "^9.0.0", + "web3": "^1.2.9", "socket.io": "^2.0.4" + }, + "devDependencies": { + "typescript": "^3.9.3" } } diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/tsconfig.json b/packages/ledger-plugin/go-ethereum/validator/unit-test/tsconfig.json new file mode 100644 index 0000000000..928b357062 --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist", + "sourceMap": false, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "ES2017", + "module": "CommonJS", + "typeRoots": [ + "node_modules/@types", + "./typings" + ], + "lib": [ + "es2017", + "dom" + ] + }, +} diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.js b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.js deleted file mode 100644 index 313f679a4b..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.js +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * validatrorDriver_getNumericBalance.js - */ - -//////// -// Usage -// 1) Set parameter to parameter variable -// [parameter variables of getNumericBalance] referredAddress -// 2) Specify the function to execute with "requestData" -// 3) execute -// -//////// - -// Validator test program.(socket.io client) -var io = require('socket.io-client'); -var config = require('config'); - -// Specify the server (Validator) of the communication destination -var validatorUrl = config.validatorUrl; -console.log('validatorUrl: ' + validatorUrl); -var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 -}; -var socket = io(validatorUrl, options); - -// for test -// ec1-accounts[0] Address: {686b88b469a06e663e9c1c448ae646e1d6031c73} -// ec1-accounts[1] Address: {9bece585f400a2714c99aff66a09814aa75de781} -// ec1-accounts[2] Address: {7370b07a74c4fe2caadf38c6d5788aa77d3a8843} -// ec1-accounts[3] Address: {a075cfe69fae5160c4284ee778ea02d6fb4b8f74} -// ec1-accounts[4] Address: {b5431683f672782f0ebc74830047d824e7d3e05b} - -// ## Request for "getNumericBalance" -var referedAddress = "9bece585f400a2714c99aff66a09814aa75de781"; -var func1 = "getNumericBalance"; -var args1 = { - referedAddress : referedAddress -}; - -// function param -var requestData = { - func : func1, // func1 or func1 - args : args1 // arg1 or arg1 -}; - - - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - - -socket.on('connect_error', (err) => { - console.log('####connect_error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('connect_timeout', (err) => { - console.log('####Error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('error', (err) => { - console.log('####Error:', err); -}); - -socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); -}); - - -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); -} - -// request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); -} - - -function sendRequest() { - // - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); -} - -setTimeout(requestStartMonitor, 2000); -setTimeout(sendRequest, 4000); diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorSync_getNumericBalance.js b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.ts similarity index 85% rename from packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorSync_getNumericBalance.js rename to packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.ts index 845be52889..a92ed4dc0e 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorSync_getNumericBalance.js +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_getNumericBalance.ts @@ -14,6 +14,8 @@ // //////// +{ + // Validator test program.(socket.io client) var io = require('socket.io-client'); var config = require('config'); @@ -39,21 +41,16 @@ var socket = io(validatorUrl, options); var referedAddress = "36e146d5afab61ab125ee671708eeb380aea05b6"; var reqID = "reqID_001"; -var func1 = "getNumericBalance"; -var args1 = { - referedAddress : referedAddress, - reqID: reqID -}; - // function param -var requestData = { - func : func1, // func1 or func1 - args : args1 // arg1 or arg1 +const requestData = { + contract: {}, // NOTE: Since contract does not need to be specified, specify an empty object. + method: {type: "web3Eth", command: "getBalance"}, + args: {"args": [referedAddress]}, + reqID: reqID }; - -function json2str(jsonObj) { +const json2str = (jsonObj) => { try { return JSON.stringify(jsonObj); } @@ -87,7 +84,7 @@ socket.on('eventReceived', function (res) { }); -function requestStopMonitor() { +const requestStopMonitor = () => { console.log('##exec requestStopMonitor()'); socket.emit('stopMonitor'); @@ -99,7 +96,7 @@ function requestStopMonitor() { } // request StartMonitor -function requestStartMonitor() { +const requestStartMonitor = () => { console.log('##exec requestStartMonitor()'); socket.emit('startMonitor'); @@ -107,12 +104,15 @@ function requestStartMonitor() { } -function sendRequest() { +const sendRequest = () => { // console.log('exec sendRequest()'); console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); + // socket.emit('request', requestData); + socket.emit('request2', requestData); } setTimeout(requestStartMonitor, 2000); setTimeout(sendRequest, 4000); + +} diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendRawTransaction.ts b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendRawTransaction.ts new file mode 100644 index 0000000000..b5778a8e7b --- /dev/null +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendRawTransaction.ts @@ -0,0 +1,167 @@ +/* + * Copyright 2019-2020 Fujitsu Laboratories Ltd. + * SPDX-License-Identifier: Apache-2.0 + * + * validatorDriver_sendRawTransaction.js + */ + +//////// +// Usage +// 1) Set parameter to parameter variable +// [parameter variables of sendRawTransaction] fromAddress,fromAddressPkey,toAddress,amount,amount +// 2) execute +// +//////// + +{ + +// Validator test program.(socket.io client) +var io = require('socket.io-client'); +var config = require('config'); + +// Specify the server (Validator) of the communication destination +var validatorUrl = config.validatorUrl; +console.log('validatorUrl: ' + validatorUrl); +var options = { + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 +}; +var socket = io(validatorUrl, options); + +// for signing +var Common = require('ethereumjs-common').default; +var Tx = require('ethereumjs-tx').Transaction; +const Web3 = require('web3'); +var gethUrl = config.gethUrl; +console.log('gethUrl: ' + gethUrl); +const provider = new Web3.providers.HttpProvider(gethUrl); +const web3 = new Web3(provider); + +//ethereumjs-tx2.1.2_support +const customCommon = Common.forCustomChain( + 'mainnet', + { + name: config.chainName, + networkId: config.networkId, + chainId: config.chainId, + }, + 'petersburg', +) + +// for test +// ec1-accounts[0] Address: {ec709e1774f0ce4aba47b52a499f9abaaa159f71}, pkey: 40d7e5931a6e0807d3ebd70518f635dbf575975d3bb564ff34c99be416067c89 +// ec1-accounts[1] Address: {36e146d5afab61ab125ee671708eeb380aea05b6}, pkey: 13a45756bc314465c4ae2ff0eb9ab58cf72453c04604d8fa14393eb25ce96d06 +// ec1-accounts[2] Address: {06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97}, pkey: cb5d48d371916a4ea1627189d8af4f642a5d72746a06b559780c3f5932658207 +// ec1-accounts[3] Address: {9d624f7995e8bd70251f8265f2f9f2b49f169c55}, pkey: 3d966c433eb650f40287debacd92afb9c390024e359f9f719b2ca6c0ab07339a +// ec1-accounts[4] Address: {2666a32bf7594ab5395d766dcfbf03d557dab538}, pkey: 918b9b842a633c04e7e97b917d091736334dab6dd71fdc1dcbf0c763014caaf4 + +// ## Request Params +var fromAddress = "36e146d5afab61ab125ee671708eeb380aea05b6"; +var fromAddressPkey = "13a45756bc314465c4ae2ff0eb9ab58cf72453c04604d8fa14393eb25ce96d06"; +var toAddress = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; +var amount = 100; + +var gas = 21000; + +const json2str = (jsonObj) => { + try { + return JSON.stringify(jsonObj); + } + catch (error) { + return null; + } +} + +const makeTxTransferNumericAsset = () => { + //web3_v1.2.9_support + web3.eth.getTransactionCount('0x' + fromAddress).then(_nance => { + var txnCount = _nance; + // NOTE: No need to count up. + + var gasPrice = web3.eth.gasPrice; + + var privKey = Buffer.from(fromAddressPkey, 'hex'); + console.log('##privKey=' + fromAddressPkey); + var rawTx = { + "nonce": web3.utils.toHex(txnCount), + "to": '0x' + toAddress, + "value": amount, + "gas": gas, + + } + console.log('txnCount=' + web3.utils.toHex(txnCount)); + console.log('##rawTx=' + json2str(rawTx)); + var tx = new Tx(rawTx, { common: customCommon },); + tx.sign(privKey); + var serializedTx = tx.serialize(); + var serializedTxHex = '0x' + serializedTx.toString('hex'); + console.log('##serializedTxHex=' + serializedTxHex); + + var func = "sendRawTransaction"; + + var args = { + serializedTx: serializedTxHex + }; + // function param + const requestData = { + contract: {}, // NOTE: Since contract does not need to be specified, specify an empty object. + method: {type: "web3Eth", command: "sendRawTransaction"}, + args: {"args": [serializedTxHex]} + }; + + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + socket.emit('request2', requestData); + }) +} + + +socket.on('connect_error', (err) => { + console.log('####connect_error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('connect_timeout', (err) => { + console.log('####Error:', err); + // end communication + socket.disconnect(); + process.exit(0); +}); + +socket.on('error', (err) => { + console.log('####Error:', err); +}); + +socket.on('eventReceived', function (res) { + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); +}); + + +const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); +} + +// request StartMonitor +const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); +} + + +setTimeout(requestStartMonitor, 2000); +setTimeout(makeTxTransferNumericAsset, 4000); + +} diff --git a/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendSignedTransaction.js b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendSignedTransaction.js deleted file mode 100644 index 97db8c8e32..0000000000 --- a/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_sendSignedTransaction.js +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2019-2020 Fujitsu Laboratories Ltd. - * SPDX-License-Identifier: Apache-2.0 - * - * validatrorDriver_sendRawTransaction.js - */ - -//////// -// Usage -// 1) Set parameter to parameter variable -// [parameter variables of sendRawTransaction] fromAddress,fromAddressPkey,toAddress,amount,amount -// 2) execute -// -//////// - -// Validator test program.(socket.io client) -var io = require('socket.io-client'); -var config = require('config'); - -// Specify the server (Validator) of the communication destination -var validatorUrl = config.validatorUrl; -console.log('validatorUrl: ' + validatorUrl); -var options = { - rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used - reconnection : false, - timeout : 20000 -}; -var socket = io(validatorUrl, options); - -// for signing -var Tx = require('ethereumjs-tx'); -const Web3 = require('web3'); -var gethUrl = config.gethUrl; -console.log('gethUrl: ' + gethUrl); -const provider = new Web3.providers.HttpProvider(gethUrl); -const web3 = new Web3(provider); - - -// for test -// ec1-accounts[0] Address: {686b88b469a06e663e9c1c448ae646e1d6031c73}, pkey: fe47fab697963b8ab1ed82817db727f6b2f7cf522584da89cea82958224f6540 -// ec1-accounts[1] Address: {9bece585f400a2714c99aff66a09814aa75de781}, pkey: ee00377add8fcc7509cde13b974e12d5d7032462689b5398c275ca271c5f2b92 -// ec1-accounts[2] Address: {7370b07a74c4fe2caadf38c6d5788aa77d3a8843}, pkey: 6a6c15c2d03f41f2de94027a5ddde7f6631b72cac8ea102f386ceafa93aab236 -// ec1-accounts[3] Address: {a075cfe69fae5160c4284ee778ea02d6fb4b8f74}, pkey: 34e3c7eaec470daaec0a104448103e685c9ae71f782efa9fc74f3fc0092676da -// ec1-accounts[4] Address: {b5431683f672782f0ebc74830047d824e7d3e05b}, pkey: 2925a764049f0041fb8681a0acc8502388066aaa7228cee5216d01ce4d4117f7 - -// ## Request Params -var fromAddress = "686b88b469a06e663e9c1c448ae646e1d6031c73"; -var fromAddressPkey = "fe47fab697963b8ab1ed82817db727f6b2f7cf522584da89cea82958224f6540"; -var toAddress = "9bece585f400a2714c99aff66a09814aa75de781"; -var amount = 50; - -var gas = 21000; - -function json2str(jsonObj) { - try { - return JSON.stringify(jsonObj); - } - catch (error) { - return null; - } -} - -function makeTxTransferNumericAsset() { - var txnCount = web3.eth.getTransactionCount('0x' + fromAddress); - // NOTE: No need to count up. - - var gasPrice = web3.eth.gasPrice; - - var privKey = Buffer.from(fromAddressPkey, 'hex'); - console.log('##privKey=' + fromAddressPkey); - var rawTx = { - "nonce" : web3.toHex(txnCount), - "to" : '0x' + toAddress, - "value" : amount, - "gas" : gas, - } - console.log('##rawTx=' + json2str(rawTx)); - var tx = new Tx(rawTx); - tx.sign(privKey); - var serializedTx = tx.serialize(); - var serializedTxHex = '0x' + serializedTx.toString('hex'); - console.log('##serializedTxHex=' + serializedTxHex); - return (serializedTxHex); -} - -var func = "sendRawTransaction"; -var args = { - serializedTx : makeTxTransferNumericAsset(), -}; - -// function param -var requestData = { - func : func, - args : args -}; - - - -socket.on('connect_error', (err) => { - console.log('####connect_error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('connect_timeout', (err) => { - console.log('####Error:', err); - // end communication - socket.disconnect(); - process.exit(0); -}); - -socket.on('error', (err) => { - console.log('####Error:', err); -}); - -socket.on('eventReceived', function (res) { - // output the data received from the client - console.log('#[recv]eventReceived, res: ' + json2str(res)); -}); - - -function requestStopMonitor() { - console.log('##exec requestStopMonitor()'); - socket.emit('stopMonitor'); - - setTimeout(function(){ - // end communication - socket.disconnect(); - process.exit(0); - },5000); -} - -// request StartMonitor -function requestStartMonitor() { - console.log('##exec requestStartMonitor()'); - socket.emit('startMonitor'); - - setTimeout(requestStopMonitor,15000); -} - - -function sendRequest() { - // - console.log('exec sendRequest()'); - console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); -} - -setTimeout(requestStartMonitor, 2000); -setTimeout(sendRequest, 4000); diff --git a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_getNumericBalance.js b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_transferNumericAsset.ts similarity index 67% rename from packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_getNumericBalance.js rename to packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_transferNumericAsset.ts index 41d9bc914d..364bad8ac0 100644 --- a/packages/ledger-plugin/go-ethereum-ts/validator/unit-test/validatorDriver_getNumericBalance.js +++ b/packages/ledger-plugin/go-ethereum/validator/unit-test/validatorDriver_transferNumericAsset.ts @@ -2,18 +2,20 @@ * Copyright 2019-2020 Fujitsu Laboratories Ltd. * SPDX-License-Identifier: Apache-2.0 * - * validatorDriver_getNumericBalance.js + * validatorDriver_transferNumericAsset.js */ //////// // Usage // 1) Set parameter to parameter variable -// [parameter variables of getNumericBalance] referredAddress +// [parameter variables of transferNumericAsset] fromAddress,toAddress,amount // 2) Specify the function to execute with "requestData" // 3) execute // //////// +{ + // Validator test program.(socket.io client) var io = require('socket.io-client'); var config = require('config'); @@ -35,22 +37,41 @@ var socket = io(validatorUrl, options); // ec1-accounts[3] Address: {9d624f7995e8bd70251f8265f2f9f2b49f169c55} // ec1-accounts[4] Address: {2666a32bf7594ab5395d766dcfbf03d557dab538} -// ## Request for "getNumericBalance" -var referedAddress = "36e146d5afab61ab125ee671708eeb380aea05b6"; -var func1 = "getNumericBalance"; -var args1 = { - referedAddress : referedAddress + +// ## Request for "transferNumericAsset" +var fromAddress = "36e146d5afab61ab125ee671708eeb380aea05b6"; +var toAddress = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97"; +var amount = 50; +var func2 = "transferNumericAsset"; +var args2 = { + fromAddress : fromAddress, + toAddress : toAddress, + amount : amount }; +const reqID = "reqID_002"; + // function param -var requestData = { - func : func1, // func1 or func1 - args : args1 // arg1 or arg1 +//var requestData = { +// contract: {}, +// method: {"method": func2}, +// args: {"args": [args2]} +//}; +const requestData = { + contract: {}, // NOTE: Since contract does not need to be specified, specify an empty object. + method: {type: "web3Eth", command: "sendTransaction"}, + args: {"args": [ + { + "from" : fromAddress, + "to" : toAddress, + "value" : amount + } + ]}, + reqID: reqID }; - -function json2str(jsonObj) { +const json2str = (jsonObj) => { try { return JSON.stringify(jsonObj); } @@ -84,7 +105,7 @@ socket.on('eventReceived', function (res) { }); -function requestStopMonitor() { +const requestStopMonitor = () => { console.log('##exec requestStopMonitor()'); socket.emit('stopMonitor'); @@ -96,7 +117,7 @@ function requestStopMonitor() { } // request StartMonitor -function requestStartMonitor() { +const requestStartMonitor = () => { console.log('##exec requestStartMonitor()'); socket.emit('startMonitor'); @@ -104,12 +125,14 @@ function requestStartMonitor() { } -function sendRequest() { +const sendRequest = () => { // console.log('exec sendRequest()'); console.log('#[send]requestData: ' + json2str(requestData)); - socket.emit('request', requestData); + socket.emit('request2', requestData); } setTimeout(requestStartMonitor, 2000); setTimeout(sendRequest, 4000); + +} diff --git a/packages/package.json b/packages/package.json index 21115ca6b2..61feddbd8f 100644 --- a/packages/package.json +++ b/packages/package.json @@ -1,93 +1,13 @@ { - "name": "@hyperledger/cactus", + "name": "packages", "private": true, "scripts": { - "run-ci": "./tools/ci.sh", - "configure": "lerna clean --yes && lerna bootstrap && npm-run-all build generate-api-server-config", - "generate-api-server-config": "node ./tools/generate-api-server-config.js", - "start:api-server": "node ./packages/cactus-cmd-api-server/dist/lib/main/typescript/cmd/cactus-api.js --config-file=.config.json", - "start:cockpit": "lerna run --scope '*/cactus-cockpit' --stream serve:proxy", - "export-open-api-spec": "ts-node -e 'import(\"./packages/cactus-cmd-api-server/src/main/typescript/openapi-spec\").then((x) => x.exportToFileSystemAsJson());'", - "pregenerate-sdk": "npm-run-all export-open-api-spec", - "generate-sdk": "openapi-generator generate --input-spec cactus-openapi-spec.json -g typescript-axios -o packages/cactus-sdk/src/main/typescript/generated/openapi/typescript-axios/", - "clean": "lerna exec --stream --ignore '*/*cockpit' -- del-cli dist/** && del-cli packages/cactus-sdk/src/main/typescript/generated/openapi/typescript-axios/*", - "lint": "lerna exec --stream --ignore '*/*cockpit' -- cross-env DEBUG= tslint --project tsconfig.json", - "tsc": "lerna run tsc", - "build": "npm-run-all build:dev build:prod", - "build:prod": "npm-run-all build:prod:backend webpack:prod:web build:prod:frontend", - "build:prod:backend": "npm-run-all webpack:prod:node", - "build:prod:frontend": "lerna run build:prod:frontend", - "build:dev": "npm-run-all build:dev:backend webpack:dev:web build:dev:frontend", - "build:dev:backend": "npm-run-all lint clean generate-sdk tsc webpack:dev:node", - "build:dev:frontend": "lerna run build:dev:frontend", - "build:dev:cmd-api-server": "lerna exec --stream --scope '*/*api-server' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:common": "lerna exec --stream --scope '*/*common' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:core-api": "lerna exec --stream --scope '*/*core-api' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:test-tooling": "lerna exec --stream --scope '*/*test-tooling' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:plugin-ledger-connector-quorum": "lerna exec --stream --scope '*/*connector-quorum' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:plugin-consortium-manual": "lerna exec --stream --scope '*/*manual-consortium' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "build:dev:sdk": "lerna exec --stream --scope '*/*sdk' -- 'del-cli dist/** && tsc --project ./tsconfig.json && webpack --env=dev --target=node --config ../../webpack.config.js'", - "webpack": "npm-run-all webpack:dev webpack:prod", - "webpack:dev": "lerna run webpack:dev", - "webpack:dev:web": "lerna run webpack:dev:web", - "webpack:dev:node": "lerna run webpack:dev:node", - "webpack:prod": "lerna run webpack:prod", - "webpack:prod:web": "lerna run webpack:prod:web", - "webpack:prod:node": "lerna run webpack:prod:node", - "test:all": "tap --jobs=1 --timeout=600 \"packages/cactus-*/src/test/typescript/{unit,integration}/\"", - "test:unit": "tap --timeout=600 \"packages/cactus-*/src/test/typescript/unit/\"", - "test:browser": "karma start karma.conf.js", - "test:integration": "tap --jobs=1 --timeout=600 \"packages/cactus-*/src/test/typescript/integration/\"", - "changelog": "conventional-changelog --infile CHANGELOG.md --outfile CHANGELOG.md && git add CHANGELOG.md", - "commit": "git-cz --signoff", - "prettier": "prettier --write --config .prettierrc.json \"./**/*.{ts,js}\"", - "version": "lerna version --no-push --conventional-commits --sign-git-commit --sign-git-tag", - "package-build": "npm run package-build-ts && npm run package-copy-static-assets", - "package-build-ts": "tsc", - "package-tslint": "tslint -c tslint.json -p tsconfig.json './business-logic-plugin/*.ts' './ledger-plugin/*.ts' './routing-interface/**/*.ts'", - "package-copy-static-assets": "ts-node copyStaticAssets.ts" + "build": "npm run build-ts && npm run copy-static-assets", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json './business-logic-plugin/*.ts' './ledger-plugin/*.ts' './routing-interface/**/*.ts'", + "copy-static-assets": "ts-node copyStaticAssets.ts" }, - "devDependencies": { - "@commitlint/cli": "8.1.0", - "@commitlint/config-conventional": "8.0.0", - "@openapitools/openapi-generator-cli": "1.0.10-4.2.3", - "@types/node-fetch": "2.5.4", - "@types/tape": "4.13.0", - "@types/uuid": "3.4.6", - "cache-loader": "4.1.0", - "commitizen": "4.0.3", - "conventional-changelog-cli": "2.0.28", - "cross-env": "5.2.0", - "cz-conventional-changelog": "3.0.2", - "del-cli": "3.0.0", - "electron": "9.1.1", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.17.3", - "eslint-plugin-node": "9.1.0", - "eslint-plugin-promise": "4.1.1", - "eslint-plugin-standard": "4.0.0", - "husky": "4.2.5", - "inquirer": "7.1.0", - "karma": "5.1.0", - "karma-chrome-launcher": "3.1.0", - "karma-electron": "6.3.1", - "karma-tap": "4.2.0", - "karma-webpack": "4.0.2", - "lerna": "3.20.2", - "lint-staged": "10.2.2", - "npm-run-all": "4.1.5", - "prettier": "2.0.5", - "secp256k1": "4.0.0", - "source-map-loader": "0.2.4", - "tap": "14.10.6", - "tape": "5.0.1", - "ts-loader": "6.2.1", - "ts-node": "8.9.1", - "tslint": "6.0.0", - "typescript": "3.9.3", - "webpack": "4.41.6", - "webpack-bundle-analyzer": "3.6.0", - "webpack-cli": "3.3.11", + "dependencies": { "@types/node": "^14.0.24", "body-parser": "^1.19.0", "cookie-parser": "~1.4.4", @@ -103,19 +23,11 @@ "morgan": "~1.9.1", "shelljs": "^0.8.4", "socket.io": "^2.0.4", + "ts-node": "8.9.1", "web3": "^1.2.9" }, - "config": { - "commitizen": { - "path": "./node_modules/cz-conventional-changelog" - } - }, - "husky": { - "hooks": { - "pre-commit": "lint-staged" - } - }, - "lint-staged": { - "./**/*.{ts,js}": "prettier --write --config .prettierrc.json" + "devDependencies": { + "tslint": "6.0.0", + "typescript": "3.9.3" } } diff --git a/packages/routing-interface/AssetManagement.ts b/packages/routing-interface/AssetManagement.ts new file mode 100644 index 0000000000..d6d35fc484 --- /dev/null +++ b/packages/routing-interface/AssetManagement.ts @@ -0,0 +1,101 @@ +/* + * Copyright 2020 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * AssetManagement.ts + */ + +import { LedgerOperation } from '../business-logic-plugin/LedgerOperation'; +import { LPInfoHolder } from './util/LPInfoHolder'; +import { VerifierBase } from '../ledger-plugin/VerifierBase'; +import { ContractInfoHolder } from './util/ContractInfoHolder'; +import { ConfigUtil } from './util/ConfigUtil'; + +const fs = require('fs'); +const path = require('path'); +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = 'AssetManagement'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +export class AssetManagement { + private connectInfo: LPInfoHolder = null; // connection information + private contractInfoholder: ContractInfoHolder = null; // contract information + private verifierEthereum: VerifierBase = null; + + constructor() { + this.connectInfo = new LPInfoHolder(); + this.contractInfoholder = new ContractInfoHolder(); + } + + addAsset(amount: string): Promise { + return new Promise((resolve, reject) => { + if (this.verifierEthereum === null) { + logger.debug("create verifierEthereum"); + const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("84jUisrs"); + this.verifierEthereum = new VerifierBase(ledgerPluginInfo); + } + + // for Neo + const contractInfo: string = this.contractInfoholder.getContractInfo("AssetContract"); + const contractInfoObj: {} = JSON.parse(contractInfo); + const coinbase = contractInfoObj['_eth']['coinbase']; + const address = contractInfoObj['address']; + const abi = contractInfoObj['abi']; + const contract = { + "address": address, + "abi": abi + }; + const method = {type: "contract", command: "addAsset", function: "sendTransaction"}; + const args = {"args": [amount, {from: coinbase}]}; + + this.verifierEthereum.execSyncFunctionNeo(contract, method, args).then(result => { + const response = { + "status": result.status, + "Transaction hash": result.data + } + resolve(response); + }).catch((err) => { + logger.error(err); + reject(err); + }); + + }); + } + + getAsset(): Promise { + return new Promise((resolve, reject) => { + if (this.verifierEthereum === null) { + logger.debug("create verifierEthereum"); + const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("84jUisrs"); + this.verifierEthereum = new VerifierBase(ledgerPluginInfo); + } + + // for Neo + const contractInfo: string = this.contractInfoholder.getContractInfo("AssetContract"); + const contractInfoObj: {} = JSON.parse(contractInfo); + const address = contractInfoObj['address']; + const abi = contractInfoObj['abi']; + const contract = { + "address": address, + "abi": abi + }; + const method = {type: "contract", command: "getAsset", function: "call"}; + const args = {"args": []}; + + this.verifierEthereum.execSyncFunctionNeo(contract, method, args).then(result => { + const response = { + "status": result.status, + "asset": parseFloat(result.data) + } + resolve(response); + }).catch((err) => { + logger.error(err); + reject(err); + }); + + }); + } + +} diff --git a/packages/routing-interface/BalanceManagement.ts b/packages/routing-interface/BalanceManagement.ts index c7643e3a4b..d82d3229ea 100644 --- a/packages/routing-interface/BalanceManagement.ts +++ b/packages/routing-interface/BalanceManagement.ts @@ -5,22 +5,16 @@ * BalanceManagement.ts */ -import { Request } from 'express'; -import { BusinessLogicPlugin } from '../business-logic-plugin/BusinessLogicPlugin'; import { LedgerOperation } from '../business-logic-plugin/LedgerOperation'; -import { BLPRegistry } from './util/BLPRegistry'; import { LPInfoHolder } from './util/LPInfoHolder'; -import { json2str } from '../ledger-plugin/DriverCommon' import { VerifierBase } from '../ledger-plugin/VerifierBase'; -import { VerifierEventListener, LedgerEvent } from '../ledger-plugin/LedgerPlugin'; -import { getTargetBLPInstance } from '../config/BLP_config'; import { ConfigUtil } from './util/ConfigUtil'; const fs = require('fs'); const path = require('path'); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; -const moduleName = 'TransactionManagement'; +const moduleName = 'BalanceManagement'; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; @@ -39,13 +33,23 @@ export class BalanceManagement { const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("84jUisrs"); this.verifierEthereum = new VerifierBase(ledgerPluginInfo); } - - const execData = {"referedAddress": account}; - const ledgerOperation: LedgerOperation = new LedgerOperation("getNumericBalance", "", execData); - this.verifierEthereum.execSyncFunction(ledgerOperation).then(result => { - resolve(result); - }).catch(function (err) { + // for LedgerOperation + // const execData = {"referedAddress": account}; + // const ledgerOperation: LedgerOperation = new LedgerOperation("getNumericBalance", "", execData); + + // for Neo + const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. + const method = {type: "web3Eth", command: "getBalance"}; + const args = {"args": [account]}; + + this.verifierEthereum.execSyncFunctionNeo(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/packages/routing-interface/CarsManagement.ts b/packages/routing-interface/CarsManagement.ts new file mode 100644 index 0000000000..f64601f4f4 --- /dev/null +++ b/packages/routing-interface/CarsManagement.ts @@ -0,0 +1,73 @@ +/* + * Copyright 2020 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * CarsManagement.ts + */ + +import { LedgerOperation } from '../business-logic-plugin/LedgerOperation'; +import { LPInfoHolder } from './util/LPInfoHolder'; +import { VerifierBase } from '../ledger-plugin/VerifierBase'; +import { ConfigUtil } from './util/ConfigUtil'; + +const fs = require('fs'); +const path = require('path'); +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = 'CarsManagement'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +export class CarsManagement { + private connectInfo: LPInfoHolder = null; // connection information + private verifierFabric: VerifierBase = null; + + constructor() { + this.connectInfo = new LPInfoHolder(); + } + + queryCar(carID: string): Promise { + return new Promise((resolve, reject) => { + if (this.verifierFabric === null) { + logger.debug("create verifierFabric"); + const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("r9IS4dDf"); + this.verifierFabric = new VerifierBase(ledgerPluginInfo); + } + + const contract = {"channelName": "mychannel", "contractName": "fabcar"}; + const method = {type: "evaluateTransaction", command: "queryCar"}; + const args = {"args": [carID]}; + + this.verifierFabric.execSyncFunctionNeo(contract, method, args).then(result => { + resolve(result); + }).catch((err) => { + logger.error(err); + reject(err); + }); + + }); + } + + queryAllCars(): Promise { + return new Promise((resolve, reject) => { + if (this.verifierFabric === null) { + logger.debug("create verifierFabric"); + const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("r9IS4dDf"); + this.verifierFabric = new VerifierBase(ledgerPluginInfo); + } + + const contract = {"channelName": "mychannel", "contractName": "fabcar"}; + const method = {type: "evaluateTransaction", command: "queryAllCars"}; + const args = {"args": []}; + + this.verifierFabric.execSyncFunctionNeo(contract, method, args).then(result => { + resolve(result); + }).catch((err) => { + logger.error(err); + reject(err); + }); + + }); + } + +} diff --git a/packages/routing-interface/routes/asset.ts b/packages/routing-interface/routes/asset.ts new file mode 100644 index 0000000000..34edd4832a --- /dev/null +++ b/packages/routing-interface/routes/asset.ts @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * asset.ts + */ + +import { Router, NextFunction, Request, Response } from 'express'; +import { RIFUtil } from '../util/RIFUtil'; +import { ConfigUtil } from '../util/ConfigUtil'; +import { RIFError, BadRequestError, InternalServerError } from '../RIFError'; +import { AssetManagement } from '../AssetManagement'; + +const fs = require('fs'); +const path = require('path'); +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = 'asset'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +const router: Router = Router(); +const assetManagement: AssetManagement = new AssetManagement(); + +// POST : add asset. +router.post('/', (req: Request, res: Response, next: NextFunction) => { + try { + assetManagement.addAsset(req.body.amount).then(result => { + logger.debug("result(addAsset) = " + JSON.stringify(result)); + res.status(200).json(result); + }).catch((err) => { + logger.error(err); + }); + + } catch (err) { + logger.error(`##err name: ${err.constructor.name}`); + + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + + logger.error(`##err in asset: ${err}`); + next(err); + } +}); + +// GET : get asset. +router.get('/', (req: Request, res: Response, next: NextFunction) => { + try { + + assetManagement.getAsset().then(result => { + logger.debug("result(getAsset) = " + JSON.stringify(result)); + res.status(200).json(result); + }).catch((err) => { + logger.error(err); + }); + + } catch (err) { + logger.error(`##err name: ${err.constructor.name}`); + + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + + logger.error(`##err in asset: ${err}`); + next(err); + } +}); + +export default router; diff --git a/packages/routing-interface/routes/balance.ts b/packages/routing-interface/routes/balance.ts index a83658dc90..ab66bba3eb 100644 --- a/packages/routing-interface/routes/balance.ts +++ b/packages/routing-interface/routes/balance.ts @@ -29,7 +29,7 @@ router.get('/:account', (req: Request, res: Response, next: NextFunction) => { balanceManagement.getBalance(req.params.account).then(result => { logger.debug("result(getBalance) = " + JSON.stringify(result)); res.status(200).json(result); - }).catch(function (err) { + }).catch((err) => { logger.error(err); }); diff --git a/packages/routing-interface/routes/cars.ts b/packages/routing-interface/routes/cars.ts new file mode 100644 index 0000000000..e818efca35 --- /dev/null +++ b/packages/routing-interface/routes/cars.ts @@ -0,0 +1,79 @@ +/* + * Copyright 2020 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * cars.ts + */ + +import { Router, NextFunction, Request, Response } from 'express'; +import { RIFUtil } from '../util/RIFUtil'; +import { ConfigUtil } from '../util/ConfigUtil'; +import { RIFError, BadRequestError, InternalServerError } from '../RIFError'; +import { CarsManagement } from '../CarsManagement'; + +const fs = require('fs'); +const path = require('path'); +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = 'cars'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +const router: Router = Router(); +const carsManagement: CarsManagement = new CarsManagement(); + +/* GET query car. */ +router.get('/:carID', (req: Request, res: Response, next: NextFunction) => { + try { + logger.debug(`start queryCar`); + + carsManagement.queryCar(req.params.carID).then(result => { + logger.debug("result(queryCar) = " + JSON.stringify(result)); + res.status(200).json(result); + }).catch((err) => { + logger.error(err); + }); + + } catch (err) { + logger.error(`##(queryCar)err name: ${err.constructor.name}`); + + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + + logger.error(`##err in queryCar: ${err}`); + next(err); + } +}); + +/* GET query all cars. */ +router.get('/', (req: Request, res: Response, next: NextFunction) => { + try { + logger.debug(`start queryAllCars`); + + carsManagement.queryAllCars().then(result => { + logger.debug("result(queryAllCars) = " + JSON.stringify(result)); + res.status(200).json(result); + }).catch((err) => { + logger.error(err); + }); + + } catch (err) { + logger.error(`##(queryAllCars)err name: ${err.constructor.name}`); + + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + + logger.error(`##err in queryAllCars: ${err}`); + next(err); + } +}); + +export default router; diff --git a/packages/routing-interface/util/ContractInfoHolder.ts b/packages/routing-interface/util/ContractInfoHolder.ts new file mode 100644 index 0000000000..8c47f33ffb --- /dev/null +++ b/packages/routing-interface/util/ContractInfoHolder.ts @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * ContractInfoHolder.ts + */ + +import { DBAccess } from './DBAccess'; +import { ConfigUtil } from '../util/ConfigUtil'; + +const fs = require('fs'); +const path = require('path'); +const config: any = ConfigUtil.getConfig(); +import { getLogger } from "log4js"; +const moduleName = 'ContractInfoHolder'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +export class ContractInfoHolder { + contractInfo: [] = []; + + constructor() { + // TODO: Get contract information for all contracts + const dbAccess: DBAccess = new DBAccess(); + this.contractInfo = dbAccess.getContractInfo(); + } + + getContractInfo(contractName?: string): string { + // TODO: Get information about the specified LedgerPlugin + + if (contractName) { + let ret: string = ""; + this.contractInfo.forEach(info => { + if (info['contractName'] === contractName) { + ret = JSON.stringify(info); + } + }); + if (ret === "") { + logger.warn('ContractInfo is Not Found : contractName = ' + contractName); + } + return ret; + } else { + return JSON.stringify(this.contractInfo); + } + } +} diff --git a/packages/routing-interface/util/DBAccess.ts b/packages/routing-interface/util/DBAccess.ts index ac474b6610..8642854635 100644 --- a/packages/routing-interface/util/DBAccess.ts +++ b/packages/routing-interface/util/DBAccess.ts @@ -11,9 +11,11 @@ const fs = require('fs'); const path = require('path'); const configDefault: any = ConfigUtil.getConfig(); const configVerifier: any = JSON.parse(fs.readFileSync(path.resolve(__dirname, "../../config/verifier-config.json"), 'utf8')); +const configContract: any = JSON.parse(fs.readFileSync(path.resolve(__dirname, "../../config/contractInfo.json"), 'utf8')); export class DBAccess { ledgerPluginInfo: []; + contractInfo: []; blpRegistryInfo: []; constructor() { @@ -27,6 +29,13 @@ export class DBAccess { return this.ledgerPluginInfo; } + getContractInfo(): [] { + // TODO: Future access to DB for contract information + + this.contractInfo = configContract.contractInfo; + return this.contractInfo; + } + getBLPRegistryInfo(): [] { // TODO: Future access to DB for business logic plugin information diff --git a/packages/script-build-packages.sh b/packages/script-build-packages.sh index 9a5ee0f179..0836a0e9fe 100755 --- a/packages/script-build-packages.sh +++ b/packages/script-build-packages.sh @@ -1,4 +1,4 @@ ## Build packages echo "[process] Build packages" npm install -num run build \ No newline at end of file +npm run build \ No newline at end of file diff --git a/packages/tsconfig.json b/packages/tsconfig.json index 04d5bd3a94..a67b4c7d65 100644 --- a/packages/tsconfig.json +++ b/packages/tsconfig.json @@ -69,7 +69,10 @@ "outDir": "../dist/packages" }, "include": [ - "./**/*.ts", + "./business-logic-plugin/*.ts", + "./config/*.ts", + "./ledger-plugin/*.ts", + "./routing-interface/**/*.ts", ], "exclude": [ "copyStaticAssets.ts" diff --git a/tools/docker/fabric14-fabcar-testnet/script-start-docker.sh b/tools/docker/fabric14-fabcar-testnet/script-start-docker.sh index 379f522ec1..3d7dc653f3 100755 --- a/tools/docker/fabric14-fabcar-testnet/script-start-docker.sh +++ b/tools/docker/fabric14-fabcar-testnet/script-start-docker.sh @@ -1,6 +1,7 @@ echo "[process] start docker environment for Fabric testnet" curl -sSL https://bit.ly/2ysbOFE | bash -s -- 1.4.1 1.4.1 cp -a wallet fabric-samples/fabcar/javascript +cp -a wallet ../../../examples/cartrade/script-test-getFunctions/fabric cd fabric-samples/fabcar ./startFabric.sh cd javascript diff --git a/tools/docker/geth-testnet/data-geth1/genesis.json b/tools/docker/geth-testnet/data-geth1/genesis.json index 748c449724..5d2f5701ee 100644 --- a/tools/docker/geth-testnet/data-geth1/genesis.json +++ b/tools/docker/geth-testnet/data-geth1/genesis.json @@ -1,20 +1,22 @@ { - "config": { - "chainId": 10, - "homesteadBlock": 0, - "eip155Block": 0, - "eip158Block": 0 - }, - "alloc" : { - "ec709e1774f0ce4aba47b52a499f9abaaa159f71": - {"balance":"100000000000000000000000000"} - }, - "coinbase" : "0x3333333333333333333333333333333333333333", - "difficulty" : "0x4000", - "extraData" : "", - "gasLimit" : "0x8000000", - "nonce" : "0x0000000000000042", - "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000", - "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000", - "timestamp" : "0x00" -} + "config": { + "chainId": 10, + "homesteadBlock": 0, + "eip155Block": 0, + "eip158Block": 0 + }, + "alloc" : { + "ec709e1774f0ce4aba47b52a499f9abaaa159f71": + {"balance":"100000000000000000000000000"}, + "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97": + {"balance":"100000"} + }, + "coinbase" : "0x3333333333333333333333333333333333333333", + "difficulty" : "0x4000", + "extraData" : "", + "gasLimit" : "0x8000000", + "nonce" : "0x0000000000000042", + "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000", + "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000", + "timestamp" : "0x00" + } \ No newline at end of file