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 (http://zbar.sourceforge.net/download.html) to enable this plugin"
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 = unicode( self.gui.main_window.payto_e.text() )
92 # label or alias, with address in brackets
93 m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
94 to_address = m.group(2) if m else r
96 if not is_valid(to_address):
97 QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
101 amount = self.gui.main_window.read_amount(unicode( self.gui.main_window.amount_e.text()))
103 QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Amount'), _('OK'))
106 fee = self.gui.main_window.read_amount(unicode( self.gui.main_window.fee_e.text()))
108 QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Fee'), _('OK'))
112 tx = self.gui.main_window.wallet.mktx( [(to_address, amount)], None, fee)
113 except Exception as e:
114 self.gui.main_window.show_message(str(e))
117 if tx.requires_fee(self.gui.main_window.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
118 QMessageBox.warning(self.gui.main_window, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
129 except Exception as e:
130 self.gui.main_window.show_message(str(e))
133 json_text = json.dumps(tx.as_dict()).replace(' ', '')
134 self.show_tx_qrcode(json_text, 'Unsigned Transaction')
135 except Exception as e:
136 self.gui.main_window.show_message(str(e))
138 def show_tx_qrcode(self, data, title):
140 d = QDialog(self.gui.main_window)
142 d.setWindowTitle(title)
143 d.setMinimumSize(250, 525)
145 qrw = QRCodeWidget(data)
146 vbox.addWidget(qrw, 0)
151 filename = "qrcode.bmp"
152 electrum_gui.bmp.save_qrcode(qrw.qr, filename)
153 QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
155 b = QPushButton(_("Save"))
157 b.clicked.connect(print_qr)
159 b = QPushButton(_("Close"))
161 b.clicked.connect(d.accept)
164 vbox.addLayout(hbox, 1)
168 def read_raw_qr(self):
169 qrcode = self.scan_qr()
171 tx = self.gui.main_window.tx_from_text(qrcode)
173 self.create_transaction_details_window(tx)
175 def create_transaction_details_window(self, tx):
176 dialog = QDialog(self.gui.main_window)
177 dialog.setMinimumWidth(500)
178 dialog.setWindowTitle(_('Process Offline transaction'))
184 l.addWidget(QLabel(_("Transaction status:")), 3,0)
185 l.addWidget(QLabel(_("Actions")), 4,0)
187 if tx.is_complete == False:
188 l.addWidget(QLabel(_("Unsigned")), 3,1)
189 if self.gui.main_window.wallet.seed :
190 b = QPushButton("Sign transaction")
191 b.clicked.connect(lambda: self.sign_raw_transaction(tx, tx.inputs, dialog))
194 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
196 l.addWidget(QLabel(_("Signed")), 3,1)
197 b = QPushButton("Broadcast transaction")
199 result, result_message = self.gui.main_window.wallet.sendtx( tx )
201 self.gui.main_window.show_message(_("Transaction successfully sent:")+' %s' % (result_message))
205 self.gui.main_window.show_message(_("There was a problem sending your transaction:") + '\n %s' % (result_message))
206 b.clicked.connect(lambda: broadcast( tx ))
209 closeButton = QPushButton(_("Close"))
210 closeButton.clicked.connect(lambda: dialog.done(0))
211 l.addWidget(closeButton, 4,2)
215 def do_protect(self, func, args):
216 if self.gui.main_window.wallet.use_encryption:
217 password = self.gui.main_window.password_dialog()
224 args = (self,) + args + (password,)
226 args = (self,password)
230 return lambda s, *args: s.do_protect(func, args)
233 def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
235 self.gui.main_window.wallet.signrawtransaction(tx, input_info, [], password)
236 txtext = json.dumps(tx.as_dict()).replace(' ', '')
237 self.show_tx_qrcode(txtext, 'Signed Transaction')
238 except Exception as e:
239 self.gui.main_window.show_message(str(e))
242 def fill_from_qr(self):
243 qrcode = parse_uri(self.scan_qr())
247 if 'address' in qrcode:
248 self.gui.main_window.payto_e.setText(qrcode['address'])
249 if 'amount' in qrcode:
250 self.gui.main_window.amount_e.setText(str(qrcode['amount']))
251 if 'label' in qrcode:
252 self.gui.main_window.message_e.setText(qrcode['label'])
253 if 'message' in qrcode:
254 self.gui.main_window.message_e.setText("%s (%s)" % (self.gui.main_window.message_e.text(), qrcode['message']))
256 def video_device(self):
257 device = self.config.get("video_device", "default")
258 if device == 'default':
262 def requires_settings(self):
265 def settings_widget(self, window):
266 return EnterButton(_('Settings'), self.settings_dialog)
268 def _find_system_cameras(self):
269 device_root = "/sys/class/video4linux"
270 devices = {} # Name -> device
271 if os.path.exists(device_root):
272 for device in os.listdir(device_root):
273 name = open(os.path.join(device_root, device, 'name')).read()
274 devices[name] = os.path.join("/dev",device)
277 def settings_dialog(self):
278 system_cameras = self._find_system_cameras()
281 layout = QGridLayout(d)
282 layout.addWidget(QLabel("Choose a video device:"),0,0)
284 # Create a combo box with the available video devices:
287 # on change trigger for video device selection, makes the
288 # manual device selection only appear when needed:
290 combo_text = str(combo.itemText(x))
291 combo_data = combo.itemData(x)
292 if combo_text == "Manually specify a device":
293 custom_device_label.setVisible(True)
294 self.video_device_edit.setVisible(True)
295 if self.config.get("video_device") == "default":
296 self.video_device_edit.setText("")
298 self.video_device_edit.setText(self.config.get("video_device"))
300 custom_device_label.setVisible(False)
301 self.video_device_edit.setVisible(False)
302 self.video_device_edit.setText(combo_data.toString())
304 # on save trigger for the video device selection window,
305 # stores the chosen video device on close.
307 device = str(self.video_device_edit.text())
308 self.config.set_key("video_device", device)
311 custom_device_label = QLabel("Video device: ")
312 custom_device_label.setVisible(False)
313 layout.addWidget(custom_device_label,1,0)
314 self.video_device_edit = QLineEdit()
315 self.video_device_edit.setVisible(False)
316 layout.addWidget(self.video_device_edit, 1,1,2,2)
317 combo.currentIndexChanged.connect(on_change)
319 combo.addItem("Default","default")
320 for camera, device in system_cameras.items():
321 combo.addItem(camera, device)
322 combo.addItem("Manually specify a device",self.config.get("video_device"))
324 # Populate the previously chosen device:
325 index = combo.findData(self.config.get("video_device"))
326 combo.setCurrentIndex(index)
328 layout.addWidget(combo,0,1)
330 self.accept = QPushButton(_("Done"))
331 self.accept.clicked.connect(on_save)
332 layout.addWidget(self.accept,4,2)
343 # It's just an address (not BIP21)
344 return {'address': uri}
347 # Workaround for urlparse, it don't handle bitcoin: URI properly
348 uri = uri.replace(':', '://')
351 result = {'address': uri.netloc}
353 if uri.path.startswith('?'):
354 params = parse_qs(uri.path[1:])
356 params = parse_qs(uri.path)
358 for k,v in params.items():
359 if k in ('amount', 'label', 'message'):
368 if __name__ == '__main__':
371 assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
372 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
374 assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
375 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
377 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
378 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
380 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
381 {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
383 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
384 {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})