allow address creation beyond gap limit in GUI. fixes #512
[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_valid(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             assert is_valid(address), "Address " + address + " is invalid!"
783         amount = sum( map(lambda x:x[1], outputs) )
784         inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
785         if not inputs:
786             raise ValueError("Not enough funds")
787         for txin in inputs:
788             self.add_input_info(txin)
789         outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
790         return Transaction.from_io(inputs, outputs)
791
792     def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
793         tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
794         keypairs = {}
795         self.add_keypairs(tx, keypairs, password)
796         if keypairs:
797             self.sign_transaction(tx, keypairs, password)
798         return tx
799
800     def add_input_info(self, txin):
801         address = txin['address']
802         account_id, sequence = self.get_address_index(address)
803         account = self.accounts[account_id]
804         redeemScript = account.redeem_script(sequence)
805         txin['x_pubkeys'] = account.get_xpubkeys(sequence)
806         txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
807         txin['signatures'] = [None] * len(pubkeys)
808
809         if redeemScript:
810             txin['redeemScript'] = redeemScript
811             txin['num_sig'] = 2
812         else:
813             txin['redeemPubkey'] = account.get_pubkey(*sequence)
814             txin['num_sig'] = 1
815
816     def sign_transaction(self, tx, keypairs, password):
817         tx.sign(keypairs)
818         run_hook('sign_transaction', tx, password)
819
820     def sendtx(self, tx):
821         # synchronous
822         h = self.send_tx(tx)
823         self.tx_event.wait()
824         return self.receive_tx(h, tx)
825
826     def send_tx(self, tx):
827         # asynchronous
828         self.tx_event.clear()
829         self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
830         return tx.hash()
831
832     def on_broadcast(self, i, r):
833         self.tx_result = r.get('result')
834         self.tx_event.set()
835
836     def receive_tx(self, tx_hash, tx):
837         out = self.tx_result
838         if out != tx_hash:
839             return False, "error: " + out
840         run_hook('receive_tx', tx, self)
841         return True, out
842
843     def update_password(self, old_password, new_password):
844         if new_password == '':
845             new_password = None
846
847         if self.has_seed():
848             decoded = self.get_seed(old_password)
849             self.seed = pw_encode( decoded, new_password)
850             self.storage.put('seed', self.seed, True)
851
852         imported_account = self.accounts.get(IMPORTED_ACCOUNT)
853         if imported_account:
854             imported_account.update_password(old_password, new_password)
855             self.save_accounts()
856
857         for k, v in self.master_private_keys.items():
858             b = pw_decode(v, old_password)
859             c = pw_encode(b, new_password)
860             self.master_private_keys[k] = c
861         self.storage.put('master_private_keys', self.master_private_keys, True)
862
863         self.use_encryption = (new_password != None)
864         self.storage.put('use_encryption', self.use_encryption,True)
865
866     def freeze(self,addr):
867         if self.is_mine(addr) and addr not in self.frozen_addresses:
868             self.frozen_addresses.append(addr)
869             self.storage.put('frozen_addresses', self.frozen_addresses, True)
870             return True
871         else:
872             return False
873
874     def unfreeze(self,addr):
875         if self.is_mine(addr) and addr in self.frozen_addresses:
876             self.frozen_addresses.remove(addr)
877             self.storage.put('frozen_addresses', self.frozen_addresses, True)
878             return True
879         else:
880             return False
881
882     def set_verifier(self, verifier):
883         self.verifier = verifier
884
885         # review transactions that are in the history
886         for addr, hist in self.history.items():
887             if hist == ['*']: continue
888             for tx_hash, tx_height in hist:
889                 if tx_height>0:
890                     # add it in case it was previously unconfirmed
891                     self.verifier.add(tx_hash, tx_height)
892
893         # if we are on a pruning server, remove unverified transactions
894         vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
895         for tx_hash in self.transactions.keys():
896             if tx_hash not in vr:
897                 self.transactions.pop(tx_hash)
898
899     def check_new_history(self, addr, hist):
900         # check that all tx in hist are relevant
901         if hist != ['*']:
902             for tx_hash, height in hist:
903                 tx = self.transactions.get(tx_hash)
904                 if not tx: continue
905                 if not tx.has_address(addr):
906                     return False
907
908         # check that we are not "orphaning" a transaction
909         old_hist = self.history.get(addr,[])
910         if old_hist == ['*']: return True
911
912         for tx_hash, height in old_hist:
913             if tx_hash in map(lambda x:x[0], hist): continue
914             found = False
915             for _addr, _hist in self.history.items():
916                 if _addr == addr: continue
917                 if _hist == ['*']: continue
918                 _tx_hist = map(lambda x:x[0], _hist)
919                 if tx_hash in _tx_hist:
920                     found = True
921                     break
922
923             if not found:
924                 tx = self.transactions.get(tx_hash)
925                 # tx might not be there
926                 if not tx: continue
927
928                 # already verified?
929                 if self.verifier.get_height(tx_hash):
930                     continue
931                 # unconfirmed tx
932                 print_error("new history is orphaning transaction:", tx_hash)
933                 # check that all outputs are not mine, request histories
934                 ext_requests = []
935                 for _addr, _v in tx.outputs:
936                     # assert not self.is_mine(_addr)
937                     ext_requests.append( ('blockchain.address.get_history', [_addr]) )
938
939                 ext_h = self.network.synchronous_get(ext_requests)
940                 print_error("sync:", ext_requests, ext_h)
941                 height = None
942                 for h in ext_h:
943                     if h == ['*']: continue
944                     for item in h:
945                         if item.get('tx_hash') == tx_hash:
946                             height = item.get('height')
947                 if height:
948                     print_error("found height for", tx_hash, height)
949                     self.verifier.add(tx_hash, height)
950                 else:
951                     print_error("removing orphaned tx from history", tx_hash)
952                     self.transactions.pop(tx_hash)
953
954         return True
955
956     def check_new_tx(self, tx_hash, tx):
957         # 1 check that tx is referenced in addr_history.
958         addresses = []
959         for addr, hist in self.history.items():
960             if hist == ['*']:continue
961             for txh, height in hist:
962                 if txh == tx_hash:
963                     addresses.append(addr)
964
965         if not addresses:
966             return False
967
968         # 2 check that referencing addresses are in the tx
969         for addr in addresses:
970             if not tx.has_address(addr):
971                 return False
972
973         return True
974
975     def start_threads(self, network):
976         from verifier import TxVerifier
977         self.network = network
978         if self.network is not None:
979             self.verifier = TxVerifier(self.network, self.storage)
980             self.verifier.start()
981             self.set_verifier(self.verifier)
982             self.synchronizer = WalletSynchronizer(self, network)
983             self.synchronizer.start()
984         else:
985             self.verifier = None
986             self.synchronizer =None
987
988     def stop_threads(self):
989         if self.network:
990             self.verifier.stop()
991             self.synchronizer.stop()
992
993     def restore(self, cb):
994         pass
995
996     def get_accounts(self):
997         return self.accounts
998
999     def save_accounts(self):
1000         d = {}
1001         for k, v in self.accounts.items():
1002             d[k] = v.dump()
1003         self.storage.put('accounts', d, True)
1004
1005     def can_import(self):
1006         return not self.is_watching_only()
1007
1008     def is_used(self, address):
1009         h = self.history.get(address,[])
1010         c, u = self.get_addr_balance(address)
1011         return len(h), len(h) > 0 and c == -u
1012
1013     def address_is_old(self, address, age_limit=2):
1014         age = -1
1015         h = self.history.get(address, [])
1016         if h == ['*']:
1017             return True
1018         for tx_hash, tx_height in h:
1019             if tx_height == 0:
1020                 tx_age = 0
1021             else:
1022                 tx_age = self.network.get_local_height() - tx_height + 1
1023             if tx_age > age:
1024                 age = tx_age
1025         return age > age_limit
1026
1027
1028 class Imported_Wallet(Abstract_Wallet):
1029
1030     def __init__(self, storage):
1031         Abstract_Wallet.__init__(self, storage)
1032         a = self.accounts.get(IMPORTED_ACCOUNT)
1033         if not a:
1034             self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1035         self.storage.put('wallet_type', 'imported', True)
1036
1037     def is_watching_only(self):
1038         acc = self.accounts[IMPORTED_ACCOUNT]
1039         n = acc.keypairs.values()
1040         return n == [(None, None)] * len(n)
1041
1042     def has_seed(self):
1043         return False
1044
1045     def is_deterministic(self):
1046         return False
1047
1048     def check_password(self, password):
1049         self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1050
1051     def is_used(self, address):
1052         h = self.history.get(address,[])
1053         return len(h), False
1054
1055     def get_master_public_keys(self):
1056         return {}
1057
1058     def is_beyond_limit(self, address, account, is_change):
1059         return False
1060
1061 class Deterministic_Wallet(Abstract_Wallet):
1062
1063     def __init__(self, storage):
1064         Abstract_Wallet.__init__(self, storage)
1065
1066     def has_seed(self):
1067         return self.seed != ''
1068
1069     def is_deterministic(self):
1070         return True
1071
1072     def is_watching_only(self):
1073         return not self.has_seed()
1074
1075     def add_seed(self, seed, password):
1076         if self.seed:
1077             raise Exception("a seed exists")
1078
1079         self.seed_version, self.seed = self.prepare_seed(seed)
1080         if password:
1081             self.seed = pw_encode( self.seed, password)
1082             self.use_encryption = True
1083         else:
1084             self.use_encryption = False
1085
1086         self.storage.put('seed', self.seed, True)
1087         self.storage.put('seed_version', self.seed_version, True)
1088         self.storage.put('use_encryption', self.use_encryption,True)
1089         self.create_master_keys(password)
1090
1091     def get_seed(self, password):
1092         return pw_decode(self.seed, password)
1093
1094     def get_mnemonic(self, password):
1095         return self.get_seed(password)
1096
1097     def change_gap_limit(self, value):
1098         if value >= self.gap_limit:
1099             self.gap_limit = value
1100             self.storage.put('gap_limit', self.gap_limit, True)
1101             #self.interface.poke('synchronizer')
1102             return True
1103
1104         elif value >= self.min_acceptable_gap():
1105             for key, account in self.accounts.items():
1106                 addresses = account[0]
1107                 k = self.num_unused_trailing_addresses(addresses)
1108                 n = len(addresses) - k + value
1109                 addresses = addresses[0:n]
1110                 self.accounts[key][0] = addresses
1111
1112             self.gap_limit = value
1113             self.storage.put('gap_limit', self.gap_limit, True)
1114             self.save_accounts()
1115             return True
1116         else:
1117             return False
1118
1119     def num_unused_trailing_addresses(self, addresses):
1120         k = 0
1121         for a in addresses[::-1]:
1122             if self.history.get(a):break
1123             k = k + 1
1124         return k
1125
1126     def min_acceptable_gap(self):
1127         # fixme: this assumes wallet is synchronized
1128         n = 0
1129         nmax = 0
1130
1131         for account in self.accounts.values():
1132             addresses = account.get_addresses(0)
1133             k = self.num_unused_trailing_addresses(addresses)
1134             for a in addresses[0:-k]:
1135                 if self.history.get(a):
1136                     n = 0
1137                 else:
1138                     n += 1
1139                     if n > nmax: nmax = n
1140         return nmax + 1
1141
1142     def create_new_address(self, account, for_change):
1143         if account is None:
1144             account = self.default_account()
1145         address = account.create_new_address(for_change)
1146         self.history[address] = []
1147         self.synchronizer.add(address)
1148         self.save_accounts()
1149         return address
1150
1151     def synchronize_sequence(self, account, for_change):
1152         limit = self.gap_limit_for_change if for_change else self.gap_limit
1153         while True:
1154             addresses = account.get_addresses(for_change)
1155             if len(addresses) < limit:
1156                 self.create_new_address(account, for_change)
1157                 continue
1158             if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1159                 break
1160             else:
1161                 self.create_new_address(account, for_change)
1162
1163     def check_pending_accounts(self):
1164         for account_id, addr in self.next_addresses.items():
1165             if self.address_is_old(addr):
1166                 print_error( "creating account", account_id )
1167                 xpub = self.master_public_keys[account_id]
1168                 account = BIP32_Account({'xpub':xpub})
1169                 self.add_account(account_id, account)
1170                 self.next_addresses.pop(account_id)
1171
1172     def synchronize_account(self, account):
1173         self.synchronize_sequence(account, 0)
1174         self.synchronize_sequence(account, 1)
1175
1176     def synchronize(self):
1177         self.check_pending_accounts()
1178         for account in self.accounts.values():
1179             if type(account) in [ImportedAccount, PendingAccount]:
1180                 continue
1181             self.synchronize_account(account)
1182
1183     def restore(self, callback):
1184         from i18n import _
1185         def wait_for_wallet():
1186             self.set_up_to_date(False)
1187             while not self.is_up_to_date():
1188                 msg = "%s\n%s %d\n%s %.1f"%(
1189                     _("Please wait..."),
1190                     _("Addresses generated:"),
1191                     len(self.addresses(True)),
1192                     _("Kilobytes received:"),
1193                     self.network.interface.bytes_received/1024.)
1194
1195                 apply(callback, (msg,))
1196                 time.sleep(0.1)
1197
1198         def wait_for_network():
1199             while not self.network.is_connected():
1200                 msg = "%s \n" % (_("Connecting..."))
1201                 apply(callback, (msg,))
1202                 time.sleep(0.1)
1203
1204         # wait until we are connected, because the user might have selected another server
1205         if self.network:
1206             wait_for_network()
1207             wait_for_wallet()
1208         else:
1209             self.synchronize()
1210         self.fill_addressbook()
1211
1212     def create_account(self, name, password):
1213         i = self.num_accounts()
1214         account_id = self.account_id(i)
1215         account = self.make_account(account_id, password)
1216         self.add_account(account_id, account)
1217         if name:
1218             self.set_label(account_id, name)
1219
1220         # add address of the next account
1221         _, _ = self.next_account_address(password)
1222
1223
1224     def add_account(self, account_id, account):
1225         self.accounts[account_id] = account
1226         self.save_accounts()
1227
1228     def account_is_pending(self, k):
1229         return type(self.accounts.get(k)) == PendingAccount
1230
1231     def delete_pending_account(self, k):
1232         assert self.account_is_pending(k)
1233         self.accounts.pop(k)
1234         self.save_accounts()
1235
1236     def create_pending_account(self, name, password):
1237         account_id, addr = self.next_account_address(password)
1238         self.set_label(account_id, name)
1239         self.accounts[account_id] = PendingAccount({'pending':addr})
1240         self.save_accounts()
1241
1242     def is_beyond_limit(self, address, account, is_change):
1243         if type(account) == ImportedAccount:
1244             return False
1245         addr_list = account.get_addresses(is_change)
1246         i = addr_list.index(address)
1247         prev_addresses = addr_list[:max(0, i)]
1248         limit = self.gap_limit_for_change if is_change else self.gap_limit
1249         if len(prev_addresses) < limit:
1250             return False
1251         prev_addresses = prev_addresses[max(0, i - limit):]
1252         for addr in prev_addresses:
1253             if self.address_is_old(addr):
1254                 return False
1255         return True
1256
1257
1258 class NewWallet(Deterministic_Wallet):
1259
1260     def __init__(self, storage):
1261         Deterministic_Wallet.__init__(self, storage)
1262
1263     def default_account(self):
1264         return self.accounts["m/0'"]
1265
1266     def is_watching_only(self):
1267         return self.master_private_keys is {}
1268
1269     def can_create_accounts(self):
1270         return 'm/' in self.master_private_keys.keys()
1271
1272     def get_master_public_key(self):
1273         return self.master_public_keys["m/"]
1274
1275     def get_master_public_keys(self):
1276         out = {}
1277         for k, account in self.accounts.items():
1278             name = self.get_account_name(k)
1279             mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1280             out[name] = mpk_text
1281         return out
1282
1283     def get_master_private_key(self, account, password):
1284         k = self.master_private_keys.get(account)
1285         if not k: return
1286         xpriv = pw_decode( k, password)
1287         return xpriv
1288
1289     def check_password(self, password):
1290         xpriv = self.get_master_private_key( "m/", password )
1291         xpub = self.master_public_keys["m/"]
1292         assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1293
1294     def create_xprv_wallet(self, xprv, password):
1295         xpub = bitcoin.xpub_from_xprv(xprv)
1296         account = BIP32_Account({'xpub':xpub})
1297         account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1298         self.storage.put('seed_version', self.seed_version, True)
1299         self.add_master_private_key(account_id, xprv, password)
1300         self.add_master_public_key(account_id, xpub)
1301         self.add_account(account_id, account)
1302
1303     def create_watching_only_wallet(self, xpub):
1304         account = BIP32_Account({'xpub':xpub})
1305         account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1306         self.storage.put('seed_version', self.seed_version, True)
1307         self.add_master_public_key(account_id, xpub)
1308         self.add_account(account_id, account)
1309
1310     def create_accounts(self, password):
1311         # First check the password is valid (this raises if it isn't).
1312         self.check_password(password)
1313         self.create_account('Main account', password)
1314
1315     def add_master_public_key(self, name, xpub):
1316         self.master_public_keys[name] = xpub
1317         self.storage.put('master_public_keys', self.master_public_keys, True)
1318
1319     def add_master_private_key(self, name, xpriv, password):
1320         self.master_private_keys[name] = pw_encode(xpriv, password)
1321         self.storage.put('master_private_keys', self.master_private_keys, True)
1322
1323     def add_master_keys(self, root, account_id, password):
1324         x = self.master_private_keys.get(root)
1325         if x:
1326             master_xpriv = pw_decode(x, password )
1327             xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1328             self.add_master_public_key(account_id, xpub)
1329             self.add_master_private_key(account_id, xpriv, password)
1330         else:
1331             master_xpub = self.master_public_keys[root]
1332             xpub = bip32_public_derivation(master_xpub, root, account_id)
1333             self.add_master_public_key(account_id, xpub)
1334         return xpub
1335
1336     def create_master_keys(self, password):
1337         xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1338         self.add_master_public_key("m/", xpub)
1339         self.add_master_private_key("m/", xpriv, password)
1340
1341     def find_root_by_master_key(self, xpub):
1342         for key, xpub2 in self.master_public_keys.items():
1343             if key == "m/":continue
1344             if xpub == xpub2:
1345                 return key
1346
1347     def num_accounts(self):
1348         keys = []
1349         for k, v in self.accounts.items():
1350             if type(v) != BIP32_Account:
1351                 continue
1352             keys.append(k)
1353
1354         i = 0
1355         while True:
1356             account_id = self.account_id(i)
1357             if account_id not in keys: break
1358             i += 1
1359         return i
1360
1361     def next_account_address(self, password):
1362         i = self.num_accounts()
1363         account_id = self.account_id(i)
1364
1365         addr = self.next_addresses.get(account_id)
1366         if not addr:
1367             account = self.make_account(account_id, password)
1368             addr = account.first_address()
1369             self.next_addresses[account_id] = addr
1370             self.storage.put('next_addresses', self.next_addresses)
1371
1372         return account_id, addr
1373
1374     def account_id(self, i):
1375         return "m/%d'"%i
1376
1377     def make_account(self, account_id, password):
1378         """Creates and saves the master keys, but does not save the account"""
1379         xpub = self.add_master_keys("m/", account_id, password)
1380         account = BIP32_Account({'xpub':xpub})
1381         return account
1382
1383     def make_seed(self):
1384         import mnemonic, ecdsa
1385         entropy = ecdsa.util.randrange( pow(2,160) )
1386         nonce = 0
1387         while True:
1388             ss = "%040x"%(entropy+nonce)
1389             s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1390             # we keep only 13 words, that's approximately 139 bits of entropy
1391             words = mnemonic.mn_encode(s)[0:13]
1392             seed = ' '.join(words)
1393             if is_new_seed(seed):
1394                 break  # this will remove 8 bits of entropy
1395             nonce += 1
1396         return seed
1397
1398     def prepare_seed(self, seed):
1399         import unicodedata
1400         return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1401
1402
1403 class Wallet_2of2(NewWallet):
1404     """ This class is used for multisignature addresses"""
1405
1406     def __init__(self, storage):
1407         NewWallet.__init__(self, storage)
1408         self.storage.put('wallet_type', '2of2', True)
1409
1410     def default_account(self):
1411         return self.accounts['m/']
1412
1413     def can_create_accounts(self):
1414         return False
1415
1416     def can_import(self):
1417         return False
1418
1419     def create_account(self):
1420         xpub1 = self.master_public_keys.get("m/")
1421         xpub2 = self.master_public_keys.get("cold/")
1422         account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1423         self.add_account('m/', account)
1424
1425     def get_master_public_keys(self):
1426         xpub1 = self.master_public_keys.get("m/")
1427         xpub2 = self.master_public_keys.get("cold/")
1428         return {'hot':xpub1, 'cold':xpub2}
1429
1430     def get_action(self):
1431         xpub1 = self.master_public_keys.get("m/")
1432         xpub2 = self.master_public_keys.get("cold/")
1433         if xpub1 is None:
1434             return 'create_2of2_1'
1435         if xpub2 is None:
1436             return 'create_2of2_2'
1437
1438
1439 class Wallet_2of3(Wallet_2of2):
1440     """ This class is used for multisignature addresses"""
1441
1442     def __init__(self, storage):
1443         Wallet_2of2.__init__(self, storage)
1444         self.storage.put('wallet_type', '2of3', True)
1445
1446     def create_account(self):
1447         xpub1 = self.master_public_keys.get("m/")
1448         xpub2 = self.master_public_keys.get("cold/")
1449         xpub3 = self.master_public_keys.get("remote/")
1450         account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1451         self.add_account('m/', account)
1452
1453     def get_master_public_keys(self):
1454         xpub1 = self.master_public_keys.get("m/")
1455         xpub2 = self.master_public_keys.get("cold/")
1456         xpub3 = self.master_public_keys.get("remote/")
1457         return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1458
1459     def get_action(self):
1460         xpub1 = self.master_public_keys.get("m/")
1461         xpub2 = self.master_public_keys.get("cold/")
1462         xpub3 = self.master_public_keys.get("remote/")
1463         # fixme: we use order of creation
1464         if xpub2 and xpub1 is None:
1465             return 'create_2fa_2'
1466         if xpub1 is None:
1467             return 'create_2of3_1'
1468         if xpub2 is None or xpub3 is None:
1469             return 'create_2of3_2'
1470
1471
1472 class OldWallet(Deterministic_Wallet):
1473
1474     def default_account(self):
1475         return self.accounts[0]
1476
1477     def make_seed(self):
1478         import mnemonic
1479         seed = random_seed(128)
1480         return ' '.join(mnemonic.mn_encode(seed))
1481
1482     def prepare_seed(self, seed):
1483         import mnemonic
1484         # see if seed was entered as hex
1485         seed = seed.strip()
1486         try:
1487             assert seed
1488             seed.decode('hex')
1489             return OLD_SEED_VERSION, str(seed)
1490         except Exception:
1491             pass
1492
1493         words = seed.split()
1494         seed = mnemonic.mn_decode(words)
1495         if not seed:
1496             raise Exception("Invalid seed")
1497
1498         return OLD_SEED_VERSION, seed
1499
1500     def create_master_keys(self, password):
1501         seed = self.get_seed(password)
1502         mpk = OldAccount.mpk_from_seed(seed)
1503         self.storage.put('master_public_key', mpk, True)
1504
1505     def get_master_public_key(self):
1506         return self.storage.get("master_public_key")
1507
1508     def get_master_public_keys(self):
1509         return {'Main Account':self.get_master_public_key()}
1510
1511     def create_accounts(self, password):
1512         mpk = self.storage.get("master_public_key")
1513         self.create_account(mpk)
1514
1515     def create_account(self, mpk):
1516         self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1517         self.save_accounts()
1518
1519     def create_watching_only_wallet(self, mpk):
1520         self.seed_version = OLD_SEED_VERSION
1521         self.storage.put('seed_version', self.seed_version, True)
1522         self.storage.put('master_public_key', mpk, True)
1523         self.create_account(mpk)
1524
1525     def get_seed(self, password):
1526         seed = pw_decode(self.seed, password).encode('utf8')
1527         return seed
1528
1529     def check_password(self, password):
1530         seed = self.get_seed(password)
1531         self.accounts[0].check_seed(seed)
1532
1533     def get_mnemonic(self, password):
1534         import mnemonic
1535         s = self.get_seed(password)
1536         return ' '.join(mnemonic.mn_encode(s))
1537
1538     def check_pending_accounts(self):
1539         pass
1540
1541
1542 # former WalletFactory
1543 class Wallet(object):
1544     """The main wallet "entry point".
1545     This class is actually a factory that will return a wallet of the correct
1546     type when passed a WalletStorage instance."""
1547
1548     def __new__(self, storage):
1549         config = storage.config
1550         if config.get('bitkey', False):
1551             # if user requested support for Bitkey device,
1552             # import Bitkey driver
1553             from wallet_bitkey import WalletBitkey
1554             return WalletBitkey(config)
1555
1556         if storage.get('wallet_type') == '2of2':
1557             return Wallet_2of2(storage)
1558
1559         if storage.get('wallet_type') == '2of3':
1560             return Wallet_2of3(storage)
1561
1562         if storage.get('wallet_type') == 'imported':
1563             return Imported_Wallet(storage)
1564
1565         if not storage.file_exists:
1566             seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1567         else:
1568             seed_version = storage.get('seed_version')
1569             if not seed_version:
1570                 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1571
1572         if seed_version == OLD_SEED_VERSION:
1573             return OldWallet(storage)
1574         elif seed_version == NEW_SEED_VERSION:
1575             return NewWallet(storage)
1576         else:
1577             msg = "This wallet seed is not supported."
1578             if seed_version in [5]:
1579                 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1580             print msg
1581             sys.exit(1)
1582
1583     @classmethod
1584     def is_seed(self, seed):
1585         if not seed:
1586             return False
1587         elif is_old_seed(seed):
1588             return True
1589         elif is_new_seed(seed):
1590             return True
1591         else:
1592             return False
1593
1594     @classmethod
1595     def is_old_mpk(self, mpk):
1596         try:
1597             int(mpk, 16)
1598             assert len(mpk) == 128
1599             return True
1600         except:
1601             return False
1602
1603     @classmethod
1604     def is_xpub(self, text):
1605         try:
1606             assert text[0:4] == 'xpub'
1607             deserialize_xkey(text)
1608             return True
1609         except:
1610             return False
1611
1612     @classmethod
1613     def is_xprv(self, text):
1614         try:
1615             assert text[0:4] == 'xprv'
1616             deserialize_xkey(text)
1617             return True
1618         except:
1619             return False
1620
1621     @classmethod
1622     def is_address(self, text):
1623         if not text:
1624             return False
1625         for x in text.split():
1626             if not bitcoin.is_address(x):
1627                 return False
1628         return True
1629
1630     @classmethod
1631     def is_private_key(self, text):
1632         if not text:
1633             return False
1634         for x in text.split():
1635             if not bitcoin.is_private_key(x):
1636                 return False
1637         return True
1638
1639     @classmethod
1640     def from_seed(self, seed, storage):
1641         if is_old_seed(seed):
1642             klass = OldWallet
1643         elif is_new_seed(seed):
1644             klass = NewWallet
1645         w = klass(storage)
1646         return w
1647
1648     @classmethod
1649     def from_address(self, text, storage):
1650         w = Imported_Wallet(storage)
1651         for x in text.split():
1652             w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1653         w.save_accounts()
1654         return w
1655
1656     @classmethod
1657     def from_private_key(self, text, storage):
1658         w = Imported_Wallet(storage)
1659         for x in text.split():
1660             w.import_key(x, None)
1661         return w
1662
1663     @classmethod
1664     def from_old_mpk(self, mpk, storage):
1665         w = OldWallet(storage)
1666         w.seed = ''
1667         w.create_watching_only_wallet(mpk)
1668         return w
1669
1670     @classmethod
1671     def from_xpub(self, xpub, storage):
1672         w = NewWallet(storage)
1673         w.create_watching_only_wallet(xpub)
1674         return w
1675
1676     @classmethod
1677     def from_xprv(self, xprv, password, storage):
1678         w = NewWallet(storage)
1679         w.create_xprv_wallet(xprv, password)
1680         return w