实体映射返回空值

时间:2018-07-28 01:39:15

标签: mocha solidity truffle

因此,基本上,我在智能合约中创建一个映射来存储用户数据的哈希。它从用户ID映射到哈希本身(一个bytes32值)。我使用双sha256哈希并将其存储在具有上述id的映射中。用于存储它的函数通过返回映射中id处的值来返回哈希。此哈希是正确的,至少意味着它最初正确存储。但是,我还有另一个函数可以从id中获取哈希值,并且在javascript测试中始终返回null值。我想知道这是测试还是合同本身的问题。

pragma solidity ^0.4.22;
contract UserStore {
    mapping(uint => bytes32) UserHashes; //User id to hash

    event HashStored (
        uint id,
        bytes32 original, 
        bytes32 hash
    );


    function HashData(bytes32 data) returns (bytes32){
        return sha256(abi.encodePacked(sha256(abi.encodePacked(data))));
    }


    function StoreHash(uint user_id,  bytes32 data) external view returns (bytes32){ 
        UserHashes[user_id] = HashData(data);
        HashStored(user_id, data, UserHashes[user_id]);
        return UserHashes[user_id];
    }

    /*
        Gets the hash from the blockchain.
    */
    function GetHash(uint u_id) view public returns (bytes32){
        return UserHashes[u_id];
    }
}

每次运行此测试时,GetHash都会返回0值;

contract("Storage_Test", function(accounts) {

    const args = {user_id: 0,
                  data: "This is some security data",
                  group_id : 15,
                  user_ids  : [1,2,3,4,5],
                  num_accounts : 2
    }
    it("Hash Test: Multiple Storage and retrieving", async function() { return 
await UserStore.deployed()
    .then(async function(instance) {
        var temp = args.data;
        var _temp;
        for (i = 1; i < args.num_accounts; i++) {
            _temp = temp;
            temp = await instance.HashData.call(temp);
            //  console.log("Datahash: " + temp);
            result = await instance.StoreHash.call(i, _temp);
            //  console.log("Result:   " + result);
            assert.equal(result, temp, "Hash at " + i + " wasn't returned 
correctly");
        }
        temp = args.data;
        for (i= 1; i < args.num_accounts; i++) {
            temp = await instance.HashData.call(temp);
            result = await instance.GetHash.call(i);
            assert.equal( result, temp, "Hash at " + i + " wasn't stored 
correctly");
        }
    })
    }); 
});

1 个答案:

答案 0 :(得分:2)

instance.StoreHash.call(...)更改为instance.StoreHash.sendTransaction(...)call()在本地运行该功能,而不是提交事务。结果是任何状态更改都不会持久。