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
158 self.transactions = {}
159 tx_list = self.storage.get('transactions',{})
160 for k, raw in tx_list.items():
162 tx = Transaction.deserialize(raw)
164 print_msg("Warning: Cannot deserialize transactions. skipping")
167 self.add_pubkey_addresses(tx)
168 self.transactions[k] = tx
170 for h,tx in self.transactions.items():
171 if not self.check_new_tx(h, tx):
172 print_error("removing unreferenced tx", h)
173 self.transactions.pop(h)
176 self.prevout_values = {} # my own transaction outputs
177 self.spent_outputs = []
182 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
183 # interface.is_up_to_date() returns true when all requests have been answered and processed
184 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
186 self.up_to_date = False
187 self.lock = threading.Lock()
188 self.transaction_lock = threading.Lock()
189 self.tx_event = threading.Event()
190 for tx_hash, tx in self.transactions.items():
191 self.update_tx_outputs(tx_hash)
193 def add_pubkey_addresses(self, tx):
194 # find the address corresponding to pay-to-pubkey inputs
198 tx.add_pubkey_addresses(self.transactions)
200 # outputs of tx: inputs of tx2
201 for type, x, v in tx.outputs:
203 for tx2 in self.transactions.values():
204 tx2.add_pubkey_addresses({h:tx})
206 def get_action(self):
209 def convert_imported_keys(self, password):
210 for k, v in self.imported_keys.items():
211 sec = pw_decode(v, password)
212 pubkey = public_key_from_private_key(sec)
213 address = public_key_to_bc_address(pubkey.decode('hex'))
215 self.import_key(sec, password)
216 self.imported_keys.pop(k)
217 self.storage.put('imported_keys', self.imported_keys)
219 def load_accounts(self):
221 self.imported_keys = self.storage.get('imported_keys',{})
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.get_seed(password)
385 # build a list of public/private keys
388 # add private keys from parameter
389 for sec in private_keys:
390 pubkey = public_key_from_private_key(sec)
391 keypairs[ pubkey ] = sec
394 self.add_keypairs(tx, keypairs, password)
396 # sign the transaction
397 self.sign_transaction(tx, keypairs, password)
399 def sign_message(self, address, message, password):
400 keys = self.get_private_key(address, password)
401 assert len(keys) == 1
403 key = regenerate_key(sec)
404 compressed = is_compressed(sec)
405 return key.sign_message(message, compressed, address)
407 def decrypt_message(self, pubkey, message, password):
408 address = public_key_to_bc_address(pubkey.decode('hex'))
409 keys = self.get_private_key(address, password)
411 ec = regenerate_key(secret)
412 decrypted = ec.decrypt_message(message)
416 return self.history.values() != [[]] * len(self.history)
418 def add_contact(self, address, label=None):
419 self.addressbook.append(address)
420 self.storage.put('contacts', self.addressbook, True)
422 self.set_label(address, label)
424 def delete_contact(self, addr):
425 if addr in self.addressbook:
426 self.addressbook.remove(addr)
427 self.storage.put('addressbook', self.addressbook, True)
429 def fill_addressbook(self):
430 for tx_hash, tx in self.transactions.items():
431 is_relevant, is_send, _, _ = self.get_tx_value(tx)
433 for addr in tx.get_output_addresses():
434 if not self.is_mine(addr) and addr not in self.addressbook:
435 self.addressbook.append(addr)
437 # self.update_tx_labels()
439 def get_num_tx(self, address):
441 for tx in self.transactions.values():
442 if address in tx.get_output_addresses(): n += 1
445 def get_address_flags(self, addr):
446 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
447 flags += "F" if addr in self.frozen_addresses else "-"
450 def get_tx_value(self, tx, account=None):
451 domain = self.get_account_addresses(account)
452 return tx.get_value(domain, self.prevout_values)
454 def update_tx_outputs(self, tx_hash):
455 tx = self.transactions.get(tx_hash)
457 for i, (addr, value) in enumerate(tx.get_outputs()):
458 key = tx_hash+ ':%d'%i
459 self.prevout_values[key] = value
461 for item in tx.inputs:
462 if self.is_mine(item.get('address')):
463 key = item['prevout_hash'] + ':%d'%item['prevout_n']
464 self.spent_outputs.append(key)
466 def get_addr_balance(self, address):
467 #assert self.is_mine(address)
468 h = self.history.get(address,[])
469 if h == ['*']: return 0,0
471 received_coins = [] # list of coins received at address
473 for tx_hash, tx_height in h:
474 tx = self.transactions.get(tx_hash)
477 for i, (addr, value) in enumerate(tx.get_outputs()):
479 key = tx_hash + ':%d'%i
480 received_coins.append(key)
482 for tx_hash, tx_height in h:
483 tx = self.transactions.get(tx_hash)
487 for item in tx.inputs:
488 addr = item.get('address')
490 key = item['prevout_hash'] + ':%d'%item['prevout_n']
491 value = self.prevout_values.get( key )
492 if key in received_coins:
495 for i, (addr, value) in enumerate(tx.get_outputs()):
496 key = tx_hash + ':%d'%i
506 def get_account_name(self, k):
507 return self.labels.get(k, self.accounts[k].get_name(k))
509 def get_account_names(self):
511 for k in self.accounts.keys():
512 account_names[k] = self.get_account_name(k)
515 def get_account_addresses(self, a, include_change=True):
517 o = self.addresses(include_change)
518 elif a in self.accounts:
519 ac = self.accounts[a]
520 o = ac.get_addresses(0)
521 if include_change: o += ac.get_addresses(1)
524 def get_account_balance(self, account):
525 return self.get_balance(self.get_account_addresses(account))
527 def get_frozen_balance(self):
528 return self.get_balance(self.frozen_addresses)
530 def get_balance(self, domain=None):
531 if domain is None: domain = self.addresses(True)
534 c, u = self.get_addr_balance(addr)
539 def get_unspent_coins(self, domain=None):
541 if domain is None: domain = self.addresses(True)
543 h = self.history.get(addr, [])
544 if h == ['*']: continue
545 for tx_hash, tx_height in h:
546 tx = self.transactions.get(tx_hash)
547 if tx is None: raise Exception("Wallet not synchronized")
548 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
549 for i, (address, value) in enumerate(tx.get_outputs()):
550 output = {'address':address, 'value':value, 'prevout_n':i}
551 if address != addr: continue
552 key = tx_hash + ":%d"%i
553 if key in self.spent_outputs: continue
554 output['prevout_hash'] = tx_hash
555 output['height'] = tx_height
556 output['coinbase'] = is_coinbase
557 coins.append((tx_height, output))
561 coins = sorted(coins)
562 if coins[-1][0] != 0:
563 while coins[0][0] == 0:
564 coins = coins[1:] + [ coins[0] ]
565 return [x[1] for x in coins]
567 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
568 """ todo: minimize tx size """
570 fee = self.fee if fixed_fee is None else fixed_fee
574 domain = self.addresses(True)
575 for i in self.frozen_addresses:
576 if i in domain: domain.remove(i)
577 coins = self.get_unspent_coins(domain)
582 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
584 v = item.get('value')
587 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
588 if total >= amount + fee: break
592 return inputs, total, fee
594 def set_fee(self, fee):
597 self.storage.put('fee_per_kb', self.fee, True)
599 def estimated_fee(self, inputs, num_outputs):
600 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
601 fee = self.fee * int(math.ceil(estimated_size/1000.))
604 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
605 "add change to a transaction"
606 change_amount = total - ( amount + fee )
607 if change_amount > DUST_THRESHOLD:
610 # send change to one of the accounts involved in the tx
611 address = inputs[0].get('address')
612 account, _ = self.get_address_index(address)
614 if not self.use_change or account == IMPORTED_ACCOUNT:
615 change_addr = inputs[-1]['address']
617 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
619 # Insert the change output at a random position in the outputs
620 posn = random.randint(0, len(outputs))
621 outputs[posn:posn] = [( 'address', change_addr, change_amount)]
624 def get_history(self, address):
626 return self.history.get(address)
628 def get_status(self, h):
629 if not h: return None
630 if h == ['*']: return '*'
632 for tx_hash, height in h:
633 status += tx_hash + ':%d:' % height
634 return hashlib.sha256( status ).digest().encode('hex')
636 def receive_tx_callback(self, tx_hash, tx, tx_height):
638 with self.transaction_lock:
639 self.add_pubkey_addresses(tx)
640 if not self.check_new_tx(tx_hash, tx):
641 # may happen due to pruning
642 print_error("received transaction that is no longer referenced in history", tx_hash)
644 self.transactions[tx_hash] = tx
645 self.network.pending_transactions_for_notifications.append(tx)
646 self.save_transactions()
647 if self.verifier and tx_height>0:
648 self.verifier.add(tx_hash, tx_height)
649 self.update_tx_outputs(tx_hash)
651 def save_transactions(self):
653 for k,v in self.transactions.items():
655 self.storage.put('transactions', tx, True)
657 def receive_history_callback(self, addr, hist):
659 if not self.check_new_history(addr, hist):
660 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
663 self.history[addr] = hist
664 self.storage.put('addr_history', self.history, True)
667 for tx_hash, tx_height in hist:
669 # add it in case it was previously unconfirmed
670 if self.verifier: self.verifier.add(tx_hash, tx_height)
672 def get_tx_history(self, account=None):
673 if not self.verifier:
676 with self.transaction_lock:
677 history = self.transactions.items()
678 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
682 for tx_hash, tx in history:
683 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
684 if v is not None: balance += v
686 c, u = self.get_account_balance(account)
689 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
691 balance = c + u - balance
692 for tx_hash, tx in history:
693 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
696 if value is not None:
699 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
700 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
704 def get_label(self, tx_hash):
705 label = self.labels.get(tx_hash)
706 is_default = (label == '') or (label is None)
707 if is_default: label = self.get_default_label(tx_hash)
708 return label, is_default
710 def get_default_label(self, tx_hash):
711 tx = self.transactions.get(tx_hash)
714 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
716 for o_addr in tx.get_output_addresses():
717 if not self.is_mine(o_addr):
719 default_label = self.labels[o_addr]
721 default_label = '>' + o_addr
724 default_label = '(internal)'
726 for o_addr in tx.get_output_addresses():
727 if self.is_mine(o_addr) and not self.is_change(o_addr):
730 for o_addr in tx.get_output_addresses():
731 if self.is_mine(o_addr):
738 default_label = self.labels[o_addr]
740 default_label = '<' + o_addr
744 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
745 for type, address, x in outputs:
746 if type == 'op_return':
748 if type == 'address':
749 assert is_address(address), "Address " + address + " is invalid!"
750 amount = sum( map(lambda x:x[2], outputs) )
751 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
753 raise ValueError("Not enough funds")
755 self.add_input_info(txin)
756 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
757 return Transaction(inputs, outputs)
759 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
760 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
762 self.add_keypairs(tx, keypairs, password)
764 self.sign_transaction(tx, keypairs, password)
767 def add_input_info(self, txin):
768 address = txin['address']
769 account_id, sequence = self.get_address_index(address)
770 account = self.accounts[account_id]
771 redeemScript = account.redeem_script(*sequence)
772 pubkeys = account.get_pubkeys(*sequence)
773 x_pubkeys = account.get_xpubkeys(*sequence)
774 # sort pubkeys and x_pubkeys, using the order of pubkeys
775 pubkeys, x_pubkeys = zip( *sorted(zip(pubkeys, x_pubkeys)))
776 txin['pubkeys'] = list(pubkeys)
777 txin['x_pubkeys'] = list(x_pubkeys)
778 txin['signatures'] = [None] * len(pubkeys)
781 txin['redeemScript'] = redeemScript
784 txin['redeemPubkey'] = account.get_pubkey(*sequence)
787 def sign_transaction(self, tx, keypairs, password):
789 run_hook('sign_transaction', tx, password)
791 def sendtx(self, tx):
795 return self.receive_tx(h, tx)
797 def send_tx(self, tx):
799 self.tx_event.clear()
800 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
803 def on_broadcast(self, i, r):
804 self.tx_result = r.get('result')
807 def receive_tx(self, tx_hash, tx):
810 return False, "error: " + out
811 run_hook('receive_tx', tx, self)
814 def update_password(self, old_password, new_password):
815 if new_password == '':
819 decoded = self.get_seed(old_password)
820 self.seed = pw_encode( decoded, new_password)
821 self.storage.put('seed', self.seed, True)
823 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
825 imported_account.update_password(old_password, new_password)
828 for k, v in self.master_private_keys.items():
829 b = pw_decode(v, old_password)
830 c = pw_encode(b, new_password)
831 self.master_private_keys[k] = c
832 self.storage.put('master_private_keys', self.master_private_keys, True)
834 self.use_encryption = (new_password != None)
835 self.storage.put('use_encryption', self.use_encryption,True)
837 def freeze(self,addr):
838 if self.is_mine(addr) and addr not in self.frozen_addresses:
839 self.frozen_addresses.append(addr)
840 self.storage.put('frozen_addresses', self.frozen_addresses, True)
845 def unfreeze(self,addr):
846 if self.is_mine(addr) and addr in self.frozen_addresses:
847 self.frozen_addresses.remove(addr)
848 self.storage.put('frozen_addresses', self.frozen_addresses, True)
853 def set_verifier(self, verifier):
854 self.verifier = verifier
856 # review transactions that are in the history
857 for addr, hist in self.history.items():
858 if hist == ['*']: continue
859 for tx_hash, tx_height in hist:
861 # add it in case it was previously unconfirmed
862 self.verifier.add(tx_hash, tx_height)
864 # if we are on a pruning server, remove unverified transactions
865 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
866 for tx_hash in self.transactions.keys():
867 if tx_hash not in vr:
868 self.transactions.pop(tx_hash)
870 def check_new_history(self, addr, hist):
871 # check that all tx in hist are relevant
873 for tx_hash, height in hist:
874 tx = self.transactions.get(tx_hash)
876 if not tx.has_address(addr):
879 # check that we are not "orphaning" a transaction
880 old_hist = self.history.get(addr,[])
881 if old_hist == ['*']: return True
883 for tx_hash, height in old_hist:
884 if tx_hash in map(lambda x:x[0], hist): continue
886 for _addr, _hist in self.history.items():
887 if _addr == addr: continue
888 if _hist == ['*']: continue
889 _tx_hist = map(lambda x:x[0], _hist)
890 if tx_hash in _tx_hist:
895 tx = self.transactions.get(tx_hash)
896 # tx might not be there
900 if self.verifier.get_height(tx_hash):
903 print_error("new history is orphaning transaction:", tx_hash)
904 # check that all outputs are not mine, request histories
906 for _addr in tx.get_output_addresses():
907 # assert not self.is_mine(_addr)
908 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
910 ext_h = self.network.synchronous_get(ext_requests)
911 print_error("sync:", ext_requests, ext_h)
914 if h == ['*']: continue
916 if item.get('tx_hash') == tx_hash:
917 height = item.get('height')
919 print_error("found height for", tx_hash, height)
920 self.verifier.add(tx_hash, height)
922 print_error("removing orphaned tx from history", tx_hash)
923 self.transactions.pop(tx_hash)
927 def check_new_tx(self, tx_hash, tx):
928 # 1 check that tx is referenced in addr_history.
930 for addr, hist in self.history.items():
931 if hist == ['*']:continue
932 for txh, height in hist:
934 addresses.append(addr)
939 # 2 check that referencing addresses are in the tx
940 for addr in addresses:
941 if not tx.has_address(addr):
946 def start_threads(self, network):
947 from verifier import TxVerifier
948 self.network = network
949 if self.network is not None:
950 self.verifier = TxVerifier(self.network, self.storage)
951 self.verifier.start()
952 self.set_verifier(self.verifier)
953 self.synchronizer = WalletSynchronizer(self, network)
954 self.synchronizer.start()
957 self.synchronizer =None
959 def stop_threads(self):
962 self.synchronizer.stop()
964 def restore(self, cb):
967 def get_accounts(self):
970 def save_accounts(self):
972 for k, v in self.accounts.items():
974 self.storage.put('accounts', d, True)
976 def can_import(self):
977 return not self.is_watching_only()
979 def is_used(self, address):
980 h = self.history.get(address,[])
981 c, u = self.get_addr_balance(address)
982 return len(h), len(h) > 0 and c == -u
984 def address_is_old(self, address, age_limit=2):
986 h = self.history.get(address, [])
989 for tx_hash, tx_height in h:
993 tx_age = self.network.get_local_height() - tx_height + 1
996 return age > age_limit
999 class Imported_Wallet(Abstract_Wallet):
1001 def __init__(self, storage):
1002 Abstract_Wallet.__init__(self, storage)
1003 a = self.accounts.get(IMPORTED_ACCOUNT)
1005 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1006 self.storage.put('wallet_type', 'imported', True)
1008 def is_watching_only(self):
1009 acc = self.accounts[IMPORTED_ACCOUNT]
1010 n = acc.keypairs.values()
1011 return n == [(None, None)] * len(n)
1016 def is_deterministic(self):
1019 def check_password(self, password):
1020 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1022 def is_used(self, address):
1023 h = self.history.get(address,[])
1024 return len(h), False
1026 def get_master_public_keys(self):
1029 def is_beyond_limit(self, address, account, is_change):
1033 class Deterministic_Wallet(Abstract_Wallet):
1035 def __init__(self, storage):
1036 Abstract_Wallet.__init__(self, storage)
1039 return self.seed != ''
1041 def is_deterministic(self):
1044 def is_watching_only(self):
1045 return not self.has_seed()
1047 def add_seed(self, seed, password):
1049 raise Exception("a seed exists")
1051 self.seed_version, self.seed = self.prepare_seed(seed)
1053 self.seed = pw_encode( self.seed, password)
1054 self.use_encryption = True
1056 self.use_encryption = False
1058 self.storage.put('seed', self.seed, True)
1059 self.storage.put('seed_version', self.seed_version, True)
1060 self.storage.put('use_encryption', self.use_encryption,True)
1061 self.create_master_keys(password)
1063 def get_seed(self, password):
1064 return pw_decode(self.seed, password)
1066 def get_mnemonic(self, password):
1067 return self.get_seed(password)
1069 def change_gap_limit(self, value):
1070 if value >= self.gap_limit:
1071 self.gap_limit = value
1072 self.storage.put('gap_limit', self.gap_limit, True)
1073 #self.interface.poke('synchronizer')
1076 elif value >= self.min_acceptable_gap():
1077 for key, account in self.accounts.items():
1078 addresses = account[0]
1079 k = self.num_unused_trailing_addresses(addresses)
1080 n = len(addresses) - k + value
1081 addresses = addresses[0:n]
1082 self.accounts[key][0] = addresses
1084 self.gap_limit = value
1085 self.storage.put('gap_limit', self.gap_limit, True)
1086 self.save_accounts()
1091 def num_unused_trailing_addresses(self, addresses):
1093 for a in addresses[::-1]:
1094 if self.history.get(a):break
1098 def min_acceptable_gap(self):
1099 # fixme: this assumes wallet is synchronized
1103 for account in self.accounts.values():
1104 addresses = account.get_addresses(0)
1105 k = self.num_unused_trailing_addresses(addresses)
1106 for a in addresses[0:-k]:
1107 if self.history.get(a):
1111 if n > nmax: nmax = n
1114 def create_new_address(self, account=None, for_change=0):
1116 account = self.default_account()
1117 address = account.create_new_address(for_change)
1118 self.history[address] = []
1119 if self.synchronizer:
1120 self.synchronizer.add(address)
1121 self.save_accounts()
1124 def synchronize_sequence(self, account, for_change):
1125 limit = self.gap_limit_for_change if for_change else self.gap_limit
1127 addresses = account.get_addresses(for_change)
1128 if len(addresses) < limit:
1129 self.create_new_address(account, for_change)
1131 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1134 self.create_new_address(account, for_change)
1136 def check_pending_accounts(self):
1137 for account_id, addr in self.next_addresses.items():
1138 if self.address_is_old(addr):
1139 print_error( "creating account", account_id )
1140 xpub = self.master_public_keys[account_id]
1141 account = BIP32_Account({'xpub':xpub})
1142 self.add_account(account_id, account)
1143 self.next_addresses.pop(account_id)
1145 def synchronize_account(self, account):
1146 self.synchronize_sequence(account, 0)
1147 self.synchronize_sequence(account, 1)
1149 def synchronize(self):
1150 self.check_pending_accounts()
1151 for account in self.accounts.values():
1152 if type(account) in [ImportedAccount, PendingAccount]:
1154 self.synchronize_account(account)
1156 def restore(self, callback):
1158 def wait_for_wallet():
1159 self.set_up_to_date(False)
1160 while not self.is_up_to_date():
1161 msg = "%s\n%s %d\n%s %.1f"%(
1162 _("Please wait..."),
1163 _("Addresses generated:"),
1164 len(self.addresses(True)),
1165 _("Kilobytes received:"),
1166 self.network.interface.bytes_received/1024.)
1168 apply(callback, (msg,))
1171 def wait_for_network():
1172 while not self.network.is_connected():
1173 msg = "%s \n" % (_("Connecting..."))
1174 apply(callback, (msg,))
1177 # wait until we are connected, because the user might have selected another server
1183 self.fill_addressbook()
1185 def create_account(self, name, password):
1186 i = self.num_accounts()
1187 account_id = self.account_id(i)
1188 account = self.make_account(account_id, password)
1189 self.add_account(account_id, account)
1191 self.set_label(account_id, name)
1193 # add address of the next account
1194 _, _ = self.next_account_address(password)
1197 def add_account(self, account_id, account):
1198 self.accounts[account_id] = account
1199 self.save_accounts()
1201 def account_is_pending(self, k):
1202 return type(self.accounts.get(k)) == PendingAccount
1204 def delete_pending_account(self, k):
1205 assert self.account_is_pending(k)
1206 self.accounts.pop(k)
1207 self.save_accounts()
1209 def create_pending_account(self, name, password):
1210 account_id, addr = self.next_account_address(password)
1211 self.set_label(account_id, name)
1212 self.accounts[account_id] = PendingAccount({'pending':addr})
1213 self.save_accounts()
1215 def is_beyond_limit(self, address, account, is_change):
1216 if type(account) == ImportedAccount:
1218 addr_list = account.get_addresses(is_change)
1219 i = addr_list.index(address)
1220 prev_addresses = addr_list[:max(0, i)]
1221 limit = self.gap_limit_for_change if is_change else self.gap_limit
1222 if len(prev_addresses) < limit:
1224 prev_addresses = prev_addresses[max(0, i - limit):]
1225 for addr in prev_addresses:
1226 if self.history.get(addr):
1230 def get_action(self):
1231 if not self.get_master_public_key():
1232 return 'create_seed'
1233 if not self.accounts:
1234 return 'create_accounts'
1237 class NewWallet(Deterministic_Wallet):
1239 def __init__(self, storage):
1240 Deterministic_Wallet.__init__(self, storage)
1241 self.master_public_keys = storage.get('master_public_keys', {})
1242 self.master_private_keys = storage.get('master_private_keys', {})
1244 def default_account(self):
1245 return self.accounts["m/0'"]
1247 def is_watching_only(self):
1248 return not bool(self.master_private_keys)
1250 def can_create_accounts(self):
1251 return 'm/' in self.master_private_keys.keys()
1253 def get_master_public_key(self):
1254 """xpub of the main account"""
1255 return self.master_public_keys.get("m/0'")
1257 def get_master_public_keys(self):
1259 for k, account in self.accounts.items():
1260 name = self.get_account_name(k)
1261 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1262 out[name] = mpk_text
1265 def get_master_private_key(self, account, password):
1266 k = self.master_private_keys.get(account)
1268 xpriv = pw_decode( k, password)
1271 def check_password(self, password):
1272 xpriv = self.get_master_private_key( "m/", password )
1273 xpub = self.master_public_keys["m/"]
1274 assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1276 def create_xprv_wallet(self, xprv, password):
1277 xpub = bitcoin.xpub_from_xprv(xprv)
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_private_key(account_id, xprv, password)
1282 self.add_master_public_key(account_id, xpub)
1283 self.add_account(account_id, account)
1285 def create_watching_only_wallet(self, xpub):
1286 account = BIP32_Account({'xpub':xpub})
1287 account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1288 self.storage.put('seed_version', self.seed_version, True)
1289 self.add_master_public_key(account_id, xpub)
1290 self.add_account(account_id, account)
1292 def create_accounts(self, password):
1293 # First check the password is valid (this raises if it isn't).
1294 if not self.is_watching_only():
1295 self.check_password(password)
1296 self.create_account('Main account', password)
1298 def add_master_public_key(self, name, xpub):
1299 self.master_public_keys[name] = xpub
1300 self.storage.put('master_public_keys', self.master_public_keys, True)
1302 def add_master_private_key(self, name, xpriv, password):
1303 self.master_private_keys[name] = pw_encode(xpriv, password)
1304 self.storage.put('master_private_keys', self.master_private_keys, True)
1306 def add_master_keys(self, root, account_id, password):
1307 x = self.master_private_keys.get(root)
1309 master_xpriv = pw_decode(x, password )
1310 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1311 self.add_master_public_key(account_id, xpub)
1312 self.add_master_private_key(account_id, xpriv, password)
1314 master_xpub = self.master_public_keys[root]
1315 xpub = bip32_public_derivation(master_xpub, root, account_id)
1316 self.add_master_public_key(account_id, xpub)
1319 def create_master_keys(self, password):
1320 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1321 self.add_master_public_key("m/", xpub)
1322 self.add_master_private_key("m/", xpriv, password)
1324 def can_sign(self, tx):
1325 if self.is_watching_only():
1327 if tx.is_complete():
1329 addr_list, xpub_list = tx.inputs_to_sign()
1330 for addr in addr_list:
1331 if self.is_mine(addr):
1333 mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
1334 for xpub, sequence in xpub_list:
1339 def find_root_by_master_key(self, xpub):
1340 for key, xpub2 in self.master_public_keys.items():
1341 if key == "m/":continue
1345 def num_accounts(self):
1347 for k, v in self.accounts.items():
1348 if type(v) != BIP32_Account:
1354 account_id = self.account_id(i)
1355 if account_id not in keys: break
1359 def next_account_address(self, password):
1360 i = self.num_accounts()
1361 account_id = self.account_id(i)
1363 addr = self.next_addresses.get(account_id)
1365 account = self.make_account(account_id, password)
1366 addr = account.first_address()
1367 self.next_addresses[account_id] = addr
1368 self.storage.put('next_addresses', self.next_addresses)
1370 return account_id, addr
1372 def account_id(self, i):
1375 def make_account(self, account_id, password):
1376 """Creates and saves the master keys, but does not save the account"""
1377 xpub = self.add_master_keys("m/", account_id, password)
1378 account = BIP32_Account({'xpub':xpub})
1381 def make_seed(self):
1382 import mnemonic, ecdsa
1383 entropy = ecdsa.util.randrange( pow(2,160) )
1386 ss = "%040x"%(entropy+nonce)
1387 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1388 # we keep only 13 words, that's approximately 139 bits of entropy
1389 words = mnemonic.mn_encode(s)[0:13]
1390 seed = ' '.join(words)
1391 if is_new_seed(seed):
1392 break # this will remove 8 bits of entropy
1396 def prepare_seed(self, seed):
1398 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1401 class Wallet_2of2(NewWallet):
1402 """ This class is used for multisignature addresses"""
1404 def __init__(self, storage):
1405 NewWallet.__init__(self, storage)
1406 self.storage.put('wallet_type', '2of2', True)
1408 def default_account(self):
1409 return self.accounts['m/']
1411 def can_create_accounts(self):
1414 def can_import(self):
1417 def create_account(self, name, password):
1418 xpub1 = self.master_public_keys.get("m/")
1419 xpub2 = self.master_public_keys.get("cold/")
1420 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1421 self.add_account('m/', account)
1423 def get_master_public_keys(self):
1424 xpub1 = self.master_public_keys.get("m/")
1425 xpub2 = self.master_public_keys.get("cold/")
1426 return {'hot':xpub1, 'cold':xpub2}
1428 def get_action(self):
1429 xpub1 = self.master_public_keys.get("m/")
1430 xpub2 = self.master_public_keys.get("cold/")
1432 return 'create_seed'
1434 return 'add_cosigner'
1435 if not self.accounts:
1436 return 'create_accounts'
1439 class Wallet_2of3(Wallet_2of2):
1440 """ This class is used for multisignature addresses"""
1442 def __init__(self, storage):
1443 Wallet_2of2.__init__(self, storage)
1444 self.storage.put('wallet_type', '2of3', True)
1446 def create_account(self, name, password):
1447 xpub1 = self.master_public_keys.get("m/")
1448 xpub2 = self.master_public_keys.get("cold/")
1449 xpub3 = self.master_public_keys.get("remote/")
1450 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1451 self.add_account('m/', account)
1453 def get_master_public_keys(self):
1454 xpub1 = self.master_public_keys.get("m/")
1455 xpub2 = self.master_public_keys.get("cold/")
1456 xpub3 = self.master_public_keys.get("remote/")
1457 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1459 def get_action(self):
1460 xpub1 = self.master_public_keys.get("m/")
1461 xpub2 = self.master_public_keys.get("cold/")
1462 xpub3 = self.master_public_keys.get("remote/")
1464 return 'create_seed'
1465 if xpub2 is None or xpub3 is None:
1466 return 'add_two_cosigners'
1467 if not self.accounts:
1468 return 'create_accounts'
1471 class OldWallet(Deterministic_Wallet):
1473 def default_account(self):
1474 return self.accounts[0]
1476 def make_seed(self):
1478 seed = random_seed(128)
1479 return ' '.join(mnemonic.mn_encode(seed))
1481 def prepare_seed(self, seed):
1483 # see if seed was entered as hex
1488 return OLD_SEED_VERSION, str(seed)
1492 words = seed.split()
1493 seed = mnemonic.mn_decode(words)
1495 raise Exception("Invalid seed")
1497 return OLD_SEED_VERSION, seed
1499 def create_master_keys(self, password):
1500 seed = self.get_seed(password)
1501 mpk = OldAccount.mpk_from_seed(seed)
1502 self.storage.put('master_public_key', mpk, True)
1504 def get_master_public_key(self):
1505 return self.storage.get("master_public_key")
1507 def get_master_public_keys(self):
1508 return {'Main Account':self.get_master_public_key()}
1510 def create_accounts(self, password):
1511 mpk = self.storage.get("master_public_key")
1512 self.create_account(mpk)
1514 def create_account(self, mpk):
1515 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1516 self.save_accounts()
1518 def create_watching_only_wallet(self, mpk):
1519 self.seed_version = OLD_SEED_VERSION
1520 self.storage.put('seed_version', self.seed_version, True)
1521 self.storage.put('master_public_key', mpk, True)
1522 self.create_account(mpk)
1524 def get_seed(self, password):
1525 seed = pw_decode(self.seed, password).encode('utf8')
1528 def check_password(self, password):
1529 seed = self.get_seed(password)
1530 self.accounts[0].check_seed(seed)
1532 def get_mnemonic(self, password):
1534 s = self.get_seed(password)
1535 return ' '.join(mnemonic.mn_encode(s))
1537 def check_pending_accounts(self):
1540 def can_sign(self, tx):
1541 if self.is_watching_only():
1543 if tx.is_complete():
1545 addr_list, xpub_list = tx.inputs_to_sign()
1546 for addr in addr_list:
1547 if self.is_mine(addr):
1549 for xpub, sequence in xpub_list:
1550 if xpub == self.master_public_key:
1554 # former WalletFactory
1555 class Wallet(object):
1556 """The main wallet "entry point".
1557 This class is actually a factory that will return a wallet of the correct
1558 type when passed a WalletStorage instance."""
1560 def __new__(self, storage):
1561 config = storage.config
1563 self.wallet_types = [
1564 ('standard', ("Standard wallet"), NewWallet if config.get('bip32') else OldWallet),
1565 ('imported', ("Imported wallet"), Imported_Wallet),
1566 ('2of2', ("Multisig wallet (2 of 2)"), Wallet_2of2),
1567 ('2of3', ("Multisig wallet (2 of 3)"), Wallet_2of3)
1569 run_hook('add_wallet_types', self.wallet_types)
1571 for t, l, WalletClass in self.wallet_types:
1572 if t == storage.get('wallet_type'):
1573 return WalletClass(storage)
1575 if not storage.file_exists:
1576 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1578 seed_version = storage.get('seed_version')
1579 if not seed_version:
1580 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1582 if seed_version == OLD_SEED_VERSION:
1583 return OldWallet(storage)
1584 elif seed_version == NEW_SEED_VERSION:
1585 return NewWallet(storage)
1587 msg = "This wallet seed is not supported."
1588 if seed_version in [5]:
1589 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1594 def is_seed(self, seed):
1597 elif is_old_seed(seed):
1599 elif is_new_seed(seed):
1605 def is_old_mpk(self, mpk):
1608 assert len(mpk) == 128
1614 def is_xpub(self, text):
1616 assert text[0:4] == 'xpub'
1617 deserialize_xkey(text)
1623 def is_xprv(self, text):
1625 assert text[0:4] == 'xprv'
1626 deserialize_xkey(text)
1632 def is_address(self, text):
1635 for x in text.split():
1636 if not bitcoin.is_address(x):
1641 def is_private_key(self, text):
1644 for x in text.split():
1645 if not bitcoin.is_private_key(x):
1650 def from_seed(self, seed, storage):
1651 if is_old_seed(seed):
1653 elif is_new_seed(seed):
1659 def from_address(self, text, storage):
1660 w = Imported_Wallet(storage)
1661 for x in text.split():
1662 w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1667 def from_private_key(self, text, storage):
1668 w = Imported_Wallet(storage)
1669 for x in text.split():
1670 w.import_key(x, None)
1674 def from_old_mpk(self, mpk, storage):
1675 w = OldWallet(storage)
1677 w.create_watching_only_wallet(mpk)
1681 def from_xpub(self, xpub, storage):
1682 w = NewWallet(storage)
1683 w.create_watching_only_wallet(xpub)
1687 def from_xprv(self, xprv, password, storage):
1688 w = NewWallet(storage)
1689 w.create_xprv_wallet(xprv, password)