1

I have following contract:

pragma solidity ^0.4.0;

contract Lottery {
  address public owner;
  bytes32 public hash;

  function Lottery() {        
    owner = msg.sender;
    hash = sha3(10, owner);
  }

  function get() constant returns (address, bytes32) {
    return (owner, hash);
  }
}

Which returns:

{
    "0": "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c",
    "1": "bytes32: 0x68690d4f19be42f79fab7837a1959281e0cb7c0a67c4c1efb7a1fcb008e5806e"
}

sha3() can get multiple input into each other. I want to obtain same bytes32 hash on the nodejs by providing same inputs as some uint value and "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c".as sha3(uint, address).


I have followed following guide: (https://ethereum.stackexchange.com/a/34420/4575)

The javascript code I have:

module.exports = require('js-sha3');

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

if(!web3.isConnected()){
    console.log("not connected");
    process.exit();
}

var owner = "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"; //given input on the smart-contract.

hash = web3.utils.sha3( 10 + web3.utils.hexToBytes(owner) )
console.log(hash)

Which prints:

0xaf62552265611d75712f03dd8d2ae6efcb4c140dc8357ea015bd0572dd33ca82

That is not the same output I got on the solidity.

[Q] What should I do to get the same output using sha3 by providing same uint, address as multiple parameter input on nodejs?

Thank you for your valuable time and help.

2

Solidity's keccak256/sha3 concatenates its arguments. 10 will be considered a bytes8, so it will be padded to that size.

Prepend your hex string with 0a (and be careful to remove the intervening "0x"):

> web3.sha3('0a' + 'ca35b7d915458ef540ade6068dfe2f44e8fa733c', { encoding: 'hex' })
'bbeea4a4cc90c8c1ea202ba19af7d6bd3e1059bd4529ae931ba6712c171ca1b4'
  • Basically, is sha3(uint, address) concatenate multiple inputs into each other as byte format? @smarx – alper Dec 26 '17 at 15:13
  • 1
    Yes, in general sha3(a, b, c, d, ...) is the hash of the concatenation of all the arguments' binary representations. Be careful with types, though. If 10 is a uint256, then be sure to use 32 bytes for it instead of just 1. – user19510 Dec 26 '17 at 15:14
  • If 10is a uint256, should I define it as "0a" and 31 0s follows it? @smarx – alper Dec 26 '17 at 15:23
  • 1
    No, 63 0s followed by an a. (Total length should be 32 bytes, big-endian, so 64 characters in hex with the least significant digit, the a, at the end.) – user19510 Dec 26 '17 at 15:25
  • 1
    const number = 10; require('pad')(64, number.toString(16), '0') – user19510 Dec 26 '17 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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