1

This question already has an answer here:

sha3 of address-type argument calculated in solidity

function get_sha() constant returns (address, bytes32) {
    return (msg.sender, sha3(msg.sender));
}

is different from that calculated in web3js using buffer constructed from hex representation of the argument:

  • returned from contract:
    address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c
    bytes32: 0xb1591967aed668a4b27645ff40c444892d91bf5951b382995d4d4f6ee3a2ce03

  • returned by web3js:
    > web3.sha3(Buffer.from('ca35b7d915458ef540ade6068dfe2f44e8fa733c', 'hex').toString())
    '0xd53a2663473d029b80bddef493a064cc91bad113e4a61353b243b769c6909222'

They match if I compare sha3s of string-type arguments like "a", but don't match in case of address-type argument. I also tried to pad string inside Buffer.from(...) with 24 zeros on the left and on the right, so that it would represent 32 bytes, but the result is still incorrect.

How can I make web3's value match that of solidity's?

marked as duplicate by carver, atomh33ls, Matthew Schmidt, Richard Horrocks, eth Aug 13 '17 at 6:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Try web3.sha3('0xca35b7d915458ef540ade6068dfe2f44e8fa733c') or web3.sha3('0xca35b7d915458ef540ade6068dfe2f44e8fa733c', { encoding: 'hex' })

  • Thanks, second variant with encoding works correctly. Do you happen to know why it didn't work with buffer? how does it get parsed in this case? – xaxa Aug 11 '17 at 20:26
  • I'm guessing that sha3 doesn't accept buffers, only strings. – DeviateFish Aug 11 '17 at 23:35
  • This is why I use toString() on the buffer... – xaxa Aug 12 '17 at 17:37
  • Wrong encoding on the string, perhaps? Try using your original approach, but with toString('ascii') instead? – DeviateFish Aug 14 '17 at 1:21
  • Unfortunately it doesn't work either, I also tried latin1 and other options from node.js docs – xaxa Aug 14 '17 at 15:15
3

One of my friend fixed this issue by making some changes in original solidity-sha3 package which was created to match the behavior of sha3 in Solidity and web3.sha3 but still there were some issues.

Now, this Nodejs package and solidity's sha3 behaves same.

In order to use it, you will have to include it inside package.json as shown below -

"solidity-sha3": "https://github.com/nalinranjan/solidity-sha3/tarball/master"

and then run

npm install

After that if you want to use solidity-sha3 package in your test cases, you can import it like this -

const sha3 = require('solidity-sha3').default;

Hope this helps.

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