simplification
[electrum-nvc.git] / 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     try:
42         md = hashlib.new('ripemd160')
43         md.update(hashlib.sha256(public_key).digest())
44         return md.digest()
45     except:
46         import ripemd
47         md = ripemd.new(hashlib.sha256(public_key).digest())
48         return md.digest()
49
50
51 def public_key_to_bc_address(public_key):
52     h160 = hash_160(public_key)
53     return hash_160_to_bc_address(h160)
54
55 def hash_160_to_bc_address(h160):
56     vh160 = chr(addrtype) + h160
57     h = Hash(vh160)
58     addr = vh160 + h[0:4]
59     return b58encode(addr)
60
61 def bc_address_to_hash_160(addr):
62     bytes = b58decode(addr, 25)
63     return bytes[1:21]
64
65 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
66 __b58base = len(__b58chars)
67
68 def b58encode(v):
69     """ encode v, which is a string of bytes, to base58.                
70     """
71
72     long_value = 0L
73     for (i, c) in enumerate(v[::-1]):
74         long_value += (256**i) * ord(c)
75
76     result = ''
77     while long_value >= __b58base:
78         div, mod = divmod(long_value, __b58base)
79         result = __b58chars[mod] + result
80         long_value = div
81     result = __b58chars[long_value] + result
82
83     # Bitcoin does a little leading-zero-compression:
84     # leading 0-bytes in the input become leading-1s
85     nPad = 0
86     for c in v:
87         if c == '\0': nPad += 1
88         else: break
89
90     return (__b58chars[0]*nPad) + result
91
92 def b58decode(v, length):
93     """ decode v into a string of len bytes
94     """
95     long_value = 0L
96     for (i, c) in enumerate(v[::-1]):
97         long_value += __b58chars.find(c) * (__b58base**i)
98
99     result = ''
100     while long_value >= 256:
101         div, mod = divmod(long_value, 256)
102         result = chr(mod) + result
103         long_value = div
104     result = chr(long_value) + result
105
106     nPad = 0
107     for c in v:
108         if c == __b58chars[0]: nPad += 1
109         else: break
110
111     result = chr(0)*nPad + result
112     if length is not None and len(result) != length:
113         return None
114
115     return result
116
117
118 def Hash(data):
119     return hashlib.sha256(hashlib.sha256(data).digest()).digest()
120
121 def EncodeBase58Check(vchIn):
122     hash = Hash(vchIn)
123     return b58encode(vchIn + hash[0:4])
124
125 def DecodeBase58Check(psz):
126     vchRet = b58decode(psz, None)
127     key = vchRet[0:-4]
128     csum = vchRet[-4:]
129     hash = Hash(key)
130     cs32 = hash[0:4]
131     if cs32 != csum:
132         return None
133     else:
134         return key
135
136 def PrivKeyToSecret(privkey):
137     return privkey[9:9+32]
138
139 def SecretToASecret(secret):
140     vchIn = chr(addrtype+128) + secret
141     return EncodeBase58Check(vchIn)
142
143 def ASecretToSecret(key):
144     vch = DecodeBase58Check(key)
145     if vch and vch[0] == chr(addrtype+128):
146         return vch[1:]
147     else:
148         return False
149
150 ########### end pywallet functions #######################
151
152 # URL decode
153 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
154 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
155
156
157 def int_to_hex(i, length=1):
158     s = hex(i)[2:].rstrip('L')
159     s = "0"*(2*length - len(s)) + s
160     return s.decode('hex')[::-1].encode('hex')
161
162
163 # AES
164 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
165 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
166
167
168
169 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
170 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
171 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
172 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
173 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
174 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
175 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
176 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
177 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
178 oid_secp256k1 = (1,3,132,0,10)
179 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
180
181
182 def filter(s): 
183     out = re.sub('( [^\n]*|)\n','',s)
184     out = out.replace(' ','')
185     out = out.replace('\n','')
186     return out
187
188 def raw_tx( inputs, outputs, for_sig = None ):
189     s  = int_to_hex(1,4)                                     +   '     version\n' 
190     s += int_to_hex( len(inputs) )                           +   '     number of inputs\n'
191     for i in range(len(inputs)):
192         _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
193         s += p_hash.decode('hex')[::-1].encode('hex')        +  '     prev hash\n'
194         s += int_to_hex(p_index,4)                           +  '     prev index\n'
195         if for_sig is None:
196             sig = sig + chr(1)                               # hashtype
197             script  = int_to_hex( len(sig))                  +  '     push %d bytes\n'%len(sig)
198             script += sig.encode('hex')                      +  '     sig\n'
199             pubkey = chr(4) + pubkey
200             script += int_to_hex( len(pubkey))               +  '     push %d bytes\n'%len(pubkey)
201             script += pubkey.encode('hex')                   +  '     pubkey\n'
202         elif for_sig==i:
203             script = p_script                                +  '     scriptsig \n'
204         else:
205             script=''
206         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
207         s += script
208         s += "ffffffff"                                      +  '     sequence\n'
209     s += int_to_hex( len(outputs) )                          +  '     number of outputs\n'
210     for output in outputs:
211         addr, amount = output
212         s += int_to_hex( amount, 8)                          +  '     amount: %d\n'%amount 
213         script = '76a9'                                      # op_dup, op_hash_160
214         script += '14'                                       # push 0x14 bytes
215         script += bc_address_to_hash_160(addr).encode('hex')
216         script += '88ac'                                     # op_equalverify, op_checksig
217         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
218         s += script                                          +  '     script \n'
219     s += int_to_hex(0,4)                                     # lock time
220     if for_sig is not None: s += int_to_hex(1, 4)            # hash type
221     return s
222
223
224
225
226 def format_satoshis(x, is_diff=False, num_zeros = 0):
227     from decimal import Decimal
228     s = str( Decimal(x) /100000000 )
229     if is_diff and x>0:
230         s = "+" + s
231     if not '.' in s: s += '.'
232     p = s.find('.')
233     s += "0"*( 1 + num_zeros - ( len(s) - p ))
234     s += " "*( 9 - ( len(s) - p ))
235     s = " "*( 5 - ( p )) + s
236     return s
237
238
239 from version import ELECTRUM_VERSION, SEED_VERSION
240 from interface import DEFAULT_SERVERS
241
242
243
244
245 class Wallet:
246     def __init__(self, gui_callback = lambda: None):
247
248         self.electrum_version = ELECTRUM_VERSION
249         self.seed_version = SEED_VERSION
250         self.gui_callback = gui_callback
251
252         self.gap_limit = 5           # configuration
253         self.fee = 100000
254         self.num_zeros = 0
255         self.master_public_key = ''
256
257         # saved fields
258         self.use_encryption = False
259         self.addresses = []          # receiving addresses visible for user
260         self.change_addresses = []   # addresses used as change
261         self.seed = ''               # encrypted
262         self.history = {}
263         self.labels = {}             # labels for addresses and transactions
264         self.aliases = {}            # aliases for addresses
265         self.authorities = {}        # trusted addresses
266         
267         self.receipts = {}           # signed URIs
268         self.receipt = None          # next receipt
269         self.addressbook = []        # outgoing addresses, for payments
270
271         # not saved
272         self.tx_history = {}
273
274         self.imported_keys = {}
275         self.remote_url = None
276
277         self.was_updated = True
278         self.blocks = -1
279         self.banner = ''
280         self.up_to_date_event = threading.Event()
281         self.up_to_date_event.clear()
282         self.up_to_date = False
283         self.lock = threading.Lock()
284         self.tx_event = threading.Event()
285
286         self.pick_random_server()
287
288
289
290     def pick_random_server(self):
291         self.server = random.choice( DEFAULT_SERVERS )         # random choice when the wallet is created
292
293     def is_up_to_date(self):
294         return self.interface.responses.empty() and not self.interface.unanswered_requests
295
296     def set_server(self, server):
297         # raise an error if the format isnt correct
298         a,b,c = server.split(':')
299         b = int(b)
300         assert c in ['t','h','n']
301         # set the server
302         if server != self.server:
303             self.server = server
304             self.save()
305             self.interface.is_connected = False  # this exits the polling loop
306
307     def set_path(self, wallet_path):
308
309         if wallet_path is not None:
310             self.path = wallet_path
311         else:
312             # backward compatibility: look for wallet file in the default data directory
313             if "HOME" in os.environ:
314                 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
315             elif "LOCALAPPDATA" in os.environ:
316                 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
317             elif "APPDATA" in os.environ:
318                 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
319             else:
320                 raise BaseException("No home directory found in environment variables.")
321
322             if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
323             self.path = os.path.join( wallet_dir, 'electrum.dat' )
324
325     def import_key(self, keypair, password):
326         address, key = keypair.split(':')
327         if not self.is_valid(address): return False
328         if address in self.all_addresses(): return False
329         b = ASecretToSecret( key )
330         if not b: return False
331         secexp = int( b.encode('hex'), 16)
332         private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
333         # sanity check
334         public_key = private_key.get_verifying_key()
335         if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
336         self.imported_keys[address] = self.pw_encode( key, password )
337         return True
338
339     def new_seed(self, password):
340         seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
341         #self.init_mpk(seed)
342         # encrypt
343         self.seed = self.pw_encode( seed, password )
344
345
346     def init_mpk(self,seed):
347         # public key
348         curve = SECP256k1
349         secexp = self.stretch_key(seed)
350         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
351         self.master_public_key = master_private_key.get_verifying_key().to_string()
352
353     def all_addresses(self):
354         return self.addresses + self.change_addresses + self.imported_keys.keys()
355
356     def is_mine(self, address):
357         return address in self.all_addresses()
358
359     def is_change(self, address):
360         return address in self.change_addresses
361
362     def is_valid(self,addr):
363         ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
364         if not ADDRESS_RE.match(addr): return False
365         try:
366             h = bc_address_to_hash_160(addr)
367         except:
368             return False
369         return addr == hash_160_to_bc_address(h)
370
371     def stretch_key(self,seed):
372         oldseed = seed
373         for i in range(100000):
374             seed = hashlib.sha256(seed + oldseed).digest()
375         return string_to_number( seed )
376
377     def get_sequence(self,n,for_change):
378         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
379
380     def get_private_key(self, address, password):
381         """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
382         order = generator_secp256k1.order()
383         
384         if address in self.imported_keys.keys():
385             b = self.pw_decode( self.imported_keys[address], password )
386             b = ASecretToSecret( b )
387             secexp = int( b.encode('hex'), 16)
388         else:
389             if address in self.addresses:
390                 n = self.addresses.index(address)
391                 for_change = False
392             elif address in self.change_addresses:
393                 n = self.change_addresses.index(address)
394                 for_change = True
395             else:
396                 raise BaseException("unknown address")
397             try:
398                 seed = self.pw_decode( self.seed, password)
399             except:
400                 raise BaseException("Invalid password")
401             secexp = self.stretch_key(seed)
402             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
403
404         pk = number_to_string(secexp,order)
405         return pk
406
407     def msg_magic(self, message):
408         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
409
410     def sign_message(self, address, message, password):
411         private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
412         public_key = private_key.get_verifying_key()
413         signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
414         assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
415         for i in range(4):
416             sig = base64.b64encode( chr(27+i) + signature )
417             try:
418                 self.verify_message( address, sig, message)
419                 return sig
420             except:
421                 continue
422         else:
423             raise BaseException("error: cannot sign message")
424         
425             
426     def verify_message(self, address, signature, message):
427         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
428         from ecdsa import numbertheory, ellipticcurve, util
429         import msqr
430         curve = curve_secp256k1
431         G = generator_secp256k1
432         order = G.order()
433         # extract r,s from signature
434         sig = base64.b64decode(signature)
435         if len(sig) != 65: raise BaseException("Wrong encoding")
436         r,s = util.sigdecode_string(sig[1:], order)
437         recid = ord(sig[0]) - 27
438         # 1.1
439         x = r + (recid/2) * order
440         # 1.3
441         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
442         beta = msqr.modular_sqrt(alpha, curve.p())
443         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
444         # 1.4 the constructor checks that nR is at infinity
445         R = ellipticcurve.Point(curve, x, y, order)
446         # 1.5 compute e from message:
447         h = Hash( self.msg_magic( message ) )
448         e = string_to_number(h)
449         minus_e = -e % order
450         # 1.6 compute Q = r^-1 (sR - eG)
451         inv_r = numbertheory.inverse_mod(r,order)
452         Q = inv_r * ( s * R + minus_e * G )
453         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
454         # check that Q is the public key
455         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
456         # check that we get the original signing address
457         addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
458         # print addr
459         if address != addr:
460             print "bad signature"
461             raise BaseException("Bad signature")
462     
463
464     def create_new_address(self, for_change):
465         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
466         curve = SECP256k1
467         n = len(self.change_addresses) if for_change else len(self.addresses)
468         z = self.get_sequence(n,for_change)
469         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
470         pubkey_point = master_public_key.pubkey.point + z*curve.generator
471         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
472         address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
473         if for_change:
474             self.change_addresses.append(address)
475         else:
476             self.addresses.append(address)
477
478         self.history[address] = []
479         print address
480         return address
481
482
483
484     def synchronize(self):
485         if not self.master_public_key:
486             return []
487
488         new_addresses = []
489         while True:
490             if self.change_addresses == []:
491                 new_addresses.append( self.create_new_address(True) )
492                 continue
493             a = self.change_addresses[-1]
494             if self.history.get(a):
495                 new_addresses.append( self.create_new_address(True) )
496             else:
497                 break
498
499         n = self.gap_limit
500         while True:
501             if len(self.addresses) < n:
502                 new_addresses.append( self.create_new_address(False) )
503                 continue
504             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
505                 break
506             else:
507                 new_addresses.append( self.create_new_address(False) )
508
509         if self.remote_url:
510             num = self.get_remote_number()
511             while len(self.addresses)<num:
512                 new_addresses.append( self.create_new_address(False) )
513
514         return new_addresses
515
516
517     def get_remote_number(self):
518         import jsonrpclib
519         server = jsonrpclib.Server(self.remote_url)
520         out = server.getnum()
521         return out
522
523     def get_remote_mpk(self):
524         import jsonrpclib
525         server = jsonrpclib.Server(self.remote_url)
526         out = server.getkey()
527         return out
528
529     def is_found(self):
530         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
531
532     def fill_addressbook(self):
533         for tx in self.tx_history.values():
534             if tx['value']<0:
535                 for i in tx['outputs']:
536                     if not self.is_mine(i) and i not in self.addressbook:
537                         self.addressbook.append(i)
538         # redo labels
539         self.update_tx_labels()
540
541
542     def save(self):
543         s = {
544             'seed_version':self.seed_version,
545             'use_encryption':self.use_encryption,
546             'master_public_key': self.master_public_key.encode('hex'),
547             'fee':self.fee,
548             'server':self.server,
549             'seed':self.seed,
550             'addresses':self.addresses,
551             'change_addresses':self.change_addresses,
552             'history':self.history, 
553             'labels':self.labels,
554             'contacts':self.addressbook,
555             'imported_keys':self.imported_keys,
556             'aliases':self.aliases,
557             'authorities':self.authorities,
558             'receipts':self.receipts,
559             'num_zeros':self.num_zeros,
560             }
561         f = open(self.path,"w")
562         f.write( repr(s) )
563         f.close()
564
565     def read(self):
566         import interface
567
568         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
569         self.file_exists = False
570         try:
571             f = open(self.path,"r")
572             data = f.read()
573             f.close()
574         except:
575             return
576         data = interface.old_to_new(data)
577         try:
578             d = ast.literal_eval( data )
579             self.seed_version = d.get('seed_version')
580             self.master_public_key = d.get('master_public_key').decode('hex')
581             self.use_encryption = d.get('use_encryption')
582             self.fee = int( d.get('fee') )
583             self.seed = d.get('seed')
584             self.server = d.get('server')
585             #blocks = d.get('blocks')
586             self.addresses = d.get('addresses')
587             self.change_addresses = d.get('change_addresses')
588             self.history = d.get('history')
589             self.labels = d.get('labels')
590             self.addressbook = d.get('contacts')
591             self.imported_keys = d.get('imported_keys',{})
592             self.aliases = d.get('aliases',{})
593             self.authorities = d.get('authorities',{})
594             self.receipts = d.get('receipts',{})
595             self.num_zeros = d.get('num_zeros',0)
596         except:
597             raise BaseException("cannot read wallet file")
598
599         self.update_tx_history()
600
601         if self.seed_version != SEED_VERSION:
602             raise BaseException(upgrade_msg)
603
604         if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
605
606         self.file_exists = True
607
608
609         
610
611     def get_addr_balance(self, addr):
612         assert self.is_mine(addr)
613         h = self.history.get(addr,[])
614         c = u = 0
615         for item in h:
616             v = item['value']
617             if item['height']:
618                 c += v
619             else:
620                 u += v
621         return c, u
622
623     def get_balance(self):
624         conf = unconf = 0
625         for addr in self.all_addresses(): 
626             c, u = self.get_addr_balance(addr)
627             conf += c
628             unconf += u
629         return conf, unconf
630
631
632     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
633         """ todo: minimize tx size """
634         total = 0
635         fee = self.fee if fixed_fee is None else fixed_fee
636
637         coins = []
638         domain = [from_addr] if from_addr else self.all_addresses()
639         for addr in domain:
640             h = self.history.get(addr)
641             if h is None: continue
642             for item in h:
643                 if item.get('raw_output_script'):
644                     coins.append( (addr,item))
645
646         coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
647         inputs = []
648         for c in coins: 
649             addr, item = c
650             v = item.get('value')
651             total += v
652             inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
653             fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
654             if total >= amount + fee: break
655         else:
656             #print "not enough funds: %d %d"%(total, fee)
657             inputs = []
658         return inputs, total, fee
659
660     def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
661         outputs = [ (to_addr, amount) ]
662         change_amount = total - ( amount + fee )
663         if change_amount != 0:
664             # normally, the update thread should ensure that the last change address is unused
665             if not change_addr:
666                 change_addr = self.change_addresses[-1]
667             outputs.append( ( change_addr,  change_amount) )
668         return outputs
669
670     def sign_inputs( self, inputs, outputs, password ):
671         s_inputs = []
672         for i in range(len(inputs)):
673             addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
674             private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
675             public_key = private_key.get_verifying_key()
676             pubkey = public_key.to_string()
677             tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
678             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
679             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
680             s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
681         return s_inputs
682
683     def pw_encode(self, s, password):
684         if password:
685             secret = Hash(password)
686             return EncodeAES(secret, s)
687         else:
688             return s
689
690     def pw_decode(self, s, password):
691         if password is not None:
692             secret = Hash(password)
693             d = DecodeAES(secret, s)
694             if s == self.seed:
695                 try:
696                     d.decode('hex')
697                 except:
698                     raise BaseException("Invalid password")
699             return d
700         else:
701             return s
702
703     def get_status(self, address):
704         h = self.history.get(address)
705         if not h:
706             status = None
707         else:
708             lastpoint = h[-1]
709             status = lastpoint['block_hash']
710             if status == 'mempool': 
711                 status = status + ':%d'% len(h)
712         return status
713
714     def receive_status_callback(self, addr, status):
715         with self.lock:
716             if self.get_status(addr) != status:
717                 #print "updating status for", addr, status
718                 self.interface.get_history(addr)
719
720     def receive_history_callback(self, addr, data): 
721         #print "updating history for", addr
722         with self.lock:
723             self.history[addr] = data
724             self.update_tx_history()
725             self.save()
726
727     def get_tx_history(self):
728         lines = self.tx_history.values()
729         lines = sorted(lines, key=operator.itemgetter("timestamp"))
730         return lines
731
732     def update_tx_history(self):
733         self.tx_history= {}
734         for addr in self.all_addresses():
735             h = self.history.get(addr)
736             if h is None: continue
737             for tx in h:
738                 tx_hash = tx['tx_hash']
739                 line = self.tx_history.get(tx_hash)
740                 if not line:
741                     self.tx_history[tx_hash] = copy.copy(tx)
742                     line = self.tx_history.get(tx_hash)
743                 else:
744                     line['value'] += tx['value']
745                 if line['height'] == 0:
746                     line['timestamp'] = 1e12
747         self.update_tx_labels()
748
749     def update_tx_labels(self):
750         for tx in self.tx_history.values():
751             default_label = ''
752             if tx['value']<0:
753                 for o_addr in tx['outputs']:
754                     if not self.is_change(o_addr):
755                         dest_label = self.labels.get(o_addr)
756                         if dest_label:
757                             default_label = 'to: ' + dest_label
758                         else:
759                             default_label = 'to: ' + o_addr
760             else:
761                 for o_addr in tx['outputs']:
762                     if self.is_mine(o_addr) and not self.is_change(o_addr):
763                         dest_label = self.labels.get(o_addr)
764                         if dest_label:
765                             default_label = 'at: ' + dest_label
766                         else:
767                             default_label = 'at: ' + o_addr
768             tx['default_label'] = default_label
769
770     def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
771         if not self.is_valid(to_address):
772             raise BaseException("Invalid address")
773         inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
774         if not inputs:
775             raise BaseException("Not enough funds")
776         outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
777         s_inputs = self.sign_inputs( inputs, outputs, password )
778
779         tx = filter( raw_tx( s_inputs, outputs ) )
780         if to_address not in self.addressbook:
781             self.addressbook.append(to_address)
782         if label: 
783             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
784             self.labels[tx_hash] = label
785
786         return tx
787
788     def sendtx(self, tx):
789         tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
790         self.tx_event.clear()
791         self.interface.send([('blockchain.transaction.broadcast', [tx])])
792         self.tx_event.wait()
793         out = self.tx_result 
794         if out != tx_hash:
795             return False, "error: " + out
796         if self.receipt:
797             self.receipts[tx_hash] = self.receipt
798             self.receipt = None
799         return True, out
800
801
802     def read_alias(self, alias):
803         # this might not be the right place for this function.
804         import urllib
805
806         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
807         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
808         if m1:
809             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
810         elif m2:
811             url = 'http://' + alias + '/bitcoin.id'
812         else:
813             return ''
814         try:
815             lines = urllib.urlopen(url).readlines()
816         except:
817             return ''
818
819         # line 0
820         line = lines[0].strip().split(':')
821         if len(line) == 1:
822             auth_name = None
823             target = signing_addr = line[0]
824         else:
825             target, auth_name, signing_addr, signature = line
826             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
827             print msg, signature
828             self.verify_message(signing_addr, signature, msg)
829         
830         # other lines are signed updates
831         for line in lines[1:]:
832             line = line.strip()
833             if not line: continue
834             line = line.split(':')
835             previous = target
836             print repr(line)
837             target, signature = line
838             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
839
840         if not self.is_valid(target):
841             raise BaseException("Invalid bitcoin address")
842
843         return target, signing_addr, auth_name
844
845     def update_password(self, seed, new_password):
846         if new_password == '': new_password = None
847         self.use_encryption = (new_password != None)
848         self.seed = self.pw_encode( seed, new_password)
849         for k in self.imported_keys.keys():
850             a = self.imported_keys[k]
851             b = self.pw_decode(a, password)
852             c = self.pw_encode(b, new_password)
853             self.imported_keys[k] = c
854         self.save()
855
856     def get_alias(self, alias, interactive = False, show_message=None, question = None):
857         try:
858             target, signing_address, auth_name = self.read_alias(alias)
859         except BaseException, e:
860             # raise exception if verify fails (verify the chain)
861             if interactive:
862                 show_message("Alias error: " + e.message)
863             return
864
865         print target, signing_address, auth_name
866
867         if auth_name is None:
868             a = self.aliases.get(alias)
869             if not a:
870                 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)
871                 if interactive and question( msg ):
872                     self.aliases[alias] = (signing_address, target)
873                 else:
874                     target = None
875             else:
876                 if signing_address != a[0]:
877                     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
878                     if interactive and question( msg ):
879                         self.aliases[alias] = (signing_address, target)
880                     else:
881                         target = None
882         else:
883             if signing_address not in self.authorities.keys():
884                 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)
885                 if interactive and question( msg ):
886                     self.authorities[signing_address] = auth_name
887                 else:
888                     target = None
889
890         if target:
891             self.aliases[alias] = (signing_address, target)
892             
893         return target
894
895
896     def parse_url(self, url, show_message, question):
897         o = url[8:].split('?')
898         address = o[0]
899         if len(o)>1:
900             params = o[1].split('&')
901         else:
902             params = []
903
904         amount = label = message = signature = identity = ''
905         for p in params:
906             k,v = p.split('=')
907             uv = urldecode(v)
908             if k == 'amount': amount = uv
909             elif k == 'message': message = uv
910             elif k == 'label': label = uv
911             elif k == 'signature':
912                 identity, signature = uv.split(':')
913                 url = url.replace('&%s=%s'%(k,v),'')
914             else: 
915                 print k,v
916
917         if signature:
918             if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
919                 signing_address = self.get_alias(identity, True, show_message, question)
920             elif self.is_valid(identity):
921                 signing_address = identity
922             else:
923                 signing_address = None
924             if not signing_address:
925                 return
926             try:
927                 self.verify_message(signing_address, signature, url )
928                 self.receipt = (signing_address, signature, url)
929             except:
930                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
931                 address = amount = label = identity = message = ''
932
933         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
934             payto_address = self.get_alias(address, True, show_message, question)
935             if payto_address:
936                 address = address + ' <' + payto_address + '>'
937
938         return address, amount, label, message, signature, identity, url
939
940
941     def update(self):
942         self.interface.poke()
943         self.up_to_date_event.wait()
944
945
946     def start_session(self, interface):
947         self.interface = interface
948         self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
949         self.interface.subscribe(self.all_addresses())
950
951
952
953