def prompt_auth(self, msg): import getpass print_msg(msg) response = getpass.getpass('') if len(response) == 0: return None return response
def runCommand(self): command = self.getCommand() self.addToHistory(command) command = self.getConstruct(command) if command: tmp_stdout = sys.stdout class stdoutProxy(): def __init__(self, write_func): self.write_func = write_func self.skip = False def flush(self): pass def write(self, text): if not self.skip: stripped_text = text.rstrip('\n') self.write_func(stripped_text) QtCore.QCoreApplication.processEvents() self.skip = not self.skip if type(self.namespace.get(command)) == type(lambda:None): self.appendPlainText("'{}' is a function. Type '{}()' to use it in the Python console." .format(command, command)) self.newPrompt() return sys.stdout = stdoutProxy(self.appendPlainText) try: try: # eval is generally considered bad practice. use it wisely! result = eval(command, self.namespace, self.namespace) if result != None: if self.is_json: util.print_msg(util.json_encode(result)) else: self.appendPlainText(repr(result)) except SyntaxError: # exec is generally considered bad practice. use it wisely! exec(command, self.namespace, self.namespace) except SystemExit: self.close() except BaseException: traceback_lines = traceback.format_exc().split('\n') # Remove traceback mentioning this file, and a linebreak for i in (3,2,1,-1): traceback_lines.pop(i) self.appendPlainText('\n'.join(traceback_lines)) sys.stdout = tmp_stdout self.newPrompt() self.set_json(False)
def _send(self, parent, blob): def sender_thread(): with self._audio_interface() as interface: src = BytesIO(blob) dst = interface.player() amodem.main.send(config=self.modem_config, src=src, dst=dst) print_msg('Sending:', repr(blob)) blob = zlib.compress(blob.encode('ascii')) kbps = self.modem_config.modem_bps / 1e3 msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps) WaitingDialog(parent, msg, sender_thread)
def init_daemon(config_options): config = SimpleConfig(config_options) storage = WalletStorage(config.get_wallet_path()) if getattr(storage, 'backup_file', None): print_msg('Info: %s' % storage.backup_message) if not storage.file_exists(): print_msg("Error: Wallet file not found.") print_msg( "Type 'electrum-sparks create' to create a new wallet, or provide a path to a wallet with the -w option" ) sys.exit(0) if storage.is_encrypted(): if storage.is_encrypted_with_hw_device(): plugins = init_plugins(config, 'cmdline') password = get_password_for_hw_device_encrypted_storage(plugins) elif config.get('password'): password = config.get('password') else: password = prompt_password('Password:'******'password'] = password
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 getattr(storage, 'backup_file', None): print_msg('Info: %s' % storage.backup_message) if cmd.requires_wallet and not storage.file_exists(): print_msg("Error: Wallet file not found.") print_msg( "Type 'electrum-sparks 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'] = password if cmd.name == 'password': new_password = prompt_password('New password:'******'new_password'] = new_password return cmd, password
def get_connected_hw_devices(plugins): support = plugins.get_hardware_support() if not support: print_msg('No hardware wallet support found on your system.') sys.exit(1) # scan devices devices = [] devmgr = plugins.device_manager for name, description, plugin in support: try: u = devmgr.unpaired_device_infos(None, plugin) except: devmgr.print_error("error", name) continue devices += list(map(lambda x: (name, x), u)) return devices
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_msg(msg) print_msg("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
def get_password_for_hw_device_encrypted_storage(plugins): devices = get_connected_hw_devices(plugins) if len(devices) == 0: print_msg( "Error: No connected hw device found. Cannot decrypt this wallet.") sys.exit(1) elif len(devices) > 1: print_msg("Warning: multiple hardware devices detected. " "The first one will be used to decrypt the wallet.") # FIXME we use the "first" device, in case of multiple ones name, device_info = devices[0] plugin = plugins.get_plugin(name) derivation = get_derivation_used_for_hw_device_encryption() try: xpub = plugin.get_xpub(device_info.device.id_, derivation, 'standard', plugin.handler) except UserCancelled: sys.exit(0) password = keystore.Xpub.get_pubkey_from_xpub(xpub, ()) return password
def run_offline_command(config, config_options, plugins): cmdname = config.get('cmd') cmd = known_commands[cmdname] password = config_options.get('password') if cmd.requires_wallet: storage = WalletStorage(config.get_wallet_path()) if storage.is_encrypted(): if storage.is_encrypted_with_hw_device(): password = get_password_for_hw_device_encrypted_storage( plugins) config_options['password'] = password storage.decrypt(password) wallet = Wallet(storage) else: wallet = None # check password if cmd.requires_password and wallet.has_password(): try: seed = wallet.check_password(password) except InvalidPassword: print_msg("Error: This password does not decode this wallet.") sys.exit(1) if cmd.requires_network: print_msg("Warning: running command offline") # arguments passed to function args = [config.get(x) for x in cmd.params] # decode json arguments if cmdname not in ('setconfig', ): args = list(map(json_decode, args)) # options kwargs = {} for x in cmd.options: kwargs[x] = (config_options.get(x) if x in ['password', 'new_password'] else config.get(x)) cmd_runner = Commands(config, wallet, None) func = getattr(cmd_runner, cmd.name) result = func(*args, **kwargs) # save wallet if wallet: wallet.storage.write() return result
def get_passphrase(self, msg, confirm): import getpass print_msg(msg) return getpass.getpass('')
def yes_no_question(self, msg): print_msg(msg) return raw_input() in 'yY'
def on_finished(blob): if blob: blob = zlib.decompress(blob).decode('ascii') print_msg('Received:', repr(blob)) parent.setText(blob)
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-sparks daemon start'") sys.exit(1) else: plugins = init_plugins(config, 'cmdline')
from electrum_sparks.util import print_msg, json_encode try: addr = sys.argv[1] except Exception: print("usage: watch_address <sparks_address>") sys.exit(1) sh = bitcoin.address_to_scripthash(addr) # start network c = SimpleConfig() network = Network(c) network.start() # wait until connected while network.is_connecting(): time.sleep(0.1) if not network.is_connected(): print_msg("daemon is not connected") sys.exit(1) # 2. send the subscription callback = lambda response: print_msg(json_encode(response.get('result'))) network.subscribe_to_address(addr, callback) # 3. wait for results while network.is_connected(): time.sleep(1)
def show_message(self, msg, on_cancel=None): print_msg(msg)
def show_error(self, msg, blocking=False): print_msg(msg)
def run_non_RPC(config): cmdname = config.get('cmd') storage = WalletStorage(config.get_wallet_path()) if storage.file_exists(): sys.exit("Error: Remove the existing wallet first!") def password_dialog(): return prompt_password( "Password (hit return if you do not wish to encrypt your wallet):") if cmdname == 'restore': text = config.get('text').strip() passphrase = config.get('passphrase', '') password = password_dialog() if keystore.is_private(text) else None if keystore.is_address_list(text): wallet = Imported_Wallet(storage) for x in text.split(): wallet.import_address(x) elif keystore.is_private_key_list(text): k = keystore.Imported_KeyStore({}) storage.put('keystore', k.dump()) storage.put('use_encryption', bool(password)) wallet = Imported_Wallet(storage) for x in text.split(): wallet.import_private_key(x, password) storage.write() else: if keystore.is_seed(text): k = keystore.from_seed(text, passphrase, False) elif keystore.is_master_key(text): k = keystore.from_master_key(text) else: sys.exit("Error: Seed or key not recognized") if password: k.update_password(None, password) storage.put('keystore', k.dump()) storage.put('wallet_type', 'standard') storage.put('use_encryption', bool(password)) storage.write() wallet = Wallet(storage) if not config.get('offline'): network = Network(config) network.start() wallet.start_threads(network) print_msg("Recovering wallet...") wallet.synchronize() wallet.wait_until_synchronized() wallet.stop_threads() # note: we don't wait for SPV msg = "Recovery successful" if wallet.is_found( ) else "Found no history for this wallet" else: msg = "This wallet was restored offline. It may contain more addresses than displayed." print_msg(msg) elif cmdname == 'create': password = password_dialog() passphrase = config.get('passphrase', '') seed_type = 'standard' seed = Mnemonic('en').make_seed(seed_type) k = keystore.from_seed(seed, passphrase, False) storage.put('keystore', k.dump()) storage.put('wallet_type', 'standard') wallet = Wallet(storage) wallet.update_password(None, password, True) wallet.synchronize() print_msg("Your wallet generation seed is:\n\"%s\"" % seed) print_msg( "Please keep it in a safe place; if you lose it, you will not be able to restore your wallet." ) wallet.storage.write() print_msg("Wallet saved in '%s'" % wallet.storage.path) sys.exit(0)
#!/usr/bin/env python3 import sys from .. import Network from electrum_sparks.util import json_encode, print_msg from electrum_sparks import bitcoin try: addr = sys.argv[1] except Exception: print("usage: get_history <sparks_address>") sys.exit(1) n = Network() n.start() _hash = bitcoin.address_to_scripthash(addr) h = n.get_history_for_scripthash(_hash) print_msg(json_encode(h))
def debug_msg(*args): if DEBUG: print_msg(*args)