How can I check whether a transaction hash is valid or not using Python [web3.py]?

The answers I found was in javascript, related:

  • Why can't you just check if the transaction with this hash exists on the chain ? Oct 9 '21 at 12:24
  • I don't want to check if the transaction hash exists on the chain, which will also consumes additional time to check from.
    – alper
    Oct 9 '21 at 22:23
  • Considering a hash is just a bunch of characters with a specific length (the string), any string with said length is a valid transaction hash. Oct 10 '21 at 7:15
  • Besides length it should not contain any invalid characters
    – alper
    Oct 10 '21 at 8:38

With the help of regex at https://ethereum.stackexchange.com/a/34286/4575:


import re

def is_transaction_valid(tx_hash) -> bool:
    pattern = re.compile(r"^0x[a-fA-F0-9]{64}")
    return bool(re.fullmatch(pattern, tx_hash))

tx_hash = "0xd65dc6bf6dcc111237f9acfbfa6003ea4a4d88f2e071f4307d3af81ae877f7be"
if is_transaction_valid(tx_hash):
    print(f"{tx_hash} is an valid transaction.")
    print(f"{tx_hash} is NOT a valid transaction.")

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.