Gregory Johnson
Gregory Johnson

Reputation: 3

Solidity mapping returning null values

So basically, I create a mapping within a smart contract to store hashes of user data. It's mapped from a user id to the hash itself (a bytes32 value). I use a double sha256 hash and store it in the mapping with the aforementioned id. The function for storing it returns the hash by returning the values at the id in the mapping. This hash is correct, meaning at the very least it's initially stored correctly. However, I have another function that gets the hash from the id and it always returns a null value in the javascript tests. I am wondering if it's a problem with the test or with the contract itself.

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];
    }
}

Everytime I run this test, GetHash returns a 0 value;

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");
        }
    })
    }); 
});

Upvotes: 0

Views: 881

Answers (1)

Adam Kipnis
Adam Kipnis

Reputation: 10991

Change instance.StoreHash.call(...) to instance.StoreHash.sendTransaction(...). call() runs the function locally instead of submitting the transaction. The result is any state change isn’t persisted.

Upvotes: 2

Related Questions