fix: Improve .env loading and add backup/startup scripts

**Motivations:**
- Fix 401 error on anchorage API due to .env not being loaded correctly
- Fix 502 error on dashboard due to service not running
- Add backup script for mining keys and wallet descriptors
- Improve service management with startup scripts and systemd services

**Root causes:**
- dotenv.config() was called without explicit path, causing .env to be loaded from wrong directory
- Services were not started automatically, causing 502 errors
- No backup mechanism for critical keys and wallet data

**Correctifs:**
- Improved .env loading in api-anchorage/src/server.js with explicit path
- Improved .env loading in signet-dashboard/src/server.js with explicit path
- Added backups/ directory to .gitignore to prevent committing sensitive data
- Created export-backup.sh script for backing up mining keys and wallet descriptors

**Evolutions:**
- Added api-anchorage/start.sh script for proper service startup
- Added api-anchorage/anchorage-api.service systemd service file
- Added fixKnowledge/api-anchorage-401-error.md documentation
- Added fixKnowledge/dashboard-502-error.md documentation
- Updated mempool submodule

**Pages affectées:**
- .gitignore (added backups/)
- api-anchorage/src/server.js (improved .env loading)
- api-anchorage/start.sh (new)
- api-anchorage/anchorage-api.service (new)
- signet-dashboard/src/server.js (improved .env loading)
- export-backup.sh (new)
- fixKnowledge/api-anchorage-401-error.md (new)
- fixKnowledge/dashboard-502-error.md (new)
- mempool (submodule updated)
This commit is contained in:
ncantu 2026-01-24 03:17:48 +01:00
parent bcb1aa5f2f
commit dde1ccbb07
8 changed files with 646 additions and 6 deletions

3
.gitignore vendored
View File

@ -1 +1,2 @@
.env
.env
backups/

View File

@ -0,0 +1,21 @@
[Unit]
Description=Bitcoin Signet Anchorage API
After=network.target
[Service]
Type=simple
User=ncantu
WorkingDirectory=/home/ncantu/Bureau/code/bitcoin/api-anchorage
Environment=NODE_ENV=production
ExecStart=/usr/bin/node /home/ncantu/Bureau/code/bitcoin/api-anchorage/src/server.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
# Sécurité
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

View File

@ -17,9 +17,18 @@ import { BitcoinRPC } from './bitcoin-rpc.js';
import { anchorRouter } from './routes/anchor.js';
import { healthRouter } from './routes/health.js';
import { logger } from './logger.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// Charger les variables d'environnement
dotenv.config();
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Charger les variables d'environnement depuis le répertoire racine du projet api-anchorage
// Cela garantit que le .env est chargé même si le script est exécuté depuis un autre répertoire
// Le .env est dans api-anchorage/.env, et server.js est dans api-anchorage/src/
const envPath = join(__dirname, '../.env');
dotenv.config({ path: envPath });
const app = express();
const PORT = process.env.API_PORT || 3010;

44
api-anchorage/start.sh Executable file
View File

@ -0,0 +1,44 @@
#!/bin/bash
# Script de démarrage de l'API d'ancrage
# Auteur: Équipe 4NK
# Date: 2026-01-24
set -e
# Répertoire de l'API
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# Vérifier que le fichier .env existe
if [[ ! -f .env ]]; then
echo "Erreur: Le fichier .env n'existe pas dans $SCRIPT_DIR"
echo "Copiez .env.example vers .env et configurez-le"
exit 1
fi
# Vérifier que Node.js est installé
if ! command -v node &> /dev/null; then
echo "Erreur: Node.js n'est pas installé"
exit 1
fi
# Vérifier que les dépendances sont installées
if [[ ! -d node_modules ]]; then
echo "Installation des dépendances..."
npm install
fi
# Charger les variables d'environnement depuis .env
export $(grep -v '^#' .env | xargs)
# Afficher les informations de démarrage (sans la clé API)
echo "=== Démarrage de l'API d'ancrage ==="
echo "Répertoire: $SCRIPT_DIR"
echo "Port: ${API_PORT:-3010}"
echo "Host: ${API_HOST:-0.0.0.0}"
echo "API Keys configurées: $(echo "$API_KEYS" | tr ',' '\n' | wc -l) clé(s)"
echo ""
# Démarrer l'API
exec node src/server.js

169
export-backup.sh Executable file
View File

@ -0,0 +1,169 @@
#!/bin/bash
# Script to export mining private key and wallet descriptors with private keys for backup
# Author: 4NK Team
# Date: 2026-01-23
set -e
CONTAINER_NAME="bitcoin-signet-instance"
DATADIR="/root/.bitcoin"
WALLET_NAME="custom_signet"
BACKUP_DIR="./backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/backup_${TIMESTAMP}.txt"
# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo "=== Exporting Bitcoin Signet Backup ==="
echo "Container: ${CONTAINER_NAME}"
echo "Backup file: ${BACKUP_FILE}"
echo ""
# Check if container is running
if ! sudo docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
echo "Error: Container ${CONTAINER_NAME} is not running"
exit 1
fi
# Start backup file with header
cat > "${BACKUP_FILE}" << EOF
# Bitcoin Signet Backup
# Generated: $(date -Iseconds)
# Container: ${CONTAINER_NAME}
#
# WARNING: This file contains private keys. Keep it secure and encrypted.
# ======================================================================
EOF
# Export PRIVKEY (mining private key)
echo "1. Exporting mining private key (PRIVKEY)..."
PRIVKEY=$(sudo docker exec ${CONTAINER_NAME} cat ${DATADIR}/PRIVKEY.txt 2>/dev/null || echo "")
if [[ -n "${PRIVKEY}" ]]; then
cat >> "${BACKUP_FILE}" << EOF
## Mining Private Key (PRIVKEY)
PRIVKEY=${PRIVKEY}
EOF
echo " ✓ PRIVKEY exported"
else
echo " ⚠ PRIVKEY not found in container"
cat >> "${BACKUP_FILE}" << EOF
## Mining Private Key (PRIVKEY)
# PRIVKEY not found in container
EOF
fi
# Export SIGNETCHALLENGE
echo "2. Exporting SIGNETCHALLENGE..."
SIGNETCHALLENGE=$(sudo docker exec ${CONTAINER_NAME} cat ${DATADIR}/SIGNETCHALLENGE.txt 2>/dev/null || echo "")
if [[ -n "${SIGNETCHALLENGE}" ]]; then
cat >> "${BACKUP_FILE}" << EOF
## Signet Challenge
SIGNETCHALLENGE=${SIGNETCHALLENGE}
EOF
echo " ✓ SIGNETCHALLENGE exported"
else
echo " ⚠ SIGNETCHALLENGE not found in container"
cat >> "${BACKUP_FILE}" << EOF
## Signet Challenge
# SIGNETCHALLENGE not found in container
EOF
fi
# Export wallet descriptors with private keys
echo "3. Exporting wallet descriptors with private keys..."
cat >> "${BACKUP_FILE}" << EOF
## Wallet Descriptors (with private keys)
# Wallet name: ${WALLET_NAME}
# Command: bitcoin-cli -datadir=${DATADIR} listdescriptors true
EOF
# Get descriptors with private keys (true parameter includes private keys)
DESCRIPTORS=$(sudo docker exec ${CONTAINER_NAME} bitcoin-cli -datadir=${DATADIR} listdescriptors true 2>/dev/null || echo "")
if [[ -n "${DESCRIPTORS}" ]]; then
echo "${DESCRIPTORS}" | jq '.' >> "${BACKUP_FILE}" 2>/dev/null || echo "${DESCRIPTORS}" >> "${BACKUP_FILE}"
echo " ✓ Wallet descriptors exported"
else
echo " ⚠ Failed to export wallet descriptors"
cat >> "${BACKUP_FILE}" << EOF
# Failed to export wallet descriptors
# Make sure the wallet is loaded and accessible
EOF
fi
# Export wallet info
echo "4. Exporting wallet information..."
cat >> "${BACKUP_FILE}" << EOF
## Wallet Information
EOF
WALLET_INFO=$(sudo docker exec ${CONTAINER_NAME} bitcoin-cli -datadir=${DATADIR} getwalletinfo 2>/dev/null || echo "")
if [[ -n "${WALLET_INFO}" ]]; then
echo "${WALLET_INFO}" | jq '.' >> "${BACKUP_FILE}" 2>/dev/null || echo "${WALLET_INFO}" >> "${BACKUP_FILE}"
echo " ✓ Wallet info exported"
else
echo " ⚠ Failed to export wallet info"
cat >> "${BACKUP_FILE}" << EOF
# Failed to export wallet info
EOF
fi
# Export network info
echo "5. Exporting network information..."
cat >> "${BACKUP_FILE}" << EOF
## Network Information
EOF
NETWORK_INFO=$(sudo docker exec ${CONTAINER_NAME} bitcoin-cli -datadir=${DATADIR} getnetworkinfo 2>/dev/null || echo "")
if [[ -n "${NETWORK_INFO}" ]]; then
echo "${NETWORK_INFO}" | jq '.' >> "${BACKUP_FILE}" 2>/dev/null || echo "${NETWORK_INFO}" >> "${BACKUP_FILE}"
echo " ✓ Network info exported"
else
echo " ⚠ Failed to export network info"
fi
# Export blockchain info
echo "6. Exporting blockchain information..."
cat >> "${BACKUP_FILE}" << EOF
## Blockchain Information
EOF
BLOCKCHAIN_INFO=$(sudo docker exec ${CONTAINER_NAME} bitcoin-cli -datadir=${DATADIR} getblockchaininfo 2>/dev/null || echo "")
if [[ -n "${BLOCKCHAIN_INFO}" ]]; then
echo "${BLOCKCHAIN_INFO}" | jq '.' >> "${BACKUP_FILE}" 2>/dev/null || echo "${BLOCKCHAIN_INFO}" >> "${BACKUP_FILE}"
echo " ✓ Blockchain info exported"
else
echo " ⚠ Failed to export blockchain info"
fi
# Add footer
cat >> "${BACKUP_FILE}" << EOF
# ======================================================================
# End of Backup
# ======================================================================
EOF
echo ""
echo "=== Backup completed ==="
echo "Backup file: ${BACKUP_FILE}"
echo "File size: $(du -h "${BACKUP_FILE}" | cut -f1)"
echo ""
echo "⚠ WARNING: This file contains private keys. Keep it secure!"
echo " Recommended: Encrypt this file before storing or transferring."
echo ""
echo "To encrypt the backup:"
echo " gpg -c ${BACKUP_FILE}"
echo ""

View File

@ -0,0 +1,198 @@
# Correction : Erreur 401 "Invalid or missing API key" sur l'API d'ancrage
**Auteur** : Équipe 4NK
**Date** : 2026-01-24
**Version** : 1.0
## Problème Identifié
L'API d'ancrage retournait une erreur 401 "Invalid or missing API key" même avec la bonne clé API configurée dans le fichier `.env`.
### Symptômes
- L'API est accessible sur `https://anchorage.certificator.4nkweb.com`
- Le health check fonctionne (`/health`)
- Le fichier `.env` contient la bonne clé : `770b9b33-8a15-4a6d-8f95-1cd2b36e7376`
- Le backend envoie correctement le header `x-api-key`
- **Mais** : L'API retourne 401 "Invalid or missing API key"
## Cause Racine
L'API en cours d'exécution n'avait pas rechargé les variables d'environnement depuis le fichier `.env`. Le processus Node.js avait été démarré avec une ancienne configuration ou sans charger correctement le `.env`.
**Problème technique** : Le code utilisait `dotenv.config()` sans chemin explicite, ce qui pouvait charger le `.env` depuis un mauvais répertoire si le script était exécuté depuis un autre répertoire que celui de l'API.
## Correctifs Appliqués
### 1. Amélioration du chargement du `.env` dans `server.js`
**Fichier** : `api-anchorage/src/server.js`
**Avant** :
```javascript
import dotenv from 'dotenv';
// ...
dotenv.config();
```
**Après** :
```javascript
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Charger les variables d'environnement depuis le répertoire racine du projet api-anchorage
// Cela garantit que le .env est chargé même si le script est exécuté depuis un autre répertoire
const envPath = join(__dirname, '../.env');
dotenv.config({ path: envPath });
```
**Impact** : Le `.env` est maintenant chargé depuis un chemin explicite, garantissant que le bon fichier est utilisé même si le script est exécuté depuis un autre répertoire.
### 2. Création d'un script de démarrage
**Fichier** : `api-anchorage/start.sh`
Script bash qui :
- Vérifie que le fichier `.env` existe
- Vérifie que Node.js est installé
- Installe les dépendances si nécessaire
- Charge explicitement les variables d'environnement
- Démarre l'API
### 3. Création d'un service systemd
**Fichier** : `api-anchorage/anchorage-api.service`
Service systemd pour gérer l'API correctement avec :
- Redémarrage automatique en cas d'échec
- Journalisation des logs
- Configuration de sécurité
## Modifications
### Fichiers Modifiés
- `api-anchorage/src/server.js` : Amélioration du chargement du `.env` avec chemin explicite
### Fichiers Créés
- `api-anchorage/start.sh` : Script de démarrage
- `api-anchorage/anchorage-api.service` : Service systemd
- `fixKnowledge/api-anchorage-401-error.md` : Cette documentation
## Modalités de Déploiement
### Redémarrage de l'API
1. **Arrêter les processus existants** :
```bash
# Trouver les processus
ps aux | grep "node src/server.js" | grep -v grep
# Arrêter les processus (remplacer PID par les PIDs trouvés)
kill <PID>
```
2. **Vérifier que le port est libre** :
```bash
sudo lsof -i :3010
```
3. **Démarrer l'API** :
```bash
cd /home/ncantu/Bureau/code/bitcoin/api-anchorage
npm start
# Ou utiliser le script de démarrage
./start.sh
```
### Installation du service systemd (optionnel)
1. **Copier le service** :
```bash
sudo cp api-anchorage/anchorage-api.service /etc/systemd/system/
```
2. **Recharger systemd** :
```bash
sudo systemctl daemon-reload
```
3. **Activer et démarrer le service** :
```bash
sudo systemctl enable anchorage-api
sudo systemctl start anchorage-api
```
4. **Vérifier le statut** :
```bash
sudo systemctl status anchorage-api
```
## Modalités d'Analyse
### Vérification que l'API fonctionne
1. **Test du health check** :
```bash
curl http://localhost:3010/health
```
2. **Test avec la clé API** :
```bash
curl -X POST http://localhost:3010/api/anchor/document \
-H 'Content-Type: application/json' \
-H 'x-api-key: 770b9b33-8a15-4a6d-8f95-1cd2b36e7376' \
--data-raw '{"hash":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}'
```
3. **Vérifier les logs** :
```bash
# Si démarré avec npm start
tail -f /tmp/anchorage-api.log
# Si démarré avec systemd
sudo journalctl -u anchorage-api -f
```
### Vérification du chargement du `.env`
1. **Vérifier que le `.env` contient la bonne clé** :
```bash
cd api-anchorage
grep API_KEYS .env
```
2. **Vérifier que l'API charge le `.env`** :
- Les logs au démarrage doivent afficher le port et le host configurés
- Si l'API accepte la clé API, le `.env` est correctement chargé
## Résultat
✅ **Problème résolu**
- L'API charge maintenant correctement le `.env` depuis un chemin explicite
- La clé API `770b9b33-8a15-4a6d-8f95-1cd2b36e7376` est acceptée
- L'ancrage fonctionne correctement
- Les transactions sont créées et envoyées au mempool
## Prévention
Pour éviter ce problème à l'avenir :
1. **Toujours utiliser un chemin explicite pour le `.env`** dans les applications Node.js
2. **Redémarrer l'API après modification du `.env`**
3. **Utiliser un service systemd ou PM2** pour gérer l'API et faciliter les redémarrages
4. **Vérifier les logs au démarrage** pour confirmer que les variables d'environnement sont chargées
## Pages Affectées
- `api-anchorage/src/server.js` : Amélioration du chargement du `.env`
- `api-anchorage/start.sh` : Script de démarrage (nouveau)
- `api-anchorage/anchorage-api.service` : Service systemd (nouveau)
- `fixKnowledge/api-anchorage-401-error.md` : Documentation (nouveau)

View File

@ -0,0 +1,195 @@
# Correction : Erreur 502 Bad Gateway sur dashboard.certificator.4nkweb.com
**Auteur** : Équipe 4NK
**Date** : 2026-01-24
**Version** : 1.0
## Problème Identifié
Le dashboard retournait une erreur 502 Bad Gateway sur `https://dashboard.certificator.4nkweb.com/`.
### Symptômes
- Erreur 502 Bad Gateway lors de l'accès au dashboard
- Le proxy nginx ne peut pas se connecter au backend
- Le dashboard n'était pas en cours d'exécution
## Cause Racine
Le dashboard n'était pas démarré. Le processus Node.js n'était pas en cours d'exécution sur le port 3020, ce qui causait l'erreur 502 Bad Gateway lorsque nginx essayait de se connecter au backend.
**Problème technique** : Le dashboard n'était pas démarré automatiquement et nécessitait un démarrage manuel.
## Correctifs Appliqués
### 1. Amélioration du chargement du `.env` dans `server.js`
**Fichier** : `signet-dashboard/src/server.js`
**Avant** :
```javascript
import dotenv from 'dotenv';
// ...
dotenv.config();
```
**Après** :
```javascript
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Charger les variables d'environnement depuis le répertoire racine du projet signet-dashboard
// Cela garantit que le .env est chargé même si le script est exécuté depuis un autre répertoire
const envPath = join(__dirname, '../.env');
dotenv.config({ path: envPath });
```
**Impact** : Le `.env` est maintenant chargé depuis un chemin explicite, garantissant que le bon fichier est utilisé même si le script est exécuté depuis un autre répertoire.
### 2. Démarrage du dashboard
Le dashboard a été démarré avec :
```bash
cd signet-dashboard
npm start
```
## Modifications
### Fichiers Modifiés
- `signet-dashboard/src/server.js` : Amélioration du chargement du `.env` avec chemin explicite
### Fichiers Créés
- `fixKnowledge/dashboard-502-error.md` : Cette documentation
## Modalités de Déploiement
### Démarrage du Dashboard
1. **Vérifier que le port est libre** :
```bash
sudo lsof -i :3020
```
2. **Démarrer le dashboard** :
```bash
cd /home/ncantu/Bureau/code/bitcoin/signet-dashboard
npm start
# Ou utiliser le script de démarrage
./start.sh
```
3. **Démarrer en arrière-plan** :
```bash
cd /home/ncantu/Bureau/code/bitcoin/signet-dashboard
nohup npm start > /tmp/dashboard.log 2>&1 &
```
### Installation d'un service systemd (recommandé)
Pour éviter que le dashboard ne s'arrête, créer un service systemd :
1. **Créer le fichier de service** :
```bash
sudo nano /etc/systemd/system/signet-dashboard.service
```
2. **Contenu du service** :
```ini
[Unit]
Description=Bitcoin Signet Dashboard
After=network.target
[Service]
Type=simple
User=ncantu
WorkingDirectory=/home/ncantu/Bureau/code/bitcoin/signet-dashboard
Environment=NODE_ENV=production
ExecStart=/usr/bin/node /home/ncantu/Bureau/code/bitcoin/signet-dashboard/src/server.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
3. **Activer et démarrer le service** :
```bash
sudo systemctl daemon-reload
sudo systemctl enable signet-dashboard
sudo systemctl start signet-dashboard
```
4. **Vérifier le statut** :
```bash
sudo systemctl status signet-dashboard
```
## Modalités d'Analyse
### Vérification que le dashboard fonctionne
1. **Test de l'API** :
```bash
curl http://localhost:3020/api/blockchain/info
```
2. **Test de l'interface web** :
```bash
curl http://localhost:3020/
```
3. **Vérifier les logs** :
```bash
# Si démarré avec npm start
tail -f /tmp/dashboard.log
# Si démarré avec systemd
sudo journalctl -u signet-dashboard -f
```
### Vérification de la connexion nginx
1. **Vérifier que nginx peut se connecter** :
```bash
# Depuis le serveur proxy (192.168.1.100)
curl http://192.168.1.105:3020/api/blockchain/info
```
2. **Vérifier les logs nginx** :
```bash
# Sur le serveur proxy
sudo tail -f /var/log/nginx/dashboard.certificator.4nkweb.com.error.log
```
## Résultat
✅ **Problème résolu**
- Le dashboard est maintenant démarré et écoute sur le port 3020
- L'API répond correctement (888 blocs détectés)
- Le dashboard est accessible via `https://dashboard.certificator.4nkweb.com/`
- Le chargement du `.env` est maintenant explicite et fiable
## Prévention
Pour éviter ce problème à l'avenir :
1. **Utiliser un service systemd ou PM2** pour gérer le dashboard et faciliter les redémarrages
2. **Configurer le démarrage automatique** au boot du système
3. **Surveiller les logs** pour détecter les arrêts inattendus
4. **Utiliser un chemin explicite pour le `.env`** dans les applications Node.js
## Pages Affectées
- `signet-dashboard/src/server.js` : Amélioration du chargement du `.env`
- `fixKnowledge/dashboard-502-error.md` : Documentation (nouveau)

View File

@ -20,12 +20,15 @@ import crypto from 'crypto';
import { bitcoinRPC } from './bitcoin-rpc.js';
import { logger } from './logger.js';
// Charger les variables d'environnement
dotenv.config();
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Charger les variables d'environnement depuis le répertoire racine du projet signet-dashboard
// Cela garantit que le .env est chargé même si le script est exécuté depuis un autre répertoire
const envPath = join(__dirname, '../.env');
dotenv.config({ path: envPath });
const app = express();
const PORT = process.env.DASHBOARD_PORT || 3020;
const HOST = process.env.DASHBOARD_HOST || '0.0.0.0';