Replace NIP-04 messaging with NIP-17 (NIP-44 + NIP-59 gift wrapping)

Modernize the entire customer-merchant communication layer from deprecated
NIP-04 (kind 4, AES-256-CBC) to NIP-17 private direct messages using
NIP-44 v2 encryption (ChaCha20 + HMAC-SHA256) and NIP-59 gift wrapping
(rumor/seal/gift-wrap protocol). No backwards compatibility retained.

New modules:
- nostr/nip44.py: NIP-44 v2 encryption verified against official spec vectors
- nostr/nip59.py: NIP-59 gift wrap with wrap/unwrap convenience functions
- tests/: 44 unit tests for NIP-44 and NIP-59

Key changes:
- Subscription filters: kind 4 → kind 1059 gift wraps
- Message handler: _handle_nip04_message → _handle_gift_wrap (unwrap + route)
- send_dm/reply_to_structured_dm: NIP-59 gift wrap to recipient + self-archive
- Merchant model: removed NIP-04 crypto methods (decrypt/encrypt/build_dm_event)
- helpers.py: removed NIP-04 functions, kept Schnorr signing + key normalization
- views_api.py: consolidated DM sending through send_dm() service function

Reliability improvements:
- Event deduplication via bounded LRU set in NostrClient
- Subscription health monitor (resubscribes after 120s of silence)
- Preserved 5-minute lenient time window from prior work

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Padreug 2026-04-27 08:16:55 +02:00
commit 725944ae9c
13 changed files with 869 additions and 165 deletions

View file

@ -1,4 +1,5 @@
import asyncio
import time
from asyncio import Queue
from lnbits.core.models import Payment
@ -9,9 +10,13 @@ from .nostr.nostr_client import NostrClient
from .services import (
handle_order_paid,
process_nostr_message,
resubscribe_to_all_merchants,
subscribe_to_all_merchants,
)
HEALTH_CHECK_INTERVAL = 30 # seconds between health checks
STALE_THRESHOLD = 120 # seconds without events before resubscribing
async def wait_for_paid_invoices():
invoice_queue = Queue()
@ -35,17 +40,38 @@ async def on_invoice_paid(payment: Payment) -> None:
async def wait_for_nostr_events(nostr_client: NostrClient):
logger.info("[NOSTRMARKET DEBUG] Starting wait_for_nostr_events task")
logger.info("[NOSTRMARKET] Starting wait_for_nostr_events task")
while True:
try:
logger.info("[NOSTRMARKET DEBUG] Subscribing to all merchants...")
logger.info("[NOSTRMARKET] Subscribing to all merchants...")
await subscribe_to_all_merchants()
while True:
logger.debug("[NOSTRMARKET DEBUG] Waiting for nostr event...")
message = await nostr_client.get_event()
logger.info(f"[NOSTRMARKET DEBUG] Received event from nostr_client: {message[:100]}...")
await process_nostr_message(message)
except Exception as e:
logger.warning(f"[NOSTRMARKET DEBUG] Subscription failed. Will retry in 10 seconds: {e}")
logger.warning(f"[NOSTRMARKET] Subscription failed. Retrying in 10s: {e}")
await asyncio.sleep(10)
async def subscription_health_monitor(nostr_client: NostrClient):
"""
Periodically check if events are flowing. If no events have been
received for STALE_THRESHOLD seconds, force a resubscription with
overlap to catch any missed events.
"""
logger.info("[NOSTRMARKET] Starting subscription health monitor")
while True:
await asyncio.sleep(HEALTH_CHECK_INTERVAL)
try:
if not nostr_client.is_websocket_connected:
continue
elapsed = time.time() - nostr_client.last_event_at
if nostr_client.last_event_at > 0 and elapsed > STALE_THRESHOLD:
logger.warning(
f"[NOSTRMARKET] ⚠️ No events for {elapsed:.0f}s, resubscribing..."
)
await resubscribe_to_all_merchants()
except Exception as e:
logger.error(f"[NOSTRMARKET] Health monitor error: {e}")