10 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
13 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
16 print_lock = threading.Lock()
18 args = [str(item) for item in args]
20 sys.stderr.write(timestr() + " " + " ".join(args) + "\n")
27 def __init__(self, config):
28 self.lock = threading.Lock()
33 print_log( "Stopping Stratum" )
42 class Processor(threading.Thread):
45 threading.Thread.__init__(self)
47 self.dispatcher = None
48 self.queue = queue.Queue()
50 def process(self, request):
53 def add_request(self, request):
54 self.queue.put(request)
56 def push_response(self, response):
57 #print "response", response
58 self.dispatcher.request_dispatcher.push_response(response)
61 while not self.shared.stopped():
62 request = self.queue.get(10000000000)
66 traceback.print_exc(file=sys.stdout)
68 print_log( "processor terminating")
74 def __init__(self, config):
75 self.shared = Shared(config)
76 self.request_dispatcher = RequestDispatcher(self.shared)
77 self.request_dispatcher.start()
78 self.response_dispatcher = \
79 ResponseDispatcher(self.shared, self.request_dispatcher)
80 self.response_dispatcher.start()
82 def register(self, prefix, processor):
83 processor.dispatcher = self
84 processor.shared = self.shared
86 self.request_dispatcher.processors[prefix] = processor
90 class RequestDispatcher(threading.Thread):
92 def __init__(self, shared):
94 threading.Thread.__init__(self)
96 self.request_queue = queue.Queue()
97 self.response_queue = queue.Queue()
98 self.internal_ids = {}
100 self.lock = threading.Lock()
104 def push_response(self, item):
105 self.response_queue.put(item)
107 def pop_response(self):
108 return self.response_queue.get()
110 def push_request(self, session, item):
111 self.request_queue.put((session,item))
113 def pop_request(self):
114 return self.request_queue.get()
116 def get_session_by_address(self, address):
117 for x in self.sessions:
118 if x.address == address:
121 def get_session_id(self, internal_id):
123 return self.internal_ids.pop(internal_id)
125 def store_session_id(self, session, msgid):
127 self.internal_ids[self.internal_id] = session, msgid
129 self.internal_id += 1
133 if self.shared is None:
134 raise TypeError("self.shared not set in Processor")
135 while not self.shared.stopped():
136 session, request = self.pop_request()
138 self.do_dispatch(session, request)
140 traceback.print_exc(file=sys.stdout)
148 def do_dispatch(self, session, request):
149 """ dispatch request to the relevant processor """
151 method = request['method']
152 params = request.get('params',[])
153 suffix = method.split('.')[-1]
155 if session is not None:
156 is_new = session.protocol_version >= 0.5
157 if suffix == 'subscribe':
158 session.subscribe_to_service(method, params)
160 # store session and id locally
161 request['id'] = self.store_session_id(session, request['id'])
163 prefix = request['method'].split('.')[0]
165 p = self.processors[prefix]
167 print_log( "error: no processor for", prefix)
170 p.add_request(request)
172 if method in ['server.version']:
173 session.version = params[0]
175 session.protocol_version = float(params[1])
179 #if session.protocol_version < 0.6:
180 # print_log("stopping session from old client", session.protocol_version)
183 def get_sessions(self):
188 def add_session(self, session):
190 self.sessions.append(session)
192 def collect_garbage(self):
193 # Deep copy entire sessions list and blank it
194 # This is done to minimise lock contention
196 sessions = self.sessions[:]
198 for session in sessions:
199 if not session.stopped():
200 # If session is still alive then re-add it back
201 # to our internal register
202 self.add_session(session)
208 self._stopped = False
209 self.lock = threading.Lock()
210 self.subscriptions = []
213 self.version = 'unknown'
214 self.protocol_version = 0.
215 self.time = time.time()
216 threading.Timer(2, self.info).start()
218 # Debugging method. Doesn't need to be threadsafe.
220 for sub in self.subscriptions:
223 if method == 'blockchain.address.subscribe':
229 if self.subscriptions:
230 print_log( "%4s"%self.name, "%15s"%self.address, "%35s"%addr, "%3d"%len(self.subscriptions), self.version )
236 def subscribe_to_service(self, method, params):
237 subdesc = self.build_subdesc(method, params)
239 if subdesc is not None:
240 self.subscriptions.append(subdesc)
242 # subdesc = A subscription description
244 def build_subdesc(method, params):
245 if method == "blockchain.numblocks.subscribe":
247 elif method == "blockchain.headers.subscribe":
249 elif method in ["blockchain.address.subscribe"]:
253 return method, params[0]
257 def contains_subscription(self, subdesc):
259 return subdesc in self.subscriptions
262 class ResponseDispatcher(threading.Thread):
264 def __init__(self, shared, request_dispatcher):
266 self.request_dispatcher = request_dispatcher
267 threading.Thread.__init__(self)
271 while not self.shared.stopped():
275 response = self.request_dispatcher.pop_response()
276 #print "pop response", response
277 internal_id = response.get('id')
278 method = response.get('method')
279 params = response.get('params')
282 if internal_id is None: # and method is not None and params is not None:
283 found = self.notification(method, params, response)
284 if not found and method == 'blockchain.address.subscribe':
285 params2 = [self.shared.config.get('server','password')] + params
286 self.request_dispatcher.push_request(None,{'method':method.replace('.subscribe', '.unsubscribe'), 'params':params2, 'id':None})
289 elif internal_id is not None:
290 self.send_response(internal_id, response)
292 print_log( "no method", response)
294 def notification(self, method, params, response):
295 subdesc = Session.build_subdesc(method, params)
297 for session in self.request_dispatcher.sessions:
298 if session.stopped():
300 if session.contains_subscription(subdesc):
301 session.send_response(response)
303 # if not found: print_log( "no subscriber for", subdesc)
306 def send_response(self, internal_id, response):
307 session, message_id = self.request_dispatcher.get_session_id(internal_id)
309 response['id'] = message_id
310 session.send_response(response)
312 # print_log( "send_response: no session", message_id, internal_id, response )