def call(cls, command, *args, **kwargs): # command line config_options = { 'cmd': command } config_options.update(cls.config_options) config_options.update(kwargs) # print(config_options) config = SimpleConfig(config_options) cmdname = config.get('cmd') 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) return result
def get_peers(): config = SimpleConfig() peers = {} # 1. get connected interfaces server = config.get('server') interfaces = get_interfaces([server]) if not interfaces: print("No connection to", server) return [] # 2. get list of peers interface = interfaces[server] interface.queue_request('server.peers.subscribe', [], 0) responses = wait_on_interfaces(interfaces).get(server) if responses: response = responses[0][1] # One response, (req, response) tuple peers = parse_servers(response.get('result')) return peers
def init_daemon(config_options): config = SimpleConfig(config_options) storage = WalletStorage(config.get_wallet_path()) if 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) 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 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
def get_peers(): config = SimpleConfig() peers = {} # 1. get connected interfaces server = config.get('server') interfaces = get_interfaces([server]) if not interfaces: print("No connection to", server) return [] # 2. get list of peers interface = interfaces[server] interface.queue_request('server.peers.subscribe', [], 0) responses = wait_on_interfaces(interfaces).get(server) if responses: response = responses[0][1] # One response, (req, response) tuple peers = parse_servers(response.get('result')) return peers
# 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': 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) d.init_gui(config, plugins) sys.exit(0)
def main(): parser = argparse.ArgumentParser( description='Install merchant add on files\ for BTCP Electrum wallet running in daemon mode.', prog="python3 -m electrum-merchant", epilog="Consult documentation on:\ http://docs.electrum.org/en/latest/merchant.html", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-f', '--flavour', nargs='?', required=False, default="simple", help='Which merchant flavour should be installed [simple]') parser.add_argument('-n', '--network', nargs='?', required=False, default="mainnet", help='Coin network [mainnet, testnet]') args = parser.parse_args() log.info('Downloading and installing files into request directory') if args.network == "mainnet": config = SimpleConfig() elif args.network == "testnet": config = SimpleConfig(options={'testnet': True}) else: log.error("Unknown network, exiting...") exit(1) rdir = config.get('requests_dir') if not rdir: log.error( "requests_dir not found in Electrum configuration, exiting...") exit(1) sdir = os.path.join(rdir, 'static') if not os.path.exists(rdir): os.mkdir(rdir) if not os.path.exists(sdir): os.mkdir(sdir) # Copying the flavoured index.html log.info("copying index.html from flavour %s" % args.flavour) indexsrc = get_data(args.flavour + "/index.html") indexdst = os.path.join(rdir, 'index.html') shutil.copy(indexsrc, indexdst) # Downloading libraries from NPM registry and unpacking them downloader = NpmPackageDownloader(sdir) downloader.download('jquery') downloader.download('qrcodejs') walkFiles(sdir) # Downloading libraries from other sources and unpacking them # jquery-ui r = requests.get("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js") if r.status_code == 200: with open(os.path.join(sdir, 'jquery-ui.min.js'), 'w') as f: f.write(r.text) log.info('Downloaded Jquery-UI.') else: log.error('Problems with downloading Jquery-UI.') # jquery-ui-fix-3 r = requests.get("https://code.jquery.com/jquery-migrate-3.0.1.min.js") if r.status_code == 200: with open(os.path.join(sdir, 'jquery-migrate-3.0.1.js'), 'w') as f: f.write(r.text) log.info('Downloaded Jquery-UI 3.x fix.') else: log.error('Problems with downloading Jquery-UI.') # jquery-ui themes r = requests.get( "https://jqueryui.com/resources/download/jquery-ui-themes-1.12.1.zip") if r.status_code == 200: z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall(sdir) log.info('Downloaded Jquery-UI themes.') else: log.error('Problems with downloading Jquery-UI themes.') # Finally :-) log.info('Finished.')
import urllib, shutil, os from electrum import SimpleConfig if __name__ == "__main__": config= SimpleConfig() rdir = config.get('requests_dir') if not rdir: print("requests_dir not found in Electrum configuration") exit(1) if not os.path.exists(rdir): os.mkdir(rdir) index = os.path.join(rdir, 'index.html') print("copying index.html") src = os.path.join(os.path.dirname(__file__), 'www', 'index.html') shutil.copy(src, index) files = [ "https://code.jquery.com/jquery-1.9.1.min.js", "https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.js", "https://code.jquery.com/ui/1.10.3/jquery-ui.js", "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] for URL in files: path = urllib.parse.urlsplit(URL).path filename = os.path.basename(path) path = os.path.join(rdir, filename) if not os.path.exists(path): print("downloading ", URL) urllib.request.urlretrieve(URL, path)
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)