Building a method to write the MTH and the FTH to the blockchain

The pWrite method takes the last MTH and FTH as input and writes them to the blockchain. The hashes are indexed in the blockchain by the timestamp at which the hashes where calculated. This is done so as to create a timestamped audit log of all the times that a new entry was recorded for the secured directory in the blockchain. 

  1. The pWrite function is similar in structure to bWrite. It first defines a new wallet object and a gateway to connect to our docsapp chaincode:
async function pWrite(FTH,MTH) {

try {
const wallet = new FileSystemWallet('/home/ishan/docsapp/wallet');
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}

const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
const network = await gateway.getNetwork('mychannel');
const contract = network.getContract('docsapp');

It uses the user 1 identity and connects to the mychannel channel. The wallet object points to the wallet we created for DocsApp. The contract object is set to docsapp.

  1. As we've already discussed, the hashes, MTH and FTH, are indexed by the time in which they were recorded. So, we need to fetch the current UTC timestamp. This is done using the following steps. The UTC timestamp is captured to the dateTime variable:
var today = new Date();

var dateTime = Date.UTC(today.getFullYear(), today.getMonth()+1, today.getDate(),
today.getHours(),today.getMinutes(),today.getSeconds());

  1. Now, we submit the transaction to our DocsApp chaincode contract:
await contract.submitTransaction('addPathHash',dateTime.toString(),MTH,FTH);
console.log("Transaction PathHash has been submitted");
await gateway.disconnect();
return dateTime.toString();

Note how this time, we call the chaincode addPathHash method to write the MTH and FTH hashes. The input parameters are dataTime, MTH, and FTH.

  1. A message is logged to the console upon successful submission and the gateway is disconnected. The dateTime variable is returned to the requester and can be used in the future for retrieving the MTH and FTH.
  1. A catch statement is added to catch any errors during transaction submission:
catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
}

This ends our analysis of the pWrite method. Let's look at the methods we'll use to read from the blockchain next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75