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