Проверить баланс биткоин кошелька python

Use Python to get the balance of a Bitcoin wallet

In this article we will use Python to get the balance of a Bitcoin wallet. Bitcoin is a decentralized digital currency that can be sent and received without the need for intermediaries such as banks. The most common way to interact with the Bitcoin network is through a software or hardware wallet. A Bitcoin wallet is a program that allows a user to store, send and receive Bitcoin. In this article, we will explore how to use Python to get the balance of a Bitcoin wallet.

Before we begin, it is important to note that there are several different libraries available for interacting with the Bitcoin network in Python. The most popular of these libraries is Bitcoinlib. Bitcoinlib is a powerful and easy to use library that provides a simple interface for interacting with the Bitcoin network.

Install Bitcoinlib

To use Bitcoinlib, we first need to install it. This can be done using pip, the package installer for Python. To install Bitcoinlib, open up a terminal and enter the following command:

Copy codepip install bitcoinlib 

Interact with the Bitcoin network

Once Bitcoinlib is installed, we can start using it to interact with the Bitcoin network. The first thing we need to do is to import the library. This can be done by adding the following line to the top of your Python script:

Copy codeimport bitcoinlib 

Next, we need to create a connection to the Bitcoin network. This can be done using the .connect_to_local() method provided by Bitcoinlib. This method connects to a local Bitcoin node using the default settings. If you want to connect to a remote node, you can use the .connect() method and pass in the host and port of the remote node.

Copy codeconnection = bitcoinlib.connect_to_local() 

Once we have a connection to the Bitcoin network, we can use it to retrieve the balance of a Bitcoin wallet. To do this, we need to know the address of the wallet. The address is a string of letters and numbers that represents the location of the wallet on the Bitcoin network.

To get the balance of a wallet, we can use the .getbalance() method provided by Bitcoinlib. This method takes the address of the wallet as a parameter and returns the balance in satoshis. One satoshi is the smallest unit of Bitcoin, equivalent to 0.00000001 BTC.

Copy codeaddress = '1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2' balance = connection.getbalance(address) print(balance) 

The above code will print the balance of the wallet with the address 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2 in satoshis.

Читайте также:  Center tag and html

To convert the balance from satoshis to Bitcoin, we can simply divide the balance by 100 million (100 million satoshis is equal to 1 Bitcoin). The following code snippet shows how to convert the balance to Bitcoin.

Copy codebalance_btc = balance / 100000000 print(balance_btc) 

The above code will print the balance of the wallet in Bitcoin.

Other options

It’s worth noting that there are other libraries available for interacting with the Bitcoin network in Python, such as python-bitcoinlib, pycoin and pybitcointools, but Bitcoinlib is the most comprehensive and easy-to-use library and it’s actively maintained.

In conclusion, using Python and a library like Bitcoinlib makes it relatively easy to interact with the Bitcoin network and retrieve information about a wallet, such as its balance. This can be useful for building applications that needRegenerate response

Resources

Blockchain Networks

Below is a list of EVM compatible Mainnet and Testnet blockchain networks. Each link contains network configuration, links to multiple faucets for test ETH and tokens, bridge details, and technical resources for each blockchain. Basically everything you need to test and deploy smart contracts or decentralized applications on each chain. For a list of popular Ethereum forums and chat applications click here.

Ethereum test network configuration and test ETH faucet information
Optimistic Ethereum Mainnet and Testnet configuration, bridge details, etc.
Polygon network Mainnet and Testnet configuration, faucets for test MATIC tokens, bridge details, etc.
Binance Smart Chain Mainnet and Testnet configuration, faucets for test BNB tokens, bridge details, etc.
Fanton networt Mainnet and Testnet configuration, faucets for test FTM tokens, bridge details, etc.
Kucoin Chain Mainnet and Testnet configuration, faucets for test KCS tokens, bridge details, etc.

Web3 Software Libraries

You can use the following libraries to interact with an EVM compatible blockchain.

  • Python: Web3.py A Python library for interacting with Ethereum. Web3.py examples
  • Js: Web3.js Ethereum JavaScript API
  • Java: Web3j Web3 Java Ethereum Ðapp API
  • PHP: Web3.php A php interface for interacting with the Ethereum blockchain and ecosystem.

Источник

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

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

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

Давайте перейдем в репозиторию «CryptoDeepTools» и разберем в детали работу 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

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

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

Запускаем 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])', 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 %.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

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

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

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Tool checks balances for massive amount of addresses

License

geniusprodigy/bitcoin-balance-checker

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Tool checks balances for massive amount of addresses

You can use this tool using the two address lists generated by my other tool which is very useful: https://github.com/geniusprodigy/mega-tool-pvkmassconvert

  • Create a .txt file named «list-addresses» and replace the directory sample file. Or edit the existing file with your Bitcoins Addresses, 1 per line, or use the two files generated on Output from my other tool «mega-tool-pvkmassconvert» by editing the file name for the name that the code recognizes «list-addresses».

If you prefer, you can edit the file name recognized by the code in line 87 of the script. Edit and enter the name you want so that this file is read by the software.

Whenever a Address with balance is found, you will hear 3 beeps of the bell sound, it is an alert that you can deactivate if you wish, just change the value True to «False» in line 21 of the source code.

Ps: The 10 most valuable (old) bitcoin addresses in history were used as an example to be checked.

The output is a file addresses-with-balance-yay.txt

This file contains all Bitcoin Addresses in which balance was found in the scan.

It is sorted by Address and the balance just ahead already formed in the default Bitcoin unit.

If this helped you, please leave a tip. BTC Address: 1FrRd4iZRMU8i2Pbffzkac5u4KwUptmc7S Use at your own risk. I am not responsible for any use.

About

Tool checks balances for massive amount of addresses

Источник

Оцените статью