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