一段程序看懂比特幣原理

jopen 10年前發布 | 7K 次閱讀 比特幣

  自從比特幣火起來以后,網上對比特幣的解釋可謂汗牛充棟,紛繁復雜。但對于程序員來說,最直接的方式莫過于直接看程序代碼了。嫌比特幣代碼龐雜沒關系,我找到一段簡明扼要的代碼,用來理解比特幣再好不過了。

  以下這段程序轉自知乎上 Wu Hao 的回答

 function mine ()
{
    while(true)
    {
        longestChain = getLongestValidChain ()

    -- A number that changes every time, so that you don't waste  --

           time trying to calculate a valid blockHash with the same -- input. nonce = getNewNonce ()

    currentTXs = getUnconfirmedTransactionsFromNetwork ()

    newBlock = getNewBlock (longestChain, currentTXs, nonce)

    -- http://en.wikipedia.org/wiki/SHA-2 -- and this is what all the

             "mining machines" are doing. blockHash = sha256(newBlock)

    if (meetReqirements (blockHash))
    {
        broadcast (newBlock)
        -- Now the height the block chain is incremented by 1 -- 

              (if the new block is accepted by other peers), -- and all the TXs in the new block are "confirmed" } } } ////////////////////////////////////////////////////// function sendBTC (amount) { sourceTXs = pickConfirmedTransactionsToBeSpent (amount) tx = generateTX (sourceTXs, targetAddrs, amount, fee) signedTx = sign (tx, privateKeysOfAllInputAddress) broadcast (signedTx) } ///////////////////////////////////////////////////////////////</pre>

  下面是我的解釋:

  挖礦過程就是不斷從比特幣網絡中獲取所有未確認交易getUnconfirmedTransactionsFromNetwork (),把它們打包成一個區塊并掛載目前最長的區塊鏈上getNewBlock (longestChain, currentTXs, nonce),然后計算新的區塊的散列值sha256(newBlock),如果散列值正好滿足挖礦難度了meetReqirements (blockHash),那么就挖礦成功了。所謂挖礦難度,指的是要求的二進制散列值末尾 0 的個數,而散列值是碰運氣生成的,除了窮舉沒有別的辦法,要求的 0 個數越多挖礦的難度就越大。

  付款過程就是把一些有余額的已確認交易拿出來作為發送地址pickConfirmedTransactionsToBeSpent (amount),然后根據目標地址支付一定交易費生成新的交易generateTX (sourceTXs, targetAddrs, amount, fee),并用錢包私鑰對交易簽名sign (tx, privateKeysOfAllInputAddress),然后廣播出去。

來自: www.byvoid.com
                    <span id="shareA4" class="fl">                          </span>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!