当前位置: 首页 > 科技观察

一档了解比特币原理的程序

时间:2023-03-12 04:11:30 科技观察

自比特币流行以来,网上对比特币的解释可谓是纷繁复杂。但是对于程序员来说,最直接的方式就是直接看程序代码。比特币代码再复杂也没关系。我找到了一个简明的代码来理解比特币。以下程序转自知乎吴豪的回答。functionmine(){while(true){longestChain=getLongestValidChain()--数字每次都会改变,这样你就不会浪费--timetryingtocalculateavalidblockHashwiththesame--input。http://en.wikipedia.org/wiki/SHA-2——这就是所有“挖矿机器”正在做的事情。blockHash=sha256(newBlock)if(meetReqirements(blockHash)){broadcast(newBlock)--Nowtheheighttheblockchainisincrementedby1--(ifthenewblockisacceptedbyotherpeers),--andalltheTXsinthenewblockare"confirmed"}}}/////////////////////////////////////////////////////////////////functionsendBTC(amount){sourceTXs=pickConfirmedTransactionsToBeSpent(amount)tx=generateTX(sourceTXs,targetAddrs,amount,fee)signedTx=sign(tx,privateKeysOfAllInputAddress)广播(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