Bugfix: allow blockchain.address.subscribe notifications to work.
[electrum-server.git] / processor.py
1 import json
2 import socket
3 import threading
4 import time
5 import traceback, sys
6 import Queue as queue
7
8 def random_string(N):
9     import random, string
10     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
11
12 def timestr():
13     return time.strftime("[%d/%m/%Y-%H:%M:%S]")
14
15
16 class Shared:
17
18     def __init__(self):
19         self.lock = threading.Lock()
20         self._stopped = False
21
22     def stop(self):
23         print "Stopping Stratum"
24         with self.lock:
25             self._stopped = True
26
27     def stopped(self):
28         with self.lock:
29             return self._stopped
30
31
32 class Processor(threading.Thread):
33
34     def __init__(self):
35         threading.Thread.__init__(self)
36         self.daemon = True
37         self.dispatcher = None
38
39     def process(self, request):
40         pass
41
42     def push_response(self, response):
43         print "response", response
44         self.dispatcher.request_dispatcher.push_response(response)
45
46
47
48 class Dispatcher:
49
50     def __init__(self):
51         self.shared = Shared()
52         self.request_dispatcher = RequestDispatcher(self.shared)
53         self.request_dispatcher.start()
54         self.response_dispatcher = \
55             ResponseDispatcher(self.shared, self.request_dispatcher)
56         self.response_dispatcher.start()
57
58     def register(self, prefix, processor):
59         processor.dispatcher = self
60         processor.shared = self.shared
61         processor.start()
62         self.request_dispatcher.processors[prefix] = processor
63
64
65
66 class RequestDispatcher(threading.Thread):
67
68     def __init__(self, shared):
69         self.shared = shared
70         threading.Thread.__init__(self)
71         self.daemon = True
72         self.request_queue = queue.Queue()
73         self.response_queue = queue.Queue()
74         self.internal_ids = {}
75         self.internal_id = 1
76         self.lock = threading.Lock()
77         self.sessions = []
78         self.processors = {}
79
80     def push_response(self, item):
81         self.response_queue.put(item)
82
83     def pop_response(self):
84         return self.response_queue.get()
85
86     def push_request(self, session, item):
87         self.request_queue.put((session,item))
88
89     def pop_request(self):
90         return self.request_queue.get()
91
92     def get_session_id(self, internal_id):
93         with self.lock:
94             return self.internal_ids.pop(internal_id)
95
96     def store_session_id(self, session, msgid):
97         with self.lock:
98             self.internal_ids[self.internal_id] = session, msgid
99             r = self.internal_id
100             self.internal_id += 1
101             return r
102
103     def run(self):
104         if self.shared is None:
105             raise TypeError("self.shared not set in Processor")
106         while not self.shared.stopped():
107             session, request = self.pop_request()
108             self.process(session, request)
109
110         self.stop()
111
112     def stop(self):
113         pass
114
115     def process(self, session, request):
116         method = request['method']
117         params = request.get('params',[])
118
119         suffix = method.split('.')[-1]
120         if suffix == 'subscribe':
121             session.subscribe_to_service(method, params)
122
123         # store session and id locally
124         request['id'] = self.store_session_id(session, request['id'])
125
126         # dispatch request to the relevant module..
127         prefix = request['method'].split('.')[0]
128         try:
129             p = self.processors[prefix]
130         except:
131             print "error: no processor for", prefix
132             return
133         try:
134             p.process(request)
135         except:
136             traceback.print_exc(file=sys.stdout)
137
138         if method in ['server.version']:
139             session.version = params[0]
140
141
142     def add_session(self, session):
143         with self.lock:
144             self.sessions.append(session)
145
146     def collect_garbage(self):
147         # Deep copy entire sessions list and blank it
148         # This is done to minimise lock contention
149         with self.lock:
150             sessions = self.sessions[:]
151             self.sessions = []
152         for session in sessions:
153             if not session.stopped():
154                 # If session is still alive then re-add it back
155                 # to our internal register
156                 self.add_session(session)
157
158
159 class Session:
160
161     def __init__(self):
162         self._stopped = False
163         self.lock = threading.Lock()
164         self.subscriptions = []
165         self.address = ''
166         self.name = ''
167         #threading.Timer(2, self.info).start()
168
169     # Debugging method. Doesn't need to be threadsafe.
170     def info(self):
171         for sub in self.subscriptions:
172             print sub
173             method, params = sub
174             if method == 'blockchain.address.subscribe':
175                 addr = params[0]
176                 break
177         else:
178             addr = None
179         print (timestr(), self.name, self.address, addr,
180                len(self.subscriptions), self.version)
181
182     def stopped(self):
183         with self.lock:
184             return self._stopped
185
186     def subscribe_to_service(self, method, params):
187         subdesc = self.build_subdesc(method, params)
188         with self.lock:
189             self.subscriptions.append(subdesc)
190
191     # subdesc = A subscription description
192     def build_subdesc(self, method, params):
193         if method == "blockchain.numblocks.subscribe":
194             return method,
195         elif method == "blockchain.address.get_history":
196             if not params:
197                 return None
198             else:
199                 return method, params[0]
200         else:
201             return None
202
203     def contains_subscription(self, subdesc):
204         with self.lock:
205             return subdesc in self.subscriptions
206     
207
208 class ResponseDispatcher(threading.Thread):
209
210     def __init__(self, shared, processor):
211         self.shared = shared
212         self.processor = processor
213         threading.Thread.__init__(self)
214         self.daemon = True
215
216     def run(self):
217         while not self.shared.stopped():
218             self.update()
219
220     def update(self):
221         response = self.processor.pop_response()
222         #print "pop response", response
223         internal_id = response.get('id')
224         method = response.get('method')
225         params = response.get('params', [])
226
227         # A notification
228         if internal_id is None and method is None:
229             self.notification(response)
230         elif internal_id is not None:
231             self.send_response(internal_id, response)
232         else:
233             print "no method", response
234
235     def notification(self, response):
236         subdesc = self.build_subdesc(method, params)
237         for session in self.processor.sessions:
238             if session.stopped():
239                 continue
240             if session.contains_subscription(subdesc):
241                 session.send_response(response)
242
243     def send_response(self, internal_id, response):
244         session, message_id = self.processor.get_session_id(internal_id)
245         response['id'] = message_id
246         session.send_response(response)
247