fix #745
[electrum-nvc.git] / lib / wallet.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 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 import sys
20 import os
21 import hashlib
22 import ast
23 import threading
24 import random
25 import time
26 import math
27
28 from util import print_msg, print_error
29
30 from bitcoin import *
31 from account import *
32 from version import *
33
34 from transaction import Transaction
35 from plugins import run_hook
36 import bitcoin
37 from synchronizer import WalletSynchronizer
38
39 COINBASE_MATURITY = 100
40 DUST_THRESHOLD = 5430
41
42 # internal ID for imported account
43 IMPORTED_ACCOUNT = '/x'
44
45
46
47 class WalletStorage:
48
49     def __init__(self, config):
50         self.lock = threading.Lock()
51         self.config = config
52         self.data = {}
53         self.file_exists = False
54         self.path = self.init_path(config)
55         print_error( "wallet path", self.path )
56         if self.path:
57             self.read(self.path)
58
59
60     def init_path(self, config):
61         """Set the path of the wallet."""
62
63         # command line -w option
64         path = config.get('wallet_path')
65         if path:
66             return path
67
68         # path in config file
69         path = config.get('default_wallet_path')
70         if path:
71             return path
72
73         # default path
74         dirpath = os.path.join(config.path, "wallets")
75         if not os.path.exists(dirpath):
76             os.mkdir(dirpath)
77
78         new_path = os.path.join(config.path, "wallets", "default_wallet")
79
80         # default path in pre 1.9 versions
81         old_path = os.path.join(config.path, "electrum.dat")
82         if os.path.exists(old_path) and not os.path.exists(new_path):
83             os.rename(old_path, new_path)
84
85         return new_path
86
87
88     def read(self, path):
89         """Read the contents of the wallet file."""
90         try:
91             with open(self.path, "r") as f:
92                 data = f.read()
93         except IOError:
94             return
95         try:
96             d = ast.literal_eval( data )  #parse raw data from reading wallet file
97         except Exception:
98             raise IOError("Cannot read wallet file.")
99
100         self.data = d
101         self.file_exists = True
102
103
104     def get(self, key, default=None):
105         v = self.data.get(key)
106         if v is None:
107             v = default
108         return v
109
110     def put(self, key, value, save = True):
111
112         with self.lock:
113             if value is not None:
114                 self.data[key] = value
115             elif key in self.data:
116                 self.data.pop(key)
117             if save:
118                 self.write()
119
120     def write(self):
121         s = repr(self.data)
122         f = open(self.path,"w")
123         f.write( s )
124         f.close()
125         if 'ANDROID_DATA' not in os.environ:
126             import stat
127             os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
128
129
130 class Abstract_Wallet:
131     """
132     Wallet classes are created to handle various address generation methods.
133     Completion states (watching-only, single account, no seed, etc) are handled inside classes.
134     """
135
136     def __init__(self, storage):
137         self.storage = storage
138         self.electrum_version = ELECTRUM_VERSION
139         self.gap_limit_for_change = 3 # constant
140         # saved fields
141         self.seed_version          = storage.get('seed_version', NEW_SEED_VERSION)
142         self.gap_limit             = storage.get('gap_limit', 5)
143         self.use_change            = storage.get('use_change',True)
144         self.use_encryption        = storage.get('use_encryption', False)
145         self.seed                  = storage.get('seed', '')               # encrypted
146         self.labels                = storage.get('labels', {})
147         self.frozen_addresses      = storage.get('frozen_addresses',[])
148         self.addressbook           = storage.get('contacts', [])
149
150         self.history               = storage.get('addr_history',{})        # address -> list(txid, height)
151
152         self.fee                   = int(storage.get('fee_per_kb', 10000))
153
154         self.master_public_keys = storage.get('master_public_keys',{})
155         self.master_private_keys = storage.get('master_private_keys', {})
156
157         self.next_addresses = storage.get('next_addresses',{})
158
159
160         # This attribute is set when wallet.start_threads is called.
161         self.synchronizer = None
162
163         self.load_accounts()
164
165         self.transactions = {}
166         tx_list = self.storage.get('transactions',{})
167         for k,v in tx_list.items():
168             try:
169                 tx = Transaction(v)
170             except Exception:
171                 print_msg("Warning: Cannot deserialize transactions. skipping")
172                 continue
173
174             self.add_extra_addresses(tx)
175             self.transactions[k] = tx
176
177         for h,tx in self.transactions.items():
178             if not self.check_new_tx(h, tx):
179                 print_error("removing unreferenced tx", h)
180                 self.transactions.pop(h)
181
182
183         # not saved
184         self.prevout_values = {}     # my own transaction outputs
185         self.spent_outputs = []
186
187         # spv
188         self.verifier = None
189
190         # there is a difference between wallet.up_to_date and interface.is_up_to_date()
191         # interface.is_up_to_date() returns true when all requests have been answered and processed
192         # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
193
194         self.up_to_date = False
195         self.lock = threading.Lock()
196         self.transaction_lock = threading.Lock()
197         self.tx_event = threading.Event()
198         for tx_hash, tx in self.transactions.items():
199             self.update_tx_outputs(tx_hash)
200
201     def add_extra_addresses(self, tx):
202         h = tx.hash()
203         # find the address corresponding to pay-to-pubkey inputs
204         tx.add_extra_addresses(self.transactions)
205         for o in tx.d.get('outputs'):
206             if o.get('is_pubkey'):
207                 for tx2 in self.transactions.values():
208                     tx2.add_extra_addresses({h:tx})
209
210     def get_action(self):
211         pass
212
213     def convert_imported_keys(self, password):
214         for k, v in self.imported_keys.items():
215             sec = pw_decode(v, password)
216             pubkey = public_key_from_private_key(sec)
217             address = public_key_to_bc_address(pubkey.decode('hex'))
218             assert address == k
219             self.import_key(sec, password)
220             self.imported_keys.pop(k)
221         self.storage.put('imported_keys', self.imported_keys)
222
223     def load_accounts(self):
224         self.accounts = {}
225         self.imported_keys = self.storage.get('imported_keys',{})
226
227         d = self.storage.get('accounts', {})
228         for k, v in d.items():
229             if k == 0:
230                 v['mpk'] = self.storage.get('master_public_key')
231                 self.accounts[k] = OldAccount(v)
232             elif v.get('imported'):
233                 self.accounts[k] = ImportedAccount(v)
234             elif v.get('xpub3'):
235                 self.accounts[k] = BIP32_Account_2of3(v)
236             elif v.get('xpub2'):
237                 self.accounts[k] = BIP32_Account_2of2(v)
238             elif v.get('xpub'):
239                 self.accounts[k] = BIP32_Account(v)
240             elif v.get('pending'):
241                 self.accounts[k] = PendingAccount(v)
242             else:
243                 print_error("cannot load account", v)
244
245     def synchronize(self):
246         pass
247
248     def can_create_accounts(self):
249         return False
250
251     def set_up_to_date(self,b):
252         with self.lock: self.up_to_date = b
253
254     def is_up_to_date(self):
255         with self.lock: return self.up_to_date
256
257     def update(self):
258         self.up_to_date = False
259         while not self.is_up_to_date():
260             time.sleep(0.1)
261
262     def is_imported(self, addr):
263         account = self.accounts.get(IMPORTED_ACCOUNT)
264         if account:
265             return addr in account.get_addresses(0)
266         else:
267             return False
268
269     def has_imported_keys(self):
270         account = self.accounts.get(IMPORTED_ACCOUNT)
271         return account is not None
272
273     def import_key(self, sec, password):
274         try:
275             pubkey = public_key_from_private_key(sec)
276             address = public_key_to_bc_address(pubkey.decode('hex'))
277         except Exception:
278             raise Exception('Invalid private key')
279
280         if self.is_mine(address):
281             raise Exception('Address already in wallet')
282
283         if self.accounts.get(IMPORTED_ACCOUNT) is None:
284             self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
285         self.accounts[IMPORTED_ACCOUNT].add(address, pubkey, sec, password)
286         self.save_accounts()
287
288         if self.synchronizer:
289             self.synchronizer.subscribe_to_addresses([address])
290         return address
291
292     def delete_imported_key(self, addr):
293         account = self.accounts[IMPORTED_ACCOUNT]
294         account.remove(addr)
295         if not account.get_addresses(0):
296             self.accounts.pop(IMPORTED_ACCOUNT)
297         self.save_accounts()
298
299     def set_label(self, name, text = None):
300         changed = False
301         old_text = self.labels.get(name)
302         if text:
303             if old_text != text:
304                 self.labels[name] = text
305                 changed = True
306         else:
307             if old_text:
308                 self.labels.pop(name)
309                 changed = True
310
311         if changed:
312             self.storage.put('labels', self.labels, True)
313
314         run_hook('set_label', name, text, changed)
315         return changed
316
317     def addresses(self, include_change = True, _next=True):
318         o = []
319         for a in self.accounts.keys():
320             o += self.get_account_addresses(a, include_change)
321
322         if _next:
323             for addr in self.next_addresses.values():
324                 if addr not in o:
325                     o += [addr]
326         return o
327
328     def is_mine(self, address):
329         return address in self.addresses(True)
330
331     def is_change(self, address):
332         if not self.is_mine(address): return False
333         acct, s = self.get_address_index(address)
334         if s is None: return False
335         return s[0] == 1
336
337     def get_address_index(self, address):
338
339         for account in self.accounts.keys():
340             for for_change in [0,1]:
341                 addresses = self.accounts[account].get_addresses(for_change)
342                 for addr in addresses:
343                     if address == addr:
344                         return account, (for_change, addresses.index(addr))
345
346         for k,v in self.next_addresses.items():
347             if v == address:
348                 return k, (0,0)
349
350         raise Exception("Address not found", address)
351
352     def getpubkeys(self, addr):
353         assert is_address(addr) and self.is_mine(addr)
354         account, sequence = self.get_address_index(addr)
355         a = self.accounts[account]
356         return a.get_pubkeys( sequence )
357
358     def get_private_key(self, address, password):
359         if self.is_watching_only():
360             return []
361         account_id, sequence = self.get_address_index(address)
362         return self.accounts[account_id].get_private_key(sequence, self, password)
363
364     def get_public_keys(self, address):
365         account_id, sequence = self.get_address_index(address)
366         return self.accounts[account_id].get_pubkeys(sequence)
367
368     def can_sign(self, tx):
369
370         if self.is_watching_only():
371             return False
372
373         if tx.is_complete():
374             return False
375
376         addr_list, xpub_list = tx.inputs_to_sign()
377         for addr in addr_list:
378             if self.is_mine(addr):
379                 return True
380
381         mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
382         for xpub, sequence in xpub_list:
383             if xpub in mpk:
384                 return True
385
386         return False
387
388     def add_keypairs(self, tx, keypairs, password):
389         # first check the provided password. This will raise if invalid.
390         self.check_password(password)
391
392         addr_list, xpub_list = tx.inputs_to_sign()
393         for addr in addr_list:
394             if self.is_mine(addr):
395                 private_keys = self.get_private_key(addr, password)
396                 for sec in private_keys:
397                     pubkey = public_key_from_private_key(sec)
398                     keypairs[ pubkey ] = sec
399
400         for xpub, sequence in xpub_list:
401             # look for account that can sign
402             for k, account in self.accounts.items():
403                 if xpub in account.get_master_pubkeys():
404                     break
405             else:
406                 continue
407
408             addr = account.get_address(*sequence)
409             pk = self.get_private_key(addr, password)
410             for sec in pk:
411                 pubkey = public_key_from_private_key(sec)
412                 keypairs[pubkey] = sec
413
414     def signrawtransaction(self, tx, private_keys, password):
415         # check that the password is correct. This will raise if it's not.
416         self.get_seed(password)
417
418         # build a list of public/private keys
419         keypairs = {}
420
421         # add private keys from parameter
422         for sec in private_keys:
423             pubkey = public_key_from_private_key(sec)
424             keypairs[ pubkey ] = sec
425
426         # add private_keys
427         self.add_keypairs(tx, keypairs, password)
428
429         # sign the transaction
430         self.sign_transaction(tx, keypairs, password)
431
432     def sign_message(self, address, message, password):
433         keys = self.get_private_key(address, password)
434         assert len(keys) == 1
435         sec = keys[0]
436         key = regenerate_key(sec)
437         compressed = is_compressed(sec)
438         return key.sign_message(message, compressed, address)
439
440     def decrypt_message(self, pubkey, message, password):
441         address = public_key_to_bc_address(pubkey.decode('hex'))
442         keys = self.get_private_key(address, password)
443         secret = keys[0]
444         ec = regenerate_key(secret)
445         decrypted = ec.decrypt_message(message)
446         return decrypted
447
448     def is_found(self):
449         return self.history.values() != [[]] * len(self.history)
450
451     def add_contact(self, address, label=None):
452         self.addressbook.append(address)
453         self.storage.put('contacts', self.addressbook, True)
454         if label:
455             self.set_label(address, label)
456
457     def delete_contact(self, addr):
458         if addr in self.addressbook:
459             self.addressbook.remove(addr)
460             self.storage.put('addressbook', self.addressbook, True)
461
462     def fill_addressbook(self):
463         for tx_hash, tx in self.transactions.items():
464             is_relevant, is_send, _, _ = self.get_tx_value(tx)
465             if is_send:
466                 for addr, v in tx.outputs:
467                     if not self.is_mine(addr) and addr not in self.addressbook:
468                         self.addressbook.append(addr)
469         # redo labels
470         # self.update_tx_labels()
471
472     def get_num_tx(self, address):
473         n = 0
474         for tx in self.transactions.values():
475             if address in map(lambda x:x[0], tx.outputs): n += 1
476         return n
477
478     def get_address_flags(self, addr):
479         flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
480         flags += "F" if addr in self.frozen_addresses else "-"
481         return flags
482
483     def get_tx_value(self, tx, account=None):
484         domain = self.get_account_addresses(account)
485         return tx.get_value(domain, self.prevout_values)
486
487     def update_tx_outputs(self, tx_hash):
488         tx = self.transactions.get(tx_hash)
489
490         for i, (addr, value) in enumerate(tx.outputs):
491             key = tx_hash+ ':%d'%i
492             self.prevout_values[key] = value
493
494         for item in tx.inputs:
495             if self.is_mine(item.get('address')):
496                 key = item['prevout_hash'] + ':%d'%item['prevout_n']
497                 self.spent_outputs.append(key)
498
499     def get_addr_balance(self, address):
500         #assert self.is_mine(address)
501         h = self.history.get(address,[])
502         if h == ['*']: return 0,0
503         c = u = 0
504         received_coins = []   # list of coins received at address
505
506         for tx_hash, tx_height in h:
507             tx = self.transactions.get(tx_hash)
508             if not tx: continue
509
510             for i, (addr, value) in enumerate(tx.outputs):
511                 if addr == address:
512                     key = tx_hash + ':%d'%i
513                     received_coins.append(key)
514
515         for tx_hash, tx_height in h:
516             tx = self.transactions.get(tx_hash)
517             if not tx: continue
518             v = 0
519
520             for item in tx.inputs:
521                 addr = item.get('address')
522                 if addr == address:
523                     key = item['prevout_hash']  + ':%d'%item['prevout_n']
524                     value = self.prevout_values.get( key )
525                     if key in received_coins:
526                         v -= value
527
528             for i, (addr, value) in enumerate(tx.outputs):
529                 key = tx_hash + ':%d'%i
530                 if addr == address:
531                     v += value
532
533             if tx_height:
534                 c += v
535             else:
536                 u += v
537         return c, u
538
539     def get_account_name(self, k):
540         return self.labels.get(k, self.accounts[k].get_name(k))
541
542     def get_account_names(self):
543         account_names = {}
544         for k in self.accounts.keys():
545             account_names[k] = self.get_account_name(k)
546         return account_names
547
548     def get_account_addresses(self, a, include_change=True):
549         if a is None:
550             o = self.addresses(include_change)
551         elif a in self.accounts:
552             ac = self.accounts[a]
553             o = ac.get_addresses(0)
554             if include_change: o += ac.get_addresses(1)
555         return o
556
557     def get_account_balance(self, account):
558         return self.get_balance(self.get_account_addresses(account))
559
560     def get_frozen_balance(self):
561         return self.get_balance(self.frozen_addresses)
562
563     def get_balance(self, domain=None):
564         if domain is None: domain = self.addresses(True)
565         cc = uu = 0
566         for addr in domain:
567             c, u = self.get_addr_balance(addr)
568             cc += c
569             uu += u
570         return cc, uu
571
572     def get_unspent_coins(self, domain=None):
573         coins = []
574         if domain is None: domain = self.addresses(True)
575         for addr in domain:
576             h = self.history.get(addr, [])
577             if h == ['*']: continue
578             for tx_hash, tx_height in h:
579                 tx = self.transactions.get(tx_hash)
580                 if tx is None: raise Exception("Wallet not synchronized")
581                 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
582                 for o in tx.d.get('outputs'):
583                     output = o.copy()
584                     if output.get('address') != addr: continue
585                     key = tx_hash + ":%d" % output.get('prevout_n')
586                     if key in self.spent_outputs: continue
587                     output['prevout_hash'] = tx_hash
588                     output['height'] = tx_height
589                     output['coinbase'] = is_coinbase
590                     coins.append((tx_height, output))
591
592         # sort by age
593         if coins:
594             coins = sorted(coins)
595             if coins[-1][0] != 0:
596                 while coins[0][0] == 0:
597                     coins = coins[1:] + [ coins[0] ]
598         return [x[1] for x in coins]
599
600     def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
601         """ todo: minimize tx size """
602         total = 0
603         fee = self.fee if fixed_fee is None else fixed_fee
604
605         if not coins:
606             if domain is None:
607                 domain = self.addresses(True)
608             for i in self.frozen_addresses:
609                 if i in domain: domain.remove(i)
610             coins = self.get_unspent_coins(domain)
611
612         inputs = []
613
614         for item in coins:
615             if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
616                 continue
617             v = item.get('value')
618             total += v
619             inputs.append(item)
620             fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
621             if total >= amount + fee: break
622         else:
623             inputs = []
624
625         return inputs, total, fee
626
627     def set_fee(self, fee):
628         if self.fee != fee:
629             self.fee = fee
630             self.storage.put('fee_per_kb', self.fee, True)
631
632     def estimated_fee(self, inputs, num_outputs):
633         estimated_size =  len(inputs) * 180 + num_outputs * 34    # this assumes non-compressed keys
634         fee = self.fee * int(math.ceil(estimated_size/1000.))
635         return fee
636
637     def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
638         "add change to a transaction"
639         change_amount = total - ( amount + fee )
640         if change_amount > DUST_THRESHOLD:
641             if not change_addr:
642
643                 # send change to one of the accounts involved in the tx
644                 address = inputs[0].get('address')
645                 account, _ = self.get_address_index(address)
646
647                 if not self.use_change or account == IMPORTED_ACCOUNT:
648                     change_addr = inputs[-1]['address']
649                 else:
650                     change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
651
652             # Insert the change output at a random position in the outputs
653             posn = random.randint(0, len(outputs))
654             outputs[posn:posn] = [( change_addr,  change_amount)]
655         return outputs
656
657     def get_history(self, address):
658         with self.lock:
659             return self.history.get(address)
660
661     def get_status(self, h):
662         if not h: return None
663         if h == ['*']: return '*'
664         status = ''
665         for tx_hash, height in h:
666             status += tx_hash + ':%d:' % height
667         return hashlib.sha256( status ).digest().encode('hex')
668
669     def receive_tx_callback(self, tx_hash, tx, tx_height):
670
671         with self.transaction_lock:
672             self.add_extra_addresses(tx)
673             if not self.check_new_tx(tx_hash, tx):
674                 # may happen due to pruning
675                 print_error("received transaction that is no longer referenced in history", tx_hash)
676                 return
677             self.transactions[tx_hash] = tx
678             self.network.pending_transactions_for_notifications.append(tx)
679             self.save_transactions()
680             if self.verifier and tx_height>0:
681                 self.verifier.add(tx_hash, tx_height)
682             self.update_tx_outputs(tx_hash)
683
684     def save_transactions(self):
685         tx = {}
686         for k,v in self.transactions.items():
687             tx[k] = str(v)
688         self.storage.put('transactions', tx, True)
689
690     def receive_history_callback(self, addr, hist):
691
692         if not self.check_new_history(addr, hist):
693             raise Exception("error: received history for %s is not consistent with known transactions"%addr)
694
695         with self.lock:
696             self.history[addr] = hist
697             self.storage.put('addr_history', self.history, True)
698
699         if hist != ['*']:
700             for tx_hash, tx_height in hist:
701                 if tx_height>0:
702                     # add it in case it was previously unconfirmed
703                     if self.verifier: self.verifier.add(tx_hash, tx_height)
704
705     def get_tx_history(self, account=None):
706         if not self.verifier:
707             return []
708
709         with self.transaction_lock:
710             history = self.transactions.items()
711             history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
712             result = []
713
714             balance = 0
715             for tx_hash, tx in history:
716                 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
717                 if v is not None: balance += v
718
719             c, u = self.get_account_balance(account)
720
721             if balance != c+u:
722                 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
723
724             balance = c + u - balance
725             for tx_hash, tx in history:
726                 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
727                 if not is_relevant:
728                     continue
729                 if value is not None:
730                     balance += value
731
732                 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
733                 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
734
735         return result
736
737     def get_label(self, tx_hash):
738         label = self.labels.get(tx_hash)
739         is_default = (label == '') or (label is None)
740         if is_default: label = self.get_default_label(tx_hash)
741         return label, is_default
742
743     def get_default_label(self, tx_hash):
744         tx = self.transactions.get(tx_hash)
745         default_label = ''
746         if tx:
747             is_relevant, is_mine, _, _ = self.get_tx_value(tx)
748             if is_mine:
749                 for o in tx.outputs:
750                     o_addr, _ = o
751                     if not self.is_mine(o_addr):
752                         try:
753                             default_label = self.labels[o_addr]
754                         except KeyError:
755                             default_label = '>' + o_addr
756                         break
757                 else:
758                     default_label = '(internal)'
759             else:
760                 for o in tx.outputs:
761                     o_addr, _ = o
762                     if self.is_mine(o_addr) and not self.is_change(o_addr):
763                         break
764                 else:
765                     for o in tx.outputs:
766                         o_addr, _ = o
767                         if self.is_mine(o_addr):
768                             break
769                     else:
770                         o_addr = None
771
772                 if o_addr:
773                     try:
774                         default_label = self.labels[o_addr]
775                     except KeyError:
776                         default_label = '<' + o_addr
777
778         return default_label
779
780     def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
781         for address, x in outputs:
782             if address.startswith('OP_RETURN:'):
783                 continue
784             assert is_address(address), "Address " + address + " is invalid!"
785         amount = sum( map(lambda x:x[1], outputs) )
786         inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
787         if not inputs:
788             raise ValueError("Not enough funds")
789         for txin in inputs:
790             self.add_input_info(txin)
791         outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
792         return Transaction.from_io(inputs, outputs)
793
794     def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
795         tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
796         keypairs = {}
797         self.add_keypairs(tx, keypairs, password)
798         if keypairs:
799             self.sign_transaction(tx, keypairs, password)
800         return tx
801
802     def add_input_info(self, txin):
803         address = txin['address']
804         account_id, sequence = self.get_address_index(address)
805         account = self.accounts[account_id]
806         redeemScript = account.redeem_script(sequence)
807         txin['x_pubkeys'] = account.get_xpubkeys(sequence)
808         txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
809         txin['signatures'] = [None] * len(pubkeys)
810
811         if redeemScript:
812             txin['redeemScript'] = redeemScript
813             txin['num_sig'] = 2
814         else:
815             txin['redeemPubkey'] = account.get_pubkey(*sequence)
816             txin['num_sig'] = 1
817
818     def sign_transaction(self, tx, keypairs, password):
819         tx.sign(keypairs)
820         run_hook('sign_transaction', tx, password)
821
822     def sendtx(self, tx):
823         # synchronous
824         h = self.send_tx(tx)
825         self.tx_event.wait()
826         return self.receive_tx(h, tx)
827
828     def send_tx(self, tx):
829         # asynchronous
830         self.tx_event.clear()
831         self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
832         return tx.hash()
833
834     def on_broadcast(self, i, r):
835         self.tx_result = r.get('result')
836         self.tx_event.set()
837
838     def receive_tx(self, tx_hash, tx):
839         out = self.tx_result
840         if out != tx_hash:
841             return False, "error: " + out
842         run_hook('receive_tx', tx, self)
843         return True, out
844
845     def update_password(self, old_password, new_password):
846         if new_password == '':
847             new_password = None
848
849         if self.has_seed():
850             decoded = self.get_seed(old_password)
851             self.seed = pw_encode( decoded, new_password)
852             self.storage.put('seed', self.seed, True)
853
854         imported_account = self.accounts.get(IMPORTED_ACCOUNT)
855         if imported_account:
856             imported_account.update_password(old_password, new_password)
857             self.save_accounts()
858
859         for k, v in self.master_private_keys.items():
860             b = pw_decode(v, old_password)
861             c = pw_encode(b, new_password)
862             self.master_private_keys[k] = c
863         self.storage.put('master_private_keys', self.master_private_keys, True)
864
865         self.use_encryption = (new_password != None)
866         self.storage.put('use_encryption', self.use_encryption,True)
867
868     def freeze(self,addr):
869         if self.is_mine(addr) and addr not in self.frozen_addresses:
870             self.frozen_addresses.append(addr)
871             self.storage.put('frozen_addresses', self.frozen_addresses, True)
872             return True
873         else:
874             return False
875
876     def unfreeze(self,addr):
877         if self.is_mine(addr) and addr in self.frozen_addresses:
878             self.frozen_addresses.remove(addr)
879             self.storage.put('frozen_addresses', self.frozen_addresses, True)
880             return True
881         else:
882             return False
883
884     def set_verifier(self, verifier):
885         self.verifier = verifier
886
887         # review transactions that are in the history
888         for addr, hist in self.history.items():
889             if hist == ['*']: continue
890             for tx_hash, tx_height in hist:
891                 if tx_height>0:
892                     # add it in case it was previously unconfirmed
893                     self.verifier.add(tx_hash, tx_height)
894
895         # if we are on a pruning server, remove unverified transactions
896         vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
897         for tx_hash in self.transactions.keys():
898             if tx_hash not in vr:
899                 self.transactions.pop(tx_hash)
900
901     def check_new_history(self, addr, hist):
902         # check that all tx in hist are relevant
903         if hist != ['*']:
904             for tx_hash, height in hist:
905                 tx = self.transactions.get(tx_hash)
906                 if not tx: continue
907                 if not tx.has_address(addr):
908                     return False
909
910         # check that we are not "orphaning" a transaction
911         old_hist = self.history.get(addr,[])
912         if old_hist == ['*']: return True
913
914         for tx_hash, height in old_hist:
915             if tx_hash in map(lambda x:x[0], hist): continue
916             found = False
917             for _addr, _hist in self.history.items():
918                 if _addr == addr: continue
919                 if _hist == ['*']: continue
920                 _tx_hist = map(lambda x:x[0], _hist)
921                 if tx_hash in _tx_hist:
922                     found = True
923                     break
924
925             if not found:
926                 tx = self.transactions.get(tx_hash)
927                 # tx might not be there
928                 if not tx: continue
929
930                 # already verified?
931                 if self.verifier.get_height(tx_hash):
932                     continue
933                 # unconfirmed tx
934                 print_error("new history is orphaning transaction:", tx_hash)
935                 # check that all outputs are not mine, request histories
936                 ext_requests = []
937                 for _addr, _v in tx.outputs:
938                     # assert not self.is_mine(_addr)
939                     ext_requests.append( ('blockchain.address.get_history', [_addr]) )
940
941                 ext_h = self.network.synchronous_get(ext_requests)
942                 print_error("sync:", ext_requests, ext_h)
943                 height = None
944                 for h in ext_h:
945                     if h == ['*']: continue
946                     for item in h:
947                         if item.get('tx_hash') == tx_hash:
948                             height = item.get('height')
949                 if height:
950                     print_error("found height for", tx_hash, height)
951                     self.verifier.add(tx_hash, height)
952                 else:
953                     print_error("removing orphaned tx from history", tx_hash)
954                     self.transactions.pop(tx_hash)
955
956         return True
957
958     def check_new_tx(self, tx_hash, tx):
959         # 1 check that tx is referenced in addr_history.
960         addresses = []
961         for addr, hist in self.history.items():
962             if hist == ['*']:continue
963             for txh, height in hist:
964                 if txh == tx_hash:
965                     addresses.append(addr)
966
967         if not addresses:
968             return False
969
970         # 2 check that referencing addresses are in the tx
971         for addr in addresses:
972             if not tx.has_address(addr):
973                 return False
974
975         return True
976
977     def start_threads(self, network):
978         from verifier import TxVerifier
979         self.network = network
980         if self.network is not None:
981             self.verifier = TxVerifier(self.network, self.storage)
982             self.verifier.start()
983             self.set_verifier(self.verifier)
984             self.synchronizer = WalletSynchronizer(self, network)
985             self.synchronizer.start()
986         else:
987             self.verifier = None
988             self.synchronizer =None
989
990     def stop_threads(self):
991         if self.network:
992             self.verifier.stop()
993             self.synchronizer.stop()
994
995     def restore(self, cb):
996         pass
997
998     def get_accounts(self):
999         return self.accounts
1000
1001     def save_accounts(self):
1002         d = {}
1003         for k, v in self.accounts.items():
1004             d[k] = v.dump()
1005         self.storage.put('accounts', d, True)
1006
1007     def can_import(self):
1008         return not self.is_watching_only()
1009
1010     def is_used(self, address):
1011         h = self.history.get(address,[])
1012         c, u = self.get_addr_balance(address)
1013         return len(h), len(h) > 0 and c == -u
1014
1015     def address_is_old(self, address, age_limit=2):
1016         age = -1
1017         h = self.history.get(address, [])
1018         if h == ['*']:
1019             return True
1020         for tx_hash, tx_height in h:
1021             if tx_height == 0:
1022                 tx_age = 0
1023             else:
1024                 tx_age = self.network.get_local_height() - tx_height + 1
1025             if tx_age > age:
1026                 age = tx_age
1027         return age > age_limit
1028
1029
1030 class Imported_Wallet(Abstract_Wallet):
1031
1032     def __init__(self, storage):
1033         Abstract_Wallet.__init__(self, storage)
1034         a = self.accounts.get(IMPORTED_ACCOUNT)
1035         if not a:
1036             self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1037         self.storage.put('wallet_type', 'imported', True)
1038
1039     def is_watching_only(self):
1040         acc = self.accounts[IMPORTED_ACCOUNT]
1041         n = acc.keypairs.values()
1042         return n == [(None, None)] * len(n)
1043
1044     def has_seed(self):
1045         return False
1046
1047     def is_deterministic(self):
1048         return False
1049
1050     def check_password(self, password):
1051         self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1052
1053     def is_used(self, address):
1054         h = self.history.get(address,[])
1055         return len(h), False
1056
1057     def get_master_public_keys(self):
1058         return {}
1059
1060     def is_beyond_limit(self, address, account, is_change):
1061         return False
1062
1063 class Deterministic_Wallet(Abstract_Wallet):
1064
1065     def __init__(self, storage):
1066         Abstract_Wallet.__init__(self, storage)
1067
1068     def has_seed(self):
1069         return self.seed != ''
1070
1071     def is_deterministic(self):
1072         return True
1073
1074     def is_watching_only(self):
1075         return not self.has_seed()
1076
1077     def add_seed(self, seed, password):
1078         if self.seed:
1079             raise Exception("a seed exists")
1080
1081         self.seed_version, self.seed = self.prepare_seed(seed)
1082         if password:
1083             self.seed = pw_encode( self.seed, password)
1084             self.use_encryption = True
1085         else:
1086             self.use_encryption = False
1087
1088         self.storage.put('seed', self.seed, True)
1089         self.storage.put('seed_version', self.seed_version, True)
1090         self.storage.put('use_encryption', self.use_encryption,True)
1091         self.create_master_keys(password)
1092
1093     def get_seed(self, password):
1094         return pw_decode(self.seed, password)
1095
1096     def get_mnemonic(self, password):
1097         return self.get_seed(password)
1098
1099     def change_gap_limit(self, value):
1100         if value >= self.gap_limit:
1101             self.gap_limit = value
1102             self.storage.put('gap_limit', self.gap_limit, True)
1103             #self.interface.poke('synchronizer')
1104             return True
1105
1106         elif value >= self.min_acceptable_gap():
1107             for key, account in self.accounts.items():
1108                 addresses = account[0]
1109                 k = self.num_unused_trailing_addresses(addresses)
1110                 n = len(addresses) - k + value
1111                 addresses = addresses[0:n]
1112                 self.accounts[key][0] = addresses
1113
1114             self.gap_limit = value
1115             self.storage.put('gap_limit', self.gap_limit, True)
1116             self.save_accounts()
1117             return True
1118         else:
1119             return False
1120
1121     def num_unused_trailing_addresses(self, addresses):
1122         k = 0
1123         for a in addresses[::-1]:
1124             if self.history.get(a):break
1125             k = k + 1
1126         return k
1127
1128     def min_acceptable_gap(self):
1129         # fixme: this assumes wallet is synchronized
1130         n = 0
1131         nmax = 0
1132
1133         for account in self.accounts.values():
1134             addresses = account.get_addresses(0)
1135             k = self.num_unused_trailing_addresses(addresses)
1136             for a in addresses[0:-k]:
1137                 if self.history.get(a):
1138                     n = 0
1139                 else:
1140                     n += 1
1141                     if n > nmax: nmax = n
1142         return nmax + 1
1143
1144     def create_new_address(self, account=None, for_change=0):
1145         if account is None:
1146             account = self.default_account()
1147         address = account.create_new_address(for_change)
1148         self.history[address] = []
1149         if self.synchronizer:
1150             self.synchronizer.add(address)
1151         self.save_accounts()
1152         return address
1153
1154     def synchronize_sequence(self, account, for_change):
1155         limit = self.gap_limit_for_change if for_change else self.gap_limit
1156         while True:
1157             addresses = account.get_addresses(for_change)
1158             if len(addresses) < limit:
1159                 self.create_new_address(account, for_change)
1160                 continue
1161             if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1162                 break
1163             else:
1164                 self.create_new_address(account, for_change)
1165
1166     def check_pending_accounts(self):
1167         for account_id, addr in self.next_addresses.items():
1168             if self.address_is_old(addr):
1169                 print_error( "creating account", account_id )
1170                 xpub = self.master_public_keys[account_id]
1171                 account = BIP32_Account({'xpub':xpub})
1172                 self.add_account(account_id, account)
1173                 self.next_addresses.pop(account_id)
1174
1175     def synchronize_account(self, account):
1176         self.synchronize_sequence(account, 0)
1177         self.synchronize_sequence(account, 1)
1178
1179     def synchronize(self):
1180         self.check_pending_accounts()
1181         for account in self.accounts.values():
1182             if type(account) in [ImportedAccount, PendingAccount]:
1183                 continue
1184             self.synchronize_account(account)
1185
1186     def restore(self, callback):
1187         from i18n import _
1188         def wait_for_wallet():
1189             self.set_up_to_date(False)
1190             while not self.is_up_to_date():
1191                 msg = "%s\n%s %d\n%s %.1f"%(
1192                     _("Please wait..."),
1193                     _("Addresses generated:"),
1194                     len(self.addresses(True)),
1195                     _("Kilobytes received:"),
1196                     self.network.interface.bytes_received/1024.)
1197
1198                 apply(callback, (msg,))
1199                 time.sleep(0.1)
1200
1201         def wait_for_network():
1202             while not self.network.is_connected():
1203                 msg = "%s \n" % (_("Connecting..."))
1204                 apply(callback, (msg,))
1205                 time.sleep(0.1)
1206
1207         # wait until we are connected, because the user might have selected another server
1208         if self.network:
1209             wait_for_network()
1210             wait_for_wallet()
1211         else:
1212             self.synchronize()
1213         self.fill_addressbook()
1214
1215     def create_account(self, name, password):
1216         i = self.num_accounts()
1217         account_id = self.account_id(i)
1218         account = self.make_account(account_id, password)
1219         self.add_account(account_id, account)
1220         if name:
1221             self.set_label(account_id, name)
1222
1223         # add address of the next account
1224         _, _ = self.next_account_address(password)
1225
1226
1227     def add_account(self, account_id, account):
1228         self.accounts[account_id] = account
1229         self.save_accounts()
1230
1231     def account_is_pending(self, k):
1232         return type(self.accounts.get(k)) == PendingAccount
1233
1234     def delete_pending_account(self, k):
1235         assert self.account_is_pending(k)
1236         self.accounts.pop(k)
1237         self.save_accounts()
1238
1239     def create_pending_account(self, name, password):
1240         account_id, addr = self.next_account_address(password)
1241         self.set_label(account_id, name)
1242         self.accounts[account_id] = PendingAccount({'pending':addr})
1243         self.save_accounts()
1244
1245     def is_beyond_limit(self, address, account, is_change):
1246         if type(account) == ImportedAccount:
1247             return False
1248         addr_list = account.get_addresses(is_change)
1249         i = addr_list.index(address)
1250         prev_addresses = addr_list[:max(0, i)]
1251         limit = self.gap_limit_for_change if is_change else self.gap_limit
1252         if len(prev_addresses) < limit:
1253             return False
1254         prev_addresses = prev_addresses[max(0, i - limit):]
1255         for addr in prev_addresses:
1256             if self.address_is_old(addr):
1257                 return False
1258         return True
1259
1260
1261 class NewWallet(Deterministic_Wallet):
1262
1263     def __init__(self, storage):
1264         Deterministic_Wallet.__init__(self, storage)
1265
1266     def default_account(self):
1267         return self.accounts["m/0'"]
1268
1269     def is_watching_only(self):
1270         return self.master_private_keys is {}
1271
1272     def can_create_accounts(self):
1273         return 'm/' in self.master_private_keys.keys()
1274
1275     def get_master_public_key(self):
1276         return self.master_public_keys["m/"]
1277
1278     def get_master_public_keys(self):
1279         out = {}
1280         for k, account in self.accounts.items():
1281             name = self.get_account_name(k)
1282             mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1283             out[name] = mpk_text
1284         return out
1285
1286     def get_master_private_key(self, account, password):
1287         k = self.master_private_keys.get(account)
1288         if not k: return
1289         xpriv = pw_decode( k, password)
1290         return xpriv
1291
1292     def check_password(self, password):
1293         xpriv = self.get_master_private_key( "m/", password )
1294         xpub = self.master_public_keys["m/"]
1295         assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1296
1297     def create_xprv_wallet(self, xprv, password):
1298         xpub = bitcoin.xpub_from_xprv(xprv)
1299         account = BIP32_Account({'xpub':xpub})
1300         account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1301         self.storage.put('seed_version', self.seed_version, True)
1302         self.add_master_private_key(account_id, xprv, password)
1303         self.add_master_public_key(account_id, xpub)
1304         self.add_account(account_id, account)
1305
1306     def create_watching_only_wallet(self, xpub):
1307         account = BIP32_Account({'xpub':xpub})
1308         account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1309         self.storage.put('seed_version', self.seed_version, True)
1310         self.add_master_public_key(account_id, xpub)
1311         self.add_account(account_id, account)
1312
1313     def create_accounts(self, password):
1314         # First check the password is valid (this raises if it isn't).
1315         self.check_password(password)
1316         self.create_account('Main account', password)
1317
1318     def add_master_public_key(self, name, xpub):
1319         self.master_public_keys[name] = xpub
1320         self.storage.put('master_public_keys', self.master_public_keys, True)
1321
1322     def add_master_private_key(self, name, xpriv, password):
1323         self.master_private_keys[name] = pw_encode(xpriv, password)
1324         self.storage.put('master_private_keys', self.master_private_keys, True)
1325
1326     def add_master_keys(self, root, account_id, password):
1327         x = self.master_private_keys.get(root)
1328         if x:
1329             master_xpriv = pw_decode(x, password )
1330             xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1331             self.add_master_public_key(account_id, xpub)
1332             self.add_master_private_key(account_id, xpriv, password)
1333         else:
1334             master_xpub = self.master_public_keys[root]
1335             xpub = bip32_public_derivation(master_xpub, root, account_id)
1336             self.add_master_public_key(account_id, xpub)
1337         return xpub
1338
1339     def create_master_keys(self, password):
1340         xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1341         self.add_master_public_key("m/", xpub)
1342         self.add_master_private_key("m/", xpriv, password)
1343
1344     def find_root_by_master_key(self, xpub):
1345         for key, xpub2 in self.master_public_keys.items():
1346             if key == "m/":continue
1347             if xpub == xpub2:
1348                 return key
1349
1350     def num_accounts(self):
1351         keys = []
1352         for k, v in self.accounts.items():
1353             if type(v) != BIP32_Account:
1354                 continue
1355             keys.append(k)
1356
1357         i = 0
1358         while True:
1359             account_id = self.account_id(i)
1360             if account_id not in keys: break
1361             i += 1
1362         return i
1363
1364     def next_account_address(self, password):
1365         i = self.num_accounts()
1366         account_id = self.account_id(i)
1367
1368         addr = self.next_addresses.get(account_id)
1369         if not addr:
1370             account = self.make_account(account_id, password)
1371             addr = account.first_address()
1372             self.next_addresses[account_id] = addr
1373             self.storage.put('next_addresses', self.next_addresses)
1374
1375         return account_id, addr
1376
1377     def account_id(self, i):
1378         return "m/%d'"%i
1379
1380     def make_account(self, account_id, password):
1381         """Creates and saves the master keys, but does not save the account"""
1382         xpub = self.add_master_keys("m/", account_id, password)
1383         account = BIP32_Account({'xpub':xpub})
1384         return account
1385
1386     def make_seed(self):
1387         import mnemonic, ecdsa
1388         entropy = ecdsa.util.randrange( pow(2,160) )
1389         nonce = 0
1390         while True:
1391             ss = "%040x"%(entropy+nonce)
1392             s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1393             # we keep only 13 words, that's approximately 139 bits of entropy
1394             words = mnemonic.mn_encode(s)[0:13]
1395             seed = ' '.join(words)
1396             if is_new_seed(seed):
1397                 break  # this will remove 8 bits of entropy
1398             nonce += 1
1399         return seed
1400
1401     def prepare_seed(self, seed):
1402         import unicodedata
1403         return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1404
1405
1406 class Wallet_2of2(NewWallet):
1407     """ This class is used for multisignature addresses"""
1408
1409     def __init__(self, storage):
1410         NewWallet.__init__(self, storage)
1411         self.storage.put('wallet_type', '2of2', True)
1412
1413     def default_account(self):
1414         return self.accounts['m/']
1415
1416     def can_create_accounts(self):
1417         return False
1418
1419     def can_import(self):
1420         return False
1421
1422     def create_account(self):
1423         xpub1 = self.master_public_keys.get("m/")
1424         xpub2 = self.master_public_keys.get("cold/")
1425         account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1426         self.add_account('m/', account)
1427
1428     def get_master_public_keys(self):
1429         xpub1 = self.master_public_keys.get("m/")
1430         xpub2 = self.master_public_keys.get("cold/")
1431         return {'hot':xpub1, 'cold':xpub2}
1432
1433     def get_action(self):
1434         xpub1 = self.master_public_keys.get("m/")
1435         xpub2 = self.master_public_keys.get("cold/")
1436         if xpub1 is None:
1437             return 'create_2of2_1'
1438         if xpub2 is None:
1439             return 'create_2of2_2'
1440
1441
1442 class Wallet_2of3(Wallet_2of2):
1443     """ This class is used for multisignature addresses"""
1444
1445     def __init__(self, storage):
1446         Wallet_2of2.__init__(self, storage)
1447         self.storage.put('wallet_type', '2of3', True)
1448
1449     def create_account(self):
1450         xpub1 = self.master_public_keys.get("m/")
1451         xpub2 = self.master_public_keys.get("cold/")
1452         xpub3 = self.master_public_keys.get("remote/")
1453         account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1454         self.add_account('m/', account)
1455
1456     def get_master_public_keys(self):
1457         xpub1 = self.master_public_keys.get("m/")
1458         xpub2 = self.master_public_keys.get("cold/")
1459         xpub3 = self.master_public_keys.get("remote/")
1460         return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1461
1462     def get_action(self):
1463         xpub1 = self.master_public_keys.get("m/")
1464         xpub2 = self.master_public_keys.get("cold/")
1465         xpub3 = self.master_public_keys.get("remote/")
1466         # fixme: we use order of creation
1467         if xpub2 and xpub1 is None:
1468             return 'create_2fa_2'
1469         if xpub1 is None:
1470             return 'create_2of3_1'
1471         if xpub2 is None or xpub3 is None:
1472             return 'create_2of3_2'
1473
1474
1475 class OldWallet(Deterministic_Wallet):
1476
1477     def default_account(self):
1478         return self.accounts[0]
1479
1480     def make_seed(self):
1481         import mnemonic
1482         seed = random_seed(128)
1483         return ' '.join(mnemonic.mn_encode(seed))
1484
1485     def prepare_seed(self, seed):
1486         import mnemonic
1487         # see if seed was entered as hex
1488         seed = seed.strip()
1489         try:
1490             assert seed
1491             seed.decode('hex')
1492             return OLD_SEED_VERSION, str(seed)
1493         except Exception:
1494             pass
1495
1496         words = seed.split()
1497         seed = mnemonic.mn_decode(words)
1498         if not seed:
1499             raise Exception("Invalid seed")
1500
1501         return OLD_SEED_VERSION, seed
1502
1503     def create_master_keys(self, password):
1504         seed = self.get_seed(password)
1505         mpk = OldAccount.mpk_from_seed(seed)
1506         self.storage.put('master_public_key', mpk, True)
1507
1508     def get_master_public_key(self):
1509         return self.storage.get("master_public_key")
1510
1511     def get_master_public_keys(self):
1512         return {'Main Account':self.get_master_public_key()}
1513
1514     def create_accounts(self, password):
1515         mpk = self.storage.get("master_public_key")
1516         self.create_account(mpk)
1517
1518     def create_account(self, mpk):
1519         self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1520         self.save_accounts()
1521
1522     def create_watching_only_wallet(self, mpk):
1523         self.seed_version = OLD_SEED_VERSION
1524         self.storage.put('seed_version', self.seed_version, True)
1525         self.storage.put('master_public_key', mpk, True)
1526         self.create_account(mpk)
1527
1528     def get_seed(self, password):
1529         seed = pw_decode(self.seed, password).encode('utf8')
1530         return seed
1531
1532     def check_password(self, password):
1533         seed = self.get_seed(password)
1534         self.accounts[0].check_seed(seed)
1535
1536     def get_mnemonic(self, password):
1537         import mnemonic
1538         s = self.get_seed(password)
1539         return ' '.join(mnemonic.mn_encode(s))
1540
1541     def check_pending_accounts(self):
1542         pass
1543
1544
1545 # former WalletFactory
1546 class Wallet(object):
1547     """The main wallet "entry point".
1548     This class is actually a factory that will return a wallet of the correct
1549     type when passed a WalletStorage instance."""
1550
1551     def __new__(self, storage):
1552         config = storage.config
1553         if config.get('bitkey', False):
1554             # if user requested support for Bitkey device,
1555             # import Bitkey driver
1556             from wallet_bitkey import WalletBitkey
1557             return WalletBitkey(config)
1558
1559         if storage.get('wallet_type') == '2of2':
1560             return Wallet_2of2(storage)
1561
1562         if storage.get('wallet_type') == '2of3':
1563             return Wallet_2of3(storage)
1564
1565         if storage.get('wallet_type') == 'imported':
1566             return Imported_Wallet(storage)
1567
1568         if not storage.file_exists:
1569             seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1570         else:
1571             seed_version = storage.get('seed_version')
1572             if not seed_version:
1573                 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1574
1575         if seed_version == OLD_SEED_VERSION:
1576             return OldWallet(storage)
1577         elif seed_version == NEW_SEED_VERSION:
1578             return NewWallet(storage)
1579         else:
1580             msg = "This wallet seed is not supported."
1581             if seed_version in [5]:
1582                 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1583             print msg
1584             sys.exit(1)
1585
1586     @classmethod
1587     def is_seed(self, seed):
1588         if not seed:
1589             return False
1590         elif is_old_seed(seed):
1591             return True
1592         elif is_new_seed(seed):
1593             return True
1594         else:
1595             return False
1596
1597     @classmethod
1598     def is_old_mpk(self, mpk):
1599         try:
1600             int(mpk, 16)
1601             assert len(mpk) == 128
1602             return True
1603         except:
1604             return False
1605
1606     @classmethod
1607     def is_xpub(self, text):
1608         try:
1609             assert text[0:4] == 'xpub'
1610             deserialize_xkey(text)
1611             return True
1612         except:
1613             return False
1614
1615     @classmethod
1616     def is_xprv(self, text):
1617         try:
1618             assert text[0:4] == 'xprv'
1619             deserialize_xkey(text)
1620             return True
1621         except:
1622             return False
1623
1624     @classmethod
1625     def is_address(self, text):
1626         if not text:
1627             return False
1628         for x in text.split():
1629             if not bitcoin.is_address(x):
1630                 return False
1631         return True
1632
1633     @classmethod
1634     def is_private_key(self, text):
1635         if not text:
1636             return False
1637         for x in text.split():
1638             if not bitcoin.is_private_key(x):
1639                 return False
1640         return True
1641
1642     @classmethod
1643     def from_seed(self, seed, storage):
1644         if is_old_seed(seed):
1645             klass = OldWallet
1646         elif is_new_seed(seed):
1647             klass = NewWallet
1648         w = klass(storage)
1649         return w
1650
1651     @classmethod
1652     def from_address(self, text, storage):
1653         w = Imported_Wallet(storage)
1654         for x in text.split():
1655             w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1656         w.save_accounts()
1657         return w
1658
1659     @classmethod
1660     def from_private_key(self, text, storage):
1661         w = Imported_Wallet(storage)
1662         for x in text.split():
1663             w.import_key(x, None)
1664         return w
1665
1666     @classmethod
1667     def from_old_mpk(self, mpk, storage):
1668         w = OldWallet(storage)
1669         w.seed = ''
1670         w.create_watching_only_wallet(mpk)
1671         return w
1672
1673     @classmethod
1674     def from_xpub(self, xpub, storage):
1675         w = NewWallet(storage)
1676         w.create_watching_only_wallet(xpub)
1677         return w
1678
1679     @classmethod
1680     def from_xprv(self, xprv, password, storage):
1681         w = NewWallet(storage)
1682         w.create_xprv_wallet(xprv, password)
1683         return w