我使用hashlib在python中编写了一个简单的SHA256区块链挖掘算法。我在这里尝试做的是更改数据中的一个随机数,然后计算SHA256散列。只要散列的开头有预定义数量的零,它就会将散列及其对应的nonce输出到控制台。目标是在开始时有11个零。
import hashlib
import threading
#bn=block number d=input data, ph=previous hash
bn = 1
d = "mydata"
ph = "0000000000000000000000000000000000000000000000000000000000000000"
class MyThread(threading.Thread):
def __init__(self, threadID, begin, end):
threading.Thread.__init__(self)
self.threadID = threadID
self.end = end
self.begin = begin
def run(self):
for val in range(self.begin, self.end):
mine(self.threadID, val)
print("done " + str(self.threadID))
#hashing function
def mine(id, x):
hash = hashlib.sha256((str(bn) + str(x) + str(d) + str(ph)).encode('utf-8')).hexdigest()
if hash.find("0000000", 0, 7) > -1:
# print(id)
print(x)
print(hash)
#now break it up and distribute it to the threads
#Possible SHA256 Combinations 8388608000000
pc = 8388608000000
#Number of desired Threads (more threads help more?)
nt = 704
#calculating the steps
step = round((pc)/(nt))
#starting the threads with each thread calculating a different range of nonces.
for x in range (1, nt):
thread = MyThread((x), (x-1)*(step), (x)*(step))
thread.start()我怎么才能加快速度呢?
目前,我在Intel8250u四核上运行,我可以轻松地获得开头为7个零的散列。然而,8个零已经花费了5个小时。有趣的是,只有大约20-30%的CPU被使用。我如何让它在所有线程并行运行的内核上运行?
你有没有别的办法可以让我加速这件事?我有更好的硬件(Threadripper 1920),但我担心单独的硬件不会给我带来300x - 4000x (最好的情况)的速度提升……
我的第一个想法是把它外包给GPU,因为我知道比特币挖掘从CPU发展到了GPU。在查看Numba时,我发现它不支持Hashlib。我还看到使用Pypy编译这个代码可能会加快速度?你们喜欢哪种方法?我很困惑..。
谢谢你对我这么耐心
发布于 2020-07-21 21:24:24
在这方面,Python有点奇怪。你在这里做的是多线程,而不是多处理。由于全局解释器锁,这些线程实际上并不是同时运行的。如果您想要实际并行运行计算,请查看multiprocessing module for Python。
编辑:正如贾里德提到的,由于现在大多数挖掘都是用specialized hardware完成的,所以在你的个人电脑上挖掘比特币不再有利可图。作为一个项目,这很酷,但我不期望它能让你赚钱。
https://stackoverflow.com/questions/63015399
复制相似问题