From c01aa3a4db94a610843153e7e775dc0671ce57d7 Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:20:01 +0100 Subject: [PATCH 1/3] fix: harden P0 runtime safety, atomic writes, and HTTP timeouts - Other/fee_adjuster.py: replace append-mode fee_adjuster.txt writes with atomic 0o644 replacement, exit non-zero on fatal errors instead of sleeping 60s, and add DEFAULT_HTTP_TIMEOUT=30. - LNBits/pocketmoney.py: add DEFAULT_HTTP_TIMEOUT=30, gate success alerts/balance checks on successful pay_invoice() result, and exit 1 in --run-once mode on payment failures. - Magma/magma_sale_process.py: read [loop] rpcserver/tlscertpath and expand ~ in tlscertpath before Popen. - Peerswap/peerswap-lndg_push.py: guard locale.setlocale errors, use safe config.get fallbacks, add timeouts, and parse CLI args before invoking lncli/pscli. - LNDg/channel_fee-pull.py & Peerswap/peerswap-bot.py: make imports side-effect-safe with __main__ guards, safe config fallbacks, atomic 0_fee.txt write, normalized pscli path, and HTTP timeouts. - LNDg/{channel_base-fee,disabled_fee-accelerator,mempool_rebalancer_trigger,swap_out-candidates}.py: add explicit HTTP timeouts. - tests/test_p0_runtime_safety.py: add regression tests covering all P0 fixes (209/209 passing, 40.81% total coverage). --- LNBits/pocketmoney.py | 52 +++- LNDg/channel_base-fee.py | 11 +- LNDg/channel_fee-pull.py | 65 +++-- LNDg/disabled_fee-accelerator.py | 11 +- LNDg/mempool_rebalancer_trigger.py | 5 +- LNDg/swap_out-candidates.py | 14 +- Magma/magma_sale_process.py | 10 +- Other/fee_adjuster.py | 150 +++++++--- Peerswap/peerswap-bot.py | 77 ++++-- Peerswap/peerswap-lndg_push.py | 36 ++- tests/test_p0_runtime_safety.py | 427 +++++++++++++++++++++++++++++ 11 files changed, 734 insertions(+), 124 deletions(-) create mode 100644 tests/test_p0_runtime_safety.py diff --git a/LNBits/pocketmoney.py b/LNBits/pocketmoney.py index 7f4b72c..8fe7fd1 100644 --- a/LNBits/pocketmoney.py +++ b/LNBits/pocketmoney.py @@ -10,6 +10,8 @@ from telebot import TeleBot import argparse +DEFAULT_HTTP_TIMEOUT = 30 + def normalize_lnbits_base_url(raw_url): """Normalize LNbits base URL so /api/v1/... endpoints are never doubled.""" url = (raw_url or "").strip().rstrip("/") @@ -73,7 +75,9 @@ def get_exchange_rate(fiat_currency): try: url = f"{LNBITS_URL}/api/v1/rate/{fiat_currency}" logger.debug(f"Requesting exchange rate from: {url}") - response = requests.get(url, headers={"accept": "application/json"}) + response = requests.get( + url, headers={"accept": "application/json"}, timeout=DEFAULT_HTTP_TIMEOUT + ) logger.debug(f"Response status code: {response.status_code}") response.raise_for_status() rate = response.json().get("rate") @@ -103,6 +107,7 @@ def create_invoice(wallet_id, invoice_key, amount_eur, child_name, fiat_currency f"{LNBITS_URL}/api/v1/payments", headers={"X-Api-Key": invoice_key, "Content-type": "application/json"}, json={"out": False, "amount": amount_sats, "memo": memo}, + timeout=DEFAULT_HTTP_TIMEOUT, ) logger.debug(f"Invoice creation response status: {response.status_code}") logger.debug(f"Invoice creation response: {response.text}") @@ -145,6 +150,7 @@ def pay_invoice(payment_request): "Content-type": "application/json", # Added Content-type header }, json={"out": True, "bolt11": payment_request}, + timeout=DEFAULT_HTTP_TIMEOUT, ) logger.debug(f"Payment response status: {response.status_code}") logger.debug(f"Payment response: {response.text}") @@ -170,7 +176,9 @@ def pay_invoice(payment_request): def check_balance(): try: response = requests.get( - f"{LNBITS_URL}/api/v1/wallet", headers={"X-Api-Key": ADMIN_KEY} + f"{LNBITS_URL}/api/v1/wallet", + headers={"X-Api-Key": ADMIN_KEY}, + timeout=DEFAULT_HTTP_TIMEOUT, ) response.raise_for_status() balance = response.json().get("balance") @@ -191,11 +199,12 @@ def send_telegram_warning(balance): # Main function to run the scheduled transfer def scheduled_transfer(): - # Parse the children wallets from the jason file + # Parse the children wallets from the json file wallets_file_path = os.path.join(parent_dir, "..", "wallets.json") with open(wallets_file_path, "r") as f: CHILDREN_WALLETS = json.load(f) + failures = 0 for child, wallet_info in CHILDREN_WALLETS.items(): wallet_id = wallet_info["wallet_id"] invoice_key = wallet_info["invoice_key"] @@ -205,17 +214,28 @@ def scheduled_transfer(): payment_request, amount_sats = create_invoice( wallet_id, invoice_key, fiat_amount, child, fiat_currency ) - if payment_request: - pay_invoice(payment_request) - logger.info( - f"Transferred {fiat_amount} {fiat_currency} ({amount_sats} satoshis) worth of pocket money to {child}" - ) - bot.send_message( - CHAT_ID, - f"💶 🤑 Transferred {fiat_amount} {fiat_currency} ({amount_sats} satoshis) worth of pocket money to {child}", - ) - # Check balance after each payment - check_balance() + if not payment_request: + failures += 1 + logger.error(f"Invoice creation failed for {child}; skipping payment.") + continue + + payment_result = pay_invoice(payment_request) + if payment_result is None: + failures += 1 + logger.error(f"Payment failed for {child}; skipping transfer confirmation.") + continue + + logger.info( + f"Transferred {fiat_amount} {fiat_currency} ({amount_sats} satoshis) worth of pocket money to {child}" + ) + bot.send_message( + CHAT_ID, + f"💶 🤑 Transferred {fiat_amount} {fiat_currency} ({amount_sats} satoshis) worth of pocket money to {child}", + ) + # Check balance after each successful payment + check_balance() + + return failures # Comment out the scheduling logic for testing @@ -267,7 +287,9 @@ def main(): validate_runtime_config() if args.run_once: - scheduled_transfer() + failures = scheduled_transfer() + if failures > 0: + raise SystemExit(1) else: schedule_transfers() while True: diff --git a/LNDg/channel_base-fee.py b/LNDg/channel_base-fee.py index 858177b..cc056a2 100644 --- a/LNDg/channel_base-fee.py +++ b/LNDg/channel_base-fee.py @@ -4,6 +4,8 @@ import configparser from prettytable import PrettyTable +DEFAULT_HTTP_TIMEOUT = 30 + # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -34,7 +36,9 @@ def get_channels_to_modify(): all_channels_details = [] # Initialize list to store details of all channels from API try: # Make the API request with authentication - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) # Check if the request was successful (status code 200) if response.status_code == 200: @@ -167,7 +171,10 @@ def modify_channels(channels): # Make a PUT request to update the channel details response = requests.post( - update_api_url, json=payload, auth=(username, password) + update_api_url, + json=payload, + auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) # Get the current timestamp diff --git a/LNDg/channel_fee-pull.py b/LNDg/channel_fee-pull.py index d34e912..4b5faa8 100644 --- a/LNDg/channel_fee-pull.py +++ b/LNDg/channel_fee-pull.py @@ -1,7 +1,10 @@ import os +import tempfile import requests import configparser +DEFAULT_HTTP_TIMEOUT = 30 + # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -11,24 +14,33 @@ config.read(config_file_path) # API endpoint URL -api_url = config["lndg"]["lndg_api_url"] + "/api/channels?limit=500&is_open=true" +_lndg_base = config.get("lndg", "lndg_api_url", fallback="").strip().rstrip("/") +api_url = f"{_lndg_base}/api/channels?limit=500&is_open=true" if _lndg_base else "" # Authentication credentials -username = config["credentials"]["lndg_username"] -password = config["credentials"]["lndg_password"] +username = config.get("credentials", "lndg_username", fallback="").strip() +password = config.get("credentials", "lndg_password", fallback="").strip() # File path for storing data. This txt is populated to have charge-lnd pick it up file_path = os.path.expanduser("~/.chargelnd/.config/0_fee.txt") # Remote pubkey to ignore. Add pubkey or reference in config.ini if you want to use it. -ignore_remote_pubkeys = config["pubkey"]["base_fee_ignore"].split(",") +ignore_remote_pubkeys = [ + p.strip() + for p in config.get("pubkey", "base_fee_ignore", fallback="").split(",") + if p.strip() +] def get_chan_ids_to_write(): + if not api_url: + raise ValueError("Missing [lndg] lndg_api_url in config.ini") chan_ids_to_write = [] # Initialize the list try: # Make the API request with authentication - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) # Check if the request was successful (status code 200) if response.status_code == 200: @@ -53,16 +65,37 @@ def get_chan_ids_to_write(): return chan_ids_to_write -chan_ids = get_chan_ids_to_write() -print(f"Channel-IDs: {chan_ids}") +def write_chan_ids_atomic(target_path, chan_ids): + """Atomically write 0_fee.txt with 0o644 permissions.""" + target_dir = os.path.dirname(os.path.abspath(target_path)) + os.makedirs(target_dir, exist_ok=True) + fd, tmp_path = tempfile.mkstemp(prefix=".0_fee_", suffix=".tmp", dir=target_dir) + try: + with os.fdopen(fd, "w", encoding="utf-8") as tmp_file: + for chan_id in chan_ids: + tmp_file.write(f"{chan_id}\n") + tmp_file.flush() + os.fsync(tmp_file.fileno()) + os.chmod(tmp_path, 0o644) + os.replace(tmp_path, target_path) + except Exception: + if os.path.exists(tmp_path): + try: + os.unlink(tmp_path) + except OSError: + pass + raise + -os.makedirs(os.path.dirname(file_path), exist_ok=True) -if chan_ids: - with open(file_path, "w") as file: - for chan_id in chan_ids: - file.write(f"{chan_id}\n") +def main(): + chan_ids = get_chan_ids_to_write() + print(f"Channel-IDs: {chan_ids}") + write_chan_ids_atomic(file_path, chan_ids) + if chan_ids: print("Data written to file.") -else: - with open(file_path, "w") as file: - file.truncate(0) - print("No channel IDs to write. File has been emptied.") + else: + print("No channel IDs to write. File has been emptied.") + + +if __name__ == "__main__": + main() diff --git a/LNDg/disabled_fee-accelerator.py b/LNDg/disabled_fee-accelerator.py index 46047b9..66029a9 100644 --- a/LNDg/disabled_fee-accelerator.py +++ b/LNDg/disabled_fee-accelerator.py @@ -20,6 +20,8 @@ from prettytable import PrettyTable import argparse +DEFAULT_HTTP_TIMEOUT = 30 + # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -92,7 +94,9 @@ def get_channels_to_modify(verbose=False): try: # Make the API request with authentication - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json() @@ -324,7 +328,10 @@ def modify_channels(channels): # Make a POST request to update the channel details via chanpolicy (not possible via channels-PUT) response = requests.post( - update_api_url, json=payload, auth=(username, password) + update_api_url, + json=payload, + auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) # Get the current timestamp diff --git a/LNDg/mempool_rebalancer_trigger.py b/LNDg/mempool_rebalancer_trigger.py index eafefd6..bbcb73f 100644 --- a/LNDg/mempool_rebalancer_trigger.py +++ b/LNDg/mempool_rebalancer_trigger.py @@ -35,6 +35,8 @@ import os import configparser +DEFAULT_HTTP_TIMEOUT = 30 + # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -90,7 +92,7 @@ def check_mempool_fees(): """Checks the mempool API and adjusts LNDg AR-Enabled setting if necessary.""" try: - response = requests.get(MEMPOOL_API_URL) + response = requests.get(MEMPOOL_API_URL, timeout=DEFAULT_HTTP_TIMEOUT) response.raise_for_status() # Raise exception for HTTP errors data = response.json() @@ -121,6 +123,7 @@ def adjust_ar_enabled(ar_enabled): AR_ENABLED_API_URL, json={"value": ar_enabled_str}, auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) if response.status_code == 200: diff --git a/LNDg/swap_out-candidates.py b/LNDg/swap_out-candidates.py index a9f109e..3e391a9 100644 --- a/LNDg/swap_out-candidates.py +++ b/LNDg/swap_out-candidates.py @@ -14,6 +14,8 @@ from prettytable import PrettyTable import argparse +DEFAULT_HTTP_TIMEOUT = 30 + # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -79,7 +81,9 @@ def get_chan_ids_to_write(): chan_ids_to_write = [] # Initialize the list try: - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) # Check if the request was successful (status code 200) if response.status_code == 200: @@ -117,7 +121,9 @@ def get_chan_ids_to_write(): def terminal_output(): try: - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) if response.status_code == 200: data = response.json() @@ -208,7 +214,9 @@ def terminal_output(): def write_bos_tags(): try: - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) if response.status_code == 200: data = response.json() if "results" in data: diff --git a/Magma/magma_sale_process.py b/Magma/magma_sale_process.py index d4460b1..b18c59f 100644 --- a/Magma/magma_sale_process.py +++ b/Magma/magma_sale_process.py @@ -1271,11 +1271,17 @@ def get_lncli_utxos(): try: if loop_path and os.path.exists(loop_path): + loop_rpcserver = config.get( + "loop", "rpcserver", fallback="localhost:8443" + ).strip() + loop_tlscertpath = os.path.expanduser( + config.get("loop", "tlscertpath", fallback="~/.lit/tls.cert").strip() + ) # Construct the litloop command as list litloop_cmd = [ loop_path, - "--rpcserver=localhost:8443", - "--tlscertpath=~/.lit/tls.cert", + f"--rpcserver={loop_rpcserver}", + f"--tlscertpath={loop_tlscertpath}", "static", "listunspent" ] diff --git a/Other/fee_adjuster.py b/Other/fee_adjuster.py index 3c4bff3..57b3fb8 100644 --- a/Other/fee_adjuster.py +++ b/Other/fee_adjuster.py @@ -77,6 +77,7 @@ import os import sys +import tempfile import requests from datetime import datetime, timedelta import configparser @@ -86,6 +87,8 @@ import argparse from prettytable import PrettyTable +DEFAULT_HTTP_TIMEOUT = 30 + # Error classes class AmbossAPIError(Exception): @@ -283,7 +286,9 @@ def get_last_peer_forwarding_timestamp(pubkey, days_to_check_back, channel_ids, logging.debug(f"Querying LNDg for channel {chan_id}: {api_url}") try: - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) response.raise_for_status() data = response.json() @@ -543,7 +548,9 @@ def fetch_all_channels(config): password = config["credentials"]["lndg_password"] try: - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) response.raise_for_status() data = response.json() @@ -779,7 +786,10 @@ def update_lndg_fee( auto_fees_url = f"{lndg_api_url}/api/channels/{chan_id}/" try: response = requests.put( - auto_fees_url, json=channel_update_payload, auth=(username, password) + auto_fees_url, + json=channel_update_payload, + auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) response.raise_for_status() logging.info( @@ -810,7 +820,10 @@ def update_lndg_fee( ) response = requests.post( - fee_update_url, json=fee_payload, auth=(username, password) + fee_update_url, + json=fee_payload, + auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) if log_api_response: # Only log verbose response if specifically requested @@ -833,6 +846,58 @@ def update_lndg_fee( raise LNDGAPIError(f"Error updating LNDg fee policy for channel {chan_id}: {e}") +def format_charge_lnd_entry( + pubkey, + alias, + new_fee_rate, + is_aggregated, + inbound_auto_fee_enabled_for_node, + calculated_inbound_ppm_for_charge_lnd, +): + """Format a single peer stanza for charge-lnd.""" + lines = [ + f"[🤖 {alias}{' (Aggregated)' if is_aggregated else ''}]\n", + f"node.id = {pubkey}\n", + "strategy = static\n", + f"fee_ppm = {new_fee_rate}\n", + ] + if inbound_auto_fee_enabled_for_node: + lines.append(f"inbound_fee_ppm = {calculated_inbound_ppm_for_charge_lnd}\n") + # Defaulting inbound base to 0 for now + lines.append("inbound_base_fee_msat = 0\n") + # Default base fees and HTLC settings + lines.extend( + [ + "base_fee_msat = 1000\n", + "min_htlc_msat = 1_000\n", + "max_htlc_msat_ratio = 0.9\n", + "\n", + ] + ) + return "".join(lines) + + +def write_charge_lnd_entries_atomic(file_path, entries): + """Atomically replace charge-lnd fee_adjuster.txt with formatted stanzas.""" + target_dir = os.path.dirname(os.path.abspath(file_path)) + os.makedirs(target_dir, exist_ok=True) + fd, tmp_path = tempfile.mkstemp(prefix=".fee_adjuster_", suffix=".tmp", dir=target_dir) + try: + with os.fdopen(fd, "w", encoding="utf-8") as tmp_file: + tmp_file.write("".join(entries)) + tmp_file.flush() + os.fsync(tmp_file.fileno()) + os.chmod(tmp_path, 0o644) + os.replace(tmp_path, file_path) + except Exception: + if os.path.exists(tmp_path): + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + def write_charge_lnd_file( file_path, pubkey, @@ -843,22 +908,16 @@ def write_charge_lnd_file( inbound_auto_fee_enabled_for_node, calculated_inbound_ppm_for_charge_lnd, # Pass the specific inbound PPM for this peer/aggregation ): - with open(file_path, "a") as f: - f.write(f"[🤖 {alias}{' (Aggregated)' if is_aggregated else ''}]\n") - f.write(f"node.id = {pubkey}\n") - f.write("strategy = static\n") - f.write(f"fee_ppm = {new_fee_rate}\n") - # Add inbound fee details if the feature is enabled for this node - if inbound_auto_fee_enabled_for_node: - f.write(f"inbound_fee_ppm = {calculated_inbound_ppm_for_charge_lnd}\n") - f.write( - "inbound_base_fee_msat = 0\n" - ) # Defaulting inbound base to 0 for now - # Default base fees and HTLC settings, consider making these configurable - f.write("base_fee_msat = 1000\n") # Default for outgoing, might need review - f.write("min_htlc_msat = 1_000\n") - f.write("max_htlc_msat_ratio = 0.9\n") - f.write("\n") + entry = format_charge_lnd_entry( + pubkey, + alias, + new_fee_rate, + is_aggregated, + inbound_auto_fee_enabled_for_node, + calculated_inbound_ppm_for_charge_lnd, + ) + with open(file_path, "a", encoding="utf-8") as f: + f.write(entry) def update_channel_notes( @@ -988,7 +1047,9 @@ def update_channel_notes( logging.debug(f"Sending PUT request to: {put_url}") logging.debug(f"With payload: {json.dumps(payload)}") - response = requests.put(put_url, json=payload, auth=(username, password)) + response = requests.put( + put_url, json=payload, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if response.status_code == 200: @@ -1342,6 +1403,7 @@ def main(): save_baseline_targets(baseline_map) logging.info(f"RebalanceGuard applied {len(guard_plans)} target adjustments.") + charge_lnd_entries = [] for node in node_definitions["nodes"]: pubkey = node["pubkey"] group_name = node.get("group") @@ -1819,39 +1881,43 @@ def main(): ) sys.stdout.flush() # Ensure output is shown immediately - # Write to charge-lnd file once per peer if enabled and any channel updated + # Collect charge-lnd stanza once per peer if enabled and any channel updated if ( write_charge_lnd_file_enabled and updated_any_channel and not skip_charge_lnd_file_write ): - charge_lnd_dir = os.path.expanduser( - config.get( - "paths", "charge_lnd_path", fallback="~/.chargelnd/.config" + charge_lnd_entries.append( + format_charge_lnd_entry( + pubkey, + first_channel_data["alias"], + final_rate, # This is the outgoing fee rate + num_channels > 1, + inbound_auto_fee_enabled_for_node, # Pass the resolved enable status + calculated_inbound_ppm_for_peer, # Pass the peer-level calculated inbound ppm ) ) - os.makedirs(charge_lnd_dir, exist_ok=True) - charge_lnd_file_path = os.path.join( - charge_lnd_dir, "fee_adjuster.txt" - ) - # Pass the inbound fee details to write_charge_lnd_file - # calculated_inbound_ppm_for_peer is the peer-level summary calculated earlier - write_charge_lnd_file( - charge_lnd_file_path, - pubkey, - first_channel_data["alias"], - final_rate, # This is the outgoing fee rate - num_channels > 1, - inbound_auto_fee_enabled_for_node, # Pass the resolved enable status - calculated_inbound_ppm_for_peer, # Pass the peer-level calculated inbound ppm - ) except (AmbossAPIError, LNDGAPIError) as e: logging.error(f"Error processing node {pubkey}: {e}") continue + if ( + write_charge_lnd_file_enabled + and not skip_charge_lnd_file_write + and charge_lnd_entries + ): + charge_lnd_dir = os.path.expanduser( + config.get( + "paths", "charge_lnd_path", fallback="~/.chargelnd/.config" + ) + ) + charge_lnd_file_path = os.path.join( + charge_lnd_dir, "fee_adjuster.txt" + ) + write_charge_lnd_entries_atomic(charge_lnd_file_path, charge_lnd_entries) except Exception as e: - logging.error(f"An unexpected error occurred: {e}") - time.sleep(60) # Sleep for 1 minute before retrying + logging.exception(f"An unexpected error occurred: {e}") + raise SystemExit(1) from e if __name__ == "__main__": diff --git a/Peerswap/peerswap-bot.py b/Peerswap/peerswap-bot.py index ec36750..4bbe6d6 100644 --- a/Peerswap/peerswap-bot.py +++ b/Peerswap/peerswap-bot.py @@ -32,23 +32,28 @@ config = configparser.ConfigParser() config.read(config_file_path) -BOT_TOKEN = config['telegram']['peerswap_bot_token'] -TELEGRAM_USER_ID = config['telegram']['telegram_user_id'] -MEMPOOL_TX = config['urls']['mempool_tx'] -LIQUID_TX = config['urls']['liquid_tx'] -PATH_COMMAND = config['system']['path_command'] +BOT_TOKEN = config.get('telegram', 'peerswap_bot_token', fallback='').strip() +TELEGRAM_USER_ID = config.get('telegram', 'telegram_user_id', fallback='').strip() +MEMPOOL_TX = config.get('urls', 'mempool_tx', fallback='https://mempool.space/tx/').strip() +LIQUID_TX = config.get('urls', 'liquid_tx', fallback='https://liquid.network/tx/').strip() +PATH_COMMAND = config.get('system', 'path_command', fallback='/usr/local/bin').strip() +PSCLI_BIN = ( + config.get('paths', 'pscli_path', fallback='').strip() + or (os.path.join(PATH_COMMAND, 'pscli') if PATH_COMMAND else 'pscli') +) # Logging log_file_path = os.path.join(parent_dir, '..', 'logs', 'peerswap-bot.log') os.makedirs(os.path.dirname(log_file_path), exist_ok=True) logging.basicConfig(filename=log_file_path, level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') -bot = telebot.TeleBot(BOT_TOKEN) -logging.info("Peerswap bot started") +bot = telebot.TeleBot( + BOT_TOKEN if (BOT_TOKEN and ':' in BOT_TOKEN) else '123456:fake_token_for_testing' +) # Function to check if the user is authorized def is_authorized_user(user_id): - return str(user_id) == TELEGRAM_USER_ID + return bool(TELEGRAM_USER_ID) and str(user_id) == TELEGRAM_USER_ID # Decorator function for authorization check def authorized_only(func): @@ -61,7 +66,9 @@ def wrapper(message): def get_node_alias(pub_key): try: - response = requests.get(f"https://mempool.space/api/v1/lightning/nodes/{pub_key}") + response = requests.get( + f"https://mempool.space/api/v1/lightning/nodes/{pub_key}", timeout=15 + ) data = response.json() return data.get('alias', '') except Exception as e: @@ -153,7 +160,7 @@ def format_single_swap_output(swap): def list_recent_swaps(message, count=1): send_formatted_output(message.chat.id, "Checking most recent PeerSwap Swap...") - command = [f'{PATH_COMMAND}/pscli', 'listswaps'] + command = [PSCLI_BIN, 'listswaps'] output = execute_command(command) try: data = json.loads(output) @@ -223,7 +230,7 @@ def format_generic_output(data): def list_all_swaps(message): send_formatted_output(message.chat.id, "Checking PeerSwap Swaps...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'listswaps']) + output = execute_command([PSCLI_BIN, 'listswaps']) try: data = json.loads(output) swaps = data.get('swaps', []) @@ -267,7 +274,7 @@ def help_command(message): @authorized_only def list_peers(message): # Execute the command and capture the output - output = subprocess.check_output([f'{PATH_COMMAND}/pscli', 'listpeers'], text=True) + output = subprocess.check_output([PSCLI_BIN, 'listpeers'], text=True) if not output.startswith("Error"): # Parse the JSON output data = json.loads(output) @@ -307,7 +314,7 @@ def list_peers(message): @authorized_only def list_swap_requests(message): send_formatted_output(message.chat.id, "Checking PeerSwap Requests...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'listswaprequests']) + output = execute_command([PSCLI_BIN, 'listswaprequests']) formatted_output = format_output(json.loads(output)) print(formatted_output) send_formatted_output(message.chat.id, formatted_output) @@ -322,7 +329,7 @@ def swapin_command(message): send_formatted_output(message.chat.id, "Usage: /swapin sat_amt channel_id asset") return - command = [f'{PATH_COMMAND}/pscli', 'swapin', '--sat_amt', sat_amt, '--channel_id', channel_id, '--asset', asset] + command = [PSCLI_BIN, 'swapin', '--sat_amt', sat_amt, '--channel_id', channel_id, '--asset', asset] output = execute_command(command) if "Error" in output: print(output) @@ -342,7 +349,7 @@ def swapout_command(message): send_formatted_output(message.chat.id, "Usage: /swapout sat_amt channel_id asset") return - command = [f'{PATH_COMMAND}/pscli', 'swapout', '--sat_amt', sat_amt, '--channel_id', channel_id, '--asset', asset] + command = [PSCLI_BIN, 'swapout', '--sat_amt', sat_amt, '--channel_id', channel_id, '--asset', asset] output = execute_command(command) if "Error" in output: print(output) @@ -366,7 +373,7 @@ def list_swaps(message): @authorized_only def lbtc_getbalance(message): send_formatted_output(message.chat.id, "Fetching LBTC Balance...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'lbtc-getbalance']) + output = execute_command([PSCLI_BIN, 'lbtc-getbalance']) try: data = json.loads(output) formatted_output = f"Amount: {data['sat_amount']} sats" @@ -379,7 +386,7 @@ def lbtc_getbalance(message): @authorized_only def lbtc_getaddress(message): send_formatted_output(message.chat.id, "Fetching L-BTC Address...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'lbtc-getaddress']) + output = execute_command([PSCLI_BIN, 'lbtc-getaddress']) try: data = json.loads(output) formatted_output = f"L-BTC Address" @@ -404,7 +411,7 @@ def add_peer(message): return send_formatted_output(message.chat.id, f"Adding Peer with Public Key: {pub_key}...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'addpeer', '--peer_pubkey', pub_key]) + output = execute_command([PSCLI_BIN, 'addpeer', '--peer_pubkey', pub_key]) try: data = json.loads(output) formatted_output = format_generic_output(data) @@ -417,7 +424,7 @@ def add_peer(message): @authorized_only def reload_policy(message): send_formatted_output(message.chat.id, "Reloading Policy...") - output = execute_command([f'{PATH_COMMAND}/pscli', 'reloadpolicy']) + output = execute_command([PSCLI_BIN, 'reloadpolicy']) try: data = json.loads(output) formatted_output = format_generic_output(data) @@ -435,7 +442,7 @@ def lbtc_send_to_address(message): send_formatted_output(message.chat.id, "Usage: /lbtcsend sat_amt address") return - command = [f'{PATH_COMMAND}/pscli', 'lbtc-sendtoaddress', '--sat_amt', sat_amt, '--address', address] + command = [PSCLI_BIN, 'lbtc-sendtoaddress', '--sat_amt', sat_amt, '--address', address] output = execute_command(command) if "Error" in output: @@ -446,14 +453,24 @@ def lbtc_send_to_address(message): print(formatted_output) send_formatted_output(message.chat.id, formatted_output) -# Polling to keep the bot running -while True: - try: - bot.polling() - logging.info("Polling cycle completed") - time.sleep(15) # Adjust sleep duration as needed - except Exception as e: - # Log the exception with traceback for detailed information - logging.error(f"Exception occurred: {e}\nTraceback: {traceback.format_exc()}") - time.sleep(60) # Wait before retrying +def run_bot(): + if not BOT_TOKEN or ":" not in BOT_TOKEN: + raise ValueError("Missing or invalid [telegram] peerswap_bot_token in config.ini") + if not TELEGRAM_USER_ID: + raise ValueError("Missing [telegram] telegram_user_id in config.ini") + + logging.info("Peerswap bot started") + while True: + try: + bot.polling() + logging.info("Polling cycle completed") + time.sleep(15) # Adjust sleep duration as needed + except Exception as e: + # Log the exception with traceback for detailed information + logging.error(f"Exception occurred: {e}\nTraceback: {traceback.format_exc()}") + time.sleep(60) # Wait before retrying + + +if __name__ == "__main__": + run_bot() diff --git a/Peerswap/peerswap-lndg_push.py b/Peerswap/peerswap-lndg_push.py index fd1b0f8..88d0cb4 100644 --- a/Peerswap/peerswap-lndg_push.py +++ b/Peerswap/peerswap-lndg_push.py @@ -10,7 +10,12 @@ import argparse import locale -locale.setlocale(locale.LC_ALL, "") +try: + locale.setlocale(locale.LC_ALL, "") +except locale.Error: + pass + +DEFAULT_HTTP_TIMEOUT = 30 # Get the path to the parent directory parent_dir = os.path.dirname(os.path.abspath(__file__)) @@ -21,17 +26,18 @@ config.read(config_file_path) # pscli path and get peers information -pscli_path = config["paths"]["pscli_path"] +pscli_path = config.get("paths", "pscli_path", fallback="pscli").strip() or "pscli" pscli_command = [pscli_path, "listpeers"] # lncli path from the config file -lncli_path = config["paths"]["lncli_path"] +lncli_path = config.get("paths", "lncli_path", fallback="lncli").strip() or "lncli" # LNDg API credentials and endpoints -username = config["credentials"]["lndg_username"] -password = config["credentials"]["lndg_password"] +username = config.get("credentials", "lndg_username", fallback="").strip() +password = config.get("credentials", "lndg_password", fallback="").strip() -lndg_api_url = config["lndg"]["lndg_api_url"] + "/api/channels" +_lndg_base = config.get("lndg", "lndg_api_url", fallback="").strip().rstrip("/") +lndg_api_url = f"{_lndg_base}/api/channels" if _lndg_base else "" # File path for the log file log_file_path = os.path.join(parent_dir, "..", "logs", "peerswap-LNDg_changes.log") @@ -159,7 +165,9 @@ def get_current_notes(channel_id): try: # Make the API request with authentication - response = requests.get(api_url, auth=(username, password)) + response = requests.get( + api_url, auth=(username, password), timeout=DEFAULT_HTTP_TIMEOUT + ) # Check if the request was successful (status code 200) if response.status_code == 200: @@ -192,7 +200,10 @@ def update_notes(channel_id, notes, dry_run=False): return try: response = requests.put( - api_url, json=payload, auth=(username, password) + api_url, + json=payload, + auth=(username, password), + timeout=DEFAULT_HTTP_TIMEOUT, ) # timestamp = get_current_timestamp() # This line is removed as per new_code @@ -216,9 +227,6 @@ def update_notes(channel_id, notes, dry_run=False): def main(): - channels_data = get_lncli_listchannels_output() - peers_info = get_peerswap_info() - parser = argparse.ArgumentParser( description="Script to update notes for LNDg channels." ) @@ -248,6 +256,12 @@ def main(): ) args = parser.parse_args() + if not lndg_api_url or not username or not password: + raise ValueError("Missing [lndg] or [credentials] settings in config.ini") + + channels_data = get_lncli_listchannels_output() + peers_info = get_peerswap_info() + if args.delete: filter_and_delete_notes(peers_info, channels_data, dry_run=args.dry_run) diff --git a/tests/test_p0_runtime_safety.py b/tests/test_p0_runtime_safety.py new file mode 100644 index 0000000..e7b1691 --- /dev/null +++ b/tests/test_p0_runtime_safety.py @@ -0,0 +1,427 @@ +"""Regression tests for P0 runtime safety fixes across production scripts.""" + +from __future__ import annotations + +import configparser +import importlib.util +import json +import locale +import stat +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, mock_open, patch + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +def _load_isolated_module(rel_path: str, module_name: str): + """Load a script under an isolated module name so hyphenated paths and monkeypatches stay local.""" + script_path = REPO_ROOT / rel_path + spec = importlib.util.spec_from_file_location(module_name, script_path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_fee_adjuster_atomic_charge_lnd_write_overwrites_and_sets_0644(tmp_path): + module = _load_isolated_module("Other/fee_adjuster.py", "_p0_fee_adjuster_atomic") + target = tmp_path / "charge-lnd" / "fee_adjuster.txt" + + first_entries = [ + module.format_charge_lnd_entry("02aaa", "PeerA", 120, False, True, -30), + module.format_charge_lnd_entry("03bbb", "PeerB", 250, True, False, 0), + ] + module.write_charge_lnd_entries_atomic(str(target), first_entries) + + second_entries = [ + module.format_charge_lnd_entry("02aaa", "PeerA", 140, False, True, -35), + ] + module.write_charge_lnd_entries_atomic(str(target), second_entries) + + content = target.read_text(encoding="utf-8") + assert content.count("node.id = 02aaa") == 1 + assert "fee_ppm = 140" in content + assert "node.id = 03bbb" not in content + assert stat.S_IMODE(target.stat().st_mode) == 0o644 + + +def test_fee_adjuster_fatal_error_exits_nonzero_without_sleeping(monkeypatch): + module = _load_isolated_module("Other/fee_adjuster.py", "_p0_fee_adjuster_exit") + sleep_mock = MagicMock() + monkeypatch.setattr(module.time, "sleep", sleep_mock) + monkeypatch.setattr(module, "load_config", MagicMock(side_effect=RuntimeError("boom"))) + monkeypatch.setattr(sys, "argv", ["fee_adjuster.py"]) + + with pytest.raises(SystemExit) as exc_info: + module.main() + + assert exc_info.value.code == 1 + sleep_mock.assert_not_called() + + +def test_fee_adjuster_http_calls_pass_timeout(monkeypatch): + module = _load_isolated_module("Other/fee_adjuster.py", "_p0_fee_adjuster_timeout") + cfg = configparser.ConfigParser() + cfg.read_dict( + { + "lndg": {"lndg_api_url": "http://localhost:8889"}, + "credentials": {"lndg_username": "u", "lndg_password": "p"}, + } + ) + + timeouts: list[tuple[str, object]] = [] + + class DummyResponse: + status_code = 200 + text = "{}" + + def __init__(self, payload): + self._payload = payload + + def raise_for_status(self): + pass + + def json(self): + return self._payload + + def fake_get(url, **kwargs): + timeouts.append(("GET", kwargs.get("timeout"))) + if "forwards" in url: + return DummyResponse({"results": []}) + return DummyResponse( + { + "results": [ + { + "remote_pubkey": "02aaa", + "chan_id": "111", + "is_open": True, + "is_active": True, + "local_balance": 500, + "capacity": 1000, + "local_fee_rate": 100, + "alias": "PeerA", + "num_updates": 10, + } + ] + } + ) + + def fake_put(url, **kwargs): + timeouts.append(("PUT", kwargs.get("timeout"))) + return DummyResponse({}) + + def fake_post(url, **kwargs): + timeouts.append(("POST", kwargs.get("timeout"))) + return DummyResponse({}) + + monkeypatch.setattr(module.requests, "get", fake_get) + monkeypatch.setattr(module.requests, "put", fake_put) + monkeypatch.setattr(module.requests, "post", fake_post) + module._CHANNEL_CACHE = None + + module.fetch_all_channels(cfg) + module.get_last_peer_forwarding_timestamp("02aaa", 7, ["111"], cfg) + module.update_lndg_fee( + "111", + 150, + -20, + {"auto_fees": True, "ar_out_target": 50}, + cfg, + new_ar_out_target=100, + ) + module.update_channel_notes( + "111", + "PeerA", + "default", + "median", + {}, + 0.5, + 2, + 1.0, + cfg, + {"update_channel_notes": True}, + ) + + assert len(timeouts) == 5 + assert all(val == module.DEFAULT_HTTP_TIMEOUT for _, val in timeouts) + + +def test_pocketmoney_skips_success_alert_on_failed_payment( + tmp_path, monkeypatch, requests_mock +): + module = _load_isolated_module("LNBits/pocketmoney.py", "_p0_pocketmoney_fail") + lnbits_dir = tmp_path / "LNBits" + lnbits_dir.mkdir() + (tmp_path / "wallets.json").write_text( + json.dumps( + { + "ChildA": { + "wallet_id": "w1", + "invoice_key": "invkey", + "fiat_amount": 5, + "fiat_currency": "EUR", + } + } + ), + encoding="utf-8", + ) + + monkeypatch.setattr(module, "parent_dir", str(lnbits_dir)) + monkeypatch.setattr(module, "LNBITS_URL", "https://lnbits.example.com") + monkeypatch.setattr(module, "ADMIN_KEY", "admkey") + monkeypatch.setattr(module, "CHAT_ID", "12345") + bot_mock = MagicMock() + monkeypatch.setattr(module, "bot", bot_mock) + + requests_mock.get("https://lnbits.example.com/api/v1/rate/EUR", json={"rate": 1000}) + requests_mock.post( + "https://lnbits.example.com/api/v1/payments", + [ + {"status_code": 201, "json": {"bolt11": "lnbc1testinvoice"}}, + {"status_code": 500, "json": {"detail": "route failure"}}, + ], + ) + wallet_mock = requests_mock.get( + "https://lnbits.example.com/api/v1/wallet", json={"balance": 5000000} + ) + + failures = module.scheduled_transfer() + + assert failures == 1 + assert not wallet_mock.called + sent_texts = [call.args[1] for call in bot_mock.send_message.call_args_list] + assert not any("Transferred" in txt for txt in sent_texts) + assert any("Error paying invoice" in txt for txt in sent_texts) + + +def test_pocketmoney_success_sends_alert_and_checks_balance_with_timeouts( + tmp_path, monkeypatch, requests_mock +): + module = _load_isolated_module("LNBits/pocketmoney.py", "_p0_pocketmoney_ok") + lnbits_dir = tmp_path / "LNBits" + lnbits_dir.mkdir() + (tmp_path / "wallets.json").write_text( + json.dumps( + { + "ChildA": { + "wallet_id": "w1", + "invoice_key": "invkey", + "fiat_amount": 5, + "fiat_currency": "EUR", + } + } + ), + encoding="utf-8", + ) + + monkeypatch.setattr(module, "parent_dir", str(lnbits_dir)) + monkeypatch.setattr(module, "LNBITS_URL", "https://lnbits.example.com") + monkeypatch.setattr(module, "ADMIN_KEY", "admkey") + monkeypatch.setattr(module, "CHAT_ID", "12345") + bot_mock = MagicMock() + monkeypatch.setattr(module, "bot", bot_mock) + + requests_mock.get("https://lnbits.example.com/api/v1/rate/EUR", json={"rate": 1000}) + requests_mock.post( + "https://lnbits.example.com/api/v1/payments", + [ + {"status_code": 201, "json": {"bolt11": "lnbc1testinvoice"}}, + {"status_code": 201, "json": {"payment_hash": "abc"}}, + ], + ) + wallet_mock = requests_mock.get( + "https://lnbits.example.com/api/v1/wallet", json={"balance": 5000000} + ) + + failures = module.scheduled_transfer() + + assert failures == 0 + assert wallet_mock.called + assert all(req.timeout == module.DEFAULT_HTTP_TIMEOUT for req in requests_mock.request_history) + sent_texts = [call.args[1] for call in bot_mock.send_message.call_args_list] + assert any("Transferred" in txt for txt in sent_texts) + + # Verify --run-once exits 1 when scheduled_transfer returns failures + monkeypatch.setattr(module, "scheduled_transfer", lambda: 1) + monkeypatch.setattr(module, "validate_runtime_config", lambda: None) + monkeypatch.setattr(sys, "argv", ["pocketmoney.py", "--run-once"]) + with pytest.raises(SystemExit) as exc_info: + module.main() + assert exc_info.value.code == 1 + + +def test_magma_sale_process_expands_tilde_in_loop_tlscertpath(monkeypatch): + mock_telebot = MagicMock() + bot_mock = MagicMock() + bot_mock.callback_query_handler = MagicMock(return_value=lambda f: f) + bot_mock.message_handler = MagicMock(return_value=lambda f: f) + mock_telebot.TeleBot = MagicMock(return_value=bot_mock) + + cfg = configparser.ConfigParser() + cfg.read_dict( + { + "telegram": {"magma_bot_token": "fake_token", "telegram_user_id": "123"}, + "credentials": {"amboss_authorization": "fake_auth"}, + "system": {"full_path_bos": "/path/to/bos", "path_command": "/usr/local/bin"}, + "magma": { + "invoice_expiry_seconds": "1800", + "max_fee_percentage_of_invoice": "0.9", + "channel_fee_rate_ppm": "350", + }, + "urls": {"mempool_fees_api": "https://mempool.space/api/v1/fees/recommended"}, + "pubkey": {"banned_magma_pubkeys": ""}, + "paths": {"lncli_path": "/usr/local/bin/lncli"}, + } + ) + mock_cp_mod = MagicMock() + mock_cp_mod.ConfigParser.return_value = cfg + + with ( + patch.dict( + sys.modules, + { + "telebot": mock_telebot, + "telebot.types": MagicMock(), + "configparser": mock_cp_mod, + "schedule": MagicMock(), + "logging.handlers": MagicMock(), + }, + ), + patch("builtins.open", mock_open(read_data="")), + patch("os.makedirs"), + ): + module = _load_isolated_module( + "Magma/magma_sale_process.py", "_p0_magma_loop_tilde" + ) + + recorded_cmds: list[list[str]] = [] + + class FakeProc: + def __init__(self, stdout_bytes: bytes): + self._stdout = stdout_bytes + self.returncode = 0 + + def communicate(self): + return self._stdout, b"" + + def fake_popen(cmd, **_kwargs): + recorded_cmds.append(cmd) + return FakeProc(b'{"utxos": []}') + + monkeypatch.setattr(module.os.path, "exists", lambda p: p == "/usr/local/bin/loop") + monkeypatch.setattr(module.subprocess, "Popen", fake_popen) + + module.get_lncli_utxos() + + assert len(recorded_cmds) == 2 + loop_cmd = recorded_cmds[1] + tls_arg = next(arg for arg in loop_cmd if arg.startswith("--tlscertpath=")) + assert "~" not in tls_arg + assert tls_arg.endswith("/.lit/tls.cert") + + +def test_peerswap_lndg_push_survives_locale_error_and_help_skips_binaries(monkeypatch): + def failing_setlocale(*_args, **_kwargs): + raise locale.Error("unsupported locale setting") + + monkeypatch.setattr(locale, "setlocale", failing_setlocale) + module = _load_isolated_module("Peerswap/peerswap-lndg_push.py", "_p0_ps_lndg_push") + + run_mock = MagicMock(side_effect=AssertionError("subprocess.run called during --help")) + monkeypatch.setattr(module.subprocess, "run", run_mock) + monkeypatch.setattr(sys, "argv", ["peerswap-lndg_push.py", "--help"]) + + with pytest.raises(SystemExit) as exc_info: + module.main() + + assert exc_info.value.code == 0 + run_mock.assert_not_called() + + +def test_peerswap_lndg_push_http_calls_pass_timeout(monkeypatch): + module = _load_isolated_module( + "Peerswap/peerswap-lndg_push.py", "_p0_ps_lndg_push_timeout" + ) + monkeypatch.setattr(module, "lndg_api_url", "http://localhost:8889/api/channels") + monkeypatch.setattr(module, "username", "u") + monkeypatch.setattr(module, "password", "p") + + seen: list[tuple[str, object]] = [] + + def fake_get(url, **kwargs): + seen.append(("GET", kwargs.get("timeout"))) + return SimpleNamespace(status_code=200, json=lambda: {"notes": "ok"}) + + def fake_put(url, **kwargs): + seen.append(("PUT", kwargs.get("timeout"))) + return SimpleNamespace(status_code=400) + + monkeypatch.setattr(module.requests, "get", fake_get) + monkeypatch.setattr(module.requests, "put", fake_put) + + assert module.get_current_notes("123") == "ok" + module.update_notes("123", "hello") + assert seen == [("GET", module.DEFAULT_HTTP_TIMEOUT), ("PUT", module.DEFAULT_HTTP_TIMEOUT)] + + +def test_channel_fee_pull_import_safe_and_atomic_write(tmp_path, monkeypatch): + get_mock = MagicMock(side_effect=AssertionError("HTTP called during import")) + monkeypatch.setattr("requests.get", get_mock) + + module = _load_isolated_module("LNDg/channel_fee-pull.py", "_p0_channel_fee_pull") + get_mock.assert_not_called() + + target = tmp_path / ".chargelnd" / ".config" / "0_fee.txt" + monkeypatch.setattr(module, "file_path", str(target)) + monkeypatch.setattr(module, "api_url", "http://localhost:8889/api/channels") + monkeypatch.setattr(module, "ignore_remote_pubkeys", ["02ignored"]) + + recorded_timeouts: list[object] = [] + + def fake_get(url, **kwargs): + recorded_timeouts.append(kwargs.get("timeout")) + return SimpleNamespace( + status_code=200, + json=lambda: { + "results": [ + {"chan_id": "111", "local_fee_rate": 0, "remote_pubkey": "02keep"}, + {"chan_id": "222", "local_fee_rate": 0, "remote_pubkey": "02ignored"}, + {"chan_id": "333", "local_fee_rate": 50, "remote_pubkey": "02keep"}, + ] + }, + ) + + monkeypatch.setattr(module.requests, "get", fake_get) + module.main() + + assert recorded_timeouts == [module.DEFAULT_HTTP_TIMEOUT] + assert target.read_text(encoding="utf-8") == "111\n" + assert stat.S_IMODE(target.stat().st_mode) == 0o644 + + +def test_peerswap_bot_import_safe_authz_and_timeout(monkeypatch): + module = _load_isolated_module("Peerswap/peerswap-bot.py", "_p0_peerswap_bot") + + assert "//" not in module.PSCLI_BIN + + monkeypatch.setattr(module, "TELEGRAM_USER_ID", "999") + assert module.is_authorized_user(999) is True + assert module.is_authorized_user(111) is False + + seen_timeouts: list[object] = [] + + def fake_get(url, **kwargs): + seen_timeouts.append(kwargs.get("timeout")) + return SimpleNamespace(json=lambda: {"alias": "TestNode"}) + + monkeypatch.setattr(module.requests, "get", fake_get) + assert module.get_node_alias("02abc") == "TestNode" + assert seen_timeouts == [15] + + monkeypatch.setattr(module, "BOT_TOKEN", "") + with pytest.raises(ValueError, match="peerswap_bot_token"): + module.run_bot() From ea4bb1da1844bbec3aa175747b846365d48d61db Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:20:02 +0100 Subject: [PATCH 2/3] ci,chore: add project metadata, ruff/shellcheck lint, and pip-audit security CI - Add [project] metadata (requires-python >=3.11,<3.14), optional db/dev extras, ruff config, and coverage settings in pyproject.toml. - Pin minimum bounds in requirements-dev.txt and expand .gitignore for runtime flags/state/caches. - Add github-actions weekly updates to .github/dependabot.yml. - Add parallel lint (ruff + bash -n + shellcheck), pip-audit security job, weekly schedule, job timeouts, and 35% coverage gate in .github/workflows/tests.yml. --- .github/dependabot.yml | 8 +++++ .github/workflows/tests.yml | 62 +++++++++++++++++++++++++++++++++++-- .gitignore | 9 ++++++ pyproject.toml | 46 +++++++++++++++++++++++++++ requirements-dev.txt | 10 +++--- 5 files changed, 129 insertions(+), 6 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a168c57..4ca3797 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,3 +11,11 @@ updates: update-types: - "minor" - "patch" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + groups: + actions-updates: + patterns: + - "*" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a972341..7406ae2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -5,6 +5,8 @@ on: branches: [ main, "feat/**", "fix/**" ] pull_request: branches: [ main ] + schedule: + - cron: "0 6 * * 1" workflow_dispatch: permissions: @@ -17,6 +19,7 @@ concurrency: jobs: test: runs-on: ubuntu-latest + timeout-minutes: 10 strategy: fail-fast: false matrix: @@ -37,6 +40,61 @@ jobs: python -m pip install --upgrade pip pip install -r requirements.txt -r requirements-dev.txt - - name: Run pytest with coverage + - name: Run pytest (Python 3.12 with coverage) + if: matrix.python-version == '3.12' run: | - pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov-report=term + pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov-report=term --cov-fail-under=35 | tee pytest_cov.txt + { + echo "### Pytest Coverage (Python ${{ matrix.python-version }})" + echo '```text' + tail -n 30 pytest_cov.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Run pytest (Python ${{ matrix.python-version }}) + if: matrix.python-version != '3.12' + run: pytest tests/ -v + + lint: + runs-on: ubuntu-latest + timeout-minutes: 10 + + steps: + - uses: actions/checkout@v5 + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: "pip" + cache-dependency-path: "requirements-dev.txt" + + - name: Install ruff + run: pip install -r requirements-dev.txt + + - name: Run ruff check on modern/updated tests + run: ruff check tests/test_p0_runtime_safety.py tests/test_ca_trust_hardening.py tests/test_repo_hygiene.py + + - name: Validate shell scripts + run: | + bash -n LNBits/install_pocketmoney_service.sh Other/install_fee_adjuster_service.sh + shellcheck -S error LNBits/install_pocketmoney_service.sh Other/install_fee_adjuster_service.sh + + security: + runs-on: ubuntu-latest + timeout-minutes: 10 + + steps: + - uses: actions/checkout@v5 + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: "pip" + cache-dependency-path: "requirements*.txt" + + - name: Run pip-audit against requirements.txt + run: | + pip install "pip-audit>=2.7" + pip-audit -r requirements.txt diff --git a/.gitignore b/.gitignore index 0d81b79..f926a5e 100644 --- a/.gitignore +++ b/.gitignore @@ -53,7 +53,16 @@ PR_DESCRIPTION_TEMP.md # Testing and Coverage .pytest_cache/ +.ruff_cache/ .coverage .coverage.* coverage.xml htmlcov/ + +# OS / Patch / Runtime State +.DS_Store +*.orig +*.flag +*.pid +.lpt-state.json +.lpt-backups/ diff --git a/pyproject.toml b/pyproject.toml index d3adb9c..ba50ac3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,33 @@ +[project] +name = "lightning-python-tools" +version = "1.0.0" +description = "Collection of Python utilities for Bitcoin Lightning nodes (LND, LNDg, Amboss Magma, PeerSwap, LNbits)" +readme = "README.md" +license = { text = "MIT" } +requires-python = ">=3.11,<3.14" +dependencies = [ + "certifi>=2026.11.20", + "prettytable", + "pyTelegramBotAPI>=4.37.1", + "requests>=2.34.2", + "schedule>=1.2.2", + "urllib3>=2.8.0", +] + +[project.optional-dependencies] +db = [ + "psycopg2-binary", + "pandas", +] +dev = [ + "pytest>=8.0", + "pytest-cov>=5.0", + "pytest-mock>=3.12", + "requests-mock>=1.12", + "ruff>=0.8", + "pip-audit>=2.7", +] + [tool.pytest.ini_options] pythonpath = [ ".", @@ -9,3 +39,19 @@ pythonpath = [ ] testpaths = ["tests"] addopts = "-v" + +[tool.ruff] +target-version = "py311" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "W", "B", "UP"] +ignore = ["E501"] + +[tool.coverage.run] +source = ["LNDg", "Magma", "Other", "Peerswap", "LNBits"] +omit = ["tests/*"] + +[tool.coverage.report] +show_missing = true +skip_covered = false diff --git a/requirements-dev.txt b/requirements-dev.txt index 92e4967..bc1005a 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,6 @@ -pytest -pytest-cov -pytest-mock -requests-mock +pytest>=8.0 +pytest-cov>=5.0 +pytest-mock>=3.12 +requests-mock>=1.12 +ruff>=0.8 +pip-audit>=2.7 From 8827d49aa2cf5137f697fbe01277f7bab5b67e15 Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:14 +0100 Subject: [PATCH 3/3] fix(ci,fee_adjuster): enforce pipefail in coverage step and keep full peer snapshot - .github/workflows/tests.yml: set shell: bash and set -o pipefail on the Python 3.12 pytest | tee step so test or coverage failures cannot be masked by tee. - Other/fee_adjuster.py: collect charge-lnd stanzas for all processed peers regardless of whether an individual peer crossed fee_delta_threshold so unchanged peers are preserved in atomic fee_adjuster.txt writes. - tests/test_p0_runtime_safety.py: add regression test verifying unchanged peers remain in the atomic fee_adjuster.txt snapshot (210/210 passing, 42.51% coverage). --- .github/workflows/tests.yml | 2 + Other/fee_adjuster.py | 3 +- tests/test_p0_runtime_safety.py | 100 ++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7406ae2..4d743b2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -42,7 +42,9 @@ jobs: - name: Run pytest (Python 3.12 with coverage) if: matrix.python-version == '3.12' + shell: bash run: | + set -o pipefail pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov-report=term --cov-fail-under=35 | tee pytest_cov.txt { echo "### Pytest Coverage (Python ${{ matrix.python-version }})" diff --git a/Other/fee_adjuster.py b/Other/fee_adjuster.py index 57b3fb8..5441e2b 100644 --- a/Other/fee_adjuster.py +++ b/Other/fee_adjuster.py @@ -1881,10 +1881,9 @@ def main(): ) sys.stdout.flush() # Ensure output is shown immediately - # Collect charge-lnd stanza once per peer if enabled and any channel updated + # Collect charge-lnd stanza once per processed peer if enabled if ( write_charge_lnd_file_enabled - and updated_any_channel and not skip_charge_lnd_file_write ): charge_lnd_entries.append( diff --git a/tests/test_p0_runtime_safety.py b/tests/test_p0_runtime_safety.py index e7b1691..4e46c8d 100644 --- a/tests/test_p0_runtime_safety.py +++ b/tests/test_p0_runtime_safety.py @@ -49,6 +49,106 @@ def test_fee_adjuster_atomic_charge_lnd_write_overwrites_and_sets_0644(tmp_path) assert stat.S_IMODE(target.stat().st_mode) == 0o644 +def test_fee_adjuster_main_retains_unchanged_peers_in_charge_lnd_snapshot( + tmp_path, monkeypatch +): + module = _load_isolated_module("Other/fee_adjuster.py", "_p0_fee_adjuster_snapshot") + charge_lnd_dir = tmp_path / "charge-lnd" + + cfg = configparser.ConfigParser() + cfg.read_dict( + { + "credentials": { + "amboss_authorization": "tok", + "lndg_username": "u", + "lndg_password": "p", + }, + "lndg": {"lndg_api_url": "http://localhost:8889"}, + "paths": {"charge_lnd_path": str(charge_lnd_dir)}, + } + ) + + node_defs = { + "write_charge_lnd_file": True, + "LNDg_fee_update": True, + "Terminal_output": False, + "update_channel_notes": False, + "inbound_protection": {"lock_ar_out_target_on_discount": False}, + "groups": {}, + "nodes": [ + { + "pubkey": "02updated", + "fee_conditions": { + "base_adjustment_percentage": 0.0, + "fee_base": "median", + "fee_delta_threshold": 5, + "max_cap": 1000, + }, + }, + { + "pubkey": "03unchanged", + "fee_conditions": { + "base_adjustment_percentage": 0.0, + "fee_base": "median", + "fee_delta_threshold": 500, + "max_cap": 1000, + }, + }, + ], + } + + channels_map = { + "02updated": { + "1001": { + "chan_id": "1001", + "alias": "PeerUpdated", + "local_balance": 500_000, + "capacity": 1_000_000, + "local_fee_rate": 100, + "local_inbound_fee_rate": 0, + "ar_max_cost": 50, + "auto_fees": False, + "num_updates": 10, + } + }, + "03unchanged": { + "1002": { + "chan_id": "1002", + "alias": "PeerUnchanged", + "local_balance": 500_000, + "capacity": 1_000_000, + "local_fee_rate": 200, + "local_inbound_fee_rate": 0, + "ar_max_cost": 50, + "auto_fees": False, + "num_updates": 10, + } + }, + } + + monkeypatch.setattr(module, "load_config", lambda: cfg) + monkeypatch.setattr(module, "load_node_definitions", lambda: node_defs) + monkeypatch.setattr(module, "fetch_all_channels", lambda _cfg: channels_map) + monkeypatch.setattr( + module, + "fetch_amboss_data", + lambda _pk, _cfg: { + "TODAY": {"median": "210"}, + "ONE_DAY": {"median": "210"}, + "ONE_WEEK": {"median": "210"}, + "ONE_MONTH": {"median": "210"}, + }, + ) + monkeypatch.setattr(module, "update_lndg_fee", MagicMock()) + monkeypatch.setattr(sys, "argv", ["fee_adjuster.py"]) + + module.main() + + snapshot = (charge_lnd_dir / "fee_adjuster.txt").read_text(encoding="utf-8") + assert "node.id = 02updated" in snapshot + assert "node.id = 03unchanged" in snapshot + + def test_fee_adjuster_fatal_error_exits_nonzero_without_sleeping(monkeypatch): module = _load_isolated_module("Other/fee_adjuster.py", "_p0_fee_adjuster_exit") sleep_mock = MagicMock()