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',20000))
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})
243 def set_up_to_date(self,b):
244 with self.lock: self.up_to_date = b
247 def is_up_to_date(self):
248 with self.lock: return self.up_to_date
252 self.up_to_date = False
253 while not self.is_up_to_date():
257 def import_key(self, sec, password):
259 seed = self.get_seed(password)
261 address = address_from_private_key(sec)
263 raise Exception('Invalid private key')
265 if self.is_mine(address):
266 raise Exception('Address already in wallet')
268 # store the originally requested keypair into the imported keys table
269 self.imported_keys[address] = pw_encode(sec, password )
270 self.storage.put('imported_keys', self.imported_keys, True)
271 if self.synchronizer:
272 self.synchronizer.subscribe_to_addresses([address])
275 def delete_imported_key(self, addr):
276 if addr in self.imported_keys:
277 self.imported_keys.pop(addr)
278 self.storage.put('imported_keys', self.imported_keys, True)
282 import mnemonic, ecdsa
283 entropy = ecdsa.util.randrange( pow(2,160) )
286 ss = "%040x"%(entropy+nonce)
287 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
288 # we keep only 13 words, that's approximately 139 bits of entropy
289 words = mnemonic.mn_encode(s)[0:13]
290 seed = ' '.join(words)
291 if is_new_seed(seed):
292 break # this will remove 8 bits of entropy
298 def init_seed(self, seed):
299 import mnemonic, unicodedata
302 raise Exception("a seed exists")
304 self.seed_version = NEW_SEED_VERSION
307 self.seed = self.make_seed()
310 self.seed = unicodedata.normalize('NFC', unicode(seed.strip()))
314 def save_seed(self, password):
316 self.seed = pw_encode( self.seed, password)
317 self.use_encryption = True
318 self.storage.put('seed', self.seed, True)
319 self.storage.put('seed_version', self.seed_version, True)
320 self.storage.put('use_encryption', self.use_encryption,True)
321 self.create_accounts(password)
324 def create_watching_only_wallet(self, xpub):
325 self.master_public_keys = { "m/": xpub }
326 self.storage.put('master_public_keys', self.master_public_keys, True)
327 self.storage.put('seed_version', self.seed_version, True)
328 account = BIP32_Account({'xpub':xpub})
329 self.add_account("m/", account)
332 def create_accounts(self, password):
333 seed = pw_decode(self.seed, password)
334 # create default account
335 self.create_master_keys(password)
336 self.create_account('Main account', password)
339 def create_master_keys(self, password):
340 xpriv, xpub = bip32_root(self.get_seed(password))
341 self.master_public_keys["m/"] = xpub
342 self.master_private_keys["m/"] = pw_encode(xpriv, password)
343 self.storage.put('master_public_keys', self.master_public_keys, True)
344 self.storage.put('master_private_keys', self.master_private_keys, True)
347 def find_root_by_master_key(self, xpub):
348 for key, xpub2 in self.master_public_keys.items():
349 if key == "m/":continue
353 def is_watching_only(self):
354 return (self.seed == '') and (self.master_private_keys == {})
357 def num_accounts(self, account_type = '1of1'):
358 keys = self.accounts.keys()
361 account_id = self.account_id(account_type, i)
362 if account_id not in keys: break
367 def next_account_address(self, account_type, password):
368 i = self.num_accounts(account_type)
369 account_id = self.account_id(account_type, i)
371 addr = self.next_addresses.get(account_id)
373 account = self.make_account(account_id, password)
374 addr = account.first_address()
375 self.next_addresses[account_id] = addr
376 self.storage.put('next_addresses', self.next_addresses)
378 return account_id, addr
380 def account_id(self, account_type, i):
381 if account_type == '1of1':
386 def make_account(self, account_id, password):
387 """Creates and saves the master keys, but does not save the account"""
388 master_xpriv = pw_decode( self.master_private_keys["m/"] , password )
389 xpriv, xpub = bip32_private_derivation(master_xpriv, "m/", account_id)
390 self.master_private_keys[account_id] = pw_encode(xpriv, password)
391 self.master_public_keys[account_id] = xpub
392 self.storage.put('master_public_keys', self.master_public_keys, True)
393 self.storage.put('master_private_keys', self.master_private_keys, True)
394 account = BIP32_Account({'xpub':xpub})
398 def set_label(self, name, text = None):
400 old_text = self.labels.get(name)
403 self.labels[name] = text
407 self.labels.pop(name)
411 self.storage.put('labels', self.labels, True)
413 run_hook('set_label', name, text, changed)
417 def create_account(self, name, password):
418 i = self.num_accounts('1of1')
419 account_id = self.account_id('1of1', i)
420 account = self.make_account(account_id, password)
421 self.add_account(account_id, account)
423 self.set_label(account_id, name)
425 # add address of the next account
426 _, _ = self.next_account_address('1of1', password)
429 def add_account(self, account_id, account):
430 self.accounts[account_id] = account
431 if account_id in self.pending_accounts:
432 self.pending_accounts.pop(account_id)
433 self.storage.put('pending_accounts', self.pending_accounts)
437 def save_accounts(self):
439 for k, v in self.accounts.items():
441 self.storage.put('accounts', d, True)
445 def load_accounts(self):
446 d = self.storage.get('accounts', {})
448 for k, v in d.items():
450 v['mpk'] = self.storage.get('master_public_key')
451 self.accounts[k] = OldAccount(v)
453 self.accounts[k] = BIP32_Account_2of3(v)
455 self.accounts[k] = BIP32_Account_2of2(v)
457 self.accounts[k] = BIP32_Account(v)
461 self.pending_accounts = self.storage.get('pending_accounts',{})
464 def delete_pending_account(self, k):
465 self.pending_accounts.pop(k)
466 self.storage.put('pending_accounts', self.pending_accounts)
468 def account_is_pending(self, k):
469 return k in self.pending_accounts
471 def create_pending_account(self, acct_type, name, password):
472 account_id, addr = self.next_account_address(acct_type, password)
473 self.set_label(account_id, name)
474 self.pending_accounts[account_id] = addr
475 self.storage.put('pending_accounts', self.pending_accounts)
477 def get_pending_accounts(self):
478 return self.pending_accounts.items()
481 def addresses(self, include_change = True, _next=True):
482 o = self.get_account_addresses(-1, include_change)
483 for a in self.accounts.keys():
484 o += self.get_account_addresses(a, include_change)
487 for addr in self.next_addresses.values():
493 def is_mine(self, address):
494 return address in self.addresses(True)
497 def is_change(self, address):
498 if not self.is_mine(address): return False
499 if address in self.imported_keys.keys(): return False
500 acct, s = self.get_address_index(address)
501 if s is None: return False
504 def get_master_public_key(self):
505 return self.storage.get("master_public_keys")["m/"]
507 def get_master_private_key(self, account, password):
508 k = self.master_private_keys.get(account)
510 xpriv = pw_decode( k, password)
514 def get_address_index(self, address):
515 if address in self.imported_keys.keys():
518 for account in self.accounts.keys():
519 for for_change in [0,1]:
520 addresses = self.accounts[account].get_addresses(for_change)
521 for addr in addresses:
523 return account, (for_change, addresses.index(addr))
525 for k,v in self.next_addresses.items():
529 raise Exception("Address not found", address)
532 def getpubkeys(self, addr):
533 assert is_valid(addr) and self.is_mine(addr)
534 account, sequence = self.get_address_index(addr)
536 a = self.accounts[account]
537 return a.get_pubkeys( sequence )
540 def get_roots(self, account):
542 for a in account.split('&'):
544 m = re.match("m/(\d+')", s)
545 roots.append( m.group(1) )
549 def is_seeded(self, account):
553 for root in self.get_roots(account):
554 if root not in self.master_private_keys.keys():
558 def rebase_sequence(self, account, sequence):
559 # account has one or more xpub
560 # sequence is a sequence of public derivations
563 for a in account.split('&'):
565 m = re.match("m/(\d+)'", s)
567 num = int(m.group(1))
568 dd.append( (root, [num,c,i] ) )
575 def get_seed(self, password):
576 s = pw_decode(self.seed, password)
577 seed = mnemonic_to_seed(s,'').encode('hex')
581 def get_mnemonic(self, password):
582 return pw_decode(self.seed, password)
585 def get_private_key(self, address, password):
586 if self.is_watching_only():
589 # first check the provided password
590 seed = self.get_seed(password)
593 if address in self.imported_keys.keys():
594 out.append( pw_decode( self.imported_keys[address], password ) )
596 account_id, sequence = self.get_address_index(address)
597 account = self.accounts[account_id]
598 xpubs = account.get_master_pubkeys()
599 roots = [k for k, v in self.master_public_keys.iteritems() if v in xpubs]
601 xpriv = self.get_master_private_key(root, password)
604 _, _, _, c, k = deserialize_xkey(xpriv)
605 pk = bip32_private_key( sequence, k, c )
611 def get_public_keys(self, address):
612 account_id, sequence = self.get_address_index(address)
613 return self.accounts[account_id].get_pubkeys(sequence)
616 def add_keypairs_from_wallet(self, tx, keypairs, password):
617 for txin in tx.inputs:
618 address = txin['address']
619 if not self.is_mine(address):
621 private_keys = self.get_private_key(address, password)
622 for sec in private_keys:
623 pubkey = public_key_from_private_key(sec)
624 keypairs[ pubkey ] = sec
625 if address in self.imported_keys.keys():
626 txin['redeemPubkey'] = pubkey
629 def add_keypairs_from_KeyID(self, tx, keypairs, password):
630 # first check the provided password
631 seed = self.get_seed(password)
633 for txin in tx.inputs:
634 keyid = txin.get('KeyID')
637 for s in keyid.split('&'):
638 m = re.match("bip32\((.*),(/\d+/\d+)\)", s)
641 sequence = m.group(2)
642 root = self.find_root_by_master_key(xpub)
643 if not root: continue
644 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
645 root = root + '%d'%sequence[0]
646 sequence = sequence[1:]
647 roots.append((root,sequence))
649 account_id = " & ".join( map(lambda x:x[0], roots) )
650 account = self.accounts.get(account_id)
651 if not account: continue
652 addr = account.get_address(*sequence)
653 txin['address'] = addr # fixme: side effect
654 pk = self.get_private_key(addr, password)
656 pubkey = public_key_from_private_key(sec)
657 keypairs[pubkey] = sec
661 def signrawtransaction(self, tx, input_info, private_keys, password):
663 # check that the password is correct
664 seed = self.get_seed(password)
667 tx.add_input_info(input_info)
669 # add redeem script for coins that are in the wallet
670 # FIXME: add redeemPubkey too!
673 unspent_coins = self.get_unspent_coins()
675 # an exception may be raised is the wallet is not synchronized
678 for txin in tx.inputs:
679 for item in unspent_coins:
680 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
681 print_error( "tx input is in unspent coins" )
682 txin['scriptPubKey'] = item['scriptPubKey']
683 account, sequence = self.get_address_index(item['address'])
685 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
686 print_error("added redeemScript", txin['redeemScript'])
690 # build a list of public/private keys
693 # add private keys from parameter
694 for sec in private_keys:
695 pubkey = public_key_from_private_key(sec)
696 keypairs[ pubkey ] = sec
698 # add private_keys from KeyID
699 self.add_keypairs_from_KeyID(tx, keypairs, password)
701 # add private keys from wallet
702 self.add_keypairs_from_wallet(tx, keypairs, password)
703 self.sign_transaction(tx, keypairs, password)
706 def sign_message(self, address, message, password):
707 keys = self.get_private_key(address, password)
708 assert len(keys) == 1
710 key = regenerate_key(sec)
711 compressed = is_compressed(sec)
712 return key.sign_message(message, compressed, address)
716 def decrypt_message(self, pubkey, message, password):
717 address = public_key_to_bc_address(pubkey.decode('hex'))
718 keys = self.get_private_key(address, password)
720 ec = regenerate_key(secret)
721 decrypted = ec.decrypt_message(message)
725 def change_gap_limit(self, value):
726 if value >= self.gap_limit:
727 self.gap_limit = value
728 self.storage.put('gap_limit', self.gap_limit, True)
729 #self.interface.poke('synchronizer')
732 elif value >= self.min_acceptable_gap():
733 for key, account in self.accounts.items():
734 addresses = account[0]
735 k = self.num_unused_trailing_addresses(addresses)
736 n = len(addresses) - k + value
737 addresses = addresses[0:n]
738 self.accounts[key][0] = addresses
740 self.gap_limit = value
741 self.storage.put('gap_limit', self.gap_limit, True)
747 def num_unused_trailing_addresses(self, addresses):
749 for a in addresses[::-1]:
750 if self.history.get(a):break
754 def min_acceptable_gap(self):
755 # fixme: this assumes wallet is synchronized
759 for account in self.accounts.values():
760 addresses = account.get_addresses(0)
761 k = self.num_unused_trailing_addresses(addresses)
762 for a in addresses[0:-k]:
763 if self.history.get(a):
767 if n > nmax: nmax = n
771 def address_is_old(self, address):
773 h = self.history.get(address, [])
776 for tx_hash, tx_height in h:
780 tx_age = self.network.get_local_height() - tx_height + 1
786 def synchronize_sequence(self, account, for_change):
787 limit = self.gap_limit_for_change if for_change else self.gap_limit
790 addresses = account.get_addresses(for_change)
791 if len(addresses) < limit:
792 address = account.create_new_address(for_change)
793 self.history[address] = []
794 new_addresses.append( address )
797 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
800 address = account.create_new_address(for_change)
801 self.history[address] = []
802 new_addresses.append( address )
807 def check_pending_accounts(self):
808 for account_id, addr in self.next_addresses.items():
809 if self.address_is_old(addr):
810 print_error( "creating account", account_id )
811 xpub = self.master_public_keys[account_id]
812 account = BIP32_Account({'xpub':xpub})
813 self.add_account(account_id, account)
814 self.next_addresses.pop(account_id)
817 def synchronize_account(self, account):
819 new += self.synchronize_sequence(account, 0)
820 new += self.synchronize_sequence(account, 1)
824 def synchronize(self):
825 self.check_pending_accounts()
827 for account in self.accounts.values():
828 new += self.synchronize_account(account)
831 self.storage.put('addr_history', self.history, True)
836 return self.history.values() != [[]] * len(self.history)
839 def add_contact(self, address, label=None):
840 self.addressbook.append(address)
841 self.storage.put('contacts', self.addressbook, True)
843 self.set_label(address, label)
846 def delete_contact(self, addr):
847 if addr in self.addressbook:
848 self.addressbook.remove(addr)
849 self.storage.put('addressbook', self.addressbook, True)
852 def fill_addressbook(self):
853 for tx_hash, tx in self.transactions.items():
854 is_relevant, is_send, _, _ = self.get_tx_value(tx)
856 for addr, v in tx.outputs:
857 if not self.is_mine(addr) and addr not in self.addressbook:
858 self.addressbook.append(addr)
860 # self.update_tx_labels()
862 def get_num_tx(self, address):
864 for tx in self.transactions.values():
865 if address in map(lambda x:x[0], tx.outputs): n += 1
869 def get_address_flags(self, addr):
870 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
871 flags += "F" if addr in self.frozen_addresses else "-"
875 def get_tx_value(self, tx, account=None):
876 domain = self.get_account_addresses(account)
877 return tx.get_value(domain, self.prevout_values)
880 def update_tx_outputs(self, tx_hash):
881 tx = self.transactions.get(tx_hash)
883 for i, (addr, value) in enumerate(tx.outputs):
884 key = tx_hash+ ':%d'%i
885 self.prevout_values[key] = value
887 for item in tx.inputs:
888 if self.is_mine(item.get('address')):
889 key = item['prevout_hash'] + ':%d'%item['prevout_n']
890 self.spent_outputs.append(key)
893 def get_addr_balance(self, address):
894 assert self.is_mine(address)
895 h = self.history.get(address,[])
896 if h == ['*']: return 0,0
898 received_coins = [] # list of coins received at address
900 for tx_hash, tx_height in h:
901 tx = self.transactions.get(tx_hash)
904 for i, (addr, value) in enumerate(tx.outputs):
906 key = tx_hash + ':%d'%i
907 received_coins.append(key)
909 for tx_hash, tx_height in h:
910 tx = self.transactions.get(tx_hash)
914 for item in tx.inputs:
915 addr = item.get('address')
917 key = item['prevout_hash'] + ':%d'%item['prevout_n']
918 value = self.prevout_values.get( key )
919 if key in received_coins:
922 for i, (addr, value) in enumerate(tx.outputs):
923 key = tx_hash + ':%d'%i
934 def get_account_name(self, k):
935 default = "Unnamed account"
936 m = re.match("m/0'/(\d+)", k)
940 default = "Main account"
942 default = "Account %s"%num
944 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
947 default = "2of2 account %s"%num
948 name = self.labels.get(k, default)
952 def get_account_names(self):
954 for k, account in self.accounts.items():
955 accounts[k] = self.get_account_name(k)
956 if self.imported_keys:
957 accounts[-1] = 'Imported keys'
961 def get_account_addresses(self, a, include_change=True):
963 o = self.addresses(True)
965 o = self.imported_keys.keys()
967 ac = self.accounts[a]
968 o = ac.get_addresses(0)
969 if include_change: o += ac.get_addresses(1)
972 def get_imported_balance(self):
973 return self.get_balance(self.imported_keys.keys())
975 def get_account_balance(self, account):
976 return self.get_balance(self.get_account_addresses(account))
978 def get_frozen_balance(self):
979 return self.get_balance(self.frozen_addresses)
981 def get_balance(self, domain=None):
982 if domain is None: domain = self.addresses(True)
985 c, u = self.get_addr_balance(addr)
991 def get_unspent_coins(self, domain=None):
993 if domain is None: domain = self.addresses(True)
995 h = self.history.get(addr, [])
996 if h == ['*']: continue
997 for tx_hash, tx_height in h:
998 tx = self.transactions.get(tx_hash)
999 if tx is None: raise Exception("Wallet not synchronized")
1000 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1001 for o in tx.d.get('outputs'):
1003 if output.get('address') != addr: continue
1004 key = tx_hash + ":%d" % output.get('prevout_n')
1005 if key in self.spent_outputs: continue
1006 output['prevout_hash'] = tx_hash
1007 output['height'] = tx_height
1008 output['coinbase'] = is_coinbase
1009 coins.append((tx_height, output))
1013 coins = sorted(coins)
1014 if coins[-1][0] != 0:
1015 while coins[0][0] == 0:
1016 coins = coins[1:] + [ coins[0] ]
1017 return [x[1] for x in coins]
1020 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None ):
1021 """ todo: minimize tx size """
1023 fee = self.fee if fixed_fee is None else fixed_fee
1025 domain = self.addresses(True)
1027 for i in self.frozen_addresses:
1028 if i in domain: domain.remove(i)
1030 coins = self.get_unspent_coins(domain)
1034 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
1036 addr = item.get('address')
1037 v = item.get('value')
1040 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
1041 if total >= amount + fee: break
1045 return inputs, total, fee
1048 def set_fee(self, fee):
1051 self.storage.put('fee_per_kb', self.fee, True)
1053 def estimated_fee(self, inputs, num_outputs):
1054 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
1055 fee = self.fee * int(math.ceil(estimated_size/1000.))
1059 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1060 "add change to a transaction"
1061 change_amount = total - ( amount + fee )
1062 if change_amount > DUST_THRESHOLD:
1065 # send change to one of the accounts involved in the tx
1066 address = inputs[0].get('address')
1067 account, _ = self.get_address_index(address)
1069 if not self.use_change or account == -1:
1070 change_addr = inputs[-1]['address']
1072 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1074 # Insert the change output at a random position in the outputs
1075 posn = random.randint(0, len(outputs))
1076 outputs[posn:posn] = [( change_addr, change_amount)]
1080 def get_history(self, address):
1082 return self.history.get(address)
1085 def get_status(self, h):
1086 if not h: return None
1087 if h == ['*']: return '*'
1089 for tx_hash, height in h:
1090 status += tx_hash + ':%d:' % height
1091 return hashlib.sha256( status ).digest().encode('hex')
1094 def receive_tx_callback(self, tx_hash, tx, tx_height):
1096 with self.transaction_lock:
1097 self.add_extra_addresses(tx)
1098 if not self.check_new_tx(tx_hash, tx):
1099 # may happen due to pruning
1100 print_error("received transaction that is no longer referenced in history", tx_hash)
1102 self.transactions[tx_hash] = tx
1103 self.network.interface.pending_transactions_for_notifications.append(tx)
1104 self.save_transactions()
1105 if self.verifier and tx_height>0:
1106 self.verifier.add(tx_hash, tx_height)
1107 self.update_tx_outputs(tx_hash)
1110 def save_transactions(self):
1112 for k,v in self.transactions.items():
1114 self.storage.put('transactions', tx, True)
1116 def receive_history_callback(self, addr, hist):
1118 if not self.check_new_history(addr, hist):
1119 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
1122 self.history[addr] = hist
1123 self.storage.put('addr_history', self.history, True)
1126 for tx_hash, tx_height in hist:
1128 # add it in case it was previously unconfirmed
1129 if self.verifier: self.verifier.add(tx_hash, tx_height)
1132 def get_tx_history(self, account=None):
1133 if not self.verifier:
1136 with self.transaction_lock:
1137 history = self.transactions.items()
1138 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1142 for tx_hash, tx in history:
1143 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1144 if v is not None: balance += v
1146 c, u = self.get_account_balance(account)
1149 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1151 balance = c + u - balance
1152 for tx_hash, tx in history:
1153 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1156 if value is not None:
1159 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1160 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1165 def get_label(self, tx_hash):
1166 label = self.labels.get(tx_hash)
1167 is_default = (label == '') or (label is None)
1168 if is_default: label = self.get_default_label(tx_hash)
1169 return label, is_default
1172 def get_default_label(self, tx_hash):
1173 tx = self.transactions.get(tx_hash)
1176 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1178 for o in tx.outputs:
1180 if not self.is_mine(o_addr):
1182 default_label = self.labels[o_addr]
1184 default_label = '>' + o_addr
1187 default_label = '(internal)'
1189 for o in tx.outputs:
1191 if self.is_mine(o_addr) and not self.is_change(o_addr):
1194 for o in tx.outputs:
1196 if self.is_mine(o_addr):
1202 dest_label = self.labels.get(o_addr)
1204 default_label = self.labels[o_addr]
1206 default_label = '<' + o_addr
1208 return default_label
1211 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1212 for address, x in outputs:
1213 assert is_valid(address), "Address " + address + " is invalid!"
1214 amount = sum( map(lambda x:x[1], outputs) )
1215 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain )
1217 raise ValueError("Not enough funds")
1218 self.add_input_info(inputs)
1219 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1220 return Transaction.from_io(inputs, outputs)
1223 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1224 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1226 self.add_keypairs_from_wallet(tx, keypairs, password)
1228 self.sign_transaction(tx, keypairs, password)
1232 def add_input_info(self, inputs):
1234 address = txin['address']
1235 if address in self.imported_keys.keys():
1237 account_id, sequence = self.get_address_index(address)
1238 account = self.accounts[account_id]
1239 txin['KeyID'] = account.get_keyID(sequence)
1240 redeemScript = account.redeem_script(sequence)
1242 txin['redeemScript'] = redeemScript
1244 txin['redeemPubkey'] = account.get_pubkey(*sequence)
1247 def sign_transaction(self, tx, keypairs, password):
1249 run_hook('sign_transaction', tx, password)
1252 def sendtx(self, tx):
1254 h = self.send_tx(tx)
1255 self.tx_event.wait()
1256 return self.receive_tx(h, tx)
1258 def send_tx(self, tx):
1260 self.tx_event.clear()
1261 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1264 def on_broadcast(self, i, r):
1265 self.tx_result = r.get('result')
1268 def receive_tx(self, tx_hash, tx):
1269 out = self.tx_result
1271 return False, "error: " + out
1272 run_hook('receive_tx', tx, self)
1277 def update_password(self, old_password, new_password):
1278 if new_password == '': new_password = None
1279 decoded = self.get_seed(old_password)
1280 self.seed = pw_encode( decoded, new_password)
1281 self.storage.put('seed', self.seed, True)
1282 self.use_encryption = (new_password != None)
1283 self.storage.put('use_encryption', self.use_encryption,True)
1284 for k in self.imported_keys.keys():
1285 a = self.imported_keys[k]
1286 b = pw_decode(a, old_password)
1287 c = pw_encode(b, new_password)
1288 self.imported_keys[k] = c
1289 self.storage.put('imported_keys', self.imported_keys, True)
1291 for k, v in self.master_private_keys.items():
1292 b = pw_decode(v, old_password)
1293 c = pw_encode(b, new_password)
1294 self.master_private_keys[k] = c
1295 self.storage.put('master_private_keys', self.master_private_keys, True)
1298 def freeze(self,addr):
1299 if self.is_mine(addr) and addr not in self.frozen_addresses:
1300 self.frozen_addresses.append(addr)
1301 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1306 def unfreeze(self,addr):
1307 if self.is_mine(addr) and addr in self.frozen_addresses:
1308 self.frozen_addresses.remove(addr)
1309 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1315 def set_verifier(self, verifier):
1316 self.verifier = verifier
1318 # review transactions that are in the history
1319 for addr, hist in self.history.items():
1320 if hist == ['*']: continue
1321 for tx_hash, tx_height in hist:
1323 # add it in case it was previously unconfirmed
1324 self.verifier.add(tx_hash, tx_height)
1327 # if we are on a pruning server, remove unverified transactions
1328 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1329 for tx_hash in self.transactions.keys():
1330 if tx_hash not in vr:
1331 self.transactions.pop(tx_hash)
1335 def check_new_history(self, addr, hist):
1337 # check that all tx in hist are relevant
1339 for tx_hash, height in hist:
1340 tx = self.transactions.get(tx_hash)
1342 if not tx.has_address(addr):
1345 # check that we are not "orphaning" a transaction
1346 old_hist = self.history.get(addr,[])
1347 if old_hist == ['*']: return True
1349 for tx_hash, height in old_hist:
1350 if tx_hash in map(lambda x:x[0], hist): continue
1352 for _addr, _hist in self.history.items():
1353 if _addr == addr: continue
1354 if _hist == ['*']: continue
1355 _tx_hist = map(lambda x:x[0], _hist)
1356 if tx_hash in _tx_hist:
1361 tx = self.transactions.get(tx_hash)
1362 # tx might not be there
1366 if self.verifier.get_height(tx_hash):
1369 print_error("new history is orphaning transaction:", tx_hash)
1370 # check that all outputs are not mine, request histories
1372 for _addr, _v in tx.outputs:
1373 # assert not self.is_mine(_addr)
1374 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1376 ext_h = self.network.synchronous_get(ext_requests)
1377 print_error("sync:", ext_requests, ext_h)
1380 if h == ['*']: continue
1382 if item.get('tx_hash') == tx_hash:
1383 height = item.get('height')
1385 print_error("found height for", tx_hash, height)
1386 self.verifier.add(tx_hash, height)
1388 print_error("removing orphaned tx from history", tx_hash)
1389 self.transactions.pop(tx_hash)
1395 def check_new_tx(self, tx_hash, tx):
1396 # 1 check that tx is referenced in addr_history.
1398 for addr, hist in self.history.items():
1399 if hist == ['*']:continue
1400 for txh, height in hist:
1402 addresses.append(addr)
1407 # 2 check that referencing addresses are in the tx
1408 for addr in addresses:
1409 if not tx.has_address(addr):
1415 def start_threads(self, network):
1416 from verifier import TxVerifier
1417 self.network = network
1418 if self.network is not None:
1419 self.verifier = TxVerifier(self.network, self.storage)
1420 self.verifier.start()
1421 self.set_verifier(self.verifier)
1422 self.synchronizer = WalletSynchronizer(self, network)
1423 self.synchronizer.start()
1425 self.verifier = None
1426 self.synchronizer =None
1428 def stop_threads(self):
1430 self.verifier.stop()
1431 self.synchronizer.stop()
1434 def restore(self, callback):
1436 def wait_for_wallet():
1437 self.set_up_to_date(False)
1438 while not self.is_up_to_date():
1439 msg = "%s\n%s %d\n%s %.1f"%(
1440 _("Please wait..."),
1441 _("Addresses generated:"),
1442 len(self.addresses(True)),
1443 _("Kilobytes received:"),
1444 self.network.interface.bytes_received/1024.)
1446 apply(callback, (msg,))
1449 def wait_for_network():
1450 while not self.network.is_connected():
1451 msg = "%s \n" % (_("Connecting..."))
1452 apply(callback, (msg,))
1455 # wait until we are connected, because the user might have selected another server
1462 self.fill_addressbook()
1467 class WalletSynchronizer(threading.Thread):
1470 def __init__(self, wallet, network):
1471 threading.Thread.__init__(self)
1473 self.wallet = wallet
1474 self.network = network
1475 self.was_updated = True
1476 self.running = False
1477 self.lock = threading.Lock()
1478 self.queue = Queue.Queue()
1481 with self.lock: self.running = False
1483 def is_running(self):
1484 with self.lock: return self.running
1487 def subscribe_to_addresses(self, addresses):
1489 for addr in addresses:
1490 messages.append(('blockchain.address.subscribe', [addr]))
1491 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1498 while self.is_running():
1500 if not self.network.is_connected():
1501 self.network.wait_until_connected()
1503 self.run_interface()
1506 def run_interface(self):
1508 print_error("synchronizer: connected to", self.network.main_server())
1512 requested_histories = {}
1514 # request any missing transactions
1515 for history in self.wallet.history.values():
1516 if history == ['*']: continue
1517 for tx_hash, tx_height in history:
1518 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1519 missing_tx.append( (tx_hash, tx_height) )
1522 print_error("missing tx", missing_tx)
1525 self.subscribe_to_addresses(self.wallet.addresses(True))
1527 while self.is_running():
1528 # 1. create new addresses
1529 new_addresses = self.wallet.synchronize()
1531 # request missing addresses
1533 self.subscribe_to_addresses(new_addresses)
1535 # request missing transactions
1536 for tx_hash, tx_height in missing_tx:
1537 if (tx_hash, tx_height) not in requested_tx:
1538 self.network.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1539 requested_tx.append( (tx_hash, tx_height) )
1542 # detect if situation has changed
1543 if self.network.is_up_to_date() and self.queue.empty():
1544 if not self.wallet.is_up_to_date():
1545 self.wallet.set_up_to_date(True)
1546 self.was_updated = True
1548 if self.wallet.is_up_to_date():
1549 self.wallet.set_up_to_date(False)
1550 self.was_updated = True
1552 if self.was_updated:
1553 self.network.trigger_callback('updated')
1554 self.was_updated = False
1558 r = self.queue.get(block=True, timeout=1)
1563 #if interface != self.network.interface:
1569 # 3. handle response
1570 method = r['method']
1571 params = r['params']
1572 result = r.get('result')
1573 error = r.get('error')
1578 if method == 'blockchain.address.subscribe':
1580 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1581 if requested_histories.get(addr) is None:
1582 self.network.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1583 requested_histories[addr] = result
1585 elif method == 'blockchain.address.get_history':
1587 print_error("receiving history", addr, result)
1589 assert requested_histories.pop(addr) == '*'
1590 self.wallet.receive_history_callback(addr, result)
1593 # check that txids are unique
1596 tx_hash = item['tx_hash']
1597 if tx_hash not in txids:
1598 txids.append(tx_hash)
1599 hist.append( (tx_hash, item['height']) )
1601 if len(hist) != len(result):
1602 raise Exception("error: server sent history with non-unique txid", result)
1604 # check that the status corresponds to what was announced
1605 rs = requested_histories.pop(addr)
1606 if self.wallet.get_status(hist) != rs:
1607 raise Exception("error: status mismatch: %s"%addr)
1609 # store received history
1610 self.wallet.receive_history_callback(addr, hist)
1612 # request transactions that we don't have
1613 for tx_hash, tx_height in hist:
1614 if self.wallet.transactions.get(tx_hash) is None:
1615 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1616 missing_tx.append( (tx_hash, tx_height) )
1618 elif method == 'blockchain.transaction.get':
1620 tx_height = params[1]
1621 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1622 tx = Transaction(result)
1623 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1624 self.was_updated = True
1625 requested_tx.remove( (tx_hash, tx_height) )
1626 print_error("received tx:", tx_hash, len(tx.raw))
1629 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1631 if self.was_updated and not requested_tx:
1632 self.network.trigger_callback('updated')
1633 # Updated gets called too many times from other places as well; if we use that signal we get the notification three times
1634 self.network.trigger_callback("new_transaction")
1635 self.was_updated = False
1640 class OldWallet(NewWallet):
1642 def init_seed(self, seed):
1646 raise Exception("a seed exists")
1649 seed = random_seed(128)
1651 self.seed_version = OLD_SEED_VERSION
1653 # see if seed was entered as hex
1658 self.seed = str(seed)
1663 words = seed.split()
1665 mnemonic.mn_decode(words)
1669 self.seed = mnemonic.mn_decode(words)
1672 raise Exception("Invalid seed")
1676 def get_master_public_key(self):
1677 return self.storage.get("master_public_key")
1679 def create_accounts(self, password):
1680 seed = pw_decode(self.seed, password)
1681 mpk = OldAccount.mpk_from_seed(seed)
1682 self.create_account(mpk)
1684 def create_account(self, mpk):
1685 self.storage.put('master_public_key', mpk, True)
1686 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1687 self.save_accounts()
1689 def create_watching_only_wallet(self, mpk):
1690 self.seed_version = OLD_SEED_VERSION
1691 self.storage.put('seed_version', self.seed_version, True)
1692 self.create_account(mpk)
1694 def get_seed(self, password):
1695 seed = pw_decode(self.seed, password)
1696 self.accounts[0].check_seed(seed)
1699 def get_mnemonic(self, password):
1701 s = pw_decode(self.seed, password)
1702 return ' '.join(mnemonic.mn_encode(s))
1705 def add_keypairs_from_KeyID(self, tx, keypairs, password):
1706 # first check the provided password
1707 seed = self.get_seed(password)
1708 for txin in tx.inputs:
1709 keyid = txin.get('KeyID')
1711 m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
1714 if mpk != self.storage.get('master_public_key'): continue
1715 for_change = int(m.group(2))
1716 num = int(m.group(3))
1717 account = self.accounts[0]
1718 addr = account.get_address(for_change, num)
1719 txin['address'] = addr # fixme: side effect
1720 pk = account.get_private_key(seed, (for_change, num))
1721 pubkey = public_key_from_private_key(pk)
1722 keypairs[pubkey] = pk
1725 def get_account_name(self, k):
1727 return 'Main account'
1729 def is_seeded(self, account):
1730 return self.seed is not None
1732 def get_private_key(self, address, password):
1733 if self.is_watching_only():
1736 # first check the provided password
1737 seed = self.get_seed(password)
1740 if address in self.imported_keys.keys():
1741 out.append( pw_decode( self.imported_keys[address], password ) )
1743 account_id, sequence = self.get_address_index(address)
1744 pk = self.accounts[0].get_private_key(seed, sequence)
1748 def check_pending_accounts(self):
1752 # former WalletFactory
1753 class Wallet(object):
1755 def __new__(self, storage):
1756 config = storage.config
1757 if config.get('bitkey', False):
1758 # if user requested support for Bitkey device,
1759 # import Bitkey driver
1760 from wallet_bitkey import WalletBitkey
1761 return WalletBitkey(config)
1763 if not storage.file_exists:
1764 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1766 seed_version = storage.get('seed_version')
1767 if not seed_version:
1768 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1770 if seed_version == OLD_SEED_VERSION:
1771 return OldWallet(storage)
1772 elif seed_version == NEW_SEED_VERSION:
1773 return NewWallet(storage)
1775 msg = "This wallet seed is not supported."
1776 if seed_version in [5]:
1777 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1784 def is_seed(self, seed):
1787 elif is_old_seed(seed):
1789 elif is_new_seed(seed):
1795 def from_seed(self, seed, storage):
1796 klass = self.is_seed(seed)
1802 def from_mpk(self, mpk, storage):
1811 w = OldWallet(storage)
1813 w.create_watching_only_wallet(mpk)
1815 w = NewWallet(storage)
1816 w.create_watching_only_wallet(mpk)