Source code for pypergraph.keyring.accounts.dag_account

import hashlib
from typing import List

import base58
from cryptography.hazmat.primitives import serialization

from pypergraph.core.constants import PKCS_PREFIX, KeyringAssetType, NetworkId
from .ecdsa_account import EcdsaAccount


[docs] class DagAccount(EcdsaAccount): @property def decimals(self) -> int: return 8 @property def network_id(self) -> str: return NetworkId.Constellation.value @property def has_token_support(self) -> bool: return False @property def supported_assets(self) -> List[str]: return [KeyringAssetType.DAG.value]
[docs] @staticmethod def validate_address(address: str) -> bool: if not address: return False valid_len = len(address) == 40 valid_prefix = address.startswith("DAG") valid_parity = address[3].isdigit() and 0 <= int(address[3]) < 10 base58_part = address[4:] valid_base58 = ( len(base58_part) == 36 and base58_part == base58.b58encode(base58.b58decode(base58_part)).decode() ) return valid_len and valid_prefix and valid_parity and valid_base58
[docs] def get_public_key(self) -> str: public_key = self.wallet.public_key() public_bytes = public_key.public_bytes( encoding=serialization.Encoding.X962, format=serialization.PublicFormat.UncompressedPoint, ) return public_bytes.hex()
[docs] def get_address(self) -> str: return self.get_address_from_public_key(self.get_public_key())
[docs] def verify_message(self, msg: str, signature: str, says_address: str) -> bool: public_key = self.recover_signed_msg_public_key(msg, signature) actual_address = self.get_address_from_public_key(public_key) return says_address == actual_address
[docs] @staticmethod def sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
[docs] def get_address_from_public_key(self, public_key_hex: str) -> str: """ :param public_key_hex: The private key as a hexadecimal string. :return: The DAG address corresponding to the public key (node ID). """ if len(public_key_hex) == 128: public_key = PKCS_PREFIX + "04" + public_key_hex elif len(public_key_hex) == 130 and public_key_hex[:2] == "04": public_key = PKCS_PREFIX + public_key_hex else: raise ValueError("KeyStore :: Not a valid public key.") public_key = hashlib.sha256(bytes.fromhex(public_key)).hexdigest() public_key = base58.b58encode(bytes.fromhex(public_key)).decode() public_key = public_key[len(public_key) - 36 :] check_digits = "".join([char for char in public_key if char.isdigit()]) check_digit = 0 for n in check_digits: check_digit += int(n) if check_digit >= 9: check_digit = check_digit % 9 address = f"DAG{check_digit}{public_key}" return address