how to verify ethereum message -web3 in python

To verify an Ethereum message using Web3 in Python, you can follow these steps:

  1. Import the required packages.
main.py
from web3.auto import w3
import codecs
39 chars
3 lines
  1. Define the message and signature in hexadecimal format.
main.py
message = "Hello, world!"
signature = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
139 chars
3 lines
  1. Decode the signature and extract the v, r, and s values.
main.py
signature_bytes = codecs.decode(signature[2:], 'hex')
v = signature_bytes[-1]
r = int.from_bytes(signature_bytes[:32], byteorder='big')
s = int.from_bytes(signature_bytes[32:64], byteorder='big')
196 chars
5 lines
  1. Use the web3.eth.account.recover_message method to recover the public address of the signer.
main.py
signer = w3.eth.account.recover_message(message, vrs=(v, r, s))
64 chars
2 lines
  1. Compare the recovered public address with the expected public address to verify the message.
main.py
expected_address = "0x0123456789abcdef0123456789abcdef0123456"
if signer.lower() == expected_address.lower():
    print("Message signature is valid!")
else:
    print("Message signature is invalid.")
200 chars
6 lines

Note that the expected public address should match the address of the signer who signed the message. If the two addresses don't match, the message signature is not valid.

gistlibby LogSnag