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