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