Created
October 9, 2023 22:03
-
-
Save earonesty/e49e99661705ee5fc209c431d91fd8fd to your computer and use it in GitHub Desktop.
very simple pub/priv key module using coincurve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import os | |
from hashlib import sha256 | |
from typing import Optional | |
import coincurve as secp256k1 | |
"""Minimalist pub/priv key classes for signing and verification based on coincurve""" | |
class PublicKey: | |
def __init__(self, raw_bytes: bytes) -> None: | |
""" | |
:param raw_bytes: The formatted public key. | |
:type data: bytes | |
""" | |
if isinstance(raw_bytes, PrivateKey): | |
self.raw_bytes = raw_bytes.public_key.raw_bytes | |
elif isinstance(raw_bytes, secp256k1.keys.PublicKey): | |
self.raw_bytes = raw_bytes.format(compressed=True)[2:] | |
elif isinstance(raw_bytes, secp256k1.keys.PublicKeyXOnly): | |
self.raw_bytes = raw_bytes.format() | |
elif isinstance(raw_bytes, str): | |
self.raw_bytes = bytes.fromhex(raw_bytes) | |
else: | |
self.raw_bytes = raw_bytes | |
def hex(self) -> str: | |
return self.raw_bytes.hex() | |
def verify(self, sig: bytes, message: bytes) -> bool: | |
pk = secp256k1.PublicKeyXOnly(self.raw_bytes) | |
return pk.verify(sig, message) | |
@classmethod | |
def from_hex(cls, hex: str) -> 'PublicKey': | |
return cls(bytes.fromhex(hex)) | |
def __repr__(self): | |
pubkey = self.hex() | |
return f'PublicKey({pubkey[:10]}...{pubkey[-10:]})' | |
def __eq__(self, other): | |
return isinstance(other, PublicKey) and self.raw_bytes == other.raw_bytes | |
def __hash__(self): | |
return hash(self.raw_bytes) | |
def __str__(self): | |
"""Return public key in hex form | |
:return: string | |
:rtype: str | |
""" | |
return self.hex() | |
def __bytes__(self): | |
"""Return raw bytes | |
:return: Raw bytes | |
:rtype: bytes | |
""" | |
return self.raw_secret | |
def test_cp(): | |
pk = PrivateKey() | |
pk2 = PrivateKey(pk.raw_secret) | |
assert pk == pk2 | |
def test_fromhex(): | |
pk = PrivateKey() | |
pk2 = PrivateKey.from_hex(pk.hex()) | |
assert pk == pk2 | |
def test_sig(): | |
pk = PrivateKey() | |
pub = pk.public_key | |
sig = pk.sign(b'1' * 32) | |
assert pub.verify(sig, b'1' * 32) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment