How to mine Bitcoin using Python? ( Part – I )

Arnab Mondal 25 Jul, 2022 • 7 min read

This article was published as a part of the Data Science Blogathon

Introduction

Bitcoin is the latest trend in the cryptocurrency world which aims to disrupt the centralized banking system of the world by making it decentralized. Before we jump into the world of crypto-currency we need to understand what is Bitcoin 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 listicle about “5 Tips and Tricks to speed up your Python Programs” and then continue on with this article.

What is a Bitcoin?

bitcoin mining

A bitcoin is an online form of currency that was created in January of 2009 by a mysterious man who goes by 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 lower transaction fee than a traditional payment system for even a large amount of money and all you need to send someone money is their wallet address.

There are no physical coins lying around with the name bitcoin on them but the whole thing is virtual which is maintained on a public ledger to which everyone has equal access. All the transactions are verified with a huge amount of computing power and they are not issued by any bank. They are truly decentralized and secure at the same time. Bitcoin is also commonly known as “BTC”.

The key points to remember are :

  • Bitcoin was launched in 2009 and is the largest cryptocurrency by volume in the world by market cap.
  • Bitcoin is traded, created, distributed, and stored using blockchain technology.
  • Bitcoin prices have been known to be very volatile with massive growth and crashes.
  • It was the first cryptocurrency to meet such popularity and later it inspired a list of other cryptocurrencies or also known as “Altcoins”

Analyzing Bitcoin

 

 

 Analyzing Bitcoin

The Bitcoin ecosystem is made out of nodes or miners who execute the bitcoin code and store it in the blockchain. Each blockchain contains transactions in them and everyone has the whole blockchain to them, thus they can access and see the new blocks being added to the system and it is tamper-proof.

Anyone can view the transactions happening right now and there are over 12000 nodes as of January 2021 and this number keeps on growing every day. Bitcoins are stored in wallets with their own address and it is managed using the public key and the private key which uses encryption to generate long length of strings. The Public key can be thought of as a bank account number or a UPI ID. It is public and telling it to others will do no harm to you. On the other hand, your private key is like your ATM pin or the UPI ID pin. You should never disclose it to anyone else and keep it private at all times.

What is Peer to Peer Technology?

 

 

 What is Peer to Peer Technology?

Bitcoin was perhaps the first digital currency to utilize peer-to-peer technology to create an instant payment system. Any individual with sufficient computing power can become a miner and they process transactions on the blocks. They are motivated by the rewards which is the release of a new bitcoin and transaction fees which is paid in bitcoin.

The miners together make the decentralized authority that upholds the credibility of the whole bitcoin network. It also helps to beat inflation as there will never be more than 21 million bitcoin and by the end of January 2021, 18,614,806 bitcoins have already been mined.  Central banking systems can print more currency whenever they want to so that they can match the rate of the growth in goods but Bitcoins work according to the algorithm and it sets the release date ahead of the time to effectively deal with inflation.

What is Bitcoin Mining?

 

 

 What is Bitcoin Mining?

 

Mining is the process by which bitcoins are gradually released to become a part of the circulation. Mining generally refers to solving a computationally tough mathematical puzzle. Bitcoin Mining is the process of adding verified transactions to the chain and the reward gets halved every 210,000 blocks that are mined. In 2009 the reward was 50 bitcoins per block and after the third halving on 11th MAy 2020, the reward is now down to 6.25 bitcoins.

Any hardware specification can be used for mining but some are just more efficient than the others like ASIC of Application Specific Integrated Circuits or even GPU which outperform the CPU and mine faster than a CPU. One bitcoin can be divided up to 8 decimal places and the smallest unit is known as one Satoshi. If the miners do accept the change, then it can be further divided up into more decimal places.

What is Bitcoin Mining? 2

A Bitcoin Transaction has a miner’s fee attached with it and every transaction is added to a new blockchain and then the next block gets created with the correct hash. With the public key of the sender, the message can be decrypted, and hence never share your private key with anyone.

 

How to Mine Bitcoin?

 How to Mine Bitcoin?

Mining is achieved by finding the correct hash which has a preset number of zeros in the beginning and it also signifies the difficulty level. We begin with importing a necessary library.

from bitcoin import *

If you do not have the package, then you can install it via pip :

pip install bitcoin

After that, we need to create our Private and public key, along with our wallet address. We can do that with the following code.

Python Code:

Now we move onto the computational part where we are going to use SHA256 encryption to find the correct hash. We import the library and then do a test run of what SHA256 actually means.

from hashlib import sha256
sha256("ABC".encode("ascii")).hexdigest()

Output :

b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

When you execute the same code, you will get the same hash code for a particular string and hence it always gives a definite output for a definite input. The length of the hash is 64 and each digit is hexadecimal, which makes it equal to 4 bits and hence the whole number is actually 256 bits and that is why it is also known as SHA256.

Bitcoin follows a protocol that the first ‘n’ number of digits of the has must be zero. Currently the value of ‘n’ stands at 20 but I am gonna show it to you using smaller ‘n’ so that the code actually finishes execution in linear time. The text over which you would apply SHA256 is made up of the Block number, transition details, previous hash value, and since all the 3 previous values are constant for a block and cannot be changed, a new value called ‘Nonce’ is introduced. Our goal is to find the Nonce value so that the hash of the block produces the required number of zeros in the beginning according to the protocol.

mine bitcoin

We will begin coding by taking a dummy transaction along with the latest block number and the previous hash value. We will begin with 4 zeros in the beginning and work our way up and you will realize why bitcoin mining is a tough job. We begin by defining a SHA256 and a mine Function which 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)

Then we 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")

Output :

Bitcoin mined with nonce value: 36674
Hash value :  000086ae35230f32b08e9da254bd7ba1b351f11d40bde27a7ebd5e7ec9568f8d
The mining process took  0.08681821823120117 seconds

If we change the difficulty value by even 1, hence it will be 5, the output will be.

Output :

Bitcoin mined with nonce value : 2387325
Hash value :  00000f5254db00fa0dde976d53bb39c11f9350292949493943a90610d62c1a5e
The mining process took  4.895745515823364 seconds

Hence you can see the drastic change in the time taken by the same code when the difficulty is increased from 4 to 5 and it only keeps on increasing exponentially. Thus that is the main reason why mining one bitcoin takes so much energy and computational power. If that was not enough, you have to be the first one to find the hash or you will not be rewarded. So you are also competing with all the other miners out there and this whole system works on the ‘PoW’ or ‘Proof of Work concept’.

Endnotes

We will discuss more how to connect the mining results to a wallet and how to mine other coins of the same or different concepts in the next part and if you want a sneak peek, you can check out this google collab notebook. If you like my article and want to read more, you can find all my articles listed here. Feel free to reach out to me on LinkedIn for any queries or doubts.

Thank you for reading till the end and Stay safe everyone <3.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

Arnab Mondal 25 Jul 2022

Just a guy who loves to code and learn new languages and concepts

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Patt Robinson
Patt Robinson 10 Jun, 2021

Don't put all your eggs in 1 basket. Bitcoin will always be around because of the coin exchanges and its own blockchain. Given.. I Ran into a video few months ago, I found so many people showering Accolades to digitalcurrency14 @gmailCom who has made a great Impact to so many young crypto investors since last year, some said he has the best strategy to trade Forex, Bitcoin and mine, I was tired of Gdax and Binance small profits i was getting, so I reached out to via email, and he gave me the best tips to excel in the world of Crypto, i bet you his signals, investment management, fund recovery of lost investors funds from their scam broker platforms and mining team are unlike anything you have ever seen. Now I don’t just Hold, I make more Gains, after 3months I can Boast of increasing my Portfolio from 2Btc to 12.5Btc in less than six months, all Thanks to Digital currency Almighty Formula for Trading mining and investment, Y'all can reach out to him via his email

Max Mazor
Max Mazor 20 Jun, 2021

Hi, This is a grate article, very informative. Where can i find the part 2 ? :) I need to figure out how to connect and start mining by my own mining soft and algorithm. Very appreciate!

Quam
Quam 02 Aug, 2021

Man, can you please post it's next part how to connect to wallet.

Sebastian Amsel
Sebastian Amsel 16 Aug, 2021

Bitcoin is more than an asset....I am here to testify how jim helped me mine 6 btc within 72 hours and this is nothing but the truth because i have all the btc kept in my hard wallet already just as advised by the prof so i don't get hacked again. It all started when i got an update from my close friend about the prof helping him accumulate some btc. I email the him right away and he shed more light on it. He explained and gave me the process which i followed and all i have to do is to wait. I joined the mining team and the prof attached my address to his mining pool. I got 2 btc daily till it's completely 6 btc on the third day. I got all on my blockchain account and the he advise i move the btc to my hard wallet asap. I cannot stop thanking what he did because i've been ripped by some online websites that i was investing with without getting a result. I have known the him for barely 2 weeks and it felt like a dream. I will advise anybody willing to mine bitcoins to join jim's mining team because your result is guaranteed without any excuses or delays. (MORGANJIMCRYPTONARY@GMAIL. COM)

Rohan Devaki
Rohan Devaki 23 Dec, 2021

does this code generate actual bitcoins that we can withdraw to our wallet?

Kenneth
Kenneth 27 Dec, 2021

Love the post but I have been waiting for partii"how to connect the mining results to a wallet and how to mine other coins of the same or different concepts" but nothing out yet. I will be grateful if you can do the second part. I will be looking forward to it

Kenneth
Kenneth 27 Dec, 2021

I have been waiting for partii"how to connect the mining results to a wallet and how to mine other coins of the same or different concepts". But nothing's out yet . I will be grateful if look on to it.

Ashish Reddy
Ashish Reddy 11 Jan, 2022

That's an awesome article Arnab. Bitcoin mining using Python is amazing. You described it very well. Thanks for sharing this important information.

James morrison
James morrison 19 Jan, 2022

great blog first of all! I had one question regarding bitcoin. how can bitcoin give the status of the safest option for money transfer when each day its price is fluctuating. how can it be compared with money when it can be said as stored of value?

Patt Robinson
Patt Robinson 23 Jan, 2022

Bitcoin will always be around because of the coin exchanges and its own blockchain. Given.. I Ran into a video few months ago, I found so many people showering Accolades to digitalcurrency14 @gmailCom who has made a great Impact to so many young crypto investors since last year, some said he has the best strategy to trade Forex, Bitcoin and mine, I was tired of Gdax and Binance small profits i was getting, so I reached out to him via email, and he gave me the best tips to excel in the world of Crypto, i bet you his signals, investment management, fund recovery of lost investors funds from their scam broker platforms and mining team are unlike anything you have ever seen. Now I don’t just Hold, I make more Gains, after 3months I can Boast of increasing my Portfolio from 2Btc to 12.5Btc in less than six months, all Thanks to Digital currency

mayuri
mayuri 24 May, 2023

awesome article thanks for information