Initial commit
[stratum-mining.git] / mining / subscription.py
1 from stratum.pubsub import Pubsub, Subscription
2 from mining.interfaces import Interfaces
3
4 import stratum.logger
5 log = stratum.logger.get_logger('subscription')
6
7 class MiningSubscription(Subscription):
8     '''This subscription object implements
9     logic for broadcasting new jobs to the clients.'''
10     
11     event = 'mining.notify'
12     
13     @classmethod
14     def on_block(cls, is_new_block):
15         '''This is called when TemplateRegistry registers
16            new block which we have to broadcast clients.'''
17         
18         start = Interfaces.timestamper.time()
19         
20         clean_jobs = is_new_block
21         (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = \
22                         Interfaces.template_registry.get_last_broadcast_args()
23         
24         # Push new job to subscribed clients
25         cls.emit(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
26         
27         cnt = Pubsub.get_subscription_count(cls.event)
28         log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (Interfaces.timestamper.time() - start)))
29         
30     def _finish_after_subscribe(self, result):
31         '''Send new job to newly subscribed client'''
32         try:        
33             (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = \
34                         Interfaces.template_registry.get_last_broadcast_args()
35         except Exception:
36             log.error("Template not ready yet")
37             return result
38         
39         # Force set higher difficulty
40         # TODO
41         #self.connection_ref().rpc('mining.set_difficulty', [2,], is_notification=True)
42         
43         # Force client to remove previous jobs if any (eg. from previous connection)
44         clean_jobs = True
45         self.emit_single(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
46         
47         return result
48                 
49     def after_subscribe(self, *args):
50         '''This will send new job to the client *after* he receive subscription details.
51         on_finish callback solve the issue that job is broadcasted *during*
52         the subscription request and client receive messages in wrong order.'''
53         self.connection_ref().on_finish.addCallback(self._finish_after_subscribe)