fix: sanitize outputs
[electrum-nvc.git] / gui / qt / paytoedit.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2012 thomasv@gitorious
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 from PyQt4.QtCore import *
20 from PyQt4.QtGui import *
21
22 import re
23 from decimal import Decimal
24 from electrum import bitcoin
25
26 RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}'
27 RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>'
28
29 frozen_style = "QWidget { background-color:none; border:none;}"
30 normal_style = "QTextEdit { }"
31
32 class PayToEdit(QTextEdit):
33
34     def __init__(self, amount_edit):
35         QTextEdit.__init__(self)
36         self.amount_edit = amount_edit
37         self.document().contentsChanged.connect(self.update_size)
38         self.heightMin = 0
39         self.heightMax = 150
40         self.setMinimumHeight(27)
41         self.setMaximumHeight(27)
42         self.c = None
43         self.textChanged.connect(self.check_text)
44         self.outputs = []
45
46     def lock_amount(self):
47         self.amount_edit.setFrozen(True)
48
49     def unlock_amount(self):
50         self.amount_edit.setFrozen(False)
51
52     def setFrozen(self, b):
53         self.setReadOnly(b)
54         self.setStyleSheet(frozen_style if b else normal_style)
55
56     def setGreen(self):
57         self.setStyleSheet("QWidget { background-color:#00ff00;}")
58
59     def parse_address_and_amount(self, line):
60         x, y = line.split(',')
61         address = self.parse_address(x)
62         amount = self.parse_amount(y)
63         return address, amount
64
65
66     def parse_amount(self, x):
67         p = pow(10, self.amount_edit.decimal_point())
68         return int( p * Decimal(x.strip()))
69
70
71     def parse_address(self, line):
72         r = line.strip()
73         m = re.match('^'+RE_ALIAS+'$', r)
74         address = m.group(2) if m else r
75         assert bitcoin.is_address(address)
76         return address
77
78
79     def check_text(self):
80         # filter out empty lines
81         lines = filter( lambda x: x, self.lines())
82         outputs = []
83         total = 0
84
85         self.payto_address = None
86
87         if len(lines) == 1:
88             try:
89                 self.payto_address = self.parse_address(lines[0])
90             except:
91                 pass
92
93             if self.payto_address:
94                 self.unlock_amount()
95                 try:
96                     amount = self.amount_edit.get_amount()
97                 except:
98                     amount = None
99
100                 self.outputs = [(self.payto_address, amount)]
101                 return
102
103         for line in lines:
104             try:
105                 to_address, amount = self.parse_address_and_amount(line)
106             except:
107                 continue
108                 
109             outputs.append((to_address, amount))
110             total += amount
111
112         self.outputs = outputs
113         self.payto_address = None
114
115         if total:
116             self.amount_edit.setAmount(total)
117         else:
118             self.amount_edit.setText("")
119
120         if total or len(lines)>1:
121             self.lock_amount()
122         else:
123             self.unlock_amount()
124
125
126     def get_outputs(self):
127         return self.outputs
128
129
130     def lines(self):
131         return str(self.toPlainText()).split('\n')
132
133
134     def is_multiline(self):
135         return len(self.lines()) > 1
136
137
138     def update_size(self):
139         docHeight = self.document().size().height()
140         if self.heightMin <= docHeight <= self.heightMax:
141             self.setMinimumHeight(docHeight + 2)
142             self.setMaximumHeight(docHeight + 2)
143
144
145     def setCompleter(self, completer):
146         self.c = completer
147         self.c.setWidget(self)
148         self.c.setCompletionMode(QCompleter.PopupCompletion)
149         self.c.activated.connect(self.insertCompletion)
150
151
152     def insertCompletion(self, completion):
153         if self.c.widget() != self:
154             return
155         tc = self.textCursor()
156         extra = completion.length() - self.c.completionPrefix().length()
157         tc.movePosition(QTextCursor.Left)
158         tc.movePosition(QTextCursor.EndOfWord)
159         tc.insertText(completion.right(extra))
160         self.setTextCursor(tc)
161  
162
163     def textUnderCursor(self):
164         tc = self.textCursor()
165         tc.select(QTextCursor.WordUnderCursor)
166         return tc.selectedText()
167
168
169     def keyPressEvent(self, e):
170         if self.isReadOnly():
171             return
172
173         if self.c.popup().isVisible():
174             if e.key() in [Qt.Key_Enter, Qt.Key_Return]:
175                 e.ignore()
176                 return
177
178         if e.key() in [Qt.Key_Tab]:
179             e.ignore()
180             return
181
182         if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline():
183             e.ignore()
184             return
185
186         isShortcut = (e.modifiers() and Qt.ControlModifier) and e.key() == Qt.Key_E
187
188         if not self.c or not isShortcut:
189             QTextEdit.keyPressEvent(self, e)
190
191
192         ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier)
193         if self.c is None or (ctrlOrShift and e.text().isEmpty()):
194             return
195
196         eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=")
197         hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift;
198         completionPrefix = self.textUnderCursor()
199
200         if not isShortcut and (hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)) ):
201             self.c.popup().hide()
202             return
203
204         if completionPrefix != self.c.completionPrefix():
205             self.c.setCompletionPrefix(completionPrefix);
206             self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0))
207
208         cr = self.cursorRect()
209         cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width())
210         self.c.complete(cr)
211
212