我正在创建一个dapp,使用react在ipfs上存储图像,并在区块链上存储相应的散列。在区块链上存储散列的目的是时间戳、所有权证明等,我也希望在稍后阶段检索哈希。我需要知道如何在区块链上存储和检索散列。
发布于 2020-12-16 20:13:30
如果您选择Ethereum区块链,最简单的方法是创建一个智能契约,最简单的示例如下所示。
通过调用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_]) ;
}
}发布于 2020-12-22 15:39:59
如果您只需要存储和检索图像的If散列,那么只需使用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之类的库来检索它们。在indexed参数之前使用id关键字可以有效地搜索包含所需值的特定日志。没有它,您必须检索由特定事件生成的所有日志,并手动搜索它们。
有几种方法可以检索过去的日志,但我将使用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)
});https://stackoverflow.com/questions/65317127
复制相似问题