UniqueSessionIdManager: Support for delaying releases of session ids, and picking...
[bitcoin:eloipool.git] / jsonrpcserver.py
1 # Eloipool - Python Bitcoin pool server
2 # Copyright (C) 2011-2012  Luke Dashjr <luke-jr+eloipool@utopios.org>
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as
6 # published by the Free Software Foundation, either version 3 of the
7 # License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 from binascii import b2a_hex
18 import httpserver
19 import json
20 import logging
21 import networkserver
22 import socket
23 from time import time
24 import traceback
25
26 WithinLongpoll = httpserver.AsyncRequest
27
28 class _SentJSONError(BaseException):
29         def __init__(self, rv):
30                 self.rv = rv
31
32 class JSONRPCHandler(httpserver.HTTPHandler):
33         default_quirks = {
34                 'NELH': None,  # FIXME: identify which clients have a problem with this
35         }
36         
37         LPHeaders = {
38                 'X-Long-Polling': None,
39         }
40         
41         JSONRPCURIs = (b'/', b'/LP', b'/LP/')
42         
43         logger = logging.getLogger('JSONRPCHandler')
44         
45         def final_init(server):
46                 pass
47         
48         def sendReply(self, status=200, body=b'', headers=None, *a, **ka):
49                 headers = dict(headers) if headers else {}
50                 if body and body[0] == 123:  # b'{'
51                         headers.setdefault('Content-Type', 'application/json')
52                 if status == 200 and self.path in self.JSONRPCURIs:
53                         if not body:
54                                 headers.setdefault('Content-Type', 'application/json')
55                         headers.setdefault('X-Long-Polling', '/LP')
56                 return super().sendReply(status, body, headers, *a, **ka)
57         
58         def fmtError(self, reason = '', code = 100):
59                 reason = json.dumps(reason)
60                 reason = r'{"result":null,"id":null,"error":{"name":"JSONRPCError","code":%d,"message":%s}}' % (code, reason)
61                 reason = reason.encode('utf8')
62                 return reason
63         
64         def doError(self, reason = '', code = 100):
65                 reason = self.fmtError(reason, code)
66                 return self.sendReply(500, reason)
67         
68         def checkAuthentication(self, un, pw):
69                 return bool(un)
70         
71         _MidstateNotAdv = (b'phoenix', b'poclbm', b'gminor')
72         def doHeader_user_agent(self, value):
73                 self.reqinfo['UA'] = value
74                 quirks = self.quirks
75                 (UA, v, *x) = value.split(b'/', 1) + [None]
76                 
77                 # Temporary HACK to keep working with older gmp-proxy
78                 # NOTE: This will go away someday.
79                 if UA == b'AuthServiceProxy':
80                         # SubmitBlock Boolean
81                         quirks['SBB'] = None
82                 
83                 try:
84                         if v[0] == b'v': v = v[1:]
85                         v = tuple(map(int, v.split(b'.'))) + (0,0,0)
86                 except:
87                         pass
88                 if UA in self._MidstateNotAdv:
89                         if UA == b'phoenix':
90                                 if v != (1, 50, 0):
91                                         quirks['midstate'] = None
92                                 if v[0] < 2 and v[1] < 8 and v[2] < 1:
93                                         quirks['NELH'] = None
94                         else:
95                                 quirks['midstate'] = None
96         
97         def doHeader_x_minimum_wait(self, value):
98                 self.reqinfo['MinWait'] = int(value)
99         
100         def doHeader_x_mining_extensions(self, value):
101                 self.extensions = value.decode('ascii').lower().split(' ')
102         
103         def processLP(self, lpid):
104                 lpw = self.server.LPId
105                 if isinstance(lpid, str):
106                         if lpw != lpid:
107                                 return
108                 self.doLongpoll()
109         
110         def doLongpoll(self, *a):
111                 timeNow = time()
112                 
113                 self._LP = True
114                 self._LPCall = a
115                 if 'NELH' not in self.quirks:
116                         # [NOT No] Early Longpoll Headers
117                         self.sendReply(200, body=None, headers=self.LPHeaders)
118                         self.push(b"1\r\n{\r\n")
119                         self.changeTask(self._chunkedKA, timeNow + 45)
120                 else:
121                         self.changeTask(None)
122                 
123                 waitTime = self.reqinfo.get('MinWait', 15)  # TODO: make default configurable
124                 self.waitTime = waitTime + timeNow
125                 
126                 totfromme = self.LPTrack()
127                 self.server._LPClients[id(self)] = self
128                 self.logger.debug("New LP client; %d total; %d from %s" % (len(self.server._LPClients), totfromme, self.remoteHost))
129                 
130                 raise WithinLongpoll
131         
132         def _chunkedKA(self):
133                 # Keepalive via chunked transfer encoding
134                 self.push(b"1\r\n \r\n")
135                 self.changeTask(self._chunkedKA, time() + 45)
136         
137         def LPTrack(self):
138                 myip = self.remoteHost
139                 if myip not in self.server.LPTracking:
140                         self.server.LPTracking[myip] = 0
141                 self.server.LPTracking[myip] += 1
142                 
143                 myuser = self.Username
144                 if myuser not in self.server.LPTrackingByUser:
145                         self.server.LPTrackingByUser[myuser] = 0
146                 self.server.LPTrackingByUser[myuser] += 1
147                 
148                 return self.server.LPTracking[myip]
149         
150         def LPUntrack(self):
151                 self.server.LPTracking[self.remoteHost] -= 1
152                 self.server.LPTrackingByUser[self.Username] -= 1
153         
154         def cleanupLP(self):
155                 # Called when the connection is closed
156                 if not self._LP:
157                         return
158                 self.changeTask(None)
159                 try:
160                         del self.server._LPClients[id(self)]
161                 except KeyError:
162                         pass
163                 self.LPUntrack()
164         
165         def wakeLongpoll(self, wantClear = False):
166                 now = time()
167                 if now < self.waitTime:
168                         self.changeTask(lambda: self.wakeLongpoll(wantClear), self.waitTime)
169                         return
170                 else:
171                         self.changeTask(None)
172                 
173                 self.LPUntrack()
174                 
175                 self.server.tls.wantClear = wantClear
176                 try:
177                         rv = self._doJSON_i(*self._LPCall, longpoll=True)
178                 except WithinLongpoll:
179                         # Not sure why this would happen right now, but handle it sanely...
180                         return
181                 finally:
182                         self.server.tls.wantClear = False
183                 if 'NELH' not in self.quirks:
184                         rv = rv[1:]  # strip the '{' we already sent
185                         self.push(('%x' % len(rv)).encode('utf8') + b"\r\n" + rv + b"\r\n0\r\n\r\n")
186                         self.reset_request()
187                         return
188                 
189                 try:
190                         self.sendReply(200, body=rv, headers=self.LPHeaders, tryCompression=False)
191                         raise httpserver.RequestNotHandled
192                 except httpserver.RequestHandled:
193                         # Expected
194                         pass
195                 finally:
196                         self.reset_request()
197         
198         def _doJSON_i(self, reqid, method, params, longpoll = False):
199                 try:
200                         rv = getattr(self, method)(*params)
201                 except WithinLongpoll:
202                         self._LPCall = (reqid, method, params)
203                         raise
204                 except Exception as e:
205                         self.logger.error(("Error during JSON-RPC call (UA=%s, IP=%s): %s%s\n" % (self.reqinfo.get('UA'), self.remoteHost, method, params)) + traceback.format_exc())
206                         efun = self.fmtError if longpoll else self.doError
207                         return efun(r'Service error: %s' % (e,))
208                 try:
209                         rv.setdefault('submitold', True)
210                 except:
211                         pass
212                 rv = {'id': reqid, 'error': None, 'result': rv}
213                 try:
214                         rv = json.dumps(rv)
215                 except:
216                         efun = self.fmtError if longpoll else self.doError
217                         return efun(r'Error encoding reply in JSON')
218                 rv = rv.encode('utf8')
219                 return rv if longpoll else self.sendReply(200, rv, headers=self._JSONHeaders)
220         
221         def doJSON(self, data, longpoll = False):
222                 # TODO: handle JSON errors
223                 try:
224                         data = data.decode('utf8')
225                 except UnicodeDecodeError as e:
226                         return self.doError(str(e))
227                 if longpoll and not data:
228                         self.JSONRPCId = jsonid = 1
229                         self.JSONRPCMethod = 'getwork'
230                         self._JSONHeaders = {}
231                         return self.doLongpoll(1, 'doJSON_getwork', ())
232                 try:
233                         data = json.loads(data)
234                         method = str(data['method']).lower()
235                         self.JSONRPCId = jsonid = data['id']
236                         self.JSONRPCMethod = method
237                         method = 'doJSON_' + method
238                 except ValueError:
239                         return self.doError(r'Parse error')
240                 except TypeError:
241                         return self.doError(r'Bad call')
242                 if not hasattr(self, method):
243                         return self.doError(r'Procedure not found')
244                 # TODO: handle errors as JSON-RPC
245                 self._JSONHeaders = {}
246                 params = data.setdefault('params', ())
247                 procfun = self._doJSON_i
248                 if longpoll and not params:
249                         procfun = self.doLongpoll
250                 return procfun(jsonid, method, params)
251         
252         def handle_close(self):
253                 self.cleanupLP()
254                 super().handle_close()
255         
256         def handle_request(self):
257                 if not self.method in (b'GET', b'POST'):
258                         return self.sendReply(405)
259                 if not self.path in self.JSONRPCURIs:
260                         if isinstance(self.path, bytes) and self.path[:5] == b'/src/':
261                                 return self.handle_src_request()
262                         return self.sendReply(404)
263                 if not self.Username:
264                         return self.doAuthenticate()
265                 try:
266                         data = b''.join(self.incoming)
267                         return self.doJSON(data, self.path[:3] == b'/LP')
268                 except socket.error:
269                         raise
270                 except WithinLongpoll:
271                         raise
272                 except httpserver.RequestHandled:
273                         raise
274                 except:
275                         self.logger.error(traceback.format_exc())
276                         return self.doError('uncaught error')
277         
278         def reset_request(self):
279                 self._LP = False
280                 self.JSONRPCMethod = None
281                 super().reset_request()
282         
283 setattr(JSONRPCHandler, 'doHeader_user-agent', JSONRPCHandler.doHeader_user_agent);
284 setattr(JSONRPCHandler, 'doHeader_x-minimum-wait', JSONRPCHandler.doHeader_x_minimum_wait);
285 setattr(JSONRPCHandler, 'doHeader_x-mining-extensions', JSONRPCHandler.doHeader_x_mining_extensions);
286
287 JSONRPCListener = networkserver.NetworkListener
288
289 class JSONRPCServer(networkserver.AsyncSocketServer):
290         logger = logging.getLogger('JSONRPCServer')
291         
292         waker = True
293         
294         def __init__(self, *a, **ka):
295                 ka.setdefault('RequestHandlerClass', JSONRPCHandler)
296                 super().__init__(*a, **ka)
297                 
298                 self.SecretUser = None
299                 self.ShareTarget = 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
300                 
301                 self._LPId = 0
302                 self.LPId = '%d' % (time(),)
303                 self.LPRequest = False
304                 self._LPClients = {}
305                 self._LPWaitTime = time() + 15
306                 
307                 self.LPTracking = {}
308                 self.LPTrackingByUser = {}
309         
310         def final_init(self):
311                 JSONRPCHandler.final_init(self)
312         
313         def pre_schedule(self):
314                 if self.LPRequest == 1:
315                         self._LPsch()
316         
317         def wakeLongpoll(self, wantClear = False):
318                 if self.LPRequest:
319                         self.logger.info('Ignoring longpoll attempt while another is waiting')
320                         return
321                 self._LPId += 1
322                 self.LPId = '%d %d' % (time(), self._LPId)
323                 self._LPWantClear = wantClear
324                 self.LPRequest = 1
325                 self.wakeup()
326         
327         def _LPsch(self):
328                 now = time()
329                 if self._LPWaitTime > now:
330                         delay = self._LPWaitTime - now
331                         self.logger.info('Waiting %.3g seconds to longpoll' % (delay,))
332                         self.schedule(self._actualLP, self._LPWaitTime)
333                         self.LPRequest = 2
334                 else:
335                         self._actualLP()
336         
337         def _actualLP(self):
338                 self.LPRequest = False
339                 C = tuple(self._LPClients.values())
340                 self._LPClients = {}
341                 if not C:
342                         self.logger.info('Nobody to longpoll')
343                         return
344                 OC = len(C)
345                 self.logger.debug("%d clients to wake up..." % (OC,))
346                 
347                 now = time()
348                 
349                 for ic in C:
350                         self.lastHandler = ic
351                         try:
352                                 ic.wakeLongpoll(self._LPWantClear)
353                         except socket.error:
354                                 OC -= 1
355                                 # Ignore socket errors; let the main event loop take care of them later
356                         except:
357                                 OC -= 1
358                                 self.logger.debug('Error waking longpoll handler:\n' + traceback.format_exc())
359                 
360                 self._LPWaitTime = time()
361                 self.logger.info('Longpoll woke up %d clients in %.3f seconds' % (OC, self._LPWaitTime - now))
362                 self._LPWaitTime += 5  # TODO: make configurable: minimum time between longpolls
363         
364         def TopLPers(self, n = 0x10):
365                 tmp = list(self.LPTracking.keys())
366                 tmp.sort(key=lambda k: self.LPTracking[k])
367                 for jerk in map(lambda k: (k, self.LPTracking[k]), tmp[-n:]):
368                         print(jerk)
369         
370         def TopLPersByUser(self, n = 0x10):
371                 tmp = list(self.LPTrackingByUser.keys())
372                 tmp.sort(key=lambda k: self.LPTrackingByUser[k])
373                 for jerk in map(lambda k: (k, self.LPTrackingByUser[k]), tmp[-n:]):
374                         print(jerk)