{"id":31786038,"url":"https://github.com/zfdang/enclave-lottery-app","last_synced_at":"2025-10-10T12:43:48.744Z","repository":{"id":315734444,"uuid":"1060484307","full_name":"zfdang/enclave-lottery-app","owner":"zfdang","description":null,"archived":false,"fork":false,"pushed_at":"2025-09-27T14:14:28.000Z","size":393,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-27T16:13:37.210Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zfdang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/security.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-20T02:15:34.000Z","updated_at":"2025-09-27T14:14:31.000Z","dependencies_parsed_at":"2025-09-20T12:17:05.778Z","dependency_job_id":"96419390-e300-4529-ae10-f85d60f10754","html_url":"https://github.com/zfdang/enclave-lottery-app","commit_stats":null,"previous_names":["zfdang/enclave-lottery-app"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/zfdang/enclave-lottery-app","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zfdang%2Fenclave-lottery-app","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zfdang%2Fenclave-lottery-app/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zfdang%2Fenclave-lottery-app/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zfdang%2Fenclave-lottery-app/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zfdang","download_url":"https://codeload.github.com/zfdang/enclave-lottery-app/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zfdang%2Fenclave-lottery-app/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279003896,"owners_count":26083641,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-10-10T12:43:46.362Z","updated_at":"2025-10-10T12:43:48.736Z","avatar_url":"https://github.com/zfdang.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Enclave Lottery App\n\nPassive, event‑driven lottery operator + React frontend for an Ethereum smart contract. Built for enclave or container deployment; minimal moving parts, no background schedulers.\n\n## ✨ Highlights\n\n* PassiveOperator reacts to on‑chain + time window state (no internal status machine)\n* EventManager polls contract → publishes websocket events (`round_update`, `participants_update`, `history_update`, `config_update`)\n* React (Vite) frontend consumes events in real time (activity feed, countdown, participants list)\n* Single smart contract (Lottery.sol) – winner‑takes‑all with publisher / sparsity commissions\n* Deterministic draw/refund decision logic based on contract timestamps \u0026 participant thresholds\n* Clean layered config: file + env overrides with namespaced prefixes\n* Production‑ready logging (structured friendly text, optional file handler via env)\n* Deployable inside AWS Nitro Enclave (isolation) or plain Docker for development\n\n## 🚀 Quick Start (Local Dev)\n\nRequires: Python 3.11+, Node 18+, Anvil (or any Ethereum RPC), Docker optional.\n\n```bash\n# 1. Start local chain (Anvil example)\nanvil --block-time 1 \u0026\n\n# 2. (Optional) Deploy contract if not already deployed\n#   Use your existing deployment tooling or forge script; ensure address + operator key are set below.\n\n# 3. Backend deps\ncd enclave\npython -m venv venv \u0026\u0026 source venv/bin/activate\npip install -r requirements.txt\n\n# 4. Frontend deps\ncd src/frontend\nnpm install\n\n# 5. Set environment (example minimal – prefer exporting instead of committing)\nexport BLOCKCHAIN_RPC_URL=http://127.0.0.1:8545\nexport BLOCKCHAIN_CHAIN_ID=31337\nexport BLOCKCHAIN_OPERATOR_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\nexport BLOCKCHAIN_CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3\n\n# 6. Run backend (serves API + websocket)\ncd ../../\npython src/main.py\n\n# 7. Run frontend (separate shell)\ncd src/frontend\nnpm run dev\n```\n\nVisit Vite dev URL (typically http://localhost:5173). Connect wallet (MetaMask) pointed at same chain.\n\n## 🧩 Architecture (Current)\n\n```\n┌───────────────┐        ┌──────────────────────┐        ┌──────────────────┐\n│   Frontend    │  WS/HTTP│   Backend (Python)   │  RPC   │  Ethereum Node    │\n│ React + Vite  │◄──────►│ FastAPI WebServer    │◄──────►│ (Anvil/GetH/Gnosis)│\n│ WebSocket Feed│        │ EventManager (polls) │        │  + Lottery.sol    │\n│ Bet Actions   │  tx    │ PassiveOperator      │  emits │  On‑chain state   │\n└───────────────┘  via UI└──────────────────────┘  events└──────────────────┘\n```\n\nKey runtime loop:\n1. EventManager periodically calls contract view functions + decodes new logs.\n2. State snapshots stored in memory + broadcast as typed websocket events.\n3. PassiveOperator listens for `round_update`; when draw or refund window opens it submits the appropriate transaction.\n4. Frontend listens over websocket and re-renders instantly.\n\nNo cron, no internal scheduler thread beyond polling intervals.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `lottery/event_manager.py` | Poll contract, build canonical serialized snapshots \u0026 activity feed |\n| `lottery/operator.py` | Stateless decision logic: draw or refund when conditions satisfied |\n| `blockchain/client.py` | Thin async wrapper around web3.py (events, views, tx send) |\n| `utils/config.py` | Layered config + env overlay (prefix based) |\n| `utils/logger.py` | Centralized logging bootstrap |\n| `src/frontend` | React UI (Vite, websocket consumer) |\n\n## � Websocket Events\n\nDetailed schemas in `docs/EVENTS.md` (to be added). Summary:\n\n| Event | Description |\n|-------|-------------|\n| `round_update` | Current round timing, pot, state, winner (if any) |\n| `participants_update` | Aggregated participant bet amounts |\n| `history_update` | Recently completed/refunded rounds |\n| `config_update` | Contract config + derived operator settings |\n\n## ⚙️ Configuration Overview\n\nSee `docs/CONFIG.md` for authoritative list. Active namespaces (env prefixes):\n\n* `BLOCKCHAIN_` – RPC URL, chain id, operator private key, contract address, gas settings\n* `EVENTMGR_` – polling intervals, feed/history capacities\n* `SERVER_` – host / port\n* `APP_` – logging (e.g. `APP_LOG_LEVEL`, `APP_LOG_FILE`)\n* `ENCLAVE_` – enclave specific (vsock, attestation) if deploying in Nitro\n* Frontend: `VITE_*` variables (e.g. `VITE_API_URL`, `VITE_WS_URL`)\n\nLegacy variable names and demo‑mode specific knobs (draw_interval_minutes, single_bet_amount, scheduler references, REACT_APP_*) have been removed.\n\nMinimal backend config example (env):\n```bash\nexport BLOCKCHAIN_RPC_URL=http://127.0.0.1:8545\nexport BLOCKCHAIN_CHAIN_ID=31337\nexport BLOCKCHAIN_CONTRACT_ADDRESS=0x...\nexport BLOCKCHAIN_OPERATOR_PRIVATE_KEY=0x...\nexport EVENTMGR_POLL_INTERVAL_SECONDS=2\nexport APP_LOG_LEVEL=INFO\n```\n\n## 🧪 Testing (Lightweight)\n\nAt present the repository focuses on runtime behavior; add unit tests around operator timing logic and event serialization as needed. Suggested quick manual validation:\n\n1. Start backend with verbose logs (`APP_LOG_LEVEL=DEBUG`).\n2. Place bets via UI; observe `participants_update` events.\n3. Advance time (or wait) until `min_draw_time` → backend submits `drawWinner` and emits updated `round_update` with winner.\n4. Inspect chain logs for Draw event alignment.\n\n## � Development Workflow\n\nFrontend:\n```bash\ncd enclave/src/frontend\nnpm run dev\n```\n\nBackend:\n```bash\ncd enclave\nsource venv/bin/activate\npython src/main.py\n```\n\nRebuild frontend production bundle (if serving statically inside backend later):\n```bash\nnpm run build\n```\n\n## 🚢 Deployment (Summary)\n\nDocker (dev/test):\n```bash\n./scripts/build_docker.sh\ndocker run --rm -p 6080:6080 \\\n  -e BLOCKCHAIN_RPC_URL=http://host.docker.internal:8545 \\\n  -e BLOCKCHAIN_CHAIN_ID=31337 \\\n  -e BLOCKCHAIN_CONTRACT_ADDRESS=0x... \\\n  -e BLOCKCHAIN_OPERATOR_PRIVATE_KEY=0x... \\\n  enclave-lottery-app:latest\n```\n\nNitro Enclave: build an EIF using `./scripts/build_enclave.sh` then launch via `nitro-cli run-enclave` (details in `docs/deployment.md`).\n\n## 🔐 Security Notes (Implemented vs Conceptual)\n\nImplemented presently:\n* Process isolation (optionally hardware enclave)\n* Least-privilege on-chain actions (only operator key can draw/refund)\n* Basic log redaction of private key\n\nConceptual / future (referenced historically, not fully implemented):\n* Attestation verification flow exposed to end users\n* Advanced entropy mixing or VRF integration\n* Rate limiting \u0026 JWT/session auth for authenticated endpoints (current API is public for read + transaction relay for operator only)\n\nSee forthcoming `docs/security.md` update for a fuller breakdown.\n\n## 📄 Additional Documentation (Incoming Refresh)\n\n| File | Purpose |\n|------|---------|\n| `docs/CONFIG.md` | Definitive config keys \u0026 precedence |\n| `docs/EVENTS.md` | Websocket event payload schemas |\n| `docs/API.md` | REST + websocket endpoints |\n| `docs/FRONTEND.md` | Frontend architecture \u0026 build |\n| `docs/deployment.md` | Deployment guides (Docker / Enclave) |\n| `docs/security.md` | Threat model \u0026 controls |\n\n## 🤝 Contributing\n\nPull requests welcome. Please ensure:\n* Changes keep passive, minimal architecture (avoid reintroducing schedulers unless justified)\n* Add/update docs \u0026 types with behavior changes\n* Avoid committing secrets / private keys\n\n---\n\nBuilt with Python, FastAPI, web3.py, React, TypeScript.\n\nMIT Licensed. See `LICENSE`.\n\nLegacy demo system and engine references were intentionally removed in favor of the current lean model.\n\n```bash\n# Automatically install all prerequisites (except blockchain)\n./scripts/setup_environment.sh\n```\n\n### Unified Demo System (Recommended)\n\n```bash\n# Launch the comprehensive demo suite\npython3 demo.py\n```\n\n**Available Demo Modes:**\n- **1) Quick Demo (5 min)** - Core functionality showcase with blockchain\n- **2) Interactive Demo** - Step-by-step guided experience  \n- **3) Technical Demo** - Detailed system analysis including enclave features\n- **4) Web Demo** - Launch full web interface with real-time blockchain interaction\n- **5) Docker Demo** - Real enclave container environment with blockchain integration\n- **6) Exit** - Exit the demo system\n\n### Prerequisites\n\n- Local blockchain running (Anvil, Hardhat, or Ganache) on `http://localhost:8545`\n- Python 3.11+ with required dependencies\n- Docker 20.10+ (for container demos and enclave builds)\n- Node.js 18+ (for frontend builds)\n- AWS Nitro CLI (for production enclave deployment)\n\n## 🏗️ Architecture\n\n```\n┌─────────────────┐    ┌──────────────────────┐    ┌─────────────────┐\n│   User Browser  │◄──►│ Enclave/Container    │◄──►│ Ethereum Network│\n│                 │    │ Environment          │    │                 │\n│ - React Frontend│    │ - Lottery Engine     │    │ - Smart Contract│\n│ - MetaMask      │    │ - FastAPI Server     │    │ - Result Storage│\n│ - WebSocket     │    │ - Blockchain Client  │    │ - Transparency  │\n│ - Demo Interface│    │ - Docker Runtime     │    │ - Verification  │\n└─────────────────┘    └──────────────────────┘    └─────────────────┘\n```\n\n### Demo Architecture\n\nThe application provides multiple demonstration environments:\n\n- **Development Mode**: Direct Python execution for development\n- **Docker Mode**: Container-based execution simulating enclave isolation\n- **Enclave Mode**: Full AWS Nitro Enclave deployment for production\n\n## 📋 Installation \u0026 Usage\n\n### Manual Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd enclave-lottery-app\n   ```\n\n2. **Install prerequisites**\n   ```bash\n   ./scripts/setup_environment.sh\n   ```\n\n3. **Start local blockchain**\n   ```bash\n   # Install and start Anvil (recommended)\n   curl -L https://foundry.paradigm.xyz | bash\n   foundryup\n   anvil\n   ```\n\n4. **Build the application**\n   ```bash\n   ```bash\n   # Build Docker images and compile contracts\n   ./scripts/build_docker.sh\n   ```\n\n5. **Build enclave (for production)**\n   ```bash\n   # Build EIF file for AWS Nitro Enclave deployment\n   ./scripts/build_enclave.sh\n   ```\n\n6. **Run demonstrations**\n   ```bash\n   # Launch unified demo system\n   python3 demo.py\n   \n   # Or run specific components\n   ./scripts/comprehensive_demo.sh    # Web-based comprehensive demo\n   ```\n\n### Quick Demo Examples\n\n#### Docker Demo Experience\n```bash\n# Select option 5 in demo.py for Docker Demo\npython3 demo.py\n# ➜ 5) 🐳 Docker Demo - Real enclave container environment\n\n# Features:\n# - Automatic Docker image building and container lifecycle\n# - Network isolation with blockchain connectivity to host\n# - Interactive web interface on http://localhost:8081\n# - API endpoint testing and container log viewing\n# - One-click cleanup functionality\n```\n\n#### Development Mode\n```bash\n# For development and testing\npython3 demo.py\n# Interactive lottery simulation with blockchain integration\n```\n\n## 📋 Usage\n\n### For Developers \u0026 Evaluators\n\n1. **Start with Demos**: Use `python3 demo.py` to explore different demonstration modes\n2. **Docker Demo**: Experience enclave-like isolation with container technology\n3. **Web Interface**: Access live web UI during demos for real-time interaction\n4. **API Testing**: Use built-in API demonstration features to test endpoints\n5. **Blockchain Integration**: Observe live blockchain transactions during demos\n\n### For Players (in demo environments)\n\n1. **Connect Wallet**: Click \"Connect Wallet\" and approve MetaMask connection\n2. **Place Bets**: Enter your bet amount (minimum 0.01 ETH) and click \"Place Bet\"\n3. **Watch Countdown**: Monitor the countdown timer to the next draw\n4. **View Results**: Check the winner announcement and your betting history\n5. **Verify on Blockchain**: All results are recorded on Ethereum for transparency\n\n### For Production Deployment\n\n1. **Deploy Infrastructure**: Follow the deployment guide in `docs/deployment.md`\n2. **Build Enclave**: Use `./scripts/build_enclave.sh` to create EIF file\n3. **Deploy to AWS**: Upload EIF to AWS and start Nitro Enclave\n4. **Monitor System**: Use the provided monitoring dashboards\n5. **Verify Attestation**: Regularly check enclave attestation documents\n\n## 📁 Project Structure\n\n```\nenclave-lottery-app/\n├── demo.py                     # Unified demo system with multiple modes\n├── DEMO_GUIDE.md              # Comprehensive demo documentation\n├── enclave/                   # Main enclave application\n│   ├── src/\n│   │   ├── main.py           # Enclave entry point\n│   │   ├── web_server.py     # FastAPI web server\n│   │   ├── lottery/          # Lottery game logic\n│   │   │   ├── operator.py   # PassiveOperator (draw/refund logic)\n│   │   │   └── event_manager.py # Poll + event serialization\n│   │   ├── blockchain/       # Ethereum integration\n│   │   │   ├── client.py     # Blockchain client\n│   │   │   ├── client.py      # Enhanced blockchain client\n│   │   │   └── contracts/    # Solidity contracts\n│   │   │       └── Lottery.sol\n│   │   ├── frontend/         # React application\n│   │   │   ├── src/\n│   │   │   │   ├── App.tsx   # Main React component\n│   │   │   │   └── components/ # UI components\n│   │   │   └── public/       # Static assets\n│   │   └── utils/            # Utility modules\n│   ├── config/\n│   │   └── enclave.conf      # Enclave configuration\n│   ├── requirements.txt      # Python dependencies\n│   └── Dockerfile           # Container image definition\n├── scripts/                 # Build, deploy, and demo scripts\n│   ├── setup_environment.sh # One-command setup\n│   ├── build_docker.sh      # Build Docker images\n│   ├── build_enclave.sh     # Build EIF file for AWS Nitro\n│   └── comprehensive_demo.sh# Web-based demo\n├── host-proxy/              # Host communication proxy\n├── docs/                    # Documentation\n│   ├── architecture.md      # System architecture\n│   ├── deployment.md        # Deployment guide\n│   ├── DEVELOPMENT.md       # Development workflows\n│   └── security.md          # Security documentation\n├── .env                     # Environment configuration\n└── README.md               # This file\n```\n\n## 🔧 Configuration\n\n\u003e 📖 **Complete Configuration Guide**: See [docs/CONFIG.md](docs/CONFIG.md) for comprehensive configuration management documentation.\n\n### Quick Configuration Setup\n\nThe application uses a **three-tier configuration system** with the following priority (highest to lowest):\n\n1. **Environment Variables** (highest priority)\n2. **Configuration File** (`enclave/config/enclave.conf`) \n3. **Hardcoded Defaults** (lowest priority)\n\n### Environment Variables\n\nCopy the template and customize for your environment:\n\n```bash\n# Copy template to create your configuration\ncp .env.example .env\n\n# Edit with your actual values\nnano .env\n```\n\nExample `.env` configuration:\n\n```bash\n# Blockchain Configuration (standardized environment variables)\nETHEREUM_RPC_URL=http://localhost:8545       # Ethereum RPC URL\nCHAIN_ID=31337                               # Chain ID (31337 for Anvil/Hardhat)\nPRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\nCONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3\n\n# Server Configuration\nSERVER_HOST=localhost                        # Server bind address\nSERVER_PORT=6080                             # Server port\n\n# Lottery Configuration\nLOTTERY_DRAW_INTERVAL_MINUTES=5              # Draw interval (minutes)\nLOTTERY_BETTING_CUTOFF_MINUTES=1             # Betting cutoff time (minutes)\nLOTTERY_SINGLE_BET_AMOUNT=0.01               # Single bet amount (ETH)\nLOTTERY_MAX_BETS_PER_USER=10                 # Maximum bets per user\n\n# Enclave Configuration\nENCLAVE_VSOCK_PORT=5005                      # VSock port\nENCLAVE_ATTESTATION_ENABLED=false            # Enable attestation (set to true in production)\n\n# Frontend Configuration\n# (Legacy REACT_APP_* env vars removed; use VITE_* now)\n```\n\n**Important Notes:**\n- ⚠️ Never commit real private keys to Git repositories\n- 🔒 Use secret management services in production\n- 📋 Legacy environment variable names are still supported for backward compatibility\n\n### Configuration Migration\n\nThe system supports both new standardized and legacy environment variable names:\n\n| New Standard | Legacy | Description |\n|-------------|---------|-------------|\n| `ETHEREUM_RPC_URL` | `BLOCKCHAIN_RPC_URL` | Ethereum RPC endpoint |\n| `CHAIN_ID` | `BLOCKCHAIN_CHAIN_ID` | Blockchain chain ID |\n| `PRIVATE_KEY` | `BLOCKCHAIN_PRIVATE_KEY` | Private key for transactions |\n| `SERVER_HOST` | `LOTTERY_SERVER_HOST` | Server bind address |\n| `SERVER_PORT` | `LOTTERY_SERVER_PORT` | Server port |\n\n### Enclave Configuration\n\nThe `enclave/config/enclave.conf` file contains lottery-specific settings:\n\n```json\n{\n  \"server\": {\n    \"host\": \"0.0.0.0\",\n    \"port\": 6080\n  },\n  \"lottery\": {\n    \"draw_interval_minutes\": 10,\n    \"betting_cutoff_minutes\": 1,\n    \"single_bet_amount\": \"0.01\",\n    \"max_bets_per_user\": 100\n  },\n  \"blockchain\": {\n    \"rpc_url\": \"http://localhost:8545\",\n    \"chain_id\": 31337,\n    \"contract_address\": \"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266\",\n    \"private_key\": \"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\"\n  },\n  \"enclave\": {\n    \"vsock_port\": 5000,\n    \"attestation_enabled\": true\n  }\n}\n```\n\n## 🛡️ Security\n\n### Enclave Attestation\n\nBefore trusting the lottery, users can verify the enclave attestation:\n\n```bash\n# Get attestation document\nnitro-cli get-attestation-document --enclave-id \u003cenclave-id\u003e\n\n# Verify the document contains expected measurements\n# PCR0: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\n# PCR1: 202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f\n# PCR2: 404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f\n```\n\n### Random Number Generation\n\nThe lottery uses cryptographically secure random number generation:\n\n1. **Hardware Entropy**: AWS Nitro Enclave hardware random number generator\n2. **Additional Entropy**: Combination of timestamp and betting state\n3. **Cryptographic Hash**: SHA-256 for combining entropy sources\n4. **Verifiable**: All random generation is recorded on blockchain\n\n### Smart Contract Security\n\n- **Access Control**: Only the enclave can record lottery results\n- **Reentrancy Protection**: Guards against reentrancy attacks\n- **Input Validation**: All inputs are validated and sanitized\n- **Gas Optimization**: Fixed gas limits prevent gas-based attacks\n\n## 📊 Monitoring\n\n### Health Checks\n\n- **Application Health**: `GET /health` - Application status\n- **Enclave Status**: `nitro-cli describe-enclaves` - Enclave information\n- **Blockchain Connection**: Ethereum node connectivity check\n- **Database Status**: Application state consistency\n\n### Metrics\n\n- **Performance**: Response times, throughput, error rates\n- **Security**: Failed attempts, unusual patterns, attestation status\n- **Business**: Betting volume, user activity, draw statistics\n- **Infrastructure**: CPU, memory, network usage\n\n### Alerts\n\n- **Critical**: Enclave failures, security breaches\n- **High**: Performance degradation, failed draws\n- **Medium**: Unusual betting patterns, high error rates\n- **Low**: Information updates, maintenance notices\n\n## 🧪 Testing \u0026 Development\n\n### Demo Testing\n\n```bash\n# Test all demo modes\npython3 demo.py\n\n# Test specific components\n./scripts/comprehensive_demo.sh  # Web-based demo\n```\n\n### Unit Tests\n\n```bash\n# Backend tests\ncd enclave\npython -m pytest tests/ -v\n\n# Frontend tests  \ncd enclave/src/frontend\nnpm test\n```\n\n### Build Testing\n\n```bash\n# Test Docker build\n./scripts/build_docker.sh\n\n# Test enclave build (requires AWS Nitro CLI)\n./scripts/build_enclave.sh\n\n# Test with container runtime\ndocker run --rm -p 6080:6080 enclave-lottery-app:latest\n```\n\n### Local Development\n\n```bash\n# Development environment setup\ncd enclave\npython -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\n\n# Start backend development server\npython src/main.py --dev\n\n# Start frontend development server (separate terminal)\ncd src/frontend\nnpm install \u0026\u0026 npm start\n```\n\n## � Deployment Options\n\n### 1. Docker Deployment (Recommended for Testing)\n\n```bash\n# Build and run with Docker\n./scripts/build_docker.sh\ndocker run -d --name lottery-app \\\n  -p 6080:6080 \\\n  --add-host host.docker.internal:host-gateway \\\n  -e ETHEREUM_RPC_URL=http://host.docker.internal:8545 \\\n  -e CONTRACT_ADDRESS=your_contract_address \\\n  enclave-lottery-app:latest\n```\n\n### 2. AWS Nitro Enclave Deployment (Production)\n\n```bash\n# Build enclave image file (EIF)\n./scripts/build_enclave.sh\n\n# Deploy to AWS EC2 with Nitro Enclave support\nsudo nitro-cli run-enclave \\\n  --eif-path lottery.eif \\\n  --cpu-count 2 \\\n  --memory 1024 \\\n  --enclave-cid 16\n```\n\n### 3. Local Development Deployment\n\n```bash\n# Direct Python execution\ncd enclave\nsource venv/bin/activate\npython src/main.py\n```\n\n## 🎮 Demo Modes Explained\n\n### Quick Demo (Option 1)\n- **Duration**: ~5 minutes\n- **Features**: Automated lottery simulation with 5 users, blockchain integration\n- **Best for**: Quick functionality overview\n\n### Interactive Demo (Option 2)  \n- **Duration**: User-controlled\n- **Features**: Step-by-step guided experience with user input\n- **Best for**: Understanding game mechanics\n\n### Technical Demo (Option 3)\n- **Duration**: ~10 minutes  \n- **Features**: Detailed system analysis, enclave features, technical insights\n- **Best for**: Technical evaluation and architecture understanding\n\n### Web Demo (Option 4)\n- **Duration**: Persistent\n- **Features**: Full web interface with real-time updates, MetaMask integration\n- **Best for**: End-user experience testing\n\n### Docker Demo (Option 5)  \n- **Duration**: User-controlled\n- **Features**: Real container environment, network isolation, API testing\n- **Best for**: Enclave simulation and container deployment testing\n\n### Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes with proper tests\n4. Follow code standards (PEP 8 for Python, ESLint for TypeScript)\n5. Update documentation as needed\n6. **Run the test suite (`python3 demo.py` for integration testing)\n7. Submit a pull request\n\n## 📝 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🆘 Getting Started \u0026 Support\n\n### Quick Start Checklist\n\n1. ✅ **Setup Environment**: Run `./scripts/setup_environment.sh`\n2. ✅ **Start Blockchain**: Launch Anvil with `anvil` command  \n3. ✅ **Build Application**: Execute `./scripts/build_docker.sh`\n4. ✅ **Run Demo**: Launch `python3 demo.py` and select a demo mode\n5. ✅ **Explore Features**: Try Docker Demo (option 5) for full container experience\n\n### Documentation\n\n- 📖 [Demo Guide](DEMO_GUIDE.md) - Comprehensive demo documentation\n- 🏗️ [Architecture Guide](docs/architecture.md) - System design and components\n- 🚀 [Deployment Guide](docs/deployment.md) - Production deployment instructions\n- 🔒 [Security Guide](docs/security.md) - Security features and best practices\n- 💻 [Development Guide](docs/DEVELOPMENT.md) - Development workflows and setup\n\n### Troubleshooting\n\n**Common Issues:**\n\n- **Blockchain Connection**: Ensure Anvil is running on `http://localhost:8545`\n- **Docker Issues**: Check Docker daemon is running and user has permissions\n- **Port Conflicts**: Default ports 6080/6080 should be available\n- **Build Failures**: Run `./scripts/setup_environment.sh` to install dependencies\n\n**Getting Help:**\n\n- 🐛 **Issues**: Report bugs and feature requests on GitHub Issues\n- 💬 **Discussions**: Join community discussions on GitHub Discussions  \n- 🔒 **Security**: Report security issues privately to security@example.com\n- 📧 **Contact**: General inquiries to support@example.com\n\n### FAQ\n\n**Q: How do I know the lottery is fair?**\nA: The lottery uses cryptographically secure random numbers, runs in isolated containers/enclaves, and records all results on the blockchain for transparency. The demo modes let you verify this behavior.\n\n**Q: What's the difference between Docker Demo and actual AWS Nitro Enclave?**\nA: Docker Demo simulates enclave isolation using containers, while AWS Nitro Enclave provides hardware-level isolation. Both run the same lottery code with identical security properties.\n\n**Q: Can I run my own lottery instance?**\nA: Yes! The entire system is open source. Use the build scripts and deployment guides to set up your own instance.\n\n**Q: How are gas fees handled?**\nA: The lottery contract is optimized for gas efficiency. Users only pay standard Ethereum transaction fees for their bets.\n\n**Q: What blockchain networks are supported?**\nA: Currently supports any Ethereum-compatible network. Default setup uses local Anvil for testing.\n\n## 🗺️ Roadmap\n\n### Current Version (1.0)\n- ✅ Complete demo system with 5 different modes\n- ✅ Docker container simulation of enclave environment  \n- ✅ AWS Nitro Enclave build pipeline\n- ✅ Blockchain integration with smart contracts\n- ✅ React-based web interface\n- ✅ Comprehensive documentation\n\n### Version 1.1 (Next Release)\n- [ ] Enhanced mobile-responsive interface\n- [ ] Multi-token support (USDC, DAI, etc.)\n- [ ] Advanced betting strategies\n- [ ] Real-time monitoring dashboard\n- [ ] Performance optimizations\n\n### Version 1.2 (Future)\n- [ ] Cross-chain lottery support\n- [ ] DAO governance for lottery parameters\n- [ ] Staking rewards for participants\n- [ ] Advanced analytics and insights\n\n### Version 2.0 (Long-term)\n- [ ] Multi-game platform expansion\n- [ ] NFT integration and rewards\n- [ ] Social features and referrals\n- [ ] Machine learning for fraud detection\n\n---\n\n**🎯 Built with modern technologies:** AWS Nitro Enclaves, Docker, Ethereum, React, FastAPI, and Python\n\n**🔒 Security-first design:** Hardware isolation, blockchain transparency, and cryptographic verification\n\n**🎮 Demo-driven development:** Multiple demonstration modes for comprehensive evaluation","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzfdang%2Fenclave-lottery-app","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzfdang%2Fenclave-lottery-app","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzfdang%2Fenclave-lottery-app/lists"}