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 push_response(self, response):
44 #print "response", response
45 self.dispatcher.request_dispatcher.push_response(response)
48 while not self.shared.stopped():
49 request = self.queue.get(10000000000)
53 traceback.print_exc(file=sys.stdout)
55 print "processor terminating"
62 self.shared = Shared()
63 self.request_dispatcher = RequestDispatcher(self.shared)
64 self.request_dispatcher.start()
65 self.response_dispatcher = \
66 ResponseDispatcher(self.shared, self.request_dispatcher)
67 self.response_dispatcher.start()
69 def register(self, prefix, processor):
70 processor.dispatcher = self
71 processor.shared = self.shared
73 self.request_dispatcher.processors[prefix] = processor
77 class RequestDispatcher(threading.Thread):
79 def __init__(self, shared):
81 threading.Thread.__init__(self)
83 self.request_queue = queue.Queue()
84 self.response_queue = queue.Queue()
85 self.internal_ids = {}
87 self.lock = threading.Lock()
91 def push_response(self, item):
92 self.response_queue.put(item)
94 def pop_response(self):
95 return self.response_queue.get()
97 def push_request(self, session, item):
98 self.request_queue.put((session,item))
100 def pop_request(self):
101 return self.request_queue.get()
103 def get_session_by_address(self, address):
104 for x in self.sessions:
105 if x.address == address:
108 def get_session_id(self, internal_id):
110 return self.internal_ids.pop(internal_id)
112 def store_session_id(self, session, msgid):
114 self.internal_ids[self.internal_id] = session, msgid
116 self.internal_id += 1
120 if self.shared is None:
121 raise TypeError("self.shared not set in Processor")
122 while not self.shared.stopped():
123 session, request = self.pop_request()
125 self.do_dispatch(session, request)
127 traceback.print_exc(file=sys.stdout)
135 def do_dispatch(self, session, request):
136 """ dispatch request to the relevant processor """
138 method = request['method']
139 params = request.get('params',[])
140 suffix = method.split('.')[-1]
142 is_new = session.protocol_version >= 0.5
144 if is_new and method == 'blockchain.address.get_history':
145 method = 'blockchain.address.get_history2'
146 request['method'] = method
148 if suffix == 'subscribe':
149 if is_new and method == 'blockchain.address.subscribe':
150 method = 'blockchain.address.subscribe2'
151 request['method'] = method
153 session.subscribe_to_service(method, params)
155 # store session and id locally
156 request['id'] = self.store_session_id(session, request['id'])
158 prefix = request['method'].split('.')[0]
160 p = self.processors[prefix]
162 print "error: no processor for", prefix
167 if method in ['server.version']:
168 session.version = params[0]
170 session.protocol_version = float(params[1])
174 def get_sessions(self):
179 def add_session(self, session):
181 self.sessions.append(session)
183 def collect_garbage(self):
184 # Deep copy entire sessions list and blank it
185 # This is done to minimise lock contention
187 sessions = self.sessions[:]
189 for session in sessions:
190 if not session.stopped():
191 # If session is still alive then re-add it back
192 # to our internal register
193 self.add_session(session)
199 self._stopped = False
200 self.lock = threading.Lock()
201 self.subscriptions = []
204 self.version = 'unknown'
205 self.protocol_version = 0.
206 self.time = time.time()
207 threading.Timer(2, self.info).start()
209 # Debugging method. Doesn't need to be threadsafe.
211 for sub in self.subscriptions:
214 if method == 'blockchain.address.subscribe':
220 if self.subscriptions:
221 print timestr(), self.name, self.address, addr,\
222 len(self.subscriptions), self.version
228 def subscribe_to_service(self, method, params):
229 subdesc = self.build_subdesc(method, params)
231 if subdesc is not None:
232 self.subscriptions.append(subdesc)
234 # subdesc = A subscription description
236 def build_subdesc(method, params):
237 if method == "blockchain.numblocks.subscribe":
239 elif method == "blockchain.headers.subscribe":
241 elif method in ["blockchain.address.subscribe", "blockchain.address.subscribe2"]:
245 return method, params[0]
249 def contains_subscription(self, subdesc):
251 return subdesc in self.subscriptions
254 class ResponseDispatcher(threading.Thread):
256 def __init__(self, shared, processor):
258 self.processor = processor
259 threading.Thread.__init__(self)
263 while not self.shared.stopped():
267 response = self.processor.pop_response()
268 #print "pop response", response
269 internal_id = response.get('id')
270 method = response.get('method')
271 params = response.get('params')
273 if method == "blockchain.address.subscribe2":
274 method = "blockchain.address.subscribe"
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 session.send_response(response)
293 def send_response(self, internal_id, response):
294 session, message_id = self.processor.get_session_id(internal_id)
296 response['id'] = message_id
297 session.send_response(response)
299 print "send_response: no session", message_id, internal_id, response