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/>.
34 from util import print_msg, print_error, format_satoshis
37 from transaction import Transaction, is_extended_pubkey
38 from plugins import run_hook
40 from synchronizer import WalletSynchronizer
42 COINBASE_MATURITY = 100
45 # internal ID for imported account
46 IMPORTED_ACCOUNT = '/x'
55 def __init__(self, config):
56 self.lock = threading.Lock()
59 self.file_exists = False
60 self.path = self.init_path(config)
61 print_error( "wallet path", self.path )
66 def init_path(self, config):
67 """Set the path of the wallet."""
69 # command line -w option
70 path = config.get('wallet_path')
75 path = config.get('default_wallet_path')
80 dirpath = os.path.join(config.path, "wallets")
81 if not os.path.exists(dirpath):
84 new_path = os.path.join(config.path, "wallets", "default_wallet")
86 # default path in pre 1.9 versions
87 old_path = os.path.join(config.path, "electrum.dat")
88 if os.path.exists(old_path) and not os.path.exists(new_path):
89 os.rename(old_path, new_path)
95 """Read the contents of the wallet file."""
97 with open(self.path, "r") as f:
102 d = ast.literal_eval( data ) #parse raw data from reading wallet file
104 raise IOError("Cannot read wallet file.")
107 self.file_exists = True
110 def get(self, key, default=None):
111 v = self.data.get(key)
116 def put(self, key, value, save = True):
119 if value is not None:
120 self.data[key] = value
121 elif key in self.data:
128 f = open(self.path,"w")
131 if 'ANDROID_DATA' not in os.environ:
133 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
141 class Abstract_Wallet:
143 def __init__(self, storage):
145 self.storage = storage
146 self.electrum_version = ELECTRUM_VERSION
147 self.gap_limit_for_change = 3 # constant
149 self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
150 self.gap_limit = storage.get('gap_limit', 5)
151 self.use_change = storage.get('use_change',True)
152 self.use_encryption = storage.get('use_encryption', False)
153 self.seed = storage.get('seed', '') # encrypted
154 self.labels = storage.get('labels', {})
155 self.frozen_addresses = storage.get('frozen_addresses',[])
156 self.addressbook = storage.get('contacts', [])
158 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
160 self.fee = int(storage.get('fee_per_kb', 10000))
162 self.master_public_keys = storage.get('master_public_keys',{})
163 self.master_private_keys = storage.get('master_private_keys', {})
165 self.next_addresses = storage.get('next_addresses',{})
168 # This attribute is set when wallet.start_threads is called.
169 self.synchronizer = None
173 self.transactions = {}
174 tx_list = self.storage.get('transactions',{})
175 for k,v in tx_list.items():
179 print_msg("Warning: Cannot deserialize transactions. skipping")
182 self.add_extra_addresses(tx)
183 self.transactions[k] = tx
185 for h,tx in self.transactions.items():
186 if not self.check_new_tx(h, tx):
187 print_error("removing unreferenced tx", h)
188 self.transactions.pop(h)
192 self.prevout_values = {} # my own transaction outputs
193 self.spent_outputs = []
198 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
199 # interface.is_up_to_date() returns true when all requests have been answered and processed
200 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
202 self.up_to_date = False
203 self.lock = threading.Lock()
204 self.transaction_lock = threading.Lock()
205 self.tx_event = threading.Event()
207 for tx_hash, tx in self.transactions.items():
208 self.update_tx_outputs(tx_hash)
211 def add_extra_addresses(self, tx):
213 # find the address corresponding to pay-to-pubkey inputs
214 tx.add_extra_addresses(self.transactions)
215 for o in tx.d.get('outputs'):
216 if o.get('is_pubkey'):
217 for tx2 in self.transactions.values():
218 tx2.add_extra_addresses({h:tx})
221 def get_action(self):
225 def convert_imported_keys(self, password):
226 for k, v in self.imported_keys.items():
227 sec = pw_decode(v, password)
228 pubkey = public_key_from_private_key(sec)
229 address = public_key_to_bc_address(pubkey.decode('hex'))
231 self.import_key(sec, password)
232 self.imported_keys.pop(k)
233 self.storage.put('imported_keys', self.imported_keys)
236 def load_accounts(self):
238 self.imported_keys = self.storage.get('imported_keys',{})
240 d = self.storage.get('accounts', {})
241 for k, v in d.items():
243 v['mpk'] = self.storage.get('master_public_key')
244 self.accounts[k] = OldAccount(v)
245 elif v.get('imported'):
246 self.accounts[k] = ImportedAccount(v)
248 self.accounts[k] = BIP32_Account_2of3(v)
250 self.accounts[k] = BIP32_Account_2of2(v)
252 self.accounts[k] = BIP32_Account(v)
253 elif v.get('pending'):
254 self.accounts[k] = PendingAccount(v)
256 print_error("cannot load account", v)
259 def synchronize(self):
262 def can_create_accounts(self):
265 def set_up_to_date(self,b):
266 with self.lock: self.up_to_date = b
268 def is_up_to_date(self):
269 with self.lock: return self.up_to_date
273 self.up_to_date = False
274 while not self.is_up_to_date():
277 def is_imported(self, addr):
278 account = self.accounts.get(IMPORTED_ACCOUNT)
280 return addr in account.get_addresses(0)
284 def has_imported_keys(self):
285 account = self.accounts.get(IMPORTED_ACCOUNT)
286 return account is not None
288 def import_key(self, sec, password):
290 pubkey = public_key_from_private_key(sec)
291 address = public_key_to_bc_address(pubkey.decode('hex'))
293 raise Exception('Invalid private key')
295 if self.is_mine(address):
296 raise Exception('Address already in wallet')
298 if self.accounts.get(IMPORTED_ACCOUNT) is None:
299 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
300 self.accounts[IMPORTED_ACCOUNT].add(address, pubkey, sec, password)
303 if self.synchronizer:
304 self.synchronizer.subscribe_to_addresses([address])
308 def delete_imported_key(self, addr):
309 account = self.accounts[IMPORTED_ACCOUNT]
311 if not account.get_addresses(0):
312 self.accounts.pop(IMPORTED_ACCOUNT)
316 def set_label(self, name, text = None):
318 old_text = self.labels.get(name)
321 self.labels[name] = text
325 self.labels.pop(name)
329 self.storage.put('labels', self.labels, True)
331 run_hook('set_label', name, text, changed)
337 def addresses(self, include_change = True, _next=True):
339 for a in self.accounts.keys():
340 o += self.get_account_addresses(a, include_change)
343 for addr in self.next_addresses.values():
349 def is_mine(self, address):
350 return address in self.addresses(True)
353 def is_change(self, address):
354 if not self.is_mine(address): return False
355 acct, s = self.get_address_index(address)
356 if s is None: return False
360 def get_address_index(self, address):
362 for account in self.accounts.keys():
363 for for_change in [0,1]:
364 addresses = self.accounts[account].get_addresses(for_change)
365 for addr in addresses:
367 return account, (for_change, addresses.index(addr))
369 for k,v in self.next_addresses.items():
373 raise Exception("Address not found", address)
376 def getpubkeys(self, addr):
377 assert is_valid(addr) and self.is_mine(addr)
378 account, sequence = self.get_address_index(addr)
379 a = self.accounts[account]
380 return a.get_pubkeys( sequence )
383 def get_private_key(self, address, password):
384 if self.is_watching_only():
386 account_id, sequence = self.get_address_index(address)
387 return self.accounts[account_id].get_private_key(sequence, self, password)
390 def get_public_keys(self, address):
391 account_id, sequence = self.get_address_index(address)
392 return self.accounts[account_id].get_pubkeys(sequence)
395 def add_keypairs(self, tx, keypairs, password):
396 # first check the provided password
397 seed = self.get_seed(password)
399 for txin in tx.inputs:
400 x_pubkeys = txin['x_pubkeys']
401 address = txin['address']
403 if self.is_mine(address):
405 private_keys = self.get_private_key(address, password)
406 for sec in private_keys:
407 pubkey = public_key_from_private_key(sec)
408 keypairs[ pubkey ] = sec
412 from account import BIP32_Account, OldAccount
413 for x_pubkey in x_pubkeys:
414 if not is_extended_pubkey(x_pubkey):
417 if x_pubkey[0:2] == 'ff':
418 xpub, sequence = BIP32_Account.parse_xpubkey(x_pubkey)
419 elif x_pubkey[0:2] == 'fe':
420 xpub, sequence = OldAccount.parse_xpubkey(x_pubkey)
422 # look for account that can sign
423 for k, account in self.accounts.items():
424 if xpub in account.get_master_pubkeys():
429 addr = account.get_address(*sequence)
430 assert txin['address'] == addr
431 pk = self.get_private_key(addr, password)
433 pubkey = public_key_from_private_key(sec)
434 keypairs[pubkey] = sec
439 def signrawtransaction(self, tx, private_keys, password):
441 # check that the password is correct
442 seed = self.get_seed(password)
444 # build a list of public/private keys
447 # add private keys from parameter
448 for sec in private_keys:
449 pubkey = public_key_from_private_key(sec)
450 keypairs[ pubkey ] = sec
453 self.add_keypairs(tx, keypairs, password)
455 # sign the transaction
456 self.sign_transaction(tx, keypairs, password)
459 def sign_message(self, address, message, password):
460 keys = self.get_private_key(address, password)
461 assert len(keys) == 1
463 key = regenerate_key(sec)
464 compressed = is_compressed(sec)
465 return key.sign_message(message, compressed, address)
469 def decrypt_message(self, pubkey, message, password):
470 address = public_key_to_bc_address(pubkey.decode('hex'))
471 keys = self.get_private_key(address, password)
473 ec = regenerate_key(secret)
474 decrypted = ec.decrypt_message(message)
480 return self.history.values() != [[]] * len(self.history)
483 def add_contact(self, address, label=None):
484 self.addressbook.append(address)
485 self.storage.put('contacts', self.addressbook, True)
487 self.set_label(address, label)
490 def delete_contact(self, addr):
491 if addr in self.addressbook:
492 self.addressbook.remove(addr)
493 self.storage.put('addressbook', self.addressbook, True)
496 def fill_addressbook(self):
497 for tx_hash, tx in self.transactions.items():
498 is_relevant, is_send, _, _ = self.get_tx_value(tx)
500 for addr, v in tx.outputs:
501 if not self.is_mine(addr) and addr not in self.addressbook:
502 self.addressbook.append(addr)
504 # self.update_tx_labels()
506 def get_num_tx(self, address):
508 for tx in self.transactions.values():
509 if address in map(lambda x:x[0], tx.outputs): n += 1
513 def get_address_flags(self, addr):
514 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
515 flags += "F" if addr in self.frozen_addresses else "-"
519 def get_tx_value(self, tx, account=None):
520 domain = self.get_account_addresses(account)
521 return tx.get_value(domain, self.prevout_values)
524 def update_tx_outputs(self, tx_hash):
525 tx = self.transactions.get(tx_hash)
527 for i, (addr, value) in enumerate(tx.outputs):
528 key = tx_hash+ ':%d'%i
529 self.prevout_values[key] = value
531 for item in tx.inputs:
532 if self.is_mine(item.get('address')):
533 key = item['prevout_hash'] + ':%d'%item['prevout_n']
534 self.spent_outputs.append(key)
537 def get_addr_balance(self, address):
538 #assert self.is_mine(address)
539 h = self.history.get(address,[])
540 if h == ['*']: return 0,0
542 received_coins = [] # list of coins received at address
544 for tx_hash, tx_height in h:
545 tx = self.transactions.get(tx_hash)
548 for i, (addr, value) in enumerate(tx.outputs):
550 key = tx_hash + ':%d'%i
551 received_coins.append(key)
553 for tx_hash, tx_height in h:
554 tx = self.transactions.get(tx_hash)
558 for item in tx.inputs:
559 addr = item.get('address')
561 key = item['prevout_hash'] + ':%d'%item['prevout_n']
562 value = self.prevout_values.get( key )
563 if key in received_coins:
566 for i, (addr, value) in enumerate(tx.outputs):
567 key = tx_hash + ':%d'%i
578 def get_account_name(self, k):
579 return self.labels.get(k, self.accounts[k].get_name(k))
582 def get_account_names(self):
584 for k in self.accounts.keys():
585 account_names[k] = self.get_account_name(k)
589 def get_account_addresses(self, a, include_change=True):
591 o = self.addresses(True)
592 elif a in self.accounts:
593 ac = self.accounts[a]
594 o = ac.get_addresses(0)
595 if include_change: o += ac.get_addresses(1)
599 def get_account_balance(self, account):
600 return self.get_balance(self.get_account_addresses(account))
602 def get_frozen_balance(self):
603 return self.get_balance(self.frozen_addresses)
605 def get_balance(self, domain=None):
606 if domain is None: domain = self.addresses(True)
609 c, u = self.get_addr_balance(addr)
615 def get_unspent_coins(self, domain=None):
617 if domain is None: domain = self.addresses(True)
619 h = self.history.get(addr, [])
620 if h == ['*']: continue
621 for tx_hash, tx_height in h:
622 tx = self.transactions.get(tx_hash)
623 if tx is None: raise Exception("Wallet not synchronized")
624 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
625 for o in tx.d.get('outputs'):
627 if output.get('address') != addr: continue
628 key = tx_hash + ":%d" % output.get('prevout_n')
629 if key in self.spent_outputs: continue
630 output['prevout_hash'] = tx_hash
631 output['height'] = tx_height
632 output['coinbase'] = is_coinbase
633 coins.append((tx_height, output))
637 coins = sorted(coins)
638 if coins[-1][0] != 0:
639 while coins[0][0] == 0:
640 coins = coins[1:] + [ coins[0] ]
641 return [x[1] for x in coins]
644 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
645 """ todo: minimize tx size """
647 fee = self.fee if fixed_fee is None else fixed_fee
651 domain = self.addresses(True)
652 for i in self.frozen_addresses:
653 if i in domain: domain.remove(i)
654 coins = self.get_unspent_coins(domain)
659 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
661 addr = item.get('address')
662 v = item.get('value')
665 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
666 if total >= amount + fee: break
670 return inputs, total, fee
673 def set_fee(self, fee):
676 self.storage.put('fee_per_kb', self.fee, True)
678 def estimated_fee(self, inputs, num_outputs):
679 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
680 fee = self.fee * int(math.ceil(estimated_size/1000.))
684 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
685 "add change to a transaction"
686 change_amount = total - ( amount + fee )
687 if change_amount > DUST_THRESHOLD:
690 # send change to one of the accounts involved in the tx
691 address = inputs[0].get('address')
692 account, _ = self.get_address_index(address)
694 if not self.use_change or account == IMPORTED_ACCOUNT:
695 change_addr = inputs[-1]['address']
697 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
699 # Insert the change output at a random position in the outputs
700 posn = random.randint(0, len(outputs))
701 outputs[posn:posn] = [( change_addr, change_amount)]
705 def get_history(self, address):
707 return self.history.get(address)
710 def get_status(self, h):
711 if not h: return None
712 if h == ['*']: return '*'
714 for tx_hash, height in h:
715 status += tx_hash + ':%d:' % height
716 return hashlib.sha256( status ).digest().encode('hex')
719 def receive_tx_callback(self, tx_hash, tx, tx_height):
721 with self.transaction_lock:
722 self.add_extra_addresses(tx)
723 if not self.check_new_tx(tx_hash, tx):
724 # may happen due to pruning
725 print_error("received transaction that is no longer referenced in history", tx_hash)
727 self.transactions[tx_hash] = tx
728 self.network.pending_transactions_for_notifications.append(tx)
729 self.save_transactions()
730 if self.verifier and tx_height>0:
731 self.verifier.add(tx_hash, tx_height)
732 self.update_tx_outputs(tx_hash)
735 def save_transactions(self):
737 for k,v in self.transactions.items():
739 self.storage.put('transactions', tx, True)
741 def receive_history_callback(self, addr, hist):
743 if not self.check_new_history(addr, hist):
744 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
747 self.history[addr] = hist
748 self.storage.put('addr_history', self.history, True)
751 for tx_hash, tx_height in hist:
753 # add it in case it was previously unconfirmed
754 if self.verifier: self.verifier.add(tx_hash, tx_height)
757 def get_tx_history(self, account=None):
758 if not self.verifier:
761 with self.transaction_lock:
762 history = self.transactions.items()
763 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
767 for tx_hash, tx in history:
768 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
769 if v is not None: balance += v
771 c, u = self.get_account_balance(account)
774 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
776 balance = c + u - balance
777 for tx_hash, tx in history:
778 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
781 if value is not None:
784 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
785 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
790 def get_label(self, tx_hash):
791 label = self.labels.get(tx_hash)
792 is_default = (label == '') or (label is None)
793 if is_default: label = self.get_default_label(tx_hash)
794 return label, is_default
797 def get_default_label(self, tx_hash):
798 tx = self.transactions.get(tx_hash)
801 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
805 if not self.is_mine(o_addr):
807 default_label = self.labels[o_addr]
809 default_label = '>' + o_addr
812 default_label = '(internal)'
816 if self.is_mine(o_addr) and not self.is_change(o_addr):
821 if self.is_mine(o_addr):
827 dest_label = self.labels.get(o_addr)
829 default_label = self.labels[o_addr]
831 default_label = '<' + o_addr
836 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
837 for address, x in outputs:
838 assert is_valid(address), "Address " + address + " is invalid!"
839 amount = sum( map(lambda x:x[1], outputs) )
840 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
842 raise ValueError("Not enough funds")
844 self.add_input_info(txin)
845 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
846 return Transaction.from_io(inputs, outputs)
849 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
850 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
852 self.add_keypairs(tx, keypairs, password)
854 self.sign_transaction(tx, keypairs, password)
858 def add_input_info(self, txin):
859 address = txin['address']
860 account_id, sequence = self.get_address_index(address)
861 account = self.accounts[account_id]
862 redeemScript = account.redeem_script(sequence)
863 txin['x_pubkeys'] = account.get_xpubkeys(sequence)
864 txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
865 txin['signatures'] = [None] * len(pubkeys)
868 txin['redeemScript'] = redeemScript
871 txin['redeemPubkey'] = account.get_pubkey(*sequence)
875 def sign_transaction(self, tx, keypairs, password):
877 run_hook('sign_transaction', tx, password)
880 def sendtx(self, tx):
884 return self.receive_tx(h, tx)
886 def send_tx(self, tx):
888 self.tx_event.clear()
889 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
892 def on_broadcast(self, i, r):
893 self.tx_result = r.get('result')
896 def receive_tx(self, tx_hash, tx):
899 return False, "error: " + out
900 run_hook('receive_tx', tx, self)
904 def update_password(self, old_password, new_password):
905 if new_password == '':
909 decoded = self.get_seed(old_password)
910 self.seed = pw_encode( decoded, new_password)
911 self.storage.put('seed', self.seed, True)
913 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
915 imported_account.update_password(old_password, new_password)
918 for k, v in self.master_private_keys.items():
919 b = pw_decode(v, old_password)
920 c = pw_encode(b, new_password)
921 self.master_private_keys[k] = c
922 self.storage.put('master_private_keys', self.master_private_keys, True)
924 self.use_encryption = (new_password != None)
925 self.storage.put('use_encryption', self.use_encryption,True)
928 def freeze(self,addr):
929 if self.is_mine(addr) and addr not in self.frozen_addresses:
930 self.frozen_addresses.append(addr)
931 self.storage.put('frozen_addresses', self.frozen_addresses, True)
937 def unfreeze(self,addr):
938 if self.is_mine(addr) and addr in self.frozen_addresses:
939 self.frozen_addresses.remove(addr)
940 self.storage.put('frozen_addresses', self.frozen_addresses, True)
946 def set_verifier(self, verifier):
947 self.verifier = verifier
949 # review transactions that are in the history
950 for addr, hist in self.history.items():
951 if hist == ['*']: continue
952 for tx_hash, tx_height in hist:
954 # add it in case it was previously unconfirmed
955 self.verifier.add(tx_hash, tx_height)
957 # if we are on a pruning server, remove unverified transactions
958 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
959 for tx_hash in self.transactions.keys():
960 if tx_hash not in vr:
961 self.transactions.pop(tx_hash)
964 def check_new_history(self, addr, hist):
966 # check that all tx in hist are relevant
968 for tx_hash, height in hist:
969 tx = self.transactions.get(tx_hash)
971 if not tx.has_address(addr):
974 # check that we are not "orphaning" a transaction
975 old_hist = self.history.get(addr,[])
976 if old_hist == ['*']: return True
978 for tx_hash, height in old_hist:
979 if tx_hash in map(lambda x:x[0], hist): continue
981 for _addr, _hist in self.history.items():
982 if _addr == addr: continue
983 if _hist == ['*']: continue
984 _tx_hist = map(lambda x:x[0], _hist)
985 if tx_hash in _tx_hist:
990 tx = self.transactions.get(tx_hash)
991 # tx might not be there
995 if self.verifier.get_height(tx_hash):
998 print_error("new history is orphaning transaction:", tx_hash)
999 # check that all outputs are not mine, request histories
1001 for _addr, _v in tx.outputs:
1002 # assert not self.is_mine(_addr)
1003 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1005 ext_h = self.network.synchronous_get(ext_requests)
1006 print_error("sync:", ext_requests, ext_h)
1009 if h == ['*']: continue
1011 if item.get('tx_hash') == tx_hash:
1012 height = item.get('height')
1014 print_error("found height for", tx_hash, height)
1015 self.verifier.add(tx_hash, height)
1017 print_error("removing orphaned tx from history", tx_hash)
1018 self.transactions.pop(tx_hash)
1023 def check_new_tx(self, tx_hash, tx):
1024 # 1 check that tx is referenced in addr_history.
1026 for addr, hist in self.history.items():
1027 if hist == ['*']:continue
1028 for txh, height in hist:
1030 addresses.append(addr)
1035 # 2 check that referencing addresses are in the tx
1036 for addr in addresses:
1037 if not tx.has_address(addr):
1043 def start_threads(self, network):
1044 from verifier import TxVerifier
1045 self.network = network
1046 if self.network is not None:
1047 self.verifier = TxVerifier(self.network, self.storage)
1048 self.verifier.start()
1049 self.set_verifier(self.verifier)
1050 self.synchronizer = WalletSynchronizer(self, network)
1051 self.synchronizer.start()
1053 self.verifier = None
1054 self.synchronizer =None
1056 def stop_threads(self):
1058 self.verifier.stop()
1059 self.synchronizer.stop()
1061 def restore(self, cb):
1064 def get_accounts(self):
1065 return self.accounts
1067 def save_accounts(self):
1069 for k, v in self.accounts.items():
1071 self.storage.put('accounts', d, True)
1073 def can_import(self):
1074 return not self.is_watching_only()
1076 def is_used(self, address):
1077 h = self.history.get(address,[])
1078 c, u = self.get_addr_balance(address)
1079 return len(h), len(h) > 0 and c == -u
1082 class Imported_Wallet(Abstract_Wallet):
1084 def __init__(self, storage):
1085 Abstract_Wallet.__init__(self, storage)
1086 a = self.accounts.get(IMPORTED_ACCOUNT)
1088 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1089 self.storage.put('wallet_type', 'imported', True)
1092 def is_watching_only(self):
1093 acc = self.accounts[IMPORTED_ACCOUNT]
1094 n = acc.keypairs.values()
1095 return n == [(None, None)] * len(n)
1100 def is_deterministic(self):
1103 def check_password(self, password):
1104 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1106 def is_used(self, address):
1107 h = self.history.get(address,[])
1108 return len(h), False
1111 class Deterministic_Wallet(Abstract_Wallet):
1113 def __init__(self, storage):
1114 Abstract_Wallet.__init__(self, storage)
1117 return self.seed != ''
1119 def is_deterministic(self):
1122 def is_watching_only(self):
1123 return not self.has_seed()
1125 def add_seed(self, seed, password):
1127 raise Exception("a seed exists")
1129 self.seed_version, self.seed = self.prepare_seed(seed)
1131 self.seed = pw_encode( self.seed, password)
1132 self.use_encryption = True
1134 self.use_encryption = False
1136 self.storage.put('seed', self.seed, True)
1137 self.storage.put('seed_version', self.seed_version, True)
1138 self.storage.put('use_encryption', self.use_encryption,True)
1139 self.create_master_keys(password)
1141 def get_seed(self, password):
1142 return pw_decode(self.seed, password)
1144 def get_mnemonic(self, password):
1145 return self.get_seed(password)
1147 def change_gap_limit(self, value):
1148 if value >= self.gap_limit:
1149 self.gap_limit = value
1150 self.storage.put('gap_limit', self.gap_limit, True)
1151 #self.interface.poke('synchronizer')
1154 elif value >= self.min_acceptable_gap():
1155 for key, account in self.accounts.items():
1156 addresses = account[0]
1157 k = self.num_unused_trailing_addresses(addresses)
1158 n = len(addresses) - k + value
1159 addresses = addresses[0:n]
1160 self.accounts[key][0] = addresses
1162 self.gap_limit = value
1163 self.storage.put('gap_limit', self.gap_limit, True)
1164 self.save_accounts()
1169 def num_unused_trailing_addresses(self, addresses):
1171 for a in addresses[::-1]:
1172 if self.history.get(a):break
1176 def min_acceptable_gap(self):
1177 # fixme: this assumes wallet is synchronized
1181 for account in self.accounts.values():
1182 addresses = account.get_addresses(0)
1183 k = self.num_unused_trailing_addresses(addresses)
1184 for a in addresses[0:-k]:
1185 if self.history.get(a):
1189 if n > nmax: nmax = n
1193 def address_is_old(self, address):
1195 h = self.history.get(address, [])
1198 for tx_hash, tx_height in h:
1202 tx_age = self.network.get_local_height() - tx_height + 1
1208 def synchronize_sequence(self, account, for_change):
1209 limit = self.gap_limit_for_change if for_change else self.gap_limit
1212 addresses = account.get_addresses(for_change)
1213 if len(addresses) < limit:
1214 address = account.create_new_address(for_change)
1215 self.history[address] = []
1216 new_addresses.append( address )
1219 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1222 address = account.create_new_address(for_change)
1223 self.history[address] = []
1224 new_addresses.append( address )
1226 return new_addresses
1229 def check_pending_accounts(self):
1230 for account_id, addr in self.next_addresses.items():
1231 if self.address_is_old(addr):
1232 print_error( "creating account", account_id )
1233 xpub = self.master_public_keys[account_id]
1234 account = BIP32_Account({'xpub':xpub})
1235 self.add_account(account_id, account)
1236 self.next_addresses.pop(account_id)
1239 def synchronize_account(self, account):
1241 new += self.synchronize_sequence(account, 0)
1242 new += self.synchronize_sequence(account, 1)
1246 def synchronize(self):
1247 self.check_pending_accounts()
1249 for account in self.accounts.values():
1250 if type(account) in [ImportedAccount, PendingAccount]:
1252 new += self.synchronize_account(account)
1254 self.save_accounts()
1255 self.storage.put('addr_history', self.history, True)
1259 def restore(self, callback):
1261 def wait_for_wallet():
1262 self.set_up_to_date(False)
1263 while not self.is_up_to_date():
1264 msg = "%s\n%s %d\n%s %.1f"%(
1265 _("Please wait..."),
1266 _("Addresses generated:"),
1267 len(self.addresses(True)),
1268 _("Kilobytes received:"),
1269 self.network.interface.bytes_received/1024.)
1271 apply(callback, (msg,))
1274 def wait_for_network():
1275 while not self.network.is_connected():
1276 msg = "%s \n" % (_("Connecting..."))
1277 apply(callback, (msg,))
1280 # wait until we are connected, because the user might have selected another server
1287 self.fill_addressbook()
1290 def create_account(self, name, password):
1291 i = self.num_accounts()
1292 account_id = self.account_id(i)
1293 account = self.make_account(account_id, password)
1294 self.add_account(account_id, account)
1296 self.set_label(account_id, name)
1298 # add address of the next account
1299 _, _ = self.next_account_address(password)
1302 def add_account(self, account_id, account):
1303 self.accounts[account_id] = account
1304 self.save_accounts()
1308 def account_is_pending(self, k):
1309 return type(self.accounts.get(k)) == PendingAccount
1311 def delete_pending_account(self, k):
1312 assert self.account_is_pending(k)
1313 self.accounts.pop(k)
1314 self.save_accounts()
1316 def create_pending_account(self, name, password):
1317 account_id, addr = self.next_account_address(password)
1318 self.set_label(account_id, name)
1319 self.accounts[account_id] = PendingAccount({'pending':addr})
1320 self.save_accounts()
1325 class NewWallet(Deterministic_Wallet):
1327 def __init__(self, storage):
1328 Deterministic_Wallet.__init__(self, storage)
1330 def can_create_accounts(self):
1331 return not self.is_watching_only()
1333 def get_master_public_key(self):
1334 return self.master_public_keys["m/"]
1336 def get_master_public_keys(self):
1338 for k, account in self.accounts.items():
1339 name = self.get_account_name(k)
1340 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1341 out[name] = mpk_text
1344 def get_master_private_key(self, account, password):
1345 k = self.master_private_keys.get(account)
1347 xpriv = pw_decode( k, password)
1350 def check_password(self, password):
1351 xpriv = self.get_master_private_key( "m/", password )
1352 xpub = self.master_public_keys["m/"]
1353 assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1355 def create_watching_only_wallet(self, xpub):
1356 self.storage.put('seed_version', self.seed_version, True)
1357 self.add_master_public_key("m/", xpub)
1358 account = BIP32_Account({'xpub':xpub})
1359 self.add_account("m/", account)
1362 def create_accounts(self, password):
1363 seed = pw_decode(self.seed, password)
1364 self.create_account('Main account', password)
1367 def add_master_public_key(self, name, mpk):
1368 self.master_public_keys[name] = mpk
1369 self.storage.put('master_public_keys', self.master_public_keys, True)
1372 def add_master_private_key(self, name, xpriv, password):
1373 self.master_private_keys[name] = pw_encode(xpriv, password)
1374 self.storage.put('master_private_keys', self.master_private_keys, True)
1377 def add_master_keys(self, root, account_id, password):
1378 x = self.master_private_keys.get(root)
1380 master_xpriv = pw_decode(x, password )
1381 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1382 self.add_master_public_key(account_id, xpub)
1383 self.add_master_private_key(account_id, xpriv, password)
1385 master_xpub = self.master_public_keys[root]
1386 xpub = bip32_public_derivation(master_xpub, root, account_id)
1387 self.add_master_public_key(account_id, xpub)
1391 def create_master_keys(self, password):
1392 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1393 self.add_master_public_key("m/", xpub)
1394 self.add_master_private_key("m/", xpriv, password)
1397 def find_root_by_master_key(self, xpub):
1398 for key, xpub2 in self.master_public_keys.items():
1399 if key == "m/":continue
1404 def num_accounts(self):
1406 for k, v in self.accounts.items():
1407 if type(v) != BIP32_Account:
1413 account_id = self.account_id(i)
1414 if account_id not in keys: break
1419 def next_account_address(self, password):
1420 i = self.num_accounts()
1421 account_id = self.account_id(i)
1423 addr = self.next_addresses.get(account_id)
1425 account = self.make_account(account_id, password)
1426 addr = account.first_address()
1427 self.next_addresses[account_id] = addr
1428 self.storage.put('next_addresses', self.next_addresses)
1430 return account_id, addr
1432 def account_id(self, i):
1435 def make_account(self, account_id, password):
1436 """Creates and saves the master keys, but does not save the account"""
1437 xpub = self.add_master_keys("m/", account_id, password)
1438 account = BIP32_Account({'xpub':xpub})
1442 def make_seed(self):
1443 import mnemonic, ecdsa
1444 entropy = ecdsa.util.randrange( pow(2,160) )
1447 ss = "%040x"%(entropy+nonce)
1448 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1449 # we keep only 13 words, that's approximately 139 bits of entropy
1450 words = mnemonic.mn_encode(s)[0:13]
1451 seed = ' '.join(words)
1452 if is_new_seed(seed):
1453 break # this will remove 8 bits of entropy
1457 def prepare_seed(self, seed):
1459 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1463 class Wallet_2of2(NewWallet):
1465 def __init__(self, storage):
1466 NewWallet.__init__(self, storage)
1467 self.storage.put('wallet_type', '2of2', True)
1469 def can_create_accounts(self):
1472 def can_import(self):
1475 def create_account(self):
1476 xpub1 = self.master_public_keys.get("m/")
1477 xpub2 = self.master_public_keys.get("cold/")
1478 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1479 self.add_account('m/', account)
1481 def get_master_public_keys(self):
1482 xpub1 = self.master_public_keys.get("m/")
1483 xpub2 = self.master_public_keys.get("cold/")
1484 return {'hot':xpub1, 'cold':xpub2}
1486 def get_action(self):
1487 xpub1 = self.master_public_keys.get("m/")
1488 xpub2 = self.master_public_keys.get("cold/")
1490 return 'create_2of2_1'
1492 return 'create_2of2_2'
1496 class Wallet_2of3(Wallet_2of2):
1498 def __init__(self, storage):
1499 Wallet_2of2.__init__(self, storage)
1500 self.storage.put('wallet_type', '2of3', True)
1502 def create_account(self):
1503 xpub1 = self.master_public_keys.get("m/")
1504 xpub2 = self.master_public_keys.get("cold/")
1505 xpub3 = self.master_public_keys.get("remote/")
1506 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1507 self.add_account('m/', account)
1509 def get_master_public_keys(self):
1510 xpub1 = self.master_public_keys.get("m/")
1511 xpub2 = self.master_public_keys.get("cold/")
1512 xpub3 = self.master_public_keys.get("remote/")
1513 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1515 def get_action(self):
1516 xpub1 = self.master_public_keys.get("m/")
1517 xpub2 = self.master_public_keys.get("cold/")
1518 xpub3 = self.master_public_keys.get("remote/")
1519 # fixme: we use order of creation
1520 if xpub2 and xpub1 is None:
1521 return 'create_2fa_2'
1523 return 'create_2of3_1'
1524 if xpub2 is None or xpub3 is None:
1525 return 'create_2of3_2'
1531 class OldWallet(Deterministic_Wallet):
1533 def make_seed(self):
1535 seed = random_seed(128)
1536 return ' '.join(mnemonic.mn_encode(seed))
1538 def prepare_seed(self, seed):
1540 # see if seed was entered as hex
1545 return OLD_SEED_VERSION, str(seed)
1549 words = seed.split()
1550 seed = mnemonic.mn_decode(words)
1552 raise Exception("Invalid seed")
1554 return OLD_SEED_VERSION, seed
1557 def create_master_keys(self, password):
1558 seed = self.get_seed(password)
1559 mpk = OldAccount.mpk_from_seed(seed)
1560 self.storage.put('master_public_key', mpk, True)
1562 def get_master_public_key(self):
1563 return self.storage.get("master_public_key")
1565 def get_master_public_keys(self):
1566 return {'Main Account':self.get_master_public_key()}
1568 def create_accounts(self, password):
1569 mpk = self.storage.get("master_public_key")
1570 self.create_account(mpk)
1572 def create_account(self, mpk):
1573 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1574 self.save_accounts()
1576 def create_watching_only_wallet(self, mpk):
1577 self.seed_version = OLD_SEED_VERSION
1578 self.storage.put('seed_version', self.seed_version, True)
1579 self.storage.put('master_public_key', mpk, True)
1580 self.create_account(mpk)
1582 def get_seed(self, password):
1583 seed = pw_decode(self.seed, password).encode('utf8')
1586 def check_password(self, password):
1587 seed = self.get_seed(password)
1588 self.accounts[0].check_seed(seed)
1590 def get_mnemonic(self, password):
1592 s = self.get_seed(password)
1593 return ' '.join(mnemonic.mn_encode(s))
1595 def check_pending_accounts(self):
1599 # former WalletFactory
1600 class Wallet(object):
1602 def __new__(self, storage):
1603 config = storage.config
1604 if config.get('bitkey', False):
1605 # if user requested support for Bitkey device,
1606 # import Bitkey driver
1607 from wallet_bitkey import WalletBitkey
1608 return WalletBitkey(config)
1610 if storage.get('wallet_type') == '2of2':
1611 return Wallet_2of2(storage)
1613 if storage.get('wallet_type') == '2of3':
1614 return Wallet_2of3(storage)
1616 if storage.get('wallet_type') == 'imported':
1617 return Imported_Wallet(storage)
1620 if not storage.file_exists:
1621 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1623 seed_version = storage.get('seed_version')
1624 if not seed_version:
1625 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1627 if seed_version == OLD_SEED_VERSION:
1628 return OldWallet(storage)
1629 elif seed_version == NEW_SEED_VERSION:
1630 return NewWallet(storage)
1632 msg = "This wallet seed is not supported."
1633 if seed_version in [5]:
1634 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1641 def is_seed(self, seed):
1644 elif is_old_seed(seed):
1646 elif is_new_seed(seed):
1652 def is_mpk(self, mpk):
1660 return len(mpk) == 128
1663 deserialize_xkey(mpk)
1669 def is_address(self, text):
1672 for x in text.split():
1673 if not bitcoin.is_address(x):
1678 def is_private_key(self, text):
1681 for x in text.split():
1682 if not bitcoin.is_private_key(x):
1687 def from_seed(self, seed, storage):
1688 if is_old_seed(seed):
1690 elif is_new_seed(seed):
1696 def from_address(self, text, storage):
1697 w = Imported_Wallet(storage)
1698 for x in text.split():
1699 w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1704 def from_private_key(self, text, storage):
1705 w = Imported_Wallet(storage)
1706 for x in text.split():
1707 w.import_key(x, None)
1711 def from_mpk(self, mpk, storage):
1720 w = OldWallet(storage)
1722 w.create_watching_only_wallet(mpk)
1724 w = NewWallet(storage)
1725 w.create_watching_only_wallet(mpk)