Как конвертировать публичные ключи Bitcoin-PUBKEY HEX в Bitcoin-адрес Base58 и проверить баланс на наличие монет BTC

В этой статье мы научимся тому, как в большом количестве данных проверить баланс монет Биткоина используя для этого Python-скрипт bitcoin-checker.py

Результат проверки Python-скрипта bitcoin-checker.py
Результат проверки Python-скрипта bitcoin-checker.py


Так же мы научимся конвертировать публичный ключ Биткоина PUBKEY (HEX) в Биткойн Адрес (Base58) всю эту большую работу делает Python-скрипт pubtoaddr.py

В итоге мы с особой легкостью будем проверять баланс Биткоина, сканируя Блокчейн в терминале Google Colab [TerminalGoogleColab]

Ранее я записывал видеоинструкцию: «TERMINAL в Google Colab создаем все удобства для работ в GITHUB»

Давайте перейдем в репозиторию «CryptoDeepTools» и разберем в детали работу Bash-скрипта:getbalance.sh

Commands:

git clone https://github.com/demining/CryptoDeepTools.git

cd CryptoDeepTools/03CheckBitcoinAddressBalance/

sudo apt install python2-minimal

wget https://bootstrap.pypa.io/pip/2.7/get-pip.py

sudo python2 get-pip.py

pip3 install -r requirements.txt

chmod +x getbalance.sh

./getbalance.sh

Файлы
Файлы
Код нашего Bash-скрипта: getbalance.sh
Код нашего Bash-скрипта: getbalance.sh
grep 'PUBKEY = ' signatures.json > pubkeyall.json

Утилита grep собирает все публичные ключи в один общий файл: pubkeyall.json

sort -u pubkeyall.json > pubkey.json

Утилита sort сортирует и удаляет дубли отбирает уникальные публичные ключи и результат сохраняет в файл: pubkey.json

rm pubkeyall.json

Утилита rm удаляет pubkeyall.json

sed -i 's/PUBKEY = //g' pubkey.json

Утилита sed стирает префикс PUBKEY =

python3 pubtoaddr.py

Запускаем Python-скрипт pubtoaddr.py конвертируем из файла pubkey.json где хранятся наши публичные ключи Биткоина PUBKEY (HEX) в файл addresses.json результат сохранится как Биткойн Адреса (Base58)

import hashlib
import base58
 
def hash160(hex_str):
    sha = hashlib.sha256()
    rip = hashlib.new('ripemd160')
    sha.update(hex_str)
    rip.update(sha.digest())
    return rip.hexdigest()  # .hexdigest() is hex ASCII
 
 
pub_keys = open('pubkey.json', 'r', encoding='utf-8')
new_file = open('addresses.json', 'a', encoding='utf-8')
compress_pubkey = False
 
for pub_key in pub_keys:
    pub_key = pub_key.replace('\n', '')
    if compress_pubkey:
        if (ord(bytearray.fromhex(pub_key[-2:])) % 2 == 0):
            pubkey_compressed = '02'
        else:
            pubkey_compressed = '03'
        pubkey_compressed += pub_key[2:66]
        hex_str = bytearray.fromhex(pubkey_compressed)
    else:
        hex_str = bytearray.fromhex(pub_key)
 
 
    key_hash = '00' + hash160(hex_str)
 
 
    sha = hashlib.sha256()
    sha.update(bytearray.fromhex(key_hash))
    checksum = sha.digest()
    sha = hashlib.sha256()
    sha.update(checksum)
    checksum = sha.hexdigest()[0:8]
 
#   new_file.write("" + (base58.b58encode(bytes(bytearray.fromhex(key_hash + checksum)))).decode('utf-8'))
    new_file.write((base58.b58encode(bytes(bytearray.fromhex(key_hash + checksum)))).decode('utf-8') + "\n")
pub_keys.close()
new_file.close()

Мы получили файл addresses.json теперь проверим баланс монет Биткоина используя для этого Python-скрипт bitcoin-checker.py

Запускаем Python-скриптpython2 bitcoin-checker.py

import sys
import re
from time import sleep

try:    # if is python3
    from urllib.request import urlopen
except: # if is python2
    from urllib2 import urlopen


def check_balance(address):

    #Modify the value of the variable below to False if you do not want Bell Sound when the Software finds balance.
    SONG_BELL = True

    #Add time different of 0 if you need more security on the checks
    WARN_WAIT_TIME = 0

    blockchain_tags_json = [ 
        'total_received',
        'final_balance',
        ]

    SATOSHIS_PER_BTC = 1e+8

    check_address = address

    parse_address_structure = re.match(r' *([a-zA-Z1-9]{1,34})', check_address)
    if ( parse_address_structure is not None ):
        check_address = parse_address_structure.group(1)
    else:
        print( "\nThis Bitcoin Address is invalid" + check_address )
        exit(1)

    #Read info from Blockchain about the Address
    reading_state=1
    while (reading_state):
        try:
            htmlfile = urlopen("https://blockchain.info/address/%s?format=json" % check_address, timeout = 10)
            htmltext = htmlfile.read().decode('utf-8')
            reading_state  = 0
        except:
            reading_state+=1
            print( "Checking... " + str(reading_state) )
            sleep(60*reading_state)

    print( "\nBitcoin Address = " + check_address )

    blockchain_info_array = []
    tag = ''
    try:
        for tag in blockchain_tags_json:
            blockchain_info_array.append (
                float( re.search( r'%s":(\d+),' % tag, htmltext ).group(1) ) )
    except:
        print( "Error '%s'." % tag );
        exit(1)

    for i, btc_tokens in enumerate(blockchain_info_array):

        sys.stdout.write ("%s \t= " % blockchain_tags_json[i])
        if btc_tokens > 0.0:
            print( "%.8f Bitcoin" % (btc_tokens/SATOSHIS_PER_BTC) );
        else:
            print( "0 Bitcoin" );

        if (SONG_BELL and blockchain_tags_json[i] == 'final_balance' and btc_tokens > 0.0): 
            
            #If you have a balance greater than 0 you will hear the bell
            sys.stdout.write ('\a\a\a')
            sys.stdout.flush()

            arq1.write("Bitcoin Address: %s" % check_address)
            arq1.write("\t Balance: %.8f Bitcoin" % (btc_tokens/SATOSHIS_PER_BTC))
            arq1.write("\n")
            arq1.close()
            if (WARN_WAIT_TIME > 0):
                sleep(WARN_WAIT_TIME)

#Add the filename of your list of Bitcoin Addresses for check all.
with open("addresses.json") as file:
    for line in file:

    	arq1 = open('balance.json', 'a')
        address = str.strip(line)
        print ("__________________________________________________\n")
        
        check_balance(address)
print "__________________________________________________\n"
arq1.close()

В итоге результат сохранится в файле: balance.json

Файл: balance.json
Файл: balance.json

Теперь мы научились:

  • Конвертировать публичные ключи Биткоина PUBKEY (HEX) в Биткойн Адрес (Base58)
  • Проверять все Биткойн Адреса (Base58) на наличие монет Биткоина
  • Применить это для криптоанализа

Исходный код: https://github.com/demining/CryptoDeepTools/tree/main/03CheckBitcoinAddressBalance

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/Hsk6QIzb7oY

Crypto Deep Tech