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
39 COINBASE_MATURITY = 100
42 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
43 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
45 def pw_encode(s, password):
47 secret = Hash(password)
48 return EncodeAES(secret, s)
52 def pw_decode(s, password):
53 if password is not None:
54 secret = Hash(password)
56 d = DecodeAES(secret, s)
58 raise BaseException('Invalid password')
67 from version import ELECTRUM_VERSION, SEED_VERSION
72 def __init__(self, config):
73 self.lock = threading.Lock()
75 self.file_exists = False
76 self.path = self.init_path(config)
77 print_error( "wallet path", self.path )
82 def init_path(self, config):
83 """Set the path of the wallet."""
85 # command line -w option
86 path = config.get('wallet_path')
91 path = config.get('default_wallet_path')
95 # default path in pre 1.9 versions
96 old_path = os.path.join(config.path, "electrum.dat")
97 if os.path.exists(old_path):
101 dirpath = os.path.join(config.path, "wallets")
102 if not os.path.exists(dirpath):
105 return os.path.join(config.path, "wallets", "default_wallet")
108 def read(self, path):
109 """Read the contents of the wallet file."""
111 with open(self.path, "r") as f:
116 d = ast.literal_eval( data ) #parse raw data from reading wallet file
118 raise IOError("Cannot read wallet file.")
121 self.file_exists = True
124 def get(self, key, default=None):
125 return self.data.get(key, default)
127 def put(self, key, value, save = True):
130 if value is not None:
131 self.data[key] = value
139 f = open(self.path,"w")
142 if 'ANDROID_DATA' not in os.environ:
144 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
149 def __init__(self, storage):
151 self.storage = storage
152 self.electrum_version = ELECTRUM_VERSION
153 self.gap_limit_for_change = 3 # constant
156 self.seed_version = storage.get('seed_version', SEED_VERSION)
158 self.gap_limit = storage.get('gap_limit', 5)
159 self.use_change = storage.get('use_change',True)
160 self.use_encryption = storage.get('use_encryption', False)
161 self.seed = storage.get('seed', '') # encrypted
162 self.labels = storage.get('labels', {})
163 self.frozen_addresses = storage.get('frozen_addresses',[])
164 self.prioritized_addresses = storage.get('prioritized_addresses',[])
165 self.addressbook = storage.get('contacts', [])
167 self.imported_keys = storage.get('imported_keys',{})
168 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
170 self.fee = int(storage.get('fee_per_kb',20000))
172 self.master_public_keys = storage.get('master_public_keys',{})
173 self.master_private_keys = storage.get('master_private_keys', {})
175 self.next_addresses = storage.get('next_addresses',{})
177 if self.seed_version < 4:
178 raise ValueError("This wallet seed is deprecated.")
182 self.transactions = {}
183 tx_list = self.storage.get('transactions',{})
184 for k,v in tx_list.items():
188 print_msg("Warning: Cannot deserialize transactions. skipping")
191 self.add_extra_addresses(tx)
192 self.transactions[k] = tx
194 for h,tx in self.transactions.items():
195 if not self.check_new_tx(h, tx):
196 print_error("removing unreferenced tx", h)
197 self.transactions.pop(h)
201 self.prevout_values = {} # my own transaction outputs
202 self.spent_outputs = []
207 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
208 # interface.is_up_to_date() returns true when all requests have been answered and processed
209 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
211 self.up_to_date = False
212 self.lock = threading.Lock()
213 self.transaction_lock = threading.Lock()
214 self.tx_event = threading.Event()
216 for tx_hash, tx in self.transactions.items():
217 self.update_tx_outputs(tx_hash)
220 def add_extra_addresses(self, tx):
222 # find the address corresponding to pay-to-pubkey inputs
223 tx.add_extra_addresses(self.transactions)
224 for o in tx.d.get('outputs'):
225 if o.get('is_pubkey'):
226 for tx2 in self.transactions.values():
227 tx2.add_extra_addresses({h:tx})
232 def set_up_to_date(self,b):
233 with self.lock: self.up_to_date = b
236 def is_up_to_date(self):
237 with self.lock: return self.up_to_date
241 self.up_to_date = False
242 while not self.is_up_to_date():
246 def import_key(self, sec, password):
248 seed = self.decode_seed(password)
250 address = address_from_private_key(sec)
252 raise BaseException('Invalid private key')
254 if self.is_mine(address):
255 raise BaseException('Address already in wallet')
257 # store the originally requested keypair into the imported keys table
258 self.imported_keys[address] = pw_encode(sec, password )
259 self.storage.put('imported_keys', self.imported_keys, True)
260 if self.synchronizer:
261 self.synchronizer.subscribe_to_addresses([address])
264 def delete_imported_key(self, addr):
265 if addr in self.imported_keys:
266 self.imported_keys.pop(addr)
267 self.storage.put('imported_keys', self.imported_keys, True)
270 def init_seed(self, seed):
271 if self.seed: raise BaseException("a seed exists")
273 seed = random_seed(128)
278 self.storage.put('seed', self.seed, True)
279 self.storage.put('seed_version', self.seed_version, True)
281 def create_watching_only_wallet(self, c0, K0):
283 self.master_public_keys = {
284 "m/0'/": (c0, K0, cK0),
286 self.storage.put('master_public_keys', self.master_public_keys, True)
287 self.create_account('1','Main account')
290 def create_accounts(self):
291 # create default account
292 self.create_master_keys('1', self.seed)
293 self.create_account('1','Main account')
296 def create_master_keys(self, account_type, seed):
297 master_k, master_c, master_K, master_cK = bip32_init(self.seed)
298 if account_type == '1':
299 k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/")
300 self.master_public_keys["m/0'/"] = (c0, K0, cK0)
301 self.master_private_keys["m/0'/"] = k0
302 elif account_type == '2of2':
303 k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/")
304 k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/")
305 self.master_public_keys["m/1'/"] = (c1, K1, cK1)
306 self.master_public_keys["m/2'/"] = (c2, K2, cK2)
307 self.master_private_keys["m/1'/"] = k1
308 self.master_private_keys["m/2'/"] = k2
309 elif account_type == '2of3':
310 k3, c3, K3, cK3 = bip32_private_derivation(master_k, master_c, "m/", "m/3'/")
311 k4, c4, K4, cK4 = bip32_private_derivation(master_k, master_c, "m/", "m/4'/")
312 k5, c5, K5, cK5 = bip32_private_derivation(master_k, master_c, "m/", "m/5'/")
313 self.master_public_keys["m/3'/"] = (c3, K3, cK3)
314 self.master_public_keys["m/4'/"] = (c4, K4, cK4)
315 self.master_public_keys["m/5'/"] = (c5, K5, cK5)
316 self.master_private_keys["m/3'/"] = k3
317 self.master_private_keys["m/4'/"] = k4
318 self.master_private_keys["m/5'/"] = k5
320 self.storage.put('master_public_keys', self.master_public_keys, True)
321 self.storage.put('master_private_keys', self.master_private_keys, True)
323 def has_master_public_keys(self, account_type):
324 if account_type == '1':
325 return "m/0'/" in self.master_public_keys
326 elif account_type == '2of2':
327 return set(["m/1'/", "m/2'/"]) <= set(self.master_public_keys.keys())
328 elif account_type == '2of3':
329 return set(["m/3'/", "m/4'/", "m/5'/"]) <= set(self.master_public_keys.keys())
331 def find_root_by_master_key(self, c, K):
332 for key, v in self.master_public_keys.items():
333 if key == "m/":continue
335 if (c == cc) and (K == KK):
338 def deseed_root(self, seed, password):
339 # for safety, we ask the user to enter their seed
340 assert seed == self.decode_seed(password)
342 self.storage.put('seed', '', True)
345 def deseed_branch(self, k):
346 # check that parent has no seed
347 assert self.seed == ''
348 self.master_private_keys.pop(k)
349 self.storage.put('master_private_keys', self.master_private_keys, True)
351 def is_watching_only(self):
352 return (self.seed == '') and (self.master_private_keys == {})
356 def account_id(self, account_type, i):
357 if account_type == '1':
359 elif account_type == '2of2':
360 return "m/1'/%d & m/2'/%d"%(i,i)
361 elif account_type == '2of3':
362 return "m/3'/%d & m/4'/%d & m/5'/%d"%(i,i,i)
364 raise BaseException('unknown account type')
367 def num_accounts(self, account_type):
368 keys = self.accounts.keys()
371 account_id = self.account_id(account_type, i)
372 if account_id not in keys: break
377 def new_account_address(self, account_type = '1'):
378 i = self.num_accounts(account_type)
379 k = self.account_id(account_type,i)
381 addr = self.next_addresses.get(k)
383 account_id, account = self.next_account(account_type)
384 addr = account.first_address()
385 self.next_addresses[k] = addr
386 self.storage.put('next_addresses',self.next_addresses)
391 def next_account(self, account_type = '1'):
393 i = self.num_accounts(account_type)
394 account_id = self.account_id(account_type,i)
396 if account_type is '1':
397 master_c0, master_K0, _ = self.master_public_keys["m/0'/"]
398 c0, K0, cK0 = bip32_public_derivation(master_c0.decode('hex'), master_K0.decode('hex'), "m/0'/", "m/0'/%d"%i)
399 account = BIP32_Account({ 'c':c0, 'K':K0, 'cK':cK0 })
401 elif account_type == '2of2':
402 master_c1, master_K1, _ = self.master_public_keys["m/1'/"]
403 c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i)
404 master_c2, master_K2, _ = self.master_public_keys["m/2'/"]
405 c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i)
406 account = BIP32_Account_2of2({ 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 })
408 elif account_type == '2of3':
409 master_c3, master_K3, _ = self.master_public_keys["m/3'/"]
410 c3, K3, cK3 = bip32_public_derivation(master_c3.decode('hex'), master_K3.decode('hex'), "m/3'/", "m/3'/%d"%i)
411 master_c4, master_K4, _ = self.master_public_keys["m/4'/"]
412 c4, K4, cK4 = bip32_public_derivation(master_c4.decode('hex'), master_K4.decode('hex'), "m/4'/", "m/4'/%d"%i)
413 master_c5, master_K5, _ = self.master_public_keys["m/5'/"]
414 c5, K5, cK5 = bip32_public_derivation(master_c5.decode('hex'), master_K5.decode('hex'), "m/5'/", "m/5'/%d"%i)
415 account = BIP32_Account_2of3({ 'c':c3, 'K':K3, 'cK':cK3, 'c2':c4, 'K2':K4, 'cK2':cK4, 'c3':c5, 'K3':K5, 'cK3':cK5 })
417 return account_id, account
420 def set_label(self, name, text = None):
422 old_text = self.labels.get(name)
425 self.labels[name] = text
429 self.labels.pop(name)
433 self.storage.put('labels', self.labels, True)
435 run_hook('set_label', name, text, changed)
440 def create_account(self, account_type = '1', name = None):
441 k, account = self.next_account(account_type)
442 if k in self.pending_accounts:
443 self.pending_accounts.pop(k)
444 self.storage.put('pending_accounts', self.pending_accounts)
446 self.accounts[k] = account
449 self.set_label(k, name)
452 def create_old_account(self):
453 mpk = OldAccount.mpk_from_seed(self.seed)
454 self.storage.put('master_public_key', mpk, True)
455 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
459 def save_accounts(self):
461 for k, v in self.accounts.items():
463 self.storage.put('accounts', d, True)
467 def load_accounts(self):
468 d = self.storage.get('accounts', {})
470 for k, v in d.items():
472 v['mpk'] = self.storage.get('master_public_key')
473 self.accounts[k] = OldAccount(v)
475 self.accounts[k] = BIP32_Account_2of2(v)
477 self.accounts[k] = BIP32_Account(v)
479 self.pending_accounts = self.storage.get('pending_accounts',{})
482 def delete_pending_account(self, k):
483 self.pending_accounts.pop(k)
484 self.storage.put('pending_accounts', self.pending_accounts)
486 def account_is_pending(self, k):
487 return k in self.pending_accounts
489 def create_pending_account(self, acct_type, name):
490 k, addr = self.new_account_address(acct_type)
491 self.set_label(k, name)
492 self.pending_accounts[k] = addr
493 self.storage.put('pending_accounts', self.pending_accounts)
495 def get_pending_accounts(self):
496 return self.pending_accounts.items()
499 def addresses(self, include_change = True, _next=True):
500 o = self.get_account_addresses(-1, include_change)
501 for a in self.accounts.keys():
502 o += self.get_account_addresses(a, include_change)
505 for addr in self.next_addresses.values():
511 def is_mine(self, address):
512 return address in self.addresses(True)
515 def is_change(self, address):
516 if not self.is_mine(address): return False
517 if address in self.imported_keys.keys(): return False
518 acct, s = self.get_address_index(address)
519 if s is None: return False
522 def get_master_public_key(self):
523 if self.seed_version == 4:
524 return self.storage.get("master_public_key")
526 c, K, cK = self.storage.get("master_public_keys")["m/0'/"]
529 def get_master_private_key(self, account, password):
530 master_k = pw_decode( self.master_private_keys[account], password)
531 master_c, master_K, master_Kc = self.master_public_keys[account]
533 K, Kc = get_pubkeys_from_secret(master_k.decode('hex'))
534 assert K.encode('hex') == master_K
536 raise BaseException("Invalid password")
540 def get_address_index(self, address):
541 if address in self.imported_keys.keys():
544 for account in self.accounts.keys():
545 for for_change in [0,1]:
546 addresses = self.accounts[account].get_addresses(for_change)
547 for addr in addresses:
549 return account, (for_change, addresses.index(addr))
551 for k,v in self.next_addresses.items():
555 raise BaseException("Address not found", address)
558 def get_roots(self, account):
560 for a in account.split('&'):
562 m = re.match("(m/\d+'/)(\d+)", s)
563 roots.append( m.group(1) )
566 def is_seeded(self, account):
567 if type(account) is int:
568 return self.seed is not None
570 for root in self.get_roots(account):
571 if root not in self.master_private_keys.keys():
575 def rebase_sequence(self, account, sequence):
578 for a in account.split('&'):
580 m = re.match("(m/\d+'/)(\d+)", s)
582 num = int(m.group(2))
583 dd.append( (root, [num,c,i] ) )
587 def get_keyID(self, account, sequence):
591 rs = self.rebase_sequence(account, sequence)
593 for root, public_sequence in rs:
594 c, K, _ = self.master_public_keys[root]
595 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
596 dd.append( 'bip32(%s,%s,%s)'%(c,K, s) )
601 def decode_seed(self, password):
602 seed = pw_decode(self.seed, password)
603 #todo: #self.sequences[0].check_seed(seed)
607 def get_private_key(self, address, password):
609 if address in self.imported_keys.keys():
610 out.append( pw_decode( self.imported_keys[address], password ) )
612 account, sequence = self.get_address_index(address)
614 seed = self.decode_seed(password)
615 pk = self.accounts[account].get_private_key(seed, sequence)
619 # assert address == self.accounts[account].get_address(*sequence)
620 rs = self.rebase_sequence( account, sequence)
621 for root, public_sequence in rs:
623 if root not in self.master_private_keys.keys(): continue
624 master_k = self.get_master_private_key(root, password)
625 master_c, _, _ = self.master_public_keys[root]
626 pk = bip32_private_key( public_sequence, master_k.decode('hex'), master_c.decode('hex'))
632 def add_keypairs_from_wallet(self, tx, keypairs, password):
633 for txin in tx.inputs:
634 address = txin['address']
635 private_keys = self.get_private_key(address, password)
636 for sec in private_keys:
637 pubkey = public_key_from_private_key(sec)
638 keypairs[ pubkey ] = sec
641 def add_keypairs_from_KeyID(self, tx, keypairs, password):
642 for txin in tx.inputs:
643 keyid = txin.get('KeyID')
646 for s in keyid.split('&'):
647 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
651 sequence = m.group(3)
652 root = self.find_root_by_master_key(c,K)
653 if not root: continue
654 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
655 root = root + '%d'%sequence[0]
656 sequence = sequence[1:]
657 roots.append((root,sequence))
659 account_id = " & ".join( map(lambda x:x[0], roots) )
660 account = self.accounts.get(account_id)
661 if not account: continue
662 addr = account.get_address(*sequence)
663 txin['address'] = addr # fixme: side effect
664 pk = self.get_private_key(addr, password)
666 pubkey = public_key_from_private_key(sec)
667 keypairs[pubkey] = sec
671 def signrawtransaction(self, tx, input_info, private_keys, password):
673 # check that the password is correct
674 seed = self.decode_seed(password)
677 tx.add_input_info(input_info)
679 # add redeem script for coins that are in the wallet
680 # FIXME: add redeemPubkey too!
681 unspent_coins = self.get_unspent_coins()
682 for txin in tx.inputs:
683 for item in unspent_coins:
684 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
685 print_error( "tx input is in unspent coins" )
686 txin['scriptPubKey'] = item['scriptPubKey']
687 account, sequence = self.get_address_index(item['address'])
689 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
690 print_error("added redeemScript", txin['redeemScript'])
694 # build a list of public/private keys
697 # add private keys from parameter
698 for sec in private_keys:
699 pubkey = public_key_from_private_key(sec)
700 keypairs[ pubkey ] = sec
702 # add private_keys from KeyID
703 self.add_keypairs_from_KeyID(tx, keypairs, password)
705 # add private keys from wallet
706 self.add_keypairs_from_wallet(tx, keypairs, password)
707 self.sign_transaction(tx, keypairs)
710 def sign_message(self, address, message, password):
711 keys = self.get_private_key(address, password)
712 assert len(keys) == 1
714 key = regenerate_key(sec)
715 compressed = is_compressed(sec)
716 return key.sign_message(message, compressed, address)
719 def change_gap_limit(self, value):
720 if value >= self.gap_limit:
721 self.gap_limit = value
722 self.storage.put('gap_limit', self.gap_limit, True)
723 #self.interface.poke('synchronizer')
726 elif value >= self.min_acceptable_gap():
727 for key, account in self.accounts.items():
728 addresses = account[0]
729 k = self.num_unused_trailing_addresses(addresses)
730 n = len(addresses) - k + value
731 addresses = addresses[0:n]
732 self.accounts[key][0] = addresses
734 self.gap_limit = value
735 self.storage.put('gap_limit', self.gap_limit, True)
741 def num_unused_trailing_addresses(self, addresses):
743 for a in addresses[::-1]:
744 if self.history.get(a):break
748 def min_acceptable_gap(self):
749 # fixme: this assumes wallet is synchronized
753 for account in self.accounts.values():
754 addresses = account.get_addresses(0)
755 k = self.num_unused_trailing_addresses(addresses)
756 for a in addresses[0:-k]:
757 if self.history.get(a):
761 if n > nmax: nmax = n
765 def address_is_old(self, address):
767 h = self.history.get(address, [])
770 for tx_hash, tx_height in h:
774 tx_age = self.verifier.blockchain.height() - tx_height + 1
780 def synchronize_sequence(self, account, for_change):
781 limit = self.gap_limit_for_change if for_change else self.gap_limit
784 addresses = account.get_addresses(for_change)
785 if len(addresses) < limit:
786 address = account.create_new_address(for_change)
787 self.history[address] = []
788 new_addresses.append( address )
791 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
794 address = account.create_new_address(for_change)
795 self.history[address] = []
796 new_addresses.append( address )
802 def create_pending_accounts(self):
803 for account_type in ['1','2of2','2of3']:
804 if not self.has_master_public_keys(account_type):
806 k, a = self.new_account_address(account_type)
807 if self.address_is_old(a):
808 print_error( "creating account", a )
809 self.create_account(account_type)
810 self.next_addresses.pop(k)
813 def synchronize_account(self, account):
815 new += self.synchronize_sequence(account, 0)
816 new += self.synchronize_sequence(account, 1)
820 def synchronize(self):
821 if self.master_public_keys:
822 self.create_pending_accounts()
824 for account in self.accounts.values():
825 new += self.synchronize_account(account)
828 self.storage.put('addr_history', self.history, True)
833 return self.history.values() != [[]] * len(self.history)
836 def add_contact(self, address, label=None):
837 self.addressbook.append(address)
838 self.storage.put('contacts', self.addressbook, True)
840 self.set_label(address, label)
843 def delete_contact(self, addr):
844 if addr in self.addressbook:
845 self.addressbook.remove(addr)
846 self.storage.put('addressbook', self.addressbook, True)
849 def fill_addressbook(self):
850 for tx_hash, tx in self.transactions.items():
851 is_relevant, is_send, _, _ = self.get_tx_value(tx)
853 for addr, v in tx.outputs:
854 if not self.is_mine(addr) and addr not in self.addressbook:
855 self.addressbook.append(addr)
857 # self.update_tx_labels()
859 def get_num_tx(self, address):
861 for tx in self.transactions.values():
862 if address in map(lambda x:x[0], tx.outputs): n += 1
866 def get_address_flags(self, addr):
867 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
868 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
872 def get_tx_value(self, tx, account=None):
873 domain = self.get_account_addresses(account)
874 return tx.get_value(domain, self.prevout_values)
877 def update_tx_outputs(self, tx_hash):
878 tx = self.transactions.get(tx_hash)
880 for i, (addr, value) in enumerate(tx.outputs):
881 key = tx_hash+ ':%d'%i
882 self.prevout_values[key] = value
884 for item in tx.inputs:
885 if self.is_mine(item.get('address')):
886 key = item['prevout_hash'] + ':%d'%item['prevout_n']
887 self.spent_outputs.append(key)
890 def get_addr_balance(self, address):
891 assert self.is_mine(address)
892 h = self.history.get(address,[])
893 if h == ['*']: return 0,0
895 received_coins = [] # list of coins received at address
897 for tx_hash, tx_height in h:
898 tx = self.transactions.get(tx_hash)
901 for i, (addr, value) in enumerate(tx.outputs):
903 key = tx_hash + ':%d'%i
904 received_coins.append(key)
906 for tx_hash, tx_height in h:
907 tx = self.transactions.get(tx_hash)
911 for item in tx.inputs:
912 addr = item.get('address')
914 key = item['prevout_hash'] + ':%d'%item['prevout_n']
915 value = self.prevout_values.get( key )
916 if key in received_coins:
919 for i, (addr, value) in enumerate(tx.outputs):
920 key = tx_hash + ':%d'%i
931 def get_account_name(self, k):
933 if self.seed_version == 4:
934 name = 'Main account'
938 default = "Unnamed account"
939 m = re.match("m/0'/(\d+)", k)
943 default = "Main account"
945 default = "Account %s"%num
947 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
950 default = "2of2 account %s"%num
951 name = self.labels.get(k, default)
955 def get_account_names(self):
957 for k, account in self.accounts.items():
958 accounts[k] = self.get_account_name(k)
959 if self.imported_keys:
960 accounts[-1] = 'Imported keys'
963 def get_account_addresses(self, a, include_change=True):
965 o = self.addresses(True)
967 o = self.imported_keys.keys()
969 ac = self.accounts[a]
970 o = ac.get_addresses(0)
971 if include_change: o += ac.get_addresses(1)
974 def get_imported_balance(self):
975 return self.get_balance(self.imported_keys.keys())
977 def get_account_balance(self, account):
978 return self.get_balance(self.get_account_addresses(account))
980 def get_frozen_balance(self):
981 return self.get_balance(self.frozen_addresses)
983 def get_balance(self, domain=None):
984 if domain is None: domain = self.addresses(True)
987 c, u = self.get_addr_balance(addr)
993 def get_unspent_coins(self, domain=None):
995 if domain is None: domain = self.addresses(True)
997 h = self.history.get(addr, [])
998 if h == ['*']: continue
999 for tx_hash, tx_height in h:
1000 tx = self.transactions.get(tx_hash)
1001 if tx is None: raise BaseException("Wallet not synchronized")
1002 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1003 for output in tx.d.get('outputs'):
1004 if output.get('address') != addr: continue
1005 key = tx_hash + ":%d" % output.get('prevout_n')
1006 if key in self.spent_outputs: continue
1007 output['prevout_hash'] = tx_hash
1008 output['height'] = tx_height
1009 output['coinbase'] = is_coinbase
1010 coins.append((tx_height, output))
1014 coins = sorted(coins)
1015 if coins[-1][0] != 0:
1016 while coins[0][0] == 0:
1017 coins = coins[1:] + [ coins[0] ]
1018 return [x[1] for x in coins]
1022 def choose_tx_inputs_from_account( self, amount, fixed_fee, account ):
1023 domain = self.get_account_addresses(account) if account else None
1024 return self.choose_tx_inputs( amount, fixed_fee, domain )
1027 def choose_tx_inputs( self, amount, fixed_fee, domain = None ):
1028 """ todo: minimize tx size """
1030 fee = self.fee if fixed_fee is None else fixed_fee
1032 domain = self.addresses(True)
1034 for i in self.frozen_addresses:
1035 if i in domain: domain.remove(i)
1038 for i in self.prioritized_addresses:
1041 prioritized.append(i)
1043 coins = self.get_unspent_coins(domain)
1044 prioritized_coins = self.get_unspent_coins(prioritized)
1047 coins = prioritized_coins + coins
1050 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.blockchain.height:
1052 addr = item.get('address')
1053 v = item.get('value')
1056 fee = self.estimated_fee(inputs) if fixed_fee is None else fixed_fee
1057 if total >= amount + fee: break
1061 return inputs, total, fee
1064 def set_fee(self, fee):
1067 self.storage.put('fee_per_kb', self.fee, True)
1069 def estimated_fee(self, inputs):
1070 estimated_size = len(inputs) * 180 + 80 # this assumes non-compressed keys
1071 fee = self.fee * int(round(estimated_size/1024.))
1072 if fee == 0: fee = self.fee
1076 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1077 "add change to a transaction"
1078 change_amount = total - ( amount + fee )
1079 if change_amount != 0:
1082 # send change to one of the accounts involved in the tx
1083 address = inputs[0].get('address')
1084 account, _ = self.get_address_index(address)
1086 if not self.use_change or account == -1:
1087 change_addr = inputs[-1]['address']
1089 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1091 # Insert the change output at a random position in the outputs
1092 posn = random.randint(0, len(outputs))
1093 outputs[posn:posn] = [( change_addr, change_amount)]
1097 def get_history(self, address):
1099 return self.history.get(address)
1102 def get_status(self, h):
1103 if not h: return None
1104 if h == ['*']: return '*'
1106 for tx_hash, height in h:
1107 status += tx_hash + ':%d:' % height
1108 return hashlib.sha256( status ).digest().encode('hex')
1111 def receive_tx_callback(self, tx_hash, tx, tx_height):
1113 with self.transaction_lock:
1114 self.add_extra_addresses(tx)
1115 if not self.check_new_tx(tx_hash, tx):
1116 # may happen due to pruning
1117 print_error("received transaction that is no longer referenced in history", tx_hash)
1119 self.transactions[tx_hash] = tx
1120 self.network.interface.pending_transactions_for_notifications.append(tx)
1121 self.save_transactions()
1122 if self.verifier and tx_height>0:
1123 self.verifier.add(tx_hash, tx_height)
1124 self.update_tx_outputs(tx_hash)
1127 def save_transactions(self):
1129 for k,v in self.transactions.items():
1131 self.storage.put('transactions', tx, True)
1133 def receive_history_callback(self, addr, hist):
1135 if not self.check_new_history(addr, hist):
1136 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
1139 self.history[addr] = hist
1140 self.storage.put('addr_history', self.history, True)
1143 for tx_hash, tx_height in hist:
1145 # add it in case it was previously unconfirmed
1146 if self.verifier: self.verifier.add(tx_hash, tx_height)
1149 def get_tx_history(self, account=None):
1150 with self.transaction_lock:
1151 history = self.transactions.items()
1152 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1156 for tx_hash, tx in history:
1157 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1158 if v is not None: balance += v
1160 c, u = self.get_account_balance(account)
1163 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1165 balance = c + u - balance
1166 for tx_hash, tx in history:
1167 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1170 if value is not None:
1173 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1174 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1179 def get_label(self, tx_hash):
1180 label = self.labels.get(tx_hash)
1181 is_default = (label == '') or (label is None)
1182 if is_default: label = self.get_default_label(tx_hash)
1183 return label, is_default
1186 def get_default_label(self, tx_hash):
1187 tx = self.transactions.get(tx_hash)
1190 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1192 for o in tx.outputs:
1194 if not self.is_mine(o_addr):
1196 default_label = self.labels[o_addr]
1198 default_label = o_addr
1201 default_label = '(internal)'
1203 for o in tx.outputs:
1205 if self.is_mine(o_addr) and not self.is_change(o_addr):
1208 for o in tx.outputs:
1210 if self.is_mine(o_addr):
1216 dest_label = self.labels.get(o_addr)
1218 default_label = self.labels[o_addr]
1220 default_label = o_addr
1222 return default_label
1225 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1226 for address, x in outputs:
1227 assert is_valid(address)
1228 amount = sum( map(lambda x:x[1], outputs) )
1229 inputs, total, fee = self.choose_tx_inputs( amount, fee, domain )
1231 raise ValueError("Not enough funds")
1232 self.add_input_info(inputs)
1233 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1234 return Transaction.from_io(inputs, outputs)
1237 def mktx_from_account(self, outputs, password, fee=None, account=None):
1238 domain = self.get_account_addresses(account) if account else None
1239 return self.mktx(outputs, password, fee, change_addr=None, domain=domain)
1242 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1243 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1245 self.add_keypairs_from_wallet(tx, keypairs, password)
1247 self.sign_transaction(tx, keypairs)
1251 def add_input_info(self, inputs):
1253 address = txin['address']
1254 account, sequence = self.get_address_index(address)
1255 txin['KeyID'] = self.get_keyID(account, sequence)
1256 redeemScript = self.accounts[account].redeem_script(sequence)
1258 txin['redeemScript'] = redeemScript
1260 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1263 def sign_transaction(self, tx, keypairs):
1265 run_hook('sign_transaction', tx)
1268 def sendtx(self, tx):
1270 h = self.send_tx(tx)
1271 self.tx_event.wait()
1272 return self.receive_tx(h)
1274 def send_tx(self, tx):
1276 self.tx_event.clear()
1277 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1280 def on_broadcast(self, i, r):
1281 self.tx_result = r.get('result')
1284 def receive_tx(self,tx_hash):
1285 out = self.tx_result
1287 return False, "error: " + out
1292 def update_password(self, seed, old_password, new_password):
1293 if new_password == '': new_password = None
1294 # this will throw an exception if unicode cannot be converted
1295 self.seed = pw_encode( seed, new_password)
1296 self.storage.put('seed', self.seed, True)
1297 self.use_encryption = (new_password != None)
1298 self.storage.put('use_encryption', self.use_encryption,True)
1299 for k in self.imported_keys.keys():
1300 a = self.imported_keys[k]
1301 b = pw_decode(a, old_password)
1302 c = pw_encode(b, new_password)
1303 self.imported_keys[k] = c
1304 self.storage.put('imported_keys', self.imported_keys, True)
1306 for k, v in self.master_private_keys.items():
1307 b = pw_decode(v, old_password)
1308 c = pw_encode(b, new_password)
1309 self.master_private_keys[k] = c
1310 self.storage.put('master_private_keys', self.master_private_keys, True)
1313 def freeze(self,addr):
1314 if self.is_mine(addr) and addr not in self.frozen_addresses:
1315 self.unprioritize(addr)
1316 self.frozen_addresses.append(addr)
1317 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1322 def unfreeze(self,addr):
1323 if self.is_mine(addr) and addr in self.frozen_addresses:
1324 self.frozen_addresses.remove(addr)
1325 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1330 def prioritize(self,addr):
1331 if self.is_mine(addr) and addr not in self.prioritized_addresses:
1333 self.prioritized_addresses.append(addr)
1334 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1339 def unprioritize(self,addr):
1340 if self.is_mine(addr) and addr in self.prioritized_addresses:
1341 self.prioritized_addresses.remove(addr)
1342 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1348 def set_verifier(self, verifier):
1349 self.verifier = verifier
1351 # review transactions that are in the history
1352 for addr, hist in self.history.items():
1353 if hist == ['*']: continue
1354 for tx_hash, tx_height in hist:
1356 # add it in case it was previously unconfirmed
1357 self.verifier.add(tx_hash, tx_height)
1360 # if we are on a pruning server, remove unverified transactions
1361 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1362 for tx_hash in self.transactions.keys():
1363 if tx_hash not in vr:
1364 self.transactions.pop(tx_hash)
1368 def check_new_history(self, addr, hist):
1370 # check that all tx in hist are relevant
1372 for tx_hash, height in hist:
1373 tx = self.transactions.get(tx_hash)
1375 if not tx.has_address(addr):
1378 # check that we are not "orphaning" a transaction
1379 old_hist = self.history.get(addr,[])
1380 if old_hist == ['*']: return True
1382 for tx_hash, height in old_hist:
1383 if tx_hash in map(lambda x:x[0], hist): continue
1385 for _addr, _hist in self.history.items():
1386 if _addr == addr: continue
1387 if _hist == ['*']: continue
1388 _tx_hist = map(lambda x:x[0], _hist)
1389 if tx_hash in _tx_hist:
1394 tx = self.transactions.get(tx_hash)
1395 # tx might not be there
1399 if self.verifier.get_height(tx_hash):
1402 print_error("new history is orphaning transaction:", tx_hash)
1403 # check that all outputs are not mine, request histories
1405 for _addr, _v in tx.outputs:
1406 # assert not self.is_mine(_addr)
1407 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1409 ext_h = self.network.synchronous_get(ext_requests)
1410 print_error("sync:", ext_requests, ext_h)
1413 if h == ['*']: continue
1415 if item.get('tx_hash') == tx_hash:
1416 height = item.get('height')
1418 print_error("found height for", tx_hash, height)
1419 self.verifier.add(tx_hash, height)
1421 print_error("removing orphaned tx from history", tx_hash)
1422 self.transactions.pop(tx_hash)
1428 def check_new_tx(self, tx_hash, tx):
1429 # 1 check that tx is referenced in addr_history.
1431 for addr, hist in self.history.items():
1432 if hist == ['*']:continue
1433 for txh, height in hist:
1435 addresses.append(addr)
1440 # 2 check that referencing addresses are in the tx
1441 for addr in addresses:
1442 if not tx.has_address(addr):
1448 def start_threads(self, network):
1449 from verifier import TxVerifier
1450 self.network = network
1451 self.verifier = TxVerifier(self.network, self.storage)
1452 self.verifier.start()
1453 self.set_verifier(self.verifier)
1454 self.synchronizer = WalletSynchronizer(self, network)
1455 self.synchronizer.start()
1457 def stop_threads(self):
1458 self.verifier.stop()
1459 self.synchronizer.stop()
1463 def restore(self, callback):
1465 def wait_for_wallet():
1466 self.set_up_to_date(False)
1467 while not self.is_up_to_date():
1468 msg = "%s\n%s %d\n%s %.1f"%(
1469 _("Please wait..."),
1470 _("Addresses generated:"),
1471 len(self.addresses(True)),_("Kilobytes received:"),
1472 self.network.interface.bytes_received/1024.)
1474 apply(callback, (msg,))
1477 def wait_for_network():
1478 while not self.network.interface.is_connected:
1479 msg = "%s \n" % (_("Connecting..."))
1480 apply(callback, (msg,))
1483 # wait until we are connected, because the user might have selected another server
1486 # try to restore old account
1487 self.create_old_account()
1491 self.seed_version = 4
1492 self.storage.put('seed_version', self.seed_version, True)
1494 self.accounts.pop(0)
1495 self.create_accounts()
1501 class WalletSynchronizer(threading.Thread):
1504 def __init__(self, wallet, network):
1505 threading.Thread.__init__(self)
1507 self.wallet = wallet
1508 self.network = network
1509 self.was_updated = True
1510 self.running = False
1511 self.lock = threading.Lock()
1512 self.queue = Queue.Queue()
1515 with self.lock: self.running = False
1517 def is_running(self):
1518 with self.lock: return self.running
1521 def subscribe_to_addresses(self, addresses):
1523 for addr in addresses:
1524 messages.append(('blockchain.address.subscribe', [addr]))
1525 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1532 while self.is_running():
1534 if not self.network.is_connected():
1535 print_error("synchronizer: waiting for interface")
1536 self.network.wait_until_connected()
1538 self.run_interface(self.network.interface)
1541 def run_interface(self, interface):
1543 print_error("synchronizer: connected to", interface.server)
1547 requested_histories = {}
1549 # request any missing transactions
1550 for history in self.wallet.history.values():
1551 if history == ['*']: continue
1552 for tx_hash, tx_height in history:
1553 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1554 missing_tx.append( (tx_hash, tx_height) )
1557 print_error("missing tx", missing_tx)
1560 self.subscribe_to_addresses(self.wallet.addresses(True))
1562 while self.is_running():
1563 # 1. create new addresses
1564 new_addresses = self.wallet.synchronize()
1566 # request missing addresses
1568 self.subscribe_to_addresses(new_addresses)
1570 # request missing transactions
1571 for tx_hash, tx_height in missing_tx:
1572 if (tx_hash, tx_height) not in requested_tx:
1573 interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1574 requested_tx.append( (tx_hash, tx_height) )
1577 # detect if situation has changed
1578 if interface.is_up_to_date() and self.queue.empty():
1579 if not self.wallet.is_up_to_date():
1580 self.wallet.set_up_to_date(True)
1581 self.was_updated = True
1583 if self.wallet.is_up_to_date():
1584 self.wallet.set_up_to_date(False)
1585 self.was_updated = True
1587 if self.was_updated:
1588 self.wallet.network.trigger_callback('updated')
1589 self.was_updated = False
1593 r = self.queue.get(block=True, timeout=1)
1597 if interface != self.network.interface:
1603 # 3. handle response
1604 method = r['method']
1605 params = r['params']
1606 result = r.get('result')
1607 error = r.get('error')
1612 if method == 'blockchain.address.subscribe':
1614 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1615 if requested_histories.get(addr) is None:
1616 interface.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1617 requested_histories[addr] = result
1619 elif method == 'blockchain.address.get_history':
1621 print_error("receiving history", addr, result)
1623 assert requested_histories.pop(addr) == '*'
1624 self.wallet.receive_history_callback(addr, result)
1627 # check that txids are unique
1630 tx_hash = item['tx_hash']
1631 if tx_hash not in txids:
1632 txids.append(tx_hash)
1633 hist.append( (tx_hash, item['height']) )
1635 if len(hist) != len(result):
1636 raise BaseException("error: server sent history with non-unique txid", result)
1638 # check that the status corresponds to what was announced
1639 rs = requested_histories.pop(addr)
1640 if self.wallet.get_status(hist) != rs:
1641 raise BaseException("error: status mismatch: %s"%addr)
1643 # store received history
1644 self.wallet.receive_history_callback(addr, hist)
1646 # request transactions that we don't have
1647 for tx_hash, tx_height in hist:
1648 if self.wallet.transactions.get(tx_hash) is None:
1649 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1650 missing_tx.append( (tx_hash, tx_height) )
1652 elif method == 'blockchain.transaction.get':
1654 tx_height = params[1]
1655 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1656 tx = Transaction(result)
1657 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1658 self.was_updated = True
1659 requested_tx.remove( (tx_hash, tx_height) )
1660 print_error("received tx:", tx_hash, len(tx.raw))
1663 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1665 if self.was_updated and not requested_tx:
1666 self.wallet.network.trigger_callback('updated')
1667 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
1669 self.was_updated = False