1

I want to hash a given array of address (using keccak256) into a single variable byte32.

for example:

function hashOfArray( address [] list) public constant returns (byte32) {
      var hash = ...
     return hash;
}
4
  • keccak256(list) should work well
    – qbsp
    Commented May 8, 2018 at 8:55
  • but keccak256(list) != keccak256(list[0],..,list[n])
    – maroodb
    Commented May 8, 2018 at 9:02
  • @maroodb that won't make a difference if you are going to compare hashes. Commented May 8, 2018 at 13:36
  • Also, are you sure keccak256(list) != keccak256(list[0], ... list[n])? I believe it should be, and in my testing it is.
    – user19510
    Commented May 8, 2018 at 17:44

1 Answer 1

1

You can use keccak256(list) to compare 2 arrays.

The hash will be the same only if the two arrays have the same size and the same content in the same order.

I wrote a smart contract where we can test that:

pragma solidity ^0.4.23;

contract Test {

    function cond1() pure internal returns (bool) {
        // same array with different content
        uint[] memory array_a = new uint[](1);
        bytes32 hash1 = keccak256(array_a);
        array_a[0] = 42;
        bytes32 hash2 = keccak256(array_a);
        // hashes should be different
        return hash1 != hash2;
    }

    function cond2() pure internal returns (bool) {
        // different arrays with same size and content
        uint[] memory array_a = new uint[](1);
        uint[] memory array_b = new uint[](1);
        array_a[0] = 42;
        array_b[0] = 42;
        // hashes should be equal
        return keccak256(array_a) == keccak256(array_b);
    }

    function cond3() pure internal returns (bool) {
        // empty arrays with different sizes
        uint[] memory array_a = new uint[](1);
        uint[] memory array_b = new uint[](2);
        // hashes should be different
        return keccak256(array_a) != keccak256(array_b);
    }

    function cond4() pure internal returns (bool) {
        // same content, in different order
        uint[] memory array_a = new uint[](2);
        uint[] memory array_b = new uint[](2);
        array_a[0] = 42; array_a[1] = 17;
        array_b[0] = 17; array_a[1] = 42;
        // hashes should be different
        return keccak256(array_a) != keccak256(array_b);
    }

    function testConditions() pure public returns (bool) {
        return cond1() && cond2() && cond3() && cond4();
    }
}

Calling testConditions() will return true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.