This article was published as part of the Data Science Blogathon
Introduction
Before jumping into the world of cryptocurrencies, we need to understand what bitcoin is and how to mine with python. If your system is old or Python runs slower than other languages on your local machine, then you can read this list on "5 tips and tricks to speed up your Python programs" and then continue with this article.
What is a Bitcoin?

A bitcoin is a form of online currency that was created in January 2009 by a mysterious man who uses the pseudonym. “Satoshi Nakamoto”. The whitepaper can be found here. The identity of the person is a mystery to date and Bitcoin actually offers a fee of transactionThe "transaction" refers to the process by which an exchange of goods takes place, services or money between two or more parties. This concept is fundamental in the economic and legal field, since it involves mutual agreement and consideration of specific terms. Transactions can be formal, as contracts, or informal, and are essential for the functioning of markets and businesses.... lower than a traditional payment system even for a large amount of money and all you need to send money to someone is their wallet address.
There are no physical coins with the name bitcoin on them, but everything is virtual and is kept in a public book to which everyone has the same access. All transactions are verified with a large amount of computing power and are not issued by any bank. They are really decentralized and secure at the same time. Bitcoin is also commonly known as “BTC”.
The key points to remember are:
- Bitcoin launched in 2009 and is the largest cryptocurrency in the world by market capitalization volume.
- Bitcoin is traded, creates, distributes and stores using blockchain technology.
- Bitcoin prices are known to be very volatile with massive growth and declines.
- It was the first cryptocurrency to achieve such popularity and later inspired a list of other cryptocurrencies or also known as “Altcoins”.
Analyzing Bitcoin

The Bitcoin ecosystem is made up of nodes or miners that run bitcoin code and store it on the blockchain. Each blockchain contains transactions on them and they all have the entire blockchain, so they can access and see the new blocks being added to the system and it is tamper proof.
Anyone can see the transactions that occur at the moment and there are more than 12000 nodes as of January 2021 and this number keeps growing every day. Bitcoins are stored in wallets with their own address and managed using the public key and the private key that uses encryption to generate long-lasting chains. The public key can be thought of as a bank account number or a UPI ID. It's public and telling others won't hurt. Secondly, your private key is like your ATM pin or UPI identification pin. You should never reveal it to anyone else and keep it private at all times.
What is Peer to Peer technology?
Bitcoin was perhaps the first digital currency to use peer-to-peer technology to create an instant payment system.. Any individual with sufficient computing power can become a miner and process transactions on the blocks. They are motivated by the rewards that are the launch of a new bitcoin and the transaction fees that are paid in bitcoin.
The miners together form the decentralized authority that upholds the credibility of the entire bitcoin network. It also helps beat inflation, since there will never be more than 21 million bitcoins and, by the end of January 2021, have already been extracted 18.614.806 bitcoins. Central banking systems can print more currency whenever they want so they can match the growth rate of goods, but bitcoins work according to algorithm and set launch date ahead of time to effectively deal with inflation.
What is Bitcoin Mining?

Mining is the process by which bitcoins are gradually released to become part of circulation. Mining generally refers to solving a computationally difficult mathematical puzzle. Bitcoin Mining is the process of adding verified transactions to the chain and the reward is halved each 210,000 blocks to be mined. In 2009, the reward was 50 bitcoins per block and after the third halving the 11 May 2020, the reward has now been reduced to 6.25 bitcoins.
Any hardware specification can be used for mining, but some are more efficient than others, as application-specific IC ASICs or even GPUs, that outperform the CPU and extract faster than a CPU. One bitcoin can be divided up to 8 decimal places and the smallest unit is known as a Satoshi. If the miners accept the change, then it can be divided into more decimal places.
A Bitcoin transaction has a miner fee attached and each transaction is added to a new blockchain and then the next block with the correct hash is created. With the sender's public key, the message can be decrypted and, Thus, never share your private key with anyone.
How to mine Bitcoin?

Mining is achieved by finding the correct hash which has a preset number of zeros at the beginning and also signifies the level of difficulty. We start with the import of a necessary library.
from bitcoin import *
If you don't have the package, you can install it via pip:
pip install bitcoin
Thereafter, we need to create our private and public key, together with our wallet address. We can do that with the following code.
#Generate private key
my_private_key = random_key()
#display private key
print("Private Key: %sn" % my_private_key)
#Generate public key
my_public_key = privtopub(my_private_key)
print("Public Key: %sn" % my_public_key)
#Create a bitcoin address
my_bitcoin_address = pubtoaddr(my_public_key)
print("Bitcoin Address: %sn" % my_bitcoin_address)
Production :
Private Key: 82bd4291ebaa6508001600da1fea067f4b63998ed85d996aed41df944c3762be Public Key: 04f85fa7c009dba8d1e6b7229949116f03cb3de0dfaf4d6ef3e6320a278dfc8dd91baf058fcafe0b5fbf94d09d79412c629d19cc9debceb1676d3c6c794630943d Bitcoin Address: 1FtaFRNgxVqq4s4szhC74EZkJyShmeH5AU
Now we move on to the computational part where we will use SHA256 encryption to find the correct hash. We import the library and then do a test of what SHA256 really means.
from hashlib import sha256
sha256("ABC".encode("ascii")).hexdigest()
Production :
b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78
When you run the same code, you will get the same hash code for a particular string and, Thus, always gives a defined output for a defined input. The length of the hash is 64 and each digit is hexadecimal, what makes it equal to 4 bits y, Thus, the whole number is actually 256 bits and that is why it is also known as SHA256.
Bitcoin follows a protocol in which the first number 'n’ digits must be zero. Nowadays, the value of 'n’ it is 20, but I'll show you using a 'n’ smaller for code to finish execution in linear time. The text on which SHA256 would apply is composed of the block number, transition details, the previous hash value and, since the 3 Above values are constant for a block and cannot be changed, a new value called 'Nonce' is introduced. Our goal is to find the value of Nonce so that the block hash produces the required number of leading zeros according to the protocol.

We will start coding by taking a dummy transaction along with the last block number and the previous hash value. We will start with 4 zeros at the beginning and we will move up and you will realize why bitcoin mining is hard work. We start by defining a SHA256 and a mine function that we would call.
def SHA256(text):
return sha256(text.encode("ascii")).hexdigest()
MAX_NONCE = 10000000 # You can also use a while loop to run infinitely with no upper limit
def mine(block_number,transaction,previous_hash,prefix_zeros):
prefix_str="0"*prefix_zeros
for nonce in range(MAX_NONCE):
text= str(block_number) + transaction + previous_hash + str(nonce)
hash = SHA256(text)
# print(hash)
if hash.startswith(prefix_str):
print("Bitcoin mined with nonce value :",nonce)
return hash
print("Could not find a hash in the given range of upto", MAX_NONCE)
We then provide the required details and start mining with 4 zeros at the beginning of the hash.
transactions=""' A->B->10 B->c->5 ''' difficulty = 4 import time as t begin=t.time() new_hash = mine(684260,transactions,"000000000000000000006bd3d6ef94d8a01de84e171d3553534783b128f06aad",difficulty) print("Hash value : ",new_hash) time_taken=t.time()- begin print("The mining process took ",time_taken,"seconds")
Production :
Bitcoin mined with nonce value: 36674 Hash value : 000086ae35230f32b08e9da254bd7ba1b351f11d40bde27a7ebd5e7ec9568f8d The mining process took 0.08681821823120117 seconds
If we change the difficulty value even in 1, Thus, it will be 5, the output will be.
Production :
Bitcoin mined with nonce value : 2387325 Hash value : 00000f5254db00fa0dde976d53bb39c11f9350292949493943a90610d62c1a5e The mining process took 4.895745515823364 seconds
Therefore, you can see the drastic change in the time it takes for the same code when the difficulty increases from 4 a 5 and it just keeps increasing exponentially. Therefore, that's the main reason mining a bitcoin requires so much energy and computational power. If that wasn't enough, you must be the first to find the hash or you will not be rewarded. Then, it is also competing with all the other miners and this whole system works on the concept of ‘PoW’ or 'Proof of work'.
Final notes
We will discuss more about how to connect mining results to a wallet and how to mine other coins from the same or different concepts in the next part and if you want a sneak peek, you can check this. google collab notebook. If you like my article and want to read more, you can find all my items listed here. Feel free to contact me at LinkedIn for any question or doubt.
Thanks for reading to the end and stay safe for everyone <3.
The media shown in this article is not the property of DataPeaker and is used at the author's discretion.



