概念
对于单向散列函数,输出是不可知的。但在假设输出结果是随机平均分布的情况下,可以预先计算出特定范围的结果的可能性,推导要计算出满足特定条件的结果所花费的工作量。
在比特币的区块链实现中,POW是一种保护区块链网络,维持通货稳定的手段。因为对比特币来说,一个非常重要的原则是维持每10分钟生成一个区块。新的通货只会从新区块的第一个交易(coinbase transaction)产生。如此,维持区块的生成频率就是维持通货的稳定。
比特币区块头部会有一个字段Target和一个字段nonce(最后一个字段)。简单来说,POW就是通过改变nonce字段,使得区块头部的散列值在数值上小于Target字段。通过设定特殊的Target值,使得调整nonce以得出满足条件的散列值这一过程的平均时间为10分钟。而只有区块头部散列值在数值上小于Target的区块,才会被视为是有效的区块。
target
关于target的格式,前2位16进制数为指数(exponent),后6位16进制数是系数(coefficient)。
计算出实际的Target的公式为:
Target = coefficient * 2 ^ (8 * (exponent - 3))
retargeting
每10分钟创建一个区块是比特币的核心原则,保证通货发行的稳定性。随着矿机的性能的提高,Target也需要周期性的调整以维持该原则,保证比特币的稳定。
比特币的每个节点会每隔2016个区块重新调整一次target,以维持每10分钟生成一个区块的原则。
调整公式为:
新Target = 旧Target * (前2016个区块所花费的时间 / 20160 分)
实现
#! /usr/bin/env python
# example of proof-of-work algorithm
import hashlib
import time
max_nonce = 2 ** 32 # 4 billion
def proof_of_work(header, difficulty_bits):
# calculate the difficulty target
target = 2 ** (256 - difficulty_bits)
for nonce in xrange(max_nonce):
hash_result = hashlib.sha256(str(header) + str(nonce)).hexdigest()
# check if this is a valid result, below the target
if long(hash_result, 16) < target:
print "Success with nonce %d" % nonce
print "Hash is %s" % hash_result
return (hash_result, nonce)
print "Failed after %d (max_nonce) tries" % nonce
return nonce
if __name__ == '__main__':
nonce = 0
hash_result = ''
# difficulty from 0 to 31 bits
for difficulty_bits in xrange(32):
difficulty = 2 ** difficulty_bits
print "Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits)
print "Starting search..."
# checkpoint the current time
start_time = time.time()
# make a new block which includes the hash from the previous block
# we fake a block of transactions - just a string
new_block = 'test block with transactions' + hash_result
# find a valid nonce for the new block
(hash_result, nonce) = proof_of_work(new_block, difficulty_bits)
# checkpoint how long it took to find a result
end_time = time.time()
elapsed_time = end_time - start_time
print "Elapsed Time: %.4f seconds" % elapsed_time
if elapsed_time > 0:
# estimate the hashes per second
hash_power = float(long(nonce)/elapsed_time)
print "Hashing Power: %ld hashes per second" % hash_power