javakotlinsoliditysmartcontractsweb3-java

Get hashMessage in Java/Kotlin same like in solidity


I need a function (Java/Kotlin) that returns hashMessage which corresponds to Solidity function:

function getMessageHash(address _signer, uint _amount, uint _id) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(_signer, _amount, _id));
} 

This function should return value of format: hash = "0xcf36ac4f97dc10d91fc2cbb20d718e94a8cbfe0f82eaedc6a4aa38946fb797cd"

I've tried using Hash.sha3(String hexInput). from the org.web3j.crypto.Hash package but it only accepts one parameter. I can't figure out what does abi.encodePacked() is doing with parameters under the "hood".


Solution

  • I've finally found the solution, so I'll post it here if anyone needs it. The main question was, what is the abi.encodePacked() method doing "under the hood".

    HERE is a detailed explanation how some of the parameters are encoded in this method.

    For the particular question and method with next parameters: encodedMessage = abi.encodePacked("0x1b77882d1e55ffff0bc1c4215b869a2a36f7054d", 1, 1) the result from this method is: encodedMessage = 1b77882d1e55ffff0bc1c4215b869a2a36f7054d00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001

    For the _signer (string) the prefix (0x) was removed, for _amount and _id (uint) I used TypeEncoder.encode(Uint256(1)). Encoded values for each parameter is appended to the previous one, and at last hashed together with method: val hashedMessage = Hash.sha3(encodedMessage) which result is: 0xe06176482c2b2619110be196a3d999dedf922782c0fe85603b19044bf30b3856

    Later on hashedMessage can be used for signing or verification of signature. But that is out of the scope of this question.