主页 > imtoken官网地址打不 > 了解比特币原理的程序
了解比特币原理的程序
imtoken官网地址打不 2023-02-24 05:45:50
自比特币走红以来,网上对比特币的解释可谓纷繁复杂。 但是对于程序员来说,最直接的方式就是直接看程序代码。 比特币代码再复杂也没关系。 我找到了一个简明的代码来理解比特币。
以下程序转自知乎吴豪的回答。
- 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),然后进行广播。
原文链接: