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
38 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
39 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
41 def pw_encode(s, password):
43 secret = Hash(password)
44 return EncodeAES(secret, s)
48 def pw_decode(s, password):
49 if password is not None:
50 secret = Hash(password)
52 d = DecodeAES(secret, s)
54 raise BaseException('Invalid password')
63 from version import ELECTRUM_VERSION, SEED_VERSION
68 def __init__(self, config):
70 self.file_exists = False
71 self.init_path(config)
72 print_error( "wallet path", self.path )
77 def init_path(self, config):
78 """Set the path of the wallet."""
80 path = config.get('wallet_path')
82 path = config.get('default_wallet_path')
87 self.path = os.path.join(config.path, "electrum.dat")
91 """Read the contents of the wallet file."""
93 with open(self.path, "r") as f:
98 d = ast.literal_eval( data ) #parse raw data from reading wallet file
100 raise IOError("Cannot read wallet file.")
103 self.file_exists = True
106 def get(self, key, default=None):
107 return self.data.get(key, default)
109 def put(self, key, value, save = True):
111 if self.data.get(key) is not None:
112 self.data[key] = value
114 # add key to wallet config
115 self.data[key] = value
123 f = open(self.path,"w")
126 if self.get('gui') != 'android':
128 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
133 def __init__(self, storage):
135 self.storage = storage
136 self.electrum_version = ELECTRUM_VERSION
137 self.gap_limit_for_change = 3 # constant
140 self.seed_version = storage.get('seed_version', SEED_VERSION)
142 self.gap_limit = storage.get('gap_limit', 5)
143 self.use_change = storage.get('use_change',True)
144 self.use_encryption = storage.get('use_encryption', False)
145 self.seed = storage.get('seed', '') # encrypted
146 self.labels = storage.get('labels', {})
147 self.frozen_addresses = storage.get('frozen_addresses',[])
148 self.prioritized_addresses = storage.get('prioritized_addresses',[])
149 self.addressbook = storage.get('contacts', [])
151 self.imported_keys = storage.get('imported_keys',{})
152 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
154 self.fee = int(storage.get('fee_per_kb',20000))
156 self.master_public_keys = storage.get('master_public_keys',{})
157 self.master_private_keys = storage.get('master_private_keys', {})
159 self.first_addresses = storage.get('first_addresses',{})
161 #if self.seed_version != SEED_VERSION:
162 # raise ValueError("This wallet seed is deprecated. Please restore from seed.")
166 self.transactions = {}
167 tx = storage.get('transactions',{})
169 for k,v in tx.items(): self.transactions[k] = Transaction(v)
171 print_msg("Warning: Cannot deserialize transactions. skipping")
174 self.prevout_values = {} # my own transaction outputs
175 self.spent_outputs = []
180 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
181 # interface.is_up_to_date() returns true when all requests have been answered and processed
182 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
184 self.up_to_date = False
185 self.lock = threading.Lock()
186 self.transaction_lock = threading.Lock()
187 self.tx_event = threading.Event()
189 for tx_hash, tx in self.transactions.items():
190 if self.check_new_tx(tx_hash, tx):
191 self.update_tx_outputs(tx_hash)
193 print_error("unreferenced tx", tx_hash)
194 self.transactions.pop(tx_hash)
197 def set_up_to_date(self,b):
198 with self.lock: self.up_to_date = b
200 def is_up_to_date(self):
201 with self.lock: return self.up_to_date
204 self.up_to_date = False
205 self.interface.poke('synchronizer')
206 while not self.is_up_to_date(): time.sleep(0.1)
208 def import_key(self, sec, password):
210 seed = self.decode_seed(password)
212 address = address_from_private_key(sec)
214 raise BaseException('Invalid private key')
216 if self.is_mine(address):
217 raise BaseException('Address already in wallet')
219 # store the originally requested keypair into the imported keys table
220 self.imported_keys[address] = pw_encode(sec, password )
221 self.storage.put('imported_keys', self.imported_keys, True)
224 def delete_imported_key(self, addr):
225 if addr in self.imported_keys:
226 self.imported_keys.pop(addr)
227 self.storage.put('imported_keys', self.imported_keys, True)
230 def init_seed(self, seed):
231 if self.seed: raise BaseException("a seed exists")
233 seed = random_seed(128)
238 self.storage.put('seed', self.seed, True)
239 self.storage.put('seed_version', self.seed_version, True)
241 master_k, master_c, master_K, master_cK = bip32_init(self.seed)
244 k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/")
246 k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/")
247 k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/")
249 k3, c3, K3, cK3 = bip32_private_derivation(master_k, master_c, "m/", "m/3'/")
250 k4, c4, K4, cK4 = bip32_private_derivation(master_k, master_c, "m/", "m/4'/")
251 k5, c5, K5, cK5 = bip32_private_derivation(master_k, master_c, "m/", "m/5'/")
253 self.master_public_keys = {
254 "m/0'/": (c0, K0, cK0),
255 "m/1'/": (c1, K1, cK1),
256 "m/2'/": (c2, K2, cK2),
257 "m/3'/": (c3, K3, cK3),
258 "m/4'/": (c4, K4, cK4),
259 "m/5'/": (c5, K5, cK5)
262 self.master_private_keys = {
271 self.storage.put('master_public_keys', self.master_public_keys, True)
272 self.storage.put('master_private_keys', self.master_private_keys, True)
274 # create default account
275 self.create_account('1','Main account')
278 def find_root_by_master_key(self, c, K):
279 for key, v in self.master_public_keys.items():
280 if key == "m/":continue
282 if (c == cc) and (K == KK):
285 def deseed_root(self, seed, password):
286 # for safety, we ask the user to enter their seed
287 assert seed == self.decode_seed(password)
289 self.storage.put('seed', '', True)
292 def deseed_branch(self, k):
293 # check that parent has no seed
294 assert self.seed == ''
295 self.master_private_keys.pop(k)
296 self.storage.put('master_private_keys', self.master_private_keys, True)
299 def account_id(self, account_type, i):
300 if account_type == '1':
302 elif account_type == '2of2':
303 return "m/1'/%d & m/2'/%d"%(i,i)
304 elif account_type == '2of3':
305 return "m/3'/%d & m/4'/%d & m/5'/%d"%(i,i,i)
307 raise BaseException('unknown account type')
310 def num_accounts(self, account_type):
311 keys = self.accounts.keys()
314 account_id = self.account_id(account_type, i)
315 if account_id not in keys: break
320 def new_account_address(self, account_type = '1'):
321 i = self.num_accounts(account_type)
322 k = self.account_id(account_type,i)
324 addr = self.first_addresses.get(k)
326 account_id, account = self.next_account(account_type)
327 addr = account.first_address()
328 self.first_addresses[k] = addr
329 self.storage.put('first_addresses',self.first_addresses)
334 def next_account(self, account_type = '1'):
336 i = self.num_accounts(account_type)
337 account_id = self.account_id(account_type,i)
339 if account_type is '1':
340 master_c0, master_K0, _ = self.master_public_keys["m/0'/"]
341 c0, K0, cK0 = bip32_public_derivation(master_c0.decode('hex'), master_K0.decode('hex'), "m/0'/", "m/0'/%d"%i)
342 account = BIP32_Account({ 'c':c0, 'K':K0, 'cK':cK0 })
344 elif account_type == '2of2':
345 master_c1, master_K1, _ = self.master_public_keys["m/1'/"]
346 c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i)
347 master_c2, master_K2, _ = self.master_public_keys["m/2'/"]
348 c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i)
349 account = BIP32_Account_2of2({ 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 })
351 elif account_type == '2of3':
352 master_c3, master_K3, _ = self.master_public_keys["m/3'/"]
353 c3, K3, cK3 = bip32_public_derivation(master_c3.decode('hex'), master_K3.decode('hex'), "m/3'/", "m/3'/%d"%i)
354 master_c4, master_K4, _ = self.master_public_keys["m/4'/"]
355 c4, K4, cK4 = bip32_public_derivation(master_c4.decode('hex'), master_K4.decode('hex'), "m/4'/", "m/4'/%d"%i)
356 master_c5, master_K5, _ = self.master_public_keys["m/5'/"]
357 c5, K5, cK5 = bip32_public_derivation(master_c5.decode('hex'), master_K5.decode('hex'), "m/5'/", "m/5'/%d"%i)
358 account = BIP32_Account_2of3({ 'c':c3, 'K':K3, 'cK':cK3, 'c2':c4, 'K2':K4, 'cK2':cK4, 'c3':c5, 'K3':K5, 'cK3':cK5 })
360 return account_id, account
363 def create_account(self, account_type = '1', name = None):
364 account_id, account = self.next_account(account_type)
365 self.accounts[account_id] = account
368 self.labels[account_id] = name
369 self.storage.put('labels', self.labels, True)
372 def create_old_account(self):
373 mpk = OldAccount.mpk_from_seed(self.seed)
374 self.storage.put('master_public_key', mpk, True)
375 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
379 def save_accounts(self):
381 for k, v in self.accounts.items():
383 self.storage.put('accounts', d, True)
387 def load_accounts(self):
388 d = self.storage.get('accounts', {})
390 for k, v in d.items():
392 v['mpk'] = self.storage.get('master_public_key')
393 self.accounts[k] = OldAccount(v)
395 self.accounts[k] = BIP32_Account_2of2(v)
397 self.accounts[k] = BIP32_Account(v)
400 def addresses(self, include_change = True):
401 o = self.get_account_addresses(-1, include_change)
402 for a in self.accounts.keys():
403 o += self.get_account_addresses(a, include_change)
404 o += self.first_addresses.values()
408 def is_mine(self, address):
409 return address in self.addresses(True)
412 def is_change(self, address):
413 if not self.is_mine(address): return False
414 if address in self.imported_keys.keys(): return False
415 acct, s = self.get_address_index(address)
418 def get_master_public_key(self):
420 return self.storage.get("master_public_key")
422 def get_master_private_key(self, account, password):
423 master_k = pw_decode( self.master_private_keys[account], password)
424 master_c, master_K, master_Kc = self.master_public_keys[account]
426 K, Kc = get_pubkeys_from_secret(master_k.decode('hex'))
427 assert K.encode('hex') == master_K
429 raise BaseException("Invalid password")
433 def get_address_index(self, address):
434 if address in self.imported_keys.keys():
437 for account in self.accounts.keys():
438 for for_change in [0,1]:
439 addresses = self.accounts[account].get_addresses(for_change)
440 for addr in addresses:
442 return account, (for_change, addresses.index(addr))
444 raise BaseException("not found")
447 def rebase_sequence(self, account, sequence):
450 for a in account.split('&'):
452 m = re.match("(m/\d+'/)(\d+)", s)
454 num = int(m.group(2))
455 dd.append( (root, [num,c,i] ) )
459 def get_keyID(self, account, sequence):
463 rs = self.rebase_sequence(account, sequence)
465 for root, public_sequence in rs:
466 c, K, _ = self.master_public_keys[root]
467 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
468 dd.append( 'bip32(%s,%s,%s)'%(c,K, s) )
472 def get_public_key(self, address):
473 account, sequence = self.get_address_index(address)
474 return self.accounts[account].get_pubkey( *sequence )
477 def decode_seed(self, password):
478 seed = pw_decode(self.seed, password)
479 #todo: #self.sequences[0].check_seed(seed)
483 def get_private_key(self, address, password):
485 if address in self.imported_keys.keys():
486 out.append( pw_decode( self.imported_keys[address], password ) )
488 account, sequence = self.get_address_index(address)
490 seed = self.decode_seed(password)
491 pk = self.accounts[account].get_private_key(seed, sequence)
495 # assert address == self.accounts[account].get_address(*sequence)
496 rs = self.rebase_sequence( account, sequence)
497 for root, public_sequence in rs:
499 if root not in self.master_private_keys.keys(): continue
500 master_k = self.get_master_private_key(root, password)
501 master_c, _, _ = self.master_public_keys[root]
502 pk = bip32_private_key( public_sequence, master_k.decode('hex'), master_c.decode('hex'))
510 def signrawtransaction(self, tx, input_info, private_keys, password):
512 unspent_coins = self.get_unspent_coins()
513 seed = self.decode_seed(password)
515 # build a list of public/private keys
517 for sec in private_keys:
518 pubkey = public_key_from_private_key(sec)
519 keypairs[ pubkey ] = sec
522 for txin in tx.inputs:
523 # convert to own format
524 txin['tx_hash'] = txin['prevout_hash']
525 txin['index'] = txin['prevout_n']
527 for item in input_info:
528 if item.get('txid') == txin['tx_hash'] and item.get('vout') == txin['index']:
529 txin['raw_output_script'] = item['scriptPubKey']
530 txin['redeemScript'] = item.get('redeemScript')
531 txin['KeyID'] = item.get('KeyID')
534 for item in unspent_coins:
535 if txin['tx_hash'] == item['tx_hash'] and txin['index'] == item['index']:
536 print_error( "tx input is in unspent coins" )
537 txin['raw_output_script'] = item['raw_output_script']
538 account, sequence = self.get_address_index(item['address'])
540 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
543 raise BaseException("Unknown transaction input. Please provide the 'input_info' parameter, or synchronize this wallet")
545 # if available, derive private_keys from KeyID
546 keyid = txin.get('KeyID')
549 for s in keyid.split('&'):
550 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
554 sequence = m.group(3)
555 root = self.find_root_by_master_key(c,K)
556 if not root: continue
557 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
558 root = root + '%d'%sequence[0]
559 sequence = sequence[1:]
560 roots.append((root,sequence))
562 account_id = " & ".join( map(lambda x:x[0], roots) )
563 account = self.accounts.get(account_id)
564 if not account: continue
565 addr = account.get_address(*sequence)
566 txin['address'] = addr
567 pk = self.get_private_key(addr, password)
569 pubkey = public_key_from_private_key(sec)
570 keypairs[pubkey] = sec
572 redeem_script = txin.get("redeemScript")
573 print_error( "p2sh:", "yes" if redeem_script else "no")
575 addr = hash_160_to_bc_address(hash_160(redeem_script.decode('hex')), 5)
577 addr = deserialize.get_address_from_output_script(txin["raw_output_script"].decode('hex'))
578 txin['address'] = addr
580 # add private keys that are in the wallet
581 pk = self.get_private_key(addr, password)
583 pubkey = public_key_from_private_key(sec)
584 keypairs[pubkey] = sec
585 if not redeem_script:
586 txin['redeemPubkey'] = pubkey
592 def sign_message(self, address, message, password):
593 sec = self.get_private_key(address, password)
594 key = regenerate_key(sec)
595 compressed = is_compressed(sec)
596 return key.sign_message(message, compressed, address)
598 def verify_message(self, address, signature, message):
600 EC_KEY.verify_message(address, signature, message)
602 except BaseException as e:
603 print_error("Verification error: {0}".format(e))
607 def change_gap_limit(self, value):
608 if value >= self.gap_limit:
609 self.gap_limit = value
610 self.storage.put('gap_limit', self.gap_limit, True)
611 self.interface.poke('synchronizer')
614 elif value >= self.min_acceptable_gap():
615 for key, account in self.accounts.items():
616 addresses = account[0]
617 k = self.num_unused_trailing_addresses(addresses)
618 n = len(addresses) - k + value
619 addresses = addresses[0:n]
620 self.accounts[key][0] = addresses
622 self.gap_limit = value
623 self.storage.put('gap_limit', self.gap_limit, True)
629 def num_unused_trailing_addresses(self, addresses):
631 for a in addresses[::-1]:
632 if self.history.get(a):break
636 def min_acceptable_gap(self):
637 # fixme: this assumes wallet is synchronized
641 for account in self.accounts.values():
642 addresses = account.get_addresses(0)
643 k = self.num_unused_trailing_addresses(addresses)
644 for a in addresses[0:-k]:
645 if self.history.get(a):
649 if n > nmax: nmax = n
653 def address_is_old(self, address):
655 h = self.history.get(address, [])
658 for tx_hash, tx_height in h:
662 tx_age = self.verifier.blockchain.height - tx_height + 1
668 def synchronize_sequence(self, account, for_change):
669 limit = self.gap_limit_for_change if for_change else self.gap_limit
672 addresses = account.get_addresses(for_change)
673 if len(addresses) < limit:
674 address = account.create_new_address(for_change)
675 self.history[address] = []
676 new_addresses.append( address )
679 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
682 address = account.create_new_address(for_change)
683 self.history[address] = []
684 new_addresses.append( address )
690 def create_pending_accounts(self):
691 for account_type in ['1','2of2','2of3']:
692 a = self.new_account_address(account_type)
693 if self.address_is_old(a):
694 print "creating account", a
695 self.create_account(account_type)
698 def synchronize_account(self, account):
700 new += self.synchronize_sequence(account, 0)
701 new += self.synchronize_sequence(account, 1)
705 def synchronize(self):
706 if self.master_public_keys:
707 self.create_pending_accounts()
709 for account in self.accounts.values():
710 new += self.synchronize_account(account)
713 self.storage.put('addr_history', self.history, True)
718 return self.history.values() != [[]] * len(self.history)
721 def add_contact(self, address, label=None):
722 self.addressbook.append(address)
723 self.storage.put('contacts', self.addressbook, True)
725 self.labels[address] = label
726 self.storage.put('labels', self.labels, True)
728 def delete_contact(self, addr):
729 if addr in self.addressbook:
730 self.addressbook.remove(addr)
731 self.storage.put('addressbook', self.addressbook, True)
734 def fill_addressbook(self):
735 for tx_hash, tx in self.transactions.items():
736 is_relevant, is_send, _, _ = self.get_tx_value(tx)
738 for addr, v in tx.outputs:
739 if not self.is_mine(addr) and addr not in self.addressbook:
740 self.addressbook.append(addr)
742 # self.update_tx_labels()
744 def get_num_tx(self, address):
746 for tx in self.transactions.values():
747 if address in map(lambda x:x[0], tx.outputs): n += 1
751 def get_address_flags(self, addr):
752 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
753 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
757 def get_tx_value(self, tx, account=None):
758 domain = self.get_account_addresses(account)
759 return tx.get_value(domain, self.prevout_values)
762 def update_tx_outputs(self, tx_hash):
763 tx = self.transactions.get(tx_hash)
765 for i, (addr, value) in enumerate(tx.outputs):
766 key = tx_hash+ ':%d'%i
767 self.prevout_values[key] = value
769 for item in tx.inputs:
770 if self.is_mine(item.get('address')):
771 key = item['prevout_hash'] + ':%d'%item['prevout_n']
772 self.spent_outputs.append(key)
775 def get_addr_balance(self, address):
776 assert self.is_mine(address)
777 h = self.history.get(address,[])
778 if h == ['*']: return 0,0
780 received_coins = [] # list of coins received at address
782 for tx_hash, tx_height in h:
783 tx = self.transactions.get(tx_hash)
786 for i, (addr, value) in enumerate(tx.outputs):
788 key = tx_hash + ':%d'%i
789 received_coins.append(key)
791 for tx_hash, tx_height in h:
792 tx = self.transactions.get(tx_hash)
796 for item in tx.inputs:
797 addr = item.get('address')
799 key = item['prevout_hash'] + ':%d'%item['prevout_n']
800 value = self.prevout_values.get( key )
801 if key in received_coins:
804 for i, (addr, value) in enumerate(tx.outputs):
805 key = tx_hash + ':%d'%i
816 def get_account_name(self, k):
818 if self.seed_version == 4:
819 name = 'Main account'
823 name = self.labels.get(k, 'Unnamed account')
826 def get_account_names(self):
828 for k, account in self.accounts.items():
829 accounts[k] = self.get_account_name(k)
830 if self.imported_keys:
831 accounts[-1] = 'Imported keys'
834 def get_account_addresses(self, a, include_change=True):
836 o = self.addresses(True)
838 o = self.imported_keys.keys()
840 ac = self.accounts[a]
841 o = ac.get_addresses(0)
842 if include_change: o += ac.get_addresses(1)
845 def get_imported_balance(self):
847 for addr in self.imported_keys.keys():
848 c, u = self.get_addr_balance(addr)
853 def get_account_balance(self, account):
855 return self.get_balance()
857 return self.get_imported_balance()
860 for addr in self.get_account_addresses(account):
861 c, u = self.get_addr_balance(addr)
866 def get_frozen_balance(self):
868 for addr in self.frozen_addresses:
869 c, u = self.get_addr_balance(addr)
875 def get_balance(self):
877 for a in self.accounts.keys():
878 c, u = self.get_account_balance(a)
881 c, u = self.get_imported_balance()
887 def get_unspent_coins(self, domain=None):
889 if domain is None: domain = self.addresses(True)
891 h = self.history.get(addr, [])
892 if h == ['*']: continue
893 for tx_hash, tx_height in h:
894 tx = self.transactions.get(tx_hash)
895 if tx is None: raise BaseException("Wallet not synchronized")
896 for output in tx.d.get('outputs'):
897 if output.get('address') != addr: continue
898 key = tx_hash + ":%d" % output.get('index')
899 if key in self.spent_outputs: continue
900 output['tx_hash'] = tx_hash
906 def choose_tx_inputs( self, amount, fixed_fee, account = None ):
907 """ todo: minimize tx size """
909 fee = self.fee if fixed_fee is None else fixed_fee
910 domain = self.get_account_addresses(account)
912 prioritized_coins = []
913 for i in self.frozen_addresses:
914 if i in domain: domain.remove(i)
916 for i in self.prioritized_addresses:
917 if i in domain: domain.remove(i)
919 coins = self.get_unspent_coins(domain)
920 prioritized_coins = self.get_unspent_coins(self.prioritized_addresses)
923 coins = prioritized_coins + coins
926 addr = item.get('address')
927 v = item.get('value')
929 inputs.append( item )
930 fee = self.estimated_fee(inputs) if fixed_fee is None else fixed_fee
931 if total >= amount + fee: break
935 return inputs, total, fee
938 def set_fee(self, fee):
941 self.storage.put('fee_per_kb', self.fee, True)
943 def estimated_fee(self, inputs):
944 estimated_size = len(inputs) * 180 + 80 # this assumes non-compressed keys
945 fee = self.fee * int(round(estimated_size/1024.))
946 if fee == 0: fee = self.fee
950 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None, account=0 ):
951 "add change to a transaction"
952 change_amount = total - ( amount + fee )
953 if change_amount != 0:
956 # send change to one of the accounts involved in the tx
957 address = inputs[0].get('address')
958 account, _ = self.get_address_index(address)
960 if not self.use_change or account == -1:
961 change_addr = inputs[-1]['address']
963 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
965 # Insert the change output at a random position in the outputs
966 posn = random.randint(0, len(outputs))
967 outputs[posn:posn] = [( change_addr, change_amount)]
971 def get_history(self, address):
973 return self.history.get(address)
976 def get_status(self, h):
977 if not h: return None
978 if h == ['*']: return '*'
980 for tx_hash, height in h:
981 status += tx_hash + ':%d:' % height
982 return hashlib.sha256( status ).digest().encode('hex')
985 def receive_tx_callback(self, tx_hash, tx, tx_height):
986 if not self.check_new_tx(tx_hash, tx):
987 # may happen due to pruning
988 print_error("received transaction that is no longer referenced in history", tx_hash)
991 with self.transaction_lock:
992 self.transactions[tx_hash] = tx
994 self.interface.pending_transactions_for_notifications.append(tx)
996 self.save_transactions()
997 if self.verifier and tx_height>0:
998 self.verifier.add(tx_hash, tx_height)
999 self.update_tx_outputs(tx_hash)
1002 def save_transactions(self):
1004 for k,v in self.transactions.items():
1006 self.storage.put('transactions', tx, True)
1008 def receive_history_callback(self, addr, hist):
1010 if not self.check_new_history(addr, hist):
1011 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
1014 self.history[addr] = hist
1015 self.storage.put('addr_history', self.history, True)
1018 for tx_hash, tx_height in hist:
1020 # add it in case it was previously unconfirmed
1021 if self.verifier: self.verifier.add(tx_hash, tx_height)
1024 def get_tx_history(self, account=None):
1025 with self.transaction_lock:
1026 history = self.transactions.items()
1027 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1031 for tx_hash, tx in history:
1032 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1033 if v is not None: balance += v
1035 c, u = self.get_account_balance(account)
1038 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1040 balance = c + u - balance
1041 for tx_hash, tx in history:
1042 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1045 if value is not None:
1048 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1049 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1054 def get_label(self, tx_hash):
1055 label = self.labels.get(tx_hash)
1056 is_default = (label == '') or (label is None)
1057 if is_default: label = self.get_default_label(tx_hash)
1058 return label, is_default
1061 def get_default_label(self, tx_hash):
1062 tx = self.transactions.get(tx_hash)
1065 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1067 for o in tx.outputs:
1069 if not self.is_mine(o_addr):
1071 default_label = self.labels[o_addr]
1073 default_label = o_addr
1076 default_label = '(internal)'
1078 for o in tx.outputs:
1080 if self.is_mine(o_addr) and not self.is_change(o_addr):
1083 for o in tx.outputs:
1085 if self.is_mine(o_addr):
1091 dest_label = self.labels.get(o_addr)
1093 default_label = self.labels[o_addr]
1095 default_label = o_addr
1097 return default_label
1100 def mktx(self, outputs, password, fee=None, change_addr=None, account=None ):
1102 for address, x in outputs:
1103 assert is_valid(address)
1105 amount = sum( map(lambda x:x[1], outputs) )
1107 inputs, total, fee = self.choose_tx_inputs( amount, fee, account )
1109 raise ValueError("Not enough funds")
1111 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr, account)
1112 tx = Transaction.from_io(inputs, outputs)
1115 for i, txin in enumerate(tx.inputs):
1116 address = txin['address']
1118 account, sequence = self.get_address_index(address)
1119 txin['KeyID'] = self.get_keyID(account, sequence)
1121 redeemScript = self.accounts[account].redeem_script(sequence)
1123 txin['redeemScript'] = redeemScript
1125 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1127 private_keys = self.get_private_key(address, password)
1129 for sec in private_keys:
1130 pubkey = public_key_from_private_key(sec)
1131 keypairs[ pubkey ] = sec
1134 for address, x in outputs:
1135 if address not in self.addressbook and not self.is_mine(address):
1136 self.addressbook.append(address)
1142 def sendtx(self, tx):
1144 h = self.send_tx(tx)
1145 self.tx_event.wait()
1146 return self.receive_tx(h)
1148 def send_tx(self, tx):
1150 self.tx_event.clear()
1151 self.interface.send([('blockchain.transaction.broadcast', [str(tx)])], 'synchronizer')
1154 def receive_tx(self,tx_hash):
1155 out = self.tx_result
1157 return False, "error: " + out
1162 def update_password(self, seed, old_password, new_password):
1163 if new_password == '': new_password = None
1164 # this will throw an exception if unicode cannot be converted
1165 self.seed = pw_encode( seed, new_password)
1166 self.storage.put('seed', self.seed, True)
1167 self.use_encryption = (new_password != None)
1168 self.storage.put('use_encryption', self.use_encryption,True)
1169 for k in self.imported_keys.keys():
1170 a = self.imported_keys[k]
1171 b = pw_decode(a, old_password)
1172 c = pw_encode(b, new_password)
1173 self.imported_keys[k] = c
1174 self.storage.put('imported_keys', self.imported_keys, True)
1176 for k, v in self.master_private_keys.items():
1177 b = pw_decode(v, old_password)
1178 c = pw_encode(b, new_password)
1179 self.master_private_keys[k] = c
1180 self.storage.put('master_private_keys', self.master_private_keys, True)
1183 def freeze(self,addr):
1184 if self.is_mine(addr) and addr not in self.frozen_addresses:
1185 self.unprioritize(addr)
1186 self.frozen_addresses.append(addr)
1187 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1192 def unfreeze(self,addr):
1193 if self.is_mine(addr) and addr in self.frozen_addresses:
1194 self.frozen_addresses.remove(addr)
1195 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1200 def prioritize(self,addr):
1201 if self.is_mine(addr) and addr not in self.prioritized_addresses:
1203 self.prioritized_addresses.append(addr)
1204 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1209 def unprioritize(self,addr):
1210 if self.is_mine(addr) and addr in self.prioritized_addresses:
1211 self.prioritized_addresses.remove(addr)
1212 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1218 def set_verifier(self, verifier):
1219 self.verifier = verifier
1221 # review transactions that are in the history
1222 for addr, hist in self.history.items():
1223 if hist == ['*']: continue
1224 for tx_hash, tx_height in hist:
1226 # add it in case it was previously unconfirmed
1227 self.verifier.add(tx_hash, tx_height)
1230 # if we are on a pruning server, remove unverified transactions
1231 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1232 for tx_hash in self.transactions.keys():
1233 if tx_hash not in vr:
1234 self.transactions.pop(tx_hash)
1238 def check_new_history(self, addr, hist):
1240 # check that all tx in hist are relevant
1242 for tx_hash, height in hist:
1243 tx = self.transactions.get(tx_hash)
1245 if not tx.has_address(addr):
1248 # check that we are not "orphaning" a transaction
1249 old_hist = self.history.get(addr,[])
1250 if old_hist == ['*']: return True
1252 for tx_hash, height in old_hist:
1253 if tx_hash in map(lambda x:x[0], hist): continue
1255 for _addr, _hist in self.history.items():
1256 if _addr == addr: continue
1257 if _hist == ['*']: continue
1258 _tx_hist = map(lambda x:x[0], _hist)
1259 if tx_hash in _tx_hist:
1264 tx = self.transactions.get(tx_hash)
1265 # tx might not be there
1269 if self.verifier.get_height(tx_hash):
1272 print_error("new history is orphaning transaction:", tx_hash)
1273 # check that all outputs are not mine, request histories
1275 for _addr, _v in tx.outputs:
1276 # assert not self.is_mine(_addr)
1277 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1279 ext_h = self.interface.synchronous_get(ext_requests)
1280 print_error("sync:", ext_requests, ext_h)
1283 if h == ['*']: continue
1285 if item.get('tx_hash') == tx_hash:
1286 height = item.get('height')
1288 print_error("found height for", tx_hash, height)
1289 self.verifier.add(tx_hash, height)
1291 print_error("removing orphaned tx from history", tx_hash)
1292 self.transactions.pop(tx_hash)
1298 def check_new_tx(self, tx_hash, tx):
1299 # 1 check that tx is referenced in addr_history.
1301 for addr, hist in self.history.items():
1302 if hist == ['*']:continue
1303 for txh, height in hist:
1305 addresses.append(addr)
1310 # 2 check that referencing addresses are in the tx
1311 for addr in addresses:
1312 if not tx.has_address(addr):
1318 def start_threads(self, interface, blockchain):
1319 from verifier import TxVerifier
1320 self.interface = interface
1321 self.verifier = TxVerifier(interface, blockchain, self.storage)
1322 self.verifier.start()
1323 self.set_verifier(self.verifier)
1324 self.synchronizer = WalletSynchronizer(self)
1325 self.synchronizer.start()
1327 def stop_threads(self):
1328 self.verifier.stop()
1329 self.synchronizer.stop()
1334 class WalletSynchronizer(threading.Thread):
1337 def __init__(self, wallet):
1338 threading.Thread.__init__(self)
1340 self.wallet = wallet
1341 wallet.synchronizer = self
1342 self.interface = self.wallet.interface
1343 self.interface.register_channel('synchronizer')
1344 self.wallet.interface.register_callback('connected', lambda: self.wallet.set_up_to_date(False))
1345 self.was_updated = True
1346 self.running = False
1347 self.lock = threading.Lock()
1350 with self.lock: self.running = False
1351 self.interface.poke('synchronizer')
1353 def is_running(self):
1354 with self.lock: return self.running
1357 def subscribe_to_addresses(self, addresses):
1359 for addr in addresses:
1360 messages.append(('blockchain.address.subscribe', [addr]))
1361 self.interface.send( messages, 'synchronizer')
1365 if not self.interface.is_connected:
1366 print_error( "synchronizer: waiting for interface")
1367 self.interface.connect_event.wait()
1369 with self.lock: self.running = True
1373 requested_histories = {}
1375 # request any missing transactions
1376 for history in self.wallet.history.values():
1377 if history == ['*']: continue
1378 for tx_hash, tx_height in history:
1379 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1380 missing_tx.append( (tx_hash, tx_height) )
1381 print_error("missing tx", missing_tx)
1383 # wait until we are connected, in case the user is not connected
1384 while not self.interface.is_connected:
1388 self.subscribe_to_addresses(self.wallet.addresses(True))
1390 while self.is_running():
1391 # 1. create new addresses
1392 new_addresses = self.wallet.synchronize()
1394 # request missing addresses
1396 self.subscribe_to_addresses(new_addresses)
1398 # request missing transactions
1399 for tx_hash, tx_height in missing_tx:
1400 if (tx_hash, tx_height) not in requested_tx:
1401 self.interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], 'synchronizer')
1402 requested_tx.append( (tx_hash, tx_height) )
1405 # detect if situation has changed
1406 if not self.interface.is_up_to_date('synchronizer'):
1407 if self.wallet.is_up_to_date():
1408 self.wallet.set_up_to_date(False)
1409 self.was_updated = True
1411 if not self.wallet.is_up_to_date():
1412 self.wallet.set_up_to_date(True)
1413 self.was_updated = True
1415 if self.was_updated:
1416 self.interface.trigger_callback('updated')
1417 self.was_updated = False
1420 r = self.interface.get_response('synchronizer')
1422 # poke sends None. (needed during stop)
1425 # 3. handle response
1426 method = r['method']
1427 params = r['params']
1428 result = r.get('result')
1429 error = r.get('error')
1434 if method == 'blockchain.address.subscribe':
1436 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1437 if requested_histories.get(addr) is None:
1438 self.interface.send([('blockchain.address.get_history', [addr])], 'synchronizer')
1439 requested_histories[addr] = result
1441 elif method == 'blockchain.address.get_history':
1443 print_error("receiving history", addr, result)
1445 assert requested_histories.pop(addr) == '*'
1446 self.wallet.receive_history_callback(addr, result)
1449 # check that txids are unique
1452 tx_hash = item['tx_hash']
1453 if tx_hash not in txids:
1454 txids.append(tx_hash)
1455 hist.append( (tx_hash, item['height']) )
1457 if len(hist) != len(result):
1458 raise BaseException("error: server sent history with non-unique txid", result)
1460 # check that the status corresponds to what was announced
1461 rs = requested_histories.pop(addr)
1462 if self.wallet.get_status(hist) != rs:
1463 raise BaseException("error: status mismatch: %s"%addr)
1465 # store received history
1466 self.wallet.receive_history_callback(addr, hist)
1468 # request transactions that we don't have
1469 for tx_hash, tx_height in hist:
1470 if self.wallet.transactions.get(tx_hash) is None:
1471 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1472 missing_tx.append( (tx_hash, tx_height) )
1474 elif method == 'blockchain.transaction.get':
1476 tx_height = params[1]
1477 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1478 tx = Transaction(result)
1479 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1480 self.was_updated = True
1481 requested_tx.remove( (tx_hash, tx_height) )
1482 print_error("received tx:", tx_hash, len(tx.raw))
1484 elif method == 'blockchain.transaction.broadcast':
1485 self.wallet.tx_result = result
1486 self.wallet.tx_event.set()
1489 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1491 if self.was_updated and not requested_tx:
1492 self.interface.trigger_callback('updated')
1493 self.interface.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
1496 self.was_updated = False