Bitcoin mining algorithm example
- Step 0 - Retrieve the hash of the previous block from the network.
- Step 1 - Gather a list of potential transactions known as a "block". This list of transactions comes from the peer-to-peer bitcoin network.
- Step 2 - Calculate a hash for a block of potential transactions along with a random number.
- Step 3 - If the hash is more than the currently set difficulty level, then you have mined that block. If not, start over from Step 1. Any additions to the list of transactions from step 1 along with change in the random number from Step 2 mean that there's a chance that the criterion will be met in the next go around.
From a programmers view, the pseudo code might look something like this:
P := The hash of the previously mined block B := A block of transactions H := A hash function D := Difficulty Level 0 Retreive P 1 Construct/Modify B 2 IF H(P, B, Some Random Number) > D END 3 GOTO 1
I should warn you that there are a few inaccuracies in that description, but for the most part, that should be good enough. And here are a few more useful clarifications:
What's a hash?
A hash is a function that converts data into a number within a certain range. The hash has the property that knowing it's output is essentially unpredictable (within the given range). The specific hash function used for bitcoin mining is SHA256 applied twice.
How does the difficulty level work?
This unpredictable nature of the hash function means that putting in random data (the transaction + the random number) will essentially produce a random number within a certain range. Further restricting the range of the desired output affects how likely one is to find it in a single round. This creates a way to probabilisticly determine how often a solution will be found based on the number of times the algorithm can be run on the network. Specifically, when you hear the term Gigahashes or Terrahashes, this refers to the number of times step 3 can be run. As the number of hashes per second across the entire network grows, the network automatically raises the difficulty such that a solution will be found within about 10 minutes.