|
| 1 | +from importlib import import_module |
| 2 | +from typing import Any, Union |
| 3 | + |
| 4 | +from aleph_message.models import AlephMessage, Chain |
| 5 | + |
| 6 | +from aleph.sdk.chains.common import get_verification_buffer |
| 7 | +from aleph.sdk.query.responses import Post |
| 8 | + |
| 9 | +validator_chains_map = { |
| 10 | + # TODO: Add AVAX |
| 11 | + Chain.ETH: "ethereum", |
| 12 | + Chain.SOL: "sol", |
| 13 | + Chain.CSDK: "cosmos", |
| 14 | + Chain.DOT: "substrate", |
| 15 | + Chain.NULS2: "nuls2", |
| 16 | + Chain.TEZOS: "tezos", |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +def try_import_verify_signature(chain: str) -> Any: |
| 21 | + """Try to import a chain signature validator.""" |
| 22 | + try: |
| 23 | + return import_module(f"aleph.sdk.chains.{chain}").verify_signature |
| 24 | + except (ImportError, AttributeError): |
| 25 | + return None |
| 26 | + |
| 27 | + |
| 28 | +validators = { |
| 29 | + key: try_import_verify_signature(value) |
| 30 | + for key, value in validator_chains_map.items() |
| 31 | +} |
| 32 | +""" |
| 33 | +This is a dict containing all currently available signature validators, indexed by their Chain abbreviation. |
| 34 | +
|
| 35 | +Ex.: validators["SOL"] -> aleph.sdk.chains.solana.verify_signature() |
| 36 | +""" |
| 37 | + |
| 38 | + |
| 39 | +def verify_message_signature(message: Union[AlephMessage, Post]) -> None: |
| 40 | + """Verify the signature of a message, raise an error if invalid or unsupported. |
| 41 | + A BadSignatureError is raised when the signature is incorrect. |
| 42 | + A ValueError is raised when the chain is not supported or required dependencies are missing. |
| 43 | + """ |
| 44 | + if message.chain not in validators: |
| 45 | + raise ValueError(f"Chain {message.chain} is not supported.") |
| 46 | + validator = validators[message.chain] |
| 47 | + if validator is None: |
| 48 | + raise ValueError( |
| 49 | + f"Chain {message.chain} is not installed. Install it with `aleph-sdk-python[{message.chain}]`." |
| 50 | + ) |
| 51 | + signature = message.signature |
| 52 | + public_key = message.sender |
| 53 | + message = get_verification_buffer(message.dict()) |
| 54 | + validator(signature, public_key, message) |
0 commit comments