diff --git a/lib/daemon.py b/lib/daemon.py index ef2a561dd..30dd8998c 100644 --- a/lib/daemon.py +++ b/lib/daemon.py @@ -33,8 +33,8 @@ from .jsonrpc import VerifyingJSONRPCServer from version import ELECTRUM_VERSION from network import Network -from util import json_decode, DaemonThread -from util import print_msg, print_error, print_stderr, UserCancelled +from util import (json_decode, DaemonThread, print_msg, print_error, + print_stderr, UserCancelled, to_string, int_to_bytes) from wallet import Wallet from storage import WalletStorage from commands import known_commands, Commands @@ -102,7 +102,7 @@ def get_rpc_credentials(config): nbytes = bits // 8 + (bits % 8 > 0) pw_int = ecdsa.util.randrange(pow(2, bits)) pw_b64 = base64.b64encode( - pw_int.to_bytes(nbytes, 'big'), b'-_') + int_to_bytes(pw_int, nbytes, 'big'), b'-_') rpc_password = to_string(pw_b64, 'ascii') config.set_key('rpcuser', rpc_user) config.set_key('rpcpassword', rpc_password, save=True) diff --git a/lib/jsonrpc.py b/lib/jsonrpc.py index 02b544296..ba1604f2a 100644 --- a/lib/jsonrpc.py +++ b/lib/jsonrpc.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python2 # # Electrum - lightweight Bitcoin client # Copyright (C) 2018 Thomas Voegtlin @@ -52,6 +52,8 @@ class VerifyingJSONRPCServer(SimpleJSONRPCServer): self.rpc_user = kargs['rpc_user'] self.rpc_password = kargs['rpc_password'] + del kargs['rpc_user'] + del kargs['rpc_password'] class VerifyingRequestHandler(SimpleJSONRPCRequestHandler): def parse_request(myself): diff --git a/lib/util.py b/lib/util.py index 552c22370..344cc412b 100644 --- a/lib/util.py +++ b/lib/util.py @@ -247,6 +247,38 @@ def android_check_data_dir(): def get_headers_dir(config): return android_headers_dir() if 'ANDROID_DATA' in os.environ else config.path +def to_string(x, enc): + if isinstance(x, (bytes, bytearray)): + return x.decode(enc) + if isinstance(x, str): + return x + else: + raise TypeError("Not a string or bytes like object") + +def to_bytes(something, encoding='utf8'): + """ + cast string to bytes() like object, but for python2 support it's bytearray copy + """ + if isinstance(something, bytes): + return something + if isinstance(something, str) or isinstance(something, unicode): + return something.encode(encoding) + elif isinstance(something, bytearray): + return bytes(something) + else: + raise TypeError("Not a string or bytes like object") + +# based on https://stackoverflow.com/questions/16022556/has-python-3-to-bytes-been-back-ported-to-python-2-7 +def int_to_bytes(n, length, endianess='big'): + hex_n = '%x' % n + hex_n2 = '0'*(len(hex_n) % 2) + hex_n + left_padded_hex_n = hex_n2.zfill(length*2) + if len(left_padded_hex_n) > length*2: + raise OverflowError() + assert len(left_padded_hex_n) == length*2 + bytes_n = left_padded_hex_n.decode('hex') + return bytes_n if endianess == 'big' else bytes_n[::-1] + def user_dir(): if 'ANDROID_DATA' in os.environ: return android_check_data_dir()