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