Learning-Bitcoin-from-the-C.../src/18_4_accessing_bitcoind_with_python.py

193 lines
7.1 KiB
Python

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from pprint import pprint
import logging
# logging.basicConfig()
# logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)
# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_user = "<ENTER_THE_RPC_USER_FROM_bitcoin.conf>"
rpc_pass = "<ENTER_THE_RPC_PASSWORD_FROM_bitcoin.conf>"
rpc_host = "127.0.0.1"
rpc_client = AuthServiceProxy(f"http://{rpc_user}:{rpc_pass}@{rpc_host}:18332", timeout=240)
# Getting Basic Info
print("Getting Basic Info")
## Get Wallet Info
wallet_info = rpc_client.getwalletinfo()
print("---------------------------------------------------------------")
print("Wallet Info:")
print("-----------")
pprint(wallet_info)
print("---------------------------------------------------------------\n")
## Get Network Info
network_info = rpc_client.getnetworkinfo()
print("---------------------------------------------------------------")
print("Network Info:")
print("------------")
pprint(network_info)
print("---------------------------------------------------------------\n")
## Get Blockcount
block_count = rpc_client.getblockcount()
print("---------------------------------------------------------------")
print("Block Count:", block_count)
print("---------------------------------------------------------------\n")
# Get Blockchain Info
blockchain_info = rpc_client.getblockchaininfo()
print("---------------------------------------------------------------")
print("Blockchain Info:")
print("---------------")
pprint(blockchain_info)
print("---------------------------------------------------------------\n")
# Get Peer Info
peer_info = rpc_client.getpeerinfo()
print("---------------------------------------------------------------")
print("Peer Info:")
print("---------")
pprint(peer_info)
print("---------------------------------------------------------------\n")
# Exploring a Block
print("Exploring a Block")
blockhash_630000 = rpc_client.getblockhash(630000)
block_630000 = rpc_client.getblock(blockhash_630000)
nTx = block_630000['nTx']
if nTx > 10:
it_txs = 10
list_tx_heading = "First 10 transactions: "
else:
it_txs = nTx
list_tx_heading = f"All the {it_txs} transactions: "
print("---------------------------------------------------------------")
print("BLOCK No. 630000 :")
print("-------------")
print("Block Hash...: ", blockhash_630000)
print("Merkle Root..: ", block_630000['merkleroot'])
print("Block Size...: ", block_630000['size'])
print("Block Weight.: ", block_630000['weight'])
print("Nonce........: ", block_630000['nonce'])
print("Difficulty...: ", block_630000['difficulty'])
print("Number of Tx.: ", nTx)
print(list_tx_heading)
print("---------------------")
i = 0
while i < it_txs:
print(i, ":", block_630000['tx'][i])
i += 1
print("---------------------------------------------------------------\n")
# Exploring an Address
print("Exploring an Address")
track_address = "<your address>"
tx_list = rpc_client.listtransactions()
address_tx_list = []
for tx in tx_list:
if tx['address'] == track_address:
address_tx_list.append(tx)
pprint(address_tx_list)
# Exploring UTXOs
print("Exploring UTXOs")
## List Utxos
utxos = rpc_client.listunspent()
print("Utxos: ")
print("-----")
pprint(utxos)
print("------------------------------------------\n")
## Select a UTXO - first one selected here
utxo_txid = utxos[0]['txid']
## Get UTXO Hex
utxo_hex = rpc_client.gettransaction(utxo_txid)['hex']
## Get tx Details
utxo_tx_details = rpc_client.decoderawtransaction(utxo_hex)
print("Details of Utxo with txid:", utxo_txid)
print("---------------------------------------------------------------")
print("UTXO Details:")
print("------------")
pprint(utxo_tx_details)
print("---------------------------------------------------------------\n")
# Creating a Transaction
print("Creating a Transaction")
## Create New Addresses
new_address = rpc_client.getnewaddress("Learning-Bitcoin-from-the-Command-Line")
new_change_address = rpc_client.getrawchangeaddress()
print("---------------------------------------------------------------")
print("New Address Recipient: ", new_address)
print("New Address Change...: ", new_change_address)
print("---------------------------------------------------------------\n")
## Set Transaction Details
selected_utxo = utxos[0] # we select the first utxo here
utxo_address = selected_utxo['address']
utxo_txid = selected_utxo['txid']
utxo_vout = selected_utxo['vout']
utxo_amt = float(selected_utxo['amount'])
# here we are sending bitcoins to an address generated by us in our own wallet.
recipient_address = new_address
recipient_amt = utxo_amt / 2 # sending half coins to recipient
miner_fee = 0.00000200 # choose appropriate fee based on your tx size
change_address = new_change_address
change_amt = float('%.8f'%((utxo_amt - recipient_amt) - miner_fee))
print("---------------------------------------------------------------")
print("Transaction Details:")
print("-------------------")
print("UTXO Address.......: ", utxo_address)
print("UTXO Txid..........: ", utxo_txid)
print("Vector ID of Output: ", utxo_vout)
print("UTXO Amount........: ", utxo_amt)
print("Tx Amount..........: ", recipient_amt)
print("Recipient Address..: ", recipient_address)
print("Change Address.....: ", change_address)
print("Miner Fee..........: ", miner_fee)
print("Change Amount......: ", change_amt)
print("---------------------------------------------------------------\n")
## create a raw transacion
txids_vouts = [{"txid": utxo_txid, "vout": utxo_vout}]
addresses_amts = {f"{recipient_address}": recipient_amt, f"{change_address}": change_amt}
create_raw_tx = rpc_client.createrawtransaction(txids_vouts, addresses_amts)
unsigned_tx_hex = create_raw_tx
print("---------------------------------------------------------------")
print("Unsigned Transaction Hex: ", unsigned_tx_hex)
print("---------------------------------------------------------------\n")
## Check details of the Transaction
tx_details = rpc_client.decoderawtransaction(unsigned_tx_hex)
print("---------------------------------------------------------------")
print("New Transaction Details:")
print("-----------------------")
pprint(tx_details)
print("---------------------------------------------------------------\n")
## Sign Transanciton
address_priv_key = [] # list of priv keys of each utxo
address_priv_key.append(rpc_client.dumpprivkey(utxo_address))
print("---------------------------------------------------------------")
print(f"Private key of address {utxo_address}: ", address_priv_key)
print("---------------------------------------------------------------\n")
signed_tx = rpc_client.signrawtransactionwithkey(unsigned_tx_hex, address_priv_key)
print("---------------------------------------------------------------")
print("Signed Transaction: ")
print("----------------------")
pprint(signed_tx)
print("---------------------------------------------------------------\n")
## Send Transaction
send_tx = rpc_client.sendrawtransaction(signed_tx['hex'])
print("---------------------------------------------------------------")
print("TXID of sent transaction: ", send_tx)
print("---------------------------------------------------------------\n")
print("Now explore! ;)")