Simple Bitcoin Miner in Python

NeuralNine · Beginner ·💻 AI-Assisted Coding ·5y ago

Key Takeaways

The video demonstrates how to implement a simple Bitcoin miner in Python using the SHA-256 hashing algorithm, and explains the basic concept of Bitcoin mining and its underlying algorithm. It utilizes the hash library and Python's hashlib to compute hashes and find a hash with a certain number of leading zeros.

Full Transcript

[Music] what is going on guys welcome back in today's video we're going to build a bitcoin miner in python so let us get right into it all right so first of all before we get into coding i want to mention that in this video we're not going to build a professional complete perfect bitcoin mining software so if you're interested in bitcoin mining for a profit first of all this video is not financial advice in any way but besides that i would just not recommend using a simple python script that you made on your own i would recommend using professional hardware professional software and even if you build your own software i would recommend doing it in c c plus plus in a low level language that allows you to max out the performance because python is kind of slow so having said all that we're going to build a bitcoin mining script in python so we're going to learn about the process we're going to see how it's done we're going to do it we're going to implement the function but again i would just not recommend using this um in in actual profit oriented bitcoin mining so the first thing we do is we import the hash lift module the hash library and this is just a library that's going to allow us to to take the hash or to compute the hash of an input and the basic idea of bitcoin mining is that you have some information in a block so for example the block number the transactions you have um the the previous hash and so on and what you want to do is you want to take that input and turn it into a hash or what you do in blockchain is you turn it into a hash however for bitcoin you want that hash to have a certain amount of leading zeros let's say 4 let's say 8 16 whatever this depends on the difficulty but you're trying to get a hash that has let's say four leading zeros this is just an example here so let's say you have a hash like this or something like that and in this hash you have all the information i mean in the hash itself you don't have the information but this hash was computed with the information with a certain block number with certain transactions with a certain previous hash and so on and what we want to do now is we want to actually have the same information and slightly change the input by adding a so-called nonce this is just a number that you add to the information in the hope that the result is going to have a certain format for example zero zero zero zero and then some other stuff like that for example so if you find a nonce just a number that you add in the end and this number with the information produces a hash like that you have mind uh one unit of that cryptocurrency now of course in bitcoin you don't have full leading zeros i think at the moment you have like 16 or eight or more than 16 i don't know uh but the point is you you gotta find some non some number that you add um that produces those leading zeros if you can't find that number you haven't mined a bitcoin once you find that number as the first person you have mined that bitcoin um and there is no shortcut because the hash function is kind of unpredictable it's quite random so a slight change in the input is going to result in a radical change in the output so it's very hard to actually um to actually find the results so or so basically what you can do is you can just guess and we're going to build a script that is going to guess and mine and it's uh it's a very lucky process actually you just need to it's it's like uh rolling dice you need to find the right number and then you have the hash and the one who finds the number first is going to make the most money so let's start by defining the function here let's say we have def mine and in mind we're going to have the block number and we're going to have transactions and we're going to have previous hash for example i'm going to leave this empty for now let me just show you what an actual hash result looks like so we're going to say print hash lip dot sha 256 which is the hashing algorithm that bitcoin uses uh let's just hash the string hello world here we need to encode it first and then we need to hex digest the output and then we can run this so we're going to navigate to the directory and we're going to say python3 main.py and as you can see this is the hash of the hello world string the sha 256 hash and if we go ahead and change a slight letter here so if i change the l to a t for example let's just go ahead and do that uh now we have hello word with t and d uh the hash is going to be completely different so i can rerun this and you can see that the hash is completely different a slight change in the input produces a radical change in the output and this is what we're going to try to do we're going to change the input in a slight way we're not going to change anything in the transactions or the block number we're just going to add a nonce number and we're going to try to produce a hash with 4 8 16 leading zeros something like that um and we're going to do this in the mind function here so let's get into it we're going to first say or before we go into the mind function let's first define two values up here first we're going to define a nonce limit this is the maximum number that we're going to check i'm just going to choose a high number here uh and then we're going to also define how many zeros we're looking for so zeros equals four in the beginning here because four is going to be easy to find um and what we're going to do in the mind function here is we're going to see four nons in range for nons in range non's limit so up until this limit we're going to try all the numbers and what we're going to do is we're going to build a base text so we're going to say string of the block number plus the transaction hash plus the previous hash in string format obviously plus the string of this nonce and this is going to be the new factor the random factor or not the random factor but the changing input factor this is going to be the base text and then we're going to try to find a hash that has four leading zeros in this case so we're going to say try so hash underscore try equals hashlip.sha256 base text and code and hex digest like that this is going to be the hash that is the result of the data that we already have plus this additional nots and we're now going to say what do we have here unused variable okay we're going to say if this hash tri which is a string starts with the character 0 but how many times in this case four times because we're using this variable here if we have this four times then we're going to say print f string found hash with nonce and we're going to say nones here and we're going to return the hash as a proof if we go through all the numbers without finding such a hash we will just return negative one you can also print an error message or raise an exception whatever so this is the basic idea here now before we apply this on actual bitcoin data we're just going to um to do this on our own fictional data here so we're just going to imagine some values let's say block number equals 24 we're going to say transactions equals and then we get some transaction hashes like oh like that for example just some imaginary stuff and then we're going to say our previous hash is going to be something similar like that for example i don't know um this is just transactions previous hash and so on block number and we can go ahead and try to come up with a combined uh combined text here and we're just going to say string of block number plus transactions plus previous hash and we will just print the hash lib dot shot 256 not shot 3 2 56 just oh actually like that shot 256 um off this combined text here and code it obviously hex digest obviously and this is going to be the basic hash without any nonsense so we're going to try to to see what this is we're going to go into the bash here execute it again this is the hash that we currently have now of course you can see as a proof here if i change this to 2 so i changed a 1 to a 2 the result is going to be completely different here so let's just leave it at 2 here what we're trying to do is we're trying to now add nonsense here at the end so that we end up with leading 0. so if i add 78 for example of course as a string like that if i add 78 here i'm going to again get a different hash without leading zeros in this case but what we're going to do in this function is we're going to try all this so we're going to now delete this here and we're going to call the mind function on the block number on the transactions and on the previous hash and we're going to see if we can find any uh nons for four leading zeros which shouldn't be too hard so we're actually going to uh oh what happened here there you go and it found the hash with nons 107 607 we can actually see if that's true so we're going to undo all this here and we're going to what was the number uh one 107617 one oh seven six one seven so this should be uh what is needed to produce a hash with four leading zeroes and as you can see it is and it was quite fast even though we had to go through so many numbers the hash is found quite quickly now of course i can also try to to find six or eight zeroes but it's get it gets harder and harder it's very unlikely to find them so it's not that easy with four numbers it's quite easy or full zeros it's quite easy but if i go to six probably it's going to take a little bit longer already uh we need to call the mind function again so let's just call mine block number again transactions again and previous hash again and it's still working working working i'm not even sure if it's going to find anything in in a quick time here um but you can see it takes quite some while already quite some time already maybe it's going to be done in a second maybe it's going to take two minutes sometimes if you're looking for 16 zeros you're going to maybe wait a year or something depending on your computational power it's very unlikely you can actually go ahead while this is or actually let's stop this year um you can actually calculate uh the likelihood of finding such a number since you have hexadecimal numbers here for one position you can have 16 different characters you can have zeros one two three and so on then a b c d e f and in order to get uh 16 zeros in a row or eight zeros in a row what you need to do is you need to do to take the probability 1 over 16 which is the probability of getting getting a zero in a particular place to the power of how many zeros you're waiting for and this is the likelihood of getting it first try and then you can of course um say one minus that and multiply it with itself to see uh how likely it is to not have this after the millionth try or something like that uh but it's but it's not an easy thing to find those bitcoin hashes so if you're actually interested in doing this on actual bitcoin uh you can go to the website blockchain.com btc now this is the first bitcoin block ever mind so this is not something that you should uh be working on but here you can see that we're working with one two three four five six seven eight leading zeros this was pretty easy then um and the reward was 50 bitcoin now nowadays it's not 50 bitcoin anymore nowadays you're getting i think 6.25 bitcoin and you're going to have to find 16 if not more leading zeros you just go to blockchain.com and i think uh actually to blockchain.com oh my god now it's going to lag again sorry okay i had some lags what i was trying to say is that if you go on blockchain.com and then you go to explorer you can see the latest mind blocks and you can get the information from there i'm not going to click on it right now because my pc is not the best one uh but basically you can get all the information on hashes and on transaction hashes and block numbers which is the height actually uh from there and then you can use this information to mine the next blog again as i said if you're going to do actual professional bitcoin mining not just for educational purposes i would recommend getting some actual professional hardware and software because that is not the most efficient way to mine bitcoins obviously alright so that's it for today's video hope you enjoyed and hope you'll learn something if so let me know by hitting the like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free other than that thank you very much for watching see you next video and bye [Music] you

Original Description

Today we learn how Bitcoin mining is done and we implement the basic algorithm in Python. DISCLAIMER: This is not investing advice. I am not a professional who is qualified in giving any financial advice. This is a video purely about programming using financial data. I do not recommend this script for actual profit-oriented Bitcoin mining. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 💻 Exclusive Content 💻 👥 Patreon: https://www.patreon.com/neuralnine 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to implement a simple Bitcoin miner in Python using the SHA-256 hashing algorithm, and explains the basic concept of Bitcoin mining and its underlying algorithm. The viewer will learn how to use the hash library and hashlib to compute hashes and find a hash with a certain number of leading zeros. The video also provides information on blockchain.com and its explorer.

Key Takeaways
  1. Import the hash library and define a function to mine a bitcoin
  2. Compute the SHA-256 hash of an input and add a nonce to produce a hash with leading zeros
  3. Define a function to mine a block and iterate over nonce values to find a hash with leading zeros
  4. Use a brute-force approach to find a hash with leading zeros and calculate the likelihood of finding a hash with leading zeros
  5. Compare the time it takes to find a hash with leading zeros across different numbers of zeros
💡 The SHA-256 hashing algorithm is used to find a hash with a certain number of leading zeros, which is the basic concept of Bitcoin mining. The algorithm is unpredictable and random, making it hard to find the right hash.

Related Reads

Up next
Vibe Coding with Claude Changed How I Build Things!
PlivoAI
Watch →