learn deep. ship safe.Follow ByteMun
Cyber Security🔥 Trending #5

How Bitcoin Mining Works: SHA-256, Hashing and Proof of Work Explained

Bitcoin mining explained from the hash up: why SHA-256 is hashing and not encryption, what's inside the 80-byte block header, how difficulty works, and whether cloud mining contracts pay back in 2026.

Featured image for a guide to Bitcoin mining and SHA-256, showing a chain of blocks whose hashes start with zeros and the formula SHA256(SHA256(header)) < target
Hash the header twice, beat the target, add the block.

Bitcoin mining is a global guessing contest. Miners repeatedly run an 80-byte block header through SHA-256 twice, changing a number called the nonce each time, until the result falls below a target set by the network. The first miner to find one adds the next block of transactions and earns 3.125 new BTC plus fees.

That one sentence hides a lot of good engineering. In this guide I'll unpack it piece by piece, with code you can run: what a blockchain really is, why SHA-256 is a hash and not encryption, how difficulty works, why nobody mines Bitcoin on a laptop any more, and what the numbers say about cloud mining contracts in late 2026.

Every figure below that isn't cited to a source comes from code I ran myself. The scripts are included so you can check them.

Mining in one picture: hash the header twice, compare with the target, change the nonce, repeat. The network does this about 10^21 times a second.

Diagram of the six fields in an 80-byte Bitcoin block header (version, previous block hash, merkle root, time, bits and nonce) feeding a double SHA-256 loop that checks whether the hash is below the target
Mining in one picture: hash the header twice, compare with the target, change the nonce, repeat. The network does this about 10^21 times a second.

Blockchain in one paragraph

A blockchain is a ledger split into blocks, where each block stores the hash of the block before it. Change one old transaction and that block's hash changes, which breaks the link stored in the next block, which breaks the one after that, all the way to the tip. To rewrite history you'd have to redo the mining work for every block since, faster than the rest of the network is adding new ones. That's the whole security model: history is protected by the cost of the work stacked on top of it. Mining is how that work gets done, and the block reward is why anyone bothers.

SHA-256 is hashing, not encryption

People often call SHA-256 "encryption". It isn't, and the difference matters for understanding Bitcoin.

Hashing (SHA-256)Encryption (AES, RSA)Digital signatures (ECDSA, Schnorr)PurposeFingerprint dataHide dataProve who authorised somethingReversible?No, one-wayYes, with the keyVerifiable with the public keyUses a key?NoYesPrivate key signs, public key verifiesOutputAlways 256 bitsSame size as input, roughlySignatureRole in BitcoinMining, block links, transaction IDs, merkle trees, addressesNot used in the core protocolSpending coins

Bitcoin's base protocol doesn't encrypt your transactions. Everything on the chain is public. What keeps your coins safe is a signature made with your private key on the secp256k1 elliptic curve (ECDSA, plus Schnorr signatures since the 2021 Taproot upgrade). What keeps the ledger safe is SHA-256. Wallet software may encrypt your key file on disk, but that's your wallet, not Bitcoin.

The properties that make SHA-256 useful

A cryptographic hash function like SHA-256 takes any input and returns a fixed 256-bit (64 hex character) fingerprint. Four properties matter for Bitcoin mining:

  1. Deterministic. The same input always gives the same hash, so every node can check a block independently.

  2. One-way (preimage resistance). Given a hash, there's no known shortcut to find an input that produces it. You can only guess.

  3. Collision resistant. Finding two different inputs with the same hash is infeasible.

  4. Avalanche effect. A tiny change in the input produces a completely different hash.

Here's the avalanche effect on two strings that differ by one capital letter:

SHA-256("ByteMuni") = 97e4c57814939f90d11c006d6d85bbb7bc57aeae5fdafb02df6ba6643ac7bd44
SHA-256("Bytemuni") = 1bb07bea6fcd274c6b5799b0b4994726cfd2a9c796bc6f84f76f2c6318fbdecc

To measure it properly, I flipped one random bit in each of 20,000 random 64-byte messages and counted how many of the 256 output bits changed.

Histogram from 20,000 trials showing that flipping one input bit changes on average 128 of the 256 SHA-256 output bits, with a bell-shaped spread from 98 to 158 bits
One flipped input bit changed 128.0 output bits on average, exactly what you'd expect if each output bit were a coin toss.

One flipped input bit changed 128.0 output bits on average, exactly what you'd expect if each output bit were a coin toss.

The average was 127.96 bits, almost exactly half. That's the key to mining: because the output looks random, the only way to find a hash with a particular property is to try inputs until one works. There's no cleverer path. That makes mining a fair, verifiable lottery where your number of tickets is your number of hashes.

What miners actually hash

A miner doesn't hash transactions one by one. It hashes an 80-byte block header with six fields:

FieldSizeWhat it holdsVersion4 bytesRules the block followsPrevious block hash32 bytesThe link to the chainMerkle root32 bytesOne hash that commits to every transaction in the blockTime4 bytesUnix timestampBits4 bytesThe current target, in compact formNonce4 bytesThe number miners change on each attempt

The merkle root is a neat trick. Transactions are hashed in pairs, those hashes are hashed in pairs, and so on until one hash remains. Change any transaction and the root changes, so the 80-byte header seals the entire block.

You can verify all of this yourself on Bitcoin's very first block, mined on 3 January 2009:

import hashlib, struct

def sha256d(b: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()

# Bitcoin genesis block header fields (block 0, 3 Jan 2009)
version     = 1
prev_hash   = "00" * 32
merkle_root = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
timestamp   = 1231006505          # 2009-01-03 18:15:05 UTC
bits        = 0x1d00ffff          # compact difficulty target
nonce       = 2083236893

header = (
    struct.pack("<I", version)
    + bytes.fromhex(prev_hash)[::-1]       # hashes are stored little-endian
    + bytes.fromhex(merkle_root)[::-1]
    + struct.pack("<III", timestamp, bits, nonce)
)
assert len(header) == 80

block_hash = sha256d(header)[::-1].hex()   # displayed big-endian
print(block_hash)
# 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f

exponent, mantissa = bits >> 24, bits & 0xFFFFFF
target = mantissa * 2 ** (8 * (exponent - 3))
print("valid PoW:", int(block_hash, 16) < target)   # True

Two details trip up most people who try this:

  • Bitcoin uses SHA-256 twice (often written SHA-256d). That's the sha256d function.

  • Byte order is reversed. Hashes are stored little-endian inside the header but shown big-endian in block explorers. Forget the [::-1] and you'll get a hash that matches nothing.

Run it and you get the famous genesis hash with its ten leading hex zeros. The winning nonce was 2,083,236,893, so if Satoshi's miner counted up from zero, it tried about two billion headers to find it.

Bitcoin mining difficulty: how blocks stay at 10 minutes

The "leading zeros" are really a comparison: the hash, read as a 256-bit number, must be smaller than the target. A smaller target means fewer winning hashes, which means more guessing.

Every 2,016 blocks (about two weeks), every node recalculates the target. If the last 2,016 blocks came faster than 10 minutes each on average, the target shrinks; if slower, it grows. A single adjustment can't move by more than a factor of four either way. No central server decides this. Every node runs the same arithmetic on the same chain and gets the same answer.

Difficulty is just a friendlier way to express the target: how many times harder than the easiest possible block. A useful rule of thumb follows from it:

Expected hashes per block ≈ difficulty × 2³²

Bitcoin difficulty was 132.72 trillion before the October 16, 2026 adjustment, according to Pickaxe, which reported an estimated rise of 5.5–6.4% as network hashrate held above 1,000 EH/s (exahashes per second). Plugging in:

132.72 × 10^12 × 2^32 ≈ 5.7 × 10^23 hashes per block
5.7 × 10^23 ÷ 1.0 × 10^21 hashes/second ≈ 570 seconds ≈ 9.5 minutes

Close to the 10-minute target, which is exactly why the next adjustment pushed difficulty up: hashrate had grown, so blocks were arriving slightly early.

Watch difficulty scale on your own machine

This toy miner shows the core loop. Instead of Bitcoin's real target, it asks for a number of leading zero bits:

import hashlib, os, struct, time

def sha256d(b: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()

def mine(header_76: bytes, zero_bits: int):
    """Try nonces until the double-SHA-256 hash has `zero_bits` leading zero bits."""
    target = 1 << (256 - zero_bits)
    for nonce in range(2**32):
        h = sha256d(header_76 + struct.pack("<I", nonce))
        if int.from_bytes(h[::-1], "big") < target:
            return nonce, h[::-1].hex()
    return None, None   # nonce space exhausted: real miners change the timestamp or extranonce

header = os.urandom(76)  # stand-in for version, prev hash, merkle root, time, bits
for zb in (8, 16, 20):
    t = time.perf_counter(); nonce, h = mine(header, zb)
    print(f"{zb} zero bits: nonce={nonce:,}  {time.perf_counter()-t:.2f}s  {h[:16]}...")

One run on my machine:

8 zero bits: nonce=253  0.00s  00201789fcbe53f3...
16 zero bits: nonce=92,514  0.12s  0000e9863f3f8189...
20 zero bits: nonce=1,040,249  1.11s  00000b2b7eecc524...

Each extra zero bit doubles the expected work. Twenty bits took about a million tries. Bitcoin's current target needs the equivalent of roughly 79 leading zero bits, since 2⁷⁹ ≈ 5.7 × 10²³. Notice also the comment about the nonce running out: 4 bytes gives only about 4.3 billion values, which a modern ASIC burns through in a fraction of a millisecond. Real miners also vary an "extranonce" inside the coinbase transaction, which changes the merkle root and gives them a fresh header to search.

Why nobody solo-mines Bitcoin on a laptop

My Python loop managed about 1.25 million double-SHA-256 hashes per second on one CPU core. Here's how long, on average, three different miners would wait to find one block at today's difficulty:

Log-scale bar chart of expected time to find a Bitcoin block: 14.4 billion years for Python on one CPU core, about 30 years for one 600 TH/s ASIC mining solo, and about 9.5 minutes for the whole network at 1,000 EH/s
A laptop would need longer than the age of the universe. Even one of the most efficient ASICs on the market would wait about 30 years on average.

A laptop would need longer than the age of the universe. Even one of the most efficient ASICs on the market would wait about 30 years on average.

  • Python on one CPU core: about 14.4 billion years, longer than the universe has existed.

  • One top-end ASIC (a 600 TH/s Antminer S23 XP Hyd) mining alone: about 30 years on average.

  • The whole network: about 9.5 minutes.

That's why Bitcoin mining moved from CPUs to GPUs to ASICs (chips built to do nothing but SHA-256d), and why almost everyone mines through a pool. A pool combines thousands of miners' hashrate, finds blocks regularly, and pays each member according to the work they contributed. You trade a tiny chance of a big win for a small, steady income. Pools prove your contribution by having you submit "shares": hashes that beat an easier target set by the pool. They don't win blocks, but they show you were really hashing.

The economic side of the hardware is measured in joules per terahash (J/TH), the energy each trillion hashes costs. According to MillionMiner's October 2026 roundup, the newest hydro-cooled machines run at roughly 9–10 J/TH, while good air-cooled models sit around 12–14 J/TH. Because electricity is the biggest running cost, efficiency decides who stays profitable when margins tighten.

The money: block rewards, halvings and hashprice

Miners earn two things per block: the block subsidy (newly created bitcoin) and the transaction fees users attach.

  • The subsidy has been 3.125 BTC since the April 2024 halving.

  • It halves every 210,000 blocks. The next halving is at block 1,050,000, expected around April 2028, when it drops to 1.5625 BTC (BitRef).

  • Because of this schedule, total supply can never exceed 21 million BTC. The last fractions of a coin should be issued around the year 2140, after which miners will earn fees only.

Fees are small right now. On October 22, 2026, fees made up only about 0.70% of block rewards, according to TokenPost. That's a long-term question for Bitcoin's security: as the subsidy keeps halving, fees need to grow to keep miners paid.

The industry sums all of this into one number, hashprice: expected revenue per unit of hashrate per day. TokenPost reported hashprice at $36.55 per PH/s per day on October 22, 2026. Per 100 TH/s, that's about $3.66 a day, gross, before electricity or any fees. Keep that number in mind for the next section.

Cloud mining: what you're actually buying

Cloud mining means renting hashrate from a company that owns and runs the machines. You pay for a contract, say 100 TH/s for 12 months, and receive a share of the mining output, usually daily, minus electricity and maintenance fees. The appeal is obvious: no noisy hardware, no heat, no power bill.

The question to ask is simple: can this contract pay back more than it costs? Here's a worked example, with every assumption stated:

  • 100 TH/s for 12 months, $800 upfront (a hypothetical price)

  • Revenue starts at the Oct 22, 2026 hashprice: $3.66/day gross

  • Electricity charged at 10 J/TH and $0.06/kWh: $1.44/day

  • Maintenance fee: $0.50/day

  • BTC price held constant; three hashprice scenarios over the year

Line chart of cumulative net payout over a 12-month, 100 TH/s cloud mining contract, reaching $626 if hashprice stays flat, $493 if it falls 20% and $359 if it falls 40%, all below the $800 contract price
Even with hashprice flat for a full year, this contract returns $626 against an $800 price. Rising difficulty only makes it worse.

Even with hashprice flat for a full year, this contract returns $626 against an $800 price. Rising difficulty only makes it worse.

Results: $626 with flat hashprice, $493 if it falls 20%, $359 if it falls 40%. Hashprice usually drifts down as more machines join the network, and in April 2028 the subsidy halves. Under these assumptions, the most this contract could be worth is about $626, and any price above that is a bet on Bitcoin's price rising, not a mining return. You could make that same bet by simply buying bitcoin, without the counterparty risk.

To check any contract yourself:

daily net  = hashrate_TH × (hashprice_per_TH − electricity_per_TH − maintenance_per_TH)
break-even = contract price ÷ daily net        (in days, if hashprice never falls)

If the break-even is longer than the contract, walk away.

Cloud mining red flags

Cloud mining has a long history of fraud. Many "mining" sites run no hardware at all and pay early users with later users' deposits. Walk away if you see:

  • Guaranteed or fixed daily returns. Real mining income moves with difficulty, BTC price and fees every day.

  • Returns far above the hashprice math. If a site promises $10/day for 100 TH/s when the whole network pays about $3.66 gross, the extra money is coming from somewhere else.

  • Referral levels and recruitment bonuses. That's a pyramid's growth engine.

  • "Free" Bitcoin cloud mining. Electricity is never free. These are usually phishing or deposit traps.

  • No verifiable company, data-centre location or pool payouts. A real operator can show which pool its hashrate points to.

  • Any request for your seed phrase or private key. No legitimate service ever needs it. Credential phishing targets crypto users the same way it targets developers; ByteMuni's report on GhostAction's phishing and OAuth attacks shows how convincing these campaigns have become.

Test withdrawals with a small amount before committing more, and assume any contract can stop paying.

Liquidity mining isn't mining

"Liquidity mining" shares the word but has nothing to do with hashing. In decentralized finance (DeFi), you deposit a pair of tokens into a pool on a decentralized exchange that runs as an automated market maker (AMM). Traders swap against that pool, and you earn a share of their fees, sometimes plus bonus tokens.

The main risk is impermanent loss: if the two tokens' prices move apart, you can end up with less value than if you'd just held them. Add smart-contract bugs and token rewards that can lose value fast. It's a lending-style activity with market risk, not computation, and it doesn't secure Bitcoin.

Proof of Work vs Proof of Stake

Bitcoin mining is Proof of Work (PoW): it secures a chain with spent energy. Proof of Stake (PoS) secures it with locked-up capital: validators deposit coins as collateral and can lose them if they cheat. Ethereum switched from PoW to PoS in The Merge in September 2022, which is why "Ether mining" no longer exists.

Proof of Work (Bitcoin)Proof of Stake (Ethereum)What you commitElectricity and hardwareCoins locked as collateralWho produces blocksWhoever finds a valid hash firstValidators chosen in proportion to stakeCost of attackingOut-hash the honest networkAcquire a large share of staked coinsEnergy useHigh, by designMuch lowerMain criticismEnergy consumptionWealth concentration, more complex rules

Bitcoin's developers and most of its community see PoW's energy cost as the point: it ties the ledger to a physical, external cost that can't be faked or printed.

Is SHA-256 still safe?

Yes. No practical preimage or collision attack on SHA-256 is publicly known, and Bitcoin's security has rested on it since 2009. If you're curious how hard SHA-256 is to "learn", ByteMuni ran an experiment training a neural network to reverse it in Exploring Neural Networks for Reversing SHA256, with the results you'd expect.

Two real-world risks to Bitcoin mining and the chain it secures are worth understanding. More security coverage lives in ByteMuni's cyber security section.

  • 51% attack. A miner or group controlling most of the hashrate could reorder recent blocks and double-spend their own coins. They couldn't steal other people's coins or create coins out of nothing, because signatures and consensus rules still apply. At ~1,000 EH/s, building that much hashrate would cost billions in hardware and energy.

  • Quantum computers. Grover's algorithm would only give a quadratic speedup on hashing, which works out like extra mining hardware rather than a break. The bigger quantum concern is Shor's algorithm against the elliptic-curve signatures, not SHA-256, and mainly for coins whose public keys are already visible on-chain. Upgrading to post-quantum signatures is an active research and proposal area in the Bitcoin community.

A note for readers in India

If you mine or receive crypto in India, the tax rules are strict. Gains on transferring virtual digital assets are taxed at a flat 30% plus 4% cess under Section 115BBH, a 1% TDS applies to transfers above the yearly threshold, and losses can't be set off against other income. How mining rewards themselves are taxed when you receive them is less clearly settled, so talk to a chartered accountant before you start (Mudrex's mining tax explainer is a useful starting point). This isn't tax advice.

The bottom line

Bitcoin mining is SHA-256 run as a fair lottery: hash an 80-byte header twice, compare it with a target, change the nonce, repeat about 10²¹ times a second across the planet. The avalanche effect makes guessing the only strategy, difficulty keeps blocks near 10 minutes, and halvings cap supply at 21 million.

For individuals, the honest takeaway from the math is that profitable mining today is an industrial business built on cheap power and efficient ASICs. If you want to learn, run the code above. If you're considering a cloud contract, do the hashprice math first, because the numbers rarely add up in your favour.

Sources

Frequently asked questions

Is SHA-256 encryption?

No. SHA-256 is a one-way hash function: it turns any input into a fixed 256-bit fingerprint and can't be reversed with a key. Encryption is reversible. Bitcoin uses SHA-256 for mining, block links and transaction IDs, and digital signatures (ECDSA and Schnorr) to authorise spending.

Why does Bitcoin hash the block header twice?

Bitcoin applies SHA-256 twice (SHA-256d) to the 80-byte block header. The design choice is usually explained as protection against length-extension attacks on single SHA-256. For mining it simply means every attempt costs two SHA-256 computations.

Can I mine Bitcoin on my laptop or phone?

Technically yes, practically no. At October 2026 difficulty, a single CPU core running at about 1.25 million hashes per second would need around 14 billion years on average to find a block. Even joining a pool, the electricity would cost far more than the bitcoin earned.

How often does Bitcoin mining difficulty change?

Every 2,016 blocks, about every two weeks. Every node recalculates the target so blocks keep arriving roughly every 10 minutes. One adjustment can change difficulty by at most a factor of four.

When is the next Bitcoin halving?

Only if the contract costs less than the hashprice math says it will earn. At the October 22, 2026 hashprice, 100 TH/s earns about $3.66 a day before electricity and fees. Contracts with guaranteed or fixed daily returns are a major red flag.

What is the difference between mining and liquidity mining?

Bitcoin mining spends computation to secure the blockchain and earn block rewards. Liquidity mining means depositing tokens into a DeFi pool to earn trading fees and rewards. It involves no hashing and carries risks like impermanent loss and smart-contract bugs.

How this article was made: researched and edited by Deepak Kumar, drafted with help from AI tools.

Written by

· Senior Software Engineer

Deepak Kumar is a Senior Software Engineer based in New Delhi. He maintains production systems with millions of readers, where a missed patch is an incident rather than a headline. He started ByteMuni to publish clear, source-checked guides for working developers.