let the send tab parse and return its own fields
[electrum-nvc.git] / plugins / qrscanner.py
1 from electrum.util import print_error
2 from urlparse import urlparse, parse_qs
3 from PyQt4.QtGui import QPushButton, QMessageBox, QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QLineEdit, QComboBox
4 from PyQt4.QtCore import Qt
5
6 from electrum.i18n import _
7 import re
8 import os
9 from electrum import Transaction
10 from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
11 from electrum_gui.qt.qrcodewidget import QRCodeWidget
12 from electrum import bmp
13 from electrum_gui.qt import HelpButton, EnterButton
14 import json
15
16 try:
17     import zbar
18 except ImportError:
19     zbar = None
20
21 from electrum import BasePlugin
22 class Plugin(BasePlugin):
23
24     def fullname(self): return 'QR scans'
25
26     def description(self): return "QR Scans.\nInstall the zbar package to enable this plugin.\nOn linux, type: 'apt-get install python-zbar'"
27
28     def __init__(self, gui, name):
29         BasePlugin.__init__(self, gui, name)
30         self._is_available = self._init()
31
32     def _init(self):
33         if not zbar:
34             return False
35         try:
36             proc = zbar.Processor()
37             proc.init(video_device=self.video_device())
38         except zbar.SystemError:
39             # Cannot open video device
40             pass
41             #return False
42
43         return True
44
45     def load_wallet(self, wallet):
46         b = QPushButton(_("Scan QR code"))
47         b.clicked.connect(self.fill_from_qr)
48         self.send_tab_grid.addWidget(b, 1, 5)
49         b2 = QPushButton(_("Scan TxQR"))
50         b2.clicked.connect(self.read_raw_qr)
51         
52         if not wallet.seed:
53             b3 = QPushButton(_("Show unsigned TxQR"))
54             b3.clicked.connect(self.show_raw_qr)
55             self.send_tab_grid.addWidget(b3, 7, 1)
56             self.send_tab_grid.addWidget(b2, 7, 2)
57         else:
58             self.send_tab_grid.addWidget(b2, 7, 1)
59
60     def is_available(self):
61         return self._is_available
62
63     def create_send_tab(self, grid):
64         self.send_tab_grid = grid
65
66     def scan_qr(self):
67         proc = zbar.Processor()
68         try:
69             proc.init(video_device=self.video_device())
70         except zbar.SystemError, e:
71             QMessageBox.warning(self.gui.main_window, _('Error'), _(e), _('OK'))
72             return
73
74         proc.visible = True
75
76         while True:
77             try:
78                 proc.process_one()
79             except Exception:
80                 # User closed the preview window
81                 return {}
82
83             for r in proc.results:
84                 if str(r.type) != 'QRCODE':
85                     continue
86                 return r.data
87         
88     def show_raw_qr(self):
89         r = self.gui.main_window.read_send_tab()
90         if not r:
91             return
92
93         outputs, fee, label, coins = r
94         try:
95             tx = self.gui.main_window.wallet.make_unsigned_transaction(outputs, fee, None, None, coins)
96         except Exception as e:
97             self.gui.main_window.show_message(str(e))
98             return
99
100         if tx.requires_fee(self.gui.main_window.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
101             QMessageBox.warning(self.gui.main_window, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
102             return
103
104         try:
105             out = {
106             "hex" : tx.hash(),
107             "complete" : "false"
108             }
109     
110             input_info = []
111
112         except Exception as e:
113             self.gui.main_window.show_message(str(e))
114
115         try:
116             json_text = json.dumps(tx.as_dict()).replace(' ', '')
117             self.show_tx_qrcode(json_text, 'Unsigned Transaction')
118         except Exception as e:
119             self.gui.main_window.show_message(str(e))
120
121     def show_tx_qrcode(self, data, title):
122         if not data: return
123         d = QDialog(self.gui.main_window)
124         d.setModal(1)
125         d.setWindowTitle(title)
126         d.setMinimumSize(250, 525)
127         vbox = QVBoxLayout()
128         qrw = QRCodeWidget(data)
129         vbox.addWidget(qrw, 0)
130         hbox = QHBoxLayout()
131         hbox.addStretch(1)
132
133         def print_qr(self):
134             filename = "qrcode.bmp"
135             electrum_gui.bmp.save_qrcode(qrw.qr, filename)
136             QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
137
138         b = QPushButton(_("Save"))
139         hbox.addWidget(b)
140         b.clicked.connect(print_qr)
141
142         b = QPushButton(_("Close"))
143         hbox.addWidget(b)
144         b.clicked.connect(d.accept)
145         b.setDefault(True)
146
147         vbox.addLayout(hbox, 1)
148         d.setLayout(vbox)
149         d.exec_()
150
151     def read_raw_qr(self):
152         qrcode = self.scan_qr()
153         if qrcode:
154             tx = self.gui.main_window.tx_from_text(qrcode)
155             if tx:
156                 self.create_transaction_details_window(tx)
157
158     def create_transaction_details_window(self, tx):            
159         dialog = QDialog(self.gui.main_window)
160         dialog.setMinimumWidth(500)
161         dialog.setWindowTitle(_('Process Offline transaction'))
162         dialog.setModal(1)
163
164         l = QGridLayout()
165         dialog.setLayout(l)
166
167         l.addWidget(QLabel(_("Transaction status:")), 3,0)
168         l.addWidget(QLabel(_("Actions")), 4,0)
169
170         if tx.is_complete == False:
171             l.addWidget(QLabel(_("Unsigned")), 3,1)
172             if self.gui.main_window.wallet.seed :
173                 b = QPushButton("Sign transaction")
174                 b.clicked.connect(lambda: self.sign_raw_transaction(tx, tx.inputs, dialog))
175                 l.addWidget(b, 4, 1)
176             else:
177                 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
178         else:
179             l.addWidget(QLabel(_("Signed")), 3,1)
180             b = QPushButton("Broadcast transaction")
181             def broadcast(tx):
182                 result, result_message = self.gui.main_window.wallet.sendtx( tx )
183                 if result:
184                     self.gui.main_window.show_message(_("Transaction successfully sent:")+' %s' % (result_message))
185                     if dialog:
186                         dialog.done(0)
187                 else:
188                     self.gui.main_window.show_message(_("There was a problem sending your transaction:") + '\n %s' % (result_message))
189             b.clicked.connect(lambda: broadcast( tx ))
190             l.addWidget(b,4,1)
191     
192         closeButton = QPushButton(_("Close"))
193         closeButton.clicked.connect(lambda: dialog.done(0))
194         l.addWidget(closeButton, 4,2)
195
196         dialog.exec_()
197
198     def do_protect(self, func, args):
199         if self.gui.main_window.wallet.use_encryption:
200             password = self.gui.main_window.password_dialog()
201             if not password:
202                 return
203         else:
204             password = None
205             
206         if args != (False,):
207             args = (self,) + args + (password,)
208         else:
209             args = (self,password)
210         apply( func, args)
211
212     def protected(func):
213         return lambda s, *args: s.do_protect(func, args)
214
215     @protected
216     def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
217         try:
218             self.gui.main_window.wallet.signrawtransaction(tx, input_info, [], password)
219             txtext = json.dumps(tx.as_dict()).replace(' ', '')
220             self.show_tx_qrcode(txtext, 'Signed Transaction')
221         except Exception as e:
222             self.gui.main_window.show_message(str(e))
223
224
225     def fill_from_qr(self):
226         qrcode = parse_uri(self.scan_qr())
227         if not qrcode:
228             return
229
230         if 'address' in qrcode:
231             self.gui.main_window.payto_e.setText(qrcode['address'])
232         if 'amount' in qrcode:
233             self.gui.main_window.amount_e.setText(str(qrcode['amount']))
234         if 'label' in qrcode:
235             self.gui.main_window.message_e.setText(qrcode['label'])
236         if 'message' in qrcode:
237             self.gui.main_window.message_e.setText("%s (%s)" % (self.gui.main_window.message_e.text(), qrcode['message']))
238                 
239     def video_device(self):
240         device = self.config.get("video_device", "default")
241         if device == 'default':
242             device = ''
243         return device
244
245     def requires_settings(self):
246         return True
247
248     def settings_widget(self, window):
249         return EnterButton(_('Settings'), self.settings_dialog)
250     
251     def _find_system_cameras(self):
252         device_root = "/sys/class/video4linux"
253         devices = {} # Name -> device
254         if os.path.exists(device_root):
255             for device in os.listdir(device_root):
256                 name = open(os.path.join(device_root, device, 'name')).read()
257                 devices[name] = os.path.join("/dev",device)
258         return devices
259
260     def settings_dialog(self):
261         system_cameras = self._find_system_cameras()
262
263         d = QDialog()
264         layout = QGridLayout(d)
265         layout.addWidget(QLabel("Choose a video device:"),0,0)
266
267         # Create a combo box with the available video devices:
268         combo = QComboBox()
269
270         # on change trigger for video device selection, makes the
271         # manual device selection only appear when needed:
272         def on_change(x):
273             combo_text = str(combo.itemText(x))
274             combo_data = combo.itemData(x)
275             if combo_text == "Manually specify a device":
276                 custom_device_label.setVisible(True)
277                 self.video_device_edit.setVisible(True)
278                 if self.config.get("video_device") == "default":
279                     self.video_device_edit.setText("")
280                 else:
281                     self.video_device_edit.setText(self.config.get("video_device"))
282             else:
283                 custom_device_label.setVisible(False)
284                 self.video_device_edit.setVisible(False)
285                 self.video_device_edit.setText(combo_data.toString())
286
287         # on save trigger for the video device selection window,
288         # stores the chosen video device on close.
289         def on_save():
290             device = str(self.video_device_edit.text())
291             self.config.set_key("video_device", device)
292             d.accept()
293
294         custom_device_label = QLabel("Video device: ")
295         custom_device_label.setVisible(False)
296         layout.addWidget(custom_device_label,1,0)
297         self.video_device_edit = QLineEdit()
298         self.video_device_edit.setVisible(False)
299         layout.addWidget(self.video_device_edit, 1,1,2,2)
300         combo.currentIndexChanged.connect(on_change)
301
302         combo.addItem("Default","default")
303         for camera, device in system_cameras.items():
304             combo.addItem(camera, device)
305         combo.addItem("Manually specify a device",self.config.get("video_device"))
306
307         # Populate the previously chosen device:
308         index = combo.findData(self.config.get("video_device"))
309         combo.setCurrentIndex(index)
310
311         layout.addWidget(combo,0,1)
312
313         self.accept = QPushButton(_("Done"))
314         self.accept.clicked.connect(on_save)
315         layout.addWidget(self.accept,4,2)
316
317         if d.exec_():
318           return True
319         else:
320           return False
321
322
323
324 def parse_uri(uri):
325     if ':' not in uri:
326         # It's just an address (not BIP21)
327         return {'address': uri}
328
329     if '//' not in uri:
330         # Workaround for urlparse, it don't handle bitcoin: URI properly
331         uri = uri.replace(':', '://')
332         
333     uri = urlparse(uri)
334     result = {'address': uri.netloc} 
335     
336     if uri.query.startswith('?'):
337         params = parse_qs(uri.query[1:])
338     else:
339         params = parse_qs(uri.query)    
340
341     for k,v in params.items():
342         if k in ('amount', 'label', 'message'):
343             result[k] = v[0]
344         
345     return result    
346
347
348
349
350
351 if __name__ == '__main__':
352     # Run some tests
353     
354     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
355            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
356
357     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
358            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
359     
360     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
361            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
362     
363     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
364            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
365     
366     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
367            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
368     
369