
今天的越学越快乐系列文章为大家带来POW算法的简单介绍和基本使用,让大家对比特币、以太坊等数字货币的共识算法有个基本的认识。
什么是POW算法
POW是指工作量证明(Proof of Work)的简称,也就是刚开始比特币设计者中本聪使用的共识算法,也就是激励人们进行挖矿(证明自己的工作成果)的共识机制,正是这种机制实现了去中心化的安全。
矿工们(人为财死,鸟为食亡)在挖矿(通常会在挖矿节点,也就是连接到比特币网络中进行哈希计算并得到正确结果的节点)过程中得到两种类型的交易:创建新区块的新币奖励,以及区块中所包含交易的交易费
要说到这个POW,我们必须提一下哈希函数
,也就是输入一个任意长度的数据,输出得到一个固定长度且绝不雷同的值,可以将其视为输入的数字指纹。目前比特币、以太坊等都是SHA256算法来计算某个数据的函数值,也就是通过哈希函数得到该数据的数字指纹,通过这个数字指纹来验证比特币中的交易等信息。那我们接下来看看在Python中如何简单地实现POW算法,具体事例如下
#!/usr/bin/env python
# example of proof-of-work algorithm
import hashlib
import time
try:
long # Python 2
xrange
except NameError:
long = int # Python 3
xrange = range
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)
以上代码来自精《通比特币》书中的POW示例
接下来我在本地运行一下这个示例代码python proof-of-work-example.py
,执行完成后可以看到有如下输出

从以上的输出结果我们可以看到挖矿难度影响着比特币产生的效率,这个挖矿难度会根据整个比特币网络的算了进行调整,也就是说要产生新的区块必须拥有更多的算力,也就是将更多的电力转化为哈希算力。
怎么在区块链的世界里也有能量守恒的规律呢?
POW算法用在何处
在数字货币领域用在比特币、以太坊等主流的公有链上,也可以用在联盟链和私有链上
为什么要使用POW算法
这是最初使用在比特币网络上的共识机制,也是比特币世界中的人们达成的去中心化的规则或者说协议,正是这些协议才使得比特币安全地运行十年(虽然在这过程中出现了分叉等问题,但是这也是比特币网络不断发展演进的结果)。我想也正是中本聪基于当时技术并设计出一种电子现金系统并应用在当时尚未成熟的电子支付市场,是一次大胆而具有伟大变革意义的创新吧。
个人感想
当然现阶段,我对于POW算法的理解比较粗浅,对于比特币的设计、原理和运行机制更是一知半解,我希望在此学习和探索比特币、以太坊的道路上有更多的人去贡献自己的一份力量,我更期待数字货币能带来前所未有的变革和业务进化吧。这也是我第二遍读《精通比特币》这本书,我到现在才明白“书读百遍其义自见”的这样浅显的道理。要是我的文章对你有所帮助,那将是我莫大的荣幸。
网友评论