From c48e850e5397533bc7da1d70e3b9822f9e93579e Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Wed, 5 Aug 2020 12:47:48 +0100 Subject: [PATCH 01/12] Add jmwalletd and support wallet display RPC. Uses Klein to provide HTTP server support. --- jmclient/jmclient/client_protocol.py | 4 +- jmclient/jmclient/wallet_utils.py | 33 ++++++- scripts/jmwalletd.py | 127 +++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 4 deletions(-) create mode 100644 scripts/jmwalletd.py diff --git a/jmclient/jmclient/client_protocol.py b/jmclient/jmclient/client_protocol.py index 45155c9df..6bae76c34 100644 --- a/jmclient/jmclient/client_protocol.py +++ b/jmclient/jmclient/client_protocol.py @@ -848,13 +848,13 @@ def start_daemon_on_port(p, f, name, port_offset): # Note the reactor.connect*** entries do not include BIP78 which # starts in jmclient.payjoin: - if usessl: + if usessl: if factory: reactor.connectSSL(host, jmcport, factory, ClientContextFactory()) if snickerfactory: reactor.connectSSL(host, snickerport, snickerfactory, ClientContextFactory()) - else: + else: if factory: reactor.connectTCP(host, jmcport, factory) if snickerfactory: diff --git a/jmclient/jmclient/wallet_utils.py b/jmclient/jmclient/wallet_utils.py index ed1b2a1cb..0e2484c06 100644 --- a/jmclient/jmclient/wallet_utils.py +++ b/jmclient/jmclient/wallet_utils.py @@ -178,6 +178,12 @@ def serialize(self): extradata = self.serialize_extra_data() return self.serclass(self.separator.join([left, addr, amounts, extradata])) + def serialize_json(self): + return {"hd_path": self.wallet_path_repr, + "address": self.serialize_address(), + "amount": self.serialize_amounts(), + "labels": self.serialize_extra_data()} + def serialize_wallet_position(self): return self.wallet_path_repr.ljust(20) @@ -230,6 +236,14 @@ def serialize(self, entryseparator="\n", summarize=False): lines.append(footer) return self.serclass(entryseparator.join(lines)) + def serialize_json(self, summarize=False): + if summarize: + return {} + else: + return {"branch": self.serialize_branch_header(), + "balance": self.get_fmt_balance(), + "entries": [x.serialize_json() for x in self.branchentries]} + def serialize_branch_header(self): start = "external addresses" if self.address_type == 0 else "internal addresses" if self.address_type == -1: @@ -264,6 +278,14 @@ def serialize(self, entryseparator="\n", summarize=False): return self.serclass(entryseparator.join([header] + [ x.serialize(entryseparator) for x in self.branches] + [footer])) + def serialize_json(self, summarize=False): + result = {"account": str(self.account), + "account_balance": self.get_fmt_balance()} + if summarize: + return result + result["branches"] = [x.serialize_json() for x in self.branches] + return result + class WalletView(WalletViewBase): def __init__(self, wallet_path_repr, accounts, wallet_name="JM wallet", serclass=str, custom_separator=None): @@ -287,6 +309,10 @@ def serialize(self, entryseparator="\n", summarize=False): return self.serclass(entryseparator.join([header] + [ x.serialize(entryseparator, summarize=False) for x in self.accounts] + [footer])) + def serialize_json(self, summarize=False): + return {"wallet_name": self.wallet_name, + "total_balance": self.get_fmt_balance(), + "accounts": [x.serialize_json(summarize=summarize) for x in self.accounts]} def get_tx_info(txid, tx_cache=None): """ @@ -394,7 +420,7 @@ def wallet_showutxos(wallet_service, showprivkey): def wallet_display(wallet_service, showprivkey, displayall=False, - serialized=True, summarized=False, mixdepth=None): + serialized=True, summarized=False, mixdepth=None, jsonified=False): """build the walletview object, then return its serialization directly if serialized, else return the WalletView object. @@ -547,7 +573,10 @@ def get_addr_status(addr_path, utxos, is_new, is_internal): path = wallet_service.get_path_repr(wallet_service.get_path()) walletview = WalletView(path, acctlist) if serialized: - return walletview.serialize(summarize=summarized) + if jsonified: + return walletview.serialize_json(summarize=summarized) + else: + return walletview.serialize(summarize=summarized) else: return walletview diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py new file mode 100644 index 000000000..c0de0878d --- /dev/null +++ b/scripts/jmwalletd.py @@ -0,0 +1,127 @@ +#! /usr/bin/env python + +import datetime +import os +import time +import abc +import json +from io import BytesIO +from twisted.python.log import startLogging +from twisted.internet import endpoints, reactor, ssl +from twisted.web.server import Site +from klein import Klein + +from optparse import OptionParser +from jmbase import get_log +from jmclient import Maker, jm_single, load_program_config, \ + JMClientProtocolFactory, start_reactor, calc_cj_fee, \ + WalletService, add_base_options, get_wallet_path, open_test_wallet_maybe, wallet_display +from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE + +jlog = get_log() + +def get_ssl_context(cert_directory): + """Construct an SSL context factory from the user's privatekey/cert. + TODO: + Currently just hardcoded for tests. + """ + return ssl.DefaultOpenSSLContextFactory(os.path.join(cert_directory, "key.pem"), + os.path.join(cert_directory, "cert.pem")) + +def response(request, succeed=True, status=200, **kwargs): + """ + Build the response body as JSON and set the proper content-type + header. + """ + request.setHeader('Content-Type', 'application/json') + request.setHeader('Access-Control-Allow-Origin', '*') + request.setResponseCode(status) + return json.dumps( + [{'succeed': succeed, 'status': status, **kwargs}]) + +def start_REST_server(port): + app = Klein() + reactor.listenSSL(port, Site(app.resource()), contextFactory=get_ssl_context(".")) + return app + +def jmwalletd_main(): + import sys + wallet_service = None + parser = OptionParser(usage='usage: %prog [options] [wallet file]') + parser.add_option('-p', '--port', action='store', type='int', + dest='port', default=28183, + help='the port over which to serve RPC') + # TODO: remove the non-relevant base options: + add_base_options(parser) + + (options, args) = parser.parse_args() + + load_program_config(config_path=options.datadir) + + app = start_REST_server(options.port) + + @app.route('/wallet//display', methods=['GET']) + def displaywallet(request, walletname): + print(request) + nonlocal wallet_service + if not wallet_service: + #todo return a specific error + print('called display but no wallet loaded.') + else: + walletinfo = wallet_display(wallet_service, False, jsonified=True) + return response(request, walletname=walletname, walletinfo=walletinfo) + + # handling CORS preflight: + #@app.route('/', branch=True, methods=['OPTIONS']) + @app.route('/wallet//unlock', methods=['OPTIONS']) + def preflight(request, walletname): + print(request) + request.setHeader("Access-Control-Allow-Origin", "*") + request.setHeader("Access-Control-Allow-Methods", "POST") + request.setHeader("Access-Control-Allow-Headers", "Content-Type") + + @app.route('/wallet//display', methods=['OPTIONS']) + def preflight2(request, walletname): + print(request) + request.setHeader("Access-Control-Allow-Origin", "*") + request.setHeader("Access-Control-Allow-Methods", "GET") + request.setHeader("Access-Control-Allow-Headers", "Content-Type") + + @app.route('/wallet//unlock', methods=['POST']) + def unlockwallet(request, walletname): + print(request) + assert isinstance(request.content, BytesIO) + passwordjson = request.content.read().decode("utf-8") + password = json.loads(passwordjson)["password"] + nonlocal wallet_service + if wallet_service is None: + wallet_path = get_wallet_path(walletname, None) + wallet = open_test_wallet_maybe( + wallet_path, walletname, 4, + password=password.encode("utf-8"), + ask_for_password=False) + wallet_service = WalletService(wallet) + while not wallet_service.synced: + wallet_service.sync_wallet(fast=True) + wallet_service.startService() + return response(request, walletname=walletname, already_loaded=False) + else: + print('wallet was already unlocked.') + return response(request, walletname=walletname, already_loaded=True) + + if jm_single().bc_interface is None: + jlog.error("Running jmwallet-daemon requires configured " + + "blockchain source.") + sys.exit(EXIT_FAILURE) + jlog.info("Starting jmwalletd") + + nodaemon = jm_single().config.getint("DAEMON", "no_daemon") + daemon = True if nodaemon == 1 else False + if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]: + startLogging(sys.stdout) + start_reactor(jm_single().config.get("DAEMON", "daemon_host"), + jm_single().config.getint("DAEMON", "daemon_port"), + None, daemon=daemon) + +if __name__ == "__main__": + jmwalletd_main() From b553bbb3f902f9a60d116304d184901c52234300 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Mon, 24 Aug 2020 15:34:34 +0100 Subject: [PATCH 02/12] Add cookie based auth to requests, lock method This commit adds a basic authorization method to all requests using a cookie stored by the client (so similar to what is done by Bitcoin RPC). This cookie is sent in a custom header 'JMCookie'. Additionally, preflight CORS requests are handled for all routes generically. Also more comments are added to the current main functions. Also a /lock route is added to allow the user to shut down the wallet service and close the wallet. Still very rudimentary of course. --- scripts/jmwalletd.py | 119 +++++++++++++++++++++++++++++++++---------- 1 file changed, 93 insertions(+), 26 deletions(-) diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index c0de0878d..d382f6189 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -20,6 +20,26 @@ jlog = get_log() +# only serving single concurrent user for now; cookie global: +cookie = None +wallet_service = None + +# for debugging; twisted.web.server.Request objects do not easily serialize: +def print_req(request): + print(request) + print(request.method) + print(request.uri) + print(request.args) + print(request.path) + print(request.content) + print(list(request.requestHeaders.getAllRawHeaders())) + +class NotAuthorized(Exception): + pass + +class NoWalletFound(Exception): + pass + def get_ssl_context(cert_directory): """Construct an SSL context factory from the user's privatekey/cert. TODO: @@ -39,6 +59,12 @@ def response(request, succeed=True, status=200, **kwargs): return json.dumps( [{'succeed': succeed, 'status': status, **kwargs}]) +def check_cookie(request): + request_cookie = request.getHeader(b"JMCookie") + if cookie != request_cookie: + print("Invalid cookie: ", request_cookie) + raise NotAuthorized() + def start_REST_server(port): app = Klein() reactor.listenSSL(port, Site(app.resource()), contextFactory=get_ssl_context(".")) @@ -46,7 +72,6 @@ def start_REST_server(port): def jmwalletd_main(): import sys - wallet_service = None parser = OptionParser(usage='usage: %prog [options] [wallet file]') parser.add_option('-p', '--port', action='store', type='int', dest='port', default=28183, @@ -60,50 +85,92 @@ def jmwalletd_main(): app = start_REST_server(options.port) + @app.handle_errors(NotAuthorized) + def not_authorized(request, failure): + request.setResponseCode(401) + return "Invalid credentials." + + @app.handle_errors(NoWalletFound) + def no_wallet_found(request, failure): + request.setResponseCode(404) + return "No wallet loaded." + @app.route('/wallet//display', methods=['GET']) def displaywallet(request, walletname): - print(request) - nonlocal wallet_service + print_req(request) + check_cookie(request) if not wallet_service: - #todo return a specific error - print('called display but no wallet loaded.') + print("called display but no wallet loaded") + raise NoWalletFound() else: walletinfo = wallet_display(wallet_service, False, jsonified=True) return response(request, walletname=walletname, walletinfo=walletinfo) - # handling CORS preflight: - #@app.route('/', branch=True, methods=['OPTIONS']) - @app.route('/wallet//unlock', methods=['OPTIONS']) - def preflight(request, walletname): - print(request) + # handling CORS preflight for any route: + @app.route('/', branch=True, methods=['OPTIONS']) + def preflight(request): + print_req(request) request.setHeader("Access-Control-Allow-Origin", "*") request.setHeader("Access-Control-Allow-Methods", "POST") - request.setHeader("Access-Control-Allow-Headers", "Content-Type") - - @app.route('/wallet//display', methods=['OPTIONS']) - def preflight2(request, walletname): - print(request) - request.setHeader("Access-Control-Allow-Origin", "*") - request.setHeader("Access-Control-Allow-Methods", "GET") - request.setHeader("Access-Control-Allow-Headers", "Content-Type") + # "Cookie" is reserved so we specifically allow our custom cookie using + # name "JMCookie". + request.setHeader("Access-Control-Allow-Headers", "Content-Type, JMCookie") + + @app.route('/wallet//lock', methods=['GET']) + def lockwallet(request, walletname): + global wallet_service + print_req(request) + check_cookie(request) + if not wallet_service: + print("called lock but no wallet loaded") + raise NoWalletFound() + else: + wallet_service.stopService() + # reset local reference to null + wallet_service = None + # success status implicit: + return response(request, walletname=walletname) @app.route('/wallet//unlock', methods=['POST']) def unlockwallet(request, walletname): - print(request) + global wallet_service + global cookie + print_req(request) assert isinstance(request.content, BytesIO) - passwordjson = request.content.read().decode("utf-8") - password = json.loads(passwordjson)["password"] - nonlocal wallet_service + auth_json = json.loads(request.content.read().decode("utf-8")) + password = auth_json["password"] if wallet_service is None: wallet_path = get_wallet_path(walletname, None) - wallet = open_test_wallet_maybe( - wallet_path, walletname, 4, - password=password.encode("utf-8"), - ask_for_password=False) + try: + wallet = open_test_wallet_maybe( + wallet_path, walletname, 4, + password=password.encode("utf-8"), + ask_for_password=False) + except StoragePasswordError: + raise NotAuthorized("invalid password") + except StorageError as e: + # e.g. .lock file exists: + raise NotAuthorized(repr(e)) + + # since wallet loaded correctly, authorization is passed, so set + # cookie for this wallet (currently THE wallet, daemon does not + # yet support multiple). This is maintained for as long as the + # daemon is active (i.e. no expiry currently implemented), + # or until the user switches to a new wallet. + cookie = request.getHeader(b"JMCookie") + if cookie is None: + # TODO different error class? this could mislead: + raise NotAuthorized() + + # the daemon blocks here until the wallet synchronization + # from the blockchain interface completes; currently this is + # fine as long as the client handles the response asynchronously: wallet_service = WalletService(wallet) while not wallet_service.synced: wallet_service.sync_wallet(fast=True) wallet_service.startService() + # now that the WalletService instance is active and ready to + # respond to requests, we return the status to the client: return response(request, walletname=walletname, already_loaded=False) else: print('wallet was already unlocked.') From eb4b064dfda62598a6430b6d28f5dcce6abd7cfb Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Thu, 27 Aug 2020 16:19:15 +0100 Subject: [PATCH 03/12] encapsulate WalletDaemon as a Service --- scripts/jmwalletd.py | 115 ++++++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 51 deletions(-) diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index d382f6189..2ffaf3246 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -9,6 +9,7 @@ from twisted.python.log import startLogging from twisted.internet import endpoints, reactor, ssl from twisted.web.server import Site +from twisted.application.service import Service from klein import Klein from optparse import OptionParser @@ -20,10 +21,6 @@ jlog = get_log() -# only serving single concurrent user for now; cookie global: -cookie = None -wallet_service = None - # for debugging; twisted.web.server.Request objects do not easily serialize: def print_req(request): print(request) @@ -59,56 +56,60 @@ def response(request, succeed=True, status=200, **kwargs): return json.dumps( [{'succeed': succeed, 'status': status, **kwargs}]) -def check_cookie(request): - request_cookie = request.getHeader(b"JMCookie") - if cookie != request_cookie: - print("Invalid cookie: ", request_cookie) - raise NotAuthorized() - -def start_REST_server(port): - app = Klein() - reactor.listenSSL(port, Site(app.resource()), contextFactory=get_ssl_context(".")) - return app - -def jmwalletd_main(): - import sys - parser = OptionParser(usage='usage: %prog [options] [wallet file]') - parser.add_option('-p', '--port', action='store', type='int', - dest='port', default=28183, - help='the port over which to serve RPC') - # TODO: remove the non-relevant base options: - add_base_options(parser) - - (options, args) = parser.parse_args() - load_program_config(config_path=options.datadir) - app = start_REST_server(options.port) +class JMWalletDaemon(Service): + app = Klein() + def __init__(self, port, wallet_service=None): + # only serving single concurrent user for now; + # cookie tracks that single user's state. + self.cookie = None + self.port = port + self.wallet_service = wallet_service + + def startService(self): + """ Encapsulates start up actions. + Here starting the TLS server. + """ + super().startService() + reactor.listenSSL(self.port, Site(self.app.resource()), + contextFactory=get_ssl_context(".")) + + def stopService(self): + """ Encapsulates shut down actions. + """ + super().stopService() @app.handle_errors(NotAuthorized) - def not_authorized(request, failure): + def not_authorized(self, request, failure): request.setResponseCode(401) return "Invalid credentials." @app.handle_errors(NoWalletFound) - def no_wallet_found(request, failure): + def no_wallet_found(self, request, failure): request.setResponseCode(404) return "No wallet loaded." + def check_cookie(self, request): + request_cookie = request.getHeader(b"JMCookie") + if self.cookie != request_cookie: + print("Invalid cookie: ", request_cookie) + raise NotAuthorized() + @app.route('/wallet//display', methods=['GET']) - def displaywallet(request, walletname): + def displaywallet(self, request, walletname): print_req(request) - check_cookie(request) - if not wallet_service: + self.check_cookie(request) + if not self.wallet_service: print("called display but no wallet loaded") raise NoWalletFound() else: - walletinfo = wallet_display(wallet_service, False, jsonified=True) + walletinfo = wallet_display(self.wallet_service, False, jsonified=True) return response(request, walletname=walletname, walletinfo=walletinfo) # handling CORS preflight for any route: @app.route('/', branch=True, methods=['OPTIONS']) - def preflight(request): + def preflight(self, request): print_req(request) request.setHeader("Access-Control-Allow-Origin", "*") request.setHeader("Access-Control-Allow-Methods", "POST") @@ -117,29 +118,25 @@ def preflight(request): request.setHeader("Access-Control-Allow-Headers", "Content-Type, JMCookie") @app.route('/wallet//lock', methods=['GET']) - def lockwallet(request, walletname): - global wallet_service + def lockwallet(self, request, walletname): print_req(request) - check_cookie(request) - if not wallet_service: + self.check_cookie(request) + if not self.wallet_service: print("called lock but no wallet loaded") raise NoWalletFound() else: - wallet_service.stopService() - # reset local reference to null - wallet_service = None + self.wallet_service.stopService() + self.wallet_service = None # success status implicit: return response(request, walletname=walletname) @app.route('/wallet//unlock', methods=['POST']) - def unlockwallet(request, walletname): - global wallet_service - global cookie + def unlockwallet(self, request, walletname): print_req(request) assert isinstance(request.content, BytesIO) auth_json = json.loads(request.content.read().decode("utf-8")) password = auth_json["password"] - if wallet_service is None: + if self.wallet_service is None: wallet_path = get_wallet_path(walletname, None) try: wallet = open_test_wallet_maybe( @@ -157,18 +154,18 @@ def unlockwallet(request, walletname): # yet support multiple). This is maintained for as long as the # daemon is active (i.e. no expiry currently implemented), # or until the user switches to a new wallet. - cookie = request.getHeader(b"JMCookie") - if cookie is None: + self.cookie = request.getHeader(b"JMCookie") + if self.cookie is None: # TODO different error class? this could mislead: raise NotAuthorized() # the daemon blocks here until the wallet synchronization # from the blockchain interface completes; currently this is # fine as long as the client handles the response asynchronously: - wallet_service = WalletService(wallet) - while not wallet_service.synced: - wallet_service.sync_wallet(fast=True) - wallet_service.startService() + self.wallet_service = WalletService(wallet) + while not self.wallet_service.synced: + self.wallet_service.sync_wallet(fast=True) + self.wallet_service.startService() # now that the WalletService instance is active and ready to # respond to requests, we return the status to the client: return response(request, walletname=walletname, already_loaded=False) @@ -176,12 +173,28 @@ def unlockwallet(request, walletname): print('wallet was already unlocked.') return response(request, walletname=walletname, already_loaded=True) +def jmwalletd_main(): + import sys + parser = OptionParser(usage='usage: %prog [options] [wallet file]') + parser.add_option('-p', '--port', action='store', type='int', + dest='port', default=28183, + help='the port over which to serve RPC') + # TODO: remove the non-relevant base options: + add_base_options(parser) + + (options, args) = parser.parse_args() + + load_program_config(config_path=options.datadir) + if jm_single().bc_interface is None: jlog.error("Running jmwallet-daemon requires configured " + "blockchain source.") sys.exit(EXIT_FAILURE) jlog.info("Starting jmwalletd") + jm_wallet_daemon = JMWalletDaemon(options.port) + jm_wallet_daemon.startService() + nodaemon = jm_single().config.getint("DAEMON", "no_daemon") daemon = True if nodaemon == 1 else False if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]: From 30ccf52ac341bdacc06d2c8ea90d138af5a9dc6e Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Mon, 31 Aug 2020 16:04:40 +0100 Subject: [PATCH 04/12] add snicker receiver service start, stop --- jmclient/jmclient/__init__.py | 6 +- jmclient/jmclient/client_protocol.py | 18 ++++- jmclient/jmclient/snicker_receiver.py | 47 ++++++++++- scripts/jmwalletd.py | 110 ++++++++++++++++++++++++-- 4 files changed, 170 insertions(+), 11 deletions(-) diff --git a/jmclient/jmclient/__init__.py b/jmclient/jmclient/__init__.py index 1a900fa51..7bd381b4a 100644 --- a/jmclient/jmclient/__init__.py +++ b/jmclient/jmclient/__init__.py @@ -30,7 +30,8 @@ from .snicker_receiver import SNICKERError, SNICKERReceiver from .client_protocol import (JMTakerClientProtocol, JMClientProtocolFactory, start_reactor, SNICKERClientProtocolFactory, - BIP78ClientProtocolFactory) + BIP78ClientProtocolFactory, + get_daemon_serving_params) from .podle import (set_commitment_file, get_commitment_file, add_external_commitments, PoDLE, generate_podle, get_podle_commitments, @@ -58,7 +59,8 @@ from .wallet_service import WalletService from .maker import Maker from .yieldgenerator import YieldGenerator, YieldGeneratorBasic, ygmain -from .payjoin import (parse_payjoin_setup, send_payjoin, +from .snicker_receiver import SNICKERError, SNICKERReceiver, SNICKERReceiverService +from .payjoin import (parse_payjoin_setup, send_payjoin, PayjoinServer, JMBIP78ReceiverManager) # Set default logging handler to avoid "No handler found" warnings. diff --git a/jmclient/jmclient/client_protocol.py b/jmclient/jmclient/client_protocol.py index 6bae76c34..a824f8aff 100644 --- a/jmclient/jmclient/client_protocol.py +++ b/jmclient/jmclient/client_protocol.py @@ -20,6 +20,15 @@ SNICKERReceiver, process_shutdown) import jmbitcoin as btc +# module level variable representing the port +# on which the daemon is running. +# note that this var is only set if we are running +# client+daemon in one process. +daemon_serving_port = -1 +daemon_serving_host = "" + +def get_daemon_serving_params(): + return (daemon_serving_host, daemon_serving_port) jlog = get_log() @@ -787,9 +796,9 @@ def start_reactor(host, port, factory=None, snickerfactory=None, #(Cannot start the reactor in tests) #Not used in prod (twisted logging): #startLogging(stdout) - usessl = True if jm_single().config.get("DAEMON", - "use_ssl") != 'false' else False - + global daemon_serving_host + global daemon_serving_port + usessl = True if jm_single().config.get("DAEMON", "use_ssl") != 'false' else False jmcport, snickerport, bip78port = [port]*3 if daemon: try: @@ -829,6 +838,9 @@ def start_daemon_on_port(p, f, name, port_offset): p[0] += 1 return p[0] + daemon_serving_port = port + daemon_serving_host = host + if jm_coinjoin: # TODO either re-apply this port incrementing logic # to other protocols, or re-work how the ports work entirely. diff --git a/jmclient/jmclient/snicker_receiver.py b/jmclient/jmclient/snicker_receiver.py index cdc2f03e7..a17f40651 100644 --- a/jmclient/jmclient/snicker_receiver.py +++ b/jmclient/jmclient/snicker_receiver.py @@ -1,5 +1,8 @@ #! /usr/bin/env python +import os +from twisted.application.service import Service +from twisted.internet import task import jmbitcoin as btc from jmclient.configure import jm_single from jmbase import (get_log, utxo_to_utxostr, @@ -11,7 +14,45 @@ class SNICKERError(Exception): pass -class SNICKERReceiver(Service): +class SNICKERReceiverService(Service): + def __init__(self, receiver): + assert isinstance(receiver, SNICKERReceiver) + self.receiver = receiver + # main monitor loop + self.monitor_loop = task.LoopingCall(self.receiver.poll_for_proposals) + + def startService(self): + """ Encapsulates start up actions. + This service depends on the receiver's + wallet service to start, so wait for that. + """ + self.wait_for_wallet = task.LoopingCall(self.wait_for_wallet_sync) + self.wait_for_wallet.start(5.0) + + def wait_for_wallet_sync(self): + if self.receiver.wallet_service.isRunning(): + jlog.info("SNICKER service starting because wallet service is up.") + self.wait_for_wallet.stop() + self.monitor_loop.start(5.0) + super().startService() + + def stopService(self, wallet=False): + """ Encapsulates shut down actions. + Optionally also shut down the underlying + wallet service (default False). + """ + if self.monitor_loop: + self.monitor_loop.stop() + if wallet: + self.receiver.wallet_service.stopService() + super().stopService() + + def isRunning(self): + if self.running == 1: + return True + return False + +class SNICKERReceiver(object): supported_flags = [] def __init__(self, wallet_service, acceptance_callback=None, @@ -66,6 +107,10 @@ def __init__(self, wallet_service, acceptance_callback=None, def default_info_callback(self, msg): jlog.info(msg) + if not os.path.exists(self.proposals_source): + with open(self.proposals_source, "wb") as f: + jlog.info("created proposals source file.") + def default_acceptance_callback(self, our_ins, their_ins, our_outs, their_outs): diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index 2ffaf3246..7d530bf45 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -7,7 +7,7 @@ import json from io import BytesIO from twisted.python.log import startLogging -from twisted.internet import endpoints, reactor, ssl +from twisted.internet import endpoints, reactor, ssl, task from twisted.web.server import Site from twisted.application.service import Service from klein import Klein @@ -16,7 +16,10 @@ from jmbase import get_log from jmclient import Maker, jm_single, load_program_config, \ JMClientProtocolFactory, start_reactor, calc_cj_fee, \ - WalletService, add_base_options, get_wallet_path, open_test_wallet_maybe, wallet_display + WalletService, add_base_options, get_wallet_path, \ + open_test_wallet_maybe, wallet_display, YieldGenerator, \ + get_daemon_serving_params, YieldGeneratorBasic, \ + SNICKERReceiverService, SNICKERReceiver from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE jlog = get_log() @@ -37,6 +40,20 @@ class NotAuthorized(Exception): class NoWalletFound(Exception): pass +class InvalidRequestFormat(Exception): + pass + +class BackendNotReady(Exception): + pass + +# error class for services which are only +# started once: +class ServiceAlreadyStarted(Exception): + pass + +class ServiceNotStarted(Exception): + pass + def get_ssl_context(cert_directory): """Construct an SSL context factory from the user's privatekey/cert. TODO: @@ -56,8 +73,6 @@ def response(request, succeed=True, status=200, **kwargs): return json.dumps( [{'succeed': succeed, 'status': status, **kwargs}]) - - class JMWalletDaemon(Service): app = Klein() def __init__(self, port, wallet_service=None): @@ -66,6 +81,9 @@ def __init__(self, port, wallet_service=None): self.cookie = None self.port = port self.wallet_service = wallet_service + # Client may start snicker service, but only + # one instance. + self.snicker_service = None def startService(self): """ Encapsulates start up actions. @@ -90,6 +108,25 @@ def no_wallet_found(self, request, failure): request.setResponseCode(404) return "No wallet loaded." + @app.handle_errors(BackendNotReady) + def backend_not_ready(self, request, failure): + request.setResponseCode(500) + return "Backend daemon not available" + + @app.handle_errors(InvalidRequestFormat) + def invalid_request_format(self, request, failure): + request.setResponseCode(401) + return "Invalid request format." + + @app.handle_errors(ServiceAlreadyStarted) + def service_already_started(self, request, failure): + request.setResponseCode(401) + return "Service already started." + + def service_not_started(self, request, failure): + request.setResponseCode(401) + return "Service cannot be stopped as it is not running." + def check_cookie(self, request): request_cookie = request.getHeader(b"JMCookie") if self.cookie != request_cookie: @@ -117,6 +154,51 @@ def preflight(self, request): # name "JMCookie". request.setHeader("Access-Control-Allow-Headers", "Content-Type, JMCookie") + @app.route('/wallet//snicker/start', methods=['GET']) + def start_snicker(self, request, walletname): + if not self.wallet_service: + raise NoWalletFound() + if self.snicker_service and self.snicker_service.isRunning(): + raise ServiceAlreadyStarted() + # TODO: allow client to inject acceptance callbacks to Receiver + self.snicker_service = SNICKERReceiverService( + SNICKERReceiver(self.wallet_service)) + self.snicker_service.startService() + # TODO waiting for startup seems perhaps not needed here? + return response(request, walletname=walletname) + + @app.route('/wallet//snicker/stop', methods=['GET']) + def stop_snicker(self, request, walletname): + if not self.wallet_service: + raise NoWalletFound() + if not self.snicker_service: + raise ServiceNotStarted() + self.snicker_service.stopService() + return response(request, walletname=walletname) + + @app.route('/wallet//maker/start', methods=['POST']) + def start_maker(self, request, walletname): + """ Use the configuration in the POST body to start the yield generator: + """ + assert isinstance(request.content, BytesIO) + config_json = self.get_POST_body(request, ["txfee", "cjfee_a", "cjfee_r", + "ordertype", "minsize"]) + if not config_json: + raise InvalidRequestFormat() + if not self.wallet_service: + raise NoWalletFound() + maker = YieldGeneratorBasic(self.wallet_service, + [config_json[x] for x in ["txfee", "cjfee_a", + "cjfee_r", "ordertype", "minsize"]]) + jlog.info('starting yield generator') + clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER") + daemon_serving_host, daemon_serving_port = get_daemon_serving_params() + print("host and port in use: ", daemon_serving_host, daemon_serving_port) + if daemon_serving_port == -1 or daemon_serving_host == "": + raise BackendNotReady() + reactor.connectTCP(daemon_serving_host, daemon_serving_port, clientfactory) + return response(request, walletname=walletname) + @app.route('/wallet//lock', methods=['GET']) def lockwallet(self, request, walletname): print_req(request) @@ -130,11 +212,29 @@ def lockwallet(self, request, walletname): # success status implicit: return response(request, walletname=walletname) + def get_POST_body(self, request, keys): + """ given a request object, retrieve values corresponding + to keys keys in a dict, assuming they were encoded using JSON. + If *any* of the keys are not present, return False, else + returns a dict of those key-value pairs. + """ + assert isinstance(request.content, BytesIO) + json_data = json.loads(request.content.read().decode("utf-8")) + retval = {} + for k in keys: + if k in json_data: + retval[k] = json_data[k] + else: + return False + return retval + @app.route('/wallet//unlock', methods=['POST']) def unlockwallet(self, request, walletname): print_req(request) assert isinstance(request.content, BytesIO) - auth_json = json.loads(request.content.read().decode("utf-8")) + auth_json = self.get_POST_body(request, ["password"]) + if not auth_json: + raise InvalidRequestFormat() password = auth_json["password"] if self.wallet_service is None: wallet_path = get_wallet_path(walletname, None) From 3593c768effa6aeb92e5258c2cca6c93e0d50820 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Thu, 3 Sep 2020 12:14:25 +0100 Subject: [PATCH 05/12] Maker function as stoppable service. This commit adds a JMShutdown command to the AMP protocol, allowing a clean shutdown of a long running bot (e.g. maker) by shutting down its message channel connections. The yield generator is now made a Service. --- jmbase/jmbase/commands.py | 7 +++ jmclient/jmclient/__init__.py | 3 +- jmclient/jmclient/client_protocol.py | 9 +++ jmclient/jmclient/yieldgenerator.py | 37 +++++++++++++ jmdaemon/jmdaemon/daemon_protocol.py | 6 ++ jmdaemon/jmdaemon/irc.py | 12 +++- scripts/jmwalletd.py | 82 +++++++++++++++++++++------- 7 files changed, 132 insertions(+), 24 deletions(-) diff --git a/jmbase/jmbase/commands.py b/jmbase/jmbase/commands.py index ec039c3a7..8134988aa 100644 --- a/jmbase/jmbase/commands.py +++ b/jmbase/jmbase/commands.py @@ -67,6 +67,13 @@ class JMMsgSignatureVerify(JMCommand): (b'fullmsg', Unicode()), (b'hostid', Unicode())] +class JMShutdown(JMCommand): + """ Requests shutdown of the current + message channel connections (to be used + when the client is shutting down). + """ + arguments = [] + """TAKER specific commands """ diff --git a/jmclient/jmclient/__init__.py b/jmclient/jmclient/__init__.py index 7bd381b4a..706d35a3d 100644 --- a/jmclient/jmclient/__init__.py +++ b/jmclient/jmclient/__init__.py @@ -58,7 +58,8 @@ wallet_change_passphrase) from .wallet_service import WalletService from .maker import Maker -from .yieldgenerator import YieldGenerator, YieldGeneratorBasic, ygmain +from .yieldgenerator import YieldGenerator, YieldGeneratorBasic, ygmain, \ + YieldGeneratorService from .snicker_receiver import SNICKERError, SNICKERReceiver, SNICKERReceiverService from .payjoin import (parse_payjoin_setup, send_payjoin, PayjoinServer, JMBIP78ReceiverManager) diff --git a/jmclient/jmclient/client_protocol.py b/jmclient/jmclient/client_protocol.py index a824f8aff..12f09f47b 100644 --- a/jmclient/jmclient/client_protocol.py +++ b/jmclient/jmclient/client_protocol.py @@ -376,6 +376,15 @@ def make_tx(self, nick_list, txhex): txhex=txhex) self.defaultCallbacks(d) + def request_mc_shutdown(self): + """ To ensure that lingering message channel + connections are shut down when the client itself + is shutting down. + """ + d = self.callRemote(commands.JMShutdown) + self.defaultCallbacks(d) + return {'accepted': True} + class JMMakerClientProtocol(JMClientProtocol): def __init__(self, factory, maker, nick_priv=None): self.factory = factory diff --git a/jmclient/jmclient/yieldgenerator.py b/jmclient/jmclient/yieldgenerator.py index 9f8c4bb3d..b846fc711 100644 --- a/jmclient/jmclient/yieldgenerator.py +++ b/jmclient/jmclient/yieldgenerator.py @@ -6,6 +6,7 @@ import abc import base64 from twisted.python.log import startLogging +from twisted.application.service import Service from optparse import OptionParser from jmbase import get_log from jmclient import (Maker, jm_single, load_program_config, @@ -226,6 +227,42 @@ def select_output_address(self, input_mixdepth, offer, amount): cjoutmix = (input_mixdepth + 1) % (self.wallet_service.mixdepth + 1) return self.wallet_service.get_internal_addr(cjoutmix) +class YieldGeneratorService(Service): + def __init__(self, wallet_service, yg_config): + self.wallet_service = wallet_service + self.yg_config = yg_config + self.yieldgen = None + + def startService(self): + """ We instantiate the Maker class only + here as its constructor will automatically + create orders based on the wallet. + Note makers already intrinsically handle + not-yet-synced wallet services, so there is + no need to check this here. + """ + # TODO genericise to any YG class: + self.yieldgen = YieldGeneratorBasic(self.wallet_service, self.yg_config) + self.clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER") + + nodaemon = jm_single().config.getint("DAEMON", "no_daemon") + daemon = True if nodaemon == 1 else False + if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]: + startLogging(sys.stdout) + # here 'start_reactor' does not start the reactor but instantiates + # the connection to the daemon backend. + start_reactor(jm_single().config.get("DAEMON", "daemon_host"), + jm_single().config.getint("DAEMON", "daemon_port"), + self.clientfactory, rs=False) + super().startService() + + def stopService(self): + """ TODO need a method exposed to gracefully + shut down a maker bot. + """ + jlog.info("Shutting down YieldGenerator service.") + self.clientfactory.proto_client.request_mc_shutdown() + super().stopService() def ygmain(ygclass, nickserv_password='', gaplimit=6): import sys diff --git a/jmdaemon/jmdaemon/daemon_protocol.py b/jmdaemon/jmdaemon/daemon_protocol.py index c2992fd29..49782bdfe 100644 --- a/jmdaemon/jmdaemon/daemon_protocol.py +++ b/jmdaemon/jmdaemon/daemon_protocol.py @@ -585,6 +585,12 @@ def on_JM_MSGSIGNATURE_VERIFY(self, verif_result, nick, fullmsg, hostid): self.mcc.on_verified_privmsg(nick, fullmsg, hostid) return {'accepted': True} + @JMShutdown.responder + def on_JM_SHUTDOWN(self): + self.mc_shutdown() + self.jm_state = 0 + return {'accepted': True} + """Taker specific responders """ diff --git a/jmdaemon/jmdaemon/irc.py b/jmdaemon/jmdaemon/irc.py index 25e25e61d..3697b3513 100644 --- a/jmdaemon/jmdaemon/irc.py +++ b/jmdaemon/jmdaemon/irc.py @@ -105,6 +105,10 @@ def __init__(self, self.tx_irc_client = None #TODO can be configuration var, how long between reconnect attempts: self.reconnect_interval = 10 + + # service is used to wrap endpoints for Tor connections: + self.reconnecting_service = None + #implementation of abstract base class methods; #these are mostly but not exclusively acting as pass through #to the wrapped twisted IRC client protocol @@ -115,6 +119,8 @@ def run(self): def shutdown(self): self.tx_irc_client.quit() self.give_up = True + if self.reconnecting_service: + self.reconnecting_service.stopService() def _pubmsg(self, msg): self.tx_irc_client._pubmsg(msg) @@ -157,8 +163,8 @@ def build_irc(self): use_tls = False ircEndpoint = TorSocksEndpoint(torEndpoint, self.serverport[0], self.serverport[1], tls=use_tls) - myRS = ClientService(ircEndpoint, factory) - myRS.startService() + self.reconnecting_service = ClientService(ircEndpoint, factory) + self.reconnecting_service.startService() else: try: factory = TxIRCFactory(self) @@ -203,7 +209,7 @@ def connectionMade(self): def connectionLost(self, reason=protocol.connectionDone): wlog("INFO", "Lost IRC connection to: " + str(self.hostname) + " . Should reconnect automatically soon.") - if self.wrapper.on_disconnect: + if not self.wrapper.give_up and self.wrapper.on_disconnect: reactor.callLater(0.0, self.wrapper.on_disconnect, self.wrapper) return irc.IRCClient.connectionLost(self, reason) diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index 7d530bf45..fa8cc32b3 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -5,6 +5,7 @@ import time import abc import json +import atexit from io import BytesIO from twisted.python.log import startLogging from twisted.internet import endpoints, reactor, ssl, task @@ -18,7 +19,7 @@ JMClientProtocolFactory, start_reactor, calc_cj_fee, \ WalletService, add_base_options, get_wallet_path, \ open_test_wallet_maybe, wallet_display, YieldGenerator, \ - get_daemon_serving_params, YieldGeneratorBasic, \ + get_daemon_serving_params, YieldGeneratorService, \ SNICKERReceiverService, SNICKERReceiver from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE @@ -74,28 +75,56 @@ def response(request, succeed=True, status=200, **kwargs): [{'succeed': succeed, 'status': status, **kwargs}]) class JMWalletDaemon(Service): + """ This class functions as an HTTP/TLS server, + with acccess control, allowing a single client(user) + to control functioning of encapsulated Joinmarket services. + """ + app = Klein() - def __init__(self, port, wallet_service=None): - # only serving single concurrent user for now; - # cookie tracks that single user's state. + def __init__(self, port): + """ Port is the port to serve this daemon + (using HTTP/TLS). + """ + # cookie tracks single user's state. self.cookie = None self.port = port - self.wallet_service = wallet_service - # Client may start snicker service, but only + # the collection of services which this + # daemon may switch on and off: + self.services = {} + # master single wallet service which we + # allow the client to start/stop. + self.services["wallet"] = None + # label for convenience: + self.wallet_service = self.services["wallet"] + # Client may start other services, but only # one instance. - self.snicker_service = None + self.services["snicker"] = None + self.services["maker"] = None + # ensure shut down does not leave dangling services: + atexit.register(self.stopService) def startService(self): """ Encapsulates start up actions. Here starting the TLS server. """ super().startService() + # we do not auto-start any service, including the base + # wallet service, since the client must actively request + # that with the appropriate credential (password). reactor.listenSSL(self.port, Site(self.app.resource()), contextFactory=get_ssl_context(".")) def stopService(self): """ Encapsulates shut down actions. """ + # Currently valid authorization tokens must be removed + # from the daemon: + self.cookie = None + # if the wallet-daemon is shut down, all services + # it encapsulates must also be shut down. + for name, service in self.services.items(): + if service: + service.stopService() super().stopService() @app.handle_errors(NotAuthorized) @@ -130,7 +159,8 @@ def service_not_started(self, request, failure): def check_cookie(self, request): request_cookie = request.getHeader(b"JMCookie") if self.cookie != request_cookie: - print("Invalid cookie: ", request_cookie) + jlog.warn("Invalid cookie: " + str( + request_cookie) + ", request rejected.") raise NotAuthorized() @app.route('/wallet//display', methods=['GET']) @@ -156,24 +186,26 @@ def preflight(self, request): @app.route('/wallet//snicker/start', methods=['GET']) def start_snicker(self, request, walletname): + self.check_cookie(request) if not self.wallet_service: raise NoWalletFound() - if self.snicker_service and self.snicker_service.isRunning(): + if self.services["snicker"] and self.services["snicker"].isRunning(): raise ServiceAlreadyStarted() # TODO: allow client to inject acceptance callbacks to Receiver - self.snicker_service = SNICKERReceiverService( + self.services["snicker"] = SNICKERReceiverService( SNICKERReceiver(self.wallet_service)) - self.snicker_service.startService() + self.services["snicker"].startService() # TODO waiting for startup seems perhaps not needed here? return response(request, walletname=walletname) @app.route('/wallet//snicker/stop', methods=['GET']) def stop_snicker(self, request, walletname): + self.check_cookie(request) if not self.wallet_service: raise NoWalletFound() - if not self.snicker_service: + if not self.services["snicker"]: raise ServiceNotStarted() - self.snicker_service.stopService() + self.services["snicker"].stopService() return response(request, walletname=walletname) @app.route('/wallet//maker/start', methods=['POST']) @@ -187,16 +219,26 @@ def start_maker(self, request, walletname): raise InvalidRequestFormat() if not self.wallet_service: raise NoWalletFound() - maker = YieldGeneratorBasic(self.wallet_service, - [config_json[x] for x in ["txfee", "cjfee_a", - "cjfee_r", "ordertype", "minsize"]]) - jlog.info('starting yield generator') - clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER") + + # daemon must be up before this is started; check: daemon_serving_host, daemon_serving_port = get_daemon_serving_params() - print("host and port in use: ", daemon_serving_host, daemon_serving_port) if daemon_serving_port == -1 or daemon_serving_host == "": raise BackendNotReady() - reactor.connectTCP(daemon_serving_host, daemon_serving_port, clientfactory) + + self.services["maker"] = YieldGeneratorService(self.wallet_service, + [config_json[x] for x in ["txfee", "cjfee_a", + "cjfee_r", "ordertype", "minsize"]]) + self.services["maker"].startService() + return response(request, walletname=walletname) + + @app.route('/wallet//maker/stop', methods=['GET']) + def stop_maker(self, request, walletname): + self.check_cookie(request) + if not self.wallet_service: + raise NoWalletFound() + if not self.services["maker"]: + raise ServiceNotStarted() + self.services["maker"].stopService() return response(request, walletname=walletname) @app.route('/wallet//lock', methods=['GET']) From 5f41f615976b5fa73674bcc28f32bca12e871e06 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Mon, 14 Sep 2020 13:55:19 +0100 Subject: [PATCH 06/12] add create wallet rpc --- scripts/jmwalletd.py | 99 +++++++++++++++++++++++++++++++++----------- 1 file changed, 74 insertions(+), 25 deletions(-) diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index fa8cc32b3..a11760915 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -18,9 +18,9 @@ from jmclient import Maker, jm_single, load_program_config, \ JMClientProtocolFactory, start_reactor, calc_cj_fee, \ WalletService, add_base_options, get_wallet_path, \ - open_test_wallet_maybe, wallet_display, YieldGenerator, \ - get_daemon_serving_params, YieldGeneratorService, \ - SNICKERReceiverService, SNICKERReceiver + open_test_wallet_maybe, wallet_display, SegwitLegacyWallet, \ + SegwitWallet, get_daemon_serving_params, YieldGeneratorService, \ + SNICKERReceiverService, SNICKERReceiver, create_wallet, StorageError from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE jlog = get_log() @@ -52,6 +52,10 @@ class BackendNotReady(Exception): class ServiceAlreadyStarted(Exception): pass +# for the special case of the wallet service: +class WalletAlreadyUnlocked(Exception): + pass + class ServiceNotStarted(Exception): pass @@ -152,6 +156,11 @@ def service_already_started(self, request, failure): request.setResponseCode(401) return "Service already started." + @app.handle_errors(WalletAlreadyUnlocked) + def wallet_already_unlocked(self, request, failure): + request.setResponseCode(401) + return "Wallet already unlocked." + def service_not_started(self, request, failure): request.setResponseCode(401) return "Service cannot be stopped as it is not running." @@ -270,6 +279,64 @@ def get_POST_body(self, request, keys): return False return retval + @app.route('/wallet/create', methods=["POST"]) + def createwallet(self, request): + print_req(request) + + # we only handle one wallet at a time; + # if there is a currently unlocked wallet, + # refuse to process the request: + if self.wallet_service: + raise WalletAlreadyUnlocked() + + request_data = self.get_POST_body(request, + ["walletname", "password", "wallettype"]) + if not request_data or request_data["wallettype"] not in [ + "sw", "sw-legacy"]: + raise InvalidRequestFormat() + + wallet_cls = SegwitWallet if request_data[ + "wallettype"]=="sw" else SegwitLegacyWallet + + # use the config's data location combined with the json + # data to construct the wallet path: + wallet_root_path = os.path.join(jm_single().datadir, "wallets") + wallet_name = os.path.join(wallet_root_path, request_data["walletname"]) + try: + wallet = create_wallet(wallet_name, request_data["password"], + 4, wallet_cls=wallet_cls) + except StorageError as e: + raise NotAuthorized(repr(e)) + + # finally, after the wallet is successfully created, we should + # start the wallet service: + return self.initialize_wallet_service(request, wallet) + + def initialize_wallet_service(self, request, wallet): + """ Called only when the wallet has loaded correctly, so + authorization is passed, so set cookie for this wallet + (currently THE wallet, daemon does not yet support multiple). + This is maintained for as long as the daemon is active (i.e. + no expiry currently implemented), or until the user switches + to a new wallet. + """ + self.cookie = request.getHeader(b"JMCookie") + if self.cookie is None: + raise NotAuthorized("No cookie") + + # the daemon blocks here until the wallet synchronization + # from the blockchain interface completes; currently this is + # fine as long as the client handles the response asynchronously: + self.wallet_service = WalletService(wallet) + while not self.wallet_service.synced: + self.wallet_service.sync_wallet(fast=True) + self.wallet_service.startService() + # now that the WalletService instance is active and ready to + # respond to requests, we return the status to the client: + return response(request, + walletname=self.wallet_service.get_wallet_name(), + already_loaded=False) + @app.route('/wallet//unlock', methods=['POST']) def unlockwallet(self, request, walletname): print_req(request) @@ -290,30 +357,12 @@ def unlockwallet(self, request, walletname): except StorageError as e: # e.g. .lock file exists: raise NotAuthorized(repr(e)) - - # since wallet loaded correctly, authorization is passed, so set - # cookie for this wallet (currently THE wallet, daemon does not - # yet support multiple). This is maintained for as long as the - # daemon is active (i.e. no expiry currently implemented), - # or until the user switches to a new wallet. - self.cookie = request.getHeader(b"JMCookie") - if self.cookie is None: - # TODO different error class? this could mislead: - raise NotAuthorized() - - # the daemon blocks here until the wallet synchronization - # from the blockchain interface completes; currently this is - # fine as long as the client handles the response asynchronously: - self.wallet_service = WalletService(wallet) - while not self.wallet_service.synced: - self.wallet_service.sync_wallet(fast=True) - self.wallet_service.startService() - # now that the WalletService instance is active and ready to - # respond to requests, we return the status to the client: - return response(request, walletname=walletname, already_loaded=False) + return self.initialize_wallet_service(request, wallet) else: print('wallet was already unlocked.') - return response(request, walletname=walletname, already_loaded=True) + return response(request, + walletname=self.wallet_service.get_wallet_name(), + already_loaded=True) def jmwalletd_main(): import sys From e7ba21eb499bbc83b567bd4e300e337986acab5c Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Sat, 21 Nov 2020 14:53:24 +0000 Subject: [PATCH 07/12] Ensure maker client connects to correct daemon Access the port that was chosen (to avoid conflicting with other simultaneously running jmdaemon instances, especially in test scenarios) in the jmwalletd startup, and use that in starting the YieldGenerator service. Also fixes a bug in YieldGenerator service startup - self.yieldgen not maker. --- jmclient/jmclient/yieldgenerator.py | 25 +++++++++++-------------- scripts/jmwalletd.py | 1 + 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/jmclient/jmclient/yieldgenerator.py b/jmclient/jmclient/yieldgenerator.py index b846fc711..4ddee70cb 100644 --- a/jmclient/jmclient/yieldgenerator.py +++ b/jmclient/jmclient/yieldgenerator.py @@ -228,8 +228,10 @@ def select_output_address(self, input_mixdepth, offer, amount): return self.wallet_service.get_internal_addr(cjoutmix) class YieldGeneratorService(Service): - def __init__(self, wallet_service, yg_config): + def __init__(self, wallet_service, daemon_host, daemon_port, yg_config): self.wallet_service = wallet_service + self.daemon_host = daemon_host + self.daemon_port = daemon_port self.yg_config = yg_config self.yieldgen = None @@ -243,26 +245,21 @@ def startService(self): """ # TODO genericise to any YG class: self.yieldgen = YieldGeneratorBasic(self.wallet_service, self.yg_config) - self.clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER") - - nodaemon = jm_single().config.getint("DAEMON", "no_daemon") - daemon = True if nodaemon == 1 else False - if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]: - startLogging(sys.stdout) + self.clientfactory = JMClientProtocolFactory(self.yieldgen, proto_type="MAKER") # here 'start_reactor' does not start the reactor but instantiates - # the connection to the daemon backend. - start_reactor(jm_single().config.get("DAEMON", "daemon_host"), - jm_single().config.getint("DAEMON", "daemon_port"), - self.clientfactory, rs=False) + # the connection to the daemon backend; note daemon=False, i.e. the daemon + # backend is assumed to be started elsewhere; we just connect to it with a client. + start_reactor(self.daemon_host, self.daemon_port, self.clientfactory, rs=False) super().startService() def stopService(self): """ TODO need a method exposed to gracefully shut down a maker bot. """ - jlog.info("Shutting down YieldGenerator service.") - self.clientfactory.proto_client.request_mc_shutdown() - super().stopService() + if self.running: + jlog.info("Shutting down YieldGenerator service.") + self.clientfactory.proto_client.request_mc_shutdown() + super().stopService() def ygmain(ygclass, nickserv_password='', gaplimit=6): import sys diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index a11760915..5f4449efd 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -235,6 +235,7 @@ def start_maker(self, request, walletname): raise BackendNotReady() self.services["maker"] = YieldGeneratorService(self.wallet_service, + daemon_serving_host, daemon_serving_port, [config_json[x] for x in ["txfee", "cjfee_a", "cjfee_r", "ordertype", "minsize"]]) self.services["maker"].startService() From 3afab7246f81bb1a37d23d62c505688814829799 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Sun, 22 Nov 2020 12:35:21 +0000 Subject: [PATCH 08/12] Add payment(direct send) request, first draft --- scripts/jmwalletd.py | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index 5f4449efd..33318d8dd 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -15,9 +15,10 @@ from optparse import OptionParser from jmbase import get_log +from jmbitcoin import human_readable_transaction from jmclient import Maker, jm_single, load_program_config, \ JMClientProtocolFactory, start_reactor, calc_cj_fee, \ - WalletService, add_base_options, get_wallet_path, \ + WalletService, add_base_options, get_wallet_path, direct_send, \ open_test_wallet_maybe, wallet_display, SegwitLegacyWallet, \ SegwitWallet, get_daemon_serving_params, YieldGeneratorService, \ SNICKERReceiverService, SNICKERReceiver, create_wallet, StorageError @@ -217,6 +218,25 @@ def stop_snicker(self, request, walletname): self.services["snicker"].stopService() return response(request, walletname=walletname) + @app.route('/wallet//taker/direct-send', methods=['POST']) + def send_direct(self, request, walletname): + """ Use the contents of the POST body to do a direct send from + the active wallet at the chosen mixdepth. + """ + assert isinstance(request.content, BytesIO) + payment_info_json = self.get_POST_body(request, ["mixdepth", "amount_sats", + "destination"]) + if not payment_info_json: + raise InvalidRequestFormat() + if not self.wallet_service: + raise NoWalletFound() + tx = direct_send(self.wallet_service, payment_info_json["amount_sats"], + payment_info_json["mixdepth"], + optin_rbf=payment_info_json["optin_rbf"], + return_transaction=True) + return response(request, walletname=walletname, + txinfo=human_readable_transaction(tx)) + @app.route('/wallet//maker/start', methods=['POST']) def start_maker(self, request, walletname): """ Use the configuration in the POST body to start the yield generator: @@ -370,7 +390,7 @@ def jmwalletd_main(): parser = OptionParser(usage='usage: %prog [options] [wallet file]') parser.add_option('-p', '--port', action='store', type='int', dest='port', default=28183, - help='the port over which to serve RPC') + help='the port over which to serve RPC, default 28183') # TODO: remove the non-relevant base options: add_base_options(parser) @@ -382,7 +402,7 @@ def jmwalletd_main(): jlog.error("Running jmwallet-daemon requires configured " + "blockchain source.") sys.exit(EXIT_FAILURE) - jlog.info("Starting jmwalletd") + jlog.info("Starting jmwalletd on port: " + str(options.port)) jm_wallet_daemon = JMWalletDaemon(options.port) jm_wallet_daemon.startService() From c675075dd66ba2c64f06903e46147abddde30b8c Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Sat, 13 Mar 2021 14:48:32 +0000 Subject: [PATCH 09/12] fix errors from rebase --- jmclient/jmclient/client_protocol.py | 10 +++++----- scripts/jmwalletd.py | 3 ++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/jmclient/jmclient/client_protocol.py b/jmclient/jmclient/client_protocol.py index 12f09f47b..eef4fbd16 100644 --- a/jmclient/jmclient/client_protocol.py +++ b/jmclient/jmclient/client_protocol.py @@ -870,15 +870,15 @@ def start_daemon_on_port(p, f, name, port_offset): # Note the reactor.connect*** entries do not include BIP78 which # starts in jmclient.payjoin: if usessl: - if factory: + if factory: reactor.connectSSL(host, jmcport, factory, ClientContextFactory()) - if snickerfactory: + if snickerfactory: reactor.connectSSL(host, snickerport, snickerfactory, - ClientContextFactory()) + ClientContextFactory()) else: - if factory: + if factory: reactor.connectTCP(host, jmcport, factory) - if snickerfactory: + if snickerfactory: reactor.connectTCP(host, snickerport, snickerfactory) if rs: if not gui: diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index 33318d8dd..d7f1aa91b 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -21,7 +21,8 @@ WalletService, add_base_options, get_wallet_path, direct_send, \ open_test_wallet_maybe, wallet_display, SegwitLegacyWallet, \ SegwitWallet, get_daemon_serving_params, YieldGeneratorService, \ - SNICKERReceiverService, SNICKERReceiver, create_wallet, StorageError + SNICKERReceiverService, SNICKERReceiver, create_wallet, \ + StorageError, StoragePasswordError from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE jlog = get_log() From d5a1ea5d584cdb1a633dcd5e1996bf211fb549e1 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Sat, 13 Mar 2021 17:47:20 +0000 Subject: [PATCH 10/12] add RPC documentation file --- docs/JSON-RPC-API-using-jmwalletd.md | 118 +++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 docs/JSON-RPC-API-using-jmwalletd.md diff --git a/docs/JSON-RPC-API-using-jmwalletd.md b/docs/JSON-RPC-API-using-jmwalletd.md new file mode 100644 index 000000000..6601d3a3d --- /dev/null +++ b/docs/JSON-RPC-API-using-jmwalletd.md @@ -0,0 +1,118 @@ +## JSON-RPC API for Joinmarket using jmwalletd.py + +### Introduction - how to start the server + +After installing Joinmarket as per the [INSTALL GUIDE](INSTALL.md), navigate to the `scripts/` directory as usual and start the server with: + +``` +(jmvenv) $python jmwalletd.py +``` + +which with defaults will start serving the RPC over HTTP on port 28183. + +This HTTP server does *NOT* currently support multiple sessions; it is intended as a manager/daemon for all the Joinmarket services for a single user. + +#### Rules about making requests + +Currently authentication is done by providing a cookie on first request, which must then be reused to keep the same session. The cookie is sent in an HTTP header with name `b'JMCookie'`. This is fine for an early testing stage, but will be improved/reworked, and that will be documented here. + +GET requests are used in case no content or parameters need to be provided with the request. + +POST requests are used in case content or parameters are to be provided with the request, and they are provided as utf-8 encoded serialized JSON, in the *body* of the POST request. + +Note that for some methods, it's particularly important to deal with the HTTP response asynchronously, since it can take some time for wallet synchronization, service startup etc. to occur. + +### Methods + +#### `createwallet` + +Make a new wallet. The variable "wallettype" should be "sw" for native segwit wallets (now the Joinmarket default), otherwise a segwit legacy wallet (BIP49) will be created. + +* HTTP Request type: POST +* Route: `/wallet/create` +* POST body contents: {"walletname": walletname, "password": password, "wallettype": wallettype} +* Returns: on success, {"walletname": walletname, "already_loaded": False} + +(TODO some confusion over two different walletnames here, I need to check, but the wallet name sent by the caller will be used for the file name, I believe). + +#### `unlockwallet` + +Open an existing wallet using a password. + +* HTTP Request type: POST +* Route: `/wallet//unlock` +* POST body contents: {"password": password} +* Returns: on success, {"walletname": walletname, "already_loaded": True} + +(see previous on walletname, same applies here). + +#### `lockwallet` + +Stops the wallet service for the current wallet; meaning it cannot then be accessed without re-authentication. + +* HTTP Request type: GET +* Route: `/wallet//lock` +* Returns: on success, {"walletname": walletname} + +(see previous on walletname, same applies here). + +#### `displaywallet` + +Get JSON representation of wallet contents for wallet named `walletname`: + +* HTTP Request type: GET +* Route: `/wallet//display` +* Returns: a JSON object which is the entire wallet contents, mixdepth by mixdepth. + - Example output from a signet wallet is given at the bottom of the document. + +#### `maker/start` + +Starts the yield generator/maker service for the given wallet, using the IRC and tor network connections +in the backend (inside the process started with jmwalletd). +See Joinmarket yield generator config defaults in `jmclient.configure` module for info on the data that must +be specified in the POST body contents. + +* HTTP Request type: POST +* Route: `/wallet//maker/start` +* POST body contents: {"txfee", "cjfee_a", "cjfee_r", "ordertype", "minsize"] +* Returns: on success, {"walletname": walletname} + +(see previous on walletname, same applies here). + +#### `maker/stop` + +Stops the yieldgenerator/maker service if currently running for the given wallet. + +* HTTP Request type: GET +* Route: `/wallet//maker/start` +* Returns: on success, {"walletname": walletname} + +(see previous on walletname, same applies here). + +#### `snicker/start` + +Starts the SNICKER service (see [here](SNICKER.md)) for the given wallet. Note that this requires +no configuration for now, though that is likely to change. Also note this is not yet supported for +mainnet. + +* HTTP Request type: GET +* Route: `/wallet//snicker/start` +* Returns: on success, {"walletname": walletname} + +(see previous on walletname, same applies here). + +#### `snicker/stop` + +Stops the snicker service if currently running for the given wallet. + +* HTTP Request type: GET +* Route: `/wallet//snicker/start` +* Returns: on success, {"walletname": walletname} + +(see previous on walletname, same applies here). + +##### Example wallet display JSON output from signet wallet + +``` +{'wallet_name': 'JM wallet', 'total_balance': '0.15842426', 'accounts': [{'account': '0', 'account_balance': '0.00861458', 'branches': [{'branch': "external addresses\tm/84'/1'/0'/0\ttpubDFGxEsV7NvVc4h2XL4QEppZt3CrDiCFksP97H6YbFPmCTKM6KMP2xUxW57gAu7bzDfB3YTqnMeKQaQRS5GJM3xMcrhbi5AGsQUd7p4PLMDV", 'balance': '0.00000000', 'entries': [{'hd_path': "m/84'/1'/0'/0/4", 'address': 'tb1qzugshsm85x6luegyjc6mk5zces2zqr0j8m4zkd', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/0'/0/5", 'address': 'tb1qcwmdkg229ghmd8r3xgq4a9zxp459crws66n4ve', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/0'/0/6", 'address': 'tb1q7lv6dwex3mhwp32vhku0fvpar9faar2lu595su', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/0'/0/7", 'address': 'tb1qm42ltytvp22kj9efp995yu0r0r7x570d8j8crc', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/0'/0/8", 'address': 'tb1qwvux8g0khuvvkla3zaqdslj6xpgwtq7jlvwmgu', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/0'/0/9", 'address': 'tb1q3xr7l9nylsdlyqf9rkw0rg3f0yx6slguhtwpzp', 'amount': '0.00000000', 'labels': 'new'}]}, {'branch': "internal addresses\tm/84'/1'/0'/1\t", 'balance': '0.00861458', 'entries': [{'hd_path': "m/84'/1'/0'/1/7", 'address': 'tb1qjrzxkulgc5dnlyz0rjqj68zxgqjesqn839ue2w', 'amount': '0.00396839', 'labels': 'cj-out'}, {'hd_path': "m/84'/1'/0'/1/12", 'address': 'tb1qeqkk4te2t6gqt7jfgu8a9k4je2wwfw3d2m7gku', 'amount': '0.00464619', 'labels': 'non-cj-change'}]}]}, {'account': '1', 'account_balance': '0.09380968', 'branches': [{'branch': "external addresses\tm/84'/1'/1'/0\ttpubDE1TKa8tm3WWh4f9fV325BgYWX9i7WFMaQRd1C3tSFYU9RJEyE8w2Cw2KnhgXSKyjS4keeWAkc3iLEqp3pxUEG9T49RCtQiMpjuZM71FLpL", 'balance': '0.00000000', 'entries': [{'hd_path': "m/84'/1'/1'/0/0", 'address': 'tb1qd6qqg3uzk9sw88yhvpqpwt3tx5ls4hau3mwh3g', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/1'/0/1", 'address': 'tb1qhkrmqn9e4ldzlwna8w5w9l5vaw978zlrl54hmh', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/1'/0/2", 'address': 'tb1qp83afad8dl98w366vnvct0zc49qu33c2nfx386', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/1'/0/3", 'address': 'tb1qjv0elh4kn5yaywajedgcrf93ujzz3m3q7ld7k3', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/1'/0/4", 'address': 'tb1qk25u4ch7w0xylzh0krn4hefphe6xpyh0vc33sl', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/1'/0/5", 'address': 'tb1qs3ep9nlypwn43swv75zwv6lgl3wgsmha20g87p', 'amount': '0.00000000', 'labels': 'new'}]}, {'branch': "internal addresses\tm/84'/1'/1'/1\t", 'balance': '0.09380968', 'entries': [{'hd_path': "m/84'/1'/1'/1/44", 'address': 'tb1qgmgpk22ueq9xk8f722aqjnuwd6s3jv58nwwan2', 'amount': '0.00009631', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/1'/1/49", 'address': 'tb1qjq86y8nzvafv5dsde93zf0emv7yrsphvupv69e', 'amount': '0.00013383', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/1'/1/54", 'address': 'tb1q7lvxk407xs38t24hfzy7vprp9t7tfsemv4rfym', 'amount': '0.00371951', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/1'/1/56", 'address': 'tb1qn2azshrkcg0d7py5apgfr0jh29nt9w2fmx9fyy', 'amount': '0.08986003', 'labels': 'non-cj-change'}]}, {'branch': 'Imported keys\tm/0\t', 'balance': '0.00000000', 'entries': [{'hd_path': 'imported/1/0', 'address': 'tb1q8znprh8c85za3mpwzn3qf9m0vwqzjkfu4qdncy', 'amount': '0.00000000', 'labels': 'empty'}, {'hd_path': 'imported/1/1', 'address': 'tb1qu4ajg3enea90xxtjuwcurj3d6lkqrud8p7w0yu', 'amount': '0.00000000', 'labels': 'empty'}, {'hd_path': 'imported/1/2', 'address': 'tb1qg7saqx69yalcqshfr8mjndy0gpx2umxrwqs823', 'amount': '0.00000000', 'labels': 'empty'}]}]}, {'account': '2', 'account_balance': '0.05600000', 'branches': [{'branch': "external addresses\tm/84'/1'/2'/0\ttpubDF8K7wXCrRXX1CQLVZGwMvEg9YEWF2VRpM1tjCwpMZDRRqKjpJ5YaeaDaLkqN1D7YM4pkX32FcCnosbhLQz2BgRiPNNdybWuvSBKp72mJsJ", 'balance': '0.00000000', 'entries': [{'hd_path': "m/84'/1'/2'/0/0", 'address': 'tb1qw95x9m84t6hqcun560vqfk3yc6ptl4g9arsty0', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/2'/0/1", 'address': 'tb1qek4humez7rcwl53ly6uzr4mfwd0s2lu92e356q', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/2'/0/2", 'address': 'tb1qxne4hyyeq2vrh0dfzs56th29qsymp9eq5pljdc', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/2'/0/3", 'address': 'tb1qz3jk544j5vtwztznxfdwfgt8zcw77mjcut8vdz', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/2'/0/4", 'address': 'tb1qg902humlsuc5s6aua6ew3d893hlgcxr05ntpyd', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/2'/0/5", 'address': 'tb1qukz3l34ydy9snq8rkjaknk0ns04kfnlh34neqd', 'amount': '0.00000000', 'labels': 'new'}]}, {'branch': "internal addresses\tm/84'/1'/2'/1\t", 'balance': '0.05600000', 'entries': [{'hd_path': "m/84'/1'/2'/1/1", 'address': 'tb1qrtz5cwpneheg2v2v32wzc3h9yv0rzplxjtx9vc', 'amount': '0.00800000', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/2'/1/2", 'address': 'tb1qp4276g23y2w8g3367de25ustxkygjydmwk4fw2', 'amount': '0.00800000', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/2'/1/3", 'address': 'tb1qtqgvw445807tzcm8yhq6xgu3vmdfh66czx8jea', 'amount': '0.00800000', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/2'/1/4", 'address': 'tb1qxj7ulxdthe0dwxr5457p5d0w5u3jg7rwmc05pm', 'amount': '0.02400000', 'labels': 'non-cj-change'}, {'hd_path': "m/84'/1'/2'/1/5", 'address': 'tb1qv3kfe9ew42z0ldncgzmqcjznatsxz0vudvcjrv', 'amount': '0.00800000', 'labels': 'non-cj-change'}]}]}, {'account': '3', 'account_balance': '0.00000000', 'branches': [{'branch': "external addresses\tm/84'/1'/3'/0\ttpubDE9VN56aLW9BurCxHHGAWidSnVuU86ZsKPYQgxpTgkZxbogJYfj1vWJbtYip7WV5REcgmtjETb5eShXV8VUBzvCAMzuRm5Kv4ZGnnCiX6Jg", 'balance': '0.00000000', 'entries': [{'hd_path': "m/84'/1'/3'/0/0", 'address': 'tb1qp2w6ezmqn8nk9kc4gkpetgjj2mzqgp5x3hk86m', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/3'/0/1", 'address': 'tb1qd0tt93aulqs508mtap5p8gls5z57fqa4ggnfx7', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/3'/0/2", 'address': 'tb1qsp4hv46vgz4yjwt4p2wekh2gfmek7vgznrnd96', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/3'/0/3", 'address': 'tb1qvs322uyrwh7a74dsxel0xcrgucm27c6dzdmj9j', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/3'/0/4", 'address': 'tb1qnq9uk9azs9s7m5474ws7z7wxnwv3s3lxrtjter', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/3'/0/5", 'address': 'tb1q5tlq36q6ps0m9zu6h08gd3azsgkgvm73sjcmxw', 'amount': '0.00000000', 'labels': 'new'}]}, {'branch': "internal addresses\tm/84'/1'/3'/1\t", 'balance': '0.00000000', 'entries': []}]}, {'account': '4', 'account_balance': '0.00000000', 'branches': [{'branch': "external addresses\tm/84'/1'/4'/0\ttpubDE6QfTimeNgCFSYuxPPaLc1Cp3VokAuJAusYoiGwWtVHVtQDsepf5dRAFNLWMwpBCgKDYkXdWGs2JspxXPokrtooPh7db5fniqYbdKGqD4F", 'balance': '0.00000000', 'entries': [{'hd_path': "m/84'/1'/4'/0/3", 'address': 'tb1qr2llfup6cnh27n77nm7egcyf9r7c0ykucrcu8k', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/4'/0/4", 'address': 'tb1qahqjnd2y8j770l2m4kpf4fyfve9425c0zdumms', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/4'/0/5", 'address': 'tb1q0jm0cxwcm2g60489fvtmeeaf7mzg658t8f8fk4', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/4'/0/6", 'address': 'tb1qtpm5putpkzmrmecden0yytuuk4n9emhvxwqu8m', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/4'/0/7", 'address': 'tb1qn60fc04pmprn9wpzkt0dnt80awu0rpy99w376g', 'amount': '0.00000000', 'labels': 'new'}, {'hd_path': "m/84'/1'/4'/0/8", 'address': 'tb1qakvrpp2hd3a3303zx7w2shmvfc7tqk28pwa9sj', 'amount': '0.00000000', 'labels': 'new'}]}, {'branch': "internal addresses\tm/84'/1'/4'/1\t", 'balance': '0.00000000', 'entries': []}]}]} +``` \ No newline at end of file From b3841041594f453cbf0920a82298affec53e8d4d Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Wed, 21 Jul 2021 10:55:54 +0100 Subject: [PATCH 11/12] rebase on master --- jmclient/jmclient/__init__.py | 2 +- jmclient/jmclient/client_protocol.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jmclient/jmclient/__init__.py b/jmclient/jmclient/__init__.py index 706d35a3d..fbedeb7ad 100644 --- a/jmclient/jmclient/__init__.py +++ b/jmclient/jmclient/__init__.py @@ -61,7 +61,7 @@ from .yieldgenerator import YieldGenerator, YieldGeneratorBasic, ygmain, \ YieldGeneratorService from .snicker_receiver import SNICKERError, SNICKERReceiver, SNICKERReceiverService -from .payjoin import (parse_payjoin_setup, send_payjoin, PayjoinServer, +from .payjoin import (parse_payjoin_setup, send_payjoin, JMBIP78ReceiverManager) # Set default logging handler to avoid "No handler found" warnings. diff --git a/jmclient/jmclient/client_protocol.py b/jmclient/jmclient/client_protocol.py index eef4fbd16..25c8137fc 100644 --- a/jmclient/jmclient/client_protocol.py +++ b/jmclient/jmclient/client_protocol.py @@ -871,15 +871,15 @@ def start_daemon_on_port(p, f, name, port_offset): # starts in jmclient.payjoin: if usessl: if factory: - reactor.connectSSL(host, jmcport, factory, ClientContextFactory()) + reactor.connectSSL(host, jmcport, factory, ClientContextFactory()) if snickerfactory: - reactor.connectSSL(host, snickerport, snickerfactory, + reactor.connectSSL(host, snickerport, snickerfactory, ClientContextFactory()) else: if factory: - reactor.connectTCP(host, jmcport, factory) + reactor.connectTCP(host, jmcport, factory) if snickerfactory: - reactor.connectTCP(host, snickerport, snickerfactory) + reactor.connectTCP(host, snickerport, snickerfactory) if rs: if not gui: reactor.run(installSignalHandlers=ish) From 0c4c0810d1f9c5f9523f67412db8247d1593c557 Mon Sep 17 00:00:00 2001 From: Adam Gibson Date: Wed, 21 Jul 2021 13:39:25 +0100 Subject: [PATCH 12/12] address flake8 complaints --- jmclient/jmclient/snicker_receiver.py | 1 - scripts/jmwalletd.py | 11 ++++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/jmclient/jmclient/snicker_receiver.py b/jmclient/jmclient/snicker_receiver.py index a17f40651..ccb4d5a9e 100644 --- a/jmclient/jmclient/snicker_receiver.py +++ b/jmclient/jmclient/snicker_receiver.py @@ -7,7 +7,6 @@ from jmclient.configure import jm_single from jmbase import (get_log, utxo_to_utxostr, hextobin, bintohex) -from twisted.application.service import Service jlog = get_log() diff --git a/scripts/jmwalletd.py b/scripts/jmwalletd.py index d7f1aa91b..322c7afb1 100644 --- a/scripts/jmwalletd.py +++ b/scripts/jmwalletd.py @@ -1,14 +1,11 @@ #! /usr/bin/env python -import datetime import os -import time -import abc import json import atexit from io import BytesIO from twisted.python.log import startLogging -from twisted.internet import endpoints, reactor, ssl, task +from twisted.internet import reactor, ssl from twisted.web.server import Site from twisted.application.service import Service from klein import Klein @@ -16,14 +13,14 @@ from optparse import OptionParser from jmbase import get_log from jmbitcoin import human_readable_transaction -from jmclient import Maker, jm_single, load_program_config, \ - JMClientProtocolFactory, start_reactor, calc_cj_fee, \ +from jmclient import jm_single, load_program_config, \ + start_reactor, \ WalletService, add_base_options, get_wallet_path, direct_send, \ open_test_wallet_maybe, wallet_display, SegwitLegacyWallet, \ SegwitWallet, get_daemon_serving_params, YieldGeneratorService, \ SNICKERReceiverService, SNICKERReceiver, create_wallet, \ StorageError, StoragePasswordError -from jmbase.support import EXIT_ARGERROR, EXIT_FAILURE +from jmbase.support import EXIT_FAILURE jlog = get_log()