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
4 from PyQt4.QtCore import Qt
5 from electrum_gui.i18n import _
8 from electrum.bitcoin import MIN_RELAY_TX_FEE, Transaction, is_valid
9 from electrum_gui.qrcodewidget import QRCodeWidget
10 import electrum_gui.bmp
18 from electrum_gui import BasePlugin
19 class Plugin(BasePlugin):
21 def fullname(self): return 'QR scans'
23 def description(self): return "QR Scans.\nInstall the zbar package (http://zbar.sourceforge.net/download.html) to enable this plugin"
25 def __init__(self, gui, name):
26 BasePlugin.__init__(self, gui, name)
27 self._is_available = self._init()
33 proc = zbar.Processor()
35 except zbar.SystemError:
36 # Cannot open video device
41 def is_available(self):
42 return self._is_available
44 def create_send_tab(self, grid):
45 b = QPushButton(_("Scan QR code"))
46 b.clicked.connect(self.fill_from_qr)
47 grid.addWidget(b, 1, 5)
48 b2 = QPushButton(_("Scan TxQR"))
49 b2.clicked.connect(self.read_raw_qr)
51 if not self.gui.wallet.seed:
52 b3 = QPushButton(_("Show unsigned TxQR"))
53 b3.clicked.connect(self.show_raw_qr)
54 grid.addWidget(b3, 7, 1)
55 grid.addWidget(b2, 7, 2)
57 grid.addWidget(b2, 7, 1)
61 proc = zbar.Processor()
69 # User closed the preview window
72 for r in proc.results:
73 if str(r.type) != 'QRCODE':
77 def show_raw_qr(self):
78 r = unicode( self.gui.payto_e.text() )
81 # label or alias, with address in brackets
82 m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
83 to_address = m.group(2) if m else r
85 if not is_valid(to_address):
86 QMessageBox.warning(self.gui, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
90 amount = self.gui.read_amount(unicode( self.gui.amount_e.text()))
92 QMessageBox.warning(self.gui, _('Error'), _('Invalid Amount'), _('OK'))
95 fee = self.gui.read_amount(unicode( self.gui.fee_e.text()))
97 QMessageBox.warning(self.gui, _('Error'), _('Invalid Fee'), _('OK'))
101 tx = self.gui.wallet.mktx( [(to_address, amount)], None, fee, account=self.gui.current_account)
102 except BaseException, e:
103 self.gui.show_message(str(e))
106 if tx.requires_fee(self.gui.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
107 QMessageBox.warning(self.gui, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
118 except BaseException, e:
119 self.gui.show_message(str(e))
122 json_text = json.dumps(tx.as_dict()).replace(' ', '')
123 self.show_tx_qrcode(json_text, 'Unsigned Transaction')
124 except BaseException, e:
125 self.gui.show_message(str(e))
127 def show_tx_qrcode(self, data, title):
129 d = QDialog(self.gui)
131 d.setWindowTitle(title)
132 d.setMinimumSize(250, 525)
134 qrw = QRCodeWidget(data)
135 vbox.addWidget(qrw, 0)
140 filename = "qrcode.bmp"
141 electrum_gui.bmp.save_qrcode(qrw.qr, filename)
142 QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
144 b = QPushButton(_("Save"))
146 b.clicked.connect(print_qr)
148 b = QPushButton(_("Close"))
150 b.clicked.connect(d.accept)
153 vbox.addLayout(hbox, 1)
157 def read_raw_qr(self):
158 qrcode = self.scan_qr()
160 tx_dict = self.gui.tx_dict_from_text(qrcode)
162 self.create_transaction_details_window(tx_dict)
165 def create_transaction_details_window(self, tx_dict):
166 tx = Transaction(tx_dict["hex"])
168 dialog = QDialog(self.gui)
169 dialog.setMinimumWidth(500)
170 dialog.setWindowTitle(_('Process Offline transaction'))
176 l.addWidget(QLabel(_("Transaction status:")), 3,0)
177 l.addWidget(QLabel(_("Actions")), 4,0)
179 if tx_dict["complete"] == False:
180 l.addWidget(QLabel(_("Unsigned")), 3,1)
181 if self.gui.wallet.seed :
182 b = QPushButton("Sign transaction")
183 input_info = json.loads(tx_dict["input_info"])
184 b.clicked.connect(lambda: self.sign_raw_transaction(tx, input_info, dialog))
187 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
189 l.addWidget(QLabel(_("Signed")), 3,1)
190 b = QPushButton("Broadcast transaction")
191 b.clicked.connect(lambda: self.gui.send_raw_transaction(tx, dialog))
194 l.addWidget( self.gui.generate_transaction_information_widget(tx), 0,0,2,3)
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.gui.wallet.use_encryption:
203 password = self.gui.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.gui.wallet.signrawtransaction(tx, input_info, [], password)
222 txtext = json.dumps(tx.as_dict()).replace(' ', '')
223 self.show_tx_qrcode(txtext, 'Signed Transaction')
224 except BaseException, e:
225 self.gui.show_message(str(e))
228 def fill_from_qr(self):
229 qrcode = parse_uri(self.scan_qr())
233 if 'address' in qrcode:
234 self.gui.payto_e.setText(qrcode['address'])
235 if 'amount' in qrcode:
236 self.gui.amount_e.setText(str(qrcode['amount']))
237 if 'label' in qrcode:
238 self.gui.message_e.setText(qrcode['label'])
239 if 'message' in qrcode:
240 self.gui.message_e.setText("%s (%s)" % (self.gui.message_e.text(), qrcode['message']))
247 # It's just an address (not BIP21)
248 return {'address': uri}
251 # Workaround for urlparse, it don't handle bitcoin: URI properly
252 uri = uri.replace(':', '://')
255 result = {'address': uri.netloc}
257 if uri.path.startswith('?'):
258 params = parse_qs(uri.path[1:])
260 params = parse_qs(uri.path)
262 for k,v in params.items():
263 if k in ('amount', 'label', 'message'):
272 if __name__ == '__main__':
275 assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
276 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
278 assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
279 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
281 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
282 {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
284 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
285 {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
287 assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
288 {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})