33import hashlib
44import struct
55import time
6- import multiprocessing
76import os
87
98def get_input (prompt , data_type = str ):
@@ -111,7 +110,7 @@ def calculate_difficulty(hash_result):
111110 difficulty = max_target / hash_int
112111 return difficulty
113112
114- def mine_worker (job , target , extranonce1 , extranonce2_size , nonce_start , nonce_end , result_queue , stop_event ):
113+ def mine (job , target , extranonce1 , extranonce2_size ):
115114 job_id , prevhash , coinb1 , coinb2 , merkle_branch , version , nbits , ntime , clean_jobs = job
116115
117116 extranonce2 = struct .pack ('<Q' , 0 )[:extranonce2_size ]
@@ -125,10 +124,7 @@ def mine_worker(job, target, extranonce1, extranonce2_size, nonce_start, nonce_e
125124 block_header = (version + prevhash + merkle_root [::- 1 ].hex () + ntime + nbits ).encode ('utf-8' )
126125 target_bin = bytes .fromhex (target )[::- 1 ]
127126
128- for nonce in range (nonce_start , nonce_end ):
129- if stop_event .is_set ():
130- return
131-
127+ for nonce in range (2 ** 32 ):
132128 nonce_bin = struct .pack ('<I' , nonce )
133129 hash_result = hashlib .sha256 (hashlib .sha256 (block_header + nonce_bin ).digest ()).digest ()
134130
@@ -137,30 +133,7 @@ def mine_worker(job, target, extranonce1, extranonce2_size, nonce_start, nonce_e
137133 if difficulty > min_diff :
138134 print (f"Nonce found: { nonce } , Difficulty: { difficulty } " )
139135 print (f"Hash: { hash_result [::- 1 ].hex ()} " )
140- result_queue .put ((job_id , extranonce2 , ntime , nonce ))
141- stop_event .set ()
142- return
143-
144- def mine (sock , job , target , extranonce1 , extranonce2_size ):
145- num_processes = multiprocessing .cpu_count ()
146- nonce_range = 2 ** 32 // num_processes
147- result_queue = multiprocessing .Queue ()
148- stop_event = multiprocessing .Event ()
149-
150- while not stop_event .is_set ():
151- processes = []
152- for i in range (num_processes ):
153- nonce_start = i * nonce_range
154- nonce_end = (i + 1 ) * nonce_range
155- p = multiprocessing .Process (target = mine_worker , args = (job , target , extranonce1 , extranonce2_size , nonce_start , nonce_end , result_queue , stop_event ))
156- processes .append (p )
157- p .start ()
158-
159- for p in processes :
160- p .join ()
161-
162- if not result_queue .empty ():
163- return result_queue .get ()
136+ return job_id , extranonce2 , ntime , nonce
164137
165138def submit_solution (sock , job_id , extranonce2 , ntime , nonce ):
166139 message = {
@@ -192,7 +165,7 @@ def submit_solution(sock, job_id, extranonce2, ntime, nonce):
192165 for response in receive_messages (sock ):
193166 if response ['method' ] == 'mining.notify' :
194167 job = response ['params' ]
195- result = mine (sock , job , job [6 ], extranonce1 , extranonce2_size )
168+ result = mine (job , job [6 ], extranonce1 , extranonce2_size )
196169 if result :
197170 submit_solution (sock , * result )
198171 except Exception as e :
0 commit comments