Python Bitcoin Miner

Pratik Solanki
4 min readApr 16, 2021

We will be writing code for a python bitcoin miner. I will cover some theories behind blockchain. First and then we’ll write the code the timestamp for coding is given below.

If you know the theory behind blockchain. And if you know how it works, you can straight away jump into coding. bitcoin is nothing but ledgers.

What are ledgers?

I have an example of a ledger. A ledger nothing but it is a set of transactions.

let’s say you go to a grocery store you buy vegetables for 35 dollars. So the ledger entry will be you are paying the vegetable owner 35 dollars. And then the vegetable guy. let’s say go to a doctor and he pays money for let’s said some medicine.

let’s say he pays 25 dollars so then it will be like a vegetable owner paying to pharmacy 25 dollars.
it’s just a set of transactions this is more like your bank account in a bank account. Let’s say you have a 2000 dollar deposit for your salary. And then 500 lets say you spent on a mortgage.

What is left with you?

well, 1500 dollars. so the ledger is a set of transactions at the end you have your account balance. So that’s all that bitcoin is. Here I have shown you a sample ledger. And this ledger might have millions of transactions.

In the bitcoin world, the bitcoin ledger stores all transaction that has happened since bitcoin was invented. So that will be millions of transactions so you need to store them in blocks. Because storing them continuously in one continuous memory location is not possible. So if you have studied the linked list in your data structures. In the linked list you have one node and then you have an address to the second node. It is similar to that.

You have one blockchain where you have block one, block two, block three. And these are just the block size of bitcoin is one megabyte. So in one megabyte, you store some transactions then you move to the next block. For the further transaction and these blocks are linked together. Now bitcoin protocol has some security mechanism to avoid fraud for which we need to go a little into cryptography.

What is cryptography? And What is the cryptographic hash function?

so let’s look at that. In cryptography, there is a function called sha256 where you give an input string, and it will generate a hash. If you know about the hash function this is just a hash function. That will generate a hash that is 256 bit long. In terms of hexadecimal, it will be 64 hexadecimal digits this is impossible to guess.

If I give you this kind of hash to make a guess on x. It’s close to impossible the only way you have is you try and error you try different strings. And try to see you know which one produces the desired output.

It is simple python code you write only three lines of python code. To produce sha of any string and sha256 is a cryptographic hash function.

from hashlib import sha256

text = “ABC”

print(sha256(text.encode(“ascii”)).hexdigest())

In a blockchain, the actual block is not the only transaction it has a couple of more components. It has a block number. It has the previous hash and then the bitcoin protocol is such that. You convert this whole block into a string.

How many digits?

Well, it changes from time to time right now. I think it’s 30 digits but at some point when it starts started. It was less so let’s say we are saying that the first four digits of the hash. Should be zero so that is our difficulty level so you need to add.

so for doing bitcoin mining these miners get a reward in 2009 if you mine one block you will

Today thousands of people are doing bitcoin mining. But the thing is this guesswork seems easy. But we’ll see in the code it’s very time-consuming it’s not a difficult algorithm.

The code is simple but it takes a lot of computation power, electricity to get to the right guess. And if 10 people are doing guess. Who makes the correct guess first that person will win the reward. Let’s say I make a guess after 10-minute Another person is making a guess. That person doesn’t get a reward. So that’s the theory, in the end, the blockchain looks like this. Where every block will have a reference to the previous hash.

Let’s get into the coding of python bitcoin miner :

I have open the PyCharm community edition and have created this file. Where I have imported the

hashlib

module so that I can use the sha256 function.

python bitcoin miner program:

from hashlib import sha256

MAX_NONCE = 100000000000

def SHA256(text):

return sha256(text.encode(“ascii”)).hexdigest()

def mine(block_number, transactions, previous_hash, prefix_zeros):

prefix_str = ‘0’*prefix_zeros

for nonce in range(MAX_NONCE):

text = str(block_number) + transactions + previous_hash + str(nonce)

new_hash = SHA256(text)

if new_hash.startswith(prefix_str):

print(f”Yay! Successfully mined bitcoins with nonce value:{nonce}”)

return new_hash

raise BaseException(f”Couldn’t find correct has after trying {MAX_NONCE} times”)

if __name__==’__main__’:

transactions=’’’

Dhaval->Bhavin->20,

Mando->Cara->45

‘’’

difficulty=4 # try changing this to higher number and you will see it will take more time for mining as difficulty increases

import time

start = time.time()

print(“start mining”)

new_hash = mine(5,transactions,’0000000xa036944e29568d0cff17edbe038f81208fecf9a66be9a2b8321c6ec7', difficulty)

total_time = str((time.time() — start))

print(f”end mining. Mining took: {total_time} seconds”)

print(new_hash)

--

--