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
24 from ecdsa.util import string_to_number, number_to_string
26 print "python-ecdsa does not seem to be installed. Try 'sudo easy_install ecdsa'"
32 print "AES does not seem to be installed. Try 'sudo easy_install slowaes'"
36 ############ functions from pywallet #####################
40 def hash_160(public_key):
41 md = hashlib.new('ripemd160')
42 md.update(hashlib.sha256(public_key).digest())
45 def public_key_to_bc_address(public_key):
46 h160 = hash_160(public_key)
47 return hash_160_to_bc_address(h160)
49 def hash_160_to_bc_address(h160):
50 vh160 = chr(addrtype) + h160
53 return b58encode(addr)
55 def bc_address_to_hash_160(addr):
56 bytes = b58decode(addr, 25)
59 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
60 __b58base = len(__b58chars)
63 """ encode v, which is a string of bytes, to base58.
67 for (i, c) in enumerate(v[::-1]):
68 long_value += (256**i) * ord(c)
71 while long_value >= __b58base:
72 div, mod = divmod(long_value, __b58base)
73 result = __b58chars[mod] + result
75 result = __b58chars[long_value] + result
77 # Bitcoin does a little leading-zero-compression:
78 # leading 0-bytes in the input become leading-1s
81 if c == '\0': nPad += 1
84 return (__b58chars[0]*nPad) + result
86 def b58decode(v, length):
87 """ decode v into a string of len bytes
90 for (i, c) in enumerate(v[::-1]):
91 long_value += __b58chars.find(c) * (__b58base**i)
94 while long_value >= 256:
95 div, mod = divmod(long_value, 256)
96 result = chr(mod) + result
98 result = chr(long_value) + result
102 if c == __b58chars[0]: nPad += 1
105 result = chr(0)*nPad + result
106 if length is not None and len(result) != length:
113 return hashlib.sha256(hashlib.sha256(data).digest()).digest()
115 def EncodeBase58Check(vchIn):
117 return b58encode(vchIn + hash[0:4])
119 def DecodeBase58Check(psz):
120 vchRet = b58decode(psz, None)
130 def PrivKeyToSecret(privkey):
131 return privkey[9:9+32]
133 def SecretToASecret(secret):
134 vchIn = chr(addrtype+128) + secret
135 return EncodeBase58Check(vchIn)
137 def ASecretToSecret(key):
138 vch = DecodeBase58Check(key)
139 if vch and vch[0] == chr(addrtype+128):
144 ########### end pywallet functions #######################
147 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
148 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
151 def int_to_hex(i, length=1):
152 s = hex(i)[2:].rstrip('L')
153 s = "0"*(2*length - len(s)) + s
154 return s.decode('hex')[::-1].encode('hex')
158 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
159 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
163 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
164 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
165 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
166 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
167 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
168 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
169 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
170 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
171 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
172 oid_secp256k1 = (1,3,132,0,10)
173 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
177 out = re.sub('( [^\n]*|)\n','',s)
178 out = out.replace(' ','')
179 out = out.replace('\n','')
182 def raw_tx( inputs, outputs, for_sig = None ):
183 s = int_to_hex(1,4) + ' version\n'
184 s += int_to_hex( len(inputs) ) + ' number of inputs\n'
185 for i in range(len(inputs)):
186 _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
187 s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n'
188 s += int_to_hex(p_index,4) + ' prev index\n'
190 sig = sig + chr(1) # hashtype
191 script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig)
192 script += sig.encode('hex') + ' sig\n'
193 pubkey = chr(4) + pubkey
194 script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey)
195 script += pubkey.encode('hex') + ' pubkey\n'
197 script = p_script + ' scriptsig \n'
200 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
202 s += "ffffffff" + ' sequence\n'
203 s += int_to_hex( len(outputs) ) + ' number of outputs\n'
204 for output in outputs:
205 addr, amount = output
206 s += int_to_hex( amount, 8) + ' amount: %d\n'%amount
207 script = '76a9' # op_dup, op_hash_160
208 script += '14' # push 0x14 bytes
209 script += bc_address_to_hash_160(addr).encode('hex')
210 script += '88ac' # op_equalverify, op_checksig
211 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
212 s += script + ' script \n'
213 s += int_to_hex(0,4) # lock time
214 if for_sig is not None: s += int_to_hex(1, 4) # hash type
220 def format_satoshis(x, is_diff=False):
221 from decimal import Decimal
222 s = str( Decimal(x) /100000000 )
225 if not '.' in s: s += '.'
227 s += " "*( 9 - ( len(s) - p ))
228 s = " "*( 5 - ( p )) + s
232 from version import ELECTRUM_VERSION, SEED_VERSION
240 self.electrum_version = ELECTRUM_VERSION
241 self.seed_version = SEED_VERSION
243 self.gap_limit = 5 # configuration
245 self.master_public_key = ''
248 self.use_encryption = False
249 self.addresses = [] # receiving addresses visible for user
250 self.change_addresses = [] # addresses used as change
251 self.seed = '' # encrypted
252 self.status = {} # current status of addresses
254 self.labels = {} # labels for addresses and transactions
255 self.aliases = {} # aliases for addresses
256 self.authorities = {} # trusted addresses
258 self.receipts = {} # signed URIs
259 self.receipt = None # next receipt
260 self.addressbook = [] # outgoing addresses, for payments
265 self.imported_keys = {}
266 self.remote_url = None
268 self.was_updated = False
271 self.up_to_date_event = threading.Event()
272 self.up_to_date_event.clear()
275 def set_server(self, host, port):
276 if host!= self.host or port!=self.port:
279 self.interface.is_connected = False # this exits the polling loop
281 def set_path(self, wallet_path):
283 if wallet_path is not None:
284 self.path = wallet_path
286 # backward compatibility: look for wallet file in the default data directory
287 if "HOME" in os.environ:
288 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
289 elif "LOCALAPPDATA" in os.environ:
290 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
291 elif "APPDATA" in os.environ:
292 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
294 raise BaseException("No home directory found in environment variables.")
296 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
297 self.path = os.path.join( wallet_dir, 'electrum.dat' )
299 def import_key(self, keypair, password):
300 address, key = keypair.split(':')
301 if not self.is_valid(address): return False
302 if address in self.all_addresses(): return False
303 b = ASecretToSecret( key )
304 if not b: return False
305 secexp = int( b.encode('hex'), 16)
306 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
308 public_key = private_key.get_verifying_key()
309 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
310 self.imported_keys[address] = self.pw_encode( key, password )
313 def new_seed(self, password):
314 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
317 self.seed = self.pw_encode( seed, password )
320 self.create_new_address_without_history(True)
321 for i in range(self.gap_limit):
322 self.create_new_address_without_history(False)
325 def init_mpk(self,seed):
328 secexp = self.stretch_key(seed)
329 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
330 self.master_public_key = master_private_key.get_verifying_key().to_string()
332 def all_addresses(self):
333 return self.addresses + self.change_addresses + self.imported_keys.keys()
335 def is_mine(self, address):
336 return address in self.all_addresses()
338 def is_change(self, address):
339 return address in self.change_addresses
341 def is_valid(self,addr):
342 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
343 if not ADDRESS_RE.match(addr): return False
345 h = bc_address_to_hash_160(addr)
348 return addr == hash_160_to_bc_address(h)
350 def stretch_key(self,seed):
352 for i in range(100000):
353 seed = hashlib.sha256(seed + oldseed).digest()
354 return string_to_number( seed )
356 def get_sequence(self,n,for_change):
357 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
359 def get_private_key(self, address, password):
360 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
361 order = generator_secp256k1.order()
363 if address in self.imported_keys.keys():
364 b = self.pw_decode( self.imported_keys[address], password )
365 b = ASecretToSecret( b )
366 secexp = int( b.encode('hex'), 16)
368 if address in self.addresses:
369 n = self.addresses.index(address)
371 elif address in self.change_addresses:
372 n = self.change_addresses.index(address)
375 raise BaseException("unknown address")
377 seed = self.pw_decode( self.seed, password)
379 raise BaseException("Invalid password")
380 secexp = self.stretch_key(seed)
381 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
383 pk = number_to_string(secexp,order)
386 def msg_magic(self, message):
387 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
389 def sign_message(self, address, message, password):
390 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
391 public_key = private_key.get_verifying_key()
392 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
393 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
395 sig = base64.b64encode( chr(27+i) + signature )
397 self.verify_message( address, sig, message)
402 raise BaseException("error: cannot sign message")
405 def verify_message(self, address, signature, message):
406 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
407 from ecdsa import numbertheory, ellipticcurve, util
409 curve = curve_secp256k1
410 G = generator_secp256k1
412 # extract r,s from signature
413 sig = base64.b64decode(signature)
414 if len(sig) != 65: raise BaseException("Wrong encoding")
415 r,s = util.sigdecode_string(sig[1:], order)
416 recid = ord(sig[0]) - 27
418 x = r + (recid/2) * order
420 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
421 beta = msqr.modular_sqrt(alpha, curve.p())
422 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
423 # 1.4 the constructor checks that nR is at infinity
424 R = ellipticcurve.Point(curve, x, y, order)
425 # 1.5 compute e from message:
426 h = Hash( self.msg_magic( message ) )
427 e = string_to_number(h)
429 # 1.6 compute Q = r^-1 (sR - eG)
430 inv_r = numbertheory.inverse_mod(r,order)
431 Q = inv_r * ( s * R + minus_e * G )
432 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
433 # check that Q is the public key
434 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
435 # check that we get the original signing address
436 addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
439 print "bad signature"
440 raise BaseException("Bad signature")
443 def create_new_address_without_history(self, for_change):
444 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
446 n = len(self.change_addresses) if for_change else len(self.addresses)
447 z = self.get_sequence(n,for_change)
448 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
449 pubkey_point = master_public_key.pubkey.point + z*curve.generator
450 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
451 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
453 self.change_addresses.append(address)
455 self.addresses.append(address)
457 self.history[address] = []
458 self.status[address] = None
463 def create_new_address(self, bool):
464 address = self.create_new_address_without_history(bool)
465 self.interface.subscribe([address])
469 def synchronize(self):
470 if not self.master_public_key:
475 if self.change_addresses == []:
476 self.create_new_address(True)
479 a = self.change_addresses[-1]
480 if self.history.get(a):
481 self.create_new_address(True)
488 if len(self.addresses) < n:
489 self.create_new_address(False)
492 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
495 self.create_new_address(False)
499 num = self.get_remote_number()
500 while len(self.addresses)<num:
501 self.create_new_address(False)
507 def get_remote_number(self):
509 server = jsonrpclib.Server(self.remote_url)
510 out = server.getnum()
513 def get_remote_mpk(self):
515 server = jsonrpclib.Server(self.remote_url)
516 out = server.getkey()
520 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
522 def fill_addressbook(self):
523 for tx in self.tx_history.values():
525 for i in tx['outputs']:
526 if not self.is_mine(i) and i not in self.addressbook:
527 self.addressbook.append(i)
529 self.update_tx_labels()
534 'seed_version':self.seed_version,
535 'use_encryption':self.use_encryption,
536 'master_public_key': self.master_public_key.encode('hex'),
540 #'blocks':self.interface.blocks,
542 'addresses':self.addresses,
543 'change_addresses':self.change_addresses,
544 'status':self.status,
545 'history':self.history,
546 'labels':self.labels,
547 'contacts':self.addressbook,
548 'imported_keys':self.imported_keys,
549 'aliases':self.aliases,
550 'authorities':self.authorities,
551 'receipts':self.receipts,
553 f = open(self.path,"w")
560 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
561 self.file_exists = False
563 f = open(self.path,"r")
568 self.port = DEFAULT_PORT
571 d = ast.literal_eval( data )
572 self.seed_version = d.get('seed_version')
573 self.master_public_key = d.get('master_public_key').decode('hex')
574 self.use_encryption = d.get('use_encryption')
575 self.fee = int( d.get('fee') )
576 self.seed = d.get('seed')
577 self.host = d.get('host')
578 self.port = d.get('port')
579 blocks = d.get('blocks')
580 self.addresses = d.get('addresses')
581 self.change_addresses = d.get('change_addresses')
582 self.status = d.get('status')
583 self.history = d.get('history')
584 self.labels = d.get('labels')
585 self.addressbook = d.get('contacts')
586 self.imported_keys = d.get('imported_keys',{})
587 self.aliases = d.get('aliases',{})
588 self.authorities = d.get('authorities',{})
589 self.receipts = d.get('receipts',{})
591 raise BaseException("cannot read wallet file")
593 self.update_tx_history()
595 if self.seed_version != SEED_VERSION:
596 raise BaseException(upgrade_msg)
598 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
600 self.file_exists = True
601 #self.interface = interface.start_interface(self)
604 def get_new_address(self):
606 for addr in self.addresses[-self.gap_limit:]:
607 if not self.history.get(addr):
609 if n < self.gap_limit:
610 new_address = self.create_new_address(False)
611 self.history[new_address] = [] #get from server
612 return True, new_address
614 return False, "The last %d addresses in your list have never been used. You should use them first, or increase the allowed gap size in your preferences. "%self.gap_limit
616 def get_addr_balance(self, addr):
617 if self.is_mine(addr):
618 h = self.history.get(addr)
620 h = self.interface.retrieve_history(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()
648 h = self.history.get(addr)
649 if h is None: continue
651 if item.get('raw_scriptPubKey'):
652 coins.append( (addr,item))
654 coins = sorted( coins, key = lambda x: x[1]['nTime'] )
658 v = item.get('value')
660 inputs.append((addr, v, item['tx_hash'], item['pos'], item['raw_scriptPubKey'], None, None) )
661 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
662 if total >= amount + fee: break
664 #print "not enough funds: %d %d"%(total, fee)
666 return inputs, total, fee
668 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
669 outputs = [ (to_addr, amount) ]
670 change_amount = total - ( amount + fee )
671 if change_amount != 0:
672 # normally, the update thread should ensure that the last change address is unused
674 change_addr = self.change_addresses[-1]
675 outputs.append( ( change_addr, change_amount) )
678 def sign_inputs( self, inputs, outputs, password ):
680 for i in range(len(inputs)):
681 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
682 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
683 public_key = private_key.get_verifying_key()
684 pubkey = public_key.to_string()
685 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
686 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
687 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
688 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
691 def pw_encode(self, s, password):
693 secret = Hash(password)
694 return EncodeAES(secret, s)
698 def pw_decode(self, s, password):
699 if password is not None:
700 secret = Hash(password)
701 d = DecodeAES(secret, s)
706 raise BaseException("Invalid password")
711 def receive_status_callback(self, addr, status):
712 if self.status.get(addr) != status:
713 #print "updating status for", addr, repr(self.status.get(addr)), repr(status)
714 self.status[addr] = status
715 self.interface.get_history(addr)
717 def receive_history_callback(self, addr, data):
718 #print "updating history for", addr
719 self.history[addr] = data
720 self.update_tx_history()
723 def get_tx_history(self):
724 lines = self.tx_history.values()
725 lines = sorted(lines, key=operator.itemgetter("nTime"))
728 def update_tx_history(self):
730 for addr in self.all_addresses():
731 h = self.history.get(addr)
732 if h is None: continue
734 tx_hash = tx['tx_hash']
735 line = self.tx_history.get(tx_hash)
737 self.tx_history[tx_hash] = copy.copy(tx)
738 line = self.tx_history.get(tx_hash)
740 line['value'] += tx['value']
741 if line['height'] == 0:
743 self.update_tx_labels()
745 def update_tx_labels(self):
746 for tx in self.tx_history.values():
749 for o_addr in tx['outputs']:
750 if not self.is_change(o_addr):
751 dest_label = self.labels.get(o_addr)
753 default_label = 'to: ' + dest_label
755 default_label = 'to: ' + o_addr
757 for o_addr in tx['outputs']:
758 if self.is_mine(o_addr) and not self.is_change(o_addr):
759 dest_label = self.labels.get(o_addr)
761 default_label = 'at: ' + dest_label
763 default_label = 'at: ' + o_addr
764 tx['default_label'] = default_label
766 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
767 if not self.is_valid(to_address):
768 raise BaseException("Invalid address")
769 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
771 raise BaseException("Not enough funds")
772 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
773 s_inputs = self.sign_inputs( inputs, outputs, password )
775 tx = filter( raw_tx( s_inputs, outputs ) )
776 if to_address not in self.addressbook:
777 self.addressbook.append(to_address)
779 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
780 self.labels[tx_hash] = label
784 def sendtx(self, tx):
785 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
786 out = self.interface.send_tx(tx)
788 return False, "error: " + out
790 self.receipts[tx_hash] = self.receipt
795 def read_alias(self, alias):
796 # this might not be the right place for this function.
799 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
800 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
802 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
804 url = 'http://' + alias + '/bitcoin.id'
808 lines = urllib.urlopen(url).readlines()
813 line = lines[0].strip().split(':')
816 target = signing_addr = line[0]
818 target, auth_name, signing_addr, signature = line
819 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
821 self.verify_message(signing_addr, signature, msg)
823 # other lines are signed updates
824 for line in lines[1:]:
826 if not line: continue
827 line = line.split(':')
830 target, signature = line
831 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
833 if not self.is_valid(target):
834 raise BaseException("Invalid bitcoin address")
836 return target, signing_addr, auth_name
838 def update_password(self, seed, new_password):
839 self.use_encryption = (new_password != '')
840 self.seed = self.pw_encode( seed, new_password)
841 for k in self.imported_keys.keys():
842 a = self.imported_keys[k]
843 b = self.pw_decode(a, password)
844 c = self.pw_encode(b, new_password)
845 self.imported_keys[k] = c
848 def get_alias(self, alias, interactive = False, show_message=None, question = None):
850 target, signing_address, auth_name = self.read_alias(alias)
851 except BaseException, e:
852 # raise exception if verify fails (verify the chain)
854 show_message("Alias error: " + e.message)
857 print target, signing_address, auth_name
859 if auth_name is None:
860 a = self.aliases.get(alias)
862 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)
863 if interactive and question( msg ):
864 self.aliases[alias] = (signing_address, target)
868 if signing_address != a[0]:
869 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
870 if interactive and question( msg ):
871 self.aliases[alias] = (signing_address, target)
875 if signing_address not in self.authorities.keys():
876 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)
877 if interactive and question( msg ):
878 self.authorities[signing_address] = auth_name
883 self.aliases[alias] = (signing_address, target)
888 def parse_url(self, url, show_message, question):
889 o = url[8:].split('?')
892 params = o[1].split('&')
896 amount = label = message = signature = identity = ''
900 if k == 'amount': amount = uv
901 elif k == 'message': message = uv
902 elif k == 'label': label = uv
903 elif k == 'signature':
904 identity, signature = uv.split(':')
905 url = url.replace('&%s=%s'%(k,v),'')
910 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
911 signing_address = self.get_alias(identity, True, show_message, question)
912 elif self.is_valid(identity):
913 signing_address = identity
915 signing_address = None
916 if not signing_address:
919 self.verify_message(signing_address, signature, url )
920 self.receipt = (signing_address, signature, url)
922 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
923 address = amount = label = identity = message = ''
925 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
926 payto_address = self.get_alias(address, True, show_message, question)
928 address = address + ' <' + payto_address + '>'
930 return address, amount, label, message, signature, identity, url
934 def handle_response(self, r):
942 if method == 'server.banner':
944 self.was_updated = True
946 elif method == 'session.poll':
948 blocks, changed_addresses = result
949 if blocks == -1: raise BaseException("session not found")
950 self.blocks = int(blocks)
951 if changed_addresses:
952 self.was_updated = True
953 for addr, status in changed_addresses.items():
954 self.receive_status_callback(addr, status)
956 elif method == 'server.peers':
957 self.interface.servers = map( lambda x:x[1], result )
959 elif method == 'address.subscribe':
961 self.receive_status_callback(addr, result)
963 elif method == 'address.get_history':
965 self.receive_history_callback(addr, result)
966 self.was_updated = True
968 elif method == 'transaction.broadcast':
969 self.tx_result = result
972 elif method == 'numblocks.subscribe':
975 elif method == 'client.version':
979 print "unknown message:", method, params, result
983 self.up_to_date_event.wait()
987 while self.interface.is_connected:
988 # the interface should use an input queue for requests so that we don't care about synchronous
989 is_new = self.synchronize() # in synchronous mode, this puts new responses in the queue
990 if self.interface.is_up_to_date() and not is_new:
991 self.up_to_date = True
992 self.up_to_date_event.set()
994 self.up_to_date = False
996 response = self.interface.responses.get()
997 self.handle_response(response)
999 def start_interface(self):
1000 from interface import NativeInterface, AsynchronousInterface, HttpInterface, DEFAULT_SERVERS
1004 self.host = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
1006 if self.port == 50000:
1007 InterfaceClass = NativeInterface
1008 elif self.port == 50001:
1009 InterfaceClass = AsynchronousInterface
1010 elif self.port in [80, 81, 8080, 8081]:
1011 InterfaceClass = HttpInterface
1013 print "unknown port number: %d. using native protocol."%self.port
1014 InterfaceClass = NativeInterface
1016 self.interface = InterfaceClass(self.host, self.port)
1017 addresses = self.all_addresses()
1018 version = self.electrum_version
1019 self.interface.start_session(addresses, version)
1020 print "Starting new session: %s:%d"%(self.host,self.port)