fix: 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
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 class PendingAccount(Account):
53     def __init__(self, v):
54         self.addresses = [ v['pending'] ]
55         self.change = []
56
57     def has_change(self):
58         return False
59
60     def dump(self):
61         return {'pending':self.addresses[0]}
62
63 class ImportedAccount(Account):
64     def __init__(self, d):
65         self.addresses = d.keys()
66
67     def has_change(self):
68         return False
69
70
71 class OldAccount(Account):
72     """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
73
74     def __init__(self, v):
75         self.addresses = v.get(0, [])
76         self.change = v.get(1, [])
77         self.mpk = v['mpk'].decode('hex')
78
79     def dump(self):
80         return {0:self.addresses, 1:self.change}
81
82     @classmethod
83     def mpk_from_seed(klass, seed):
84         curve = SECP256k1
85         secexp = klass.stretch_key(seed)
86         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
87         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
88         return master_public_key
89
90     @classmethod
91     def stretch_key(self,seed):
92         oldseed = seed
93         for i in range(100000):
94             seed = hashlib.sha256(seed + oldseed).digest()
95         return string_to_number( seed )
96
97     def get_sequence(self, for_change, n):
98         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.mpk ) )
99
100     def get_address(self, for_change, n):
101         pubkey = self.get_pubkey(for_change, n)
102         address = public_key_to_bc_address( pubkey.decode('hex') )
103         return address
104
105     def get_pubkey(self, for_change, n):
106         curve = SECP256k1
107         mpk = self.mpk
108         z = self.get_sequence(for_change, n)
109         master_public_key = ecdsa.VerifyingKey.from_string( mpk, curve = SECP256k1 )
110         pubkey_point = master_public_key.pubkey.point + z*curve.generator
111         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
112         return '04' + public_key2.to_string().encode('hex')
113
114     def get_private_key_from_stretched_exponent(self, for_change, n, secexp):
115         order = generator_secp256k1.order()
116         secexp = ( secexp + self.get_sequence(for_change, n) ) % order
117         pk = number_to_string( secexp, generator_secp256k1.order() )
118         compressed = False
119         return SecretToASecret( pk, compressed )
120         
121     def get_private_key(self, seed, sequence):
122         for_change, n = sequence
123         secexp = self.stretch_key(seed)
124         return self.get_private_key_from_stretched_exponent(for_change, n, secexp)
125
126     def check_seed(self, seed):
127         curve = SECP256k1
128         secexp = self.stretch_key(seed)
129         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
130         master_public_key = master_private_key.get_verifying_key().to_string()
131         if master_public_key != self.mpk:
132             print_error('invalid password (mpk)', self.mpk.encode('hex'), master_public_key.encode('hex'))
133             raise Exception('Invalid password')
134         return True
135
136     def redeem_script(self, sequence):
137         return None
138
139     def get_master_pubkeys(self):
140         return [self.mpk]
141
142     def get_type(self):
143         return _('Old Electrum format')
144
145     def get_keyID(self, sequence):
146         a, b = sequence
147         return 'old(%s,%d,%d)'%(self.mpk,a,b)
148
149
150
151 class BIP32_Account(Account):
152
153     def __init__(self, v):
154         Account.__init__(self, v)
155         self.xpub = v['xpub']
156
157     def dump(self):
158         d = Account.dump(self)
159         d['xpub'] = self.xpub
160         return d
161
162     def get_address(self, for_change, n):
163         pubkey = self.get_pubkey(for_change, n)
164         address = public_key_to_bc_address( pubkey.decode('hex') )
165         return address
166
167     def first_address(self):
168         return self.get_address(0,0)
169
170     def get_master_pubkeys(self):
171         return [self.xpub]
172
173     def get_pubkey_from_x(self, xpub, for_change, n):
174         _, _, _, c, cK = deserialize_xkey(xpub)
175         for i in [for_change, n]:
176             cK, c = CKD_pub(cK, c, i)
177         return cK.encode('hex')
178
179     def get_pubkeys(self, sequence):
180         return sorted(map(lambda x: self.get_pubkey_from_x(x, *sequence), self.get_master_pubkeys()))
181
182     def get_pubkey(self, for_change, n):
183         return self.get_pubkeys((for_change, n))[0]
184
185     def redeem_script(self, sequence):
186         return None
187
188     def get_type(self):
189         return _('Standard 1 of 1')
190
191     def get_keyID(self, sequence):
192         s = '/' + '/'.join( map(lambda x:str(x), sequence) )
193         return '&'.join( map(lambda x: 'bip32(%s,%s)'%(x, s), self.get_master_pubkeys() ) )
194
195
196 class BIP32_Account_2of2(BIP32_Account):
197
198     def __init__(self, v):
199         BIP32_Account.__init__(self, v)
200         self.xpub2 = v['xpub2']
201
202     def dump(self):
203         d = BIP32_Account.dump(self)
204         d['xpub2'] = self.xpub2
205         return d
206
207     def redeem_script(self, sequence):
208         pubkeys = self.get_pubkeys(sequence)
209         return Transaction.multisig_script(pubkeys, 2)
210
211     def get_address(self, for_change, n):
212         address = hash_160_to_bc_address(hash_160(self.redeem_script((for_change, n)).decode('hex')), 5)
213         return address
214
215     def get_master_pubkeys(self):
216         return [self.xpub, self.xpub2]
217
218     def get_type(self):
219         return _('Multisig 2 of 2')
220
221
222 class BIP32_Account_2of3(BIP32_Account_2of2):
223
224     def __init__(self, v):
225         BIP32_Account_2of2.__init__(self, v)
226         self.xpub3 = v['xpub3']
227
228     def dump(self):
229         d = BIP32_Account_2of2.dump(self)
230         d['xpub3'] = self.xpub3
231         return d
232
233     def get_master_pubkeys(self):
234         return [self.xpub, self.xpub2, self.xpub3]
235
236     def get_type(self):
237         return _('Multisig 2 of 3')
238
239
240
241