【发布时间】:2015-12-08 20:56:53
【问题描述】:
我正在尝试在 python 中编写一个简单的工作量证明 nonce-finder。
def proof_of_work(b, nBytes):
nonce = 0
# while the first nBytes of hash(b + nonce) are not 0
while sha256(b + uint2bytes(nonce))[:nBytes] != bytes(nBytes):
nonce = nonce + 1
return nonce
现在我正在尝试进行多处理,因此它可以使用所有 CPU 内核并更快地找到 nonce。我的想法是使用multiprocessing.Pool 并多次执行函数proof_of_work,传递两个参数num_of_cpus_running 和this_cpu_id,如下所示:
def proof_of_work(b, nBytes, num_of_cpus_running, this_cpu_id):
nonce = this_cpu_id
while sha256(b + uint2bytes(nonce))[:nBytes] != bytes(nBytes):
nonce = nonce + num_of_cpus_running
return nonce
所以,如果有 4 个核心,每个核心都会像这样计算 nonce:
core 0: 0, 4, 8, 16, 32 ...
core 1: 1, 5, 9, 17, 33 ...
core 2: 2, 6, 10, 18, 34 ...
core 3: 3, 7, 15, 31, 38 ...
所以,我必须重写proof_of_work,所以当任何进程找到随机数时,其他人都停止寻找随机数,考虑到找到的随机数必须是所需字节为 0 的最低值. 如果 CPU 因某种原因加速,并返回高于最低有效 nonce 的有效 nonce,则工作证明无效。
我唯一不知道该怎么做的是,只有在进程 B 发现的 nonce 低于进程 A 现在正在计算的 nonce 时,进程 A 才会停止的部分。如果它更高, A 一直在计算(以防万一),直到它到达 B 提供的 nonce。
我希望我正确地解释了自己。另外,如果我写的任何东西有更快的实现,我很想听听。非常感谢!
【问题讨论】:
-
@MaartenBodewes 恐怕我不明白你的意思,也许我还是太菜鸟程序员xD。 cpu_id 只是我分配给每个进程的一个数字。首先我得到 cpu 核心的数量
x = multiprocessing.cpu_count()然后启动 x 个进程,每个进程都有一个不同的 ID,只是递增 1。希望我没弄错。 -
对不起,这只是我的一个误会。我从未深入研究过这些工作证明协议。我鄙视比特币之类的东西——我不喜欢将能量转化为金钱的协议,我更喜欢它。
-
@MaartenBodewes 工作证明不仅用于比特币。我用它来防止 DDoS 攻击。
标签: python cryptography sha256 python-multiprocessing nonce