Fix label sync plugin and add in backwards compatibility with 1.8 wallets. Fixes...
[electrum-nvc.git] / plugins / labels.py
1 from electrum.util import print_error
2
3 import httplib, urllib
4 import socket
5 import hashlib
6 import json
7 from urlparse import urlparse, parse_qs
8 try:
9     import PyQt4
10 except:
11     sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
12
13 from PyQt4.QtGui import *
14 from PyQt4.QtCore import *
15 import PyQt4.QtCore as QtCore
16 import PyQt4.QtGui as QtGui
17 import aes
18 import base64
19 from electrum import bmp, pyqrnative
20 from electrum.plugins import BasePlugin
21 from electrum.i18n import _
22
23 from electrum_gui.qt import HelpButton
24
25 class Plugin(BasePlugin):
26
27     def fullname(self):
28         return _('Label Sync')
29
30     def description(self):
31         return '%s\n\n%s%s%s' % (_("This plugin can sync your labels across multiple Electrum installs by using a remote database to save your data. Labels, transactions and addresses are all sent and stored encrypted on the remote server. This code might increase the load of your wallet with a few microseconds as it will sync labels on each startup."), _("To get started visit"), " http://labelectrum.herokuapp.com/ ", _(" to sign up for an account."))
32
33     def version(self):
34         return "0.2.1"
35
36     def encode(self, message):
37         encrypted = aes.encryptData(self.encode_password, unicode(message))
38         encoded_message = base64.b64encode(encrypted)
39
40         return encoded_message
41
42     def decode(self, message):
43         decoded_message = aes.decryptData(self.encode_password, base64.b64decode(unicode(message)) )
44
45         return decoded_message
46
47
48     def init(self):
49         self.target_host = 'labelectrum.herokuapp.com'
50         self.window = self.gui.main_window
51
52     def load_wallet(self, wallet):
53         self.wallet = wallet
54         if self.wallet.get_master_public_key():
55             mpk = self.wallet.get_master_public_key()
56         else:
57             mpk = self.wallet.master_public_keys["m/0'/"][1]
58         self.encode_password = hashlib.sha1(mpk).digest().encode('hex')[:32]
59         self.wallet_id = hashlib.sha256(mpk).digest().encode('hex')
60
61         addresses = [] 
62         for account in self.wallet.accounts.values():
63             for address in account.get_addresses(0):
64                 addresses.append(address)
65
66         self.addresses = addresses
67
68         if self.auth_token():
69             # If there is an auth token we can try to actually start syncing
70             self.full_pull()
71
72     def auth_token(self):
73         return self.config.get("plugin_label_api_key")
74
75     def is_available(self):
76         return True
77
78     def requires_settings(self):
79         return True
80
81     def set_label(self, item,label, changed):
82         if not changed:
83             return 
84         try:
85             bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}}
86             params = json.dumps(bundle)
87             connection = httplib.HTTPConnection(self.target_host)
88             connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
89
90             response = connection.getresponse()
91             if response.reason == httplib.responses[httplib.NOT_FOUND]:
92                 return
93             response = json.loads(response.read())
94         except socket.gaierror as e:
95             print_error('Error connecting to service: %s ' %  e)
96             return False
97
98     def settings_dialog(self):
99         def check_for_api_key(api_key):
100             if api_key and len(api_key) > 12:
101               self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
102               self.upload.setEnabled(True)
103               self.download.setEnabled(True)
104               self.accept.setEnabled(True)
105             else:
106               self.upload.setEnabled(False)
107               self.download.setEnabled(False)
108               self.accept.setEnabled(False)
109
110         d = QDialog()
111         layout = QGridLayout(d)
112         layout.addWidget(QLabel("API Key: "),0,0)
113
114         self.auth_token_edit = QLineEdit(self.auth_token())
115         self.auth_token_edit.textChanged.connect(check_for_api_key)
116
117         layout.addWidget(QLabel("Label sync options: "),2,0)
118         layout.addWidget(self.auth_token_edit, 0,1,1,2)
119
120         decrypt_key_text =  QLineEdit(self.encode_password)
121         decrypt_key_text.setReadOnly(True)
122         layout.addWidget(decrypt_key_text, 1,1)
123         layout.addWidget(QLabel("Decryption key: "),1,0)
124         layout.addWidget(HelpButton("This key can be used on the LabElectrum website to decrypt your data in case you want to review it online."),1,2)
125
126         self.upload = QPushButton("Force upload")
127         self.upload.clicked.connect(self.full_push)
128         layout.addWidget(self.upload, 2,1)
129
130         self.download = QPushButton("Force download")
131         self.download.clicked.connect(lambda: self.full_pull(True))
132         layout.addWidget(self.download, 2,2)
133
134         c = QPushButton(_("Cancel"))
135         c.clicked.connect(d.reject)
136
137         self.accept = QPushButton(_("Done"))
138         self.accept.clicked.connect(d.accept)
139
140         layout.addWidget(c,3,1)
141         layout.addWidget(self.accept,3,2)
142
143         check_for_api_key(self.auth_token())
144
145         if d.exec_():
146           return True
147         else:
148           return False
149
150     def enable(self):
151         if not self.auth_token(): # First run, throw plugin settings in your face
152             self.init()
153             self.load_wallet(self.gui.main_window.wallet)
154             if self.settings_dialog():
155                 self.set_enabled(True)
156                 return True
157             else:
158                 self.set_enabled(False)
159                 return False
160
161         self.set_enabled(True)
162         return True
163
164
165     def full_push(self):
166         if self.do_full_push():
167             QMessageBox.information(None, _("Labels uploaded"), _("Your labels have been uploaded."))
168
169     def full_pull(self, force = False):
170         if self.do_full_pull(force) and force:
171             QMessageBox.information(None, _("Labels synchronized"), _("Your labels have been synchronized."))
172             self.window.update_history_tab()
173             self.window.update_completions()
174             self.window.update_receive_tab()
175             self.window.update_contacts_tab()
176
177     def do_full_push(self):
178         try:
179             bundle = {"labels": {}}
180             for key, value in self.wallet.labels.iteritems():
181                 encoded = self.encode(key)
182                 bundle["labels"][encoded] = self.encode(value)
183
184             params = json.dumps(bundle)
185             connection = httplib.HTTPConnection(self.target_host)
186             connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
187
188             response = connection.getresponse()
189             if response.reason == httplib.responses[httplib.NOT_FOUND]:
190                 return
191             try:
192                 response = json.loads(response.read())
193             except ValueError as e:
194                 return False
195
196             if "error" in response:
197                 QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
198                 return False
199
200             return True
201         except socket.gaierror as e:
202             print_error('Error connecting to service: %s ' %  e)
203             return False
204
205     def do_full_pull(self, force = False):
206         try:
207             connection = httplib.HTTPConnection(self.target_host)
208             connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
209             response = connection.getresponse()
210             if response.reason == httplib.responses[httplib.NOT_FOUND]:
211                 return
212             try:
213                 response = json.loads(response.read())
214             except ValueError as e:
215                 return False
216
217             if "error" in response:
218                 QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
219                 return False
220
221             for label in response:
222                  decoded_key = self.decode(label["external_id"]) 
223                  decoded_label = self.decode(label["text"]) 
224                  if force or not self.wallet.labels.get(decoded_key):
225                      self.wallet.labels[decoded_key] = decoded_label 
226             return True
227         except socket.gaierror as e:
228             print_error('Error connecting to service: %s ' %  e)
229             return False