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