How the PoW problem works in Bitcoin

The PoW algorithm starts by taking the longest chain. In Bitcoin, there are multiple ways blocks can be finalized (depending on the included transactions). Thus, there may be multiple available "solved" chains that could be selected as a base by the Bitcoin nodes. As part of the algorithm, Bitcoin takes the chain that is the longest and thus has had the most computing power applied to it. The following diagram illustrates a PoW chain:

The difficult puzzle in Bitcoin is to find an input that, when added to the prior block hash and the list of transactions, produces a hash that starts with a certain number of zeros.

Typically, the input to the function is the Merkle root of all transactions and the prior block hash. To simplify this for illustrative purposes, imagine that we have a simple input, such as I love Blockchains. Let's also assume that the system has the easiest possible difficulty: a single zero at the start of the hash. The SHA-256 hash of I love Blockchains is as follows:

ef34c91b820b3faf29104f9d8179bfe2c236d1e8252cb3ea6d8cb7c897bb7d96.

As you can see, it does not begin with 0. To solve the block for this input, we need to find a string (called a nonce) that we can add to this string so that hashing the combination (nonce + I love Blockchains) results in a string starting with 0. As it turns out, we can only do this through testing. For instance, if we add 1 to the beginning, we get 1I love Blockchains, and the hash is as follows:

b2fc53e03ea88d69ebd763e4fccad88bdb1d7f2fd35588a35ec6498155c702ed

No luck. What about 2 and 3? These will also fail to solve the puzzle. As it happens, 4I love Blockchains has a hash that starts with 0:

0fd29b2154f84e157d9f816fa8a774121bca253779acb07b07cfbf501825415d

It only took four tries, but this is a very low difficulty. Each additional zero doubles the challenge of finding a proper input that will compute a proper hash. As of writing, a valid Bitcoin block requires 18 zeros to be valid.

This process of trying to find the nonce that results in a proper hash is called mining. Every computer mining a PoW chain is competing to see who can find a proper nonce first. The winner gets to create the next block in the chain and is rewarded in tokens. For more details, see Chapter 17, Mining.

The advantage of PoW is that anyone can join a PoW network, and it is well established as a functional consensus mechanism. The primary downsides of PoW networks are slow speeds and financial costs: running all the computers to do these computations is very expensive, and the output is not put to any real productive use. This is considered bad for the environment and can result in increased energy prices wherever large amounts of blockchain mining are done. In some areas, blockchain mining has been banned for this reason.

As a result of these downsides, proof-of-stake (PoS) was invented.