various bugfixes for imported addresses
[electrum-nvc.git] / lib / account.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2013 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 import bitcoin
20 from bitcoin import *
21 from i18n import _
22 from transaction import Transaction, is_extended_pubkey
23 from util import print_msg
24
25
26 class Account(object):
27     def __init__(self, v):
28         self.addresses = v.get('0', [])
29         self.change = v.get('1', [])
30
31     def dump(self):
32         return {'0':self.addresses, '1':self.change}
33
34     def get_addresses(self, for_change):
35         return self.change[:] if for_change else self.addresses[:]
36
37     def create_new_address(self, for_change):
38         addresses = self.change if for_change else self.addresses
39         n = len(addresses)
40         address = self.get_address( for_change, n)
41         addresses.append(address)
42         print_msg(address)
43         return address
44
45     def get_address(self, for_change, n):
46         pass
47         
48     def get_pubkeys(self, sequence):
49         return [ self.get_pubkey( *sequence )]
50
51     def has_change(self):
52         return True
53
54     def get_name(self, k):
55         return _('Main account')
56
57     def get_keyID(self, *sequence):
58         pass
59
60     def redeem_script(self, *sequence):
61         pass
62
63
64 class PendingAccount(Account):
65     def __init__(self, v):
66         self.addresses = [ v['pending'] ]
67         self.change = []
68
69     def has_change(self):
70         return False
71
72     def dump(self):
73         return {'pending':self.addresses[0]}
74
75     def get_name(self, k):
76         return _('Pending account')
77
78     def get_master_pubkeys(self):
79         return []
80
81 class ImportedAccount(Account):
82     def __init__(self, d):
83         self.keypairs = d['imported']
84
85     def get_addresses(self, for_change):
86         return [] if for_change else sorted(self.keypairs.keys())
87
88     def get_pubkey(self, *sequence):
89         for_change, i = sequence
90         assert for_change == 0
91         addr = self.get_addresses(0)[i]
92         return self.keypairs[addr][0]
93
94     def get_xpubkeys(self, *sequence):
95         return self.get_pubkeys(*sequence)
96
97     def get_private_key(self, sequence, wallet, password):
98         from wallet import pw_decode
99         for_change, i = sequence
100         assert for_change == 0
101         address = self.get_addresses(0)[i]
102         pk = pw_decode(self.keypairs[address][1], password)
103         # this checks the password
104         assert address == address_from_private_key(pk)
105         return [pk]
106
107     def has_change(self):
108         return False
109
110     def add(self, address, pubkey, privkey, password):
111         from wallet import pw_encode
112         self.keypairs[address] = (pubkey, pw_encode(privkey, password ))
113
114     def remove(self, address):
115         self.keypairs.pop(address)
116
117     def dump(self):
118         return {'imported':self.keypairs}
119
120     def get_name(self, k):
121         return _('Imported keys')
122
123
124     def update_password(self, old_password, new_password):
125         for k, v in self.keypairs.items():
126             pubkey, a = v
127             b = pw_decode(a, old_password)
128             c = pw_encode(b, new_password)
129             self.keypairs[k] = (pubkey, c)
130
131
132 class OldAccount(Account):
133     """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
134
135     def __init__(self, v):
136         self.addresses = v.get(0, [])
137         self.change = v.get(1, [])
138         self.mpk = v['mpk'].decode('hex')
139
140     def dump(self):
141         return {0:self.addresses, 1:self.change}
142
143     @classmethod
144     def mpk_from_seed(klass, seed):
145         curve = SECP256k1
146         secexp = klass.stretch_key(seed)
147         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
148         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
149         return master_public_key
150
151     @classmethod
152     def stretch_key(self,seed):
153         oldseed = seed
154         for i in range(100000):
155             seed = hashlib.sha256(seed + oldseed).digest()
156         return string_to_number( seed )
157
158     @classmethod
159     def get_sequence(self, mpk, for_change, n):
160         return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk ) )
161
162     def get_address(self, for_change, n):
163         pubkey = self.get_pubkey(for_change, n)
164         address = public_key_to_bc_address( pubkey.decode('hex') )
165         return address
166
167     @classmethod
168     def get_pubkey_from_mpk(self, mpk, for_change, n):
169         curve = SECP256k1
170         z = self.get_sequence(mpk, for_change, n)
171         master_public_key = ecdsa.VerifyingKey.from_string( mpk, curve = SECP256k1 )
172         pubkey_point = master_public_key.pubkey.point + z*curve.generator
173         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
174         return '04' + public_key2.to_string().encode('hex')
175
176     def get_pubkey(self, for_change, n):
177         return self.get_pubkey_from_mpk(self.mpk, for_change, n)
178
179     def get_private_key_from_stretched_exponent(self, for_change, n, secexp):
180         order = generator_secp256k1.order()
181         secexp = ( secexp + self.get_sequence(self.mpk, for_change, n) ) % order
182         pk = number_to_string( secexp, generator_secp256k1.order() )
183         compressed = False
184         return SecretToASecret( pk, compressed )
185         
186
187     def get_private_key(self, sequence, wallet, password):
188         seed = wallet.get_seed(password)
189         self.check_seed(seed)
190         for_change, n = sequence
191         secexp = self.stretch_key(seed)
192         pk = self.get_private_key_from_stretched_exponent(for_change, n, secexp)
193         return [pk]
194
195
196     def check_seed(self, seed):
197         curve = SECP256k1
198         secexp = self.stretch_key(seed)
199         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
200         master_public_key = master_private_key.get_verifying_key().to_string()
201         if master_public_key != self.mpk:
202             print_error('invalid password (mpk)', self.mpk.encode('hex'), master_public_key.encode('hex'))
203             raise Exception('Invalid password')
204         return True
205
206     def redeem_script(self, sequence):
207         return None
208
209     def get_master_pubkeys(self):
210         return [self.mpk.encode('hex')]
211
212     def get_type(self):
213         return _('Old Electrum format')
214
215     def get_keyID(self, sequence):
216         a, b = sequence
217         return 'old(%s,%d,%d)'%(self.mpk.encode('hex'),a,b)
218
219     def get_xpubkeys(self, sequence):
220         s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), sequence))
221         mpk = self.mpk.encode('hex')
222         x_pubkey = 'fe' + mpk + s
223         return [ x_pubkey ]
224
225     @classmethod
226     def parse_xpubkey(self, x_pubkey):
227         assert is_extended_pubkey(x_pubkey)
228         pk = x_pubkey[2:]
229         mpk = pk[0:128]
230         dd = pk[128:]
231         s = []
232         while dd:
233             n = int(bitcoin.rev_hex(dd[0:4]), 16)
234             dd = dd[4:]
235             s.append(n)
236         assert len(s) == 2
237         return mpk, s
238
239
240 class BIP32_Account(Account):
241
242     def __init__(self, v):
243         Account.__init__(self, v)
244         self.xpub = v['xpub']
245
246     def dump(self):
247         d = Account.dump(self)
248         d['xpub'] = self.xpub
249         return d
250
251     def get_address(self, for_change, n):
252         pubkey = self.get_pubkey(for_change, n)
253         address = public_key_to_bc_address( pubkey.decode('hex') )
254         return address
255
256     def first_address(self):
257         return self.get_address(0,0)
258
259     def get_master_pubkeys(self):
260         return [self.xpub]
261
262     @classmethod
263     def get_pubkey_from_x(self, xpub, for_change, n):
264         _, _, _, c, cK = deserialize_xkey(xpub)
265         for i in [for_change, n]:
266             cK, c = CKD_pub(cK, c, i)
267         return cK.encode('hex')
268
269     def get_pubkeys(self, sequence):
270         return sorted(map(lambda x: self.get_pubkey_from_x(x, *sequence), self.get_master_pubkeys()))
271
272     def get_pubkey(self, for_change, n):
273         return self.get_pubkeys((for_change, n))[0]
274
275
276     def get_private_key(self, sequence, wallet, password):
277         out = []
278         xpubs = self.get_master_pubkeys()
279         roots = [k for k, v in wallet.master_public_keys.iteritems() if v in xpubs]
280         for root in roots:
281             xpriv = wallet.get_master_private_key(root, password)
282             if not xpriv:
283                 continue
284             _, _, _, c, k = deserialize_xkey(xpriv)
285             pk = bip32_private_key( sequence, k, c )
286             out.append(pk)
287                     
288         return out
289
290
291     def redeem_script(self, sequence):
292         return None
293
294     def get_type(self):
295         return _('Standard 1 of 1')
296
297     def get_xpubkeys(self, sequence):
298         s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), sequence))
299         mpks = self.get_master_pubkeys()
300         out = []
301         for xpub in mpks:
302             pubkey = self.get_pubkey_from_x(xpub, *sequence)
303             x_pubkey = 'ff' + bitcoin.DecodeBase58Check(xpub).encode('hex') + s
304             out.append( (pubkey, x_pubkey ) )
305         # sort it, so that x_pubkeys are in the same order as pubkeys
306         out.sort()
307         return map(lambda x:x[1], out )
308
309     @classmethod
310     def parse_xpubkey(self, pubkey):
311         assert is_extended_pubkey(pubkey)
312         pk = pubkey.decode('hex')
313         pk = pk[1:]
314         xkey = bitcoin.EncodeBase58Check(pk[0:78])
315         dd = pk[78:]
316         s = []
317         while dd:
318             n = int( bitcoin.rev_hex(dd[0:2].encode('hex')), 16)
319             dd = dd[2:]
320             s.append(n)
321         assert len(s) == 2
322         return xkey, s
323
324
325     def get_name(self, k):
326         name = "Unnamed account"
327         m = re.match("m/(\d+)'", k)
328         if m:
329             num = m.group(1)
330             if num == '0':
331                 name = "Main account"
332             else:
333                 name = "Account %s"%num
334                     
335         return name
336
337
338
339 class BIP32_Account_2of2(BIP32_Account):
340
341     def __init__(self, v):
342         BIP32_Account.__init__(self, v)
343         self.xpub2 = v['xpub2']
344
345     def dump(self):
346         d = BIP32_Account.dump(self)
347         d['xpub2'] = self.xpub2
348         return d
349
350     def redeem_script(self, sequence):
351         pubkeys = self.get_pubkeys(sequence)
352         return Transaction.multisig_script(pubkeys, 2)
353
354     def get_address(self, for_change, n):
355         address = hash_160_to_bc_address(hash_160(self.redeem_script((for_change, n)).decode('hex')), 5)
356         return address
357
358     def get_master_pubkeys(self):
359         return [self.xpub, self.xpub2]
360
361     def get_type(self):
362         return _('Multisig 2 of 2')
363
364
365 class BIP32_Account_2of3(BIP32_Account_2of2):
366
367     def __init__(self, v):
368         BIP32_Account_2of2.__init__(self, v)
369         self.xpub3 = v['xpub3']
370
371     def dump(self):
372         d = BIP32_Account_2of2.dump(self)
373         d['xpub3'] = self.xpub3
374         return d
375
376     def get_master_pubkeys(self):
377         return [self.xpub, self.xpub2, self.xpub3]
378
379     def get_type(self):
380         return _('Multisig 2 of 3')
381
382
383
384