Sådan fungerer Bitcoin-minedrift virkelig

Når Bitcoin nærmer sig almindelig vedtagelse og anerkendelse, bliver dens grundlæggende sikkerhedsmodel, der er karakteriseret som minedrift, sat under rampelyset og undersøgt mere og mere hver dag.

Folk er i stigende grad bekymrede over og interesseret i miljøbelastningen af ​​Bitcoin-minedrift, sikkerheden og graden af ​​decentralisering af den underliggende model og endda den potentielle indvirkning af et kvantecomputerbrud på fremtiden for Bitcoin og andre kryptokurver.

Ofte beskrives proof-of-work som et "kryptografisk puslespil", men hvad er egentlig dette puslespil?

For virkelig at forstå disse spørgsmål (og eventuelle mulige svar) skal du have en grundlæggende forståelse af Bitcoin-minedrift selv og dens udvikling.

Denne artikel vil undersøge alle de tekniske komponenter og bevægelige dele af proof-of-work, og hvordan de problemfrit synkroniseres med hinanden for at give Bitcoin mulighed for at være den decentraliserede platform, den er i dag.

Hvorfor minedrift fungerer: kryptografisk envejshashing

Bitcoin-blockchain beskrives ofte som en database, der er kryptografisk sikker og efterfølgende uforanderlig. Den underliggende teknologi, der driver denne uforanderlighed og sikkerhed, er kryptografisk hashing.

En kryptografisk hash-funktion er en matematisk funktion, der enkelt sagt tager ethvert input og kortlægger det til en streng i fast størrelse.

Der er dog fire specielle egenskaber ved disse funktioner, der gør dem uvurderlige for Bitcoin-netværket. De er:

  1. Deterministisk - for ethvert input til den kryptografiske hash-funktion vil den resulterende output altid være den samme.
  2. Hurtig - Computing output af hash-funktionen, givet ethvert input, er en relativt hurtig proces (behøver ikke tung beregning)
  3. Unikt - Hvert input til funktionen skal resultere i en helt tilfældig og unik output (med andre ord, ingen to input resulterer i den samme output)
  4. Irreversibel - Givet en output af en hash-funktion, kan den originale input ikke opnås

Disse regler danner det fundament, der gør det muligt for Bitcoin-minedrift at sikre netværket.

Især valgte skaberen af ​​Bitcoin-protokollen, Satoshi Nakomoto, at bruge SHA-256-hashfunktionen som grundlag for Bitcoin-minedrift. Dette er en specifik kryptografisk hash-funktion, der er matematisk bevist at indeholde ovenstående egenskaber. Det udsender altid et 256 bit nummer (den mest basale beregningsenhed), som normalt er repræsenteret i det hexadecimale talsystem med 64 tegn for menneskelig læsbarhed.

Outputtet fra SHA-256-funktionen kaldes normalt hash for dets input.

Her er et eksempel på en SHA-256-funktion input og output (du kan selv prøve det her):

Input to SHA-256:  Output to SHA-256: 77077b1f4c3ad44c83dc0bdb8d937e9b71c0ef07a35c2664bb7da85be738eacf

Interessant nok bruges dobbelt hashing på de fleste steder, hvor hashing bruges i Bitcoin-protokollen . Dette betyder, at output fra den oprindelige SHA-256-funktion derefter sættes lige tilbage i SHA-256-funktionen for at opnå en anden output. Sådan ser processen ud:

Input to SHA-256(first round):  Output (first round): 77077b1f4c3ad44c83dc0bdb8d937e9b71c0ef07a35c2664bb7da85be738eacf Input to SHA-256 (second round): 77077b1f4c3ad44c83dc0bdb8d937e9b71c0ef07a35c2664bb7da85be738eacf Output (second round and final result): 3c6c55b0e4b607b672b50f04e028a6951aed6dc97b91e103fb0f348c3f1dfa00

Dobbelt hashing bruges til at beskytte mod fødselsdagsangreb. Et fødselsdagsangreb er et scenario, hvor en angriber er i stand til at producere den samme hash som en anden input ved at bruge en helt anden input (kaldet en kollision ). Dette bryder den tredje egenskab ved unikhed. Uden det kan to helt forskellige Bitcoin-blokke repræsenteres af nøjagtigt den samme hash, hvilket gør det muligt for angribere potentielt at slå blokke ud.

Med SHA-256-funktionen er sandsynligheden for, at dette angreb finder sted uendeligt lille. Hvis det ikke var tæt på umuligt, ville SHA-256 blive betragtet som ødelagt.

Andre hashfunktioner er dog tidligere blevet "brudt". For at beskytte mod at dette sker med SHA-256 i fremtiden (og effektivt bryde sikkerhedsmodellen for Bitcoin) er det bedst at hash hash . Dette halverer sandsynligheden for en kollision, hvilket gør protokollen meget mere sikker.

På et meget højt niveau er Bitcoin-minedrift et system, hvor alle Bitcoin-transaktioner sendes til Bitcoin-minearbejdere. Minearbejdere vælger en megabyte værdi af transaktioner, bundter dem som et input til SHA-256-funktionen og forsøger at finde en bestemt output, som netværket accepterer. Den første minearbejder, der finder dette output og offentliggør blokken til netværket, modtager en belønning i form af transaktionsgebyrer og oprettelsen af ​​nye Bitcoin.

Lad os tage tingene et skridt videre og dykke ned i selve Bitcoin-blockchain for at se, hvad det præcist er, som minearbejdere gør for at gøre netværket sikkert.

Bitcoin Mining: En teknisk introduktion

Minedrift blev introduceret som løsningen på problemet med dobbeltforbrug. Hvis jeg har 1 Bitcoin, og jeg sender den til Bob, og derefter prøver at sende den samme Bitcoin til Alice, sikrer netværket, at kun en transaktion accepteres. Det gør det gennem den velkendte proces kaldet minedrift.

Før du dykker ned i de tekniske detaljer, er det vigtigt at forstå, hvorfor minedrift er nødvendig for at sikre netværket. Da fiat-valuta eksisterer nu, oprettes og valideres den valuta, vi har, af en føderal reserve. Fordi Bitcoin opererer under den stive antagelse om decentralisering og konsensus, kan der ikke eksistere nogen central myndighed, der validerer og tidsstempler udstedelsen af ​​denne valuta og validering af eventuelle transaktioner, der forekommer med den valuta.

Satoshi Nakamoto foreslog den eneste kendte løsning på det tidspunkt til løsning af dette valideringsproblem i et konsensusorienteret system. Titlen i Bitcoin-hvidbogen som bevis på arbejde , retfærdiggør denne ordning elegant, at transaktioner valideres af dem, der er villige til at bruge tilstrækkelig fysisk beregningsenergi og tid til at gøre det, samtidig med at der indføres et incitament til at inducere markedskonkurrence. Denne konkurrence gør det muligt for decentraliseringens egenskab at dukke op og trives organisk i økosystemet.

Et blik inde i en blok

En Bitcoin-blok består primært af to komponenter:

1. Transaktioner i form af et mærketræ

Minecomputere indsamler nok transaktioner til at udfylde en blok og samle dem i et mærketræ.

Et mærketræ er et relativt simpelt koncept: Transaktioner ligger i bunden af ​​træet som blade og hashes ved hjælp af SHA-256-funktionen. Kombinationen af ​​to bladtransaktioner hashes igen ved hjælp af SHA-256-funktionen til at danne en forælder til bladene. Denne forælder hasheres kontinuerligt opad i kombination med andre forældre til hashede transaktioner, indtil der oprettes en enkelt rod . Hashen af ​​denne rod er effektivt en unik repræsentation af de transaktioner, der er under den.

Roden til mærketræet er en kombination af hashen af ​​hver transaktion i træet.

Husk, at output for enhver indgang til en hash-funktion er helt unik. Derfor, når de fleste noder på netværket modtager en udvundet blok, fungerer roden til merkle-træ-hash som en uforanderlig oversigt over alle transaktionerne i den givne blok.

Hvis en ondsindet aktør forsøgte at ændre indholdet af en transaktion i en blok, ville dens hash blive ændret. Denne ændring af en hash vil blive spredt op i transaktionens mærketræ, indtil rodens hash ændres. Enhver knude kan derefter hurtigt fange denne ondsindede handling ved at sammenligne roden af ​​den ændrede blocks merkle-træ til den for en gyldig blok's merkle-træ.

2. Blokoverskriften

Blokoverskriften er et resumé af indholdet af selve blokken. Den indeholder følgende seks komponenter :

  • The version of software the Bitcoin client is running
  • The timestamp of the block
  • The root of its containing transactions' merkle tree
  • The hash of the block before it
  • A nonce
  • The target

Remember that the root of the transaction merkle tree acts as an effective summary of every transaction in the block without having to look at each transaction.

The hash of the previous block before it allows the network to properly place the block in chronological order. This is where the term blockchain is derived from — each block is chained to a previous block.

The nonce and target are what make mining tick. They are the basis for solving the SHA-256 puzzle that miners need to solve.

Please note that all of this data in the block header is compressed into 80 bytes using a notation called little-endian, making the transfer of block headers between nodes a trivially efficient process. For the purposes of this explanation, we’ll ignore this compression and assume data is in its original form.

Explaining the Mining Problem

The target stored in the block header is simply a numeric value stored in bits. In traditional base 10 notation, this target ranges anywhere between 0 to somewhere in the range of 2²²⁴ (a 67+ digitnumber), depending on how many miners are competing to solve this problem at the same time.

Recall that the output of SHA-256 is just a number. The goal of a miner is to take the current block’s header, add a random number to it called the nonce, and calculate its hash. This numeric value of the hash must be smaller than the target value.

That’s all there is to it. But it’s much easier said than done.

Recall the first property of SHA-256: an input into a hash function will always result in the same output. Therefore, if the miner took the block header, hashed it, and realized that the hash value wasn’t less than the target, they would have to change the input somehow in order to try finding a hash below the target value.

This is where the nonce comes in.

The miner adds a number (starting from 0), called the nonce, to the block header, and hashes that value. If the hash value isn’t less than the target, the miner will increment the nonce by 1, add it again to the block header, and hash that changed value. This process is repeated continuously until a hash less than the target value is found.

A Mining Example

Here’s a rough approximation of what made up the first block header:

  • The merkle root of the transaction in the Genesis block:
Merkle Root: 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
  • The first known Bitcoin version: 0.1.0
  • The timestamp of the block: 2009–01–03 18:15:05
  • The target (this is also the highest the target will ever be):
Target: 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
  • No previous block hash — this was the first block, and so this is a unique case

The final block header after adding its components together:

Let’s take this large header and compute the double-hash:

SHA-256 of header: 7d80bd12dfdccbdde2c41c9f406edfc05afb3320f5affc4f510b05a3394e1c91 SHA-256 of the previous result (final result): c5aa3150f61b752c8fb39525f911981e2f9982c8b9bc907c73914585ad2ef12b

Both the target and the output hash are incredibly large numbers when converted to base 10 (remember, over 67 digits long). Instead of trying to demonstrate the comparison of the two here, the following Python function handles the comparison instead:

def isBlockHashLessThanTarget(blockHash, target): return int(blockHash, 16) < int(target, 16)

True is returned if the hash is less than the target, false otherwise.

Here is the result with our target and block hash:

Now we take the original block hexadecimal value and add 1 to it. Here is the following result:

We then run the same hashing algorithm and comparison on this changed data. If its not below the target, keep repeating.

Once a successful hash is found, the latest nonce used to find this solution is saved within the block.

The listed nonce on the Genesis block is 2,083,236,893.

This means Satoshi Nakomoto iterated through this process over 2 billion times before he found a hash that was acceptable.

I’ve written a small Python implementation of this Genesis block mining process that can be found on my GitHub.

subhan-nadeem/bitcoin-mining-python

bitcoin-mining-python - A Python implementation of the Bitcoin mining algorithm

github.com

See how long it would take for you to successfully mine the Genesis block!

A Caveat: extraNonce

The nonce value in a block header is stored as a 32-bit number. This means that the highest nonce anybody is able to achieve is 2³² (approximately 4 billion). After 4 billion iterations, the nonce is exhausted, and if a solution is not found, miners are once again stuck.

The solution to this is to add a field to the coinbase (the transaction contents of a block, stored as the merkle tree) called the extraNonce. The size of this extraNonce is only limited by the size of block itself, and so it can be as large as miners wish as long as the block size is within protocol limits.

If all 4 billion possible values of the nonce are exhausted, the extraNonce is added and incremented to the coinbase. A new merkle root and subsequently new block header are calculated, and the nonce is iterated over once again. This process is repeated until a sufficient hash is found.

It’s best to avoid adding the extraNonce until the nonce is exhausted, because any change to the extraNonce changes the merkle tree. This requires extra computation in order to propagate the change upwards until a new root of the merkle tree is calculated.

The Miner Reward

A miner who successfully publishes a block the fastest is rewarded brand new Bitcoin, created out of thin air. That reward currently stands at 12.5 BTC. Just how do these Bitcoins come into existence?

Each miner simply adds a new output transaction to their block that attributes 12.5 Bitcoins to themselves before beginning to mine the block. The network protocol will accept this special transaction as valid upon receiving a newly validated block. This special transaction is called a generation transaction.

Its the miner’s responsibility to add this transaction into the block before mining it. There has been at least one case where miners forgot to add the reward to the transaction before mining a block, effectively destroying 12.5 BTC!

Validating Proof-of-Work

Let’s say our miner has found a hash that is less than the target. All this miner has to do is publish the mined block with the original six components to any connected nodes.

This node receiving the block will first verify the transaction set, ensuring all transactions are valid (for example, all transactions are appropriately signed, and coins aren’t being double-spent and/or being created out of thin air).

It will then simply double-hash theblock header and ensure the value is below the block’s included target value. Once the block is deemed valid, the new node will continue to propagate this block across the network until every node has an up-to-date ledger.

As you can see, newly published blocks can easily be verified by any given node. However, publishing a valid block to the network requires an incredibly large amount of computational power (thus, electricity and time). This asymmetry is what allows the network to be secured while simultaneously allowing individuals who wish to conduct economic activity on the network to do so in a relatively seamless manner.

The Block Time and Adjusting the Target

As the first miners began mining, they each monitored the block time. Each Bitcoin block has a set block time of 10 minutes. What this means is that given the current level of computing power (networkhashrate) on the network, nodes will always expect newly validated blocks to be produced every 10 minutes on average.

We can reasonably expect blocks to be produced within 10 minutes because the probability of finding a block, given the network hashrate, is known.

For example, let’s take the easiest target that’s ever existed in Bitcoin: the genesis block. The probability of any single hash being less than the easiest target is 1 in 2³². That’s one in over four billion. Therefore, we can reasonably expect somebody to run 2³² iterations of the mining problem in order to find a proper hash. Nodes on the network expected four billion of these iterations to be run across allminers on the network every 10 minutes.

If, over a large sample size of blocks, blocks start appearing faster than 10 minutes, this is a pretty clear indication that nodes on the network are iterating through four billion hashes much faster than 10 minutes. This situation prompts every node to adjust the target proportionally based on the increase (or decrease) in network power to ensure blocks continue to be produced every 10 minutes.

In actuality, nodes on the network monitor the block time across 2016 blocks, which comes out to exactly two weeks. Every two weeks, the total block time is compared to the expected block time (which is 20160 minutes).

To obtain the new target, simply multiply the existing target by the ratio of the total actual block time over the last two weeks to get the expected block time. This will adjust the target proportionally to the amount of entering or exiting computing power on the network.

The block time and the ability to easily calculate the probability of finding a valid block lets nodes easily monitor and determine the total hashpower on the network and adjust the network. No matter how much computing power is added to the network or how quickly its added, on average the block time will always remain at 10 minutes.

The current total hash rate on the network is 28.27 exahash per second. That’s 28.27 x 10¹⁸ hashes run every second across all computers on the network.

In summary

We have now comprehensively covered the following:

  • Hvorfor kryptografisk envejshashing er afgørende for bevis for arbejde
  • En opdeling af opførelsen af ​​en Bitcoin-blok
  • Den egentlige minedrift og selve iteration
  • Hvordan noder let kan validere andre blokke
  • Hvordan netværket formår at opretholde algoritmen og konkurrenceevnen ved at overvåge blokeringstiden og justere målet

Du skal nu være i stand til at forstå og forklare, hvordan proof-of-work faktisk fungerer, og hvorfor det anses for at være en helt sikker algoritme, der muliggør decentralisering og konsensus!

Følg mig på Twitter og Medium, hvis du er interesseret i mere dybtgående og informative skrivninger som disse i fremtiden!