Solidity 结构 arrar

Solidity struct arrar

我 运行 遇到包含数组的结构的可靠性问题,你能帮我看看我遗漏了什么吗?任何帮助将不胜感激!

   struct Info {
    uint a;
    uint256 b;
    uint[] data;
}

mapping(address => Info) infos;

function set() public {
    infos[msg.sender].a = 1;
    infos[msg.sender].b = 2;
    infos[msg.sender].data.push(3);
}

function get() public {
      infos[msg.sender].a; //yes It is equal to 1
      infos[msg.sender].b; //yes It is equal to 2
      infos[msg.sender].data[0]; //The problem here is that anyone calling this function can read data[0]=3
}

我对你的要求有点困惑,但我提供的第一个解决方案修改了你的智能合约,使映射对象信息和 getter 函数都是私有的(仅在定义的合约中可用) .

contract test{
       struct Info {
        uint a;
        uint b;
        uint[] data;
    }
    
    mapping(address => Info) private infos;
    
    function set() public {
        infos[msg.sender].a = 1;
        infos[msg.sender].b = 2;
        infos[msg.sender].data.push(3);
    }
    
    function get() private view{
      infos[msg.sender].a; //yes It is equal to 1
      infos[msg.sender].b; //yes It is equal to 2
      infos[msg.sender].data[0]; //The problem here is that anyone calling this function can read data[0]=3
    } }

第二种解决方案是在getter函数中添加一个叫做'require'的东西,这样只有部署智能合约的人才能查看数组索引。构造函数将部署合约的人指定为 'owner'.

contract test{
    struct Info {
        uint a;
        uint b;
        uint[] data;
    }
    
    address owner;
    
    constructor() {
        owner = msg.sender;
    }
    
    mapping(address => Info) infos;
    
    function set() public {
        infos[msg.sender].a = 1;
        infos[msg.sender].b = 2;
        infos[msg.sender].data.push(3);
    }
    
    function get() public view{
      infos[msg.sender].a; //yes It is equal to 1
      infos[msg.sender].b; //yes It is equal to 2
      require(owner == msg.sender, 'you cannot read this data, you are not the owner!');
      infos[msg.sender].data[0]; //The problem here is that anyone calling this function can read data[0]=3
    }
}

如果我误解了你的问题,请告诉我。