encryption of bip32 master private keys
[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
22
23 class Account(object):
24     def __init__(self, v):
25         self.addresses = v.get('0', [])
26         self.change = v.get('1', [])
27         self.name = v.get('name', 'unnamed')
28
29     def dump(self):
30         return {'0':self.addresses, '1':self.change, 'name':self.name}
31
32     def get_name(self):
33         return self.name
34
35     def get_addresses(self, for_change):
36         return self.change[:] if for_change else self.addresses[:]
37
38     def create_new_address(self, for_change):
39         addresses = self.change if for_change else self.addresses
40         n = len(addresses)
41         address = self.get_address( for_change, n)
42         addresses.append(address)
43         print address
44         return address
45
46     def get_address(self, for_change, n):
47         pass
48         
49
50
51
52 class OldAccount(Account):
53     """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
54
55     def __init__(self, mpk, mpk2 = None, mpk3 = None):
56         self.mpk = mpk
57         self.mpk2 = mpk2
58         self.mpk3 = mpk3
59
60     @classmethod
61     def mpk_from_seed(klass, seed):
62         curve = SECP256k1
63         secexp = klass.stretch_key(seed)
64         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
65         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
66         return master_public_key
67
68     @classmethod
69     def stretch_key(self,seed):
70         oldseed = seed
71         for i in range(100000):
72             seed = hashlib.sha256(seed + oldseed).digest()
73         return string_to_number( seed )
74
75     def get_sequence(self, sequence, mpk):
76         for_change, n = sequence
77         return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk.decode('hex') ) )
78
79     def get_address(self, sequence):
80         if not self.mpk2:
81             pubkey = self.get_pubkey(sequence)
82             address = public_key_to_bc_address( pubkey.decode('hex') )
83         elif not self.mpk3:
84             pubkey1 = self.get_pubkey(sequence)
85             pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2)
86             address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"]
87         else:
88             pubkey1 = self.get_pubkey(sequence)
89             pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2)
90             pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3)
91             address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"]
92         return address
93
94     def get_pubkey(self, sequence, mpk=None):
95         curve = SECP256k1
96         if mpk is None: mpk = self.mpk
97         z = self.get_sequence(sequence, mpk)
98         master_public_key = ecdsa.VerifyingKey.from_string( mpk.decode('hex'), curve = SECP256k1 )
99         pubkey_point = master_public_key.pubkey.point + z*curve.generator
100         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
101         return '04' + public_key2.to_string().encode('hex')
102
103     def get_private_key_from_stretched_exponent(self, sequence, secexp):
104         order = generator_secp256k1.order()
105         secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order
106         pk = number_to_string( secexp, generator_secp256k1.order() )
107         compressed = False
108         return SecretToASecret( pk, compressed )
109         
110     def get_private_key(self, sequence, seed):
111         secexp = self.stretch_key(seed)
112         return self.get_private_key_from_stretched_exponent(sequence, secexp)
113
114     def get_private_keys(self, sequence_list, seed):
115         secexp = self.stretch_key(seed)
116         return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list]
117
118     def check_seed(self, seed):
119         curve = SECP256k1
120         secexp = self.stretch_key(seed)
121         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
122         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
123         if master_public_key != self.mpk:
124             print_error('invalid password (mpk)')
125             raise BaseException('Invalid password')
126         return True
127
128     def get_input_info(self, sequence):
129         if not self.mpk2:
130             pk_addr = self.get_address(sequence)
131             redeemScript = None
132         elif not self.mpk3:
133             pubkey1 = self.get_pubkey(sequence)
134             pubkey2 = self.get_pubkey(sequence,mpk=self.mpk2)
135             pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key
136             redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript']
137         else:
138             pubkey1 = self.get_pubkey(sequence)
139             pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2)
140             pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3)
141             pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key
142             redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript']
143         return pk_addr, redeemScript
144
145
146
147 class BIP32_Account(Account):
148
149     def __init__(self, v):
150         Account.__init__(self, v)
151         self.c = v['c'].decode('hex')
152         self.K = v['K'].decode('hex')
153         self.cK = v['cK'].decode('hex')
154
155     def dump(self):
156         d = Account.dump(self)
157         d['c'] = self.c.encode('hex')
158         d['K'] = self.K.encode('hex')
159         d['cK'] = self.cK.encode('hex')
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 )
165         return address
166
167     def get_pubkey(self, for_change, n):
168         K = self.K
169         chain = self.c
170         for i in [for_change, n]:
171             K, K_compressed, chain = CKD_prime(K, chain, i)
172         return K_compressed
173
174     def get_private_key(self, sequence, master_k):
175         chain = self.c
176         k = master_k
177         for i in sequence:
178             k, chain = CKD(k, chain, i)
179         return SecretToASecret(k, True)
180
181     def get_private_keys(self, sequence_list, seed):
182         return [ self.get_private_key( sequence, seed) for sequence in sequence_list]
183
184     def check_seed(self, seed):
185         master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
186         assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex'))
187
188     def get_input_info(self, sequence):
189         chain, i = sequence
190         pk_addr = self.get_address(chain, i)
191         redeemScript = None
192         return pk_addr, redeemScript
193
194
195
196 class BIP32_Account_2of2(BIP32_Account):
197
198     def __init__(self, v):
199         BIP32_Account.__init__(self, v)
200         self.c2 = v['c2'].decode('hex')
201         self.K2 = v['K2'].decode('hex')
202         self.cK2 = v['cK2'].decode('hex')
203
204     def dump(self):
205         d = BIP32_Account.dump(self)
206         d['c2'] = self.c2.encode('hex')
207         d['K2'] = self.K2.encode('hex')
208         d['cK2'] = self.cK2.encode('hex')
209         return d
210
211     def get_pubkey2(self, for_change, n):
212         K = self.K2
213         chain = self.c2
214         for i in [for_change, n]:
215             K, K_compressed, chain = CKD_prime(K, chain, i)
216         return K_compressed
217
218     def get_address(self, for_change, n):
219         pubkey1 = self.get_pubkey(for_change, n)
220         pubkey2 = self.get_pubkey2(for_change, n)
221         address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"]
222         return address
223
224     def get_input_info(self, sequence):
225         chain, i = sequence
226         pubkey1 = self.get_pubkey(chain, i)
227         pubkey2 = self.get_pubkey2(chain, i)
228         # fixme
229         pk_addr = None # public_key_to_bc_address( pubkey1 ) # we need to return that address to get the right private key
230         redeemScript = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)['redeemScript']
231         return pk_addr, redeemScript
232