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
41 COINBASE_MATURITY = 100
45 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
46 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
48 def pw_encode(s, password):
50 secret = Hash(password)
51 return EncodeAES(secret, s)
55 def pw_decode(s, password):
56 if password is not None:
57 secret = Hash(password)
59 d = DecodeAES(secret, s)
61 raise Exception('Invalid password')
75 def __init__(self, config):
76 self.lock = threading.Lock()
79 self.file_exists = False
80 self.path = self.init_path(config)
81 print_error( "wallet path", self.path )
86 def init_path(self, config):
87 """Set the path of the wallet."""
89 # command line -w option
90 path = config.get('wallet_path')
95 path = config.get('default_wallet_path')
100 dirpath = os.path.join(config.path, "wallets")
101 if not os.path.exists(dirpath):
104 new_path = os.path.join(config.path, "wallets", "default_wallet")
106 # default path in pre 1.9 versions
107 old_path = os.path.join(config.path, "electrum.dat")
108 if os.path.exists(old_path) and not os.path.exists(new_path):
109 os.rename(old_path, new_path)
114 def read(self, path):
115 """Read the contents of the wallet file."""
117 with open(self.path, "r") as f:
122 d = ast.literal_eval( data ) #parse raw data from reading wallet file
124 raise IOError("Cannot read wallet file.")
127 self.file_exists = True
130 def get(self, key, default=None):
131 v = self.data.get(key)
136 def put(self, key, value, save = True):
139 if value is not None:
140 self.data[key] = value
148 f = open(self.path,"w")
151 if 'ANDROID_DATA' not in os.environ:
153 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
161 def __init__(self, storage):
163 self.storage = storage
164 self.electrum_version = ELECTRUM_VERSION
165 self.gap_limit_for_change = 3 # constant
168 self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
170 self.gap_limit = storage.get('gap_limit', 5)
171 self.use_change = storage.get('use_change',True)
172 self.use_encryption = storage.get('use_encryption', False)
173 self.seed = storage.get('seed', '') # encrypted
174 self.labels = storage.get('labels', {})
175 self.frozen_addresses = storage.get('frozen_addresses',[])
176 self.addressbook = storage.get('contacts', [])
178 self.imported_keys = storage.get('imported_keys',{})
179 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
181 self.fee = int(storage.get('fee_per_kb', 10000))
183 self.master_public_keys = storage.get('master_public_keys',{})
184 self.master_private_keys = storage.get('master_private_keys', {})
186 self.next_addresses = storage.get('next_addresses',{})
189 # This attribute is set when wallet.start_threads is called.
190 self.synchronizer = None
194 self.transactions = {}
195 tx_list = self.storage.get('transactions',{})
196 for k,v in tx_list.items():
200 print_msg("Warning: Cannot deserialize transactions. skipping")
203 self.add_extra_addresses(tx)
204 self.transactions[k] = tx
206 for h,tx in self.transactions.items():
207 if not self.check_new_tx(h, tx):
208 print_error("removing unreferenced tx", h)
209 self.transactions.pop(h)
213 self.prevout_values = {} # my own transaction outputs
214 self.spent_outputs = []
219 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
220 # interface.is_up_to_date() returns true when all requests have been answered and processed
221 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
223 self.up_to_date = False
224 self.lock = threading.Lock()
225 self.transaction_lock = threading.Lock()
226 self.tx_event = threading.Event()
228 for tx_hash, tx in self.transactions.items():
229 self.update_tx_outputs(tx_hash)
232 def add_extra_addresses(self, tx):
234 # find the address corresponding to pay-to-pubkey inputs
235 tx.add_extra_addresses(self.transactions)
236 for o in tx.d.get('outputs'):
237 if o.get('is_pubkey'):
238 for tx2 in self.transactions.values():
239 tx2.add_extra_addresses({h:tx})
242 def get_action(self):
246 def can_create_accounts(self):
247 return not self.is_watching_only()
250 def set_up_to_date(self,b):
251 with self.lock: self.up_to_date = b
254 def is_up_to_date(self):
255 with self.lock: return self.up_to_date
259 self.up_to_date = False
260 while not self.is_up_to_date():
264 def import_key(self, sec, password):
266 seed = self.get_seed(password)
268 address = address_from_private_key(sec)
270 raise Exception('Invalid private key')
272 if self.is_mine(address):
273 raise Exception('Address already in wallet')
275 # store the originally requested keypair into the imported keys table
276 self.imported_keys[address] = pw_encode(sec, password )
277 self.storage.put('imported_keys', self.imported_keys, True)
278 if self.synchronizer:
279 self.synchronizer.subscribe_to_addresses([address])
282 def delete_imported_key(self, addr):
283 if addr in self.imported_keys:
284 self.imported_keys.pop(addr)
285 self.storage.put('imported_keys', self.imported_keys, True)
289 import mnemonic, ecdsa
290 entropy = ecdsa.util.randrange( pow(2,160) )
293 ss = "%040x"%(entropy+nonce)
294 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
295 # we keep only 13 words, that's approximately 139 bits of entropy
296 words = mnemonic.mn_encode(s)[0:13]
297 seed = ' '.join(words)
298 if is_new_seed(seed):
299 break # this will remove 8 bits of entropy
305 def prepare_seed(self, seed):
307 return NEW_SEED_VERSION, unicodedata.normalize('NFC', unicode(seed.strip()))
311 def add_seed(self, seed, password):
313 raise Exception("a seed exists")
315 self.seed_version, self.seed = self.prepare_seed(seed)
317 self.seed = pw_encode( self.seed, password)
318 self.use_encryption = True
320 self.use_encryption = False
322 self.storage.put('seed', self.seed, True)
323 self.storage.put('seed_version', self.seed_version, True)
324 self.storage.put('use_encryption', self.use_encryption,True)
325 self.create_master_keys(password)
328 def create_watching_only_wallet(self, xpub):
329 self.storage.put('seed_version', self.seed_version, True)
330 self.add_master_public_key("m/", xpub)
331 account = BIP32_Account({'xpub':xpub})
332 self.add_account("m/", account)
337 def create_accounts(self, password):
338 seed = pw_decode(self.seed, password)
339 self.create_account('Main account', password)
342 def add_master_public_key(self, name, mpk):
343 self.master_public_keys[name] = mpk
344 self.storage.put('master_public_keys', self.master_public_keys, True)
347 def add_master_private_key(self, name, xpriv, password):
348 self.master_private_keys[name] = pw_encode(xpriv, password)
349 self.storage.put('master_private_keys', self.master_private_keys, True)
352 def add_master_keys(self, root, account_id, password):
353 x = self.master_private_keys.get(root)
355 master_xpriv = pw_decode(x, password )
356 xpriv, xpub = bip32_private_derivation(master_xpriv, root, account_id)
357 self.add_master_public_key(account_id, xpub)
358 self.add_master_private_key(account_id, xpriv, password)
360 master_xpub = self.master_public_keys[root]
361 xpub = bip32_public_derivation(master_xpub, root, account_id)
362 self.add_master_public_key(account_id, xpub)
366 def create_master_keys(self, password):
367 xpriv, xpub = bip32_root(self.get_seed(password))
368 self.add_master_public_key("m/", xpub)
369 self.add_master_private_key("m/", xpriv, password)
372 def find_root_by_master_key(self, xpub):
373 for key, xpub2 in self.master_public_keys.items():
374 if key == "m/":continue
378 def is_watching_only(self):
379 return (self.seed == '') and (self.master_private_keys == {})
382 def num_accounts(self):
383 keys = self.accounts.keys()
386 account_id = self.account_id(i)
387 if account_id not in keys: break
392 def next_account_address(self, password):
393 i = self.num_accounts()
394 account_id = self.account_id(i)
396 addr = self.next_addresses.get(account_id)
398 account = self.make_account(account_id, password)
399 addr = account.first_address()
400 self.next_addresses[account_id] = addr
401 self.storage.put('next_addresses', self.next_addresses)
403 return account_id, addr
405 def account_id(self, i):
408 def make_account(self, account_id, password):
409 """Creates and saves the master keys, but does not save the account"""
410 xpub = self.add_master_keys("m/", account_id, password)
411 account = BIP32_Account({'xpub':xpub})
415 def set_label(self, name, text = None):
417 old_text = self.labels.get(name)
420 self.labels[name] = text
424 self.labels.pop(name)
428 self.storage.put('labels', self.labels, True)
430 run_hook('set_label', name, text, changed)
434 def create_account(self, name, password):
435 i = self.num_accounts()
436 account_id = self.account_id(i)
437 account = self.make_account(account_id, password)
438 self.add_account(account_id, account)
440 self.set_label(account_id, name)
442 # add address of the next account
443 _, _ = self.next_account_address(password)
446 def add_account(self, account_id, account):
447 self.accounts[account_id] = account
448 if account_id in self.pending_accounts:
449 self.pending_accounts.pop(account_id)
450 self.storage.put('pending_accounts', self.pending_accounts)
454 def save_accounts(self):
456 for k, v in self.accounts.items():
458 self.storage.put('accounts', d, True)
462 def load_accounts(self):
463 d = self.storage.get('accounts', {})
465 for k, v in d.items():
467 v['mpk'] = self.storage.get('master_public_key')
468 self.accounts[k] = OldAccount(v)
470 self.accounts[k] = BIP32_Account_2of3(v)
472 self.accounts[k] = BIP32_Account_2of2(v)
474 self.accounts[k] = BIP32_Account(v)
478 self.pending_accounts = self.storage.get('pending_accounts',{})
481 def delete_pending_account(self, k):
482 self.pending_accounts.pop(k)
483 self.storage.put('pending_accounts', self.pending_accounts)
485 def account_is_pending(self, k):
486 return k in self.pending_accounts
488 def create_pending_account(self, name, password):
489 account_id, addr = self.next_account_address(password)
490 self.set_label(account_id, name)
491 self.pending_accounts[account_id] = addr
492 self.storage.put('pending_accounts', self.pending_accounts)
494 def get_pending_accounts(self):
495 return self.pending_accounts.items()
498 def addresses(self, include_change = True, _next=True):
499 o = self.get_account_addresses(-1, include_change)
500 for a in self.accounts.keys():
501 o += self.get_account_addresses(a, include_change)
504 for addr in self.next_addresses.values():
510 def is_mine(self, address):
511 return address in self.addresses(True)
514 def is_change(self, address):
515 if not self.is_mine(address): return False
516 if address in self.imported_keys.keys(): return False
517 acct, s = self.get_address_index(address)
518 if s is None: return False
521 def get_master_public_key(self):
522 return self.master_public_keys["m/"]
524 def get_master_public_keys(self):
526 for k, account in self.accounts.items():
527 name = self.get_account_name(k)
528 mpk_text = '\n\n'.join( account.get_master_pubkeys() )
532 def get_master_private_key(self, account, password):
533 k = self.master_private_keys.get(account)
535 xpriv = pw_decode( k, password)
539 def get_address_index(self, address):
540 if address in self.imported_keys.keys():
543 for account in self.accounts.keys():
544 for for_change in [0,1]:
545 addresses = self.accounts[account].get_addresses(for_change)
546 for addr in addresses:
548 return account, (for_change, addresses.index(addr))
550 for k,v in self.next_addresses.items():
554 raise Exception("Address not found", address)
557 def getpubkeys(self, addr):
558 assert is_valid(addr) and self.is_mine(addr)
559 account, sequence = self.get_address_index(addr)
561 a = self.accounts[account]
562 return a.get_pubkeys( sequence )
565 def get_roots(self, account):
567 for a in account.split('&'):
569 m = re.match("m/(\d+')", s)
570 roots.append( m.group(1) )
574 def is_seeded(self, account):
578 for root in self.get_roots(account):
579 if root not in self.master_private_keys.keys():
583 def rebase_sequence(self, account, sequence):
584 # account has one or more xpub
585 # sequence is a sequence of public derivations
588 for a in account.split('&'):
590 m = re.match("m/(\d+)'", s)
592 num = int(m.group(1))
593 dd.append( (root, [num,c,i] ) )
600 def get_seed(self, password):
601 s = pw_decode(self.seed, password)
602 seed = mnemonic_to_seed(s,'').encode('hex')
606 def get_mnemonic(self, password):
607 return pw_decode(self.seed, password)
610 def get_private_key(self, address, password):
611 if self.is_watching_only():
614 # first check the provided password
615 seed = self.get_seed(password)
618 if address in self.imported_keys.keys():
619 out.append( pw_decode( self.imported_keys[address], password ) )
621 account_id, sequence = self.get_address_index(address)
622 account = self.accounts[account_id]
623 xpubs = account.get_master_pubkeys()
624 roots = [k for k, v in self.master_public_keys.iteritems() if v in xpubs]
626 xpriv = self.get_master_private_key(root, password)
629 _, _, _, c, k = deserialize_xkey(xpriv)
630 pk = bip32_private_key( sequence, k, c )
636 def get_public_keys(self, address):
637 account_id, sequence = self.get_address_index(address)
638 return self.accounts[account_id].get_pubkeys(sequence)
641 def add_keypairs_from_wallet(self, tx, keypairs, password):
642 for txin in tx.inputs:
643 address = txin['address']
644 if not self.is_mine(address):
646 private_keys = self.get_private_key(address, password)
647 for sec in private_keys:
648 pubkey = public_key_from_private_key(sec)
649 keypairs[ pubkey ] = sec
650 if address in self.imported_keys.keys():
651 txin['redeemPubkey'] = pubkey
654 def add_keypairs_from_KeyID(self, tx, keypairs, password):
655 # first check the provided password
656 seed = self.get_seed(password)
658 for txin in tx.inputs:
659 keyid = txin.get('KeyID')
662 for s in keyid.split('&'):
663 m = re.match("bip32\((.*),(/\d+/\d+)\)", s)
666 sequence = m.group(2)
667 root = self.find_root_by_master_key(xpub)
668 if not root: continue
669 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
670 root = root + '%d'%sequence[0]
671 sequence = sequence[1:]
672 roots.append((root,sequence))
674 account_id = " & ".join( map(lambda x:x[0], roots) )
675 account = self.accounts.get(account_id)
676 if not account: continue
677 addr = account.get_address(*sequence)
678 txin['address'] = addr # fixme: side effect
679 pk = self.get_private_key(addr, password)
681 pubkey = public_key_from_private_key(sec)
682 keypairs[pubkey] = sec
686 def signrawtransaction(self, tx, input_info, private_keys, password):
688 # check that the password is correct
689 seed = self.get_seed(password)
691 # if input_info is not known, build it using wallet UTXOs
694 unspent_coins = self.get_unspent_coins()
695 for txin in tx.inputs:
696 for item in unspent_coins:
697 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
698 info = { 'address':item['address'], 'scriptPubKey':item['scriptPubKey'] }
699 self.add_input_info(info)
700 input_info.append(info)
703 print_error( "input not in UTXOs" )
704 input_info.append(None)
706 # add input_info to the transaction
707 print_error("input_info", input_info)
708 tx.add_input_info(input_info)
710 # build a list of public/private keys
713 # add private keys from parameter
714 for sec in private_keys:
715 pubkey = public_key_from_private_key(sec)
716 keypairs[ pubkey ] = sec
718 # add private_keys from KeyID
719 self.add_keypairs_from_KeyID(tx, keypairs, password)
720 # add private keys from wallet
721 self.add_keypairs_from_wallet(tx, keypairs, password)
722 # sign the transaction
723 self.sign_transaction(tx, keypairs, password)
726 def sign_message(self, address, message, password):
727 keys = self.get_private_key(address, password)
728 assert len(keys) == 1
730 key = regenerate_key(sec)
731 compressed = is_compressed(sec)
732 return key.sign_message(message, compressed, address)
736 def decrypt_message(self, pubkey, message, password):
737 address = public_key_to_bc_address(pubkey.decode('hex'))
738 keys = self.get_private_key(address, password)
740 ec = regenerate_key(secret)
741 decrypted = ec.decrypt_message(message)
745 def change_gap_limit(self, value):
746 if value >= self.gap_limit:
747 self.gap_limit = value
748 self.storage.put('gap_limit', self.gap_limit, True)
749 #self.interface.poke('synchronizer')
752 elif value >= self.min_acceptable_gap():
753 for key, account in self.accounts.items():
754 addresses = account[0]
755 k = self.num_unused_trailing_addresses(addresses)
756 n = len(addresses) - k + value
757 addresses = addresses[0:n]
758 self.accounts[key][0] = addresses
760 self.gap_limit = value
761 self.storage.put('gap_limit', self.gap_limit, True)
767 def num_unused_trailing_addresses(self, addresses):
769 for a in addresses[::-1]:
770 if self.history.get(a):break
774 def min_acceptable_gap(self):
775 # fixme: this assumes wallet is synchronized
779 for account in self.accounts.values():
780 addresses = account.get_addresses(0)
781 k = self.num_unused_trailing_addresses(addresses)
782 for a in addresses[0:-k]:
783 if self.history.get(a):
787 if n > nmax: nmax = n
791 def address_is_old(self, address):
793 h = self.history.get(address, [])
796 for tx_hash, tx_height in h:
800 tx_age = self.network.get_local_height() - tx_height + 1
806 def synchronize_sequence(self, account, for_change):
807 limit = self.gap_limit_for_change if for_change else self.gap_limit
810 addresses = account.get_addresses(for_change)
811 if len(addresses) < limit:
812 address = account.create_new_address(for_change)
813 self.history[address] = []
814 new_addresses.append( address )
817 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
820 address = account.create_new_address(for_change)
821 self.history[address] = []
822 new_addresses.append( address )
827 def check_pending_accounts(self):
828 for account_id, addr in self.next_addresses.items():
829 if self.address_is_old(addr):
830 print_error( "creating account", account_id )
831 xpub = self.master_public_keys[account_id]
832 account = BIP32_Account({'xpub':xpub})
833 self.add_account(account_id, account)
834 self.next_addresses.pop(account_id)
837 def synchronize_account(self, account):
839 new += self.synchronize_sequence(account, 0)
840 new += self.synchronize_sequence(account, 1)
844 def synchronize(self):
845 self.check_pending_accounts()
847 for account in self.accounts.values():
848 new += self.synchronize_account(account)
851 self.storage.put('addr_history', self.history, True)
856 return self.history.values() != [[]] * len(self.history)
859 def add_contact(self, address, label=None):
860 self.addressbook.append(address)
861 self.storage.put('contacts', self.addressbook, True)
863 self.set_label(address, label)
866 def delete_contact(self, addr):
867 if addr in self.addressbook:
868 self.addressbook.remove(addr)
869 self.storage.put('addressbook', self.addressbook, True)
872 def fill_addressbook(self):
873 for tx_hash, tx in self.transactions.items():
874 is_relevant, is_send, _, _ = self.get_tx_value(tx)
876 for addr, v in tx.outputs:
877 if not self.is_mine(addr) and addr not in self.addressbook:
878 self.addressbook.append(addr)
880 # self.update_tx_labels()
882 def get_num_tx(self, address):
884 for tx in self.transactions.values():
885 if address in map(lambda x:x[0], tx.outputs): n += 1
889 def get_address_flags(self, addr):
890 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
891 flags += "F" if addr in self.frozen_addresses else "-"
895 def get_tx_value(self, tx, account=None):
896 domain = self.get_account_addresses(account)
897 return tx.get_value(domain, self.prevout_values)
900 def update_tx_outputs(self, tx_hash):
901 tx = self.transactions.get(tx_hash)
903 for i, (addr, value) in enumerate(tx.outputs):
904 key = tx_hash+ ':%d'%i
905 self.prevout_values[key] = value
907 for item in tx.inputs:
908 if self.is_mine(item.get('address')):
909 key = item['prevout_hash'] + ':%d'%item['prevout_n']
910 self.spent_outputs.append(key)
913 def get_addr_balance(self, address):
914 assert self.is_mine(address)
915 h = self.history.get(address,[])
916 if h == ['*']: return 0,0
918 received_coins = [] # list of coins received at address
920 for tx_hash, tx_height in h:
921 tx = self.transactions.get(tx_hash)
924 for i, (addr, value) in enumerate(tx.outputs):
926 key = tx_hash + ':%d'%i
927 received_coins.append(key)
929 for tx_hash, tx_height in h:
930 tx = self.transactions.get(tx_hash)
934 for item in tx.inputs:
935 addr = item.get('address')
937 key = item['prevout_hash'] + ':%d'%item['prevout_n']
938 value = self.prevout_values.get( key )
939 if key in received_coins:
942 for i, (addr, value) in enumerate(tx.outputs):
943 key = tx_hash + ':%d'%i
954 def get_account_name(self, k):
955 default = "Unnamed account"
956 m = re.match("m/0'/(\d+)", k)
960 default = "Main account"
962 default = "Account %s"%num
964 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
967 default = "2of2 account %s"%num
968 name = self.labels.get(k, default)
972 def get_account_names(self):
974 for k, account in self.accounts.items():
975 accounts[k] = self.get_account_name(k)
976 if self.imported_keys:
977 accounts[-1] = 'Imported keys'
981 def get_account_addresses(self, a, include_change=True):
983 o = self.addresses(True)
985 o = self.imported_keys.keys()
987 ac = self.accounts[a]
988 o = ac.get_addresses(0)
989 if include_change: o += ac.get_addresses(1)
992 def get_imported_balance(self):
993 return self.get_balance(self.imported_keys.keys())
995 def get_account_balance(self, account):
996 return self.get_balance(self.get_account_addresses(account))
998 def get_frozen_balance(self):
999 return self.get_balance(self.frozen_addresses)
1001 def get_balance(self, domain=None):
1002 if domain is None: domain = self.addresses(True)
1005 c, u = self.get_addr_balance(addr)
1011 def get_unspent_coins(self, domain=None):
1013 if domain is None: domain = self.addresses(True)
1015 h = self.history.get(addr, [])
1016 if h == ['*']: continue
1017 for tx_hash, tx_height in h:
1018 tx = self.transactions.get(tx_hash)
1019 if tx is None: raise Exception("Wallet not synchronized")
1020 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1021 for o in tx.d.get('outputs'):
1023 if output.get('address') != addr: continue
1024 key = tx_hash + ":%d" % output.get('prevout_n')
1025 if key in self.spent_outputs: continue
1026 output['prevout_hash'] = tx_hash
1027 output['height'] = tx_height
1028 output['coinbase'] = is_coinbase
1029 coins.append((tx_height, output))
1033 coins = sorted(coins)
1034 if coins[-1][0] != 0:
1035 while coins[0][0] == 0:
1036 coins = coins[1:] + [ coins[0] ]
1037 return [x[1] for x in coins]
1040 def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None ):
1041 """ todo: minimize tx size """
1043 fee = self.fee if fixed_fee is None else fixed_fee
1045 domain = self.addresses(True)
1047 for i in self.frozen_addresses:
1048 if i in domain: domain.remove(i)
1050 coins = self.get_unspent_coins(domain)
1054 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.get_local_height():
1056 addr = item.get('address')
1057 v = item.get('value')
1060 fee = self.estimated_fee(inputs, num_outputs) if fixed_fee is None else fixed_fee
1061 if total >= amount + fee: break
1065 return inputs, total, fee
1068 def set_fee(self, fee):
1071 self.storage.put('fee_per_kb', self.fee, True)
1073 def estimated_fee(self, inputs, num_outputs):
1074 estimated_size = len(inputs) * 180 + num_outputs * 34 # this assumes non-compressed keys
1075 fee = self.fee * int(math.ceil(estimated_size/1000.))
1079 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1080 "add change to a transaction"
1081 change_amount = total - ( amount + fee )
1082 if change_amount > DUST_THRESHOLD:
1085 # send change to one of the accounts involved in the tx
1086 address = inputs[0].get('address')
1087 account, _ = self.get_address_index(address)
1089 if not self.use_change or account == -1:
1090 change_addr = inputs[-1]['address']
1092 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1094 # Insert the change output at a random position in the outputs
1095 posn = random.randint(0, len(outputs))
1096 outputs[posn:posn] = [( change_addr, change_amount)]
1100 def get_history(self, address):
1102 return self.history.get(address)
1105 def get_status(self, h):
1106 if not h: return None
1107 if h == ['*']: return '*'
1109 for tx_hash, height in h:
1110 status += tx_hash + ':%d:' % height
1111 return hashlib.sha256( status ).digest().encode('hex')
1114 def receive_tx_callback(self, tx_hash, tx, tx_height):
1116 with self.transaction_lock:
1117 self.add_extra_addresses(tx)
1118 if not self.check_new_tx(tx_hash, tx):
1119 # may happen due to pruning
1120 print_error("received transaction that is no longer referenced in history", tx_hash)
1122 self.transactions[tx_hash] = tx
1123 self.network.pending_transactions_for_notifications.append(tx)
1124 self.save_transactions()
1125 if self.verifier and tx_height>0:
1126 self.verifier.add(tx_hash, tx_height)
1127 self.update_tx_outputs(tx_hash)
1130 def save_transactions(self):
1132 for k,v in self.transactions.items():
1134 self.storage.put('transactions', tx, True)
1136 def receive_history_callback(self, addr, hist):
1138 if not self.check_new_history(addr, hist):
1139 raise Exception("error: received history for %s is not consistent with known transactions"%addr)
1142 self.history[addr] = hist
1143 self.storage.put('addr_history', self.history, True)
1146 for tx_hash, tx_height in hist:
1148 # add it in case it was previously unconfirmed
1149 if self.verifier: self.verifier.add(tx_hash, tx_height)
1152 def get_tx_history(self, account=None):
1153 if not self.verifier:
1156 with self.transaction_lock:
1157 history = self.transactions.items()
1158 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1162 for tx_hash, tx in history:
1163 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1164 if v is not None: balance += v
1166 c, u = self.get_account_balance(account)
1169 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1171 balance = c + u - balance
1172 for tx_hash, tx in history:
1173 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1176 if value is not None:
1179 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1180 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1185 def get_label(self, tx_hash):
1186 label = self.labels.get(tx_hash)
1187 is_default = (label == '') or (label is None)
1188 if is_default: label = self.get_default_label(tx_hash)
1189 return label, is_default
1192 def get_default_label(self, tx_hash):
1193 tx = self.transactions.get(tx_hash)
1196 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1198 for o in tx.outputs:
1200 if not self.is_mine(o_addr):
1202 default_label = self.labels[o_addr]
1204 default_label = '>' + o_addr
1207 default_label = '(internal)'
1209 for o in tx.outputs:
1211 if self.is_mine(o_addr) and not self.is_change(o_addr):
1214 for o in tx.outputs:
1216 if self.is_mine(o_addr):
1222 dest_label = self.labels.get(o_addr)
1224 default_label = self.labels[o_addr]
1226 default_label = '<' + o_addr
1228 return default_label
1231 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1232 for address, x in outputs:
1233 assert is_valid(address), "Address " + address + " is invalid!"
1234 amount = sum( map(lambda x:x[1], outputs) )
1235 inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain )
1237 raise ValueError("Not enough funds")
1239 self.add_input_info(txin)
1240 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1241 return Transaction.from_io(inputs, outputs)
1244 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1245 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1247 self.add_keypairs_from_wallet(tx, keypairs, password)
1249 self.sign_transaction(tx, keypairs, password)
1253 def add_input_info(self, txin):
1254 address = txin['address']
1255 if address in self.imported_keys.keys():
1257 account_id, sequence = self.get_address_index(address)
1258 account = self.accounts[account_id]
1259 txin['KeyID'] = account.get_keyID(sequence)
1260 redeemScript = account.redeem_script(sequence)
1262 txin['redeemScript'] = redeemScript
1264 txin['redeemPubkey'] = account.get_pubkey(*sequence)
1267 def sign_transaction(self, tx, keypairs, password):
1269 run_hook('sign_transaction', tx, password)
1272 def sendtx(self, tx):
1274 h = self.send_tx(tx)
1275 self.tx_event.wait()
1276 return self.receive_tx(h, tx)
1278 def send_tx(self, tx):
1280 self.tx_event.clear()
1281 self.network.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1284 def on_broadcast(self, i, r):
1285 self.tx_result = r.get('result')
1288 def receive_tx(self, tx_hash, tx):
1289 out = self.tx_result
1291 return False, "error: " + out
1292 run_hook('receive_tx', tx, self)
1297 def update_password(self, old_password, new_password):
1298 if new_password == '': new_password = None
1299 decoded = self.get_seed(old_password)
1300 self.seed = pw_encode( decoded, new_password)
1301 self.storage.put('seed', self.seed, True)
1302 self.use_encryption = (new_password != None)
1303 self.storage.put('use_encryption', self.use_encryption,True)
1304 for k in self.imported_keys.keys():
1305 a = self.imported_keys[k]
1306 b = pw_decode(a, old_password)
1307 c = pw_encode(b, new_password)
1308 self.imported_keys[k] = c
1309 self.storage.put('imported_keys', self.imported_keys, True)
1311 for k, v in self.master_private_keys.items():
1312 b = pw_decode(v, old_password)
1313 c = pw_encode(b, new_password)
1314 self.master_private_keys[k] = c
1315 self.storage.put('master_private_keys', self.master_private_keys, True)
1318 def freeze(self,addr):
1319 if self.is_mine(addr) and addr not in self.frozen_addresses:
1320 self.frozen_addresses.append(addr)
1321 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1326 def unfreeze(self,addr):
1327 if self.is_mine(addr) and addr in self.frozen_addresses:
1328 self.frozen_addresses.remove(addr)
1329 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1335 def set_verifier(self, verifier):
1336 self.verifier = verifier
1338 # review transactions that are in the history
1339 for addr, hist in self.history.items():
1340 if hist == ['*']: continue
1341 for tx_hash, tx_height in hist:
1343 # add it in case it was previously unconfirmed
1344 self.verifier.add(tx_hash, tx_height)
1347 # if we are on a pruning server, remove unverified transactions
1348 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1349 for tx_hash in self.transactions.keys():
1350 if tx_hash not in vr:
1351 self.transactions.pop(tx_hash)
1355 def check_new_history(self, addr, hist):
1357 # check that all tx in hist are relevant
1359 for tx_hash, height in hist:
1360 tx = self.transactions.get(tx_hash)
1362 if not tx.has_address(addr):
1365 # check that we are not "orphaning" a transaction
1366 old_hist = self.history.get(addr,[])
1367 if old_hist == ['*']: return True
1369 for tx_hash, height in old_hist:
1370 if tx_hash in map(lambda x:x[0], hist): continue
1372 for _addr, _hist in self.history.items():
1373 if _addr == addr: continue
1374 if _hist == ['*']: continue
1375 _tx_hist = map(lambda x:x[0], _hist)
1376 if tx_hash in _tx_hist:
1381 tx = self.transactions.get(tx_hash)
1382 # tx might not be there
1386 if self.verifier.get_height(tx_hash):
1389 print_error("new history is orphaning transaction:", tx_hash)
1390 # check that all outputs are not mine, request histories
1392 for _addr, _v in tx.outputs:
1393 # assert not self.is_mine(_addr)
1394 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1396 ext_h = self.network.synchronous_get(ext_requests)
1397 print_error("sync:", ext_requests, ext_h)
1400 if h == ['*']: continue
1402 if item.get('tx_hash') == tx_hash:
1403 height = item.get('height')
1405 print_error("found height for", tx_hash, height)
1406 self.verifier.add(tx_hash, height)
1408 print_error("removing orphaned tx from history", tx_hash)
1409 self.transactions.pop(tx_hash)
1415 def check_new_tx(self, tx_hash, tx):
1416 # 1 check that tx is referenced in addr_history.
1418 for addr, hist in self.history.items():
1419 if hist == ['*']:continue
1420 for txh, height in hist:
1422 addresses.append(addr)
1427 # 2 check that referencing addresses are in the tx
1428 for addr in addresses:
1429 if not tx.has_address(addr):
1435 def start_threads(self, network):
1436 from verifier import TxVerifier
1437 self.network = network
1438 if self.network is not None:
1439 self.verifier = TxVerifier(self.network, self.storage)
1440 self.verifier.start()
1441 self.set_verifier(self.verifier)
1442 self.synchronizer = WalletSynchronizer(self, network)
1443 self.synchronizer.start()
1445 self.verifier = None
1446 self.synchronizer =None
1448 def stop_threads(self):
1450 self.verifier.stop()
1451 self.synchronizer.stop()
1454 def restore(self, callback):
1456 def wait_for_wallet():
1457 self.set_up_to_date(False)
1458 while not self.is_up_to_date():
1459 msg = "%s\n%s %d\n%s %.1f"%(
1460 _("Please wait..."),
1461 _("Addresses generated:"),
1462 len(self.addresses(True)),
1463 _("Kilobytes received:"),
1464 self.network.interface.bytes_received/1024.)
1466 apply(callback, (msg,))
1469 def wait_for_network():
1470 while not self.network.is_connected():
1471 msg = "%s \n" % (_("Connecting..."))
1472 apply(callback, (msg,))
1475 # wait until we are connected, because the user might have selected another server
1482 self.fill_addressbook()
1486 class Imported_Wallet(NewWallet):
1488 def __init__(self, storage):
1489 NewWallet.__init__(self, storage)
1491 def is_watching_only(self):
1492 n = self.imported_keys.values()
1493 return n == [''] * len(n)
1497 class Wallet_2of2(NewWallet):
1499 def __init__(self, storage):
1500 NewWallet.__init__(self, storage)
1501 self.storage.put('wallet_type', '2of2', True)
1503 def can_create_accounts(self):
1506 def create_account(self):
1507 xpub1 = self.master_public_keys.get("m/")
1508 xpub2 = self.master_public_keys.get("cold/")
1509 account = BIP32_Account_2of2({'xpub':xpub1, 'xpub2':xpub2})
1510 self.add_account('m/', account)
1512 def get_master_public_keys(self):
1513 xpub1 = self.master_public_keys.get("m/")
1514 xpub2 = self.master_public_keys.get("cold/")
1515 return {'hot':xpub1, 'cold':xpub2}
1517 def get_action(self):
1518 xpub1 = self.master_public_keys.get("m/")
1519 xpub2 = self.master_public_keys.get("cold/")
1521 return 'create_2of2_1'
1523 return 'create_2of2_2'
1527 class Wallet_2of3(Wallet_2of2):
1529 def __init__(self, storage):
1530 NewWallet.__init__(self, storage)
1531 self.storage.put('wallet_type', '2of3', True)
1533 def create_account(self):
1534 xpub1 = self.master_public_keys.get("m/")
1535 xpub2 = self.master_public_keys.get("cold/")
1536 xpub3 = self.master_public_keys.get("remote/")
1537 account = BIP32_Account_2of3({'xpub':xpub1, 'xpub2':xpub2, 'xpub3':xpub3})
1538 self.add_account('m/', account)
1540 def get_master_public_keys(self):
1541 xpub1 = self.master_public_keys.get("m/")
1542 xpub2 = self.master_public_keys.get("cold/")
1543 xpub3 = self.master_public_keys.get("remote/")
1544 return {'hot':xpub1, 'cold':xpub2, 'remote':xpub3}
1546 def get_action(self):
1547 xpub1 = self.master_public_keys.get("m/")
1548 xpub2 = self.master_public_keys.get("cold/")
1549 xpub3 = self.master_public_keys.get("remote/")
1551 return 'create_2of3_1'
1553 return 'create_2of3_2'
1555 return 'create_2of3_3'
1558 class WalletSynchronizer(threading.Thread):
1560 def __init__(self, wallet, network):
1561 threading.Thread.__init__(self)
1563 self.wallet = wallet
1564 self.network = network
1565 self.was_updated = True
1566 self.running = False
1567 self.lock = threading.Lock()
1568 self.queue = Queue.Queue()
1571 with self.lock: self.running = False
1573 def is_running(self):
1574 with self.lock: return self.running
1577 def subscribe_to_addresses(self, addresses):
1579 for addr in addresses:
1580 messages.append(('blockchain.address.subscribe', [addr]))
1581 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1588 while self.is_running():
1590 if not self.network.is_connected():
1591 self.network.wait_until_connected()
1593 self.run_interface()
1596 def run_interface(self):
1598 print_error("synchronizer: connected to", self.network.main_server())
1602 requested_histories = {}
1604 # request any missing transactions
1605 for history in self.wallet.history.values():
1606 if history == ['*']: continue
1607 for tx_hash, tx_height in history:
1608 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1609 missing_tx.append( (tx_hash, tx_height) )
1612 print_error("missing tx", missing_tx)
1615 self.subscribe_to_addresses(self.wallet.addresses(True))
1617 while self.is_running():
1618 # 1. create new addresses
1619 new_addresses = self.wallet.synchronize()
1621 # request missing addresses
1623 self.subscribe_to_addresses(new_addresses)
1625 # request missing transactions
1626 for tx_hash, tx_height in missing_tx:
1627 if (tx_hash, tx_height) not in requested_tx:
1628 self.network.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1629 requested_tx.append( (tx_hash, tx_height) )
1632 # detect if situation has changed
1633 if self.network.is_up_to_date() and self.queue.empty():
1634 if not self.wallet.is_up_to_date():
1635 self.wallet.set_up_to_date(True)
1636 self.was_updated = True
1638 if self.wallet.is_up_to_date():
1639 self.wallet.set_up_to_date(False)
1640 self.was_updated = True
1642 if self.was_updated:
1643 self.network.trigger_callback('updated')
1644 self.was_updated = False
1648 r = self.queue.get(block=True, timeout=1)
1653 #if interface != self.network.interface:
1659 # 3. handle response
1660 method = r['method']
1661 params = r['params']
1662 result = r.get('result')
1663 error = r.get('error')
1668 if method == 'blockchain.address.subscribe':
1670 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1671 if requested_histories.get(addr) is None:
1672 self.network.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1673 requested_histories[addr] = result
1675 elif method == 'blockchain.address.get_history':
1677 print_error("receiving history", addr, result)
1679 assert requested_histories.pop(addr) == '*'
1680 self.wallet.receive_history_callback(addr, result)
1683 # check that txids are unique
1686 tx_hash = item['tx_hash']
1687 if tx_hash not in txids:
1688 txids.append(tx_hash)
1689 hist.append( (tx_hash, item['height']) )
1691 if len(hist) != len(result):
1692 raise Exception("error: server sent history with non-unique txid", result)
1694 # check that the status corresponds to what was announced
1695 rs = requested_histories.pop(addr)
1696 if self.wallet.get_status(hist) != rs:
1697 raise Exception("error: status mismatch: %s"%addr)
1699 # store received history
1700 self.wallet.receive_history_callback(addr, hist)
1702 # request transactions that we don't have
1703 for tx_hash, tx_height in hist:
1704 if self.wallet.transactions.get(tx_hash) is None:
1705 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1706 missing_tx.append( (tx_hash, tx_height) )
1708 elif method == 'blockchain.transaction.get':
1710 tx_height = params[1]
1711 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1712 tx = Transaction(result)
1713 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1714 self.was_updated = True
1715 requested_tx.remove( (tx_hash, tx_height) )
1716 print_error("received tx:", tx_hash, len(tx.raw))
1719 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1721 if self.was_updated and not requested_tx:
1722 self.network.trigger_callback('updated')
1723 # Updated gets called too many times from other places as well; if we use that signal we get the notification three times
1724 self.network.trigger_callback("new_transaction")
1725 self.was_updated = False
1730 class OldWallet(NewWallet):
1732 def can_create_accounts(self):
1735 def make_seed(self):
1737 seed = random_seed(128)
1738 return ' '.join(mnemonic.mn_encode(seed))
1740 def prepare_seed(self, seed):
1742 # see if seed was entered as hex
1747 return OLD_SEED_VERSION, str(seed)
1751 words = seed.split()
1752 seed = mnemonic.mn_decode(words)
1754 raise Exception("Invalid seed")
1756 return OLD_SEED_VERSION, seed
1759 def create_master_keys(self, password):
1760 seed = pw_decode(self.seed, password)
1761 mpk = OldAccount.mpk_from_seed(seed)
1762 self.storage.put('master_public_key', mpk, True)
1764 def get_master_public_key(self):
1765 return self.storage.get("master_public_key")
1767 def get_master_public_keys(self):
1768 return {'Main Account':self.get_master_public_key()}
1770 def create_accounts(self, password):
1771 mpk = self.storage.get("master_public_key")
1772 self.create_account(mpk)
1774 def create_account(self, mpk):
1775 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
1776 self.save_accounts()
1778 def create_watching_only_wallet(self, mpk):
1779 self.seed_version = OLD_SEED_VERSION
1780 self.storage.put('seed_version', self.seed_version, True)
1781 self.storage.put('master_public_key', mpk, True)
1782 self.create_account(mpk)
1784 def get_seed(self, password):
1785 seed = pw_decode(self.seed, password)
1786 self.accounts[0].check_seed(seed)
1789 def get_mnemonic(self, password):
1791 s = pw_decode(self.seed, password)
1792 return ' '.join(mnemonic.mn_encode(s))
1795 def add_keypairs_from_KeyID(self, tx, keypairs, password):
1796 # first check the provided password
1797 seed = self.get_seed(password)
1798 for txin in tx.inputs:
1799 keyid = txin.get('KeyID')
1801 m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
1804 if mpk != self.storage.get('master_public_key'): continue
1805 for_change = int(m.group(2))
1806 num = int(m.group(3))
1807 account = self.accounts[0]
1808 addr = account.get_address(for_change, num)
1809 txin['address'] = addr # fixme: side effect
1810 pk = account.get_private_key(seed, (for_change, num))
1811 pubkey = public_key_from_private_key(pk)
1812 keypairs[pubkey] = pk
1815 def get_account_name(self, k):
1817 return 'Main account'
1819 def is_seeded(self, account):
1820 return self.seed is not None
1822 def get_private_key(self, address, password):
1823 if self.is_watching_only():
1826 # first check the provided password
1827 seed = self.get_seed(password)
1830 if address in self.imported_keys.keys():
1831 out.append( pw_decode( self.imported_keys[address], password ) )
1833 account_id, sequence = self.get_address_index(address)
1834 pk = self.accounts[0].get_private_key(seed, sequence)
1838 def check_pending_accounts(self):
1842 # former WalletFactory
1843 class Wallet(object):
1845 def __new__(self, storage):
1846 config = storage.config
1847 if config.get('bitkey', False):
1848 # if user requested support for Bitkey device,
1849 # import Bitkey driver
1850 from wallet_bitkey import WalletBitkey
1851 return WalletBitkey(config)
1853 if storage.get('wallet_type') == '2of2':
1854 return Wallet_2of2(storage)
1856 if storage.get('wallet_type') == '2of3':
1857 return Wallet_2of3(storage)
1859 if storage.file_exists and not storage.get('seed'):
1860 # wallet made of imported keys
1861 return Imported_Wallet(storage)
1864 if not storage.file_exists:
1865 seed_version = NEW_SEED_VERSION if config.get('bip32') is True else OLD_SEED_VERSION
1867 seed_version = storage.get('seed_version')
1868 if not seed_version:
1869 seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
1871 if seed_version == OLD_SEED_VERSION:
1872 return OldWallet(storage)
1873 elif seed_version == NEW_SEED_VERSION:
1874 return NewWallet(storage)
1876 msg = "This wallet seed is not supported."
1877 if seed_version in [5]:
1878 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
1885 def is_seed(self, seed):
1888 elif is_old_seed(seed):
1890 elif is_new_seed(seed):
1896 def is_mpk(self, mpk):
1904 return len(mpk) == 128
1907 deserialize_xkey(mpk)
1913 def is_address(self, text):
1914 for x in text.split():
1915 if not bitcoin.is_address(x):
1920 def is_private_key(self, text):
1921 for x in text.split():
1922 if not bitcoin.is_private_key(x):
1927 def from_seed(self, seed, storage):
1928 if is_old_seed(seed):
1930 elif is_new_seed(seed):
1936 def from_address(self, text, storage):
1937 w = Imported_Wallet(storage)
1938 for x in text.split():
1939 w.imported_keys[x] = ''
1940 w.storage.put('imported_keys', w.imported_keys, True)
1944 def from_private_key(self, text, storage):
1945 w = Imported_Wallet(storage)
1946 for x in text.split():
1947 w.import_key(x, None)
1951 def from_mpk(self, mpk, storage):
1960 w = OldWallet(storage)
1962 w.create_watching_only_wallet(mpk)
1964 w = NewWallet(storage)
1965 w.create_watching_only_wallet(mpk)