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