一段程序看懂比特币原理

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

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

以下这段程序转自知乎上Wu Hao的回答

  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),那么就挖矿成功了。所谓挖矿难度,指的是要求的二进制散列值末尾0的个数,而散列值是碰运气生成的,除了穷举没有别的办法,要求的0个数越多挖矿的难度就越大。

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

原文链接:https://www.byvoid.com/zhs/blog/bitcoin-principle-program

责任编辑:林师授 来源: byvoid.com
相关推荐

2017-04-06 12:20:16

2013-12-09 16:35:25

2018-11-02 16:16:41

程序硬盘存储

2021-10-28 19:35:02

代码main方法

2020-04-03 10:14:57

内存蠕虫代码web安全

2015-10-09 11:44:06

2012-03-01 14:13:36

Java

2014-07-08 09:21:10

死代码创意歌曲

2018-06-19 08:02:00

统计程序微信

2020-12-31 10:14:42

防注入代码绕过

2022-06-21 12:27:12

JavaScript前端

2021-01-18 08:09:20

Java程序JIT

2014-09-09 14:47:20

2021-02-04 07:55:28

代码离职互联网

2021-01-04 05:58:57

WindowsXP微软操作系统

2022-02-08 09:00:00

智能自动化人工智能RPA

2015-03-27 11:34:59

JavaJava编写引发内存泄露

2017-11-20 16:44:59

云端算力

2021-04-08 09:14:24

js前端函数

2019-10-14 09:51:08

爬虫网络系统
点赞
收藏

51CTO技术栈公众号