I wrote this piece of code with the goal to store unique documents hash. Used mapping to accomplished that.

pragma solidity ^0.5.16;

contract DocumentHash{

    string public documentHash;
    mapping (string => string) hashAlreadyRegistered;
    function setDocumentHash(string memory hash) public {
        require(keccak256( abi.encodePacked((""))) != keccak256(abi.encodePacked((hash))), "Empty hash!");
        require(keccak256( abi.encodePacked((hashAlreadyRegistered[documentHash]))) != keccak256(abi.encodePacked((hash))), "Hash already registered");
        documentHash = hash;
        hashAlreadyRegistered[documentHash] = hash;
    function getDocumentHash() public view returns(string memory) {
        return documentHash;

When i start a local server (npm start) with geth connection and send a hash to this contract, it works fine. When i try to send same hash, it active the expected behavior (require condition). But if i for example, restart the local server and geth connection, i'm able to store the same hash that i stored already. Wont the hash's be unique? or my code fails somewhere?

1 Answer 1


Might sound silly, but are you sure you are not redeploying the contract on the restart? Make sure you are working on the same contract with the same state (data). If yes then you can try replacing your current validation with this one:

require(bytes(hash).length  > 0, "Empty hash!");
require(bytes(hashAlreadyRegistered[hash]).length  == 0, "Hash already registered");

I noticed that if I pass 123 to method setDocumentHash and after this I pass 1234 then I'm able again to pass 123 without the contract giving me error back which tells me something is not working with your validation?

  • it's weird, in local server it didn't happen. Executing code in the remix the behavior is exactly you said. Commented Jun 19, 2020 at 15:57
  • i wrote another code to get the unique documents hash using a simple array. It's seems to work but when i return the array values, it get duplicate each time a push a value. the code is here:ipfs.io/ipfs/QmWfiuDMc1w1JKDtB4HJ8nrrWVyNjMg1qg1SuRkpvDbVPa appears i'm missing some concepts here Commented Jun 19, 2020 at 16:12

Your Answer

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

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