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
39 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
40 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
42 def pw_encode(s, password):
44 secret = Hash(password)
45 return EncodeAES(secret, s)
49 def pw_decode(s, password):
50 if password is not None:
51 secret = Hash(password)
53 d = DecodeAES(secret, s)
55 raise BaseException('Invalid password')
64 from version import ELECTRUM_VERSION, SEED_VERSION
69 def __init__(self, config):
71 self.file_exists = False
72 self.init_path(config)
73 print_error( "wallet path", self.path )
78 def init_path(self, config):
79 """Set the path of the wallet."""
81 path = config.get('wallet_path')
83 path = config.get('default_wallet_path')
88 self.path = os.path.join(config.path, "electrum.dat")
92 """Read the contents of the wallet file."""
94 with open(self.path, "r") as f:
99 d = ast.literal_eval( data ) #parse raw data from reading wallet file
101 raise IOError("Cannot read wallet file.")
104 self.file_exists = True
107 def get(self, key, default=None):
108 return self.data.get(key, default)
110 def put(self, key, value, save = True):
112 if self.data.get(key) is not None:
113 self.data[key] = value
115 # add key to wallet config
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, key, value):
399 self.labels[key] = value
400 self.storage.put('labels', self.labels, True)
403 def create_account(self, account_type = '1', name = None):
404 account_id, account = self.next_account(account_type)
405 self.accounts[account_id] = account
408 self.set_label(account_id, name)
411 def create_old_account(self):
412 mpk = OldAccount.mpk_from_seed(self.seed)
413 self.storage.put('master_public_key', mpk, True)
414 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
418 def save_accounts(self):
420 for k, v in self.accounts.items():
422 self.storage.put('accounts', d, True)
426 def load_accounts(self):
427 d = self.storage.get('accounts', {})
429 for k, v in d.items():
431 v['mpk'] = self.storage.get('master_public_key')
432 self.accounts[k] = OldAccount(v)
434 self.accounts[k] = BIP32_Account_2of2(v)
436 self.accounts[k] = BIP32_Account(v)
439 def addresses(self, include_change = True, next=False):
440 o = self.get_account_addresses(-1, include_change)
441 for a in self.accounts.keys():
442 o += self.get_account_addresses(a, include_change)
445 for addr in self.next_addresses.values():
451 def is_mine(self, address):
452 return address in self.addresses(True)
455 def is_change(self, address):
456 if not self.is_mine(address): return False
457 if address in self.imported_keys.keys(): return False
458 acct, s = self.get_address_index(address)
459 if s is None: return False
462 def get_master_public_key(self):
463 if self.seed_version == 4:
464 return self.storage.get("master_public_key")
466 c, K, cK = self.storage.get("master_public_keys")["m/0'/"]
469 def get_master_private_key(self, account, password):
470 master_k = pw_decode( self.master_private_keys[account], password)
471 master_c, master_K, master_Kc = self.master_public_keys[account]
473 K, Kc = get_pubkeys_from_secret(master_k.decode('hex'))
474 assert K.encode('hex') == master_K
476 raise BaseException("Invalid password")
480 def get_address_index(self, address):
481 if address in self.imported_keys.keys():
484 for account in self.accounts.keys():
485 for for_change in [0,1]:
486 addresses = self.accounts[account].get_addresses(for_change)
487 for addr in addresses:
489 return account, (for_change, addresses.index(addr))
491 raise BaseException("Address not found", address)
494 def get_roots(self, account):
496 for a in account.split('&'):
498 m = re.match("(m/\d+'/)(\d+)", s)
499 roots.append( m.group(1) )
502 def is_seeded(self, account):
503 if type(account) is int:
504 return self.seed is not None
506 for root in self.get_roots(account):
507 if root not in self.master_private_keys.keys():
511 def rebase_sequence(self, account, sequence):
514 for a in account.split('&'):
516 m = re.match("(m/\d+'/)(\d+)", s)
518 num = int(m.group(2))
519 dd.append( (root, [num,c,i] ) )
523 def get_keyID(self, account, sequence):
527 rs = self.rebase_sequence(account, sequence)
529 for root, public_sequence in rs:
530 c, K, _ = self.master_public_keys[root]
531 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
532 dd.append( 'bip32(%s,%s,%s)'%(c,K, s) )
536 def get_public_key(self, address):
537 account, sequence = self.get_address_index(address)
538 return self.accounts[account].get_pubkey( *sequence )
541 def decode_seed(self, password):
542 seed = pw_decode(self.seed, password)
543 #todo: #self.sequences[0].check_seed(seed)
547 def get_private_key(self, address, password):
549 if address in self.imported_keys.keys():
550 out.append( pw_decode( self.imported_keys[address], password ) )
552 account, sequence = self.get_address_index(address)
554 seed = self.decode_seed(password)
555 pk = self.accounts[account].get_private_key(seed, sequence)
559 # assert address == self.accounts[account].get_address(*sequence)
560 rs = self.rebase_sequence( account, sequence)
561 for root, public_sequence in rs:
563 if root not in self.master_private_keys.keys(): continue
564 master_k = self.get_master_private_key(root, password)
565 master_c, _, _ = self.master_public_keys[root]
566 pk = bip32_private_key( public_sequence, master_k.decode('hex'), master_c.decode('hex'))
574 def signrawtransaction(self, tx, input_info, private_keys, password):
576 unspent_coins = self.get_unspent_coins()
577 seed = self.decode_seed(password)
579 # build a list of public/private keys
581 for sec in private_keys:
582 pubkey = public_key_from_private_key(sec)
583 keypairs[ pubkey ] = sec
586 for txin in tx.inputs:
587 # convert to own format
588 txin['tx_hash'] = txin['prevout_hash']
589 txin['index'] = txin['prevout_n']
591 for item in input_info:
592 if item.get('txid') == txin['tx_hash'] and item.get('vout') == txin['index']:
593 txin['raw_output_script'] = item['scriptPubKey']
594 txin['redeemScript'] = item.get('redeemScript')
595 txin['KeyID'] = item.get('KeyID')
598 for item in unspent_coins:
599 if txin['tx_hash'] == item['tx_hash'] and txin['index'] == item['index']:
600 print_error( "tx input is in unspent coins" )
601 txin['raw_output_script'] = item['raw_output_script']
602 account, sequence = self.get_address_index(item['address'])
604 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
607 raise BaseException("Unknown transaction input. Please provide the 'input_info' parameter, or synchronize this wallet")
609 # if available, derive private_keys from KeyID
610 keyid = txin.get('KeyID')
613 for s in keyid.split('&'):
614 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
618 sequence = m.group(3)
619 root = self.find_root_by_master_key(c,K)
620 if not root: continue
621 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
622 root = root + '%d'%sequence[0]
623 sequence = sequence[1:]
624 roots.append((root,sequence))
626 account_id = " & ".join( map(lambda x:x[0], roots) )
627 account = self.accounts.get(account_id)
628 if not account: continue
629 addr = account.get_address(*sequence)
630 txin['address'] = addr
631 pk = self.get_private_key(addr, password)
633 pubkey = public_key_from_private_key(sec)
634 keypairs[pubkey] = sec
636 redeem_script = txin.get("redeemScript")
637 print_error( "p2sh:", "yes" if redeem_script else "no")
639 addr = hash_160_to_bc_address(hash_160(redeem_script.decode('hex')), 5)
642 _, addr = transaction.get_address_from_output_script(txin["raw_output_script"].decode('hex'))
643 txin['address'] = addr
645 # add private keys that are in the wallet
646 pk = self.get_private_key(addr, password)
648 pubkey = public_key_from_private_key(sec)
649 keypairs[pubkey] = sec
650 if not redeem_script:
651 txin['redeemPubkey'] = pubkey
657 def sign_message(self, address, message, password):
658 keys = self.get_private_key(address, password)
659 assert len(keys) == 1
661 key = regenerate_key(sec)
662 compressed = is_compressed(sec)
663 return key.sign_message(message, compressed, address)
665 def verify_message(self, address, signature, message):
667 EC_KEY.verify_message(address, signature, message)
669 except BaseException as e:
670 print_error("Verification error: {0}".format(e))
674 def change_gap_limit(self, value):
675 if value >= self.gap_limit:
676 self.gap_limit = value
677 self.storage.put('gap_limit', self.gap_limit, True)
678 #self.interface.poke('synchronizer')
681 elif value >= self.min_acceptable_gap():
682 for key, account in self.accounts.items():
683 addresses = account[0]
684 k = self.num_unused_trailing_addresses(addresses)
685 n = len(addresses) - k + value
686 addresses = addresses[0:n]
687 self.accounts[key][0] = addresses
689 self.gap_limit = value
690 self.storage.put('gap_limit', self.gap_limit, True)
696 def num_unused_trailing_addresses(self, addresses):
698 for a in addresses[::-1]:
699 if self.history.get(a):break
703 def min_acceptable_gap(self):
704 # fixme: this assumes wallet is synchronized
708 for account in self.accounts.values():
709 addresses = account.get_addresses(0)
710 k = self.num_unused_trailing_addresses(addresses)
711 for a in addresses[0:-k]:
712 if self.history.get(a):
716 if n > nmax: nmax = n
720 def address_is_old(self, address):
722 h = self.history.get(address, [])
725 for tx_hash, tx_height in h:
729 tx_age = self.verifier.blockchain.height - tx_height + 1
735 def synchronize_sequence(self, account, for_change):
736 limit = self.gap_limit_for_change if for_change else self.gap_limit
739 addresses = account.get_addresses(for_change)
740 if len(addresses) < limit:
741 address = account.create_new_address(for_change)
742 self.history[address] = []
743 new_addresses.append( address )
746 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
749 address = account.create_new_address(for_change)
750 self.history[address] = []
751 new_addresses.append( address )
757 def create_pending_accounts(self):
758 for account_type in ['1','2of2','2of3']:
759 a = self.new_account_address(account_type)
760 if self.address_is_old(a):
761 print_error( "creating account", a )
762 self.create_account(account_type)
765 def synchronize_account(self, account):
767 new += self.synchronize_sequence(account, 0)
768 new += self.synchronize_sequence(account, 1)
772 def synchronize(self):
773 if self.master_public_keys:
774 self.create_pending_accounts()
776 for account in self.accounts.values():
777 new += self.synchronize_account(account)
780 self.storage.put('addr_history', self.history, True)
785 return self.history.values() != [[]] * len(self.history)
788 def add_contact(self, address, label=None):
789 self.addressbook.append(address)
790 self.storage.put('contacts', self.addressbook, True)
792 self.set_label(address, label)
795 def delete_contact(self, addr):
796 if addr in self.addressbook:
797 self.addressbook.remove(addr)
798 self.storage.put('addressbook', self.addressbook, True)
801 def fill_addressbook(self):
802 for tx_hash, tx in self.transactions.items():
803 is_relevant, is_send, _, _ = self.get_tx_value(tx)
805 for addr, v in tx.outputs:
806 if not self.is_mine(addr) and addr not in self.addressbook:
807 self.addressbook.append(addr)
809 # self.update_tx_labels()
811 def get_num_tx(self, address):
813 for tx in self.transactions.values():
814 if address in map(lambda x:x[0], tx.outputs): n += 1
818 def get_address_flags(self, addr):
819 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
820 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
824 def get_tx_value(self, tx, account=None):
825 domain = self.get_account_addresses(account)
826 return tx.get_value(domain, self.prevout_values)
829 def update_tx_outputs(self, tx_hash):
830 tx = self.transactions.get(tx_hash)
832 for i, (addr, value) in enumerate(tx.outputs):
833 key = tx_hash+ ':%d'%i
834 self.prevout_values[key] = value
836 for item in tx.inputs:
837 if self.is_mine(item.get('address')):
838 key = item['prevout_hash'] + ':%d'%item['prevout_n']
839 self.spent_outputs.append(key)
842 def get_addr_balance(self, address):
843 assert self.is_mine(address)
844 h = self.history.get(address,[])
845 if h == ['*']: return 0,0
847 received_coins = [] # list of coins received at address
849 for tx_hash, tx_height in h:
850 tx = self.transactions.get(tx_hash)
853 for i, (addr, value) in enumerate(tx.outputs):
855 key = tx_hash + ':%d'%i
856 received_coins.append(key)
858 for tx_hash, tx_height in h:
859 tx = self.transactions.get(tx_hash)
863 for item in tx.inputs:
864 addr = item.get('address')
866 key = item['prevout_hash'] + ':%d'%item['prevout_n']
867 value = self.prevout_values.get( key )
868 if key in received_coins:
871 for i, (addr, value) in enumerate(tx.outputs):
872 key = tx_hash + ':%d'%i
883 def get_account_name(self, k):
885 if self.seed_version == 4:
886 name = 'Main account'
890 name = self.labels.get(k, 'Unnamed account')
893 def get_account_names(self):
895 for k, account in self.accounts.items():
896 accounts[k] = self.get_account_name(k)
897 if self.imported_keys:
898 accounts[-1] = 'Imported keys'
901 def get_account_addresses(self, a, include_change=True):
903 o = self.addresses(True)
905 o = self.imported_keys.keys()
907 ac = self.accounts[a]
908 o = ac.get_addresses(0)
909 if include_change: o += ac.get_addresses(1)
912 def get_imported_balance(self):
914 for addr in self.imported_keys.keys():
915 c, u = self.get_addr_balance(addr)
920 def get_account_balance(self, account):
922 return self.get_balance()
924 return self.get_imported_balance()
927 for addr in self.get_account_addresses(account):
928 c, u = self.get_addr_balance(addr)
933 def get_frozen_balance(self):
935 for addr in self.frozen_addresses:
936 c, u = self.get_addr_balance(addr)
942 def get_balance(self):
944 for a in self.accounts.keys():
945 c, u = self.get_account_balance(a)
948 c, u = self.get_imported_balance()
954 def get_unspent_coins(self, domain=None):
956 if domain is None: domain = self.addresses(True)
958 h = self.history.get(addr, [])
959 if h == ['*']: continue
960 for tx_hash, tx_height in h:
961 tx = self.transactions.get(tx_hash)
962 if tx is None: raise BaseException("Wallet not synchronized")
963 for output in tx.d.get('outputs'):
964 if output.get('address') != addr: continue
965 key = tx_hash + ":%d" % output.get('index')
966 if key in self.spent_outputs: continue
967 output['tx_hash'] = tx_hash
968 output['height'] = tx_height
969 coins.append((tx_height, output))
973 coins = sorted(coins)
974 if coins[-1][0] != 0:
975 while coins[0][0] == 0:
976 coins = coins[1:] + [ coins[0] ]
977 return [x[1] for x in coins]
981 def choose_tx_inputs( self, amount, fixed_fee, domain = None ):
982 """ todo: minimize tx size """
984 fee = self.fee if fixed_fee is None else fixed_fee
986 domain = self.addresses()
988 for i in self.frozen_addresses:
989 if i in domain: domain.remove(i)
992 for i in self.prioritized_addresses:
995 prioritized.append(i)
997 coins = self.get_unspent_coins(domain)
998 prioritized_coins = self.get_unspent_coins(prioritized)
1001 coins = prioritized_coins + coins
1004 addr = item.get('address')
1005 v = item.get('value')
1007 inputs.append( item )
1008 fee = self.estimated_fee(inputs) if fixed_fee is None else fixed_fee
1009 if total >= amount + fee: break
1013 return inputs, total, fee
1016 def set_fee(self, fee):
1019 self.storage.put('fee_per_kb', self.fee, True)
1021 def estimated_fee(self, inputs):
1022 estimated_size = len(inputs) * 180 + 80 # this assumes non-compressed keys
1023 fee = self.fee * int(round(estimated_size/1024.))
1024 if fee == 0: fee = self.fee
1028 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1029 "add change to a transaction"
1030 change_amount = total - ( amount + fee )
1031 if change_amount != 0:
1034 # send change to one of the accounts involved in the tx
1035 address = inputs[0].get('address')
1036 account, _ = self.get_address_index(address)
1038 if not self.use_change or account == -1:
1039 change_addr = inputs[-1]['address']
1041 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1043 # Insert the change output at a random position in the outputs
1044 posn = random.randint(0, len(outputs))
1045 outputs[posn:posn] = [( change_addr, change_amount)]
1049 def get_history(self, address):
1051 return self.history.get(address)
1054 def get_status(self, h):
1055 if not h: return None
1056 if h == ['*']: return '*'
1058 for tx_hash, height in h:
1059 status += tx_hash + ':%d:' % height
1060 return hashlib.sha256( status ).digest().encode('hex')
1063 def receive_tx_callback(self, tx_hash, tx, tx_height):
1065 with self.transaction_lock:
1066 self.add_extra_addresses(tx)
1067 if not self.check_new_tx(tx_hash, tx):
1068 # may happen due to pruning
1069 print_error("received transaction that is no longer referenced in history", tx_hash)
1071 self.transactions[tx_hash] = tx
1072 self.network.interface.pending_transactions_for_notifications.append(tx)
1073 self.save_transactions()
1074 if self.verifier and tx_height>0:
1075 self.verifier.add(tx_hash, tx_height)
1076 self.update_tx_outputs(tx_hash)
1079 def save_transactions(self):
1081 for k,v in self.transactions.items():
1083 self.storage.put('transactions', tx, True)
1085 def receive_history_callback(self, addr, hist):
1087 if not self.check_new_history(addr, hist):
1088 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
1091 self.history[addr] = hist
1092 self.storage.put('addr_history', self.history, True)
1095 for tx_hash, tx_height in hist:
1097 # add it in case it was previously unconfirmed
1098 if self.verifier: self.verifier.add(tx_hash, tx_height)
1101 def get_tx_history(self, account=None):
1102 with self.transaction_lock:
1103 history = self.transactions.items()
1104 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1108 for tx_hash, tx in history:
1109 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1110 if v is not None: balance += v
1112 c, u = self.get_account_balance(account)
1115 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1117 balance = c + u - balance
1118 for tx_hash, tx in history:
1119 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1122 if value is not None:
1125 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1126 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1131 def get_label(self, tx_hash):
1132 label = self.labels.get(tx_hash)
1133 is_default = (label == '') or (label is None)
1134 if is_default: label = self.get_default_label(tx_hash)
1135 return label, is_default
1138 def get_default_label(self, tx_hash):
1139 tx = self.transactions.get(tx_hash)
1142 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1144 for o in tx.outputs:
1146 if not self.is_mine(o_addr):
1148 default_label = self.labels[o_addr]
1150 default_label = o_addr
1153 default_label = '(internal)'
1155 for o in tx.outputs:
1157 if self.is_mine(o_addr) and not self.is_change(o_addr):
1160 for o in tx.outputs:
1162 if self.is_mine(o_addr):
1168 dest_label = self.labels.get(o_addr)
1170 default_label = self.labels[o_addr]
1172 default_label = o_addr
1174 return default_label
1177 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1178 for address, x in outputs:
1179 assert is_valid(address)
1180 amount = sum( map(lambda x:x[1], outputs) )
1181 inputs, total, fee = self.choose_tx_inputs( amount, fee, domain )
1183 raise ValueError("Not enough funds")
1184 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1185 return Transaction.from_io(inputs, outputs)
1188 def mktx_from_account(self, outputs, password, fee=None, change_addr=None, account=None):
1189 domain = self.get_account_addresses(account) if account else None
1190 return self.mktx(outputs, password, fee, change_addr, domain)
1193 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1194 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1195 self.sign_transaction(tx, password)
1199 def sign_transaction(self, tx, password):
1201 for i, txin in enumerate(tx.inputs):
1202 address = txin['address']
1203 account, sequence = self.get_address_index(address)
1204 txin['KeyID'] = self.get_keyID(account, sequence)
1205 redeemScript = self.accounts[account].redeem_script(sequence)
1207 txin['redeemScript'] = redeemScript
1209 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1210 private_keys = self.get_private_key(address, password)
1211 for sec in private_keys:
1212 pubkey = public_key_from_private_key(sec)
1213 keypairs[ pubkey ] = sec
1217 def sendtx(self, tx):
1219 h = self.send_tx(tx)
1220 self.tx_event.wait()
1221 return self.receive_tx(h)
1223 def send_tx(self, tx):
1225 self.tx_event.clear()
1226 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1229 def on_broadcast(self, i, r):
1230 self.tx_result = r.get('result')
1233 def receive_tx(self,tx_hash):
1234 out = self.tx_result
1236 return False, "error: " + out
1241 def update_password(self, seed, old_password, new_password):
1242 if new_password == '': new_password = None
1243 # this will throw an exception if unicode cannot be converted
1244 self.seed = pw_encode( seed, new_password)
1245 self.storage.put('seed', self.seed, True)
1246 self.use_encryption = (new_password != None)
1247 self.storage.put('use_encryption', self.use_encryption,True)
1248 for k in self.imported_keys.keys():
1249 a = self.imported_keys[k]
1250 b = pw_decode(a, old_password)
1251 c = pw_encode(b, new_password)
1252 self.imported_keys[k] = c
1253 self.storage.put('imported_keys', self.imported_keys, True)
1255 for k, v in self.master_private_keys.items():
1256 b = pw_decode(v, old_password)
1257 c = pw_encode(b, new_password)
1258 self.master_private_keys[k] = c
1259 self.storage.put('master_private_keys', self.master_private_keys, True)
1262 def freeze(self,addr):
1263 if self.is_mine(addr) and addr not in self.frozen_addresses:
1264 self.unprioritize(addr)
1265 self.frozen_addresses.append(addr)
1266 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1271 def unfreeze(self,addr):
1272 if self.is_mine(addr) and addr in self.frozen_addresses:
1273 self.frozen_addresses.remove(addr)
1274 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1279 def prioritize(self,addr):
1280 if self.is_mine(addr) and addr not in self.prioritized_addresses:
1282 self.prioritized_addresses.append(addr)
1283 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1288 def unprioritize(self,addr):
1289 if self.is_mine(addr) and addr in self.prioritized_addresses:
1290 self.prioritized_addresses.remove(addr)
1291 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1297 def set_verifier(self, verifier):
1298 self.verifier = verifier
1300 # review transactions that are in the history
1301 for addr, hist in self.history.items():
1302 if hist == ['*']: continue
1303 for tx_hash, tx_height in hist:
1305 # add it in case it was previously unconfirmed
1306 self.verifier.add(tx_hash, tx_height)
1309 # if we are on a pruning server, remove unverified transactions
1310 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1311 for tx_hash in self.transactions.keys():
1312 if tx_hash not in vr:
1313 self.transactions.pop(tx_hash)
1317 def check_new_history(self, addr, hist):
1319 # check that all tx in hist are relevant
1321 for tx_hash, height in hist:
1322 tx = self.transactions.get(tx_hash)
1324 if not tx.has_address(addr):
1327 # check that we are not "orphaning" a transaction
1328 old_hist = self.history.get(addr,[])
1329 if old_hist == ['*']: return True
1331 for tx_hash, height in old_hist:
1332 if tx_hash in map(lambda x:x[0], hist): continue
1334 for _addr, _hist in self.history.items():
1335 if _addr == addr: continue
1336 if _hist == ['*']: continue
1337 _tx_hist = map(lambda x:x[0], _hist)
1338 if tx_hash in _tx_hist:
1343 tx = self.transactions.get(tx_hash)
1344 # tx might not be there
1348 if self.verifier.get_height(tx_hash):
1351 print_error("new history is orphaning transaction:", tx_hash)
1352 # check that all outputs are not mine, request histories
1354 for _addr, _v in tx.outputs:
1355 # assert not self.is_mine(_addr)
1356 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1358 ext_h = self.network.interface.synchronous_get(ext_requests)
1359 print_error("sync:", ext_requests, ext_h)
1362 if h == ['*']: continue
1364 if item.get('tx_hash') == tx_hash:
1365 height = item.get('height')
1367 print_error("found height for", tx_hash, height)
1368 self.verifier.add(tx_hash, height)
1370 print_error("removing orphaned tx from history", tx_hash)
1371 self.transactions.pop(tx_hash)
1377 def check_new_tx(self, tx_hash, tx):
1378 # 1 check that tx is referenced in addr_history.
1380 for addr, hist in self.history.items():
1381 if hist == ['*']:continue
1382 for txh, height in hist:
1384 addresses.append(addr)
1389 # 2 check that referencing addresses are in the tx
1390 for addr in addresses:
1391 if not tx.has_address(addr):
1397 def start_threads(self, network):
1398 from verifier import TxVerifier
1399 self.network = network
1400 self.verifier = TxVerifier(self.network, self.storage)
1401 self.verifier.start()
1402 self.set_verifier(self.verifier)
1403 self.synchronizer = WalletSynchronizer(self)
1404 self.synchronizer.start()
1406 def stop_threads(self):
1407 self.verifier.stop()
1408 self.synchronizer.stop()
1412 def restore(self, callback):
1414 def wait_for_wallet():
1415 self.set_up_to_date(False)
1416 while not self.is_up_to_date():
1417 msg = "%s\n%s %d\n%s %.1f"%(
1418 _("Please wait..."),
1419 _("Addresses generated:"),
1420 len(self.addresses(True)),_("Kilobytes received:"),
1421 self.network.interface.bytes_received/1024.)
1423 apply(callback, (msg,))
1426 def wait_for_network():
1427 while not self.network.interface.is_connected:
1428 msg = "%s \n" % (_("Connecting..."))
1429 apply(callback, (msg,))
1432 # wait until we are connected, because the user might have selected another server
1435 # try to restore old account
1436 self.create_old_account()
1440 self.seed_version = 4
1441 self.storage.put('seed_version', wallet.seed_version, True)
1443 self.accounts.pop(0)
1444 self.create_accounts()
1450 class WalletSynchronizer(threading.Thread):
1453 def __init__(self, wallet):
1454 threading.Thread.__init__(self)
1456 self.wallet = wallet
1457 wallet.synchronizer = self
1458 self.network = self.wallet.network
1459 #self.wallet.network.register_callback('connected', lambda: self.wallet.set_up_to_date(False))
1460 self.was_updated = True
1461 self.running = False
1462 self.lock = threading.Lock()
1463 self.queue = Queue.Queue()
1466 with self.lock: self.running = False
1468 def is_running(self):
1469 with self.lock: return self.running
1472 def subscribe_to_addresses(self, addresses):
1474 for addr in addresses:
1475 messages.append(('blockchain.address.subscribe', [addr]))
1476 self.network.interface.send( messages, lambda i,r: self.queue.put(r))
1483 while self.is_running():
1484 interface = self.network.interface
1485 if not interface.is_connected:
1486 print_error("synchronizer: waiting for interface")
1487 interface.connect_event.wait()
1489 self.run_interface(interface)
1492 def run_interface(self, interface):
1494 print_error("synchronizer: connected to", interface.server)
1498 requested_histories = {}
1500 # request any missing transactions
1501 for history in self.wallet.history.values():
1502 if history == ['*']: continue
1503 for tx_hash, tx_height in history:
1504 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1505 missing_tx.append( (tx_hash, tx_height) )
1508 print_error("missing tx", missing_tx)
1511 self.subscribe_to_addresses(self.wallet.addresses(True, next=True))
1513 while self.is_running():
1514 # 1. create new addresses
1515 new_addresses = self.wallet.synchronize()
1517 # request missing addresses
1519 self.subscribe_to_addresses(new_addresses)
1521 # request missing transactions
1522 for tx_hash, tx_height in missing_tx:
1523 if (tx_hash, tx_height) not in requested_tx:
1524 interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1525 requested_tx.append( (tx_hash, tx_height) )
1528 # detect if situation has changed
1529 if interface.is_up_to_date() and self.queue.empty():
1530 if not self.wallet.is_up_to_date():
1531 self.wallet.set_up_to_date(True)
1532 self.was_updated = True
1534 if self.wallet.is_up_to_date():
1535 self.wallet.set_up_to_date(False)
1536 self.was_updated = True
1538 if self.was_updated:
1539 self.wallet.network.trigger_callback('updated')
1540 self.was_updated = False
1544 r = self.queue.get(block=True, timeout=1)
1548 if interface != self.network.interface:
1554 # 3. handle response
1555 method = r['method']
1556 params = r['params']
1557 result = r.get('result')
1558 error = r.get('error')
1563 if method == 'blockchain.address.subscribe':
1565 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1566 if requested_histories.get(addr) is None:
1567 interface.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1568 requested_histories[addr] = result
1570 elif method == 'blockchain.address.get_history':
1572 print_error("receiving history", addr, result)
1574 assert requested_histories.pop(addr) == '*'
1575 self.wallet.receive_history_callback(addr, result)
1578 # check that txids are unique
1581 tx_hash = item['tx_hash']
1582 if tx_hash not in txids:
1583 txids.append(tx_hash)
1584 hist.append( (tx_hash, item['height']) )
1586 if len(hist) != len(result):
1587 raise BaseException("error: server sent history with non-unique txid", result)
1589 # check that the status corresponds to what was announced
1590 rs = requested_histories.pop(addr)
1591 if self.wallet.get_status(hist) != rs:
1592 raise BaseException("error: status mismatch: %s"%addr)
1594 # store received history
1595 self.wallet.receive_history_callback(addr, hist)
1597 # request transactions that we don't have
1598 for tx_hash, tx_height in hist:
1599 if self.wallet.transactions.get(tx_hash) is None:
1600 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1601 missing_tx.append( (tx_hash, tx_height) )
1603 elif method == 'blockchain.transaction.get':
1605 tx_height = params[1]
1606 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1607 tx = Transaction(result)
1608 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1609 self.was_updated = True
1610 requested_tx.remove( (tx_hash, tx_height) )
1611 print_error("received tx:", tx_hash, len(tx.raw))
1614 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1616 if self.was_updated and not requested_tx:
1617 self.wallet.network.trigger_callback('updated')
1618 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
1620 self.was_updated = False