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 def encode_point(pubkey, compressed=False):
54 order = generator_secp256k1.order()
55 p = pubkey.pubkey.point
56 x_str = ecdsa.util.number_to_string(p.x(), order)
57 y_str = ecdsa.util.number_to_string(p.y(), order)
59 return chr(2 + (p.y() & 1)) + x_str
61 return chr(4) + pubkey.to_string() #x_str + y_str
63 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
64 __b58base = len(__b58chars)
67 """ encode v, which is a string of bytes, to base58.
71 for (i, c) in enumerate(v[::-1]):
72 long_value += (256**i) * ord(c)
75 while long_value >= __b58base:
76 div, mod = divmod(long_value, __b58base)
77 result = __b58chars[mod] + result
79 result = __b58chars[long_value] + result
81 # Bitcoin does a little leading-zero-compression:
82 # leading 0-bytes in the input become leading-1s
85 if c == '\0': nPad += 1
88 return (__b58chars[0]*nPad) + result
90 def b58decode(v, length):
91 """ decode v into a string of len bytes
94 for (i, c) in enumerate(v[::-1]):
95 long_value += __b58chars.find(c) * (__b58base**i)
98 while long_value >= 256:
99 div, mod = divmod(long_value, 256)
100 result = chr(mod) + result
102 result = chr(long_value) + result
106 if c == __b58chars[0]: nPad += 1
109 result = chr(0)*nPad + result
110 if length is not None and len(result) != length:
117 return hashlib.sha256(hashlib.sha256(data).digest()).digest()
119 def EncodeBase58Check(vchIn):
121 return b58encode(vchIn + hash[0:4])
123 def DecodeBase58Check(psz):
124 vchRet = b58decode(psz, None)
134 def PrivKeyToSecret(privkey):
135 return privkey[9:9+32]
137 def SecretToASecret(secret):
138 vchIn = chr(addrtype+128) + secret
139 return EncodeBase58Check(vchIn)
141 def ASecretToSecret(key):
142 vch = DecodeBase58Check(key)
143 if vch and vch[0] == chr(addrtype+128):
148 ########### end pywallet functions #######################
151 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
152 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
155 def int_to_hex(i, length=1):
156 s = hex(i)[2:].rstrip('L')
157 s = "0"*(2*length - len(s)) + s
158 return s.decode('hex')[::-1].encode('hex')
162 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
163 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
167 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
168 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
169 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
170 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
171 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
172 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
173 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
174 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
175 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
176 oid_secp256k1 = (1,3,132,0,10)
177 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
181 out = re.sub('( [^\n]*|)\n','',s)
182 out = out.replace(' ','')
183 out = out.replace('\n','')
186 def raw_tx( inputs, outputs, for_sig = None ):
187 s = int_to_hex(1,4) + ' version\n'
188 s += int_to_hex( len(inputs) ) + ' number of inputs\n'
189 for i in range(len(inputs)):
190 _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
191 s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n'
192 s += int_to_hex(p_index,4) + ' prev index\n'
194 sig = sig + chr(1) # hashtype
195 script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig)
196 script += sig.encode('hex') + ' sig\n'
197 pubkey = chr(4) + pubkey
198 script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey)
199 script += pubkey.encode('hex') + ' pubkey\n'
201 script = p_script + ' scriptsig \n'
204 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
206 s += "ffffffff" + ' sequence\n'
207 s += int_to_hex( len(outputs) ) + ' number of outputs\n'
208 for output in outputs:
209 addr, amount = output
210 s += int_to_hex( amount, 8) + ' amount: %d\n'%amount
211 script = '76a9' # op_dup, op_hash_160
212 script += '14' # push 0x14 bytes
213 script += bc_address_to_hash_160(addr).encode('hex')
214 script += '88ac' # op_equalverify, op_checksig
215 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
216 s += script + ' script \n'
217 s += int_to_hex(0,4) # lock time
218 if for_sig is not None: s += int_to_hex(1, 4) # hash type
224 def format_satoshis(x, is_diff=False, num_zeros = 0):
225 from decimal import Decimal
227 sign, digits, exp = s.as_tuple()
228 digits = map(str, digits)
229 while len(digits) < 9:
231 digits.insert(-8,'.')
232 s = ''.join(digits).rstrip('0')
239 s += "0"*( 1 + num_zeros - ( len(s) - p ))
240 s += " "*( 9 - ( len(s) - p ))
241 s = " "*( 5 - ( p )) + s
245 from version import ELECTRUM_VERSION, SEED_VERSION
246 from interface import DEFAULT_SERVERS
252 def __init__(self, gui_callback = lambda: None):
254 self.electrum_version = ELECTRUM_VERSION
255 self.seed_version = SEED_VERSION
256 self.gui_callback = gui_callback
258 self.gap_limit = 5 # configuration
259 self.use_change = True
262 self.master_public_key = ''
265 self.use_encryption = False
266 self.addresses = [] # receiving addresses visible for user
267 self.change_addresses = [] # addresses used as change
268 self.seed = '' # encrypted
270 self.labels = {} # labels for addresses and transactions
271 self.aliases = {} # aliases for addresses
272 self.authorities = {} # trusted addresses
273 self.frozen_addresses = []
274 self.prioritized_addresses = []
275 self.expert_mode = False
277 self.receipts = {} # signed URIs
278 self.receipt = None # next receipt
279 self.addressbook = [] # outgoing addresses, for payments
284 self.imported_keys = {}
285 self.remote_url = None
287 self.was_updated = True
291 # there is a difference between self.up_to_date and self.is_up_to_date()
292 # self.is_up_to_date() returns true when all requests have been answered and processed
293 # self.up_to_date is true when the wallet is synchronized (stronger requirement)
294 self.up_to_date_event = threading.Event()
295 self.up_to_date_event.clear()
296 self.up_to_date = False
297 self.lock = threading.Lock()
298 self.tx_event = threading.Event()
300 self.pick_random_server()
304 def pick_random_server(self):
305 self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
307 def is_up_to_date(self):
308 return self.interface.responses.empty() and not self.interface.unanswered_requests
310 def set_server(self, server):
311 # raise an error if the format isnt correct
312 a,b,c = server.split(':')
314 assert c in ['t','h','n']
316 if server != self.server:
319 self.interface.is_connected = False # this exits the polling loop
320 self.interface.poke()
322 def set_path(self, wallet_path):
324 if wallet_path is not None:
325 self.path = wallet_path
327 # backward compatibility: look for wallet file in the default data directory
328 if "HOME" in os.environ:
329 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
330 elif "LOCALAPPDATA" in os.environ:
331 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
332 elif "APPDATA" in os.environ:
333 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
335 raise BaseException("No home directory found in environment variables.")
337 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
338 self.path = os.path.join( wallet_dir, 'electrum.dat' )
340 def import_key(self, keypair, password):
341 address, key = keypair.split(':')
342 if not self.is_valid(address):
343 raise BaseException('Invalid Bitcoin address')
344 if address in self.all_addresses():
345 raise BaseException('Address already in wallet')
346 b = ASecretToSecret( key )
348 raise BaseException('Unsupported key format')
349 secexp = int( b.encode('hex'), 16)
350 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
352 public_key = private_key.get_verifying_key()
353 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ):
354 raise BaseException('Address does not match private key')
355 self.imported_keys[address] = self.pw_encode( key, password )
357 def new_seed(self, password):
358 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
361 self.seed = self.pw_encode( seed, password )
364 def init_mpk(self,seed):
367 secexp = self.stretch_key(seed)
368 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
369 self.master_public_key = master_private_key.get_verifying_key().to_string()
371 def all_addresses(self):
372 return self.addresses + self.change_addresses + self.imported_keys.keys()
374 def is_mine(self, address):
375 return address in self.all_addresses()
377 def is_change(self, address):
378 return address in self.change_addresses
380 def is_valid(self,addr):
381 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
382 if not ADDRESS_RE.match(addr): return False
384 h = bc_address_to_hash_160(addr)
387 return addr == hash_160_to_bc_address(h)
389 def stretch_key(self,seed):
391 for i in range(100000):
392 seed = hashlib.sha256(seed + oldseed).digest()
393 return string_to_number( seed )
395 def get_sequence(self,n,for_change):
396 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
398 def get_private_key_base58(self, address, password):
399 pk = self.get_private_key(address, password)
400 if pk is None: return None
401 return SecretToASecret( pk )
403 def get_private_key(self, address, password):
404 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
405 order = generator_secp256k1.order()
407 if address in self.imported_keys.keys():
408 b = self.pw_decode( self.imported_keys[address], password )
409 if not b: return None
410 b = ASecretToSecret( b )
411 secexp = int( b.encode('hex'), 16)
413 if address in self.addresses:
414 n = self.addresses.index(address)
416 elif address in self.change_addresses:
417 n = self.change_addresses.index(address)
420 raise BaseException("unknown address")
422 seed = self.pw_decode( self.seed, password)
424 raise BaseException("Invalid password")
425 if not seed: return None
426 secexp = self.stretch_key(seed)
427 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
429 pk = number_to_string(secexp,order)
432 def msg_magic(self, message):
433 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
435 def sign_message(self, address, message, password):
436 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
437 public_key = private_key.get_verifying_key()
438 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
439 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
441 sig = base64.b64encode( chr(27+i) + signature )
443 self.verify_message( address, sig, message)
448 raise BaseException("error: cannot sign message")
451 def verify_message(self, address, signature, message):
452 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
453 from ecdsa import numbertheory, ellipticcurve, util
455 curve = curve_secp256k1
456 G = generator_secp256k1
458 # extract r,s from signature
459 sig = base64.b64decode(signature)
460 if len(sig) != 65: raise BaseException("Wrong encoding")
461 r,s = util.sigdecode_string(sig[1:], order)
463 if nV < 27 or nV >= 35:
464 raise BaseException("Bad encoding")
473 x = r + (recid/2) * order
475 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
476 beta = msqr.modular_sqrt(alpha, curve.p())
477 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
478 # 1.4 the constructor checks that nR is at infinity
479 R = ellipticcurve.Point(curve, x, y, order)
480 # 1.5 compute e from message:
481 h = Hash( self.msg_magic( message ) )
482 e = string_to_number(h)
484 # 1.6 compute Q = r^-1 (sR - eG)
485 inv_r = numbertheory.inverse_mod(r,order)
486 Q = inv_r * ( s * R + minus_e * G )
487 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
488 # check that Q is the public key
489 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
490 # check that we get the original signing address
491 addr = public_key_to_bc_address( encode_point(public_key, compressed) )
493 raise BaseException("Bad signature")
496 def create_new_address(self, for_change):
497 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
499 n = len(self.change_addresses) if for_change else len(self.addresses)
500 z = self.get_sequence(n,for_change)
501 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
502 pubkey_point = master_public_key.pubkey.point + z*curve.generator
503 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
504 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
506 self.change_addresses.append(address)
508 self.addresses.append(address)
510 self.history[address] = []
515 def change_gap_limit(self, value):
516 if value >= self.gap_limit:
517 self.gap_limit = value
519 self.interface.poke()
522 elif value >= self.min_acceptable_gap():
523 k = self.num_unused_trailing_addresses()
524 n = len(self.addresses) - k + value
525 self.addresses = self.addresses[0:n]
526 self.gap_limit = value
532 def num_unused_trailing_addresses(self):
534 for a in self.addresses[::-1]:
535 if self.history.get(a):break
539 def min_acceptable_gap(self):
540 # fixme: this assumes wallet is synchronized
543 k = self.num_unused_trailing_addresses()
544 for a in self.addresses[0:-k]:
545 if self.history.get(a):
549 if n > nmax: nmax = n
553 def synchronize(self):
554 if not self.master_public_key:
559 if self.change_addresses == []:
560 new_addresses.append( self.create_new_address(True) )
562 a = self.change_addresses[-1]
563 if self.history.get(a):
564 new_addresses.append( self.create_new_address(True) )
570 if len(self.addresses) < n:
571 new_addresses.append( self.create_new_address(False) )
573 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
576 new_addresses.append( self.create_new_address(False) )
579 num = self.get_remote_number()
580 while len(self.addresses)<num:
581 new_addresses.append( self.create_new_address(False) )
586 def get_remote_number(self):
588 server = jsonrpclib.Server(self.remote_url)
589 out = server.getnum()
592 def get_remote_mpk(self):
594 server = jsonrpclib.Server(self.remote_url)
595 out = server.getkey()
599 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
601 def fill_addressbook(self):
602 for tx in self.tx_history.values():
604 for i in tx['outputs']:
605 if not self.is_mine(i) and i not in self.addressbook:
606 self.addressbook.append(i)
608 self.update_tx_labels()
613 'seed_version':self.seed_version,
614 'use_encryption':self.use_encryption,
615 'use_change':self.use_change,
616 'master_public_key': self.master_public_key.encode('hex'),
618 'server':self.server,
620 'addresses':self.addresses,
621 'change_addresses':self.change_addresses,
622 'history':self.history,
623 'labels':self.labels,
624 'contacts':self.addressbook,
625 'imported_keys':self.imported_keys,
626 'aliases':self.aliases,
627 'authorities':self.authorities,
628 'receipts':self.receipts,
629 'num_zeros':self.num_zeros,
630 'frozen_addresses':self.frozen_addresses,
631 'prioritized_addresses':self.prioritized_addresses,
632 'expert_mode':self.expert_mode,
633 'gap_limit':self.gap_limit,
635 f = open(self.path,"w")
639 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
644 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
645 self.file_exists = False
647 f = open(self.path,"r")
653 d = ast.literal_eval( data )
654 interface.old_to_new(d)
655 self.seed_version = d.get('seed_version')
656 self.master_public_key = d.get('master_public_key').decode('hex')
657 self.use_encryption = d.get('use_encryption')
658 self.use_change = bool(d.get('use_change',True))
659 self.fee = int( d.get('fee') )
660 self.seed = d.get('seed')
661 self.server = d.get('server')
662 #blocks = d.get('blocks')
663 self.addresses = d.get('addresses')
664 self.change_addresses = d.get('change_addresses')
665 self.history = d.get('history')
666 self.labels = d.get('labels')
667 self.addressbook = d.get('contacts')
668 self.imported_keys = d.get('imported_keys',{})
669 self.aliases = d.get('aliases',{})
670 self.authorities = d.get('authorities',{})
671 self.receipts = d.get('receipts',{})
672 self.num_zeros = d.get('num_zeros',0)
673 self.frozen_addresses = d.get('frozen_addresses',[])
674 self.prioritized_addresses = d.get('prioritized_addresses',[])
675 self.expert_mode = d.get('expert_mode',False)
676 self.gap_limit = d.get('gap_limit',5)
678 raise BaseException("cannot read wallet file")
680 self.update_tx_history()
682 if self.seed_version != SEED_VERSION:
683 raise BaseException(upgrade_msg)
685 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
687 self.file_exists = True
690 def get_address_flags(self, addr):
691 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
692 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
696 def get_addr_balance(self, addr):
697 assert self.is_mine(addr)
698 h = self.history.get(addr,[])
708 def get_balance(self):
710 for addr in self.all_addresses():
711 c, u = self.get_addr_balance(addr)
717 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
718 """ todo: minimize tx size """
720 fee = self.fee if fixed_fee is None else fixed_fee
723 prioritized_coins = []
724 domain = [from_addr] if from_addr else self.all_addresses()
725 for i in self.frozen_addresses:
726 if i in domain: domain.remove(i)
728 for i in self.prioritized_addresses:
729 if i in domain: domain.remove(i)
732 h = self.history.get(addr)
733 if h is None: continue
735 if item.get('raw_output_script'):
736 coins.append( (addr,item))
738 coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
740 for addr in self.prioritized_addresses:
741 h = self.history.get(addr)
742 if h is None: continue
744 if item.get('raw_output_script'):
745 prioritized_coins.append( (addr,item))
747 prioritized_coins = sorted( prioritized_coins, key = lambda x: x[1]['timestamp'] )
750 coins = prioritized_coins + coins
754 v = item.get('value')
756 inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
757 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
758 if total >= amount + fee: break
760 #print "not enough funds: %s %s"%(format_satoshis(total), format_satoshis(fee))
762 return inputs, total, fee
764 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
765 outputs = [ (to_addr, amount) ]
766 change_amount = total - ( amount + fee )
767 if change_amount != 0:
768 # normally, the update thread should ensure that the last change address is unused
770 change_addr = self.change_addresses[-1]
771 outputs.append( ( change_addr, change_amount) )
774 def sign_inputs( self, inputs, outputs, password ):
776 for i in range(len(inputs)):
777 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
778 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
779 public_key = private_key.get_verifying_key()
780 pubkey = public_key.to_string()
781 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
782 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
783 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
784 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
787 def pw_encode(self, s, password):
789 secret = Hash(password)
790 return EncodeAES(secret, s)
794 def pw_decode(self, s, password):
795 if password is not None:
796 secret = Hash(password)
797 d = DecodeAES(secret, s)
802 raise BaseException("Invalid password")
807 def get_status(self, address):
808 h = self.history.get(address)
813 status = lastpoint['block_hash']
814 if status == 'mempool':
815 status = status + ':%d'% len(h)
818 def receive_status_callback(self, addr, status):
820 if self.get_status(addr) != status:
821 #print "updating status for", addr, status
822 self.interface.get_history(addr)
824 def receive_history_callback(self, addr, data):
825 #print "updating history for", addr
827 self.history[addr] = data
828 self.update_tx_history()
831 def get_tx_history(self):
832 lines = self.tx_history.values()
833 lines = sorted(lines, key=operator.itemgetter("timestamp"))
836 def update_tx_history(self):
838 for addr in self.all_addresses():
839 h = self.history.get(addr)
840 if h is None: continue
842 tx_hash = tx['tx_hash']
843 line = self.tx_history.get(tx_hash)
845 self.tx_history[tx_hash] = copy.copy(tx)
846 line = self.tx_history.get(tx_hash)
848 line['value'] += tx['value']
849 if line['height'] == 0:
850 line['timestamp'] = 1e12
851 self.update_tx_labels()
853 def update_tx_labels(self):
854 for tx in self.tx_history.values():
857 for o_addr in tx['outputs']:
858 if not self.is_mine(o_addr):
859 dest_label = self.labels.get(o_addr)
861 default_label = 'to: ' + dest_label
863 default_label = 'to: ' + o_addr
865 for o_addr in tx['outputs']:
866 if self.is_mine(o_addr) and not self.is_change(o_addr):
869 for o_addr in tx['outputs']:
870 if self.is_mine(o_addr):
876 dest_label = self.labels.get(o_addr)
878 default_label = 'at: ' + dest_label
880 default_label = 'at: ' + o_addr
882 tx['default_label'] = default_label
884 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
885 if not self.is_valid(to_address):
886 raise BaseException("Invalid address")
887 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
889 raise BaseException("Not enough funds")
891 if not self.use_change and not change_addr:
892 change_addr = inputs[0][0]
893 print "sending change to", change_addr
895 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
896 s_inputs = self.sign_inputs( inputs, outputs, password )
898 tx = filter( raw_tx( s_inputs, outputs ) )
899 if to_address not in self.addressbook:
900 self.addressbook.append(to_address)
902 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
903 self.labels[tx_hash] = label
907 def sendtx(self, tx):
908 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
909 self.tx_event.clear()
910 self.interface.send([('blockchain.transaction.broadcast', [tx])])
914 return False, "error: " + out
916 self.receipts[tx_hash] = self.receipt
921 def read_alias(self, alias):
922 # this might not be the right place for this function.
925 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
926 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
928 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
930 url = 'http://' + alias + '/bitcoin.id'
934 lines = urllib.urlopen(url).readlines()
939 line = lines[0].strip().split(':')
942 target = signing_addr = line[0]
944 target, auth_name, signing_addr, signature = line
945 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
947 self.verify_message(signing_addr, signature, msg)
949 # other lines are signed updates
950 for line in lines[1:]:
952 if not line: continue
953 line = line.split(':')
956 target, signature = line
957 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
959 if not self.is_valid(target):
960 raise BaseException("Invalid bitcoin address")
962 return target, signing_addr, auth_name
964 def update_password(self, seed, old_password, new_password):
965 if new_password == '': new_password = None
966 self.use_encryption = (new_password != None)
967 self.seed = self.pw_encode( seed, new_password)
968 for k in self.imported_keys.keys():
969 a = self.imported_keys[k]
970 b = self.pw_decode(a, old_password)
971 c = self.pw_encode(b, new_password)
972 self.imported_keys[k] = c
975 def get_alias(self, alias, interactive = False, show_message=None, question = None):
977 target, signing_address, auth_name = self.read_alias(alias)
978 except BaseException, e:
979 # raise exception if verify fails (verify the chain)
981 show_message("Alias error: " + str(e))
984 print target, signing_address, auth_name
986 if auth_name is None:
987 a = self.aliases.get(alias)
989 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)
990 if interactive and question( msg ):
991 self.aliases[alias] = (signing_address, target)
995 if signing_address != a[0]:
996 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
997 if interactive and question( msg ):
998 self.aliases[alias] = (signing_address, target)
1002 if signing_address not in self.authorities.keys():
1003 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)
1004 if interactive and question( msg ):
1005 self.authorities[signing_address] = auth_name
1010 self.aliases[alias] = (signing_address, target)
1015 def parse_url(self, url, show_message, question):
1016 o = url[8:].split('?')
1019 params = o[1].split('&')
1023 amount = label = message = signature = identity = ''
1027 if k == 'amount': amount = uv
1028 elif k == 'message': message = uv
1029 elif k == 'label': label = uv
1030 elif k == 'signature':
1031 identity, signature = uv.split(':')
1032 url = url.replace('&%s=%s'%(k,v),'')
1036 if label and self.labels.get(address) != label:
1037 if question('Give label "%s" to address %s ?'%(label,address)):
1038 if address not in self.addressbook and address not in self.all_addresses():
1039 self.addressbook.append(address)
1040 self.labels[address] = label
1043 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
1044 signing_address = self.get_alias(identity, True, show_message, question)
1045 elif self.is_valid(identity):
1046 signing_address = identity
1048 signing_address = None
1049 if not signing_address:
1052 self.verify_message(signing_address, signature, url )
1053 self.receipt = (signing_address, signature, url)
1055 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
1056 address = amount = label = identity = message = ''
1058 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
1059 payto_address = self.get_alias(address, True, show_message, question)
1061 address = address + ' <' + payto_address + '>'
1063 return address, amount, label, message, signature, identity, url
1067 self.interface.poke()
1068 self.up_to_date_event.wait(10000000000)
1071 def start_session(self, interface):
1072 self.interface = interface
1073 self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
1074 self.interface.subscribe(self.all_addresses())
1077 def freeze(self,addr):
1078 if addr in self.all_addresses() and addr not in self.frozen_addresses:
1079 self.unprioritize(addr)
1080 self.frozen_addresses.append(addr)
1086 def unfreeze(self,addr):
1087 if addr in self.all_addresses() and addr in self.frozen_addresses:
1088 self.frozen_addresses.remove(addr)
1094 def prioritize(self,addr):
1095 if addr in self.all_addresses() and addr not in self.prioritized_addresses:
1097 self.prioritized_addresses.append(addr)
1103 def unprioritize(self,addr):
1104 if addr in self.all_addresses() and addr in self.prioritized_addresses:
1105 self.prioritized_addresses.remove(addr)