Before we jump into the earth of crypto-currency we need to understand what is Bitcoin and how to mine with python ? If your system is previous 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?
A bitcoin is an on-line form of currency that was created in January of 2009 by a mysterious world 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 boastfully total of money and all you need to send person 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 populace ledger to which everyone has equal entree. All the transactions are verified with a huge come of computing ability and they are not issued by any bank. They are in truth decentralize and impregnable at the same time. Bitcoin is besides normally 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”
The Bitcoin ecosystem is made out of nodes or miners who execute the bitcoin code and storehouse 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 encoding to generate long length of strings. The Public key can be thought of as a bank score act 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 fall. You should never disclose it to anyone else and keep it individual at all times .
What is Peer to Peer Technology?
Bitcoin was possibly the first digital currency to utilize peer-to-peer technology to create an instantaneous payment system. Any individual with sufficient computing office can become a miner and they process transactions on the blocks. They are motivated by the rewards which is the release of a modern 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 besides 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 increase in goods but Bitcoins work according to the algorithm and it sets the acquittance date ahead of the time to efficaciously deal with ostentation .
What is Bitcoin Mining?
mining is the process by which bitcoins are gradually released to become a share of the circulation. Mining generally refers to solving a computationally bully mathematical puzzle. Bitcoin Mining is the process of adding verified transactions to the chain and the honor gets halved every 210,000 blocks that are mined. In 2009 the reward was 50 bitcoins per jam and after the one-third halve on 11th MAy 2020, the reward is immediately down to 6.25 bitcoins .
Any hardware stipulation can be used for mine but some are merely 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 of measurement is known as one Satoshi. If the miners do accept the switch, then it can be farther divided up into more decimal places .
A Bitcoin Transaction has a miner ’ sulfur fee attached with it and every transaction is added to a new blockchain and then the next barricade gets created with the adjust 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?
mining is achieved by finding the correct hash which has a preset phone number of zero in the begin and it besides signifies the difficulty level. We begin with importing a necessity library .
from bitcoin import *
If you do not have the package, then you can install it via blip :
pip install bitcoin
After that, we need to create our Private and public cardinal, along with our wallet address. We can do that with the postdate 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)
Private Key: 82bd4291ebaa6508001600da1fea067f4b63998ed85d996aed41df944c3762be Public Key: 04f85fa7c009dba8d1e6b7229949116f03cb3de0dfaf4d6ef3e6320a278dfc8dd91baf058fcafe0b5fbf94d09d79412c629d19cc9debceb1676d3c6c794630943d Bitcoin Address: 1FtaFRNgxVqq4s4szhC74EZkJyShmeH5AU
nowadays we move onto the computational separate where we are going to use SHA256 encoding to find the compensate hash. We import the library and then do a test function of what SHA256 actually means .
from hashlib import sha256 sha256("ABC".encode("ascii")).hexdigest()
When you execute the lapp code, you will get the like hash code for a particular string and therefore it always gives a definite output signal for a definite remark. The distance of the hash is 64 and each digit is hexadecimal, which makes it peer to 4 bits and therefore the whole number is actually 256 bits and that is why it is besides known as SHA256 .
Bitcoin follows a protocol that the beginning ‘ n ’ number of digits of the has must be zero. presently the respect of ‘ n ’ stands at 20 but I am gon na show it to you using smaller ‘ n ’ so that the code actually finishes performance in linear time. The text over which you would apply SHA256 is made up of the Block number, passage details, former hash value, and since all the 3 previous values are constant for a block and can not be changed, a new respect called ‘ Nonce ’ is introduced. Our goal is to find the Nonce value so that the hashish of the forget produces the ask number of zero in the begin according to the protocol .
We will begin coding by taking a dummy transaction along with the latest block number and the former hash measure. We will begin with 4 zeros in the begin and work our way up and you will realize why bitcoin mining is a street fighter occupation. 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 necessitate 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 signal :
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, therefore it will be 5, the output will be .
Bitcoin mined with nonce value : 2387325 Hash value : 00000f5254db00fa0dde976d53bb39c11f9350292949493943a90610d62c1a5e The mining process took 4.895745515823364 seconds
therefore you can see the drastic transfer 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 chief cause why mining one bitcoin takes therefore much energy and computational power. If that was not adequate, you have to be the first one to find the hashish or you will not be rewarded. So you are besides competing with all the early miners out there and this whole organization works on the ‘ PoW ’ or ‘ Proof of Work concept ’ .
We will discuss more how to connect the mine 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 fink 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 barren 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.