3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
34 from util import print_msg, print_error, format_satoshis
37 from transaction import Transaction
38 from plugins import run_hook
40 COINBASE_MATURITY = 100
44 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
45 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
47 def pw_encode(s, password):
49 secret = Hash(password)
50 return EncodeAES(secret, s)
54 def pw_decode(s, password):
55 if password is not None:
56 secret = Hash(password)
58 d = DecodeAES(secret, s)
60 raise Exception('Invalid password')
74 def __init__(self, config):
75 self.lock = threading.Lock()
78 self.file_exists = False
79 self.path = self.init_path(config)
80 print_error( "wallet path", self.path )
85 def init_path(self, config):
86 """Set the path of the wallet."""
88 # command line -w option
89 path = config.get('wallet_path')
94 path = config.get('default_wallet_path')
99 dirpath = os.path.join(config.path, "wallets")
100 if not os.path.exists(dirpath):
103 new_path = os.path.join(config.path, "wallets", "default_wallet")
105 # default path in pre 1.9 versions
106 old_path = os.path.join(config.path, "electrum.dat")
107 if os.path.exists(old_path) and not os.path.exists(new_path):
108 os.rename(old_path, new_path)
113 def read(self, path):
114 """Read the contents of the wallet file."""
116 with open(self.path, "r") as f:
121 d = ast.literal_eval( data ) #parse raw data from reading wallet file
123 raise IOError("Cannot read wallet file.")
126 self.file_exists = True
129 def get(self, key, default=None):
130 v = self.data.get(key)
135 def put(self, key, value, save = True):
138 if value is not None:
139 self.data[key] = value
147 f = open(self.path,"w")
150 if 'ANDROID_DATA' not in os.environ:
152 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
160 def __init__(self, storage):
162 self.storage = storage
163 self.electrum_version = ELECTRUM_VERSION
164 self.gap_limit_for_change = 3 # constant
167 self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
169 self.gap_limit = storage.get('gap_limit', 5)
170 self.use_change = storage.get('use_change',True)
171 self.use_encryption = storage.get('use_encryption', False)
172 self.seed = storage.get('seed', '') # encrypted
173 self.labels = storage.get('labels', {})
174 self.frozen_addresses = storage.get('frozen_addresses',[])
175 self.addressbook = storage.get('contacts', [])
177 self.imported_keys = storage.get('imported_keys',{})
178 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
180 self.fee = int(storage.get('fee_per_kb', 10000))
182 self.master_public_keys = storage.get('master_public_keys',{})
183 self.master_private_keys = storage.get('master_private_keys', {})
185 self.next_addresses = storage.get('next_addresses',{})
188 # This attribute is set when wallet.start_threads is called.
189 self.synchronizer = None
193 self.transactions = {}
194 tx_list = self.storage.get('transactions',{})
195 for k,v in tx_list.items():
199 print_msg("Warning: Cannot deserialize transactions. skipping")
202 self.add_extra_addresses(tx)
203 self.transactions[k] = tx
205 for h,tx in self.transactions.items():
206 if not self.check_new_tx(h, tx):
207 print_error("removing unreferenced tx", h)
208 self.transactions.pop(h)
212 self.prevout_values = {} # my own transaction outputs
213 self.spent_outputs = []
218 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
219 # interface.is_up_to_date() returns true when all requests have been answered and processed
220 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
222 self.up_to_date = False
223 self.lock = threading.Lock()
224 self.transaction_lock = threading.Lock()
225 self.tx_event = threading.Event()
227 for tx_hash, tx in self.transactions.items():
228 self.update_tx_outputs(tx_hash)
231 def add_extra_addresses(self, tx):
233 # find the address corresponding to pay-to-pubkey inputs
234 tx.add_extra_addresses(self.transactions)
235 for o in tx.d.get('outputs'):
236 if o.get('is_pubkey'):
237 for tx2 in self.transactions.values():
238 tx2.add_extra_addresses({h:tx})
241 def get_action(self):
245 def can_create_accounts(self):
246 return not self.is_watching_only()
249 def set_up_to_date(self,b):
250 with self.lock: self.up_to_date = b
253 def is_up_to_date(self):
254 with self.lock: return self.up_to_date
258 self.up_to_date = False
259 while not self.is_up_to_date():
263 def import_key(self, sec, password):
265 seed = self.get_seed(password)
267 address = address_from_private_key(sec)
269 raise Exception('Invalid private key')
271 if self.is_mine(address):
272 raise Exception('Address already in wallet')
274 # store the originally requested keypair into the imported keys table
275 self.imported_keys[address] = pw_encode(sec, password )
276 self.storage.put('imported_keys', self.imported_keys, True)
277 if self.synchronizer:
278 self.synchronizer.subscribe_to_addresses([address])
281 def delete_imported_key(self, addr):
282 if addr in self.imported_keys:
283 self.imported_keys.pop(addr)
284 self.storage.put('imported_keys', self.imported_keys, True)
288 import mnemonic, ecdsa
289 entropy = ecdsa.util.randrange( pow(2,160) )
292 ss = "%040x"%(entropy+nonce)
293 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
294 # we keep only 13 words, that's approximately 139 bits of entropy
295 words = mnemonic.mn_encode(s)[0:13]
296 seed = ' '.join(words)
297 if is_new_seed(seed):
298 break # this will remove 8 bits of entropy
304 def prepare_seed(self, seed):
306 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
310 def add_seed(self, seed, password):
312 raise Exception("a seed exists")
314 self.seed_version, self.seed = self.prepare_seed(seed)
316 self.seed = pw_encode( self.seed, password)
317 self.use_encryption = True
319 self.use_encryption = False
321 self.storage.put('seed', self.seed, True)
322 self.storage.put('seed_version', self.seed_version, True)
323 self.storage.put('use_encryption', self.use_encryption,True)
324 self.create_master_keys(password)
327 def create_watching_only_wallet(self, xpub):
328 self.storage.put('seed_version', self.seed_version, True)
329 self.add_master_public_key("m/", xpub)
330 account = BIP32_Account({'xpub':xpub})
331 self.add_account("m/", account)
334 def create_accounts(self, password):
335 seed = pw_decode(self.seed, password)
336 self.create_account('Main account', password)
339 def add_master_public_key(self, name, mpk):
340 self.master_public_keys[name] = mpk
341 self.storage.put('master_public_keys', self.master_public_keys, True)
344 def add_master_private_key(self, name, xpriv, password):
345 self.master_private_keys[name] = pw_encode(xpriv, password)
346 self.storage.put('master_private_keys', self.master_private_keys, True)
349 def add_master_keys(self, root, account_id, password):
350 x = self.master_private_keys.get(root)
352 master_xpriv = pw_decode(x, password )
353 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
354 self.add_master_public_key(account_id, xpub)
355 self.add_master_private_key(account_id, xpriv, password)
357 master_xpub = self.master_public_keys[root]
358 xpub = bip32_public_derivation(master_xpub, root, account_id)
359 self.add_master_public_key(account_id, xpub)
363 def create_master_keys(self, password):
364 xpriv, xpub = bip32_root(self.get_seed(password))
365 self.add_master_public_key("m/", xpub)
366 self.add_master_private_key("m/", xpriv, password)
369 def find_root_by_master_key(self, xpub):
370 for key, xpub2 in self.master_public_keys.items():
371 if key == "m/":continue
375 def is_watching_only(self):
376 return (self.seed == '') and (self.master_private_keys == {})
379 def num_accounts(self):
380 keys = self.accounts.keys()
383 account_id = self.account_id(i)
384 if account_id not in keys: break
389 def next_account_address(self, password):
390 i = self.num_accounts()
391 account_id = self.account_id(i)
393 addr = self.next_addresses.get(account_id)
395 account = self.make_account(account_id, password)
396 addr = account.first_address()
397 self.next_addresses[account_id] = addr
398 self.storage.put('next_addresses', self.next_addresses)
400 return account_id, addr
402 def account_id(self, i):
405 def make_account(self, account_id, password):
406 """Creates and saves the master keys, but does not save the account"""
407 xpub = self.add_master_keys("m/", account_id, password)
408 account = BIP32_Account({'xpub':xpub})
412 def set_label(self, name, text = None):
414 old_text = self.labels.get(name)
417 self.labels[name] = text
421 self.labels.pop(name)
425 self.storage.put('labels', self.labels, True)
427 run_hook('set_label', name, text, changed)
431 def create_account(self, name, password):
432 i = self.num_accounts()
433 account_id = self.account_id(i)
434 account = self.make_account(account_id, password)
435 self.add_account(account_id, account)
437 self.set_label(account_id, name)
439 # add address of the next account
440 _, _ = self.next_account_address(password)
443 def add_account(self, account_id, account):
444 self.accounts[account_id] = account
445 if account_id in self.pending_accounts:
446 self.pending_accounts.pop(account_id)
447 self.storage.put('pending_accounts', self.pending_accounts)
451 def save_accounts(self):
453 for k, v in self.accounts.items():
455 self.storage.put('accounts', d, True)
459 def load_accounts(self):
460 d = self.storage.get('accounts', {})
462 for k, v in d.items():
464 v['mpk'] = self.storage.get('master_public_key')
465 self.accounts[k] = OldAccount(v)
467 self.accounts[k] = BIP32_Account_2of3(v)
469 self.accounts[k] = BIP32_Account_2of2(v)
471 self.accounts[k] = BIP32_Account(v)
475 self.pending_accounts = self.storage.get('pending_accounts',{})
478 def delete_pending_account(self, k):
479 self.pending_accounts.pop(k)
480 self.storage.put('pending_accounts', self.pending_accounts)
482 def account_is_pending(self, k):
483 return k in self.pending_accounts
485 def create_pending_account(self, name, password):
486 account_id, addr = self.next_account_address(password)
487 self.set_label(account_id, name)
488 self.pending_accounts[account_id] = addr
489 self.storage.put('pending_accounts', self.pending_accounts)
491 def get_pending_accounts(self):
492 return self.pending_accounts.items()
495 def addresses(self, include_change = True, _next=True):
496 o = self.get_account_addresses(-1, include_change)
497 for a in self.accounts.keys():
498 o += self.get_account_addresses(a, include_change)
501 for addr in self.next_addresses.values():
507 def is_mine(self, address):
508 return address in self.addresses(True)
511 def is_change(self, address):
512 if not self.is_mine(address): return False
513 if address in self.imported_keys.keys(): return False
514 acct, s = self.get_address_index(address)
515 if s is None: return False
518 def get_master_public_key(self):
519 return self.master_public_keys["m/"]
521 def get_master_public_keys(self):
523 for k, account in self.accounts.items():
524 name = self.get_account_name(k)
525 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
529 def get_master_private_key(self, account, password):
530 k = self.master_private_keys.get(account)
532 xpriv = pw_decode( k, password)
536 def get_address_index(self, address):
537 if address in self.imported_keys.keys():
540 for account in self.accounts.keys():
541 for for_change in [0,1]:
542 addresses = self.accounts[account].get_addresses(for_change)
543 for addr in addresses:
545 return account, (for_change, addresses.index(addr))
547 for k,v in self.next_addresses.items():
551 raise Exception("Address not found", address)
554 def getpubkeys(self, addr):
555 assert is_valid(addr) and self.is_mine(addr)
556 account, sequence = self.get_address_index(addr)
558 a = self.accounts[account]
559 return a.get_pubkeys( sequence )
562 def get_roots(self, account):
564 for a in account.split('&'):
566 m = re.match("m/(\d+')", s)
567 roots.append( m.group(1) )
571 def is_seeded(self, account):
575 for root in self.get_roots(account):
576 if root not in self.master_private_keys.keys():
580 def rebase_sequence(self, account, sequence):
581 # account has one or more xpub
582 # sequence is a sequence of public derivations
585 for a in account.split('&'):
587 m = re.match("m/(\d+)'", s)
589 num = int(m.group(1))
590 dd.append( (root, [num,c,i] ) )
597 def get_seed(self, password):
598 s = pw_decode(self.seed, password)
599 seed = mnemonic_to_seed(s,'').encode('hex')
603 def get_mnemonic(self, password):
604 return pw_decode(self.seed, password)
607 def get_private_key(self, address, password):
608 if self.is_watching_only():
611 # first check the provided password
612 seed = self.get_seed(password)
615 if address in self.imported_keys.keys():
616 out.append( pw_decode( self.imported_keys[address], password ) )
618 account_id, sequence = self.get_address_index(address)
619 account = self.accounts[account_id]
620 xpubs = account.get_master_pubkeys()
621 roots = [k for k, v in self.master_public_keys.iteritems() if v in xpubs]
623 xpriv = self.get_master_private_key(root, password)
626 _, _, _, c, k = deserialize_xkey(xpriv)
627 pk = bip32_private_key( sequence, k, c )
633 def get_public_keys(self, address):
634 account_id, sequence = self.get_address_index(address)
635 return self.accounts[account_id].get_pubkeys(sequence)
638 def add_keypairs_from_wallet(self, tx, keypairs, password):
639 for txin in tx.inputs:
640 address = txin['address']
641 if not self.is_mine(address):
643 private_keys = self.get_private_key(address, password)
644 for sec in private_keys:
645 pubkey = public_key_from_private_key(sec)
646 keypairs[ pubkey ] = sec
647 if address in self.imported_keys.keys():
648 txin['redeemPubkey'] = pubkey
651 def add_keypairs_from_KeyID(self, tx, keypairs, password):
652 # first check the provided password
653 seed = self.get_seed(password)
655 for txin in tx.inputs:
656 keyid = txin.get('KeyID')
659 for s in keyid.split('&'):
660 m = re.match("bip32\((.*),(/\d+/\d+)\)", s)
663 sequence = m.group(2)
664 root = self.find_root_by_master_key(xpub)
665 if not root: continue
666 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
667 root = root + '%d'%sequence[0]
668 sequence = sequence[1:]
669 roots.append((root,sequence))
671 account_id = " & ".join( map(lambda x:x[0], roots) )
672 account = self.accounts.get(account_id)
673 if not account: continue
674 addr = account.get_address(*sequence)
675 txin['address'] = addr # fixme: side effect
676 pk = self.get_private_key(addr, password)
678 pubkey = public_key_from_private_key(sec)
679 keypairs[pubkey] = sec
683 def signrawtransaction(self, tx, input_info, private_keys, password):
685 # check that the password is correct
686 seed = self.get_seed(password)
688 # if input_info is not known, build it using wallet UTXOs
691 unspent_coins = self.get_unspent_coins()
692 for txin in tx.inputs:
693 for item in unspent_coins:
694 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
695 info = { 'address':item['address'], 'scriptPubKey':item['scriptPubKey'] }
696 self.add_input_info(info)
697 input_info.append(info)
700 print_error( "input not in UTXOs" )
701 input_info.append(None)
703 # add input_info to the transaction
704 print_error("input_info", input_info)
705 tx.add_input_info(input_info)
707 # build a list of public/private keys
710 # add private keys from parameter
711 for sec in private_keys:
712 pubkey = public_key_from_private_key(sec)
713 keypairs[ pubkey ] = sec
715 # add private_keys from KeyID
716 self.add_keypairs_from_KeyID(tx, keypairs, password)
717 # add private keys from wallet
718 self.add_keypairs_from_wallet(tx, keypairs, password)
719 # sign the transaction
720 self.sign_transaction(tx, keypairs, password)
723 def sign_message(self, address, message, password):
724 keys = self.get_private_key(address, password)
725 assert len(keys) == 1
727 key = regenerate_key(sec)
728 compressed = is_compressed(sec)
729 return key.sign_message(message, compressed, address)
733 def decrypt_message(self, pubkey, message, password):
734 address = public_key_to_bc_address(pubkey.decode('hex'))
735 keys = self.get_private_key(address, password)
737 ec = regenerate_key(secret)
738 decrypted = ec.decrypt_message(message)
742 def change_gap_limit(self, value):
743 if value >= self.gap_limit:
744 self.gap_limit = value
745 self.storage.put('gap_limit', self.gap_limit, True)
746 #self.interface.poke('synchronizer')
749 elif value >= self.min_acceptable_gap():
750 for key, account in self.accounts.items():
751 addresses = account[0]
752 k = self.num_unused_trailing_addresses(addresses)
753 n = len(addresses) - k + value
754 addresses = addresses[0:n]
755 self.accounts[key][0] = addresses
757 self.gap_limit = value
758 self.storage.put('gap_limit', self.gap_limit, True)
764 def num_unused_trailing_addresses(self, addresses):
766 for a in addresses[::-1]:
767 if self.history.get(a):break
771 def min_acceptable_gap(self):
772 # fixme: this assumes wallet is synchronized
776 for account in self.accounts.values():
777 addresses = account.get_addresses(0)
778 k = self.num_unused_trailing_addresses(addresses)
779 for a in addresses[0:-k]:
780 if self.history.get(a):
784 if n > nmax: nmax = n
788 def address_is_old(self, address):
790 h = self.history.get(address, [])
793 for tx_hash, tx_height in h:
797 tx_age = self.network.get_local_height() - tx_height + 1
803 def synchronize_sequence(self, account, for_change):
804 limit = self.gap_limit_for_change if for_change else self.gap_limit
807 addresses = account.get_addresses(for_change)
808 if len(addresses) < limit:
809 address = account.create_new_address(for_change)
810 self.history[address] = []
811 new_addresses.append( address )
814 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
817 address = account.create_new_address(for_change)
818 self.history[address] = []
819 new_addresses.append( address )
824 def check_pending_accounts(self):
825 for account_id, addr in self.next_addresses.items():
826 if self.address_is_old(addr):
827 print_error( "creating account", account_id )
828 xpub = self.master_public_keys[account_id]
829 account = BIP32_Account({'xpub':xpub})
830 self.add_account(account_id, account)
831 self.next_addresses.pop(account_id)
834 def synchronize_account(self, account):
836 new += self.synchronize_sequence(account, 0)
837 new += self.synchronize_sequence(account, 1)
841 def synchronize(self):
842 self.check_pending_accounts()
844 for account in self.accounts.values():
845 new += self.synchronize_account(account)
848 self.storage.put('addr_history', self.history, True)
853 return self.history.values() != [[]] * len(self.history)
856 def add_contact(self, address, label=None):
857 self.addressbook.append(address)
858 self.storage.put('contacts', self.addressbook, True)
860 self.set_label(address, label)
863 def delete_contact(self, addr):
864 if addr in self.addressbook:
865 self.addressbook.remove(addr)
866 self.storage.put('addressbook', self.addressbook, True)
869 def fill_addressbook(self):
870 for tx_hash, tx in self.transactions.items():
871 is_relevant, is_send, _, _ = self.get_tx_value(tx)
873 for addr, v in tx.outputs:
874 if not self.is_mine(addr) and addr not in self.addressbook:
875 self.addressbook.append(addr)
877 # self.update_tx_labels()
879 def get_num_tx(self, address):
881 for tx in self.transactions.values():
882 if address in map(lambda x:x[0], tx.outputs): n += 1
886 def get_address_flags(self, addr):
887 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
888 flags += "F" if addr in self.frozen_addresses else "-"
892 def get_tx_value(self, tx, account=None):
893 domain = self.get_account_addresses(account)
894 return tx.get_value(domain, self.prevout_values)
897 def update_tx_outputs(self, tx_hash):
898 tx = self.transactions.get(tx_hash)
900 for i, (addr, value) in enumerate(tx.outputs):
901 key = tx_hash+ ':%d'%i
902 self.prevout_values[key] = value
904 for item in tx.inputs:
905 if self.is_mine(item.get('address')):
906 key = item['prevout_hash'] + ':%d'%item['prevout_n']
907 self.spent_outputs.append(key)
910 def get_addr_balance(self, address):
911 assert self.is_mine(address)
912 h = self.history.get(address,[])
913 if h == ['*']: return 0,0
915 received_coins = [] # list of coins received at address
917 for tx_hash, tx_height in h:
918 tx = self.transactions.get(tx_hash)
921 for i, (addr, value) in enumerate(tx.outputs):
923 key = tx_hash + ':%d'%i
924 received_coins.append(key)
926 for tx_hash, tx_height in h:
927 tx = self.transactions.get(tx_hash)
931 for item in tx.inputs:
932 addr = item.get('address')
934 key = item['prevout_hash'] + ':%d'%item['prevout_n']
935 value = self.prevout_values.get( key )
936 if key in received_coins:
939 for i, (addr, value) in enumerate(tx.outputs):
940 key = tx_hash + ':%d'%i
951 def get_account_name(self, k):
952 default = "Unnamed account"
953 m = re.match("m/0'/(\d+)", k)
957 default = "Main account"
959 default = "Account %s"%num
961 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
964 default = "2of2 account %s"%num
965 name = self.labels.get(k, default)
969 def get_account_names(self):
971 for k, account in self.accounts.items():
972 accounts[k] = self.get_account_name(k)
973 if self.imported_keys:
974 accounts[-1] = 'Imported keys'
978 def get_account_addresses(self, a, include_change=True):
980 o = self.addresses(True)
982 o = self.imported_keys.keys()
984 ac = self.accounts[a]
985 o = ac.get_addresses(0)
986 if include_change: o += ac.get_addresses(1)
989 def get_imported_balance(self):
990 return self.get_balance(self.imported_keys.keys())
992 def get_account_balance(self, account):
993 return self.get_balance(self.get_account_addresses(account))
995 def get_frozen_balance(self):
996 return self.get_balance(self.frozen_addresses)
998 def get_balance(self, domain=None):
999 if domain is None: domain = self.addresses(True)
1002 c, u = self.get_addr_balance(addr)
1008 def get_unspent_coins(self, domain=None):
1010 if domain is None: domain = self.addresses(True)
1012 h = self.history.get(addr, [])
1013 if h == ['*']: continue
1014 for tx_hash, tx_height in h:
1015 tx = self.transactions.get(tx_hash)
1016 if tx is None: raise Exception("Wallet not synchronized")
1017 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1018 for o in tx.d.get('outputs'):
1020 if output.get('address') != addr: continue
1021 key = tx_hash + ":%d" % output.get('prevout_n')
1022 if key in self.spent_outputs: continue
1023 output['prevout_hash'] = tx_hash
1024 output['height'] = tx_height
1025 output['coinbase'] = is_coinbase
1026 coins.append((tx_height, output))
1030 coins = sorted(coins)
1031 if coins[-1][0] != 0:
1032 while coins[0][0] == 0:
1033 coins = coins[1:] + [ coins[0] ]
1034 return [x[1] for x in coins]
1037 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None ):
1038 """ todo: minimize tx size """
1040 fee = self.fee if fixed_fee is None else fixed_fee
1042 domain = self.addresses(True)
1044 for i in self.frozen_addresses:
1045 if i in domain: domain.remove(i)
1047 coins = self.get_unspent_coins(domain)
1051 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
1053 addr = item.get('address')
1054 v = item.get('value')
1057 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
1058 if total >= amount + fee: break
1062 return inputs, total, fee
1065 def set_fee(self, fee):
1068 self.storage.put('fee_per_kb', self.fee, True)
1070 def estimated_fee(self, inputs, num_outputs):
1071 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
1072 fee = self.fee * int(math.ceil(estimated_size/1000.))
1076 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1077 "add change to a transaction"
1078 change_amount = total - ( amount + fee )
1079 if change_amount > DUST_THRESHOLD:
1082 # send change to one of the accounts involved in the tx
1083 address = inputs[0].get('address')
1084 account, _ = self.get_address_index(address)
1086 if not self.use_change or account == -1:
1087 change_addr = inputs[-1]['address']
1089 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1091 # Insert the change output at a random position in the outputs
1092 posn = random.randint(0, len(outputs))
1093 outputs[posn:posn] = [( change_addr, change_amount)]
1097 def get_history(self, address):
1099 return self.history.get(address)
1102 def get_status(self, h):
1103 if not h: return None
1104 if h == ['*']: return '*'
1106 for tx_hash, height in h:
1107 status += tx_hash + ':%d:' % height
1108 return hashlib.sha256( status ).digest().encode('hex')
1111 def receive_tx_callback(self, tx_hash, tx, tx_height):
1113 with self.transaction_lock:
1114 self.add_extra_addresses(tx)
1115 if not self.check_new_tx(tx_hash, tx):
1116 # may happen due to pruning
1117 print_error("received transaction that is no longer referenced in history", tx_hash)
1119 self.transactions[tx_hash] = tx
1120 self.network.pending_transactions_for_notifications.append(tx)
1121 self.save_transactions()
1122 if self.verifier and tx_height>0:
1123 self.verifier.add(tx_hash, tx_height)
1124 self.update_tx_outputs(tx_hash)
1127 def save_transactions(self):
1129 for k,v in self.transactions.items():
1131 self.storage.put('transactions', tx, True)
1133 def receive_history_callback(self, addr, hist):
1135 if not self.check_new_history(addr, hist):
1136 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
1139 self.history[addr] = hist
1140 self.storage.put('addr_history', self.history, True)
1143 for tx_hash, tx_height in hist:
1145 # add it in case it was previously unconfirmed
1146 if self.verifier: self.verifier.add(tx_hash, tx_height)
1149 def get_tx_history(self, account=None):
1150 if not self.verifier:
1153 with self.transaction_lock:
1154 history = self.transactions.items()
1155 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1159 for tx_hash, tx in history:
1160 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1161 if v is not None: balance += v
1163 c, u = self.get_account_balance(account)
1166 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1168 balance = c + u - balance
1169 for tx_hash, tx in history:
1170 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1173 if value is not None:
1176 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1177 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1182 def get_label(self, tx_hash):
1183 label = self.labels.get(tx_hash)
1184 is_default = (label == '') or (label is None)
1185 if is_default: label = self.get_default_label(tx_hash)
1186 return label, is_default
1189 def get_default_label(self, tx_hash):
1190 tx = self.transactions.get(tx_hash)
1193 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1195 for o in tx.outputs:
1197 if not self.is_mine(o_addr):
1199 default_label = self.labels[o_addr]
1201 default_label = '>' + o_addr
1204 default_label = '(internal)'
1206 for o in tx.outputs:
1208 if self.is_mine(o_addr) and not self.is_change(o_addr):
1211 for o in tx.outputs:
1213 if self.is_mine(o_addr):
1219 dest_label = self.labels.get(o_addr)
1221 default_label = self.labels[o_addr]
1223 default_label = '<' + o_addr
1225 return default_label
1228 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1229 for address, x in outputs:
1230 assert is_valid(address), "Address " + address + " is invalid!"
1231 amount = sum( map(lambda x:x[1], outputs) )
1232 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain )
1234 raise ValueError("Not enough funds")
1236 self.add_input_info(txin)
1237 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1238 return Transaction.from_io(inputs, outputs)
1241 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1242 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1244 self.add_keypairs_from_wallet(tx, keypairs, password)
1246 self.sign_transaction(tx, keypairs, password)
1250 def add_input_info(self, txin):
1251 address = txin['address']
1252 if address in self.imported_keys.keys():
1254 account_id, sequence = self.get_address_index(address)
1255 account = self.accounts[account_id]
1256 txin['KeyID'] = account.get_keyID(sequence)
1257 redeemScript = account.redeem_script(sequence)
1259 txin['redeemScript'] = redeemScript
1261 txin['redeemPubkey'] = account.get_pubkey(*sequence)
1264 def sign_transaction(self, tx, keypairs, password):
1266 run_hook('sign_transaction', tx, password)
1269 def sendtx(self, tx):
1271 h = self.send_tx(tx)
1272 self.tx_event.wait()
1273 return self.receive_tx(h, tx)
1275 def send_tx(self, tx):
1277 self.tx_event.clear()
1278 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1281 def on_broadcast(self, i, r):
1282 self.tx_result = r.get('result')
1285 def receive_tx(self, tx_hash, tx):
1286 out = self.tx_result
1288 return False, "error: " + out
1289 run_hook('receive_tx', tx, self)
1294 def update_password(self, old_password, new_password):
1295 if new_password == '': new_password = None
1296 decoded = self.get_seed(old_password)
1297 self.seed = pw_encode( decoded, new_password)
1298 self.storage.put('seed', self.seed, True)
1299 self.use_encryption = (new_password != None)
1300 self.storage.put('use_encryption', self.use_encryption,True)
1301 for k in self.imported_keys.keys():
1302 a = self.imported_keys[k]
1303 b = pw_decode(a, old_password)
1304 c = pw_encode(b, new_password)
1305 self.imported_keys[k] = c
1306 self.storage.put('imported_keys', self.imported_keys, True)
1308 for k, v in self.master_private_keys.items():
1309 b = pw_decode(v, old_password)
1310 c = pw_encode(b, new_password)
1311 self.master_private_keys[k] = c
1312 self.storage.put('master_private_keys', self.master_private_keys, True)
1315 def freeze(self,addr):
1316 if self.is_mine(addr) and addr not in self.frozen_addresses:
1317 self.frozen_addresses.append(addr)
1318 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1323 def unfreeze(self,addr):
1324 if self.is_mine(addr) and addr in self.frozen_addresses:
1325 self.frozen_addresses.remove(addr)
1326 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1332 def set_verifier(self, verifier):
1333 self.verifier = verifier
1335 # review transactions that are in the history
1336 for addr, hist in self.history.items():
1337 if hist == ['*']: continue
1338 for tx_hash, tx_height in hist:
1340 # add it in case it was previously unconfirmed
1341 self.verifier.add(tx_hash, tx_height)
1344 # if we are on a pruning server, remove unverified transactions
1345 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1346 for tx_hash in self.transactions.keys():
1347 if tx_hash not in vr:
1348 self.transactions.pop(tx_hash)
1352 def check_new_history(self, addr, hist):
1354 # check that all tx in hist are relevant
1356 for tx_hash, height in hist:
1357 tx = self.transactions.get(tx_hash)
1359 if not tx.has_address(addr):
1362 # check that we are not "orphaning" a transaction
1363 old_hist = self.history.get(addr,[])
1364 if old_hist == ['*']: return True
1366 for tx_hash, height in old_hist:
1367 if tx_hash in map(lambda x:x[0], hist): continue
1369 for _addr, _hist in self.history.items():
1370 if _addr == addr: continue
1371 if _hist == ['*']: continue
1372 _tx_hist = map(lambda x:x[0], _hist)
1373 if tx_hash in _tx_hist:
1378 tx = self.transactions.get(tx_hash)
1379 # tx might not be there
1383 if self.verifier.get_height(tx_hash):
1386 print_error("new history is orphaning transaction:", tx_hash)
1387 # check that all outputs are not mine, request histories
1389 for _addr, _v in tx.outputs:
1390 # assert not self.is_mine(_addr)
1391 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1393 ext_h = self.network.synchronous_get(ext_requests)
1394 print_error("sync:", ext_requests, ext_h)
1397 if h == ['*']: continue
1399 if item.get('tx_hash') == tx_hash:
1400 height = item.get('height')
1402 print_error("found height for", tx_hash, height)
1403 self.verifier.add(tx_hash, height)
1405 print_error("removing orphaned tx from history", tx_hash)
1406 self.transactions.pop(tx_hash)
1412 def check_new_tx(self, tx_hash, tx):
1413 # 1 check that tx is referenced in addr_history.
1415 for addr, hist in self.history.items():
1416 if hist == ['*']:continue
1417 for txh, height in hist:
1419 addresses.append(addr)
1424 # 2 check that referencing addresses are in the tx
1425 for addr in addresses:
1426 if not tx.has_address(addr):
1432 def start_threads(self, network):
1433 from verifier import TxVerifier
1434 self.network = network
1435 if self.network is not None:
1436 self.verifier = TxVerifier(self.network, self.storage)
1437 self.verifier.start()
1438 self.set_verifier(self.verifier)
1439 self.synchronizer = WalletSynchronizer(self, network)
1440 self.synchronizer.start()
1442 self.verifier = None
1443 self.synchronizer =None
1445 def stop_threads(self):
1447 self.verifier.stop()
1448 self.synchronizer.stop()
1451 def restore(self, callback):
1453 def wait_for_wallet():
1454 self.set_up_to_date(False)
1455 while not self.is_up_to_date():
1456 msg = "%s\n%s %d\n%s %.1f"%(
1457 _("Please wait..."),
1458 _("Addresses generated:"),
1459 len(self.addresses(True)),
1460 _("Kilobytes received:"),
1461 self.network.interface.bytes_received/1024.)
1463 apply(callback, (msg,))
1466 def wait_for_network():
1467 while not self.network.is_connected():
1468 msg = "%s \n" % (_("Connecting..."))
1469 apply(callback, (msg,))
1472 # wait until we are connected, because the user might have selected another server
1479 self.fill_addressbook()
1483 class Wallet_2of2(NewWallet):
1485 def __init__(self, storage):
1486 NewWallet.__init__(self, storage)
1487 self.storage.put('wallet_type', '2of2', True)
1489 def can_create_accounts(self):
1492 def create_account(self):
1493 xpub1 = self.master_public_keys.get("m/")
1494 xpub2 = self.master_public_keys.get("cold/")
1495 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1496 self.add_account('m/', account)
1498 def get_master_public_keys(self):
1499 xpub1 = self.master_public_keys.get("m/")
1500 xpub2 = self.master_public_keys.get("cold/")
1501 return {'hot':xpub1, 'cold':xpub2}
1503 def get_action(self):
1504 xpub1 = self.master_public_keys.get("m/")
1505 xpub2 = self.master_public_keys.get("cold/")
1507 return 'create_2of2_1'
1509 return 'create_2of2_2'
1513 class Wallet_2of3(Wallet_2of2):
1515 def __init__(self, storage):
1516 NewWallet.__init__(self, storage)
1517 self.storage.put('wallet_type', '2of3', True)
1519 def create_account(self):
1520 xpub1 = self.master_public_keys.get("m/")
1521 xpub2 = self.master_public_keys.get("cold/")
1522 xpub3 = self.master_public_keys.get("remote/")
1523 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1524 self.add_account('m/', account)
1526 def get_master_public_keys(self):
1527 xpub1 = self.master_public_keys.get("m/")
1528 xpub2 = self.master_public_keys.get("cold/")
1529 xpub3 = self.master_public_keys.get("remote/")
1530 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1532 def get_action(self):
1533 xpub1 = self.master_public_keys.get("m/")
1534 xpub2 = self.master_public_keys.get("cold/")
1535 xpub3 = self.master_public_keys.get("remote/")
1537 return 'create_2of3_1'
1539 return 'create_2of3_2'
1541 return 'create_2of3_3'
1544 class WalletSynchronizer(threading.Thread):
1547 def __init__(self, wallet, network):
1548 threading.Thread.__init__(self)
1550 self.wallet = wallet
1551 self.network = network
1552 self.was_updated = True
1553 self.running = False
1554 self.lock = threading.Lock()
1555 self.queue = Queue.Queue()
1558 with self.lock: self.running = False
1560 def is_running(self):
1561 with self.lock: return self.running
1564 def subscribe_to_addresses(self, addresses):
1566 for addr in addresses:
1567 messages.append(('blockchain.address.subscribe', [addr]))
1568 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1575 while self.is_running():
1577 if not self.network.is_connected():
1578 self.network.wait_until_connected()
1580 self.run_interface()
1583 def run_interface(self):
1585 print_error("synchronizer: connected to", self.network.main_server())
1589 requested_histories = {}
1591 # request any missing transactions
1592 for history in self.wallet.history.values():
1593 if history == ['*']: continue
1594 for tx_hash, tx_height in history:
1595 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1596 missing_tx.append( (tx_hash, tx_height) )
1599 print_error("missing tx", missing_tx)
1602 self.subscribe_to_addresses(self.wallet.addresses(True))
1604 while self.is_running():
1605 # 1. create new addresses
1606 new_addresses = self.wallet.synchronize()
1608 # request missing addresses
1610 self.subscribe_to_addresses(new_addresses)
1612 # request missing transactions
1613 for tx_hash, tx_height in missing_tx:
1614 if (tx_hash, tx_height) not in requested_tx:
1615 self.network.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1616 requested_tx.append( (tx_hash, tx_height) )
1619 # detect if situation has changed
1620 if self.network.is_up_to_date() and self.queue.empty():
1621 if not self.wallet.is_up_to_date():
1622 self.wallet.set_up_to_date(True)
1623 self.was_updated = True
1625 if self.wallet.is_up_to_date():
1626 self.wallet.set_up_to_date(False)
1627 self.was_updated = True
1629 if self.was_updated:
1630 self.network.trigger_callback('updated')
1631 self.was_updated = False
1635 r = self.queue.get(block=True, timeout=1)
1640 #if interface != self.network.interface:
1646 # 3. handle response
1647 method = r['method']
1648 params = r['params']
1649 result = r.get('result')
1650 error = r.get('error')
1655 if method == 'blockchain.address.subscribe':
1657 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1658 if requested_histories.get(addr) is None:
1659 self.network.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1660 requested_histories[addr] = result
1662 elif method == 'blockchain.address.get_history':
1664 print_error("receiving history", addr, result)
1666 assert requested_histories.pop(addr) == '*'
1667 self.wallet.receive_history_callback(addr, result)
1670 # check that txids are unique
1673 tx_hash = item['tx_hash']
1674 if tx_hash not in txids:
1675 txids.append(tx_hash)
1676 hist.append( (tx_hash, item['height']) )
1678 if len(hist) != len(result):
1679 raise Exception("error: server sent history with non-unique txid", result)
1681 # check that the status corresponds to what was announced
1682 rs = requested_histories.pop(addr)
1683 if self.wallet.get_status(hist) != rs:
1684 raise Exception("error: status mismatch: %s"%addr)
1686 # store received history
1687 self.wallet.receive_history_callback(addr, hist)
1689 # request transactions that we don't have
1690 for tx_hash, tx_height in hist:
1691 if self.wallet.transactions.get(tx_hash) is None:
1692 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1693 missing_tx.append( (tx_hash, tx_height) )
1695 elif method == 'blockchain.transaction.get':
1697 tx_height = params[1]
1698 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1699 tx = Transaction(result)
1700 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1701 self.was_updated = True
1702 requested_tx.remove( (tx_hash, tx_height) )
1703 print_error("received tx:", tx_hash, len(tx.raw))
1706 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1708 if self.was_updated and not requested_tx:
1709 self.network.trigger_callback('updated')
1710 # Updated gets called too many times from other places as well; if we use that signal we get the notification three times
1711 self.network.trigger_callback("new_transaction")
1712 self.was_updated = False
1717 class OldWallet(NewWallet):
1719 def can_create_accounts(self):
1722 def make_seed(self):
1724 seed = random_seed(128)
1725 return ' '.join(mnemonic.mn_encode(seed))
1727 def prepare_seed(self, seed):
1729 # see if seed was entered as hex
1734 return OLD_SEED_VERSION, str(seed)
1738 words = seed.split()
1739 seed = mnemonic.mn_decode(words)
1741 raise Exception("Invalid seed")
1743 return OLD_SEED_VERSION, seed
1746 def create_master_keys(self, password):
1747 seed = pw_decode(self.seed, password)
1748 mpk = OldAccount.mpk_from_seed(seed)
1749 self.storage.put('master_public_key', mpk, True)
1751 def get_master_public_key(self):
1752 return self.storage.get("master_public_key")
1754 def get_master_public_keys(self):
1755 return {'Main Account':self.get_master_public_key()}
1757 def create_accounts(self, password):
1758 mpk = self.storage.get("master_public_key")
1759 self.create_account(mpk)
1761 def create_account(self, mpk):
1762 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1763 self.save_accounts()
1765 def create_watching_only_wallet(self, mpk):
1766 self.seed_version = OLD_SEED_VERSION
1767 self.storage.put('seed_version', self.seed_version, True)
1768 self.storage.put('master_public_key', mpk, True)
1769 self.create_account(mpk)
1771 def get_seed(self, password):
1772 seed = pw_decode(self.seed, password)
1773 self.accounts[0].check_seed(seed)
1776 def get_mnemonic(self, password):
1778 s = pw_decode(self.seed, password)
1779 return ' '.join(mnemonic.mn_encode(s))
1782 def add_keypairs_from_KeyID(self, tx, keypairs, password):
1783 # first check the provided password
1784 seed = self.get_seed(password)
1785 for txin in tx.inputs:
1786 keyid = txin.get('KeyID')
1788 m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
1791 if mpk != self.storage.get('master_public_key'): continue
1792 for_change = int(m.group(2))
1793 num = int(m.group(3))
1794 account = self.accounts[0]
1795 addr = account.get_address(for_change, num)
1796 txin['address'] = addr # fixme: side effect
1797 pk = account.get_private_key(seed, (for_change, num))
1798 pubkey = public_key_from_private_key(pk)
1799 keypairs[pubkey] = pk
1802 def get_account_name(self, k):
1804 return 'Main account'
1806 def is_seeded(self, account):
1807 return self.seed is not None
1809 def get_private_key(self, address, password):
1810 if self.is_watching_only():
1813 # first check the provided password
1814 seed = self.get_seed(password)
1817 if address in self.imported_keys.keys():
1818 out.append( pw_decode( self.imported_keys[address], password ) )
1820 account_id, sequence = self.get_address_index(address)
1821 pk = self.accounts[0].get_private_key(seed, sequence)
1825 def check_pending_accounts(self):
1829 # former WalletFactory
1830 class Wallet(object):
1832 def __new__(self, storage):
1833 config = storage.config
1834 if config.get('bitkey', False):
1835 # if user requested support for Bitkey device,
1836 # import Bitkey driver
1837 from wallet_bitkey import WalletBitkey
1838 return WalletBitkey(config)
1840 if storage.get('wallet_type') == '2of2':
1841 return Wallet_2of2(storage)
1843 if storage.get('wallet_type') == '2of3':
1844 return Wallet_2of3(storage)
1847 if not storage.file_exists:
1848 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1850 seed_version = storage.get('seed_version')
1851 if not seed_version:
1852 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1854 if seed_version == OLD_SEED_VERSION:
1855 return OldWallet(storage)
1856 elif seed_version == NEW_SEED_VERSION:
1857 return NewWallet(storage)
1859 msg = "This wallet seed is not supported."
1860 if seed_version in [5]:
1861 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1868 def is_seed(self, seed):
1871 elif is_old_seed(seed):
1873 elif is_new_seed(seed):
1879 def is_mpk(self, mpk):
1887 return len(mpk) == 128
1890 deserialize_xkey(mpk)
1897 def from_seed(self, seed, storage):
1898 if is_old_seed(seed):
1900 elif is_new_seed(seed):
1906 def from_mpk(self, mpk, storage):
1915 w = OldWallet(storage)
1917 w.create_watching_only_wallet(mpk)
1919 w = NewWallet(storage)
1920 w.create_watching_only_wallet(mpk)