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]")
19 self.lock = threading.Lock()
23 print "Stopping Stratum"
32 class Processor(threading.Thread):
35 threading.Thread.__init__(self)
37 self.dispatcher = None
38 self.queue = queue.Queue()
40 def process(self, request):
43 def add_request(self, request):
44 self.queue.put(request)
46 def push_response(self, response):
47 #print "response", response
48 self.dispatcher.request_dispatcher.push_response(response)
51 while not self.shared.stopped():
52 request = self.queue.get(10000000000)
56 traceback.print_exc(file=sys.stdout)
58 print "processor terminating"
65 self.shared = Shared()
66 self.request_dispatcher = RequestDispatcher(self.shared)
67 self.request_dispatcher.start()
68 self.response_dispatcher = \
69 ResponseDispatcher(self.shared, self.request_dispatcher)
70 self.response_dispatcher.start()
72 def register(self, prefix, processor):
73 processor.dispatcher = self
74 processor.shared = self.shared
76 self.request_dispatcher.processors[prefix] = processor
80 class RequestDispatcher(threading.Thread):
82 def __init__(self, shared):
84 threading.Thread.__init__(self)
86 self.request_queue = queue.Queue()
87 self.response_queue = queue.Queue()
88 self.internal_ids = {}
90 self.lock = threading.Lock()
94 def push_response(self, item):
95 self.response_queue.put(item)
97 def pop_response(self):
98 return self.response_queue.get()
100 def push_request(self, session, item):
101 self.request_queue.put((session,item))
103 def pop_request(self):
104 return self.request_queue.get()
106 def get_session_by_address(self, address):
107 for x in self.sessions:
108 if x.address == address:
111 def get_session_id(self, internal_id):
113 return self.internal_ids.pop(internal_id)
115 def store_session_id(self, session, msgid):
117 self.internal_ids[self.internal_id] = session, msgid
119 self.internal_id += 1
123 if self.shared is None:
124 raise TypeError("self.shared not set in Processor")
125 while not self.shared.stopped():
126 session, request = self.pop_request()
128 self.do_dispatch(session, request)
130 traceback.print_exc(file=sys.stdout)
138 def do_dispatch(self, session, request):
139 """ dispatch request to the relevant processor """
141 method = request['method']
142 params = request.get('params',[])
143 suffix = method.split('.')[-1]
145 is_new = session.protocol_version >= 0.5
147 if is_new and method == 'blockchain.address.get_history':
148 method = 'blockchain.address.get_history2'
149 request['method'] = method
151 if suffix == 'subscribe':
152 if is_new and method == 'blockchain.address.subscribe':
153 method = 'blockchain.address.subscribe2'
154 request['method'] = method
156 session.subscribe_to_service(method, params)
158 # store session and id locally
159 request['id'] = self.store_session_id(session, request['id'])
161 prefix = request['method'].split('.')[0]
163 p = self.processors[prefix]
165 print "error: no processor for", prefix
168 p.add_request(request)
170 if method in ['server.version']:
171 session.version = params[0]
173 session.protocol_version = float(params[1])
177 def get_sessions(self):
182 def add_session(self, session):
184 self.sessions.append(session)
186 def collect_garbage(self):
187 # Deep copy entire sessions list and blank it
188 # This is done to minimise lock contention
190 sessions = self.sessions[:]
192 for session in sessions:
193 if not session.stopped():
194 # If session is still alive then re-add it back
195 # to our internal register
196 self.add_session(session)
202 self._stopped = False
203 self.lock = threading.Lock()
204 self.subscriptions = []
207 self.version = 'unknown'
208 self.protocol_version = 0.
209 self.time = time.time()
210 threading.Timer(2, self.info).start()
212 # Debugging method. Doesn't need to be threadsafe.
214 for sub in self.subscriptions:
217 if method == 'blockchain.address.subscribe':
223 if self.subscriptions:
224 print timestr(), self.name, self.address, addr,\
225 len(self.subscriptions), self.version
231 def subscribe_to_service(self, method, params):
232 subdesc = self.build_subdesc(method, params)
234 if subdesc is not None:
235 self.subscriptions.append(subdesc)
237 # subdesc = A subscription description
239 def build_subdesc(method, params):
240 if method == "blockchain.numblocks.subscribe":
242 elif method == "blockchain.headers.subscribe":
244 elif method in ["blockchain.address.subscribe", "blockchain.address.subscribe2"]:
248 return method, params[0]
252 def contains_subscription(self, subdesc):
254 return subdesc in self.subscriptions
257 class ResponseDispatcher(threading.Thread):
259 def __init__(self, shared, processor):
261 self.processor = processor
262 threading.Thread.__init__(self)
266 while not self.shared.stopped():
270 response = self.processor.pop_response()
271 #print "pop response", response
272 internal_id = response.get('id')
273 method = response.get('method')
274 params = response.get('params')
277 if internal_id is None: # and method is not None and params is not None:
278 self.notification(method, params, response)
280 elif internal_id is not None: # and method is None and params is None:
281 self.send_response(internal_id, response)
283 print "no method", response
285 def notification(self, method, params, response):
286 subdesc = Session.build_subdesc(method, params)
287 for session in self.processor.sessions:
288 if session.stopped():
290 if session.contains_subscription(subdesc):
291 if response.get('method') == "blockchain.address.subscribe2":
292 response['method'] = "blockchain.address.subscribe"
293 session.send_response(response)
295 def send_response(self, internal_id, response):
296 session, message_id = self.processor.get_session_id(internal_id)
298 response['id'] = message_id
299 session.send_response(response)
301 print "send_response: no session", message_id, internal_id, response