Created
June 27, 2021 11:15
-
-
Save miohtama/3dcb8425c0a1d8a6daba8036a9d7937a to your computer and use it in GitHub Desktop.
Ethereum address to for SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EthereumAddress(types.TypeDecorator): | |
"""SQLAlchemy class to store Ethereum addresses as binary in SQL database. | |
Ethereum address is 160 bits, the last bytes of 256 bit public key of the address's signer. | |
Ethereum address checksum is encoded in the case of hex letters. | |
We skip any Ethereum address checksum checks, as they slow down large data processing too much. | |
Any returned address data will be in lowercase. | |
""" | |
# Address is 20 bytes (160 bits) | |
impl = types.LargeBinary(20) | |
cache_ok = True | |
def load_dialect_impl(self, dialect): | |
return dialect.type_descriptor(types.LargeBinary(20)) | |
def process_bind_param(self, val: str, dialect): | |
assert val.startswith("0x"), f"Bad Ethereum address {val}" | |
val = bytearray.fromhex(val[2:]) | |
assert len(val) == 20, f"Ethereum address length not 160 bits: {val}" | |
return val | |
def process_result_value(self, val: bytes, dialect): | |
assert type(val) == bytes | |
assert len(val) == 20 | |
return "0x" + bytearray(val).hex() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment