how to verify ethereum message in python in javascript

Python Solution:

The following code can be used to verify an Ethereum message in Python:

main.py
import json
from web3 import Web3

# input variables
address = '0xADDRESS'
signed_message = '0xSIGNED_MESSAGE'
original_message = 'ORIGINAL_MESSAGE'

# get the message hash
message_hash = Web3.keccak(text=original_message).hex()

# parse signed message
parsed_message = Web3.toBytes(hexstr=signed_message)

message_prefix = '\x19Ethereum Signed Message:\n' + str(len(original_message))
message_to_sign = message_prefix + original_message

# verify message signature
recovered_address = Web3.toChecksumAddress(Web3, eth_account_to_check=Web3.eth.account.recover_message(message_to_sign, vrs=parsed_message))

if address == recovered_address:
    print('Message successfully verified!')
else:
    print('Message verification failed.')
733 chars
25 lines

JavaScript Solution:

The following code can be used to verify an Ethereum message in JavaScript:

index.tsx
const {toChecksumAddress, keccak} = require('web3-utils');
const {recoverPersonalSignature} = require('eth-sig-util');

// input variables
const address = '0xADDRESS';
const signedMessage = '0xSIGNED_MESSAGE';
const originalMessage = 'ORIGINAL_MESSAGE';

// get the message hash
const messageHash = '0x' + keccak(originalMessage).toString('hex');

// parse signed message
const {v, r, s} = JSON.parse(signedMessage);

// verify message signature
const recoveredAddress = toChecksumAddress(recoverPersonalSignature({
    data: messageHash,
    sig: `0x${r}${s.substr(2)}${v.toString(16).padStart(2, '0')}`,
}));

if (address === recoveredAddress) {
    console.log('Message successfully verified!');
} else {
    console.log('Message verification failed.');
}
759 chars
26 lines

Note that web3-utils and eth-sig-util packages need to be installed in your JavaScript project for the code to work.

gistlibby LogSnag