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

0 8
Avatar for Shubham007
2 years ago

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?

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.

#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)

Output :

Private Key: 82bd4291ebaa6508001600da1fea067f4b63998ed85d996aed41df944c3762be
Public Key: 04f85fa7c009dba8d1e6b7229949116f03cb3de0dfaf4d6ef3e6320a278dfc8dd91baf058fcafe0b5fbf94d09d79412c629d19cc9debceb1676d3c6c794630943d
Bitcoin Address: 1FtaFRNgxVqq4s4szhC74EZkJyShmeH5AU

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.

Hope You like My Articles , I will be Sharing So many articles on Cryptocurrency Stay Tune

0
$ 0.00
Avatar for Shubham007
2 years ago

Comments