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/>.
33 from util import print_msg, print_error, format_satoshis
36 from transaction import Transaction
37 from plugins import run_hook
40 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
41 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
43 def pw_encode(s, password):
45 secret = Hash(password)
46 return EncodeAES(secret, s)
50 def pw_decode(s, password):
51 if password is not None:
52 secret = Hash(password)
54 d = DecodeAES(secret, s)
56 raise BaseException('Invalid password')
65 from version import ELECTRUM_VERSION, SEED_VERSION
70 def __init__(self, config):
71 self.lock = threading.Lock()
73 self.file_exists = False
74 self.init_path(config)
75 print_error( "wallet path", self.path )
80 def init_path(self, config):
81 """Set the path of the wallet."""
83 path = config.get('wallet_path')
85 path = config.get('default_wallet_path')
90 self.path = os.path.join(config.path, "electrum.dat")
94 """Read the contents of the wallet file."""
96 with open(self.path, "r") as f:
101 d = ast.literal_eval( data ) #parse raw data from reading wallet file
103 raise IOError("Cannot read wallet file.")
106 self.file_exists = True
109 def get(self, key, default=None):
110 return self.data.get(key, default)
112 def put(self, key, value, save = True):
115 if value is not None:
116 self.data[key] = value
124 f = open(self.path,"w")
127 if self.get('gui') != 'android':
129 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
134 def __init__(self, storage):
136 self.storage = storage
137 self.electrum_version = ELECTRUM_VERSION
138 self.gap_limit_for_change = 3 # constant
141 self.seed_version = storage.get('seed_version', SEED_VERSION)
143 self.gap_limit = storage.get('gap_limit', 5)
144 self.use_change = storage.get('use_change',True)
145 self.use_encryption = storage.get('use_encryption', False)
146 self.seed = storage.get('seed', '') # encrypted
147 self.labels = storage.get('labels', {})
148 self.frozen_addresses = storage.get('frozen_addresses',[])
149 self.prioritized_addresses = storage.get('prioritized_addresses',[])
150 self.addressbook = storage.get('contacts', [])
152 self.imported_keys = storage.get('imported_keys',{})
153 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
155 self.fee = int(storage.get('fee_per_kb',20000))
157 self.master_public_keys = storage.get('master_public_keys',{})
158 self.master_private_keys = storage.get('master_private_keys', {})
160 self.next_addresses = storage.get('next_addresses',{})
162 if self.seed_version < 4:
163 raise ValueError("This wallet seed is deprecated.")
167 self.transactions = {}
168 tx_list = self.storage.get('transactions',{})
169 for k,v in tx_list.items():
173 print_msg("Warning: Cannot deserialize transactions. skipping")
176 self.add_extra_addresses(tx)
177 self.transactions[k] = tx
179 for h,tx in self.transactions.items():
180 if not self.check_new_tx(h, tx):
181 print_error("removing unreferenced tx", h)
182 self.transactions.pop(h)
186 self.prevout_values = {} # my own transaction outputs
187 self.spent_outputs = []
192 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
193 # interface.is_up_to_date() returns true when all requests have been answered and processed
194 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
196 self.up_to_date = False
197 self.lock = threading.Lock()
198 self.transaction_lock = threading.Lock()
199 self.tx_event = threading.Event()
201 for tx_hash, tx in self.transactions.items():
202 self.update_tx_outputs(tx_hash)
205 def add_extra_addresses(self, tx):
207 # find the address corresponding to pay-to-pubkey inputs
208 tx.add_extra_addresses(self.transactions)
209 for o in tx.d.get('outputs'):
210 if o.get('is_pubkey'):
211 for tx2 in self.transactions.values():
212 tx2.add_extra_addresses({h:tx})
217 def set_up_to_date(self,b):
218 with self.lock: self.up_to_date = b
221 def is_up_to_date(self):
222 with self.lock: return self.up_to_date
226 self.up_to_date = False
227 while not self.is_up_to_date():
231 def import_key(self, sec, password):
233 seed = self.decode_seed(password)
235 address = address_from_private_key(sec)
237 raise BaseException('Invalid private key')
239 if self.is_mine(address):
240 raise BaseException('Address already in wallet')
242 # store the originally requested keypair into the imported keys table
243 self.imported_keys[address] = pw_encode(sec, password )
244 self.storage.put('imported_keys', self.imported_keys, True)
245 if self.synchronizer:
246 self.synchronizer.subscribe_to_addresses([address])
249 def delete_imported_key(self, addr):
250 if addr in self.imported_keys:
251 self.imported_keys.pop(addr)
252 self.storage.put('imported_keys', self.imported_keys, True)
255 def init_seed(self, seed):
256 if self.seed: raise BaseException("a seed exists")
258 seed = random_seed(128)
263 self.storage.put('seed', self.seed, True)
264 self.storage.put('seed_version', self.seed_version, True)
266 def create_watching_only_wallet(self, c0, K0):
268 self.master_public_keys = {
269 "m/0'/": (c0, K0, cK0),
271 self.storage.put('master_public_keys', self.master_public_keys, True)
272 self.create_account('1','Main account')
274 def create_accounts(self):
276 master_k, master_c, master_K, master_cK = bip32_init(self.seed)
279 k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/")
281 k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/")
282 k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/")
284 k3, c3, K3, cK3 = bip32_private_derivation(master_k, master_c, "m/", "m/3'/")
285 k4, c4, K4, cK4 = bip32_private_derivation(master_k, master_c, "m/", "m/4'/")
286 k5, c5, K5, cK5 = bip32_private_derivation(master_k, master_c, "m/", "m/5'/")
288 self.master_public_keys = {
289 "m/0'/": (c0, K0, cK0),
290 "m/1'/": (c1, K1, cK1),
291 "m/2'/": (c2, K2, cK2),
292 "m/3'/": (c3, K3, cK3),
293 "m/4'/": (c4, K4, cK4),
294 "m/5'/": (c5, K5, cK5)
297 self.master_private_keys = {
306 self.storage.put('master_public_keys', self.master_public_keys, True)
307 self.storage.put('master_private_keys', self.master_private_keys, True)
309 # create default account
310 self.create_account('1','Main account')
313 def find_root_by_master_key(self, c, K):
314 for key, v in self.master_public_keys.items():
315 if key == "m/":continue
317 if (c == cc) and (K == KK):
320 def deseed_root(self, seed, password):
321 # for safety, we ask the user to enter their seed
322 assert seed == self.decode_seed(password)
324 self.storage.put('seed', '', True)
327 def deseed_branch(self, k):
328 # check that parent has no seed
329 assert self.seed == ''
330 self.master_private_keys.pop(k)
331 self.storage.put('master_private_keys', self.master_private_keys, True)
334 def account_id(self, account_type, i):
335 if account_type == '1':
337 elif account_type == '2of2':
338 return "m/1'/%d & m/2'/%d"%(i,i)
339 elif account_type == '2of3':
340 return "m/3'/%d & m/4'/%d & m/5'/%d"%(i,i,i)
342 raise BaseException('unknown account type')
345 def num_accounts(self, account_type):
346 keys = self.accounts.keys()
349 account_id = self.account_id(account_type, i)
350 if account_id not in keys: break
355 def new_account_address(self, account_type = '1'):
356 i = self.num_accounts(account_type)
357 k = self.account_id(account_type,i)
359 addr = self.next_addresses.get(k)
361 account_id, account = self.next_account(account_type)
362 addr = account.first_address()
363 self.next_addresses[k] = addr
364 self.storage.put('next_addresses',self.next_addresses)
369 def next_account(self, account_type = '1'):
371 i = self.num_accounts(account_type)
372 account_id = self.account_id(account_type,i)
374 if account_type is '1':
375 master_c0, master_K0, _ = self.master_public_keys["m/0'/"]
376 c0, K0, cK0 = bip32_public_derivation(master_c0.decode('hex'), master_K0.decode('hex'), "m/0'/", "m/0'/%d"%i)
377 account = BIP32_Account({ 'c':c0, 'K':K0, 'cK':cK0 })
379 elif account_type == '2of2':
380 master_c1, master_K1, _ = self.master_public_keys["m/1'/"]
381 c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i)
382 master_c2, master_K2, _ = self.master_public_keys["m/2'/"]
383 c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i)
384 account = BIP32_Account_2of2({ 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 })
386 elif account_type == '2of3':
387 master_c3, master_K3, _ = self.master_public_keys["m/3'/"]
388 c3, K3, cK3 = bip32_public_derivation(master_c3.decode('hex'), master_K3.decode('hex'), "m/3'/", "m/3'/%d"%i)
389 master_c4, master_K4, _ = self.master_public_keys["m/4'/"]
390 c4, K4, cK4 = bip32_public_derivation(master_c4.decode('hex'), master_K4.decode('hex'), "m/4'/", "m/4'/%d"%i)
391 master_c5, master_K5, _ = self.master_public_keys["m/5'/"]
392 c5, K5, cK5 = bip32_public_derivation(master_c5.decode('hex'), master_K5.decode('hex'), "m/5'/", "m/5'/%d"%i)
393 account = BIP32_Account_2of3({ 'c':c3, 'K':K3, 'cK':cK3, 'c2':c4, 'K2':K4, 'cK2':cK4, 'c3':c5, 'K3':K5, 'cK3':cK5 })
395 return account_id, account
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)
418 def create_account(self, account_type = '1', name = None):
419 account_id, account = self.next_account(account_type)
420 self.accounts[account_id] = account
423 self.set_label(account_id, name)
426 def create_old_account(self):
427 mpk = OldAccount.mpk_from_seed(self.seed)
428 self.storage.put('master_public_key', mpk, True)
429 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
433 def save_accounts(self):
435 for k, v in self.accounts.items():
437 self.storage.put('accounts', d, True)
441 def load_accounts(self):
442 d = self.storage.get('accounts', {})
444 for k, v in d.items():
446 v['mpk'] = self.storage.get('master_public_key')
447 self.accounts[k] = OldAccount(v)
449 self.accounts[k] = BIP32_Account_2of2(v)
451 self.accounts[k] = BIP32_Account(v)
454 def addresses(self, include_change = True, next=False):
455 o = self.get_account_addresses(-1, include_change)
456 for a in self.accounts.keys():
457 o += self.get_account_addresses(a, include_change)
460 for addr in self.next_addresses.values():
466 def is_mine(self, address):
467 return address in self.addresses(True)
470 def is_change(self, address):
471 if not self.is_mine(address): return False
472 if address in self.imported_keys.keys(): return False
473 acct, s = self.get_address_index(address)
474 if s is None: return False
477 def get_master_public_key(self):
478 if self.seed_version == 4:
479 return self.storage.get("master_public_key")
481 c, K, cK = self.storage.get("master_public_keys")["m/0'/"]
484 def get_master_private_key(self, account, password):
485 master_k = pw_decode( self.master_private_keys[account], password)
486 master_c, master_K, master_Kc = self.master_public_keys[account]
488 K, Kc = get_pubkeys_from_secret(master_k.decode('hex'))
489 assert K.encode('hex') == master_K
491 raise BaseException("Invalid password")
495 def get_address_index(self, address):
496 if address in self.imported_keys.keys():
499 for account in self.accounts.keys():
500 for for_change in [0,1]:
501 addresses = self.accounts[account].get_addresses(for_change)
502 for addr in addresses:
504 return account, (for_change, addresses.index(addr))
506 raise BaseException("Address not found", address)
509 def get_roots(self, account):
511 for a in account.split('&'):
513 m = re.match("(m/\d+'/)(\d+)", s)
514 roots.append( m.group(1) )
517 def is_seeded(self, account):
518 if type(account) is int:
519 return self.seed is not None
521 for root in self.get_roots(account):
522 if root not in self.master_private_keys.keys():
526 def rebase_sequence(self, account, sequence):
529 for a in account.split('&'):
531 m = re.match("(m/\d+'/)(\d+)", s)
533 num = int(m.group(2))
534 dd.append( (root, [num,c,i] ) )
538 def get_keyID(self, account, sequence):
542 rs = self.rebase_sequence(account, sequence)
544 for root, public_sequence in rs:
545 c, K, _ = self.master_public_keys[root]
546 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
547 dd.append( 'bip32(%s,%s,%s)'%(c,K, s) )
551 def get_public_key(self, address):
552 account, sequence = self.get_address_index(address)
553 return self.accounts[account].get_pubkey( *sequence )
556 def decode_seed(self, password):
557 seed = pw_decode(self.seed, password)
558 #todo: #self.sequences[0].check_seed(seed)
562 def get_private_key(self, address, password):
564 if address in self.imported_keys.keys():
565 out.append( pw_decode( self.imported_keys[address], password ) )
567 account, sequence = self.get_address_index(address)
569 seed = self.decode_seed(password)
570 pk = self.accounts[account].get_private_key(seed, sequence)
574 # assert address == self.accounts[account].get_address(*sequence)
575 rs = self.rebase_sequence( account, sequence)
576 for root, public_sequence in rs:
578 if root not in self.master_private_keys.keys(): continue
579 master_k = self.get_master_private_key(root, password)
580 master_c, _, _ = self.master_public_keys[root]
581 pk = bip32_private_key( public_sequence, master_k.decode('hex'), master_c.decode('hex'))
587 def add_keypairs_from_wallet(self, tx, keypairs, password):
588 for txin in tx.inputs:
589 address = txin['address']
590 private_keys = self.get_private_key(address, password)
591 for sec in private_keys:
592 pubkey = public_key_from_private_key(sec)
593 keypairs[ pubkey ] = sec
596 def add_keypairs_from_KeyID(self, tx, keypairs, password):
597 for txin in tx.inputs:
598 keyid = txin.get('KeyID')
601 for s in keyid.split('&'):
602 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
606 sequence = m.group(3)
607 root = self.find_root_by_master_key(c,K)
608 if not root: continue
609 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
610 root = root + '%d'%sequence[0]
611 sequence = sequence[1:]
612 roots.append((root,sequence))
614 account_id = " & ".join( map(lambda x:x[0], roots) )
615 account = self.accounts.get(account_id)
616 if not account: continue
617 addr = account.get_address(*sequence)
618 txin['address'] = addr # fixme: side effect
619 pk = self.get_private_key(addr, password)
621 pubkey = public_key_from_private_key(sec)
622 keypairs[pubkey] = sec
626 def signrawtransaction(self, tx, input_info, private_keys, password):
628 # check that the password is correct
629 seed = self.decode_seed(password)
632 tx.add_input_info(input_info)
634 # add redeem script for coins that are in the wallet
635 # FIXME: add redeemPubkey too!
636 unspent_coins = self.get_unspent_coins()
637 for txin in tx.inputs:
638 for item in unspent_coins:
639 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
640 print_error( "tx input is in unspent coins" )
641 txin['scriptPubKey'] = item['scriptPubKey']
642 account, sequence = self.get_address_index(item['address'])
644 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
645 print_error("added redeemScript", txin['redeemScript'])
649 # build a list of public/private keys
652 # add private keys from parameter
653 for sec in private_keys:
654 pubkey = public_key_from_private_key(sec)
655 keypairs[ pubkey ] = sec
657 # add private_keys from KeyID
658 self.add_keypairs_from_KeyID(tx, keypairs, password)
660 # add private keys from wallet
661 self.add_keypairs_from_wallet(tx, keypairs, password)
662 self.sign_transaction(tx, keypairs)
665 def sign_message(self, address, message, password):
666 keys = self.get_private_key(address, password)
667 assert len(keys) == 1
669 key = regenerate_key(sec)
670 compressed = is_compressed(sec)
671 return key.sign_message(message, compressed, address)
673 def verify_message(self, address, signature, message):
675 EC_KEY.verify_message(address, signature, message)
677 except BaseException as e:
678 print_error("Verification error: {0}".format(e))
682 def change_gap_limit(self, value):
683 if value >= self.gap_limit:
684 self.gap_limit = value
685 self.storage.put('gap_limit', self.gap_limit, True)
686 #self.interface.poke('synchronizer')
689 elif value >= self.min_acceptable_gap():
690 for key, account in self.accounts.items():
691 addresses = account[0]
692 k = self.num_unused_trailing_addresses(addresses)
693 n = len(addresses) - k + value
694 addresses = addresses[0:n]
695 self.accounts[key][0] = addresses
697 self.gap_limit = value
698 self.storage.put('gap_limit', self.gap_limit, True)
704 def num_unused_trailing_addresses(self, addresses):
706 for a in addresses[::-1]:
707 if self.history.get(a):break
711 def min_acceptable_gap(self):
712 # fixme: this assumes wallet is synchronized
716 for account in self.accounts.values():
717 addresses = account.get_addresses(0)
718 k = self.num_unused_trailing_addresses(addresses)
719 for a in addresses[0:-k]:
720 if self.history.get(a):
724 if n > nmax: nmax = n
728 def address_is_old(self, address):
730 h = self.history.get(address, [])
733 for tx_hash, tx_height in h:
737 tx_age = self.verifier.blockchain.height - tx_height + 1
743 def synchronize_sequence(self, account, for_change):
744 limit = self.gap_limit_for_change if for_change else self.gap_limit
747 addresses = account.get_addresses(for_change)
748 if len(addresses) < limit:
749 address = account.create_new_address(for_change)
750 self.history[address] = []
751 new_addresses.append( address )
754 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
757 address = account.create_new_address(for_change)
758 self.history[address] = []
759 new_addresses.append( address )
765 def create_pending_accounts(self):
766 for account_type in ['1','2of2','2of3']:
767 a = self.new_account_address(account_type)
768 if self.address_is_old(a):
769 print_error( "creating account", a )
770 self.create_account(account_type)
773 def synchronize_account(self, account):
775 new += self.synchronize_sequence(account, 0)
776 new += self.synchronize_sequence(account, 1)
780 def synchronize(self):
781 if self.master_public_keys:
782 self.create_pending_accounts()
784 for account in self.accounts.values():
785 new += self.synchronize_account(account)
788 self.storage.put('addr_history', self.history, True)
793 return self.history.values() != [[]] * len(self.history)
796 def add_contact(self, address, label=None):
797 self.addressbook.append(address)
798 self.storage.put('contacts', self.addressbook, True)
800 self.set_label(address, label)
803 def delete_contact(self, addr):
804 if addr in self.addressbook:
805 self.addressbook.remove(addr)
806 self.storage.put('addressbook', self.addressbook, True)
809 def fill_addressbook(self):
810 for tx_hash, tx in self.transactions.items():
811 is_relevant, is_send, _, _ = self.get_tx_value(tx)
813 for addr, v in tx.outputs:
814 if not self.is_mine(addr) and addr not in self.addressbook:
815 self.addressbook.append(addr)
817 # self.update_tx_labels()
819 def get_num_tx(self, address):
821 for tx in self.transactions.values():
822 if address in map(lambda x:x[0], tx.outputs): n += 1
826 def get_address_flags(self, addr):
827 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
828 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
832 def get_tx_value(self, tx, account=None):
833 domain = self.get_account_addresses(account)
834 return tx.get_value(domain, self.prevout_values)
837 def update_tx_outputs(self, tx_hash):
838 tx = self.transactions.get(tx_hash)
840 for i, (addr, value) in enumerate(tx.outputs):
841 key = tx_hash+ ':%d'%i
842 self.prevout_values[key] = value
844 for item in tx.inputs:
845 if self.is_mine(item.get('address')):
846 key = item['prevout_hash'] + ':%d'%item['prevout_n']
847 self.spent_outputs.append(key)
850 def get_addr_balance(self, address):
851 assert self.is_mine(address)
852 h = self.history.get(address,[])
853 if h == ['*']: return 0,0
855 received_coins = [] # list of coins received at address
857 for tx_hash, tx_height in h:
858 tx = self.transactions.get(tx_hash)
861 for i, (addr, value) in enumerate(tx.outputs):
863 key = tx_hash + ':%d'%i
864 received_coins.append(key)
866 for tx_hash, tx_height in h:
867 tx = self.transactions.get(tx_hash)
871 for item in tx.inputs:
872 addr = item.get('address')
874 key = item['prevout_hash'] + ':%d'%item['prevout_n']
875 value = self.prevout_values.get( key )
876 if key in received_coins:
879 for i, (addr, value) in enumerate(tx.outputs):
880 key = tx_hash + ':%d'%i
891 def get_account_name(self, k):
893 if self.seed_version == 4:
894 name = 'Main account'
898 name = self.labels.get(k, 'Unnamed account')
901 def get_account_names(self):
903 for k, account in self.accounts.items():
904 accounts[k] = self.get_account_name(k)
905 if self.imported_keys:
906 accounts[-1] = 'Imported keys'
909 def get_account_addresses(self, a, include_change=True):
911 o = self.addresses(True)
913 o = self.imported_keys.keys()
915 ac = self.accounts[a]
916 o = ac.get_addresses(0)
917 if include_change: o += ac.get_addresses(1)
920 def get_imported_balance(self):
922 for addr in self.imported_keys.keys():
923 c, u = self.get_addr_balance(addr)
928 def get_account_balance(self, account):
930 return self.get_balance()
932 return self.get_imported_balance()
935 for addr in self.get_account_addresses(account):
936 c, u = self.get_addr_balance(addr)
941 def get_frozen_balance(self):
943 for addr in self.frozen_addresses:
944 c, u = self.get_addr_balance(addr)
950 def get_balance(self):
952 for a in self.accounts.keys():
953 c, u = self.get_account_balance(a)
956 c, u = self.get_imported_balance()
962 def get_unspent_coins(self, domain=None):
964 if domain is None: domain = self.addresses(True)
966 h = self.history.get(addr, [])
967 if h == ['*']: continue
968 for tx_hash, tx_height in h:
969 tx = self.transactions.get(tx_hash)
970 if tx is None: raise BaseException("Wallet not synchronized")
971 for output in tx.d.get('outputs'):
972 if output.get('address') != addr: continue
973 key = tx_hash + ":%d" % output.get('prevout_n')
974 if key in self.spent_outputs: continue
975 output['prevout_hash'] = tx_hash
976 output['height'] = tx_height
977 coins.append((tx_height, output))
981 coins = sorted(coins)
982 if coins[-1][0] != 0:
983 while coins[0][0] == 0:
984 coins = coins[1:] + [ coins[0] ]
985 return [x[1] for x in coins]
989 def choose_tx_inputs( self, amount, fixed_fee, domain = None ):
990 """ todo: minimize tx size """
992 fee = self.fee if fixed_fee is None else fixed_fee
994 domain = self.addresses()
996 for i in self.frozen_addresses:
997 if i in domain: domain.remove(i)
1000 for i in self.prioritized_addresses:
1003 prioritized.append(i)
1005 coins = self.get_unspent_coins(domain)
1006 prioritized_coins = self.get_unspent_coins(prioritized)
1009 coins = prioritized_coins + coins
1012 addr = item.get('address')
1013 v = item.get('value')
1016 fee = self.estimated_fee(inputs) if fixed_fee is None else fixed_fee
1017 if total >= amount + fee: break
1021 return inputs, total, fee
1024 def set_fee(self, fee):
1027 self.storage.put('fee_per_kb', self.fee, True)
1029 def estimated_fee(self, inputs):
1030 estimated_size = len(inputs) * 180 + 80 # this assumes non-compressed keys
1031 fee = self.fee * int(round(estimated_size/1024.))
1032 if fee == 0: fee = self.fee
1036 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1037 "add change to a transaction"
1038 change_amount = total - ( amount + fee )
1039 if change_amount != 0:
1042 # send change to one of the accounts involved in the tx
1043 address = inputs[0].get('address')
1044 account, _ = self.get_address_index(address)
1046 if not self.use_change or account == -1:
1047 change_addr = inputs[-1]['address']
1049 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1051 # Insert the change output at a random position in the outputs
1052 posn = random.randint(0, len(outputs))
1053 outputs[posn:posn] = [( change_addr, change_amount)]
1057 def get_history(self, address):
1059 return self.history.get(address)
1062 def get_status(self, h):
1063 if not h: return None
1064 if h == ['*']: return '*'
1066 for tx_hash, height in h:
1067 status += tx_hash + ':%d:' % height
1068 return hashlib.sha256( status ).digest().encode('hex')
1071 def receive_tx_callback(self, tx_hash, tx, tx_height):
1073 with self.transaction_lock:
1074 self.add_extra_addresses(tx)
1075 if not self.check_new_tx(tx_hash, tx):
1076 # may happen due to pruning
1077 print_error("received transaction that is no longer referenced in history", tx_hash)
1079 self.transactions[tx_hash] = tx
1080 self.network.interface.pending_transactions_for_notifications.append(tx)
1081 self.save_transactions()
1082 if self.verifier and tx_height>0:
1083 self.verifier.add(tx_hash, tx_height)
1084 self.update_tx_outputs(tx_hash)
1087 def save_transactions(self):
1089 for k,v in self.transactions.items():
1091 self.storage.put('transactions', tx, True)
1093 def receive_history_callback(self, addr, hist):
1095 if not self.check_new_history(addr, hist):
1096 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
1099 self.history[addr] = hist
1100 self.storage.put('addr_history', self.history, True)
1103 for tx_hash, tx_height in hist:
1105 # add it in case it was previously unconfirmed
1106 if self.verifier: self.verifier.add(tx_hash, tx_height)
1109 def get_tx_history(self, account=None):
1110 with self.transaction_lock:
1111 history = self.transactions.items()
1112 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1116 for tx_hash, tx in history:
1117 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1118 if v is not None: balance += v
1120 c, u = self.get_account_balance(account)
1123 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1125 balance = c + u - balance
1126 for tx_hash, tx in history:
1127 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1130 if value is not None:
1133 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1134 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1139 def get_label(self, tx_hash):
1140 label = self.labels.get(tx_hash)
1141 is_default = (label == '') or (label is None)
1142 if is_default: label = self.get_default_label(tx_hash)
1143 return label, is_default
1146 def get_default_label(self, tx_hash):
1147 tx = self.transactions.get(tx_hash)
1150 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1152 for o in tx.outputs:
1154 if not self.is_mine(o_addr):
1156 default_label = self.labels[o_addr]
1158 default_label = o_addr
1161 default_label = '(internal)'
1163 for o in tx.outputs:
1165 if self.is_mine(o_addr) and not self.is_change(o_addr):
1168 for o in tx.outputs:
1170 if self.is_mine(o_addr):
1176 dest_label = self.labels.get(o_addr)
1178 default_label = self.labels[o_addr]
1180 default_label = o_addr
1182 return default_label
1185 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1186 for address, x in outputs:
1187 assert is_valid(address)
1188 amount = sum( map(lambda x:x[1], outputs) )
1189 inputs, total, fee = self.choose_tx_inputs( amount, fee, domain )
1191 raise ValueError("Not enough funds")
1192 self.add_input_info(inputs)
1193 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1194 return Transaction.from_io(inputs, outputs)
1197 def mktx_from_account(self, outputs, password, fee=None, change_addr=None, account=None):
1198 domain = self.get_account_addresses(account) if account else None
1199 return self.mktx(outputs, password, fee, change_addr, domain)
1202 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1203 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1205 self.add_keypairs_from_wallet(tx, keypairs, password)
1206 self.sign_transaction(tx, keypairs)
1210 def add_input_info(self, inputs):
1212 address = txin['address']
1213 account, sequence = self.get_address_index(address)
1214 txin['KeyID'] = self.get_keyID(account, sequence)
1215 redeemScript = self.accounts[account].redeem_script(sequence)
1217 txin['redeemScript'] = redeemScript
1219 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1222 def sign_transaction(self, tx, keypairs):
1224 run_hook('sign_transaction', tx)
1227 def sendtx(self, tx):
1229 h = self.send_tx(tx)
1230 self.tx_event.wait()
1231 return self.receive_tx(h)
1233 def send_tx(self, tx):
1235 self.tx_event.clear()
1236 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1239 def on_broadcast(self, i, r):
1240 self.tx_result = r.get('result')
1243 def receive_tx(self,tx_hash):
1244 out = self.tx_result
1246 return False, "error: " + out
1251 def update_password(self, seed, old_password, new_password):
1252 if new_password == '': new_password = None
1253 # this will throw an exception if unicode cannot be converted
1254 self.seed = pw_encode( seed, new_password)
1255 self.storage.put('seed', self.seed, True)
1256 self.use_encryption = (new_password != None)
1257 self.storage.put('use_encryption', self.use_encryption,True)
1258 for k in self.imported_keys.keys():
1259 a = self.imported_keys[k]
1260 b = pw_decode(a, old_password)
1261 c = pw_encode(b, new_password)
1262 self.imported_keys[k] = c
1263 self.storage.put('imported_keys', self.imported_keys, True)
1265 for k, v in self.master_private_keys.items():
1266 b = pw_decode(v, old_password)
1267 c = pw_encode(b, new_password)
1268 self.master_private_keys[k] = c
1269 self.storage.put('master_private_keys', self.master_private_keys, True)
1272 def freeze(self,addr):
1273 if self.is_mine(addr) and addr not in self.frozen_addresses:
1274 self.unprioritize(addr)
1275 self.frozen_addresses.append(addr)
1276 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1281 def unfreeze(self,addr):
1282 if self.is_mine(addr) and addr in self.frozen_addresses:
1283 self.frozen_addresses.remove(addr)
1284 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1289 def prioritize(self,addr):
1290 if self.is_mine(addr) and addr not in self.prioritized_addresses:
1292 self.prioritized_addresses.append(addr)
1293 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1298 def unprioritize(self,addr):
1299 if self.is_mine(addr) and addr in self.prioritized_addresses:
1300 self.prioritized_addresses.remove(addr)
1301 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1307 def set_verifier(self, verifier):
1308 self.verifier = verifier
1310 # review transactions that are in the history
1311 for addr, hist in self.history.items():
1312 if hist == ['*']: continue
1313 for tx_hash, tx_height in hist:
1315 # add it in case it was previously unconfirmed
1316 self.verifier.add(tx_hash, tx_height)
1319 # if we are on a pruning server, remove unverified transactions
1320 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1321 for tx_hash in self.transactions.keys():
1322 if tx_hash not in vr:
1323 self.transactions.pop(tx_hash)
1327 def check_new_history(self, addr, hist):
1329 # check that all tx in hist are relevant
1331 for tx_hash, height in hist:
1332 tx = self.transactions.get(tx_hash)
1334 if not tx.has_address(addr):
1337 # check that we are not "orphaning" a transaction
1338 old_hist = self.history.get(addr,[])
1339 if old_hist == ['*']: return True
1341 for tx_hash, height in old_hist:
1342 if tx_hash in map(lambda x:x[0], hist): continue
1344 for _addr, _hist in self.history.items():
1345 if _addr == addr: continue
1346 if _hist == ['*']: continue
1347 _tx_hist = map(lambda x:x[0], _hist)
1348 if tx_hash in _tx_hist:
1353 tx = self.transactions.get(tx_hash)
1354 # tx might not be there
1358 if self.verifier.get_height(tx_hash):
1361 print_error("new history is orphaning transaction:", tx_hash)
1362 # check that all outputs are not mine, request histories
1364 for _addr, _v in tx.outputs:
1365 # assert not self.is_mine(_addr)
1366 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1368 ext_h = self.network.interface.synchronous_get(ext_requests)
1369 print_error("sync:", ext_requests, ext_h)
1372 if h == ['*']: continue
1374 if item.get('tx_hash') == tx_hash:
1375 height = item.get('height')
1377 print_error("found height for", tx_hash, height)
1378 self.verifier.add(tx_hash, height)
1380 print_error("removing orphaned tx from history", tx_hash)
1381 self.transactions.pop(tx_hash)
1387 def check_new_tx(self, tx_hash, tx):
1388 # 1 check that tx is referenced in addr_history.
1390 for addr, hist in self.history.items():
1391 if hist == ['*']:continue
1392 for txh, height in hist:
1394 addresses.append(addr)
1399 # 2 check that referencing addresses are in the tx
1400 for addr in addresses:
1401 if not tx.has_address(addr):
1407 def start_threads(self, network):
1408 from verifier import TxVerifier
1409 self.network = network
1410 self.verifier = TxVerifier(self.network, self.storage)
1411 self.verifier.start()
1412 self.set_verifier(self.verifier)
1413 self.synchronizer = WalletSynchronizer(self)
1414 self.synchronizer.start()
1416 def stop_threads(self):
1417 self.verifier.stop()
1418 self.synchronizer.stop()
1422 def restore(self, callback):
1424 def wait_for_wallet():
1425 self.set_up_to_date(False)
1426 while not self.is_up_to_date():
1427 msg = "%s\n%s %d\n%s %.1f"%(
1428 _("Please wait..."),
1429 _("Addresses generated:"),
1430 len(self.addresses(True)),_("Kilobytes received:"),
1431 self.network.interface.bytes_received/1024.)
1433 apply(callback, (msg,))
1436 def wait_for_network():
1437 while not self.network.interface.is_connected:
1438 msg = "%s \n" % (_("Connecting..."))
1439 apply(callback, (msg,))
1442 # wait until we are connected, because the user might have selected another server
1445 # try to restore old account
1446 self.create_old_account()
1450 self.seed_version = 4
1451 self.storage.put('seed_version', wallet.seed_version, True)
1453 self.accounts.pop(0)
1454 self.create_accounts()
1460 class WalletSynchronizer(threading.Thread):
1463 def __init__(self, wallet):
1464 threading.Thread.__init__(self)
1466 self.wallet = wallet
1467 wallet.synchronizer = self
1468 self.network = self.wallet.network
1469 #self.wallet.network.register_callback('connected', lambda: self.wallet.set_up_to_date(False))
1470 self.was_updated = True
1471 self.running = False
1472 self.lock = threading.Lock()
1473 self.queue = Queue.Queue()
1476 with self.lock: self.running = False
1478 def is_running(self):
1479 with self.lock: return self.running
1482 def subscribe_to_addresses(self, addresses):
1484 for addr in addresses:
1485 messages.append(('blockchain.address.subscribe', [addr]))
1486 self.network.interface.send( messages, lambda i,r: self.queue.put(r))
1493 while self.is_running():
1494 interface = self.network.interface
1495 if not interface.is_connected:
1496 print_error("synchronizer: waiting for interface")
1497 interface.connect_event.wait()
1499 self.run_interface(interface)
1502 def run_interface(self, interface):
1504 print_error("synchronizer: connected to", interface.server)
1508 requested_histories = {}
1510 # request any missing transactions
1511 for history in self.wallet.history.values():
1512 if history == ['*']: continue
1513 for tx_hash, tx_height in history:
1514 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1515 missing_tx.append( (tx_hash, tx_height) )
1518 print_error("missing tx", missing_tx)
1521 self.subscribe_to_addresses(self.wallet.addresses(True, next=True))
1523 while self.is_running():
1524 # 1. create new addresses
1525 new_addresses = self.wallet.synchronize()
1527 # request missing addresses
1529 self.subscribe_to_addresses(new_addresses)
1531 # request missing transactions
1532 for tx_hash, tx_height in missing_tx:
1533 if (tx_hash, tx_height) not in requested_tx:
1534 interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1535 requested_tx.append( (tx_hash, tx_height) )
1538 # detect if situation has changed
1539 if interface.is_up_to_date() and self.queue.empty():
1540 if not self.wallet.is_up_to_date():
1541 self.wallet.set_up_to_date(True)
1542 self.was_updated = True
1544 if self.wallet.is_up_to_date():
1545 self.wallet.set_up_to_date(False)
1546 self.was_updated = True
1548 if self.was_updated:
1549 self.wallet.network.trigger_callback('updated')
1550 self.was_updated = False
1554 r = self.queue.get(block=True, timeout=1)
1558 if interface != self.network.interface:
1564 # 3. handle response
1565 method = r['method']
1566 params = r['params']
1567 result = r.get('result')
1568 error = r.get('error')
1573 if method == 'blockchain.address.subscribe':
1575 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1576 if requested_histories.get(addr) is None:
1577 interface.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1578 requested_histories[addr] = result
1580 elif method == 'blockchain.address.get_history':
1582 print_error("receiving history", addr, result)
1584 assert requested_histories.pop(addr) == '*'
1585 self.wallet.receive_history_callback(addr, result)
1588 # check that txids are unique
1591 tx_hash = item['tx_hash']
1592 if tx_hash not in txids:
1593 txids.append(tx_hash)
1594 hist.append( (tx_hash, item['height']) )
1596 if len(hist) != len(result):
1597 raise BaseException("error: server sent history with non-unique txid", result)
1599 # check that the status corresponds to what was announced
1600 rs = requested_histories.pop(addr)
1601 if self.wallet.get_status(hist) != rs:
1602 raise BaseException("error: status mismatch: %s"%addr)
1604 # store received history
1605 self.wallet.receive_history_callback(addr, hist)
1607 # request transactions that we don't have
1608 for tx_hash, tx_height in hist:
1609 if self.wallet.transactions.get(tx_hash) is None:
1610 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1611 missing_tx.append( (tx_hash, tx_height) )
1613 elif method == 'blockchain.transaction.get':
1615 tx_height = params[1]
1616 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1617 tx = Transaction(result)
1618 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1619 self.was_updated = True
1620 requested_tx.remove( (tx_hash, tx_height) )
1621 print_error("received tx:", tx_hash, len(tx.raw))
1624 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1626 if self.was_updated and not requested_tx:
1627 self.wallet.network.trigger_callback('updated')
1628 self.wallet.network.trigger_callback("new_transaction") # Updated gets called too many times from other places as well; if we use that signal we get the notification three times
1630 self.was_updated = False