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'
49 def __init__(self, config):
50 self.lock = threading.Lock()
53 self.file_exists = False
54 self.path = self.init_path(config)
55 print_error( "wallet path", self.path )
60 def init_path(self, config):
61 """Set the path of the wallet."""
63 # command line -w option
64 path = config.get('wallet_path')
69 path = config.get('default_wallet_path')
74 dirpath = os.path.join(config.path, "wallets")
75 if not os.path.exists(dirpath):
78 new_path = os.path.join(config.path, "wallets", "default_wallet")
80 # default path in pre 1.9 versions
81 old_path = os.path.join(config.path, "electrum.dat")
82 if os.path.exists(old_path) and not os.path.exists(new_path):
83 os.rename(old_path, new_path)
89 """Read the contents of the wallet file."""
91 with open(self.path, "r") as f:
96 d = ast.literal_eval( data ) #parse raw data from reading wallet file
98 raise IOError("Cannot read wallet file.")
101 self.file_exists = True
104 def get(self, key, default=None):
105 v = self.data.get(key)
110 def put(self, key, value, save = True):
113 if value is not None:
114 self.data[key] = value
115 elif key in self.data:
122 f = open(self.path,"w")
125 if 'ANDROID_DATA' not in os.environ:
127 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
130 class Abstract_Wallet:
132 Wallet classes are created to handle various address generation methods.
133 Completion states (watching-only, single account, no seed, etc) are handled inside classes.
136 def __init__(self, storage):
137 self.storage = storage
138 self.electrum_version = ELECTRUM_VERSION
139 self.gap_limit_for_change = 3 # constant
141 self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
142 self.gap_limit = storage.get('gap_limit', 5)
143 self.use_change = storage.get('use_change',True)
144 self.use_encryption = storage.get('use_encryption', False)
145 self.seed = storage.get('seed', '') # encrypted
146 self.labels = storage.get('labels', {})
147 self.frozen_addresses = storage.get('frozen_addresses',[])
148 self.addressbook = storage.get('contacts', [])
150 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
152 self.fee = int(storage.get('fee_per_kb', 10000))
154 self.master_public_keys = storage.get('master_public_keys',{})
155 self.master_private_keys = storage.get('master_private_keys', {})
157 self.next_addresses = storage.get('next_addresses',{})
160 # This attribute is set when wallet.start_threads is called.
161 self.synchronizer = None
165 self.transactions = {}
166 tx_list = self.storage.get('transactions',{})
167 for k,v in tx_list.items():
171 print_msg("Warning: Cannot deserialize transactions. skipping")
174 self.add_extra_addresses(tx)
175 self.transactions[k] = tx
177 for h,tx in self.transactions.items():
178 if not self.check_new_tx(h, tx):
179 print_error("removing unreferenced tx", h)
180 self.transactions.pop(h)
184 self.prevout_values = {} # my own transaction outputs
185 self.spent_outputs = []
190 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
191 # interface.is_up_to_date() returns true when all requests have been answered and processed
192 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
194 self.up_to_date = False
195 self.lock = threading.Lock()
196 self.transaction_lock = threading.Lock()
197 self.tx_event = threading.Event()
198 for tx_hash, tx in self.transactions.items():
199 self.update_tx_outputs(tx_hash)
201 def add_extra_addresses(self, tx):
203 # find the address corresponding to pay-to-pubkey inputs
204 tx.add_extra_addresses(self.transactions)
205 for o in tx.d.get('outputs'):
206 if o.get('is_pubkey'):
207 for tx2 in self.transactions.values():
208 tx2.add_extra_addresses({h:tx})
210 def get_action(self):
213 def convert_imported_keys(self, password):
214 for k, v in self.imported_keys.items():
215 sec = pw_decode(v, password)
216 pubkey = public_key_from_private_key(sec)
217 address = public_key_to_bc_address(pubkey.decode('hex'))
219 self.import_key(sec, password)
220 self.imported_keys.pop(k)
221 self.storage.put('imported_keys', self.imported_keys)
223 def load_accounts(self):
225 self.imported_keys = self.storage.get('imported_keys',{})
227 d = self.storage.get('accounts', {})
228 for k, v in d.items():
230 v['mpk'] = self.storage.get('master_public_key')
231 self.accounts[k] = OldAccount(v)
232 elif v.get('imported'):
233 self.accounts[k] = ImportedAccount(v)
235 self.accounts[k] = BIP32_Account_2of3(v)
237 self.accounts[k] = BIP32_Account_2of2(v)
239 self.accounts[k] = BIP32_Account(v)
240 elif v.get('pending'):
241 self.accounts[k] = PendingAccount(v)
243 print_error("cannot load account", v)
245 def synchronize(self):
248 def can_create_accounts(self):
251 def set_up_to_date(self,b):
252 with self.lock: self.up_to_date = b
254 def is_up_to_date(self):
255 with self.lock: return self.up_to_date
258 self.up_to_date = False
259 while not self.is_up_to_date():
262 def is_imported(self, addr):
263 account = self.accounts.get(IMPORTED_ACCOUNT)
265 return addr in account.get_addresses(0)
269 def has_imported_keys(self):
270 account = self.accounts.get(IMPORTED_ACCOUNT)
271 return account is not None
273 def import_key(self, sec, password):
275 pubkey = public_key_from_private_key(sec)
276 address = public_key_to_bc_address(pubkey.decode('hex'))
278 raise Exception('Invalid private key')
280 if self.is_mine(address):
281 raise Exception('Address already in wallet')
283 if self.accounts.get(IMPORTED_ACCOUNT) is None:
284 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
285 self.accounts[IMPORTED_ACCOUNT].add(address, pubkey, sec, password)
288 if self.synchronizer:
289 self.synchronizer.subscribe_to_addresses([address])
292 def delete_imported_key(self, addr):
293 account = self.accounts[IMPORTED_ACCOUNT]
295 if not account.get_addresses(0):
296 self.accounts.pop(IMPORTED_ACCOUNT)
299 def set_label(self, name, text = None):
301 old_text = self.labels.get(name)
304 self.labels[name] = text
308 self.labels.pop(name)
312 self.storage.put('labels', self.labels, True)
314 run_hook('set_label', name, text, changed)
317 def addresses(self, include_change = True, _next=True):
319 for a in self.accounts.keys():
320 o += self.get_account_addresses(a, include_change)
323 for addr in self.next_addresses.values():
328 def is_mine(self, address):
329 return address in self.addresses(True)
331 def is_change(self, address):
332 if not self.is_mine(address): return False
333 acct, s = self.get_address_index(address)
334 if s is None: return False
337 def get_address_index(self, address):
339 for account in self.accounts.keys():
340 for for_change in [0,1]:
341 addresses = self.accounts[account].get_addresses(for_change)
342 for addr in addresses:
344 return account, (for_change, addresses.index(addr))
346 for k,v in self.next_addresses.items():
350 raise Exception("Address not found", address)
352 def getpubkeys(self, addr):
353 assert is_address(addr) and self.is_mine(addr)
354 account, sequence = self.get_address_index(addr)
355 a = self.accounts[account]
356 return a.get_pubkeys( sequence )
358 def get_private_key(self, address, password):
359 if self.is_watching_only():
361 account_id, sequence = self.get_address_index(address)
362 return self.accounts[account_id].get_private_key(sequence, self, password)
364 def get_public_keys(self, address):
365 account_id, sequence = self.get_address_index(address)
366 return self.accounts[account_id].get_pubkeys(sequence)
368 def can_sign(self, tx):
370 if self.is_watching_only():
376 addr_list, xpub_list = tx.inputs_to_sign()
377 for addr in addr_list:
378 if self.is_mine(addr):
381 mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
382 for xpub, sequence in xpub_list:
388 def add_keypairs(self, tx, keypairs, password):
389 # first check the provided password. This will raise if invalid.
390 self.check_password(password)
392 addr_list, xpub_list = tx.inputs_to_sign()
393 for addr in addr_list:
394 if self.is_mine(addr):
395 private_keys = self.get_private_key(addr, password)
396 for sec in private_keys:
397 pubkey = public_key_from_private_key(sec)
398 keypairs[ pubkey ] = sec
400 for xpub, sequence in xpub_list:
401 # look for account that can sign
402 for k, account in self.accounts.items():
403 if xpub in account.get_master_pubkeys():
408 addr = account.get_address(*sequence)
409 pk = self.get_private_key(addr, password)
411 pubkey = public_key_from_private_key(sec)
412 keypairs[pubkey] = sec
414 def signrawtransaction(self, tx, private_keys, password):
415 # check that the password is correct. This will raise if it's not.
416 self.get_seed(password)
418 # build a list of public/private keys
421 # add private keys from parameter
422 for sec in private_keys:
423 pubkey = public_key_from_private_key(sec)
424 keypairs[ pubkey ] = sec
427 self.add_keypairs(tx, keypairs, password)
429 # sign the transaction
430 self.sign_transaction(tx, keypairs, password)
432 def sign_message(self, address, message, password):
433 keys = self.get_private_key(address, password)
434 assert len(keys) == 1
436 key = regenerate_key(sec)
437 compressed = is_compressed(sec)
438 return key.sign_message(message, compressed, address)
440 def decrypt_message(self, pubkey, message, password):
441 address = public_key_to_bc_address(pubkey.decode('hex'))
442 keys = self.get_private_key(address, password)
444 ec = regenerate_key(secret)
445 decrypted = ec.decrypt_message(message)
449 return self.history.values() != [[]] * len(self.history)
451 def add_contact(self, address, label=None):
452 self.addressbook.append(address)
453 self.storage.put('contacts', self.addressbook, True)
455 self.set_label(address, label)
457 def delete_contact(self, addr):
458 if addr in self.addressbook:
459 self.addressbook.remove(addr)
460 self.storage.put('addressbook', self.addressbook, True)
462 def fill_addressbook(self):
463 for tx_hash, tx in self.transactions.items():
464 is_relevant, is_send, _, _ = self.get_tx_value(tx)
466 for addr, v in tx.outputs:
467 if not self.is_mine(addr) and addr not in self.addressbook:
468 self.addressbook.append(addr)
470 # self.update_tx_labels()
472 def get_num_tx(self, address):
474 for tx in self.transactions.values():
475 if address in map(lambda x:x[0], tx.outputs): n += 1
478 def get_address_flags(self, addr):
479 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
480 flags += "F" if addr in self.frozen_addresses else "-"
483 def get_tx_value(self, tx, account=None):
484 domain = self.get_account_addresses(account)
485 return tx.get_value(domain, self.prevout_values)
487 def update_tx_outputs(self, tx_hash):
488 tx = self.transactions.get(tx_hash)
490 for i, (addr, value) in enumerate(tx.outputs):
491 key = tx_hash+ ':%d'%i
492 self.prevout_values[key] = value
494 for item in tx.inputs:
495 if self.is_mine(item.get('address')):
496 key = item['prevout_hash'] + ':%d'%item['prevout_n']
497 self.spent_outputs.append(key)
499 def get_addr_balance(self, address):
500 #assert self.is_mine(address)
501 h = self.history.get(address,[])
502 if h == ['*']: return 0,0
504 received_coins = [] # list of coins received at address
506 for tx_hash, tx_height in h:
507 tx = self.transactions.get(tx_hash)
510 for i, (addr, value) in enumerate(tx.outputs):
512 key = tx_hash + ':%d'%i
513 received_coins.append(key)
515 for tx_hash, tx_height in h:
516 tx = self.transactions.get(tx_hash)
520 for item in tx.inputs:
521 addr = item.get('address')
523 key = item['prevout_hash'] + ':%d'%item['prevout_n']
524 value = self.prevout_values.get( key )
525 if key in received_coins:
528 for i, (addr, value) in enumerate(tx.outputs):
529 key = tx_hash + ':%d'%i
539 def get_account_name(self, k):
540 return self.labels.get(k, self.accounts[k].get_name(k))
542 def get_account_names(self):
544 for k in self.accounts.keys():
545 account_names[k] = self.get_account_name(k)
548 def get_account_addresses(self, a, include_change=True):
550 o = self.addresses(include_change)
551 elif a in self.accounts:
552 ac = self.accounts[a]
553 o = ac.get_addresses(0)
554 if include_change: o += ac.get_addresses(1)
557 def get_account_balance(self, account):
558 return self.get_balance(self.get_account_addresses(account))
560 def get_frozen_balance(self):
561 return self.get_balance(self.frozen_addresses)
563 def get_balance(self, domain=None):
564 if domain is None: domain = self.addresses(True)
567 c, u = self.get_addr_balance(addr)
572 def get_unspent_coins(self, domain=None):
574 if domain is None: domain = self.addresses(True)
576 h = self.history.get(addr, [])
577 if h == ['*']: continue
578 for tx_hash, tx_height in h:
579 tx = self.transactions.get(tx_hash)
580 if tx is None: raise Exception("Wallet not synchronized")
581 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
582 for o in tx.d.get('outputs'):
584 if output.get('address') != addr: continue
585 key = tx_hash + ":%d" % output.get('prevout_n')
586 if key in self.spent_outputs: continue
587 output['prevout_hash'] = tx_hash
588 output['height'] = tx_height
589 output['coinbase'] = is_coinbase
590 coins.append((tx_height, output))
594 coins = sorted(coins)
595 if coins[-1][0] != 0:
596 while coins[0][0] == 0:
597 coins = coins[1:] + [ coins[0] ]
598 return [x[1] for x in coins]
600 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
601 """ todo: minimize tx size """
603 fee = self.fee if fixed_fee is None else fixed_fee
607 domain = self.addresses(True)
608 for i in self.frozen_addresses:
609 if i in domain: domain.remove(i)
610 coins = self.get_unspent_coins(domain)
615 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
617 v = item.get('value')
620 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
621 if total >= amount + fee: break
625 return inputs, total, fee
627 def set_fee(self, fee):
630 self.storage.put('fee_per_kb', self.fee, True)
632 def estimated_fee(self, inputs, num_outputs):
633 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
634 fee = self.fee * int(math.ceil(estimated_size/1000.))
637 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
638 "add change to a transaction"
639 change_amount = total - ( amount + fee )
640 if change_amount > DUST_THRESHOLD:
643 # send change to one of the accounts involved in the tx
644 address = inputs[0].get('address')
645 account, _ = self.get_address_index(address)
647 if not self.use_change or account == IMPORTED_ACCOUNT:
648 change_addr = inputs[-1]['address']
650 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
652 # Insert the change output at a random position in the outputs
653 posn = random.randint(0, len(outputs))
654 outputs[posn:posn] = [( change_addr, change_amount)]
657 def get_history(self, address):
659 return self.history.get(address)
661 def get_status(self, h):
662 if not h: return None
663 if h == ['*']: return '*'
665 for tx_hash, height in h:
666 status += tx_hash + ':%d:' % height
667 return hashlib.sha256( status ).digest().encode('hex')
669 def receive_tx_callback(self, tx_hash, tx, tx_height):
671 with self.transaction_lock:
672 self.add_extra_addresses(tx)
673 if not self.check_new_tx(tx_hash, tx):
674 # may happen due to pruning
675 print_error("received transaction that is no longer referenced in history", tx_hash)
677 self.transactions[tx_hash] = tx
678 self.network.pending_transactions_for_notifications.append(tx)
679 self.save_transactions()
680 if self.verifier and tx_height>0:
681 self.verifier.add(tx_hash, tx_height)
682 self.update_tx_outputs(tx_hash)
684 def save_transactions(self):
686 for k,v in self.transactions.items():
688 self.storage.put('transactions', tx, True)
690 def receive_history_callback(self, addr, hist):
692 if not self.check_new_history(addr, hist):
693 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
696 self.history[addr] = hist
697 self.storage.put('addr_history', self.history, True)
700 for tx_hash, tx_height in hist:
702 # add it in case it was previously unconfirmed
703 if self.verifier: self.verifier.add(tx_hash, tx_height)
705 def get_tx_history(self, account=None):
706 if not self.verifier:
709 with self.transaction_lock:
710 history = self.transactions.items()
711 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
715 for tx_hash, tx in history:
716 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
717 if v is not None: balance += v
719 c, u = self.get_account_balance(account)
722 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
724 balance = c + u - balance
725 for tx_hash, tx in history:
726 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
729 if value is not None:
732 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
733 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
737 def get_label(self, tx_hash):
738 label = self.labels.get(tx_hash)
739 is_default = (label == '') or (label is None)
740 if is_default: label = self.get_default_label(tx_hash)
741 return label, is_default
743 def get_default_label(self, tx_hash):
744 tx = self.transactions.get(tx_hash)
747 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
751 if not self.is_mine(o_addr):
753 default_label = self.labels[o_addr]
755 default_label = '>' + o_addr
758 default_label = '(internal)'
762 if self.is_mine(o_addr) and not self.is_change(o_addr):
767 if self.is_mine(o_addr):
774 default_label = self.labels[o_addr]
776 default_label = '<' + o_addr
780 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
781 for address, x in outputs:
782 if address.startswith('OP_RETURN:'):
784 assert is_address(address), "Address " + address + " is invalid!"
785 amount = sum( map(lambda x:x[1], outputs) )
786 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
788 raise ValueError("Not enough funds")
790 self.add_input_info(txin)
791 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
792 return Transaction.from_io(inputs, outputs)
794 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
795 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
797 self.add_keypairs(tx, keypairs, password)
799 self.sign_transaction(tx, keypairs, password)
802 def add_input_info(self, txin):
803 address = txin['address']
804 account_id, sequence = self.get_address_index(address)
805 account = self.accounts[account_id]
806 redeemScript = account.redeem_script(sequence)
807 txin['x_pubkeys'] = account.get_xpubkeys(sequence)
808 txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
809 txin['signatures'] = [None] * len(pubkeys)
812 txin['redeemScript'] = redeemScript
815 txin['redeemPubkey'] = account.get_pubkey(*sequence)
818 def sign_transaction(self, tx, keypairs, password):
820 run_hook('sign_transaction', tx, password)
822 def sendtx(self, tx):
826 return self.receive_tx(h, tx)
828 def send_tx(self, tx):
830 self.tx_event.clear()
831 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
834 def on_broadcast(self, i, r):
835 self.tx_result = r.get('result')
838 def receive_tx(self, tx_hash, tx):
841 return False, "error: " + out
842 run_hook('receive_tx', tx, self)
845 def update_password(self, old_password, new_password):
846 if new_password == '':
850 decoded = self.get_seed(old_password)
851 self.seed = pw_encode( decoded, new_password)
852 self.storage.put('seed', self.seed, True)
854 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
856 imported_account.update_password(old_password, new_password)
859 for k, v in self.master_private_keys.items():
860 b = pw_decode(v, old_password)
861 c = pw_encode(b, new_password)
862 self.master_private_keys[k] = c
863 self.storage.put('master_private_keys', self.master_private_keys, True)
865 self.use_encryption = (new_password != None)
866 self.storage.put('use_encryption', self.use_encryption,True)
868 def freeze(self,addr):
869 if self.is_mine(addr) and addr not in self.frozen_addresses:
870 self.frozen_addresses.append(addr)
871 self.storage.put('frozen_addresses', self.frozen_addresses, True)
876 def unfreeze(self,addr):
877 if self.is_mine(addr) and addr in self.frozen_addresses:
878 self.frozen_addresses.remove(addr)
879 self.storage.put('frozen_addresses', self.frozen_addresses, True)
884 def set_verifier(self, verifier):
885 self.verifier = verifier
887 # review transactions that are in the history
888 for addr, hist in self.history.items():
889 if hist == ['*']: continue
890 for tx_hash, tx_height in hist:
892 # add it in case it was previously unconfirmed
893 self.verifier.add(tx_hash, tx_height)
895 # if we are on a pruning server, remove unverified transactions
896 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
897 for tx_hash in self.transactions.keys():
898 if tx_hash not in vr:
899 self.transactions.pop(tx_hash)
901 def check_new_history(self, addr, hist):
902 # check that all tx in hist are relevant
904 for tx_hash, height in hist:
905 tx = self.transactions.get(tx_hash)
907 if not tx.has_address(addr):
910 # check that we are not "orphaning" a transaction
911 old_hist = self.history.get(addr,[])
912 if old_hist == ['*']: return True
914 for tx_hash, height in old_hist:
915 if tx_hash in map(lambda x:x[0], hist): continue
917 for _addr, _hist in self.history.items():
918 if _addr == addr: continue
919 if _hist == ['*']: continue
920 _tx_hist = map(lambda x:x[0], _hist)
921 if tx_hash in _tx_hist:
926 tx = self.transactions.get(tx_hash)
927 # tx might not be there
931 if self.verifier.get_height(tx_hash):
934 print_error("new history is orphaning transaction:", tx_hash)
935 # check that all outputs are not mine, request histories
937 for _addr, _v in tx.outputs:
938 # assert not self.is_mine(_addr)
939 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
941 ext_h = self.network.synchronous_get(ext_requests)
942 print_error("sync:", ext_requests, ext_h)
945 if h == ['*']: continue
947 if item.get('tx_hash') == tx_hash:
948 height = item.get('height')
950 print_error("found height for", tx_hash, height)
951 self.verifier.add(tx_hash, height)
953 print_error("removing orphaned tx from history", tx_hash)
954 self.transactions.pop(tx_hash)
958 def check_new_tx(self, tx_hash, tx):
959 # 1 check that tx is referenced in addr_history.
961 for addr, hist in self.history.items():
962 if hist == ['*']:continue
963 for txh, height in hist:
965 addresses.append(addr)
970 # 2 check that referencing addresses are in the tx
971 for addr in addresses:
972 if not tx.has_address(addr):
977 def start_threads(self, network):
978 from verifier import TxVerifier
979 self.network = network
980 if self.network is not None:
981 self.verifier = TxVerifier(self.network, self.storage)
982 self.verifier.start()
983 self.set_verifier(self.verifier)
984 self.synchronizer = WalletSynchronizer(self, network)
985 self.synchronizer.start()
988 self.synchronizer =None
990 def stop_threads(self):
993 self.synchronizer.stop()
995 def restore(self, cb):
998 def get_accounts(self):
1001 def save_accounts(self):
1003 for k, v in self.accounts.items():
1005 self.storage.put('accounts', d, True)
1007 def can_import(self):
1008 return not self.is_watching_only()
1010 def is_used(self, address):
1011 h = self.history.get(address,[])
1012 c, u = self.get_addr_balance(address)
1013 return len(h), len(h) > 0 and c == -u
1015 def address_is_old(self, address, age_limit=2):
1017 h = self.history.get(address, [])
1020 for tx_hash, tx_height in h:
1024 tx_age = self.network.get_local_height() - tx_height + 1
1027 return age > age_limit
1030 class Imported_Wallet(Abstract_Wallet):
1032 def __init__(self, storage):
1033 Abstract_Wallet.__init__(self, storage)
1034 a = self.accounts.get(IMPORTED_ACCOUNT)
1036 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1037 self.storage.put('wallet_type', 'imported', True)
1039 def is_watching_only(self):
1040 acc = self.accounts[IMPORTED_ACCOUNT]
1041 n = acc.keypairs.values()
1042 return n == [(None, None)] * len(n)
1047 def is_deterministic(self):
1050 def check_password(self, password):
1051 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1053 def is_used(self, address):
1054 h = self.history.get(address,[])
1055 return len(h), False
1057 def get_master_public_keys(self):
1060 def is_beyond_limit(self, address, account, is_change):
1063 class Deterministic_Wallet(Abstract_Wallet):
1065 def __init__(self, storage):
1066 Abstract_Wallet.__init__(self, storage)
1069 return self.seed != ''
1071 def is_deterministic(self):
1074 def is_watching_only(self):
1075 return not self.has_seed()
1077 def add_seed(self, seed, password):
1079 raise Exception("a seed exists")
1081 self.seed_version, self.seed = self.prepare_seed(seed)
1083 self.seed = pw_encode( self.seed, password)
1084 self.use_encryption = True
1086 self.use_encryption = False
1088 self.storage.put('seed', self.seed, True)
1089 self.storage.put('seed_version', self.seed_version, True)
1090 self.storage.put('use_encryption', self.use_encryption,True)
1091 self.create_master_keys(password)
1093 def get_seed(self, password):
1094 return pw_decode(self.seed, password)
1096 def get_mnemonic(self, password):
1097 return self.get_seed(password)
1099 def change_gap_limit(self, value):
1100 if value >= self.gap_limit:
1101 self.gap_limit = value
1102 self.storage.put('gap_limit', self.gap_limit, True)
1103 #self.interface.poke('synchronizer')
1106 elif value >= self.min_acceptable_gap():
1107 for key, account in self.accounts.items():
1108 addresses = account[0]
1109 k = self.num_unused_trailing_addresses(addresses)
1110 n = len(addresses) - k + value
1111 addresses = addresses[0:n]
1112 self.accounts[key][0] = addresses
1114 self.gap_limit = value
1115 self.storage.put('gap_limit', self.gap_limit, True)
1116 self.save_accounts()
1121 def num_unused_trailing_addresses(self, addresses):
1123 for a in addresses[::-1]:
1124 if self.history.get(a):break
1128 def min_acceptable_gap(self):
1129 # fixme: this assumes wallet is synchronized
1133 for account in self.accounts.values():
1134 addresses = account.get_addresses(0)
1135 k = self.num_unused_trailing_addresses(addresses)
1136 for a in addresses[0:-k]:
1137 if self.history.get(a):
1141 if n > nmax: nmax = n
1144 def create_new_address(self, account=None, for_change=0):
1146 account = self.default_account()
1147 address = account.create_new_address(for_change)
1148 self.history[address] = []
1149 self.synchronizer.add(address)
1150 self.save_accounts()
1153 def synchronize_sequence(self, account, for_change):
1154 limit = self.gap_limit_for_change if for_change else self.gap_limit
1156 addresses = account.get_addresses(for_change)
1157 if len(addresses) < limit:
1158 self.create_new_address(account, for_change)
1160 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1163 self.create_new_address(account, for_change)
1165 def check_pending_accounts(self):
1166 for account_id, addr in self.next_addresses.items():
1167 if self.address_is_old(addr):
1168 print_error( "creating account", account_id )
1169 xpub = self.master_public_keys[account_id]
1170 account = BIP32_Account({'xpub':xpub})
1171 self.add_account(account_id, account)
1172 self.next_addresses.pop(account_id)
1174 def synchronize_account(self, account):
1175 self.synchronize_sequence(account, 0)
1176 self.synchronize_sequence(account, 1)
1178 def synchronize(self):
1179 self.check_pending_accounts()
1180 for account in self.accounts.values():
1181 if type(account) in [ImportedAccount, PendingAccount]:
1183 self.synchronize_account(account)
1185 def restore(self, callback):
1187 def wait_for_wallet():
1188 self.set_up_to_date(False)
1189 while not self.is_up_to_date():
1190 msg = "%s\n%s %d\n%s %.1f"%(
1191 _("Please wait..."),
1192 _("Addresses generated:"),
1193 len(self.addresses(True)),
1194 _("Kilobytes received:"),
1195 self.network.interface.bytes_received/1024.)
1197 apply(callback, (msg,))
1200 def wait_for_network():
1201 while not self.network.is_connected():
1202 msg = "%s \n" % (_("Connecting..."))
1203 apply(callback, (msg,))
1206 # wait until we are connected, because the user might have selected another server
1212 self.fill_addressbook()
1214 def create_account(self, name, password):
1215 i = self.num_accounts()
1216 account_id = self.account_id(i)
1217 account = self.make_account(account_id, password)
1218 self.add_account(account_id, account)
1220 self.set_label(account_id, name)
1222 # add address of the next account
1223 _, _ = self.next_account_address(password)
1226 def add_account(self, account_id, account):
1227 self.accounts[account_id] = account
1228 self.save_accounts()
1230 def account_is_pending(self, k):
1231 return type(self.accounts.get(k)) == PendingAccount
1233 def delete_pending_account(self, k):
1234 assert self.account_is_pending(k)
1235 self.accounts.pop(k)
1236 self.save_accounts()
1238 def create_pending_account(self, name, password):
1239 account_id, addr = self.next_account_address(password)
1240 self.set_label(account_id, name)
1241 self.accounts[account_id] = PendingAccount({'pending':addr})
1242 self.save_accounts()
1244 def is_beyond_limit(self, address, account, is_change):
1245 if type(account) == ImportedAccount:
1247 addr_list = account.get_addresses(is_change)
1248 i = addr_list.index(address)
1249 prev_addresses = addr_list[:max(0, i)]
1250 limit = self.gap_limit_for_change if is_change else self.gap_limit
1251 if len(prev_addresses) < limit:
1253 prev_addresses = prev_addresses[max(0, i - limit):]
1254 for addr in prev_addresses:
1255 if self.address_is_old(addr):
1260 class NewWallet(Deterministic_Wallet):
1262 def __init__(self, storage):
1263 Deterministic_Wallet.__init__(self, storage)
1265 def default_account(self):
1266 return self.accounts["m/0'"]
1268 def is_watching_only(self):
1269 return self.master_private_keys is {}
1271 def can_create_accounts(self):
1272 return 'm/' in self.master_private_keys.keys()
1274 def get_master_public_key(self):
1275 return self.master_public_keys["m/"]
1277 def get_master_public_keys(self):
1279 for k, account in self.accounts.items():
1280 name = self.get_account_name(k)
1281 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1282 out[name] = mpk_text
1285 def get_master_private_key(self, account, password):
1286 k = self.master_private_keys.get(account)
1288 xpriv = pw_decode( k, password)
1291 def check_password(self, password):
1292 xpriv = self.get_master_private_key( "m/", password )
1293 xpub = self.master_public_keys["m/"]
1294 assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1296 def create_xprv_wallet(self, xprv, password):
1297 xpub = bitcoin.xpub_from_xprv(xprv)
1298 account = BIP32_Account({'xpub':xpub})
1299 account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1300 self.storage.put('seed_version', self.seed_version, True)
1301 self.add_master_private_key(account_id, xprv, password)
1302 self.add_master_public_key(account_id, xpub)
1303 self.add_account(account_id, account)
1305 def create_watching_only_wallet(self, xpub):
1306 account = BIP32_Account({'xpub':xpub})
1307 account_id = 'm/' + bitcoin.get_xkey_name(xpub)
1308 self.storage.put('seed_version', self.seed_version, True)
1309 self.add_master_public_key(account_id, xpub)
1310 self.add_account(account_id, account)
1312 def create_accounts(self, password):
1313 # First check the password is valid (this raises if it isn't).
1314 self.check_password(password)
1315 self.create_account('Main account', password)
1317 def add_master_public_key(self, name, xpub):
1318 self.master_public_keys[name] = xpub
1319 self.storage.put('master_public_keys', self.master_public_keys, True)
1321 def add_master_private_key(self, name, xpriv, password):
1322 self.master_private_keys[name] = pw_encode(xpriv, password)
1323 self.storage.put('master_private_keys', self.master_private_keys, True)
1325 def add_master_keys(self, root, account_id, password):
1326 x = self.master_private_keys.get(root)
1328 master_xpriv = pw_decode(x, password )
1329 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1330 self.add_master_public_key(account_id, xpub)
1331 self.add_master_private_key(account_id, xpriv, password)
1333 master_xpub = self.master_public_keys[root]
1334 xpub = bip32_public_derivation(master_xpub, root, account_id)
1335 self.add_master_public_key(account_id, xpub)
1338 def create_master_keys(self, password):
1339 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1340 self.add_master_public_key("m/", xpub)
1341 self.add_master_private_key("m/", xpriv, password)
1343 def find_root_by_master_key(self, xpub):
1344 for key, xpub2 in self.master_public_keys.items():
1345 if key == "m/":continue
1349 def num_accounts(self):
1351 for k, v in self.accounts.items():
1352 if type(v) != BIP32_Account:
1358 account_id = self.account_id(i)
1359 if account_id not in keys: break
1363 def next_account_address(self, password):
1364 i = self.num_accounts()
1365 account_id = self.account_id(i)
1367 addr = self.next_addresses.get(account_id)
1369 account = self.make_account(account_id, password)
1370 addr = account.first_address()
1371 self.next_addresses[account_id] = addr
1372 self.storage.put('next_addresses', self.next_addresses)
1374 return account_id, addr
1376 def account_id(self, i):
1379 def make_account(self, account_id, password):
1380 """Creates and saves the master keys, but does not save the account"""
1381 xpub = self.add_master_keys("m/", account_id, password)
1382 account = BIP32_Account({'xpub':xpub})
1385 def make_seed(self):
1386 import mnemonic, ecdsa
1387 entropy = ecdsa.util.randrange( pow(2,160) )
1390 ss = "%040x"%(entropy+nonce)
1391 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1392 # we keep only 13 words, that's approximately 139 bits of entropy
1393 words = mnemonic.mn_encode(s)[0:13]
1394 seed = ' '.join(words)
1395 if is_new_seed(seed):
1396 break # this will remove 8 bits of entropy
1400 def prepare_seed(self, seed):
1402 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1405 class Wallet_2of2(NewWallet):
1406 """ This class is used for multisignature addresses"""
1408 def __init__(self, storage):
1409 NewWallet.__init__(self, storage)
1410 self.storage.put('wallet_type', '2of2', True)
1412 def default_account(self):
1413 return self.accounts['m/']
1415 def can_create_accounts(self):
1418 def can_import(self):
1421 def create_account(self):
1422 xpub1 = self.master_public_keys.get("m/")
1423 xpub2 = self.master_public_keys.get("cold/")
1424 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1425 self.add_account('m/', account)
1427 def get_master_public_keys(self):
1428 xpub1 = self.master_public_keys.get("m/")
1429 xpub2 = self.master_public_keys.get("cold/")
1430 return {'hot':xpub1, 'cold':xpub2}
1432 def get_action(self):
1433 xpub1 = self.master_public_keys.get("m/")
1434 xpub2 = self.master_public_keys.get("cold/")
1436 return 'create_2of2_1'
1438 return 'create_2of2_2'
1441 class Wallet_2of3(Wallet_2of2):
1442 """ This class is used for multisignature addresses"""
1444 def __init__(self, storage):
1445 Wallet_2of2.__init__(self, storage)
1446 self.storage.put('wallet_type', '2of3', True)
1448 def create_account(self):
1449 xpub1 = self.master_public_keys.get("m/")
1450 xpub2 = self.master_public_keys.get("cold/")
1451 xpub3 = self.master_public_keys.get("remote/")
1452 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1453 self.add_account('m/', account)
1455 def get_master_public_keys(self):
1456 xpub1 = self.master_public_keys.get("m/")
1457 xpub2 = self.master_public_keys.get("cold/")
1458 xpub3 = self.master_public_keys.get("remote/")
1459 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1461 def get_action(self):
1462 xpub1 = self.master_public_keys.get("m/")
1463 xpub2 = self.master_public_keys.get("cold/")
1464 xpub3 = self.master_public_keys.get("remote/")
1465 # fixme: we use order of creation
1466 if xpub2 and xpub1 is None:
1467 return 'create_2fa_2'
1469 return 'create_2of3_1'
1470 if xpub2 is None or xpub3 is None:
1471 return 'create_2of3_2'
1474 class OldWallet(Deterministic_Wallet):
1476 def default_account(self):
1477 return self.accounts[0]
1479 def make_seed(self):
1481 seed = random_seed(128)
1482 return ' '.join(mnemonic.mn_encode(seed))
1484 def prepare_seed(self, seed):
1486 # see if seed was entered as hex
1491 return OLD_SEED_VERSION, str(seed)
1495 words = seed.split()
1496 seed = mnemonic.mn_decode(words)
1498 raise Exception("Invalid seed")
1500 return OLD_SEED_VERSION, seed
1502 def create_master_keys(self, password):
1503 seed = self.get_seed(password)
1504 mpk = OldAccount.mpk_from_seed(seed)
1505 self.storage.put('master_public_key', mpk, True)
1507 def get_master_public_key(self):
1508 return self.storage.get("master_public_key")
1510 def get_master_public_keys(self):
1511 return {'Main Account':self.get_master_public_key()}
1513 def create_accounts(self, password):
1514 mpk = self.storage.get("master_public_key")
1515 self.create_account(mpk)
1517 def create_account(self, mpk):
1518 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1519 self.save_accounts()
1521 def create_watching_only_wallet(self, mpk):
1522 self.seed_version = OLD_SEED_VERSION
1523 self.storage.put('seed_version', self.seed_version, True)
1524 self.storage.put('master_public_key', mpk, True)
1525 self.create_account(mpk)
1527 def get_seed(self, password):
1528 seed = pw_decode(self.seed, password).encode('utf8')
1531 def check_password(self, password):
1532 seed = self.get_seed(password)
1533 self.accounts[0].check_seed(seed)
1535 def get_mnemonic(self, password):
1537 s = self.get_seed(password)
1538 return ' '.join(mnemonic.mn_encode(s))
1540 def check_pending_accounts(self):
1544 # former WalletFactory
1545 class Wallet(object):
1546 """The main wallet "entry point".
1547 This class is actually a factory that will return a wallet of the correct
1548 type when passed a WalletStorage instance."""
1550 def __new__(self, storage):
1551 config = storage.config
1552 if config.get('bitkey', False):
1553 # if user requested support for Bitkey device,
1554 # import Bitkey driver
1555 from wallet_bitkey import WalletBitkey
1556 return WalletBitkey(config)
1558 if storage.get('wallet_type') == '2of2':
1559 return Wallet_2of2(storage)
1561 if storage.get('wallet_type') == '2of3':
1562 return Wallet_2of3(storage)
1564 if storage.get('wallet_type') == 'imported':
1565 return Imported_Wallet(storage)
1567 if not storage.file_exists:
1568 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1570 seed_version = storage.get('seed_version')
1571 if not seed_version:
1572 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1574 if seed_version == OLD_SEED_VERSION:
1575 return OldWallet(storage)
1576 elif seed_version == NEW_SEED_VERSION:
1577 return NewWallet(storage)
1579 msg = "This wallet seed is not supported."
1580 if seed_version in [5]:
1581 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1586 def is_seed(self, seed):
1589 elif is_old_seed(seed):
1591 elif is_new_seed(seed):
1597 def is_old_mpk(self, mpk):
1600 assert len(mpk) == 128
1606 def is_xpub(self, text):
1608 assert text[0:4] == 'xpub'
1609 deserialize_xkey(text)
1615 def is_xprv(self, text):
1617 assert text[0:4] == 'xprv'
1618 deserialize_xkey(text)
1624 def is_address(self, text):
1627 for x in text.split():
1628 if not bitcoin.is_address(x):
1633 def is_private_key(self, text):
1636 for x in text.split():
1637 if not bitcoin.is_private_key(x):
1642 def from_seed(self, seed, storage):
1643 if is_old_seed(seed):
1645 elif is_new_seed(seed):
1651 def from_address(self, text, storage):
1652 w = Imported_Wallet(storage)
1653 for x in text.split():
1654 w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1659 def from_private_key(self, text, storage):
1660 w = Imported_Wallet(storage)
1661 for x in text.split():
1662 w.import_key(x, None)
1666 def from_old_mpk(self, mpk, storage):
1667 w = OldWallet(storage)
1669 w.create_watching_only_wallet(mpk)
1673 def from_xpub(self, xpub, storage):
1674 w = NewWallet(storage)
1675 w.create_watching_only_wallet(xpub)
1679 def from_xprv(self, xprv, password, storage):
1680 w = NewWallet(storage)
1681 w.create_xprv_wallet(xprv, password)