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
6 from electrum.i18n import _
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
21 from electrum import BasePlugin
22 class Plugin(BasePlugin):
24 def fullname(self): return 'QR scans'
26 def description(self): return "QR Scans.\nInstall the zbar package to enable this plugin.\nOn linux, type: 'apt-get install python-zbar'"
28 def __init__(self, gui, name):
29 BasePlugin.__init__(self, gui, name)
30 self._is_available = self._init()
36 proc = zbar.Processor()
37 proc.init(video_device=self.video_device())
38 except zbar.SystemError:
39 # Cannot open video device
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)
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)
58 self.send_tab_grid.addWidget(b2, 7, 1)
60 def is_available(self):
61 return self._is_available
63 def create_send_tab(self, grid):
64 self.send_tab_grid = grid
67 proc = zbar.Processor()
69 proc.init(video_device=self.video_device())
70 except zbar.SystemError, e:
71 QMessageBox.warning(self.gui.main_window, _('Error'), _(e), _('OK'))
80 # User closed the preview window
83 for r in proc.results:
84 if str(r.type) != 'QRCODE':
88 def show_raw_qr(self):
89 r = self.gui.main_window.read_send_tab()
93 outputs, fee, label, coins = r
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))
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'))
112 except Exception as e:
113 self.gui.main_window.show_message(str(e))
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))
121 def show_tx_qrcode(self, data, title):
123 d = QDialog(self.gui.main_window)
125 d.setWindowTitle(title)
126 d.setMinimumSize(250, 525)
128 qrw = QRCodeWidget(data)
129 vbox.addWidget(qrw, 0)
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'))
138 b = QPushButton(_("Save"))
140 b.clicked.connect(print_qr)
142 b = QPushButton(_("Close"))
144 b.clicked.connect(d.accept)
147 vbox.addLayout(hbox, 1)
151 def read_raw_qr(self):
152 qrcode = self.scan_qr()
154 tx = self.gui.main_window.tx_from_text(qrcode)
156 self.create_transaction_details_window(tx)
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'))
167 l.addWidget(QLabel(_("Transaction status:")), 3,0)
168 l.addWidget(QLabel(_("Actions")), 4,0)
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))
177 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
179 l.addWidget(QLabel(_("Signed")), 3,1)
180 b = QPushButton("Broadcast transaction")
182 result, result_message = self.gui.main_window.wallet.sendtx( tx )
184 self.gui.main_window.show_message(_("Transaction successfully sent:")+' %s' % (result_message))
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 ))
192 closeButton = QPushButton(_("Close"))
193 closeButton.clicked.connect(lambda: dialog.done(0))
194 l.addWidget(closeButton, 4,2)
198 def do_protect(self, func, args):
199 if self.gui.main_window.wallet.use_encryption:
200 password = self.gui.main_window.password_dialog()
207 args = (self,) + args + (password,)
209 args = (self,password)
213 return lambda s, *args: s.do_protect(func, args)
216 def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
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))
225 def fill_from_qr(self):
226 qrcode = parse_uri(self.scan_qr())
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']))
239 def video_device(self):
240 device = self.config.get("video_device", "default")
241 if device == 'default':
245 def requires_settings(self):
248 def settings_widget(self, window):
249 return EnterButton(_('Settings'), self.settings_dialog)
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)
260 def settings_dialog(self):
261 system_cameras = self._find_system_cameras()
264 layout = QGridLayout(d)
265 layout.addWidget(QLabel("Choose a video device:"),0,0)
267 # Create a combo box with the available video devices:
270 # on change trigger for video device selection, makes the
271 # manual device selection only appear when needed:
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("")
281 self.video_device_edit.setText(self.config.get("video_device"))
283 custom_device_label.setVisible(False)
284 self.video_device_edit.setVisible(False)
285 self.video_device_edit.setText(combo_data.toString())
287 # on save trigger for the video device selection window,
288 # stores the chosen video device on close.
290 device = str(self.video_device_edit.text())
291 self.config.set_key("video_device", device)
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)
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"))
307 # Populate the previously chosen device:
308 index = combo.findData(self.config.get("video_device"))
309 combo.setCurrentIndex(index)
311 layout.addWidget(combo,0,1)
313 self.accept = QPushButton(_("Done"))
314 self.accept.clicked.connect(on_save)
315 layout.addWidget(self.accept,4,2)
326 # It's just an address (not BIP21)
327 return {'address': uri}
330 # Workaround for urlparse, it don't handle bitcoin: URI properly
331 uri = uri.replace(':', '://')
334 result = {'address': uri.netloc}
336 if uri.query.startswith('?'):
337 params = parse_qs(uri.query[1:])
339 params = parse_qs(uri.query)
341 for k,v in params.items():
342 if k in ('amount', 'label', 'message'):
351 if __name__ == '__main__':
354 assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
355 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
357 assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
358 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
360 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
361 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
363 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
364 {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
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'})