站长网 资讯 一段程序明白比特币原理

一段程序明白比特币原理

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

自从比特币火起来以后,网上对比特币的解释可谓汗牛充栋,纷繁复杂。但对于程序员来说,最直接的方式莫过于直接看程序代码了。嫌比特币代码庞杂没关系,我找到一段简明扼要的代码,用来理解比特币再好不过了。
 
以下这段程序转自知乎上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),然后广播出去。

本文来自网络,不代表站长网立场,转载请注明出处:https://www.tzzz.com.cn/html/biancheng/zx/2021/1105/20145.html

作者: dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。
联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部