new bitcoind backend (experimental)
[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 print_lock = threading.Lock()
17 def print_log(*args):
18     args = [str(item) for item in args]
19     with print_lock:
20         sys.stderr.write(" ".join(args) + "\n")
21         sys.stderr.flush()
22
23
24
25 class Shared:
26
27     def __init__(self):
28         self.lock = threading.Lock()
29         self._stopped = False
30
31     def stop(self):
32         print_log( "Stopping Stratum" )
33         with self.lock:
34             self._stopped = True
35
36     def stopped(self):
37         with self.lock:
38             return self._stopped
39
40
41 class Processor(threading.Thread):
42
43     def __init__(self):
44         threading.Thread.__init__(self)
45         self.daemon = True
46         self.dispatcher = None
47         self.queue = queue.Queue()
48
49     def process(self, request):
50         pass
51
52     def add_request(self, request):
53         self.queue.put(request)
54
55     def push_response(self, response):
56         #print "response", response
57         self.dispatcher.request_dispatcher.push_response(response)
58
59     def run(self):
60         while not self.shared.stopped():
61             request = self.queue.get(10000000000)
62             try:
63                 self.process(request)
64             except:
65                 traceback.print_exc(file=sys.stdout)
66
67         print_log( "processor terminating")
68             
69
70
71 class Dispatcher:
72
73     def __init__(self):
74         self.shared = Shared()
75         self.request_dispatcher = RequestDispatcher(self.shared)
76         self.request_dispatcher.start()
77         self.response_dispatcher = \
78             ResponseDispatcher(self.shared, self.request_dispatcher)
79         self.response_dispatcher.start()
80
81     def register(self, prefix, processor):
82         processor.dispatcher = self
83         processor.shared = self.shared
84         processor.start()
85         self.request_dispatcher.processors[prefix] = processor
86
87
88
89 class RequestDispatcher(threading.Thread):
90
91     def __init__(self, shared):
92         self.shared = shared
93         threading.Thread.__init__(self)
94         self.daemon = True
95         self.request_queue = queue.Queue()
96         self.response_queue = queue.Queue()
97         self.internal_ids = {}
98         self.internal_id = 1
99         self.lock = threading.Lock()
100         self.sessions = []
101         self.processors = {}
102
103     def push_response(self, item):
104         self.response_queue.put(item)
105
106     def pop_response(self):
107         return self.response_queue.get()
108
109     def push_request(self, session, item):
110         self.request_queue.put((session,item))
111
112     def pop_request(self):
113         return self.request_queue.get()
114
115     def get_session_by_address(self, address):
116         for x in self.sessions:
117             if x.address == address:
118                 return x
119
120     def get_session_id(self, internal_id):
121         with self.lock:
122             return self.internal_ids.pop(internal_id)
123
124     def store_session_id(self, session, msgid):
125         with self.lock:
126             self.internal_ids[self.internal_id] = session, msgid
127             r = self.internal_id
128             self.internal_id += 1
129             return r
130
131     def run(self):
132         if self.shared is None:
133             raise TypeError("self.shared not set in Processor")
134         while not self.shared.stopped():
135             session, request = self.pop_request()
136             try:
137                 self.do_dispatch(session, request)
138             except:
139                 traceback.print_exc(file=sys.stdout)
140                 
141
142         self.stop()
143
144     def stop(self):
145         pass
146
147     def do_dispatch(self, session, request):
148         """ dispatch request to the relevant processor """
149
150         method = request['method']
151         params = request.get('params',[])
152         suffix = method.split('.')[-1]
153
154         is_new = session.protocol_version >= 0.5
155
156         if is_new and method == 'blockchain.address.get_history': 
157             method = 'blockchain.address.get_history2'
158             request['method'] = method
159
160         if suffix == 'subscribe':
161             if is_new and method == 'blockchain.address.subscribe': 
162                 method = 'blockchain.address.subscribe2'
163                 request['method'] = method
164
165             session.subscribe_to_service(method, params)
166
167         # store session and id locally
168         request['id'] = self.store_session_id(session, request['id'])
169
170         prefix = request['method'].split('.')[0]
171         try:
172             p = self.processors[prefix]
173         except:
174             print_log( "error: no processor for", prefix)
175             return
176
177         p.add_request(request)
178
179         if method in ['server.version']:
180             session.version = params[0]
181             try:
182                 session.protocol_version = float(params[1])
183             except:
184                 pass
185
186     def get_sessions(self):
187         with self.lock:
188             r = self.sessions[:]
189         return r
190
191     def add_session(self, session):
192         with self.lock:
193             self.sessions.append(session)
194
195     def collect_garbage(self):
196         # Deep copy entire sessions list and blank it
197         # This is done to minimise lock contention
198         with self.lock:
199             sessions = self.sessions[:]
200             self.sessions = []
201         for session in sessions:
202             if not session.stopped():
203                 # If session is still alive then re-add it back
204                 # to our internal register
205                 self.add_session(session)
206
207
208 class Session:
209
210     def __init__(self):
211         self._stopped = False
212         self.lock = threading.Lock()
213         self.subscriptions = []
214         self.address = ''
215         self.name = ''
216         self.version = 'unknown'
217         self.protocol_version = 0.
218         self.time = time.time()
219         threading.Timer(2, self.info).start()
220
221     # Debugging method. Doesn't need to be threadsafe.
222     def info(self):
223         for sub in self.subscriptions:
224             #print sub
225             method = sub[0]
226             if method == 'blockchain.address.subscribe':
227                 addr = sub[1]
228                 break
229         else:
230             addr = None
231
232         if self.subscriptions:
233             print_log( timestr(), self.name, self.address, addr, len(self.subscriptions), self.version )
234
235     def stopped(self):
236         with self.lock:
237             return self._stopped
238
239     def subscribe_to_service(self, method, params):
240         subdesc = self.build_subdesc(method, params)
241         with self.lock:
242             if subdesc is not None:
243                 self.subscriptions.append(subdesc)
244
245     # subdesc = A subscription description
246     @staticmethod
247     def build_subdesc(method, params):
248         if method == "blockchain.numblocks.subscribe":
249             return method,
250         elif method == "blockchain.headers.subscribe":
251             return method,
252         elif method in ["blockchain.address.subscribe", "blockchain.address.subscribe2"]:
253             if not params:
254                 return None
255             else:
256                 return method, params[0]
257         else:
258             return None
259
260     def contains_subscription(self, subdesc):
261         with self.lock:
262             return subdesc in self.subscriptions
263     
264
265 class ResponseDispatcher(threading.Thread):
266
267     def __init__(self, shared, processor):
268         self.shared = shared
269         self.processor = processor
270         threading.Thread.__init__(self)
271         self.daemon = True
272
273     def run(self):
274         while not self.shared.stopped():
275             self.update()
276
277     def update(self):
278         response = self.processor.pop_response()
279         #print "pop response", response
280         internal_id = response.get('id')
281         method = response.get('method')
282         params = response.get('params')
283
284         # A notification
285         if internal_id is None: # and method is not None and params is not None:
286             self.notification(method, params, response)
287         # A response
288         elif internal_id is not None: # and method is None and params is None:
289             self.send_response(internal_id, response)
290         else:
291             print_log( "no method", response)
292
293     def notification(self, method, params, response):
294         subdesc = Session.build_subdesc(method, params)
295         for session in self.processor.sessions:
296             if session.stopped():
297                 continue
298             if session.contains_subscription(subdesc):
299                 if response.get('method') == "blockchain.address.subscribe2":
300                     response['method'] = "blockchain.address.subscribe"
301                 session.send_response(response)
302
303     def send_response(self, internal_id, response):
304         session, message_id = self.processor.get_session_id(internal_id)
305         if session:
306             response['id'] = message_id
307             session.send_response(response)
308         else:
309             print_log( "send_response: no session", message_id, internal_id, response )
310