user9109285
user9109285

Reputation:

How to get keccak256 hash in Solidity

I just got started with solidity, I have used truffle to compile and deploy the code to ganache, everything works as I expect, I can call the other functions in the code, but there are certain functions that only the owner can access, the code appears to use keccak256 to get back the address calling the function and determine if the caller address is allowed, I have tried to hash my eth address using this website:

https://emn178.github.io/online-tools/keccak_256.html

and then add the hash to the code before recompiling again, but calling the owner function still throws this error:

"Error: VM Exception while processing transaction: revert"

What am i doing wrong ?

Here's the code with the original hash.

modifier onlyOwner(){
    address _customerAddress = msg.sender;
    require(owners[keccak256(_customerAddress)]);
    _;
}

// owners list
mapping(bytes32 => bool) public owners;


function PetShop()
    public
{
    // add owners here
    owners[0x66e62cf7a807daaf3e42f7af3befe7b2416a79ba5348820245a69fe701f80eb4] = true;   
}

/*----------  Owner ONLY FUNCTIONS  ----------*/

function disableDogs() 
    onlyOwner()
    public
{
    onlyDogs = false;
}

/*-----replace owner ------*/
function setOwner(bytes32 _identifier, bool _status)
    onlyOwner()
    public
{
    owners[_identifier] = _status;
}

/*-----set price for pet adoption----*/
function setAdoptionRequirement(uint256 _amountOfTokens)
    onlyOwner()
    public
{
    AdoptionRequirement = _amountOfTokens;
}

Upvotes: 0

Views: 5041

Answers (2)

Yilmaz
Yilmaz

Reputation: 49709

as of now

 // .encodePacked merges inputs together
 owners[keccak256(abi.encodePacked(_text, _num, _addr))}=true

abi.encodePacked() , Solidity supports a non-standard packed mode where:

  • types shorter than 32 bytes are neither zero padded nor sign extended

  • dynamic types are encoded in-place and without the length.

  • array elements are padded, but still encoded in-place

Upvotes: 0

Adam Kipnis
Adam Kipnis

Reputation: 11001

The keccak256 implementation in Solidity stores data differently.

keccak256(...) returns (bytes32): compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments

Just use the function yourself when creating the contract:

function PetShop() public {
    // add owners here
    owners[keccak256(msg.sender)] = true;   
}

Upvotes: 1

Related Questions