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/>.
20 import sys, base64, os, re, hashlib, copy, operator, ast, threading, random
24 from ecdsa.util import string_to_number, number_to_string
26 print "python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'"
32 print "AES does not seem to be installed. Try 'sudo pip install slowaes'"
36 ############ functions from pywallet #####################
40 def hash_160(public_key):
42 md = hashlib.new('ripemd160')
43 md.update(hashlib.sha256(public_key).digest())
47 md = ripemd.new(hashlib.sha256(public_key).digest())
51 def public_key_to_bc_address(public_key):
52 h160 = hash_160(public_key)
53 return hash_160_to_bc_address(h160)
55 def hash_160_to_bc_address(h160):
56 vh160 = chr(addrtype) + h160
59 return b58encode(addr)
61 def bc_address_to_hash_160(addr):
62 bytes = b58decode(addr, 25)
65 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
66 __b58base = len(__b58chars)
69 """ encode v, which is a string of bytes, to base58.
73 for (i, c) in enumerate(v[::-1]):
74 long_value += (256**i) * ord(c)
77 while long_value >= __b58base:
78 div, mod = divmod(long_value, __b58base)
79 result = __b58chars[mod] + result
81 result = __b58chars[long_value] + result
83 # Bitcoin does a little leading-zero-compression:
84 # leading 0-bytes in the input become leading-1s
87 if c == '\0': nPad += 1
90 return (__b58chars[0]*nPad) + result
92 def b58decode(v, length):
93 """ decode v into a string of len bytes
96 for (i, c) in enumerate(v[::-1]):
97 long_value += __b58chars.find(c) * (__b58base**i)
100 while long_value >= 256:
101 div, mod = divmod(long_value, 256)
102 result = chr(mod) + result
104 result = chr(long_value) + result
108 if c == __b58chars[0]: nPad += 1
111 result = chr(0)*nPad + result
112 if length is not None and len(result) != length:
119 return hashlib.sha256(hashlib.sha256(data).digest()).digest()
121 def EncodeBase58Check(vchIn):
123 return b58encode(vchIn + hash[0:4])
125 def DecodeBase58Check(psz):
126 vchRet = b58decode(psz, None)
136 def PrivKeyToSecret(privkey):
137 return privkey[9:9+32]
139 def SecretToASecret(secret):
140 vchIn = chr(addrtype+128) + secret
141 return EncodeBase58Check(vchIn)
143 def ASecretToSecret(key):
144 vch = DecodeBase58Check(key)
145 if vch and vch[0] == chr(addrtype+128):
150 ########### end pywallet functions #######################
153 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
154 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
157 def int_to_hex(i, length=1):
158 s = hex(i)[2:].rstrip('L')
159 s = "0"*(2*length - len(s)) + s
160 return s.decode('hex')[::-1].encode('hex')
164 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
165 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
169 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
170 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
171 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
172 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
173 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
174 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
175 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
176 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
177 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
178 oid_secp256k1 = (1,3,132,0,10)
179 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
183 out = re.sub('( [^\n]*|)\n','',s)
184 out = out.replace(' ','')
185 out = out.replace('\n','')
188 def raw_tx( inputs, outputs, for_sig = None ):
189 s = int_to_hex(1,4) + ' version\n'
190 s += int_to_hex( len(inputs) ) + ' number of inputs\n'
191 for i in range(len(inputs)):
192 _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
193 s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n'
194 s += int_to_hex(p_index,4) + ' prev index\n'
196 sig = sig + chr(1) # hashtype
197 script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig)
198 script += sig.encode('hex') + ' sig\n'
199 pubkey = chr(4) + pubkey
200 script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey)
201 script += pubkey.encode('hex') + ' pubkey\n'
203 script = p_script + ' scriptsig \n'
206 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
208 s += "ffffffff" + ' sequence\n'
209 s += int_to_hex( len(outputs) ) + ' number of outputs\n'
210 for output in outputs:
211 addr, amount = output
212 s += int_to_hex( amount, 8) + ' amount: %d\n'%amount
213 script = '76a9' # op_dup, op_hash_160
214 script += '14' # push 0x14 bytes
215 script += bc_address_to_hash_160(addr).encode('hex')
216 script += '88ac' # op_equalverify, op_checksig
217 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
218 s += script + ' script \n'
219 s += int_to_hex(0,4) # lock time
220 if for_sig is not None: s += int_to_hex(1, 4) # hash type
226 def format_satoshis(x, is_diff=False, num_zeros = 0):
227 from decimal import Decimal
228 s = str( Decimal(x) /100000000 )
231 if not '.' in s: s += '.'
233 s += "0"*( 1 + num_zeros - ( len(s) - p ))
234 s += " "*( 9 - ( len(s) - p ))
235 s = " "*( 5 - ( p )) + s
239 from version import ELECTRUM_VERSION, SEED_VERSION
240 from interface import DEFAULT_SERVERS
246 def __init__(self, gui_callback = lambda: None):
248 self.electrum_version = ELECTRUM_VERSION
249 self.seed_version = SEED_VERSION
250 self.gui_callback = gui_callback
252 self.gap_limit = 5 # configuration
255 self.master_public_key = ''
258 self.use_encryption = False
259 self.addresses = [] # receiving addresses visible for user
260 self.change_addresses = [] # addresses used as change
261 self.seed = '' # encrypted
263 self.labels = {} # labels for addresses and transactions
264 self.aliases = {} # aliases for addresses
265 self.authorities = {} # trusted addresses
266 self.frozen_addresses = []
268 self.receipts = {} # signed URIs
269 self.receipt = None # next receipt
270 self.addressbook = [] # outgoing addresses, for payments
275 self.imported_keys = {}
276 self.remote_url = None
278 self.was_updated = True
282 # there is a difference between self.up_to_date and self.is_up_to_date()
283 # self.is_up_to_date() returns true when all requests have been answered and processed
284 # self.up_to_date is true when the wallet is synchronized (stronger requirement)
285 self.up_to_date_event = threading.Event()
286 self.up_to_date_event.clear()
287 self.up_to_date = False
288 self.lock = threading.Lock()
289 self.tx_event = threading.Event()
291 self.pick_random_server()
295 def pick_random_server(self):
296 self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
298 def is_up_to_date(self):
299 return self.interface.responses.empty() and not self.interface.unanswered_requests
301 def set_server(self, server):
302 # raise an error if the format isnt correct
303 a,b,c = server.split(':')
305 assert c in ['t','h','n']
307 if server != self.server:
310 self.interface.is_connected = False # this exits the polling loop
311 self.interface.poke()
313 def set_path(self, wallet_path):
315 if wallet_path is not None:
316 self.path = wallet_path
318 # backward compatibility: look for wallet file in the default data directory
319 if "HOME" in os.environ:
320 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
321 elif "LOCALAPPDATA" in os.environ:
322 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
323 elif "APPDATA" in os.environ:
324 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
326 raise BaseException("No home directory found in environment variables.")
328 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
329 self.path = os.path.join( wallet_dir, 'electrum.dat' )
331 def import_key(self, keypair, password):
332 address, key = keypair.split(':')
333 if not self.is_valid(address): return False
334 if address in self.all_addresses(): return False
335 b = ASecretToSecret( key )
336 if not b: return False
337 secexp = int( b.encode('hex'), 16)
338 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
340 public_key = private_key.get_verifying_key()
341 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
342 self.imported_keys[address] = self.pw_encode( key, password )
345 def new_seed(self, password):
346 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
349 self.seed = self.pw_encode( seed, password )
352 def init_mpk(self,seed):
355 secexp = self.stretch_key(seed)
356 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
357 self.master_public_key = master_private_key.get_verifying_key().to_string()
359 def all_addresses(self):
360 return self.addresses + self.change_addresses + self.imported_keys.keys()
362 def is_mine(self, address):
363 return address in self.all_addresses()
365 def is_change(self, address):
366 return address in self.change_addresses
368 def is_valid(self,addr):
369 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
370 if not ADDRESS_RE.match(addr): return False
372 h = bc_address_to_hash_160(addr)
375 return addr == hash_160_to_bc_address(h)
377 def stretch_key(self,seed):
379 for i in range(100000):
380 seed = hashlib.sha256(seed + oldseed).digest()
381 return string_to_number( seed )
383 def get_sequence(self,n,for_change):
384 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
386 def get_private_key(self, address, password):
387 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
388 order = generator_secp256k1.order()
390 if address in self.imported_keys.keys():
391 b = self.pw_decode( self.imported_keys[address], password )
392 b = ASecretToSecret( b )
393 secexp = int( b.encode('hex'), 16)
395 if address in self.addresses:
396 n = self.addresses.index(address)
398 elif address in self.change_addresses:
399 n = self.change_addresses.index(address)
402 raise BaseException("unknown address")
404 seed = self.pw_decode( self.seed, password)
406 raise BaseException("Invalid password")
407 secexp = self.stretch_key(seed)
408 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
410 pk = number_to_string(secexp,order)
413 def msg_magic(self, message):
414 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
416 def sign_message(self, address, message, password):
417 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
418 public_key = private_key.get_verifying_key()
419 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
420 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
422 sig = base64.b64encode( chr(27+i) + signature )
424 self.verify_message( address, sig, message)
429 raise BaseException("error: cannot sign message")
432 def verify_message(self, address, signature, message):
433 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
434 from ecdsa import numbertheory, ellipticcurve, util
436 curve = curve_secp256k1
437 G = generator_secp256k1
439 # extract r,s from signature
440 sig = base64.b64decode(signature)
441 if len(sig) != 65: raise BaseException("Wrong encoding")
442 r,s = util.sigdecode_string(sig[1:], order)
443 recid = ord(sig[0]) - 27
445 x = r + (recid/2) * order
447 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
448 beta = msqr.modular_sqrt(alpha, curve.p())
449 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
450 # 1.4 the constructor checks that nR is at infinity
451 R = ellipticcurve.Point(curve, x, y, order)
452 # 1.5 compute e from message:
453 h = Hash( self.msg_magic( message ) )
454 e = string_to_number(h)
456 # 1.6 compute Q = r^-1 (sR - eG)
457 inv_r = numbertheory.inverse_mod(r,order)
458 Q = inv_r * ( s * R + minus_e * G )
459 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
460 # check that Q is the public key
461 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
462 # check that we get the original signing address
463 addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
466 print "bad signature"
467 raise BaseException("Bad signature")
470 def create_new_address(self, for_change):
471 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
473 n = len(self.change_addresses) if for_change else len(self.addresses)
474 z = self.get_sequence(n,for_change)
475 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
476 pubkey_point = master_public_key.pubkey.point + z*curve.generator
477 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
478 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
480 self.change_addresses.append(address)
482 self.addresses.append(address)
484 self.history[address] = []
490 def synchronize(self):
491 if not self.master_public_key:
496 if self.change_addresses == []:
497 new_addresses.append( self.create_new_address(True) )
499 a = self.change_addresses[-1]
500 if self.history.get(a):
501 new_addresses.append( self.create_new_address(True) )
507 if len(self.addresses) < n:
508 new_addresses.append( self.create_new_address(False) )
510 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
513 new_addresses.append( self.create_new_address(False) )
516 num = self.get_remote_number()
517 while len(self.addresses)<num:
518 new_addresses.append( self.create_new_address(False) )
523 def get_remote_number(self):
525 server = jsonrpclib.Server(self.remote_url)
526 out = server.getnum()
529 def get_remote_mpk(self):
531 server = jsonrpclib.Server(self.remote_url)
532 out = server.getkey()
536 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
538 def fill_addressbook(self):
539 for tx in self.tx_history.values():
541 for i in tx['outputs']:
542 if not self.is_mine(i) and i not in self.addressbook:
543 self.addressbook.append(i)
545 self.update_tx_labels()
550 'seed_version':self.seed_version,
551 'use_encryption':self.use_encryption,
552 'master_public_key': self.master_public_key.encode('hex'),
554 'server':self.server,
556 'addresses':self.addresses,
557 'change_addresses':self.change_addresses,
558 'history':self.history,
559 'labels':self.labels,
560 'contacts':self.addressbook,
561 'imported_keys':self.imported_keys,
562 'aliases':self.aliases,
563 'authorities':self.authorities,
564 'receipts':self.receipts,
565 'num_zeros':self.num_zeros,
566 'frozen_addresses':self.frozen_addresses,
568 f = open(self.path,"w")
575 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
576 self.file_exists = False
578 f = open(self.path,"r")
583 data = interface.old_to_new(data)
585 d = ast.literal_eval( data )
586 self.seed_version = d.get('seed_version')
587 self.master_public_key = d.get('master_public_key').decode('hex')
588 self.use_encryption = d.get('use_encryption')
589 self.fee = int( d.get('fee') )
590 self.seed = d.get('seed')
591 self.server = d.get('server')
592 #blocks = d.get('blocks')
593 self.addresses = d.get('addresses')
594 self.change_addresses = d.get('change_addresses')
595 self.history = d.get('history')
596 self.labels = d.get('labels')
597 self.addressbook = d.get('contacts')
598 self.imported_keys = d.get('imported_keys',{})
599 self.aliases = d.get('aliases',{})
600 self.authorities = d.get('authorities',{})
601 self.receipts = d.get('receipts',{})
602 self.num_zeros = d.get('num_zeros',0)
603 self.frozen_addresses = d.get('frozen_addresses',[])
605 raise BaseException("cannot read wallet file")
607 self.update_tx_history()
609 if self.seed_version != SEED_VERSION:
610 raise BaseException(upgrade_msg)
612 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
614 self.file_exists = True
619 def get_addr_balance(self, addr):
620 assert self.is_mine(addr)
621 h = self.history.get(addr,[])
631 def get_balance(self):
633 for addr in self.all_addresses():
634 c, u = self.get_addr_balance(addr)
640 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
641 """ todo: minimize tx size """
643 fee = self.fee if fixed_fee is None else fixed_fee
646 domain = [from_addr] if from_addr else self.all_addresses()
647 for i in self.frozen_addresses:
648 if i in domain: domain.remove(i)
651 h = self.history.get(addr)
652 if h is None: continue
654 if item.get('raw_output_script'):
655 coins.append( (addr,item))
657 coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
661 v = item.get('value')
663 inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
664 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
665 if total >= amount + fee: break
667 #print "not enough funds: %d %d"%(total, fee)
669 return inputs, total, fee
671 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
672 outputs = [ (to_addr, amount) ]
673 change_amount = total - ( amount + fee )
674 if change_amount != 0:
675 # normally, the update thread should ensure that the last change address is unused
677 change_addr = self.change_addresses[-1]
678 outputs.append( ( change_addr, change_amount) )
681 def sign_inputs( self, inputs, outputs, password ):
683 for i in range(len(inputs)):
684 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
685 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
686 public_key = private_key.get_verifying_key()
687 pubkey = public_key.to_string()
688 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
689 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
690 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
691 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
694 def pw_encode(self, s, password):
696 secret = Hash(password)
697 return EncodeAES(secret, s)
701 def pw_decode(self, s, password):
702 if password is not None:
703 secret = Hash(password)
704 d = DecodeAES(secret, s)
709 raise BaseException("Invalid password")
714 def get_status(self, address):
715 h = self.history.get(address)
720 status = lastpoint['block_hash']
721 if status == 'mempool':
722 status = status + ':%d'% len(h)
725 def receive_status_callback(self, addr, status):
727 if self.get_status(addr) != status:
728 #print "updating status for", addr, status
729 self.interface.get_history(addr)
731 def receive_history_callback(self, addr, data):
732 #print "updating history for", addr
734 self.history[addr] = data
735 self.update_tx_history()
738 def get_tx_history(self):
739 lines = self.tx_history.values()
740 lines = sorted(lines, key=operator.itemgetter("timestamp"))
743 def update_tx_history(self):
745 for addr in self.all_addresses():
746 h = self.history.get(addr)
747 if h is None: continue
749 tx_hash = tx['tx_hash']
750 line = self.tx_history.get(tx_hash)
752 self.tx_history[tx_hash] = copy.copy(tx)
753 line = self.tx_history.get(tx_hash)
755 line['value'] += tx['value']
756 if line['height'] == 0:
757 line['timestamp'] = 1e12
758 self.update_tx_labels()
760 def update_tx_labels(self):
761 for tx in self.tx_history.values():
764 for o_addr in tx['outputs']:
765 if not self.is_change(o_addr):
766 dest_label = self.labels.get(o_addr)
768 default_label = 'to: ' + dest_label
770 default_label = 'to: ' + o_addr
772 for o_addr in tx['outputs']:
773 if self.is_mine(o_addr) and not self.is_change(o_addr):
774 dest_label = self.labels.get(o_addr)
776 default_label = 'at: ' + dest_label
778 default_label = 'at: ' + o_addr
779 tx['default_label'] = default_label
781 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
782 if not self.is_valid(to_address):
783 raise BaseException("Invalid address")
784 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
786 raise BaseException("Not enough funds")
787 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
788 s_inputs = self.sign_inputs( inputs, outputs, password )
790 tx = filter( raw_tx( s_inputs, outputs ) )
791 if to_address not in self.addressbook:
792 self.addressbook.append(to_address)
794 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
795 self.labels[tx_hash] = label
799 def sendtx(self, tx):
800 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
801 self.tx_event.clear()
802 self.interface.send([('blockchain.transaction.broadcast', [tx])])
806 return False, "error: " + out
808 self.receipts[tx_hash] = self.receipt
813 def read_alias(self, alias):
814 # this might not be the right place for this function.
817 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
818 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
820 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
822 url = 'http://' + alias + '/bitcoin.id'
826 lines = urllib.urlopen(url).readlines()
831 line = lines[0].strip().split(':')
834 target = signing_addr = line[0]
836 target, auth_name, signing_addr, signature = line
837 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
839 self.verify_message(signing_addr, signature, msg)
841 # other lines are signed updates
842 for line in lines[1:]:
844 if not line: continue
845 line = line.split(':')
848 target, signature = line
849 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
851 if not self.is_valid(target):
852 raise BaseException("Invalid bitcoin address")
854 return target, signing_addr, auth_name
856 def update_password(self, seed, new_password):
857 if new_password == '': new_password = None
858 self.use_encryption = (new_password != None)
859 self.seed = self.pw_encode( seed, new_password)
860 for k in self.imported_keys.keys():
861 a = self.imported_keys[k]
862 b = self.pw_decode(a, password)
863 c = self.pw_encode(b, new_password)
864 self.imported_keys[k] = c
867 def get_alias(self, alias, interactive = False, show_message=None, question = None):
869 target, signing_address, auth_name = self.read_alias(alias)
870 except BaseException, e:
871 # raise exception if verify fails (verify the chain)
873 show_message("Alias error: " + e.message)
876 print target, signing_address, auth_name
878 if auth_name is None:
879 a = self.aliases.get(alias)
881 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)
882 if interactive and question( msg ):
883 self.aliases[alias] = (signing_address, target)
887 if signing_address != a[0]:
888 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
889 if interactive and question( msg ):
890 self.aliases[alias] = (signing_address, target)
894 if signing_address not in self.authorities.keys():
895 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)
896 if interactive and question( msg ):
897 self.authorities[signing_address] = auth_name
902 self.aliases[alias] = (signing_address, target)
907 def parse_url(self, url, show_message, question):
908 o = url[8:].split('?')
911 params = o[1].split('&')
915 amount = label = message = signature = identity = ''
919 if k == 'amount': amount = uv
920 elif k == 'message': message = uv
921 elif k == 'label': label = uv
922 elif k == 'signature':
923 identity, signature = uv.split(':')
924 url = url.replace('&%s=%s'%(k,v),'')
929 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
930 signing_address = self.get_alias(identity, True, show_message, question)
931 elif self.is_valid(identity):
932 signing_address = identity
934 signing_address = None
935 if not signing_address:
938 self.verify_message(signing_address, signature, url )
939 self.receipt = (signing_address, signature, url)
941 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
942 address = amount = label = identity = message = ''
944 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
945 payto_address = self.get_alias(address, True, show_message, question)
947 address = address + ' <' + payto_address + '>'
949 return address, amount, label, message, signature, identity, url
953 self.interface.poke()
954 self.up_to_date_event.wait()
957 def start_session(self, interface):
958 self.interface = interface
959 self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
960 self.interface.subscribe(self.all_addresses())