Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tronpy.exceptions.BadSignature for signature from TronWeb #101

Open
keshe4ka opened this issue Jul 25, 2023 · 1 comment
Open

tronpy.exceptions.BadSignature for signature from TronWeb #101

keshe4ka opened this issue Jul 25, 2023 · 1 comment

Comments

@keshe4ka
Copy link

I get a signature line from the frontend that looks like this: 0x1d1b0779da653630d29fc4f1ea1e5a109a30d52e21e7657fa896d2fccc3b430b14089377e13b6ed35ef371a1c91873773d568219d1100fa8595e5f2eec39e3e41c (TronWeb signMessageV2 documentation example).
I'm trying to create a Signature object
signature = Signature.fromhex(decoded_token['signature'][2:])
but I'm getting a
tronpy.exceptions.BadSignature error due to assert signature_bytes[-1] in [0, 1]
What can I do?

@keshe4ka
Copy link
Author

keshe4ka commented Jul 28, 2023

I was able to solve this problem for myself by writing my own implementation:

import sha3
from tronpy.keys import Signature

TRON_MESSAGE_PREFIX = "\x19TRON Signed Message:\n"


def hash_message(message):
    if isinstance(message, str):
        message = message.encode()

    if isinstance(message, list):
        message = bytearray(message)

    message_length = str(len(message)).encode()

    h = sha3.keccak_256()
    h.update(TRON_MESSAGE_PREFIX.encode())
    h.update(message_length)
    h.update(message)

    return h.digest()


def recover_address_from_msg_hash(signature_hex_str: str, message_hash: bytes):
    """Recover public key(address) from message hash and signature."""
    signature_bytes = bytes.fromhex(signature_hex_str[2:])
    r = signature_bytes[:32]
    s = signature_bytes[32:64]
    v = signature_bytes[64] - 27  # Subtract 27 to make it 0 or 1
    signature_bytes = r + s + v.to_bytes(1, 'big')
    signature_obj = Signature(signature_bytes)

    public_key = signature_obj.recover_public_key_from_msg_hash(message_hash)
    return public_key.to_base58check_address()

I wrote this code after looking at the implementation of verifyMessageV2 in TronWeb, I hope it will be useful for those who face the same problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant