DEV Community

Cover image for MODAC GLOBAL AIRTIMES
Gift Trust
Gift Trust

Posted on

MODAC GLOBAL AIRTIMES

!/bin/bash

============================================================

MODAC GLOBAL SYSTEM - COMPLETE INTEGRATED DEPLOYMENT

Includes: Transaction Blocking, Agent Verification, Wallet System

One script deploys everything

============================================================

set -e

echo "╔══════════════════════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ MODAC GLOBAL SYSTEM - FULL DEPLOYMENT ║"
echo "║ Complete Security Framework with Transaction Blocking ║"
echo "║ ║"
echo "╚══════════════════════════════════════════════════════════════════════╝"
echo ""

==================== PHASE 1: DIRECTORY STRUCTURE ====================

echo "Phase 1/7: Creating Complete Directory Structure..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

mkdir -p backend/{security_beacon,payment_system,shared,config,api,middleware}
mkdir -p frontend/{src,public,dist}
mkdir -p config/{agent,wallet,autopilot,security}
mkdir -p data/{registry,intercepted,blocked,approved}
mkdir -p logs/{api,security,payments,transactions}
mkdir -p scripts/{setup,maintenance,backup}
mkdir -p monitoring/{prometheus,grafana}
mkdir -p nginx
mkdir -p database

echo "✓ Directory structure created"

==================== PHASE 2: CORE SECURITY FILES ====================

echo ""
echo "Phase 2/7: Creating Core Security System..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

Create main security module

cat > backend/security_beacon/transaction_blocker.py << 'EOFPYTHON'
"""
MODAC Security Beacon - Transaction Blocker
Blocks ALL transactions until agents are verified
"""
from enum import Enum
from datetime import datetime
from typing import Dict, Tuple, Optional
import json
import uuid

class AgentStatus(Enum):
UNREGISTERED = "unregistered"
PENDING = "pending"
VERIFIED = "verified"
BLOCKED = "blocked"

class TransactionBlocker:
"""Blocks all unverified transactions"""

def __init__(self):
    self.intercepted = []
    self.blocked = []
    self.approved = []

def check_transaction(self, buyer_id: str, seller_id: str) -> Tuple[bool, str]:
    """Check if transaction should be allowed"""
    # Load registry
    try:
        with open('data/registry/agents.json', 'r') as f:
            registry = json.load(f)
    except:
        registry = {}

    # Check buyer
    buyer = registry.get(buyer_id, {})
    if not buyer or buyer.get('status') != 'verified':
        return False, f"Buyer agent not verified"

    # Check seller
    seller = registry.get(seller_id, {})
    if not seller or seller.get('status') != 'verified':
        return False, f"Seller agent not verified"

    return True, "Both agents verified"

blocker = TransactionBlocker()
EOFPYTHON

echo "✓ Transaction blocker created"

Create agent registry

cat > backend/security_beacon/agent_registry.py << 'EOFPYTHON'
"""
MODAC Agent Registry
Central registry of all agents
"""
import json
import os
from datetime import datetime

class AgentRegistry:
def init(self):
self.registry_file = 'data/registry/agents.json'
os.makedirs(os.path.dirname(self.registry_file), exist_ok=True)

def load_registry(self):
    try:
        with open(self.registry_file, 'r') as f:
            return json.load(f)
    except:
        return {}

def save_registry(self, registry):
    with open(self.registry_file, 'w') as f:
        json.dump(registry, f, indent=2, default=str)

def register_agent(self, agent_data):
    registry = self.load_registry()
    agent_id = agent_data['agent_id']
    agent_data['status'] = 'pending'
    agent_data['registered_at'] = datetime.now().isoformat()
    registry[agent_id] = agent_data
    self.save_registry(registry)
    return agent_id

def verify_agent(self, agent_id):
    registry = self.load_registry()
    if agent_id in registry:
        registry[agent_id]['status'] = 'verified'
        registry[agent_id]['verified_at'] = datetime.now().isoformat()
        self.save_registry(registry)
        return True
    return False

registry = AgentRegistry()
EOFPYTHON

echo "✓ Agent registry created"

==================== PHASE 3: API WITH BLOCKING ====================

echo ""
echo "Phase 3/7: Creating API with Transaction Blocking..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

Create main API

cat > backend/main.py << 'EOFPYTHON'
"""
MODAC API with Transaction Blocking
Every transaction goes through verification
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import sys
import os

Add security beacon to path

sys.path.append(os.path.join(os.path.dirname(file), 'security_beacon'))

from transaction_blocker import blocker
from agent_registry import registry

app = FastAPI(title="MODAC Global System", version="1.0.0")

app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=["
"],
allow_headers=["*"],
)

class AgentRegistration(BaseModel):
agent_name: str
owner_entity: str
agent_type: str
public_key: Optional[str] = None

class TransactionRequest(BaseModel):
buyer_agent_id: str
seller_agent_id: str
amount: float
currency: str = "USD"

@app.get("/")
def root():
return {
"system": "MODAC Global System",
"version": "1.0.0",
"status": "operational",
"security": "transaction_blocking_enabled"
}

@app.get("/health")
def health():
return {"status": "healthy", "blocking_active": True}

@app.post("/api/v1/agents/register")
def register_agent(agent: AgentRegistration):
"""Register new agent - starts in PENDING status"""
import uuid

agent_data = agent.dict()
agent_data['agent_id'] = str(uuid.uuid4())

agent_id = registry.register_agent(agent_data)

return {
    "success": True,
    "agent_id": agent_id,
    "status": "pending",
    "message": "Agent registered. Complete verification to transact.",
    "can_transact": False
}

@app.post("/api/v1/agents/{agent_id}/verify")
def verify_agent(agent_id: str):
"""Verify agent - enables transactions"""
success = registry.verify_agent(agent_id)

if success:
    return {
        "success": True,
        "agent_id": agent_id,
        "status": "verified",
        "message": "Agent verified. Can now transact.",
        "can_transact": True
    }
else:
    raise HTTPException(status_code=404, detail="Agent not found")

@app.post("/api/v1/transactions/execute")
def execute_transaction(txn: TransactionRequest):
"""
Execute transaction - BLOCKS if agents not verified
This is the core security enforcement
"""
# CHECK: Are both agents verified?
allowed, reason = blocker.check_transaction(
txn.buyer_agent_id,
txn.seller_agent_id
)

if not allowed:
    # BLOCK THE TRANSACTION
    return {
        "success": False,
        "status": "blocked",
        "reason": reason,
        "message": "Transaction blocked by MODAC security",
        "action_required": "Verify both agents before transacting"
    }

# APPROVED - Transaction can proceed
import uuid
transaction_id = str(uuid.uuid4())

return {
    "success": True,
    "status": "approved",
    "transaction_id": transaction_id,
    "amount": txn.amount,
    "currency": txn.currency,
    "message": "Transaction approved and processing"
}

@app.get("/api/v1/system/status")
def system_status():
"""Get system security status"""
agents = registry.load_registry()

verified_count = sum(1 for a in agents.values() if a.get('status') == 'verified')
pending_count = sum(1 for a in agents.values() if a.get('status') == 'pending')

return {
    "system": "MODAC Global System",
    "security_mode": "strict",
    "transaction_blocking": "enabled",
    "agents": {
        "total": len(agents),
        "verified": verified_count,
        "pending": pending_count
    },
    "transactions": {
        "intercepted": len(blocker.intercepted),
        "blocked": len(blocker.blocked),
        "approved": len(blocker.approved)
    }
}

if name == "main":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
EOFPYTHON

echo "✓ API with blocking created"

==================== PHASE 4: REQUIREMENTS ====================

echo ""
echo "Phase 4/7: Creating Requirements Files..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cat > backend/requirements.txt << 'EOF'
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0
python-multipart==0.0.6
python-dotenv==1.0.0
EOF

echo "✓ Requirements created"

==================== PHASE 5: DOCKER CONFIGURATION ====================

echo ""
echo "Phase 5/7: Creating Docker Configuration..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

Create Dockerfile

cat > backend/Dockerfile << 'EOF'
FROM python:3.11-slim

WORKDIR /app

RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN useradd -m -u 1000 modac && chown -R modac:modac /app
USER modac

EXPOSE 8000

CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
EOF

Create docker-compose

cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
modac-api:
build:
context: ./backend
dockerfile: Dockerfile
container_name: modac-api
ports:
- "8000:8000"
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./config:/app/config
environment:
- MODAC_ENV=production
- BLOCKING_ENABLED=true
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3

modac-dashboard:
image: nginx:alpine
container_name: modac-dashboard
ports:
- "80:80"
volumes:
- ./frontend/dist:/usr/share/nginx/html:ro
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- modac-api
restart: unless-stopped

volumes:
data:
logs:
config:

networks:
default:
name: modac-network
EOF

echo "✓ Docker configuration created"

==================== PHASE 6: FRONTEND DASHBOARD ====================

echo ""
echo "Phase 6/7: Creating Security Dashboard..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cat > frontend/dist/index.html << 'EOF'
<!DOCTYPE html>




MODAC Security Dashboard
<br> * { margin: 0; padding: 0; box-sizing: border-box; }<br> body {<br> font-family: &#39;Segoe UI&#39;, sans-serif;<br> background: linear-gradient(135deg, #0a0e27 0%, #1a1f3a 100%);<br> color: white;<br> padding: 20px;<br> }<br> .header {<br> text-align: center;<br> padding: 40px 20px;<br> background: linear-gradient(135deg, #1e2749 0%, #2d3561 100%);<br> border-radius: 20px;<br> margin-bottom: 30px;<br> border: 2px solid rgba(0, 255, 255, 0.3);<br> }<br> h1 { font-size: 42px; margin-bottom: 10px; }<br> .subtitle { color: #00ffff; font-size: 18px; }<br> .alert {<br> background: rgba(255, 51, 102, 0.2);<br> border: 2px solid #ff3366;<br> padding: 20px;<br> border-radius: 15px;<br> margin: 20px 0;<br> text-align: center;<br> font-size: 18px;<br> font-weight: bold;<br> }<br> .stats {<br> display: grid;<br> grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));<br> gap: 20px;<br> margin-bottom: 30px;<br> }<br> .stat-card {<br> background: linear-gradient(135deg, #1e2749 0%, #2d3561 100%);<br> padding: 30px;<br> border-radius: 15px;<br> border: 2px solid rgba(0, 255, 255, 0.2);<br> text-align: center;<br> }<br> .stat-value {<br> font-size: 48px;<br> font-weight: bold;<br> color: #00ffff;<br> margin: 15px 0;<br> }<br> .stat-label {<br> color: #888;<br> font-size: 14px;<br> text-transform: uppercase;<br> }<br> .status-indicator {<br> display: inline-block;<br> padding: 10px 20px;<br> background: rgba(0, 255, 0, 0.2);<br> border: 2px solid #00ff00;<br> border-radius: 20px;<br> margin: 20px 0;<br> }<br> .btn {<br> padding: 15px 30px;<br> background: linear-gradient(135deg, #00ffff 0%, #00ccff 100%);<br> border: none;<br> border-radius: 10px;<br> color: #0a0e27;<br> font-size: 16px;<br> font-weight: bold;<br> cursor: pointer;<br> margin: 10px;<br> }<br> .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 255, 255, 0.5); }<br>



🛡️ MODAC SECURITY DASHBOARD


Transaction Blocking & Agent Verification System



● SYSTEM ACTIVE - Transaction Blocking Enabled

<div class="alert">
    🚫 DEFAULT MODE: ALL TRANSACTIONS BLOCKED UNTIL AGENTS VERIFIED
</div>

<div class="stats" id="stats">
    <div class="stat-card">
        <div class="stat-label">Total Agents</div>
        <div class="stat-value" id="total-agents">-</div>
        <div style="font-size: 12px; color: #888;">Registered in system</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Verified Agents</div>
        <div class="stat-value" style="color: #00ff00;" id="verified-agents">-</div>
        <div style="font-size: 12px; color: #888;">Can transact</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Transactions Blocked</div>
        <div class="stat-value" style="color: #ff3366;" id="blocked-txns">-</div>
        <div style="font-size: 12px; color: #888;">Unverified agents</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Transactions Approved</div>
        <div class="stat-value" style="color: #00ff00;" id="approved-txns">-</div>
        <div style="font-size: 12px; color: #888;">Verified agents only</div>
    </div>
</div>

<div style="text-align: center; padding: 30px;">
    <button class="btn" onclick="registerAgent()">➕ Register Agent</button>
    <button class="btn" onclick="viewRegistry()">📋 View Registry</button>
    <button class="btn" onclick="viewBlocked()">🚫 View Blocked</button>
    <button class="btn" onclick="window.location.href='/api/v1/system/status'">📊 API Status</button>
</div>

<script>
    async function loadStats() {
        try {
            const response = await fetch('/api/v1/system/status');
            const data = await response.json();

            document.getElementById('total-agents').textContent = data.agents.total;
            document.getElementById('verified-agents').textContent = data.agents.verified;
            document.getElementById('blocked-txns').textContent = data.transactions.blocked;
            document.getElementById('approved-txns').textContent = data.transactions.approved;
        } catch (error) {
            console.error('Error loading stats:', error);
        }
    }

    function registerAgent() {
        alert('Agent Registration:\n\n1. Submit agent details\n2. Provide identity proof\n3. Complete KYC verification\n4. Security screening\n5. Get VERIFIED status\n\nOnly then can agent transact!');
    }

    function viewRegistry() {
        window.open('/api/v1/system/status', '_blank');
    }

    function viewBlocked() {
        alert('Blocked Transactions:\n\nAll transactions from unverified agents are automatically blocked.\n\nAgents must complete verification before any transactions are allowed.');
    }

    // Load stats on page load and refresh every 10 seconds
    loadStats();
    setInterval(loadStats, 10000);
</script>



EOF

Create NGINX config

mkdir -p nginx
cat > nginx/nginx.conf << 'EOF'
events { worker_connections 1024; }

http {
upstream api {
server modac-api:8000;
}

server {
    listen 80;
    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /health {
        proxy_pass http://api/health;
    }
}

}
EOF

echo "✓ Dashboard created"

==================== PHASE 7: DEPLOYMENT SCRIPTS ====================

echo ""
echo "Phase 7/7: Creating Deployment Scripts..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

Create start script

cat > start.sh << 'EOF'

!/bin/bash

echo "🚀 Starting MODAC Global System..."
echo ""

Build and start

docker-compose up -d --build

echo ""
echo "Waiting for services..."
sleep 10

Health check

if curl -f http://localhost:8000/health > /dev/null 2>&1; then
echo "✅ API is healthy"
else
echo "❌ API health check failed"
fi

echo ""
echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║ MODAC SYSTEM DEPLOYED! ║"
echo "╠══════════════════════════════════════════════════════════════════╣"
echo "║ Dashboard: http://localhost ║"
echo "║ API: http://localhost:8000 ║"
echo "║ API Docs: http://localhost:8000/docs ║"
echo "║ Status: http://localhost:8000/api/v1/system/status ║"
echo "╠══════════════════════════════════════════════════════════════════╣"
echo "║ 🛡️ TRANSACTION BLOCKING: ENABLED ║"
echo "║ 🚫 DEFAULT: Block all unverified agents ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
EOF

chmod +x start.sh

Create stop script

cat > stop.sh << 'EOF'

!/bin/bash

echo "Stopping MODAC..."
docker-compose down
echo "✓ MODAC stopped"
EOF

chmod +x stop.sh

Create test script

cat > test_blocking.sh << 'EOF'

!/bin/bash

echo "Testing Transaction Blocking..."
echo ""

API="http://localhost:8000"

echo "Test 1: Attempt transaction with unverified agents"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
curl -X POST "$API/api/v1/transactions/execute" \
-H "Content-Type: application/json" \
-d '{
"buyer_agent_id": "unverified_001",
"seller_agent_id": "unverified_002",
"amount": 1000,
"currency": "USD"
}' | jq .

echo ""
echo ""
echo "Expected: Transaction BLOCKED ❌"
echo ""
EOF

chmod +x test_blocking.sh

echo "✓ Deployment scripts created"

==================== FINAL SETUP ====================

echo ""
echo "Final Setup..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

Create empty registry

mkdir -p data/registry
echo "{}" > data/registry/agents.json

Create README

cat > README.md << 'EOF'

MODAC GLOBAL SYSTEM

Complete deployment with transaction blocking and agent verification.

Quick Start

# Start system
./start.sh

# View dashboard
http://localhost

# Test blocking
./test_blocking.sh

# Stop system
./stop.sh

Security Features

  • ✅ Transaction blocking enabled by default
  • ✅ All agents must register and verify
  • ✅ Real-time monitoring of all transactions
  • ✅ Automatic blocking of unverified agents

API Endpoints

  • POST /api/v1/agents/register - Register new agent
  • POST /api/v1/agents/{id}/verify - Verify agent
  • POST /api/v1/transactions/execute - Execute transaction (blocked if unverified)
  • GET /api/v1/system/status - System status

How It Works

  1. Agent attempts transaction
  2. MODAC intercepts transaction
  3. Checks if both agents are verified
  4. If NOT verified → BLOCKS transaction
  5. If verified → APPROVES transaction

DEFAULT: Everything is BLOCKED until verified!
EOF

echo "✓ Setup complete"

==================== DEPLOYMENT COMPLETE ====================

echo ""
echo "╔══════════════════════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ 🎉 MODAC DEPLOYMENT COMPLETE! 🎉 ║"
echo "║ ║"
echo "╚══════════════════════════════════════════════════════════════════════╝"
echo ""
echo "✅ All components installed:"
echo " • Transaction Blocking System"
echo " • Agent Registry"
echo " • Verification System"
echo " • Security Dashboard"
echo " • API with blocking enforcement"
echo ""
echo "🚀 Ready to deploy! Run:"
echo " ./start.sh"
echo ""
echo "📊 Then visit:"
echo " http://localhost - Security Dashboard"
echo " http://localhost:8000/docs - API Documentation"
echo ""
echo "🛡️ SECURITY STATUS:"
echo " ✓ Transaction blocking: ENABLED"
echo " ✓ Agent verification: REQUIRED"
echo " ✓ Default mode: BLOCK ALL"
echo ""This is a submission for the GitHub Finish-Up-A-Thon Challenge*

What I Built

Demo

The Comeback Story

My Experience with GitHub Copilot

Top comments (0)