Skip to content

Commit

Permalink
feat(LedgerPlugin): add TransactionSigner on LedgerPlugin
Browse files Browse the repository at this point in the history
Signed-off-by: Takuma TAKEUCHI <takeuchi.takuma@fujitsu.com>
  • Loading branch information
takeutak committed Mar 26, 2021
1 parent dc8c564 commit df3b266
Show file tree
Hide file tree
Showing 40 changed files with 950 additions and 1,098 deletions.
10 changes: 8 additions & 2 deletions examples/cartrade/AssetManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,12 @@ export class AssetManagement {
"abi": abi
};
const method = {type: "contract", command: "addAsset", function: "sendTransaction"};
const template = "default";
const args = {"args": [amount, {from: coinbase}]};
// const method = "default";
// const args = {"method": {type: "contract", command: "addAsset", function: "sendTransaction"}, "args": {"args": [amount, {from: coinbase}]}};

this.verifierEthereum.execSyncFunctionNeo(contract, method, args).then(result => {
this.verifierEthereum.execSyncFunction(contract, method, template, args).then(result => {
const response = {
"status": result.status,
"Transaction hash": result.data
Expand Down Expand Up @@ -81,9 +84,12 @@ export class AssetManagement {
"abi": abi
};
const method = {type: "contract", command: "getAsset", function: "call"};
const template = "default";
const args = {"args": []};
// const method = "default";
// const args = {"method": {type: "contract", command: "getAsset", function: "call"}, "args": {"args": []}};

this.verifierEthereum.execSyncFunctionNeo(contract, method, args).then(result => {
this.verifierEthereum.execSyncFunction(contract, method, template, args).then(result => {
const response = {
"status": result.status,
"asset": parseFloat(result.data)
Expand Down
5 changes: 4 additions & 1 deletion examples/cartrade/BalanceManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ export class BalanceManagement {
// for Neo
const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object.
const method = {type: "web3Eth", command: "getBalance"};
const template = "default";
const args = {"args": [account]};
// const method = "default";
// const args = {"method": {type: "web3Eth", command: "getBalance"},"args": {"args": [account]}};

this.verifierEthereum.execSyncFunctionNeo(contract, method, args).then(result => {
this.verifierEthereum.execSyncFunction(contract, method, template, args).then(result => {
const response = {
"status": result.status,
"amount": parseFloat(result.data)
Expand Down
18 changes: 15 additions & 3 deletions examples/cartrade/BusinessLogicCartrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,14 @@ export class BusinessLogicCartrade extends BusinessLogicBase {
logger.debug('firstTransaction data : ' + JSON.stringify(result.data));
const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object.
const method = {type: "web3Eth", command: "sendRawTransaction"};
const template = "default";
const args = {"args": [result.data["serializedTx"]]};
// const method = "default";
// const args = {"method": {type: "web3Eth", command: "sendRawTransaction"},"args": {"args": [result.data["serializedTx"]]}};

// Run Verifier (Fabric)
verifierEthereum.requestLedgerOperationNeo(contract, method, args);
//verifierEthereum.requestLedgerOperationNeo(contract, method, args);
verifierEthereum.sendSignedTransaction(contract, method, template, args);
})
.catch(err => {
logger.error(err);
Expand Down Expand Up @@ -181,10 +185,14 @@ export class BusinessLogicCartrade extends BusinessLogicBase {
//logger.debug('secondTransaction data : ' + JSON.stringify(result.data));
const contract = {"channelName": "mychannel"};
const method = {"type": "sendSignedTransaction"};
const template = "default";
const args = {"args": [result.data]};
// const method = "default";
// const args = {"method": {"type": "sendSignedTransaction"},"args": {"args": [result.data]}};

// Run Verifier (Fabric)
verifierFabric.requestLedgerOperationNeo(contract, method, args);
// verifierFabric.requestLedgerOperationNeo(contract, method, args);
verifierFabric.sendSignedTransaction(contract, method, template, args);
})
.catch(err => {
logger.error(err);
Expand Down Expand Up @@ -234,10 +242,14 @@ export class BusinessLogicCartrade extends BusinessLogicBase {
// Set Parameter
const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object.
const method = {type: "web3Eth", command: "sendRawTransaction"};
const template = "default";
const args = {"args": [result.data["serializedTx"]]};
// const method = "default";
// const args = {"method": {type: "web3Eth", command: "sendRawTransaction"}, "args": {"args": [result.data["serializedTx"]]}};

// Run Verifier (Fabric)
verifierEthereum.requestLedgerOperationNeo(contract, method, args);
// verifierEthereum.requestLedgerOperationNeo(contract, method, args);
verifierEthereum.sendSignedTransaction(contract, method, template, args);


})
Expand Down
10 changes: 8 additions & 2 deletions examples/cartrade/CarsManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ export class CarsManagement {

const contract = {"channelName": "mychannel", "contractName": "fabcar"};
const method = {type: "evaluateTransaction", command: "queryCar"};
const template = "default";
const args = {"args": [carID]};
// const method = "default";
// const args = {"method": {type: "evaluateTransaction", command: "queryCar"},"args": {"args": [carID]}};

this.verifierFabric.execSyncFunctionNeo(contract, method, args).then(result => {
this.verifierFabric.execSyncFunction(contract, method, template, args).then(result => {
resolve(result);
}).catch((err) => {
logger.error(err);
Expand All @@ -57,9 +60,12 @@ export class CarsManagement {

const contract = {"channelName": "mychannel", "contractName": "fabcar"};
const method = {type: "evaluateTransaction", command: "queryAllCars"};
const template = "default";
const args = {"args": []};
// const method = "default";
// const args = {"method": {type: "evaluateTransaction", command: "queryAllCars"}, "args": {"args": []}};

this.verifierFabric.execSyncFunctionNeo(contract, method, args).then(result => {
this.verifierFabric.execSyncFunction(contract, method, template, args).then(result => {
resolve(result);
}).catch((err) => {
logger.error(err);
Expand Down
108 changes: 108 additions & 0 deletions examples/cartrade/TemplateTradeManagement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Copyright 2021 Hyperledger Cactus Contributors
* SPDX-License-Identifier: Apache-2.0
*
* TemplateTradeManagement.ts
*/

import { Request } from 'express';
import { LPInfoHolder } from '../../packages/routing-interface/util/LPInfoHolder';
import { VerifierBase } from '../../packages/ledger-plugin/VerifierBase';
import { ConfigUtil } from '../../packages/routing-interface/util/ConfigUtil';

const fs = require('fs');
const path = require('path');
const config: any = ConfigUtil.getConfig();
import { getLogger } from "log4js";
const moduleName = 'TemplateTradeManagement';
const logger = getLogger(`${moduleName}`);
logger.level = config.logLevel;

export class TemplateTradeManagement {
private connectInfo: LPInfoHolder = null; // connection information
private verifier: VerifierBase = null;

constructor() {
this.connectInfo = new LPInfoHolder();
}

execTemplateTrade(functionName: string, req: Request): Promise<any> {
return new Promise((resolve, reject) => {
if (this.verifier === null) {
logger.debug("create verifier");
const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("84jUisrs");
this.verifier = new VerifierBase(ledgerPluginInfo);
}

const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object.
const method = {};
const template = req.body.template;
const args = req.body.args;
logger.debug(`##contract: ${contract}, method: ${JSON.stringify(method)}, template: ${template}, args: ${JSON.stringify(args)}`);

// ex.
// contract: {}
// method: "name"
// args: {"tokenID": "token-12345", "contractID": "contract-123456"}

this.verifier.execSyncFunction(contract, method, template, args).then(result => {
const response = {
"status": result.status,
"result": JSON.stringify(result.data)
}
// resolve(response);
resolve(result);
}).catch((err) => {
logger.error(err);
reject(err);
});

});
}

execTemplateTradeAsync(functionName: string, req: Request): string {
// TODO
const tradeID = this.createTradeID();

if (this.verifier === null) {
logger.debug("create verifier");
const ledgerPluginInfo: string = this.connectInfo.getLegerPluginInfo("84jUisrs");
this.verifier = new VerifierBase(ledgerPluginInfo);
}


const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object.
const method = {};
const template = req.body.template;
const args = req.body.args;
logger.debug(`##contract: ${contract}, method: ${method}, args: ${JSON.stringify(args)}`);

// ex.
// contract: {}
// method: "transfer"
// args: {"_from": "account1", "_to": "account2", "value": 100, "tokenID": "token-12345", "contractID": "contract-123456"}

this.verifier.sendSignedTransaction(contract, method, template, args);

return tradeID;
}

createTradeID(): string {
// NOTE: tradeID is "(GMT date when the API was accepted) - (serial number)"

// TODO: Trailing number-generating part not implemented
// NOTE: The last serial number is fixed "001" for 2020/9 months.
const currentTime: Date = new Date();
const tradeID: string = currentTime.getFullYear()
+ ('0' + (currentTime.getMonth() + 1)).slice(-2)
+ ('0' + currentTime.getDate()).slice(-2)
+ ('0' + currentTime.getHours()).slice(-2)
+ ('0' + currentTime.getMinutes()).slice(-2)
+ ('0' + currentTime.getSeconds()).slice(-2)
+ ('00' + currentTime.getMilliseconds()).slice(-3)
+ "-001"; // NOTE: Serial number for the same time. Since the priority is low, it is fixed at "001" at this time.
return tradeID;
}


}
33 changes: 5 additions & 28 deletions examples/cartrade/TransactionEthereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* TransactionEthereum.ts
*/

import { TransactionSigner } from '../../packages/ledger-plugin/util/TransactionSigner';

const ethJsCommon = require('ethereumjs-common').default;
const ethJsTx = require('ethereumjs-tx').Transaction;
const libWeb3 = require('web3');
Expand All @@ -28,17 +30,6 @@ export function makeRawTransaction(txParam: { fromAddress: string, fromAddressPk
const provider = new libWeb3.providers.HttpProvider(config.cartradeInfo.ethereum.gethURL);
const web3 = new libWeb3(provider);

// ethereumjs-tx2.1.2_support
const customCommon = ethJsCommon.forCustomChain(
config.cartradeInfo.ethereum.network,
{
name: config.cartradeInfo.ethereum.chainName,
networkId: config.cartradeInfo.ethereum.networkID,
chainId: config.cartradeInfo.ethereum.chainID,
},
config.cartradeInfo.ethereum.hardfork
);

// web3_v1.2.9_support
web3.eth.getTransactionCount(txParam.fromAddress)
.then(_nonce => {
Expand All @@ -58,31 +49,18 @@ export function makeRawTransaction(txParam: { fromAddress: string, fromAddressPk
logger.debug(`#####(B) _nonce: ${_nonce}, latestNonce: ${latestNonce}, txnCount: ${txnCount}`);
setLatestNonce(txParam.fromAddress, txnCount);

const privKey: Buffer = Buffer.from(txParam.fromAddressPkey, 'hex');
logger.debug('##privKey=' + txParam.fromAddressPkey);
const rawTx: { nonce: number, to: string, value: number, gas: number } = {
"nonce": web3.utils.toHex(txnCount),
"to": txParam.toAddress,
"value": txParam.amount,
"gas": txParam.gas,
}
logger.debug('txnCount=' + web3.utils.toHex(txnCount));
logger.debug('##rawTx=' + JSON.stringify(rawTx));
const tx = new ethJsTx(rawTx, { common: customCommon });
tx.sign(privKey);

// Get Transaction ID
const hash: Buffer = tx.hash(true);
const txId: string = '0x' + hash.toString('hex')
logger.debug('##txId=' + txId);

const serializedTx: Buffer = tx.serialize();
const serializedTxHex: string = '0x' + serializedTx.toString('hex');
logger.debug('##serializedTxHex=' + serializedTxHex);
const signedTx = TransactionSigner.signTxEthereum(rawTx, txParam.fromAddressPkey);

const result: { data: {}, txId: string } = {
data: { serializedTx: serializedTxHex },
txId: txId
data: { serializedTx: signedTx["serializedTx"] },
txId: signedTx["txId"]
}

return resolve(result);
Expand All @@ -106,4 +84,3 @@ function getLatestNonce(fromAddress: string): number {
function setLatestNonce(fromAddress: string, nonce: number): void {
mapFromAddressNonce.set(fromAddress, nonce);
}

Loading

0 comments on commit df3b266

Please sign in to comment.