5330662dae546f087edd21a19c2d9f5996e6ee28
[stratum-mining.git] / mining / service.py
1 import binascii
2 from twisted.internet import defer
3
4 from stratum.services import GenericService, admin
5 from stratum.custom_exceptions import ServiceException
6 from stratum.pubsub import Pubsub
7 from interfaces import Interfaces
8 from subscription import MiningSubscription
9
10 import stratum.logger
11 log = stratum.logger.get_logger('mining')
12
13 class SubmitException(ServiceException):
14     pass
15                 
16 class MiningService(GenericService):
17     '''This service provides public API for Stratum mining proxy
18     or any Stratum-compatible miner software.
19     
20     Warning - any callable argument of this class will be propagated
21     over Stratum protocol for public audience!'''
22     
23     service_type = 'mining'
24     service_vendor = 'stratum'
25     is_default = True
26     
27     @admin
28     def update_block(self):
29         '''Connect this RPC call to 'bitcoind -blocknotify' for 
30         instant notification about new block on the network.
31         See blocknotify.sh in /scripts/ for more info.'''
32         Interfaces.template_registry.update_block()
33         return True 
34     
35     def authorize(self, worker_name, worker_password):
36         '''Let authorize worker on this connection.'''
37         
38         session = self.connection_ref().get_session()
39         session.setdefault('authorized', {})
40         
41         if Interfaces.worker_manager.authorize(worker_name, worker_password):
42             session['authorized'][worker_name] = worker_password
43             return True
44         
45         else:
46             if worker_name in session['authorized']:
47                 del session['authorized'][worker_name]
48             return False
49         
50     def subscribe(self):
51         '''Subscribe for receiving mining jobs. This will
52         return subscription details, extranonce1_hex and extranonce2_size'''
53         
54         extranonce1 = Interfaces.template_registry.get_new_extranonce1()
55         extranonce2_size = Interfaces.template_registry.extranonce2_size
56
57         session = self.connection_ref().get_session()
58         session['extranonce1'] = extranonce1
59         session['difficulty'] = 1 # Following protocol specs, default diff is 1
60
61         extranonce1_hex = binascii.hexlify(extranonce1)
62             
63         return Pubsub.subscribe(self.connection_ref(), MiningSubscription()) + (extranonce1_hex, extranonce2_size)
64     
65     '''    
66     def submit(self, worker_name, job_id, extranonce2, ntime, nonce):
67         import time
68         start = time.time()
69         
70         for x in range(100):
71             try:
72                 ret = self.submit2(worker_name, job_id, extranonce2, ntime, nonce)
73             except:
74                 pass
75             
76         log.info("LEN %.03f" % (time.time() - start))
77         return ret
78     '''
79     
80     def submit(self, worker_name, job_id, extranonce2, ntime, nonce):
81         '''Try to solve block candidate using given parameters.'''
82         
83         session = self.connection_ref().get_session()
84         session.setdefault('authorized', {})
85         
86         # Check if worker is authorized to submit shares
87         if not Interfaces.worker_manager.authorize(worker_name,
88                         session['authorized'].get(worker_name)):
89             raise SubmitException("Worker is not authorized")
90
91         # Check if extranonce1 is in connection session
92         extranonce1_bin = session.get('extranonce1', None)
93         if not extranonce1_bin:
94             raise SubmitException("Connection is not subscribed for mining")
95         
96         difficulty = session['difficulty']
97
98         # This checks if submitted share meet all requirements
99         # and it is valid proof of work.
100         (is_valid, reason, block_header, block_hash) = Interfaces.template_registry.submit_share(job_id,
101                                                 worker_name, extranonce1_bin, extranonce2, ntime, nonce, difficulty,
102                                                 Interfaces.share_manager.on_submit_block)
103    
104         # block_header and block_hash may be None when submitted data are corrupted     
105         Interfaces.share_manager.on_submit_share(worker_name, block_header, block_hash, difficulty,
106                                                  Interfaces.timestamper.time(), is_valid)
107         
108         if not is_valid:
109             raise SubmitException(reason)
110
111         return True
112             
113     # Service documentation for remote discovery
114     update_block.help_text = "Notify Stratum server about new block on the network."
115     update_block.params = [('password', 'string', 'Administrator password'),]
116     
117     authorize.help_text = "Authorize worker for submitting shares on this connection."
118     authorize.params = [('worker_name', 'string', 'Name of the worker, usually in the form of user_login.worker_id.'),
119                         ('worker_password', 'string', 'Worker password'),]
120     
121     subscribe.help_text = "Subscribes current connection for receiving new mining jobs."
122     subscribe.params = []
123     
124     submit.help_text = "Submit solved share back to the server. Excessive sending of invalid shares "\
125                        "or shares above indicated target (see Stratum mining docs for set_target()) may lead "\
126                        "to temporary or permanent ban of user,worker or IP address."
127     submit.params = [('worker_name', 'string', 'Name of the worker, usually in the form of user_login.worker_id.'),
128                      ('job_id', 'string', 'ID of job (received by mining.notify) which the current solution is based on.'),
129                      ('extranonce2', 'string', 'hex-encoded big-endian extranonce2, length depends on extranonce2_size from mining.notify.'),
130                      ('ntime', 'string', 'UNIX timestamp (32bit integer, big-endian, hex-encoded), must be >= ntime provided by mining,notify and <= current time'),
131                      ('nonce', 'string', '32bit integer, hex-encoded, big-endian'),]
132