764 lines
14 KiB
Markdown

# Référence API - <PROJECT_NAME>
Ce document est un modèle. Il doit être adapté par chaque projet dérivé. Il documente les APIs de l'infrastructure (RPC, HTTP, WebSocket) et doit rester cohérent avec la version publiée (`TEMPLATE_VERSION`) et le `CHANGELOG.md`.
## Vue d'Ensemble des APIs
L'infrastructure <PROJECT_NAME> expose plusieurs interfaces pour différents types d'interactions :
- **Bitcoin Core RPC** : Interface JSON-RPC pour Bitcoin
- **Blindbit HTTP** : API REST pour les paiements silencieux
- **SDK Relay WebSocket** : Interface temps réel pour les clients
- **SDK Relay HTTP** : API REST pour les opérations de gestion
## 1. API Bitcoin Core RPC
### Informations Générales
- **Protocole :** JSON-RPC
- **Port :** 18443
- **Authentification :** Cookie ou credentials
- **Réseau :** Signet
- **Base URL :** `http://localhost:18443`
### Authentification
#### Méthode Cookie (Recommandée)
```bash
# Le cookie est automatiquement utilisé par Bitcoin Core
curl -X POST http://localhost:18443 \
-H "Content-Type: application/json" \
--data '{"jsonrpc": "1.0", "id": "test", "method": "getblockchaininfo", "params": []}'
```
#### Méthode Credentials
```bash
curl -X POST http://localhost:18443 \
-H "Content-Type: application/json" \
-u "username:password" \
--data '{"jsonrpc": "1.0", "id": "test", "method": "getblockchaininfo", "params": []}'
```
### Endpoints Principaux
#### getblockchaininfo
Récupère les informations sur la blockchain.
**Requête :**
```json
{
"jsonrpc": "1.0",
"id": "test",
"method": "getblockchaininfo",
"params": []
}
```
**Réponse :**
```json
{
"result": {
"chain": "signet",
"blocks": 12345,
"headers": 12345,
"bestblockhash": "0000000000000000000000000000000000000000000000000000000000000000",
"difficulty": 1.0,
"mediantime": 1234567890,
"verificationprogress": 1.0,
"initialblockdownload": false,
"chainwork": "0000000000000000000000000000000000000000000000000000000000000000",
"size_on_disk": 123456789,
"pruned": false,
"pruneheight": null,
"automatic_pruning": false,
"prune_target_size": null,
"warnings": ""
},
"error": null,
"id": "test"
}
```
#### getblock
Récupère les informations d'un bloc spécifique.
**Requête :**
```json
{
"jsonrpc": "1.0",
"id": "test",
"method": "getblock",
"params": ["blockhash", 2]
}
```
**Paramètres :**
- `blockhash` : Hash du bloc
- `verbosity` : Niveau de détail (0, 1, 2)
#### getrawtransaction
Récupère une transaction brute.
**Requête :**
```json
{
"jsonrpc": "1.0",
"id": "test",
"method": "getrawtransaction",
"params": ["txid", true]
}
```
#### sendrawtransaction
Envoie une transaction brute au réseau.
**Requête :**
```json
{
"jsonrpc": "1.0",
"id": "test",
"method": "sendrawtransaction",
"params": ["hexstring"]
}
```
#### getwalletinfo
Récupère les informations du wallet.
**Requête :**
```json
{
"jsonrpc": "1.0",
"id": "test",
"method": "getwalletinfo",
"params": []
}
```
### Gestion des Erreurs
**Erreur typique :**
```json
{
"result": null,
"error": {
"code": -32601,
"message": "Method not found"
},
"id": "test"
}
```
**Codes d'erreur courants :**
- `-32601` : Méthode non trouvée
- `-32602` : Paramètres invalides
- `-32603` : Erreur interne
- `-1` : Erreur d'authentification
## 2. API Blindbit HTTP
### Informations Générales
- **Protocole :** HTTP REST
- **Port :** 8000
- **Base URL :** `http://localhost:8000`
- **Content-Type :** `application/json`
### Endpoints
#### GET /health
Vérifie la santé du service.
**Requête :**
```bash
curl -X GET http://localhost:8000/health
```
**Réponse :**
```json
{
"status": "healthy",
"timestamp": "2024-12-19T14:30:00Z",
"version": "1.0.0"
}
```
#### POST /generate-address
Génère une adresse de paiement silencieux.
**Requête :**
```json
{
"label": "payment_001",
"amount": 0.001
}
```
**Réponse :**
```json
{
"address": "bc1p...",
"label": "payment_001",
"amount": 0.001,
"created_at": "2024-12-19T14:30:00Z"
}
```
#### GET /payments
Liste les paiements reçus.
**Requête :**
```bash
curl -X GET "http://localhost:8000/payments?limit=10&offset=0"
```
**Paramètres de requête :**
- `limit` : Nombre maximum de résultats (défaut: 10)
- `offset` : Décalage pour la pagination (défaut: 0)
**Réponse :**
```json
{
"payments": [
{
"id": "payment_001",
"address": "bc1p...",
"amount": 0.001,
"txid": "txid...",
"block_height": 12345,
"created_at": "2024-12-19T14:30:00Z"
}
],
"total": 1,
"limit": 10,
"offset": 0
}
```
#### GET /payments/{id}
Récupère les détails d'un paiement spécifique.
**Requête :**
```bash
curl -X GET http://localhost:8000/payments/payment_001
```
**Réponse :**
```json
{
"id": "payment_001",
"address": "bc1p...",
"amount": 0.001,
"txid": "txid...",
"block_height": 12345,
"confirmations": 6,
"created_at": "2024-12-19T14:30:00Z",
"status": "confirmed"
}
```
### Codes de Statut HTTP
- `200` : Succès
- `201` : Créé
- `400` : Requête invalide
- `404` : Ressource non trouvée
- `500` : Erreur serveur
## 3. API SDK Relay WebSocket
### Informations Générales
- **Protocole :** WebSocket/WSS
- **Port :** 8090
- **URL :** `ws://localhost:8090` ou `wss://localhost:8090`
- **Format :** JSON
### Connexion
```javascript
const ws = new WebSocket('ws://localhost:8090');
ws.onopen = function() {
console.log('Connexion WebSocket établie');
};
ws.onmessage = function(event) {
const message = JSON.parse(event.data);
console.log('Message reçu:', message);
};
ws.onerror = function(error) {
console.error('Erreur WebSocket:', error);
};
ws.onclose = function() {
console.log('Connexion WebSocket fermée');
};
```
### Format des Messages
Tous les messages suivent le format JSON suivant :
```json
{
"type": "message_type",
"id": "unique_message_id",
"timestamp": 1234567890,
"data": {
// Données spécifiques au type de message
}
}
```
### Types de Messages
#### Messages de Synchronisation
**StateSync :**
```json
{
"type": "StateSync",
"id": "state_001",
"timestamp": 1234567890,
"data": {
"relay_id": "relay-1",
"state": "running",
"version": "1.0.0",
"uptime": 3600
}
}
```
**HealthSync :**
```json
{
"type": "HealthSync",
"id": "health_001",
"timestamp": 1234567890,
"data": {
"relay_id": "relay-1",
"status": "healthy",
"uptime": 3600,
"cpu_usage": 15.5,
"memory_usage": 45.2
}
}
```
**MetricsSync :**
```json
{
"type": "MetricsSync",
"id": "metrics_001",
"timestamp": 1234567890,
"data": {
"relay_id": "relay-1",
"messages_sent": 1000,
"messages_received": 950,
"sync_errors": 5,
"connected_relays": 3
}
}
```
#### Messages de Transaction
**TransactionReceived :**
```json
{
"type": "TransactionReceived",
"id": "tx_001",
"timestamp": 1234567890,
"data": {
"txid": "txid...",
"amount": 0.001,
"address": "bc1p...",
"block_height": 12345,
"confirmations": 1
}
}
```
**BlockScanned :**
```json
{
"type": "BlockScanned",
"id": "block_001",
"timestamp": 1234567890,
"data": {
"block_height": 12345,
"block_hash": "hash...",
"transactions_count": 150,
"silent_payments_found": 2
}
}
```
### Commandes Client
#### Ping
```json
{
"type": "ping",
"id": "ping_001",
"timestamp": 1234567890,
"data": {}
}
```
**Réponse :**
```json
{
"type": "pong",
"id": "ping_001",
"timestamp": 1234567890,
"data": {
"relay_id": "relay-1"
}
}
```
#### GetStatus
```json
{
"type": "get_status",
"id": "status_001",
"timestamp": 1234567890,
"data": {}
}
```
**Réponse :**
```json
{
"type": "status",
"id": "status_001",
"timestamp": 1234567890,
"data": {
"relay_id": "relay-1",
"status": "running",
"uptime": 3600,
"connected_relays": 3,
"last_block_height": 12345
}
}
```
## 4. API SDK Relay HTTP
### Informations Générales
- **Protocole :** HTTP REST
- **Port :** 8091
- **Base URL :** `http://localhost:8091`
- **Content-Type :** `application/json`
### Endpoints
#### GET /health
Vérifie la santé du relais.
**Requête :**
```bash
curl -X GET http://localhost:8091/health
```
**Réponse :**
```json
{
"status": "healthy",
"relay_id": "relay-1",
"uptime": 3600,
"version": "1.0.0",
"connected_relays": 3
}
```
#### GET /status
Récupère le statut détaillé du relais.
**Requête :**
```bash
curl -X GET http://localhost:8091/status
```
**Réponse :**
```json
{
"relay_id": "relay-1",
"status": "running",
"uptime": 3600,
"version": "1.0.0",
"connected_relays": 3,
"last_block_height": 12345,
"sync_metrics": {
"messages_sent": 1000,
"messages_received": 950,
"sync_errors": 5
}
}
```
#### GET /relays
Liste les relais connectés.
**Requête :**
```bash
curl -X GET http://localhost:8091/relays
```
**Réponse :**
```json
{
"relays": [
{
"relay_id": "relay-2",
"address": "sdk_relay_2:8090",
"status": "connected",
"connected_since": 1234567890,
"last_heartbeat": 1234567890
},
{
"relay_id": "relay-3",
"address": "sdk_relay_3:8090",
"status": "connected",
"connected_since": 1234567890,
"last_heartbeat": 1234567890
}
]
}
```
#### GET /metrics
Récupère les métriques de synchronisation.
**Requête :**
```bash
curl -X GET http://localhost:8091/metrics
```
**Réponse :**
```json
{
"messages_sent": 1000,
"messages_received": 950,
"sync_errors": 5,
"last_sync_timestamp": 1234567890,
"connected_relays": 3,
"mesh_health": 0.95
}
```
#### POST /sync
Force une synchronisation manuelle.
**Requête :**
```json
{
"sync_type": "StateSync",
"target_relay": "relay-2"
}
```
**Réponse :**
```json
{
"success": true,
"message": "Synchronisation initiée",
"sync_id": "sync_001"
}
```
## 5. Gestion des Erreurs
### Erreurs WebSocket
**Erreur de connexion :**
```json
{
"type": "error",
"id": "error_001",
"timestamp": 1234567890,
"data": {
"code": "CONNECTION_ERROR",
"message": "Impossible de se connecter au relais",
"details": "Connection refused"
}
}
```
**Erreur de message :**
```json
{
"type": "error",
"id": "error_002",
"timestamp": 1234567890,
"data": {
"code": "INVALID_MESSAGE",
"message": "Format de message invalide",
"details": "Missing required field 'type'"
}
}
```
### Erreurs HTTP
**Erreur 400 :**
```json
{
"error": {
"code": "INVALID_REQUEST",
"message": "Requête invalide",
"details": "Missing required parameter 'relay_id'"
}
}
```
**Erreur 500 :**
```json
{
"error": {
"code": "INTERNAL_ERROR",
"message": "Erreur interne du serveur",
"details": "Database connection failed"
}
}
```
## 6. Exemples d'Utilisation
### Exemple Python - WebSocket
```python
import asyncio
import websockets
import json
async def connect_to_relay():
uri = "ws://localhost:8090"
async with websockets.connect(uri) as websocket:
# Envoyer un ping
ping_message = {
"type": "ping",
"id": "ping_001",
"timestamp": int(time.time()),
"data": {}
}
await websocket.send(json.dumps(ping_message))
# Écouter les messages
async for message in websocket:
data = json.loads(message)
print(f"Message reçu: {data}")
asyncio.run(connect_to_relay())
```
### Exemple JavaScript - WebSocket
```javascript
const ws = new WebSocket('ws://localhost:8090');
ws.onopen = function() {
// Envoyer un ping
const pingMessage = {
type: 'ping',
id: 'ping_001',
timestamp: Date.now(),
data: {}
};
ws.send(JSON.stringify(pingMessage));
};
ws.onmessage = function(event) {
const message = JSON.parse(event.data);
console.log('Message reçu:', message);
};
```
### Exemple cURL - Bitcoin Core RPC
```bash
# Récupérer les informations de la blockchain
curl -X POST http://localhost:18443 \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "1.0",
"id": "test",
"method": "getblockchaininfo",
"params": []
}'
# Récupérer un bloc spécifique
curl -X POST http://localhost:18443 \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "1.0",
"id": "test",
"method": "getblock",
"params": ["blockhash", 2]
}'
```
## 7. Limites et Quotas
### Bitcoin Core RPC
- **Taux limite :** 1000 requêtes/minute par défaut
- **Taille des requêtes :** 32MB maximum
- **Connexions simultanées :** 125 par défaut
### Blindbit HTTP
- **Taux limite :** 100 requêtes/minute
- **Taille des requêtes :** 10MB maximum
- **Connexions simultanées :** 50
### SDK Relay WebSocket
- **Connexions simultanées :** 1000 par relais
- **Taille des messages :** 1MB maximum
- **Heartbeat :** 30 secondes
### SDK Relay HTTP
- **Taux limite :** 200 requêtes/minute
- **Taille des requêtes :** 5MB maximum
- **Connexions simultanées :** 100
## 8. Sécurité
### Authentification
- **Bitcoin Core :** Cookie d'authentification
- **Blindbit :** À définir selon les besoins
- **SDK Relay :** Authentification WebSocket (optionnelle)
### Chiffrement
- **RPC Bitcoin :** HTTP (non chiffré en local)
- **HTTP Blindbit :** HTTP (non chiffré en local)
- **WebSocket SDK Relay :** WSS (chiffré)
### Bonnes Pratiques
- Utiliser HTTPS/WSS en production
- Implémenter l'authentification appropriée
- Valider toutes les entrées
- Limiter les taux de requêtes
- Monitorer les accès
## 9. Monitoring et Observabilité
### Métriques à Surveiller
- **Latence des APIs :** Temps de réponse
- **Taux d'erreur :** Pourcentage d'erreurs
- **Débit :** Requêtes par seconde
- **Utilisation des ressources :** CPU, mémoire, réseau
### Logs
- **Logs d'accès :** Requêtes et réponses
- **Logs d'erreur :** Erreurs et exceptions
- **Logs de performance :** Métriques de performance
### Alertes
- **Erreurs 5xx :** Erreurs serveur
- **Latence élevée :** Temps de réponse > 1s
- **Taux d'erreur élevé :** > 5%
- **Services indisponibles :** Health checks en échec