6 from twisted.internet import defer
7 from lib.exceptions import SubmitException
10 log = stratum.logger.get_logger('template_registry')
12 from mining.interfaces import Interfaces
13 from extranonce_counter import ExtranonceCounter
15 class JobIdGenerator(object):
16 '''Generate pseudo-unique job_id. It does not need to be absolutely unique,
17 because pool sends "clean_jobs" flag to clients and they should drop all previous jobs.'''
23 if cls.counter % 0xffff == 0:
25 return "%x" % cls.counter
27 class TemplateRegistry(object):
28 '''Implements the main logic of the pool. Keep track
29 on valid block templates, provide internal interface for stratum
30 service and implements block validation and submits.'''
32 def __init__(self, block_template_class, coinbaser, bitcoin_rpc, instance_id,
35 self.jobs = weakref.WeakValueDictionary()
37 self.extranonce_counter = ExtranonceCounter(instance_id)
38 self.extranonce2_size = block_template_class.coinbase_transaction_class.extranonce_size \
39 - self.extranonce_counter.get_size()
41 self.coinbaser = coinbaser
42 self.block_template_class = block_template_class
43 self.bitcoin_rpc = bitcoin_rpc
44 self.on_block_callback = on_block_callback
46 self.last_block = None
47 self.update_in_progress = False
48 self.last_update = None
50 # Create first block template on startup
53 def get_new_extranonce1(self):
54 '''Generates unique extranonce1 (e.g. for newly
55 subscribed connection.'''
56 return self.extranonce_counter.get_new_bin()
58 def get_last_broadcast_args(self):
59 '''Returns arguments for mining.notify
60 from last known template.'''
61 return self.last_block.broadcast_args
63 def add_template(self, block):
64 '''Adds new template to the registry.
65 It also clean up templates which should
66 not be used anymore.'''
68 prevhash = block.prevhash_hex
70 if prevhash in self.prevhashes.keys():
74 self.prevhashes[prevhash] = []
76 # Blocks sorted by prevhash, so it's easy to drop
77 # them on blockchain update
78 self.prevhashes[prevhash].append(block)
80 # Weak reference for fast lookup using job_id
81 self.jobs[block.job_id] = block
83 # Use this template for every new request
84 self.last_block = block
86 # Drop templates of obsolete blocks
87 for ph in self.prevhashes.keys():
89 del self.prevhashes[ph]
91 log.info("New template for %s" % prevhash)
92 self.on_block_callback(new_block)
93 #from twisted.internet import reactor
94 #reactor.callLater(10, self.on_block_callback, new_block)
96 def update_block(self):
97 '''Registry calls the getblocktemplate() RPC
98 and build new block template.'''
100 if self.update_in_progress:
101 # Block has been already detected
104 self.update_in_progress = True
105 self.last_update = Interfaces.timestamper.time()
107 d = self.bitcoin_rpc.getblocktemplate()
108 d.addCallback(self._update_block)
109 d.addErrback(self._update_block_failed)
111 def _update_block_failed(self, failure):
112 log.error(str(failure))
113 self.update_in_progress = False
115 def _update_block(self, data):
116 start = Interfaces.timestamper.time()
118 template = self.block_template_class(Interfaces.timestamper, self.coinbaser, JobIdGenerator.get_new_id())
119 template.fill_from_rpc(data)
120 self.add_template(template)
122 log.info("Update finished, %.03f sec, %d txes" % \
123 (Interfaces.timestamper.time() - start, len(template.vtx)))
125 self.update_in_progress = False
128 def diff_to_target(self, difficulty):
129 '''Converts difficulty to target'''
130 diff1 = 0x00000000ffff0000000000000000000000000000000000000000000000000000
131 return diff1 / difficulty
133 def get_job(self, job_id):
134 '''For given job_id returns BlockTemplate instance or None'''
136 j = self.jobs[job_id]
138 log.info("Job id '%s' not found" % job_id)
141 # Now we have to check if job is still valid.
142 # Unfortunately weak references are not bulletproof and
143 # old reference can be found until next run of garbage collector.
144 if j.prevhash_hex not in self.prevhashes:
145 log.info("Prevhash of job '%s' is unknown" % job_id)
148 if j not in self.prevhashes[j.prevhash_hex]:
149 log.info("Job %s is unknown" % job_id)
154 def submit_share(self, job_id, worker_name, extranonce1_bin, extranonce2, ntime, nonce,
156 '''Check parameters and finalize block template. If it leads
157 to valid block candidate, asynchronously submits the block
158 back to the bitcoin network.
160 - extranonce1_bin is binary. No checks performed, it should be from session data
161 - job_id, extranonce2, ntime, nonce - in hex form sent by the client
162 - difficulty - decimal number from session, again no checks performed
163 - submitblock_callback - reference to method which receive result of submitblock()
166 # Check if extranonce2 looks correctly. extranonce2 is in hex form...
167 if len(extranonce2) != self.extranonce2_size * 2:
168 raise SubmitException("Incorrect size of extranonce2. Expected %d chars" % (self.extranonce2_size*2))
171 job = self.get_job(job_id)
173 raise SubmitException("Job '%s' not found" % job_id)
175 # Check if ntime looks correct
177 raise SubmitException("Incorrect size of ntime. Expected 8 chars")
179 if not job.check_ntime(int(ntime, 16)):
180 raise SubmitException("Ntime out of range")
184 raise SubmitException("Incorrect size of nonce. Expected 8 chars")
186 # Check for duplicated submit
187 if not job.register_submit(extranonce1_bin, extranonce2, ntime, nonce):
188 log.info("Duplicate from %s, (%s %s %s %s)" % \
189 (worker_name, binascii.hexlify(extranonce1_bin), extranonce2, ntime, nonce))
190 raise SubmitException("Duplicate share")
192 # Now let's do the hard work!
193 # ---------------------------
196 extranonce2_bin = binascii.unhexlify(extranonce2)
197 ntime_bin = binascii.unhexlify(ntime)
198 nonce_bin = binascii.unhexlify(nonce)
201 coinbase_bin = job.serialize_coinbase(extranonce1_bin, extranonce2_bin)
202 coinbase_hash = util.doublesha(coinbase_bin)
204 # 2. Calculate merkle root
205 merkle_root_bin = job.merkletree.withFirst(coinbase_hash)
206 merkle_root_int = util.uint256_from_str(merkle_root_bin)
208 # 3. Serialize header with given merkle, ntime and nonce
209 header_bin = job.serialize_header(merkle_root_int, ntime_bin, nonce_bin)
211 # 4. Reverse header and compare it with target of the user
212 hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
213 hash_int = util.uint256_from_str(hash_bin)
214 block_hash_hex = "%064x" % hash_int
215 header_hex = binascii.hexlify(header_bin)
217 target_user = self.diff_to_target(difficulty)
218 if hash_int > target_user:
219 raise SubmitException("Share is above target")
221 # Mostly for debugging purposes
222 target_info = self.diff_to_target(100000)
223 if hash_int <= target_info:
224 log.info("Yay, share with diff above 100000")
226 # 5. Compare hash with target of the network
227 if hash_int <= job.target:
228 # Yay! It is block candidate!
229 log.info("We found a block candidate! %s" % block_hash_hex)
231 # 6. Finalize and serialize block object
232 job.finalize(merkle_root_int, extranonce1_bin, extranonce2_bin, int(ntime, 16), int(nonce, 16))
234 if not job.is_valid():
236 log.error("Final job validation failed!")
238 # 7. Submit block to the network
239 serialized = binascii.hexlify(job.serialize())
240 on_submit = self.bitcoin_rpc.submitblock(serialized)
242 return (header_hex, block_hash_hex, on_submit)
244 return (header_hex, block_hash_hex, None)