SatSale

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

commit b621ffde1f3dfe14cfacf003440fc412244773f9
parent 79874fcde6d3df1f928c45b5fc9afb71931ecef3
Author: nickfarrow <nicholas.w.farrow@gmail.com>
Date:   Wed,  2 Feb 2022 01:27:12 +1100

reformat most of repo using black

Diffstat:
Mgateways/lightning_address.py | 59++++++++++++++++++++++++++++++++++++++---------------------
Mgateways/ssh_tunnel.py | 5++++-
Mnode/bitcoind.py | 9++++++---
Mnode/clightning.py | 11+++++++----
Mnode/lnd.py | 20+++++++++++++-------
Mpayments/database.py | 5++---
Mpayments/price_feed.py | 4+++-
Mpayments/weakhands.py | 15+++++++++++----
Msatsale.py | 17++++++++++++-----
9 files changed, 96 insertions(+), 49 deletions(-)

diff --git a/gateways/lightning_address.py b/gateways/lightning_address.py @@ -5,8 +5,8 @@ import logging import config -min_sats = 10**2 -max_sats = 10**6 +min_sats = 10 ** 2 +max_sats = 10 ** 6 # Following https://github.com/andrerfneves/lightning-address/blob/master/DIY.md @@ -14,52 +14,69 @@ description = config.lightning_address_comment if description is None: description = "Thank you for your support <3" -metadata = "[[\"text/plain\", \"{}\"], [\"text/identifier\", \"{}\"]]".format(description, config.lightning_address.split("@")[0]) +metadata = '[["text/plain", "{}"], ["text/identifier", "{}"]]'.format( + description, config.lightning_address.split("@")[0] +) + def add_ln_address_decorators(app, api, node): class get_ln_address(Resource): def get(self): try: - logging.info("Someone requested our ln address: {}!".format(config.lightning_address)) + logging.info( + "Someone requested our ln address: {}!".format( + config.lightning_address + ) + ) resp = { - "callback": "https://{}/lnaddr".format(config.lightning_address.split("@")[1]), - "maxSendable": max_sats*10**3, - "minSendable": min_sats*10**3, + "callback": "https://{}/lnaddr".format( + config.lightning_address.split("@")[1] + ), + "maxSendable": max_sats * 10 ** 3, + "minSendable": min_sats * 10 ** 3, "metadata": metadata, - "tag": "payRequest" - } + "tag": "payRequest", + } return resp except Exception as e: logging.error(e) return {"status": "ERROR", "reason": e} - - class init_ln_addr_payment(Resource): def get(self): if request.args.get("amount") is None: - return {"status": "ERROR", "reason": "You need to request an ?amount=MSATS"} + return { + "status": "ERROR", + "reason": "You need to request an ?amount=MSATS", + } amount_msats = int(request.args.get("amount")) - amount_btc = amount_msats / 10**(3+8) + amount_btc = amount_msats / 10 ** (3 + 8) - logging.info("Received payment request from ln address for {} msats...".format(amount_msats)) + logging.info( + "Received payment request from ln address for {} msats...".format( + amount_msats + ) + ) description_hash = hashlib.sha256(metadata.encode()).digest() try: - invoice, _ = node.create_lnd_invoice(amount_btc, memo="lightning address payment", description_hash=description_hash) + invoice, _ = node.create_lnd_invoice( + amount_btc, + memo="lightning address payment", + description_hash=description_hash, + ) logging.info("Responding with invoice {}".format(invoice)) - return { - "pr": invoice, - "routes": [] - } + return {"pr": invoice, "routes": []} except Exception as e: logging.error(e) return {"status": "ERROR", "reason": e} - - api.add_resource(get_ln_address, "/.well-known/lnurlp/{}".format(config.lightning_address.split("@")[0])) + api.add_resource( + get_ln_address, + "/.well-known/lnurlp/{}".format(config.lightning_address.split("@")[0]), + ) api.add_resource(init_ln_addr_payment, "/lnaddr") return diff --git a/gateways/ssh_tunnel.py b/gateways/ssh_tunnel.py @@ -31,6 +31,7 @@ def open_tunnel(host, port): pass return + def clightning_unix_domain_socket_ssh(rpc_store_dir=None): if rpc_store_dir is None: rpc_store_dir = os.getcwd() @@ -50,7 +51,9 @@ def clightning_unix_domain_socket_ssh(rpc_store_dir=None): return tunnel_proc except Exception as e: - logging.error("FAILED TO OPEN UNIX DOMAIN SOCKET OVER SSH. Exception: {}".format(e)) + logging.error( + "FAILED TO OPEN UNIX DOMAIN SOCKET OVER SSH. Exception: {}".format(e) + ) tunnel_proc = None pass diff --git a/node/bitcoind.py b/node/bitcoind.py @@ -39,7 +39,11 @@ class btcd: config.rpcport, config.wallet, ) - logging.info("Attempting to connect to Bitcoin node RPC with user {}.".format(config.username)) + logging.info( + "Attempting to connect to Bitcoin node RPC with user {}.".format( + config.username + ) + ) else: self.tor = True logging.info( @@ -86,8 +90,7 @@ class btcd: if not self.tor: transactions = self.rpc.listtransactions(uuid) else: - transactions = call_tor_bitcoin_rpc("listtransactions", - [uuid])["result"] + transactions = call_tor_bitcoin_rpc("listtransactions", [uuid])["result"] conf_paid = 0 unconf_paid = 0 diff --git a/node/clightning.py b/node/clightning.py @@ -18,6 +18,7 @@ import config # # session = None + class clightning: def __init__(self): from pyln.client import LightningRpc @@ -59,8 +60,10 @@ class clightning: # Create lightning invoice def create_clightning_invoice(self, btc_amount, label): # Multiplying by 10^8 to convert to satoshi units - msats_amount = int(btc_amount * 10 ** (3+8)) - lnd_invoice = self.clightning.invoice(msats_amount, label, "SatSale-{}".format(label)) + msats_amount = int(btc_amount * 10 ** (3 + 8)) + lnd_invoice = self.clightning.invoice( + msats_amount, label, "SatSale-{}".format(label) + ) return lnd_invoice["bolt11"], lnd_invoice["payment_hash"] def get_address(self, amount, label): @@ -69,7 +72,7 @@ class clightning: # Check whether the payment has been paid def check_payment(self, uuid): - invoices = self.clightning.listinvoices(uuid)['invoices'] + invoices = self.clightning.listinvoices(uuid)["invoices"] if len(invoices) == 0: logging.error("Could not find invoice on node. Something's wrong.") @@ -82,7 +85,7 @@ class clightning: unconf_paid = 0 else: # Store amount paid and convert to BTC units - conf_paid = int(invoice["msatoshi_received"]) / 10**(3+8) + conf_paid = int(invoice["msatoshi_received"]) / 10 ** (3 + 8) unconf_paid = 0 return conf_paid, unconf_paid diff --git a/node/lnd.py b/node/lnd.py @@ -77,18 +77,23 @@ class lnd: def copy_certs(self): self.certs = {"tls": "tls.cert", "macaroon": config.lnd_macaroon} - if (not os.path.isfile("tls.cert")) or (not os.path.isfile(config.lnd_macaroon)): + if (not os.path.isfile("tls.cert")) or ( + not os.path.isfile(config.lnd_macaroon) + ): try: tls_file = os.path.join(config.lnd_dir, "tls.cert") macaroon_file = os.path.join( - config.lnd_dir, "data/chain/bitcoin/mainnet/{}".format(config.lnd_macaroon) + config.lnd_dir, + "data/chain/bitcoin/mainnet/{}".format(config.lnd_macaroon), ) # SSH copy if config.tunnel_host is not None: logging.warning( "Could not find tls.cert or {} in SatSale folder. \ - Attempting to download from remote lnd directory.".format(config.lnd_macaroon) + Attempting to download from remote lnd directory.".format( + config.lnd_macaroon + ) ) subprocess.run( @@ -120,7 +125,9 @@ class lnd: def create_lnd_invoice(self, btc_amount, memo=None, description_hash=None): # Multiplying by 10^8 to convert to satoshi units sats_amount = int(btc_amount * 10 ** 8) - res = self.lnd.add_invoice(value=sats_amount, memo=memo, description_hash=description_hash) + res = self.lnd.add_invoice( + value=sats_amount, memo=memo, description_hash=description_hash + ) lnd_invoice = json.loads(MessageToJson(res)) return lnd_invoice["paymentRequest"], lnd_invoice["rHash"] @@ -131,12 +138,11 @@ class lnd: def pay_invoice(self, invoice): ret = json.loads( - MessageToJson(self.lnd.send_payment(invoice, fee_limit_msat=20*1000)) - ) + MessageToJson(self.lnd.send_payment(invoice, fee_limit_msat=20 * 1000)) + ) logging.info(ret) return - # Check whether the payment has been paid def check_payment(self, rhash): invoice_status = json.loads( diff --git a/payments/database.py b/payments/database.py @@ -1,6 +1,7 @@ import sqlite3 import logging + def create_database(name="database.db"): with sqlite3.connect("database.db") as conn: logging.info("Creating new database.db...") @@ -33,9 +34,7 @@ def load_invoices_from_db(where, name="database.db"): with sqlite3.connect(name) as conn: conn.row_factory = sqlite3.Row cur = conn.cursor() - rows = cur.execute( - "SELECT * FROM payments WHERE {}".format(where) - ).fetchall() + rows = cur.execute("SELECT * FROM payments WHERE {}".format(where)).fetchall() return rows diff --git a/payments/price_feed.py b/payments/price_feed.py @@ -45,7 +45,9 @@ def get_price(currency, currency_provider=config.currency_provider): return price except: - logging.error("Failed to find currency {} from {}.".format(currency, price_feed)) + logging.error( + "Failed to find currency {} from {}.".format(currency, price_feed) + ) return None diff --git a/payments/weakhands.py b/payments/weakhands.py @@ -9,12 +9,13 @@ quote_url = "https://sideshift.ai/api/v1/quotes" swap_url = "https://sideshift.ai/api/v1/orders" affiliate = "eK590V1Mh" + def get_quote(amount_lnbtc): quote_data = { "depositMethod": "ln", "settleMethod": "usdtla", "affiliateId": affiliate, - "depositAmount": str(amount_lnbtc) + "depositAmount": str(amount_lnbtc), } logging.info("Getting quote to swap {:.8f} LN-BTC to USDT".format(amount_lnbtc)) resp = requests.post(quote_url, json=quote_data) @@ -31,11 +32,15 @@ def get_swap(quote, amount_lnbtc, liquid_address): swap_url = "https://sideshift.ai/api/orders" data = { "type": "fixed", - "quoteId": quote['id'], + "quoteId": quote["id"], "settleAddress": liquid_address, "affiliateId": affiliate, } - logging.info("Creating order to swap {:.8f} LN-BTC to USDT (liquid: {})".format(amount_lnbtc, liquid_address)) + logging.info( + "Creating order to swap {:.8f} LN-BTC to USDT (liquid: {})".format( + amount_lnbtc, liquid_address + ) + ) resp = requests.post(swap_url, json=data) @@ -46,12 +51,14 @@ def get_swap(quote, amount_lnbtc, liquid_address): return resp.json() + def pay_swap(node, swap): - payment_req = swap['depositAddress']['paymentRequest'] + payment_req = swap["depositAddress"]["paymentRequest"] logging.info("Paying invoice: {}".format(payment_req)) node.pay_invoice(payment_req) return True + def swap_lnbtc_for_lusdt(node, amount_lnbtc, liquid_address): try: quote = get_quote(amount_lnbtc) diff --git a/satsale.py b/satsale.py @@ -27,9 +27,11 @@ from node import clightning from gateways import woo_webhook -logging.basicConfig(format='[%(asctime)s] [%(levelname)s] %(message)s', - datefmt='%Y-%m-%d %H:%M:%S %z', - level=getattr(logging, config.loglevel)) +logging.basicConfig( + format="[%(asctime)s] [%(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S %z", + level=getattr(logging, config.loglevel), +) app = Flask(__name__) @@ -222,8 +224,12 @@ class complete_payment(Resource): if status["payment_complete"] != 1: return {"message": "You havent paid you stingy bastard"} - if (config.liquid_address is not None) and (invoice['method'] in ["lnd", "clightning"]): - weakhands.swap_lnbtc_for_lusdt(lightning_node, invoice["btc_value"], config.liquid_address) + if (config.liquid_address is not None) and ( + invoice["method"] in ["lnd", "clightning"] + ): + weakhands.swap_lnbtc_for_lusdt( + lightning_node, invoice["btc_value"], config.liquid_address + ) # Call webhook to confirm payment with merchant if (invoice["webhook"] != None) and (invoice["webhook"] != ""): @@ -324,6 +330,7 @@ elif config.pay_method == "clightning": if config.lightning_address is not None: from gateways import lightning_address + lightning_address.add_ln_address_decorators(app, api, lightning_node) if config.paynym is not None: