Skip to content

Commit e362ea2

Browse files
MHHukiewitzPsycojokerhoh
committed
feat: add aleph.sdk.security module
Co-authored-by: Laurent Peuch <[email protected]> Co-authored-by: Hugo Herter <[email protected]>
1 parent 6031c7e commit e362ea2

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/aleph/sdk/security.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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)

tests/unit/test_security.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
def test_validators_loaded():
2+
import aleph.sdk.security as security
3+
4+
assert any([validator is not None for validator in security.validators.values()])

0 commit comments

Comments
 (0)