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