11import base64
22import hashlib
33import json
4- from typing import Union
4+ from pathlib import Path
5+ from typing import Optional , Union
56
67import ecdsa
78from cosmospy ._wallet import privkey_to_address , privkey_to_pubkey
9+ from ecdsa import BadSignatureError
810
911from .common import BaseAccount , get_fallback_private_key , get_verification_buffer
1012
@@ -52,7 +54,7 @@ def __init__(self, private_key=None, hrp=DEFAULT_HRP):
5254 async def sign_message (self , message ):
5355 message = self ._setup_sender (message )
5456 verif = get_verification_string (message )
55- base64_pubkey = base64 .b64encode (self .get_public_key (). encode () ).decode ("utf-8" )
57+ base64_pubkey = base64 .b64encode (self .get_public_key ()).decode ("utf-8" )
5658 signature = await self .sign_raw (verif .encode ("utf-8" ))
5759
5860 sig = {
@@ -78,17 +80,41 @@ def get_address(self) -> str:
7880 return privkey_to_address (self .private_key )
7981
8082 def get_public_key (self ) -> str :
81- return privkey_to_pubkey (self .private_key ). decode ()
83+ return privkey_to_pubkey (self .private_key )
8284
8385
84- def get_fallback_account (hrp = DEFAULT_HRP ):
85- return CSDKAccount (private_key = get_fallback_private_key (), hrp = hrp )
86+ def get_fallback_account (path : Optional [ Path ] = None , hrp = DEFAULT_HRP ):
87+ return CSDKAccount (private_key = get_fallback_private_key (path = path ), hrp = hrp )
8688
8789
8890def verify_signature (
8991 signature : Union [bytes , str ],
9092 public_key : Union [bytes , str ],
9193 message : Union [bytes , str ],
92- ) -> bool :
93- """TODO: Implement this"""
94- raise NotImplementedError ("Not implemented yet" )
94+ ):
95+ """
96+ Verifies a signature.
97+ Args:
98+ signature: The signature to verify. Can be a base64 encoded string or bytes.
99+ public_key: The public key to use for verification. Can be a base64 encoded string or bytes.
100+ message: The message to verify. Can be an utf-8 string or bytes.
101+ Raises:
102+ BadSignatureError: If the signature is invalid.!
103+ """
104+
105+ if isinstance (signature , str ):
106+ signature = base64 .b64decode (signature .encode ("utf-8" ))
107+ if isinstance (public_key , str ):
108+ public_key = base64 .b64decode (public_key )
109+ if isinstance (message , str ):
110+ message = message .encode ("utf-8" )
111+
112+ vk = ecdsa .VerifyingKey .from_string (public_key , curve = ecdsa .SECP256k1 )
113+
114+ try :
115+ vk .verify (
116+ signature , message , hashfunc = hashlib .sha256 ,
117+ )
118+ return True
119+ except Exception as e :
120+ raise BadSignatureError from e
0 commit comments