|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import hashlib |
| 4 | + |
| 5 | +import secp256k1 |
| 6 | +from ripemd.ripemd160 import ripemd160 |
| 7 | + |
| 8 | +from pactus.crypto.address import Address, AddressType |
| 9 | +from pactus.crypto.hrp import HRP |
| 10 | +from pactus.utils import utils |
| 11 | + |
| 12 | +from .signature import SIGNATURE_TYPE_SECP256K1, Signature |
| 13 | + |
| 14 | +PUBLIC_KEY_SIZE = 33 # Compressed public key |
| 15 | + |
| 16 | + |
| 17 | +class PublicKey: |
| 18 | + def __init__(self, pub: secp256k1.PublicKey) -> None: |
| 19 | + self.pub = pub |
| 20 | + |
| 21 | + @classmethod |
| 22 | + def from_string(cls, text: str) -> PublicKey: |
| 23 | + hrp, typ, data = utils.decode_to_base256_with_type(text) |
| 24 | + |
| 25 | + if hrp != HRP.PUBLIC_KEY_HRP: |
| 26 | + msg = f"Invalid hrp: {hrp}" |
| 27 | + raise ValueError(msg) |
| 28 | + |
| 29 | + if typ != SIGNATURE_TYPE_SECP256K1: |
| 30 | + msg = f"Invalid Public key type: {typ}" |
| 31 | + raise ValueError(msg) |
| 32 | + |
| 33 | + if len(data) != PUBLIC_KEY_SIZE: |
| 34 | + msg = "Public key data must be 33 bytes long" |
| 35 | + raise ValueError(msg) |
| 36 | + |
| 37 | + pub_key = secp256k1.PublicKey(bytes(data), raw=True) |
| 38 | + |
| 39 | + return cls(pub_key) |
| 40 | + |
| 41 | + def raw_bytes(self) -> bytes: |
| 42 | + return self.pub.serialize(compressed=True) |
| 43 | + |
| 44 | + def string(self) -> str: |
| 45 | + return utils.encode_from_base256_with_type( |
| 46 | + HRP.PUBLIC_KEY_HRP, |
| 47 | + SIGNATURE_TYPE_SECP256K1, |
| 48 | + self.raw_bytes(), |
| 49 | + ) |
| 50 | + |
| 51 | + def account_address(self) -> Address: |
| 52 | + blake2b = hashlib.blake2b(digest_size=32) |
| 53 | + blake2b.update(self.raw_bytes()) |
| 54 | + hash_256 = blake2b.digest() |
| 55 | + hash_160 = ripemd160(hash_256) |
| 56 | + |
| 57 | + return Address(AddressType.SECP256K1_ACCOUNT, hash_160) |
| 58 | + |
| 59 | + def verify(self, msg: bytes, sig: Signature) -> bool: |
| 60 | + try: |
| 61 | + sig_compact = sig.raw_bytes() |
| 62 | + sig_deserialized = self.pub.ecdsa_deserialize_compact(sig_compact) |
| 63 | + return self.pub.ecdsa_verify(msg, sig_deserialized) |
| 64 | + |
| 65 | + # ruff: noqa: BLE001 # unable to fix this issue |
| 66 | + except Exception: |
| 67 | + return False |
0 commit comments