Mining - How does mining work in Bitcoin?
  • Hash256
  • Hash160
  • Reverse Bytes
  • Hexadecimal
  • Satoshis
Youtube

Mining Adding new blocks to the blockchain.

Mining is the process of trying to add a new block of transactions on to the blockchain. It is basically a network-wide competition where any node on the network can work to try and add the next block on to the chain.

Each newly-mined block is broadcast across the network, where each node independently verifies it before adding it on to their blockchain.

Nodes update their blockchains with the new block.

After adding the new block, each mining node restarts the process to try to build on top of this new block in the chain. As a result, the blockchain is constantly being built thanks to a collaborative effort of nodes across the network.

The system designed so that a new block is mined once every 10 minutes on average.

1. How does mining work?

The mining process begins by filling a candidate block with transactions from your node’s memory pool.

This candidate block is what we’re going to try and mine on to our blockchain (and then send to everyone else so they can add it to their blockchain too).

Next we construct a block header for this candidate block. This is basically a short summary of all of the data inside the block, which includes a reference to an existing block in the blockchain that we want to build on top of.

You refer to a previous block by its block hash, and a summary of all the transactions in the block is contained in the merkle root.

Now we are ready to start “mining” this block. To do this we put this block’s block header through the SHA256 hash function, and hope that the number it spits out is below the current target.

Try it! - SHA256

A hash function is basically a mini computer program that takes in any amount of data, scrambles it, and produces an unpredictable result. Different blobs of data produce different results.

Note: The result of the hash function is shown in hexadecimal, but it can easily be converted to a decimal number.

Note: In mining the data gets put through the hash function twice, so this doesn’t give the same results (but it’s good for illustrative purposes).

The target is the number your block hash must get below to add the block on to the blockchain.

If the hash of your block header isn’t below the target, you can keep trying by incrementing the nonce field in the block header, which allows you to keep the same basic block header but to get a completely different hash result for it. If you’re lucky, you may end up getting a hash that’s below the current target.

The mining process is basically hashing a block header as fast as you can to try and be the first node to get a low-enough result.

If you manage to get a block hash below the target, you can broadcast your block to the network. Upon receiving the new block each node will confirm that the block header hashes to below the target, then add this “mined” block on to their blockchain.

Congratulations, you have just mined a block of transactions on to the blockchain.

From here, each node will stop working on their own candidate block, construct a new one (with fresh transactions from their memory pool), and start trying to build on top of this new block in the chain.

Miners start trying to add the next batch of transactions on to the chain.

As a result, miners are constantly working independently (yet collaboratively) to extend the blockchain with new blocks of transactions.

The process of mining is often referred to as a proof-of-work.

The term “proof-of-work” just refers to the fact that it takes work to get a block hash below a target value, and once you do anyone else can check that hashes below the target too.

In other words, the hash function is being used as a way to prove that you have performed a required amount of “work” on your block.

The proof-of-work involves scanning for a value that when hashed, such as with SHA-256, the hash begins with a number of zero bits. – Satoshi Nakamoto

2. Who can mine blocks?

Any node can try to mine a block, and each node has a chance of being successful. Therefore, we have a network-wide competition where any node on the network could be the one to add the next batch of transactions on to the blockchain.

However, although anyone can try mining, being able to perform hash calculations as fast as possible does improve your chances of successfully mining new blocks.

Anyone’s chance of finding a solution at any time is proportional to their CPU power. – Satoshi Nakamoto

As a result, miners with the most processing power (or “hashing power”) are likely to mine more blocks than those who cannot hash as quickly. So even though anyone can mine, it tends to be concentrated amongst those with specialized mining hardware, and those with access to cheap electricity to power that hardware.

3. Why mine blocks?

Because if you are able to mine a block, you can claim a block reward.

You see, when you construct a candidate block, you can put your own special transaction at the top of the block. This is called the coinbase transaction, and it allows you to send yourself a fixed amount of bitcoins that did not previously exist.

The coinbase transaction effectively allows you to create new bitcoins and send them to yourself.

So if you end up mining this block, you would be able to spend the bitcoins you claimed from the coinbase transaction once the block becomes 100 blocks deep in the longest chain.

Therefore, this block reward acts as an incentive for miners to mine new blocks and continually try to extend the longest known chain of blocks.

Tip: Sending bitcoins that do not already exist is only allowed in the coinbase transaction, which makes them the source of all new bitcoins.

Tip: The fact that mining introduces new bitcoins in to the network is why the process is called “mining”, even though from a practical point of view it’s more about adding new transactions to the blockchain.

4. How long does it take to mine a block?

The system is designed so that one miner across the bitcoin network will successfully mine a new block once every 10 minutes on average.

This timing is controlled by the target, which is like a limbo pole that a block’s hash has to get under for it to be allowed on to the blockchain.

Each node knows the current target for the current height of the blockchain.

If blocks end up being mined faster than 10 minutes on average over a two-week period (e.g. because more miners join the network), the target will adjust downwards so that it becomes more difficult to mine a block, and so the average time between blocks reverts back to around 10 minutes.

Each node adjusts the target independently, but will each calculate the same target if they each have the same chain of blocks.

As a result, the target regularly adjusts to try and keep a regular interval of 10 minutes between new blocks being mined, which allows for a predictably consistent rate of new blocks and a consistent issuance of new bitcoins in to the network.

5. Why do we use mining?

Because this system allows computers across a network to resolve conflicts, without the need for a central computer or authority to sort them out.

You see, Bitcoin runs across a network of independent computers, so it’s possible to create two conflicting transactions (sending the same bitcoins to different places) and insert them in to different nodes on the network at the same time. Some nodes will receive transaction A first, and other nodes will receive transaction B first.

How can all the computers agree on which transaction should make it in to the blockchain?

Thanks to the mechanism of mining, only one of these transactions will make it in to the blockchain.

Eventually, one of the nodes on the network will mine a block of transactions from their memory pool, and broadcast this block to the rest of the network. When nodes receive this block, they will add it to their chain, and remove any conflicting transactions from their memory pool.

As a result, the process of mining acts as a sorting mechanism for transactions across a network of computers, where mined blocks have the final say on what belongs in the blockchain. Even better, thanks to the fact that anyone can mine, no single node on the network is ever in complete control of which transactions make it on to the blockchain.

Unless of course a single miner acquires a majority of the mining power

6. How do you mine a block?

You start by constructing a block header for your block. For example, here’s what the block header for block 100,000 would have started out like:

0100000050120119172a610421a6c3011dd330d9df07b63616c2cc1f1cd00200000000006657a9252aacd5c0b2940996ecff952228c3067cc38d4885efb5a4ac4247e9f337221b4d4c86041b00000000

Now you’ve got the block header, you try and “mine” it by putting it through the SHA256 hash function (twice). You keep incrementing the nonce value as you go to try and get a result below the target.

For example:

Nonce     Hash256
--------  -------
00000000: 5bd0d617b30a972407ad69a845cd74fb201d940cd45acc15fcd4761493bc3ae2
01000000: 6879c316d8a96269825111bb0616331307bb6677b2af55127922d8c568e4b2db
02000000: 34d69cb489442234ec54462e18262bf1a9c756a4e7909e68edf979a0cb39a3fa
03000000: 8cf5e032093cfcbf4f6b443608631dd33699fca13dcbd6118992f9d451b70dd8
04000000: a32d73e3f2fd0579c44080cb6b1717582d37b8f47a8445922dee0996b503c04c
05000000: 70b11dabc90a107918a55eff7e940d41b0ce1924aeed2f0b7ccb2d4ee60e1617
06000000: b38afc30567703629226557a7748bea449693156e0b116b03a8442ccc3b9005e
07000000: 2a6008f39daa1238388eadcab111c6b556c3d89a46558c98f8ed32746fb5d7b8
08000000: 248e33c82a744786e7e16336612221850e32f8e6cb09b2eb0b0730ac6beb71b4
09000000: a4aea05d2750e49e8f95f5608293f6b4f45bd34aee51e86893dd8c0230d19185
0a000000: ce2225a69a5bf2dbb25cbb27fda78a8c4c3ac5280ec7996426eeefeb0e5e1ecb
...

Eventually you may find a nonce value that produces a hash result below the target:

Nonce    Hash256
-------- -------
0f2b5710: 000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506

Tip: In the block header the nonce is a 4-byte field, where the number is in hexadecimal and in little-endian byte-order.

Example Code

Here’s some simple Ruby code that shows how you can mine a block (like the one above). It’s quite straightforward. The only tricky part is getting the block header data in the correct format before hashing it.

require 'digest/sha2'

# -----------------
# Utility Functions
# -----------------

# The hash function used in mining (convert hexadecimal to binary first, then SHA256 twice)
def hash256(data)
  binary = [data].pack("H*")
  hash1 = Digest::SHA256.digest(binary)
  hash2 = Digest::SHA256.hexdigest(hash1)
end

# Convert a number to fit inside a field that is a specific number of bytes e.g. field(1, 4) = 00000001
def field(data, size)
  hex = data.to_i.to_s(16).rjust(size * 2, '0')
end

# Reverse the order of bytes (happens often when working with raw bitcoin data)
def reversebytes(data)
  data.scan(/../).reverse.join
end

# ------------
# Block Header
# ------------

# Target (optional)
target = '000000000004864c000000000000000000000000000000000000000000000000'

# Block Header (Fields)
version    = '1'
prevblock  = '000000000002d01c1fccc21636b607dfd930d31d01c3a62104612a1719011250'
merkleroot = 'f3e94742aca4b5ef85488dc37c06c3282295ffec960994b2c0d5ac2a25a95766'
time       = '1293623863'  # Unixtime (29 Dec 2010, 11:57:43)
bits       = '1b04864c'
nonce      = 0             # 274148111

# Block Header (Serialized)
header = reversebytes(field(version, 4)) + reversebytes(prevblock) + reversebytes(merkleroot) + reversebytes(field(time, 4)) + reversebytes(bits)

# -----
# Mine!
# -----
loop do
  # hash the block header
  attempt = header + reversebytes(field(nonce, 4))
  result = reversebytes(hash256(attempt))

  # show result
  puts "#{nonce}: #{result}"

  # end if we get a block hash below the target
  if result.to_i(16) < target.to_i(16)
    break
  end
  
  # increment the nonce and try again...
  nonce += 1
end

Commands

bitcoin-cli getblocktemplate

This command grabs transactions from your node’s memory pool and returns the data you need to start mining a new block.

Note: This command returns the key block header information like the previous block, time, and bits, but you will need to select your own transactions and construct the merkle root yourself.

bitcoin-cli submitblock [hexdata]

Send your block in to the network.

bitcoin-cli getmininginfo

Shows you some interesting mining information.

If you run bitcoin-cli getblocktemplate beforehand it will also show you how many transactions from the memory pool are currently being included in the next block.

$ bitcoin-cli getmininginfo

{
    "blocks": 619213,
    "currentblockweight": 3420452,
    "currentblocktx": 2724,
    "difficulty": 15486913440292.87,
    "networkhashps": 1.20928645955617e+20,
    "pooledtx": 3570,
    "chain": "main",
    "warnings": ""
}

By Greg Walker,

Last Updated: 23 Dec 2019
  • 23 Dec 2019: guide - made inner page tools independent of site-wide tools from header
  • 22 Dec 2019: edit
  • 22 Dec 2019: guide/mining - added image to tool
  • 22 Dec 2019: guide/mining - added tool to try sha256 hash function
  • 12 Dec 2019: guide/mining - checking and edits
  • 11 Dec 2019: guide/mining - images and code
  • 25 Nov 2019: explorer - keeping track of requests to see whats stressing the database
  • 14 Nov 2019: edits
  • 12 Nov 2019: edits
  • 11 Nov 2019: guide/mining - first draft (text)
  • 24 May 2019: Added Hashover comment system (basic functionality to test it out)
  • 26 Nov 2018: Added sub titles to every page.
  • 27 Mar 2018: Added more descriptive titles to be shown in search engines.
  • 13 Mar 2018: guide/ - renamed all files from .text to .md and removed numerical prefix. Makes it cleaner and makes for easier working with search box.

Hey there, it's Greg.

I'll let you know about cool website updates, or if something seriously interesting happens in bitcoin.


Don't worry, it doesn't happen very often.