13.8 C
Tuesday, October 4, 2022

Python Bitcoin Tutorial

We will be writing a bitcoin mining code in python in less than 15 lines 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 a 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 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 10 dollars. So then it will be like a vegetable owner paying to the pharmacy 10 dollars. So it’s just a set of transactions. This is more like your bank account in a bank account. Let’S say you have a two thousand dollar deposit for your salary and then 500. Let’S say you spent on the mortgage.

So 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 so here I have shown you a sample ledger and this ledger might have millions of transactions.

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 the linked lists in your data structures in the linked lists, 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 blocks 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 transactions, 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. So what is cryptography? And what is a 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 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 the hash function, this is just a hash function. It will generate a hash that is 256 bits 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 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 a couple of sample strings. So let’s say if you have a b c the shaft, for that will be this.

It will be the 64-bit hexadecimal number, but I’m not showing the complete number. That way, thats 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 totally random, but every time you call 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 lines of python code to produce any string and 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 a transaction, but it also has a couple of more components, so it has a 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 functions and that will produce a hash now. The protocol requires that the first few digits of this hash should be zero.

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. 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 the nonce. None is like, like number ones and add this number to a string 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 checks.

It is its first, four-digit zero. No then change it to three-four, so you have to do a lot of guesswork. 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 a trillion or trillions of trillion numbers 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 the first thirty, zero, sixty zeros depends on time to time and all these miners 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 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.5. 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 guesswork. It seems easy, but we’ll see it in the code. It’S very it’s very time-consuming. It’S not difficult. Algorithm wise.

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, whoever 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 the 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. So you see this block 2. Has this previous hash Do you see 0 0, 3 a and as more and more transaction gets added? This blockchain becomes longer and 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 the hash lib module so that I can use 256 functions 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 stars 256 functions 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 transaction.

So you know the mining function will take transactions and a 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 is 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 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 a couple of things it has a block number it has transactions, it has a 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 is actually 20. So we’ll pass this as a parameter. Okay, so let’s say the block number I want is five just making something up. The transaction is a transaction and let’s say the previous hash was and I’m doing copy paste just to save some time. Let’S say the previous hash was this: okay and my difficulty.

The difficulty is nothing but the 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 the 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 an integer, so I need to convert it into a string.

The transaction is a string. Previous has a string and 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 a nonce to be one.

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 nonces 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 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 the 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 do something else right, it will say false. So I want to check if uh this string starts with the 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 the 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 a number of prefix zeros, so prefix zeros and zero into prefix, zeros, okay, and when your new hash is computed. You check if the new hash starts with my prefix zeros, not prefix, zeros prefix string then return the 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 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 a 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 top of that, my electricity and my hardware cost are going up, so I’m raising an exception.

Okay, So now we are ready to run this. Let’S run our mining code to see this mining happened very fast, so it was able to run the for loop 2425 times and found the hash, which has the first four-digit as zero. The moment you increase the hash size, the difficulty size, it will take a long time it’s gonna take a 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 the time module in python when you say time. The 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 guesswork. It is like playing online games. If you win, you get a 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 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 these kinds of special devices.

These are, like you know, pistol ASIC machines that people have which bitcoin miners keep. They have like data centres where they keep not one such machine, but hundreds of such machines, 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 some of the actual bitcoin blocks. 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 blocks. Now look at this hash, so this is the difficulty level I was talking about. This is 20 zeros.

So right now, the 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 Nakamoto, who invented bitcoin. At that time, the number of zeroes was only eight. So it was not very difficult, and at that time you will get 50 bitcoin as a reward.

Now bitcoin value in the 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 many resources for doing the 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 lines 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 a long time by the way you might get lucky and you might find the answer easily because it also depends on your transactions and a 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.

Read More: BITCOIN on ETHEREUM!? How? Why!?

Previous article12% Bitcoin Leap
Next articleWill Amazon Accept Crypto?

Related Articles

Stay Connected

- Advertisement -

Latest Articles