0

I am creating a dapp using react to store image on ipfs and the corresponding hash on blockchain. The purpose of storing hash on blockchain is timestamping, proof of ownership wtc and i wish to retrieve the hash also at later stage. I need to know how can we store and retrieve hash on blockchain.

0

I believe there are many ways to implement your request, but following is the way I did in a previous project:

  1. Generate the hash from your front-end

I assume you already have this. Just in case, I did this way (in my case, from a backend in Node.js:

const crypto = require('crypto');

const generateHashOrderValues = (params: OrderInput) => {
    return (
        '0x' + crypto
            .createHash('sha256')
            .update(
                params.field1 +
                params.field2 +
                //...
                )
            .digest('hex')
    );
};
  1. Store the hash in your smart contract

    pragma solidity ^0.7.0;
    
    contract Trace {
    
     event SaveHash(bytes32 indexed _orderID);
    
     address payable public owner;
    
     constructor() public payable {
         owner = msg.sender;
     }
    
     modifier isOwner() {
         require(msg.sender == owner, "Caller is not the Owner");
         _;
     }
    
     function saveHash(bytes32 _orderID) external isOwner returns (bool) {
         emit SaveHash(_orderID);
         return true;
     }
    }
    
  2. Retrieve your hash

         contract.getPastEvents('SaveHash', {
             filter: {
                 _orderID: params.hash,
             },
             fromBlock: params.block_number,
             transactionHash: params.tx_hash,
         })
             .then((events) => {
                // do your stuff
             })
    

You may have noticed that I am using events. I initially had a contract with a structure to save the hashes in the storage, but in terms of gas consumption, it is cheaper to just use events in order to store and retrieve data, specially if you are considering storing large amounts of hashes.

I am also happy to receive feedback on such approach in case there are better ways to do so ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.