一段程序看懂比特幣原理
自從比特幣火起來(lái)以后,網(wǎng)上對(duì)比特幣的解釋可謂汗牛充棟,紛繁復(fù)雜。但對(duì)于程序員來(lái)說(shuō),最直接的方式莫過(guò)于直接看程序代碼了。嫌比特幣代碼龐雜沒(méi)關(guān)系,我找到一段簡(jiǎn)明扼要的代碼,用來(lái)理解比特幣再好不過(guò)了。
以下這段程序轉(zhuǎn)自知乎上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)
 - }
 - ////////////////////////////////////////////////////////////////
 
下面是我的解釋:
挖礦過(guò)程就是不斷從比特幣網(wǎng)絡(luò)中獲取所有未確認(rèn)交易getUnconfirmedTransactionsFromNetwork(),把它們打包成一個(gè)區(qū)塊并掛載目前最長(zhǎng)的區(qū)塊鏈上getNewBlock(longestChain, currentTXs, nonce),然后計(jì)算新的區(qū)塊的散列值sha256(newBlock),如果散列值正好滿足挖礦難度了meetReqirements(blockHash),那么就挖礦成功了。所謂挖礦難度,指的是要求的二進(jìn)制散列值末尾0的個(gè)數(shù),而散列值是碰運(yùn)氣生成的,除了窮舉沒(méi)有別的辦法,要求的0個(gè)數(shù)越多挖礦的難度就越大。
付款過(guò)程就是把一些有余額的已確認(rèn)交易拿出來(lái)作為發(fā)送地址pickConfirmedTransactionsToBeSpent(amount),然后根據(jù)目標(biāo)地址支付一定交易費(fèi)生成新的交易generateTX(sourceTXs, targetAddrs, amount, fee),并用錢包私鑰對(duì)交易簽名sign(tx, privateKeysOfAllInputAddress),然后廣播出去。
原文鏈接:https://www.byvoid.com/zhs/blog/bitcoin-principle-program















 
 
 






 
 
 
 