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 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
233 from interface import NativeInterface, AsynchronousInterface, HttpInterface, DEFAULT_SERVERS
242 self.electrum_version = ELECTRUM_VERSION
243 self.seed_version = SEED_VERSION
245 self.gap_limit = 5 # configuration
247 self.master_public_key = ''
250 self.use_encryption = False
251 self.addresses = [] # receiving addresses visible for user
252 self.change_addresses = [] # addresses used as change
253 self.seed = '' # encrypted
254 self.status = {} # current status of addresses
256 self.labels = {} # labels for addresses and transactions
257 self.aliases = {} # aliases for addresses
258 self.authorities = {} # trusted addresses
260 self.receipts = {} # signed URIs
261 self.receipt = None # next receipt
262 self.addressbook = [] # outgoing addresses, for payments
264 self.host = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
265 self.port = DEFAULT_PORT
270 self.imported_keys = {}
271 self.remote_url = None
273 self.was_updated = False
276 self.up_to_date_event = threading.Event()
277 self.up_to_date_event.clear()
278 self.interface_lock = threading.Lock()
279 self.tx_event = threading.Event()
282 def set_server(self, host, port):
283 if host!= self.host or port!=self.port:
286 self.interface.is_connected = False # this exits the polling loop
288 def set_path(self, wallet_path):
290 if wallet_path is not None:
291 self.path = wallet_path
293 # backward compatibility: look for wallet file in the default data directory
294 if "HOME" in os.environ:
295 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
296 elif "LOCALAPPDATA" in os.environ:
297 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
298 elif "APPDATA" in os.environ:
299 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
301 raise BaseException("No home directory found in environment variables.")
303 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
304 self.path = os.path.join( wallet_dir, 'electrum.dat' )
306 def import_key(self, keypair, password):
307 address, key = keypair.split(':')
308 if not self.is_valid(address): return False
309 if address in self.all_addresses(): return False
310 b = ASecretToSecret( key )
311 if not b: return False
312 secexp = int( b.encode('hex'), 16)
313 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
315 public_key = private_key.get_verifying_key()
316 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
317 self.imported_keys[address] = self.pw_encode( key, password )
320 def new_seed(self, password):
321 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
324 self.seed = self.pw_encode( seed, password )
327 def init_mpk(self,seed):
330 secexp = self.stretch_key(seed)
331 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
332 self.master_public_key = master_private_key.get_verifying_key().to_string()
334 def all_addresses(self):
335 return self.addresses + self.change_addresses + self.imported_keys.keys()
337 def is_mine(self, address):
338 return address in self.all_addresses()
340 def is_change(self, address):
341 return address in self.change_addresses
343 def is_valid(self,addr):
344 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
345 if not ADDRESS_RE.match(addr): return False
347 h = bc_address_to_hash_160(addr)
350 return addr == hash_160_to_bc_address(h)
352 def stretch_key(self,seed):
354 for i in range(100000):
355 seed = hashlib.sha256(seed + oldseed).digest()
356 return string_to_number( seed )
358 def get_sequence(self,n,for_change):
359 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
361 def get_private_key(self, address, password):
362 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
363 order = generator_secp256k1.order()
365 if address in self.imported_keys.keys():
366 b = self.pw_decode( self.imported_keys[address], password )
367 b = ASecretToSecret( b )
368 secexp = int( b.encode('hex'), 16)
370 if address in self.addresses:
371 n = self.addresses.index(address)
373 elif address in self.change_addresses:
374 n = self.change_addresses.index(address)
377 raise BaseException("unknown address")
379 seed = self.pw_decode( self.seed, password)
381 raise BaseException("Invalid password")
382 secexp = self.stretch_key(seed)
383 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
385 pk = number_to_string(secexp,order)
388 def msg_magic(self, message):
389 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
391 def sign_message(self, address, message, password):
392 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
393 public_key = private_key.get_verifying_key()
394 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
395 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
397 sig = base64.b64encode( chr(27+i) + signature )
399 self.verify_message( address, sig, message)
404 raise BaseException("error: cannot sign message")
407 def verify_message(self, address, signature, message):
408 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
409 from ecdsa import numbertheory, ellipticcurve, util
411 curve = curve_secp256k1
412 G = generator_secp256k1
414 # extract r,s from signature
415 sig = base64.b64decode(signature)
416 if len(sig) != 65: raise BaseException("Wrong encoding")
417 r,s = util.sigdecode_string(sig[1:], order)
418 recid = ord(sig[0]) - 27
420 x = r + (recid/2) * order
422 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
423 beta = msqr.modular_sqrt(alpha, curve.p())
424 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
425 # 1.4 the constructor checks that nR is at infinity
426 R = ellipticcurve.Point(curve, x, y, order)
427 # 1.5 compute e from message:
428 h = Hash( self.msg_magic( message ) )
429 e = string_to_number(h)
431 # 1.6 compute Q = r^-1 (sR - eG)
432 inv_r = numbertheory.inverse_mod(r,order)
433 Q = inv_r * ( s * R + minus_e * G )
434 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
435 # check that Q is the public key
436 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
437 # check that we get the original signing address
438 addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
441 print "bad signature"
442 raise BaseException("Bad signature")
445 def create_new_address(self, for_change):
446 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
448 n = len(self.change_addresses) if for_change else len(self.addresses)
449 z = self.get_sequence(n,for_change)
450 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
451 pubkey_point = master_public_key.pubkey.point + z*curve.generator
452 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
453 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
455 self.change_addresses.append(address)
457 self.addresses.append(address)
459 self.history[address] = []
460 self.status[address] = None
466 def synchronize(self):
467 if not self.master_public_key:
472 if self.change_addresses == []:
473 new_addresses.append( self.create_new_address(True) )
475 a = self.change_addresses[-1]
476 if self.history.get(a):
477 new_addresses.append( self.create_new_address(True) )
483 if len(self.addresses) < n:
484 new_addresses.append( self.create_new_address(False) )
486 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
489 new_addresses.append( self.create_new_address(False) )
492 num = self.get_remote_number()
493 while len(self.addresses)<num:
494 new_addresses.append( self.create_new_address(False) )
499 def get_remote_number(self):
501 server = jsonrpclib.Server(self.remote_url)
502 out = server.getnum()
505 def get_remote_mpk(self):
507 server = jsonrpclib.Server(self.remote_url)
508 out = server.getkey()
512 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
514 def fill_addressbook(self):
515 for tx in self.tx_history.values():
517 for i in tx['outputs']:
518 if not self.is_mine(i) and i not in self.addressbook:
519 self.addressbook.append(i)
521 self.update_tx_labels()
526 'seed_version':self.seed_version,
527 'use_encryption':self.use_encryption,
528 'master_public_key': self.master_public_key.encode('hex'),
533 'addresses':self.addresses,
534 'change_addresses':self.change_addresses,
535 'status':self.status,
536 'history':self.history,
537 'labels':self.labels,
538 'contacts':self.addressbook,
539 'imported_keys':self.imported_keys,
540 'aliases':self.aliases,
541 'authorities':self.authorities,
542 'receipts':self.receipts,
544 f = open(self.path,"w")
551 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
552 self.file_exists = False
554 f = open(self.path,"r")
560 d = ast.literal_eval( data )
561 self.seed_version = d.get('seed_version')
562 self.master_public_key = d.get('master_public_key').decode('hex')
563 self.use_encryption = d.get('use_encryption')
564 self.fee = int( d.get('fee') )
565 self.seed = d.get('seed')
566 self.host = d.get('host')
567 self.port = d.get('port')
568 blocks = d.get('blocks')
569 self.addresses = d.get('addresses')
570 self.change_addresses = d.get('change_addresses')
571 self.status = d.get('status')
572 self.history = d.get('history')
573 self.labels = d.get('labels')
574 self.addressbook = d.get('contacts')
575 self.imported_keys = d.get('imported_keys',{})
576 self.aliases = d.get('aliases',{})
577 self.authorities = d.get('authorities',{})
578 self.receipts = d.get('receipts',{})
580 raise BaseException("cannot read wallet file")
582 self.update_tx_history()
584 if self.seed_version != SEED_VERSION:
585 raise BaseException(upgrade_msg)
587 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
589 self.file_exists = True
590 #self.interface = interface.start_interface(self)
594 def get_addr_balance(self, addr):
595 if self.is_mine(addr):
596 h = self.history.get(addr)
598 h = self.interface.retrieve_history(addr)
609 def get_balance(self):
611 for addr in self.all_addresses():
612 c, u = self.get_addr_balance(addr)
618 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
619 """ todo: minimize tx size """
621 fee = self.fee if fixed_fee is None else fixed_fee
624 domain = [from_addr] if from_addr else self.all_addresses()
626 h = self.history.get(addr)
627 if h is None: continue
629 if item.get('raw_scriptPubKey'):
630 coins.append( (addr,item))
632 coins = sorted( coins, key = lambda x: x[1]['nTime'] )
636 v = item.get('value')
638 inputs.append((addr, v, item['tx_hash'], item['pos'], item['raw_scriptPubKey'], None, None) )
639 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
640 if total >= amount + fee: break
642 #print "not enough funds: %d %d"%(total, fee)
644 return inputs, total, fee
646 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
647 outputs = [ (to_addr, amount) ]
648 change_amount = total - ( amount + fee )
649 if change_amount != 0:
650 # normally, the update thread should ensure that the last change address is unused
652 change_addr = self.change_addresses[-1]
653 outputs.append( ( change_addr, change_amount) )
656 def sign_inputs( self, inputs, outputs, password ):
658 for i in range(len(inputs)):
659 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
660 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
661 public_key = private_key.get_verifying_key()
662 pubkey = public_key.to_string()
663 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
664 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
665 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
666 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
669 def pw_encode(self, s, password):
671 secret = Hash(password)
672 return EncodeAES(secret, s)
676 def pw_decode(self, s, password):
677 if password is not None:
678 secret = Hash(password)
679 d = DecodeAES(secret, s)
684 raise BaseException("Invalid password")
689 def receive_status_callback(self, addr, status):
690 if self.status.get(addr) != status:
691 #print "updating status for", addr, repr(self.status.get(addr)), repr(status)
692 self.status[addr] = status
693 self.interface.get_history(addr)
695 def receive_history_callback(self, addr, data):
696 #print "updating history for", addr
697 self.history[addr] = data
698 self.update_tx_history()
701 def get_tx_history(self):
702 lines = self.tx_history.values()
703 lines = sorted(lines, key=operator.itemgetter("nTime"))
706 def update_tx_history(self):
708 for addr in self.all_addresses():
709 h = self.history.get(addr)
710 if h is None: continue
712 tx_hash = tx['tx_hash']
713 line = self.tx_history.get(tx_hash)
715 self.tx_history[tx_hash] = copy.copy(tx)
716 line = self.tx_history.get(tx_hash)
718 line['value'] += tx['value']
719 if line['height'] == 0:
721 self.update_tx_labels()
723 def update_tx_labels(self):
724 for tx in self.tx_history.values():
727 for o_addr in tx['outputs']:
728 if not self.is_change(o_addr):
729 dest_label = self.labels.get(o_addr)
731 default_label = 'to: ' + dest_label
733 default_label = 'to: ' + o_addr
735 for o_addr in tx['outputs']:
736 if self.is_mine(o_addr) and not self.is_change(o_addr):
737 dest_label = self.labels.get(o_addr)
739 default_label = 'at: ' + dest_label
741 default_label = 'at: ' + o_addr
742 tx['default_label'] = default_label
744 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
745 if not self.is_valid(to_address):
746 raise BaseException("Invalid address")
747 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
749 raise BaseException("Not enough funds")
750 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
751 s_inputs = self.sign_inputs( inputs, outputs, password )
753 tx = filter( raw_tx( s_inputs, outputs ) )
754 if to_address not in self.addressbook:
755 self.addressbook.append(to_address)
757 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
758 self.labels[tx_hash] = label
762 def sendtx(self, tx):
763 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
764 self.tx_event.clear()
765 self.interface.send([('transaction.broadcast', [tx])])
769 return False, "error: " + out
771 self.receipts[tx_hash] = self.receipt
776 def read_alias(self, alias):
777 # this might not be the right place for this function.
780 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
781 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
783 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
785 url = 'http://' + alias + '/bitcoin.id'
789 lines = urllib.urlopen(url).readlines()
794 line = lines[0].strip().split(':')
797 target = signing_addr = line[0]
799 target, auth_name, signing_addr, signature = line
800 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
802 self.verify_message(signing_addr, signature, msg)
804 # other lines are signed updates
805 for line in lines[1:]:
807 if not line: continue
808 line = line.split(':')
811 target, signature = line
812 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
814 if not self.is_valid(target):
815 raise BaseException("Invalid bitcoin address")
817 return target, signing_addr, auth_name
819 def update_password(self, seed, new_password):
820 self.use_encryption = (new_password != '')
821 self.seed = self.pw_encode( seed, new_password)
822 for k in self.imported_keys.keys():
823 a = self.imported_keys[k]
824 b = self.pw_decode(a, password)
825 c = self.pw_encode(b, new_password)
826 self.imported_keys[k] = c
829 def get_alias(self, alias, interactive = False, show_message=None, question = None):
831 target, signing_address, auth_name = self.read_alias(alias)
832 except BaseException, e:
833 # raise exception if verify fails (verify the chain)
835 show_message("Alias error: " + e.message)
838 print target, signing_address, auth_name
840 if auth_name is None:
841 a = self.aliases.get(alias)
843 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)
844 if interactive and question( msg ):
845 self.aliases[alias] = (signing_address, target)
849 if signing_address != a[0]:
850 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
851 if interactive and question( msg ):
852 self.aliases[alias] = (signing_address, target)
856 if signing_address not in self.authorities.keys():
857 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)
858 if interactive and question( msg ):
859 self.authorities[signing_address] = auth_name
864 self.aliases[alias] = (signing_address, target)
869 def parse_url(self, url, show_message, question):
870 o = url[8:].split('?')
873 params = o[1].split('&')
877 amount = label = message = signature = identity = ''
881 if k == 'amount': amount = uv
882 elif k == 'message': message = uv
883 elif k == 'label': label = uv
884 elif k == 'signature':
885 identity, signature = uv.split(':')
886 url = url.replace('&%s=%s'%(k,v),'')
891 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
892 signing_address = self.get_alias(identity, True, show_message, question)
893 elif self.is_valid(identity):
894 signing_address = identity
896 signing_address = None
897 if not signing_address:
900 self.verify_message(signing_address, signature, url )
901 self.receipt = (signing_address, signature, url)
903 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
904 address = amount = label = identity = message = ''
906 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
907 payto_address = self.get_alias(address, True, show_message, question)
909 address = address + ' <' + payto_address + '>'
911 return address, amount, label, message, signature, identity, url
915 def handle_response(self, r):
923 if method == 'server.banner':
925 self.was_updated = True
927 elif method == 'session.poll':
929 blocks, changed_addresses = result
930 if blocks == -1: raise BaseException("session not found")
931 self.blocks = int(blocks)
932 if changed_addresses:
933 self.was_updated = True
934 for addr, status in changed_addresses.items():
935 self.receive_status_callback(addr, status)
937 elif method == 'server.peers':
938 self.interface.servers = map( lambda x:x[1], result )
940 elif method == 'address.subscribe':
942 self.receive_status_callback(addr, result)
944 elif method == 'address.get_history':
946 self.receive_history_callback(addr, result)
947 self.was_updated = True
949 elif method == 'transaction.broadcast':
950 self.tx_result = result
953 elif method == 'numblocks.subscribe':
956 elif method == 'client.version':
960 print "unknown message:", method, params, result
964 self.up_to_date_event.wait()
968 while self.interface.is_connected:
969 new_addresses = self.synchronize()
970 self.interface.subscribe(new_addresses)
971 if self.interface.is_up_to_date() and not new_addresses:
972 self.up_to_date = True
973 self.up_to_date_event.set()
975 self.up_to_date = False
977 response = self.interface.responses.get(True,100000000000) # workaround so that it can be keyboard interrupted
978 self.handle_response(response)
980 def start_interface(self):
981 if self.port == 50000:
982 InterfaceClass = NativeInterface
983 elif self.port == 50001:
984 InterfaceClass = AsynchronousInterface
985 elif self.port in [80, 81, 8080, 8081]:
986 InterfaceClass = HttpInterface
988 print "unknown port number: %d. using native protocol."%self.port
989 InterfaceClass = NativeInterface
991 self.interface = InterfaceClass(self.host, self.port)
992 addresses = self.all_addresses()
993 version = self.electrum_version
994 self.interface.start_session(addresses,version)