TransWikia.com

Hashnot matching generated from solidity contract and web3js

Ethereum Asked by chinmay on December 15, 2020

I want to make hash same as generating by solidity contract from web3 or ether’s js.

In solidity contract hash generation by below :
sha256(abi.encodePacked(no of parameters)).

Kindly help for it. how can i generate using web3 or ether’s js same hash.

2 Answers

In solidity the hash is generated using:

function generateHash(param1, param2, ... paramN) public pure returns (bytes32) {
    return keccak256(abi.encodePacked(param1, param2, ... paramN));
}

In web3.js v1.2.6, the same hash can be generated using:

web3.utils.soliditySha3(param1, param2, ... paramN);
Example:
  > const web3 = require('web3');
  > web3.utils.soliditySha3('balaji', 10000);
  > '0x6d4e07169abf3d9047d7d5283460790fe3f80395521c9a376768679fc27b4687'

In ethers.js the same hash can be generated using:

ethers.utils.soliditySha3(['paramTypes'], ['paramValues'])

Example:
  > const ethers = require('ethers');
  > > ethers.utils.solidityKeccak256(['string', 'uint256'], ['balaji', 10000]);
  > '0x6d4e07169abf3d9047d7d5283460790fe3f80395521c9a376768679fc27b4687'

Answered by balajipachai on December 15, 2020

In my opinion, this is a case where it is worthwhile for a contract to present a "helper" function that will ensure that clients can easily match the contract's hash process. I think it's important to ensure they can do so regardless of the language, and will always be able to do so in the future.

The pattern is simple. Whatever the contract is doing, code it as a public pure function. Use it internally.

This ensures external clients will always be able to match the contract's internal logic.

function hashHelper(address a, bytes32 b, uint c) public pure returns(bytes32) {
  return ... // keccak256(..., sha3( ..., whatever
}

function commit(bytes32 hash) public pure {
  // record committment
}

function reveal (address a, bytes32 b, uint c) public {
  require(hashHelper(a,b,c) == hash, "Invalid Hash inputs");
}

When clients call the pure function, it's the same as them running a hash computation locally and nothing confidential is revealed to the network.

Hope it helps.

Answered by Rob Hitchens on December 15, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP