主页 > 官网安卓版下载imtoken钱包 > 了解比特币原理的程序

了解比特币原理的程序

自比特币走红以来,网上对比特币的解释可谓纷繁复杂。 但是对于程序员来说,最直接的方式就是直接看程序代码。 比特币代码再复杂也没关系。 我找到了一个简明的代码来理解比特币。

以下程序转自知乎吴豪的回答。

  1. function mine()  
  2. {  
  3.     while(true)  
  4.     {  
  5.         longestChain = getLongestValidChain()  
  6.  
  7.         -- A number that changes every time, so that you don't waste   
  8.         -- time trying to calculate a valid blockHash with the same  
  9.         -- input.  
  10.         nonce = getNewNonce()  
  11.  
  12.         currentTXs = getUnconfirmedTransactionsFromNetwork()  
  13.  
  14.         newBlock = getNewBlock(longestChain, currentTXs, nonce)  
  15.  
  16.         -- http://en.wikipedia.org/wiki/SHA-2  
  17.         -- and this is what all the "mining machines" are doing.  
  18.         blockHash = sha256(newBlock)  
  19.  
  20.         if (meetReqirements(blockHash))  
  21.         {  
  22.             broadcast(newBlock)  
  23.             -- Now the height the block chain is incremented by 1 
  24.             -- (if the new block is accepted by other peers),  
  25.             -- and all the TXs in the new block are "confirmed" 
  26.         }  
  27.     }  
  28. }  
  29. ////////////////////////////////////////////////////////////////  
  30. function sendBTC(amount)  
  31. {  
  32.     sourceTXs = pickConfirmedTransactionsToBeSpent(amount)  
  33.     tx = generateTX(sourceTXs, targetAddrs, amount, fee)  
  34.     signedTx = sign(tx, privateKeysOfAllInputAddress)  
  35.     broadcast(signedTx)  
  36. }  
  37. //////////////////////////////////////////////////////////////// 

这是我的解释:

挖矿过程是不断从比特币网络中获取所有未确认的交易getUnconfirmedTransactionsFromNetwork()比特币样子图片,打包成一个区块挂载到当前最长的区块链getNewBlock(longestChain, currentTXs, nonce)上,然后计算新的哈希值该块是 sha256(newBlock)。 如果哈希值刚好满足挖矿难度meetReqirements(blockHash),则挖矿成功。 所谓挖矿难度是指所需二进制哈希值末尾零的个数,哈希值是偶然产生的。 除了疲惫,别无他法。 需要的零越多,挖矿难度越大。

支付过程是取出一些有余额的确认交易作为发送地址pickConfirmedTransactionsToBeSpent(amount)比特币样子图片,然后根据目标地址支付一定的交易手续费,生成新的交易generateTX(sourceTXs, targetAddrs, amount, fee),并使用钱包私钥配对交易签名sign(tx, privateKeysOfAllInputAddress),然后进行广播。

原文链接: