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