您的位置:首页 > 其它

一段程序看懂比特币原理

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

以下这段程序转自知乎上Wu Hao的回答
[cpp] view plaincopy



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)
,那么就挖矿成功了。所谓挖矿难度,指的是要求的二进制散列值小于某个阈值,阈值越小,挖矿的难度就越大。

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

原文链接:https://www.byvoid.com/zhs/blog/bitcoin-principle-program
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  比特币