@bijection(add_version) def remove_version(a: bytes) -> bytes: _a = bytearray(a) assert hex(_a[0]) == '0x80' return _a[1:] def add_checksum(a: bytes) -> bytes: assert len(a) == 33 return a + hashlib.sha256(hashlib.sha256(a).digest()).digest()[:4] @bijection(add_checksum) def remove_checksum(a: bytes) -> bytes: res = bytes(bytearray(a)[:-4]) checksum = bytes(bytearray(a)[-4:]) new_checksum = hashlib.sha256(hashlib.sha256(res).digest()).digest()[:4] assert checksum == new_checksum return res encode_privkey: Callable[[CF], str] = do(from_cf, int_to_byte, add_version, add_checksum, b58encode) decode_privkey: Callable[[str], CF] = ~encode_privkey def gen_random_privkey(): return encode_privkey(random_privkey())
from pyasn1.codec.der.decoder import decode as edr_decode import klefki.crypto.ecdsa as ecdsa from klefki.asn import signature as sig_asn from klefki.bitcoin.private import decode_privkey from klefki.bitcoin.public import decode_pubkey from klefki.bitcoin.utils import int_to_byte, byte_to_int, b64encode, b58encode from klefki.types.algebra.concrete import FiniteFieldCyclicSecp256k1 as CF from klefki.types.algebra.isomorphism import bijection, do @bijection(edr_encode) def decode_edr(value): return edr_decode(value, asn1Spec=sig_asn.ECDSA_Sig_Value())[0] sig_encode = do(edr_encode, b58encode) sig_decode = ~sig_encode def to_sigtype(sig): return tuple([v.value for v in sig]) @bijection(to_sigtype) def from_sigtype(sig): return tuple([CF(v) for v in sig]) def msgsig_to_bytes(v, r, s): return chr(v), int_to_byte(r), int_to_byte(s)
auth = sha256(sha256(priv).digest()).digest()[:4] res = priv + auth assert len(res) == 1 + 32 + 1 + 4 return res @bijection(wrap_key) def unwrap_key(key: bytes): return key[1: -5] def to_cf(a: int): return CF(a) @bijection(to_cf) def from_cf(a: CF) -> int: return a.value encode_privkey: Callable[[CF], str] = do( from_cf, int_to_byte, wrap_key, b58encode ) decode_privkey: Callable[[str], CF] = ~encode_privkey def gen_random_privkey(): return encode_privkey(random_privkey())