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