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