sdk_relay/docs/USAGE.md

11 KiB

📖 Guide d'Utilisation - sdk_relay

Guide complet pour utiliser le service de relais sdk_relay au quotidien.

🚀 Démarrage Rapide

Démarrage du Service

Avec Docker (Recommandé)

# Build de l'image
docker build -f Dockerfile -t sdk_relay .

# Démarrage du service
docker run -d \
  --name sdk_relay \
  -p 8090:8090 \
  -p 8091:8091 \
  -v $(pwd)/.conf:/app/.conf \
  -e RUST_LOG=info \
  sdk_relay

# Vérifier le statut
docker ps | grep sdk_relay

Avec Rust (Compilation native)

# Compilation release
cargo build --release

# Démarrage du service
cargo run --release -- --config .conf

# Ou en arrière-plan
nohup cargo run --release -- --config .conf > sdk_relay.log 2>&1 &

Vérification du Démarrage

# Test de santé HTTP
curl http://localhost:8091/health

# Réponse attendue
{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00Z",
  "version": "1.0.0"
}

# Test WebSocket
wscat -c ws://localhost:8090

# Test métriques
curl http://localhost:8091/metrics

🔌 Connexion WebSocket

Handshake Initial

Envoi du Handshake

{
  "type": "handshake",
  "version": "1.0",
  "client_id": "my_client_001",
  "capabilities": ["silent_payments", "relay_sync"]
}

Réponse du Handshake

{
  "type": "handshake_response",
  "status": "success",
  "server_version": "1.0.0",
  "capabilities": ["silent_payments", "relay_sync", "metrics"],
  "session_id": "session_12345"
}

Gestion des Sessions

Reconnexion Automatique

// Exemple JavaScript
const ws = new WebSocket('ws://localhost:8090');

ws.onopen = function() {
  // Envoyer handshake
  ws.send(JSON.stringify({
    type: "handshake",
    version: "1.0",
    client_id: "my_client_001"
  }));
};

ws.onclose = function() {
  // Reconnexion automatique après 5 secondes
  setTimeout(() => {
    connectWebSocket();
  }, 5000);
};

Heartbeat

// Ping toutes les 30 secondes
{
  "type": "ping",
  "timestamp": "2024-01-01T12:00:00Z"
}

// Réponse pong
{
  "type": "pong",
  "timestamp": "2024-01-01T12:00:00Z"
}

📡 API HTTP REST

Endpoints de Base

GET /health

curl http://localhost:8091/health

Réponse :

{
  "status": "healthy",
  "uptime": 3600,
  "version": "1.0.0",
  "connections": {
    "websocket": 5,
    "http": 2
  }
}

GET /metrics

curl http://localhost:8091/metrics

Réponse :

{
  "requests_total": 1250,
  "requests_per_second": 2.5,
  "websocket_connections": 5,
  "memory_usage_mb": 45.2,
  "cpu_usage_percent": 12.5
}

GET /relays

curl http://localhost:8091/relays

Réponse :

{
  "relays": [
    {
      "id": "relay_001",
      "address": "ws://relay1.example.com:8090",
      "status": "connected",
      "last_seen": "2024-01-01T12:00:00Z"
    },
    {
      "id": "relay_002",
      "address": "ws://relay2.example.com:8090",
      "status": "disconnected",
      "last_seen": "2024-01-01T11:30:00Z"
    }
  ]
}

Endpoints de Gestion

POST /sync/force

curl -X POST http://localhost:8091/sync/force

Réponse :

{
  "status": "sync_started",
  "relays_count": 3,
  "estimated_duration": 30
}

POST /relays/add

curl -X POST http://localhost:8091/relays/add \
  -H "Content-Type: application/json" \
  -d '{
    "address": "ws://newrelay.example.com:8090",
    "description": "Nouveau relais"
  }'

DELETE /relays/{id}

curl -X DELETE http://localhost:8091/relays/relay_001

🔄 Synchronisation des Relais

Architecture Mesh

Découverte des Relais

// Message de découverte
{
  "type": "discovery",
  "relay_id": "relay_001",
  "timestamp": "2024-01-01T12:00:00Z"
}

// Réponse avec liste des relais
{
  "type": "discovery_response",
  "relays": [
    {
      "id": "relay_002",
      "address": "ws://relay2.example.com:8090",
      "capabilities": ["silent_payments"]
    }
  ]
}

Synchronisation des Messages

// Message de synchronisation
{
  "type": "sync_message",
  "message_id": "msg_12345",
  "content": {
    "type": "silent_payment",
    "data": "..."
  },
  "timestamp": "2024-01-01T12:00:00Z",
  "ttl": 3600
}

// Accusé de réception
{
  "type": "sync_ack",
  "message_id": "msg_12345",
  "status": "received"
}

Gestion des Conflits

Résolution de Conflits

// Détection de conflit
{
  "type": "conflict_detected",
  "message_id": "msg_12345",
  "conflict_type": "duplicate",
  "resolution": "keep_latest"
}

💰 Silent Payments

Gestion des Paiements

Création d'un Paiement

// Demande de création
{
  "type": "create_payment",
  "payment_id": "pay_12345",
  "amount_sats": 100000,
  "recipient": "sp1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
  "metadata": {
    "description": "Paiement test"
  }
}

// Confirmation
{
  "type": "payment_created",
  "payment_id": "pay_12345",
  "status": "pending",
  "created_at": "2024-01-01T12:00:00Z"
}

Suivi des Paiements

// Mise à jour de statut
{
  "type": "payment_update",
  "payment_id": "pay_12345",
  "status": "confirmed",
  "block_height": 800000,
  "txid": "abc123...",
  "updated_at": "2024-01-01T12:05:00Z"
}

Intégration Bitcoin Core

Vérification des Blocs

// Notification de nouveau bloc
{
  "type": "block_notification",
  "block_height": 800001,
  "block_hash": "def456...",
  "timestamp": "2024-01-01T12:10:00Z"
}

Scan des Transactions

// Demande de scan
{
  "type": "scan_request",
  "addresses": [
    "sp1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh"
  ],
  "from_block": 800000,
  "to_block": 800001
}

// Résultats du scan
{
  "type": "scan_response",
  "results": [
    {
      "address": "sp1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
      "transactions": [
        {
          "txid": "abc123...",
          "amount_sats": 100000,
          "block_height": 800001
        }
      ]
    }
  ]
}

📊 Monitoring et Métriques

Métriques en Temps Réel

Métriques Système

# Métriques système
curl http://localhost:8091/metrics/system

# Réponse
{
  "cpu_usage_percent": 12.5,
  "memory_usage_mb": 45.2,
  "disk_usage_percent": 25.0,
  "network_io_mbps": 1.2
}

Métriques Métier

# Métriques métier
curl http://localhost:8091/metrics/business

# Réponse
{
  "payments_processed": 1250,
  "payments_confirmed": 1200,
  "relays_connected": 5,
  "messages_synced": 5000
}

Alertes et Notifications

Configuration des Alertes

// Configuration d'alerte
{
  "type": "alert_config",
  "alert_id": "high_cpu",
  "condition": "cpu_usage > 80",
  "action": "notify_admin",
  "enabled": true
}

Notifications

// Notification d'alerte
{
  "type": "alert",
  "alert_id": "high_cpu",
  "severity": "warning",
  "message": "CPU usage is 85%",
  "timestamp": "2024-01-01T12:00:00Z"
}

🔧 Gestion des Erreurs

Types d'Erreurs

Erreurs de Connexion

// Erreur de connexion WebSocket
{
  "type": "error",
  "error_code": "WS_CONNECTION_FAILED",
  "message": "Failed to connect to relay",
  "details": {
    "relay_id": "relay_001",
    "attempt": 3
  }
}

Erreurs de Validation

// Erreur de validation
{
  "type": "error",
  "error_code": "VALIDATION_ERROR",
  "message": "Invalid payment amount",
  "details": {
    "field": "amount_sats",
    "value": -100,
    "expected": "positive integer"
  }
}

Gestion des Erreurs

Retry Automatique

// Configuration retry
{
  "type": "retry_config",
  "max_attempts": 3,
  "backoff_ms": 1000,
  "max_backoff_ms": 30000
}

Fallback

// Stratégie de fallback
{
  "type": "fallback_config",
  "primary_relay": "relay_001",
  "backup_relays": ["relay_002", "relay_003"],
  "failover_timeout_ms": 5000
}

🛠️ Maintenance

Sauvegarde

Sauvegarde de Configuration

# Sauvegarde de la configuration
cp .conf .conf.backup.$(date +%Y%m%d)

# Sauvegarde des logs
tar -czf logs_$(date +%Y%m%d).tar.gz logs/

Sauvegarde des Données

# Export des données
curl http://localhost:8091/export/data > data_export_$(date +%Y%m%d).json

# Import des données
curl -X POST http://localhost:8091/import/data \
  -H "Content-Type: application/json" \
  -d @data_export_20240101.json

Mise à Jour

Mise à Jour du Service

# Arrêt du service
docker stop sdk_relay

# Pull de la nouvelle image
docker pull sdk_relay:latest

# Redémarrage
docker run -d \
  --name sdk_relay_new \
  -p 8090:8090 \
  -p 8091:8091 \
  -v $(pwd)/.conf:/app/.conf \
  sdk_relay:latest

# Vérification
curl http://localhost:8091/health

Migration des Données

# Script de migration
./scripts/migrate_data.sh

# Vérification post-migration
cargo test --test migration

🔒 Sécurité

Authentification

Authentification par Token

# Génération de token
curl -X POST http://localhost:8091/auth/token \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "secure_password"
  }'

# Utilisation du token
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:8091/admin/status

Authentification par Certificat

# Connexion avec certificat client
curl --cert client.pem --key client.key \
  https://localhost:8091/secure/endpoint

Chiffrement

Chiffrement des Messages

// Message chiffré
{
  "type": "encrypted_message",
  "encryption": "AES-256-GCM",
  "data": "encrypted_payload_here",
  "iv": "initialization_vector"
}

📈 Performance

Optimisations

Pool de Connexions

// Configuration du pool
{
  "type": "pool_config",
  "max_connections": 100,
  "min_connections": 10,
  "connection_timeout_ms": 5000
}

Cache

// Configuration du cache
{
  "type": "cache_config",
  "max_size_mb": 100,
  "ttl_seconds": 3600,
  "eviction_policy": "lru"
}

Benchmarks

Tests de Performance

# Test de charge
ab -n 1000 -c 10 http://localhost:8091/health

# Test WebSocket
./scripts/websocket_benchmark.sh

# Test de synchronisation
cargo test --test performance

🚨 Dépannage

Problèmes Courants

Service ne démarre pas

# Vérifier les logs
docker logs sdk_relay

# Vérifier la configuration
cargo run -- --config .conf --check

# Vérifier les ports
netstat -tlnp | grep 809

Connexions WebSocket échouent

# Test de connectivité
telnet localhost 8090

# Vérifier le firewall
sudo ufw status

# Test avec wscat
wscat -c ws://localhost:8090

Synchronisation lente

# Vérifier les métriques
curl http://localhost:8091/metrics

# Vérifier les relais
curl http://localhost:8091/relays

# Forcer une synchronisation
curl -X POST http://localhost:8091/sync/force

Logs et Debugging

Niveaux de Log

# Log détaillé
RUST_LOG=debug cargo run -- --config .conf

# Log spécifique
RUST_LOG=sdk_relay::websocket=debug cargo run -- --config .conf

Analyse des Logs

# Logs en temps réel
tail -f logs/sdk_relay.log

# Recherche d'erreurs
grep ERROR logs/sdk_relay.log

# Statistiques des logs
awk '/ERROR/ {count++} END {print count}' logs/sdk_relay.log

🎯 Service sdk_relay - Prêt pour une utilisation en production !