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')
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')
96 dirpath = os.path.join(config.path, "wallets")
97 if not os.path.exists(dirpath):
100 new_path = os.path.join(config.path, "wallets", "default_wallet")
102 # default path in pre 1.9 versions
103 old_path = os.path.join(config.path, "electrum.dat")
104 if os.path.exists(old_path) and not os.path.exists(new_path):
105 os.rename(old_path, new_path)
110 def read(self, path):
111 """Read the contents of the wallet file."""
113 with open(self.path, "r") as f:
118 d = ast.literal_eval( data ) #parse raw data from reading wallet file
120 raise IOError("Cannot read wallet file.")
123 self.file_exists = True
126 def get(self, key, default=None):
127 return self.data.get(key, default)
129 def put(self, key, value, save = True):
132 if value is not None:
133 self.data[key] = value
141 f = open(self.path,"w")
144 if 'ANDROID_DATA' not in os.environ:
146 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
151 def __init__(self, storage):
153 self.storage = storage
154 self.electrum_version = ELECTRUM_VERSION
155 self.gap_limit_for_change = 3 # constant
158 self.seed_version = storage.get('seed_version', SEED_VERSION)
160 self.gap_limit = storage.get('gap_limit', 5)
161 self.use_change = storage.get('use_change',True)
162 self.use_encryption = storage.get('use_encryption', False)
163 self.seed = storage.get('seed', '') # encrypted
164 self.labels = storage.get('labels', {})
165 self.frozen_addresses = storage.get('frozen_addresses',[])
166 self.prioritized_addresses = storage.get('prioritized_addresses',[])
167 self.addressbook = storage.get('contacts', [])
169 self.imported_keys = storage.get('imported_keys',{})
170 self.history = storage.get('addr_history',{}) # address -> list(txid, height)
172 self.fee = int(storage.get('fee_per_kb',20000))
174 self.master_public_keys = storage.get('master_public_keys',{})
175 self.master_private_keys = storage.get('master_private_keys', {})
177 self.next_addresses = storage.get('next_addresses',{})
179 if self.seed_version not in [4, 6]:
180 msg = "This wallet seed is not supported."
181 if self.seed_version in [5]:
182 msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%self.seed_version
189 self.transactions = {}
190 tx_list = self.storage.get('transactions',{})
191 for k,v in tx_list.items():
195 print_msg("Warning: Cannot deserialize transactions. skipping")
198 self.add_extra_addresses(tx)
199 self.transactions[k] = tx
201 for h,tx in self.transactions.items():
202 if not self.check_new_tx(h, tx):
203 print_error("removing unreferenced tx", h)
204 self.transactions.pop(h)
208 self.prevout_values = {} # my own transaction outputs
209 self.spent_outputs = []
214 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
215 # interface.is_up_to_date() returns true when all requests have been answered and processed
216 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
218 self.up_to_date = False
219 self.lock = threading.Lock()
220 self.transaction_lock = threading.Lock()
221 self.tx_event = threading.Event()
223 for tx_hash, tx in self.transactions.items():
224 self.update_tx_outputs(tx_hash)
227 def add_extra_addresses(self, tx):
229 # find the address corresponding to pay-to-pubkey inputs
230 tx.add_extra_addresses(self.transactions)
231 for o in tx.d.get('outputs'):
232 if o.get('is_pubkey'):
233 for tx2 in self.transactions.values():
234 tx2.add_extra_addresses({h:tx})
239 def set_up_to_date(self,b):
240 with self.lock: self.up_to_date = b
243 def is_up_to_date(self):
244 with self.lock: return self.up_to_date
248 self.up_to_date = False
249 while not self.is_up_to_date():
253 def import_key(self, sec, password):
255 seed = self.get_seed(password)
257 address = address_from_private_key(sec)
259 raise BaseException('Invalid private key')
261 if self.is_mine(address):
262 raise BaseException('Address already in wallet')
264 # store the originally requested keypair into the imported keys table
265 self.imported_keys[address] = pw_encode(sec, password )
266 self.storage.put('imported_keys', self.imported_keys, True)
267 if self.synchronizer:
268 self.synchronizer.subscribe_to_addresses([address])
271 def delete_imported_key(self, addr):
272 if addr in self.imported_keys:
273 self.imported_keys.pop(addr)
274 self.storage.put('imported_keys', self.imported_keys, True)
278 import mnemonic, ecdsa
279 entropy = ecdsa.util.randrange( pow(2,160) )
282 ss = "%040x"%(entropy+nonce)
283 s = hashlib.sha256(ss.decode('hex')).digest().encode('hex')
284 # we keep only 13 words, that's approximately 139 bits of entropy
285 words = mnemonic.mn_encode(s)[0:13]
286 seed = ' '.join(words)
287 if mnemonic_hash(seed).startswith(SEED_PREFIX):
288 break # this removes 12 bits of entropy
294 def init_seed(self, seed):
298 raise BaseException("a seed exists")
301 self.seed = random_seed(128)
302 self.seed_version = 4
306 # self.seed = self.make_seed()
307 # self.seed_version = SEED_VERSION
310 # find out what kind of wallet we are
313 self.seed_version = 4
314 self.seed = str(seed)
320 self.seed_version = 4
321 self.seed = mnemonic.mn_decode(words)
324 # mnemonic.mn_decode(words)
325 # uses_electrum_words = True
327 # uses_electrum_words = False
329 #if uses_electrum_words and len(words) != 13:
330 # self.seed_version = 4
331 # self.seed = mnemonic.mn_decode(words)
333 # assert mnemonic_hash(seed).startswith(SEED_PREFIX)
334 # self.seed_version = SEED_VERSION
339 self.storage.put('seed', self.seed, True)
340 self.storage.put('seed_version', self.seed_version, True)
342 def create_watching_only_wallet(self, c0, K0):
344 self.master_public_keys = {
345 "m/0'/": (c0, K0, cK0),
347 self.storage.put('master_public_keys', self.master_public_keys, True)
348 self.create_account('1','Main account')
351 def create_accounts(self):
352 if self.seed_version == 4:
353 self.create_old_account()
355 # create default account
356 self.create_master_keys('1')
357 self.create_account('1','Main account')
360 def create_master_keys(self, account_type):
361 master_k, master_c, master_K, master_cK = bip32_init(self.get_seed(None))
362 if account_type == '1':
363 k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/")
364 self.master_public_keys["m/0'/"] = (c0, K0, cK0)
365 self.master_private_keys["m/0'/"] = k0
366 elif account_type == '2of2':
367 k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/")
368 k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/")
369 self.master_public_keys["m/1'/"] = (c1, K1, cK1)
370 self.master_public_keys["m/2'/"] = (c2, K2, cK2)
371 self.master_private_keys["m/1'/"] = k1
372 self.master_private_keys["m/2'/"] = k2
373 elif account_type == '2of3':
374 k3, c3, K3, cK3 = bip32_private_derivation(master_k, master_c, "m/", "m/3'/")
375 k4, c4, K4, cK4 = bip32_private_derivation(master_k, master_c, "m/", "m/4'/")
376 k5, c5, K5, cK5 = bip32_private_derivation(master_k, master_c, "m/", "m/5'/")
377 self.master_public_keys["m/3'/"] = (c3, K3, cK3)
378 self.master_public_keys["m/4'/"] = (c4, K4, cK4)
379 self.master_public_keys["m/5'/"] = (c5, K5, cK5)
380 self.master_private_keys["m/3'/"] = k3
381 self.master_private_keys["m/4'/"] = k4
382 self.master_private_keys["m/5'/"] = k5
384 self.storage.put('master_public_keys', self.master_public_keys, True)
385 self.storage.put('master_private_keys', self.master_private_keys, True)
387 def has_master_public_keys(self, account_type):
388 if account_type == '1':
389 return "m/0'/" in self.master_public_keys
390 elif account_type == '2of2':
391 return set(["m/1'/", "m/2'/"]) <= set(self.master_public_keys.keys())
392 elif account_type == '2of3':
393 return set(["m/3'/", "m/4'/", "m/5'/"]) <= set(self.master_public_keys.keys())
395 def find_root_by_master_key(self, c, K):
396 for key, v in self.master_public_keys.items():
397 if key == "m/":continue
399 if (c == cc) and (K == KK):
402 def deseed_root(self, seed, password):
403 # for safety, we ask the user to enter their seed
404 assert seed == self.get_seed(password)
406 self.storage.put('seed', '', True)
409 def deseed_branch(self, k):
410 # check that parent has no seed
411 assert self.seed == ''
412 self.master_private_keys.pop(k)
413 self.storage.put('master_private_keys', self.master_private_keys, True)
415 def is_watching_only(self):
416 return (self.seed == '') and (self.master_private_keys == {})
420 def account_id(self, account_type, i):
421 if account_type == '1':
423 elif account_type == '2of2':
424 return "m/1'/%d & m/2'/%d"%(i,i)
425 elif account_type == '2of3':
426 return "m/3'/%d & m/4'/%d & m/5'/%d"%(i,i,i)
428 raise BaseException('unknown account type')
431 def num_accounts(self, account_type):
432 keys = self.accounts.keys()
435 account_id = self.account_id(account_type, i)
436 if account_id not in keys: break
441 def new_account_address(self, account_type = '1'):
442 i = self.num_accounts(account_type)
443 k = self.account_id(account_type,i)
445 addr = self.next_addresses.get(k)
447 account_id, account = self.next_account(account_type)
448 addr = account.first_address()
449 self.next_addresses[k] = addr
450 self.storage.put('next_addresses',self.next_addresses)
455 def next_account(self, account_type = '1'):
457 i = self.num_accounts(account_type)
458 account_id = self.account_id(account_type,i)
460 if account_type is '1':
461 master_c0, master_K0, _ = self.master_public_keys["m/0'/"]
462 c0, K0, cK0 = bip32_public_derivation(master_c0.decode('hex'), master_K0.decode('hex'), "m/0'/", "m/0'/%d"%i)
463 account = BIP32_Account({ 'c':c0, 'K':K0, 'cK':cK0 })
465 elif account_type == '2of2':
466 master_c1, master_K1, _ = self.master_public_keys["m/1'/"]
467 c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i)
468 master_c2, master_K2, _ = self.master_public_keys["m/2'/"]
469 c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i)
470 account = BIP32_Account_2of2({ 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 })
472 elif account_type == '2of3':
473 master_c3, master_K3, _ = self.master_public_keys["m/3'/"]
474 c3, K3, cK3 = bip32_public_derivation(master_c3.decode('hex'), master_K3.decode('hex'), "m/3'/", "m/3'/%d"%i)
475 master_c4, master_K4, _ = self.master_public_keys["m/4'/"]
476 c4, K4, cK4 = bip32_public_derivation(master_c4.decode('hex'), master_K4.decode('hex'), "m/4'/", "m/4'/%d"%i)
477 master_c5, master_K5, _ = self.master_public_keys["m/5'/"]
478 c5, K5, cK5 = bip32_public_derivation(master_c5.decode('hex'), master_K5.decode('hex'), "m/5'/", "m/5'/%d"%i)
479 account = BIP32_Account_2of3({ 'c':c3, 'K':K3, 'cK':cK3, 'c2':c4, 'K2':K4, 'cK2':cK4, 'c3':c5, 'K3':K5, 'cK3':cK5 })
481 return account_id, account
484 def set_label(self, name, text = None):
486 old_text = self.labels.get(name)
489 self.labels[name] = text
493 self.labels.pop(name)
497 self.storage.put('labels', self.labels, True)
499 run_hook('set_label', name, text, changed)
504 def create_account(self, account_type = '1', name = None):
505 k, account = self.next_account(account_type)
506 if k in self.pending_accounts:
507 self.pending_accounts.pop(k)
508 self.storage.put('pending_accounts', self.pending_accounts)
510 self.accounts[k] = account
513 self.set_label(k, name)
516 def create_old_account(self):
517 mpk = OldAccount.mpk_from_seed(self.seed)
518 self.storage.put('master_public_key', mpk, True)
519 self.accounts[0] = OldAccount({'mpk':mpk, 0:[], 1:[]})
523 def save_accounts(self):
525 for k, v in self.accounts.items():
527 self.storage.put('accounts', d, True)
531 def load_accounts(self):
532 d = self.storage.get('accounts', {})
534 for k, v in d.items():
536 v['mpk'] = self.storage.get('master_public_key')
537 self.accounts[k] = OldAccount(v)
539 self.accounts[k] = BIP32_Account_2of2(v)
541 self.accounts[k] = BIP32_Account(v)
543 self.pending_accounts = self.storage.get('pending_accounts',{})
546 def delete_pending_account(self, k):
547 self.pending_accounts.pop(k)
548 self.storage.put('pending_accounts', self.pending_accounts)
550 def account_is_pending(self, k):
551 return k in self.pending_accounts
553 def create_pending_account(self, acct_type, name):
554 k, addr = self.new_account_address(acct_type)
555 self.set_label(k, name)
556 self.pending_accounts[k] = addr
557 self.storage.put('pending_accounts', self.pending_accounts)
559 def get_pending_accounts(self):
560 return self.pending_accounts.items()
563 def addresses(self, include_change = True, _next=True):
564 o = self.get_account_addresses(-1, include_change)
565 for a in self.accounts.keys():
566 o += self.get_account_addresses(a, include_change)
569 for addr in self.next_addresses.values():
575 def is_mine(self, address):
576 return address in self.addresses(True)
579 def is_change(self, address):
580 if not self.is_mine(address): return False
581 if address in self.imported_keys.keys(): return False
582 acct, s = self.get_address_index(address)
583 if s is None: return False
586 def get_master_public_key(self):
587 if self.seed_version == 4:
588 return self.storage.get("master_public_key")
590 c, K, cK = self.storage.get("master_public_keys")["m/0'/"]
593 def get_master_private_key(self, account, password):
594 master_k = pw_decode( self.master_private_keys[account], password)
595 master_c, master_K, master_Kc = self.master_public_keys[account]
597 K, Kc = get_pubkeys_from_secret(master_k.decode('hex'))
598 assert K.encode('hex') == master_K
600 raise BaseException("Invalid password")
604 def get_address_index(self, address):
605 if address in self.imported_keys.keys():
608 for account in self.accounts.keys():
609 for for_change in [0,1]:
610 addresses = self.accounts[account].get_addresses(for_change)
611 for addr in addresses:
613 return account, (for_change, addresses.index(addr))
615 for k,v in self.next_addresses.items():
619 raise BaseException("Address not found", address)
622 def get_roots(self, account):
624 for a in account.split('&'):
626 m = re.match("(m/\d+'/)(\d+)", s)
627 roots.append( m.group(1) )
630 def is_seeded(self, account):
631 if type(account) is int:
632 return self.seed is not None
634 for root in self.get_roots(account):
635 if root not in self.master_private_keys.keys():
639 def rebase_sequence(self, account, sequence):
642 for a in account.split('&'):
644 m = re.match("(m/\d+'/)(\d+)", s)
646 num = int(m.group(2))
647 dd.append( (root, [num,c,i] ) )
651 def get_keyID(self, account, sequence):
654 mpk = self.storage.get('master_public_key')
655 return 'old(%s,%d,%d)'%(mpk,a,b)
657 rs = self.rebase_sequence(account, sequence)
659 for root, public_sequence in rs:
660 c, K, _ = self.master_public_keys[root]
661 s = '/' + '/'.join( map(lambda x:str(x), public_sequence) )
662 dd.append( 'bip32(%s,%s,%s)'%(c,K, s) )
667 def get_seed(self, password):
668 s = pw_decode(self.seed, password)
669 if self.seed_version == 4:
672 seed = mnemonic_hash(s)
673 #todo: #self.sequences[0].check_seed(seed)
677 def get_mnemonic(self, password):
679 s = pw_decode(self.seed, password)
680 if self.seed_version == 4:
681 return ' '.join(mnemonic.mn_encode(s))
687 def get_private_key(self, address, password):
689 if address in self.imported_keys.keys():
690 out.append( pw_decode( self.imported_keys[address], password ) )
692 account, sequence = self.get_address_index(address)
694 seed = self.get_seed(password)
695 pk = self.accounts[account].get_private_key(seed, sequence)
699 # assert address == self.accounts[account].get_address(*sequence)
700 rs = self.rebase_sequence( account, sequence)
701 for root, public_sequence in rs:
703 if root not in self.master_private_keys.keys(): continue
704 master_k = self.get_master_private_key(root, password)
705 master_c, _, _ = self.master_public_keys[root]
706 pk = bip32_private_key( public_sequence, master_k.decode('hex'), master_c.decode('hex'))
712 def add_keypairs_from_wallet(self, tx, keypairs, password):
713 for txin in tx.inputs:
714 address = txin['address']
715 private_keys = self.get_private_key(address, password)
716 for sec in private_keys:
717 pubkey = public_key_from_private_key(sec)
718 keypairs[ pubkey ] = sec
721 def add_keypairs_from_KeyID(self, tx, keypairs, password):
722 for txin in tx.inputs:
723 keyid = txin.get('KeyID')
726 if self.seed_version==4:
727 m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
730 if mpk != self.storage.get('master_public_key'): continue
731 index = int(m.group(2))
732 num = int(m.group(3))
733 account = self.accounts[0]
734 addr = account.get_address(index, num)
735 txin['address'] = addr # fixme: side effect
736 pk = self.get_private_key(addr, password)
738 pubkey = public_key_from_private_key(sec)
739 keypairs[pubkey] = sec
744 for s in keyid.split('&'):
745 m = re.match("bip32\(([0-9a-f]+),([0-9a-f]+),(/\d+/\d+/\d+)", s)
749 sequence = m.group(3)
750 root = self.find_root_by_master_key(c,K)
751 if not root: continue
752 sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
753 root = root + '%d'%sequence[0]
754 sequence = sequence[1:]
755 roots.append((root,sequence))
757 account_id = " & ".join( map(lambda x:x[0], roots) )
758 account = self.accounts.get(account_id)
759 if not account: continue
760 addr = account.get_address(*sequence)
761 txin['address'] = addr # fixme: side effect
762 pk = self.get_private_key(addr, password)
764 pubkey = public_key_from_private_key(sec)
765 keypairs[pubkey] = sec
769 def signrawtransaction(self, tx, input_info, private_keys, password):
771 # check that the password is correct
772 seed = self.get_seed(password)
775 tx.add_input_info(input_info)
777 # add redeem script for coins that are in the wallet
778 # FIXME: add redeemPubkey too!
779 unspent_coins = self.get_unspent_coins()
780 for txin in tx.inputs:
781 for item in unspent_coins:
782 if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
783 print_error( "tx input is in unspent coins" )
784 txin['scriptPubKey'] = item['scriptPubKey']
785 account, sequence = self.get_address_index(item['address'])
787 txin['redeemScript'] = self.accounts[account].redeem_script(sequence)
788 print_error("added redeemScript", txin['redeemScript'])
792 # build a list of public/private keys
795 # add private keys from parameter
796 for sec in private_keys:
797 pubkey = public_key_from_private_key(sec)
798 keypairs[ pubkey ] = sec
800 # add private_keys from KeyID
801 self.add_keypairs_from_KeyID(tx, keypairs, password)
803 # add private keys from wallet
804 self.add_keypairs_from_wallet(tx, keypairs, password)
805 self.sign_transaction(tx, keypairs)
808 def sign_message(self, address, message, password):
809 keys = self.get_private_key(address, password)
810 assert len(keys) == 1
812 key = regenerate_key(sec)
813 compressed = is_compressed(sec)
814 return key.sign_message(message, compressed, address)
817 def change_gap_limit(self, value):
818 if value >= self.gap_limit:
819 self.gap_limit = value
820 self.storage.put('gap_limit', self.gap_limit, True)
821 #self.interface.poke('synchronizer')
824 elif value >= self.min_acceptable_gap():
825 for key, account in self.accounts.items():
826 addresses = account[0]
827 k = self.num_unused_trailing_addresses(addresses)
828 n = len(addresses) - k + value
829 addresses = addresses[0:n]
830 self.accounts[key][0] = addresses
832 self.gap_limit = value
833 self.storage.put('gap_limit', self.gap_limit, True)
839 def num_unused_trailing_addresses(self, addresses):
841 for a in addresses[::-1]:
842 if self.history.get(a):break
846 def min_acceptable_gap(self):
847 # fixme: this assumes wallet is synchronized
851 for account in self.accounts.values():
852 addresses = account.get_addresses(0)
853 k = self.num_unused_trailing_addresses(addresses)
854 for a in addresses[0:-k]:
855 if self.history.get(a):
859 if n > nmax: nmax = n
863 def address_is_old(self, address):
865 h = self.history.get(address, [])
868 for tx_hash, tx_height in h:
872 tx_age = self.verifier.blockchain.height() - tx_height + 1
878 def synchronize_sequence(self, account, for_change):
879 limit = self.gap_limit_for_change if for_change else self.gap_limit
882 addresses = account.get_addresses(for_change)
883 if len(addresses) < limit:
884 address = account.create_new_address(for_change)
885 self.history[address] = []
886 new_addresses.append( address )
889 if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]:
892 address = account.create_new_address(for_change)
893 self.history[address] = []
894 new_addresses.append( address )
900 def create_pending_accounts(self):
901 for account_type in ['1','2of2','2of3']:
902 if not self.has_master_public_keys(account_type):
904 k, a = self.new_account_address(account_type)
905 if self.address_is_old(a):
906 print_error( "creating account", a )
907 self.create_account(account_type)
908 self.next_addresses.pop(k)
911 def synchronize_account(self, account):
913 new += self.synchronize_sequence(account, 0)
914 new += self.synchronize_sequence(account, 1)
918 def synchronize(self):
919 if self.master_public_keys:
920 self.create_pending_accounts()
922 for account in self.accounts.values():
923 new += self.synchronize_account(account)
926 self.storage.put('addr_history', self.history, True)
931 return self.history.values() != [[]] * len(self.history)
934 def add_contact(self, address, label=None):
935 self.addressbook.append(address)
936 self.storage.put('contacts', self.addressbook, True)
938 self.set_label(address, label)
941 def delete_contact(self, addr):
942 if addr in self.addressbook:
943 self.addressbook.remove(addr)
944 self.storage.put('addressbook', self.addressbook, True)
947 def fill_addressbook(self):
948 for tx_hash, tx in self.transactions.items():
949 is_relevant, is_send, _, _ = self.get_tx_value(tx)
951 for addr, v in tx.outputs:
952 if not self.is_mine(addr) and addr not in self.addressbook:
953 self.addressbook.append(addr)
955 # self.update_tx_labels()
957 def get_num_tx(self, address):
959 for tx in self.transactions.values():
960 if address in map(lambda x:x[0], tx.outputs): n += 1
964 def get_address_flags(self, addr):
965 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
966 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
970 def get_tx_value(self, tx, account=None):
971 domain = self.get_account_addresses(account)
972 return tx.get_value(domain, self.prevout_values)
975 def update_tx_outputs(self, tx_hash):
976 tx = self.transactions.get(tx_hash)
978 for i, (addr, value) in enumerate(tx.outputs):
979 key = tx_hash+ ':%d'%i
980 self.prevout_values[key] = value
982 for item in tx.inputs:
983 if self.is_mine(item.get('address')):
984 key = item['prevout_hash'] + ':%d'%item['prevout_n']
985 self.spent_outputs.append(key)
988 def get_addr_balance(self, address):
989 assert self.is_mine(address)
990 h = self.history.get(address,[])
991 if h == ['*']: return 0,0
993 received_coins = [] # list of coins received at address
995 for tx_hash, tx_height in h:
996 tx = self.transactions.get(tx_hash)
999 for i, (addr, value) in enumerate(tx.outputs):
1001 key = tx_hash + ':%d'%i
1002 received_coins.append(key)
1004 for tx_hash, tx_height in h:
1005 tx = self.transactions.get(tx_hash)
1009 for item in tx.inputs:
1010 addr = item.get('address')
1012 key = item['prevout_hash'] + ':%d'%item['prevout_n']
1013 value = self.prevout_values.get( key )
1014 if key in received_coins:
1017 for i, (addr, value) in enumerate(tx.outputs):
1018 key = tx_hash + ':%d'%i
1029 def get_account_name(self, k):
1031 if self.seed_version == 4:
1032 name = 'Main account'
1034 name = 'Old account'
1036 default = "Unnamed account"
1037 m = re.match("m/0'/(\d+)", k)
1041 default = "Main account"
1043 default = "Account %s"%num
1045 m = re.match("m/1'/(\d+) & m/2'/(\d+)", k)
1048 default = "2of2 account %s"%num
1049 name = self.labels.get(k, default)
1053 def get_account_names(self):
1055 for k, account in self.accounts.items():
1056 accounts[k] = self.get_account_name(k)
1057 if self.imported_keys:
1058 accounts[-1] = 'Imported keys'
1061 def get_account_addresses(self, a, include_change=True):
1063 o = self.addresses(True)
1065 o = self.imported_keys.keys()
1067 ac = self.accounts[a]
1068 o = ac.get_addresses(0)
1069 if include_change: o += ac.get_addresses(1)
1072 def get_imported_balance(self):
1073 return self.get_balance(self.imported_keys.keys())
1075 def get_account_balance(self, account):
1076 return self.get_balance(self.get_account_addresses(account))
1078 def get_frozen_balance(self):
1079 return self.get_balance(self.frozen_addresses)
1081 def get_balance(self, domain=None):
1082 if domain is None: domain = self.addresses(True)
1085 c, u = self.get_addr_balance(addr)
1091 def get_unspent_coins(self, domain=None):
1093 if domain is None: domain = self.addresses(True)
1095 h = self.history.get(addr, [])
1096 if h == ['*']: continue
1097 for tx_hash, tx_height in h:
1098 tx = self.transactions.get(tx_hash)
1099 if tx is None: raise BaseException("Wallet not synchronized")
1100 is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
1101 for output in tx.d.get('outputs'):
1102 if output.get('address') != addr: continue
1103 key = tx_hash + ":%d" % output.get('prevout_n')
1104 if key in self.spent_outputs: continue
1105 output['prevout_hash'] = tx_hash
1106 output['height'] = tx_height
1107 output['coinbase'] = is_coinbase
1108 coins.append((tx_height, output))
1112 coins = sorted(coins)
1113 if coins[-1][0] != 0:
1114 while coins[0][0] == 0:
1115 coins = coins[1:] + [ coins[0] ]
1116 return [x[1] for x in coins]
1120 def choose_tx_inputs_from_account( self, amount, fixed_fee, account ):
1121 domain = self.get_account_addresses(account) if account else None
1122 return self.choose_tx_inputs( amount, fixed_fee, domain )
1125 def choose_tx_inputs( self, amount, fixed_fee, domain = None ):
1126 """ todo: minimize tx size """
1128 fee = self.fee if fixed_fee is None else fixed_fee
1130 domain = self.addresses(True)
1132 for i in self.frozen_addresses:
1133 if i in domain: domain.remove(i)
1136 for i in self.prioritized_addresses:
1139 prioritized.append(i)
1141 coins = self.get_unspent_coins(domain)
1142 prioritized_coins = self.get_unspent_coins(prioritized)
1145 coins = prioritized_coins + coins
1148 if item.get('coinbase') and item.get('height') + COINBASE_MATURITY > self.network.blockchain.height:
1150 addr = item.get('address')
1151 v = item.get('value')
1154 fee = self.estimated_fee(inputs) if fixed_fee is None else fixed_fee
1155 if total >= amount + fee: break
1159 return inputs, total, fee
1162 def set_fee(self, fee):
1165 self.storage.put('fee_per_kb', self.fee, True)
1167 def estimated_fee(self, inputs):
1168 estimated_size = len(inputs) * 180 + 80 # this assumes non-compressed keys
1169 fee = self.fee * int(round(estimated_size/1024.))
1170 if fee == 0: fee = self.fee
1174 def add_tx_change( self, inputs, outputs, amount, fee, total, change_addr=None):
1175 "add change to a transaction"
1176 change_amount = total - ( amount + fee )
1177 if change_amount != 0:
1180 # send change to one of the accounts involved in the tx
1181 address = inputs[0].get('address')
1182 account, _ = self.get_address_index(address)
1184 if not self.use_change or account == -1:
1185 change_addr = inputs[-1]['address']
1187 change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
1189 # Insert the change output at a random position in the outputs
1190 posn = random.randint(0, len(outputs))
1191 outputs[posn:posn] = [( change_addr, change_amount)]
1195 def get_history(self, address):
1197 return self.history.get(address)
1200 def get_status(self, h):
1201 if not h: return None
1202 if h == ['*']: return '*'
1204 for tx_hash, height in h:
1205 status += tx_hash + ':%d:' % height
1206 return hashlib.sha256( status ).digest().encode('hex')
1209 def receive_tx_callback(self, tx_hash, tx, tx_height):
1211 with self.transaction_lock:
1212 self.add_extra_addresses(tx)
1213 if not self.check_new_tx(tx_hash, tx):
1214 # may happen due to pruning
1215 print_error("received transaction that is no longer referenced in history", tx_hash)
1217 self.transactions[tx_hash] = tx
1218 self.network.interface.pending_transactions_for_notifications.append(tx)
1219 self.save_transactions()
1220 if self.verifier and tx_height>0:
1221 self.verifier.add(tx_hash, tx_height)
1222 self.update_tx_outputs(tx_hash)
1225 def save_transactions(self):
1227 for k,v in self.transactions.items():
1229 self.storage.put('transactions', tx, True)
1231 def receive_history_callback(self, addr, hist):
1233 if not self.check_new_history(addr, hist):
1234 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
1237 self.history[addr] = hist
1238 self.storage.put('addr_history', self.history, True)
1241 for tx_hash, tx_height in hist:
1243 # add it in case it was previously unconfirmed
1244 if self.verifier: self.verifier.add(tx_hash, tx_height)
1247 def get_tx_history(self, account=None):
1248 with self.transaction_lock:
1249 history = self.transactions.items()
1250 history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
1254 for tx_hash, tx in history:
1255 is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
1256 if v is not None: balance += v
1258 c, u = self.get_account_balance(account)
1261 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
1263 balance = c + u - balance
1264 for tx_hash, tx in history:
1265 is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
1268 if value is not None:
1271 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
1272 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
1277 def get_label(self, tx_hash):
1278 label = self.labels.get(tx_hash)
1279 is_default = (label == '') or (label is None)
1280 if is_default: label = self.get_default_label(tx_hash)
1281 return label, is_default
1284 def get_default_label(self, tx_hash):
1285 tx = self.transactions.get(tx_hash)
1288 is_relevant, is_mine, _, _ = self.get_tx_value(tx)
1290 for o in tx.outputs:
1292 if not self.is_mine(o_addr):
1294 default_label = self.labels[o_addr]
1296 default_label = o_addr
1299 default_label = '(internal)'
1301 for o in tx.outputs:
1303 if self.is_mine(o_addr) and not self.is_change(o_addr):
1306 for o in tx.outputs:
1308 if self.is_mine(o_addr):
1314 dest_label = self.labels.get(o_addr)
1316 default_label = self.labels[o_addr]
1318 default_label = o_addr
1320 return default_label
1323 def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
1324 for address, x in outputs:
1325 assert is_valid(address)
1326 amount = sum( map(lambda x:x[1], outputs) )
1327 inputs, total, fee = self.choose_tx_inputs( amount, fee, domain )
1329 raise ValueError("Not enough funds")
1330 self.add_input_info(inputs)
1331 outputs = self.add_tx_change(inputs, outputs, amount, fee, total, change_addr)
1332 return Transaction.from_io(inputs, outputs)
1335 def mktx_from_account(self, outputs, password, fee=None, account=None):
1336 domain = self.get_account_addresses(account) if account else None
1337 return self.mktx(outputs, password, fee, change_addr=None, domain=domain)
1340 def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
1341 tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
1343 self.add_keypairs_from_wallet(tx, keypairs, password)
1345 self.sign_transaction(tx, keypairs)
1349 def add_input_info(self, inputs):
1351 address = txin['address']
1352 if address in self.imported_keys.keys():
1354 account, sequence = self.get_address_index(address)
1355 txin['KeyID'] = self.get_keyID(account, sequence)
1356 redeemScript = self.accounts[account].redeem_script(sequence)
1358 txin['redeemScript'] = redeemScript
1360 txin['redeemPubkey'] = self.accounts[account].get_pubkey(*sequence)
1363 def sign_transaction(self, tx, keypairs):
1365 run_hook('sign_transaction', tx)
1368 def sendtx(self, tx):
1370 h = self.send_tx(tx)
1371 self.tx_event.wait()
1372 return self.receive_tx(h)
1374 def send_tx(self, tx):
1376 self.tx_event.clear()
1377 self.network.interface.send([('blockchain.transaction.broadcast', [str(tx)])], self.on_broadcast)
1380 def on_broadcast(self, i, r):
1381 self.tx_result = r.get('result')
1384 def receive_tx(self,tx_hash):
1385 out = self.tx_result
1387 return False, "error: " + out
1392 def update_password(self, old_password, new_password):
1393 if new_password == '': new_password = None
1394 # this will throw an exception if unicode cannot be converted
1395 decoded = pw_decode(self.seed, old_password)
1396 self.seed = pw_encode( decoded, new_password)
1397 self.storage.put('seed', self.seed, True)
1398 self.use_encryption = (new_password != None)
1399 self.storage.put('use_encryption', self.use_encryption,True)
1400 for k in self.imported_keys.keys():
1401 a = self.imported_keys[k]
1402 b = pw_decode(a, old_password)
1403 c = pw_encode(b, new_password)
1404 self.imported_keys[k] = c
1405 self.storage.put('imported_keys', self.imported_keys, True)
1407 for k, v in self.master_private_keys.items():
1408 b = pw_decode(v, old_password)
1409 c = pw_encode(b, new_password)
1410 self.master_private_keys[k] = c
1411 self.storage.put('master_private_keys', self.master_private_keys, True)
1414 def freeze(self,addr):
1415 if self.is_mine(addr) and addr not in self.frozen_addresses:
1416 self.unprioritize(addr)
1417 self.frozen_addresses.append(addr)
1418 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1423 def unfreeze(self,addr):
1424 if self.is_mine(addr) and addr in self.frozen_addresses:
1425 self.frozen_addresses.remove(addr)
1426 self.storage.put('frozen_addresses', self.frozen_addresses, True)
1431 def prioritize(self,addr):
1432 if self.is_mine(addr) and addr not in self.prioritized_addresses:
1434 self.prioritized_addresses.append(addr)
1435 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1440 def unprioritize(self,addr):
1441 if self.is_mine(addr) and addr in self.prioritized_addresses:
1442 self.prioritized_addresses.remove(addr)
1443 self.storage.put('prioritized_addresses', self.prioritized_addresses, True)
1449 def set_verifier(self, verifier):
1450 self.verifier = verifier
1452 # review transactions that are in the history
1453 for addr, hist in self.history.items():
1454 if hist == ['*']: continue
1455 for tx_hash, tx_height in hist:
1457 # add it in case it was previously unconfirmed
1458 self.verifier.add(tx_hash, tx_height)
1461 # if we are on a pruning server, remove unverified transactions
1462 vr = self.verifier.transactions.keys() + self.verifier.verified_tx.keys()
1463 for tx_hash in self.transactions.keys():
1464 if tx_hash not in vr:
1465 self.transactions.pop(tx_hash)
1469 def check_new_history(self, addr, hist):
1471 # check that all tx in hist are relevant
1473 for tx_hash, height in hist:
1474 tx = self.transactions.get(tx_hash)
1476 if not tx.has_address(addr):
1479 # check that we are not "orphaning" a transaction
1480 old_hist = self.history.get(addr,[])
1481 if old_hist == ['*']: return True
1483 for tx_hash, height in old_hist:
1484 if tx_hash in map(lambda x:x[0], hist): continue
1486 for _addr, _hist in self.history.items():
1487 if _addr == addr: continue
1488 if _hist == ['*']: continue
1489 _tx_hist = map(lambda x:x[0], _hist)
1490 if tx_hash in _tx_hist:
1495 tx = self.transactions.get(tx_hash)
1496 # tx might not be there
1500 if self.verifier.get_height(tx_hash):
1503 print_error("new history is orphaning transaction:", tx_hash)
1504 # check that all outputs are not mine, request histories
1506 for _addr, _v in tx.outputs:
1507 # assert not self.is_mine(_addr)
1508 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
1510 ext_h = self.network.synchronous_get(ext_requests)
1511 print_error("sync:", ext_requests, ext_h)
1514 if h == ['*']: continue
1516 if item.get('tx_hash') == tx_hash:
1517 height = item.get('height')
1519 print_error("found height for", tx_hash, height)
1520 self.verifier.add(tx_hash, height)
1522 print_error("removing orphaned tx from history", tx_hash)
1523 self.transactions.pop(tx_hash)
1529 def check_new_tx(self, tx_hash, tx):
1530 # 1 check that tx is referenced in addr_history.
1532 for addr, hist in self.history.items():
1533 if hist == ['*']:continue
1534 for txh, height in hist:
1536 addresses.append(addr)
1541 # 2 check that referencing addresses are in the tx
1542 for addr in addresses:
1543 if not tx.has_address(addr):
1549 def start_threads(self, network):
1550 from verifier import TxVerifier
1551 self.network = network
1552 self.verifier = TxVerifier(self.network, self.storage)
1553 self.verifier.start()
1554 self.set_verifier(self.verifier)
1555 self.synchronizer = WalletSynchronizer(self, network)
1556 self.synchronizer.start()
1558 def stop_threads(self):
1559 self.verifier.stop()
1560 self.synchronizer.stop()
1564 def restore(self, callback):
1566 def wait_for_wallet():
1567 self.set_up_to_date(False)
1568 while not self.is_up_to_date():
1569 msg = "%s\n%s %d\n%s %.1f"%(
1570 _("Please wait..."),
1571 _("Addresses generated:"),
1572 len(self.addresses(True)),_("Kilobytes received:"),
1573 self.network.interface.bytes_received/1024.)
1575 apply(callback, (msg,))
1578 def wait_for_network():
1579 while not self.network.interface.is_connected:
1580 msg = "%s \n" % (_("Connecting..."))
1581 apply(callback, (msg,))
1584 # wait until we are connected, because the user might have selected another server
1588 self.create_accounts()
1594 class WalletSynchronizer(threading.Thread):
1597 def __init__(self, wallet, network):
1598 threading.Thread.__init__(self)
1600 self.wallet = wallet
1601 self.network = network
1602 self.was_updated = True
1603 self.running = False
1604 self.lock = threading.Lock()
1605 self.queue = Queue.Queue()
1608 with self.lock: self.running = False
1610 def is_running(self):
1611 with self.lock: return self.running
1614 def subscribe_to_addresses(self, addresses):
1616 for addr in addresses:
1617 messages.append(('blockchain.address.subscribe', [addr]))
1618 self.network.subscribe( messages, lambda i,r: self.queue.put(r))
1625 while self.is_running():
1627 if not self.network.is_connected():
1628 print_error("synchronizer: waiting for interface")
1629 self.network.wait_until_connected()
1631 self.run_interface(self.network.interface)
1634 def run_interface(self, interface):
1636 print_error("synchronizer: connected to", interface.server)
1640 requested_histories = {}
1642 # request any missing transactions
1643 for history in self.wallet.history.values():
1644 if history == ['*']: continue
1645 for tx_hash, tx_height in history:
1646 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1647 missing_tx.append( (tx_hash, tx_height) )
1650 print_error("missing tx", missing_tx)
1653 self.subscribe_to_addresses(self.wallet.addresses(True))
1655 while self.is_running():
1656 # 1. create new addresses
1657 new_addresses = self.wallet.synchronize()
1659 # request missing addresses
1661 self.subscribe_to_addresses(new_addresses)
1663 # request missing transactions
1664 for tx_hash, tx_height in missing_tx:
1665 if (tx_hash, tx_height) not in requested_tx:
1666 interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
1667 requested_tx.append( (tx_hash, tx_height) )
1670 # detect if situation has changed
1671 if interface.is_up_to_date() and self.queue.empty():
1672 if not self.wallet.is_up_to_date():
1673 self.wallet.set_up_to_date(True)
1674 self.was_updated = True
1676 if self.wallet.is_up_to_date():
1677 self.wallet.set_up_to_date(False)
1678 self.was_updated = True
1680 if self.was_updated:
1681 self.wallet.network.trigger_callback('updated')
1682 self.was_updated = False
1686 r = self.queue.get(block=True, timeout=1)
1690 if interface != self.network.interface:
1696 # 3. handle response
1697 method = r['method']
1698 params = r['params']
1699 result = r.get('result')
1700 error = r.get('error')
1705 if method == 'blockchain.address.subscribe':
1707 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1708 if requested_histories.get(addr) is None:
1709 interface.send([('blockchain.address.get_history', [addr])], lambda i,r:self.queue.put(r))
1710 requested_histories[addr] = result
1712 elif method == 'blockchain.address.get_history':
1714 print_error("receiving history", addr, result)
1716 assert requested_histories.pop(addr) == '*'
1717 self.wallet.receive_history_callback(addr, result)
1720 # check that txids are unique
1723 tx_hash = item['tx_hash']
1724 if tx_hash not in txids:
1725 txids.append(tx_hash)
1726 hist.append( (tx_hash, item['height']) )
1728 if len(hist) != len(result):
1729 raise BaseException("error: server sent history with non-unique txid", result)
1731 # check that the status corresponds to what was announced
1732 rs = requested_histories.pop(addr)
1733 if self.wallet.get_status(hist) != rs:
1734 raise BaseException("error: status mismatch: %s"%addr)
1736 # store received history
1737 self.wallet.receive_history_callback(addr, hist)
1739 # request transactions that we don't have
1740 for tx_hash, tx_height in hist:
1741 if self.wallet.transactions.get(tx_hash) is None:
1742 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1743 missing_tx.append( (tx_hash, tx_height) )
1745 elif method == 'blockchain.transaction.get':
1747 tx_height = params[1]
1748 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1749 tx = Transaction(result)
1750 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1751 self.was_updated = True
1752 requested_tx.remove( (tx_hash, tx_height) )
1753 print_error("received tx:", tx_hash, len(tx.raw))
1756 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1758 if self.was_updated and not requested_tx:
1759 self.wallet.network.trigger_callback('updated')
1760 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
1762 self.was_updated = False