1. 程式人生 > >#比特幣挖礦part1# 挖礦演算法

#比特幣挖礦part1# 挖礦演算法

之前,我總以為挖礦就是把Nonce值都試一遍,然後用SHA256演算法算一遍。後面發現自己把東西看得太簡單,我嘗試嘗試講講比特幣的挖礦演算法的流程。

區塊頭

首先挖礦演算法的目標物件只是區塊中的區塊頭,共80個位元組,我們來看看區塊頭有哪些欄位:
這裡寫圖片描述

注意:

  1. Target(難度目標):該區塊工作量證明演算法的難度目標
  2. 其實區塊頭不包括Padding+Length部分,這個部分只是為了滿足SHA256演算法的使用條件。
  3. 欄位的不同顏色代表該欄位內容變化頻率。綠色:像Version、Target、以及Padding+Length(有約定俗成的標準)這些內容相對出塊的速度來說變化頻率很低;黃色:像hashPreBlock、hashMerkleRoot、Timestamp這些幾乎與出塊的速度一致的頻率;紅色:像Nonce這個的變化頻率遠遠快與出塊速率。

挖礦演算法流程

這裡寫圖片描述

為什麼要做雙重hash(SHA256(1)後還來個SHA256(2))

The SHA256 hashing algorithm, like all hashes constructed using the Merkle-Damgård paradigm, is vulnerable to this attack. The length extension attack allows an attacker who knows SHA256(x) to calculate SHA256(x||y) without the knowledge of x. Although it is unclear how length extension attacks may make the Bitcoin protocol susceptible to harm, it is believed that Satoshi Nakamoto decided to play it safe and include the double hashing in his design.

Another explanation [6] for this double hashing is that 128 rounds of SHA256 may remain safe longer if in the far future, a practical pre-image or a partial pre-image attack was found against SHA256.

挖礦演算法實現以及編碼方式