Skip to content

Instantly share code, notes, and snippets.

@mmv08
Last active August 24, 2021 16:07
Show Gist options
  • Save mmv08/868451c00ef810c7046489b2e6f497ef to your computer and use it in GitHub Desktop.
Save mmv08/868451c00ef810c7046489b2e6f497ef to your computer and use it in GitHub Desktop.
python ecrecover
from hexbytes import HexBytes
from ethereum.utils import checksum_encode, ecrecover_to_pub, sha3
from typing import Tuple, Union
def signature_split(signatures: Union[bytes, str], pos: int = 0) -> Tuple[int, int, int]:
"""
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
"""
signatures = HexBytes(signatures)
signature_pos = 65 * pos
if len(signatures[signature_pos:signature_pos + 65]) < 65:
raise ValueError(
f'Signature must be at least 65 bytes {signatures.hex()}')
r = int.from_bytes(signatures[signature_pos:32 + signature_pos], 'big')
s = int.from_bytes(
signatures[32 + signature_pos:64 + signature_pos], 'big')
v = signatures[64 + signature_pos]
return v, r, s
contract_transaction_hash = HexBytes(
"0xec57e49d4625ffc09c99b0554931ee18ab272a07fbc53cf625723a9006945d99")
signature = HexBytes(
"0x1d15a31aa051266966c16c2766c95f2a444263ea5366a3f514699d46b1d31af91597e6aef9078e548c5c7d5f81ec87859136720040d1d67e77d9ebaf58a797b91c")
v, r, s = signature_split(signature)
encoded_64_address = ecrecover_to_pub(
HexBytes(contract_transaction_hash), v, r, s)
address_bytes = checksum_encode(sha3(encoded_64_address)[-20:])
print(address_bytes)
[tool.poetry]
name = "signature-recovery-py"
version = "0.1.0"
description = ""
authors = ["Shadowy SuperCoder <[email protected]>"]
[tool.poetry.dependencies]
ethereum = "2.3.2"
hexbytes = "0.1.0"
typing-extensions = "^3.10.0"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment