From dfda16a698d7ef3d79b9392228ea4a6a1d28305c Mon Sep 17 00:00:00 2001 From: MMDRZA <95309780+Pymmdrza@users.noreply.github.com> Date: Tue, 26 Sep 2023 01:42:00 +0300 Subject: [PATCH] upload new version `1.9.6` --- cryptofuzz/CLI.py | 78 +++ cryptofuzz/Wallet.py | 1194 ++++++++++++++++++++++++++++++++++++++++ cryptofuzz/__init__.py | 62 +++ cryptofuzz/__main__.py | 103 ++++ cryptofuzz/assest.py | 26 + cryptofuzz/bs58.py | 232 ++++++++ cryptofuzz/example.py | 310 +++++++++++ cryptofuzz/hd.py | 376 +++++++++++++ cryptofuzz/utils.py | 293 ++++++++++ 9 files changed, 2674 insertions(+) create mode 100644 cryptofuzz/CLI.py create mode 100644 cryptofuzz/Wallet.py create mode 100644 cryptofuzz/__init__.py create mode 100644 cryptofuzz/__main__.py create mode 100644 cryptofuzz/assest.py create mode 100644 cryptofuzz/bs58.py create mode 100644 cryptofuzz/example.py create mode 100644 cryptofuzz/hd.py create mode 100644 cryptofuzz/utils.py diff --git a/cryptofuzz/CLI.py b/cryptofuzz/CLI.py new file mode 100644 index 0000000..7bdeb4f --- /dev/null +++ b/cryptofuzz/CLI.py @@ -0,0 +1,78 @@ +import argparse, os, json +from .Wallet import * + + +red = "\033[91m" +green = "\033[92m" +yellow = "\033[93m" +magenta = "\033[95m" +cyan = "\033[96m" +white = "\033[97m" +reset = "\033[0m" + +parser = argparse.ArgumentParser(description="CryptoFuzz CLI") +parser.add_argument("-g", "--generate", action="store_true", help="Generate a new wallet") +parser.add_argument('-t', '--total', type=int, help="Number of wallets to generate") +parser.add_argument('-s', '--save', action="store_true", help="Save All Details OutputFile.txt") + +args = parser.parse_args() + +FileName_Output = "OutputFile.json" +current_directory = os.getcwd() +filePath = os.path.join(current_directory, FileName_Output) +jsonFile = open(filePath, 'a') +jsonFile.write("[\n") +count = 0 +if args.generate: + if args.total: + for i in range(args.total): + pvk = getPrivateKey() + wif_compress = PrivateKey_To_Wif(pvk, True) + wif_uncompress = PrivateKey_To_Wif(pvk, False) + mnemonic_str = PrivateKey_To_Mnemonic(pvk) + xprv = PrivateKey_To_XPRV(pvk) + xpub = PrivateKey_To_XPUB(pvk) + dec = PrivateKey_To_Decimal(pvk) + bin_ = PrivateKey_To_Binary(pvk) + caddr = PrivateKey_To_CompressAddr(pvk) + uaddr = PrivateKey_To_UncompressAddr(pvk) + bin1 = str(bin_[0:16]) + bin2 = str(bin_[-16:]) + mnStr = mnemonic_str[0:64] + data_Content = { + f"Private Key ": f"{pvk}", + f"WIF Compress ": f"{wif_compress}", + f"WIF UnCompress ": f"{wif_uncompress}", + f"Mnemonic ": f"{mnStr}...", + f"XPRV ": f"{xprv}", + f"XPUB ": f"{xpub}", + f"Decimal ": f"{dec}", + f"Binary ": f"{bin1}...{bin2}", + f"Address Compress ": f"{caddr}", + f"Address UnCompress": f"{uaddr}" + } + dataContent = { + "Private Key": pvk, + "WIF Compress": wif_compress, + "WIF UnCompress": wif_uncompress, + "Mnemonic": mnemonic_str, + "XPRV": xprv, + "XPUB": xpub, + "Decimal": dec, + "Binary": bin_, + "Address Compress": caddr, + "Address UnCompress": uaddr + } + + outputstr = json.dumps(data_Content, indent=4) + print(outputstr) + if args.save: + count += 1 + json.dump(dataContent, jsonFile, indent=4) + if count % args.total == 0: + jsonFile.write("\n") + else: + jsonFile.write(",\n") + jsonFile.write(']\n') + else: + print("Number of wallets must be greater than 0") diff --git a/cryptofuzz/Wallet.py b/cryptofuzz/Wallet.py new file mode 100644 index 0000000..66cb2b9 --- /dev/null +++ b/cryptofuzz/Wallet.py @@ -0,0 +1,1194 @@ +# programmer and owner mmdrza.com +import os + +from . import Generator, Convertor +from . import ( + Bitcoin, BitcoinGold, Dash, DigiByte, Dogecoin, Ethereum, Litecoin, Qtum, Ravencoin, Tron, Zcash +) + +# ---------------------------------------------------------- +convertor = Convertor() +generator = Generator() + + +# ---------------------------------------------------------- +def getPrivateKey() -> str: + """ + + Generate a private key without repeating. + :return private key: + :rtype str: + + + --------------------------------------------------- + + >>> Privatekey = getPrivateKey() + + --------------------------------------------------- + """ + return generator.generate_private_key() + + +# ---------------------------------------------------------- +def getMnemonic(size: int = 12) -> str: + """ + + Generate Random Standard Mnemonic BIP39. + + :param size: + :type size: Int + :return mnemonic: + :rtype str: + + -------------------------------------------------- + + >>> Mnemonic = getMnemonic() + + -------------------------------------------------- + + """ + return generator.generate_mnemonic(size=size) + +# ---------------------------------------------------------- +def getBinary() -> str: + """ + + Generate random Binary With Length 256 (256 bits). + + :rtype str: + :return binary: + + + ------------------------------------------------- + + >>> Binary = getBinary() + + ------------------------------------------------ + + """ + return generator.generate_binary() + +# ---------------------------------------------------------- +def getRootKey() -> str: + """ + + Generate Root Key. + + :rtype str: + :return root key: + + ------------------------------------------------ + + >>> RootKey = getRootKey() + + ------------------------------------------------ + + """ + + return generator.generate_xprv() + +# ------------------------------------------------------------------- +def getBytes() -> bytes: return os.urandom(32) + +# ------------------------------------------------------------------- +def getDecimal() -> int: return generator.generate_decimal() + +# ------------------------------------------------------------------- +def PrivateKey_To_Addr(hexed: str, compress: bool = False) -> str: + """ + + Convert Private key Hex To Compress and UnCompress Address. + + :param hexed: + :type hexed: str + :param compress: + :type compress: bool + :return address: + :rtype str: + + ---------------------------------------------------------- + + >>> privatekey = "0A97965...A45517" # example Private Key + >>> address_compress = PrivateKey_To_Addr(privatekey, True) + >>> address_uncompress = PrivateKey_To_Addr(privatekey, False) + + ---------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + if compress: + return convertor.bytes_to_addr(seed, True) + else: + return convertor.bytes_to_addr(seed, False) + + +# ---------------------------------------------------------- +def PrivateKey_To_Wif(hexed: str, compress: bool = False) -> str: + """ + + Convert Private key Hex To Compress and UnCompress WIF. + + :param hexed: + :type hexed: str + :param compress: + :type compress: bool + :return wif: + :rtype str: + + ------------------------------------------------------------ + + >>> privatekey = "0A97965...A45517" # example Private Key + >>> wif_compress = PrivateKey_To_Wif(privatekey, True) + >>> wif_uncompress = PrivateKey_To_Wif(privatekey, False) + + ------------------------------------------------------------ + + """ + + seed = convertor.hex_to_bytes(hexed) + if compress: + return convertor.bytes_to_wif(seed, True) + else: + return convertor.bytes_to_wif(seed, False) + + +# ---------------------------------------------------------- +def PrivateKey_To_PublicKey(hexed: str, compress: bool = False) -> str: + """ + + Convert Private key Hex To compress and uncompress Public Key. + + :param hexed: + :type hexed: str + :param compress: + :type compress: bool + :return public key: + :rtype str: + + ------------------------------------------------ + + >>> privatekey = "0A97965...A45517" # example Private Key + >>> publickey_compress = PrivateKey_To_PublicKey(privatekey, True) + >>> publickey_uncompress = PrivateKey_To_PublicKey(privatekey, False) + + ------------------------------------------------ + + """ + seed = convertor.hex_to_bytes(hexed) + if compress: + return convertor.bytes_to_public(seed, True).hex() + else: + return convertor.bytes_to_public(seed, False).hex() + + +# ---------------------------------------------------------- +def PrivateKey_To_Mnemonic(hexed: str) -> str: + """ + + Convert Private key Hex To Mnemonic. + + :param hexed: + :type hexed: str + :return mnemonic: + :rtype str: + + -------------------------------------------------------- + + >>> privatekey = "0A97965...A45517" # example Private Key + >>> mnemonic = PrivateKey_To_Mnemonic(privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_mne(seed) + + +# ---------------------------------------------------------- +def PrivateKey_To_Byte(hexed: str) -> bytes: + """ + + Convert Private key Hex To Byte. + + :param hexed: + :type hexed: Str. + :return byte: + :rtype bytes: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> byte = PrivateKey_To_Byte(Privatekey) + + -------------------------------------------------------- + """ + return convertor.hex_to_bytes(hexed) + + +# ---------------------------------------------------------- +def PrivateKey_To_Binary(hexed: str) -> str: + """ + + Convert Private key Hex To Binary. + + :param hexed: + :type hexed: Str + :return binary: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> binary = PrivateKey_To_Binary(Privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_binary(seed) + + +# ---------------------------------------------------------- +def PrivateKey_To_Decimal(hexed: str) -> int: + """ + + Convert Private key Hex To Decimal. + + :param hexed: + :type hexed: Str + :return decimal: + :rtype int: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> decimal = PrivateKey_To_Decimal(Privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_int(seed) + + +# ---------------------------------------------------------- +def PrivateKey_To_XPRV(hexed: str) -> str: + """ + + Convert Private key Hex To XPRV. + + :param hexed: + :type hexed: Str + :return xprv: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> xprv = PrivateKey_To_XPRV(Privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_xprv(seed) + + +# ---------------------------------------------------------- +def PrivateKey_To_CompressAddr(hexed: str) -> str: + """ + + Convert Private key Hex To Compress Address. + + :param hexed: + :type hexed: Str + :return address: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> address_compress = PrivateKey_To_CompressAddr(Privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_addr(seed, True) + + +# ---------------------------------------------------------- +def PrivateKey_To_UncompressAddr(hexed: str) -> str: + """ + + Convert Private key Hex To UnCompress Address. + + :param hexed: + :type hexed: Str + :return address: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> address_uncompress = PrivateKey_To_UncompressAddr(Privatekey) + + -------------------------------------------------------- + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_addr(seed, False) + + +# ---------------------------------------------------------- +def PrivateKey_To_XPUB(hexed: str) -> str: + """ + + Convert Private key Hex To XPUB. + + :param hexed: + :type hexed: Str + :return xpub: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> xpub = PrivateKey_To_XPUB(Privatekey) + + -------------------------------------------------------- + + + """ + seed = convertor.hex_to_bytes(hexed) + return convertor.bytes_to_xpub(seed) + + +# ---------------------------------------------------------- +def Bytes_To_PrivateKey(byte: bytes) -> str: + """ + + Convert Byte To Private Key. + + :param byte: + :type byte: Bytes + :return private key: + :rtype str: + + -------------------------------------------------------- + + >>> Privatekey = "0A97965...A45517" # example Private Key + >>> privatekey = Bytes_To_PrivateKey(Privatekey) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_hex(byte) + + +# ---------------------------------------------------------- +def Bytes_To_Address(seed: bytes, compress: bool = False): + """ + + Convert Bytes To Compressed and Uncompressed Address. + + + :param seed: + :type seed: Bytes + :param compress: + :type compress: bool + :return address: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> address_compress = Bytes_To_Address(seedBytes, True) + >>> address_uncompress = Bytes_To_Address(seedBytes, False) + + -------------------------------------------------------- + + """ + if compress: + return convertor.bytes_to_addr(seedBytes=seed, compress=True) + else: + return convertor.bytes_to_addr(seedBytes=seed, compress=False) + + +# ---------------------------------------------------------- +def Bytes_To_Mnemonic(seed: bytes) -> str: + """ + + + Convert Bytes To Mnemonic. + + :param seed: + :type seed: Bytes + :return mnemonic: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> mnemonic = Bytes_To_Mnemonic(seedBytes) + + -------------------------------------------------------- + + + """ + return convertor.bytes_to_mne(seed) + + +# ---------------------------------------------------------- +def Bytes_To_XPRV(seed: bytes) -> str: + """ + + Convert Bytes To XPRV. + + :param seed: + :type seed: Bytes + :return xprv: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> xprv = Bytes_To_XPRV(seedBytes) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_xprv(seed) + + +# ---------------------------------------------------------- +def Bytes_To_Binary(seed: bytes): + """ + + Convert Bytes To Binary. + + :param seed: + :type seed: Bytes + :return binary: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> binary = Bytes_To_Binary(seedBytes) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_binary(seed) + + +# ---------------------------------------------------------- +def Bytes_To_PublicKey(seed: bytes, compress: bool = False): + """ + + Convert Bytes To Public Key Compressed and Uncompressed. + + :param seed: + :type seed: Bytes + :param compress: + :type compress: bool + :return public: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> public_compress = Bytes_To_PublicKey(seedBytes, True) + >>> public_uncompress = Bytes_To_PublicKey(seedBytes, False) + + -------------------------------------------------------- + + """ + + if compress: + return convertor.bytes_to_public(seed, True).hex() + else: + return convertor.bytes_to_public(seed, False).hex() + + +# ---------------------------------------------------------- +def Bytes_To_Compress_Addr(seed: bytes) -> str: + """ + + Convert Bytes To Compressed Address. + + :param seed: + :type seed: Bytes + :return address: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> address_compress = Bytes_To_Compress_Addr(seedBytes) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_addr(seed, True) + + +# ---------------------------------------------------------- +def Bytes_To_Uncompress_Addr(seed: bytes) -> str: + """ + + Convert Bytes To Uncompressed Address. + + :param seed: + :type seed: Bytes + :return address: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> address_uncompress = Bytes_To_Uncompress_Addr(seedBytes) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_addr(seed, False) + + +# ---------------------------------------------------------- +def Bytes_To_Decimal(seed: bytes): + """ + + Convert Bytes To Decimal. + + :param seed: + :type seed: Bytes + :return decimal: + :rtype int: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> decimal = Bytes_To_Decimal(seedBytes) + + -------------------------------------------------------- + + """ + return convertor.bytes_to_int(seed) + + +# ---------------------------------------------------------- +def Bytes_To_XPUB(seed: bytes) -> str: + return convertor.bytes_to_xpub(seed) + +# ---------------------------------------------------------- +def Bytes_To_Wif(seed: bytes, compress: bool = False) -> str: + """ + + Convert Bytes To Wif Compressed and UnCompressed. + + :param seed: + :type seed: Bytes + :param compress: + :type compress: bool + :return wif: + :rtype str: + + -------------------------------------------------------- + + >>> seedBytes = b"\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00" # example seed + >>> wif_compress = Bytes_To_Wif(seedBytes, True) + >>> wif_uncompress = Bytes_To_Wif(seedBytes, False) + + -------------------------------------------------------- + + + """ + if compress: + return convertor.bytes_to_wif(seed, True) + else: + return convertor.bytes_to_wif(seed, False) + + +# ---------------------------------------------------------- +def Mnemonic_To_Bytes(mnemonic: str) -> bytes: + return convertor.mne_to_seed(mnemonic=mnemonic) + + +# ---------------------------------------------------------- +def Mnemonic_To_PrivateKey(mnemonic: str) -> str: + seed = convertor.mne_to_seed(mnemonic=mnemonic) + return convertor.bytes_to_hex(seed=seed) + + +# ---------------------------------------------------------- +def Mnemonic_To_PublicKey(mnemonic: str, compress: bool = False): + seed = convertor.mne_to_seed(mnemonic=mnemonic) + if compress: + pub = convertor.bytes_to_public(seed, True).hex() + return convertor.pub_to_addr(pub) + else: + pub = convertor.bytes_to_public(seed, False).hex() + return convertor.pub_to_addr(pub) + + +# ---------------------------------------------------------- +def Mnemonic_To_Decimal(mnemonic: str): + seed = convertor.mne_to_seed(mnemonic=mnemonic) + return convertor.bytes_to_int(seed) + + +# ---------------------------------------------------------- +def Mnemonic_To_Binary(mnemonic: str): + seed = convertor.mne_to_seed(mnemonic=mnemonic) + return convertor.bytes_to_binary(seed) + + +# ---------------------------------------------------------- +def Mnemonic_To_XPRV(mnemonic: str): + seedBytes = convertor.mne_to_seed(mnemonic) + return convertor.bytes_to_xprv(seedBytes) + + +# ---------------------------------------------------------- +def Mnemonic_To_Addr(mnemonic: str, compress: bool = False) -> str: + seedBytes = convertor.mne_to_seed(mnemonic) + if compress: + return convertor.bytes_to_addr(seedBytes, True) + else: + return convertor.bytes_to_addr(seedBytes, False) + + +# ---------------------------------------------------------- +def Mnemonic_To_XPUB(mnemonic: str): + seedBytes = convertor.mne_to_seed(mnemonic) + return convertor.bytes_to_xpub(seedBytes) + + +# ---------------------------------------------------------- +def Mnemonic_To_Wif(mnemonic: str, compress: bool = False) -> str: + seedBytes = convertor.mne_to_seed(mnemonic) + if compress: + return convertor.bytes_to_wif(seedBytes, True) + else: + return convertor.bytes_to_wif(seedBytes, False) + + +# ---------------------------------------------------------- +def Passphrase_To_Addr(passphrase: str, compress: bool = False) -> str: + if compress: + return convertor.pass_to_addr(passphrase, True) + else: + return convertor.pass_to_addr(passphrase, False) + + +# ---------------------------------------------------------- +def Passphrase_To_Bytes(passphrase: str) -> bytes: + return convertor.pass_to_bytes(passphrase) + + +# ---------------------------------------------------------- +def Passphrase_To_PrivateKey(passphrase: str) -> str: + return convertor.bytes_to_hex(convertor.pass_to_bytes(passphrase)) + + +# ---------------------------------------------------------- +def Passphrase_To_PublicKey(passphrase: str, compress: bool = False) -> str: + seed = convertor.pass_to_bytes(passphrase) + if compress: + return convertor.bytes_to_public(seed, True).hex() + else: + return convertor.bytes_to_public(seed, False).hex() + + +# ---------------------------------------------------------- +def Passphrase_To_Wif(passphrase: str, compress: bool = False) -> str: + seed = convertor.pass_to_bytes(passphrase) + if compress: + return convertor.bytes_to_wif(seed, True) + else: + return convertor.bytes_to_wif(seed, False) + + +# ---------------------------------------------------------- +def Passphrase_To_RootKey(passphrase: str) -> str: + seed = convertor.pass_to_bytes(passphrase) + return convertor.bytes_to_xprv(seed) + + +# ---------------------------------------------------------- +def Passphrase_To_XPUB(passphrase: str) -> str: + seed = convertor.pass_to_bytes(passphrase) + return convertor.bytes_to_xpub(seed) + + +# ---------------------------------------------------------- +def Passphrase_To_Decimal(passphrase: str) -> int: + seed = convertor.pass_to_bytes(passphrase) + return convertor.bytes_to_int(seed) + + +# ---------------------------------------------------------- +def Wif_To_Bytes(wif: str) -> bytes: + return convertor.wif_to_bytes(wif) + + +# ---------------------------------------------------------- +def Wif_To_Addr(wif: str, compress: bool = False) -> str: + return convertor.wif_to_addr(wif, compress) + + +# ---------------------------------------------------------- +def Wif_To_PrivateKey(wif: str) -> str: + return convertor.bytes_to_hex(convertor.wif_to_bytes(wif)) + + +# ---------------------------------------------------------- +def Wif_To_Mnemonic(wif: str) -> str: + return convertor.bytes_to_mne(convertor.wif_to_bytes(wif)) + + +# ---------------------------------------------------------- +def Wif_To_Decimal(wif: str) -> int: + return convertor.bytes_to_int(convertor.wif_to_bytes(wif)) + + +# ---------------------------------------------------------- +def Wif_To_Binary(wif: str) -> str: + return convertor.bytes_to_binary(convertor.wif_to_bytes(wif)) + + +# ---------------------------------------------------------- +def Wif_To_XPRV(wif: str) -> str: + return convertor.bytes_to_xprv(convertor.wif_to_bytes(wif)) + +# ---------------------------------------------------------- +def Wif_To_XPUB(wif: str) -> str: return convertor.bytes_to_xpub(convertor.wif_to_bytes(wif)) + +# ---------------------------------------------------------- +def Wif_To_RootKey(wif: str) -> str: + return Wif_To_XPRV(wif) + + +# ---------------------------------------------------------- +def Wif_To_PublicKey(wif: str, compress: bool = False): + seed = convertor.wif_to_bytes(wif) + if compress: + return convertor.bytes_to_public(seed, True).hex() + else: + return convertor.bytes_to_public(seed, False).hex() + + +# ---------------------------------------------------------- +def Decimal_To_PrivateKey(dec: int) -> str: + return "%064x" % dec + + +# ---------------------------------------------------------- +def Decimal_To_Bytes(dec: int) -> bytes: + return convertor.int_to_bytes(dec) + + +# ---------------------------------------------------------- +def Decimal_To_PublicKey(dec: int, compress: bool = False) -> str: + seed = Decimal_To_Bytes(dec) + if compress: + return convertor.bytes_to_public(seed, True).hex() + else: + return convertor.bytes_to_public(seed, False).hex() + + +# ---------------------------------------------------------- +def Decimal_To_Address(dec: int, compress: bool = False) -> str: + seed = Decimal_To_Bytes(dec) + if compress: + return convertor.bytes_to_addr(seed, True) + else: + return convertor.bytes_to_addr(seed, False) + + +# ---------------------------------------------------------- +def Decimal_To_Mnemonic(dec: int) -> str: + seed = convertor.int_to_bytes(dec) + return convertor.bytes_to_mne(seed) + + +# ---------------------------------------------------------- +def Decimal_To_XPRV(dec: int) -> str: + seed = convertor.int_to_bytes(dec) + return convertor.bytes_to_xprv(seed) + +# ---------------------------------------------------------- +def Decimal_To_XPUB(dec: int) -> str: + seed = convertor.int_to_bytes(dec) + return convertor.bytes_to_xpub(seed) + +# ---------------------------------------------------------- +def Decimal_To_Binary(dec: int) -> str: + seed = convertor.int_to_bytes(dec) + return convertor.bytes_to_binary(seed) + + +def Decimal_To_Wif(dec: int, compress: bool = False) -> str: + seed = convertor.int_to_bytes(dec) + if compress: + return convertor.bytes_to_wif(seed, True) + else: + return convertor.bytes_to_wif(seed, False) + +# ---------------------------------------------------------- +def Binary_To_Bytes(binary_str: str) -> bytes: + return convertor.binary_to_bytes(binary_str) + + +# ---------------------------------------------------------- +def Binary_To_Address(binary_str: str, compress: bool = False) -> str: + seed = convertor.binary_to_bytes(binary_str) + if compress: + return convertor.bytes_to_addr(seed, True) + else: + return convertor.bytes_to_addr(seed, False) + + +# ---------------------------------------------------------- +def Binary_To_PrivateKey(binary_str: str) -> str: return convertor.bytes_to_hex(convertor.binary_to_bytes(binary_str)) + + +# ---------------------------------------------------------- +def Binary_To_Mnemonic(binary_str: str) -> str: return convertor.bytes_to_mne(convertor.binary_to_bytes(binary_str)) + + +# ---------------------------------------------------------- +def Binary_To_XPRV(binary_str: str) -> str: return convertor.bytes_to_xprv(convertor.binary_to_bytes(binary_str)) + + +# ---------------------------------------------------------- +def Binary_To_XPUB(binary_str: str) -> str: return convertor.bytes_to_xpub(convertor.binary_to_bytes(binary_str)) + + +# ---------------------------------------------------------- +def Binary_To_Wif(binary_str: str, compress: bool = False) -> str: return convertor.bytes_to_wif(convertor.binary_to_bytes(binary_str), compress) + + +# ---------------------------------------------------------- +def Binary_To_PublicKey(binary_str: str, compress: bool = False) -> str: return convertor.bytes_to_public(convertor.binary_to_bytes(binary_str), compress).hex() + +# ---------------------------------------------------------- +def Binary_To_Decimal(binary_str: str) -> int: return convertor.bytes_to_int(convertor.binary_to_bytes(binary_str)) + + +# ---------------------------------------------------------- +def XPRV_To_Bytes(xprv: str) -> bytes: return convertor.xprv_to_bytes(xprv) + +def XPRV_To_PrivateKey(xprv: str) -> str: return convertor.bytes_to_hex(convertor.xprv_to_bytes(xprv)) + +def XPRV_To_PublicKey(xprv: str, compress: bool = False) -> str: return convertor.bytes_to_public(convertor.xprv_to_bytes(xprv), compress).hex() + +def XPRV_To_Wif(xprv: str, compress: bool = False) -> str: return convertor.bytes_to_wif(convertor.xprv_to_bytes(xprv), compress) + +def XPRV_To_Address(xprv: str, compress: bool = False) -> str: return convertor.bytes_to_addr(convertor.xprv_to_bytes(xprv), compress) + +def XPRV_To_Mnemonic(xprv: str) -> str: return convertor.bytes_to_mne(convertor.xprv_to_bytes(xprv)) + +def XPRV_To_XPUB(xprv: str) -> str: return convertor.bytes_to_xpub(convertor.xprv_to_bytes(xprv)) + +def XPRV_To_Decimal(xprv: str) -> int: return convertor.bytes_to_int(convertor.xprv_to_bytes(xprv)) + +# ---------------------------------------------------------- +def PrivateKey_To_Bitcoin_Addr(privatekey: str, Type: str = 'p2pkh') -> str: + """ + + Convert Private Key To Bitcoin All Type Address, Type: p2pkh, p2sh, p2wpkh, p2wsh, p2wpkh_p2sh, p2wsh_p2sh. + + :param privatekey: + :type privatekey: str + :param Type: + :type Type: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Bitcoin_Addr + + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> p2pkh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2pkh') + >>> p2sh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2sh') + >>> p2wpkh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2wpkh') + >>> p2wsh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2wsh') + >>> p2wpkh_p2sh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2wpkh_p2sh') + >>> p2wsh_p2sh = PrivateKey_To_Bitcoin_Addr(Privatekey, 'p2wsh_p2sh') + + -------------------------------------------------------- + + + """ + BTC = Bitcoin() + if Type == 'p2pkh': return BTC.hex_addr(privatekey, 'p2pkh') + elif Type == 'p2sh': return BTC.hex_addr(privatekey, 'p2sh') + elif Type == 'p2wpkh': return BTC.hex_addr(privatekey, 'p2wpkh') + elif Type == 'p2wsh': return BTC.hex_addr(privatekey, 'p2wsh') + elif Type == 'p2wpkh_p2sh': return BTC.hex_addr(privatekey, 'p2wpkh_p2sh') + elif Type == 'p2wsh_p2sh': return BTC.hex_addr(privatekey, 'p2wsh_p2sh') + else: return BTC.hex_addr(privatekey, 'p2pkh') + +# ---------------------------------------------------------- +def PrivateKey_To_Ethereum_Addr(privatekey: str) -> str: + + """ + + Convert Private Key To Ethereum Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Ethereum_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Ethereum_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + ETH = Ethereum() + return ETH.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_BitcoinGold_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Bitcoin Gold Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_BitcoinGold_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_BitcoinGold_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + BTG = BitcoinGold() + return BTG.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Dash_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Dash Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Dash_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Dash_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + DASH = Dash() + return DASH.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_DigiByte_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Digibyte Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Digibyte_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_DigiByte_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + DGB = DigiByte() + return DGB.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Tron_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Tron Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Tron_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Tron_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + TRX = Tron() + return TRX.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Litecoin_Addr(privatekey: str, Type: str = 'p2pkh') -> str: + """ + + Convert Private Key To Litecoin Address. + + :param privatekey: + :type privatekey: str + :param Type: + :type Type: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Litecoin_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> p2pkh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2pkh') + >>> p2sh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2sh') + >>> p2wpkh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2wpkh') + >>> p2wsh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2wsh') + >>> p2wpkh_p2sh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2wpkh_p2sh') + >>> p2wsh_p2sh = PrivateKey_To_Litecoin_Addr(Privatekey, 'p2wsh_p2sh') + + -------------------------------------------------------- + + """ + LTC = Litecoin() + if Type == 'p2pkh': return LTC.hex_addr(privatekey, 'p2pkh') + elif Type == 'p2sh': return LTC.hex_addr(privatekey, 'p2sh') + elif Type == 'p2wpkh': return LTC.hex_addr(privatekey, 'p2wpkh') + elif Type == 'p2wsh': return LTC.hex_addr(privatekey, 'p2wsh') + elif Type == 'p2wpkh_p2sh': return LTC.hex_addr(privatekey, 'p2wpkh_p2sh') + elif Type == 'p2wsh_p2sh': return LTC.hex_addr(privatekey, 'p2wsh_p2sh') + else: return LTC.hex_addr(privatekey, 'p2pkh') + +# ---------------------------------------------------------- +def PrivateKey_To_Zcash_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Zcash Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Zcash_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Zcash_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + ZEC = Zcash() + return ZEC.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Qtum_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Qtum Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Qtum_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Qtum_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + QTUM = Qtum() + return QTUM.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Ravencoin_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Ravencoin Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Ravencoin_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Ravencoin_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + RVN = Ravencoin() + return RVN.hex_addr(privatekey) + +# ---------------------------------------------------------- +def PrivateKey_To_Dogecoin_Addr(privatekey: str) -> str: + """ + + Convert Private Key To Dogecoin Address. + + :param privatekey: + :type privatekey: str + :returns: + + + -------------------------------------------------------- + + >>> from cryptofuzz.Wallet import PrivateKey_To_Dogecoin_Addr + >>> Privatekey = "e3bfc1c...ca52b8" # example key + >>> addr = PrivateKey_To_Dogecoin_Addr(Privatekey) + + -------------------------------------------------------- + + + """ + DOGE = Dogecoin() + return DOGE.hex_addr(privatekey) + + + + + +if __name__ == "__main__" and __package__ is None: + __package__ = "cryptofuzz" diff --git a/cryptofuzz/__init__.py b/cryptofuzz/__init__.py new file mode 100644 index 0000000..9e94190 --- /dev/null +++ b/cryptofuzz/__init__.py @@ -0,0 +1,62 @@ +# Programmer: Mmdrza.Com + +# Import modules +from .utils import Convertor, Generator +from .hd import ( + Axe, + Bitcoin, + BitcoinGold, + Dash, + DigiByte, + Dogecoin, + Ethereum, + Litecoin, + Qtum, + Ravencoin, + Tron, + Zcash, +) + +# Metadata +__version__ = "v1.3.6" +__license__ = "MIT" +__author__ = "Mohammadreza (MMDRZA)" +__email__ = "PyMmdrza@gmail.com" +__description__ = ("Generated and Converted Keys with any Type Foundation from " + "Private Key [WIF Hexed Mnemonic and Binary Bytes seed] in Python") + +# Publicly exposed elements +__all__ = [ + # Metadata + "__version__", + "__license__", + "__author__", + "__email__", + "__description__", + + # Core modules + "Wallet", + "assest", + "bs58", + "utils", + "hd", + "CLI", + + # Classes + "Convertor", + "Generator", + + # Blockchain-specific classes + "Axe", + "Bitcoin", + "BitcoinGold", + "Dash", + "DigiByte", + "Dogecoin", + "Ethereum", + "Litecoin", + "Qtum", + "Ravencoin", + "Tron", + "Zcash" +] diff --git a/cryptofuzz/__main__.py b/cryptofuzz/__main__.py new file mode 100644 index 0000000..0f95f27 --- /dev/null +++ b/cryptofuzz/__main__.py @@ -0,0 +1,103 @@ +from .Wallet import ( + + # Conversions related to Binary ------------------------------------------------------------ + + Binary_To_Address, # Convert binary to address + Binary_To_Decimal, # Convert binary to decimal Number + Binary_To_Bytes, # Convert binary to bytes + Binary_To_Mnemonic, # Convert binary to mnemonic + Binary_To_PrivateKey, # Convert binary to private key + Binary_To_PublicKey, # Convert binary to publickey + Binary_To_Wif, # Convert binary to WIF + Binary_To_XPRV, # Convert binary to XPRV + + # Conversions related to Bytes ------------------------------------------------------------ + + Bytes_To_Address, # Convert bytes to address + Bytes_To_Binary, # Convert bytes to binary + Bytes_To_Mnemonic, # Convert bytes to mnemonic + Bytes_To_PrivateKey, # Convert bytes to privatekey + Bytes_To_PublicKey, # Convert bytes to publickey + Bytes_To_Wif, # Convert bytes to WIF + Bytes_To_XPRV, # Convert bytes to XPRV + Bytes_To_XPUB, # Convert bytes to XPUB + + # Conversions related to Decimal ------------------------------------------------------------ + + Decimal_To_Address, # Convert decimal to address + Decimal_To_Binary, # Convert decimal to binary + Decimal_To_Bytes, # Convert decimal to bytes + Decimal_To_Mnemonic, # Convert decimal to mnemonic + Decimal_To_Wif, # Convert decimal to WIF + Decimal_To_XPRV, # Convert decimal to XPRV + + + # Generate Random Keys ------------------------------------------------------------------------ + Decimal_To_XPUB, # Convert decimal to XPUB + getBinary, # Generate random Binary With Length 256 (256 bits). + getBytes, # Generate Random Seed (Bytes - Without Repeating). + getDecimal, # Generate Random Decimal Number. + getMnemonic, # Generate Random Standard Mnemonic BIP39. + getPrivateKey, # Generate a private key without repeating. + getRootKey, # Generate a root key. + + # Conversions related to Mnemonic ------------------------------------------------------------ + + Mnemonic_To_Addr, # Convert mnemonic to address + Mnemonic_To_Binary, # Convert mnemonic to binary + Mnemonic_To_Bytes, # Convert mnemonic to bytes + Mnemonic_To_Decimal, # Convert mnemonic to decimal + Mnemonic_To_PrivateKey, # Convert mnemonic to privatekey + Mnemonic_To_PublicKey, # Convert mnemonic to publickey + Mnemonic_To_Wif, # Convert mnemonic to WIF + Mnemonic_To_XPRV, # Convert mnemonic to XPRV + Mnemonic_To_XPUB, # Convert mnemonic to XPUB + + # Conversions related to Passphrase ------------------------------------------------------------ + + Passphrase_To_Addr, # Convert passphrase to address + Passphrase_To_Bytes, # Convert passphrase to bytes + Passphrase_To_Decimal, # Convert passphrase to decimal representation + Passphrase_To_PrivateKey, # Convert passphrase to privatekey + Passphrase_To_PublicKey, # Convert passphrase to publickey + Passphrase_To_RootKey, # Convert passphrase to rootkey + Passphrase_To_Wif, # Convert passphrase to WIF + Passphrase_To_XPUB, # Convert passphrase to XPUB + + # Conversions related to Private Keys ------------------------------------------------------------ + + PrivateKey_To_Addr, # Convert private key to address + PrivateKey_To_Binary, # Convert private key to binary representation + PrivateKey_To_Byte, # Convert private key to bytes + PrivateKey_To_CompressAddr, # Convert private key to compressed address + PrivateKey_To_Decimal, # Convert private key to decimal representation (appears twice, may want to remove one) + PrivateKey_To_Mnemonic, # Convert private key to mnemonic + PrivateKey_To_UncompressAddr, # Convert private key to uncompressed address + PrivateKey_To_Wif, # Convert private key to WIF + PrivateKey_To_XPRV, # Convert private key to XPRV + PrivateKey_To_XPUB, # Convert private key to XPUB + + # Conversions related to WIF ------------------------------------------------------------ + + Wif_To_Addr, # Convert WIF to address + Wif_To_Binary, # Convert WIF to binary + Wif_To_Bytes, # Convert WIF to bytes + Wif_To_Decimal, # Convert WIF to decimal + Wif_To_Mnemonic, # Convert WIF to mnemonic + Wif_To_PrivateKey, # Convert WIF to privatekey + Wif_To_PublicKey, # Convert WIF to publickey + Wif_To_RootKey, # Convert WIF to rootkey + Wif_To_XPRV, # Convert WIF to XPRV + Wif_To_XPUB, # Convert WIF to XPUB + + # Conversions related to XPRV ------------------------------------------------------------ + + XPRV_To_Address, # Convert XPRV to address compressed & uncompressed + XPRV_To_Wif, # Convert XPRV to WIF compressed & uncompressed + XPRV_To_XPUB, # Convert XPRV to XPUB + XPRV_To_Bytes, # Convert XPRV to bytes + XPRV_To_Mnemonic, # Convert XPRV to mnemonic + XPRV_To_PrivateKey, # Convert XPRV to privatekey + XPRV_To_PublicKey, # Convert XPRV to publickey compressed & uncompressed + XPRV_To_Decimal, # Convert XPRV to decimal +) diff --git a/cryptofuzz/assest.py b/cryptofuzz/assest.py new file mode 100644 index 0000000..042ee05 --- /dev/null +++ b/cryptofuzz/assest.py @@ -0,0 +1,26 @@ +# script + +BITCOIN_ALPHABET = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +RIPPLE_ALPHABET = b'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz' +BIP39 = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo" +BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +ZERO_BASE_NET = "0000000000000000000000000000000000000000000000000000000000000000" +ZERO_BYTES = b'\x00\x00\x00\x00' +# main +MAIN_PREFIX = b'\x80' +MAIN_SUFFIX = b'\x01' +COMPRESSED_PREFIX = b'\x03' +COMPRESSED_PREFIX2 = b'\x02' +UNCOMPRESSED_PREFIX = b'\x04' +MAIN_DIGEST_RMD160 = b"\x00" +MAIN_DIGEST = b"\x00" +MAX_PRIVATE_KEY = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 +VERSION_NETWORK = b'\x04\x88\xAD\xE4' +FINGERPRINT_RMD160 = ZERO_BYTES +FINGERPRINT_ZERO = ZERO_BYTES + ZERO_BYTES + + +# address encode +TRON_PREFIX = b'\x41' +BCH_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" +XPUB_PREFIX = "0488B21E" \ No newline at end of file diff --git a/cryptofuzz/bs58.py b/cryptofuzz/bs58.py new file mode 100644 index 0000000..b52d9f8 --- /dev/null +++ b/cryptofuzz/bs58.py @@ -0,0 +1,232 @@ +from functools import lru_cache +from hashlib import sha256 +from typing import Mapping, Union +from .assest import ( + BITCOIN_ALPHABET as ALPHABET, + RIPPLE_ALPHABET as XRP_ALPHABET, + BASE58_ALPHABET, + MAIN_DIGEST_RMD160 +) + + +def scrub_input(v: Union[str, bytes]) -> bytes: + if isinstance(v, str): + v = v.encode('ascii') + + return v + + +def b58encode_int( + i: int, default_one: bool = True, alphabet: bytes = ALPHABET +) -> bytes: + """ + Encode an integer using Base58 + """ + if not i and default_one: + return alphabet[0:1] + string = b"" + base = len(alphabet) + while i: + i, idx = divmod(i, base) + string = alphabet[idx:idx+1] + string + return string + + +def b58encode( + v: Union[str, bytes], alphabet: bytes = ALPHABET +) -> bytes: + """ + Encode a string using Base58 + """ + v = scrub_input(v) + + mainSize = len(v) + v = v.lstrip(b'\0') + newSize = len(v) + + acc = int.from_bytes(v, byteorder='big') # first byte is most significant + + result = b58encode_int(acc, default_one=False, alphabet=alphabet) + return alphabet[0:1] * (mainSize - newSize) + result + + +@lru_cache() +def _get_base58_decode_map(alphabet: bytes, + autofix: bool) -> Mapping[int, int]: + invmap = {char: index for index, char in enumerate(alphabet)} + + if autofix: + groups = [b'0Oo', b'Il1'] + for group in groups: + pivots = [c for c in group if c in invmap] + if len(pivots) == 1: + for alternative in group: + invmap[alternative] = invmap[pivots[0]] + + return invmap + + +def b58decode_int( + v: Union[str, bytes], alphabet: bytes = ALPHABET, *, + autofix: bool = False +) -> int: + """ + Decode a Base58 encoded string as an integer + """ + if b' ' not in alphabet: + v = v.rstrip() + v = scrub_input(v) + + map = _get_base58_decode_map(alphabet, autofix=autofix) + + decimal = 0 + base = len(alphabet) + try: + for char in v: + decimal = decimal * base + map[char] + except KeyError as e: + raise ValueError( + "Invalid character {!r}".format(chr(e.args[0])) + ) from None + return decimal + + +def b58decode( + v: Union[str, bytes], alphabet: bytes = ALPHABET, *, + autofix: bool = False +) -> bytes: + """ + Decode a Base58 encoded string + """ + v = v.rstrip() + v = scrub_input(v) + + mainSize = len(v) + v = v.lstrip(alphabet[0:1]) + newSize = len(v) + + acc = b58decode_int(v, alphabet=alphabet, autofix=autofix) + + return acc.to_bytes(mainSize - newSize + (acc.bit_length() + 7) // 8, 'big') + + +def b58encode_check( + v: Union[str, bytes], alphabet: bytes = ALPHABET +) -> bytes: + """ + Encode a string using Base58 with a 4 character checksum + """ + v = scrub_input(v) + + digest = sha256(sha256(v).digest()).digest() + return b58encode(v + digest[:4], alphabet=alphabet) + + +def b58decode_check( + v: Union[str, bytes], alphabet: bytes = ALPHABET, *, + autofix: bool = False +) -> bytes: + """Decode and verify the checksum of a Base58 encoded string""" + + result = b58decode(v, alphabet=alphabet, autofix=autofix) + result, check = result[:-4], result[-4:] + digest = sha256(sha256(result).digest()).digest() + + if check != digest[:4]: + raise ValueError("Invalid checksum") + + return result + + +def base58_encode(num): + num = int(num, 16) + encoded = '' + while num: + num, remainder = divmod(num, 58) + encoded = BASE58_ALPHABET[remainder] + encoded + return encoded + +def base58_check_encode(payload, prefix=0x00): + payload = bytes([prefix]) + payload + checksum = sha256(sha256(payload).digest()).digest()[:4] + return base58_encode(payload.hex() + checksum.hex()) + +def base58encodeCheck(prefix, payload): + s = prefix + payload + raw = sha256(sha256(s).digest()).digest()[:4] + return base58encode(int.from_bytes(s + raw, 'big')) + +def string_to_int(data): + val = 0 + + if type(data) == str: + data = bytearray(data) + + for (i, c) in enumerate(data[::-1]): + val += (256 ** i) * c + return val + +def encode_(data): + enc = "" + val = string_to_int(data) + bs58size = len(BASE58_ALPHABET) + while val >= bs58size: + val, mod = divmod(val, bs58size) + enc = BASE58_ALPHABET[mod] + enc + if val: + enc = BASE58_ALPHABET[val] + enc + n = len(data) - len(data.lstrip(b"\0")) + return BASE58_ALPHABET[0] * n + enc + +def check_encode(raw): + check = sha256(sha256(raw).digest()).digest()[:4] + return encode_(raw + check) + +def decode_(data): + if isinstance(data, bytes): + data = data.decode("ascii") + + val = 0 + prefix = 0 + bs58size = len(BASE58_ALPHABET) + for cx in data: + val = (val * bs58size) + BASE58_ALPHABET.find(cx) + if val == 0: + prefix += 1 + + dec = bytearray() + while val > 0: + val, mod = divmod(val, 256) + dec.append(mod) + + dec.extend(bytearray(prefix)) + return bytes(dec[::-1]) + + +def check_decode(e): + dec = decode_(e) + raw, ck = dec[:-4], dec[-4:] + if ck != sha256(sha256(raw).digest()).digest()[:4]: + raise ValueError("base58 decoding checksum error") + else: + return raw + +def base58encode(num): + if num == 0: + return BASE58_ALPHABET[0] + arr = [] + while num: + num, rem = divmod(num, 58) + arr.append(BASE58_ALPHABET[rem]) + arr.reverse() + return ''.join(arr) + +def base58decode(raw): + decoded = 0 + for char in raw: + decoded = decoded * 58 + BASE58_ALPHABET.index(char) + bytes_rep = decoded.to_bytes((decoded.bit_length() + 7) // 8, byteorder='big') + landing = bytes_rep.lstrip(MAIN_DIGEST_RMD160) + data_size = (len(raw) - len(landing)) + return MAIN_DIGEST_RMD160 * data_size + bytes_rep + diff --git a/cryptofuzz/example.py b/cryptofuzz/example.py new file mode 100644 index 0000000..78ec11c --- /dev/null +++ b/cryptofuzz/example.py @@ -0,0 +1,310 @@ +# example cryptofuzz +import sys +from .Wallet import * + +red = "\033[91m" +green = "\033[92m" +yellow = "\033[93m" +magenta = "\033[95m" +cyan = "\033[96m" +white = "\033[97m" +reset = "\033[0m" + + +def example_privatekey(): + private_key = getPrivateKey() + wif_compress = PrivateKey_To_Wif(private_key, compress=True) + wif_Uncompress = PrivateKey_To_Wif(private_key, compress=False) + publicKey_compress = PrivateKey_To_PublicKey(private_key, compress=True) + publicKey_uncompress = PrivateKey_To_PublicKey(private_key, compress=False) + xprv = PrivateKey_To_XPRV(private_key) + xpub = PrivateKey_To_XPUB(private_key) + dec = PrivateKey_To_Decimal(private_key) + compress_address = PrivateKey_To_CompressAddr(private_key) + uncompress_address = PrivateKey_To_UncompressAddr(private_key) + print(f"{cyan}Private Key (HEX) {reset}: {private_key}") + print(f"{cyan}WIF Compress {reset}: {wif_compress}") + print(f"{cyan}WIF Uncompress {reset}: {wif_Uncompress}") + print(f"{cyan}Root Key (XPRV) {reset}: {xprv}") + print(f"{cyan}XPUB {reset}: {xpub}") + print(f"{cyan}Public Key Compress {reset}: {publicKey_compress}") + print(f"{cyan}Public Key Uncompress{reset}: {publicKey_uncompress}") + print(f"{cyan}Decimal {reset}: {dec}") + print(f"{cyan}Compress Address {reset}: {compress_address}") + print(f"{cyan}Uncompress Address {reset}: {uncompress_address}") + print(f"\n[*] {red}All Converted Data From Private Key (HEX){reset}.") + + +def example_mnemonic(): + mne = getMnemonic(12) + wif_compress = Mnemonic_To_Wif(mne, True) + wif_uncompress = Mnemonic_To_Wif(mne, False) + public_compress = Mnemonic_To_PublicKey(mnemonic=mne, compress=True) + public_uncompress = Mnemonic_To_PublicKey(mnemonic=mne, compress=False) + xprv = Mnemonic_To_XPRV(mnemonic=mne) + xpub = Mnemonic_To_XPUB(mnemonic=mne) + dec = Mnemonic_To_Decimal(mnemonic=mne) + address_compress = Mnemonic_To_Addr(mnemonic=mne, compress=True) + address_uncompress = Mnemonic_To_Addr(mnemonic=mne, compress=False) + print(f"{cyan}Mnemonic {reset}: {mne}") + print(f"{cyan}WIF Compress {reset}: {wif_compress}") + print(f"{cyan}WIF Uncompress {reset}: {wif_uncompress}") + print(f"{cyan}Public Key Compress {reset}: {public_compress}") + print(f"{cyan}Public Key Uncompress {reset}: {public_uncompress}") + print(f"{cyan}XPUB {reset}: {xpub}") + print(f"{cyan}XPRV {reset}: {xprv}") + print(f"{cyan}Decimal {reset}: {dec}") + print(f"{cyan}Address Compress {reset}: {address_compress}") + print(f"{cyan}Address Uncompress {reset}: {address_uncompress}") + print(f"[*] {red}All Converted Data From Mnemonic (BIP39){reset}.") + + +def example_bytes(): + byte = getBytes() + wif_compress = Bytes_To_Wif(byte, True) + wif_uncompress = Bytes_To_Wif(byte, False) + Public_compress = Bytes_To_PublicKey(byte, compress=True) + Public_uncompress = Bytes_To_PublicKey(byte, compress=False) + xprv = Bytes_To_XPRV(byte) + xpub = Bytes_To_XPUB(byte) + mne = Bytes_To_Mnemonic(byte) + privatekey = Bytes_To_PrivateKey(byte) + address_compress = Bytes_To_Address(byte, compress=True) + address_uncompress = Bytes_To_Address(byte, compress=False) + print(f"{cyan}Bytes {reset}: {byte}" + f"\n{cyan}WIF Compress {reset}: {wif_compress}" + f"\n{cyan}WIF Uncompress {reset}: {wif_uncompress}" + f"\n{cyan}Public Key Compress {reset}: {Public_compress}" + f"\n{cyan}Public Key Uncompress {reset}: {Public_uncompress}" + f"\n{cyan}XPUB {reset}: {xpub}" + f"\n{cyan}XPRV {reset}: {xprv}" + f"\n{cyan}Mnemonic {reset}: {mne}" + f"\n{cyan}Private Key {reset}: {privatekey}" + f"\n{cyan}Address Compress {reset}: {address_compress}" + f"\n{cyan}Address Uncompress {reset}: {address_uncompress}") + + +def example_binary(): + binary_str = getBinary() + wif_compress = Binary_To_Wif(binary_str, True) + wif_uncompress = Binary_To_Wif(binary_str, False) + PublicKey_compress = Binary_To_PublicKey(binary_str, compress=True) + PublicKey_uncompress = Binary_To_PublicKey(binary_str, compress=False) + xprv = Binary_To_XPRV(binary_str) + xpub = Binary_To_XPUB(binary_str) + dec = Binary_To_Decimal(binary_str) + address_compress = Binary_To_Address(binary_str, compress=True) + address_uncompress = Binary_To_Address(binary_str, compress=False) + print(f"{cyan}Binary {reset}: {binary_str}" + f"\n{cyan}WIF Compress {reset}: {wif_compress}" + f"\n{cyan}WIF Uncompress {reset}: {wif_uncompress}" + f"\n{cyan}Public Key Compress {reset}: {PublicKey_compress}" + f"\n{cyan}Public Key Uncompress {reset}: {PublicKey_uncompress}" + f"\n{cyan}XPUB {reset}: {xpub}" + f"\n{cyan}XPRV {reset}: {xprv}" + f"\n{cyan}Decimal {reset}: {dec}" + f"\n{cyan}Address Compress {reset}: {address_compress}" + f"\n{cyan}Address Uncompress {reset}: {address_uncompress}") + + +def example_xprv(): + xprv = getRootKey() + wif_compress = XPRV_To_Wif(xprv, True) + wif_uncompress = XPRV_To_Wif(xprv, False) + Public_compress = XPRV_To_PublicKey(xprv, compress=True) + Public_uncompress = XPRV_To_PublicKey(xprv, compress=False) + xpub = XPRV_To_XPUB(xprv) + Mne = XPRV_To_Mnemonic(xprv) + privatekey = XPRV_To_PrivateKey(xprv) + dec = XPRV_To_Decimal(xprv) + address_compress = XPRV_To_Address(xprv, compress=True) + address_uncompress = XPRV_To_Address(xprv, compress=False) + print(f"{cyan}XPRV {reset}: {xprv}" + f"\n{cyan}WIF Compress {reset}: {wif_compress}" + f"\n{cyan}WIF Uncompress {reset}: {wif_uncompress}" + f"\n{cyan}Public Key Compress {reset}: {Public_compress}" + f"\n{cyan}Public Key Uncompress {reset}: {Public_uncompress}" + f"\n{cyan}XPUB {reset}: {xpub}" + f"\n{cyan}Mnemonic {reset}: {Mne}" + f"\n{cyan}Private Key {reset}: {privatekey}" + f"\n{cyan}Decimal {reset}: {dec}" + f"\n{cyan}Address Compress {reset}: {address_compress}" + f"\n{cyan}Address Uncompress {reset}: {address_uncompress}") + + +def example_dec(): + dec = getDecimal() + privatekey = Decimal_To_PrivateKey(dec) + wif_compress = Decimal_To_Wif(dec, True) + wif_uncompress = Decimal_To_Wif(dec, False) + xprv = Decimal_To_XPRV(dec) + xpub = Decimal_To_XPUB(dec) + mne = Decimal_To_Mnemonic(dec) + public_compress = Decimal_To_PublicKey(dec, compress=True) + public_uncompress = Decimal_To_PublicKey(dec, compress=False) + address_compress = Decimal_To_Address(dec, compress=True) + address_uncompress = Decimal_To_Address(dec, compress=False) + print(f"{cyan}Decimal {reset}: {dec}" + f"\n{cyan}Private Key {reset}: {privatekey}" + f"\n{cyan}WIF Compress {reset}: {wif_compress}" + f"\n{cyan}WIF Uncompress {reset}: {wif_uncompress}" + f"\n{cyan}XPUB {reset}: {xpub}" + f"\n{cyan}XPRV {reset}: {xprv}" + f"\n{cyan}Mnemonic {reset}: {mne}" + f"\n{cyan}Public Key Compress {reset}: {public_compress}" + f"\n{cyan}Public Key Uncompress {reset}: {public_uncompress}" + f"\n{cyan}Address Compress {reset}: {address_compress}" + f"\n{cyan}Address Uncompress {reset}: {address_uncompress}" + f"\n[*] Converted All Data From Decimal.") + + +def example_wif(): + seed = getBytes() + wif_compress = Bytes_To_Wif(seed, True) + wif_uncompress = Bytes_To_Wif(seed, False) + PublicKey_compress = Wif_To_PublicKey(wif_compress, compress=True) + PublicKey_uncompress = Wif_To_PublicKey(wif_uncompress, compress=False) + xprv = Wif_To_XPRV(wif_uncompress) + xpub = Wif_To_XPUB(wif_uncompress) + dec = Wif_To_Decimal(wif_uncompress) + address_compress = Wif_To_Addr(wif_compress, compress=True) + address_uncompress = Wif_To_Addr(wif_uncompress, compress=False) + print(f"{cyan}WIF Compress {reset}: {wif_compress}" + f"\n{cyan}WIF Uncompress {reset}: {wif_uncompress}" + f"\n{cyan}Public Key Compress {reset}: {PublicKey_compress}" + f"\n{cyan}Public Key Uncompress {reset}: {PublicKey_uncompress}" + f"\n{cyan}XPUB {reset}: {xpub}" + f"\n{cyan}XPRV {reset}: {xprv}" + f"\n{cyan}Decimal {reset}: {dec}" + f"\n{cyan}Address Compress {reset}: {address_compress}" + f"\n{cyan}Address Uncompress {reset}: {address_uncompress}" + f"\n[*] Converted All Data From WIF.") + + +# ------------------------------------------------- + +def example_pvk_to_btc(): + pvk = getPrivateKey() + p2pkh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2pkh') + p2sh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2sh') + p2wpkh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2wpkh') + p2wsh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2wsh') + p2wpkh_p2sh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2wpkh_p2sh') + p2wsh_p2sh = PrivateKey_To_Bitcoin_Addr(pvk, 'p2wsh_p2sh') + print(f"{cyan}Private Key {reset}: {pvk}") + print(f"{cyan}P2PKH {reset}: {p2pkh}") + print(f"{cyan}P2SH {reset}: {p2sh}") + print(f"{cyan}P2WPKH {reset}: {p2wpkh}") + print(f"{cyan}P2WSH {reset}: {p2wsh}") + print(f"{cyan}P2WPKH in P2SH {reset}: {p2wpkh_p2sh}") + print(f"{cyan}P2WSH in P2SH {reset}: {p2wsh_p2sh}") + + +def example_pvk_to_eth(): + pvk = getPrivateKey() + eth_Addr = PrivateKey_To_Ethereum_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {eth_Addr}") + + +def example_pvk_to_dash(): + pvk = getPrivateKey() + dash_Addr = PrivateKey_To_Dash_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {dash_Addr}") + + +def example_pvk_to_ltc(): + pvk = getPrivateKey() + p2pkh = PrivateKey_To_Litecoin_Addr(pvk, 'p2pkh') + p2sh = PrivateKey_To_Litecoin_Addr(pvk, 'p2sh') + p2wpkh = PrivateKey_To_Litecoin_Addr(pvk, 'p2wpkh') + p2wsh = PrivateKey_To_Litecoin_Addr(pvk, 'p2wsh') + print(f"{cyan}Private Key {reset}: {pvk}") + print(f"{cyan}P2PKH {reset}: {p2pkh}") + print(f"{cyan}P2SH {reset}: {p2sh}") + print(f"{cyan}P2WPKH {reset}: {p2wpkh}") + print(f"{cyan}P2WSH {reset}: {p2wsh}") + + + +def example_pvk_to_digibyte(): + pvk = getPrivateKey() + digibyte_Addr = PrivateKey_To_DigiByte_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {digibyte_Addr}") + + +def example_pvk_to_dogecoin(): + pvk = getPrivateKey() + dogecoin_Addr = PrivateKey_To_Dogecoin_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {dogecoin_Addr}") + + +def example_pvk_to_bitcoingold(): + pvk = getPrivateKey() + bitcoingold_Addr = PrivateKey_To_BitcoinGold_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {bitcoingold_Addr}") + + +def example_pvk_to_qtum(): + pvk = getPrivateKey() + qtum_Addr = PrivateKey_To_Qtum_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {qtum_Addr}") + + +def example_pvk_to_zcash(): + pvk = getPrivateKey() + zcash_Addr = PrivateKey_To_Zcash_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {zcash_Addr}") + + +def example_pvk_to_rvn(): + pvk = getPrivateKey() + ravencoin_Addr = PrivateKey_To_Ravencoin_Addr(pvk) + print(f"{cyan}Private Key {reset}: {pvk}" + f"\n{cyan}Address Compress {reset}: {ravencoin_Addr}") + + +if __name__ == '__main__': + commands = sys.argv + if len(commands) > 1: + methodCommand = sys.argv[1] + if methodCommand == 'privatekey': + example_privatekey() + elif methodCommand == 'mnemonic': + example_mnemonic() + elif methodCommand == 'binary': + example_binary() + elif methodCommand == 'xprv': + example_xprv() + elif methodCommand == 'wif': + example_wif() + elif methodCommand == 'decimal': + example_dec() + elif methodCommand == 'bytes': + example_bytes() + elif methodCommand == 'ethereum': + example_pvk_to_eth() + elif methodCommand == 'bitcoin': + example_pvk_to_btc() + elif methodCommand == 'dash': + example_pvk_to_dash() + elif methodCommand == 'dogecoin': + example_pvk_to_dogecoin() + elif methodCommand == 'digibyte': + example_pvk_to_digibyte() + elif methodCommand == 'bitcoingold': + example_pvk_to_bitcoingold() + elif methodCommand == 'qtum': + example_pvk_to_qtum() + elif methodCommand == 'zcash': + example_pvk_to_zcash() + elif methodCommand == 'rvn': + example_pvk_to_rvn() + else: + print(f"{red}\n\nInvalid Command!{reset}") \ No newline at end of file diff --git a/cryptofuzz/hd.py b/cryptofuzz/hd.py new file mode 100644 index 0000000..443aba7 --- /dev/null +++ b/cryptofuzz/hd.py @@ -0,0 +1,376 @@ +from .utils import ( + re, HD_W, BTC, ETH, TRX, DGB, DOGE, DASH, BTG, RVN, ZEC, QTUM, LTC, AXE +) + +def is_valid_hex(hexstring: str) -> bool: + return re.match("^[a-fA-F0-9]*$", hexstring) is not None + + +class Bitcoin: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str, Type: str = 'p2pkh') -> str: + """ + Convert Private key Hex To All Bitcoin Format Type Addresses, Type: `p2pkh`, `p2sh`, `p2wpkh`, `p2wsh`, `p2wpkh_p2sh`, `p2wsh_p2sh`. + :param hexed: + :param Type: + :rtype str: + :return address: + + + ----------------------------------------------------------------------------------------------- + + >>> btc = Bitcoin() + >>> privatekey = "0A97965.........0102F6A45517" # example Private Key + >>> p2pkh_addr = btc.hex_addr(privatekey, Type='p2pkh') + >>> p2sh_addr = btc.hex_addr(privatekey, Type='p2sh') + >>> p2wpkh_addr = btc.hex_addr(privatekey, Type='p2wpkh') + >>> p2wsh_addr = btc.hex_addr(privatekey, Type='p2wsh') + >>> p2wpkh_p2sh_addr = btc.hex_addr(privatekey, Type='p2wpkh_p2sh') + >>> p2wsh_p2sh_addr = btc.hex_addr(privatekey, Type='p2wsh_p2sh') + + --------------------------------------------------------------------------------------------- + + + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(BTC) + hd.from_private_key(hexed) + if Type == 'p2pkh': + return hd.p2pkh_address() + elif Type == 'p2sh': + return hd.p2sh_address() + elif Type == 'p2wpkh': + return hd.p2wpkh_address() + elif Type == 'p2wsh': + return hd.p2wsh_address() + elif Type == 'p2wpkh_p2sh': + return hd.p2wpkh_in_p2sh_address() + elif Type == 'p2wsh_p2sh': + return hd.p2wsh_in_p2sh_address() + else: + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Ethereum: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Ethereum Format Type Address . + :param hexed: + :rtype str: + :return: str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(ETH) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Tron: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + + """ + Convert Private key Hex To All Tron Format Type Address . + :param hexed: + :rtype str: + :return: str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(TRX) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class DigiByte: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To DigiByte Address. + + :param hexed: + :rtype str: + :return: Str - address + + + -------------------------------------------------------------- + + >>> dgb = DigiByte() + >>> privatekey = "0A97965...A45517" # example Private Key + >>> digibyte_address = dgb.hex_addr(privatekey) + + -------------------------------------------------------------- + + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(DGB) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Dogecoin: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str, Type: str = 'p2pkh') -> str: + """ + Generate Private key Hex Address To All Dogecoin Format Type Address , Type: `p2pkh`, `p2sh`. + + :param hexed: + :type hexed: str + :param Type: + :type Type: str + :rtype: str + :return: str - address + + + -------------------------------------------------------------- + + >>> doge = Dogecoin() + >>> privatekey = "0A9796542F1030...02F6A45517" # example Private Key + >>> p2pkh_doge_addr = doge.hex_addr(privatekey, 'p2pkh') + >>> p2sh_doge_addr = doge.hex_addr(privatekey, 'p2sh') + + -------------------------------------------------------------- + + """ + + if is_valid_hex(hexed): + hd: HD_W = HD_W(DOGE) + hd.from_private_key(hexed) + if Type == 'p2pkh': + return hd.p2pkh_address() + elif Type == 'p2sh': + return hd.p2sh_address() + else: + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Dash: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Dash Address . + :param hexed: + :rtype str: + :return: Str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(DASH) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class BitcoinGold: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str, Type: str = "p2pkh") -> str: + """ + + Convert Private key Hex To All BitcoinGold Format Type Address , Type: `p2pkh`, `p2sh`, `p2wpkh`, `p2wsh`, `p2wpkh_p2sh`, `p2wsh_p2sh`. + + :param hexed: + :type hexed: Str. + :param Type: + :type Type: Str. + :rtype: Str. + :return address: + + + -------------------------------------------------------------- + + >>> btg = BitcoinGold() + >>> privatekey = "0A9796542F1030931E317...............960DC79C48D20102F6A45517" + >>> p2pkh_address = btg.hex_addr(privatekey, "p2pkh") + >>> p2sh_address = btg.hex_addr(privatekey, "p2sh") + >>> p2wpkh_address = btg.hex_addr(privatekey, "p2wpkh") + >>> p2wsh_address = btg.hex_addr(privatekey, "p2wsh") + >>> p2wpkh_in_p2sh_address = btg.hex_addr(privatekey, "p2wpkh_p2sh") + >>> p2wsh_in_p2sh_address = btg.hex_addr(privatekey, "p2wsh_p2sh") + + -------------------------------------------------------------- + + + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(BTG) + hd.from_private_key(hexed) + if Type == "p2pkh": + return hd.p2pkh_address() + elif Type == "p2sh": + return hd.p2sh_address() + elif Type == "p2wpkh": + return hd.p2wpkh_address() + elif Type == "p2wsh": + return hd.p2wsh_address() + elif Type == "p2wpkh_p2sh": + return hd.p2wpkh_in_p2sh_address() + elif Type == "p2wsh_p2sh": + return hd.p2wsh_in_p2sh_address() + else: + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Ravencoin: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Ravencoin Format Type Address . + :param hexed: + :rtype str: + :return: str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(RVN) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Zcash: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Zcash Format Type Address . + :param hexed: + :rtype str: + :return: str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(ZEC) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Qtum: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Qtum Format Type Address . + :param hexed: + :rtype str: + :return: str - address + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(QTUM) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Litecoin: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str, Type: str = 'p2pkh') -> str: + """ + + ------------------------------------------ + Convert Private key Hex To All Litecoin Format Type Address , Type: `p2pkh`, `p2sh`, `p2wpkh`, `p2wsh`, `p2wpkh_p2sh`, `p2wsh_p2sh`. + :param hexed: + :type hexed: str. + :param Type: + :type Type: str. + :returns: address. + + ------------------------------------------ + + >>> ltc = Litecoin() + >>> privatekey = "e3b0c44298fc1c149..................." + >>> p2pkh_address = ltc.hex_addr(privatekey, 'p2pkh') + >>> p2sh_address = ltc.hex_addr(privatekey, 'p2sh') + >>> p2wpkh_address = ltc.hex_addr(privatekey, 'p2wpkh') + >>> p2wsh_address = ltc.hex_addr(privatekey, 'p2wsh') + >>> p2wpkh_p2sh_address = ltc.hex_addr(privatekey, 'p2wpkh_p2sh') + >>> p2wsh_p2sh_address = ltc.hex_addr(privatekey, 'p2wsh_p2sh') + + ------------------------------------------ + + + + """ + + if is_valid_hex(hexed): + hd: HD_W = HD_W(LTC) + hd.from_private_key(hexed) + if Type == 'p2pkh': + return hd.p2pkh_address() + elif Type == 'p2sh': + return hd.p2sh_address() + elif Type == 'p2wpkh': + return hd.p2wpkh_address() + elif Type == 'p2wsh': + return hd.p2wsh_address() + elif Type == 'p2wpkh_p2sh': + return hd.p2wpkh_in_p2sh_address() + elif Type == 'p2wsh_p2sh': + return hd.p2wsh_in_p2sh_address() + else: + return hd.p2pkh_address() + + else: + ValueError("hex format invalid check again.[format: hex][64 length]") + + +class Axe: + def __int__(self): + super().__init__() + + def hex_addr(self, hexed: str) -> str: + """ + Convert Private key Hex To All Axe Format Type Addresses. + :param hexed: + :type hexed: + :rtype str: + :return: Str - address + + ------------------------------------------------------------- + + >>> Axe_ = Axe() + >>> privatekey = "e3b0c44298fc1c149..................." + >>> Axe_address = Axe_.hex_addr(privatekey) + + ------------------------------------------------------------- + + """ + if is_valid_hex(hexed): + hd: HD_W = HD_W(AXE) + hd.from_private_key(hexed) + return hd.p2pkh_address() + else: + ValueError("hex format invalid check again.[format: hex][64 length]") diff --git a/cryptofuzz/utils.py b/cryptofuzz/utils.py new file mode 100644 index 0000000..dbb6fc6 --- /dev/null +++ b/cryptofuzz/utils.py @@ -0,0 +1,293 @@ +import binascii +import os, re, hashlib +import random +import struct +import ecdsa +from typing import Union +from .bs58 import b58encode, b58decode, base58_check_encode, base58encodeCheck, base58decode, base58encode +from hdwallet import HDWallet as HD_W +from hdwallet.symbols import BTC, ETH, TRX, LTC, DOGE, DGB, BTG, RVN, QTUM, DASH, ZEC, BCH, AXE +from mnemonic import Mnemonic +from .assest import ( + MAIN_DIGEST_RMD160, + MAX_PRIVATE_KEY, + MAIN_PREFIX, + MAIN_SUFFIX, + ZERO_BASE_NET, + VERSION_NETWORK, + BASE58_ALPHABET, + FINGERPRINT_RMD160, + COMPRESSED_PREFIX, + COMPRESSED_PREFIX2, + UNCOMPRESSED_PREFIX, + MAIN_DIGEST, + XPUB_PREFIX, + ZERO_BYTES, + BIP39 +) + + +class Generator: + def __init__(self): + super().__init__() + + def checkValid(self, key: int) -> bool: + if 0 < key < MAX_PRIVATE_KEY: + return True + else: + raise ValueError(f"Secret Scalar Must be greater than 0 and less than {MAX_PRIVATE_KEY}.") + + def generate_private_key(self) -> str: + randkey = "".join(random.choice("0123456789abcdef") for _ in range(64)) + if self.checkValid(int(randkey, 16)): + return randkey + else: + return self.generate_private_key() + + def generate_xprv(self): + return "xprv" + binascii.hexlify(os.urandom(32)).decode('utf-8') + + def generate_decimal(self) -> int: return random.randint(0, MAX_PRIVATE_KEY) + def generate_binary(self) -> str: + return "".join(random.choice("01") for _ in range(256)) + + def generate_entropy(self, entropy_bits=256): + entropy = os.urandom(entropy_bits // 8) + checksum = hashlib.sha256(entropy).digest()[0] + entropy_with_checksum = entropy + bytes([checksum]) + return entropy_with_checksum + + def generate_mnemonic(self, size: int) -> str: + characters = re.findall('[A-Z][a-z]+', BIP39) + return " ".join(random.choices(characters, k=size)).lower() + + +class Convertor: + def __init__(self): + super().__init__() + self.gen = Generator() + + def double_sha256(self, data): + return hashlib.sha256(hashlib.sha256(data).digest()).digest() + + def mne_to_seed(self, mnemonic, password=""): + salt = ("mnemonic" + password).encode('utf-8') + seed = hashlib.pbkdf2_hmac('sha512', mnemonic.encode('utf-8'), salt, 2048) + return seed[:64] + + def unHexlify(self, h: str): + return binascii.unhexlify(h) + + def hex_to_bytes(self, hexed): + return binascii.unhexlify(hexed) + + def hex_to_int(self, hexed: str) -> int: + return int(hexed, 16) + + def hex_to_pub(self, hexed: str, compress: bool = False) -> bytes: + if compress: + return self.bytes_to_public(self.hex_to_bytes(hexed), True) + else: + return self.bytes_to_public(self.hex_to_bytes(hexed), False) + + def hex_to_addr(self, hexed: str, compress: bool = False) -> str: + pub = self.hex_to_pub(hexed) + if compress: + return self.pub_to_addr(pub) + else: + return self.pub_to_addr(pub) + + def bytes_to_hex(self, seed): + privatekey_int = int.from_bytes(hashlib.sha256(seed).digest(), byteorder='big') + self.gen.checkValid(privatekey_int) + pvkByte = privatekey_int.to_bytes(32, byteorder='big') + return pvkByte.hex() + + def bytes_to_int(self, seed) -> int: + return int.from_bytes(seed, byteorder='big') + + def bytes_to_pub(self, seed_bytes: bytes) -> bytes: + sk = ecdsa.SigningKey.from_string(seed_bytes[:32], curve=ecdsa.SECP256k1) + vk = sk.get_verifying_key() + pub = b'\x02' + vk.to_string()[-32:] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[-32:] + return pub + + def bytes_to_public(self, seed: bytes, compress: bool = True) -> bytes: + sk = ecdsa.SigningKey.from_string(seed, curve=ecdsa.SECP256k1) + vk = sk.get_verifying_key() + if compress: + prefix = COMPRESSED_PREFIX2 if vk.pubkey.point.y() % 2 == 0 else COMPRESSED_PREFIX + return prefix + vk.to_string()[:32] + else: + return UNCOMPRESSED_PREFIX + vk.to_string() + + def bytes_to_xpub(self, seed: bytes, chain_code=None) -> str: + if chain_code is None: + chain_code = os.urandom(32) # .hex + prefix = self.unHexlify(XPUB_PREFIX) + FINGERPRINT = ZERO_BYTES + ZERO_BYTES + pub = self.bytes_to_pub(seed) + xpub = prefix + MAIN_DIGEST + FINGERPRINT + chain_code + pub + Hash64 = self.double_sha256(xpub) + xpub += Hash64[:4] + xpubBase58 = b58encode(xpub) + return xpubBase58.decode('utf-8') + + def bytes_to_mne(self, byte: bytes): + seed = byte[:32] + return Mnemonic("english").to_mnemonic(seed) + + def bytes_to_binary(self, bytes_: bytes) -> str: + if len(bytes_) != 32: + raise ValueError("Input bytes should have a length of 32.") + + # Convert each byte to its binary representation and pad with zeros + return ''.join(format(byte, '08b') for byte in bytes_) + + def bytes_to_wif(self, private_key, compress=True): + if compress: + EXTENDED_KEY = MAIN_PREFIX + private_key + MAIN_SUFFIX + else: + EXTENDED_KEY = MAIN_PREFIX + private_key + + DOUBLE_SHA256 = self.double_sha256(EXTENDED_KEY) + CHECKSUM = DOUBLE_SHA256[:4] + + WIF = b58encode(EXTENDED_KEY + CHECKSUM) + + return WIF.decode('utf-8') + + def bytes_to_xprv(self, bytes_code: bytes) -> str: + chain_code = bytes.fromhex(ZERO_BASE_NET) + child_number = struct.pack('>L', 0) + key = MAIN_DIGEST_RMD160 + bytes_code # 0x00 + + xprv_main = VERSION_NETWORK + MAIN_DIGEST_RMD160 + FINGERPRINT_RMD160 + child_number + chain_code + key + decode_main = base58encodeCheck(b"", xprv_main) + return decode_main + + def bytes_to_addr(self, seedBytes: bytes, compress: bool = False) -> str: + if compress: + pub = self.bytes_to_public(seedBytes, compress=True) + return self.pub_to_addr(public_key=pub) + else: + pub = self.bytes_to_public(seedBytes, compress=False) + return self.pub_to_addr(public_key=pub) + + # ------------------------------------------------------------ + def pass_to_hex(self, passphrase): + return hashlib.sha256(passphrase.encode()).hexdigest() + + def pass_to_bytes(self, passphrase: str) -> bytes: + return bytes.fromhex(self.pass_to_hex(passphrase)) + + def pass_to_addr(self, passphrase, compress=False): + passBytes = self.pass_to_bytes(passphrase) + sk = ecdsa.SigningKey.from_string(passBytes, curve=ecdsa.SECP256k1) + vk = sk.verifying_key + if compress: + if vk.pubkey.point.y() & 1: + pub_key = COMPRESSED_PREFIX + vk.to_string()[:32] + else: + pub_key = COMPRESSED_PREFIX2 + vk.to_string()[:32] + else: + pub_key = UNCOMPRESSED_PREFIX + vk.to_string() + sha = hashlib.sha256(pub_key).digest() + ripemd160 = hashlib.new('ripemd160') + ripemd160.update(sha) + + address = base58_check_encode(ripemd160.digest()) + return "1" + address + + def pass_to_wif(self, passphrase, compress=False): + passBytes = self.pass_to_bytes(passphrase) + return self.bytes_to_wif(passBytes, compress) + + def pass_to_xprv(self, passphrase): + return self.bytes_to_xprv(self.pass_to_bytes(passphrase)) + + # ------------------------------------------------------------ + + def pub_to_bytes(self, pubkey, compress=True): + if compress: + prefix = (COMPRESSED_PREFIX if pubkey.pubkey.point.y() & 1 else COMPRESSED_PREFIX2) + return prefix + pubkey.pubkey.point.x().to_bytes(32, 'big') + else: + point_x = pubkey.pubkey.point.x().to_bytes(32, 'big') + point_y = pubkey.pubkey.point.y().to_bytes(32, 'big') + return UNCOMPRESSED_PREFIX + point_x + point_y + + def pub_to_hex(self, pubkey, compress=True): + return self.pub_to_bytes(pubkey, compress).hex() + + def pub_to_addr(self, public_key: bytes) -> str: + ripemd160 = hashlib.new('ripemd160') + ripemd160.update(hashlib.sha256(public_key).digest()) + hashed = MAIN_DIGEST_RMD160 + ripemd160.digest() + checksum = hashlib.sha256(hashlib.sha256(hashed).digest()).digest()[:4] + address = hashed + checksum + return b58encode(address).decode('utf-8') + + # ------------------------------------------------------------ + + def wif_to_bytes(self, wif): + wif_bytes = b58decode(wif) + isCompress = wif_bytes[-5] == 0x01 if len(wif_bytes) == 38 else False + return wif_bytes[1:-5] if isCompress else wif_bytes[1:-4] + + def wif_to_addr(self, wif: str, compress: bool = False) -> str: + pvkBytes = self.wif_to_bytes(wif) + public_key = self.bytes_to_public(pvkBytes, compress) + address = self.pub_to_addr(public_key) + return address + + # ------------------------------------------------------------ + + def xprv_to_bytes(self, xprv: str): + if not xprv.startswith("xprv") or len(xprv) <= 4: + raise ValueError("Invalid xprv format.") + xprv58 = xprv[4:] + xprvBytes = base58decode(xprv58) + return xprvBytes[:32] + + def xprv_to_addr(self, xprv, compress: bool = False): + seed = self.xprv_to_bytes(xprv) + if compress: + pub = self.bytes_to_public(seed, True) + return self.pub_to_addr(pub) + else: + pub = self.bytes_to_public(seed, False) + return self.pub_to_addr(pub) + + def xprv_to_pub(self, xprv, compress: bool = False): + seed = self.xprv_to_bytes(xprv) + if compress: + return self.bytes_to_public(seed, True) + else: + return self.bytes_to_public(seed, False) + + def xprv_to_wif(self, xprv, compress: bool = False): + seed = self.xprv_to_bytes(xprv) + if compress: + return self.bytes_to_wif(seed, True) + else: + return self.bytes_to_wif(seed, False) + + def xprv_to_mne(self, xprv): + seed = self.xprv_to_bytes(xprv) + return self.bytes_to_mne(seed) + + # ------------------------------------------------------------ + + def binary_to_bytes(self, bin_str: str) -> bytes: + if len(bin_str) != 256: + raise ValueError("The binary string must have 256 characters.") + chunks = [bin_str[i:i + 8] for i in range(0, len(bin_str), 8)] + return bytes([int(chunk, 2) for chunk in chunks]) + + def int_to_bytes(self, int_dec: int) -> bytes: + bytes_length = (int_dec.bit_length() + 7) // 8 + return int_dec.to_bytes(bytes_length, 'big') + + def int_to_hex(self, int_dec: int) -> str: + return "%064x" % int_dec