3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
28 from util import print_msg, print_error
34 from transaction import Transaction
35 from plugins import run_hook
37 from synchronizer import WalletSynchronizer
39 COINBASE_MATURITY = 100
42 # internal ID for imported account
43 IMPORTED_ACCOUNT = '/x'
46 class WalletStorage(object):
48 def __init__(self, config):
49 self.lock = threading.RLock()
52 self.file_exists = False
53 self.path = self.init_path(config)
54 print_error( "wallet path", self.path )
58 def init_path(self, config):
59 """Set the path of the wallet."""
61 # command line -w option
62 path = config.get('wallet_path')
67 path = config.get('default_wallet_path')
72 dirpath = os.path.join(config.path, "wallets")
73 if not os.path.exists(dirpath):
76 new_path = os.path.join(config.path, "wallets", "default_wallet")
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)
86 """Read the contents of the wallet file."""
88 with open(self.path, "r") as f:
93 d = ast.literal_eval( data ) #parse raw data from reading wallet file
95 raise IOError("Cannot read wallet file.")
98 self.file_exists = True
100 def get(self, key, default=None):
103 v = self.data.get(key)
108 def put(self, key, value, save = True):
111 if value is not None:
112 self.data[key] = value
113 elif key in self.data:
120 f = open(self.path,"w")
123 if 'ANDROID_DATA' not in os.environ:
125 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
128 class Abstract_Wallet(object):
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.
133 def __init__(self, storage):
134 self.storage = storage
135 self.electrum_version = ELECTRUM_VERSION
136 self.gap_limit_for_change = 3 # constant
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', [])
147 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
149 self.fee = int(storage.get('fee_per_kb', 10000))
151 self.next_addresses = storage.get('next_addresses',{})
153 # This attribute is set when wallet.start_threads is called.
154 self.synchronizer = None
156 # imported_keys is deprecated. The GUI should call convert_imported_keys
157 self.imported_keys = self.storage.get('imported_keys',{})
161 self.load_transactions()
164 self.prevout_values = {} # my own transaction outputs
165 self.spent_outputs = []
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)
178 def load_transactions(self):
179 self.transactions = {}
180 tx_list = self.storage.get('transactions',{})
181 for k, raw in tx_list.items():
183 tx = Transaction.deserialize(raw)
185 print_msg("Warning: Cannot deserialize transactions. skipping")
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)
194 def add_pubkey_addresses(self, tx):
195 # find the address corresponding to pay-to-pubkey inputs
199 tx.add_pubkey_addresses(self.transactions)
201 # outputs of tx: inputs of tx2
202 for type, x, v in tx.outputs:
204 for tx2 in self.transactions.values():
205 tx2.add_pubkey_addresses({h:tx})
207 def get_action(self):
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'))
216 self.import_key(sec, password)
217 self.imported_keys.pop(k)
218 self.storage.put('imported_keys', self.imported_keys)
220 def load_accounts(self):
223 d = self.storage.get('accounts', {})
224 for k, v in d.items():
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)
231 self.accounts[k] = BIP32_Account_2of3(v)
233 self.accounts[k] = BIP32_Account_2of2(v)
235 self.accounts[k] = BIP32_Account(v)
236 elif v.get('pending'):
237 self.accounts[k] = PendingAccount(v)
239 print_error("cannot load account", v)
241 def synchronize(self):
244 def can_create_accounts(self):
247 def set_up_to_date(self,b):
248 with self.lock: self.up_to_date = b
250 def is_up_to_date(self):
251 with self.lock: return self.up_to_date
254 self.up_to_date = False
255 while not self.is_up_to_date():
258 def is_imported(self, addr):
259 account = self.accounts.get(IMPORTED_ACCOUNT)
261 return addr in account.get_addresses(0)
265 def has_imported_keys(self):
266 account = self.accounts.get(IMPORTED_ACCOUNT)
267 return account is not None
269 def import_key(self, sec, password):
271 pubkey = public_key_from_private_key(sec)
272 address = public_key_to_bc_address(pubkey.decode('hex'))
274 raise Exception('Invalid private key')
276 if self.is_mine(address):
277 raise Exception('Address already in wallet')
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)
284 if self.synchronizer:
285 self.synchronizer.subscribe_to_addresses([address])
288 def delete_imported_key(self, addr):
289 account = self.accounts[IMPORTED_ACCOUNT]
291 if not account.get_addresses(0):
292 self.accounts.pop(IMPORTED_ACCOUNT)
295 def set_label(self, name, text = None):
297 old_text = self.labels.get(name)
300 self.labels[name] = text
304 self.labels.pop(name)
308 self.storage.put('labels', self.labels, True)
310 run_hook('set_label', name, text, changed)
313 def addresses(self, include_change = True, _next=True):
315 for a in self.accounts.keys():
316 o += self.get_account_addresses(a, include_change)
319 for addr in self.next_addresses.values():
324 def is_mine(self, address):
325 return address in self.addresses(True)
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
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:
339 return account, (for_change, addresses.index(addr))
341 for k,v in self.next_addresses.items():
345 raise Exception("Address not found", address)
347 def get_private_key(self, address, password):
348 if self.is_watching_only():
350 account_id, sequence = self.get_address_index(address)
351 return self.accounts[account_id].get_private_key(sequence, self, password)
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)
357 def add_keypairs(self, tx, keypairs, password):
358 # first check the provided password. This will raise if invalid.
359 self.check_password(password)
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
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():
376 pk = account.get_private_key(sequence, self, password)
378 pubkey = public_key_from_private_key(sec)
379 keypairs[pubkey] = sec
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
386 # add private keys from parameter
387 for sec in private_keys:
388 pubkey = public_key_from_private_key(sec)
389 keypairs[ pubkey ] = sec
391 self.add_keypairs(tx, keypairs, password)
392 # sign the transaction
393 self.sign_transaction(tx, keypairs, password)
395 def sign_message(self, address, message, password):
396 keys = self.get_private_key(address, password)
397 assert len(keys) == 1
399 key = regenerate_key(sec)
400 compressed = is_compressed(sec)
401 return key.sign_message(message, compressed, address)
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)
407 ec = regenerate_key(secret)
408 decrypted = ec.decrypt_message(message)
412 return self.history.values() != [[]] * len(self.history)
414 def add_contact(self, address, label=None):
415 self.addressbook.append(address)
416 self.storage.put('contacts', self.addressbook, True)
418 self.set_label(address, label)
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)
425 def fill_addressbook(self):
426 for tx_hash, tx in self.transactions.items():
427 is_relevant, is_send, _, _ = self.get_tx_value(tx)
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)
433 # self.update_tx_labels()
435 def get_num_tx(self, address):
437 for tx in self.transactions.values():
438 if address in tx.get_output_addresses(): n += 1
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)
445 def update_tx_outputs(self, tx_hash):
446 tx = self.transactions.get(tx_hash)
448 for i, (addr, value) in enumerate(tx.get_outputs()):
449 key = tx_hash+ ':%d'%i
450 self.prevout_values[key] = value
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)
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
462 received_coins = [] # list of coins received at address
464 for tx_hash, tx_height in h:
465 tx = self.transactions.get(tx_hash)
468 for i, (addr, value) in enumerate(tx.get_outputs()):
470 key = tx_hash + ':%d'%i
471 received_coins.append(key)
473 for tx_hash, tx_height in h:
474 tx = self.transactions.get(tx_hash)
478 for item in tx.inputs:
479 addr = item.get('address')
481 key = item['prevout_hash'] + ':%d'%item['prevout_n']
482 value = self.prevout_values.get( key )
483 if key in received_coins:
486 for i, (addr, value) in enumerate(tx.get_outputs()):
487 key = tx_hash + ':%d'%i
497 def get_account_name(self, k):
498 return self.labels.get(k, self.accounts[k].get_name(k))
500 def get_account_names(self):
502 for k in self.accounts.keys():
503 account_names[k] = self.get_account_name(k)
506 def get_account_addresses(self, a, include_change=True):
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)
515 def get_account_balance(self, account):
516 return self.get_balance(self.get_account_addresses(account))
518 def get_frozen_balance(self):
519 return self.get_balance(self.frozen_addresses)
521 def get_balance(self, domain=None):
522 if domain is None: domain = self.addresses(True)
525 c, u = self.get_addr_balance(addr)
530 def get_unspent_coins(self, domain=None):
532 if domain is None: domain = self.addresses(True)
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))
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]
558 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
559 """ todo: minimize tx size """
561 fee = self.fee if fixed_fee is None else fixed_fee
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)
573 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
575 v = item.get('value')
578 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
579 if total >= amount + fee: break
583 return inputs, total, fee
585 def set_fee(self, fee):
588 self.storage.put('fee_per_kb', self.fee, True)
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.))
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:
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)
605 if not self.use_change or account == IMPORTED_ACCOUNT:
606 change_addr = inputs[-1]['address']
608 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
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)]
615 def get_history(self, address):
617 return self.history.get(address)
619 def get_status(self, h):
620 if not h: return None
621 if h == ['*']: return '*'
623 for tx_hash, height in h:
624 status += tx_hash + ':%d:' % height
625 return hashlib.sha256( status ).digest().encode('hex')
627 def receive_tx_callback(self, tx_hash, tx, tx_height):
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)
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)
642 def save_transactions(self):
644 for k,v in self.transactions.items():
646 self.storage.put('transactions', tx, True)
648 def receive_history_callback(self, addr, hist):
650 if not self.check_new_history(addr, hist):
651 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
654 self.history[addr] = hist
655 self.storage.put('addr_history', self.history, True)
658 for tx_hash, tx_height in hist:
660 # add it in case it was previously unconfirmed
661 if self.verifier: self.verifier.add(tx_hash, tx_height)
663 def get_tx_history(self, account=None):
664 if not self.verifier:
667 with self.transaction_lock:
668 history = self.transactions.items()
669 history.sort(key = lambda x: self.verifier.get_txpos(x[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
677 c, u = self.get_account_balance(account)
680 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
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)
687 if value is not None:
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) )
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
701 def get_default_label(self, tx_hash):
702 tx = self.transactions.get(tx_hash)
705 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
707 for o_addr in tx.get_output_addresses():
708 if not self.is_mine(o_addr):
710 default_label = self.labels[o_addr]
712 default_label = '>' + o_addr
715 default_label = '(internal)'
717 for o_addr in tx.get_output_addresses():
718 if self.is_mine(o_addr) and not self.is_change(o_addr):
721 for o_addr in tx.get_output_addresses():
722 if self.is_mine(o_addr):
729 default_label = self.labels[o_addr]
731 default_label = '<' + o_addr
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':
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 )
744 raise ValueError("Not enough funds")
746 self.add_input_info(txin)
747 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
748 return Transaction(inputs, outputs)
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)
753 self.add_keypairs(tx, keypairs, password)
755 self.sign_transaction(tx, keypairs, password)
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)
772 txin['redeemScript'] = redeemScript
775 txin['redeemPubkey'] = account.get_pubkey(*sequence)
778 def sign_transaction(self, tx, keypairs, password):
780 run_hook('sign_transaction', tx, password)
782 def sendtx(self, tx):
786 return self.receive_tx(h, tx)
788 def send_tx(self, tx):
790 self.tx_event.clear()
791 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
794 def on_broadcast(self, i, r):
795 self.tx_result = r.get('result')
798 def receive_tx(self, tx_hash, tx):
801 return False, "error: " + out
802 run_hook('receive_tx', tx, self)
805 def update_password(self, old_password, new_password):
806 if new_password == '':
810 decoded = self.get_seed(old_password)
811 self.seed = pw_encode( decoded, new_password)
812 self.storage.put('seed', self.seed, True)
814 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
816 imported_account.update_password(old_password, new_password)
819 if hasattr(self, 'master_private_keys'):
820 for k, v in self.master_private_keys.items():
821 b = pw_decode(v, old_password)
822 c = pw_encode(b, new_password)
823 self.master_private_keys[k] = c
824 self.storage.put('master_private_keys', self.master_private_keys, True)
826 self.use_encryption = (new_password != None)
827 self.storage.put('use_encryption', self.use_encryption,True)
829 def freeze(self,addr):
830 if self.is_mine(addr) and addr not in self.frozen_addresses:
831 self.frozen_addresses.append(addr)
832 self.storage.put('frozen_addresses', self.frozen_addresses, True)
837 def unfreeze(self,addr):
838 if self.is_mine(addr) and addr in self.frozen_addresses:
839 self.frozen_addresses.remove(addr)
840 self.storage.put('frozen_addresses', self.frozen_addresses, True)
845 def set_verifier(self, verifier):
846 self.verifier = verifier
848 # review transactions that are in the history
849 for addr, hist in self.history.items():
850 if hist == ['*']: continue
851 for tx_hash, tx_height in hist:
853 # add it in case it was previously unconfirmed
854 self.verifier.add(tx_hash, tx_height)
856 # if we are on a pruning server, remove unverified transactions
857 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
858 for tx_hash in self.transactions.keys():
859 if tx_hash not in vr:
860 self.transactions.pop(tx_hash)
862 def check_new_history(self, addr, hist):
863 # check that all tx in hist are relevant
865 for tx_hash, height in hist:
866 tx = self.transactions.get(tx_hash)
868 if not tx.has_address(addr):
871 # check that we are not "orphaning" a transaction
872 old_hist = self.history.get(addr,[])
873 if old_hist == ['*']: return True
875 for tx_hash, height in old_hist:
876 if tx_hash in map(lambda x:x[0], hist): continue
878 for _addr, _hist in self.history.items():
879 if _addr == addr: continue
880 if _hist == ['*']: continue
881 _tx_hist = map(lambda x:x[0], _hist)
882 if tx_hash in _tx_hist:
887 tx = self.transactions.get(tx_hash)
888 # tx might not be there
892 if self.verifier.get_height(tx_hash):
895 print_error("new history is orphaning transaction:", tx_hash)
896 # check that all outputs are not mine, request histories
898 for _addr in tx.get_output_addresses():
899 # assert not self.is_mine(_addr)
900 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
902 ext_h = self.network.synchronous_get(ext_requests)
903 print_error("sync:", ext_requests, ext_h)
906 if h == ['*']: continue
908 if item.get('tx_hash') == tx_hash:
909 height = item.get('height')
911 print_error("found height for", tx_hash, height)
912 self.verifier.add(tx_hash, height)
914 print_error("removing orphaned tx from history", tx_hash)
915 self.transactions.pop(tx_hash)
919 def check_new_tx(self, tx_hash, tx):
920 # 1 check that tx is referenced in addr_history.
922 for addr, hist in self.history.items():
923 if hist == ['*']:continue
924 for txh, height in hist:
926 addresses.append(addr)
931 # 2 check that referencing addresses are in the tx
932 for addr in addresses:
933 if not tx.has_address(addr):
938 def start_threads(self, network):
939 from verifier import TxVerifier
940 self.network = network
941 if self.network is not None:
942 self.verifier = TxVerifier(self.network, self.storage)
943 self.verifier.start()
944 self.set_verifier(self.verifier)
945 self.synchronizer = WalletSynchronizer(self, network)
946 self.synchronizer.start()
949 self.synchronizer =None
951 def stop_threads(self):
954 self.synchronizer.stop()
956 def restore(self, cb):
959 def get_accounts(self):
962 def save_accounts(self):
964 for k, v in self.accounts.items():
966 self.storage.put('accounts', d, True)
968 def can_import(self):
969 return not self.is_watching_only()
971 def is_used(self, address):
972 h = self.history.get(address,[])
973 c, u = self.get_addr_balance(address)
974 return len(h), len(h) > 0 and c == -u
976 def address_is_old(self, address, age_limit=2):
978 h = self.history.get(address, [])
981 for tx_hash, tx_height in h:
985 tx_age = self.network.get_local_height() - tx_height + 1
988 return age > age_limit
991 class Imported_Wallet(Abstract_Wallet):
993 def __init__(self, storage):
994 Abstract_Wallet.__init__(self, storage)
995 a = self.accounts.get(IMPORTED_ACCOUNT)
997 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
998 self.storage.put('wallet_type', 'imported', True)
1000 def is_watching_only(self):
1001 acc = self.accounts[IMPORTED_ACCOUNT]
1002 n = acc.keypairs.values()
1003 return n == [(None, None)] * len(n)
1008 def is_deterministic(self):
1011 def check_password(self, password):
1012 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1014 def is_used(self, address):
1015 h = self.history.get(address,[])
1016 return len(h), False
1018 def get_master_public_keys(self):
1021 def is_beyond_limit(self, address, account, is_change):
1025 class Deterministic_Wallet(Abstract_Wallet):
1027 def __init__(self, storage):
1028 Abstract_Wallet.__init__(self, storage)
1031 return self.seed != ''
1033 def is_deterministic(self):
1036 def is_watching_only(self):
1037 return not self.has_seed()
1039 def add_seed(self, seed, password):
1041 raise Exception("a seed exists")
1043 self.seed_version, self.seed = self.prepare_seed(seed)
1045 self.seed = pw_encode( self.seed, password)
1046 self.use_encryption = True
1048 self.use_encryption = False
1050 self.storage.put('seed', self.seed, True)
1051 self.storage.put('seed_version', self.seed_version, True)
1052 self.storage.put('use_encryption', self.use_encryption,True)
1053 self.create_master_keys(password)
1055 def get_seed(self, password):
1056 return pw_decode(self.seed, password)
1058 def get_mnemonic(self, password):
1059 return self.get_seed(password)
1061 def change_gap_limit(self, value):
1062 if value >= self.gap_limit:
1063 self.gap_limit = value
1064 self.storage.put('gap_limit', self.gap_limit, True)
1065 #self.interface.poke('synchronizer')
1068 elif value >= self.min_acceptable_gap():
1069 for key, account in self.accounts.items():
1070 addresses = account[0]
1071 k = self.num_unused_trailing_addresses(addresses)
1072 n = len(addresses) - k + value
1073 addresses = addresses[0:n]
1074 self.accounts[key][0] = addresses
1076 self.gap_limit = value
1077 self.storage.put('gap_limit', self.gap_limit, True)
1078 self.save_accounts()
1083 def num_unused_trailing_addresses(self, addresses):
1085 for a in addresses[::-1]:
1086 if self.history.get(a):break
1090 def min_acceptable_gap(self):
1091 # fixme: this assumes wallet is synchronized
1095 for account in self.accounts.values():
1096 addresses = account.get_addresses(0)
1097 k = self.num_unused_trailing_addresses(addresses)
1098 for a in addresses[0:-k]:
1099 if self.history.get(a):
1103 if n > nmax: nmax = n
1106 def create_new_address(self, account=None, for_change=0):
1108 account = self.default_account()
1109 address = account.create_new_address(for_change)
1110 self.history[address] = []
1111 if self.synchronizer:
1112 self.synchronizer.add(address)
1113 self.save_accounts()
1116 def synchronize_sequence(self, account, for_change):
1117 limit = self.gap_limit_for_change if for_change else self.gap_limit
1119 addresses = account.get_addresses(for_change)
1120 if len(addresses) < limit:
1121 self.create_new_address(account, for_change)
1123 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1126 self.create_new_address(account, for_change)
1128 def check_pending_accounts(self):
1129 for account_id, addr in self.next_addresses.items():
1130 if self.address_is_old(addr):
1131 print_error( "creating account", account_id )
1132 xpub = self.master_public_keys[account_id]
1133 account = BIP32_Account({'xpub':xpub})
1134 self.add_account(account_id, account)
1135 self.next_addresses.pop(account_id)
1137 def synchronize_account(self, account):
1138 self.synchronize_sequence(account, 0)
1139 self.synchronize_sequence(account, 1)
1141 def synchronize(self):
1142 self.check_pending_accounts()
1143 for account in self.accounts.values():
1144 if type(account) in [ImportedAccount, PendingAccount]:
1146 self.synchronize_account(account)
1148 def restore(self, callback):
1150 def wait_for_wallet():
1151 self.set_up_to_date(False)
1152 while not self.is_up_to_date():
1153 msg = "%s\n%s %d\n%s %.1f"%(
1154 _("Please wait..."),
1155 _("Addresses generated:"),
1156 len(self.addresses(True)),
1157 _("Kilobytes received:"),
1158 self.network.interface.bytes_received/1024.)
1160 apply(callback, (msg,))
1163 def wait_for_network():
1164 while not self.network.is_connected():
1165 msg = "%s \n" % (_("Connecting..."))
1166 apply(callback, (msg,))
1169 # wait until we are connected, because the user might have selected another server
1175 self.fill_addressbook()
1177 def create_account(self, name, password):
1178 i = self.num_accounts()
1179 account_id = self.account_id(i)
1180 account = self.make_account(account_id, password)
1181 self.add_account(account_id, account)
1183 self.set_label(account_id, name)
1185 # add address of the next account
1186 _, _ = self.next_account_address(password)
1189 def add_account(self, account_id, account):
1190 self.accounts[account_id] = account
1191 self.save_accounts()
1193 def account_is_pending(self, k):
1194 return type(self.accounts.get(k)) == PendingAccount
1196 def delete_pending_account(self, k):
1197 assert self.account_is_pending(k)
1198 self.accounts.pop(k)
1199 self.save_accounts()
1201 def create_pending_account(self, name, password):
1202 account_id, addr = self.next_account_address(password)
1203 self.set_label(account_id, name)
1204 self.accounts[account_id] = PendingAccount({'pending':addr})
1205 self.save_accounts()
1207 def is_beyond_limit(self, address, account, is_change):
1208 if type(account) == ImportedAccount:
1210 addr_list = account.get_addresses(is_change)
1211 i = addr_list.index(address)
1212 prev_addresses = addr_list[:max(0, i)]
1213 limit = self.gap_limit_for_change if is_change else self.gap_limit
1214 if len(prev_addresses) < limit:
1216 prev_addresses = prev_addresses[max(0, i - limit):]
1217 for addr in prev_addresses:
1218 if self.history.get(addr):
1222 def get_action(self):
1223 if not self.get_master_public_key():
1224 return 'create_seed'
1225 if not self.accounts:
1226 return 'create_accounts'
1229 class NewWallet(Deterministic_Wallet):
1231 def __init__(self, storage):
1232 Deterministic_Wallet.__init__(self, storage)
1233 self.master_public_keys = storage.get('master_public_keys', {})
1234 self.master_private_keys = storage.get('master_private_keys', {})
1236 def default_account(self):
1237 return self.accounts["m/0'"]
1239 def is_watching_only(self):
1240 return not bool(self.master_private_keys)
1242 def can_create_accounts(self):
1243 return 'm/' in self.master_private_keys.keys()
1245 def get_master_public_key(self):
1246 """xpub of the main account"""
1247 return self.master_public_keys.get("m/0'")
1249 def get_master_public_keys(self):
1251 for k, account in self.accounts.items():
1252 name = self.get_account_name(k)
1253 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1254 out[name] = mpk_text
1257 def get_master_private_key(self, account, password):
1258 k = self.master_private_keys.get(account)
1260 xpriv = pw_decode( k, password)
1263 def check_password(self, password):
1264 xpriv = self.get_master_private_key( "m/", password )
1265 xpub = self.master_public_keys["m/"]
1266 assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1268 def create_xprv_wallet(self, xprv, password):
1269 xpub = bitcoin.xpub_from_xprv(xprv)
1270 account = BIP32_Account({'xpub':xpub})
1271 account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1272 self.storage.put('seed_version', self.seed_version, True)
1273 self.add_master_private_key(account_id, xprv, password)
1274 self.add_master_public_key(account_id, xpub)
1275 self.add_account(account_id, account)
1277 def create_watching_only_wallet(self, xpub):
1278 account = BIP32_Account({'xpub':xpub})
1279 account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1280 self.storage.put('seed_version', self.seed_version, True)
1281 self.add_master_public_key(account_id, xpub)
1282 self.add_account(account_id, account)
1284 def create_accounts(self, password):
1285 # First check the password is valid (this raises if it isn't).
1286 if not self.is_watching_only():
1287 self.check_password(password)
1288 self.create_account('Main account', password)
1290 def add_master_public_key(self, name, xpub):
1291 self.master_public_keys[name] = xpub
1292 self.storage.put('master_public_keys', self.master_public_keys, True)
1294 def add_master_private_key(self, name, xpriv, password):
1295 self.master_private_keys[name] = pw_encode(xpriv, password)
1296 self.storage.put('master_private_keys', self.master_private_keys, True)
1298 def add_master_keys(self, root, account_id, password):
1299 x = self.master_private_keys.get(root)
1301 master_xpriv = pw_decode(x, password )
1302 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1303 self.add_master_public_key(account_id, xpub)
1304 self.add_master_private_key(account_id, xpriv, password)
1306 master_xpub = self.master_public_keys[root]
1307 xpub = bip32_public_derivation(master_xpub, root, account_id)
1308 self.add_master_public_key(account_id, xpub)
1311 def create_master_keys(self, password):
1312 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1313 self.add_master_public_key("m/", xpub)
1314 self.add_master_private_key("m/", xpriv, password)
1316 def can_sign(self, tx):
1317 if self.is_watching_only():
1319 if tx.is_complete():
1321 addr_list, xpub_list = tx.inputs_to_sign()
1322 for addr in addr_list:
1323 if self.is_mine(addr):
1325 mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
1326 for xpub, sequence in xpub_list:
1331 def num_accounts(self):
1333 for k, v in self.accounts.items():
1334 if type(v) != BIP32_Account:
1340 account_id = self.account_id(i)
1341 if account_id not in keys: break
1345 def next_account_address(self, password):
1346 i = self.num_accounts()
1347 account_id = self.account_id(i)
1349 addr = self.next_addresses.get(account_id)
1351 account = self.make_account(account_id, password)
1352 addr = account.first_address()
1353 self.next_addresses[account_id] = addr
1354 self.storage.put('next_addresses', self.next_addresses)
1356 return account_id, addr
1358 def account_id(self, i):
1361 def make_account(self, account_id, password):
1362 """Creates and saves the master keys, but does not save the account"""
1363 xpub = self.add_master_keys("m/", account_id, password)
1364 account = BIP32_Account({'xpub':xpub})
1367 def make_seed(self):
1368 import mnemonic, ecdsa
1369 entropy = ecdsa.util.randrange( pow(2,160) )
1372 ss = "%040x"%(entropy+nonce)
1373 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1374 # we keep only 13 words, that's approximately 139 bits of entropy
1375 words = mnemonic.mn_encode(s)[0:13]
1376 seed = ' '.join(words)
1377 if is_new_seed(seed):
1378 break # this will remove 8 bits of entropy
1382 def prepare_seed(self, seed):
1384 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1387 class Wallet_2of2(NewWallet):
1388 """ This class is used for multisignature addresses"""
1390 def __init__(self, storage):
1391 NewWallet.__init__(self, storage)
1392 self.storage.put('wallet_type', '2of2', True)
1394 def default_account(self):
1395 return self.accounts['m/']
1397 def can_create_accounts(self):
1400 def can_import(self):
1403 def create_account(self, name, password):
1404 xpub1 = self.master_public_keys.get("m/")
1405 xpub2 = self.master_public_keys.get("cold/")
1406 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1407 self.add_account('m/', account)
1409 def get_master_public_keys(self):
1410 xpub1 = self.master_public_keys.get("m/")
1411 xpub2 = self.master_public_keys.get("cold/")
1412 return {'hot':xpub1, 'cold':xpub2}
1414 def get_action(self):
1415 xpub1 = self.master_public_keys.get("m/")
1416 xpub2 = self.master_public_keys.get("cold/")
1418 return 'create_seed'
1420 return 'add_cosigner'
1421 if not self.accounts:
1422 return 'create_accounts'
1425 class Wallet_2of3(Wallet_2of2):
1426 """ This class is used for multisignature addresses"""
1428 def __init__(self, storage):
1429 Wallet_2of2.__init__(self, storage)
1430 self.storage.put('wallet_type', '2of3', True)
1432 def create_account(self, name, password):
1433 xpub1 = self.master_public_keys.get("m/")
1434 xpub2 = self.master_public_keys.get("cold/")
1435 xpub3 = self.master_public_keys.get("remote/")
1436 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1437 self.add_account('m/', account)
1439 def get_master_public_keys(self):
1440 xpub1 = self.master_public_keys.get("m/")
1441 xpub2 = self.master_public_keys.get("cold/")
1442 xpub3 = self.master_public_keys.get("remote/")
1443 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1445 def get_action(self):
1446 xpub1 = self.master_public_keys.get("m/")
1447 xpub2 = self.master_public_keys.get("cold/")
1448 xpub3 = self.master_public_keys.get("remote/")
1450 return 'create_seed'
1451 if xpub2 is None or xpub3 is None:
1452 return 'add_two_cosigners'
1453 if not self.accounts:
1454 return 'create_accounts'
1457 class OldWallet(Deterministic_Wallet):
1459 def default_account(self):
1460 return self.accounts[0]
1462 def make_seed(self):
1464 seed = random_seed(128)
1465 return ' '.join(mnemonic.mn_encode(seed))
1467 def prepare_seed(self, seed):
1469 # see if seed was entered as hex
1474 return OLD_SEED_VERSION, str(seed)
1478 words = seed.split()
1479 seed = mnemonic.mn_decode(words)
1481 raise Exception("Invalid seed")
1483 return OLD_SEED_VERSION, seed
1485 def create_master_keys(self, password):
1486 seed = self.get_seed(password)
1487 mpk = OldAccount.mpk_from_seed(seed)
1488 self.storage.put('master_public_key', mpk, True)
1490 def get_master_public_key(self):
1491 return self.storage.get("master_public_key")
1493 def get_master_public_keys(self):
1494 return {'Main Account':self.get_master_public_key()}
1496 def create_accounts(self, password):
1497 mpk = self.storage.get("master_public_key")
1498 self.create_account(mpk)
1500 def create_account(self, mpk):
1501 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1502 self.save_accounts()
1504 def create_watching_only_wallet(self, mpk):
1505 self.seed_version = OLD_SEED_VERSION
1506 self.storage.put('seed_version', self.seed_version, True)
1507 self.storage.put('master_public_key', mpk, True)
1508 self.create_account(mpk)
1510 def get_seed(self, password):
1511 seed = pw_decode(self.seed, password).encode('utf8')
1514 def check_password(self, password):
1515 seed = self.get_seed(password)
1516 self.accounts[0].check_seed(seed)
1518 def get_mnemonic(self, password):
1520 s = self.get_seed(password)
1521 return ' '.join(mnemonic.mn_encode(s))
1523 def check_pending_accounts(self):
1526 def can_sign(self, tx):
1527 if self.is_watching_only():
1529 if tx.is_complete():
1531 addr_list, xpub_list = tx.inputs_to_sign()
1532 for addr in addr_list:
1533 if self.is_mine(addr):
1535 for xpub, sequence in xpub_list:
1536 if xpub == self.master_public_key:
1540 # former WalletFactory
1541 class Wallet(object):
1542 """The main wallet "entry point".
1543 This class is actually a factory that will return a wallet of the correct
1544 type when passed a WalletStorage instance."""
1546 def __new__(self, storage):
1547 config = storage.config
1549 self.wallet_types = [
1550 ('standard', ("Standard wallet"), NewWallet if config.get('bip32') else OldWallet),
1551 ('imported', ("Imported wallet"), Imported_Wallet),
1552 ('2of2', ("Multisig wallet (2 of 2)"), Wallet_2of2),
1553 ('2of3', ("Multisig wallet (2 of 3)"), Wallet_2of3)
1555 run_hook('add_wallet_types', self.wallet_types)
1557 for t, l, WalletClass in self.wallet_types:
1558 if t == storage.get('wallet_type'):
1559 return WalletClass(storage)
1561 if not storage.file_exists:
1562 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1564 seed_version = storage.get('seed_version')
1565 if not seed_version:
1566 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1568 if seed_version == OLD_SEED_VERSION:
1569 return OldWallet(storage)
1570 elif seed_version == NEW_SEED_VERSION:
1571 return NewWallet(storage)
1573 msg = "This wallet seed is not supported."
1574 if seed_version in [5]:
1575 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1580 def is_seed(self, seed):
1583 elif is_old_seed(seed):
1585 elif is_new_seed(seed):
1591 def is_old_mpk(self, mpk):
1594 assert len(mpk) == 128
1600 def is_xpub(self, text):
1602 assert text[0:4] == 'xpub'
1603 deserialize_xkey(text)
1609 def is_xprv(self, text):
1611 assert text[0:4] == 'xprv'
1612 deserialize_xkey(text)
1618 def is_address(self, text):
1621 for x in text.split():
1622 if not bitcoin.is_address(x):
1627 def is_private_key(self, text):
1630 for x in text.split():
1631 if not bitcoin.is_private_key(x):
1636 def from_seed(self, seed, storage):
1637 if is_old_seed(seed):
1639 elif is_new_seed(seed):
1645 def from_address(self, text, storage):
1646 w = Imported_Wallet(storage)
1647 for x in text.split():
1648 w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1653 def from_private_key(self, text, storage):
1654 w = Imported_Wallet(storage)
1655 for x in text.split():
1656 w.import_key(x, None)
1660 def from_old_mpk(self, mpk, storage):
1661 w = OldWallet(storage)
1663 w.create_watching_only_wallet(mpk)
1667 def from_xpub(self, xpub, storage):
1668 w = NewWallet(storage)
1669 w.create_watching_only_wallet(xpub)
1673 def from_xprv(self, xprv, password, storage):
1674 w = NewWallet(storage)
1675 w.create_xprv_wallet(xprv, password)