【发布时间】:2019-03-18 00:10:31
【问题描述】:
我正在做一个项目,我正在尝试创建一个非常简单的基于区块链的加密货币。这是我尝试散列块对象的方式的过度简化版本(显然Block 类的字段要复杂得多,但这是主要思想):
from Crypto.Hash import SHA
import json
from collections import OrderedDict
from random import random
class Block(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def to_dict(self):
d = OrderedDict({
'x' : self.x,
'y' : self.y,
'z' : self.z
})
return d
def json(self):
return json.dumps(self.to_dict())
def hash(self):
return SHA.new(self.json().encode('utf8')).hexdigest()
# driver code to test hashing
while True:
x, y, z = [random() for _ in range(3)]
b = Block(x, y, z)
if not bin(int(b.hash(), 16)).startswith('0b1'):
break
上面的驱动程序永远循环。问题是(无论字段的数量和/或值如何)哈希总是以0b1 开头,这与挖矿难度和工作量证明的整个概念相混淆。更重要的是,这不是散列函数的预期行为。我错过了什么?
【问题讨论】:
标签: python python-3.x hash pycrypto