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 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. """ # 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 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)
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)
def main(ctx, wallet_path, passphrase, blockchain_data_provider, insight_url, insight_api_path, debug): """ Command-line Interface for the Two1 Wallet """ if wallet_path is None: try: config = two1_config.Config(config_file) wallet_path = config.wallet_path except two1exceptions.FileDecodeError as e: raise click.ClickException( uxstring.UxString.Error.file_decode.format((str(e)))) wp = Path(wallet_path) # Initialize some logging handlers ch = logging.StreamHandler() ch_formatter = logging.Formatter('%(levelname)s: %(message)s') ch.setFormatter(ch_formatter) if not os.path.exists(wp.dirname()): os.makedirs(wp.dirname()) fh = logging.handlers.TimedRotatingFileHandler( wp.dirname().joinpath("wallet_cli.log"), when='midnight', backupCount=5) fh_formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s') fh.setFormatter(fh_formatter) logger.addHandler(ch) logger.addHandler(fh) fh.setLevel(logging.DEBUG if debug else logging.INFO) ch.setLevel(logging.DEBUG if debug else logging.WARNING) logger.setLevel(logging.DEBUG if debug else logging.INFO) logger.info("Wallet client started.") if ctx.obj is None: ctx.obj = {} ctx.obj['wallet_path'] = wallet_path ctx.obj['passphrase'] = passphrase if ctx.invoked_subcommand not in ['create', 'restore']: # Check that the wallet path exists if not Two1Wallet.check_wallet_file(ctx.obj['wallet_path']): click.echo("ERROR: Wallet file does not exist or is corrupt.") ctx.exit(code=7) p = get_passphrase() if passphrase else '' try: logger.info("Loading wallet %s ..." % (wp)) ctx.obj['wallet'] = Wallet(wallet_path=wallet_path, data_provider=ctx.obj['data_provider'], passphrase=p) logger.info("... loading complete.") except exceptions.PassphraseError as e: click.echo(str(e)) ctx.exit(code=1) except (TypeError, ValueError) as e: logger.error("Internal wallet error. Please report this as a bug.") logger.debug("".join(traceback.format_tb(e.__traceback__))) ctx.exit(code=2) def _on_close(): try: ctx.obj['wallet'].sync_wallet_file() except: pass ctx.call_on_close(_on_close)
def main(ctx, wallet_path, passphrase, blockchain_data_provider, insight_url, insight_api_path, debug): """ Command-line Interface for the Two1 Wallet """ if wallet_path is None: try: config = two1_config.Config(config_file) wallet_path = config.wallet_path except two1exceptions.FileDecodeError as e: raise click.ClickException(uxstring.UxString.Error.file_decode.format((str(e)))) wp = Path(wallet_path) # Initialize some logging handlers ch = logging.StreamHandler() ch_formatter = logging.Formatter( '%(levelname)s: %(message)s') ch.setFormatter(ch_formatter) if not os.path.exists(wp.dirname()): os.makedirs(wp.dirname()) fh = logging.handlers.TimedRotatingFileHandler(wp.dirname().joinpath("wallet_cli.log"), when='midnight', backupCount=5) fh_formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s') fh.setFormatter(fh_formatter) logger.addHandler(ch) logger.addHandler(fh) fh.setLevel(logging.DEBUG if debug else logging.INFO) ch.setLevel(logging.DEBUG if debug else logging.WARNING) logger.setLevel(logging.DEBUG if debug else logging.INFO) logger.info("Wallet client started.") if ctx.obj is None: ctx.obj = {} ctx.obj['wallet_path'] = wallet_path ctx.obj['passphrase'] = passphrase if ctx.invoked_subcommand not in ['create', 'restore', 'startdaemon', 'stopdaemon', 'uninstalldaemon']: # Check that the wallet path exists if not Two1Wallet.check_wallet_file(ctx.obj['wallet_path']): click.echo("ERROR: Wallet file does not exist or is corrupt.") ctx.exit(code=7) p = get_passphrase() if passphrase else '' try: logger.info("Loading wallet %s ..." % (wp)) ctx.obj['wallet'] = Wallet(wallet_path=wallet_path, data_provider=ctx.obj['data_provider'], passphrase=p) logger.info("... loading complete.") except exceptions.PassphraseError as e: click.echo(str(e)) ctx.exit(code=1) except (TypeError, ValueError) as e: logger.error("Internal wallet error. Please report this as a bug.") logger.debug("".join(traceback.format_tb(e.__traceback__))) ctx.exit(code=2) def _on_close(): try: ctx.obj['wallet'].sync_wallet_file() except: pass ctx.call_on_close(_on_close)
def main(ctx, wallet_path, blockchain_data_provider, insight_url, insight_api_path, data_update_interval, debug): """ Two1 Wallet daemon """ global DEF_WALLET_UPDATE_INTERVAL wp = Path(wallet_path) # Initialize some logging handlers ch = logging.handlers.TimedRotatingFileHandler(wp.dirname().joinpath("walletd.log"), when='midnight', backupCount=5) ch_formatter = logging.Formatter( '%(asctime)s %(levelname)s %(name)-8s: %(message)s') ch.setFormatter(ch_formatter) ch.setLevel(logging.DEBUG if debug else logging.INFO) logging.getLogger().addHandler(ch) console = logging.StreamHandler() console.setLevel(logging.CRITICAL) logging.getLogger().addHandler(console) logging.getLogger().setLevel(logging.DEBUG) global wallet wallet['path'] = wallet_path if not Two1Wallet.check_wallet_file(wallet['path']): logger.critical("Wallet file does not exist or have the right parameters.") sys.exit(-1) wallet['data_provider'] = ctx.obj['data_provider'] if data_update_interval is not None: DEF_WALLET_UPDATE_INTERVAL = data_update_interval wallet['update_info']['interval'] = data_update_interval logger.info("Starting daemon for wallet %s" % wallet_path) logger.info("Blockchain data provider: %s" % ctx.obj['data_provider'].__class__.__name__) logger.info("Update interval: %ds" % data_update_interval) # Check whether the wallet is locked if Two1Wallet.is_locked(wallet_path): wallet['locked'] = True logger.info("Wallet is locked.") else: logger.info("Wallet unlocked. Loading ...") try: load_wallet(wallet_path=wallet_path, data_provider=ctx.obj['data_provider'], passphrase="") logger.info("... loading complete.") except WalletNotLoadedError as e: logger.error(str(e)) logger.info("Terminating.") sys.exit(-1) create_daemon_methods() # Setup a signal handler signal.signal(signal.SIGINT, sig_handler) signal.signal(signal.SIGTERM, sig_handler) server_thread = threading.Thread(target=rpc_server.serve_forever, daemon=True) update_thread = threading.Thread(target=data_updater, daemon=True) server_thread.start() update_thread.start() logger.info("Daemon started.") server_thread.join() rpc_server.server_close() try: _check_wallet_loaded() wallet['obj'].sync_wallet_file(force_cache_write=True) except: pass sys.exit(0)
def main(ctx, wallet_path, blockchain_data_provider, insight_url, insight_api_path, data_update_interval, debug): """ Two1 Wallet daemon """ global DEF_WALLET_UPDATE_INTERVAL wp = Path(wallet_path) # Initialize some logging handlers ch = logging.handlers.TimedRotatingFileHandler(wp.dirname().joinpath("walletd.log"), when='midnight', backupCount=5) ch_formatter = logging.Formatter( '%(asctime)s %(levelname)s %(name)-8s: %(message)s') ch.setFormatter(ch_formatter) ch.setLevel(logging.DEBUG if debug else logging.INFO) logging.getLogger().addHandler(ch) console = logging.StreamHandler() console.setLevel(logging.CRITICAL) logging.getLogger().addHandler(console) logging.getLogger().setLevel(logging.DEBUG) global wallet wallet['path'] = wallet_path if not Two1Wallet.check_wallet_file(wallet['path']): logger.critical("Wallet file does not exist or have the right parameters.") sys.exit(-1) wallet['data_provider'] = ctx.obj['data_provider'] if data_update_interval is not None: DEF_WALLET_UPDATE_INTERVAL = data_update_interval wallet['update_info']['interval'] = data_update_interval logger.info("Starting daemon for wallet %s" % wallet_path) logger.info("Blockchain data provider: %s" % ctx.obj['data_provider'].__class__.__name__) logger.info("Update interval: %ds" % data_update_interval) # Check whether the wallet is locked if Two1Wallet.is_locked(wallet_path): wallet['locked'] = True logger.info("Wallet is locked.") else: logger.info("Wallet unlocked. Loading ...") try: load_wallet(wallet_path=wallet_path, data_provider=ctx.obj['data_provider'], passphrase="") logger.info("... loading complete.") except WalletNotLoadedError as e: logger.error(str(e)) logger.info("Terminating.") sys.exit(-1) create_daemon_methods() # Setup a signal handler signal.signal(signal.SIGINT, sig_handler) signal.signal(signal.SIGTERM, sig_handler) server_thread = threading.Thread(target=rpc_server.serve_forever, daemon=True) update_thread = threading.Thread(target=data_updater, daemon=True) server_thread.start() update_thread.start() logger.info("Daemon started.") server_thread.join() rpc_server.server_close() try: _check_wallet_loaded() wallet['obj'].sync_wallet_file(force_cache_write=True) except: pass sys.exit(0)