Beispiel #1
0
 def get_passphrase(self, msg, confirm):
     import getpass
     print_stderr(msg)
     if self.passphrase_on_device and self.yes_no_question(_('Enter passphrase on device?')):
         return PASSPHRASE_ON_DEVICE
     else:
         return getpass.getpass('')
Beispiel #2
0
def load_library():
    if sys.platform in ('windows', 'win32'):
        library_path = 'RaycoinViewer.dll'
    else:
        return None

    lib = ctypes.cdll.LoadLibrary(library_path)
    if not lib:
        print_stderr(
            '[blockchain] warning: RaycoinViewer library failed to load')
        return None

    try:
        lib.raycoinViewer_start.argtypes = []
        lib.raycoinViewer_start.restype = None

        lib.raycoinViewer_hasAdapter.argtypes = []
        lib.raycoinViewer_hasAdapter.restype = c_bool

        lib.raycoinViewer_getMinedBlockHash.argtypes = [
            c_char_p, POINTER(c_bool), c_char_p
        ]
        lib.raycoinViewer_getMinedBlockHash.restype = None

        lib.raycoinViewer_terminate.argtypes = []
        lib.raycoinViewer_terminate.restype = None

        lib.raycoinViewer_start()
        return lib
    except Exception as e:
        print_stderr(
            '[blockchain] warning: error using RaycoinViewer library: ' +
            str(e))
        return None
Beispiel #3
0
 def prompt_auth(self, msg):
     import getpass
     print_stderr(msg)
     response = getpass.getpass('')
     if len(response) == 0:
         return None
     return response
Beispiel #4
0
 def prompt_auth(self, msg):
     import getpass
     print_stderr(msg)
     response = getpass.getpass('')
     if len(response) == 0:
         return None
     return response
Beispiel #5
0
 def get_pin(self, msg, *, show_strength=True):
     t = { 'a':'7', 'b':'8', 'c':'9', 'd':'4', 'e':'5', 'f':'6', 'g':'1', 'h':'2', 'i':'3'}
     print_stderr(msg)
     print_stderr("a b c\nd e f\ng h i\n-----")
     o = raw_input()
     try:
         return ''.join(map(lambda x: t[x], o))
     except KeyError as e:
         raise Exception("Character {} not in matrix!".format(e)) from e
Beispiel #6
0
 def get_pin(self, msg):
     t = { 'a':'7', 'b':'8', 'c':'9', 'd':'4', 'e':'5', 'f':'6', 'g':'1', 'h':'2', 'i':'3'}
     print_stderr(msg)
     print_stderr("a b c\nd e f\ng h i\n-----")
     o = raw_input()
     try:
         return ''.join(map(lambda x: t[x], o))
     except KeyError as e:
         raise Exception("Character {} not in matrix!".format(e)) from e
Beispiel #7
0
def hash_raw_header(header: str) -> str:
    if local_hash:
        hash_hex = create_string_buffer(65)
        valid = c_bool(False)
        try:
            _raycoinviewer.raycoinViewer_getMinedBlockHash(
                c_char_p(header[:-64].encode('ascii')), valid, hash_hex)
            if not valid: hash_hex.value = b'F' * 64
            return hash_hex.value.decode('ascii')
        except Exception as e:
            print_stderr(
                '[blockchain] warning: error using RaycoinViewer library: ' +
                str(e))
    return hash_encode(bfh(header[-64:]))
Beispiel #8
0
def get_connected_hw_devices(plugins):
    supported_plugins = plugins.get_hardware_support()
    # scan devices
    devices = []
    devmgr = plugins.device_manager
    for splugin in supported_plugins:
        name, plugin = splugin.name, splugin.plugin
        if not plugin:
            e = splugin.exception
            print_stderr(f"{name}: error during plugin init: {repr(e)}")
            continue
        try:
            u = devmgr.unpaired_device_infos(None, plugin)
        except:
            devmgr.print_error(f'error getting device infos for {name}: {e}')
            continue
        devices += list(map(lambda x: (name, x), u))
    return devices
Beispiel #9
0
def init_cmdline(config_options, server):
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')
    cmd = known_commands[cmdname]

    if cmdname == 'signtransaction' and config.get('privkey'):
        cmd.requires_wallet = False
        cmd.requires_password = False

    if cmdname in ['payto', 'paytomany'] and config.get('unsigned'):
        cmd.requires_password = False

    if cmdname in ['payto', 'paytomany'] and config.get('broadcast'):
        cmd.requires_network = True

    # instantiate wallet for command-line
    storage = WalletStorage(config.get_wallet_path())

    if cmd.requires_wallet and not storage.file_exists():
        print_msg("Error: Wallet file not found.")
        print_msg(
            "Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option"
        )
        sys.exit(0)

    # important warning
    if cmd.name in ['getprivatekeys']:
        print_stderr("WARNING: ALL your private keys are secret.")
        print_stderr(
            "Exposing a single private key can compromise your entire wallet!")
        print_stderr(
            "In particular, DO NOT use 'redeem private key' services proposed by third parties."
        )

    # commands needing password
    if (cmd.requires_wallet and storage.is_encrypted() and server is None)\
       or (cmd.requires_password and (storage.get('use_encryption') or storage.is_encrypted())):
        if storage.is_encrypted_with_hw_device():
            # this case is handled later in the control flow
            password = None
        elif config.get('password'):
            password = config.get('password')
        else:
            password = prompt_password('Password:'******'password'] = config_options.get('password') or password

    if cmd.name == 'password':
        new_password = prompt_password('New password:'******'new_password'] = new_password
Beispiel #10
0
 def get_passphrase(self, msg, confirm):
     import getpass
     print_stderr(msg)
     return getpass.getpass('')
Beispiel #11
0
 def show_message(self, msg, on_cancel=None):
     print_stderr(msg)
Beispiel #12
0
 def yes_no_question(self, msg):
     print_stderr(msg)
     return raw_input() in 'yY'
Beispiel #13
0
        config_options['portable'] = True

    if config_options.get('portable'):
        config_options['electrum_path'] = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'electrum_data')

    # kivy sometimes freezes when we write to sys.stderr
    set_verbosity(
        config_options.get('verbosity'
                           ) if config_options.get('gui') != 'kivy' else '')

    # check uri
    uri = config_options.get('url')
    if uri:
        if not uri.startswith('bitcoin:'):
            print_stderr('unknown command:', uri)
            sys.exit(1)
        config_options['url'] = uri

    # todo: defer this to gui
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')

    if config.get('testnet'):
        constants.set_testnet()
    elif config.get('regtest'):
        constants.set_regtest()
    elif config.get('simnet'):
        constants.set_simnet()

    if cmdname == 'gui':
Beispiel #14
0
 def show_message(self, msg, on_cancel=None):
     print_stderr(msg)
Beispiel #15
0
 def yes_no_question(self, msg):
     print_stderr(msg)
     return raw_input() in 'yY'
Beispiel #16
0
 def yes_no_question(self, msg):
     print_stderr(msg)
     return False
Beispiel #17
0
 def show_error(self, msg, blocking=False):
     print_stderr(msg)
Beispiel #18
0
        return lib
    except Exception as e:
        print_stderr(
            '[blockchain] warning: error using RaycoinViewer library: ' +
            str(e))
        return None


local_hash = False
_raycoinviewer = None
try:
    _raycoinviewer = load_library()
    if _raycoinviewer:
        local_hash = bool(_raycoinviewer.raycoinViewer_hasAdapter())
except Exception as e:
    print_stderr('[blockchain] warning: error using RaycoinViewer library: ' +
                 str(e))


class MissingHeader(Exception):
    pass


class InvalidHeader(Exception):
    pass


def serialize_header(header_dict: dict) -> str:
    s = int_to_hex(header_dict['version'], 4) \
        + rev_hex(header_dict['prev_block_hash']) \
        + rev_hex(header_dict['merkle_root']) \
        + int_to_hex(int(header_dict['timestamp']), 4) \
Beispiel #19
0
 def get_passphrase(self, msg, confirm):
     import getpass
     print_stderr(msg)
     return getpass.getpass('')
Beispiel #20
0
 def show_error(self, msg, blocking=False):
     print_stderr(msg)
Beispiel #21
0
def launch():
    # The hook will only be used in the Qt GUI right now
    util.setup_thread_excepthook()
    # on osx, delete Process Serial Number arg generated for apps launched in Finder
    sys.argv = list(filter(lambda x: not x.startswith('-psn'), sys.argv))

    # old 'help' syntax
    if len(sys.argv) > 1 and sys.argv[1] == 'help':
        sys.argv.remove('help')
        sys.argv.append('-h')

    # read arguments from stdin pipe and prompt
    for i, arg in enumerate(sys.argv):
        if arg == '-':
            if not sys.stdin.isatty():
                sys.argv[i] = sys.stdin.read()
                break
            else:
                raise BaseException('Cannot get argument from stdin')
        elif arg == '?':
            sys.argv[i] = input("Enter argument:")
        elif arg == ':':
            sys.argv[i] = prompt_password('Enter argument (will not echo):', False)

    # parse command line
    parser = get_parser()
    args = parser.parse_args()

    # config is an object passed to the various constructors (wallet, interface, gui)
    if is_android:
        config_options = {
            'verbose': True,
            'cmd': 'gui',
            'gui': 'kivy',
        }
    else:
        config_options = args.__dict__
        f = lambda key: config_options[key] is not None and key not in config_variables.get(args.cmd, {}).keys()
        config_options = {key: config_options[key] for key in filter(f, config_options.keys())}
        if config_options.get('server'):
            config_options['auto_connect'] = False

    config_options['cwd'] = os.getcwd()

    # fixme: this can probably be achieved with a runtime hook (pyinstaller)
    if is_bundle and os.path.exists(os.path.join(sys._MEIPASS, 'is_portable')):
        config_options['portable'] = True

#if config_options.get('portable'):
    config_options['electrum_path'] = os.path.join(managers.shared().documentsDirectory(), 'electrum_data')

    # kivy sometimes freezes when we write to sys.stderr
    set_verbosity(config_options.get('verbose') and config_options.get('gui')!='kivy')

    # check uri
    '''
    uri = config_options.get('url')
    if uri:
        if not uri.startswith('bitcoin:'):
            print_stderr('unknown command:', uri)
            sys.exit(1)
        config_options['url'] = uri
    '''
    
    # todo: defer this to gui
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')

    if config.get('testnet'):
        constants.set_testnet()

    # run non-RPC commands separately
    if cmdname in ['create', 'restore']:
        run_non_RPC(config)
        sys.exit(0)

    if cmdname == 'gui':
        fd, server = daemon.get_fd_or_server(config)
        if fd is not None:
            plugins = init_plugins(config, config.get('gui', 'qt'))
            d = daemon.Daemon(config, fd, True)
            d.start()
            d.init_gui(config, plugins)
            sys.exit(0)
        else:
            result = server.gui(config_options)

    elif cmdname == 'daemon':
        subcommand = config.get('subcommand')
        if subcommand in ['load_wallet']:
            init_daemon(config_options)

        if subcommand in [None, 'start']:
            fd, server = daemon.get_fd_or_server(config)
            if fd is not None:
                if subcommand == 'start':
                    pid = os.fork()
                    if pid:
                        print_stderr("starting daemon (PID %d)" % pid)
                        sys.exit(0)
                init_plugins(config, 'cmdline')
                d = daemon.Daemon(config, fd, False)
                d.start()
                if config.get('websocket_server'):
                    from electrum import websockets
                    websockets.WebSocketServer(config, d.network).start()
                if config.get('requests_dir'):
                    path = os.path.join(config.get('requests_dir'), 'index.html')
                    if not os.path.exists(path):
                        print("Requests directory not configured.")
                        print("You can configure it using https://github.com/spesmilo/electrum-merchant")
                        sys.exit(1)
                d.join()
                sys.exit(0)
            else:
                result = server.daemon(config_options)
        else:
            server = daemon.get_server(config)
            if server is not None:
                result = server.daemon(config_options)
            else:
                print_msg("Daemon not running")
                sys.exit(1)
    else:
        # command line
        server = daemon.get_server(config)
        init_cmdline(config_options, server)
        if server is not None:
            result = server.run_cmdline(config_options)
        else:
            cmd = known_commands[cmdname]
            if cmd.requires_network:
                print_msg("Daemon not running; try 'electrum daemon start'")
                sys.exit(1)
            else:
                plugins = init_plugins(config, 'cmdline')
                result = run_offline_command(config, config_options, plugins)
                # print result
    if isinstance(result, str):
        print_msg(result)
    elif type(result) is dict and result.get('error'):
        print_stderr(result.get('error'))
    elif result is not None:
        print_msg(json_encode(result))
    sys.exit(0)