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, user_dir, format_satoshis
37 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
38 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
41 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
42 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
44 def pw_encode(s, password):
46 secret = Hash(password)
47 return EncodeAES(secret, s)
51 def pw_decode(s, password):
52 if password is not None:
53 secret = Hash(password)
55 d = DecodeAES(secret, s)
57 raise BaseException('Invalid password')
66 from version import ELECTRUM_VERSION, SEED_VERSION
70 def __init__(self, config={}):
73 self.electrum_version = ELECTRUM_VERSION
74 self.gap_limit_for_change = 3 # constant
77 self.seed_version = config.get('seed_version', SEED_VERSION)
78 self.gap_limit = config.get('gap_limit', 5)
79 self.use_change = config.get('use_change',True)
80 self.fee = int(config.get('fee',100000))
81 self.num_zeros = int(config.get('num_zeros',0))
82 self.use_encryption = config.get('use_encryption', False)
83 self.addresses = config.get('addresses', []) # receiving addresses visible for user
84 self.change_addresses = config.get('change_addresses', []) # addresses used as change
85 self.seed = config.get('seed', '') # encrypted
86 self.labels = config.get('labels', {})
87 self.aliases = config.get('aliases', {}) # aliases for addresses
88 self.authorities = config.get('authorities', {}) # trusted addresses
89 self.frozen_addresses = config.get('frozen_addresses',[])
90 self.prioritized_addresses = config.get('prioritized_addresses',[])
91 self.receipts = config.get('receipts',{}) # signed URIs
92 self.addressbook = config.get('contacts', [])
93 self.imported_keys = config.get('imported_keys',{})
94 self.history = config.get('addr_history',{}) # address -> list(txid, height)
95 self.tx_height = config.get('tx_height',{})
97 master_public_key = config.get('master_public_key','')
98 self.sequence = DeterministicSequence(master_public_key)
100 self.transactions = {}
101 tx = config.get('transactions',{})
103 for k,v in tx.items(): self.transactions[k] = Transaction(v)
105 print_msg("Warning: Cannot deserialize transactions. skipping")
108 self.requested_amounts = config.get('requested_amounts',{})
111 self.prevout_values = {} # my own transaction outputs
112 self.spent_outputs = []
113 self.receipt = None # next receipt
119 # there is a difference between wallet.up_to_date and interface.is_up_to_date()
120 # interface.is_up_to_date() returns true when all requests have been answered and processed
121 # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
123 self.up_to_date = False
124 self.lock = threading.Lock()
125 self.tx_event = threading.Event()
127 if self.seed_version != SEED_VERSION:
128 raise ValueError("This wallet seed is deprecated. Please run upgrade.py for a diagnostic.")
130 for tx_hash in self.transactions.keys():
131 self.update_tx_outputs(tx_hash)
134 def set_up_to_date(self,b):
135 with self.lock: self.up_to_date = b
137 def is_up_to_date(self):
138 with self.lock: return self.up_to_date
141 self.up_to_date = False
142 self.interface.poke('synchronizer')
143 while not self.is_up_to_date(): time.sleep(0.1)
145 def import_key(self, sec, password):
147 seed = self.decode_seed(password)
148 address = address_from_private_key(sec)
150 if address in self.all_addresses():
151 raise BaseException('Address already in wallet')
153 # store the originally requested keypair into the imported keys table
154 self.imported_keys[address] = pw_encode(sec, password )
158 def init_seed(self, seed):
159 if self.seed: raise BaseException("a seed exists")
161 seed = random_seed(128)
163 self.config.set_key('seed', self.seed, True)
164 self.config.set_key('seed_version', self.seed_version, True)
165 self.init_mpk(self.seed)
167 def init_mpk(self,seed):
169 self.sequence = DeterministicSequence.from_seed(seed)
170 self.config.set_key('master_public_key', self.sequence.master_public_key, True)
172 def all_addresses(self):
173 return self.addresses + self.change_addresses + self.imported_keys.keys()
175 def is_mine(self, address):
176 return address in self.all_addresses()
178 def is_change(self, address):
179 return address in self.change_addresses
181 def is_valid(self,addr):
182 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
183 if not ADDRESS_RE.match(addr): return False
185 addrtype, h = bc_address_to_hash_160(addr)
188 return addr == hash_160_to_bc_address(h, addrtype)
190 def get_master_public_key(self):
191 return self.sequence.master_public_key
193 def get_public_key(self, address):
194 if address in self.imported_keys.keys():
195 raise BaseException("imported key")
197 if address in self.addresses:
198 n = self.addresses.index(address)
200 elif address in self.change_addresses:
201 n = self.change_addresses.index(address)
204 return self.sequence.get_pubkey(n, for_change)
207 def decode_seed(self, password):
208 seed = pw_decode(self.seed, password)
209 self.sequence.check_seed(seed)
212 def get_private_key(self, address, password):
214 # decode seed in any case, in order to test the password
215 seed = self.decode_seed(password)
217 if address in self.imported_keys.keys():
218 return pw_decode( self.imported_keys[address], password )
220 if address in self.addresses:
221 n = self.addresses.index(address)
223 elif address in self.change_addresses:
224 n = self.change_addresses.index(address)
227 raise BaseException("unknown address", address)
229 return self.sequence.get_private_key(n, for_change, seed)
232 def sign_message(self, address, message, password):
233 sec = self.get_private_key(address, password)
234 key = regenerate_key(sec)
235 compressed = is_compressed(sec)
236 return key.sign_message(message, compressed, address)
238 def create_new_address(self, for_change):
239 n = len(self.change_addresses) if for_change else len(self.addresses)
240 address = self.get_new_address(n, for_change)
242 self.change_addresses.append(address)
244 self.addresses.append(address)
245 self.history[address] = []
248 def get_new_address(self, n, for_change):
249 pubkey = self.sequence.get_pubkey(n, for_change)
250 address = public_key_to_bc_address( pubkey.decode('hex') )
254 def change_gap_limit(self, value):
255 if value >= self.gap_limit:
256 self.gap_limit = value
258 self.interface.poke('synchronizer')
261 elif value >= self.min_acceptable_gap():
262 k = self.num_unused_trailing_addresses()
263 n = len(self.addresses) - k + value
264 self.addresses = self.addresses[0:n]
265 self.gap_limit = value
271 def num_unused_trailing_addresses(self):
273 for a in self.addresses[::-1]:
274 if self.history.get(a):break
278 def min_acceptable_gap(self):
279 # fixme: this assumes wallet is synchronized
282 k = self.num_unused_trailing_addresses()
283 for a in self.addresses[0:-k]:
284 if self.history.get(a):
288 if n > nmax: nmax = n
292 def address_is_old(self, address):
294 h = self.history.get(address, [])
297 for tx_hash, tx_height in h:
301 tx_age = self.verifier.height - tx_height + 1
307 def synchronize_sequence(self, addresses, n, for_change):
310 if len(self.addresses) < n:
311 new_addresses.append( self.create_new_address(for_change) )
313 if map( lambda a: self.address_is_old(a), addresses[-n:] ) == n*[False]:
316 new_addresses.append( self.create_new_address(for_change) )
320 def synchronize(self):
321 if not self.sequence.master_public_key:
324 new_addresses += self.synchronize_sequence(self.addresses, self.gap_limit, False)
325 new_addresses += self.synchronize_sequence(self.change_addresses, self.gap_limit_for_change, True)
330 return (len(self.change_addresses) > self.gap_limit_for_change ) or ( len(self.addresses) > self.gap_limit )
332 def fill_addressbook(self):
333 for tx_hash, tx in self.transactions.items():
334 is_send, _, _ = self.get_tx_value(tx)
336 for o in tx['outputs']:
337 addr = o.get('address')
338 if not self.is_mine(addr) and addr not in self.addressbook:
339 self.addressbook.append(addr)
341 # self.update_tx_labels()
344 def get_address_flags(self, addr):
345 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
346 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
350 def get_tx_value(self, tx, addresses=None):
351 if addresses is None: addresses = self.all_addresses()
352 return tx.get_value(addresses, self.prevout_values)
355 def get_tx_details(self, tx_hash):
357 if not tx_hash: return ''
358 tx = self.transactions.get(tx_hash)
359 is_mine, v, fee = self.get_tx_value(tx)
360 conf, timestamp = self.verifier.get_confirmations(tx_hash)
363 time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
367 inputs = map(lambda x: x.get('address'), tx.inputs)
368 outputs = map(lambda x: x.get('address'), tx.d['outputs'])
369 tx_details = "Transaction Details" +"\n\n" \
370 + "Transaction ID:\n" + tx_hash + "\n\n" \
371 + "Status: %d confirmations\n"%conf
374 tx_details += "Amount sent: %s\n"% format_satoshis(v-fee, False) \
375 + "Transaction fee: %s\n"% format_satoshis(fee, False)
377 tx_details += "Amount sent: %s\n"% format_satoshis(v, False) \
378 + "Transaction fee: unknown\n"
380 tx_details += "Amount received: %s\n"% format_satoshis(v, False) \
382 tx_details += "Date: %s\n\n"%time_str \
383 + "Inputs:\n-"+ '\n-'.join(inputs) + "\n\n" \
384 + "Outputs:\n-"+ '\n-'.join(outputs)
386 r = self.receipts.get(tx_hash)
388 tx_details += "\n_______________________________________" \
389 + '\n\nSigned URI: ' + r[2] \
390 + "\n\nSigned by: " + r[0] \
391 + '\n\nSignature: ' + r[1]
396 def update_tx_outputs(self, tx_hash):
397 tx = self.transactions.get(tx_hash)
399 for item in tx.outputs:
401 key = tx_hash+ ':%d'%i
403 self.prevout_values[key] = value
406 for item in tx.inputs:
407 if self.is_mine(item.get('address')):
408 key = item['prevout_hash'] + ':%d'%item['prevout_n']
409 self.spent_outputs.append(key)
412 def get_addr_balance(self, address):
413 assert self.is_mine(address)
414 h = self.history.get(address,[])
415 if h == ['*']: return 0,0
417 received_coins = [] # list of coins received at address
419 for tx_hash, tx_height in h:
420 tx = self.transactions.get(tx_hash)
423 for item in tx.outputs:
426 key = tx_hash + ':%d'%i
427 received_coins.append(key)
430 for tx_hash, tx_height in h:
431 tx = self.transactions.get(tx_hash)
435 for item in tx.inputs:
436 addr = item.get('address')
438 key = item['prevout_hash'] + ':%d'%item['prevout_n']
439 value = self.prevout_values.get( key )
440 if key in received_coins:
444 for item in tx.outputs:
446 key = tx_hash + ':%d'%i
457 def get_balance(self):
459 for addr in self.all_addresses():
460 c, u = self.get_addr_balance(addr)
466 def get_unspent_coins(self, domain=None):
468 if domain is None: domain = self.all_addresses()
470 h = self.history.get(addr, [])
471 if h == ['*']: continue
472 for tx_hash, tx_height in h:
473 tx = self.transactions.get(tx_hash)
474 for output in tx.d.get('outputs'):
475 if output.get('address') != addr: continue
476 key = tx_hash + ":%d" % output.get('index')
477 if key in self.spent_outputs: continue
478 output['tx_hash'] = tx_hash
484 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
485 """ todo: minimize tx size """
487 fee = self.fee if fixed_fee is None else fixed_fee
490 prioritized_coins = []
491 domain = [from_addr] if from_addr else self.all_addresses()
492 for i in self.frozen_addresses:
493 if i in domain: domain.remove(i)
495 for i in self.prioritized_addresses:
496 if i in domain: domain.remove(i)
498 coins = self.get_unspent_coins(domain)
499 prioritized_coins = self.get_unspent_coins(self.prioritized_addresses)
502 coins = prioritized_coins + coins
505 addr = item.get('address')
506 v = item.get('value')
508 item['pubkeysig'] = [(None, None)]
509 inputs.append( item )
510 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
511 if total >= amount + fee: break
513 #print "not enough funds: %s %s"%(format_satoshis(total), format_satoshis(fee))
515 return inputs, total, fee
517 def add_tx_change( self, outputs, amount, fee, total, change_addr=None ):
518 change_amount = total - ( amount + fee )
519 if change_amount != 0:
520 # normally, the update thread should ensure that the last change address is unused
522 change_addr = self.change_addresses[-self.gap_limit_for_change]
523 # Insert the change output at a random position in the outputs
524 posn = random.randint(0, len(outputs))
525 outputs[posn:posn] = [( change_addr, change_amount)]
529 def get_history(self, address):
531 return self.history.get(address)
533 def get_status(self, h):
534 if not h: return None
535 if h == ['*']: return '*'
537 for tx_hash, height in h:
538 status += tx_hash + ':%d:' % height
539 return hashlib.sha256( status ).digest().encode('hex')
543 def receive_tx_callback(self, tx_hash, tx, tx_height):
545 if not self.check_new_tx(tx_hash, tx):
546 raise BaseException("error: received transaction is not consistent with history"%tx_hash)
549 self.transactions[tx_hash] = tx
550 self.tx_height[tx_hash] = tx_height
552 #tx_height = tx.get('height')
553 if self.verifier and tx_height>0:
554 self.verifier.add(tx_hash, tx_height)
556 self.update_tx_outputs(tx_hash)
561 def receive_history_callback(self, addr, hist):
563 if not self.check_new_history(addr, hist):
564 raise BaseException("error: received history for %s is not consistent with known transactions"%addr)
567 self.history[addr] = hist
571 for tx_hash, tx_height in hist:
573 # add it in case it was previously unconfirmed
574 if self.verifier: self.verifier.add(tx_hash, tx_height)
575 # set the height in case it changed
576 txh = self.tx_height.get(tx_hash)
577 if txh is not None and txh != tx_height:
578 print_error( "changing height for tx", tx_hash )
579 self.tx_height[tx_hash] = tx_height
582 def get_tx_history(self):
584 history = self.transactions.items()
585 history.sort(key = lambda x: self.tx_height.get(x[0]) if self.tx_height.get(x[0]) else 1e12)
589 for tx_hash, tx in history:
590 is_mine, v, fee = self.get_tx_value(tx)
591 if v is not None: balance += v
592 c, u = self.get_balance()
595 v_str = format_satoshis( c+u - balance, True, self.num_zeros)
596 result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
598 balance = c + u - balance
599 for tx_hash, tx in history:
600 conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
601 is_mine, value, fee = self.get_tx_value(tx)
602 if value is not None:
605 result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
610 def get_label(self, tx_hash):
611 label = self.labels.get(tx_hash)
612 is_default = (label == '') or (label is None)
613 if is_default: label = self.get_default_label(tx_hash)
614 return label, is_default
617 def get_default_label(self, tx_hash):
618 tx = self.transactions.get(tx_hash)
621 is_mine, _, _ = self.get_tx_value(tx)
625 if not self.is_mine(o_addr):
627 default_label = self.labels[o_addr]
629 default_label = o_addr
633 if self.is_mine(o_addr) and not self.is_change(o_addr):
638 if self.is_mine(o_addr):
644 dest_label = self.labels.get(o_addr)
646 default_label = self.labels[o_addr]
648 default_label = o_addr
653 def mktx(self, outputs, label, password, fee=None, change_addr=None, from_addr= None):
655 for address, x in outputs:
656 assert self.is_valid(address)
658 amount = sum( map(lambda x:x[1], outputs) )
659 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
661 raise ValueError("Not enough funds")
663 if not self.use_change and not change_addr:
664 change_addr = inputs[-1]['address']
665 print_error( "Sending change to", change_addr )
666 outputs = self.add_tx_change(outputs, amount, fee, total, change_addr)
669 return repr({'inputs':inputs, 'outputs':outputs})
671 tx = self.signed_tx(inputs, outputs, password)
673 for address, x in outputs:
674 if address not in self.addressbook and not self.is_mine(address):
675 self.addressbook.append(address)
678 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
679 self.labels[tx_hash] = label
683 def signed_tx(self, inputs, outputs, password):
684 tx = Transaction.from_io(inputs, outputs)
686 for txin in tx.inputs:
687 addr = txin['address']
688 sec = self.get_private_key(addr, password)
689 private_keys[addr] = sec
690 tx.sign(private_keys)
693 def sendtx(self, tx):
697 return self.receive_tx(h)
699 def send_tx(self, tx):
701 self.tx_event.clear()
702 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
703 self.interface.send([('blockchain.transaction.broadcast', [tx])], 'synchronizer')
706 def receive_tx(self,tx_hash):
709 return False, "error: " + out
711 self.receipts[tx_hash] = self.receipt
716 def read_alias(self, alias):
717 # this might not be the right place for this function.
720 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
721 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
723 url = 'https://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
725 url = 'https://' + alias + '/bitcoin.id'
729 lines = urllib.urlopen(url).readlines()
734 line = lines[0].strip().split(':')
737 target = signing_addr = line[0]
739 target, auth_name, signing_addr, signature = line
740 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
742 EC_KEY.verify_message(signing_addr, signature, msg)
744 # other lines are signed updates
745 for line in lines[1:]:
747 if not line: continue
748 line = line.split(':')
751 target, signature = line
752 EC_KEY.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
754 if not self.is_valid(target):
755 raise ValueError("Invalid bitcoin address")
757 return target, signing_addr, auth_name
759 def update_password(self, seed, old_password, new_password):
760 if new_password == '': new_password = None
761 self.use_encryption = (new_password != None)
762 self.seed = pw_encode( seed, new_password)
763 self.config.set_key('seed', self.seed, True)
764 for k in self.imported_keys.keys():
765 a = self.imported_keys[k]
766 b = pw_decode(a, old_password)
767 c = pw_encode(b, new_password)
768 self.imported_keys[k] = c
771 def get_alias(self, alias, interactive = False, show_message=None, question = None):
773 target, signing_address, auth_name = self.read_alias(alias)
774 except BaseException, e:
775 # raise exception if verify fails (verify the chain)
777 show_message("Alias error: " + str(e))
780 print target, signing_address, auth_name
782 if auth_name is None:
783 a = self.aliases.get(alias)
785 msg = "Warning: the alias '%s' is self-signed.\nThe signing address is %s.\n\nDo you want to add this alias to your list of contacts?"%(alias,signing_address)
786 if interactive and question( msg ):
787 self.aliases[alias] = (signing_address, target)
791 if signing_address != a[0]:
792 msg = "Warning: the key of alias '%s' has changed since your last visit! It is possible that someone is trying to do something nasty!!!\nDo you accept to change your trusted key?"%alias
793 if interactive and question( msg ):
794 self.aliases[alias] = (signing_address, target)
798 if signing_address not in self.authorities.keys():
799 msg = "The alias: '%s' links to %s\n\nWarning: this alias was signed by an unknown key.\nSigning authority: %s\nSigning address: %s\n\nDo you want to add this key to your list of trusted keys?"%(alias,target,auth_name,signing_address)
800 if interactive and question( msg ):
801 self.authorities[signing_address] = auth_name
806 self.aliases[alias] = (signing_address, target)
811 def parse_url(self, url, show_message, question):
812 o = url[8:].split('?')
815 params = o[1].split('&')
819 amount = label = message = signature = identity = ''
823 if k == 'amount': amount = uv
824 elif k == 'message': message = uv
825 elif k == 'label': label = uv
826 elif k == 'signature':
827 identity, signature = uv.split(':')
828 url = url.replace('&%s=%s'%(k,v),'')
832 if label and self.labels.get(address) != label:
833 if question('Give label "%s" to address %s ?'%(label,address)):
834 if address not in self.addressbook and address not in self.all_addresses():
835 self.addressbook.append(address)
836 self.labels[address] = label
839 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
840 signing_address = self.get_alias(identity, True, show_message, question)
841 elif self.is_valid(identity):
842 signing_address = identity
844 signing_address = None
845 if not signing_address:
848 EC_KEY.verify_message(signing_address, signature, url )
849 self.receipt = (signing_address, signature, url)
851 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
852 address = amount = label = identity = message = ''
854 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
855 payto_address = self.get_alias(address, True, show_message, question)
857 address = address + ' <' + payto_address + '>'
859 return address, amount, label, message, signature, identity, url
863 def freeze(self,addr):
864 if addr in self.all_addresses() and addr not in self.frozen_addresses:
865 self.unprioritize(addr)
866 self.frozen_addresses.append(addr)
867 self.config.set_key('frozen_addresses', self.frozen_addresses, True)
872 def unfreeze(self,addr):
873 if addr in self.all_addresses() and addr in self.frozen_addresses:
874 self.frozen_addresses.remove(addr)
875 self.config.set_key('frozen_addresses', self.frozen_addresses, True)
880 def prioritize(self,addr):
881 if addr in self.all_addresses() and addr not in self.prioritized_addresses:
883 self.prioritized_addresses.append(addr)
884 self.config.set_key('prioritized_addresses', self.prioritized_addresses, True)
889 def unprioritize(self,addr):
890 if addr in self.all_addresses() and addr in self.prioritized_addresses:
891 self.prioritized_addresses.remove(addr)
892 self.config.set_key('prioritized_addresses', self.prioritized_addresses, True)
899 for k,v in self.transactions.items():
903 'use_encryption': self.use_encryption,
904 'use_change': self.use_change,
906 'addresses': self.addresses,
907 'change_addresses': self.change_addresses,
908 'addr_history': self.history,
909 'labels': self.labels,
910 'contacts': self.addressbook,
911 'imported_keys': self.imported_keys,
912 'aliases': self.aliases,
913 'authorities': self.authorities,
914 'receipts': self.receipts,
915 'num_zeros': self.num_zeros,
916 'frozen_addresses': self.frozen_addresses,
917 'prioritized_addresses': self.prioritized_addresses,
918 'gap_limit': self.gap_limit,
920 'tx_height': self.tx_height,
921 'requested_amounts': self.requested_amounts,
923 for k, v in s.items():
924 self.config.set_key(k,v)
927 def set_verifier(self, verifier):
928 self.verifier = verifier
930 # review stored transactions and send them to the verifier
931 # (they are not necessarily in the history, because history items might have have been pruned)
932 for tx_hash, tx in self.transactions.items():
933 tx_height = self.tx_height[tx_hash]
935 print_error( "skipping", tx_hash, tx_height )
939 self.verifier.add(tx_hash, tx_height)
941 # review transactions that are in the history
942 for addr, hist in self.history.items():
943 if hist == ['*']: continue
944 for tx_hash, tx_height in hist:
946 # add it in case it was previously unconfirmed
947 self.verifier.add(tx_hash, tx_height)
948 # set the height in case it changed
949 txh = self.tx_height.get(tx_hash)
950 if txh is not None and txh != tx_height:
951 print_error( "changing height for tx", tx_hash )
952 self.tx_height[tx_hash] = tx_height
957 def check_new_history(self, addr, hist):
959 # check that all tx in hist are relevant
961 for tx_hash, height in hist:
962 tx = self.transactions.get(tx_hash)
964 if not tx.has_address(addr):
967 # check that we are not "orphaning" a transaction
968 old_hist = self.history.get(addr,[])
969 if old_hist == ['*']: return True
971 for tx_hash, height in old_hist:
972 if tx_hash in map(lambda x:x[0], hist): continue
974 for _addr, _hist in self.history.items():
975 if _addr == addr: continue
976 if _hist == ['*']: continue
977 _tx_hist = map(lambda x:x[0], _hist)
978 if tx_hash in _tx_hist:
983 tx = self.transactions.get(tx_hash)
984 # tx might not be there
988 if self.tx_height.get(tx_hash):
991 print_error("new history is orphaning transaction:", tx_hash)
992 # check that all outputs are not mine, request histories
994 for o in tx.get('outputs'):
995 _addr = o.get('address')
996 # assert not self.is_mine(_addr)
997 ext_requests.append( ('blockchain.address.get_history', [_addr]) )
999 ext_h = self.interface.synchronous_get(ext_requests)
1002 if h == ['*']: continue
1004 if item.get('tx_hash') == tx_hash:
1005 height = item.get('height')
1006 self.tx_height[tx_hash] = height
1008 print_error("found height for", tx_hash, height)
1009 self.verifier.add(tx_hash, height)
1011 print_error("removing orphaned tx from history", tx_hash)
1012 self.transactions.pop(tx_hash)
1018 def check_new_tx(self, tx_hash, tx):
1019 # 1 check that tx is referenced in addr_history.
1021 for addr, hist in self.history.items():
1022 if hist == ['*']:continue
1023 for txh, height in hist:
1025 addresses.append(addr)
1030 # 2 check that referencing addresses are in the tx
1031 for addr in addresses:
1032 if not tx.has_address(addr):
1040 class WalletSynchronizer(threading.Thread):
1043 def __init__(self, wallet, config):
1044 threading.Thread.__init__(self)
1046 self.wallet = wallet
1047 self.interface = self.wallet.interface
1048 self.interface.register_channel('synchronizer')
1049 self.wallet.interface.register_callback('connected', lambda: self.wallet.set_up_to_date(False))
1050 self.wallet.interface.register_callback('connected', lambda: self.interface.send([('server.banner',[])],'synchronizer') )
1051 self.was_updated = True
1052 self.running = False
1053 self.lock = threading.Lock()
1056 with self.lock: self.running = False
1057 self.interface.poke('synchronizer')
1059 def is_running(self):
1060 with self.lock: return self.running
1062 def synchronize_wallet(self):
1063 new_addresses = self.wallet.synchronize()
1065 self.subscribe_to_addresses(new_addresses)
1066 self.wallet.up_to_date = False
1069 if not self.interface.is_up_to_date('synchronizer'):
1070 if self.wallet.is_up_to_date():
1071 self.wallet.set_up_to_date(False)
1072 self.was_updated = True
1075 self.wallet.set_up_to_date(True)
1076 self.was_updated = True
1079 def subscribe_to_addresses(self, addresses):
1081 for addr in addresses:
1082 messages.append(('blockchain.address.subscribe', [addr]))
1083 self.interface.send( messages, 'synchronizer')
1087 with self.lock: self.running = True
1091 requested_histories = {}
1093 # request any missing transactions
1094 for history in self.wallet.history.values():
1095 if history == ['*']: continue
1096 for tx_hash, tx_height in history:
1097 if self.wallet.transactions.get(tx_hash) is None and (tx_hash, tx_height) not in missing_tx:
1098 missing_tx.append( (tx_hash, tx_height) )
1099 print_error("missing tx", missing_tx)
1101 # wait until we are connected, in case the user is not connected
1102 while not self.interface.is_connected:
1105 # request banner, because 'connected' event happens before this thread is started
1106 self.interface.send([('server.banner',[])],'synchronizer')
1109 self.subscribe_to_addresses(self.wallet.all_addresses())
1111 while self.is_running():
1112 # 1. send new requests
1113 self.synchronize_wallet()
1115 for tx_hash, tx_height in missing_tx:
1116 if (tx_hash, tx_height) not in requested_tx:
1117 self.interface.send([ ('blockchain.transaction.get',[tx_hash, tx_height]) ], 'synchronizer')
1118 requested_tx.append( (tx_hash, tx_height) )
1121 if self.was_updated:
1122 self.interface.trigger_callback('updated')
1123 self.was_updated = False
1126 r = self.interface.get_response('synchronizer')
1128 # poke sends None. (needed during stop)
1131 # 3. handle response
1132 method = r['method']
1133 params = r['params']
1134 result = r.get('result')
1135 error = r.get('error')
1140 if method == 'blockchain.address.subscribe':
1142 if self.wallet.get_status(self.wallet.get_history(addr)) != result:
1143 if requested_histories.get(addr) is None:
1144 self.interface.send([('blockchain.address.get_history', [addr])], 'synchronizer')
1145 requested_histories[addr] = result
1147 elif method == 'blockchain.address.get_history':
1149 print_error("receiving history", addr, result)
1151 assert requested_histories.pop(addr) == '*'
1152 self.wallet.receive_history_callback(addr, result)
1155 # check that txids are unique
1158 tx_hash = item['tx_hash']
1159 if tx_hash not in txids:
1160 txids.append(tx_hash)
1161 hist.append( (tx_hash, item['height']) )
1163 if len(hist) != len(result):
1164 raise BaseException("error: server sent history with non-unique txid", result)
1166 # check that the status corresponds to what was announced
1167 rs = requested_histories.pop(addr)
1168 if self.wallet.get_status(hist) != rs:
1169 raise BaseException("error: status mismatch: %s"%addr)
1171 # store received history
1172 self.wallet.receive_history_callback(addr, hist)
1174 # request transactions that we don't have
1175 for tx_hash, tx_height in hist:
1176 if self.wallet.transactions.get(tx_hash) is None:
1177 if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
1178 missing_tx.append( (tx_hash, tx_height) )
1180 elif method == 'blockchain.transaction.get':
1182 tx_height = params[1]
1183 assert tx_hash == hash_encode(Hash(result.decode('hex')))
1184 tx = Transaction(result)
1185 self.wallet.receive_tx_callback(tx_hash, tx, tx_height)
1186 self.was_updated = True
1187 requested_tx.remove( (tx_hash, tx_height) )
1188 print_error("received tx:", tx)
1190 elif method == 'blockchain.transaction.broadcast':
1191 self.wallet.tx_result = result
1192 self.wallet.tx_event.set()
1194 elif method == 'server.banner':
1195 self.wallet.banner = result
1196 self.interface.trigger_callback('banner')
1198 print_error("Error: Unknown message:" + method + ", " + repr(params) + ", " + repr(result) )
1200 if self.was_updated and not requested_tx:
1201 self.interface.trigger_callback('updated')
1202 self.was_updated = False