Bitcoin mining with 15 lines of python code | Python Bitcoin Tutorial

💡Tryout HIVEOS Entirely Free:

we will be writing a bitcoin mining code in python in less than 15 line of code i will cover some theory behind blockchain first and then we'll write the code the timestamp for coding is given below so if you know the theory behind blockchain if you know how it works, you can straight away jump into coding. bitcoin is nothing but a ledger
what is a ledger? i have given you an example of a ledger. here it is set of transactions. let's say you go to a grocery store
you buy vegetables for 15 dollars so the ledger entry will be you are paying the vegetable owner 15 dollars and then vegetable guy.. let's say go to a doctor and he pays money for let's say some medicine.
let's say he pays 10 dollar so then it will be like vegetable owner paying to pharmacy 10 dollars.
so it's just a set of transaction this is more like your bank account in bank account
let's say you have two thousand dollar deposit for your salary, and then 500 let's say you spent on mortgage.
so what is left with you? well 1500 dollars.
so ledger is set of transaction at the end you have your account balance so that's all that bitcoin is.
so here i have shown you a sample ledger.

And this ledger might have millions of transaction. so in 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 linked list in your data structures in linked list you have one node and then you have an address to the second node so it is similar to that
you have 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 transaction then you move to next block for further transaction and these blocks are linked together now bitcoin protocol has some security mechanism to avoid fraud for which we need to go little into cryptography so what is cryptography?
and what is cryptographic hash function so let's look at that.
let's say you have a function like this if i ask you to make a guess on x will you be able to?
Well it's an easy one x is 4.
so this is a function in which you can guess input based on output very easily there are certain functions where guessing input based on output is little difficult.
for example here which two numbers will add up to 9?
well, it could be four and five three and six or maybe nine and zero.
i have a typo here zero and nine so b should be nine so this is a little difficult to guess not very difficult but little difficult in cryptography there is a function called sha256 where you give an input string and it will generate a hash you know if you know about hash function this is just a hash function it will generate a hash which is 256 bit long in 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 trial and error you try different strings and try to see you know which one produces the desired output so i'm going to show you couple of sha sample string so let's say if you have a b c the shaft for that will be this it will be 64 bit hexadecimal number but i'm not showing the complete number that way that's why i have a dot or dot when you change any character let's say you change c to d the whole hash will change
so you cannot make any guess it's like totally random but every time you call sha 256 on abd it will produce the same output
so that way it is deterministic but guessing it the other way is very very difficult here is simple python code you write only three line of python code to produce sha of any string and sha 256 is a cryptographic hash function for the reason we already discussed so in bitcoin or in a blockchain the actual block is not only transaction it has couple of more component so it has block number
it has the previous hash and then the bitcoin protocol is such that you you convert this whole block into a string
so let's say you take block number transaction previous hash you make it a string and you supply that string to sha 256 function and that will produce a hash now the protocol requires that first few digits of this hash should be zero how many digits?
well it changes 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 we are saying that first four digits of the hash should be zero so that is our difficulty level so you need to add…

now see if you just convert this to a string and create a hash
the hash might not have first four zeros so you have to introduce a new element called nonce.
noncde is like like number ones and add this number to a string and and see if this can produce a hash which has first four digit as zero because here our difficulty level is zero.
now let's say this doesn't produce that hash so then you have to make a guess work you have to change nonce to two check it is it first four digit zero. no. then change it to three four so you have to do a lot of guess work.
you are running almost like a four loop and guessing it
so try it like for loop which starts from one to let's say it goes all the way to trillion or trillions of trillion number and your end goal is to produce a hash where first four digit is zero it is simple right?
let's say I come to this number in my for loop and my hash comes becomes first four digit is zero then you can say that this block is verified or this block is confirmed and the process of guessing nonce is bitcoin mining so here we said its first four zeros in reality it will be like first thirty zero sixty zeros depends time to time and all these miners they are not doing any rocket science they are not doing any algorithmic work guys you can also do bitcoin mining will write the code right now after this theory session it's a very simple for loop where you are trying different nonce and trying to figure out a hash where first x number of digits are zero so for doing bitcoin mining these miners get a reward in 2009 if you mine one block you will get 50 bitcoins every four years the reward gets half so right now in 2020 the reward is 6.25.

Okay? in 2024 it will be half of this and bitcoin's value today is 28,000 so you would think oh 28 into 6000. this is so much money. anyone can do it and you're right there are thousands of people who are doing bitcoin mining but the thing is this guess work it seems easy but we'll see in the code it's very it's very time consuming it's not difficult algorithm wise the code is simple but it takes lot of computation power, electricity to get to the right guess
and if 10 people are doing guess whoever makes the correct guess first that person will win the reward let's say i make a guess after 10 minute other person is making 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 previous hash so you see this block 2 has this previous hash. you see? 0 0 3 a and as more and more transaction gets added this block chain becomes more and more longer
it's like a chain so more involved blocks get added and people who are miners who are making this nonce so again just to repeat all you are doing is making a guess on this nonce so let's get into coding now i have opened my pycharm community edition and have created this file where i have imported hash lib module so that i can use sha 256 function now i'll go into my zen meditation mode so that there are no distractions so first let's try this sar 256 function and see you know what it gives
so i'm just giving a random string here and i'm saying all right run this code well it's saying unicode objects must be encoded so what you need to do is you need to say encode this thing into ascii and okay actually you need to encode the actual string you know into ascii and that will give you sha 256 object now if you want to get the actual hash out of it then what you need to do is you need to say dot hex digest, okay?
so that will give you the actual 256 bit so if you count these digits it is 64.

But this is hexadecimal and each hexadecimal digit is 4 bit so this is actually 256 bit or 64 bit in terms of hexadecimal.
so now I have this function so i'll create a nice utility function so that you know i can make use of that so sha 256 text and then i will just return this so instead of abc supply the input text okay and if underscore name is equal to underscore main so this is my main python entry point and i will try to call 256 star 256 function and looks like this is working fine now what we need to do here is in order to do mining first we need to have transactions so let's create some dummy transactions so let's say my transactions are..
let's say devel is giving bhavin with my brother let's say 20 bitcoin and mandalorian is giving kara his friend 45 bitcoin okay and i need to now write a function called mine which will take this transactions so you know the mining function will take transaction and couple of more parameters and generate a new hash and this is the hash that we want so i will print that new hash here okay all right now other than transactions what are the input parameters of mining functions well let's go back to our function and see in our uh sorry let's go back to what representation that's what i mean so in in our presentation we saw that the hash is nothing but uh sha 256 called on this whole string so what is this whole string it has couple of things it has block number it has transactions it has previous hash and nonce is something which you are just guessing okay so these are the parameters that our function need so i will pass all these parameters
i also have prefix zeros so in our presentation.
the prefix zeros were four in real life right now with bitcoin the number of zeros are actually 20.

So we'll pass this as a parameter
okay so let's say block number i want is five.
just making something up. transaction is transaction and let's say the previous hash was and i'm doing copy paste just to save some time let's say previous hash was this okay and my difficulty.. difficulty is nothing but number of zeros that you want in front of your hash let's say it is four so then i supply my difficulty okay using all of this we need to produce the sha 256 which has first four digit as zero so let me hard code my nonce to be one and then i will reduce my text so my text is what block number and block number is integer so i need to convert it into a string transaction is a string.
previous has a string.
and nonce nonce is a number so convert it into a string i get the whole string of the entire block on which i call sar 256. and that is my new hash which i return from this function okay so let's first try it with nonce to be one.

pexels photo 4874359

so when i run it see i get this hash but my first four digits are not zero so then i try nonce two they're still not zero i type three now do you think i will keep on trying different nonce? well no if you are not a dumb programmer you will obviously write a for loop so you will say four nonce in range what is my range?
okay let's talk about that. let's say some max number okay what is this max number well depends on your computation power i mean you can have literally like infinite loop up to you but i will restrict it to some some big number and for that run a for loop where you are trying different nonce and trying to produce new hash.
now new hash should have first four digits as zero how do you check that well see here i'm passing prefix zero as four okay so in so i'm going to open idle i mean
i generally when i'm coding i open idle to try different things so let's say i have some string let's say some hash okay this python has a function called starts with so if you do two three four starts with it will say zero but if you do something else let's something else right it will say false so i want to check if uh this string starts with first 4 0 it doesn't start so it says false now how do i start how do i check four zero so i have seen this function i am supplying a number so from number four i want to get string four so that is easy way you will say 0 multiplied by 4 and that will give you the prefix you see it's a simple python string operation so you will say my prefix string is number of prefix zeros so prefix zeros and zero into prefix zeros okay and when your new hash is computed you check if new hash starts with my prefix zeros not prefix zeros prefix string then return new hash now of course when you get to this point you have won a big reward so you want to print that you know that yeah i mind the block okay
i mind the block and earn 6.5 bitcoin after i trading this for loop for so many times okay this is my nonce and after i trading this for a long time even if you don't get anything then you can raise an exception normally as i said you will run an infinite loop until you get an answer or you run a for loop until you exhaust your computation budget so then you will raise an exception saying okay this is too much work it's not profitable you know i'm earning bitcoin but on on top of that my electricity and my hardware cost is going up so i'm raising an exception, okay? so now we are ready to run this let's run our mining code so see this mining happened very fast so it was able to run the for loop 2425 times and found the hash which has first four digit as zero the moment you increase the hash size the difficulty size it will take long time it's gonna take long long time so i'm going to add a code to measure the time it takes to mine a given block okay so see it took some time but i don't know how much time so let's add some timer code again i'm gonna do some copy paste work to save over time so you can import time module in python when you say time…

time it gives your current time okay?
and then you do your mining and after you're done with your mining you find out the total time by doing this so here i am taking timestamp at this given instance subtracting it from start time that gives me the total time it took for mining in seconds and i will print that so let's run it so it is mining now and it is taking some time we'll know how much time it is it took 12 seconds to find the answer but you kind of get an idea that bitcoin mining is nothing but a guesswork
it is like playing online game if you win you get certain reward now you might be thinking well it is still not bad you know i have my computer i wrote this code can i win like bitcoins using this well you can but the thing is this right now the difficulty level of bitcoin uh this prefix zeros is 20.

So if i change this to 20 and run the code it might take you in one year to mine this bitcoin you understand?
it's very difficult so um bitcoin mining requires special hardware so let me just do google and show you some of the things so if you do google bitcoin mining hardware you will find this kind of special devices these are like you know pistol asic machines which people have which bitcoin miners keep they have like data centers where they keep not one such machine but hundreds of such machine and they try to make this guess faster it's like who can guess this faster and who is lucky..
so let's say i guess it and after five minutes if you guess it you don't get a chance you lose.
whoever comes first in the guessing game wins that bitcoin.
so now let me show you the some of the actual bitcoin block so when you do google bitcoin explorer you will find this website where you can see the real bitcoin blocks these are all the blocks so now let me click on this block.

the height means which block so it's like block one two three four bitcoin has been trading for so many years so right now it is 664,000 block now look at this hash so this is the difficulty level i was talking this is 20 zeros so right now bitcoin difficulty level is 20 zeros if you google bitcoin block one or bitcoin genesis block you will find the first block ever that was created this was created by satoshi satoshi nakamoto who invented bitcoin at that time the number of zeroes were only eight so it was not very difficult and at that time you will get 50 bitcoin as a reward now bitcoin value in dollar was very less at that time right now the reward you get is 6.25 bitcoin but bitcoin's value is close to 28 thousand dollars as of second january 2020 so you see why people have so much hardware so much resources of for doing mining
so that's all the code i had if you write if you look at these lines this much i'm excluding this caller code but if you look at these many lines it's less than 15 line of code that you need to mine the bitcoin so it is very simple actually the real difficulty is who can make the guess first and as i said try the difficulty level 20 or 30 okay and you will see it will take long long time by the way the you might get lucky and you might find the answer easily because it also depends on your transactions and number of other factors but in general the bitcoin mining is a difficult thing not in terms of the actual code we just saw the code it was very easy but in terms of running the actual computation i hope you like this video if you do share it with your friends also write this code and post in LinkedIn that you mind a bitcoin because you you really did and um if you have any other questions please post in a video comment below as i said i'm working on a very simple explanation based on analogy where i will explain how bitcoin blockchain cryptocurrency works in a simple language as of this recording that video is not available but in future after maybe two three weeks it will be available and whenever it is available i will post the video link in the video description below so make sure you check the video description just in case that video is available that's gonna give you a lot of understanding of how bitcoin works in a very simple stupid easy language all right thank you for watching.

bye..

As found on YouTube

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *