【问题标题】:Solidity - a mapping based on the hash of a string valueSolidity - 基于字符串值哈希的映射
【发布时间】:2021-08-10 15:41:33
【问题描述】:

我正在尝试创建 mapping(string => string) 类型的映射,您可以通过其哈希的字符串表示作为键存储一些文本,但由于无法获取计算的哈希值并将其转换为它的字符串表示。

我尝试了以下方法,但它不起作用。散列函数似乎有效,但转换为字符串却无效。 (运行函数hash()返回一个我不太明白的错误。

pragma solidity 0.8.4;
contract HashTextMap {
    
    mapping(string=>string) textMap;
    
    
    function set(string memory text) public  {
        bytes32 val;
        val = sha256(abi.encodePacked(text));
        string memory key = string(abi.encodePacked(val));
        textMap[key] = text; 
        
    }
    function get(string memory key) public view returns(string memory) {
        return textMap[key];
    }
    
    function hash(string memory text) public pure returns(string memory) {
        bytes32 val;
        val = sha256(abi.encodePacked(text));
        string memory key = string(abi.encodePacked(val));
        return key;
        
    }
}

在混音 ide 中运行此程序,合约编译并设置正常返回,但尝试我无法获取文本,因为我无法使用产生此错误的 hash() 获取哈希。

{ "error": "Failed to decode output: null: invalid codepoint at offset 0; unexpected continuation byte (argument=\"bytes\", value={\"0\":153,\"1\":168,\"2\":124,\"3\":145,\"4\":53,\"5\":23,\"6\":70,\"7\":37,\"8\":43,\"9\":238,\"10\":126,\"11\":38,\"12\":250,\"13\":191,\"14\":48,\"15\":2,\"16\":61,\"17\":234,\"18\":227,\"19\":36,\"20\":138,\"21\":6,\"22\":125,\"23\":166,\"24\":226,\"25\":63,\"26\":146,\"27\":129,\"28\":199,\"29\":135,\"30\":194,\"31\":139}, code=INVALID_ARGUMENT, version=strings/5.4.0)" } 

【问题讨论】:

  • 什么是错误信息,solidity 版本?
  • MERN 在上面更新了 q。

标签: solidity


【解决方案1】:

这应该对你有帮助 Solidity: How to represent bytes32 as string

问题是当前您正尝试将哈希转换为 utf-8 字符串。哈希具有 utf-8 不支持的值。我认为您的意思是将您的哈希表示为字符串。

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
相关资源
最近更新 更多