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