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