X-Git-Url: https://git.novaco.in/?a=blobdiff_plain;f=lib%2Futil.py;h=0415b1ce2b693e39cef81197d7f7b2196927e848;hb=3cbe11a42473af52e7c5e002c36aaaf32646f627;hp=bab166bdef6097366891f0f812502716b979ef86;hpb=25bbae132f78bd151e8ec7e394babc5713a51829;p=electrum-nvc.git diff --git a/lib/util.py b/lib/util.py index bab166b..0415b1c 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,46 +34,38 @@ 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") + return os.path.join(os.environ["HOME"], ".electrum-nvc") elif "APPDATA" in os.environ: - return os.path.join(os.environ["APPDATA"], "Electrum") + return os.path.join(os.environ["APPDATA"], "Electrum-NVC") elif "LOCALAPPDATA" in os.environ: - return os.path.join(os.environ["LOCALAPPDATA"], "Electrum") + return os.path.join(os.environ["LOCALAPPDATA"], "Electrum-NVC") + 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.""" if platform.system() == "Windows": - return os.path.join(os.environ["APPDATA"], "Electrum") + return os.path.join(os.environ["APPDATA"], "Electrum-NVC") elif platform.system() == "Linux": - return os.path.join(sys.prefix, "share", "electrum") + return os.path.join(sys.prefix, "share", "electrum-nvc") 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" + return "/Library/Application Support/Electrum-NVC" else: raise Exception("Unknown system") @@ -79,7 +82,7 @@ def local_data_dir(): return local_data -def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8): +def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 6, whitespaces=False): from decimal import Decimal s = Decimal(x) sign, digits, exp = s.as_tuple() @@ -88,15 +91,16 @@ def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8): digits.insert(0,'0') digits.insert(-decimal_point,'.') s = ''.join(digits).rstrip('0') - if sign: + if sign: s = '-' + s elif is_diff: s = "+" + s p = s.find('.') s += "0"*( 1 + num_zeros - ( len(s) - p )) - s += " "*( 1 + decimal_point - ( len(s) - p )) - s = " "*( 13 - decimal_point - ( p )) + s + if whitespaces: + s += " "*( 1 + decimal_point - ( len(s) - p )) + s = " "*( 13 - decimal_point - ( p )) + s return s @@ -149,34 +153,61 @@ 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 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) * 1000000 + if 'message' in pq: + message = pq['message'][0] + if 'label' in pq: + label = pq['label'][0] + if 'r' in pq: + request_url = 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