X-Git-Url: https://git.novaco.in/?a=blobdiff_plain;f=lib%2Futil.py;h=e734341387cd0d905e11d25a01d2166e71f75b8d;hb=8ad7a5a08591a7306973660743e481f93cd80145;hp=91573271207b08ada950529dcdfc7c15cdfbb633;hpb=d2b86091b4a4f99e487f0c3e09661d9654725de7;p=electrum-nvc.git diff --git a/lib/util.py b/lib/util.py index 9157327..e734341 100644 --- a/lib/util.py +++ b/lib/util.py @@ -1,17 +1,28 @@ -import os, sys, re +import os, sys, re, json import platform import shutil from datetime import datetime -is_verbose = True +is_verbose = False +class MyEncoder(json.JSONEncoder): + def default(self, obj): + from transaction import Transaction + if isinstance(obj, Transaction): + return obj.as_dict() + return super(MyEncoder, self).default(obj) + def set_verbosity(b): global is_verbose is_verbose = b + def print_error(*args): if not is_verbose: return + print_stderr(*args) + +def print_stderr(*args): args = [str(item) for item in args] sys.stderr.write(" ".join(args) + "\n") sys.stderr.flush() @@ -23,25 +34,13 @@ def print_msg(*args): sys.stdout.flush() def print_json(obj): - import json - s = json.dumps(obj,sort_keys = True, indent = 4) + try: + s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder) + except TypeError: + s = repr(obj) sys.stdout.write(s + "\n") sys.stdout.flush() - -def check_windows_wallet_migration(): - if platform.release() != "XP": - if os.path.exists(os.path.join(os.environ["LOCALAPPDATA"], "Electrum")): - if os.path.exists(os.path.join(os.environ["APPDATA"], "Electrum")): - print_msg("Two Electrum folders have been found, the default Electrum location for Windows has changed from %s to %s since Electrum 1.7, please check your wallets and fix the problem manually." % (os.environ["LOCALAPPDATA"], os.environ["APPDATA"])) - sys.exit() - try: - shutil.move(os.path.join(os.environ["LOCALAPPDATA"], "Electrum"), os.path.join(os.environ["APPDATA"])) - print_msg("Your wallet has been moved from %s to %s."% (os.environ["LOCALAPPDATA"], os.environ["APPDATA"])) - except: - print_msg("Failed to move your wallet.") - - def user_dir(): if "HOME" in os.environ: return os.path.join(os.environ["HOME"], ".electrum") @@ -49,9 +48,11 @@ def user_dir(): return os.path.join(os.environ["APPDATA"], "Electrum") elif "LOCALAPPDATA" in os.environ: return os.path.join(os.environ["LOCALAPPDATA"], "Electrum") + elif 'ANDROID_DATA' in os.environ: + return "/sdcard/electrum/" else: - #raise BaseException("No home directory found in environment variables.") - return + #raise Exception("No home directory found in environment variables.") + return def appdata_dir(): """Find the path to the application data directory; add an electrum folder and return path.""" @@ -61,6 +62,8 @@ def appdata_dir(): return os.path.join(sys.prefix, "share", "electrum") elif (platform.system() == "Darwin" or platform.system() == "DragonFly" or + platform.system() == "OpenBSD" or + platform.system() == "FreeBSD" or platform.system() == "NetBSD"): return "/Library/Application Support/Electrum" else: @@ -88,7 +91,7 @@ def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespa digits.insert(0,'0') digits.insert(-decimal_point,'.') s = ''.join(digits).rstrip('0') - if sign: + if sign: s = '-' + s elif is_diff: s = "+" + s @@ -97,7 +100,7 @@ def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespa s += "0"*( 1 + num_zeros - ( len(s) - p )) if whitespaces: s += " "*( 1 + decimal_point - ( len(s) - p )) - s = " "*( 13 - decimal_point - ( p )) + s + s = " "*( 13 - decimal_point - ( p )) + s return s @@ -150,34 +153,62 @@ def age(from_date, since_date = None, target_tz=None, include_seconds=False): return "over %d years ago" % (round(distance_in_minutes / 525600)) - - # URL decode -_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE) -urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x) - -def parse_url(url): - o = url[8:].split('?') - address = o[0] - if len(o)>1: - params = o[1].split('&') - else: - params = [] +#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE) +#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x) - amount = label = message = signature = identity = '' - for p in params: - k,v = p.split('=') - uv = urldecode(v) - if k == 'amount': amount = uv - elif k == 'message': message = uv - elif k == 'label': label = uv - elif k == 'signature': - identity, signature = uv.split(':') - url = url.replace('&%s=%s'%(k,v),'') - else: - print k,v +def parse_URI(uri): + import urlparse + import urllib + import bitcoin + from decimal import Decimal - return address, amount, label, message, signature, identity, url + if ':' not in uri: + assert bitcoin.is_address(uri) + return uri, None, None, None, None + u = urlparse.urlparse(uri) + assert u.scheme == 'bitcoin' + address = u.path + valid_address = bitcoin.is_address(address) + pq = urlparse.parse_qs(u.query) + + for k, v in pq.items(): + if len(v)!=1: + raise Exception('Duplicate Key', k) + + amount = label = message = request_url = '' + if 'amount' in pq: + am = pq['amount'][0] + m = re.match('([0-9\.]+)X([0-9])', am) + if m: + k = int(m.group(2)) - 8 + amount = Decimal(m.group(1)) * pow( Decimal(10) , k) + else: + amount = Decimal(am) * 100000000 + if 'message' in pq: + message = pq['message'][0] + if 'label' in pq: + label = pq['label'][0] + if 'r' in pq: + request_url = urllib.quote(pq['r'][0], '/:?') + + if request_url != '': + return address, amount, label, message, request_url + + assert valid_address + + return address, amount, label, message, request_url + + +# Python bug (http://bugs.python.org/issue1927) causes raw_input +# to be redirected improperly between stdin/stderr on Unix systems +def raw_input(prompt=None): + if prompt: + sys.stdout.write(prompt) + return builtin_raw_input() +import __builtin__ +builtin_raw_input = __builtin__.raw_input +__builtin__.raw_input = raw_input