Storing hash on blockchain (hash of image stored on ipfs)

Viewed 1382

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

2 Answers

If you choose the Ethereum blockchain, the easiest way is to create a smart contract, the simplest example of which is given below.

By calling the Put method, you save the data associated with an identifier. The Get method allows you to retrieve data by identifier without any cost.

pragma solidity >=0.5.8 <0.6.0;

contract Storage
{
    address    Owner ;

    mapping (string => string)  Collection ;

//
   constructor() public
   {
              Owner     = tx.origin ;
   }
// 
   function Put(string memory  id_, string memory data_) public
   {
       if(msg.sender!=Owner)  return ;

      Collection[id_]=data_ ;
   }
//
    function Get(string memory  id_) public view returns (string memory retVal)
    {
       return(Collection[id_]) ;
    }

}

If you just need to store and retrieve the IPFS hash of an image you can simply use Solidity's events. It may be a bit more complicated but it is a lot cheaper to deploy and use the contract.

Here is a basic approach:

event Store(string indexed id, string ipfsHash);  //declare event

function setEvent(string memory _id, string memory _ipfsHash)public{
    emit Store(_id, _ipfsHash);
}

When you emit the event in your smart contract, the parameters passed to it are stored in the transaction's logs, a special data structure of the blockchain.

Note that logs and their event data are not accessible within smart contracts. However, you can use libraries such as web3.js inside you app to retrieve them. The use of indexed keyword before the id parameter let's you effectively search for a particular log, containing a desired value. Without it, you would have to retrieve all logs produced by a particular event and search through them manually.

There are a few ways to retrieve past logs, but i will paste an example using getPastEvents :

var contract = new web3.eth.Contract(ABI_of_contract, address_of_contract);

contract.getPastEvents('Store', {
      filter : { id : '...id corresponding to the ipfsHash'},
      fromBlock : 0,
      toBlock: 'latest'},
      function(error, result){

          console.log(result) 

     });
Related