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)
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] ) )
573 def get_keyID(self, account, sequence):
574 rs = self.rebase_sequence(account, sequence)
576 for root, public_sequence in rs:
577 xpub = self.master_public_keys[root]
578 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
579 dd.append( 'bip32(%s,%s)'%(xpub, s) )
583 def get_seed(self, password):
584 s = pw_decode(self.seed, password)
585 seed = mnemonic_to_seed(s,'').encode('hex')
589 def get_mnemonic(self, password):
590 return pw_decode(self.seed, password)
593 def get_private_key(self, address, password):
594 if self.is_watching_only():
597 # first check the provided password
598 seed = self.get_seed(password)
601 if address in self.imported_keys.keys():
602 out.append( pw_decode( self.imported_keys[address], password ) )
604 account_id, sequence = self.get_address_index(address)
605 #rs = self.rebase_sequence( account, sequence)
606 rs = [(account_id, sequence)]
607 for root, public_sequence in rs:
608 xpriv = self.get_master_private_key(root, password)
609 if not xpriv: continue
610 _, _, _, c, k = deserialize_xkey(xpriv)
611 pk = bip32_private_key( public_sequence, k, c )
617 def add_keypairs_from_wallet(self, tx, keypairs, password):
618 for txin in tx.inputs:
619 address = txin['address']
620 if not self.is_mine(address):
622 private_keys = self.get_private_key(address, password)
623 for sec in private_keys:
624 pubkey = public_key_from_private_key(sec)
625 keypairs[ pubkey ] = sec
626 if address in self.imported_keys.keys():
627 txin['redeemPubkey'] = pubkey
630 def add_keypairs_from_KeyID(self, tx, keypairs, password):
631 # first check the provided password
632 seed = self.get_seed(password)
634 for txin in tx.inputs:
635 keyid = txin.get('KeyID')
638 for s in keyid.split('&'):
639 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
643 sequence = m.group(3)
644 root = self.find_root_by_master_key(c,K)
645 if not root: continue
646 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
647 root = root + '%d'%sequence[0]
648 sequence = sequence[1:]
649 roots.append((root,sequence))
651 account_id = " & ".join( map(lambda x:x[0], roots) )
652 account = self.accounts.get(account_id)
653 if not account: continue
654 addr = account.get_address(*sequence)
655 txin['address'] = addr # fixme: side effect
656 pk = self.get_private_key(addr, password)
658 pubkey = public_key_from_private_key(sec)
659 keypairs[pubkey] = sec
663 def signrawtransaction(self, tx, input_info, private_keys, password):
665 # check that the password is correct
666 seed = self.get_seed(password)
669 tx.add_input_info(input_info)
671 # add redeem script for coins that are in the wallet
672 # FIXME: add redeemPubkey too!
675 unspent_coins = self.get_unspent_coins()
677 # an exception may be raised is the wallet is not synchronized
680 for txin in tx.inputs:
681 for item in unspent_coins:
682 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
683 print_error( "tx input is in unspent coins" )
684 txin['scriptPubKey'] = item['scriptPubKey']
685 account, sequence = self.get_address_index(item['address'])
687 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
688 print_error("added redeemScript", txin['redeemScript'])
692 # build a list of public/private keys
695 # add private keys from parameter
696 for sec in private_keys:
697 pubkey = public_key_from_private_key(sec)
698 keypairs[ pubkey ] = sec
700 # add private_keys from KeyID
701 self.add_keypairs_from_KeyID(tx, keypairs, password)
703 # add private keys from wallet
704 self.add_keypairs_from_wallet(tx, keypairs, password)
705 self.sign_transaction(tx, keypairs, password)
708 def sign_message(self, address, message, password):
709 keys = self.get_private_key(address, password)
710 assert len(keys) == 1
712 key = regenerate_key(sec)
713 compressed = is_compressed(sec)
714 return key.sign_message(message, compressed, address)
718 def decrypt_message(self, pubkey, message, password):
719 address = public_key_to_bc_address(pubkey.decode('hex'))
720 keys = self.get_private_key(address, password)
722 ec = regenerate_key(secret)
723 decrypted = ec.decrypt_message(message)
727 def change_gap_limit(self, value):
728 if value >= self.gap_limit:
729 self.gap_limit = value
730 self.storage.put('gap_limit', self.gap_limit, True)
731 #self.interface.poke('synchronizer')
734 elif value >= self.min_acceptable_gap():
735 for key, account in self.accounts.items():
736 addresses = account[0]
737 k = self.num_unused_trailing_addresses(addresses)
738 n = len(addresses) - k + value
739 addresses = addresses[0:n]
740 self.accounts[key][0] = addresses
742 self.gap_limit = value
743 self.storage.put('gap_limit', self.gap_limit, True)
749 def num_unused_trailing_addresses(self, addresses):
751 for a in addresses[::-1]:
752 if self.history.get(a):break
756 def min_acceptable_gap(self):
757 # fixme: this assumes wallet is synchronized
761 for account in self.accounts.values():
762 addresses = account.get_addresses(0)
763 k = self.num_unused_trailing_addresses(addresses)
764 for a in addresses[0:-k]:
765 if self.history.get(a):
769 if n > nmax: nmax = n
773 def address_is_old(self, address):
775 h = self.history.get(address, [])
778 for tx_hash, tx_height in h:
782 tx_age = self.network.get_local_height() - tx_height + 1
788 def synchronize_sequence(self, account, for_change):
789 limit = self.gap_limit_for_change if for_change else self.gap_limit
792 addresses = account.get_addresses(for_change)
793 if len(addresses) < limit:
794 address = account.create_new_address(for_change)
795 self.history[address] = []
796 new_addresses.append( address )
799 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
802 address = account.create_new_address(for_change)
803 self.history[address] = []
804 new_addresses.append( address )
809 def check_pending_accounts(self):
810 for account_id, addr in self.next_addresses.items():
811 if self.address_is_old(addr):
812 print_error( "creating account", account_id )
813 xpub = self.master_public_keys[account_id]
814 account = BIP32_Account({'xpub':xpub})
815 self.add_account(account_id, account)
816 self.next_addresses.pop(account_id)
819 def synchronize_account(self, account):
821 new += self.synchronize_sequence(account, 0)
822 new += self.synchronize_sequence(account, 1)
826 def synchronize(self):
827 self.check_pending_accounts()
829 for account in self.accounts.values():
830 new += self.synchronize_account(account)
833 self.storage.put('addr_history', self.history, True)
838 return self.history.values() != [[]] * len(self.history)
841 def add_contact(self, address, label=None):
842 self.addressbook.append(address)
843 self.storage.put('contacts', self.addressbook, True)
845 self.set_label(address, label)
848 def delete_contact(self, addr):
849 if addr in self.addressbook:
850 self.addressbook.remove(addr)
851 self.storage.put('addressbook', self.addressbook, True)
854 def fill_addressbook(self):
855 for tx_hash, tx in self.transactions.items():
856 is_relevant, is_send, _, _ = self.get_tx_value(tx)
858 for addr, v in tx.outputs:
859 if not self.is_mine(addr) and addr not in self.addressbook:
860 self.addressbook.append(addr)
862 # self.update_tx_labels()
864 def get_num_tx(self, address):
866 for tx in self.transactions.values():
867 if address in map(lambda x:x[0], tx.outputs): n += 1
871 def get_address_flags(self, addr):
872 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
873 flags += "F" if addr in self.frozen_addresses else "-"
877 def get_tx_value(self, tx, account=None):
878 domain = self.get_account_addresses(account)
879 return tx.get_value(domain, self.prevout_values)
882 def update_tx_outputs(self, tx_hash):
883 tx = self.transactions.get(tx_hash)
885 for i, (addr, value) in enumerate(tx.outputs):
886 key = tx_hash+ ':%d'%i
887 self.prevout_values[key] = value
889 for item in tx.inputs:
890 if self.is_mine(item.get('address')):
891 key = item['prevout_hash'] + ':%d'%item['prevout_n']
892 self.spent_outputs.append(key)
895 def get_addr_balance(self, address):
896 assert self.is_mine(address)
897 h = self.history.get(address,[])
898 if h == ['*']: return 0,0
900 received_coins = [] # list of coins received at address
902 for tx_hash, tx_height in h:
903 tx = self.transactions.get(tx_hash)
906 for i, (addr, value) in enumerate(tx.outputs):
908 key = tx_hash + ':%d'%i
909 received_coins.append(key)
911 for tx_hash, tx_height in h:
912 tx = self.transactions.get(tx_hash)
916 for item in tx.inputs:
917 addr = item.get('address')
919 key = item['prevout_hash'] + ':%d'%item['prevout_n']
920 value = self.prevout_values.get( key )
921 if key in received_coins:
924 for i, (addr, value) in enumerate(tx.outputs):
925 key = tx_hash + ':%d'%i
936 def get_account_name(self, k):
937 default = "Unnamed account"
938 m = re.match("m/0'/(\d+)", k)
942 default = "Main account"
944 default = "Account %s"%num
946 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
949 default = "2of2 account %s"%num
950 name = self.labels.get(k, default)
954 def get_account_names(self):
956 for k, account in self.accounts.items():
957 accounts[k] = self.get_account_name(k)
958 if self.imported_keys:
959 accounts[-1] = 'Imported keys'
963 def get_account_addresses(self, a, include_change=True):
965 o = self.addresses(True)
967 o = self.imported_keys.keys()
969 ac = self.accounts[a]
970 o = ac.get_addresses(0)
971 if include_change: o += ac.get_addresses(1)
974 def get_imported_balance(self):
975 return self.get_balance(self.imported_keys.keys())
977 def get_account_balance(self, account):
978 return self.get_balance(self.get_account_addresses(account))
980 def get_frozen_balance(self):
981 return self.get_balance(self.frozen_addresses)
983 def get_balance(self, domain=None):
984 if domain is None: domain = self.addresses(True)
987 c, u = self.get_addr_balance(addr)
993 def get_unspent_coins(self, domain=None):
995 if domain is None: domain = self.addresses(True)
997 h = self.history.get(addr, [])
998 if h == ['*']: continue
999 for tx_hash, tx_height in h:
1000 tx = self.transactions.get(tx_hash)
1001 if tx is None: raise Exception("Wallet not synchronized")
1002 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1003 for o in tx.d.get('outputs'):
1005 if output.get('address') != addr: continue
1006 key = tx_hash + ":%d" % output.get('prevout_n')
1007 if key in self.spent_outputs: continue
1008 output['prevout_hash'] = tx_hash
1009 output['height'] = tx_height
1010 output['coinbase'] = is_coinbase
1011 coins.append((tx_height, output))
1015 coins = sorted(coins)
1016 if coins[-1][0] != 0:
1017 while coins[0][0] == 0:
1018 coins = coins[1:] + [ coins[0] ]
1019 return [x[1] for x in coins]
1022 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None ):
1023 """ todo: minimize tx size """
1025 fee = self.fee if fixed_fee is None else fixed_fee
1027 domain = self.addresses(True)
1029 for i in self.frozen_addresses:
1030 if i in domain: domain.remove(i)
1032 coins = self.get_unspent_coins(domain)
1036 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
1038 addr = item.get('address')
1039 v = item.get('value')
1042 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
1043 if total >= amount + fee: break
1047 return inputs, total, fee
1050 def set_fee(self, fee):
1053 self.storage.put('fee_per_kb', self.fee, True)
1055 def estimated_fee(self, inputs, num_outputs):
1056 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
1057 fee = self.fee * int(math.ceil(estimated_size/1000.))
1061 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1062 "add change to a transaction"
1063 change_amount = total - ( amount + fee )
1064 if change_amount > DUST_THRESHOLD:
1067 # send change to one of the accounts involved in the tx
1068 address = inputs[0].get('address')
1069 account, _ = self.get_address_index(address)
1071 if not self.use_change or account == -1:
1072 change_addr = inputs[-1]['address']
1074 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1076 # Insert the change output at a random position in the outputs
1077 posn = random.randint(0, len(outputs))
1078 outputs[posn:posn] = [( change_addr, change_amount)]
1082 def get_history(self, address):
1084 return self.history.get(address)
1087 def get_status(self, h):
1088 if not h: return None
1089 if h == ['*']: return '*'
1091 for tx_hash, height in h:
1092 status += tx_hash + ':%d:' % height
1093 return hashlib.sha256( status ).digest().encode('hex')
1096 def receive_tx_callback(self, tx_hash, tx, tx_height):
1098 with self.transaction_lock:
1099 self.add_extra_addresses(tx)
1100 if not self.check_new_tx(tx_hash, tx):
1101 # may happen due to pruning
1102 print_error("received transaction that is no longer referenced in history", tx_hash)
1104 self.transactions[tx_hash] = tx
1105 self.network.interface.pending_transactions_for_notifications.append(tx)
1106 self.save_transactions()
1107 if self.verifier and tx_height>0:
1108 self.verifier.add(tx_hash, tx_height)
1109 self.update_tx_outputs(tx_hash)
1112 def save_transactions(self):
1114 for k,v in self.transactions.items():
1116 self.storage.put('transactions', tx, True)
1118 def receive_history_callback(self, addr, hist):
1120 if not self.check_new_history(addr, hist):
1121 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
1124 self.history[addr] = hist
1125 self.storage.put('addr_history', self.history, True)
1128 for tx_hash, tx_height in hist:
1130 # add it in case it was previously unconfirmed
1131 if self.verifier: self.verifier.add(tx_hash, tx_height)
1134 def get_tx_history(self, account=None):
1135 if not self.verifier:
1138 with self.transaction_lock:
1139 history = self.transactions.items()
1140 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1144 for tx_hash, tx in history:
1145 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1146 if v is not None: balance += v
1148 c, u = self.get_account_balance(account)
1151 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1153 balance = c + u - balance
1154 for tx_hash, tx in history:
1155 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1158 if value is not None:
1161 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1162 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1167 def get_label(self, tx_hash):
1168 label = self.labels.get(tx_hash)
1169 is_default = (label == '') or (label is None)
1170 if is_default: label = self.get_default_label(tx_hash)
1171 return label, is_default
1174 def get_default_label(self, tx_hash):
1175 tx = self.transactions.get(tx_hash)
1178 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1180 for o in tx.outputs:
1182 if not self.is_mine(o_addr):
1184 default_label = self.labels[o_addr]
1186 default_label = '>' + o_addr
1189 default_label = '(internal)'
1191 for o in tx.outputs:
1193 if self.is_mine(o_addr) and not self.is_change(o_addr):
1196 for o in tx.outputs:
1198 if self.is_mine(o_addr):
1204 dest_label = self.labels.get(o_addr)
1206 default_label = self.labels[o_addr]
1208 default_label = '<' + o_addr
1210 return default_label
1213 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1214 for address, x in outputs:
1215 assert is_valid(address), "Address " + address + " is invalid!"
1216 amount = sum( map(lambda x:x[1], outputs) )
1217 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain )
1219 raise ValueError("Not enough funds")
1220 self.add_input_info(inputs)
1221 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1222 return Transaction.from_io(inputs, outputs)
1225 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1226 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1228 self.add_keypairs_from_wallet(tx, keypairs, password)
1230 self.sign_transaction(tx, keypairs, password)
1234 def add_input_info(self, inputs):
1236 address = txin['address']
1237 if address in self.imported_keys.keys():
1239 account, sequence = self.get_address_index(address)
1240 txin['KeyID'] = self.get_keyID(account, sequence)
1241 redeemScript = self.accounts[account].redeem_script(sequence)
1243 txin['redeemScript'] = redeemScript
1245 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1248 def sign_transaction(self, tx, keypairs, password):
1250 run_hook('sign_transaction', tx, password)
1253 def sendtx(self, tx):
1255 h = self.send_tx(tx)
1256 self.tx_event.wait()
1257 return self.receive_tx(h, tx)
1259 def send_tx(self, tx):
1261 self.tx_event.clear()
1262 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1265 def on_broadcast(self, i, r):
1266 self.tx_result = r.get('result')
1269 def receive_tx(self, tx_hash, tx):
1270 out = self.tx_result
1272 return False, "error: " + out
1273 run_hook('receive_tx', tx, self)
1278 def update_password(self, old_password, new_password):
1279 if new_password == '': new_password = None
1280 decoded = self.get_seed(old_password)
1281 self.seed = pw_encode( decoded, new_password)
1282 self.storage.put('seed', self.seed, True)
1283 self.use_encryption = (new_password != None)
1284 self.storage.put('use_encryption', self.use_encryption,True)
1285 for k in self.imported_keys.keys():
1286 a = self.imported_keys[k]
1287 b = pw_decode(a, old_password)
1288 c = pw_encode(b, new_password)
1289 self.imported_keys[k] = c
1290 self.storage.put('imported_keys', self.imported_keys, True)
1292 for k, v in self.master_private_keys.items():
1293 b = pw_decode(v, old_password)
1294 c = pw_encode(b, new_password)
1295 self.master_private_keys[k] = c
1296 self.storage.put('master_private_keys', self.master_private_keys, True)
1299 def freeze(self,addr):
1300 if self.is_mine(addr) and addr not in self.frozen_addresses:
1301 self.frozen_addresses.append(addr)
1302 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1307 def unfreeze(self,addr):
1308 if self.is_mine(addr) and addr in self.frozen_addresses:
1309 self.frozen_addresses.remove(addr)
1310 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1316 def set_verifier(self, verifier):
1317 self.verifier = verifier
1319 # review transactions that are in the history
1320 for addr, hist in self.history.items():
1321 if hist == ['*']: continue
1322 for tx_hash, tx_height in hist:
1324 # add it in case it was previously unconfirmed
1325 self.verifier.add(tx_hash, tx_height)
1328 # if we are on a pruning server, remove unverified transactions
1329 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1330 for tx_hash in self.transactions.keys():
1331 if tx_hash not in vr:
1332 self.transactions.pop(tx_hash)
1336 def check_new_history(self, addr, hist):
1338 # check that all tx in hist are relevant
1340 for tx_hash, height in hist:
1341 tx = self.transactions.get(tx_hash)
1343 if not tx.has_address(addr):
1346 # check that we are not "orphaning" a transaction
1347 old_hist = self.history.get(addr,[])
1348 if old_hist == ['*']: return True
1350 for tx_hash, height in old_hist:
1351 if tx_hash in map(lambda x:x[0], hist): continue
1353 for _addr, _hist in self.history.items():
1354 if _addr == addr: continue
1355 if _hist == ['*']: continue
1356 _tx_hist = map(lambda x:x[0], _hist)
1357 if tx_hash in _tx_hist:
1362 tx = self.transactions.get(tx_hash)
1363 # tx might not be there
1367 if self.verifier.get_height(tx_hash):
1370 print_error("new history is orphaning transaction:", tx_hash)
1371 # check that all outputs are not mine, request histories
1373 for _addr, _v in tx.outputs:
1374 # assert not self.is_mine(_addr)
1375 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1377 ext_h = self.network.synchronous_get(ext_requests)
1378 print_error("sync:", ext_requests, ext_h)
1381 if h == ['*']: continue
1383 if item.get('tx_hash') == tx_hash:
1384 height = item.get('height')
1386 print_error("found height for", tx_hash, height)
1387 self.verifier.add(tx_hash, height)
1389 print_error("removing orphaned tx from history", tx_hash)
1390 self.transactions.pop(tx_hash)
1396 def check_new_tx(self, tx_hash, tx):
1397 # 1 check that tx is referenced in addr_history.
1399 for addr, hist in self.history.items():
1400 if hist == ['*']:continue
1401 for txh, height in hist:
1403 addresses.append(addr)
1408 # 2 check that referencing addresses are in the tx
1409 for addr in addresses:
1410 if not tx.has_address(addr):
1416 def start_threads(self, network):
1417 from verifier import TxVerifier
1418 self.network = network
1419 if self.network is not None:
1420 self.verifier = TxVerifier(self.network, self.storage)
1421 self.verifier.start()
1422 self.set_verifier(self.verifier)
1423 self.synchronizer = WalletSynchronizer(self, network)
1424 self.synchronizer.start()
1426 self.verifier = None
1427 self.synchronizer =None
1429 def stop_threads(self):
1431 self.verifier.stop()
1432 self.synchronizer.stop()
1435 def restore(self, callback):
1437 def wait_for_wallet():
1438 self.set_up_to_date(False)
1439 while not self.is_up_to_date():
1440 msg = "%s\n%s %d\n%s %.1f"%(
1441 _("Please wait..."),
1442 _("Addresses generated:"),
1443 len(self.addresses(True)),
1444 _("Kilobytes received:"),
1445 self.network.interface.bytes_received/1024.)
1447 apply(callback, (msg,))
1450 def wait_for_network():
1451 while not self.network.is_connected():
1452 msg = "%s \n" % (_("Connecting..."))
1453 apply(callback, (msg,))
1456 # wait until we are connected, because the user might have selected another server
1463 self.fill_addressbook()
1468 class WalletSynchronizer(threading.Thread):
1471 def __init__(self, wallet, network):
1472 threading.Thread.__init__(self)
1474 self.wallet = wallet
1475 self.network = network
1476 self.was_updated = True
1477 self.running = False
1478 self.lock = threading.Lock()
1479 self.queue = Queue.Queue()
1482 with self.lock: self.running = False
1484 def is_running(self):
1485 with self.lock: return self.running
1488 def subscribe_to_addresses(self, addresses):
1490 for addr in addresses:
1491 messages.append(('blockchain.address.subscribe', [addr]))
1492 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1499 while self.is_running():
1501 if not self.network.is_connected():
1502 self.network.wait_until_connected()
1504 self.run_interface()
1507 def run_interface(self):
1509 print_error("synchronizer: connected to", self.network.main_server())
1513 requested_histories = {}
1515 # request any missing transactions
1516 for history in self.wallet.history.values():
1517 if history == ['*']: continue
1518 for tx_hash, tx_height in history:
1519 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1520 missing_tx.append( (tx_hash, tx_height) )
1523 print_error("missing tx", missing_tx)
1526 self.subscribe_to_addresses(self.wallet.addresses(True))
1528 while self.is_running():
1529 # 1. create new addresses
1530 new_addresses = self.wallet.synchronize()
1532 # request missing addresses
1534 self.subscribe_to_addresses(new_addresses)
1536 # request missing transactions
1537 for tx_hash, tx_height in missing_tx:
1538 if (tx_hash, tx_height) not in requested_tx:
1539 self.network.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1540 requested_tx.append( (tx_hash, tx_height) )
1543 # detect if situation has changed
1544 if self.network.is_up_to_date() and self.queue.empty():
1545 if not self.wallet.is_up_to_date():
1546 self.wallet.set_up_to_date(True)
1547 self.was_updated = True
1549 if self.wallet.is_up_to_date():
1550 self.wallet.set_up_to_date(False)
1551 self.was_updated = True
1553 if self.was_updated:
1554 self.network.trigger_callback('updated')
1555 self.was_updated = False
1559 r = self.queue.get(block=True, timeout=1)
1564 #if interface != self.network.interface:
1570 # 3. handle response
1571 method = r['method']
1572 params = r['params']
1573 result = r.get('result')
1574 error = r.get('error')
1579 if method == 'blockchain.address.subscribe':
1581 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1582 if requested_histories.get(addr) is None:
1583 self.network.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1584 requested_histories[addr] = result
1586 elif method == 'blockchain.address.get_history':
1588 print_error("receiving history", addr, result)
1590 assert requested_histories.pop(addr) == '*'
1591 self.wallet.receive_history_callback(addr, result)
1594 # check that txids are unique
1597 tx_hash = item['tx_hash']
1598 if tx_hash not in txids:
1599 txids.append(tx_hash)
1600 hist.append( (tx_hash, item['height']) )
1602 if len(hist) != len(result):
1603 raise Exception("error: server sent history with non-unique txid", result)
1605 # check that the status corresponds to what was announced
1606 rs = requested_histories.pop(addr)
1607 if self.wallet.get_status(hist) != rs:
1608 raise Exception("error: status mismatch: %s"%addr)
1610 # store received history
1611 self.wallet.receive_history_callback(addr, hist)
1613 # request transactions that we don't have
1614 for tx_hash, tx_height in hist:
1615 if self.wallet.transactions.get(tx_hash) is None:
1616 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1617 missing_tx.append( (tx_hash, tx_height) )
1619 elif method == 'blockchain.transaction.get':
1621 tx_height = params[1]
1622 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1623 tx = Transaction(result)
1624 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1625 self.was_updated = True
1626 requested_tx.remove( (tx_hash, tx_height) )
1627 print_error("received tx:", tx_hash, len(tx.raw))
1630 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1632 if self.was_updated and not requested_tx:
1633 self.network.trigger_callback('updated')
1634 # Updated gets called too many times from other places as well; if we use that signal we get the notification three times
1635 self.network.trigger_callback("new_transaction")
1636 self.was_updated = False
1641 class OldWallet(NewWallet):
1643 def init_seed(self, seed):
1647 raise Exception("a seed exists")
1650 seed = random_seed(128)
1652 self.seed_version = OLD_SEED_VERSION
1654 # see if seed was entered as hex
1659 self.seed = str(seed)
1664 words = seed.split()
1666 mnemonic.mn_decode(words)
1670 self.seed = mnemonic.mn_decode(words)
1673 raise Exception("Invalid seed")
1677 def get_master_public_key(self):
1678 return self.storage.get("master_public_key")
1680 def create_accounts(self, password):
1681 seed = pw_decode(self.seed, password)
1682 mpk = OldAccount.mpk_from_seed(seed)
1683 self.create_account(mpk)
1685 def create_account(self, mpk):
1686 self.storage.put('master_public_key', mpk, True)
1687 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1688 self.save_accounts()
1690 def create_watching_only_wallet(self, mpk):
1691 self.seed_version = OLD_SEED_VERSION
1692 self.storage.put('seed_version', self.seed_version, True)
1693 self.create_account(mpk)
1695 def get_seed(self, password):
1696 seed = pw_decode(self.seed, password)
1697 self.accounts[0].check_seed(seed)
1700 def get_mnemonic(self, password):
1702 s = pw_decode(self.seed, password)
1703 return ' '.join(mnemonic.mn_encode(s))
1706 def add_keypairs_from_KeyID(self, tx, keypairs, password):
1707 # first check the provided password
1708 seed = self.get_seed(password)
1709 for txin in tx.inputs:
1710 keyid = txin.get('KeyID')
1712 m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
1715 if mpk != self.storage.get('master_public_key'): continue
1716 for_change = int(m.group(2))
1717 num = int(m.group(3))
1718 account = self.accounts[0]
1719 addr = account.get_address(for_change, num)
1720 txin['address'] = addr # fixme: side effect
1721 pk = account.get_private_key(seed, (for_change, num))
1722 pubkey = public_key_from_private_key(pk)
1723 keypairs[pubkey] = pk
1726 def get_account_name(self, k):
1728 return 'Main account'
1730 def is_seeded(self, account):
1731 return self.seed is not None
1733 def get_private_key(self, address, password):
1734 if self.is_watching_only():
1737 # first check the provided password
1738 seed = self.get_seed(password)
1741 if address in self.imported_keys.keys():
1742 out.append( pw_decode( self.imported_keys[address], password ) )
1744 account_id, sequence = self.get_address_index(address)
1745 pk = self.accounts[0].get_private_key(seed, sequence)
1749 def get_keyID(self, account, sequence):
1751 mpk = self.storage.get('master_public_key')
1752 return 'old(%s,%d,%d)'%(mpk,a,b)
1754 def check_pending_accounts(self):
1758 # former WalletFactory
1759 class Wallet(object):
1761 def __new__(self, storage):
1762 config = storage.config
1763 if config.get('bitkey', False):
1764 # if user requested support for Bitkey device,
1765 # import Bitkey driver
1766 from wallet_bitkey import WalletBitkey
1767 return WalletBitkey(config)
1769 if not storage.file_exists:
1770 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1772 seed_version = storage.get('seed_version')
1773 if not seed_version:
1774 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1776 if seed_version == OLD_SEED_VERSION:
1777 return OldWallet(storage)
1778 elif seed_version == NEW_SEED_VERSION:
1779 return NewWallet(storage)
1781 msg = "This wallet seed is not supported."
1782 if seed_version in [5]:
1783 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1790 def from_seed(self, seed, storage):
1795 words = seed.strip().split()
1797 mnemonic.mn_decode(words)
1798 uses_electrum_words = True
1800 uses_electrum_words = False
1808 if is_hex or (uses_electrum_words and len(words) != 13):
1809 #print "old style wallet", len(words), words
1810 w = OldWallet(storage)
1811 w.init_seed(seed) #hex
1813 #assert is_seed(seed)
1814 w = NewWallet(storage)
1821 def from_mpk(self, mpk, storage):
1830 w = OldWallet(storage)
1832 w.create_watching_only_wallet(mpk)
1834 w = NewWallet(storage)
1835 w.create_watching_only_wallet(mpk)