3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
20 import sys, base64, os, re, hashlib, copy, operator, ast, threading, random
22 from ecdsa.util import string_to_number, number_to_string
24 ############ functions from pywallet #####################
28 def hash_160(public_key):
30 md = hashlib.new('ripemd160')
31 md.update(hashlib.sha256(public_key).digest())
35 md = ripemd.new(hashlib.sha256(public_key).digest())
39 def public_key_to_bc_address(public_key):
40 h160 = hash_160(public_key)
41 return hash_160_to_bc_address(h160)
43 def hash_160_to_bc_address(h160):
44 vh160 = chr(addrtype) + h160
47 return b58encode(addr)
49 def bc_address_to_hash_160(addr):
50 bytes = b58decode(addr, 25)
53 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
54 __b58base = len(__b58chars)
57 """ encode v, which is a string of bytes, to base58.
61 for (i, c) in enumerate(v[::-1]):
62 long_value += (256**i) * ord(c)
65 while long_value >= __b58base:
66 div, mod = divmod(long_value, __b58base)
67 result = __b58chars[mod] + result
69 result = __b58chars[long_value] + result
71 # Bitcoin does a little leading-zero-compression:
72 # leading 0-bytes in the input become leading-1s
75 if c == '\0': nPad += 1
78 return (__b58chars[0]*nPad) + result
80 def b58decode(v, length):
81 """ decode v into a string of len bytes
84 for (i, c) in enumerate(v[::-1]):
85 long_value += __b58chars.find(c) * (__b58base**i)
88 while long_value >= 256:
89 div, mod = divmod(long_value, 256)
90 result = chr(mod) + result
92 result = chr(long_value) + result
96 if c == __b58chars[0]: nPad += 1
99 result = chr(0)*nPad + result
100 if length is not None and len(result) != length:
107 return hashlib.sha256(hashlib.sha256(data).digest()).digest()
109 def EncodeBase58Check(vchIn):
111 return b58encode(vchIn + hash[0:4])
113 def DecodeBase58Check(psz):
114 vchRet = b58decode(psz, None)
124 def PrivKeyToSecret(privkey):
125 return privkey[9:9+32]
127 def SecretToASecret(secret):
128 vchIn = chr(addrtype+128) + secret
129 return EncodeBase58Check(vchIn)
131 def ASecretToSecret(key):
132 vch = DecodeBase58Check(key)
133 if vch and vch[0] == chr(addrtype+128):
138 ########### end pywallet functions #######################
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)
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')
152 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
153 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
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 )
171 out = re.sub('( [^\n]*|)\n','',s)
172 out = out.replace(' ','')
173 out = out.replace('\n','')
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'
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'
191 script = p_script + ' scriptsig \n'
194 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
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
214 def format_satoshis(x, is_diff=False, num_zeros = 0):
215 from decimal import Decimal
217 sign, digits, exp = s.as_tuple()
218 digits = map(str, digits)
219 while len(digits) < 9:
221 digits.insert(-8,'.')
222 s = ''.join(digits).rstrip('0')
229 s += "0"*( 1 + num_zeros - ( len(s) - p ))
230 s += " "*( 9 - ( len(s) - p ))
231 s = " "*( 5 - ( p )) + s
235 from version import ELECTRUM_VERSION, SEED_VERSION
236 from interface import DEFAULT_SERVERS
242 def __init__(self, gui_callback = lambda: None):
244 self.electrum_version = ELECTRUM_VERSION
245 self.seed_version = SEED_VERSION
246 self.gui_callback = gui_callback
248 self.gap_limit = 5 # configuration
251 self.master_public_key = ''
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
259 self.labels = {} # labels for addresses and transactions
260 self.aliases = {} # aliases for addresses
261 self.authorities = {} # trusted addresses
262 self.frozen_addresses = []
263 self.prioritized_addresses = []
264 self.expert_mode = False
266 self.receipts = {} # signed URIs
267 self.receipt = None # next receipt
268 self.addressbook = [] # outgoing addresses, for payments
273 self.imported_keys = {}
274 self.remote_url = None
276 self.was_updated = True
280 # there is a difference between self.up_to_date and self.is_up_to_date()
281 # self.is_up_to_date() returns true when all requests have been answered and processed
282 # self.up_to_date is true when the wallet is synchronized (stronger requirement)
283 self.up_to_date_event = threading.Event()
284 self.up_to_date_event.clear()
285 self.up_to_date = False
286 self.lock = threading.Lock()
287 self.tx_event = threading.Event()
289 self.pick_random_server()
293 def pick_random_server(self):
294 self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
296 def is_up_to_date(self):
297 return self.interface.responses.empty() and not self.interface.unanswered_requests
299 def set_server(self, server):
300 # raise an error if the format isnt correct
301 a,b,c = server.split(':')
303 assert c in ['t','h','n']
305 if server != self.server:
308 self.interface.is_connected = False # this exits the polling loop
309 self.interface.poke()
311 def set_path(self, wallet_path):
313 if wallet_path is not None:
314 self.path = wallet_path
316 # backward compatibility: look for wallet file in the default data directory
317 if "HOME" in os.environ:
318 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
319 elif "LOCALAPPDATA" in os.environ:
320 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
321 elif "APPDATA" in os.environ:
322 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
324 raise BaseException("No home directory found in environment variables.")
326 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
327 self.path = os.path.join( wallet_dir, 'electrum.dat' )
329 def import_key(self, keypair, password):
330 address, key = keypair.split(':')
331 if not self.is_valid(address):
332 raise BaseException('Invalid Bitcoin address')
333 if address in self.all_addresses():
334 raise BaseException('Address already in wallet')
335 b = ASecretToSecret( key )
337 raise BaseException('Unsupported key format')
338 secexp = int( b.encode('hex'), 16)
339 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
341 public_key = private_key.get_verifying_key()
342 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ):
343 raise BaseException('Address does not match private key')
344 self.imported_keys[address] = self.pw_encode( key, password )
346 def new_seed(self, password):
347 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
350 self.seed = self.pw_encode( seed, password )
353 def init_mpk(self,seed):
356 secexp = self.stretch_key(seed)
357 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
358 self.master_public_key = master_private_key.get_verifying_key().to_string()
360 def all_addresses(self):
361 return self.addresses + self.change_addresses + self.imported_keys.keys()
363 def is_mine(self, address):
364 return address in self.all_addresses()
366 def is_change(self, address):
367 return address in self.change_addresses
369 def is_valid(self,addr):
370 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
371 if not ADDRESS_RE.match(addr): return False
373 h = bc_address_to_hash_160(addr)
376 return addr == hash_160_to_bc_address(h)
378 def stretch_key(self,seed):
380 for i in range(100000):
381 seed = hashlib.sha256(seed + oldseed).digest()
382 return string_to_number( seed )
384 def get_sequence(self,n,for_change):
385 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
387 def get_private_key_base58(self, address, password):
388 pk = self.get_private_key(address, password)
389 if pk is None: return None
390 return SecretToASecret( pk )
392 def get_private_key(self, address, password):
393 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
394 order = generator_secp256k1.order()
396 if address in self.imported_keys.keys():
397 b = self.pw_decode( self.imported_keys[address], password )
398 if not b: return None
399 b = ASecretToSecret( b )
400 secexp = int( b.encode('hex'), 16)
402 if address in self.addresses:
403 n = self.addresses.index(address)
405 elif address in self.change_addresses:
406 n = self.change_addresses.index(address)
409 raise BaseException("unknown address")
411 seed = self.pw_decode( self.seed, password)
413 raise BaseException("Invalid password")
414 if not seed: return None
415 secexp = self.stretch_key(seed)
416 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
418 pk = number_to_string(secexp,order)
421 def msg_magic(self, message):
422 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
424 def sign_message(self, address, message, password):
425 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
426 public_key = private_key.get_verifying_key()
427 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
428 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
430 sig = base64.b64encode( chr(27+i) + signature )
432 self.verify_message( address, sig, message)
437 raise BaseException("error: cannot sign message")
440 def verify_message(self, address, signature, message):
441 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
442 from ecdsa import numbertheory, ellipticcurve, util
444 curve = curve_secp256k1
445 G = generator_secp256k1
447 # extract r,s from signature
448 sig = base64.b64decode(signature)
449 if len(sig) != 65: raise BaseException("Wrong encoding")
450 r,s = util.sigdecode_string(sig[1:], order)
451 recid = ord(sig[0]) - 27
453 x = r + (recid/2) * order
455 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
456 beta = msqr.modular_sqrt(alpha, curve.p())
457 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
458 # 1.4 the constructor checks that nR is at infinity
459 R = ellipticcurve.Point(curve, x, y, order)
460 # 1.5 compute e from message:
461 h = Hash( self.msg_magic( message ) )
462 e = string_to_number(h)
464 # 1.6 compute Q = r^-1 (sR - eG)
465 inv_r = numbertheory.inverse_mod(r,order)
466 Q = inv_r * ( s * R + minus_e * G )
467 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
468 # check that Q is the public key
469 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
470 # check that we get the original signing address
471 addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
474 print "bad signature"
475 raise BaseException("Bad signature")
478 def create_new_address(self, for_change):
479 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
481 n = len(self.change_addresses) if for_change else len(self.addresses)
482 z = self.get_sequence(n,for_change)
483 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
484 pubkey_point = master_public_key.pubkey.point + z*curve.generator
485 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
486 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
488 self.change_addresses.append(address)
490 self.addresses.append(address)
492 self.history[address] = []
497 def change_gap_limit(self, value):
498 if value >= self.gap_limit:
499 self.gap_limit = value
501 self.interface.poke()
504 elif value >= self.min_acceptable_gap():
505 k = self.num_unused_trailing_addresses()
506 n = len(self.addresses) - k + value
507 self.addresses = self.addresses[0:n]
508 self.gap_limit = value
514 def num_unused_trailing_addresses(self):
516 for a in self.addresses[::-1]:
517 if self.history.get(a):break
521 def min_acceptable_gap(self):
522 # fixme: this assumes wallet is synchronized
525 k = self.num_unused_trailing_addresses()
526 for a in self.addresses[0:-k]:
527 if self.history.get(a):
531 if n > nmax: nmax = n
535 def synchronize(self):
536 if not self.master_public_key:
541 if self.change_addresses == []:
542 new_addresses.append( self.create_new_address(True) )
544 a = self.change_addresses[-1]
545 if self.history.get(a):
546 new_addresses.append( self.create_new_address(True) )
552 if len(self.addresses) < n:
553 new_addresses.append( self.create_new_address(False) )
555 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
558 new_addresses.append( self.create_new_address(False) )
561 num = self.get_remote_number()
562 while len(self.addresses)<num:
563 new_addresses.append( self.create_new_address(False) )
568 def get_remote_number(self):
570 server = jsonrpclib.Server(self.remote_url)
571 out = server.getnum()
574 def get_remote_mpk(self):
576 server = jsonrpclib.Server(self.remote_url)
577 out = server.getkey()
581 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
583 def fill_addressbook(self):
584 for tx in self.tx_history.values():
586 for i in tx['outputs']:
587 if not self.is_mine(i) and i not in self.addressbook:
588 self.addressbook.append(i)
590 self.update_tx_labels()
595 'seed_version':self.seed_version,
596 'use_encryption':self.use_encryption,
597 'master_public_key': self.master_public_key.encode('hex'),
599 'server':self.server,
601 'addresses':self.addresses,
602 'change_addresses':self.change_addresses,
603 'history':self.history,
604 'labels':self.labels,
605 'contacts':self.addressbook,
606 'imported_keys':self.imported_keys,
607 'aliases':self.aliases,
608 'authorities':self.authorities,
609 'receipts':self.receipts,
610 'num_zeros':self.num_zeros,
611 'frozen_addresses':self.frozen_addresses,
612 'prioritized_addresses':self.prioritized_addresses,
613 'expert_mode':self.expert_mode,
614 'gap_limit':self.gap_limit,
616 f = open(self.path,"w")
620 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
625 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
626 self.file_exists = False
628 f = open(self.path,"r")
633 data = interface.old_to_new(data)
635 d = ast.literal_eval( data )
636 self.seed_version = d.get('seed_version')
637 self.master_public_key = d.get('master_public_key').decode('hex')
638 self.use_encryption = d.get('use_encryption')
639 self.fee = int( d.get('fee') )
640 self.seed = d.get('seed')
641 self.server = d.get('server')
642 #blocks = d.get('blocks')
643 self.addresses = d.get('addresses')
644 self.change_addresses = d.get('change_addresses')
645 self.history = d.get('history')
646 self.labels = d.get('labels')
647 self.addressbook = d.get('contacts')
648 self.imported_keys = d.get('imported_keys',{})
649 self.aliases = d.get('aliases',{})
650 self.authorities = d.get('authorities',{})
651 self.receipts = d.get('receipts',{})
652 self.num_zeros = d.get('num_zeros',0)
653 self.frozen_addresses = d.get('frozen_addresses',[])
654 self.prioritized_addresses = d.get('prioritized_addresses',[])
655 self.expert_mode = d.get('expert_mode',False)
656 self.gap_limit = d.get('gap_limit',5)
658 raise BaseException("cannot read wallet file")
660 self.update_tx_history()
662 if self.seed_version != SEED_VERSION:
663 raise BaseException(upgrade_msg)
665 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
667 self.file_exists = True
670 def get_address_flags(self, addr):
671 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
672 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
676 def get_addr_balance(self, addr):
677 assert self.is_mine(addr)
678 h = self.history.get(addr,[])
688 def get_balance(self):
690 for addr in self.all_addresses():
691 c, u = self.get_addr_balance(addr)
697 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
698 """ todo: minimize tx size """
700 fee = self.fee if fixed_fee is None else fixed_fee
703 prioritized_coins = []
704 domain = [from_addr] if from_addr else self.all_addresses()
705 for i in self.frozen_addresses:
706 if i in domain: domain.remove(i)
708 for i in self.prioritized_addresses:
709 if i in domain: domain.remove(i)
712 h = self.history.get(addr)
713 if h is None: continue
715 if item.get('raw_output_script'):
716 coins.append( (addr,item))
718 coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
720 for addr in self.prioritized_addresses:
721 h = self.history.get(addr)
722 if h is None: continue
724 if item.get('raw_output_script'):
725 prioritized_coins.append( (addr,item))
727 prioritized_coins = sorted( prioritized_coins, key = lambda x: x[1]['timestamp'] )
730 coins = prioritized_coins + coins
734 v = item.get('value')
736 inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
737 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
738 if total >= amount + fee: break
740 #print "not enough funds: %s %s"%(format_satoshis(total), format_satoshis(fee))
742 return inputs, total, fee
744 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
745 outputs = [ (to_addr, amount) ]
746 change_amount = total - ( amount + fee )
747 if change_amount != 0:
748 # normally, the update thread should ensure that the last change address is unused
750 change_addr = self.change_addresses[-1]
751 outputs.append( ( change_addr, change_amount) )
754 def sign_inputs( self, inputs, outputs, password ):
756 for i in range(len(inputs)):
757 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
758 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
759 public_key = private_key.get_verifying_key()
760 pubkey = public_key.to_string()
761 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
762 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
763 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
764 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
767 def pw_encode(self, s, password):
769 secret = Hash(password)
770 return EncodeAES(secret, s)
774 def pw_decode(self, s, password):
775 if password is not None:
776 secret = Hash(password)
777 d = DecodeAES(secret, s)
782 raise BaseException("Invalid password")
787 def get_status(self, address):
788 h = self.history.get(address)
793 status = lastpoint['block_hash']
794 if status == 'mempool':
795 status = status + ':%d'% len(h)
798 def receive_status_callback(self, addr, status):
800 if self.get_status(addr) != status:
801 #print "updating status for", addr, status
802 self.interface.get_history(addr)
804 def receive_history_callback(self, addr, data):
805 #print "updating history for", addr
807 self.history[addr] = data
808 self.update_tx_history()
811 def get_tx_history(self):
812 lines = self.tx_history.values()
813 lines = sorted(lines, key=operator.itemgetter("timestamp"))
816 def update_tx_history(self):
818 for addr in self.all_addresses():
819 h = self.history.get(addr)
820 if h is None: continue
822 tx_hash = tx['tx_hash']
823 line = self.tx_history.get(tx_hash)
825 self.tx_history[tx_hash] = copy.copy(tx)
826 line = self.tx_history.get(tx_hash)
828 line['value'] += tx['value']
829 if line['height'] == 0:
830 line['timestamp'] = 1e12
831 self.update_tx_labels()
833 def update_tx_labels(self):
834 for tx in self.tx_history.values():
837 for o_addr in tx['outputs']:
838 if not self.is_mine(o_addr):
839 dest_label = self.labels.get(o_addr)
841 default_label = 'to: ' + dest_label
843 default_label = 'to: ' + o_addr
845 for o_addr in tx['outputs']:
846 if self.is_mine(o_addr) and not self.is_change(o_addr):
849 for o_addr in tx['outputs']:
850 if self.is_mine(o_addr):
856 dest_label = self.labels.get(o_addr)
858 default_label = 'at: ' + dest_label
860 default_label = 'at: ' + o_addr
862 tx['default_label'] = default_label
864 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
865 if not self.is_valid(to_address):
866 raise BaseException("Invalid address")
867 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
869 raise BaseException("Not enough funds")
870 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
871 s_inputs = self.sign_inputs( inputs, outputs, password )
873 tx = filter( raw_tx( s_inputs, outputs ) )
874 if to_address not in self.addressbook:
875 self.addressbook.append(to_address)
877 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
878 self.labels[tx_hash] = label
882 def sendtx(self, tx):
883 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
884 self.tx_event.clear()
885 self.interface.send([('blockchain.transaction.broadcast', [tx])])
889 return False, "error: " + out
891 self.receipts[tx_hash] = self.receipt
896 def read_alias(self, alias):
897 # this might not be the right place for this function.
900 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
901 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
903 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
905 url = 'http://' + alias + '/bitcoin.id'
909 lines = urllib.urlopen(url).readlines()
914 line = lines[0].strip().split(':')
917 target = signing_addr = line[0]
919 target, auth_name, signing_addr, signature = line
920 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
922 self.verify_message(signing_addr, signature, msg)
924 # other lines are signed updates
925 for line in lines[1:]:
927 if not line: continue
928 line = line.split(':')
931 target, signature = line
932 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
934 if not self.is_valid(target):
935 raise BaseException("Invalid bitcoin address")
937 return target, signing_addr, auth_name
939 def update_password(self, seed, old_password, new_password):
940 if new_password == '': new_password = None
941 self.use_encryption = (new_password != None)
942 self.seed = self.pw_encode( seed, new_password)
943 for k in self.imported_keys.keys():
944 a = self.imported_keys[k]
945 b = self.pw_decode(a, old_password)
946 c = self.pw_encode(b, new_password)
947 self.imported_keys[k] = c
950 def get_alias(self, alias, interactive = False, show_message=None, question = None):
952 target, signing_address, auth_name = self.read_alias(alias)
953 except BaseException, e:
954 # raise exception if verify fails (verify the chain)
956 show_message("Alias error: " + str(e))
959 print target, signing_address, auth_name
961 if auth_name is None:
962 a = self.aliases.get(alias)
964 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)
965 if interactive and question( msg ):
966 self.aliases[alias] = (signing_address, target)
970 if signing_address != a[0]:
971 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
972 if interactive and question( msg ):
973 self.aliases[alias] = (signing_address, target)
977 if signing_address not in self.authorities.keys():
978 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)
979 if interactive and question( msg ):
980 self.authorities[signing_address] = auth_name
985 self.aliases[alias] = (signing_address, target)
990 def parse_url(self, url, show_message, question):
991 o = url[8:].split('?')
994 params = o[1].split('&')
998 amount = label = message = signature = identity = ''
1002 if k == 'amount': amount = uv
1003 elif k == 'message': message = uv
1004 elif k == 'label': label = uv
1005 elif k == 'signature':
1006 identity, signature = uv.split(':')
1007 url = url.replace('&%s=%s'%(k,v),'')
1011 if label and self.labels.get(address) != label:
1012 if question('Give label "%s" to address %s ?'%(label,address)):
1013 if address not in self.addressbook and address not in self.all_addresses():
1014 self.addressbook.append(address)
1015 self.labels[address] = label
1018 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
1019 signing_address = self.get_alias(identity, True, show_message, question)
1020 elif self.is_valid(identity):
1021 signing_address = identity
1023 signing_address = None
1024 if not signing_address:
1027 self.verify_message(signing_address, signature, url )
1028 self.receipt = (signing_address, signature, url)
1030 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
1031 address = amount = label = identity = message = ''
1033 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
1034 payto_address = self.get_alias(address, True, show_message, question)
1036 address = address + ' <' + payto_address + '>'
1038 return address, amount, label, message, signature, identity, url
1042 self.interface.poke()
1043 self.up_to_date_event.wait(10000000000)
1046 def start_session(self, interface):
1047 self.interface = interface
1048 self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
1049 self.interface.subscribe(self.all_addresses())
1052 def freeze(self,addr):
1053 if addr in self.all_addresses() and addr not in self.frozen_addresses:
1054 self.unprioritize(addr)
1055 self.frozen_addresses.append(addr)
1061 def unfreeze(self,addr):
1062 if addr in self.all_addresses() and addr in self.frozen_addresses:
1063 self.frozen_addresses.remove(addr)
1069 def prioritize(self,addr):
1070 if addr in self.all_addresses() and addr not in self.prioritized_addresses:
1072 self.prioritized_addresses.append(addr)
1078 def unprioritize(self,addr):
1079 if addr in self.all_addresses() and addr in self.prioritized_addresses:
1080 self.prioritized_addresses.remove(addr)