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