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 def __init__(self, storage):
133 self.storage = storage
134 self.electrum_version = ELECTRUM_VERSION
135 self.gap_limit_for_change = 3 # constant
137 self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
138 self.gap_limit = storage.get('gap_limit', 5)
139 self.use_change = storage.get('use_change',True)
140 self.use_encryption = storage.get('use_encryption', False)
141 self.seed = storage.get('seed', '') # encrypted
142 self.labels = storage.get('labels', {})
143 self.frozen_addresses = storage.get('frozen_addresses',[])
144 self.addressbook = storage.get('contacts', [])
146 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
148 self.fee = int(storage.get('fee_per_kb', 10000))
150 self.master_public_keys = storage.get('master_public_keys',{})
151 self.master_private_keys = storage.get('master_private_keys', {})
153 self.next_addresses = storage.get('next_addresses',{})
156 # This attribute is set when wallet.start_threads is called.
157 self.synchronizer = None
161 self.transactions = {}
162 tx_list = self.storage.get('transactions',{})
163 for k,v in tx_list.items():
167 print_msg("Warning: Cannot deserialize transactions. skipping")
170 self.add_extra_addresses(tx)
171 self.transactions[k] = tx
173 for h,tx in self.transactions.items():
174 if not self.check_new_tx(h, tx):
175 print_error("removing unreferenced tx", h)
176 self.transactions.pop(h)
180 self.prevout_values = {} # my own transaction outputs
181 self.spent_outputs = []
186 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
187 # interface.is_up_to_date() returns true when all requests have been answered and processed
188 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
190 self.up_to_date = False
191 self.lock = threading.Lock()
192 self.transaction_lock = threading.Lock()
193 self.tx_event = threading.Event()
194 for tx_hash, tx in self.transactions.items():
195 self.update_tx_outputs(tx_hash)
197 def add_extra_addresses(self, tx):
199 # find the address corresponding to pay-to-pubkey inputs
200 tx.add_extra_addresses(self.transactions)
201 for o in tx.d.get('outputs'):
202 if o.get('is_pubkey'):
203 for tx2 in self.transactions.values():
204 tx2.add_extra_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):
335 for account in self.accounts.keys():
336 for for_change in [0,1]:
337 addresses = self.accounts[account].get_addresses(for_change)
338 for addr in addresses:
340 return account, (for_change, addresses.index(addr))
342 for k,v in self.next_addresses.items():
346 raise Exception("Address not found", address)
348 def getpubkeys(self, addr):
349 assert is_valid(addr) and self.is_mine(addr)
350 account, sequence = self.get_address_index(addr)
351 a = self.accounts[account]
352 return a.get_pubkeys( sequence )
354 def get_private_key(self, address, password):
355 if self.is_watching_only():
357 account_id, sequence = self.get_address_index(address)
358 return self.accounts[account_id].get_private_key(sequence, self, password)
360 def get_public_keys(self, address):
361 account_id, sequence = self.get_address_index(address)
362 return self.accounts[account_id].get_pubkeys(sequence)
364 def can_sign(self, tx):
366 if self.is_watching_only():
372 addr_list, xpub_list = tx.inputs_to_sign()
373 for addr in addr_list:
374 if self.is_mine(addr):
377 mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
378 for xpub, sequence in xpub_list:
384 def add_keypairs(self, tx, keypairs, password):
385 # first check the provided password. This will raise if invalid.
386 self.get_seed(password)
387 addr_list, xpub_list = tx.inputs_to_sign()
388 for addr in addr_list:
389 if self.is_mine(addr):
390 private_keys = self.get_private_key(address, password)
391 for sec in private_keys:
392 pubkey = public_key_from_private_key(sec)
393 keypairs[ pubkey ] = sec
395 for xpub, sequence in xpub_list:
396 # look for account that can sign
397 for k, account in self.accounts.items():
398 if xpub in account.get_master_pubkeys():
403 addr = account.get_address(*sequence)
404 pk = self.get_private_key(addr, password)
406 pubkey = public_key_from_private_key(sec)
407 keypairs[pubkey] = sec
409 def signrawtransaction(self, tx, private_keys, password):
410 # check that the password is correct. This will raise if it's not.
411 self.get_seed(password)
413 # build a list of public/private keys
416 # add private keys from parameter
417 for sec in private_keys:
418 pubkey = public_key_from_private_key(sec)
419 keypairs[ pubkey ] = sec
422 self.add_keypairs(tx, keypairs, password)
424 # sign the transaction
425 self.sign_transaction(tx, keypairs, password)
427 def sign_message(self, address, message, password):
428 keys = self.get_private_key(address, password)
429 assert len(keys) == 1
431 key = regenerate_key(sec)
432 compressed = is_compressed(sec)
433 return key.sign_message(message, compressed, address)
435 def decrypt_message(self, pubkey, message, password):
436 address = public_key_to_bc_address(pubkey.decode('hex'))
437 keys = self.get_private_key(address, password)
439 ec = regenerate_key(secret)
440 decrypted = ec.decrypt_message(message)
444 return self.history.values() != [[]] * len(self.history)
446 def add_contact(self, address, label=None):
447 self.addressbook.append(address)
448 self.storage.put('contacts', self.addressbook, True)
450 self.set_label(address, label)
452 def delete_contact(self, addr):
453 if addr in self.addressbook:
454 self.addressbook.remove(addr)
455 self.storage.put('addressbook', self.addressbook, True)
457 def fill_addressbook(self):
458 for tx_hash, tx in self.transactions.items():
459 is_relevant, is_send, _, _ = self.get_tx_value(tx)
461 for addr, v in tx.outputs:
462 if not self.is_mine(addr) and addr not in self.addressbook:
463 self.addressbook.append(addr)
465 # self.update_tx_labels()
467 def get_num_tx(self, address):
469 for tx in self.transactions.values():
470 if address in map(lambda x:x[0], tx.outputs): n += 1
473 def get_address_flags(self, addr):
474 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
475 flags += "F" if addr in self.frozen_addresses else "-"
478 def get_tx_value(self, tx, account=None):
479 domain = self.get_account_addresses(account)
480 return tx.get_value(domain, self.prevout_values)
482 def update_tx_outputs(self, tx_hash):
483 tx = self.transactions.get(tx_hash)
485 for i, (addr, value) in enumerate(tx.outputs):
486 key = tx_hash+ ':%d'%i
487 self.prevout_values[key] = value
489 for item in tx.inputs:
490 if self.is_mine(item.get('address')):
491 key = item['prevout_hash'] + ':%d'%item['prevout_n']
492 self.spent_outputs.append(key)
494 def get_addr_balance(self, address):
495 #assert self.is_mine(address)
496 h = self.history.get(address,[])
497 if h == ['*']: return 0,0
499 received_coins = [] # list of coins received at address
501 for tx_hash, tx_height in h:
502 tx = self.transactions.get(tx_hash)
505 for i, (addr, value) in enumerate(tx.outputs):
507 key = tx_hash + ':%d'%i
508 received_coins.append(key)
510 for tx_hash, tx_height in h:
511 tx = self.transactions.get(tx_hash)
515 for item in tx.inputs:
516 addr = item.get('address')
518 key = item['prevout_hash'] + ':%d'%item['prevout_n']
519 value = self.prevout_values.get( key )
520 if key in received_coins:
523 for i, (addr, value) in enumerate(tx.outputs):
524 key = tx_hash + ':%d'%i
534 def get_account_name(self, k):
535 return self.labels.get(k, self.accounts[k].get_name(k))
537 def get_account_names(self):
539 for k in self.accounts.keys():
540 account_names[k] = self.get_account_name(k)
543 def get_account_addresses(self, a, include_change=True):
545 o = self.addresses(True)
546 elif a in self.accounts:
547 ac = self.accounts[a]
548 o = ac.get_addresses(0)
549 if include_change: o += ac.get_addresses(1)
552 def get_account_balance(self, account):
553 return self.get_balance(self.get_account_addresses(account))
555 def get_frozen_balance(self):
556 return self.get_balance(self.frozen_addresses)
558 def get_balance(self, domain=None):
559 if domain is None: domain = self.addresses(True)
562 c, u = self.get_addr_balance(addr)
567 def get_unspent_coins(self, domain=None):
569 if domain is None: domain = self.addresses(True)
571 h = self.history.get(addr, [])
572 if h == ['*']: continue
573 for tx_hash, tx_height in h:
574 tx = self.transactions.get(tx_hash)
575 if tx is None: raise Exception("Wallet not synchronized")
576 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
577 for o in tx.d.get('outputs'):
579 if output.get('address') != addr: continue
580 key = tx_hash + ":%d" % output.get('prevout_n')
581 if key in self.spent_outputs: continue
582 output['prevout_hash'] = tx_hash
583 output['height'] = tx_height
584 output['coinbase'] = is_coinbase
585 coins.append((tx_height, output))
589 coins = sorted(coins)
590 if coins[-1][0] != 0:
591 while coins[0][0] == 0:
592 coins = coins[1:] + [ coins[0] ]
593 return [x[1] for x in coins]
595 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
596 """ todo: minimize tx size """
598 fee = self.fee if fixed_fee is None else fixed_fee
602 domain = self.addresses(True)
603 for i in self.frozen_addresses:
604 if i in domain: domain.remove(i)
605 coins = self.get_unspent_coins(domain)
610 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
612 v = item.get('value')
615 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
616 if total >= amount + fee: break
620 return inputs, total, fee
622 def set_fee(self, fee):
625 self.storage.put('fee_per_kb', self.fee, True)
627 def estimated_fee(self, inputs, num_outputs):
628 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
629 fee = self.fee * int(math.ceil(estimated_size/1000.))
632 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
633 "add change to a transaction"
634 change_amount = total - ( amount + fee )
635 if change_amount > DUST_THRESHOLD:
638 # send change to one of the accounts involved in the tx
639 address = inputs[0].get('address')
640 account, _ = self.get_address_index(address)
642 if not self.use_change or account == IMPORTED_ACCOUNT:
643 change_addr = inputs[-1]['address']
645 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
647 # Insert the change output at a random position in the outputs
648 posn = random.randint(0, len(outputs))
649 outputs[posn:posn] = [( change_addr, change_amount)]
652 def get_history(self, address):
654 return self.history.get(address)
656 def get_status(self, h):
657 if not h: return None
658 if h == ['*']: return '*'
660 for tx_hash, height in h:
661 status += tx_hash + ':%d:' % height
662 return hashlib.sha256( status ).digest().encode('hex')
664 def receive_tx_callback(self, tx_hash, tx, tx_height):
666 with self.transaction_lock:
667 self.add_extra_addresses(tx)
668 if not self.check_new_tx(tx_hash, tx):
669 # may happen due to pruning
670 print_error("received transaction that is no longer referenced in history", tx_hash)
672 self.transactions[tx_hash] = tx
673 self.network.pending_transactions_for_notifications.append(tx)
674 self.save_transactions()
675 if self.verifier and tx_height>0:
676 self.verifier.add(tx_hash, tx_height)
677 self.update_tx_outputs(tx_hash)
679 def save_transactions(self):
681 for k,v in self.transactions.items():
683 self.storage.put('transactions', tx, True)
685 def receive_history_callback(self, addr, hist):
687 if not self.check_new_history(addr, hist):
688 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
691 self.history[addr] = hist
692 self.storage.put('addr_history', self.history, True)
695 for tx_hash, tx_height in hist:
697 # add it in case it was previously unconfirmed
698 if self.verifier: self.verifier.add(tx_hash, tx_height)
700 def get_tx_history(self, account=None):
701 if not self.verifier:
704 with self.transaction_lock:
705 history = self.transactions.items()
706 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
710 for tx_hash, tx in history:
711 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
712 if v is not None: balance += v
714 c, u = self.get_account_balance(account)
717 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
719 balance = c + u - balance
720 for tx_hash, tx in history:
721 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
724 if value is not None:
727 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
728 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
732 def get_label(self, tx_hash):
733 label = self.labels.get(tx_hash)
734 is_default = (label == '') or (label is None)
735 if is_default: label = self.get_default_label(tx_hash)
736 return label, is_default
738 def get_default_label(self, tx_hash):
739 tx = self.transactions.get(tx_hash)
742 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
746 if not self.is_mine(o_addr):
748 default_label = self.labels[o_addr]
750 default_label = '>' + o_addr
753 default_label = '(internal)'
757 if self.is_mine(o_addr) and not self.is_change(o_addr):
762 if self.is_mine(o_addr):
769 default_label = self.labels[o_addr]
771 default_label = '<' + o_addr
775 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
776 for address, x in outputs:
777 assert is_valid(address), "Address " + address + " is invalid!"
778 amount = sum( map(lambda x:x[1], outputs) )
779 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
781 raise ValueError("Not enough funds")
783 self.add_input_info(txin)
784 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
785 return Transaction.from_io(inputs, outputs)
787 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
788 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
790 self.add_keypairs(tx, keypairs, password)
792 self.sign_transaction(tx, keypairs, password)
795 def add_input_info(self, txin):
796 address = txin['address']
797 account_id, sequence = self.get_address_index(address)
798 account = self.accounts[account_id]
799 redeemScript = account.redeem_script(sequence)
800 txin['x_pubkeys'] = account.get_xpubkeys(sequence)
801 txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
802 txin['signatures'] = [None] * len(pubkeys)
805 txin['redeemScript'] = redeemScript
808 txin['redeemPubkey'] = account.get_pubkey(*sequence)
811 def sign_transaction(self, tx, keypairs, password):
813 run_hook('sign_transaction', tx, password)
815 def sendtx(self, tx):
819 return self.receive_tx(h, tx)
821 def send_tx(self, tx):
823 self.tx_event.clear()
824 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
827 def on_broadcast(self, i, r):
828 self.tx_result = r.get('result')
831 def receive_tx(self, tx_hash, tx):
834 return False, "error: " + out
835 run_hook('receive_tx', tx, self)
838 def update_password(self, old_password, new_password):
839 if new_password == '':
843 decoded = self.get_seed(old_password)
844 self.seed = pw_encode( decoded, new_password)
845 self.storage.put('seed', self.seed, True)
847 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
849 imported_account.update_password(old_password, new_password)
852 for k, v in self.master_private_keys.items():
853 b = pw_decode(v, old_password)
854 c = pw_encode(b, new_password)
855 self.master_private_keys[k] = c
856 self.storage.put('master_private_keys', self.master_private_keys, True)
858 self.use_encryption = (new_password != None)
859 self.storage.put('use_encryption', self.use_encryption,True)
861 def freeze(self,addr):
862 if self.is_mine(addr) and addr not in self.frozen_addresses:
863 self.frozen_addresses.append(addr)
864 self.storage.put('frozen_addresses', self.frozen_addresses, True)
869 def unfreeze(self,addr):
870 if self.is_mine(addr) and addr in self.frozen_addresses:
871 self.frozen_addresses.remove(addr)
872 self.storage.put('frozen_addresses', self.frozen_addresses, True)
877 def set_verifier(self, verifier):
878 self.verifier = verifier
880 # review transactions that are in the history
881 for addr, hist in self.history.items():
882 if hist == ['*']: continue
883 for tx_hash, tx_height in hist:
885 # add it in case it was previously unconfirmed
886 self.verifier.add(tx_hash, tx_height)
888 # if we are on a pruning server, remove unverified transactions
889 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
890 for tx_hash in self.transactions.keys():
891 if tx_hash not in vr:
892 self.transactions.pop(tx_hash)
894 def check_new_history(self, addr, hist):
895 # check that all tx in hist are relevant
897 for tx_hash, height in hist:
898 tx = self.transactions.get(tx_hash)
900 if not tx.has_address(addr):
903 # check that we are not "orphaning" a transaction
904 old_hist = self.history.get(addr,[])
905 if old_hist == ['*']: return True
907 for tx_hash, height in old_hist:
908 if tx_hash in map(lambda x:x[0], hist): continue
910 for _addr, _hist in self.history.items():
911 if _addr == addr: continue
912 if _hist == ['*']: continue
913 _tx_hist = map(lambda x:x[0], _hist)
914 if tx_hash in _tx_hist:
919 tx = self.transactions.get(tx_hash)
920 # tx might not be there
924 if self.verifier.get_height(tx_hash):
927 print_error("new history is orphaning transaction:", tx_hash)
928 # check that all outputs are not mine, request histories
930 for _addr, _v in tx.outputs:
931 # assert not self.is_mine(_addr)
932 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
934 ext_h = self.network.synchronous_get(ext_requests)
935 print_error("sync:", ext_requests, ext_h)
938 if h == ['*']: continue
940 if item.get('tx_hash') == tx_hash:
941 height = item.get('height')
943 print_error("found height for", tx_hash, height)
944 self.verifier.add(tx_hash, height)
946 print_error("removing orphaned tx from history", tx_hash)
947 self.transactions.pop(tx_hash)
951 def check_new_tx(self, tx_hash, tx):
952 # 1 check that tx is referenced in addr_history.
954 for addr, hist in self.history.items():
955 if hist == ['*']:continue
956 for txh, height in hist:
958 addresses.append(addr)
963 # 2 check that referencing addresses are in the tx
964 for addr in addresses:
965 if not tx.has_address(addr):
970 def start_threads(self, network):
971 from verifier import TxVerifier
972 self.network = network
973 if self.network is not None:
974 self.verifier = TxVerifier(self.network, self.storage)
975 self.verifier.start()
976 self.set_verifier(self.verifier)
977 self.synchronizer = WalletSynchronizer(self, network)
978 self.synchronizer.start()
981 self.synchronizer =None
983 def stop_threads(self):
986 self.synchronizer.stop()
988 def restore(self, cb):
991 def get_accounts(self):
994 def save_accounts(self):
996 for k, v in self.accounts.items():
998 self.storage.put('accounts', d, True)
1000 def can_import(self):
1001 return not self.is_watching_only()
1003 def is_used(self, address):
1004 h = self.history.get(address,[])
1005 c, u = self.get_addr_balance(address)
1006 return len(h), len(h) > 0 and c == -u
1009 class Imported_Wallet(Abstract_Wallet):
1011 def __init__(self, storage):
1012 Abstract_Wallet.__init__(self, storage)
1013 a = self.accounts.get(IMPORTED_ACCOUNT)
1015 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1016 self.storage.put('wallet_type', 'imported', True)
1018 def is_watching_only(self):
1019 acc = self.accounts[IMPORTED_ACCOUNT]
1020 n = acc.keypairs.values()
1021 return n == [(None, None)] * len(n)
1026 def is_deterministic(self):
1029 def check_password(self, password):
1030 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1032 def is_used(self, address):
1033 h = self.history.get(address,[])
1034 return len(h), False
1037 class Deterministic_Wallet(Abstract_Wallet):
1039 def __init__(self, storage):
1040 Abstract_Wallet.__init__(self, storage)
1043 return self.seed != ''
1045 def is_deterministic(self):
1048 def is_watching_only(self):
1049 return not self.has_seed()
1051 def add_seed(self, seed, password):
1053 raise Exception("a seed exists")
1055 self.seed_version, self.seed = self.prepare_seed(seed)
1057 self.seed = pw_encode( self.seed, password)
1058 self.use_encryption = True
1060 self.use_encryption = False
1062 self.storage.put('seed', self.seed, True)
1063 self.storage.put('seed_version', self.seed_version, True)
1064 self.storage.put('use_encryption', self.use_encryption,True)
1065 self.create_master_keys(password)
1067 def get_seed(self, password):
1068 return pw_decode(self.seed, password)
1070 def get_mnemonic(self, password):
1071 return self.get_seed(password)
1073 def change_gap_limit(self, value):
1074 if value >= self.gap_limit:
1075 self.gap_limit = value
1076 self.storage.put('gap_limit', self.gap_limit, True)
1077 #self.interface.poke('synchronizer')
1080 elif value >= self.min_acceptable_gap():
1081 for key, account in self.accounts.items():
1082 addresses = account[0]
1083 k = self.num_unused_trailing_addresses(addresses)
1084 n = len(addresses) - k + value
1085 addresses = addresses[0:n]
1086 self.accounts[key][0] = addresses
1088 self.gap_limit = value
1089 self.storage.put('gap_limit', self.gap_limit, True)
1090 self.save_accounts()
1095 def num_unused_trailing_addresses(self, addresses):
1097 for a in addresses[::-1]:
1098 if self.history.get(a):break
1102 def min_acceptable_gap(self):
1103 # fixme: this assumes wallet is synchronized
1107 for account in self.accounts.values():
1108 addresses = account.get_addresses(0)
1109 k = self.num_unused_trailing_addresses(addresses)
1110 for a in addresses[0:-k]:
1111 if self.history.get(a):
1115 if n > nmax: nmax = n
1118 def address_is_old(self, address):
1120 h = self.history.get(address, [])
1123 for tx_hash, tx_height in h:
1127 tx_age = self.network.get_local_height() - tx_height + 1
1132 def synchronize_sequence(self, account, for_change):
1133 limit = self.gap_limit_for_change if for_change else self.gap_limit
1136 addresses = account.get_addresses(for_change)
1137 if len(addresses) < limit:
1138 address = account.create_new_address(for_change)
1139 self.history[address] = []
1140 new_addresses.append( address )
1143 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1146 address = account.create_new_address(for_change)
1147 self.history[address] = []
1148 new_addresses.append( address )
1150 return new_addresses
1152 def check_pending_accounts(self):
1153 for account_id, addr in self.next_addresses.items():
1154 if self.address_is_old(addr):
1155 print_error( "creating account", account_id )
1156 xpub = self.master_public_keys[account_id]
1157 account = BIP32_Account({'xpub':xpub})
1158 self.add_account(account_id, account)
1159 self.next_addresses.pop(account_id)
1161 def synchronize_account(self, account):
1163 new += self.synchronize_sequence(account, 0)
1164 new += self.synchronize_sequence(account, 1)
1167 def synchronize(self):
1168 self.check_pending_accounts()
1170 for account in self.accounts.values():
1171 if type(account) in [ImportedAccount, PendingAccount]:
1173 new += self.synchronize_account(account)
1175 self.save_accounts()
1176 self.storage.put('addr_history', self.history, True)
1179 def restore(self, callback):
1181 def wait_for_wallet():
1182 self.set_up_to_date(False)
1183 while not self.is_up_to_date():
1184 msg = "%s\n%s %d\n%s %.1f"%(
1185 _("Please wait..."),
1186 _("Addresses generated:"),
1187 len(self.addresses(True)),
1188 _("Kilobytes received:"),
1189 self.network.interface.bytes_received/1024.)
1191 apply(callback, (msg,))
1194 def wait_for_network():
1195 while not self.network.is_connected():
1196 msg = "%s \n" % (_("Connecting..."))
1197 apply(callback, (msg,))
1200 # wait until we are connected, because the user might have selected another server
1206 self.fill_addressbook()
1208 def create_account(self, name, password):
1209 i = self.num_accounts()
1210 account_id = self.account_id(i)
1211 account = self.make_account(account_id, password)
1212 self.add_account(account_id, account)
1214 self.set_label(account_id, name)
1216 # add address of the next account
1217 _, _ = self.next_account_address(password)
1220 def add_account(self, account_id, account):
1221 self.accounts[account_id] = account
1222 self.save_accounts()
1224 def account_is_pending(self, k):
1225 return type(self.accounts.get(k)) == PendingAccount
1227 def delete_pending_account(self, k):
1228 assert self.account_is_pending(k)
1229 self.accounts.pop(k)
1230 self.save_accounts()
1232 def create_pending_account(self, name, password):
1233 account_id, addr = self.next_account_address(password)
1234 self.set_label(account_id, name)
1235 self.accounts[account_id] = PendingAccount({'pending':addr})
1236 self.save_accounts()
1239 class NewWallet(Deterministic_Wallet):
1241 def __init__(self, storage):
1242 Deterministic_Wallet.__init__(self, storage)
1244 def can_create_accounts(self):
1245 return not self.is_watching_only()
1247 def get_master_public_key(self):
1248 return self.master_public_keys["m/"]
1250 def get_master_public_keys(self):
1252 for k, account in self.accounts.items():
1253 name = self.get_account_name(k)
1254 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
1255 out[name] = mpk_text
1258 def get_master_private_key(self, account, password):
1259 k = self.master_private_keys.get(account)
1261 xpriv = pw_decode( k, password)
1264 def check_password(self, password):
1265 xpriv = self.get_master_private_key( "m/", password )
1266 xpub = self.master_public_keys["m/"]
1267 assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
1269 def create_watching_only_wallet(self, xpub):
1270 self.storage.put('seed_version', self.seed_version, True)
1271 self.add_master_public_key("m/", xpub)
1272 account = BIP32_Account({'xpub':xpub})
1273 self.add_account("m/", account)
1275 def create_accounts(self, password):
1276 # First check the password is valid (this raises if it isn't).
1277 pw_decode(self.seed, password)
1278 self.create_account('Main account', password)
1280 def add_master_public_key(self, name, mpk):
1281 self.master_public_keys[name] = mpk
1282 self.storage.put('master_public_keys', self.master_public_keys, True)
1284 def add_master_private_key(self, name, xpriv, password):
1285 self.master_private_keys[name] = pw_encode(xpriv, password)
1286 self.storage.put('master_private_keys', self.master_private_keys, True)
1288 def add_master_keys(self, root, account_id, password):
1289 x = self.master_private_keys.get(root)
1291 master_xpriv = pw_decode(x, password )
1292 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1293 self.add_master_public_key(account_id, xpub)
1294 self.add_master_private_key(account_id, xpriv, password)
1296 master_xpub = self.master_public_keys[root]
1297 xpub = bip32_public_derivation(master_xpub, root, account_id)
1298 self.add_master_public_key(account_id, xpub)
1301 def create_master_keys(self, password):
1302 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1303 self.add_master_public_key("m/", xpub)
1304 self.add_master_private_key("m/", xpriv, password)
1306 def find_root_by_master_key(self, xpub):
1307 for key, xpub2 in self.master_public_keys.items():
1308 if key == "m/":continue
1312 def num_accounts(self):
1314 for k, v in self.accounts.items():
1315 if type(v) != BIP32_Account:
1321 account_id = self.account_id(i)
1322 if account_id not in keys: break
1326 def next_account_address(self, password):
1327 i = self.num_accounts()
1328 account_id = self.account_id(i)
1330 addr = self.next_addresses.get(account_id)
1332 account = self.make_account(account_id, password)
1333 addr = account.first_address()
1334 self.next_addresses[account_id] = addr
1335 self.storage.put('next_addresses', self.next_addresses)
1337 return account_id, addr
1339 def account_id(self, i):
1342 def make_account(self, account_id, password):
1343 """Creates and saves the master keys, but does not save the account"""
1344 xpub = self.add_master_keys("m/", account_id, password)
1345 account = BIP32_Account({'xpub':xpub})
1348 def make_seed(self):
1349 import mnemonic, ecdsa
1350 entropy = ecdsa.util.randrange( pow(2,160) )
1353 ss = "%040x"%(entropy+nonce)
1354 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1355 # we keep only 13 words, that's approximately 139 bits of entropy
1356 words = mnemonic.mn_encode(s)[0:13]
1357 seed = ' '.join(words)
1358 if is_new_seed(seed):
1359 break # this will remove 8 bits of entropy
1363 def prepare_seed(self, seed):
1365 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1368 class Wallet_2of2(NewWallet):
1369 """ This class is used for multisignature addresses"""
1371 def __init__(self, storage):
1372 NewWallet.__init__(self, storage)
1373 self.storage.put('wallet_type', '2of2', True)
1375 def can_create_accounts(self):
1378 def can_import(self):
1381 def create_account(self):
1382 xpub1 = self.master_public_keys.get("m/")
1383 xpub2 = self.master_public_keys.get("cold/")
1384 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1385 self.add_account('m/', account)
1387 def get_master_public_keys(self):
1388 xpub1 = self.master_public_keys.get("m/")
1389 xpub2 = self.master_public_keys.get("cold/")
1390 return {'hot':xpub1, 'cold':xpub2}
1392 def get_action(self):
1393 xpub1 = self.master_public_keys.get("m/")
1394 xpub2 = self.master_public_keys.get("cold/")
1396 return 'create_2of2_1'
1398 return 'create_2of2_2'
1401 class Wallet_2of3(Wallet_2of2):
1402 """ This class is used for multisignature addresses"""
1404 def __init__(self, storage):
1405 Wallet_2of2.__init__(self, storage)
1406 self.storage.put('wallet_type', '2of3', True)
1408 def create_account(self):
1409 xpub1 = self.master_public_keys.get("m/")
1410 xpub2 = self.master_public_keys.get("cold/")
1411 xpub3 = self.master_public_keys.get("remote/")
1412 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1413 self.add_account('m/', account)
1415 def get_master_public_keys(self):
1416 xpub1 = self.master_public_keys.get("m/")
1417 xpub2 = self.master_public_keys.get("cold/")
1418 xpub3 = self.master_public_keys.get("remote/")
1419 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1421 def get_action(self):
1422 xpub1 = self.master_public_keys.get("m/")
1423 xpub2 = self.master_public_keys.get("cold/")
1424 xpub3 = self.master_public_keys.get("remote/")
1425 # fixme: we use order of creation
1426 if xpub2 and xpub1 is None:
1427 return 'create_2fa_2'
1429 return 'create_2of3_1'
1430 if xpub2 is None or xpub3 is None:
1431 return 'create_2of3_2'
1434 class OldWallet(Deterministic_Wallet):
1436 def make_seed(self):
1438 seed = random_seed(128)
1439 return ' '.join(mnemonic.mn_encode(seed))
1441 def prepare_seed(self, seed):
1443 # see if seed was entered as hex
1448 return OLD_SEED_VERSION, str(seed)
1452 words = seed.split()
1453 seed = mnemonic.mn_decode(words)
1455 raise Exception("Invalid seed")
1457 return OLD_SEED_VERSION, seed
1459 def create_master_keys(self, password):
1460 seed = self.get_seed(password)
1461 mpk = OldAccount.mpk_from_seed(seed)
1462 self.storage.put('master_public_key', mpk, True)
1464 def get_master_public_key(self):
1465 return self.storage.get("master_public_key")
1467 def get_master_public_keys(self):
1468 return {'Main Account':self.get_master_public_key()}
1470 def create_accounts(self, password):
1471 mpk = self.storage.get("master_public_key")
1472 self.create_account(mpk)
1474 def create_account(self, mpk):
1475 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1476 self.save_accounts()
1478 def create_watching_only_wallet(self, mpk):
1479 self.seed_version = OLD_SEED_VERSION
1480 self.storage.put('seed_version', self.seed_version, True)
1481 self.storage.put('master_public_key', mpk, True)
1482 self.create_account(mpk)
1484 def get_seed(self, password):
1485 seed = pw_decode(self.seed, password).encode('utf8')
1488 def check_password(self, password):
1489 seed = self.get_seed(password)
1490 self.accounts[0].check_seed(seed)
1492 def get_mnemonic(self, password):
1494 s = self.get_seed(password)
1495 return ' '.join(mnemonic.mn_encode(s))
1497 def check_pending_accounts(self):
1501 # former WalletFactory
1502 class Wallet(object):
1503 """The main wallet "entry point".
1504 This class is actually a factory that will return a wallet of the correct
1505 type when passed a WalletStorage instance."""
1507 def __new__(self, storage):
1508 config = storage.config
1509 if config.get('bitkey', False):
1510 # if user requested support for Bitkey device,
1511 # import Bitkey driver
1512 from wallet_bitkey import WalletBitkey
1513 return WalletBitkey(config)
1515 if storage.get('wallet_type') == '2of2':
1516 return Wallet_2of2(storage)
1518 if storage.get('wallet_type') == '2of3':
1519 return Wallet_2of3(storage)
1521 if storage.get('wallet_type') == 'imported':
1522 return Imported_Wallet(storage)
1524 if not storage.file_exists:
1525 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1527 seed_version = storage.get('seed_version')
1528 if not seed_version:
1529 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1531 if seed_version == OLD_SEED_VERSION:
1532 return OldWallet(storage)
1533 elif seed_version == NEW_SEED_VERSION:
1534 return NewWallet(storage)
1536 msg = "This wallet seed is not supported."
1537 if seed_version in [5]:
1538 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1543 def is_seed(self, seed):
1546 elif is_old_seed(seed):
1548 elif is_new_seed(seed):
1554 def is_mpk(self, mpk):
1562 return len(mpk) == 128
1565 deserialize_xkey(mpk)
1571 def is_address(self, text):
1574 for x in text.split():
1575 if not bitcoin.is_address(x):
1580 def is_private_key(self, text):
1583 for x in text.split():
1584 if not bitcoin.is_private_key(x):
1589 def from_seed(self, seed, storage):
1590 if is_old_seed(seed):
1592 elif is_new_seed(seed):
1598 def from_address(self, text, storage):
1599 w = Imported_Wallet(storage)
1600 for x in text.split():
1601 w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
1606 def from_private_key(self, text, storage):
1607 w = Imported_Wallet(storage)
1608 for x in text.split():
1609 w.import_key(x, None)
1613 def from_mpk(self, mpk, storage):
1621 w = OldWallet(storage)
1623 w.create_watching_only_wallet(mpk)
1625 w = NewWallet(storage)
1626 w.create_watching_only_wallet(mpk)