Python Bitcoin Miner – Blockchain and Python

Blockchain is the foundation of cryptocurrency that is receiving extensive attention for the past few years. It is more of an immutable ledger that allows transactions without involvement from a central authority. Hence, Blockchain is a data storage platform that consists of blocks connected to each other. On each block, there is data stored about the transactions.

Bitcoin is computerized cash that uses the blockchain to work, with no central authority like the government, banks, and overseeing exchanges. Hence, users can trade with fewer middlemen, which translates into smoother and cheaper transactions. With the absence of any central authority, the need for security rises. For this purpose, Bitcoin generates multiple keys to approve the multi-signature verification.

Python Bitcoin Miner

Bitcoin mining is a way to add more bitcoins to the world through arithmetical calculations. Anyone can learn how to mine Bitcoins by running a PC program or particular bitcoin mining equipment. Being an interpreted and high-level programming language, Python very well enables Blockchain mining. In order to get started, you first need to develop a mining function. The mining function then generates a digest on a given message string while providing a proof-of-work. Let’s get into the details.

Message Digest Function

Firstly, you would need to write a utility function called sha256 for creating a message digest function on a given message string:

def sha256(message):                                  

return hashlib.sha256(message.encode(‘ascii’)).hexdigest()

Once you are done writing the utility function, it will take a message as a parameter. The message will then be encoded to ASCII and a hexadecimal digest is generated which returns the value to the caller.

Mining Function

The next step is developing the mine function based on your own mining strategy. The strategy we are aiming here for is to generate a hash on the given message string that is prefixed with a given number of 1’s. The number 1’s is specified as the difficulty level and acts as a parameter to the mine function.

For instance, if you specify a difficulty level of 2, this how your generated hash on a given message would start: 11xxxxxxxx. Hence, the number of 1’s corresponds with the level of difficulty. The same is the case with level 3. For level 3, the generated hash should start with three 1’s, like 111xxxxxxxx. Based on this principle, let’s see how to develop the mining function.

Step 1:

All you need to develop a mining function are two parameters:

  • The message.
  • The difficulty level.

def mine(message, difficulty=1):

Step 2:

The difficulty level must be greater or equal to 1. Have a look at the following assert statement:

assert difficulty >= 1

Step 3:

Next, you would need to create a prefix variable using the set difficulty level.

prefix = ‘1’ * difficulty

However, it must be noted that the prefix changes according to the difficulty level. If the difficulty level is 4 the prefix would be “1111” and if it is 2, the prefix would be “11”. Also, you would need to check if your prefix exists in the generated digest of the message. Moreover, to digest the message itself, the following two lines of code are used.

for “i” in range(1000):

   digest = sha256(str(hash(message)) + str(i))

Also, to generate a new digest on the combined message, just keep on adding a new number ‘i’ to the message hash in each iteration. As you change the input to the sha256 function, the digest value also changes accordingly.

Do not forget to check if this digest value has the above-set prefix.

if digest.startswith(prefix):

If the situation is settled and everything went smooth, terminate the for loop and return the digest value to the caller.

You will get the entire mine code and this is how it will look:

def mine(message, difficulty=1):

   assert difficulty >= 1

   prefix = ‘1’ * difficulty

   for i in range(1000):

      digest = sha256(str(hash(message)) + str(i))

      if digest.startswith(prefix):

         print (“after ” + str(i) + ” iterations found nonce: “+ digest)

      return digest

At the bottom of the code, we also added the print statement for your understanding. The prints statement prints the digest value and the number of iterations.

Testing Mining Function

After generating the code, it is time to test your mining function. For this purpose, simply execute the following.

mine (“test message”, 2)

As soon as you run the above statement, you will see the following output:

after 138 iterations found nonce:

11008a740eb2fa6bf8d55baecda42a41993ca65ce66b2d3889477e6bfad1484c

As mentioned above, the generated digest starts with “11” if the difficulty level is 2. As you increase the difficulty level, it will require more iterations of course. Hence, a miner with more processing power will be able to mine faster and earlier. In the cryptocurrency market, this is how the miners compete with each other for earning their revenues.

The Bottom Line

In the guide above, we have learned how to mine Bitcoin in Python. We tried to cover almost everything that you would need to start mining. However, there are still many areas that you need to learn if you want to construct a Bitcoin miner or blockchain project in Python. For example, other than mining you must know how to write functions for managing the transactions queue, what happens after the transactions are mined, and for how long they need to be stored.

Leave a Reply