What is the best way to verify that a text I received in mu function is a valid hash? In other words, contains a specified length and is composed only by numbers and "a", "b", "c", "d", "e" or "f"?


Assuming here a hash you mean is a TXID of Ethereum transaction, as there are many hashes and ways to present.

Ethereum hashes are 256-bit numbers, usually in hexadecimal format. Hashes are not distinguishable from any big random numbers, as they do not contain checksum mechanisms and such.

Verify that the entered input is hexadecimal. Also, you might want to have additional verify that this number is higher than some statistical threshold e.g. 2^128, so that user does not enter a hexadecimal number that looks to small, e.g. 0x10.

Ultimately, you can use Ethereum node JSON-RPC API to try to fetch the transction using the TXID and see there is a valid broadcasted transaction matching the hash. The fetch part, however may take from seconds to minutes, depending how long time ago the transaction was broadcasted.

| improve this answer | |

Unless it is otherwise required to be a string, it would probably make sense for the function to accept a bytes variable. Assuming the string is coming from off-chain, this would throw if there are any invalid characters in there, and then you can just check the .length of the variable to ensure it's the correct length.

uint hashLength = 10; //Or whatever you want it to be
function acceptsHash(bytes memory hash) public{
    require(hash.length == hashLength);

    //The rest of your function goes here...

| improve this answer | |

My implementation was:

function isValidHash(bytes memory b) pure public returns (bool)  {
    if(b.length != 64) return false;

    for (uint i=0; i<64; i++) {
        if (b[i] < "0") return false;
        if (b[i] > "9" && b[i] <"a") return false;
        if (b[i] > "f") return false;

    return true;
| improve this answer | |

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.