Last active
March 1, 2018 21:04
-
-
Save recmo/e84b5c697dab24b6920c162a0d17116e to your computer and use it in GitHub Desktop.
Experiments to understand Solidity's hashing of structured data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity 0.4.20; | |
// pragma experimental ABIEncoderV2; // Does not affect outcome | |
contract Test { | |
function test1() public pure returns (bool) { | |
bytes32 hash1 = keccak256("abc", "def"); | |
bytes32 hash2 = keccak256("abcd", "ef"); | |
return hash1 == hash2; // Returns true | |
} | |
function test2() public pure returns (bool) { | |
uint8 num1 = 200; | |
int8 num2 = -56; | |
bytes32 hash1 = keccak256(num1); | |
bytes32 hash2 = keccak256(num2); | |
return hash1 == hash2; // Returns true | |
} | |
function test3() public pure returns (bool) { | |
string memory str = "Hello!!!"; | |
uint64 num = 5216694956355297569; | |
bytes32 hash1 = keccak256(str); | |
bytes32 hash2 = keccak256(num); | |
return hash1 == hash2; // Returns true | |
} | |
struct Struct1 { | |
string first; | |
string second; | |
} | |
function test4() public pure returns (bool) { | |
bytes32 hash1 = keccak256(Struct1({first:"abc", second:"def"})); | |
bytes32 hash2 = keccak256(Struct1({first:"abc", second:"def"})); | |
return hash1 == hash2; // Returns false | |
} | |
function test5() public pure returns (bool) { | |
Struct1 memory str1 = Struct1({first:"abc", second:"def"}); | |
uint256 memaddr = getAddress(str1); | |
bytes32 hash1 = keccak256(str1); | |
bytes32 hash2 = keccak256(memaddr); | |
return hash1 == hash2; // Returns true | |
} | |
function test6() public pure returns (bool) { | |
uint256[3] memory arr1 = [uint256(0), uint256(1), uint256(2)]; | |
uint256[3] memory arr2 = [uint256(0), uint256(1), uint256(2)]; | |
bytes32 hash1 = keccak256(arr1); | |
bytes32 hash2 = keccak256(arr2); | |
return hash1 == hash2; // Returns true | |
} | |
function test7() public pure returns (bool) { | |
uint256[3] memory arr1 = [uint256(0), uint256(1), uint256(2)]; | |
uint256[3] memory arr2 = [uint256(0), uint256(1), uint256(3)]; | |
bytes32 hash1 = keccak256(arr1); | |
bytes32 hash2 = keccak256(arr2); | |
return hash1 == hash2; // Returns false | |
} | |
function getAddress(Struct1 memory str1) internal pure returns (uint256 addr) { | |
assembly { addr := str1 } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment