separate start and start_session
[electrum-nvc.git] / client / wallet.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19
20 import sys, base64, os, re, hashlib, copy, operator, ast, threading, random
21
22 try:
23     import ecdsa  
24     from ecdsa.util import string_to_number, number_to_string
25 except:
26     print "python-ecdsa does not seem to be installed. Try 'sudo easy_install ecdsa'"
27     sys.exit(1)
28
29 try:
30     import aes
31 except:
32     print "AES does not seem to be installed. Try 'sudo easy_install slowaes'"
33     sys.exit(1)
34
35
36 ############ functions from pywallet ##################### 
37
38 addrtype = 0
39
40 def hash_160(public_key):
41     md = hashlib.new('ripemd160')
42     md.update(hashlib.sha256(public_key).digest())
43     return md.digest()
44
45 def public_key_to_bc_address(public_key):
46     h160 = hash_160(public_key)
47     return hash_160_to_bc_address(h160)
48
49 def hash_160_to_bc_address(h160):
50     vh160 = chr(addrtype) + h160
51     h = Hash(vh160)
52     addr = vh160 + h[0:4]
53     return b58encode(addr)
54
55 def bc_address_to_hash_160(addr):
56     bytes = b58decode(addr, 25)
57     return bytes[1:21]
58
59 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
60 __b58base = len(__b58chars)
61
62 def b58encode(v):
63     """ encode v, which is a string of bytes, to base58.                
64     """
65
66     long_value = 0L
67     for (i, c) in enumerate(v[::-1]):
68         long_value += (256**i) * ord(c)
69
70     result = ''
71     while long_value >= __b58base:
72         div, mod = divmod(long_value, __b58base)
73         result = __b58chars[mod] + result
74         long_value = div
75     result = __b58chars[long_value] + result
76
77     # Bitcoin does a little leading-zero-compression:
78     # leading 0-bytes in the input become leading-1s
79     nPad = 0
80     for c in v:
81         if c == '\0': nPad += 1
82         else: break
83
84     return (__b58chars[0]*nPad) + result
85
86 def b58decode(v, length):
87     """ decode v into a string of len bytes
88     """
89     long_value = 0L
90     for (i, c) in enumerate(v[::-1]):
91         long_value += __b58chars.find(c) * (__b58base**i)
92
93     result = ''
94     while long_value >= 256:
95         div, mod = divmod(long_value, 256)
96         result = chr(mod) + result
97         long_value = div
98     result = chr(long_value) + result
99
100     nPad = 0
101     for c in v:
102         if c == __b58chars[0]: nPad += 1
103         else: break
104
105     result = chr(0)*nPad + result
106     if length is not None and len(result) != length:
107         return None
108
109     return result
110
111
112 def Hash(data):
113     return hashlib.sha256(hashlib.sha256(data).digest()).digest()
114
115 def EncodeBase58Check(vchIn):
116     hash = Hash(vchIn)
117     return b58encode(vchIn + hash[0:4])
118
119 def DecodeBase58Check(psz):
120     vchRet = b58decode(psz, None)
121     key = vchRet[0:-4]
122     csum = vchRet[-4:]
123     hash = Hash(key)
124     cs32 = hash[0:4]
125     if cs32 != csum:
126         return None
127     else:
128         return key
129
130 def PrivKeyToSecret(privkey):
131     return privkey[9:9+32]
132
133 def SecretToASecret(secret):
134     vchIn = chr(addrtype+128) + secret
135     return EncodeBase58Check(vchIn)
136
137 def ASecretToSecret(key):
138     vch = DecodeBase58Check(key)
139     if vch and vch[0] == chr(addrtype+128):
140         return vch[1:]
141     else:
142         return False
143
144 ########### end pywallet functions #######################
145
146 # URL decode
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)
149
150
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')
155
156
157 # AES
158 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
159 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
160
161
162
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 ) 
174
175
176 def filter(s): 
177     out = re.sub('( [^\n]*|)\n','',s)
178     out = out.replace(' ','')
179     out = out.replace('\n','')
180     return out
181
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'
189         if for_sig is None:
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'
196         elif for_sig==i:
197             script = p_script                                +  '     scriptsig \n'
198         else:
199             script=''
200         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
201         s += script
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
215     return s
216
217
218
219
220 def format_satoshis(x, is_diff=False):
221     from decimal import Decimal
222     s = str( Decimal(x) /100000000 )
223     if is_diff and x>0:
224         s = "+" + s
225     if not '.' in s: s += '.'
226     p = s.find('.')
227     s += " "*( 9 - ( len(s) - p ))
228     s = " "*( 5 - ( p )) + s
229     return s
230
231
232 from version import ELECTRUM_VERSION, SEED_VERSION
233 from interface import NativeInterface, AsynchronousInterface, HttpInterface, DEFAULT_SERVERS
234
235
236 DEFAULT_PORT = 50000
237
238
239 class Wallet:
240     def __init__(self):
241
242         self.electrum_version = ELECTRUM_VERSION
243         self.seed_version = SEED_VERSION
244
245         self.gap_limit = 5           # configuration
246         self.fee = 100000
247         self.master_public_key = ''
248
249         # saved fields
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
255         self.history = {}
256         self.labels = {}             # labels for addresses and transactions
257         self.aliases = {}            # aliases for addresses
258         self.authorities = {}        # trusted addresses
259         
260         self.receipts = {}           # signed URIs
261         self.receipt = None          # next receipt
262         self.addressbook = []        # outgoing addresses, for payments
263
264         self.host = random.choice( DEFAULT_SERVERS )         # random choice when the wallet is created
265         self.port = DEFAULT_PORT
266
267         # not saved
268         self.tx_history = {}
269
270         self.imported_keys = {}
271         self.remote_url = None
272
273         self.was_updated = False 
274         self.blocks = 0 
275         self.banner = ''
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()
280
281
282     def set_server(self, host, port):
283         if host!= self.host or port!=self.port:
284             self.host = host
285             self.port = port
286             self.interface.is_connected = False  # this exits the polling loop
287
288     def set_path(self, wallet_path):
289
290         if wallet_path is not None:
291             self.path = wallet_path
292         else:
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' )
300             else:
301                 raise BaseException("No home directory found in environment variables.")
302
303             if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
304             self.path = os.path.join( wallet_dir, 'electrum.dat' )
305
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 )
314         # sanity check
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 )
318         return True
319
320     def new_seed(self, password):
321         seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
322         self.init_mpk(seed)
323         # encrypt
324         self.seed = self.pw_encode( seed, password )
325
326
327     def init_mpk(self,seed):
328         # public key
329         curve = SECP256k1
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()
333
334     def all_addresses(self):
335         return self.addresses + self.change_addresses + self.imported_keys.keys()
336
337     def is_mine(self, address):
338         return address in self.all_addresses()
339
340     def is_change(self, address):
341         return address in self.change_addresses
342
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
346         try:
347             h = bc_address_to_hash_160(addr)
348         except:
349             return False
350         return addr == hash_160_to_bc_address(h)
351
352     def stretch_key(self,seed):
353         oldseed = seed
354         for i in range(100000):
355             seed = hashlib.sha256(seed + oldseed).digest()
356         return string_to_number( seed )
357
358     def get_sequence(self,n,for_change):
359         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
360
361     def get_private_key(self, address, password):
362         """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
363         order = generator_secp256k1.order()
364         
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)
369         else:
370             if address in self.addresses:
371                 n = self.addresses.index(address)
372                 for_change = False
373             elif address in self.change_addresses:
374                 n = self.change_addresses.index(address)
375                 for_change = True
376             else:
377                 raise BaseException("unknown address")
378             try:
379                 seed = self.pw_decode( self.seed, password)
380             except:
381                 raise BaseException("Invalid password")
382             secexp = self.stretch_key(seed)
383             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
384
385         pk = number_to_string(secexp,order)
386         return pk
387
388     def msg_magic(self, message):
389         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
390
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)
396         for i in range(4):
397             sig = base64.b64encode( chr(27+i) + signature )
398             try:
399                 self.verify_message( address, sig, message)
400                 return sig
401             except:
402                 continue
403         else:
404             raise BaseException("error: cannot sign message")
405         
406             
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
410         import msqr
411         curve = curve_secp256k1
412         G = generator_secp256k1
413         order = G.order()
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
419         # 1.1
420         x = r + (recid/2) * order
421         # 1.3
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)
430         minus_e = -e % order
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() )
439         # print addr
440         if address != addr:
441             print "bad signature"
442             raise BaseException("Bad signature")
443     
444
445     def create_new_address(self, for_change):
446         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
447         curve = SECP256k1
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() )
454         if for_change:
455             self.change_addresses.append(address)
456         else:
457             self.addresses.append(address)
458
459         self.history[address] = []
460         self.status[address] = None
461         print address
462         return address
463
464
465
466     def synchronize(self):
467         if not self.master_public_key:
468             return []
469
470         new_addresses = []
471         while True:
472             if self.change_addresses == []:
473                 new_addresses.append( self.create_new_address(True) )
474                 continue
475             a = self.change_addresses[-1]
476             if self.history.get(a):
477                 new_addresses.append( self.create_new_address(True) )
478             else:
479                 break
480
481         n = self.gap_limit
482         while True:
483             if len(self.addresses) < n:
484                 new_addresses.append( self.create_new_address(False) )
485                 continue
486             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
487                 break
488             else:
489                 new_addresses.append( self.create_new_address(False) )
490
491         if self.remote_url:
492             num = self.get_remote_number()
493             while len(self.addresses)<num:
494                 new_addresses.append( self.create_new_address(False) )
495
496         return new_addresses
497
498
499     def get_remote_number(self):
500         import jsonrpclib
501         server = jsonrpclib.Server(self.remote_url)
502         out = server.getnum()
503         return out
504
505     def get_remote_mpk(self):
506         import jsonrpclib
507         server = jsonrpclib.Server(self.remote_url)
508         out = server.getkey()
509         return out
510
511     def is_found(self):
512         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
513
514     def fill_addressbook(self):
515         for tx in self.tx_history.values():
516             if tx['value']<0:
517                 for i in tx['outputs']:
518                     if not self.is_mine(i) and i not in self.addressbook:
519                         self.addressbook.append(i)
520         # redo labels
521         self.update_tx_labels()
522
523
524     def save(self):
525         s = {
526             'seed_version':self.seed_version,
527             'use_encryption':self.use_encryption,
528             'master_public_key': self.master_public_key.encode('hex'),
529             'fee':self.fee,
530             'host':self.host,
531             'port':self.port,
532             'seed':self.seed,
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,
543             }
544         f = open(self.path,"w")
545         f.write( repr(s) )
546         f.close()
547
548     def read(self):
549         import interface
550
551         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
552         self.file_exists = False
553         try:
554             f = open(self.path,"r")
555             data = f.read()
556             f.close()
557         except:
558             return
559         try:
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',{})
579         except:
580             raise BaseException("cannot read wallet file")
581
582         self.update_tx_history()
583
584         if self.seed_version != SEED_VERSION:
585             raise BaseException(upgrade_msg)
586
587         if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
588
589         self.file_exists = True
590         #self.interface = interface.start_interface(self)
591
592         
593
594     def get_addr_balance(self, addr):
595         if self.is_mine(addr):
596             h = self.history.get(addr)
597         else:
598             h = self.interface.retrieve_history(addr)
599         if not h: return 0,0
600         c = u = 0
601         for item in h:
602             v = item['value']
603             if item['height']:
604                 c += v
605             else:
606                 u += v
607         return c, u
608
609     def get_balance(self):
610         conf = unconf = 0
611         for addr in self.all_addresses(): 
612             c, u = self.get_addr_balance(addr)
613             conf += c
614             unconf += u
615         return conf, unconf
616
617
618     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
619         """ todo: minimize tx size """
620         total = 0
621         fee = self.fee if fixed_fee is None else fixed_fee
622
623         coins = []
624         domain = [from_addr] if from_addr else self.all_addresses()
625         for addr in domain:
626             h = self.history.get(addr)
627             if h is None: continue
628             for item in h:
629                 if item.get('raw_scriptPubKey'):
630                     coins.append( (addr,item))
631
632         coins = sorted( coins, key = lambda x: x[1]['nTime'] )
633         inputs = []
634         for c in coins: 
635             addr, item = c
636             v = item.get('value')
637             total += v
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
641         else:
642             #print "not enough funds: %d %d"%(total, fee)
643             inputs = []
644         return inputs, total, fee
645
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
651             if not change_addr:
652                 change_addr = self.change_addresses[-1]
653             outputs.append( ( change_addr,  change_amount) )
654         return outputs
655
656     def sign_inputs( self, inputs, outputs, password ):
657         s_inputs = []
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) )
667         return s_inputs
668
669     def pw_encode(self, s, password):
670         if password:
671             secret = Hash(password)
672             return EncodeAES(secret, s)
673         else:
674             return s
675
676     def pw_decode(self, s, password):
677         if password is not None:
678             secret = Hash(password)
679             d = DecodeAES(secret, s)
680             if s == self.seed:
681                 try:
682                     d.decode('hex')
683                 except:
684                     raise BaseException("Invalid password")
685             return d
686         else:
687             return s
688
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)
694
695     def receive_history_callback(self, addr, data):
696         #print "updating history for", addr
697         self.history[addr] = data
698         self.update_tx_history()
699         self.save()
700
701     def get_tx_history(self):
702         lines = self.tx_history.values()
703         lines = sorted(lines, key=operator.itemgetter("nTime"))
704         return lines
705
706     def update_tx_history(self):
707         self.tx_history= {}
708         for addr in self.all_addresses():
709             h = self.history.get(addr)
710             if h is None: continue
711             for tx in h:
712                 tx_hash = tx['tx_hash']
713                 line = self.tx_history.get(tx_hash)
714                 if not line:
715                     self.tx_history[tx_hash] = copy.copy(tx)
716                     line = self.tx_history.get(tx_hash)
717                 else:
718                     line['value'] += tx['value']
719                 if line['height'] == 0:
720                     line['nTime'] = 1e12
721         self.update_tx_labels()
722
723     def update_tx_labels(self):
724         for tx in self.tx_history.values():
725             default_label = ''
726             if tx['value']<0:
727                 for o_addr in tx['outputs']:
728                     if not self.is_change(o_addr):
729                         dest_label = self.labels.get(o_addr)
730                         if dest_label:
731                             default_label = 'to: ' + dest_label
732                         else:
733                             default_label = 'to: ' + o_addr
734             else:
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)
738                         if dest_label:
739                             default_label = 'at: ' + dest_label
740                         else:
741                             default_label = 'at: ' + o_addr
742             tx['default_label'] = default_label
743
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 )
748         if not inputs:
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 )
752
753         tx = filter( raw_tx( s_inputs, outputs ) )
754         if to_address not in self.addressbook:
755             self.addressbook.append(to_address)
756         if label: 
757             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
758             self.labels[tx_hash] = label
759
760         return tx
761
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])])
766         self.tx_event.wait()
767         out = self.tx_result 
768         if out != tx_hash:
769             return False, "error: " + out
770         if self.receipt:
771             self.receipts[tx_hash] = self.receipt
772             self.receipt = None
773         return True, out
774
775
776     def read_alias(self, alias):
777         # this might not be the right place for this function.
778         import urllib
779
780         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
781         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
782         if m1:
783             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
784         elif m2:
785             url = 'http://' + alias + '/bitcoin.id'
786         else:
787             return ''
788         try:
789             lines = urllib.urlopen(url).readlines()
790         except:
791             return ''
792
793         # line 0
794         line = lines[0].strip().split(':')
795         if len(line) == 1:
796             auth_name = None
797             target = signing_addr = line[0]
798         else:
799             target, auth_name, signing_addr, signature = line
800             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
801             print msg, signature
802             self.verify_message(signing_addr, signature, msg)
803         
804         # other lines are signed updates
805         for line in lines[1:]:
806             line = line.strip()
807             if not line: continue
808             line = line.split(':')
809             previous = target
810             print repr(line)
811             target, signature = line
812             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
813
814         if not self.is_valid(target):
815             raise BaseException("Invalid bitcoin address")
816
817         return target, signing_addr, auth_name
818
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
827         self.save()
828
829     def get_alias(self, alias, interactive = False, show_message=None, question = None):
830         try:
831             target, signing_address, auth_name = self.read_alias(alias)
832         except BaseException, e:
833             # raise exception if verify fails (verify the chain)
834             if interactive:
835                 show_message("Alias error: " + e.message)
836             return
837
838         print target, signing_address, auth_name
839
840         if auth_name is None:
841             a = self.aliases.get(alias)
842             if not a:
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)
846                 else:
847                     target = None
848             else:
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)
853                     else:
854                         target = None
855         else:
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
860                 else:
861                     target = None
862
863         if target:
864             self.aliases[alias] = (signing_address, target)
865             
866         return target
867
868
869     def parse_url(self, url, show_message, question):
870         o = url[8:].split('?')
871         address = o[0]
872         if len(o)>1:
873             params = o[1].split('&')
874         else:
875             params = []
876
877         amount = label = message = signature = identity = ''
878         for p in params:
879             k,v = p.split('=')
880             uv = urldecode(v)
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),'')
887             else: 
888                 print k,v
889
890         if signature:
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
895             else:
896                 signing_address = None
897             if not signing_address:
898                 return
899             try:
900                 self.verify_message(signing_address, signature, url )
901                 self.receipt = (signing_address, signature, url)
902             except:
903                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
904                 address = amount = label = identity = message = ''
905
906         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
907             payto_address = self.get_alias(address, True, show_message, question)
908             if payto_address:
909                 address = address + ' <' + payto_address + '>'
910
911         return address, amount, label, message, signature, identity, url
912
913
914
915     def handle_response(self, r):
916         if r is None:
917             return
918
919         method = r['method']
920         params = r['params']
921         result = r['result']
922
923         if method == 'server.banner':
924             self.banner = result
925             self.was_updated = True
926
927         elif method == 'session.poll':
928             # native 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)
936
937         elif method == 'server.peers':
938             self.interface.servers = map( lambda x:x[1], result )
939
940         elif method == 'address.subscribe':
941             addr = params[-1]
942             self.receive_status_callback(addr, result)
943                             
944         elif method == 'address.get_history':
945             addr = params[0]
946             self.receive_history_callback(addr, result)
947             self.was_updated = True
948
949         elif method == 'transaction.broadcast':
950             self.tx_result = result
951             self.tx_event.set()
952
953         elif method == 'numblocks.subscribe':
954             self.blocks = result
955
956         elif method == 'client.version':
957             pass
958
959         else:
960             print "unknown message:", method, params, result
961
962
963     def update(self):
964         self.up_to_date_event.wait()
965
966
967     def run(self):
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()
974             else:
975                 self.up_to_date = False
976
977             response = self.interface.responses.get(True,100000000000) # workaround so that it can be keyboard interrupted
978             self.handle_response(response)
979
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
987         else:
988             print "unknown port number: %d. using native protocol."%self.port
989             InterfaceClass = NativeInterface
990
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)
995
996