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