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