From 4454415abf7a313d39a693528de025c2fcb1f020 Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:51:41 +0100 Subject: [PATCH] docs: overhaul README and add installation, configuration, and troubleshooting guides - Streamline README.md with operator safety disclaimer (MIT / no liability / SECURITY.md), ./install.sh quickstart, CI-synced 19-script overview table, doc links, and subtle hodlmetight.org support footer. - Add docs/INSTALLATION.md, docs/CONFIGURATION.md, and docs/TROUBLESHOOTING.md covering interactive & CLI subcommands, systemd vs cron, node/vps profiles, legacy migration, doctor diagnostics, and .lpt-backups/ rollback. - Expand tests/test_repo_hygiene.py to verify relative links across all *.md files, README script table parity with lpt_installer.registry, and disclaimer/donation links. --- README.md | 268 +++++++++++-------------------------- docs/CONFIGURATION.md | 54 ++++++++ docs/INSTALLATION.md | 78 +++++++++++ docs/TROUBLESHOOTING.md | 58 ++++++++ tests/test_repo_hygiene.py | 41 ++++++ 5 files changed, 307 insertions(+), 192 deletions(-) create mode 100644 docs/CONFIGURATION.md create mode 100644 docs/INSTALLATION.md create mode 100644 docs/TROUBLESHOOTING.md diff --git a/README.md b/README.md index 5f55abd..1cd142a 100644 --- a/README.md +++ b/README.md @@ -5,228 +5,111 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Security Policy](https://img.shields.io/badge/Security-Policy-blue.svg)](SECURITY.md) -A modular suite of automation scripts, background daemons, liquidity optimizers, and monitoring utilities for **LND** Lightning Network node operators. +A modular suite of automation scripts, background daemons, liquidity optimizers, and monitoring utilities for **LND** Lightning Network node operators and companion VPS hosts. ---- - -## Table of Contents -- [Overview](#overview) -- [Architecture & Script Directory](#architecture--script-directory) - - [1. Magma (Amboss Liquidity Market)](#1-magma-amboss-liquidity-market) - - [2. LNDg Integration & Fee Management](#2-lndg-integration--fee-management) - - [3. PeerSwap Automation](#3-peerswap-automation) - - [4. Swaps, Fees & UTXO Management](#4-swaps-fees--utxo-management) - - [5. LNbits & Micro-services](#5-lnbits--micro-services) -- [Prerequisites & Installation](#prerequisites--installation) -- [Configuration Guide](#configuration-guide) -- [Running as Background Services](#running-as-background-services) - - [Automated Systemd Service Installers](#automated-systemd-service-installers) - - [Systemd Daemon Example](#systemd-daemon-example) - - [Crontab Example](#crontab-example) -- [Testing & Quality Assurance](#testing--quality-assurance) -- [Security & Vulnerability Reporting](#security--vulnerability-reporting) - ---- - -## Overview - -Operating a routing Lightning node benefits from consistent automation across liquidity pricing, channel policy tuning, and capital rebalancing: -- **Inbound Liquidity Sales**: Autonomous offer pricing, order approval, invoice creation, and channel opening on the Amboss Magma liquidity market. -- **Dynamic Fee Optimization**: Channel fee adjustments driven by Amboss network statistics, forward flow activity, liquidity bands, and stuck-channel decay. -- **Inbound Discount Protection & Rebalance Guard**: Locks `ar_out_target = 100%` on discounted channels to prevent circular rebalance loops from draining refilling liquidity, restoring targets via dynamic hysteresis once balances recover. -- **Submarine & Liquid Swaps**: Economically scored Loop Out swaps (`litloop` / `loopd`) with live prepay route probing, plus Boltz reverse swaps (Lightning to Liquid L-BTC). -- **PeerSwap Operations**: Peer eligibility tracking, LNDg telemetry sync, and interactive swap management over Telegram. - ---- - -## Architecture & Script Directory - -### 1. Magma (Amboss Liquidity Market) -Automate inbound liquidity sales on the Amboss Magma marketplace via the Magma GraphQL API (`https://magma.amboss.tech/graphql`). - -| Script | Execution Mode | Purpose | -| :--- | :--- | :--- | -| [`Magma/magma_sale_process.py`](Magma/magma_sale_process.py) | `systemd service` | **Seller Auto-Pilot Daemon**: Monitors orders awaiting seller approval or channel open, validates on-chain UTXOs and mempool fee bounds, generates Lightning invoices via `lncli addinvoice`, supports interactive Telegram approval/timeout auto-approval, opens channels, confirms funding outpoints to Amboss, and auto-rejects banned peers. See [`Magma/magma_sale.md`](Magma/magma_sale.md). | -| [`Magma/magma_market_fee.py`](Magma/magma_market_fee.py) | `cronjob` / `CLI` | **Dynamic APR & Offer Optimizer**: Queries public Magma market offers, filters by seller score, computes percentile rates and annualized yield (APR) across offer templates in `Magma/magma_config.ini` ([example](Magma/magma_config.ini.example)), and creates, updates, or toggles sell offers (with `--dry-run` support). | - ---- - -### 2. LNDg Integration & Fee Management -Synchronize marketplace metadata and automate channel policies against a local [LNDg](https://github.com/cryptosharks131/lndg) instance. - -| Script | Execution Mode | Purpose | -| :--- | :--- | :--- | -| [`LNDg/amboss_pull.py`](LNDg/amboss_pull.py) | `cronjob` / `CLI` | Pulls active Magma sell orders from Amboss, writes maturity details into LNDg channel notes, toggles auto-fees/auto-rebalance upon lease expiration, and exports `charge-lnd` fee rules. | -| [`LNDg/mempool_rebalancer_trigger.py`](LNDg/mempool_rebalancer_trigger.py) | `systemd service` | Monitors half-hour mempool fee rates (`sat/vB`) and toggles LNDg `AR-Enabled`, pausing auto-rebalancing during high-fee spikes and re-enabling it when fees normalize. | -| [`LNDg/channel_base-fee.py`](LNDg/channel_base-fee.py) | `cronjob` / `one-off` | Resets `base_fee` to `0` across open, active channels in LNDg (excluding pubkeys in `base_fee_ignore`). | -| [`LNDg/channel_fee-pull.py`](LNDg/channel_fee-pull.py) | `cronjob` / `CLI` | Exports open channel IDs currently set to `0 ppm` in LNDg to `~/.chargelnd/.config/0_fee.txt` for `charge-lnd` rule ingestion. | -| [`LNDg/disabled_fee-accelerator.py`](LNDg/disabled_fee-accelerator.py) | `cronjob` / `CLI` | Incrementally bumps `local_fee_rate` in LNDg for depleted peer groups so locally initiated channels disabled by `charge-lnd` at low liquidity can attract rebalance flow. | -| [`LNDg/swap_out-candidates.py`](LNDg/swap_out-candidates.py) | `CLI tool` | Lists high-local-balance, low-PPM channels from LNDg as swap-out candidates, with optional export to `data/low-fee-high-local.log` (`-e`) or `bos/tags.json` (`-b`). | -| [`LNDg/offline_summary.py`](LNDg/offline_summary.py) | `CLI tool` | Queries LNDg's PostgreSQL `gui_peerevents` table (`--month YYYY-MM`) and prints a summary table of average and total peer offline hours (requires optional `psycopg2` and `pandas`). | - ---- - -### 3. PeerSwap Automation -Monitor and execute Layer-1 BTC and Liquid (L-BTC) swaps with connected peers. For bare-metal, RaspiBlitz, and MiniBolt installation instructions for `elementsd` and `peerswapd`, see [`Peerswap/README.md`](Peerswap/README.md). - -| Script | Execution Mode | Purpose | -| :--- | :--- | :--- | -| [`Peerswap/peerswap-bot.py`](Peerswap/peerswap-bot.py) | `systemd service` | **PeerSwap Telegram Bot**: Interactive bot for checking L-BTC balances, listing eligible peers, initiating `swapin`/`swapout` operations, and inspecting swap status. | -| [`Peerswap/peerswap-lndg_push.py`](Peerswap/peerswap-lndg_push.py) | `cronjob` / `CLI` | Aggregates `pscli` swap counts, satoshi volumes, and paid fees per peer and writes them into LNDg channel notes. | -| [`Peerswap/ps_peers.py`](Peerswap/ps_peers.py) | `CLI tool` | Displays a terminal summary table of L-BTC balance, trusted PeerSwap peers, supported assets, channel balances, and local/remote fee rates. | - ---- - -### 4. Swaps, Fees & UTXO Management -Manage dynamic fee curves, rebalance protection, submarine swaps, and on-chain UTXO consolidation. - -| Script | Execution Mode | Purpose | -| :--- | :--- | :--- | -| [`Other/fee_adjuster.py`](Other/fee_adjuster.py) | `systemd timer` / `cronjob` | **Dynamic Fee Optimizer**: Adjusts outbound and inbound channel fees using Amboss Space peer fee metrics, 5-band liquidity curves, and stuck-channel step-downs, with optional `charge-lnd` rule export and inbound discount protection. See [`Other/fee_adjuster.md`](Other/fee_adjuster.md). | -| [`Other/rebalance_guard.py`](Other/rebalance_guard.py) | `cronjob` / `CLI tool` | **Standalone Rebalance Guard**: Audits all open LNDg channels across native Auto-Fees and `fee_adjuster.py`. Locks `ar_out_target = 100%` while an inbound discount is active and restores baseline targets via dynamic hysteresis once liquidity recovers (`--dry-run` supported). | -| [`Other/swap_out-loop.py`](Other/swap_out-loop.py) | `CLI tool` | **Economically Optimized Loop Out**: Scores candidate channels by net effective PPM (server fee + sweep fee + probed routing fee + opportunity cost), performs live fake-hash prepay probes via `lncli`, supports multi-channel MPP selection (`litloop` / `loopd`), interactive terminal UI, and native `loop_sqlite.db` history/CSV accounting. See [`Other/swap_out-loop.md`](Other/swap_out-loop.md). | -| [`Other/boltz_swap-out.py`](Other/boltz_swap-out.py) | `CLI tool` | Automates reverse submarine swaps (Lightning to Liquid L-BTC) via `boltzd` / `boltzcli`, selecting candidate outbound channels from LNDg with multi-batch payment retries and `--debug` dry-run mode. | -| [`Other/swap_wallet.py`](Other/swap_wallet.py) | `CLI tool` | Batches scheduled Lightning payouts to a Lightning Address via `bos send` through high-local-balance peers under configurable fee rate caps. | -| [`Other/lnd_utxo_consolidator.py`](Other/lnd_utxo_consolidator.py) | `CLI tool` | Interactive helper that inspects `lncli listunspent`, filters UTXOs by size and strategy, and prints a verified `lncli sendcoins` consolidation command for manual operator execution (never broadcasts directly). | +> [!WARNING] +> **Operator Safety Disclaimer** +> - **Verify before enabling:** Scripts tagged **FUNDS** or **FEES/POLICY** move mainnet Bitcoin/Lightning funds or modify live channel policies. Always inspect configurations, run `--dry-run` / `--debug` previews, and review source code yourself before enabling automation. +> - **No warranty / no liability:** Provided **"AS IS"** under the [MIT License](LICENSE). The open-source developer assumes **no liability** for lost funds, routing losses, or misconfigured nodes. +> - **Stay updated:** Watch this repository (Releases & Security Advisories) and monitor [`SECURITY.md`](SECURITY.md) regularly for vulnerability patches (`main` is the only supported branch). --- -### 5. LNbits & Micro-services +## Quickstart -| Script | Execution Mode | Purpose | -| :--- | :--- | :--- | -| [`LNBits/pocketmoney.py`](LNBits/pocketmoney.py) | `systemd timer` / `daemon` | Automated recurring satoshi allowances: converts fiat budgets (`USD`, `EUR`, `GBP`, etc.) via LNbits exchange rates, pays child wallets configured in `wallets.json`, and sends Telegram balance alerts (`--run-once` supported for systemd timers/cron). | - ---- +Use the unified installer (`./install.sh`) as your regular node operator user (never `root`). It manages `.venv` creation (`uv` fast-path or stdlib `venv`), copies and hardens config templates (`chmod 600`), validates placeholders, detects duplicate legacy units/cronjobs, and configures `systemd` services/timers or managed `cron` blocks: -## Prerequisites & Installation - -### System Requirements -- **Python**: `3.11`, `3.12`, or `3.13` -- **OS**: Linux (Debian, Ubuntu, RaspiBlitz / Raspberry Pi OS) -- **Core Node**: Running **LND** node (`lncli` accessible) -- **Optional Integrations** (depending on which scripts you use): - - [LNDg](https://github.com/cryptosharks131/lndg) REST API (used by `LNDg/` scripts, `fee_adjuster.py`, `rebalance_guard.py`, `swap_out-loop.py`, and `boltz_swap-out.py`) - - `bos` (Balance of Satoshis), `charge-lnd`, `litd` / `loopd` (`litloop`), `peerswapd` (`pscli`), `boltzd` (`boltzcli`) - - Optional Python packages `psycopg2-binary` and `pandas` (only required for `LNDg/offline_summary.py` against a PostgreSQL LNDg database) - -### Clone & Set Up Virtual Environment ```bash git clone https://github.com/TrezorHannes/Lightning-Python-Tools.git cd Lightning-Python-Tools +chmod +x install.sh -# Create and activate Python virtual environment -python3 -m venv .venv -source .venv/bin/activate - -# Upgrade pip and install runtime dependencies -pip install --upgrade pip -pip install -r requirements.txt +# Launch the interactive menu +./install.sh ``` ---- - -## Configuration Guide - -All local configuration files containing credentials or node-specific rules are ignored by Git (`.gitignore`). Copy the templates you need: +Common non-interactive CLI commands: ```bash -cp config.ini.example config.ini -cp Magma/magma_config.ini.example Magma/magma_config.ini # Required for Magma/magma_market_fee.py -cp feeConfig.json.example feeConfig.json # Required for Other/fee_adjuster.py & Other/rebalance_guard.py -cp wallets.json.example wallets.json # Required for LNBits/pocketmoney.py -chmod 600 config.ini Magma/magma_config.ini feeConfig.json wallets.json -``` +# View all 19 scripts and current installation status +./install.sh list -### Configuration Files Overview -1. **[`config.ini`](config.ini.example)** (shared core configuration): - - `[credentials]`: Amboss API token (`amboss_authorization`) and LNDg login (`lndg_username`, `lndg_password`). - - `[lndg]`: Local LNDg API URL (e.g., `http://localhost:8889`). - - `[paths]` & `[system]`: Paths to `lncli`, `pscli`, `boltzcli`, `bos` (`full_path_bos`), `boltzd` TLS cert/macaroon, `charge_lnd_path`, and `log_level`. - - `[lnd]` & `[loop]`: LND gRPC connection details and Loop Out (`litloop`, `loop_db_path`, confirmation target, liquidity ratios, probe worker count, and routing fee leeway). - - `[magma]`: Invoice expiry, route hints, on-chain fee cap ratio, initial channel PPM, peer connection retries, and polling interval. - - `[pubkey]` & `[no-swapout]`: Comma-separated pubkey exclusion lists (`base_fee_ignore`, `banned_magma_pubkeys`, `swapout_blacklist`). - - `[telegram]`: Bot tokens (`magma_bot_token`, `peerswap_bot_token`, `lnbits_bot_token`) and authorized `telegram_user_id` / `chat_id`. - - `[LNBits]` & `[Schedule]`: LNbits server URL (`base_url`, without `/api/v1`), parent wallet `admin_key`, and allowance recurrence (`daily` or `weekly`). - - `[database]`: Optional PostgreSQL settings (`name`, `host`, `port`) for `LNDg/offline_summary.py`. -2. **[`feeConfig.json`](feeConfig.json.example)**: Peer groups (`sink`, `expensive`, etc.), Amboss fee bases (`median`/`mean`), 5-band liquidity discounts/premiums, stuck-channel intervals, and `inbound_protection` thresholds. -3. **[`Magma/magma_config.ini`](Magma/magma_config.ini.example)**: Auto-pricing toggle, LND on-chain balance allocation fraction, seller-score filter, target competitiveness percentile, and `[magma_offer_*]` channel size/duration/APR templates. -4. **[`wallets.json`](wallets.json.example)**: Child wallet IDs, invoice keys, and fiat allowance amounts/currencies for `LNBits/pocketmoney.py`. +# Run environment, TLS/CA trust, permission, and conflict diagnostics +./install.sh doctor ---- - -## Running as Background Services - -### Unified Service & Scheduler Installer -Use the interactive CLI manager (`./install.sh`) to set up `.venv`, copy/harden configs (`chmod 600`), and generate `systemd` services/timers or `cron` jobs (pre-configured with OS CA trust bundle environment variables): - -```bash -chmod +x install.sh -./install.sh - -# Or install non-interactively via CLI: +# Install scheduled tools non-interactively (after editing configs) ./install.sh install fee-adjuster pocketmoney --scheduler systemd --accept-disclaimer -``` -### Systemd Daemon Example -For long-running daemons such as `Magma/magma_sale_process.py` (full guide in [`Magma/magma_sale.md`](Magma/magma_sale.md)), create `/etc/systemd/system/magma-sale.service`: - -```ini -[Unit] -Description=Amboss Magma Channel Auto-Sale Service -After=network.target lnd.service - -[Service] -Type=simple -User=admin -WorkingDirectory=/home/admin/Lightning-Python-Tools -Environment="SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt" -Environment="REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt" -ExecStart=/home/admin/Lightning-Python-Tools/.venv/bin/python3 /home/admin/Lightning-Python-Tools/Magma/magma_sale_process.py -Restart=always -RestartSec=10 - -[Install] -WantedBy=multi-user.target +# Cleanly remove managed systemd units / cron entries (preserves configs, data/, logs/) +./install.sh uninstall --all ``` -Enable and start the service: -```bash -sudo systemctl daemon-reload -sudo systemctl enable --now magma-sale.service -``` +--- -### Crontab Example -```cron -# Run dynamic fee adjuster every 30 minutes (if not using the systemd timer) -*/30 * * * * /home/admin/Lightning-Python-Tools/.venv/bin/python3 /home/admin/Lightning-Python-Tools/Other/fee_adjuster.py >> /home/admin/Lightning-Python-Tools/logs/cron_fee.log 2>&1 +## Script Directory + +The table below is verified in CI against `lpt_installer/registry.py`: + + +| ID | Script | Risk | Modes | Hosts | Description | +| :--- | :--- | :--- | :--- | :--- | :--- | +| `pocketmoney` | `LNBits/pocketmoney.py` | **FUNDS** | systemd-timer, cron, systemd-service | node, vps | Scheduled fiat-to-sat child allowances via LNbits + Telegram alerts | +| `magma-sale` | `Magma/magma_sale_process.py` | **FUNDS** | systemd-service | node | Auto-pilot daemon for Amboss Magma channel sale orders | +| `magma-market-fee` | `Magma/magma_market_fee.py` | **FEES/POLICY** | systemd-timer, cron, manual | node | Analyzes Magma offers and updates seller offer pricing/status | +| `fee-adjuster` | `Other/fee_adjuster.py` | **FEES/POLICY** | systemd-timer, cron, manual | node, vps | Dynamic 5-band + stuck-channel + inbound-discount fee optimizer | +| `rebalance-guard` | `Other/rebalance_guard.py` | **FEES/POLICY** | systemd-timer, cron, manual | node, vps | Locks ar_out_target=100% on discounted channels with hysteresis | +| `amboss-pull` | `LNDg/amboss_pull.py` | **FEES/POLICY** | systemd-timer, cron, manual | node, vps | Syncs Magma leases to LNDg notes/auto-fees and charge-lnd caps | +| `channel-base-fee` | `LNDg/channel_base-fee.py` | **FEES/POLICY** | systemd-timer, cron, manual | node, vps | Resets base_fee to 0 on open active LNDg channels | +| `channel-fee-pull` | `LNDg/channel_fee-pull.py` | **FEES/POLICY** | systemd-timer, cron, manual | node | Exports 0 ppm open channel IDs to ~/.chargelnd/.config/0_fee.txt | +| `disabled-fee-accelerator` | `LNDg/disabled_fee-accelerator.py` | **FEES/POLICY** | systemd-timer, cron, manual | node, vps | Bumps local_fee_rate on depleted channels disabled by charge-lnd | +| `mempool-rebalancer-trigger` | `LNDg/mempool_rebalancer_trigger.py` | **FEES/POLICY** | systemd-service | node, vps | Polls mempool.space and toggles LNDg AR-Enabled on fee spikes | +| `offline-summary` | `LNDg/offline_summary.py` | **READ-ONLY** | manual | node | Monthly peer offline-duration report from LNDg PostgreSQL | +| `swap-out-candidates` | `LNDg/swap_out-candidates.py` | **READ-ONLY** | manual, systemd-timer, cron | node | Lists high-local low-PPM swap-out candidates (+ optional bos export) | +| `swap-out-loop` | `Other/swap_out-loop.py` | **FUNDS** | manual | node | Economically scored Loop Out optimizer with live route probing | +| `boltz-swap-out` | `Other/boltz_swap-out.py` | **FUNDS** | manual | node | Reverse submarine swaps (LN -> Liquid L-BTC) via boltzcli | +| `swap-wallet` | `Other/swap_wallet.py` | **FUNDS** | manual | node | Interactive batched LN payments to Lightning Address via bos send | +| `lnd-utxo-consolidator` | `Other/lnd_utxo_consolidator.py` | **READ-ONLY** | manual | node | Interactive UTXO selector printing a lncli sendcoins command | +| `peerswap-bot` | `Peerswap/peerswap-bot.py` | **FUNDS** | systemd-service | node | Telegram bot daemon wrapping pscli swaps and L-BTC sends | +| `peerswap-lndg-push` | `Peerswap/peerswap-lndg_push.py` | **READ-ONLY** | systemd-timer, cron, manual | node | Pushes PeerSwap swap stats from pscli into LNDg channel notes | +| `ps-peers` | `Peerswap/ps_peers.py` | **READ-ONLY** | manual | node | Terminal table of L-BTC balance and PeerSwap peer channel policies | + + +### Deep-Dive Tool Guides +- [`Magma/magma_sale.md`](Magma/magma_sale.md) — Amboss Magma channel auto-sale daemon setup and Telegram workflow. +- [`Other/fee_adjuster.md`](Other/fee_adjuster.md) — Dynamic liquidity fee bands, stuck-channel decay, inbound discounts, and `charge-lnd` integration. +- [`Other/swap_out-loop.md`](Other/swap_out-loop.md) — Economically scored Loop Out optimizer, fake-hash route probing, and MPP selection. +- [`Peerswap/README.md`](Peerswap/README.md) — Bare-metal, RaspiBlitz, and MiniBolt setup for `elementsd` and `peerswapd`. -# Run standalone rebalance guard audit hourly -0 * * * * /home/admin/Lightning-Python-Tools/.venv/bin/python3 /home/admin/Lightning-Python-Tools/Other/rebalance_guard.py >> /home/admin/Lightning-Python-Tools/logs/cron_guard.log 2>&1 +--- -# Sync Amboss Magma channel orders to LNDg hourly -15 * * * * /home/admin/Lightning-Python-Tools/.venv/bin/python3 /home/admin/Lightning-Python-Tools/LNDg/amboss_pull.py >> /home/admin/Lightning-Python-Tools/logs/cron_amboss.log 2>&1 -``` +## Documentation + +- [**Installation & Scheduling Guide**](docs/INSTALLATION.md) — Interactive & CLI usage, `uv`/`venv` environments, `systemd` vs `cron`, `node`/`vps` host profiles, legacy unit migration, and clean uninstall. +- [**Configuration Reference**](docs/CONFIGURATION.md) — Template setup (`chmod 600`), placeholder validation, and section-by-section reference for all 4 config files. +- [**Troubleshooting & Diagnostics**](docs/TROUBLESHOOTING.md) — `./install.sh doctor` checks, OS CA trust bindings, duplicate-execution conflicts, file ownership fixes, logs, and rollback snapshots. --- ## Testing & Quality Assurance -Unit tests, Amboss GraphQL contract checks, CA trust hardening checks, and Magma sale lifecycle simulations are executed across Python `3.11`, `3.12`, and `3.13` in GitHub Actions. +GitHub Actions runs `pytest` across Python `3.11`, `3.12`, and `3.13`, `ruff`, `shellcheck`, `systemd-analyze verify`, `pip-audit`, and coverage gates (`>= 85%` on `lpt_installer`, `>= 35%` repo-wide): ```bash source .venv/bin/activate - -# Install test and coverage dependencies pip install -r requirements-dev.txt -# Run the full test suite (configured via pyproject.toml) -pytest +# Run full test suite with coverage +pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov=lpt_installer --cov-report=term + +# Run installer & CA trust gates +pytest tests/test_lpt_installer.py tests/test_ca_trust_hardening.py --cov=lpt_installer --cov-fail-under=85 -# Run with module coverage report -pytest --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits +# Run static checks +ruff check lpt_installer tests/test_lpt_installer.py tests/test_p0_runtime_safety.py tests/test_ca_trust_hardening.py tests/test_repo_hygiene.py +shellcheck -S warning install.sh +pip-audit -r requirements.txt -# Run the standalone offline Magma buy-order lifecycle simulation +# Standalone offline Magma lifecycle simulation python3 tests/simulate_magma_sale.py ``` @@ -234,9 +117,10 @@ python3 tests/simulate_magma_sale.py ## Security & Vulnerability Reporting -For our responsible disclosure policy, supported versions, and contact channels, review [`SECURITY.md`](SECURITY.md). +Review [`SECURITY.md`](SECURITY.md) for responsible disclosure channels, supported versions (`main` only), and operator hardening practices (`chmod 600` on configs, scoped macaroons, OS CA trust bindings via `SSL_CERT_FILE` and `REQUESTS_CA_BUNDLE`, and `certifi>=2026.11.20`). + +--- + +## Support / Donations -- **Vulnerability Disclosure**: Report security vulnerabilities privately via [GitHub Security Advisories](https://github.com/TrezorHannes/Lightning-Python-Tools/security/advisories) or email `security@tunnelsats.com`. -- **Secrets Management**: Never commit `config.ini`, `feeConfig.json`, `wallets.json`, `.env`, or macaroon files to Git. -- **Permissions**: Restrict file permissions on sensitive config files (`chmod 600 config.ini`). -- **Least Privilege**: Use read-only or scoped API keys and LND macaroons wherever possible. +If Lightning Python Tools helps you operate your node, optional donation methods are listed at [hodlmetight.org](https://hodlmetight.org). diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md new file mode 100644 index 0000000..c8914b6 --- /dev/null +++ b/docs/CONFIGURATION.md @@ -0,0 +1,54 @@ +# Configuration Reference + +All user configuration files containing credentials, pubkeys, or node rules are ignored by Git (see [`.gitignore`](../.gitignore)). + +## Guided Setup & Hardening + +```bash +# Copy missing templates, set chmod 600 on configs (chmod 700 on logs/ & data/), and validate +./install.sh config + +# Limit to specific tools and open config.ini in $VISUAL / $EDITOR / nano +./install.sh config --tools fee-adjuster pocketmoney --edit config.ini +``` + +`./install.sh config` never overwrites existing config files and validates: +- Required `[section]` and key presence for the selected tools. +- Untouched template placeholders (`https://yourdomain.com`, `admin_key_1`, `WALLETID*`, `INVOICEID*`, `INVOICEKEY*`, `your_lnd_host:port`, `/path/to/your/lnd/tls.cert`). +- Valid JSON syntax in `feeConfig.json` and `wallets.json`, and valid INI syntax in `config.ini` and `Magma/magma_config.ini`. +- Valid `[Schedule]` (`daily`/`weekly`, `HH:MM`, weekday name) when `pocketmoney` is selected. + +--- + +## Configuration Files + +| File | Template | Used By | +| :--- | :--- | :--- | +| `config.ini` | [`config.ini.example`](../config.ini.example) | Core shared settings across all tools except `ps-peers` | +| `feeConfig.json` | [`feeConfig.json.example`](../feeConfig.json.example) | `Other/fee_adjuster.py`, `Other/rebalance_guard.py` | +| `Magma/magma_config.ini` | [`Magma/magma_config.ini.example`](../Magma/magma_config.ini.example) | `Magma/magma_market_fee.py` | +| `wallets.json` | [`wallets.json.example`](../wallets.json.example) | `LNBits/pocketmoney.py` | + +### `config.ini` Sections + +- **`[credentials]`**: `amboss_authorization` (Amboss API Bearer token), `lndg_username`, `lndg_password`. +- **`[lndg]`**: `lndg_api_url` (e.g. `http://localhost:8889`, or a reachable tunnel/private URL for remote VPS usage). +- **`[pubkey]` & `[no-swapout]`**: Comma-separated node pubkeys (`base_fee_ignore`, `banned_magma_pubkeys`, `swapout_blacklist`). +- **`[paths]` & `[system]`**: Binary paths (`lncli_path`, `pscli_path`, `boltzcli_path`, `full_path_bos`, `path_command`), `boltzd` TLS/macaroon paths, `charge_lnd_path` (defaults to `~/.chargelnd/.config`), and `log_level`. +- **`[telegram]`**: Bot tokens (`magma_bot_token`, `peerswap_bot_token`, `lnbits_bot_token`) and authorized `telegram_user_id` (required by Telegram bots and alerts). +- **`[info]`**: `node` (your local LND identity pubkey). +- **`[urls]` & `[parameters]`**: Explorer URLs (`mempool_tx`, `liquid_tx`, `mempool_fees_api`) and `disabled_fee-accelerator.py` parameters (`fee_updated_hours_ago`, `capped_ceiling`, `agg_liquidity_threshold`). +- **`[magma]`**: `magma_sale_process.py` order polling, invoice expiry, route hints, `max_fee_percentage_of_invoice`, default `channel_fee_rate_ppm`, and connect retries. +- **`[LNBits]` & `[Schedule]`**: LNbits server `base_url` (without `/api/v1`), parent `admin_key`, and allowance `recurrence` (`daily` / `weekly`), `time` (`HH:MM`), `day_of_week`. +- **`[lnd]` & `[loop]`**: LND gRPC settings and `swap_out-loop.py` / `magma_sale_process.py` Loop parameters (`loop_command`, `loop_db_path`, `rpcserver`, `tlscertpath`, fee caps, MPP headroom). +- **`[database]`**: Local PostgreSQL connection (`name`, `host`, `port`) for `LNDg/offline_summary.py`. + +### Dry-Run & Verification Flags + +Before scheduling **FUNDS** or **FEES/POLICY** scripts, preview behavior manually: +- `Other/fee_adjuster.py --debug` — prints full waterfall calculations without writing LNDg or `charge-lnd` files. +- `Other/rebalance_guard.py --dry-run` — previews target locks and restores without mutating LNDg. +- `Magma/magma_market_fee.py --dry-run` — simulates APR offer updates without calling Amboss mutations (`--force` is required for unattended live timers). +- `Other/swap_out-loop.py --dry-run` — scores and probes channels without executing Loop Out swaps. +- `Other/boltz_swap-out.py --debug` — runs Boltz reverse swap selection in dry-run mode. +- `Peerswap/peerswap-lndg_push.py -a --dry-run` — previews LNDg channel note appends (`-a` or `-o` is used in unattended timers). diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 0000000..438c1aa --- /dev/null +++ b/docs/INSTALLATION.md @@ -0,0 +1,78 @@ +# Installation & Scheduling Guide + +This guide covers setting up **Lightning-Python-Tools** with the unified `./install.sh` manager (`lpt_installer/`). + +## Prerequisites + +- **Operating System:** Linux (Debian, Ubuntu, RaspiBlitz / Raspberry Pi OS) for `systemd` and `cron` scheduling; macOS/Linux for CLI development and tests. +- **Python:** `3.11`, `3.12`, or `3.13` (with `python3-venv` on Debian/Ubuntu if `uv` is not installed). +- **Non-root operator user:** Run `./install.sh` as your regular operator account (for example `admin`), **never** as `root` or under `sudo ./install.sh`. The installer invokes `sudo` only when writing/reloading `/etc/systemd/system/lpt-*` units. +- **Optional binaries** (depending on selected scripts): `lncli` (LND), `pscli` (PeerSwap), `litloop` / `loop` (Lightning Loop), `boltzcli` (Boltz), `bos` (Balance of Satoshis), `charge-lnd`. + +## Interactive Setup + +```bash +chmod +x install.sh +./install.sh +``` + +On first run, the installer displays the **Operator Disclaimer** (self-verification, MIT no-liability terms, and `SECURITY.md` update guidance) and persists acknowledgment in gitignored `.lpt-state.json`. From the interactive numbered menu you can: + +1. Create or update the unified `.venv` (`uv` fast-path if installed, otherwise `python3 -m venv .venv` + `pip`). +2. Copy missing config templates (`*.example`), enforce `chmod 600` on configs and `chmod 700` on `logs/` and `data/`, edit files in `$VISUAL`/`$EDITOR`/`nano`, and validate placeholders. +3. Install and enable selected tools via `systemd` or managed `cron`. +4. Uninstall managed tools cleanly while keeping user configs, logs, and data intact. +5. Run `./install.sh doctor` diagnostics. +6. Switch between host profiles (`all`, `node`, `vps`). + +## CLI Subcommands + +Every action is scriptable for SSH automation and remote VPS management: + +| Command | Purpose | +| :--- | :--- | +| `./install.sh list` | Print the 19-script overview table with risk tier, default mode, host profiles, and runtime status. | +| `./install.sh status` | Same as `list`; supports `--profile {all,node,vps}` and `--json`. | +| `./install.sh env [--db] [--recreate] [--dry-run]` | Create or refresh `.venv` (`--db` adds `psycopg2-binary` and `pandas` for `LNDg/offline_summary.py`). | +| `./install.sh config [--tools ID ...] [--edit FILE] [--dry-run]` | Copy missing templates, enforce `chmod 600` / `chmod 700`, optionally edit a file, and run placeholder/schema checks. | +| `./install.sh install ID ... [--scheduler auto\|systemd\|cron\|manual] [--accept-disclaimer] [--dry-run]` | Validate configs, ensure `.venv`, migrate legacy units, and install/start `lpt-*` units or cron entries. | +| `./install.sh uninstall [ID ... \| --all] [--remove-venv] [--purge-configs --yes] [--dry-run]` | Stop/disable `lpt-*` units and remove managed cron entries (preserves configs/logs/data unless `--purge-configs --yes` is passed). | +| `./install.sh doctor [--json]` | Run read-only checks for Python, `.venv` `certifi`, OS CA bundle, `0600` permissions, root-owned runtime files, and legacy units. | + +## Host Profiles (`node` vs `vps`) + +- **`--profile node` (e.g. a full LND/LNDg node):** Shows all 19 scripts, including tools needing local `lncli`, `pscli`, `litloop`, `boltzcli`, `bos`, or PostgreSQL. +- **`--profile vps` (e.g. a companion VPS):** Filters to HTTP-only tools and remote-LNDg-capable scripts (`pocketmoney`, `fee-adjuster`, `rebalance-guard`, `amboss-pull`, `channel-base-fee`, `disabled-fee-accelerator`, `mempool-rebalancer-trigger`). + +## Scheduling Backends: `systemd` vs `cron` + +| Feature | `systemd` Service / Timer (Recommended) | Managed `cron` Block | +| :--- | :--- | :--- | +| **Supported tools** | Daemons (`Type=simple`) & periodic tasks (`Type=oneshot` + `.timer`) | Periodic tasks only (not long-running daemons) | +| **Logging** | `journalctl -u lpt- -n 50 --no-pager` | `logs/cron_.log` | +| **Overlap protection** | Native systemd single-instance serialization | `flock -n logs/.lpt-.lock` | +| **Hang protection** | `TimeoutStartSec=300` on every `Type=oneshot` unit | `flock -n` skips overlapping runs | +| **Catch-up after downtime** | `Persistent=true` on `pocketmoney`, `fee-adjuster`, `amboss-pull` | Runs at next scheduled wall-clock slot | +| **OS CA trust** | `SSL_CERT_FILE` & `REQUESTS_CA_BUNDLE` injected automatically | `SSL_CERT_FILE` & `REQUESTS_CA_BUNDLE` set in managed block header | +| **Sandboxing** | `NoNewPrivileges=true`, `PrivateTmp=true`, `ProtectKernel*`, `ProtectSystem=full` (`strict` for HTTP-only `pocketmoney`) | Runs as current user | + +### `pocketmoney` Schedule Behavior + +`LNBits/pocketmoney.py` reads `[Schedule]` from `config.ini` (`recurrence = daily|weekly`, `time = HH:MM`, `day_of_week = friday`). When installed as `systemd-timer` or `cron`, the installer translates `[Schedule]` into `OnCalendar=` / cron syntax and passes `--run-once`. If installed as `systemd-service` (`Type=simple`), `--run-once` is omitted so `pocketmoney.py` runs its internal `schedule` daemon loop. + +## Migrating Legacy Units & Duplicate-Execution Guard + +Before installing any tool, `lpt_installer` scans `/etc/systemd/system/*.service`, `~/.config/systemd/user/*.service`, `crontab -l` (outside the managed block), and running processes for the target script filename: + +- **Known legacy systemd units** (`pocketmoney.{service,timer}`, `fee_adjuster.{service,timer}`, `magma-sale.service`, `magma-autosale-bot.service`, `peerswap-bot.service`, `mempool_rebalancer_trigger.service`) are backed up to `.lpt-backups//` (`0700`), stopped, disabled, removed, and replaced by `lpt-.*`. +- **Unmanaged crontabs, custom units, or stray processes** cause the installer to **fail closed** so funds-moving or fee-modifying scripts never run twice simultaneously. Remove or stop the conflicting entry manually first, then re-run `./install.sh install ...`. +- **Migrating `fee_adjuster` off `User=root`:** All `lpt-*` units run as your unprivileged operator user (such as `admin`), never `root`. If an older `fee_adjuster.service` previously ran as `root`, reclaim ownership on any root-created runtime files once: + +```bash +sudo chown admin:admin logs/fee-adjuster.log data/rebalance_targets_baseline.json ~/.chargelnd/.config/fee_adjuster.txt +``` + +## Uninstalling & Rollback + +- **Per-tool or full uninstall:** `./install.sh uninstall fee-adjuster` or `./install.sh uninstall --all` stops/disables `lpt-*` units, cleans the managed `cron` block (leaving your own crontab lines verbatim), and preserves `config.ini`, `Magma/magma_config.ini`, `feeConfig.json`, `wallets.json`, `logs/`, and `data/`. +- **Manual rollback:** Pre-change snapshots of `crontab.bak` and migrated legacy unit files are stored in `.lpt-backups//`. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000..28c0226 --- /dev/null +++ b/docs/TROUBLESHOOTING.md @@ -0,0 +1,58 @@ +# Troubleshooting & Diagnostics + +Run the built-in diagnostic command first whenever something fails to install, validate, or execute: + +```bash +./install.sh doctor +``` + +## `doctor` Checks Explained + +| Check | Meaning | How to Fix | +| :--- | :--- | :--- | +| `python` | Host Python must be `3.11`, `3.12`, or `3.13`. | Install Python 3.11–3.13 (`sudo apt-get install -y python3 python3-venv`). | +| `venv-certifi` | Checks `.venv` exists and `certifi >= 2026.10.19` (`requirements.txt` requires `>= 2026.11.20`). | Run `./install.sh env` (or `./install.sh env --recreate`). | +| `ca-bundle` | Verifies an OS CA certificate bundle exists (`/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, or `/etc/ssl/cert.pem`). | On Debian/Ubuntu, run `sudo apt-get install -y ca-certificates`. | +| `perms:` | Flags config files that are group/world readable. | Run `./install.sh config` or `chmod 600 `. | +| `ownership` | Flags root-owned files in `logs/` or `data/` (common after switching `fee_adjuster` from `User=root` to `User=admin`). | Fix with `sudo chown "$USER:$USER" logs/* data/*`. | +| `legacy-units` | Detects pre-existing unprefixed systemd units (`fee_adjuster.*`, `pocketmoney.*`, etc.). | Run `./install.sh install ` to back up and migrate to `lpt-*`. | + +--- + +## Common Issues + +### 1. Installer Refuses with "unmanaged duplicate execution detected" +`lpt_installer` fails closed if the script already appears in: +- a custom unit under `/etc/systemd/system/` or `~/.config/systemd/user/`, +- an unmanaged entry in `crontab -l`, or +- an active process when no known legacy unit is registered for migration. + +**Fix:** Inspect the reported unit/cron line/PID, stop or remove the duplicate manually (`crontab -e` or `sudo systemctl disable --now `), then re-run `./install.sh install ...`. + +### 2. Inspecting Logs (`systemd` vs `cron`) +- **Systemd services & timers:** + ```bash + sudo systemctl status lpt-fee-adjuster.timer lpt-fee-adjuster.service + journalctl -u lpt-fee-adjuster -n 100 --no-pager + ``` +- **Managed cron jobs:** + ```bash + tail -n 100 logs/cron_fee-adjuster.log + ``` + +### 3. `magma_sale_process.py` Halted with `logs/magma_sale_process-critical-error.flag` +If `Magma/magma_sale_process.py` encounters an unrecoverable `litloop` UTXO query failure (so it does not accidentally spend reserved static-loop UTXOs), it writes `logs/magma_sale_process-critical-error.flag` and aborts. +1. Inspect `logs/magma-sale-process.log` and confirm `loop` / `litd` status and `[loop]` `rpcserver` / `tlscertpath` settings in `config.ini`. +2. Delete `logs/magma_sale_process-critical-error.flag` once resolved, then restart `sudo systemctl restart lpt-magma-sale.service`. + +### 4. `crontab binary not found` +Minimal containers or systemd-only images without `cron` installed support `--scheduler systemd` cleanly. To use `--scheduler cron`, install `cron` first (`sudo apt-get install -y cron`). + +### 5. Rolling Back a Change +Before mutating `systemd` or `cron`, `./install.sh` saves your previous `crontab.bak` and any migrated legacy unit files under `.lpt-backups//` (`chmod 700`). To revert completely: + +```bash +./install.sh uninstall --all +# Optionally restore an earlier crontab snapshot: +crontab .lpt-backups//crontab.bak +``` diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.py index 78e4256..c91c444 100644 --- a/tests/test_repo_hygiene.py +++ b/tests/test_repo_hygiene.py @@ -9,6 +9,7 @@ import pytest import pocketmoney +from lpt_installer.registry import render_markdown_overview_table REPO_ROOT = Path(__file__).resolve().parent.parent @@ -118,3 +119,43 @@ def test_readme_relative_file_links_exist(): continue rel_path = target.split("#", maxsplit=1)[0] assert (REPO_ROOT / rel_path).exists(), f"Broken relative link in README.md: {target}" + + +def test_all_markdown_relative_file_links_exist(): + md_files = sorted( + [ + REPO_ROOT / "README.md", + REPO_ROOT / "SECURITY.md", + *(REPO_ROOT / "docs").glob("*.md"), + *(REPO_ROOT / "Magma").glob("*.md"), + *(REPO_ROOT / "Other").glob("*.md"), + REPO_ROOT / "Peerswap" / "README.md", + ] + ) + assert len(md_files) >= 6 + for md_file in md_files: + text = re.sub(r"```.*?```", "", md_file.read_text(encoding="utf-8"), flags=re.S) + for target in re.findall(r"\]\(([^)]+)\)", text): + if target.startswith(("http://", "https://", "#", "mailto:")): + continue + rel_path = target.split("#", maxsplit=1)[0] + resolved = (md_file.parent / rel_path).resolve() + assert resolved.exists(), f"Broken relative link in {md_file}: {target}" + + +def test_readme_script_table_matches_registry(): + readme_text = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + begin_marker = "" + end_marker = "" + assert begin_marker in readme_text and end_marker in readme_text + section = readme_text.split(begin_marker, maxsplit=1)[1].split(end_marker, maxsplit=1)[0].strip() + assert section == render_markdown_overview_table().strip() + + +def test_readme_contains_safety_disclaimer_and_donation_link(): + readme_text = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + lowered = readme_text.lower() + assert "security.md" in lowered + assert "mit" in lowered + assert "no liability" in lowered + assert "https://hodlmetight.org" in readme_text