0

I want to create a signature based on a hash value and a wallet address. In nodejs I would do it like follows:

        const types = ["address", "bytes32"];

        const values = [address, hash];
        const message = ethers.utils.defaultAbiCoder.encode(types, values);
        const hash = ethers.utils.keccak256(message);

        const sig = await wallet.signMessage(ethers.utils.arrayify(hash));

But how do I do this in python? I tried using the eth_abi module but it does not return the same message, hash or signature.

        types = ["address", "bytes32"]
        values = [address, codecs.decode(hash, 'hex')]
        encoded_message = encode_packed(types, values)
        hash_message = Web3.keccak(encoded_message)

        signed_message = account.signHash(hash_message)
        signature = signed_message['signature'].hex()

How can I mimic the process in nodejs in python?

3 Answers 3

1
from web3 import Web3
from eth_account import Account
from eth_abi import encode_abi_packed
import codecs

types = ["address", "bytes32"]
values = [address, codecs.decode(hash, 'hex')]
encoded_message = encode_abi_packed(types, values)
hash_message = Web3.keccak(encoded_message)

signed_message = Account.signHash(hash_message, private_key=private_key)
signature = signed_message['signature'].hex()
0

I was unable to verify the ethers output, but the correct way to encode with eth_abi is:

from eth_abi import encode

types = ["address", "bytes32"]
values = [my_address, my_hash]
message = encode(types, values)

my_hash does need to be a python bytes object

If message here is different from message in the ethers example, there may well be a bug somewhere.

0
from ethers import utils

types = ["address", "bytes32"]

values = [address, hash]
message = utils.defaultAbiCoder.encode(types, values)
hash = utils.keccak256(message)

sig = await wallet.signMessage(utils.arrayify(hash))

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.