High-performance blockchain-powered REST API for NOCIQ - Network Operations Center Intelligence & Quality with Stellar network integration
NOCIQ Backend is the core API service powering the NOCIQ platform with Stellar blockchain integration. Built with FastAPI, it provides robust endpoints for managing network outages, performing analytics, and automating SLA-based payments through Soroban smart contracts on the Stellar network.
π Stellar Features: Automated penalty/reward calculations, instant cross-border payments, smart contract execution, and immutable audit trails.
Frontend Repository: noc-iq-fe
Smart Contracts: Soroban SLA Calculator
API Documentation: Available at /docs when running
- Fast & Async: Built on FastAPI with async/await support
- Auto-generated Docs: Interactive Swagger UI and ReDoc
- Type Safety: Pydantic models for request/response validation
- CORS Support: Configured for cross-origin requests
- Rate Limiting: Protect against abuse
- Smart Contract Integration: Soroban-powered SLA calculations
- Automated Payments: Instant penalty/reward processing via Stellar
- Wallet Management: Create and manage Stellar wallets for users/organizations
- Transaction Monitoring: Real-time payment status tracking
- Multi-Asset Support: USDC (payments), NOCIQ tokens (rewards), XLM (fees)
- Immutable Audit Trails: Store RCA hashes on-chain
- CRUD operations for network outages
- Advanced filtering and search
- Bulk import/export (CSV, JSON)
- Automated report generation
- NEW: Real-time SLA status calculation
- NEW: Automatic payment trigger on outage resolution
- Structured RCA tracking
- Categorization and tagging
- Historical analysis
- NEW: Blockchain-backed RCA hash storage
- Pattern recognition
- MTTR (Mean Time To Repair) calculations
- Site-level performance metrics
- NEW: SLA compliance reporting
- NEW: Payment analytics and forecasting
- Trend analysis
- Custom report generation
- Firebase Authentication integration
- JWT token validation
- Role-based access control (RBAC)
- NEW: Stellar wallet binding per user
- API rate limiting
- Secure key management for blockchain operations
| Category | Technologies |
|---|---|
| Framework | FastAPI 0.109+ |
| Language | Python 3.9+ |
| Database | Google Firestore (NoSQL) |
| Authentication | Firebase Admin SDK |
| Blockchain | β Stellar SDK (Python), Soroban Client |
| Data Processing | Pandas, NumPy |
| Visualization | Matplotlib, Seaborn, Plotly |
| Mapping | Folium |
| Validation | Pydantic |
| ASGI Server | Uvicorn |
| Testing | Pytest, pytest-asyncio |
| Documentation | Swagger UI, ReDoc |
- Python: 3.9 or higher (Download)
- pip: Python package installer
- Git: For version control
- Firebase Project: For Firestore and Authentication
- Stellar Account: For blockchain operations (Create testnet account)
- Virtual Environment: Recommended (venv or conda)
-
Clone the repository
git clone https://github.com/OpSoll/noc-iq-be.git cd noc-iq-be -
Create a virtual environment
# Using venv python -m venv venv # Activate virtual environment # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env
Edit
.envwith your configuration:# Firebase Configuration FIREBASE_PROJECT_ID=your_project_id FIREBASE_PRIVATE_KEY_ID=your_private_key_id FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" FIREBASE_CLIENT_EMAIL=your_service_account@project.iam.gserviceaccount.com FIREBASE_CLIENT_ID=your_client_id # Application Settings APP_ENV=development DEBUG=True HOST=0.0.0.0 PORT=8000 # CORS Settings ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000 # API Configuration API_V1_PREFIX=/api/v1 PROJECT_NAME=NOCIQ API # Rate Limiting RATE_LIMIT_PER_MINUTE=60 # Stellar Configuration π STELLAR_NETWORK=testnet STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org STELLAR_SOROBAN_RPC_URL=https://soroban-testnet.stellar.org # Stellar Wallet Keys π STELLAR_POOL_SECRET_KEY=S... # Pool wallet secret (keep secure!) STELLAR_POOL_PUBLIC_KEY=G... # Pool wallet public key # Smart Contract Addresses π SLA_CONTRACT_ID=C... # Deployed SLA calculator contract ID USDC_TOKEN_ADDRESS=C... # USDC token contract address NOCIQ_TOKEN_ADDRESS=C... # NOCIQ token contract address # Payment Settings π AUTO_PAYMENT_ENABLED=true MAX_AUTO_PAYMENT_AMOUNT=10000 # Max auto-payment in USDC PAYMENT_APPROVAL_THRESHOLD=5000 # Require approval above this
-
Initialize the database (if required)
python scripts/init_db.py
-
Deploy Soroban contracts (first time setup)
# Navigate to contracts directory cd contracts # Build contracts cargo build --target wasm32-unknown-unknown --release # Deploy to testnet soroban contract deploy \ --wasm target/wasm32-unknown-unknown/release/sla_calculator.wasm \ --network testnet # Copy the contract ID to your .env file
-
Run the development server
uvicorn main:app --reload --host 0.0.0.0 --port 8000
The API will be available at:
- API:
http://localhost:8000 - Interactive Docs:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
- API:
# Check API health
curl http://localhost:8000/health
# Expected response:
# {"status": "healthy", "version": "1.0.0", "stellar_connected": true}
# Test Stellar connection π
curl http://localhost:8000/api/v1/stellar/status
# Expected response:
# {
# "network": "testnet",
# "horizon_url": "https://horizon-testnet.stellar.org",
# "pool_address": "G...",
# "pool_balance_xlm": 10000.0,
# "pool_balance_usdc": 50000.0
# }noc-iq-be/
βββ app/
β βββ api/ # API route handlers
β β βββ v1/ # API version 1
β β β βββ endpoints/
β β β β βββ outages.py
β β β β βββ rca.py
β β β β βββ analytics.py
β β β β βββ reports.py
β β β β βββ auth.py
β β β β βββ stellar_payments.py # π Stellar payments
β β β β βββ wallets.py # π Wallet management
β β β β βββ sla.py # π SLA management
β β β βββ router.py
β β βββ deps.py # Dependencies (auth, db)
β βββ core/ # Core application logic
β β βββ config.py # Configuration settings
β β βββ security.py # Security utilities
β β βββ exceptions.py
β βββ models/ # Pydantic models
β β βββ outage.py
β β βββ rca.py
β β βββ user.py
β β βββ response.py
β β βββ stellar.py # π Stellar models
β β βββ payment.py # π Payment models
β βββ services/ # Business logic
β β βββ outage_service.py
β β βββ rca_service.py
β β βββ analytics_service.py
β β βββ report_service.py
β β βββ stellar/ # π Stellar services
β β β βββ stellar_service.py
β β β βββ payment_service.py
β β β βββ wallet_service.py
β β β βββ soroban_service.py
β β β βββ token_service.py
β β βββ sla/ # π SLA services
β β βββ sla_calculator.py
β β βββ sla_monitor.py
β β βββ penalty_reward_engine.py
β βββ db/ # Database utilities
β β βββ firestore.py
β β βββ repositories/
β βββ utils/ # Utility functions
β β βββ date_utils.py
β β βββ export_utils.py
β β βββ validation.py
β β βββ stellar_utils.py # π Stellar helpers
β βββ middleware/ # Custom middleware
β βββ auth.py
β βββ cors.py
β βββ rate_limit.py
βββ config/ # Configuration files
β βββ firebase-credentials.json
βββ contracts/ # π Soroban smart contracts
β βββ sla_calculator/
β βββ payment_escrow/
β βββ multi_party_settlement/
βββ tests/ # Test suite
β βββ unit/
β βββ integration/
β βββ stellar/ # π Stellar integration tests
β βββ conftest.py
βββ scripts/ # Utility scripts
β βββ init_db.py
β βββ seed_data.py
β βββ deploy_contracts.sh # π Contract deployment
βββ .env.example # Environment variables template
βββ .gitignore
βββ main.py # Application entry point
βββ requirements.txt # Python dependencies
βββ README.md
POST /api/v1/auth/login- User loginPOST /api/v1/auth/register- User registrationPOST /api/v1/auth/refresh- Refresh access tokenPOST /api/v1/auth/logout- User logout
GET /api/v1/outages- List all outages (with filters)GET /api/v1/outages/{id}- Get outage by IDPOST /api/v1/outages- Create new outagePUT /api/v1/outages/{id}- Update outageDELETE /api/v1/outages/{id}- Delete outagePOST /api/v1/outages/bulk-import- Import multiple outagesGET /api/v1/outages/export- Export outages (CSV/JSON)
GET /api/v1/sla/status/{outage_id}- Get SLA statusPOST /api/v1/sla/calculate- Calculate SLA for resolved outagePOST /api/v1/sla/execute-payment- Execute SLA-based paymentGET /api/v1/sla/configs- Get SLA configurationsPUT /api/v1/sla/configs- Update SLA configuration (admin)
POST /api/v1/payments/process-sla- Process SLA paymentGET /api/v1/payments/history- Get payment historyGET /api/v1/payments/{tx_hash}- Get payment detailsPOST /api/v1/payments/manual- Manual payment (admin)GET /api/v1/payments/pending- Get pending payments
POST /api/v1/wallets/create- Create Stellar walletGET /api/v1/wallets/{user_id}- Get wallet detailsGET /api/v1/wallets/{address}/balance- Get wallet balancePOST /api/v1/wallets/{address}/fund- Fund wallet (testnet)
POST /api/v1/contracts/invoke- Invoke Soroban contractGET /api/v1/contracts/sla/result/{outage_id}- Get contract resultGET /api/v1/stellar/status- Get Stellar network status
GET /api/v1/rca- List all RCA recordsGET /api/v1/rca/{id}- Get RCA by IDPOST /api/v1/rca- Create RCA recordPUT /api/v1/rca/{id}- Update RCA recordDELETE /api/v1/rca/{id}- Delete RCA recordPOST /api/v1/rca/{id}/store-hash- π Store RCA hash on blockchain
GET /api/v1/analytics/mttr- Calculate MTTR metricsGET /api/v1/analytics/trends- Get outage trendsGET /api/v1/analytics/site-performance- Site-level metricsGET /api/v1/analytics/heatmap- Generate heatmap dataGET /api/v1/analytics/dashboard- Dashboard statisticsGET /api/v1/analytics/payments- π Payment analytics
POST /api/v1/reports/generate- Generate custom reportGET /api/v1/reports/{id}- Download reportGET /api/v1/reports/whatsapp/{id}- Get WhatsApp-formatted report
GET /health- Health checkGET /- API information
Full API documentation available at /docs when the server is running.
# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/unit/test_outage_service.py
# Run Stellar integration tests π
pytest tests/stellar/
# Run with verbose output
pytest -v
# Run only integration tests
pytest tests/integration/# tests/stellar/test_sla_payment.py
import pytest
from app.services.stellar.payment_service import PaymentService
@pytest.mark.asyncio
async def test_sla_payment_flow():
"""Test complete SLA payment flow on Stellar testnet"""
service = PaymentService(network="testnet")
# Create test outage
outage = {
"severity": "critical",
"mttr_minutes": 25, # Over 15 min threshold
}
# Calculate SLA
sla_result = await service.calculate_sla(outage)
assert sla_result["status"] == "violated"
assert sla_result["penalty_amount"] > 0
# Execute payment (on testnet)
payment = await service.execute_payment(sla_result)
assert payment["tx_hash"] is not None
assert payment["status"] == "confirmed"We follow PEP 8 and use the following tools:
# Format code with black
black app/
# Sort imports
isort app/
# Lint with flake8
flake8 app/
# Type checking with mypy
mypy app/Key dependencies in requirements.txt:
# Core
fastapi>=0.109.0
uvicorn[standard]>=0.27.0
pydantic>=2.5.0
# Firebase
firebase-admin>=6.4.0
# Data Processing
pandas>=2.2.0
numpy>=1.26.0
# Visualization
matplotlib>=3.8.0
seaborn>=0.13.0
plotly>=5.18.0
folium>=0.15.0
# Stellar Integration π
stellar-sdk>=9.1.0
soroban-client>=1.0.0
# Authentication & Security
python-jose[cryptography]>=3.3.0
passlib[bcrypt]>=1.7.4
python-dotenv>=1.0.0
# Testing
pytest>=7.4.0
pytest-asyncio>=0.23.0
pytest-cov>=4.1.0
httpx>=0.26.0# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]# Build image
docker build -t nociq-backend .
# Run container
docker run -d -p 8000:8000 --env-file .env nociq-backendWe welcome contributions! Please see our Contributing Guide.
- Fork the repository
- Create a feature branch:
git checkout -b feature/stellar-escrow - Write tests for your changes
- Make your changes
- Run tests:
pytest - Run linters:
black app/ && flake8 app/ - Commit:
git commit -m "feat: add payment escrow contract" - Push:
git push origin feature/stellar-escrow - Open a Pull Request
- Always test on Testnet before mainnet deployment
- Include transaction hashes in PR descriptions
- Document contract changes in detail
- Add unit tests for all Stellar functions (95%+ coverage)
- Follow Stellar SDK best practices
- Use proper key management (never commit private keys)
- Requests per second: 1000+ (with proper setup)
- Response time: <100ms (average for simple queries)
- Stellar transaction time: 3-5 seconds (network confirmation)
- Smart contract execution: <1 second
- Concurrent connections: Handles high load with async/await
- JWT token authentication
- Password hashing with bcrypt
- CORS protection
- Rate limiting
- Input validation with Pydantic
- Secure key storage for Stellar wallets (AWS Secrets Manager/KMS)
- Multi-signature support for high-value transactions
- Transaction validation before execution
- Regular dependency updates
Open an issue with:
- Clear description
- Steps to reproduce (for bugs)
- Expected vs actual behavior
- Request/response examples
- For Stellar issues: Include transaction hash and network
- Environment details (Python version, OS, etc.)
- API Documentation - Detailed endpoint descriptions
- Stellar Integration Guide π
- Smart Contract Documentation π
- Database Schema - Firestore collections structure
- Development Guide - Setup and workflows
- Deployment Guide - Production deployment
- Architecture - System design
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with FastAPI
- Database powered by Google Firestore
- Blockchain integration with Stellar β
- Smart contracts on Soroban β
- Data processing with Pandas
- Visualization using Matplotlib, Seaborn, and Plotly
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Stellar Questions: Stellar Discord
- Basic Stellar integration
- SLA smart contract deployment
- Automated payment processing
- Wallet management API
- Multi-signature transaction support
- Payment batching for gas optimization
- Advanced smart contract features (escrow, multi-party)
- GraphQL API support
- Real-time WebSocket notifications
- ML-based RCA predictions
- Prometheus metrics export
- Redis caching layer
- Kubernetes deployment configs
Made with β€οΈ by the OpSoll Team | Powered by Stellar β
Building on Stellar? Join us in the Stellar Wave Program!