def unlock_wallet(self): """ Attempt to unlock the BTC wallet with the password in the keychain. """ if not self.created or self.unlocked: # Wallet has not been created or unlocked already, do nothing. return False if self.storage.is_encrypted(): try: keychain_pw = self.get_wallet_password() self.wallet_password = keychain_pw if keychain_pw else None # Convert empty passwords to None self.storage.decrypt(self.wallet_password) self.unlocked = True except InvalidPassword: self._logger.error("Invalid BTC wallet password, unable to unlock the wallet!") except InitError: self._logger.error("Cannot initialize the keychain, unable to unlock the wallet!") else: # No need to unlock the wallet self.unlocked = True if self.unlocked: config = SimpleConfig(options={'cwd': self.wallet_dir, 'wallet_path': self.wallet_file}) if os.path.exists(config.get_wallet_path()): self.wallet = ElectrumWallet(self.storage) self.start_daemon() self.open_wallet() return True return False
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 on_balance(balance): self._logger.info("Creating Bitcoin payment with amount %f to address %s", amount, address) if balance['available'] >= amount: options = {'tx_fee': '0.0005', 'password': self.wallet_password, 'verbose': False, 'nocheck': False, 'cmd': 'payto', 'wallet_path': self.wallet_file, 'destination': address, 'cwd': self.wallet_dir, 'testnet': self.testnet, 'rbf': False, 'amount': amount, 'segwit': False, 'unsigned': False, 'portable': False} config = SimpleConfig(options) server = self.get_daemon().get_server(config) result = server.run_cmdline(options) transaction_hex = result['hex'] # Broadcast this transaction options = {'password': None, 'verbose': False, 'tx': transaction_hex, 'cmd': 'broadcast', 'testnet': self.testnet, 'timeout': 30, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False} config = SimpleConfig(options) server = self.get_daemon().get_server(config) result = server.run_cmdline(options) if not result[0]: # Transaction failed return fail(RuntimeError(result[1])) return succeed(str(result[1])) else: return fail(InsufficientFunds())
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 initialize_storage(self, wallet_dir, wallet_file): """ This will initialize the storage for the BTC wallet. """ self.wallet_dir = wallet_dir self.wallet_file = wallet_file config = SimpleConfig(options={'cwd': self.wallet_dir, 'wallet_path': self.wallet_file}) self.storage = WalletStorage(config.get_wallet_path()) if os.path.exists(config.get_wallet_path()): self.created = True
def load_wallet(self, wallet_dir, wallet_file): self.wallet_dir = wallet_dir self.wallet_file = wallet_file config = SimpleConfig(options={'cwd': self.wallet_dir, 'wallet_path': self.wallet_file}) self.storage = WalletStorage(config.get_wallet_path()) if self.storage.is_encrypted(): self.storage.decrypt(self.wallet_password) if os.path.exists(config.get_wallet_path()): self.wallet = ElectrumWallet(self.storage) self.created = True self.start_daemon() self.open_wallet()
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_transactions(self): if not self.created or not self.unlocked: return succeed([]) options = {'nolnet': False, 'password': None, 'verbose': False, 'cmd': 'history', 'wallet_path': self.wallet_file, 'testnet': self.TESTNET, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False} config = SimpleConfig(options) server = self.get_daemon().get_server(config) try: result = server.run_cmdline(options) except ProtocolError: self._logger.error("Unable to fetch transactions from BTC wallet!") return succeed([]) transactions = [] for transaction in result: outgoing = transaction['value'] < 0 from_address = ','.join(transaction['input_addresses']) to_address = ','.join(transaction['output_addresses']) transactions.append({ 'id': transaction['txid'], 'outgoing': outgoing, 'from': from_address, 'to': to_address, 'amount': abs(transaction['value']), 'fee_amount': 0.0, 'currency': 'BTC', 'timestamp': str(transaction['timestamp']), 'description': 'Confirmations: %d' % transaction['confirmations'] }) return succeed(transactions)
def get_balance(self): """ Return the balance of the wallet. """ if self.created and self.unlocked: options = {'nolnet': False, 'password': None, 'verbose': False, 'cmd': 'getbalance', 'wallet_path': self.wallet_file, 'testnet': self.TESTNET, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False} config = SimpleConfig(options) server = self.get_daemon().get_server(config) result = server.run_cmdline(options) confirmed = float(result['confirmed']) unconfirmed = float(result['unconfirmed']) if 'unconfirmed' in result else 0 unconfirmed += (float(result['unmatured']) if 'unmatured' in result else 0) return succeed({ "available": confirmed, "pending": unconfirmed, "currency": 'BTC' }) return succeed({"available": 0, "pending": 0, "currency": 'BTC'})
def get_transactions(self): options = {'nolnet': False, 'password': None, 'verbose': False, 'cmd': 'history', 'wallet_path': self.wallet_file, 'testnet': self.testnet, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False} config = SimpleConfig(options) server = self.get_daemon().get_server(config) result = server.run_cmdline(options) transactions = [] for transaction in result: outgoing = transaction['value'] < 0 if outgoing: from_address = self.get_address() to_address = '' else: from_address = '' to_address = self.get_address() transactions.append({ 'id': transaction['txid'], 'outgoing': outgoing, 'from': from_address, 'to': to_address, 'amount': abs(transaction['value']), 'fee_amount': 0.0, 'currency': 'BTC', 'timestamp': str(transaction['timestamp']), 'description': '' }) return succeed(transactions)
def Vitals(request=None): Electrum_Data = '/home/%s/.electrum/wallets/default_wallet' % TTS.USERNAME ret = { 'covername':'REX DART', 'email':'rex.dart', 'onion':'tns7i5gucaaussz4.onion', 'server_addr':'127.0.0.1', 'gpg_fp':addressbook.utils.my_address().fingerprint, 'btc_mpk':'NOT SURE', } if request: ret['server_addr'] = request.get_host() Me = addressbook.utils.my_address() ret['covername'] = Me.covername ret['email'] = Me.email ret['onion'] = re.sub('^[^@]+', '', Me.email) if os.path.exists(Electrum_Data): Config = SimpleConfig() ret['btc_mpk'] = wallet.WalletStorage(Config).get('master_public_key') return ret
def open_wallet(self): options = {'password': self.wallet_password, 'subcommand': 'load_wallet', 'verbose': False, 'cmd': 'daemon', 'testnet': self.testnet, 'oneserver': False, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False, 'wallet_path': self.wallet_file} config = SimpleConfig(options) server = self.get_daemon().get_server(config) if server is not None: # Run the command to open the wallet server.daemon(options)
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__(self, load_wallet): self.base_dir = BitVending.settings.BASE_DIR self.proc_config = {} self.__init_config__() self.__set_wallet_path__() self.config = SimpleConfig(self.proc_config) self.storage = WalletStorage(self.config) self.network = Network(self.config) self.network.start(False) if load_wallet: self.wallet = self.create_or_load_wallet() self.transaction_fee = utils.to_satoshis( float(self.proc_config.get('fee'))) return
def start_daemon(self): options = {'verbose': False, 'cmd': 'daemon', 'testnet': self.testnet, 'oneserver': False, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False, 'password': '', 'wallet_path': os.path.join('wallet', self.wallet_file)} if self.testnet: options['server'] = 'electrum.akinbo.org:51002:s' config = SimpleConfig(options) fd, _ = self.get_daemon().get_fd_or_server(config) if not fd: return self.daemon = self.get_daemon().Daemon(config, fd) self.daemon.start()
def send_request(peers, request): print "Contacting %d servers" % len(peers) # start interfaces q2 = Queue.Queue() config = SimpleConfig() interfaces = map(lambda server: Interface(server, q2, config), peers) reached_servers = [] for i in interfaces: i.start() t0 = time.time() while peers: try: i, r = q2.get(timeout=1) except: if time.time() - t0 > 10: print "timeout" break else: continue if i.server in peers: peers.remove(i.server) if i.is_connected(): reached_servers.append(i) else: print "Connection failed:", i.server print "%d servers could be reached" % len(reached_servers) results_queue = Queue.Queue() for i in reached_servers: i.send_request(request, results_queue) results = {} t0 = time.time() while reached_servers: try: i, r = results_queue.get(timeout=1) except: if time.time() - t0 > 10: break else: continue results[i.server] = r.get('result') reached_servers.remove(i) i.stop() for i in reached_servers: print i.server, "did not answer" print "%d answers" % len(results) return results
def _test_addresses(self, key_store, addresses, is_change_address): with tempfile.NamedTemporaryFile() as file, patch.object( Abstract_Wallet, 'gap_limit_for_change', self.GAP_LIMIT): config = SimpleConfig({ 'electrum_path': file.name, }) if isinstance(key_store, list): wallet = WalletIntegrityHelper.create_multisig_wallet( keystores=key_store, multisig_type='2of2', config=config, gap_limit=self.GAP_LIMIT, ) else: wallet = WalletIntegrityHelper.create_standard_wallet( key_store, config=config, gap_limit=self.GAP_LIMIT, ) # test gap limits self.assertEqual(wallet.gap_limit, self.GAP_LIMIT) self.assertEqual(wallet.gap_limit_for_change, self.GAP_LIMIT) # test addresses saved in wallet db db_saved_addresses = wallet.db.get_change_addresses( ) if is_change_address else wallet.db.get_receiving_addresses() for i, address in enumerate(addresses[:self.GAP_LIMIT]): with self.subTest(address): self.assertEqual(db_saved_addresses[i], address) # test rest of the addresses for i, address in enumerate(addresses[self.GAP_LIMIT:]): with self.subTest(address): self.assertEqual( wallet.derive_address( for_change=1 if is_change_address else 0, n=i + self.GAP_LIMIT), address) self.assertEqual( wallet.create_new_address( for_change=is_change_address), address, )
def get_interfaces(servers, timeout=10): '''Returns a map of servers to connected interfaces. If any connections fail or timeout, they will be missing from the map. ''' socket_queue = queue.Queue() config = SimpleConfig() connecting = {} for server in servers: if server not in connecting: connecting[server] = Connection(server, socket_queue, config.path) interfaces = {} timeout = time.time() + timeout count = 0 while time.time() < timeout and count < len(servers): try: server, socket = socket_queue.get(True, 0.3) except queue.Empty: continue if socket: interfaces[server] = Interface(server, socket) count += 1 return interfaces
def start_daemon(self): options = { 'verbose': False, 'cmd': 'daemon', 'testnet': self.TESTNET, 'oneserver': False, 'segwit': False, 'cwd': self.wallet_dir, 'portable': False, 'password': '', 'wallet_path': os.path.join('wallet', self.wallet_file) } if self.TESTNET: options['server'] = 'testnet1.bauerj.eu:50002:s' config = SimpleConfig(options) fd, _ = self.get_daemon().get_fd_or_server(config) if not fd: return self.daemon = self.get_daemon().Daemon(config, fd, is_gui=False) self.daemon.start()
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)
# 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)
db_instance = config.get('db', 'instance') db_user = config.get('db', 'user') db_password = config.get('db', 'password') db_name = config.get('db', 'name') electrum_server = config.get('electrum', 'server') my_password = config.get('main', 'password') my_host = config.get('main', 'host') my_port = config.getint('main', 'port') cb_received = config.get('callback', 'received') cb_expired = config.get('callback', 'expired') cb_password = config.get('callback', 'password') wallet_config = SimpleConfig() master_public_key = config.get('electrum', 'mpk') wallet_config.set_key('master_public_key', master_public_key) wallet = Wallet(wallet_config) wallet.synchronize = lambda: None # prevent address creation by the wallet omg_addresses = {} def input_reader_thread(request_queue): while True: addr, amount, confirmations = request_queue.get(True, 1000000000) if addr in omg_addresses: continue else: print "subscribing to ", addr
db_user = config.get('db','user') db_password = config.get('db','password') db_name = config.get('db','name') electrum_server = config.get('electrum','server') my_password = config.get('main','password') my_host = config.get('main','host') my_port = config.getint('main','port') cb_received = config.get('callback','received') cb_expired = config.get('callback','expired') cb_password = config.get('callback','password') wallet_config = SimpleConfig() master_public_key = config.get('electrum','mpk') wallet_config.set_key('master_public_key',master_public_key) wallet = Wallet(wallet_config) wallet.synchronize = lambda: None # prevent address creation by the wallet omg_addresses = {} def input_reader_thread(request_queue): while True: addr, amount, confirmations = request_queue.get(True,1000000000) if addr in omg_addresses: continue else: print "subscribing to ", addr
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.')
db_user = config.get("db", "user") db_password = config.get("db", "password") db_name = config.get("db", "name") electrum_server = config.get("electrum", "server") my_password = config.get("main", "password") my_host = config.get("main", "host") my_port = config.getint("main", "port") cb_received = config.get("callback", "received") cb_expired = config.get("callback", "expired") cb_password = config.get("callback", "password") wallet_config = SimpleConfig() master_public_key = config.get("electrum", "mpk") wallet_config.set_key("master_public_key", master_public_key) wallet = Wallet(wallet_config) wallet.synchronize = lambda: None # prevent address creation by the wallet omg_addresses = {} def input_reader_thread(request_queue): while True: addr, amount, confirmations = request_queue.get(True, 1000000000) if addr in omg_addresses: continue else:
print " getaddress <index> outputs deterministic bitcoin address by index\n\n" from twisted.web import server from twisted.internet import reactor from txjsonrpc.web import jsonrpc from electrum import Wallet, SimpleConfig from electrum.util import set_verbosity import ConfigParser config = ConfigParser.ConfigParser() config.read("electrum-address-generator.conf") rpc_port = int(config.get("daemon", "port")) set_verbosity(0) wallet_config = SimpleConfig() wallet_config.set_key("master_public_key", config.get("electrum", "master_public_key")) wallet = Wallet(wallet_config) wallet.synchronize = lambda: None # prevent address creation by the wallet class Json_Rpc_Server(jsonrpc.JSONRPC): def jsonrpc_getaddress(self, index): return handle_getaddress(int(index)) class Json_Rpc_Daemon: def __init__(self): reactor.listenTCP(rpc_port, server.Site(Json_Rpc_Server())) print "Electrum address generator daemon started at port " + str( rpc_port
network, util, bitcoin, ) import asyncio import threading from time import sleep # Get the global network object started loop = asyncio.get_event_loop() stopping_fut = asyncio.Future() loop_thread = threading.Thread(target=loop.run_until_complete, args=(stopping_fut, ), name='EventLoop') loop_thread.start() n = network.Network(SimpleConfig()) n.start() async def end_thread(): stopping_fut.set_result(1) asyncio.run_coroutine_threadsafe(end_thread(), loop).result() class Bitcoin: # Simple decorator which starts new event loop and then kills it after def with_new_event_loop(func): async def end_thread(stopping_fut): stopping_fut.set_result(1)
if __name__ == '__main__': if len(sys.argv) > 1: cmd = sys.argv[1] params = sys.argv[2:] + [my_password] ret = send_command(cmd, params) sys.exit(ret) conn = sqlite3.connect(database); # create table if needed check_create_table(conn) # init network config = SimpleConfig({'wallet_path':wallet_path}) network = Network(config) network.start(wait=True) # create watching_only wallet storage = WalletStorage(config) wallet = Wallet(storage) if not storage.file_exists: wallet.seed = '' wallet.create_watching_only_wallet(master_public_key,master_chain) wallet.synchronize = lambda: None # prevent address creation by the wallet wallet.start_threads(network) network.register_callback('updated', on_wallet_update) out_queue = Queue.Queue()
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)