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
254 self.electrum_version = ELECTRUM_VERSION
255 self.seed_version = SEED_VERSION
256 self.update_callbacks = []
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
280 self.debug_server = False # write server communication debug info to stdout
285 self.imported_keys = {}
286 self.remote_url = None
288 self.was_updated = True
292 # there is a difference between self.up_to_date and self.is_up_to_date()
293 # self.is_up_to_date() returns true when all requests have been answered and processed
294 # self.up_to_date is true when the wallet is synchronized (stronger requirement)
295 self.up_to_date_event = threading.Event()
296 self.up_to_date_event.clear()
297 self.up_to_date = False
298 self.lock = threading.Lock()
299 self.tx_event = threading.Event()
301 self.pick_random_server()
303 def register_callback(self, update_callback):
305 self.update_callbacks.append(update_callback)
307 def trigger_callbacks(self):
309 callbacks = self.update_callbacks[:]
310 [update() for update in callbacks]
312 def pick_random_server(self):
313 self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created
315 def is_up_to_date(self):
316 return self.interface.responses.empty() and not self.interface.unanswered_requests
318 def set_server(self, server):
319 # raise an error if the format isnt correct
320 a,b,c = server.split(':')
322 assert c in ['t','h','n']
324 if server != self.server:
327 self.interface.is_connected = False # this exits the polling loop
328 self.interface.poke()
330 def set_path(self, wallet_path):
332 if wallet_path is not None:
333 self.path = wallet_path
335 # backward compatibility: look for wallet file in the default data directory
336 if "HOME" in os.environ:
337 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
338 elif "LOCALAPPDATA" in os.environ:
339 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
340 elif "APPDATA" in os.environ:
341 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
343 raise BaseException("No home directory found in environment variables.")
345 if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
346 self.path = os.path.join( wallet_dir, 'electrum.dat' )
348 def import_key(self, keypair, password):
349 address, key = keypair.split(':')
350 if not self.is_valid(address):
351 raise BaseException('Invalid Bitcoin address')
352 if address in self.all_addresses():
353 raise BaseException('Address already in wallet')
354 b = ASecretToSecret( key )
356 raise BaseException('Unsupported key format')
357 secexp = int( b.encode('hex'), 16)
358 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
360 public_key = private_key.get_verifying_key()
361 if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ):
362 raise BaseException('Address does not match private key')
363 self.imported_keys[address] = self.pw_encode( key, password )
365 def new_seed(self, password):
366 seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
369 self.seed = self.pw_encode( seed, password )
372 def init_mpk(self,seed):
375 secexp = self.stretch_key(seed)
376 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
377 self.master_public_key = master_private_key.get_verifying_key().to_string()
379 def all_addresses(self):
380 return self.addresses + self.change_addresses + self.imported_keys.keys()
382 def is_mine(self, address):
383 return address in self.all_addresses()
385 def is_change(self, address):
386 return address in self.change_addresses
388 def is_valid(self,addr):
389 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
390 if not ADDRESS_RE.match(addr): return False
392 h = bc_address_to_hash_160(addr)
395 return addr == hash_160_to_bc_address(h)
397 def stretch_key(self,seed):
399 for i in range(100000):
400 seed = hashlib.sha256(seed + oldseed).digest()
401 return string_to_number( seed )
403 def get_sequence(self,n,for_change):
404 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
406 def get_private_key_base58(self, address, password):
407 pk = self.get_private_key(address, password)
408 if pk is None: return None
409 return SecretToASecret( pk )
411 def get_private_key(self, address, password):
412 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
413 order = generator_secp256k1.order()
415 if address in self.imported_keys.keys():
416 b = self.pw_decode( self.imported_keys[address], password )
417 if not b: return None
418 b = ASecretToSecret( b )
419 secexp = int( b.encode('hex'), 16)
421 if address in self.addresses:
422 n = self.addresses.index(address)
424 elif address in self.change_addresses:
425 n = self.change_addresses.index(address)
428 raise BaseException("unknown address")
430 seed = self.pw_decode( self.seed, password)
432 raise BaseException("Invalid password")
433 if not seed: return None
434 secexp = self.stretch_key(seed)
435 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
437 pk = number_to_string(secexp,order)
440 def msg_magic(self, message):
441 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
443 def sign_message(self, address, message, password):
444 private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
445 public_key = private_key.get_verifying_key()
446 signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
447 assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
449 sig = base64.b64encode( chr(27+i) + signature )
451 self.verify_message( address, sig, message)
456 raise BaseException("error: cannot sign message")
459 def verify_message(self, address, signature, message):
460 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
461 from ecdsa import numbertheory, ellipticcurve, util
463 curve = curve_secp256k1
464 G = generator_secp256k1
466 # extract r,s from signature
467 sig = base64.b64decode(signature)
468 if len(sig) != 65: raise BaseException("Wrong encoding")
469 r,s = util.sigdecode_string(sig[1:], order)
471 if nV < 27 or nV >= 35:
472 raise BaseException("Bad encoding")
481 x = r + (recid/2) * order
483 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
484 beta = msqr.modular_sqrt(alpha, curve.p())
485 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
486 # 1.4 the constructor checks that nR is at infinity
487 R = ellipticcurve.Point(curve, x, y, order)
488 # 1.5 compute e from message:
489 h = Hash( self.msg_magic( message ) )
490 e = string_to_number(h)
492 # 1.6 compute Q = r^-1 (sR - eG)
493 inv_r = numbertheory.inverse_mod(r,order)
494 Q = inv_r * ( s * R + minus_e * G )
495 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
496 # check that Q is the public key
497 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
498 # check that we get the original signing address
499 addr = public_key_to_bc_address( encode_point(public_key, compressed) )
501 raise BaseException("Bad signature")
504 def create_new_address(self, for_change):
505 """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """
507 n = len(self.change_addresses) if for_change else len(self.addresses)
508 z = self.get_sequence(n,for_change)
509 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
510 pubkey_point = master_public_key.pubkey.point + z*curve.generator
511 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
512 address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
514 self.change_addresses.append(address)
516 self.addresses.append(address)
518 self.history[address] = []
523 def change_gap_limit(self, value):
524 if value >= self.gap_limit:
525 self.gap_limit = value
527 self.interface.poke()
530 elif value >= self.min_acceptable_gap():
531 k = self.num_unused_trailing_addresses()
532 n = len(self.addresses) - k + value
533 self.addresses = self.addresses[0:n]
534 self.gap_limit = value
540 def num_unused_trailing_addresses(self):
542 for a in self.addresses[::-1]:
543 if self.history.get(a):break
547 def min_acceptable_gap(self):
548 # fixme: this assumes wallet is synchronized
551 k = self.num_unused_trailing_addresses()
552 for a in self.addresses[0:-k]:
553 if self.history.get(a):
557 if n > nmax: nmax = n
561 def synchronize(self):
562 if not self.master_public_key:
567 if self.change_addresses == []:
568 new_addresses.append( self.create_new_address(True) )
570 a = self.change_addresses[-1]
571 if self.history.get(a):
572 new_addresses.append( self.create_new_address(True) )
578 if len(self.addresses) < n:
579 new_addresses.append( self.create_new_address(False) )
581 if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
584 new_addresses.append( self.create_new_address(False) )
587 num = self.get_remote_number()
588 while len(self.addresses)<num:
589 new_addresses.append( self.create_new_address(False) )
594 def get_remote_number(self):
596 server = jsonrpclib.Server(self.remote_url)
597 out = server.getnum()
600 def get_remote_mpk(self):
602 server = jsonrpclib.Server(self.remote_url)
603 out = server.getkey()
607 return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
609 def fill_addressbook(self):
610 for tx in self.tx_history.values():
612 for i in tx['outputs']:
613 if not self.is_mine(i) and i not in self.addressbook:
614 self.addressbook.append(i)
616 self.update_tx_labels()
621 'seed_version':self.seed_version,
622 'use_encryption':self.use_encryption,
623 'use_change':self.use_change,
624 'master_public_key': self.master_public_key.encode('hex'),
626 'server':self.server,
628 'addresses':self.addresses,
629 'change_addresses':self.change_addresses,
630 'history':self.history,
631 'labels':self.labels,
632 'contacts':self.addressbook,
633 'imported_keys':self.imported_keys,
634 'aliases':self.aliases,
635 'authorities':self.authorities,
636 'receipts':self.receipts,
637 'num_zeros':self.num_zeros,
638 'frozen_addresses':self.frozen_addresses,
639 'prioritized_addresses':self.prioritized_addresses,
640 'expert_mode':self.expert_mode,
641 'gap_limit':self.gap_limit,
642 'debug_server':self.debug_server,
644 f = open(self.path,"w")
648 os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
653 upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
654 self.file_exists = False
656 f = open(self.path,"r")
662 d = ast.literal_eval( data )
663 interface.old_to_new(d)
664 self.seed_version = d.get('seed_version')
665 self.master_public_key = d.get('master_public_key').decode('hex')
666 self.use_encryption = d.get('use_encryption')
667 self.use_change = bool(d.get('use_change',True))
668 self.fee = int( d.get('fee') )
669 self.seed = d.get('seed')
670 self.server = d.get('server')
671 #blocks = d.get('blocks')
672 self.addresses = d.get('addresses')
673 self.change_addresses = d.get('change_addresses')
674 self.history = d.get('history')
675 self.labels = d.get('labels')
676 self.addressbook = d.get('contacts')
677 self.imported_keys = d.get('imported_keys',{})
678 self.aliases = d.get('aliases',{})
679 self.authorities = d.get('authorities',{})
680 self.receipts = d.get('receipts',{})
681 self.num_zeros = d.get('num_zeros',0)
682 self.frozen_addresses = d.get('frozen_addresses',[])
683 self.prioritized_addresses = d.get('prioritized_addresses',[])
684 self.expert_mode = d.get('expert_mode',False)
685 self.gap_limit = d.get('gap_limit',5)
686 self.debug_server = d.get('debug_server',False)
688 raise BaseException("cannot read wallet file")
690 self.update_tx_history()
692 if self.seed_version != SEED_VERSION:
693 raise BaseException(upgrade_msg)
695 if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
697 self.file_exists = True
700 def get_address_flags(self, addr):
701 flags = "C" if self.is_change(addr) else "I" if addr in self.imported_keys.keys() else "-"
702 flags += "F" if addr in self.frozen_addresses else "P" if addr in self.prioritized_addresses else "-"
706 def get_addr_balance(self, addr):
707 assert self.is_mine(addr)
708 h = self.history.get(addr,[])
718 def get_balance(self):
720 for addr in self.all_addresses():
721 c, u = self.get_addr_balance(addr)
727 def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
728 """ todo: minimize tx size """
730 fee = self.fee if fixed_fee is None else fixed_fee
733 prioritized_coins = []
734 domain = [from_addr] if from_addr else self.all_addresses()
735 for i in self.frozen_addresses:
736 if i in domain: domain.remove(i)
738 for i in self.prioritized_addresses:
739 if i in domain: domain.remove(i)
742 h = self.history.get(addr)
743 if h is None: continue
745 if item.get('raw_output_script'):
746 coins.append( (addr,item))
748 coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
750 for addr in self.prioritized_addresses:
751 h = self.history.get(addr)
752 if h is None: continue
754 if item.get('raw_output_script'):
755 prioritized_coins.append( (addr,item))
757 prioritized_coins = sorted( prioritized_coins, key = lambda x: x[1]['timestamp'] )
760 coins = prioritized_coins + coins
764 v = item.get('value')
766 inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
767 fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
768 if total >= amount + fee: break
770 #print "not enough funds: %s %s"%(format_satoshis(total), format_satoshis(fee))
772 return inputs, total, fee
774 def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
775 outputs = [ (to_addr, amount) ]
776 change_amount = total - ( amount + fee )
777 if change_amount != 0:
778 # normally, the update thread should ensure that the last change address is unused
780 change_addr = self.change_addresses[-1]
781 outputs.append( ( change_addr, change_amount) )
784 def sign_inputs( self, inputs, outputs, password ):
786 for i in range(len(inputs)):
787 addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
788 private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
789 public_key = private_key.get_verifying_key()
790 pubkey = public_key.to_string()
791 tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
792 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
793 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
794 s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
797 def pw_encode(self, s, password):
799 secret = Hash(password)
800 return EncodeAES(secret, s)
804 def pw_decode(self, s, password):
805 if password is not None:
806 secret = Hash(password)
807 d = DecodeAES(secret, s)
812 raise BaseException("Invalid password")
817 def get_status(self, address):
818 h = self.history.get(address)
823 status = lastpoint['block_hash']
824 if status == 'mempool':
825 status = status + ':%d'% len(h)
828 def receive_status_callback(self, addr, status):
830 if self.get_status(addr) != status:
831 #print "updating status for", addr, status
832 self.interface.get_history(addr)
834 def receive_history_callback(self, addr, data):
835 #print "updating history for", addr
837 self.history[addr] = data
838 self.update_tx_history()
841 def get_tx_history(self):
842 lines = self.tx_history.values()
843 lines = sorted(lines, key=operator.itemgetter("timestamp"))
846 def update_tx_history(self):
848 for addr in self.all_addresses():
849 h = self.history.get(addr)
850 if h is None: continue
852 tx_hash = tx['tx_hash']
853 line = self.tx_history.get(tx_hash)
855 self.tx_history[tx_hash] = copy.copy(tx)
856 line = self.tx_history.get(tx_hash)
858 line['value'] += tx['value']
859 if line['height'] == 0:
860 line['timestamp'] = 1e12
861 self.update_tx_labels()
863 def update_tx_labels(self):
864 for tx in self.tx_history.values():
867 for o_addr in tx['outputs']:
868 if not self.is_mine(o_addr):
869 dest_label = self.labels.get(o_addr)
871 default_label = 'to: ' + dest_label
873 default_label = 'to: ' + o_addr
875 for o_addr in tx['outputs']:
876 if self.is_mine(o_addr) and not self.is_change(o_addr):
879 for o_addr in tx['outputs']:
880 if self.is_mine(o_addr):
886 dest_label = self.labels.get(o_addr)
888 default_label = 'at: ' + dest_label
890 default_label = 'at: ' + o_addr
892 tx['default_label'] = default_label
894 def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
895 if not self.is_valid(to_address):
896 raise BaseException("Invalid address")
897 inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
899 raise BaseException("Not enough funds")
901 if not self.use_change and not change_addr:
902 change_addr = inputs[0][0]
903 print "sending change to", change_addr
905 outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
906 s_inputs = self.sign_inputs( inputs, outputs, password )
908 tx = filter( raw_tx( s_inputs, outputs ) )
909 if to_address not in self.addressbook:
910 self.addressbook.append(to_address)
912 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
913 self.labels[tx_hash] = label
917 def sendtx(self, tx):
918 tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
919 self.tx_event.clear()
920 self.interface.send([('blockchain.transaction.broadcast', [tx])])
924 return False, "error: " + out
926 self.receipts[tx_hash] = self.receipt
931 def read_alias(self, alias):
932 # this might not be the right place for this function.
935 m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
936 m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
938 url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1)
940 url = 'http://' + alias + '/bitcoin.id'
944 lines = urllib.urlopen(url).readlines()
949 line = lines[0].strip().split(':')
952 target = signing_addr = line[0]
954 target, auth_name, signing_addr, signature = line
955 msg = "alias:%s:%s:%s"%(alias,target,auth_name)
957 self.verify_message(signing_addr, signature, msg)
959 # other lines are signed updates
960 for line in lines[1:]:
962 if not line: continue
963 line = line.split(':')
966 target, signature = line
967 self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
969 if not self.is_valid(target):
970 raise BaseException("Invalid bitcoin address")
972 return target, signing_addr, auth_name
974 def update_password(self, seed, old_password, new_password):
975 if new_password == '': new_password = None
976 self.use_encryption = (new_password != None)
977 self.seed = self.pw_encode( seed, new_password)
978 for k in self.imported_keys.keys():
979 a = self.imported_keys[k]
980 b = self.pw_decode(a, old_password)
981 c = self.pw_encode(b, new_password)
982 self.imported_keys[k] = c
985 def get_alias(self, alias, interactive = False, show_message=None, question = None):
987 target, signing_address, auth_name = self.read_alias(alias)
988 except BaseException, e:
989 # raise exception if verify fails (verify the chain)
991 show_message("Alias error: " + str(e))
994 print target, signing_address, auth_name
996 if auth_name is None:
997 a = self.aliases.get(alias)
999 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)
1000 if interactive and question( msg ):
1001 self.aliases[alias] = (signing_address, target)
1005 if signing_address != a[0]:
1006 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
1007 if interactive and question( msg ):
1008 self.aliases[alias] = (signing_address, target)
1012 if signing_address not in self.authorities.keys():
1013 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)
1014 if interactive and question( msg ):
1015 self.authorities[signing_address] = auth_name
1020 self.aliases[alias] = (signing_address, target)
1025 def parse_url(self, url, show_message, question):
1026 o = url[8:].split('?')
1029 params = o[1].split('&')
1033 amount = label = message = signature = identity = ''
1037 if k == 'amount': amount = uv
1038 elif k == 'message': message = uv
1039 elif k == 'label': label = uv
1040 elif k == 'signature':
1041 identity, signature = uv.split(':')
1042 url = url.replace('&%s=%s'%(k,v),'')
1046 if label and self.labels.get(address) != label:
1047 if question('Give label "%s" to address %s ?'%(label,address)):
1048 if address not in self.addressbook and address not in self.all_addresses():
1049 self.addressbook.append(address)
1050 self.labels[address] = label
1053 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
1054 signing_address = self.get_alias(identity, True, show_message, question)
1055 elif self.is_valid(identity):
1056 signing_address = identity
1058 signing_address = None
1059 if not signing_address:
1062 self.verify_message(signing_address, signature, url )
1063 self.receipt = (signing_address, signature, url)
1065 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
1066 address = amount = label = identity = message = ''
1068 if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
1069 payto_address = self.get_alias(address, True, show_message, question)
1071 address = address + ' <' + payto_address + '>'
1073 return address, amount, label, message, signature, identity, url
1077 self.interface.poke()
1078 self.up_to_date_event.wait(10000000000)
1081 def start_session(self, interface):
1082 self.interface = interface
1083 self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
1084 self.interface.subscribe(self.all_addresses())
1087 def freeze(self,addr):
1088 if addr in self.all_addresses() and addr not in self.frozen_addresses:
1089 self.unprioritize(addr)
1090 self.frozen_addresses.append(addr)
1096 def unfreeze(self,addr):
1097 if addr in self.all_addresses() and addr in self.frozen_addresses:
1098 self.frozen_addresses.remove(addr)
1104 def prioritize(self,addr):
1105 if addr in self.all_addresses() and addr not in self.prioritized_addresses:
1107 self.prioritized_addresses.append(addr)
1113 def unprioritize(self,addr):
1114 if addr in self.all_addresses() and addr in self.prioritized_addresses:
1115 self.prioritized_addresses.remove(addr)