-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpublickey.py
53 lines (40 loc) · 1.36 KB
/
publickey.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
@ Author: Mr.Hat
@ Date: 2024/4/4 18:47
@ Description:
@ History:
"""
from __future__ import annotations
import base58
class PublicKey:
LENGTH = 32
def __init__(self, value: bytearray | bytes | int | str | list[int]):
if isinstance(value, str):
try:
self.byte_value = base58.b58decode(value)
except ValueError:
raise ValueError("Invalid public key.")
elif isinstance(value, int):
self.byte_value = bytes([value])
else:
self.byte_value = bytes(value)
if len(self.byte_value) != self.LENGTH:
raise ValueError("Invalid public key, the length is wrong.")
def __bytes__(self) -> bytes:
return (
self.byte_value
if len(self.byte_value) == self.LENGTH
else self.byte_value.rjust(self.LENGTH, b"\0")
)
def __repr__(self) -> str:
return str(self)
def __str__(self) -> str:
return self.base58_encode().decode("utf-8")
def __eq__(self, __value: object) -> bool:
if isinstance(__value, PublicKey):
return self.byte_value == __value.byte_value
return False
def base58_encode(self) -> bytes:
return base58.b58encode(bytes(self))
def base58_decode(self) -> bytes:
return base58.b58decode(self.byte_value)