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
46 self.win = self.gui.main_window
48 def load_wallet(self, wallet):
49 b = QPushButton(_("Scan QR code"))
50 b.clicked.connect(self.fill_from_qr)
51 self.send_tab_grid.addWidget(b, 1, 5)
52 b2 = QPushButton(_("Scan TxQR"))
53 b2.clicked.connect(self.read_raw_qr)
56 b3 = QPushButton(_("Show unsigned TxQR"))
57 b3.clicked.connect(self.show_raw_qr)
58 self.send_tab_grid.addWidget(b3, 7, 1)
59 self.send_tab_grid.addWidget(b2, 7, 2)
61 self.send_tab_grid.addWidget(b2, 7, 1)
63 def is_available(self):
64 return self._is_available
66 def create_send_tab(self, grid):
67 self.send_tab_grid = grid
70 proc = zbar.Processor()
72 proc.init(video_device=self.video_device())
73 except zbar.SystemError, e:
74 QMessageBox.warning(self.win, _('Error'), _(e), _('OK'))
83 # User closed the preview window
86 for r in proc.results:
87 if str(r.type) != 'QRCODE':
91 def show_raw_qr(self):
92 r = self.win.read_send_tab()
96 outputs, fee, label, coins = r
98 tx = self.win.wallet.make_unsigned_transaction(outputs, fee, None, None, coins)
99 except Exception as e:
100 self.win.show_message(str(e))
103 if tx.requires_fee(self.win.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
104 QMessageBox.warning(self.win, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
115 except Exception as e:
116 self.win.show_message(str(e))
119 json_text = json.dumps(tx.as_dict()).replace(' ', '')
120 self.show_tx_qrcode(json_text, 'Unsigned Transaction')
121 except Exception as e:
122 self.win.show_message(str(e))
124 def show_tx_qrcode(self, data, title):
126 d = QDialog(self.win)
128 d.setWindowTitle(title)
129 d.setMinimumSize(250, 525)
131 qrw = QRCodeWidget(data)
132 vbox.addWidget(qrw, 0)
137 filename = "qrcode.bmp"
138 electrum_gui.bmp.save_qrcode(qrw.qr, filename)
139 QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
141 b = QPushButton(_("Save"))
143 b.clicked.connect(print_qr)
145 b = QPushButton(_("Close"))
147 b.clicked.connect(d.accept)
150 vbox.addLayout(hbox, 1)
154 def read_raw_qr(self):
155 qrcode = self.scan_qr()
157 tx = self.win.tx_from_text(qrcode)
159 self.create_transaction_details_window(tx)
161 def create_transaction_details_window(self, tx):
162 dialog = QDialog(self.win)
163 dialog.setMinimumWidth(500)
164 dialog.setWindowTitle(_('Process Offline transaction'))
170 l.addWidget(QLabel(_("Transaction status:")), 3,0)
171 l.addWidget(QLabel(_("Actions")), 4,0)
173 if tx.is_complete == False:
174 l.addWidget(QLabel(_("Unsigned")), 3,1)
175 if self.win.wallet.seed :
176 b = QPushButton("Sign transaction")
177 b.clicked.connect(lambda: self.sign_raw_transaction(tx, tx.inputs, dialog))
180 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
182 l.addWidget(QLabel(_("Signed")), 3,1)
183 b = QPushButton("Broadcast transaction")
185 result, result_message = self.win.wallet.sendtx( tx )
187 self.win.show_message(_("Transaction successfully sent:")+' %s' % (result_message))
191 self.win.show_message(_("There was a problem sending your transaction:") + '\n %s' % (result_message))
192 b.clicked.connect(lambda: broadcast( tx ))
195 closeButton = QPushButton(_("Close"))
196 closeButton.clicked.connect(lambda: dialog.done(0))
197 l.addWidget(closeButton, 4,2)
201 def do_protect(self, func, args):
202 if self.win.wallet.use_encryption:
203 password = self.win.password_dialog()
210 args = (self,) + args + (password,)
212 args = (self,password)
216 return lambda s, *args: s.do_protect(func, args)
219 def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
221 self.win.wallet.signrawtransaction(tx, input_info, [], password)
222 txtext = json.dumps(tx.as_dict()).replace(' ', '')
223 self.show_tx_qrcode(txtext, 'Signed Transaction')
224 except Exception as e:
225 self.win.show_message(str(e))
228 def fill_from_qr(self):
229 qrcode = parse_uri(self.scan_qr())
233 if 'address' in qrcode:
234 self.win.payto_e.setText(qrcode['address'])
235 if 'amount' in qrcode:
236 self.win.amount_e.setText(str(qrcode['amount']))
237 if 'label' in qrcode:
238 self.win.message_e.setText(qrcode['label'])
239 if 'message' in qrcode:
240 self.win.message_e.setText("%s (%s)" % (self.win.message_e.text(), qrcode['message']))
242 def video_device(self):
243 device = self.config.get("video_device", "default")
244 if device == 'default':
248 def requires_settings(self):
251 def settings_widget(self, window):
252 return EnterButton(_('Settings'), self.settings_dialog)
254 def _find_system_cameras(self):
255 device_root = "/sys/class/video4linux"
256 devices = {} # Name -> device
257 if os.path.exists(device_root):
258 for device in os.listdir(device_root):
259 name = open(os.path.join(device_root, device, 'name')).read()
260 devices[name] = os.path.join("/dev",device)
263 def settings_dialog(self):
264 system_cameras = self._find_system_cameras()
267 layout = QGridLayout(d)
268 layout.addWidget(QLabel("Choose a video device:"),0,0)
270 # Create a combo box with the available video devices:
273 # on change trigger for video device selection, makes the
274 # manual device selection only appear when needed:
276 combo_text = str(combo.itemText(x))
277 combo_data = combo.itemData(x)
278 if combo_text == "Manually specify a device":
279 custom_device_label.setVisible(True)
280 self.video_device_edit.setVisible(True)
281 if self.config.get("video_device") == "default":
282 self.video_device_edit.setText("")
284 self.video_device_edit.setText(self.config.get("video_device"))
286 custom_device_label.setVisible(False)
287 self.video_device_edit.setVisible(False)
288 self.video_device_edit.setText(combo_data.toString())
290 # on save trigger for the video device selection window,
291 # stores the chosen video device on close.
293 device = str(self.video_device_edit.text())
294 self.config.set_key("video_device", device)
297 custom_device_label = QLabel("Video device: ")
298 custom_device_label.setVisible(False)
299 layout.addWidget(custom_device_label,1,0)
300 self.video_device_edit = QLineEdit()
301 self.video_device_edit.setVisible(False)
302 layout.addWidget(self.video_device_edit, 1,1,2,2)
303 combo.currentIndexChanged.connect(on_change)
305 combo.addItem("Default","default")
306 for camera, device in system_cameras.items():
307 combo.addItem(camera, device)
308 combo.addItem("Manually specify a device",self.config.get("video_device"))
310 # Populate the previously chosen device:
311 index = combo.findData(self.config.get("video_device"))
312 combo.setCurrentIndex(index)
314 layout.addWidget(combo,0,1)
316 self.accept = QPushButton(_("Done"))
317 self.accept.clicked.connect(on_save)
318 layout.addWidget(self.accept,4,2)
329 # It's just an address (not BIP21)
330 return {'address': uri}
333 # Workaround for urlparse, it don't handle bitcoin: URI properly
334 uri = uri.replace(':', '://')
337 result = {'address': uri.netloc}
339 if uri.query.startswith('?'):
340 params = parse_qs(uri.query[1:])
342 params = parse_qs(uri.query)
344 for k,v in params.items():
345 if k in ('amount', 'label', 'message'):
354 if __name__ == '__main__':
357 assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
358 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
360 assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
361 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
363 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
364 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
366 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
367 {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
369 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
370 {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})