When trying to test a smart contract that uses
sha256(abi.encodePacked(_myargument))
I don't get the same hash on truffle !
I tried both
web3.utils.keccak256('_myargument')
web3.utils.sha3('_myargument')
but both gave a hash different from what I get within the smart contract function.
So I thought it was because of abi.encodePacked, thus I tried
web3.utils.sha3(web3.eth.abi.encodeParameter('string', _myargument))
but the hash is still not the one expected.
Do you know why and how to get the same hash ? I don't understand why in general people use abi.encodePacked before hashing the argument with sha256(). If abi.encodePacked is involved, is it really necessary to keep it or can I safely remove it to just use sha256(_myargument) instead of sha256(abi.encodePacked(_myargument)) inside the smart contract ?
Best regards
Best Answer
First you need to know that
sha256
andkeccak256
functions are not the same. Check the docs to see available functions.sha256
(with pyhton):keccak256
(with web3):To get the same hash:
Output:
Choose:
About
abi.encodePacked(...)
You can test it, but with one argument, the result hash will be the same if you don't use
abi.encodePacked(...)
.EDIT:
From docs:
abi.encodePacked(...)
encode dynamic types without length and static types are not padded if they are shorter than 32 bytes.abi.encode(...)
ABI-encodes the given argumentsabi.encode("a", "bc")
result:abi.encode("ab", "c")
result:abi.encodePacked("a", "bc")
result:abi.encodePacked("ab", "c")
result: