Building a method to write a file hash to the blockchain

The asynchronous bwrite method writes a file hash to the blockchain. It takes the hash of the directory path of the file (pHash) and the document hash (dHash) as input and writes to the blockchain.

  1. Before writing to the blockchain, we need access to a registered identity that has permission to write to our blockchain. We'll use the user1 user that we registered in our wallet earlier. Using the Hyperledger Fabric SDK FileSystemWallet method, we'll create a new wallet object pointing to the wallet we created for DocsApp. We check whether the user 1 user is registered in the wallet. Execution of the method will proceed only if the user 1 user exists:
async function bWrite (pHash,dHash) {

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;
}
  1. Next, we define a new Gateway object to connect to our blockchain:
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');
  1. The Gateway object is configured with the  wallet (DocsApp wallet location), user identity (user 1), blockchain channel (mychannel), and chaincode contract (docsapp)) to point it to our chaincode in our blockchain. We use getNetwork to set the channel and getContract to set the chaincode:
await contract.submitTransaction('addDocHash',pHash,dHash);
console.log("Transaction Doc has been submitted");
await gateway.disconnect();
  1. Next, we invoke our contract and submit a new transaction. We submit a call to the contract addDocHash method and submit the file path hash (pHash) and file hash (dHash) as input parameters to the contract method. You will remember from the previous section that this method creates a document object, which it then writes to the blockchain state database indexed by the file path hash (PathHash). After successful transaction submission, a message is printed to the console and the gateway is disconnected:
} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
};
  1. A catch statement is added to catch any errors during transaction submission. 

This ends our analysis of the bWrite method. Next, we'll take a look at the pWrite method.

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

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