Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ updates:
update-types:
- "minor"
- "patch"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
groups:
actions-updates:
patterns:
- "*"
64 changes: 62 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ on:
branches: [ main, "feat/**", "fix/**" ]
pull_request:
branches: [ main ]
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:

permissions:
Expand All @@ -17,6 +19,7 @@ concurrency:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
Expand All @@ -37,6 +40,63 @@ 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'
shell: bash
run: |
pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov-report=term
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
Comment thread
tunnelsentinel[bot] marked this conversation as resolved.
Resolved
{
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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
52 changes: 37 additions & 15 deletions LNBits/pocketmoney.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("/")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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}")
Expand All @@ -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")
Expand All @@ -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"]
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
11 changes: 9 additions & 2 deletions LNDg/channel_base-fee.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__))

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
65 changes: 49 additions & 16 deletions LNDg/channel_fee-pull.py
Original file line number Diff line number Diff line change
@@ -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__))

Expand All @@ -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:
Expand All @@ -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()
11 changes: 9 additions & 2 deletions LNDg/disabled_fee-accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__))

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down
Loading