[英]How to check that an ipfs hash is an image/video/.. in React Js?
[英]Storing hash on blockchain (hash of image stored on ipfs)
我正在创建一个 dapp,使用 react 将图像存储在 ipfs 上,并在区块链上存储相应的 hash。 在区块链上存储 hash 的目的是时间戳、所有权证明等,我希望在稍后阶段也检索 hash。 我需要知道我们如何在区块链上存储和检索 hash。
如果您选择以太坊区块链,最简单的方法是创建智能合约,下面给出最简单的示例。
通过调用Put方法,您可以保存与标识符关联的数据。 Get方法允许您按标识符检索数据而无需任何费用。
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_]) ;
}
}
如果您只需要存储和检索图像的 IPFS hash,您可以简单地使用 Solidity 的 事件。 它可能有点复杂,但部署和使用合约要便宜得多。
这是一个基本的方法:
event Store(string indexed id, string ipfsHash); //declare event
function setEvent(string memory _id, string memory _ipfsHash)public{
emit Store(_id, _ipfsHash);
}
当您在智能合约中emit
event
时,传递给它的参数将存储在交易日志中,这是区块链的一种特殊数据结构。
请注意,在智能合约中无法访问日志及其事件数据。 但是,您可以在应用程序中使用诸如web3.js 之类的库来检索它们。 在id
参数之前使用indexed
关键字可以让您有效地搜索包含所需值的特定日志。 如果没有它,您将不得不检索特定事件产生的所有日志并手动搜索它们。
有几种方法可以检索过去的日志,但我将使用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)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.