In the last article, we learned about creating Bitcoin HD wallets. Today, we will talk about how to create, sign, and broadcast a Bitcoin transaction using Python.
Prerequisite
We will be using bit python library, one of the fastest and easiest libraries to develop Bitcoin related applications. To install bit use the following command.
pip install bit
Creating a Bitcoin wallet (Testnet)
For this tutorial, we will create a Bitcoin testnet wallet. Because we will be creating transactions and sending bitcoins, so we don’t want you to lose your real bitcoins.
Bitcoin Testnet is a network that simulates the original Bitcoin network but does not have any monetary value. Testnet has test bitcoins. Therefore, do not send you real bitcoins to testnet address, you will lose them.
So, let’s create a simple testnet wallet. For this, create a simple python file transaction.py and copy and paste the code below.
from bit import PrivateKeyTestnet
my_key = PrivateKeyTestnet()
print(my_key.version)
print(my_key.to_wif())
print(my_key.address)
This code will create a simple wallet and print wif (Wallet Import Format). Using this wif we can get our wallet again.
Otherwise my_key = PrivateKeyTestnet() will generate a new wallet every time.
Therefore, replace my_key = PrivateKeyTestnet() with my_key = PrivateKeyTestnet(‘wif’) once you get wif . This way, every time we re-run the above code, we will be using the same wallet.
Get Test Bitcoins
Now, we need to get some test bitcoins, so we can send it to another wallet.
To get testnet bitcoins, use this link. Enter the address generated by the above wallet. You can check your testnet transaction here.
Once the transaction is confirmed, you can also check your balance using
print(my_key.balance_as('usd'))
Note: Testnet bitcoins do not have any monetary value.
Creating Transaction
Now we are ready to create a transaction. But wait, we need a receiver address, otherwise, where will we send the transaction. You can create another wallet using the method mentioned above. However, for brevity, we will use the following testnet address.
Note: The address below is a Bitcoin testnet address, do not send real bitcoin on this address.
mkH41dfD4S8DEoSfcVSvEfpyZ9siogWWtr
Now, we have everything, so we are ready to create a Bitcoin transaction.
tx_hash = my_key.send([('mkH41dfD4S8DEoSfcVSvEfpyZ9siogWWtr', 1, 'usd')])
print(tx_hash)
Yes, using bit we can create, sign, and broadcast transactions using just one command. In addition, send() method takes an array as a parameter. This means you can create and send multiple transactions in one go.
The code above will print a transaction hash, which we can check on the Bitcoin testnet block explorer.
Once the transaction is confirmed you can recheck the balance of your wallet using.
print(my_key.get_balance())
For further reading, check out the bit documentation.