plugins: do not overload __init__, use init() instead
[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
4 from PyQt4.QtCore import Qt
5 from electrum_gui.i18n import _
6
7 import re
8 from electrum.bitcoin import MIN_RELAY_TX_FEE, Transaction, is_valid
9 from electrum_gui.qrcodewidget import QRCodeWidget
10 import electrum_gui.bmp
11 import json
12
13 try:
14     import zbar
15 except ImportError:
16     zbar = None
17
18 from electrum_gui import BasePlugin
19 class Plugin(BasePlugin):
20
21     def fullname(self): return 'QR scans'
22
23     def description(self): return "QR Scans.\nInstall the zbar package (http://zbar.sourceforge.net/download.html) to enable this plugin"
24
25     def __init__(self, gui, name):
26         BasePlugin.__init__(self, gui, name)
27         self._is_available = self._init()
28
29     def _init(self):
30         if not zbar:
31             return False
32         try:
33             proc = zbar.Processor()
34             proc.init()
35         except zbar.SystemError:
36             # Cannot open video device
37             return False
38
39         return True
40
41     def is_available(self):
42         return self._is_available
43
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)
50         
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)
56         else:
57             grid.addWidget(b2, 7, 1)
58
59
60     def scan_qr(self):
61         proc = zbar.Processor()
62         proc.init()
63         proc.visible = True
64
65         while True:
66             try:
67                 proc.process_one()
68             except:
69                 # User closed the preview window
70                 return {}
71
72             for r in proc.results:
73                 if str(r.type) != 'QRCODE':
74                     continue
75                 return r.data
76         
77     def show_raw_qr(self):
78         r = unicode( self.gui.payto_e.text() )
79         r = r.strip()
80
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
84
85         if not is_valid(to_address):
86             QMessageBox.warning(self.gui, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
87             return
88
89         try:
90             amount = self.gui.read_amount(unicode( self.gui.amount_e.text()))
91         except:
92             QMessageBox.warning(self.gui, _('Error'), _('Invalid Amount'), _('OK'))
93             return
94         try:
95             fee = self.gui.read_amount(unicode( self.gui.fee_e.text()))
96         except:
97             QMessageBox.warning(self.gui, _('Error'), _('Invalid Fee'), _('OK'))
98             return
99
100         try:
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))
104             return
105
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'))
108             return
109
110         try:
111             out = {
112             "hex" : tx.hash(),
113             "complete" : "false"
114             }
115     
116             input_info = []
117
118         except BaseException, e:
119             self.gui.show_message(str(e))
120
121         try:
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))
126
127     def show_tx_qrcode(self, data, title):
128         if not data: return
129         d = QDialog(self.gui)
130         d.setModal(1)
131         d.setWindowTitle(title)
132         d.setMinimumSize(250, 525)
133         vbox = QVBoxLayout()
134         qrw = QRCodeWidget(data)
135         vbox.addWidget(qrw, 0)
136         hbox = QHBoxLayout()
137         hbox.addStretch(1)
138
139         def print_qr(self):
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'))
143
144         b = QPushButton(_("Save"))
145         hbox.addWidget(b)
146         b.clicked.connect(print_qr)
147
148         b = QPushButton(_("Close"))
149         hbox.addWidget(b)
150         b.clicked.connect(d.accept)
151         b.setDefault(True)
152
153         vbox.addLayout(hbox, 1)
154         d.setLayout(vbox)
155         d.exec_()
156
157     def read_raw_qr(self):
158         qrcode = self.scan_qr()
159         if qrcode:
160             tx_dict = self.gui.tx_dict_from_text(qrcode)
161             if tx_dict:
162                 self.create_transaction_details_window(tx_dict)
163
164
165     def create_transaction_details_window(self, tx_dict):
166         tx = Transaction(tx_dict["hex"])
167             
168         dialog = QDialog(self.gui)
169         dialog.setMinimumWidth(500)
170         dialog.setWindowTitle(_('Process Offline transaction'))
171         dialog.setModal(1)
172
173         l = QGridLayout()
174         dialog.setLayout(l)
175
176         l.addWidget(QLabel(_("Transaction status:")), 3,0)
177         l.addWidget(QLabel(_("Actions")), 4,0)
178
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))
185                 l.addWidget(b, 4, 1)
186             else:
187                 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
188         else:
189             l.addWidget(QLabel(_("Signed")), 3,1)
190             b = QPushButton("Broadcast transaction")
191             b.clicked.connect(lambda: self.gui.send_raw_transaction(tx, dialog))
192             l.addWidget(b,4,1)
193     
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)
198
199         dialog.exec_()
200
201     def do_protect(self, func, args):
202         if self.gui.wallet.use_encryption:
203             password = self.gui.password_dialog()
204             if not password:
205                 return
206         else:
207             password = None
208             
209         if args != (False,):
210             args = (self,) + args + (password,)
211         else:
212             args = (self,password)
213         apply( func, args)
214
215     def protected(func):
216         return lambda s, *args: s.do_protect(func, args)
217
218     @protected
219     def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
220         try:
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))
226
227
228     def fill_from_qr(self):
229         qrcode = parse_uri(self.scan_qr())
230         if not qrcode:
231             return
232
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']))
241                 
242
243
244
245 def parse_uri(uri):
246     if ':' not in uri:
247         # It's just an address (not BIP21)
248         return {'address': uri}
249
250     if '//' not in uri:
251         # Workaround for urlparse, it don't handle bitcoin: URI properly
252         uri = uri.replace(':', '://')
253         
254     uri = urlparse(uri)
255     result = {'address': uri.netloc} 
256     
257     if uri.path.startswith('?'):
258         params = parse_qs(uri.path[1:])
259     else:
260         params = parse_qs(uri.path)    
261
262     for k,v in params.items():
263         if k in ('amount', 'label', 'message'):
264             result[k] = v[0]
265         
266     return result    
267
268
269
270
271
272 if __name__ == '__main__':
273     # Run some tests
274     
275     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
276            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
277
278     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
279            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
280     
281     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
282            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
283     
284     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
285            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
286     
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'})
289     
290