一段程序看懂比特币原理

jopen 7年前

  自从比特币火起来以后,网上对比特币的解释可谓汗牛充栋,纷繁复杂。但对于程序员来说,最直接的方式莫过于直接看程序代码了。嫌比特币代码庞杂没关系,我找到一段简明扼要的代码,用来理解比特币再好不过了。

  以下这段程序转自知乎上 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)  }  ///////////////////////////////////////////////////////////////

  下面是我的解释:

  挖矿过程就是不断从比特币网络中获取所有未确认交易getUnconfirmedTransactionsFromNetwork (),把它们打包成一个区块并挂载目前最长的区块链上getNewBlock (longestChain, currentTXs, nonce),然后计算新的区块的散列值sha256(newBlock),如果散列值正好满足挖矿难度了meetReqirements (blockHash),那么就挖矿成功了。所谓挖矿难度,指的是要求的二进制散列值末尾 0 的个数,而散列值是碰运气生成的,除了穷举没有别的办法,要求的 0 个数越多挖矿的难度就越大。

  付款过程就是把一些有余额的已确认交易拿出来作为发送地址pickConfirmedTransactionsToBeSpent (amount),然后根据目标地址支付一定交易费生成新的交易generateTX (sourceTXs, targetAddrs, amount, fee),并用钱包私钥对交易签名sign (tx, privateKeysOfAllInputAddress),然后广播出去。

来自: www.byvoid.com