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