首页 > 解决方案 > 哈希挖掘多处理

问题描述

我正在尝试解决 python 中的挖掘问题。给定一个字符串s和一个整数z,我必须找到以零结尾的最小字符串n,其中附加到. 我写了以下代码:sha256(sha256(x))zxns

from hashlib import sha256
from multiprocessing import Pool

def solve(string, zeros, cores):
    with Pool(cores) as p:
        for i in range(cores):
            result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)

    return result

def sub_solve(s, z, n0, cores):
    n = n0 - 1
    d = ""
    while d[:-z] != "0"*z:
        n += cores
        s1 = (s + str(n)).encode()
        h1 = sha256(s1)
        h2 = sha256(h1.digest())
        d = h2.hexdigest()
        if n % 100000 == 0:
            print("%d: %s" %(n,d))
    return n

调用solve,它应该在不同的内核中执行并行调用string = s,每个内核应该解决不同的问题。当其中一个工作进程解决问题时,整个池应终止工作。当我运行时,我得到这个输出:zeros = zcores = number of cores to usesub_solvensolve

>>> pow.solve("asd",2,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\Desktop\pow.py", line 7, in solve
    result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 355, in apply_async
    raise ValueError("Pool not running")
ValueError: Pool not running

我该如何解决这个问题?

标签: pythonhashmultiprocessingpoolbrute-force

解决方案


第一次迭代后,池由于回调而终止。因此,在下一次迭代中,没有运行池。要解决这个问题,您必须先运行循环,然后再使用with语句。

with用循环交换语句,for如下所示:

from hashlib import sha256
from multiprocessing import Pool

def solve(string, zeros, cores):
    for i in range(cores):
        with Pool(cores) as p:            
            result = p.apply_async(sub_solve, args=(string, zeros, i, cores), callback = p.terminate)

    return result

def sub_solve(s, z, n0, cores):
    n = n0 - 1
    d = ""
    while d[:-z] != "0"*z:
        n += cores
        s1 = (s + str(n)).encode()
        h1 = sha256(s1)
        h2 = sha256(h1.digest())
        d = h2.hexdigest()
        if n % 100000 == 0:
            print("%d: %s" %(n,d))
    return n

推荐阅读