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))
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',{})
155 # This attribute is set when wallet.start_threads is called.
156 self.synchronizer = None
160 self.transactions = {}
161 tx_list = self.storage.get('transactions',{})
162 for k, raw in tx_list.items():
164 tx = Transaction.deserialize(raw)
166 print_msg("Warning: Cannot deserialize transactions. skipping")
169 self.add_pubkey_addresses(tx)
170 self.transactions[k] = tx
172 for h,tx in self.transactions.items():
173 if not self.check_new_tx(h, tx):
174 print_error("removing unreferenced tx", h)
175 self.transactions.pop(h)
178 self.prevout_values = {} # my own transaction outputs
179 self.spent_outputs = []
184 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
185 # interface.is_up_to_date() returns true when all requests have been answered and processed
186 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
188 self.up_to_date = False
189 self.lock = threading.Lock()
190 self.transaction_lock = threading.Lock()
191 self.tx_event = threading.Event()
192 for tx_hash, tx in self.transactions.items():
193 self.update_tx_outputs(tx_hash)
195 def add_pubkey_addresses(self, tx):
196 # find the address corresponding to pay-to-pubkey inputs
200 tx.add_pubkey_addresses(self.transactions)
202 # outputs of tx: inputs of tx2
203 for type, x, v in tx.outputs:
205 for tx2 in self.transactions.values():
206 tx2.add_pubkey_addresses({h:tx})
208 def get_action(self):
211 def convert_imported_keys(self, password):
212 for k, v in self.imported_keys.items():
213 sec = pw_decode(v, password)
214 pubkey = public_key_from_private_key(sec)
215 address = public_key_to_bc_address(pubkey.decode('hex'))
217 self.import_key(sec, password)
218 self.imported_keys.pop(k)
219 self.storage.put('imported_keys', self.imported_keys)
221 def load_accounts(self):
223 self.imported_keys = self.storage.get('imported_keys',{})
225 d = self.storage.get('accounts', {})
226 for k, v in d.items():
228 v['mpk'] = self.storage.get('master_public_key')
229 self.accounts[k] = OldAccount(v)
230 elif v.get('imported'):
231 self.accounts[k] = ImportedAccount(v)
233 self.accounts[k] = BIP32_Account_2of3(v)
235 self.accounts[k] = BIP32_Account_2of2(v)
237 self.accounts[k] = BIP32_Account(v)
238 elif v.get('pending'):
239 self.accounts[k] = PendingAccount(v)
241 print_error("cannot load account", v)
243 def synchronize(self):
246 def can_create_accounts(self):
249 def set_up_to_date(self,b):
250 with self.lock: self.up_to_date = b
252 def is_up_to_date(self):
253 with self.lock: return self.up_to_date
256 self.up_to_date = False
257 while not self.is_up_to_date():
260 def is_imported(self, addr):
261 account = self.accounts.get(IMPORTED_ACCOUNT)
263 return addr in account.get_addresses(0)
267 def has_imported_keys(self):
268 account = self.accounts.get(IMPORTED_ACCOUNT)
269 return account is not None
271 def import_key(self, sec, password):
273 pubkey = public_key_from_private_key(sec)
274 address = public_key_to_bc_address(pubkey.decode('hex'))
276 raise Exception('Invalid private key')
278 if self.is_mine(address):
279 raise Exception('Address already in wallet')
281 if self.accounts.get(IMPORTED_ACCOUNT) is None:
282 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
283 self.accounts[IMPORTED_ACCOUNT].add(address, pubkey, sec, password)
286 if self.synchronizer:
287 self.synchronizer.subscribe_to_addresses([address])
290 def delete_imported_key(self, addr):
291 account = self.accounts[IMPORTED_ACCOUNT]
293 if not account.get_addresses(0):
294 self.accounts.pop(IMPORTED_ACCOUNT)
297 def set_label(self, name, text = None):
299 old_text = self.labels.get(name)
302 self.labels[name] = text
306 self.labels.pop(name)
310 self.storage.put('labels', self.labels, True)
312 run_hook('set_label', name, text, changed)
315 def addresses(self, include_change = True, _next=True):
317 for a in self.accounts.keys():
318 o += self.get_account_addresses(a, include_change)
321 for addr in self.next_addresses.values():
326 def is_mine(self, address):
327 return address in self.addresses(True)
329 def is_change(self, address):
330 if not self.is_mine(address): return False
331 acct, s = self.get_address_index(address)
332 if s is None: return False
335 def get_address_index(self, address):
336 for account in self.accounts.keys():
337 for for_change in [0,1]:
338 addresses = self.accounts[account].get_addresses(for_change)
339 for addr in addresses:
341 return account, (for_change, addresses.index(addr))
343 for k,v in self.next_addresses.items():
347 raise Exception("Address not found", address)
349 def get_private_key(self, address, password):
350 if self.is_watching_only():
352 account_id, sequence = self.get_address_index(address)
353 return self.accounts[account_id].get_private_key(sequence, self, password)
355 def get_public_keys(self, address):
356 account_id, sequence = self.get_address_index(address)
357 return self.accounts[account_id].get_pubkeys(sequence)
359 def can_sign(self, tx):
361 if self.is_watching_only():
367 addr_list, xpub_list = tx.inputs_to_sign()
368 for addr in addr_list:
369 if self.is_mine(addr):
372 mpk = [ self.master_public_keys[k] for k in self.master_private_keys.keys() ]
373 for xpub, sequence in xpub_list:
379 def add_keypairs(self, tx, keypairs, password):
380 # first check the provided password. This will raise if invalid.
381 self.check_password(password)
383 addr_list, xpub_list = tx.inputs_to_sign()
384 for addr in addr_list:
385 if self.is_mine(addr):
386 private_keys = self.get_private_key(addr, password)
387 for sec in private_keys:
388 pubkey = public_key_from_private_key(sec)
389 keypairs[ pubkey ] = sec
391 for xpub, sequence in xpub_list:
392 # look for account that can sign
393 for k, account in self.accounts.items():
394 if xpub in account.get_master_pubkeys():
398 pk = account.get_private_key(sequence, self, password)
400 pubkey = public_key_from_private_key(sec)
401 keypairs[pubkey] = sec
403 def signrawtransaction(self, tx, private_keys, password):
404 # check that the password is correct. This will raise if it's not.
405 self.get_seed(password)
407 # build a list of public/private keys
410 # add private keys from parameter
411 for sec in private_keys:
412 pubkey = public_key_from_private_key(sec)
413 keypairs[ pubkey ] = sec
416 self.add_keypairs(tx, keypairs, password)
418 # sign the transaction
419 self.sign_transaction(tx, keypairs, password)
421 def sign_message(self, address, message, password):
422 keys = self.get_private_key(address, password)
423 assert len(keys) == 1
425 key = regenerate_key(sec)
426 compressed = is_compressed(sec)
427 return key.sign_message(message, compressed, address)
429 def decrypt_message(self, pubkey, message, password):
430 address = public_key_to_bc_address(pubkey.decode('hex'))
431 keys = self.get_private_key(address, password)
433 ec = regenerate_key(secret)
434 decrypted = ec.decrypt_message(message)
438 return self.history.values() != [[]] * len(self.history)
440 def add_contact(self, address, label=None):
441 self.addressbook.append(address)
442 self.storage.put('contacts', self.addressbook, True)
444 self.set_label(address, label)
446 def delete_contact(self, addr):
447 if addr in self.addressbook:
448 self.addressbook.remove(addr)
449 self.storage.put('addressbook', self.addressbook, True)
451 def fill_addressbook(self):
452 for tx_hash, tx in self.transactions.items():
453 is_relevant, is_send, _, _ = self.get_tx_value(tx)
455 for addr in tx.get_output_addresses():
456 if not self.is_mine(addr) and addr not in self.addressbook:
457 self.addressbook.append(addr)
459 # self.update_tx_labels()
461 def get_num_tx(self, address):
463 for tx in self.transactions.values():
464 if address in tx.get_output_addresses(): n += 1
467 def get_address_flags(self, addr):
468 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
469 flags += "F" if addr in self.frozen_addresses else "-"
472 def get_tx_value(self, tx, account=None):
473 domain = self.get_account_addresses(account)
474 return tx.get_value(domain, self.prevout_values)
476 def update_tx_outputs(self, tx_hash):
477 tx = self.transactions.get(tx_hash)
479 for i, (addr, value) in enumerate(tx.get_outputs()):
480 key = tx_hash+ ':%d'%i
481 self.prevout_values[key] = value
483 for item in tx.inputs:
484 if self.is_mine(item.get('address')):
485 key = item['prevout_hash'] + ':%d'%item['prevout_n']
486 self.spent_outputs.append(key)
488 def get_addr_balance(self, address):
489 #assert self.is_mine(address)
490 h = self.history.get(address,[])
491 if h == ['*']: return 0,0
493 received_coins = [] # list of coins received at address
495 for tx_hash, tx_height in h:
496 tx = self.transactions.get(tx_hash)
499 for i, (addr, value) in enumerate(tx.get_outputs()):
501 key = tx_hash + ':%d'%i
502 received_coins.append(key)
504 for tx_hash, tx_height in h:
505 tx = self.transactions.get(tx_hash)
509 for item in tx.inputs:
510 addr = item.get('address')
512 key = item['prevout_hash'] + ':%d'%item['prevout_n']
513 value = self.prevout_values.get( key )
514 if key in received_coins:
517 for i, (addr, value) in enumerate(tx.get_outputs()):
518 key = tx_hash + ':%d'%i
528 def get_account_name(self, k):
529 return self.labels.get(k, self.accounts[k].get_name(k))
531 def get_account_names(self):
533 for k in self.accounts.keys():
534 account_names[k] = self.get_account_name(k)
537 def get_account_addresses(self, a, include_change=True):
539 o = self.addresses(include_change)
540 elif a in self.accounts:
541 ac = self.accounts[a]
542 o = ac.get_addresses(0)
543 if include_change: o += ac.get_addresses(1)
546 def get_account_balance(self, account):
547 return self.get_balance(self.get_account_addresses(account))
549 def get_frozen_balance(self):
550 return self.get_balance(self.frozen_addresses)
552 def get_balance(self, domain=None):
553 if domain is None: domain = self.addresses(True)
556 c, u = self.get_addr_balance(addr)
561 def get_unspent_coins(self, domain=None):
563 if domain is None: domain = self.addresses(True)
565 h = self.history.get(addr, [])
566 if h == ['*']: continue
567 for tx_hash, tx_height in h:
568 tx = self.transactions.get(tx_hash)
569 if tx is None: raise Exception("Wallet not synchronized")
570 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
571 for i, (address, value) in enumerate(tx.get_outputs()):
572 output = {'address':address, 'value':value, 'prevout_n':i}
573 if address != addr: continue
574 key = tx_hash + ":%d"%i
575 if key in self.spent_outputs: continue
576 output['prevout_hash'] = tx_hash
577 output['height'] = tx_height
578 output['coinbase'] = is_coinbase
579 coins.append((tx_height, output))
583 coins = sorted(coins)
584 if coins[-1][0] != 0:
585 while coins[0][0] == 0:
586 coins = coins[1:] + [ coins[0] ]
587 return [x[1] for x in coins]
589 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
590 """ todo: minimize tx size """
592 fee = self.fee if fixed_fee is None else fixed_fee
596 domain = self.addresses(True)
597 for i in self.frozen_addresses:
598 if i in domain: domain.remove(i)
599 coins = self.get_unspent_coins(domain)
604 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
606 v = item.get('value')
609 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
610 if total >= amount + fee: break
614 return inputs, total, fee
616 def set_fee(self, fee):
619 self.storage.put('fee_per_kb', self.fee, True)
621 def estimated_fee(self, inputs, num_outputs):
622 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
623 fee = self.fee * int(math.ceil(estimated_size/1000.))
626 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
627 "add change to a transaction"
628 change_amount = total - ( amount + fee )
629 if change_amount > DUST_THRESHOLD:
632 # send change to one of the accounts involved in the tx
633 address = inputs[0].get('address')
634 account, _ = self.get_address_index(address)
636 if not self.use_change or account == IMPORTED_ACCOUNT:
637 change_addr = inputs[-1]['address']
639 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
641 # Insert the change output at a random position in the outputs
642 posn = random.randint(0, len(outputs))
643 outputs[posn:posn] = [( 'address', change_addr, change_amount)]
646 def get_history(self, address):
648 return self.history.get(address)
650 def get_status(self, h):
651 if not h: return None
652 if h == ['*']: return '*'
654 for tx_hash, height in h:
655 status += tx_hash + ':%d:' % height
656 return hashlib.sha256( status ).digest().encode('hex')
658 def receive_tx_callback(self, tx_hash, tx, tx_height):
660 with self.transaction_lock:
661 self.add_pubkey_addresses(tx)
662 if not self.check_new_tx(tx_hash, tx):
663 # may happen due to pruning
664 print_error("received transaction that is no longer referenced in history", tx_hash)
666 self.transactions[tx_hash] = tx
667 self.network.pending_transactions_for_notifications.append(tx)
668 self.save_transactions()
669 if self.verifier and tx_height>0:
670 self.verifier.add(tx_hash, tx_height)
671 self.update_tx_outputs(tx_hash)
673 def save_transactions(self):
675 for k,v in self.transactions.items():
677 self.storage.put('transactions', tx, True)
679 def receive_history_callback(self, addr, hist):
681 if not self.check_new_history(addr, hist):
682 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
685 self.history[addr] = hist
686 self.storage.put('addr_history', self.history, True)
689 for tx_hash, tx_height in hist:
691 # add it in case it was previously unconfirmed
692 if self.verifier: self.verifier.add(tx_hash, tx_height)
694 def get_tx_history(self, account=None):
695 if not self.verifier:
698 with self.transaction_lock:
699 history = self.transactions.items()
700 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
704 for tx_hash, tx in history:
705 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
706 if v is not None: balance += v
708 c, u = self.get_account_balance(account)
711 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
713 balance = c + u - balance
714 for tx_hash, tx in history:
715 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
718 if value is not None:
721 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
722 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
726 def get_label(self, tx_hash):
727 label = self.labels.get(tx_hash)
728 is_default = (label == '') or (label is None)
729 if is_default: label = self.get_default_label(tx_hash)
730 return label, is_default
732 def get_default_label(self, tx_hash):
733 tx = self.transactions.get(tx_hash)
736 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
738 for o_addr in tx.get_output_addresses():
739 if not self.is_mine(o_addr):
741 default_label = self.labels[o_addr]
743 default_label = '>' + o_addr
746 default_label = '(internal)'
748 for o_addr in tx.get_output_addresses():
749 if self.is_mine(o_addr) and not self.is_change(o_addr):
752 for o_addr in tx.get_output_addresses():
753 if self.is_mine(o_addr):
760 default_label = self.labels[o_addr]
762 default_label = '<' + o_addr
766 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
767 for type, address, x in outputs:
768 if type == 'op_return':
770 if type == 'address':
771 assert is_address(address), "Address " + address + " is invalid!"
772 amount = sum( map(lambda x:x[2], outputs) )
773 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
775 raise ValueError("Not enough funds")
777 self.add_input_info(txin)
778 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
779 return Transaction(inputs, outputs)
781 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
782 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
784 self.add_keypairs(tx, keypairs, password)
786 self.sign_transaction(tx, keypairs, password)
789 def add_input_info(self, txin):
790 address = txin['address']
791 account_id, sequence = self.get_address_index(address)
792 account = self.accounts[account_id]
793 redeemScript = account.redeem_script(*sequence)
794 pubkeys = account.get_pubkeys(*sequence)
795 x_pubkeys = account.get_xpubkeys(*sequence)
796 # sort pubkeys and x_pubkeys, using the order of pubkeys
797 pubkeys, x_pubkeys = zip( *sorted(zip(pubkeys, x_pubkeys)))
798 txin['pubkeys'] = list(pubkeys)
799 txin['x_pubkeys'] = list(x_pubkeys)
800 txin['signatures'] = [None] * len(pubkeys)
803 txin['redeemScript'] = redeemScript
806 txin['redeemPubkey'] = account.get_pubkey(*sequence)
809 def sign_transaction(self, tx, keypairs, password):
811 run_hook('sign_transaction', tx, password)
813 def sendtx(self, tx):
817 return self.receive_tx(h, tx)
819 def send_tx(self, tx):
821 self.tx_event.clear()
822 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
825 def on_broadcast(self, i, r):
826 self.tx_result = r.get('result')
829 def receive_tx(self, tx_hash, tx):
832 return False, "error: " + out
833 run_hook('receive_tx', tx, self)
836 def update_password(self, old_password, new_password):
837 if new_password == '':
841 decoded = self.get_seed(old_password)
842 self.seed = pw_encode( decoded, new_password)
843 self.storage.put('seed', self.seed, True)
845 imported_account = self.accounts.get(IMPORTED_ACCOUNT)
847 imported_account.update_password(old_password, new_password)
850 for k, v in self.master_private_keys.items():
851 b = pw_decode(v, old_password)
852 c = pw_encode(b, new_password)
853 self.master_private_keys[k] = c
854 self.storage.put('master_private_keys', self.master_private_keys, True)
856 self.use_encryption = (new_password != None)
857 self.storage.put('use_encryption', self.use_encryption,True)
859 def freeze(self,addr):
860 if self.is_mine(addr) and addr not in self.frozen_addresses:
861 self.frozen_addresses.append(addr)
862 self.storage.put('frozen_addresses', self.frozen_addresses, True)
867 def unfreeze(self,addr):
868 if self.is_mine(addr) and addr in self.frozen_addresses:
869 self.frozen_addresses.remove(addr)
870 self.storage.put('frozen_addresses', self.frozen_addresses, True)
875 def set_verifier(self, verifier):
876 self.verifier = verifier
878 # review transactions that are in the history
879 for addr, hist in self.history.items():
880 if hist == ['*']: continue
881 for tx_hash, tx_height in hist:
883 # add it in case it was previously unconfirmed
884 self.verifier.add(tx_hash, tx_height)
886 # if we are on a pruning server, remove unverified transactions
887 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
888 for tx_hash in self.transactions.keys():
889 if tx_hash not in vr:
890 self.transactions.pop(tx_hash)
892 def check_new_history(self, addr, hist):
893 # check that all tx in hist are relevant
895 for tx_hash, height in hist:
896 tx = self.transactions.get(tx_hash)
898 if not tx.has_address(addr):
901 # check that we are not "orphaning" a transaction
902 old_hist = self.history.get(addr,[])
903 if old_hist == ['*']: return True
905 for tx_hash, height in old_hist:
906 if tx_hash in map(lambda x:x[0], hist): continue
908 for _addr, _hist in self.history.items():
909 if _addr == addr: continue
910 if _hist == ['*']: continue
911 _tx_hist = map(lambda x:x[0], _hist)
912 if tx_hash in _tx_hist:
917 tx = self.transactions.get(tx_hash)
918 # tx might not be there
922 if self.verifier.get_height(tx_hash):
925 print_error("new history is orphaning transaction:", tx_hash)
926 # check that all outputs are not mine, request histories
928 for _addr in tx.get_output_addresses():
929 # assert not self.is_mine(_addr)
930 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
932 ext_h = self.network.synchronous_get(ext_requests)
933 print_error("sync:", ext_requests, ext_h)
936 if h == ['*']: continue
938 if item.get('tx_hash') == tx_hash:
939 height = item.get('height')
941 print_error("found height for", tx_hash, height)
942 self.verifier.add(tx_hash, height)
944 print_error("removing orphaned tx from history", tx_hash)
945 self.transactions.pop(tx_hash)
949 def check_new_tx(self, tx_hash, tx):
950 # 1 check that tx is referenced in addr_history.
952 for addr, hist in self.history.items():
953 if hist == ['*']:continue
954 for txh, height in hist:
956 addresses.append(addr)
961 # 2 check that referencing addresses are in the tx
962 for addr in addresses:
963 if not tx.has_address(addr):
968 def start_threads(self, network):
969 from verifier import TxVerifier
970 self.network = network
971 if self.network is not None:
972 self.verifier = TxVerifier(self.network, self.storage)
973 self.verifier.start()
974 self.set_verifier(self.verifier)
975 self.synchronizer = WalletSynchronizer(self, network)
976 self.synchronizer.start()
979 self.synchronizer =None
981 def stop_threads(self):
984 self.synchronizer.stop()
986 def restore(self, cb):
989 def get_accounts(self):
992 def save_accounts(self):
994 for k, v in self.accounts.items():
996 self.storage.put('accounts', d, True)
998 def can_import(self):
999 return not self.is_watching_only()
1001 def is_used(self, address):
1002 h = self.history.get(address,[])
1003 c, u = self.get_addr_balance(address)
1004 return len(h), len(h) > 0 and c == -u
1006 def address_is_old(self, address, age_limit=2):
1008 h = self.history.get(address, [])
1011 for tx_hash, tx_height in h:
1015 tx_age = self.network.get_local_height() - tx_height + 1
1018 return age > age_limit
1021 class Imported_Wallet(Abstract_Wallet):
1023 def __init__(self, storage):
1024 Abstract_Wallet.__init__(self, storage)
1025 a = self.accounts.get(IMPORTED_ACCOUNT)
1027 self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
1028 self.storage.put('wallet_type', 'imported', True)
1030 def is_watching_only(self):
1031 acc = self.accounts[IMPORTED_ACCOUNT]
1032 n = acc.keypairs.values()
1033 return n == [(None, None)] * len(n)
1038 def is_deterministic(self):
1041 def check_password(self, password):
1042 self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
1044 def is_used(self, address):
1045 h = self.history.get(address,[])
1046 return len(h), False
1048 def get_master_public_keys(self):
1051 def is_beyond_limit(self, address, account, is_change):
1055 class Deterministic_Wallet(Abstract_Wallet):
1057 def __init__(self, storage):
1058 Abstract_Wallet.__init__(self, storage)
1061 return self.seed != ''
1063 def is_deterministic(self):
1066 def is_watching_only(self):
1067 return not self.has_seed()
1069 def add_seed(self, seed, password):
1071 raise Exception("a seed exists")
1073 self.seed_version, self.seed = self.prepare_seed(seed)
1075 self.seed = pw_encode( self.seed, password)
1076 self.use_encryption = True
1078 self.use_encryption = False
1080 self.storage.put('seed', self.seed, True)
1081 self.storage.put('seed_version', self.seed_version, True)
1082 self.storage.put('use_encryption', self.use_encryption,True)
1083 self.create_master_keys(password)
1085 def get_seed(self, password):
1086 return pw_decode(self.seed, password)
1088 def get_mnemonic(self, password):
1089 return self.get_seed(password)
1091 def change_gap_limit(self, value):
1092 if value >= self.gap_limit:
1093 self.gap_limit = value
1094 self.storage.put('gap_limit', self.gap_limit, True)
1095 #self.interface.poke('synchronizer')
1098 elif value >= self.min_acceptable_gap():
1099 for key, account in self.accounts.items():
1100 addresses = account[0]
1101 k = self.num_unused_trailing_addresses(addresses)
1102 n = len(addresses) - k + value
1103 addresses = addresses[0:n]
1104 self.accounts[key][0] = addresses
1106 self.gap_limit = value
1107 self.storage.put('gap_limit', self.gap_limit, True)
1108 self.save_accounts()
1113 def num_unused_trailing_addresses(self, addresses):
1115 for a in addresses[::-1]:
1116 if self.history.get(a):break
1120 def min_acceptable_gap(self):
1121 # fixme: this assumes wallet is synchronized
1125 for account in self.accounts.values():
1126 addresses = account.get_addresses(0)
1127 k = self.num_unused_trailing_addresses(addresses)
1128 for a in addresses[0:-k]:
1129 if self.history.get(a):
1133 if n > nmax: nmax = n
1136 def create_new_address(self, account=None, for_change=0):
1138 account = self.default_account()
1139 address = account.create_new_address(for_change)
1140 self.history[address] = []
1141 if self.synchronizer:
1142 self.synchronizer.add(address)
1143 self.save_accounts()
1146 def synchronize_sequence(self, account, for_change):
1147 limit = self.gap_limit_for_change if for_change else self.gap_limit
1149 addresses = account.get_addresses(for_change)
1150 if len(addresses) < limit:
1151 self.create_new_address(account, for_change)
1153 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
1156 self.create_new_address(account, for_change)
1158 def check_pending_accounts(self):
1159 for account_id, addr in self.next_addresses.items():
1160 if self.address_is_old(addr):
1161 print_error( "creating account", account_id )
1162 xpub = self.master_public_keys[account_id]
1163 account = BIP32_Account({'xpub':xpub})
1164 self.add_account(account_id, account)
1165 self.next_addresses.pop(account_id)
1167 def synchronize_account(self, account):
1168 self.synchronize_sequence(account, 0)
1169 self.synchronize_sequence(account, 1)
1171 def synchronize(self):
1172 self.check_pending_accounts()
1173 for account in self.accounts.values():
1174 if type(account) in [ImportedAccount, PendingAccount]:
1176 self.synchronize_account(account)
1178 def restore(self, callback):
1180 def wait_for_wallet():
1181 self.set_up_to_date(False)
1182 while not self.is_up_to_date():
1183 msg = "%s\n%s %d\n%s %.1f"%(
1184 _("Please wait..."),
1185 _("Addresses generated:"),
1186 len(self.addresses(True)),
1187 _("Kilobytes received:"),
1188 self.network.interface.bytes_received/1024.)
1190 apply(callback, (msg,))
1193 def wait_for_network():
1194 while not self.network.is_connected():
1195 msg = "%s \n" % (_("Connecting..."))
1196 apply(callback, (msg,))
1199 # wait until we are connected, because the user might have selected another server
1205 self.fill_addressbook()
1207 def create_account(self, name, password):
1208 i = self.num_accounts()
1209 account_id = self.account_id(i)
1210 account = self.make_account(account_id, password)
1211 self.add_account(account_id, account)
1213 self.set_label(account_id, name)
1215 # add address of the next account
1216 _, _ = self.next_account_address(password)
1219 def add_account(self, account_id, account):
1220 self.accounts[account_id] = account
1221 self.save_accounts()
1223 def account_is_pending(self, k):
1224 return type(self.accounts.get(k)) == PendingAccount
1226 def delete_pending_account(self, k):
1227 assert self.account_is_pending(k)
1228 self.accounts.pop(k)
1229 self.save_accounts()
1231 def create_pending_account(self, name, password):
1232 account_id, addr = self.next_account_address(password)
1233 self.set_label(account_id, name)
1234 self.accounts[account_id] = PendingAccount({'pending':addr})
1235 self.save_accounts()
1237 def is_beyond_limit(self, address, account, is_change):
1238 if type(account) == ImportedAccount:
1240 addr_list = account.get_addresses(is_change)
1241 i = addr_list.index(address)
1242 prev_addresses = addr_list[:max(0, i)]
1243 limit = self.gap_limit_for_change if is_change else self.gap_limit
1244 if len(prev_addresses) < limit:
1246 prev_addresses = prev_addresses[max(0, i - limit):]
1247 for addr in prev_addresses:
1248 if self.history.get(addr):
1252 def get_action(self):
1253 if not self.get_master_public_key():
1254 return 'create_seed'
1255 if not self.accounts:
1256 return 'create_accounts'
1259 class NewWallet(Deterministic_Wallet):
1261 def __init__(self, storage):
1262 Deterministic_Wallet.__init__(self, storage)
1264 def default_account(self):
1265 return self.accounts["m/0'"]
1267 def is_watching_only(self):
1268 return not bool(self.master_private_keys)
1270 def can_create_accounts(self):
1271 return 'm/' in self.master_private_keys.keys()
1273 def get_master_public_key(self):
1274 """xpub of the main account"""
1275 return self.master_public_keys.get("m/0'")
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 if not self.is_watching_only():
1315 self.check_password(password)
1316 self.create_account('Main account', password)
1318 def add_master_public_key(self, name, xpub):
1319 self.master_public_keys[name] = xpub
1320 self.storage.put('master_public_keys', self.master_public_keys, True)
1322 def add_master_private_key(self, name, xpriv, password):
1323 self.master_private_keys[name] = pw_encode(xpriv, password)
1324 self.storage.put('master_private_keys', self.master_private_keys, True)
1326 def add_master_keys(self, root, account_id, password):
1327 x = self.master_private_keys.get(root)
1329 master_xpriv = pw_decode(x, password )
1330 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
1331 self.add_master_public_key(account_id, xpub)
1332 self.add_master_private_key(account_id, xpriv, password)
1334 master_xpub = self.master_public_keys[root]
1335 xpub = bip32_public_derivation(master_xpub, root, account_id)
1336 self.add_master_public_key(account_id, xpub)
1339 def create_master_keys(self, password):
1340 xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
1341 self.add_master_public_key("m/", xpub)
1342 self.add_master_private_key("m/", xpriv, password)
1344 def find_root_by_master_key(self, xpub):
1345 for key, xpub2 in self.master_public_keys.items():
1346 if key == "m/":continue
1350 def num_accounts(self):
1352 for k, v in self.accounts.items():
1353 if type(v) != BIP32_Account:
1359 account_id = self.account_id(i)
1360 if account_id not in keys: break
1364 def next_account_address(self, password):
1365 i = self.num_accounts()
1366 account_id = self.account_id(i)
1368 addr = self.next_addresses.get(account_id)
1370 account = self.make_account(account_id, password)
1371 addr = account.first_address()
1372 self.next_addresses[account_id] = addr
1373 self.storage.put('next_addresses', self.next_addresses)
1375 return account_id, addr
1377 def account_id(self, i):
1380 def make_account(self, account_id, password):
1381 """Creates and saves the master keys, but does not save the account"""
1382 xpub = self.add_master_keys("m/", account_id, password)
1383 account = BIP32_Account({'xpub':xpub})
1386 def make_seed(self):
1387 import mnemonic, ecdsa
1388 entropy = ecdsa.util.randrange( pow(2,160) )
1391 ss = "%040x"%(entropy+nonce)
1392 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
1393 # we keep only 13 words, that's approximately 139 bits of entropy
1394 words = mnemonic.mn_encode(s)[0:13]
1395 seed = ' '.join(words)
1396 if is_new_seed(seed):
1397 break # this will remove 8 bits of entropy
1401 def prepare_seed(self, seed):
1403 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
1406 class Wallet_2of2(NewWallet):
1407 """ This class is used for multisignature addresses"""
1409 def __init__(self, storage):
1410 NewWallet.__init__(self, storage)
1411 self.storage.put('wallet_type', '2of2', True)
1413 def default_account(self):
1414 return self.accounts['m/']
1416 def can_create_accounts(self):
1419 def can_import(self):
1422 def create_account(self, name, password):
1423 xpub1 = self.master_public_keys.get("m/")
1424 xpub2 = self.master_public_keys.get("cold/")
1425 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1426 self.add_account('m/', account)
1428 def get_master_public_keys(self):
1429 xpub1 = self.master_public_keys.get("m/")
1430 xpub2 = self.master_public_keys.get("cold/")
1431 return {'hot':xpub1, 'cold':xpub2}
1433 def get_action(self):
1434 xpub1 = self.master_public_keys.get("m/")
1435 xpub2 = self.master_public_keys.get("cold/")
1437 return 'create_seed'
1439 return 'add_cosigner'
1440 if not self.accounts:
1441 return 'create_accounts'
1444 class Wallet_2of3(Wallet_2of2):
1445 """ This class is used for multisignature addresses"""
1447 def __init__(self, storage):
1448 Wallet_2of2.__init__(self, storage)
1449 self.storage.put('wallet_type', '2of3', True)
1451 def create_account(self, name, password):
1452 xpub1 = self.master_public_keys.get("m/")
1453 xpub2 = self.master_public_keys.get("cold/")
1454 xpub3 = self.master_public_keys.get("remote/")
1455 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1456 self.add_account('m/', account)
1458 def get_master_public_keys(self):
1459 xpub1 = self.master_public_keys.get("m/")
1460 xpub2 = self.master_public_keys.get("cold/")
1461 xpub3 = self.master_public_keys.get("remote/")
1462 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1464 def get_action(self):
1465 xpub1 = self.master_public_keys.get("m/")
1466 xpub2 = self.master_public_keys.get("cold/")
1467 xpub3 = self.master_public_keys.get("remote/")
1469 return 'create_seed'
1470 if xpub2 is None or xpub3 is None:
1471 return 'add_two_cosigners'
1472 if not self.accounts:
1473 return 'create_accounts'
1476 class OldWallet(Deterministic_Wallet):
1478 def default_account(self):
1479 return self.accounts[0]
1481 def make_seed(self):
1483 seed = random_seed(128)
1484 return ' '.join(mnemonic.mn_encode(seed))
1486 def prepare_seed(self, seed):
1488 # see if seed was entered as hex
1493 return OLD_SEED_VERSION, str(seed)
1497 words = seed.split()
1498 seed = mnemonic.mn_decode(words)
1500 raise Exception("Invalid seed")
1502 return OLD_SEED_VERSION, seed
1504 def create_master_keys(self, password):
1505 seed = self.get_seed(password)
1506 mpk = OldAccount.mpk_from_seed(seed)
1507 self.storage.put('master_public_key', mpk, True)
1509 def get_master_public_key(self):
1510 return self.storage.get("master_public_key")
1512 def get_master_public_keys(self):
1513 return {'Main Account':self.get_master_public_key()}
1515 def create_accounts(self, password):
1516 mpk = self.storage.get("master_public_key")
1517 self.create_account(mpk)
1519 def create_account(self, mpk):
1520 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1521 self.save_accounts()
1523 def create_watching_only_wallet(self, mpk):
1524 self.seed_version = OLD_SEED_VERSION
1525 self.storage.put('seed_version', self.seed_version, True)
1526 self.storage.put('master_public_key', mpk, True)
1527 self.create_account(mpk)
1529 def get_seed(self, password):
1530 seed = pw_decode(self.seed, password).encode('utf8')
1533 def check_password(self, password):
1534 seed = self.get_seed(password)
1535 self.accounts[0].check_seed(seed)
1537 def get_mnemonic(self, password):
1539 s = self.get_seed(password)
1540 return ' '.join(mnemonic.mn_encode(s))
1542 def check_pending_accounts(self):
1546 # former WalletFactory
1547 class Wallet(object):
1548 """The main wallet "entry point".
1549 This class is actually a factory that will return a wallet of the correct
1550 type when passed a WalletStorage instance."""
1552 def __new__(self, storage):
1553 config = storage.config
1555 self.wallet_types = [
1556 ('standard', ("Standard wallet"), NewWallet if config.get('bip32') else OldWallet),
1557 ('imported', ("Imported wallet"), Imported_Wallet),
1558 ('2of2', ("Multisig wallet (2 of 2)"), Wallet_2of2),
1559 ('2of3', ("Multisig wallet (2 of 3)"), Wallet_2of3)
1561 run_hook('add_wallet_types', self.wallet_types)
1563 for t, l, WalletClass in self.wallet_types:
1564 if t == storage.get('wallet_type'):
1565 return WalletClass(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)