Skip to content

Commit

Permalink
refactored the code in satp.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
outsidethecode committed Jan 14, 2024
1 parent 742c1f5 commit e06737d
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 140 deletions.
129 changes: 52 additions & 77 deletions weaver/core/drivers/fabric-driver/server/satp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import satp_grpc_pb from '@hyperledger/cacti-weaver-protos-js/relay/satp_grpc_pb
import driverPb from '@hyperledger/cacti-weaver-protos-js/driver/driver_pb';
import logger from './logger';
import { credentials } from '@grpc/grpc-js';

import { getNetworkConfig } from '../../../../samples/fabric/fabric-cli/src/helpers/helpers'
import { SatpAssetManager, HashFunctions } from '@hyperledger/cacti-weaver-sdk-fabric'

import fs from 'fs';
import path from 'path';
import { fabricHelper } from '../../../../samples/fabric/fabric-cli/src/helpers/fabric-functions';
import { fabricHelper, getKeyAndCertForRemoteRequestbyUserName } from '@hyperledger/cacti-weaver-fabric-cli/helpers/fabric-functions';
import { Gateway, Network, Wallets, Contract, X509Identity } from 'fabric-network'
import { getNetworkGateway } from "./fabric-code";
import { getDriverKeyCert } from './walletSetup';

const DB_NAME: string = "driverdb";
const DRIVER_ERROR_CONSTANTS = JSON.parse(
Expand All @@ -18,6 +18,10 @@ const DRIVER_ERROR_CONSTANTS = JSON.parse(
).toString(),
);

const getWallet = (walletPath: string) => {
return Wallets.newFileSystemWallet(walletPath);
};

async function performLockHelper(
performLockRequest: driverPb.PerformLockRequest,
networkName: string
Expand All @@ -30,14 +34,22 @@ async function performLockHelper(
performLockRequest2['timeout-duration'] = parseInt('3600');
performLockRequest2['locker'] = 'alice';
performLockRequest2['recipient'] = 'bob';
performLockRequest2['lockerWalletPath'] = '../wallet-network1/alice.id';
performLockRequest2['recipientWalletPath'] = '../wallet-network1/bob.id';
performLockRequest2['param'] = 'bond01:a05';
performLockRequest2['channel'] = 'mychannel';
performLockRequest2['chaincode-id'] = 'satpsimpleasset';

// Locker and recipient
const locker = performLockRequest2['locker'];
const recipient = performLockRequest2['recipient'];
const lockerWalletPath = performLockRequest2['lockerWalletPath'];
const recipientWalletPath = performLockRequest2['recipientWalletPath'];
let hashFn = performLockRequest2['hash_fn'];
let hashBase64 = performLockRequest2['hashBase64'];
const targetNetwork = performLockRequest2['target-network'];
const channel = performLockRequest2['channel'];
const chaincodeId = performLockRequest2['chaincode-id'];

// Hash
let hash: HashFunctions.Hash
Expand Down Expand Up @@ -67,29 +79,13 @@ async function performLockHelper(
timeout2 = currTime + 2 * performLockRequest2['timeout-duration']
}

const params = performLockRequest2['param'].split(':')
const netConfig = getNetworkConfig(targetNetwork)

if (!netConfig.connProfilePath || !netConfig.channelName || !netConfig.chaincode) {
console.error(
`Please use a valid --target-network. No valid environment found for ${targetNetwork} `
)
return
}

const network = await fabricHelper({
channel: netConfig.channelName,
contractName: netConfig.chaincode,
connProfilePath: netConfig.connProfilePath,
networkName: targetNetwork,
mspId: netConfig.mspId,
userString: locker
})
let gateway: Gateway = await getNetworkGateway(networkName);
const network: Network = await gateway.getNetwork(channel);
const contract = network.getContract(chaincodeId);

const lockerId = await network.wallet.get(locker)
const lockerCert = Buffer.from((lockerId).credentials.certificate).toString('base64')
const recipientId = await network.wallet.get(recipient)
const recipientCert = Buffer.from((recipientId).credentials.certificate).toString('base64')
const params = performLockRequest2['param'].split(':')
const lockerCert = Buffer.from(lockerWalletPath).toString('base64')
const recipientCert = Buffer.from(recipientWalletPath).toString('base64')

var funcToCall, asset

Expand All @@ -104,7 +100,7 @@ async function performLockHelper(
console.info(`Asset Lock: Lock ${asset}:\n`);
try {
console.info(`Trying ${asset} Lock: ${params[0]}, ${params[1]} by ${locker} for ${recipient}`)
const res = await funcToCall(network.contract,
const res = await funcToCall(contract,
params[0],
params[1],
recipientCert,
Expand All @@ -121,7 +117,7 @@ async function performLockHelper(
console.error(`Could not Lock ${asset} in ${targetNetwork}`)
}

await network.gateway.disconnect()
await gateway.disconnect()
logger.info('Gateways disconnected.')

const client = getRelayClientForAssetStatusResponse();
Expand All @@ -148,6 +144,8 @@ async function createAssetHelper(
createAssetRequest2['issuer'] = 'admin';
createAssetRequest2['facevalue'] = '300';
createAssetRequest2['maturitydate'] = '05 May 48 00:00 MST';
createAssetRequest2['channel'] = 'mychannel';
createAssetRequest2['chaincode-id'] = 'satpsimpleasset';

const targetNetwork = createAssetRequest2['target-network'];
const owner = createAssetRequest2['owner'];
Expand All @@ -159,50 +157,36 @@ async function createAssetHelper(
const maturitydate = createAssetRequest2['maturitydate'];
const tokenassettype = createAssetRequest2['tokenassettype'];
const numunits = createAssetRequest2['numunits'];
const channel = createAssetRequest2['channel'];
const chaincodeId = createAssetRequest2['chaincode-id'];

const netConfig = getNetworkConfig(targetNetwork)
console.info(netConfig)
if (!netConfig.connProfilePath || !netConfig.channelName || !netConfig.chaincode) {
console.error(
`Please use a valid --target-network. No valid environment found for ${targetNetwork} `
)
return
}

let gateway: Gateway = await getNetworkGateway(networkName);
const network: Network = await gateway.getNetwork(channel);
const contract = network.getContract(chaincodeId);
const currentQuery = {
channel: netConfig.channelName,
contractName: netConfig.chaincode,
channel: channel,
contractName: chaincodeId,
ccFunc: '',
args: []
}

const network = await fabricHelper({
channel: netConfig.channelName,
contractName: netConfig.chaincode,
connProfilePath: netConfig.connProfilePath,
networkName: targetNetwork,
mspId: netConfig.mspId,
userString: owner,
registerUser: false
})

const userId = await network.wallet.get(owner)
const userCert = Buffer.from((userId).credentials.certificate).toString('base64')
const driverkeyCert = await getDriverKeyCert();
const certificate = Buffer.from(driverkeyCert.cert).toString('base64')

if (ccType == 'bond') {
currentQuery.ccFunc = 'CreateAsset'
currentQuery.args = [...currentQuery.args, assetType, id, userCert, issuer, facevalue, maturitydate]
currentQuery.args = [...currentQuery.args, assetType, id, certificate, issuer, facevalue, maturitydate]
} else if (ccType == 'token') {
currentQuery.ccFunc = 'IssueTokenAssets'
currentQuery.args = [...currentQuery.args, tokenassettype, numunits, userCert]
currentQuery.args = [...currentQuery.args, tokenassettype, numunits, certificate]
} else {
throw new Error(`Unrecognized asset category: ${ccType}`)
}
console.log(currentQuery)

try {
console.info(`Trying creating the asset: type: ${ccType}, id: ${id}, by: ${owner}, facevalue: ${facevalue}, maturitydate: ${maturitydate}`)
const read = await network.contract.submitTransaction(currentQuery.ccFunc, ...currentQuery.args)
const read = await contract.submitTransaction(currentQuery.ccFunc, ...currentQuery.args)
const state = Buffer.from(read).toString()
if (state) {
logger.debug(`Response From Network: ${state}`)
Expand All @@ -215,7 +199,7 @@ async function createAssetHelper(
throw new Error(error)
}

await network.gateway.disconnect()
await gateway.disconnect()
logger.info('Gateways disconnected.')

const client = getRelayClientForAssetStatusResponse();
Expand Down Expand Up @@ -255,13 +239,21 @@ async function assignAssetHelper(
assignAssetRequest2['hash_fn'] = '';
assignAssetRequest2['secret'] = 'secrettext';
assignAssetRequest2['param'] = 'bond01:a0demo';
assignAssetRequest2['channel'] = 'mychannel';
assignAssetRequest2['chaincode-id'] = 'satpsimpleasset';

const targetNetwork = assignAssetRequest2['target-network'];
const locker = assignAssetRequest2['locker'];
const recipient = assignAssetRequest2['recipient'];
const fungible = assignAssetRequest2['fungible'];
const hashFn = assignAssetRequest2['hash_fn'];
const secret = assignAssetRequest2['secret'];
const channel = assignAssetRequest2['channel'];
const chaincodeId = assignAssetRequest2['chaincode-id'];

let gateway: Gateway = await getNetworkGateway(networkName);
const network: Network = await gateway.getNetwork(channel);
const contract = network.getContract(chaincodeId);

// Hash
let hash: HashFunctions.Hash
Expand All @@ -279,23 +271,6 @@ async function assignAssetHelper(

params = assignAssetRequest2['param'].split(':')

const netConfig = getNetworkConfig(targetNetwork)
if (!netConfig.connProfilePath || !netConfig.channelName || !netConfig.chaincode) {
console.error(
`Please use a valid --target-network. No valid environment found for ${targetNetwork} `
)
return
}

const network = await fabricHelper({
channel: netConfig.channelName,
contractName: netConfig.chaincode,
connProfilePath: netConfig.connProfilePath,
networkName: targetNetwork,
mspId: netConfig.mspId,
userString: recipient
})

var funcToCall = SatpAssetManager.assignAsset
var asset = assignAssetRequest2['param']

Expand All @@ -315,14 +290,14 @@ async function assignAssetHelper(
}
} else {
try {
const lockerId = await network.wallet.get(locker)
const lockerCert = Buffer.from((lockerId).credentials.certificate).toString('base64')
const driverkeyCert = await getDriverKeyCert();
const certificate = Buffer.from(driverkeyCert.cert).toString('base64')

console.info(`Trying assign asset with params: ${params[0]}, ${params[1]} locked by ${locker} for ${recipient}`)
const res = await funcToCall(network.contract,
const res = await funcToCall(contract,
params[0],
params[1],
lockerCert,
certificate,
hash)
if (!res) {
throw new Error()
Expand All @@ -334,7 +309,7 @@ async function assignAssetHelper(
throw new Error(`Could not assign non-fungible ${asset} in ${targetNetwork}: ${error}`)
}

await network.gateway.disconnect()
await gateway.disconnect()
logger.info('Gateways disconnected.')

const client = getRelayClientForAssetStatusResponse();
Expand Down
2 changes: 1 addition & 1 deletion weaver/rfcs/formats/assets/satp.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
- RFC:
- Authors: Zakwan Jaroucheh, Venkatraman Ramakrishna, Sandeep Nishad, Rafael Belchior
- Status: Proposed
- Since:
- Since: 04-Sep-2023

## Summary
This document specifies the data formats used in the [secure asset transfer protocol (SATP)](../../protocols/satp/asset-transfer/generic.md). The structures defined in this document are generic and the operations on them are generic (see the protocol specification for details.) These structures are oblivious to the specifications and semantics of any digital asset maintained by any DLT application (e.g., any application chaincode in Fabric or any CorDapp in Corda).
Expand Down
2 changes: 1 addition & 1 deletion weaver/rfcs/models/infrastructure/relay_satp.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
- RFC:
- Authors: Zakwan Jaroucheh, Venkatraman Ramakrishna, Sandeep Nishad, Rafael Belchior
- Status: Proposed
- Since:
- Since: 04-Sep-2023

## Summary

Expand Down
2 changes: 1 addition & 1 deletion weaver/rfcs/protocols/satp/asset-transfer/fabric.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
- RFC:
- Authors: Zakwan Jaroucheh, Venkatraman Ramakrishna, Sandeep Nishad, Rafael Belchior
- Status: Proposed
- Since:
- Since: 04-Sep-2023

## Summary

Expand Down
2 changes: 1 addition & 1 deletion weaver/rfcs/protocols/satp/asset-transfer/generic.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
- RFC:
- Authors: Zakwan Jaroucheh, Venkatraman Ramakrishna, Sandeep Nishad, Rafael Belchior
- Status: Proposed
- Since:
- Since: 04-Sep-2023

## Summary

Expand Down
59 changes: 0 additions & 59 deletions weaver/sdks/fabric/interoperation-node-sdk/src/AssetManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,64 +393,6 @@ const claimFungibleAssetInHTLC = async (
return result;
};

const assignAsset = async (
contract: Contract,
assetType: string,
assetID: string,
lockerECert: string,
hash: Hash,
endorsingOrgs: Array<string> = []
): Promise<any> => {

if (!contract)
{
logger.error("Contract handle not supplied");
return false;
}
if (!assetType)
{
logger.error("Asset type not supplied");
return false;
}
if (!assetID)
{
logger.error("Asset ID not supplied");
return false;
}
if (!lockerECert)
{
logger.error("Locker ECert not supplied");
return false;
}
if (!hash)
{
logger.error("Instance of Hash interface not supplied")
return false
}
if (!hash.preimage)
{
logger.error("Hash Preimage not supplied");
return false;
}

const assetExchangeAgreementStr = createAssetExchangeAgreementSerialized(assetType, assetID, "", lockerECert);
const claimInfoStr = createAssetClaimInfoSerialized(hash);

// Normal invoke function
const tx = contract.createTransaction("AssignAsset")
const ccArgs = [assetExchangeAgreementStr, claimInfoStr]
if (endorsingOrgs && endorsingOrgs.length > 0) {
tx.setEndorsingOrganizations(...endorsingOrgs)
}
const [result, submitError] = await helpers.handlePromise(
tx.submit(...ccArgs)
);
if (submitError) {
throw new Error(`AssignAsset submitTransaction Error: ${submitError}`);
}
return result;
};

/**
* Rollback step of a Hashed Time Lock Contract
* - Reclaim a unique asset instance
Expand Down Expand Up @@ -1089,7 +1031,6 @@ export {
claimAssetInHTLC,
claimAssetInHTLCusingContractId,
claimFungibleAssetInHTLC,
assignAsset,
reclaimAssetInHTLC,
reclaimAssetInHTLCusingContractId,
reclaimFungibleAssetInHTLC,
Expand Down

0 comments on commit e06737d

Please sign in to comment.