Exemple #1
0
def stopdaemon(ctx):
    """ Stops the daemon
    """
    # Check to sere if we're in a venv and don't do anything if we are
    if os.environ.get("VIRTUAL_ENV"):
        click.echo("Not stopping any daemons from within a virtualenv.")
        return

    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    msg = ""
    try:
        if d.stop():
            msg = "walletd successfully stopped."
        else:
            msg = "walletd not stopped."
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #2
0
def stopdaemon(ctx):
    """ Stops the daemon
    """
    # Check to sere if we're in a venv and don't do anything if we are
    if os.environ.get("VIRTUAL_ENV"):
        click.echo("Not stopping any daemons from within a virtualenv.")
        return

    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    msg = ""
    try:
        if d.stop():
            msg = "walletd successfully stopped."
        else:
            msg = "walletd not stopped."
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #3
0
def restore(ctx):
    """ Restore a wallet from a mnemonic

    \b
    If you accidently deleted your wallet file or the file
    became corrupted, use this command to restore your wallet. You
    must have your 12 word phrase (mnemonic) that was displayed
    when you created your wallet.
    """
    # Stop daemon if it's running.
    d = None
    try:
        d = get_daemonizer()
    except OSError as e:
        pass

    if d:
        try:
            d.stop()
        except exceptions.DaemonizerError as e:
            click.echo("ERROR: Couldn't stop daemon: %s" % e)
            ctx.exit(code=4)

    # Check to see if the current wallet path exists
    if os.path.exists(ctx.obj['wallet_path']):
        if click.confirm("Wallet file already exists and may have a balance. Do you want to delete it?"):
            os.remove(ctx.obj['wallet_path'])
        else:
            click.echo("Not continuing.")
            ctx.exit(code=4)

    # Ask for mnemonic
    mnemonic = click.prompt("Please enter the wallet's 12 word mnemonic").strip()

    # Sanity check the mnemonic
    def check_mnemonic(mnemonic):
        try:
            return Mnemonic(language='english').check(mnemonic)
        except ConfigurationError:
            return False
    if not check_mnemonic(mnemonic):
        click.echo("ERROR: Invalid mnemonic.")
        ctx.exit(code=5)

    # Try creating the wallet
    click.echo("\nRestoring...")
    wallet = Two1Wallet.import_from_mnemonic(
        data_provider=ctx.obj['data_provider'],
        mnemonic=mnemonic,
    )

    wallet.to_file(ctx.obj['wallet_path'])
    if Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
        click.echo("Wallet successfully restored. Run '21 login' to connect this wallet to your 21 account.")
    else:
        click.echo("Wallet not restored.")
        ctx.exit(code=6)
def test_get_daemonizer():
    sys.platform = 'darwin'
    d = get_daemonizer()

    assert d == Launchd

    sys.platform = 'linux'
    Systemd.check_systemd = MagicMock(return_value=True)
    d = get_daemonizer()

    assert d == Systemd

    Systemd.check_systemd = MagicMock(return_value=False)
    with pytest.raises(OSError):
        d = get_daemonizer()

    sys.platform = 'win'
    with pytest.raises(OSError):
        d = get_daemonizer()
Exemple #5
0
def startdaemon(ctx):
    """ Starts the daemon
    """
    # Check to sere if we're in a venv and don't do anything if we are
    if os.environ.get("VIRTUAL_ENV"):
        click.echo(
            "Not starting daemon while inside a virtualenv. It can be manually "
            + "started by doing 'walletd' and backgrounding the process.")
        return

    # Check if the wallet path exists
    if not Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
        click.echo("ERROR: Wallet does not exist! Not starting daemon.")
        ctx.exit(code=7)

    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    if d.started():
        click.echo("walletd already running.")
        return

    if not d.installed():
        if isinstance(ctx.obj['data_provider'], TwentyOneProvider):
            dpo = dict(provider='twentyone')

        try:
            d.install(dpo)
        except exceptions.DaemonizerError as e:
            logger.debug(str(e))
            click.echo("Error: %s" % e)
            return

    msg = ""
    try:
        if d.start():
            msg = "walletd successfully started."
        else:
            msg = "walletd not started."
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #6
0
def startdaemon(ctx):
    """ Starts the daemon
    """
    # Check to sere if we're in a venv and don't do anything if we are
    if os.environ.get("VIRTUAL_ENV"):
        click.echo("Not starting daemon while inside a virtualenv. It can be manually " +
                   "started by doing 'walletd' and backgrounding the process.")
        return

    # Check if the wallet path exists
    if not Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
        click.echo("ERROR: Wallet does not exist! Not starting daemon.")
        ctx.exit(code=7)

    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    if d.started():
        click.echo("walletd already running.")
        return

    if not d.installed():
        if isinstance(ctx.obj['data_provider'], TwentyOneProvider):
            dpo = dict(provider='twentyone')

        try:
            d.install(dpo)
        except exceptions.DaemonizerError as e:
            logger.debug(str(e))
            click.echo("Error: %s" % e)
            return

    msg = ""
    try:
        if d.start():
            msg = "walletd successfully started."
        else:
            msg = "walletd not started."
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #7
0
def get_or_create_wallet(wallet_path):
    """Create a new wallet or return the currently existing one."""
    data_provider = twentyone_provider.TwentyOneProvider(
        two1.TWO1_PROVIDER_HOST)

    if wallet.Two1Wallet.check_wallet_file(wallet_path):
        return wallet.Wallet(wallet_path=wallet_path,
                             data_provider=data_provider)

    # configure wallet with default options
    click.pause(uxstring.UxString.create_wallet)

    wallet_options = dict(data_provider=data_provider, wallet_path=wallet_path)

    if not wallet.Two1Wallet.configure(wallet_options):
        raise click.ClickException(
            uxstring.UxString.Error.create_wallet_failed)

    # Display the wallet mnemonic and tell user to back it up.
    # Read the wallet JSON file and extract it.
    with open(wallet_path, 'r') as f:
        wallet_config = json.load(f)
        mnemonic = wallet_config['master_seed']

    click.pause(uxstring.UxString.create_wallet_done %
                click.style(mnemonic, fg='green'))

    # Start the daemon, if:
    # 1. It's not already started
    # 2. It's using the default wallet path
    # 3. We're not in a virtualenv
    try:
        d = daemonizer.get_daemonizer()

        if wallet.Two1Wallet.is_configured(
        ) and not os.environ.get("VIRTUAL_ENV") and not d.started():
            d.start()
            if d.started():
                logger.info(uxstring.UxString.wallet_daemon_started)
    except (OSError, exceptions.DaemonizerError):
        pass

    if wallet.Two1Wallet.check_wallet_file(wallet_path):
        return wallet.Wallet(wallet_path=wallet_path,
                             data_provider=data_provider)
Exemple #8
0
def get_or_create_wallet(wallet_path):
    """Create a new wallet or return the currently existing one."""
    data_provider = twentyone_provider.TwentyOneProvider(two1.TWO1_PROVIDER_HOST)

    if wallet.Two1Wallet.check_wallet_file(wallet_path):
        return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider)

    # configure wallet with default options
    click.pause(uxstring.UxString.create_wallet)

    wallet_options = dict(data_provider=data_provider, wallet_path=wallet_path)

    if not wallet.Two1Wallet.configure(wallet_options):
        raise click.ClickException(uxstring.UxString.Error.create_wallet_failed)

    # Display the wallet mnemonic and tell user to back it up.
    # Read the wallet JSON file and extract it.
    with open(wallet_path, 'r') as f:
        wallet_config = json.load(f)
        mnemonic = wallet_config['master_seed']

    click.pause(uxstring.UxString.create_wallet_done % click.style(mnemonic, fg='green'))

    # Start the daemon, if:
    # 1. It's not already started
    # 2. It's using the default wallet path
    # 3. We're not in a virtualenv
    try:
        d = daemonizer.get_daemonizer()

        if wallet.Two1Wallet.is_configured() and not os.environ.get("VIRTUAL_ENV") and not d.started():
            d.start()
            if d.started():
                logger.info(uxstring.UxString.wallet_daemon_started)
    except (OSError, exceptions.DaemonizerError):
        pass

    if wallet.Two1Wallet.check_wallet_file(wallet_path):
        return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider)
Exemple #9
0
def login_21():
    """ Restore wallet to disk and log in to 21.
    """

    d = None
    try:
        d = get_daemonizer()
    except OSError as e:
        pass

    if d:
        d.stop()

    mnemonic = os.environ["TWO1_WALLET_MNEMONIC"]

    provider = TwentyOneProvider()
    wallet = Two1Wallet.import_from_mnemonic(provider, mnemonic)

    if not os.path.exists(os.path.dirname(Two1Wallet.DEFAULT_WALLET_PATH)):
        os.makedirs(os.path.dirname(Two1Wallet.DEFAULT_WALLET_PATH))
    wallet.to_file(Two1Wallet.DEFAULT_WALLET_PATH)

    # login
    config = Config()
    machine_auth = machine_auth_wallet.MachineAuthWallet(wallet)

    username = os.environ["TWO1_USERNAME"]
    password = os.environ["TWO1_PASSWORD"]

    rest_client = _rest_client.TwentyOneRestClient(two1.TWO1_HOST, machine_auth, username)

    machine_auth_pubkey_b64 = base64.b64encode(machine_auth.public_key.compressed_bytes).decode()
    payout_address = machine_auth.wallet.current_address

    rest_client.login(payout_address=payout_address, password=password)

    config.set("username", username)
    config.set("mining_auth_pubkey", machine_auth_pubkey_b64)
    config.save()
Exemple #10
0
def uninstalldaemon(ctx):
    """ Uninstalls the daemon from the init system
    """
    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    try:
        d.stop()
        if d.installed():
            rv = d.uninstall()
            if rv:
                msg = "walletd successfully uninstalled from init system."
        else:
            msg = "Unable to uninstall walletd!"
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #11
0
def uninstalldaemon(ctx):
    """ Uninstalls the daemon from the init system
    """
    try:
        d = get_daemonizer()
    except OSError as e:
        logger.debug(str(e))
        click.echo("Error: %s" % e)
        return

    try:
        d.stop()
        if d.installed():
            rv = d.uninstall()
            if rv:
                msg = "walletd successfully uninstalled from init system."
        else:
            msg = "Unable to uninstall walletd!"
    except exceptions.DaemonizerError as e:
        msg = "Error: %s" % e

    logger.debug(msg)
    click.echo(msg)
Exemple #12
0
def restore(ctx):
    """ Restore a wallet from a mnemonic

    \b
    If you accidently deleted your wallet file or the file
    became corrupted, use this command to restore your wallet. You
    must have your 12 word phrase (mnemonic) that was displayed
    when you created your wallet.
    """
    # Stop daemon if it's running.
    d = None
    try:
        d = get_daemonizer()
    except OSError as e:
        pass

    if d:
        try:
            d.stop()
        except exceptions.DaemonizerError as e:
            click.echo("ERROR: Couldn't stop daemon: %s" % e)
            ctx.exit(code=4)

    # Check to see if the current wallet path exists
    if os.path.exists(ctx.obj['wallet_path']):
        if click.confirm(
                "Wallet file already exists and may have a balance. Do you want to delete it?"
        ):
            os.remove(ctx.obj['wallet_path'])
        else:
            click.echo("Not continuing.")
            ctx.exit(code=4)

    # Ask for mnemonic
    mnemonic = click.prompt(
        "Please enter the wallet's 12 word mnemonic").strip()

    # Sanity check the mnemonic
    def check_mnemonic(mnemonic):
        try:
            return Mnemonic(language='english').check(mnemonic)
        except ConfigurationError:
            return False

    if not check_mnemonic(mnemonic):
        click.echo("ERROR: Invalid mnemonic.")
        ctx.exit(code=5)

    # Try creating the wallet
    click.echo("\nRestoring...")
    wallet = Two1Wallet.import_from_mnemonic(
        data_provider=ctx.obj['data_provider'],
        mnemonic=mnemonic,
    )

    wallet.to_file(ctx.obj['wallet_path'])
    if Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
        click.echo(
            "Wallet successfully restored. Run '21 login' to connect this wallet to your 21 account."
        )
    else:
        click.echo("Wallet not restored.")
        ctx.exit(code=6)
def test_systemd():
    sys.platform = 'linux'
    Systemd.check_systemd = MagicMock(return_value=True)
    d = get_daemonizer()

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(return_value=True)
    Systemd.ENV_FILE_PATH.exists = MagicMock(return_value=True)
    assert d.installed()

    Systemd.ENV_FILE_PATH.exists = MagicMock(return_value=False)
    assert not d.installed()

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(return_value=False)
    assert not d.installed()

    Systemd.ENV_FILE_PATH.exists = MagicMock(return_value=True)
    assert not d.installed()

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(return_value=True)
    dpo = dict(provider='chain',
               api_key_id="ID",
               api_key_secret="SECRET")
    assert d.install(dpo)

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(side_effect=[False, True])
    Systemd.ENV_FILE_PATH.exists = MagicMock(side_effect=[True])
    Systemd.check_systemd = MagicMock(return_value=True)
    Systemd._write_env_file = MagicMock(return_value=True)
    Systemd._write_service_file = MagicMock(return_value=True)

    install_rv = d.install(dpo)
    assert Systemd.SERVICE_FILE_PATH.exists.call_count == 2
    assert install_rv

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(side_effect=[False, True])
    Systemd.ENV_FILE_PATH.exists = MagicMock(side_effect=[False])
    Systemd.check_systemd = MagicMock(return_value=True)
    Systemd._write_env_file = MagicMock(return_value=True)
    Systemd._write_service_file = MagicMock(return_value=True)

    install_rv = d.install(dpo)
    assert Systemd.SERVICE_FILE_PATH.exists.call_count == 2
    assert not install_rv

    enabled_status = """● two1-wallet.service - two1 wallet daemon
   Loaded: loaded (/etc/systemd/user/two1-wallet.service; enabled)
   Active: failed (Result: exit-code) since Fri 2015-10-02 04:38:48 UTC; 2min 32s ago
  Process: 19151 ExecStart=/usr/local/bin/walletd (code=exited, status=203/EXEC)
 Main PID: 19151 (code=exited, status=203/EXEC)""".encode()

    disabled_status = """● two1-wallet.service - two1 wallet daemon
   Loaded: loaded (/etc/systemd/user/two1-wallet.service; disabled)
   Active: failed (Result: exit-code) since Fri 2015-10-02 04:38:48 UTC; 7min ago
 Main PID: 19151 (code=exited, status=203/EXEC)""".encode()

    active_status = """● two1-wallet.service - two1 wallet daemon
   Loaded: loaded (/etc/systemd/user/two1-wallet.service; enabled)
   Active: active (running) since Fri 2015-10-02 04:38:48 UTC; 2min 32s ago
 Main PID: 533 (walletd)
   CGroup: /usr/local/bin/walletd
           └─533 /usr/local/bin/walletd""".encode()

    subprocess.check_output = MagicMock(return_value=enabled_status)
    assert Systemd.enabled()

    subprocess.check_output = MagicMock(return_value=disabled_status)
    assert not Systemd.enabled()

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(side_effect=[True, True])
    Systemd.ENV_FILE_PATH.exists = MagicMock(side_effect=[True, True])
    subprocess.check_output = MagicMock(side_effect=[b"", enabled_status])
    assert Systemd.enable()

    subprocess.check_output = MagicMock(side_effect=[b"", disabled_status])
    assert Systemd.disable()

    Systemd.SERVICE_FILE_PATH.exists = MagicMock(side_effect=[True, True])
    Systemd.ENV_FILE_PATH.exists = MagicMock(side_effect=[True, True])
    subprocess.check_output = MagicMock(side_effect=[enabled_status,
                                                     enabled_status,
                                                     b"",
                                                     active_status])
    assert Systemd.start()

    subprocess.check_output = MagicMock(side_effect=[active_status,
                                                     b"",
                                                     enabled_status])
    assert Systemd.stop()