merge
[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):
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 += " "*( 9 - ( len(s) - p ))
234     s = " "*( 5 - ( p )) + s
235     return s
236
237
238 from version import ELECTRUM_VERSION, SEED_VERSION
239 from interface import DEFAULT_SERVERS
240
241
242
243
244 class Wallet:
245     def __init__(self, gui_callback = lambda: None):
246
247         self.electrum_version = ELECTRUM_VERSION
248         self.seed_version = SEED_VERSION
249         self.gui_callback = gui_callback
250
251         self.gap_limit = 5           # configuration
252         self.fee = 100000
253         self.master_public_key = ''
254
255         # saved fields
256         self.use_encryption = False
257         self.addresses = []          # receiving addresses visible for user
258         self.change_addresses = []   # addresses used as change
259         self.seed = ''               # encrypted
260         self.history = {}
261         self.labels = {}             # labels for addresses and transactions
262         self.aliases = {}            # aliases for addresses
263         self.authorities = {}        # trusted addresses
264         
265         self.receipts = {}           # signed URIs
266         self.receipt = None          # next receipt
267         self.addressbook = []        # outgoing addresses, for payments
268
269         # not saved
270         self.tx_history = {}
271
272         self.imported_keys = {}
273         self.remote_url = None
274
275         self.was_updated = True
276         self.blocks = -1
277         self.banner = ''
278         self.up_to_date_event = threading.Event()
279         self.up_to_date_event.clear()
280         self.up_to_date = False
281         self.lock = threading.Lock()
282         self.tx_event = threading.Event()
283
284         #
285         self.addresses_waiting_for_status = []
286         self.addresses_waiting_for_history = []
287         self.pick_random_server()
288
289
290
291     def pick_random_server(self):
292         self.server = random.choice( DEFAULT_SERVERS )         # random choice when the wallet is created
293
294     def is_up_to_date(self):
295         return self.interface.responses.empty() and not ( self.addresses_waiting_for_status or self.addresses_waiting_for_history )
296
297
298     def set_server(self, server):
299         # raise an error if the format isnt correct
300         a,b,c = server.split(':')
301         b = int(b)
302         assert c in ['t','h','n']
303         # set the server
304         if server != self.server:
305             self.server = server
306             self.save()
307             self.interface.is_connected = False  # this exits the polling loop
308
309     def set_path(self, wallet_path):
310
311         if wallet_path is not None:
312             self.path = wallet_path
313         else:
314             # backward compatibility: look for wallet file in the default data directory
315             if "HOME" in os.environ:
316                 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
317             elif "LOCALAPPDATA" in os.environ:
318                 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
319             elif "APPDATA" in os.environ:
320                 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
321             else:
322                 raise BaseException("No home directory found in environment variables.")
323
324             if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
325             self.path = os.path.join( wallet_dir, 'electrum.dat' )
326
327     def import_key(self, keypair, password):
328         address, key = keypair.split(':')
329         if not self.is_valid(address): return False
330         if address in self.all_addresses(): return False
331         b = ASecretToSecret( key )
332         if not b: return False
333         secexp = int( b.encode('hex'), 16)
334         private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
335         # sanity check
336         public_key = private_key.get_verifying_key()
337         if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
338         self.imported_keys[address] = self.pw_encode( key, password )
339         return True
340
341     def new_seed(self, password):
342         seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
343         #self.init_mpk(seed)
344         # encrypt
345         self.seed = self.pw_encode( seed, password )
346
347
348     def init_mpk(self,seed):
349         # public key
350         curve = SECP256k1
351         secexp = self.stretch_key(seed)
352         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
353         self.master_public_key = master_private_key.get_verifying_key().to_string()
354
355     def all_addresses(self):
356         return self.addresses + self.change_addresses + self.imported_keys.keys()
357
358     def is_mine(self, address):
359         return address in self.all_addresses()
360
361     def is_change(self, address):
362         return address in self.change_addresses
363
364     def is_valid(self,addr):
365         ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
366         if not ADDRESS_RE.match(addr): return False
367         try:
368             h = bc_address_to_hash_160(addr)
369         except:
370             return False
371         return addr == hash_160_to_bc_address(h)
372
373     def stretch_key(self,seed):
374         oldseed = seed
375         for i in range(100000):
376             seed = hashlib.sha256(seed + oldseed).digest()
377         return string_to_number( seed )
378
379     def get_sequence(self,n,for_change):
380         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
381
382     def get_private_key(self, address, password):
383         """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
384         order = generator_secp256k1.order()
385         
386         if address in self.imported_keys.keys():
387             b = self.pw_decode( self.imported_keys[address], password )
388             b = ASecretToSecret( b )
389             secexp = int( b.encode('hex'), 16)
390         else:
391             if address in self.addresses:
392                 n = self.addresses.index(address)
393                 for_change = False
394             elif address in self.change_addresses:
395                 n = self.change_addresses.index(address)
396                 for_change = True
397             else:
398                 raise BaseException("unknown address")
399             try:
400                 seed = self.pw_decode( self.seed, password)
401             except:
402                 raise BaseException("Invalid password")
403             secexp = self.stretch_key(seed)
404             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
405
406         pk = number_to_string(secexp,order)
407         return pk
408
409     def msg_magic(self, message):
410         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
411
412     def sign_message(self, address, message, password):
413         private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
414         public_key = private_key.get_verifying_key()
415         signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
416         assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
417         for i in range(4):
418             sig = base64.b64encode( chr(27+i) + signature )
419             try:
420                 self.verify_message( address, sig, message)
421                 return sig
422             except:
423                 continue
424         else:
425             raise BaseException("error: cannot sign message")
426         
427             
428     def verify_message(self, address, signature, message):
429         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
430         from ecdsa import numbertheory, ellipticcurve, util
431         import msqr
432         curve = curve_secp256k1
433         G = generator_secp256k1
434         order = G.order()
435         # extract r,s from signature
436         sig = base64.b64decode(signature)
437         if len(sig) != 65: raise BaseException("Wrong encoding")
438         r,s = util.sigdecode_string(sig[1:], order)
439         recid = ord(sig[0]) - 27
440         # 1.1
441         x = r + (recid/2) * order
442         # 1.3
443         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
444         beta = msqr.modular_sqrt(alpha, curve.p())
445         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
446         # 1.4 the constructor checks that nR is at infinity
447         R = ellipticcurve.Point(curve, x, y, order)
448         # 1.5 compute e from message:
449         h = Hash( self.msg_magic( message ) )
450         e = string_to_number(h)
451         minus_e = -e % order
452         # 1.6 compute Q = r^-1 (sR - eG)
453         inv_r = numbertheory.inverse_mod(r,order)
454         Q = inv_r * ( s * R + minus_e * G )
455         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
456         # check that Q is the public key
457         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
458         # check that we get the original signing address
459         addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
460         # print addr
461         if address != addr:
462             print "bad signature"
463             raise BaseException("Bad signature")
464     
465
466     def create_new_address(self, for_change):
467         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
468         curve = SECP256k1
469         n = len(self.change_addresses) if for_change else len(self.addresses)
470         z = self.get_sequence(n,for_change)
471         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
472         pubkey_point = master_public_key.pubkey.point + z*curve.generator
473         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
474         address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
475         if for_change:
476             self.change_addresses.append(address)
477         else:
478             self.addresses.append(address)
479
480         self.history[address] = []
481         print address
482         return address
483
484
485
486     def synchronize(self):
487         if not self.master_public_key:
488             return []
489
490         new_addresses = []
491         while True:
492             if self.change_addresses == []:
493                 new_addresses.append( self.create_new_address(True) )
494                 continue
495             a = self.change_addresses[-1]
496             if self.history.get(a):
497                 new_addresses.append( self.create_new_address(True) )
498             else:
499                 break
500
501         n = self.gap_limit
502         while True:
503             if len(self.addresses) < n:
504                 new_addresses.append( self.create_new_address(False) )
505                 continue
506             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
507                 break
508             else:
509                 new_addresses.append( self.create_new_address(False) )
510
511         if self.remote_url:
512             num = self.get_remote_number()
513             while len(self.addresses)<num:
514                 new_addresses.append( self.create_new_address(False) )
515
516         return new_addresses
517
518
519     def get_remote_number(self):
520         import jsonrpclib
521         server = jsonrpclib.Server(self.remote_url)
522         out = server.getnum()
523         return out
524
525     def get_remote_mpk(self):
526         import jsonrpclib
527         server = jsonrpclib.Server(self.remote_url)
528         out = server.getkey()
529         return out
530
531     def is_found(self):
532         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
533
534     def fill_addressbook(self):
535         for tx in self.tx_history.values():
536             if tx['value']<0:
537                 for i in tx['outputs']:
538                     if not self.is_mine(i) and i not in self.addressbook:
539                         self.addressbook.append(i)
540         # redo labels
541         self.update_tx_labels()
542
543
544     def save(self):
545         s = {
546             'seed_version':self.seed_version,
547             'use_encryption':self.use_encryption,
548             'master_public_key': self.master_public_key.encode('hex'),
549             'fee':self.fee,
550             'server':self.server,
551             'seed':self.seed,
552             'addresses':self.addresses,
553             'change_addresses':self.change_addresses,
554             'history':self.history, 
555             'labels':self.labels,
556             'contacts':self.addressbook,
557             'imported_keys':self.imported_keys,
558             'aliases':self.aliases,
559             'authorities':self.authorities,
560             'receipts':self.receipts,
561             }
562         f = open(self.path,"w")
563         f.write( repr(s) )
564         f.close()
565
566     def read(self):
567         import interface
568
569         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
570         self.file_exists = False
571         try:
572             f = open(self.path,"r")
573             data = f.read()
574             f.close()
575         except:
576             return
577         data = interface.old_to_new(data)
578         try:
579             d = ast.literal_eval( data )
580             self.seed_version = d.get('seed_version')
581             self.master_public_key = d.get('master_public_key').decode('hex')
582             self.use_encryption = d.get('use_encryption')
583             self.fee = int( d.get('fee') )
584             self.seed = d.get('seed')
585             self.server = d.get('server')
586             #blocks = d.get('blocks')
587             self.addresses = d.get('addresses')
588             self.change_addresses = d.get('change_addresses')
589             self.history = d.get('history')
590             self.labels = d.get('labels')
591             self.addressbook = d.get('contacts')
592             self.imported_keys = d.get('imported_keys',{})
593             self.aliases = d.get('aliases',{})
594             self.authorities = d.get('authorities',{})
595             self.receipts = d.get('receipts',{})
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         if self.is_mine(addr):
613             h = self.history.get(addr)
614         else:
615             h = self.interface.retrieve_history(addr)
616         if not h: return 0,0
617         c = u = 0
618         for item in h:
619             v = item['value']
620             if item['height']:
621                 c += v
622             else:
623                 u += v
624         return c, u
625
626     def get_balance(self):
627         conf = unconf = 0
628         for addr in self.all_addresses(): 
629             c, u = self.get_addr_balance(addr)
630             conf += c
631             unconf += u
632         return conf, unconf
633
634
635     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
636         """ todo: minimize tx size """
637         total = 0
638         fee = self.fee if fixed_fee is None else fixed_fee
639
640         coins = []
641         domain = [from_addr] if from_addr else self.all_addresses()
642         for addr in domain:
643             h = self.history.get(addr)
644             if h is None: continue
645             for item in h:
646                 if item.get('raw_output_script'):
647                     coins.append( (addr,item))
648
649         coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
650         inputs = []
651         for c in coins: 
652             addr, item = c
653             v = item.get('value')
654             total += v
655             inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
656             fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
657             if total >= amount + fee: break
658         else:
659             #print "not enough funds: %d %d"%(total, fee)
660             inputs = []
661         return inputs, total, fee
662
663     def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
664         outputs = [ (to_addr, amount) ]
665         change_amount = total - ( amount + fee )
666         if change_amount != 0:
667             # normally, the update thread should ensure that the last change address is unused
668             if not change_addr:
669                 change_addr = self.change_addresses[-1]
670             outputs.append( ( change_addr,  change_amount) )
671         return outputs
672
673     def sign_inputs( self, inputs, outputs, password ):
674         s_inputs = []
675         for i in range(len(inputs)):
676             addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
677             private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
678             public_key = private_key.get_verifying_key()
679             pubkey = public_key.to_string()
680             tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
681             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
682             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
683             s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
684         return s_inputs
685
686     def pw_encode(self, s, password):
687         if password:
688             secret = Hash(password)
689             return EncodeAES(secret, s)
690         else:
691             return s
692
693     def pw_decode(self, s, password):
694         if password is not None:
695             secret = Hash(password)
696             d = DecodeAES(secret, s)
697             if s == self.seed:
698                 try:
699                     d.decode('hex')
700                 except:
701                     raise BaseException("Invalid password")
702             return d
703         else:
704             return s
705
706     def get_status(self, address):
707         h = self.history.get(address)
708         if not h:
709             status = None
710         else:
711             lastpoint = h[-1]
712             status = lastpoint['block_hash']
713             if status == 'mempool': 
714                 status = status + ':%d'% len(h)
715         return status
716
717     def receive_status_callback(self, addr, status):
718         with self.lock:
719             if self.get_status(addr) != status:
720                 #print "updating status for", addr, status
721                 self.addresses_waiting_for_history.append(addr)
722                 self.interface.get_history(addr)
723             if addr in self.addresses_waiting_for_status: 
724                 self.addresses_waiting_for_status.remove(addr)
725
726     def receive_history_callback(self, addr, data): 
727         #print "updating history for", addr
728         with self.lock:
729             self.history[addr] = data
730             self.update_tx_history()
731             self.save()
732             if addr in self.addresses_waiting_for_history: self.addresses_waiting_for_history.remove(addr)
733
734     def get_tx_history(self):
735         lines = self.tx_history.values()
736         lines = sorted(lines, key=operator.itemgetter("timestamp"))
737         return lines
738
739     def update_tx_history(self):
740         self.tx_history= {}
741         for addr in self.all_addresses():
742             h = self.history.get(addr)
743             if h is None: continue
744             for tx in h:
745                 tx_hash = tx['tx_hash']
746                 line = self.tx_history.get(tx_hash)
747                 if not line:
748                     self.tx_history[tx_hash] = copy.copy(tx)
749                     line = self.tx_history.get(tx_hash)
750                 else:
751                     line['value'] += tx['value']
752                 if line['height'] == 0:
753                     line['timestamp'] = 1e12
754         self.update_tx_labels()
755
756     def update_tx_labels(self):
757         for tx in self.tx_history.values():
758             default_label = ''
759             if tx['value']<0:
760                 for o_addr in tx['outputs']:
761                     if not self.is_change(o_addr):
762                         dest_label = self.labels.get(o_addr)
763                         if dest_label:
764                             default_label = 'to: ' + dest_label
765                         else:
766                             default_label = 'to: ' + o_addr
767             else:
768                 for o_addr in tx['outputs']:
769                     if self.is_mine(o_addr) and not self.is_change(o_addr):
770                         dest_label = self.labels.get(o_addr)
771                         if dest_label:
772                             default_label = 'at: ' + dest_label
773                         else:
774                             default_label = 'at: ' + o_addr
775             tx['default_label'] = default_label
776
777     def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
778         if not self.is_valid(to_address):
779             raise BaseException("Invalid address")
780         inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
781         if not inputs:
782             raise BaseException("Not enough funds")
783         outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
784         s_inputs = self.sign_inputs( inputs, outputs, password )
785
786         tx = filter( raw_tx( s_inputs, outputs ) )
787         if to_address not in self.addressbook:
788             self.addressbook.append(to_address)
789         if label: 
790             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
791             self.labels[tx_hash] = label
792
793         return tx
794
795     def sendtx(self, tx):
796         tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
797         self.tx_event.clear()
798         self.interface.send([('blockchain.transaction.broadcast', [tx])])
799         self.tx_event.wait()
800         out = self.tx_result 
801         if out != tx_hash:
802             return False, "error: " + out
803         if self.receipt:
804             self.receipts[tx_hash] = self.receipt
805             self.receipt = None
806         return True, out
807
808
809     def read_alias(self, alias):
810         # this might not be the right place for this function.
811         import urllib
812
813         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
814         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
815         if m1:
816             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
817         elif m2:
818             url = 'http://' + alias + '/bitcoin.id'
819         else:
820             return ''
821         try:
822             lines = urllib.urlopen(url).readlines()
823         except:
824             return ''
825
826         # line 0
827         line = lines[0].strip().split(':')
828         if len(line) == 1:
829             auth_name = None
830             target = signing_addr = line[0]
831         else:
832             target, auth_name, signing_addr, signature = line
833             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
834             print msg, signature
835             self.verify_message(signing_addr, signature, msg)
836         
837         # other lines are signed updates
838         for line in lines[1:]:
839             line = line.strip()
840             if not line: continue
841             line = line.split(':')
842             previous = target
843             print repr(line)
844             target, signature = line
845             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
846
847         if not self.is_valid(target):
848             raise BaseException("Invalid bitcoin address")
849
850         return target, signing_addr, auth_name
851
852     def update_password(self, seed, new_password):
853         if new_password == '': new_password = None
854         self.use_encryption = (new_password != None)
855         self.seed = self.pw_encode( seed, new_password)
856         for k in self.imported_keys.keys():
857             a = self.imported_keys[k]
858             b = self.pw_decode(a, password)
859             c = self.pw_encode(b, new_password)
860             self.imported_keys[k] = c
861         self.save()
862
863     def get_alias(self, alias, interactive = False, show_message=None, question = None):
864         try:
865             target, signing_address, auth_name = self.read_alias(alias)
866         except BaseException, e:
867             # raise exception if verify fails (verify the chain)
868             if interactive:
869                 show_message("Alias error: " + e.message)
870             return
871
872         print target, signing_address, auth_name
873
874         if auth_name is None:
875             a = self.aliases.get(alias)
876             if not a:
877                 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)
878                 if interactive and question( msg ):
879                     self.aliases[alias] = (signing_address, target)
880                 else:
881                     target = None
882             else:
883                 if signing_address != a[0]:
884                     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
885                     if interactive and question( msg ):
886                         self.aliases[alias] = (signing_address, target)
887                     else:
888                         target = None
889         else:
890             if signing_address not in self.authorities.keys():
891                 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)
892                 if interactive and question( msg ):
893                     self.authorities[signing_address] = auth_name
894                 else:
895                     target = None
896
897         if target:
898             self.aliases[alias] = (signing_address, target)
899             
900         return target
901
902
903     def parse_url(self, url, show_message, question):
904         o = url[8:].split('?')
905         address = o[0]
906         if len(o)>1:
907             params = o[1].split('&')
908         else:
909             params = []
910
911         amount = label = message = signature = identity = ''
912         for p in params:
913             k,v = p.split('=')
914             uv = urldecode(v)
915             if k == 'amount': amount = uv
916             elif k == 'message': message = uv
917             elif k == 'label': label = uv
918             elif k == 'signature':
919                 identity, signature = uv.split(':')
920                 url = url.replace('&%s=%s'%(k,v),'')
921             else: 
922                 print k,v
923
924         if signature:
925             if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
926                 signing_address = self.get_alias(identity, True, show_message, question)
927             elif self.is_valid(identity):
928                 signing_address = identity
929             else:
930                 signing_address = None
931             if not signing_address:
932                 return
933             try:
934                 self.verify_message(signing_address, signature, url )
935                 self.receipt = (signing_address, signature, url)
936             except:
937                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
938                 address = amount = label = identity = message = ''
939
940         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
941             payto_address = self.get_alias(address, True, show_message, question)
942             if payto_address:
943                 address = address + ' <' + payto_address + '>'
944
945         return address, amount, label, message, signature, identity, url
946
947
948     def update(self):
949         self.interface.poke()
950         self.up_to_date_event.wait()
951
952
953