1

I want to generate a unique hash value based on the current timestamp. I tried to get the current timestamp by block.timestamp but it gives me the same number every time so my generated hash value is not unique. How do I deal with this?

    function generateUniqueHash() public onlyOwner returns (bytes32) {
        return keccak256(abi.encodePacked("secret", block.timestamp));
    }
3
  • Where are you testing this? Remix?
    – pbsh
    Feb 6, 2022 at 14:10
  • @pbsh Yes I tested in both remix and node solc Feb 6, 2022 at 14:48
  • why the function is not "public view"? and why are you using "onlyOwner" , it does not change the state of the contract?
    – Majd TL
    Feb 6, 2022 at 19:54

3 Answers 3

0

Works perfectly fine on my end:

first try:

{
    "0": "bytes32: 0x4fa4ee671213fd09d919f9e20942fca229302f8636cc722667a844518fdafe1d"
}

second try:

{
    "0": "bytes32: 0x1be2ff47184adae85d9ed4e084d5cab1be81a64dee3601dacafe7ae7b90b6d07"
}

and the third one:

{
    "0": "bytes32: 0xc9fe1eefcfec97a5981d0535e1d594957337ce7086a8431d14ed50942ec9437d"
}
0

If it is for a commercial project, please note that block.timestamp is not the best source of entropy/randomness as miners can (almost) freely set it: Block Timestamp Manipulation

Ex: if you are designing a money game where the outcome depends on that data, and if there is BIG money involved, it is always possible for a miner to include a transaction to your contract and predict, based on your formula, which particular value of block.timestamp will give them an advantage.

A good alternative would be to use Chainlink VRF

Otherwise, for prototyping or projects not involving money, it is of course perfectly fine to use block.timestamp

0

You can try using a unique identifier like the transaction hash or the block number to generate a unique hash value.

Here is an example using the transaction hash:

function generateUniqueHash() public onlyOwner returns (bytes32) {
    return keccak256(abi.encodePacked("secret", tx.hash));
}

And here is an example using the block number:

function generateUniqueHash() public onlyOwner returns (bytes32) {
    return keccak256(abi.encodePacked("secret", block.number));
}

Note that the block number and transaction hash can be easily accessed within a contract, so you should use them with caution as they can potentially be exploited by attackers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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