How to convert a private key from WIF/HEX format to legacy and SegWit addresses to speed up the process, we will use the Bloom filter algorithm

20.03.2025
How to convert a private key from WIF/HEX format to legacy and SegWit addresses to speed up the process, we will use the Bloom filter algorithm

Below is an example Python script that converts a Bitcoin private key to an address, converts a private key from WIF/HEX format to legacy and SegWit addresses. To speed things up, we will use the Bloom filter algorithm, although its direct application in this context may not be practical, since Bloom filters are typically used to quickly filter data, not to convert keys. However, we can use it to optimize address verification.

Required libraries

To run the script you will need the following libraries:

  • bitcoinaddress
  • pycryptodome (for working with cryptographic functions)

Install them using pip:

bashpip install bitcoinaddress pycryptodome

Script

pythonfrom bitcoinaddress import Wallet
from Crypto.Hash import SHA256
import mmh3

def private_key_to_address(private_key_wif):
    """Преобразует приватный ключ WIF в адрес."""
    wallet = Wallet(private_key_wif)
    return wallet.address

def private_key_to_segwit_address(private_key_wif):
    """Преобразует приватный ключ WIF в SegWit-адрес."""
    wallet = Wallet(private_key_wif)
    return wallet.p2sh_segwit_address

def bloom_filter(addresses):
    """Простой пример использования Bloom filter для фильтрации адресов."""
    # Инициализация Bloom filter
    size = 1000000
    hash_functions = 7
    bit_array = [0] * size

    def add(address):
        for seed in range(hash_functions):
            result = mmh3.hash(address, seed) % size
            bit_array[result] = 1

    def lookup(address):
        for seed in range(hash_functions):
            result = mmh3.hash(address, seed) % size
            if bit_array[result] == 0:
                return False
        return True

    # Добавляем адреса в Bloom filter
    for address in addresses:
        add(address)

    return lookup

# Пример использования
private_key_wif = "5HqrbgkWPqBy6dvCE7FoUiMuiCfFPRdtRsyi6NuCM2np8qBZxq5"
address = private_key_to_address(private_key_wif)
segwit_address = private_key_to_segwit_address(private_key_wif)

print(f"Адрес: {address}")
print(f"SegWit-адрес: {segwit_address}")

# Пример использования Bloom filter
addresses = [address, segwit_address]
lookup_func = bloom_filter(addresses)

# Проверка адреса
print(f"Адрес {address} найден: {lookup_func(address)}")
print(f"Адрес {segwit_address} найден: {lookup_func(segwit_address)}")

Notes

  1. Bloom Filter : This example uses Bloom filter to demonstrate how you can quickly check for addresses in a dataset. However, it is not practical for actually checking balances or working with transactions.
  2. Key Conversion : The script converts the private key to a legacy and SegWit address.
  3. Libraries : The library is used to work with Bitcoin addresses and keys bitcoinaddress. For Bloom filter, it is used mmh3for hashing.

This script demonstrates basic operations with Bitcoin private keys and their conversion to various address formats. More complex operations, such as checking balances or sending transactions, may require additional libraries and APIs.


Which Python libraries are best to use for working with Bitcoin

To work with Bitcoin in Python, you can use the following libraries:

  1. bitcoinlib : This is a powerful library that offers a wide range of tools for working with the Bitcoin blockchain. It allows you to create different types of wallets, interact with the blockchain, create and validate transactions, and generate Bitcoin addresses in different formats 5 .
  2. python-bitcoin-utils : This library is useful for working with Bitcoin transactions and provides various useful functions for analyzing and manipulating data 3 .
  3. block-io : This library can be used to integrate Bitcoin payments into applications. It provides a simple API for working with transactions and wallets 6 .
  4. blockchain : This library allows you to interact with the Bitcoin blockchain, retrieve transaction and address information, and create new transactions 6 .
  5. CCXT : Although primarily used for trading cryptocurrency exchanges, CCXT can also be useful for obtaining market data and creating trading strategies related to Bitcoin 1 .

These libraries allow developers to create a variety of Bitcoin-related applications, from simple transaction analysis scripts to complex trading bots and payment systems.


How to Convert WIF Private Key to HEX and Back

Converting a Bitcoin private key between WIF and HEX formats can be done using Python. Below is a code example that shows how to do this:

Convert HEX to WIF

To convert a key from HEX to WIF format, you can use a library base58to encode and add a checksum.

pythonimport hashlib
import base58

def hex_to_wif(hex_key):
    # Добавляем префикс '80' для приватного ключа в формате WIF
    hex_key = '80' + hex_key
    
    # Вычисляем контрольную сумму
    checksum = hashlib.sha256(hashlib.sha256(bytes.fromhex(hex_key)).digest()).digest()[:4]
    
    # Добавляем контрольную сумму к ключу
    hex_key += checksum.hex()
    
    # Кодирование Base58
    wif_key = base58.b58encode(bytes.fromhex(hex_key)).decode('utf-8')
    
    return wif_key

# Пример использования
hex_private_key = "4BBWF74CQ25A2A00409D0B24EC0418E9A41F9B5B86216A183E0E9731F4589DC6"
wif_private_key = hex_to_wif(hex_private_key)
print(f"WIF Private Key: {wif_private_key}")

Convert WIF to HEX

To convert back from WIF to HEX, you can use Base58 decoding and prefix and checksum removal.

pythonimport base58
import hashlib

def wif_to_hex(wif_key):
    # Декодирование Base58
    decoded_key = base58.b58decode(wif_key)
    
    # Удаление контрольной суммы и префикса '80'
    hex_key = decoded_key[1:-4].hex()
    
    return hex_key

# Пример использования
wif_private_key = "5JPuWYZx922hXi46Lg2RJPrLfqGmkGS9YegMNgiNvx8cJa6kPK8"
hex_private_key = wif_to_hex(wif_private_key)
print(f"HEX Private Key: {hex_private_key}")

These functions allow you to convert private keys between WIF and HEX formats. To work with these functions, you need to have the library installed base58, which can be installed using pip:

bashpip install base58

What are the tools to check the balance of a Bitcoin address

To check the balance of a Bitcoin address, you can use the following tools:

  1. Blockchain Explorers :
    • Blockchair : Supports multiple blockchains including Bitcoin.
    • Blockchain.com : Allows you to view transactions and balances.
    • Coin.Space : A simple tool to check the balance of Bitcoin addresses.
  2. Online services :
    • Crypto.ru : Offers a tool for quickly checking Bitcoin balance by wallet address.
    • MATBEA SWAP : Allows you to instantly check the balance of all wallet addresses.
  3. API and software tools :
    • Bitcoin Core (bitcoind) : Use the command getbalanceto check balance via RPC API.
    • Python libraries : Use libraries like bitcoinlibor pycryptodometo interact with the blockchain and check balances programmatically.
  4. Mobile applications :
    • Key Hunter : Allows you to check the balance of Bitcoin addresses using a private key.

These tools make it easy to check the balance of Bitcoin addresses using public blockchain data.

What errors can occur when working with Bitcoin private keys

The following errors and vulnerabilities may occur when working with Bitcoin private keys:

  1. Incorrect ECDSA implementation :
    • An incorrect implementation of the ECDSA algorithm can lead to the leakage of private keys. For example, a vulnerability DeserializeSignatureallowed attackers to create fake signatures that could be accepted as correct 1 .
  2. Weak random number generators :
    • If the random number generator does not generate truly random data, private keys may be predictable and vulnerable to brute force. This may lead to theft of funds 3 .
  3. Weak Brainwallet :
    • Using memorable phrases to generate private keys can make them vulnerable to guessing, as such phrases are often not random enough 2 .
  4. Random Vulnerability :
    • If an application uses the same nonce for different transactions, attackers can extract private keys from the signatures 2 .
  5. Incorrect storage of keys :
    • Private keys must be kept secret. If they fall into the hands of attackers, funds can be stolen 5 .
  6. Hash collisions :
    • While it is theoretically possible for different private keys to have the same hash (e.g. ripemd160), in practice this is extremely unlikely and does not pose a significant threat 8 .
  7. Runtime attacks :
    • Some attacks may rely on analysis of the execution time of operations, which may allow attackers to obtain information about private keys 1 .
  8. Vulnerabilities in software wallets :
    • Bugs in wallet applications can lead to private keys being leaked or misused 3 .

Citations:

  1. https://habr.com/ru/articles/817237/
  2. https://ru.tradingview.com/news/forklog:3031939c867b8:0/
  3. https://xakep.ru/2018/04/17/not-so-random/
  4. https://tangem.com/ru/blog/post/entropy/
  5. https://baltija.eu/2020/07/09/shest-veshei-kotorye-bitkoinery-doljny-znat-o-privatnyh-kluchah/
  6. https://www.securitylab.ru/blog/personal/%20Informacionnaya_bezopasnost_v_detalyah/343072.php
  7. https://www.ixbt.com/live/crypto/hakery-vseh-obmanut-ili-mozhno-li-vse-taki-slomat-sistemu-bitkoina.html
  8. https://github.com/svtrostov/oclexplorer/issues/6

  1. https://crypto.ru/proverit-bitcoin-koshelek/
  2. https://blog.bitbanker.org/ru/kak-posmotret-balans-lyubogo-kriptokoshelka/
  3. https://ru.beincrypto.com/top-5-besplatnyh-platform-onchein-analiza/
  4. https://qna.habr.com/q/107877
  5. https://crypto.ru/blockchain-address/
  6. https://coinsutra.com/ru/crypto-airdrop-checker-tools/
  7. https://play.google.com/store/apps/details?id=io.github.keyhunter
  8. https://coin.space/ru/bitcoin-address-check/

  1. https://habr.com/ru/articles/773412/
  2. https://www.xn--90abjnskvm1g.xn--p1ai/BitcoinPrivateKey_to_BitcoinAllKeys/index.html
  3. https://habr.com/ru/articles/682220/
  4. https://waymorr.ru/news/blog/chto-takoe-privatnyij-klyuch-bitkoin-koshelka
  5. https://forum.bits.media/index.php?%2Ftopic%2F178950-%D1%83%D1%82%D0%B8%D0%BB%D0%B8%D 1%82%D0%B0-%D0%B2%D0%BE%D1%81%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BB%D0%B5%D0%BD%D 0%B8%D1%8F-%D0%BF%D0%BE%D0%B2%D1%80%D0%B5%D0%B6%D0%B4%D1%91%D0%BD%D0%BD%D1%8B%D1%85-% D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%B9-%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B0-wif%2F
  6. http://bitcoin-zarabotat.ru/kak-konvertirovat-kljuchi-hex-v-wif-kak-matematicheskaja-zadacha/
  7. https://gist.github.com/Jun-Wang-2018/3105e29e0d61ecf88530c092199371a7
  8. https://secretscan.org/PrivateKeyWif

  1. https://bitnovosti.io/2025/01/18/python-bitcoin-crypto/
  2. https://proglib.io/p/kak-python-primenyaetsya-v-blokcheyn-2021-03-19
  3. https://qna.habr.com/q/839255
  4. https://habr.com/ru/articles/525638/
  5. https://sky.pro/media/kak-ispolzovat-python-dlya-raboty-s-blokchejn/
  6. https://vc.ru/dev/1616346-vnedryaem-oplatu-btc-kuda-ugodno-python
  7. https://dzen.ru/a/ZBXLlMLW0G807WSq
  8. https://sky.pro/media/kak-ispolzovat-python-dlya-raboty-s-kriptovalyutami/
  1. https://python-forum.io/archive/index.php/thread-16797.html
  2. https://habr.com/ru/articles/525638/
  3. https://ru.stackoverflow.com/questions/1475317/bitcoin-%D0%B0%D0%B4%D1%80%D0%B5%D1%81%D0%B0-%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82
  4. https://miningclub.info/threads/keyhunter-py-poisk-privatkey-bitcion-do-2012-na-otformatirovannyx-diskax.31532/
  5. https://pikabu.ru/story/deshifrovanie_paroley_dlya_dostupa_k_poteryannyim_bitkoin_koshelkam_s_pomoshchyu_metoda_gaussjacobi_i_protsessa_mashinnogo_obuchenie_bitcoinchatgpt_11298411
  6. https://habr.com/ru/articles/674812/
  7. https://www.programmersforum.ru/showthread.php?t=327290
  8. https://gist.github.com/imylomylo/60e47d1902c350179a47eb3c1ffe8c5d

Source code

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/i9KYih_ffr8

Video tutorial: https://dzen.ru/video/watch/6784be61b09e46422395c236

Source: https://cryptodeeptech.ru/discrete-logarithm


Useful information for enthusiasts:


Discrete Logarithm mathematical methods and tools for recovering cryptocurrency wallets Bitcoin