Move blockchain app READMEs to centralized documentation
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 10s
Blockchain Synchronization Verification / sync-verification (push) Failing after 3s
CLI Tests / test-cli (push) Failing after 4s
Documentation Validation / validate-docs (push) Successful in 8s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Successful in 38s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 2s
P2P Network Verification / p2p-verification (push) Successful in 3s
Security Scanning / security-scan (push) Successful in 40s
Smart Contract Tests / test-solidity (map[name:aitbc-token path:packages/solidity/aitbc-token]) (push) Successful in 15s
Smart Contract Tests / lint-solidity (push) Successful in 8s
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 10s
Blockchain Synchronization Verification / sync-verification (push) Failing after 3s
CLI Tests / test-cli (push) Failing after 4s
Documentation Validation / validate-docs (push) Successful in 8s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Successful in 38s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 2s
P2P Network Verification / p2p-verification (push) Successful in 3s
Security Scanning / security-scan (push) Successful in 40s
Smart Contract Tests / test-solidity (map[name:aitbc-token path:packages/solidity/aitbc-token]) (push) Successful in 15s
Smart Contract Tests / lint-solidity (push) Successful in 8s
- Relocate blockchain-event-bridge README content to docs/apps/blockchain/blockchain-event-bridge.md - Relocate blockchain-explorer README content to docs/apps/blockchain/blockchain-explorer.md - Replace app READMEs with redirect notices pointing to new documentation location - Consolidate documentation in central docs/ directory for better organization
This commit is contained in:
@@ -1,112 +1,9 @@
|
||||
# Blockchain Event Bridge
|
||||
|
||||
Bridge between AITBC blockchain events and OpenClaw agent triggers using a hybrid event-driven and polling approach.
|
||||
**Documentation has moved to:** [docs/apps/blockchain/blockchain-event-bridge.md](../../docs/apps/blockchain/blockchain-event-bridge.md)
|
||||
|
||||
## Overview
|
||||
---
|
||||
|
||||
This service connects AITBC blockchain events (blocks, transactions, smart contract events) to OpenClaw agent actions through:
|
||||
- **Event-driven**: Subscribe to gossip broker topics for real-time critical triggers
|
||||
- **Polling**: Periodic checks for batch operations and conditions
|
||||
- **Smart Contract Events**: Monitor contract events via blockchain RPC (Phase 2)
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
## Features
|
||||
|
||||
- Subscribes to blockchain block events via gossip broker
|
||||
- Subscribes to transaction events (when available)
|
||||
- Monitors smart contract events via blockchain RPC:
|
||||
- AgentStaking (stake creation, rewards, tier updates)
|
||||
- PerformanceVerifier (performance verification, penalties, rewards)
|
||||
- AgentServiceMarketplace (service listings, purchases)
|
||||
- BountyIntegration (bounty creation, completion)
|
||||
- CrossChainBridge (bridge initiation, completion)
|
||||
- Triggers coordinator API actions based on blockchain events
|
||||
- Triggers agent daemon actions for agent wallet transactions
|
||||
- Triggers marketplace state updates
|
||||
- Configurable action handlers (enable/disable per type)
|
||||
- Prometheus metrics for monitoring
|
||||
- Health check endpoint
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cd apps/blockchain-event-bridge
|
||||
poetry install
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables:
|
||||
|
||||
- `BLOCKCHAIN_RPC_URL` - Blockchain RPC endpoint (default: `http://localhost:8006`)
|
||||
- `GOSSIP_BACKEND` - Gossip broker backend: `memory`, `broadcast`, or `redis` (default: `memory`)
|
||||
- `GOSSIP_BROADCAST_URL` - Broadcast URL for Redis backend (optional)
|
||||
- `COORDINATOR_API_URL` - Coordinator API endpoint (default: `http://localhost:8011`)
|
||||
- `COORDINATOR_API_KEY` - Coordinator API key (optional)
|
||||
- `SUBSCRIBE_BLOCKS` - Subscribe to block events (default: `true`)
|
||||
- `SUBSCRIBE_TRANSACTIONS` - Subscribe to transaction events (default: `true`)
|
||||
- `ENABLE_AGENT_DAEMON_TRIGGER` - Enable agent daemon triggers (default: `true`)
|
||||
- `ENABLE_COORDINATOR_API_TRIGGER` - Enable coordinator API triggers (default: `true`)
|
||||
- `ENABLE_MARKETPLACE_TRIGGER` - Enable marketplace triggers (default: `true`)
|
||||
- `ENABLE_POLLING` - Enable polling layer (default: `false`)
|
||||
- `POLLING_INTERVAL_SECONDS` - Polling interval in seconds (default: `60`)
|
||||
|
||||
## Running
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
poetry run uvicorn blockchain_event_bridge.main:app --reload --host 127.0.0.1 --port 8204
|
||||
```
|
||||
|
||||
### Production (Systemd)
|
||||
|
||||
```bash
|
||||
sudo systemctl start aitbc-blockchain-event-bridge
|
||||
sudo systemctl enable aitbc-blockchain-event-bridge
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /` - Service information
|
||||
- `GET /health` - Health check
|
||||
- `GET /metrics` - Prometheus metrics
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
blockchain-event-bridge/
|
||||
├── src/blockchain_event_bridge/
|
||||
│ ├── main.py # FastAPI app
|
||||
│ ├── config.py # Settings
|
||||
│ ├── bridge.py # Core bridge logic
|
||||
│ ├── metrics.py # Prometheus metrics
|
||||
│ ├── event_subscribers/ # Event subscription modules
|
||||
│ ├── action_handlers/ # Action handler modules
|
||||
│ └── polling/ # Polling modules
|
||||
└── tests/
|
||||
```
|
||||
|
||||
## Event Flow
|
||||
|
||||
1. Blockchain publishes block event to gossip broker (topic: "blocks")
|
||||
2. Block event subscriber receives event
|
||||
3. Bridge parses block data and extracts transactions
|
||||
4. Bridge triggers appropriate action handlers:
|
||||
- Coordinator API handler for AI jobs, agent messages
|
||||
- Agent daemon handler for agent wallet transactions
|
||||
- Marketplace handler for marketplace listings
|
||||
5. Action handlers make HTTP calls to respective services
|
||||
6. Metrics are recorded for monitoring
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
poetry run pytest
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- Phase 2: Smart contract event subscription
|
||||
- Phase 3: Enhanced polling layer for batch operations
|
||||
- WebSocket support for real-time event streaming
|
||||
- Event replay for missed events
|
||||
For the complete documentation, see the [Blockchain Event Bridge documentation](../../docs/apps/blockchain/blockchain-event-bridge.md).
|
||||
|
||||
@@ -1,396 +1,9 @@
|
||||
# AITBC Blockchain Explorer - Enhanced Version
|
||||
# Blockchain Explorer
|
||||
|
||||
## Overview
|
||||
|
||||
The enhanced AITBC Blockchain Explorer provides comprehensive blockchain exploration capabilities with advanced search, analytics, and export features that match the power of CLI tools while providing an intuitive web interface.
|
||||
|
||||
## 🚀 New Features
|
||||
|
||||
### 🔍 Advanced Search
|
||||
- **Multi-criteria filtering**: Search by address, amount range, transaction type, and time range
|
||||
- **Complex queries**: Combine multiple filters for precise results
|
||||
- **Search history**: Save and reuse common searches
|
||||
- **Real-time results**: Instant search with pagination
|
||||
|
||||
### 📊 Analytics Dashboard
|
||||
- **Transaction volume analytics**: Visualize transaction patterns over time
|
||||
- **Network activity monitoring**: Track blockchain health and performance
|
||||
- **Validator performance**: Monitor validator statistics and rewards
|
||||
- **Time period analysis**: 1h, 24h, 7d, 30d views with interactive charts
|
||||
|
||||
### 📤 Data Export
|
||||
- **Multiple formats**: Export to CSV, JSON for analysis
|
||||
- **Custom date ranges**: Export specific time periods
|
||||
- **Bulk operations**: Export large datasets efficiently
|
||||
- **Search result exports**: Export filtered search results
|
||||
|
||||
### ⚡ Real-time Updates
|
||||
- **Live transaction feed**: Monitor transactions as they happen
|
||||
- **Real-time block updates**: See new blocks immediately
|
||||
- **Network status monitoring**: Track blockchain health
|
||||
- **Alert system**: Get notified about important events
|
||||
|
||||
## 🛠️ Installation
|
||||
|
||||
### Prerequisites
|
||||
- Python 3.13+
|
||||
- Node.js (for frontend development)
|
||||
- Access to AITBC blockchain node
|
||||
|
||||
### Setup
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/aitbc/blockchain-explorer.git
|
||||
cd blockchain-explorer
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the explorer
|
||||
python main.py
|
||||
```
|
||||
|
||||
The explorer will be available at `http://localhost:3001`
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Environment Variables
|
||||
```bash
|
||||
# Blockchain node URL
|
||||
export BLOCKCHAIN_RPC_URL="http://localhost:8082"
|
||||
|
||||
# External node URL (for backup)
|
||||
export EXTERNAL_RPC_URL="http://aitbc.keisanki.net:8082"
|
||||
|
||||
# Explorer settings
|
||||
export EXPLORER_HOST="0.0.0.0"
|
||||
export EXPLORER_PORT="3001"
|
||||
```
|
||||
|
||||
### Configuration File
|
||||
Create `.env` file:
|
||||
```env
|
||||
BLOCKCHAIN_RPC_URL=http://localhost:8082
|
||||
EXTERNAL_RPC_URL=http://aitbc.keisanki.net:8082
|
||||
EXPLORER_HOST=0.0.0.0
|
||||
EXPLORER_PORT=3001
|
||||
```
|
||||
|
||||
## 📚 API Documentation
|
||||
|
||||
### Search Endpoints
|
||||
|
||||
#### Advanced Transaction Search
|
||||
```http
|
||||
GET /api/search/transactions
|
||||
```
|
||||
|
||||
Query Parameters:
|
||||
- `address` (string): Filter by address
|
||||
- `amount_min` (float): Minimum amount
|
||||
- `amount_max` (float): Maximum amount
|
||||
- `tx_type` (string): Transaction type (transfer, stake, smart_contract)
|
||||
- `since` (datetime): Start date
|
||||
- `until` (datetime): End date
|
||||
- `limit` (int): Results per page (max 1000)
|
||||
- `offset` (int): Pagination offset
|
||||
|
||||
Example:
|
||||
```bash
|
||||
curl "http://localhost:3001/api/search/transactions?address=0x123...&amount_min=1.0&limit=50"
|
||||
```
|
||||
|
||||
#### Advanced Block Search
|
||||
```http
|
||||
GET /api/search/blocks
|
||||
```
|
||||
|
||||
Query Parameters:
|
||||
- `validator` (string): Filter by validator address
|
||||
- `since` (datetime): Start date
|
||||
- `until` (datetime): End date
|
||||
- `min_tx` (int): Minimum transaction count
|
||||
- `limit` (int): Results per page (max 1000)
|
||||
- `offset` (int): Pagination offset
|
||||
|
||||
### Analytics Endpoints
|
||||
|
||||
#### Analytics Overview
|
||||
```http
|
||||
GET /api/analytics/overview
|
||||
```
|
||||
|
||||
Query Parameters:
|
||||
- `period` (string): Time period (1h, 24h, 7d, 30d)
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"total_transactions": "1,234",
|
||||
"transaction_volume": "5,678.90 AITBC",
|
||||
"active_addresses": "89",
|
||||
"avg_block_time": "2.1s",
|
||||
"volume_data": {
|
||||
"labels": ["00:00", "02:00", "04:00"],
|
||||
"values": [100, 120, 110]
|
||||
},
|
||||
"activity_data": {
|
||||
"labels": ["00:00", "02:00", "04:00"],
|
||||
"values": [50, 60, 55]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Export Endpoints
|
||||
|
||||
#### Export Search Results
|
||||
```http
|
||||
GET /api/export/search
|
||||
```
|
||||
|
||||
Query Parameters:
|
||||
- `format` (string): Export format (csv, json)
|
||||
- `type` (string): Data type (transactions, blocks)
|
||||
- `data` (string): JSON-encoded search results
|
||||
|
||||
#### Export Latest Blocks
|
||||
```http
|
||||
GET /api/export/blocks
|
||||
```
|
||||
|
||||
Query Parameters:
|
||||
- `format` (string): Export format (csv, json)
|
||||
|
||||
## 🎯 Usage Examples
|
||||
|
||||
### Advanced Search
|
||||
1. **Search by address and amount range**:
|
||||
- Enter address in search field
|
||||
- Click "Advanced" to expand options
|
||||
- Set amount range (min: 1.0, max: 100.0)
|
||||
- Click "Search Transactions"
|
||||
|
||||
2. **Search blocks by validator**:
|
||||
- Expand advanced search
|
||||
- Enter validator address
|
||||
- Set time range if needed
|
||||
- Click "Search Blocks"
|
||||
|
||||
### Analytics
|
||||
1. **View 24-hour analytics**:
|
||||
- Select "Last 24 Hours" from dropdown
|
||||
- View transaction volume chart
|
||||
- Check network activity metrics
|
||||
|
||||
2. **Compare time periods**:
|
||||
- Switch between 1h, 24h, 7d, 30d views
|
||||
- Observe trends and patterns
|
||||
|
||||
### Export Data
|
||||
1. **Export search results**:
|
||||
- Perform search
|
||||
- Click "Export CSV" or "Export JSON"
|
||||
- Download file automatically
|
||||
|
||||
2. **Export latest blocks**:
|
||||
- Go to latest blocks section
|
||||
- Click "Export" button
|
||||
- Choose format
|
||||
|
||||
## 🔍 CLI vs Web Explorer Feature Comparison
|
||||
|
||||
| Feature | CLI | Web Explorer |
|
||||
|---------|-----|--------------|
|
||||
| **Basic Search** | ✅ `aitbc blockchain transaction` | ✅ Simple search |
|
||||
| **Advanced Search** | ✅ `aitbc blockchain search` | ✅ Advanced search form |
|
||||
| **Address Analytics** | ✅ `aitbc blockchain address` | ✅ Address details |
|
||||
| **Transaction Volume** | ✅ `aitbc blockchain analytics` | ✅ Volume charts |
|
||||
| **Data Export** | ✅ `--output csv/json` | ✅ Export buttons |
|
||||
| **Real-time Monitoring** | ✅ `aitbc blockchain monitor` | ✅ Live updates |
|
||||
| **Visual Analytics** | ❌ Text only | ✅ Interactive charts |
|
||||
| **User Interface** | ❌ Command line | ✅ Web interface |
|
||||
| **Mobile Access** | ❌ Limited | ✅ Responsive |
|
||||
|
||||
## 🚀 Performance
|
||||
|
||||
### Optimization Features
|
||||
- **Caching**: Frequently accessed data cached for performance
|
||||
- **Pagination**: Large result sets paginated to prevent memory issues
|
||||
- **Async operations**: Non-blocking API calls for better responsiveness
|
||||
- **Compression**: Gzip compression for API responses
|
||||
|
||||
### Performance Metrics
|
||||
- **Page load time**: < 2 seconds for analytics dashboard
|
||||
- **Search response**: < 500ms for filtered searches
|
||||
- **Export generation**: < 30 seconds for 1000+ records
|
||||
- **Real-time updates**: < 5 second latency
|
||||
|
||||
## 🔒 Security
|
||||
|
||||
### Security Features
|
||||
- **Input validation**: All user inputs validated and sanitized
|
||||
- **Rate limiting**: API endpoints protected from abuse
|
||||
- **CORS protection**: Cross-origin requests controlled
|
||||
- **HTTPS support**: SSL/TLS encryption for production
|
||||
|
||||
### Security Best Practices
|
||||
- **No sensitive data exposure**: Private keys never displayed
|
||||
- **Secure headers**: Security headers implemented
|
||||
- **Input sanitization**: XSS protection enabled
|
||||
- **Error handling**: No sensitive information in error messages
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Explorer not loading
|
||||
```bash
|
||||
# Check if port is available
|
||||
netstat -tulpn | grep 3001
|
||||
|
||||
# Check logs
|
||||
python main.py --log-level debug
|
||||
```
|
||||
|
||||
#### Search not working
|
||||
```bash
|
||||
# Test blockchain node connectivity
|
||||
curl http://localhost:8082/rpc/head
|
||||
|
||||
# Check API endpoints
|
||||
curl http://localhost:3001/health
|
||||
```
|
||||
|
||||
#### Analytics not displaying
|
||||
```bash
|
||||
# Check browser console for JavaScript errors
|
||||
# Verify Chart.js library is loaded
|
||||
# Test API endpoint:
|
||||
curl http://localhost:3001/api/analytics/overview
|
||||
```
|
||||
|
||||
### Debug Mode
|
||||
```bash
|
||||
# Run with debug logging
|
||||
python main.py --log-level debug
|
||||
|
||||
# Check API responses
|
||||
curl -v http://localhost:3001/api/search/transactions
|
||||
```
|
||||
|
||||
## 📱 Mobile Support
|
||||
|
||||
The enhanced explorer is fully responsive and works on:
|
||||
- **Desktop browsers**: Chrome, Firefox, Safari, Edge
|
||||
- **Tablet devices**: iPad, Android tablets
|
||||
- **Mobile phones**: iOS Safari, Chrome Mobile
|
||||
|
||||
Mobile-specific features:
|
||||
- **Touch-friendly interface**: Optimized for touch interactions
|
||||
- **Responsive charts**: Charts adapt to screen size
|
||||
- **Simplified navigation**: Mobile-optimized menu
|
||||
- **Quick actions**: One-tap export and search
|
||||
|
||||
## 🔗 Integration
|
||||
|
||||
### API Integration
|
||||
The explorer provides RESTful APIs for integration with:
|
||||
- **Custom dashboards**: Build custom analytics dashboards
|
||||
- **Mobile apps**: Integrate blockchain data into mobile applications
|
||||
- **Trading bots**: Provide blockchain data for automated trading
|
||||
- **Research tools**: Power blockchain research platforms
|
||||
|
||||
### Webhook Support
|
||||
Configure webhooks for:
|
||||
- **New block notifications**: Get notified when new blocks are mined
|
||||
- **Transaction alerts**: Receive alerts for specific transactions
|
||||
- **Network events**: Monitor network health and performance
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
### Docker Deployment
|
||||
```bash
|
||||
# Build Docker image
|
||||
docker build -t aitbc-explorer .
|
||||
|
||||
# Run container
|
||||
docker run -p 3001:3001 aitbc-explorer
|
||||
```
|
||||
|
||||
### Production Deployment
|
||||
```bash
|
||||
# Install with systemd
|
||||
sudo cp aitbc-explorer.service /etc/systemd/system/
|
||||
sudo systemctl enable aitbc-explorer
|
||||
sudo systemctl start aitbc-explorer
|
||||
|
||||
# Configure nginx reverse proxy
|
||||
sudo cp nginx.conf /etc/nginx/sites-available/aitbc-explorer
|
||||
sudo ln -s /etc/nginx/sites-available/aitbc-explorer /etc/nginx/sites-enabled/
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
```bash
|
||||
# Production environment
|
||||
export NODE_ENV=production
|
||||
export BLOCKCHAIN_RPC_URL=https://mainnet.aitbc.dev
|
||||
export EXPLORER_PORT=3001
|
||||
export LOG_LEVEL=info
|
||||
```
|
||||
|
||||
## 📈 Roadmap
|
||||
|
||||
### Upcoming Features
|
||||
- **WebSocket real-time updates**: Live blockchain monitoring
|
||||
- **Advanced charting**: More sophisticated analytics visualizations
|
||||
- **Custom dashboards**: User-configurable dashboard layouts
|
||||
- **Alert system**: Email and webhook notifications
|
||||
- **Multi-language support**: Internationalization
|
||||
- **Dark mode**: Dark theme support
|
||||
|
||||
### Future Enhancements
|
||||
- **Mobile app**: Native mobile applications
|
||||
- **API authentication**: Secure API access with API keys
|
||||
- **Advanced filtering**: More sophisticated search options
|
||||
- **Performance analytics**: Detailed performance metrics
|
||||
- **Social features**: Share and discuss blockchain data
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
||||
|
||||
### Development Setup
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone https://github.com/aitbc/blockchain-explorer.git
|
||||
cd blockchain-explorer
|
||||
|
||||
# Create virtual environment
|
||||
python -m venv venv
|
||||
source venv/bin/activate
|
||||
|
||||
# Install development dependencies
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# Run tests
|
||||
pytest
|
||||
|
||||
# Start development server
|
||||
python main.py --reload
|
||||
```
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## 📞 Support
|
||||
|
||||
- **Documentation**: [Full documentation](https://docs.aitbc.dev/explorer)
|
||||
- **Issues**: [GitHub Issues](https://github.com/aitbc/blockchain-explorer/issues)
|
||||
- **Discord**: [AITBC Discord](https://discord.gg/aitbc)
|
||||
- **Email**: support@aitbc.dev
|
||||
**Documentation has moved to:** [docs/apps/blockchain/blockchain-explorer.md](../../docs/apps/blockchain/blockchain-explorer.md)
|
||||
|
||||
---
|
||||
|
||||
*Enhanced AITBC Blockchain Explorer - Bringing CLI power to the web interface*
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
For the complete documentation, see the [Blockchain Explorer documentation](../../docs/apps/blockchain/blockchain-explorer.md).
|
||||
|
||||
@@ -1,199 +1,9 @@
|
||||
# Blockchain Node (Brother Chain)
|
||||
# Blockchain Node
|
||||
|
||||
Production-ready blockchain node for AITBC with fixed supply and secure key management.
|
||||
**Documentation has moved to:** [docs/apps/blockchain/blockchain-node.md](../../docs/apps/blockchain/blockchain-node.md)
|
||||
|
||||
## Status
|
||||
---
|
||||
|
||||
✅ **Operational** — Core blockchain functionality implemented.
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
### Capabilities
|
||||
- PoA consensus with single proposer
|
||||
- Transaction processing (TRANSFER, RECEIPT_CLAIM)
|
||||
- Gossip-based peer-to-peer networking (in-memory backend)
|
||||
- RESTful RPC API (`/rpc/*`)
|
||||
- Prometheus metrics (`/metrics`)
|
||||
- Health check endpoint (`/health`)
|
||||
- SQLite persistence with Alembic migrations
|
||||
- Multi-chain support (separate data directories per chain ID)
|
||||
|
||||
## Architecture
|
||||
|
||||
### Wallets & Supply
|
||||
- **Fixed supply**: All tokens minted at genesis; no further minting.
|
||||
- **Two wallets**:
|
||||
- `aitbc1genesis` (treasury): holds the full initial supply (default 1 B AIT). This is the **cold storage** wallet; private key is encrypted in keystore.
|
||||
- `aitbc1treasury` (spending): operational wallet for transactions; initially zero balance. Can receive funds from genesis wallet.
|
||||
- **Private keys** are stored in `keystore/*.json` using AES‑256‑GCM encryption. Password is stored in `keystore/.password` (mode 600).
|
||||
|
||||
### Chain Configuration
|
||||
- **Chain ID**: `ait-mainnet` (production)
|
||||
- **Proposer**: The genesis wallet address is the block proposer and authority.
|
||||
- **Trusted proposers**: Only the genesis wallet is allowed to produce blocks.
|
||||
- **No admin endpoints**: The `/rpc/admin/mintFaucet` endpoint has been removed.
|
||||
|
||||
## Quickstart (Production)
|
||||
|
||||
### 1. Generate Production Keys & Genesis
|
||||
|
||||
Run the setup script once to create the keystore, allocations, and genesis:
|
||||
|
||||
```bash
|
||||
cd /opt/aitbc/apps/blockchain-node
|
||||
.venv/bin/python scripts/setup_production.py --chain-id ait-mainnet
|
||||
```
|
||||
|
||||
This creates:
|
||||
- `keystore/aitbc1genesis.json` (treasury wallet)
|
||||
- `keystore/aitbc1treasury.json` (spending wallet)
|
||||
- `keystore/.password` (random strong password)
|
||||
- `data/ait-mainnet/allocations.json`
|
||||
- `data/ait-mainnet/genesis.json`
|
||||
|
||||
**Important**: Back up the keystore directory and the `.password` file securely. Loss of these means loss of funds.
|
||||
|
||||
### 2. Configure Environment
|
||||
|
||||
Copy the provided production environment file:
|
||||
|
||||
```bash
|
||||
cp .env.production .env
|
||||
```
|
||||
|
||||
Edit `.env` if you need to adjust ports or paths. Ensure `chain_id=ait-mainnet` and `proposer_id` matches the genesis wallet address (the setup script sets it automatically in `.env.production`).
|
||||
|
||||
### 3. Start the Node
|
||||
|
||||
Use the production launcher:
|
||||
|
||||
```bash
|
||||
bash scripts/mainnet_up.sh
|
||||
```
|
||||
|
||||
This starts:
|
||||
- Blockchain node (PoA proposer)
|
||||
- RPC API on `http://127.0.0.1:8026`
|
||||
|
||||
Press `Ctrl+C` to stop both.
|
||||
|
||||
### Manual Startup (Alternative)
|
||||
|
||||
```bash
|
||||
cd /opt/aitbc/apps/blockchain-node
|
||||
source .env.production # or export the variables manually
|
||||
# Terminal 1: Node
|
||||
.venv/bin/python -m aitbc_chain.main
|
||||
# Terminal 2: RPC
|
||||
.venv/bin/bin/uvicorn aitbc_chain.app:app --host 127.0.0.1 --port 8026
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
RPC API available at `http://127.0.0.1:8026/rpc`.
|
||||
|
||||
### Blockchain
|
||||
- `GET /rpc/head` — Current chain head
|
||||
- `GET /rpc/blocks/{height}` — Get block by height
|
||||
- `GET /rpc/blocks-range?start=0&end=10` — Block range
|
||||
- `GET /rpc/info` — Chain information
|
||||
- `GET /rpc/supply` — Token supply (total & circulating)
|
||||
- `GET /rpc/validators` — List of authorities
|
||||
- `GET /rpc/state` — Full state dump
|
||||
|
||||
### Transactions
|
||||
- `POST /rpc/sendTx` — Submit transaction (TRANSFER, RECEIPT_CLAIM)
|
||||
- `GET /rpc/transactions` — Latest transactions
|
||||
- `GET /rpc/tx/{tx_hash}` — Get transaction by hash
|
||||
- `POST /rpc/estimateFee` — Estimate fee
|
||||
|
||||
### Accounts
|
||||
- `GET /rpc/getBalance/{address}` — Account balance
|
||||
- `GET /rpc/address/{address}` — Address details + txs
|
||||
- `GET /rpc/addresses` — List active addresses
|
||||
|
||||
### Health & Metrics
|
||||
- `GET /health` — Health check
|
||||
- `GET /metrics` — Prometheus metrics
|
||||
|
||||
*Note: Admin endpoints (`/rpc/admin/*`) are disabled in production.*
|
||||
|
||||
## Multi‑Chain Support
|
||||
|
||||
The node can run multiple chains simultaneously by setting `supported_chains` in `.env` as a comma‑separated list (e.g., `ait-mainnet,ait-testnet`). Each chain must have its own `data/<chain_id>/genesis.json` and (optionally) its own keystore. The proposer identity is shared across chains; for multi‑chain you may want separate proposer wallets per chain.
|
||||
|
||||
## Keystore Management
|
||||
|
||||
### Encrypted Keystore Format
|
||||
- Uses Web3 keystore format (AES‑256‑GCM + PBKDF2).
|
||||
- Password stored in `keystore/.password` (chmod 600).
|
||||
- Private keys are **never** stored in plaintext.
|
||||
|
||||
### Changing the Password
|
||||
```bash
|
||||
# Use the keystore.py script to re‑encrypt with a new password
|
||||
.venv/bin/python scripts/keystore.py --name genesis --show --password <old> --new-password <new>
|
||||
```
|
||||
(Not yet implemented; currently you must manually decrypt and re‑encrypt.)
|
||||
|
||||
### Adding a New Wallet
|
||||
```bash
|
||||
.venv/bin/python scripts/keystore.py --name mywallet --create
|
||||
```
|
||||
This appends a new entry to `allocations.json` if you want it to receive genesis allocation (edit the file and regenerate genesis).
|
||||
|
||||
## Genesis & Supply
|
||||
|
||||
- Genesis file is generated by `scripts/make_genesis.py`.
|
||||
- Supply is fixed: the sum of `allocations[].balance`.
|
||||
- No tokens can be minted after genesis (`mint_per_unit=0`).
|
||||
- To change the allocation distribution, edit `allocations.json` and regenerate genesis (requires consensus to reset chain).
|
||||
|
||||
## Development / Devnet
|
||||
|
||||
The old devnet (faucet model) has been removed. For local development, use the production setup with a throwaway keystore, or create a separate `ait-devnet` chain by providing your own `allocations.json` and running `scripts/make_genesis.py` manually.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Genesis missing**: Run `scripts/setup_production.py` first.
|
||||
|
||||
**Proposer key not loaded**: Ensure `keystore/aitbc1genesis.json` exists and `keystore/.password` is readable. The node will log a warning but still run (block signing disabled until implemented).
|
||||
|
||||
**Port already in use**: Change `rpc_bind_port` in `.env` and restart.
|
||||
|
||||
**Database locked**: Delete `data/ait-mainnet/chain.db` and restart (only if you're sure no other node is using it).
|
||||
|
||||
## Project Layout
|
||||
|
||||
```
|
||||
blockchain-node/
|
||||
├── src/aitbc_chain/
|
||||
│ ├── app.py # FastAPI app + routes
|
||||
│ ├── main.py # Proposer loop + startup
|
||||
│ ├── config.py # Settings from .env
|
||||
│ ├── database.py # DB init + session mgmt
|
||||
│ ├── mempool.py # Transaction mempool
|
||||
│ ├── gossip/ # P2P message bus
|
||||
│ ├── consensus/ # PoA proposer logic
|
||||
│ ├── rpc/ # RPC endpoints
|
||||
│ └── models.py # SQLModel definitions
|
||||
├── data/
|
||||
│ └── ait-mainnet/
|
||||
│ ├── genesis.json # Generated by make_genesis.py
|
||||
│ └── chain.db # SQLite database
|
||||
├── keystore/
|
||||
│ ├── aitbc1genesis.json
|
||||
│ ├── aitbc1treasury.json
|
||||
│ └── .password
|
||||
├── scripts/
|
||||
│ ├── make_genesis.py # Genesis generator
|
||||
│ ├── setup_production.py # One‑time production setup
|
||||
│ ├── mainnet_up.sh # Production launcher
|
||||
│ └── keystore.py # Keystore utilities
|
||||
└── .env.production # Production environment template
|
||||
```
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **Never** expose RPC API to the public internet without authentication (production should add mTLS or API keys).
|
||||
- Keep keystore and password backups offline.
|
||||
- The node runs as the current user; ensure file permissions restrict access to the `keystore/` and `data/` directories.
|
||||
- In a multi‑node network, use Redis gossip backend and configure `trusted_proposers` with all authority addresses.
|
||||
For the complete documentation including architecture, setup, API reference, and troubleshooting, see the [Blockchain Node documentation](../../docs/apps/blockchain/blockchain-node.md).
|
||||
|
||||
@@ -1,55 +1,9 @@
|
||||
# Coordinator API
|
||||
|
||||
## Purpose & Scope
|
||||
**Documentation has moved to:** [docs/apps/coordinator/coordinator-api.md](../../docs/apps/coordinator/coordinator-api.md)
|
||||
|
||||
FastAPI service that accepts client compute jobs, matches miners, and tracks job lifecycle for the AITBC network.
|
||||
---
|
||||
|
||||
## Marketplace Extensions
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
Stage 2 introduces public marketplace endpoints exposed under `/v1/marketplace`:
|
||||
|
||||
- `GET /v1/marketplace/offers` – list available provider offers (filterable by status).
|
||||
- `GET /v1/marketplace/stats` – aggregated supply/demand metrics surfaced in the marketplace web dashboard.
|
||||
- `POST /v1/marketplace/bids` – accept bid submissions for matching (mock-friendly; returns `202 Accepted`).
|
||||
|
||||
These endpoints serve the `apps/marketplace-web/` dashboard via `VITE_MARKETPLACE_DATA_MODE=live`.
|
||||
|
||||
## Explorer Endpoints
|
||||
|
||||
The coordinator now exposes read-only explorer data under `/v1/explorer` for `apps/explorer-web/` live mode:
|
||||
|
||||
- `GET /v1/explorer/blocks` – block summaries derived from recent job activity.
|
||||
- `GET /v1/explorer/transactions` – transaction-like records for coordinator jobs.
|
||||
- `GET /v1/explorer/addresses` – aggregated address activity and balances.
|
||||
- `GET /v1/explorer/receipts` – latest job receipts (filterable by `job_id`).
|
||||
|
||||
Set `VITE_DATA_MODE=live` and `VITE_COORDINATOR_API` in the explorer web app to consume these APIs.
|
||||
|
||||
## Development Setup
|
||||
|
||||
1. Create a virtual environment in `apps/coordinator-api/.venv`.
|
||||
2. Install dependencies listed in `pyproject.toml` once added.
|
||||
3. Run the FastAPI app via `uvicorn app.main:app --reload`.
|
||||
|
||||
## Configuration
|
||||
|
||||
Expects environment variables defined in `.env` (see `docs/bootstrap/coordinator_api.md`).
|
||||
|
||||
### Signed receipts (optional)
|
||||
|
||||
- Generate an Ed25519 key:
|
||||
```bash
|
||||
python - <<'PY'
|
||||
from nacl.signing import SigningKey
|
||||
sk = SigningKey.generate()
|
||||
print(sk.encode().hex())
|
||||
PY
|
||||
```
|
||||
- Set `RECEIPT_SIGNING_KEY_HEX` in the `.env` file to the printed hex string to enable signed receipts returned by `/v1/miners/{job_id}/result` and retrievable via `/v1/jobs/{job_id}/receipt`.
|
||||
- Receipt history is available at `/v1/jobs/{job_id}/receipts` (requires client API key) and returns all stored signed payloads.
|
||||
- To enable coordinator attestations, set `RECEIPT_ATTESTATION_KEY_HEX` to a separate Ed25519 private key; responses include an `attestations` array alongside the miner signature.
|
||||
- Clients can verify `signature` objects using the `aitbc_crypto` package (see `protocols/receipts/spec.md`).
|
||||
|
||||
## Systemd
|
||||
|
||||
Service name: `aitbc-coordinator-api` (to be defined under `configs/systemd/`).
|
||||
For the complete documentation, see the [Coordinator API documentation](../../docs/apps/coordinator/coordinator-api.md).
|
||||
|
||||
@@ -1,41 +1,9 @@
|
||||
# Marketplace Web
|
||||
# Marketplace
|
||||
|
||||
Mock UI for exploring marketplace offers and submitting bids.
|
||||
**Documentation has moved to:** [docs/apps/marketplace/marketplace.md](../../docs/apps/marketplace/marketplace.md)
|
||||
|
||||
## Development
|
||||
---
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
The dev server listens on `http://localhost:5173/` by default. Adjust via `--host`/`--port` flags in the `systemd` unit or `package.json` script.
|
||||
|
||||
## Data Modes
|
||||
|
||||
Marketplace web reuses the explorer pattern of mock vs. live data:
|
||||
|
||||
- Set `VITE_MARKETPLACE_DATA_MODE=mock` (default) to consume JSON fixtures under `public/mock/`.
|
||||
- Set `VITE_MARKETPLACE_DATA_MODE=live` and point `VITE_MARKETPLACE_API` to the coordinator backend when integration-ready.
|
||||
|
||||
### Feature Flags & Auth
|
||||
|
||||
- `VITE_MARKETPLACE_ENABLE_BIDS` (default `true`) gates whether the bid form submits to the backend. Set to `false` to keep the UI read-only during phased rollouts.
|
||||
- `VITE_MARKETPLACE_REQUIRE_AUTH` (default `false`) enforces a bearer token session before live bid submissions. Tokens are stored in `localStorage` by `src/lib/auth.ts`; the API helpers automatically attach the `Authorization` header when a session is present.
|
||||
- Session JSON is expected to include `token` (string) and `expiresAt` (epoch ms). Expired or malformed entries are cleared automatically.
|
||||
|
||||
Document any backend expectations (e.g., coordinator accepting bearer tokens) alongside the environment variables in deployment manifests.
|
||||
|
||||
## Structure
|
||||
|
||||
- `public/mock/offers.json` – sample marketplace offers.
|
||||
- `public/mock/stats.json` – summary dashboard statistics.
|
||||
- `src/lib/api.ts` – data-mode-aware fetch helpers.
|
||||
- `src/main.ts` – renders dashboard, offers table, and bid form.
|
||||
- `src/style.css` – layout and visual styling.
|
||||
|
||||
## Submitting Bids
|
||||
|
||||
When in mock mode, bid submissions simulate latency and always succeed.
|
||||
|
||||
When in live mode, ensure the coordinator exposes `/v1/marketplace/offers`, `/v1/marketplace/stats`, and `/v1/marketplace/bids` endpoints compatible with the JSON shapes defined in `src/lib/api.ts`.
|
||||
For the complete documentation, see the [Marketplace documentation](../../docs/apps/marketplace/marketplace.md).
|
||||
|
||||
@@ -1,95 +1,9 @@
|
||||
# Pool Hub
|
||||
|
||||
## Purpose & Scope
|
||||
**Documentation has moved to:** [docs/apps/marketplace/pool-hub.md](../../docs/apps/marketplace/pool-hub.md)
|
||||
|
||||
Matchmaking gateway between coordinator job requests and available miners. See `docs/bootstrap/pool_hub.md` for architectural guidance.
|
||||
---
|
||||
|
||||
## Development Setup
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
- Create a Python virtual environment under `apps/pool-hub/.venv`.
|
||||
- Install FastAPI, Redis (optional), and PostgreSQL client dependencies once requirements are defined.
|
||||
- Implement routers and registry as described in the bootstrap document.
|
||||
|
||||
## SLA Monitoring and Billing Integration
|
||||
|
||||
Pool-Hub now includes comprehensive SLA monitoring and billing integration with coordinator-api:
|
||||
|
||||
### SLA Metrics
|
||||
|
||||
- **Miner Uptime**: Tracks miner availability based on heartbeat intervals
|
||||
- **Response Time**: Monitors average response time from match results
|
||||
- **Job Completion Rate**: Tracks successful vs failed job outcomes
|
||||
- **Capacity Availability**: Monitors overall pool capacity utilization
|
||||
|
||||
### SLA Thresholds
|
||||
|
||||
Default thresholds (configurable in settings):
|
||||
- Uptime: 95%
|
||||
- Response Time: 1000ms
|
||||
- Completion Rate: 90%
|
||||
- Capacity Availability: 80%
|
||||
|
||||
### Billing Integration
|
||||
|
||||
Pool-Hub integrates with coordinator-api's billing system to:
|
||||
- Record usage data (gpu_hours, api_calls, compute_hours)
|
||||
- Sync miner usage to tenant billing
|
||||
- Generate invoices via coordinator-api
|
||||
- Track billing metrics and costs
|
||||
|
||||
### API Endpoints
|
||||
|
||||
SLA and billing endpoints are available under `/sla/`:
|
||||
- `GET /sla/metrics/{miner_id}` - Get SLA metrics for a miner
|
||||
- `GET /sla/metrics` - Get SLA metrics across all miners
|
||||
- `GET /sla/violations` - Get SLA violations
|
||||
- `POST /sla/metrics/collect` - Trigger SLA metrics collection
|
||||
- `GET /sla/capacity/snapshots` - Get capacity planning snapshots
|
||||
- `GET /sla/capacity/forecast` - Get capacity forecast
|
||||
- `GET /sla/capacity/recommendations` - Get scaling recommendations
|
||||
- `GET /sla/billing/usage` - Get billing usage data
|
||||
- `POST /sla/billing/sync` - Trigger billing sync with coordinator-api
|
||||
|
||||
### Configuration
|
||||
|
||||
Add to `.env`:
|
||||
```bash
|
||||
# Coordinator-API Billing Integration
|
||||
COORDINATOR_BILLING_URL=http://localhost:8011
|
||||
COORDINATOR_API_KEY=your_api_key_here
|
||||
|
||||
# SLA Configuration
|
||||
SLA_UPTIME_THRESHOLD=95.0
|
||||
SLA_RESPONSE_TIME_THRESHOLD=1000.0
|
||||
SLA_COMPLETION_RATE_THRESHOLD=90.0
|
||||
SLA_CAPACITY_THRESHOLD=80.0
|
||||
|
||||
# Capacity Planning
|
||||
CAPACITY_FORECAST_HOURS=168
|
||||
CAPACITY_ALERT_THRESHOLD_PCT=80.0
|
||||
|
||||
# Billing Sync
|
||||
BILLING_SYNC_INTERVAL_HOURS=1
|
||||
|
||||
# SLA Collection
|
||||
SLA_COLLECTION_INTERVAL_SECONDS=300
|
||||
```
|
||||
|
||||
### Database Migration
|
||||
|
||||
Run the database migration to add SLA and capacity tables:
|
||||
```bash
|
||||
cd apps/pool-hub
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
Run tests for SLA and billing integration:
|
||||
```bash
|
||||
cd apps/pool-hub
|
||||
pytest tests/test_sla_collector.py
|
||||
pytest tests/test_billing_integration.py
|
||||
pytest tests/test_sla_endpoints.py
|
||||
pytest tests/test_integration_coordinator.py
|
||||
```
|
||||
For the complete documentation, see the [Pool Hub documentation](../../docs/apps/marketplace/pool-hub.md).
|
||||
|
||||
@@ -1,437 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" class="h-full">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AITBC Trade Exchange - Buy & Sell AITBC</title>
|
||||
<script src="https://unpkg.com/lucide@latest"></script>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background: #f9fafb; color: #111827; }
|
||||
.container { max-width: 1280px; margin: 0 auto; padding: 0 1rem; }
|
||||
nav { background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
|
||||
.nav-content { display: flex; justify-content: space-between; align-items: center; height: 4rem; }
|
||||
.logo { font-size: 1.25rem; font-weight: 700; }
|
||||
.card { background: white; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 1.5rem; margin-bottom: 1.5rem; }
|
||||
.grid { display: grid; gap: 1.5rem; }
|
||||
.grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
@media (max-width: 1024px) { .grid-cols-3 { grid-template-columns: 1fr; } }
|
||||
.text-2xl { font-size: 1.5rem; line-height: 2rem; font-weight: 700; }
|
||||
.text-sm { font-size: 0.875rem; line-height: 1.25rem; }
|
||||
.text-gray-600 { color: #6b7280; }
|
||||
.text-gray-900 { color: #111827; }
|
||||
.flex { display: flex; }
|
||||
.justify-between { justify-content: space-between; }
|
||||
.items-center { align-items: center; }
|
||||
.gap-4 > * + * { margin-left: 1rem; }
|
||||
button { padding: 0.5rem 1rem; border-radius: 0.375rem; font-weight: 500; cursor: pointer; border: none; }
|
||||
.bg-green-600 { background: #059669; color: white; }
|
||||
.bg-green-600:hover { background: #047857; }
|
||||
.bg-red-600 { background: #dc2626; color: white; }
|
||||
.bg-red-600:hover { background: #b91c1c; }
|
||||
input { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #e5e7eb; border-radius: 0.375rem; }
|
||||
input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.1); }
|
||||
.space-y-2 > * + * { margin-top: 0.5rem; }
|
||||
.text-right { text-align: right; }
|
||||
.text-green-600 { color: #059669; }
|
||||
.text-red-600 { color: #dc2626; }
|
||||
.py-8 { padding-top: 2rem; padding-bottom: 2rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<div class="container">
|
||||
<div class="nav-content">
|
||||
<div class="logo">AITBC Exchange</div>
|
||||
<div class="flex gap-4">
|
||||
<button onclick="toggleDarkMode()">🌙</button>
|
||||
<span id="walletBalance">Balance: Not Connected</span>
|
||||
<button id="connectWalletBtn" onclick="connectWallet()">Connect Wallet</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main class="container py-8">
|
||||
<div class="card">
|
||||
<div class="grid grid-cols-3">
|
||||
<div>
|
||||
<p class="text-sm text-gray-600">Current Price</p>
|
||||
<p class="text-2xl text-gray-900" id="currentPrice">Loading...</p>
|
||||
<p class="text-sm text-green-600" id="priceChange">--</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-600">24h Volume</p>
|
||||
<p class="text-2xl text-gray-900" id="volume24h">Loading...</p>
|
||||
<p class="text-sm text-gray-600">-- BTC</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-600">24h High / Low</p>
|
||||
<p class="text-2xl text-gray-900" id="highLow">Loading...</p>
|
||||
<p class="text-sm text-gray-600">BTC</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-3">
|
||||
<div class="card">
|
||||
<h2 style="font-size: 1.125rem; font-weight: 600; margin-bottom: 1rem;">Order Book</h2>
|
||||
<div class="space-y-2">
|
||||
<div class="flex justify-between text-sm" style="font-weight: 500; color: #6b7280; padding-bottom: 0.5rem;">
|
||||
<span>Price (BTC)</span>
|
||||
<span style="text-align: right;">Amount</span>
|
||||
<span style="text-align: right;">Total</span>
|
||||
</div>
|
||||
<div id="sellOrders"></div>
|
||||
<div id="buyOrders"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div style="display: flex; margin-bottom: 1rem;">
|
||||
<button id="buyTab" onclick="setTradeType('BUY')" style="flex: 1; margin-right: 0.5rem;" class="bg-green-600">Buy AITBC</button>
|
||||
<button id="sellTab" onclick="setTradeType('SELL')" style="flex: 1;" class="bg-red-600">Sell AITBC</button>
|
||||
</div>
|
||||
<form onsubmit="placeOrder(event)">
|
||||
<div class="space-y-2">
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.5rem;">Price (BTC)</label>
|
||||
<input type="number" id="orderPrice" step="0.000001" value="0.000010">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.5rem;">Amount (AITBC)</label>
|
||||
<input type="number" id="orderAmount" step="0.01" placeholder="0.00">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.5rem;">Total (BTC)</label>
|
||||
<input type="number" id="orderTotal" step="0.000001" readonly style="background: #f3f4f6;">
|
||||
</div>
|
||||
<button type="submit" id="submitOrder" class="bg-green-600" style="width: 100%;">Place Buy Order</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2 style="font-size: 1.125rem; font-weight: 600; margin-bottom: 1rem;">Recent Trades</h2>
|
||||
<div class="space-y-2">
|
||||
<div class="flex justify-between text-sm" style="font-weight: 500; color: #6b7280; padding-bottom: 0.5rem;">
|
||||
<span>Price (BTC)</span>
|
||||
<span style="text-align: right;">Amount</span>
|
||||
<span style="text-align: right;">Time</span>
|
||||
</div>
|
||||
<div id="recentTrades"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
const API_BASE = window.location.origin;
|
||||
let tradeType = 'BUY';
|
||||
let walletConnected = false;
|
||||
let walletAddress = null;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
lucide.createIcons();
|
||||
loadRecentTrades();
|
||||
loadOrderBook();
|
||||
updatePriceTicker();
|
||||
|
||||
setInterval(() => {
|
||||
loadRecentTrades();
|
||||
loadOrderBook();
|
||||
updatePriceTicker();
|
||||
}, 5000);
|
||||
|
||||
document.getElementById('orderAmount').addEventListener('input', updateOrderTotal);
|
||||
document.getElementById('orderPrice').addEventListener('input', updateOrderTotal);
|
||||
|
||||
// Check if wallet is already connected
|
||||
checkWalletConnection();
|
||||
});
|
||||
|
||||
// Wallet connection functions
|
||||
async function connectWallet() {
|
||||
try {
|
||||
// Check if MetaMask or other Web3 wallet is installed
|
||||
if (typeof window.ethereum !== 'undefined') {
|
||||
// Request account access
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
if (accounts.length > 0) {
|
||||
walletAddress = accounts[0];
|
||||
walletConnected = true;
|
||||
updateWalletUI();
|
||||
await loadWalletBalance();
|
||||
}
|
||||
} else if (typeof window.bitcoin !== 'undefined') {
|
||||
// Bitcoin wallet support (e.g., Unisat, Xverse)
|
||||
const accounts = await window.bitcoin.requestAccounts();
|
||||
if (accounts.length > 0) {
|
||||
walletAddress = accounts[0];
|
||||
walletConnected = true;
|
||||
updateWalletUI();
|
||||
await loadWalletBalance();
|
||||
}
|
||||
} else {
|
||||
// Fallback to our AITBC wallet
|
||||
await connectAITBCWallet();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Wallet connection failed:', error);
|
||||
alert('Failed to connect wallet. Please ensure you have a compatible wallet installed.');
|
||||
}
|
||||
}
|
||||
|
||||
async function connectAITBCWallet() {
|
||||
try {
|
||||
// Connect to AITBC wallet daemon
|
||||
const response = await fetch(`${API_BASE}/api/wallet/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
walletAddress = data.address;
|
||||
walletConnected = true;
|
||||
updateWalletUI();
|
||||
await loadWalletBalance();
|
||||
} else {
|
||||
throw new Error('Wallet connection failed');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('AITBC wallet connection failed:', error);
|
||||
alert('Could not connect to AITBC wallet. Please ensure the wallet daemon is running.');
|
||||
}
|
||||
}
|
||||
|
||||
function updateWalletUI() {
|
||||
const connectBtn = document.getElementById('connectWalletBtn');
|
||||
const balanceSpan = document.getElementById('walletBalance');
|
||||
|
||||
if (walletConnected) {
|
||||
connectBtn.textContent = 'Disconnect';
|
||||
connectBtn.onclick = disconnectWallet;
|
||||
balanceSpan.textContent = `Address: ${walletAddress.substring(0, 6)}...${walletAddress.substring(walletAddress.length - 4)}`;
|
||||
} else {
|
||||
connectBtn.textContent = 'Connect Wallet';
|
||||
connectBtn.onclick = connectWallet;
|
||||
balanceSpan.textContent = 'Balance: Not Connected';
|
||||
}
|
||||
}
|
||||
|
||||
async function disconnectWallet() {
|
||||
walletConnected = false;
|
||||
walletAddress = null;
|
||||
updateWalletUI();
|
||||
}
|
||||
|
||||
async function loadWalletBalance() {
|
||||
if (!walletConnected || !walletAddress) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/wallet/balance?address=${walletAddress}`);
|
||||
if (response.ok) {
|
||||
const balance = await response.json();
|
||||
document.getElementById('walletBalance').textContent =
|
||||
`BTC: ${balance.btc || '0.00000000'} | AITBC: ${balance.aitbc || '0.00'}`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load wallet balance:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function checkWalletConnection() {
|
||||
// Check if there's a stored wallet connection
|
||||
const stored = localStorage.getItem('aitbc_wallet');
|
||||
if (stored) {
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
walletAddress = data.address;
|
||||
walletConnected = true;
|
||||
updateWalletUI();
|
||||
loadWalletBalance();
|
||||
} catch (e) {
|
||||
localStorage.removeItem('aitbc_wallet');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setTradeType(type) {
|
||||
tradeType = type;
|
||||
const buyTab = document.getElementById('buyTab');
|
||||
const sellTab = document.getElementById('sellTab');
|
||||
const submitBtn = document.getElementById('submitOrder');
|
||||
|
||||
if (type === 'BUY') {
|
||||
buyTab.className = 'bg-green-600';
|
||||
sellTab.className = 'bg-red-600';
|
||||
submitBtn.className = 'bg-green-600';
|
||||
submitBtn.textContent = 'Place Buy Order';
|
||||
} else {
|
||||
sellTab.className = 'bg-red-600';
|
||||
buyTab.className = 'bg-green-600';
|
||||
submitBtn.className = 'bg-red-600';
|
||||
submitBtn.textContent = 'Place Sell Order';
|
||||
}
|
||||
}
|
||||
|
||||
function updateOrderTotal() {
|
||||
const price = parseFloat(document.getElementById('orderPrice').value) || 0;
|
||||
const amount = parseFloat(document.getElementById('orderAmount').value) || 0;
|
||||
document.getElementById('orderTotal').value = (price * amount).toFixed(8);
|
||||
}
|
||||
|
||||
async function loadRecentTrades() {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/trades/recent?limit=15`);
|
||||
if (response.ok) {
|
||||
const trades = await response.json();
|
||||
const container = document.getElementById('recentTrades');
|
||||
container.innerHTML = '';
|
||||
|
||||
trades.forEach(trade => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'flex justify-between text-sm';
|
||||
const time = new Date(trade.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
|
||||
const priceClass = trade.id % 2 === 0 ? 'text-green-600' : 'text-red-600';
|
||||
|
||||
div.innerHTML = `
|
||||
<span class="${priceClass}">${trade.price.toFixed(6)}</span>
|
||||
<span style="color: #6b7280; text-align: right;">${trade.amount.toFixed(2)}</span>
|
||||
<span style="color: #9ca3af; text-align: right;">${time}</span>
|
||||
`;
|
||||
container.appendChild(div);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load recent trades:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOrderBook() {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/orders/orderbook`);
|
||||
if (response.ok) {
|
||||
const orderbook = await response.json();
|
||||
displayOrderBook(orderbook);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load order book:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function displayOrderBook(orderbook) {
|
||||
const sellContainer = document.getElementById('sellOrders');
|
||||
const buyContainer = document.getElementById('buyOrders');
|
||||
|
||||
sellContainer.innerHTML = '';
|
||||
buyContainer.innerHTML = '';
|
||||
|
||||
orderbook.sells.slice(0, 8).reverse().forEach(order => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'flex justify-between text-sm';
|
||||
div.innerHTML = `
|
||||
<span class="text-red-600">${order.price.toFixed(6)}</span>
|
||||
<span style="color: #6b7280; text-align: right;">${(order.remaining || order.amount).toFixed(2)}</span>
|
||||
<span style="color: #9ca3af; text-align: right;">${((order.remaining || order.amount) * order.price).toFixed(4)}</span>
|
||||
`;
|
||||
sellContainer.appendChild(div);
|
||||
});
|
||||
|
||||
orderbook.buys.slice(0, 8).forEach(order => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'flex justify-between text-sm';
|
||||
div.innerHTML = `
|
||||
<span class="text-green-600">${order.price.toFixed(6)}</span>
|
||||
<span style="color: #6b7280; text-align: right;">${(order.remaining || order.amount).toFixed(2)}</span>
|
||||
<span style="color: #9ca3af; text-align: right;">${((order.remaining || order.amount) * order.price).toFixed(4)}</span>
|
||||
`;
|
||||
buyContainer.appendChild(div);
|
||||
});
|
||||
}
|
||||
|
||||
async function updatePriceTicker() {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/trades/recent?limit=100`);
|
||||
if (!response.ok) return;
|
||||
|
||||
const trades = await response.json();
|
||||
if (trades.length === 0) return;
|
||||
|
||||
const currentPrice = trades[0].price;
|
||||
const prices = trades.map(t => t.price);
|
||||
const high24h = Math.max(...prices);
|
||||
const low24h = Math.min(...prices);
|
||||
const priceChange = prices.length > 1 ? ((currentPrice - prices[prices.length - 1]) / prices[prices.length - 1]) * 100 : 0;
|
||||
|
||||
// Calculate 24h volume
|
||||
const volume24h = trades.reduce((sum, trade) => sum + trade.amount, 0);
|
||||
const volumeBTC = trades.reduce((sum, trade) => sum + (trade.amount * trade.price), 0);
|
||||
|
||||
document.getElementById('currentPrice').textContent = `${currentPrice.toFixed(6)} BTC`;
|
||||
document.getElementById('highLow').textContent = `${high24h.toFixed(6)} / ${low24h.toFixed(6)}`;
|
||||
document.getElementById('volume24h').textContent = `${volume24h.toFixed(0)} AITBC`;
|
||||
document.getElementById('volume24h').nextElementSibling.textContent = `≈ ${volumeBTC.toFixed(5)} BTC`;
|
||||
|
||||
const changeElement = document.getElementById('priceChange');
|
||||
changeElement.textContent = `${priceChange >= 0 ? '+' : ''}${priceChange.toFixed(2)}%`;
|
||||
changeElement.style.color = priceChange >= 0 ? '#059669' : '#dc2626';
|
||||
} catch (error) {
|
||||
console.error('Failed to update price ticker:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function placeOrder(event) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!walletConnected) {
|
||||
alert('Please connect your wallet first!');
|
||||
return;
|
||||
}
|
||||
|
||||
const price = parseFloat(document.getElementById('orderPrice').value);
|
||||
const amount = parseFloat(document.getElementById('orderAmount').value);
|
||||
|
||||
if (!price || !amount) {
|
||||
alert('Please enter valid price and amount');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/orders`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
order_type: tradeType,
|
||||
price: price,
|
||||
amount: amount,
|
||||
user_address: walletAddress
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const order = await response.json();
|
||||
alert(`${tradeType} order placed successfully! Order ID: ${order.id}`);
|
||||
|
||||
document.getElementById('orderAmount').value = '';
|
||||
document.getElementById('orderTotal').value = '';
|
||||
|
||||
loadOrderBook();
|
||||
loadWalletBalance(); // Refresh balance after order
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(`Failed to place order: ${error.detail || 'Unknown error'}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to place order:', error);
|
||||
alert('Failed to place order. Please try again.');
|
||||
}
|
||||
}
|
||||
|
||||
function toggleDarkMode() {
|
||||
document.body.style.background = document.body.style.background === 'rgb(17, 24, 39)' ? '#f9fafb' : '#111827';
|
||||
document.body.style.color = document.body.style.color === 'rgb(249, 250, 251)' ? '#111827' : '#f9fafb';
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,32 +1,9 @@
|
||||
# Wallet Daemon
|
||||
# Wallet
|
||||
|
||||
## Purpose & Scope
|
||||
**Documentation has moved to:** [docs/apps/wallet/wallet.md](../../docs/apps/wallet/wallet.md)
|
||||
|
||||
Local FastAPI service that manages encrypted keys, signs transactions/receipts, and exposes wallet RPC endpoints. Reference `docs/bootstrap/wallet_daemon.md` for the implementation plan.
|
||||
---
|
||||
|
||||
## Development Setup
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
- Create a Python virtual environment under `apps/wallet-daemon/.venv` or use Poetry.
|
||||
- Install dependencies via Poetry (preferred):
|
||||
```bash
|
||||
poetry install
|
||||
```
|
||||
- Copy/create `.env` and configure coordinator access:
|
||||
```bash
|
||||
cp .env.example .env # create file if missing
|
||||
```
|
||||
- `COORDINATOR_BASE_URL` (default `http://localhost:8011`)
|
||||
- `COORDINATOR_API_KEY` (development key to verify receipts)
|
||||
- Run the service locally:
|
||||
```bash
|
||||
poetry run uvicorn app.main:app --host 127.0.0.2 --port 8071 --reload
|
||||
```
|
||||
- REST receipt endpoints:
|
||||
- `GET /v1/receipts/{job_id}` (latest receipt + signature validations)
|
||||
- `GET /v1/receipts/{job_id}/history` (full history + validations)
|
||||
- JSON-RPC interface (`POST /rpc`):
|
||||
- Method `receipts.verify_latest`
|
||||
- Method `receipts.verify_history`
|
||||
- Keystore scaffolding:
|
||||
- `KeystoreService` uses Argon2id + XChaCha20-Poly1305 via `app/crypto/encryption.py` (in-memory for now).
|
||||
- Future milestones will add persistent storage and wallet lifecycle routes.
|
||||
For the complete documentation, see the [Wallet documentation](../../docs/apps/wallet/wallet.md).
|
||||
|
||||
@@ -1,170 +1,9 @@
|
||||
# AITBC ZK Circuits
|
||||
# ZK Circuits
|
||||
|
||||
Zero-knowledge circuits for privacy-preserving receipt attestation in the AITBC network.
|
||||
**Documentation has moved to:** [docs/apps/crypto/zk-circuits.md](../../docs/apps/crypto/zk-circuits.md)
|
||||
|
||||
## Overview
|
||||
---
|
||||
|
||||
This project implements zk-SNARK circuits to enable privacy-preserving settlement flows while maintaining verifiability of receipts.
|
||||
This file has been migrated to the central documentation location. Please update your bookmarks and references to point to the new location.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 16+
|
||||
- npm or yarn
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
cd apps/zk-circuits
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile Circuit
|
||||
|
||||
```bash
|
||||
npm run compile
|
||||
```
|
||||
|
||||
### Generate Trusted Setup
|
||||
|
||||
```bash
|
||||
# Start phase 1 setup
|
||||
npm run setup
|
||||
|
||||
# Contribute to setup (run multiple times with different participants)
|
||||
npm run contribute
|
||||
|
||||
# Prepare phase 2
|
||||
npm run prepare
|
||||
|
||||
# Generate proving key
|
||||
npm run generate-zkey
|
||||
|
||||
# Contribute to zkey (optional)
|
||||
npm run contribute-zkey
|
||||
|
||||
# Export verification key
|
||||
npm run export-verification-key
|
||||
```
|
||||
|
||||
### Generate and Verify Proof
|
||||
|
||||
```bash
|
||||
# Generate proof
|
||||
npm run generate-proof
|
||||
|
||||
# Verify proof
|
||||
npm run verify
|
||||
|
||||
# Run tests
|
||||
npm test
|
||||
```
|
||||
|
||||
## Circuit Design
|
||||
|
||||
### Current Implementation
|
||||
|
||||
The initial circuit (`receipt.circom`) implements a simple hash preimage proof:
|
||||
|
||||
- **Public Inputs**: Receipt hash
|
||||
- **Private Inputs**: Receipt data (job ID, miner ID, result, pricing)
|
||||
- **Proof**: Demonstrates knowledge of receipt data without revealing it
|
||||
|
||||
### Future Enhancements
|
||||
|
||||
1. **Full Receipt Attestation**: Complete validation of receipt structure
|
||||
2. **Signature Verification**: ECDSA signature validation
|
||||
3. **Arithmetic Validation**: Pricing and reward calculations
|
||||
4. **Range Proofs**: Confidential transaction amounts
|
||||
|
||||
## Development
|
||||
|
||||
### Circuit Structure
|
||||
|
||||
```
|
||||
receipt.circom # Main circuit file
|
||||
├── ReceiptHashPreimage # Simple hash preimage proof
|
||||
├── ReceiptAttestation # Full receipt validation (WIP)
|
||||
└── ECDSAVerify # Signature verification (WIP)
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
npm test
|
||||
|
||||
# Run specific test
|
||||
npx mocha test.js
|
||||
```
|
||||
|
||||
### Integration
|
||||
|
||||
The circuits integrate with:
|
||||
|
||||
1. **Coordinator API**: Proof generation service
|
||||
2. **Settlement Layer**: On-chain verification contracts
|
||||
3. **Pool Hub**: Privacy options for miners
|
||||
|
||||
## Security
|
||||
|
||||
### Trusted Setup
|
||||
|
||||
The Groth16 setup requires a trusted setup ceremony:
|
||||
|
||||
1. Multi-party participation (>100 recommended)
|
||||
2. Public documentation
|
||||
3. Destruction of toxic waste
|
||||
|
||||
### Audits
|
||||
|
||||
- Circuit formal verification
|
||||
- Third-party security review
|
||||
- Public disclosure of circuits
|
||||
|
||||
## Performance
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Proof Size | ~200 bytes |
|
||||
| Prover Time | 5-15 seconds |
|
||||
| Verifier Time | 3ms |
|
||||
| Gas Cost | ~200k |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Circuit compilation fails**: Check circom version and syntax
|
||||
2. **Setup fails**: Ensure sufficient disk space and memory
|
||||
3. **Proof generation slow**: Consider using faster hardware or PLONK
|
||||
|
||||
### Debug Commands
|
||||
|
||||
```bash
|
||||
# Check circuit constraints
|
||||
circom receipt.circom --r1cs --inspect
|
||||
|
||||
# View witness
|
||||
snarkjs wtns check witness.wtns receipt.wasm input.json
|
||||
|
||||
# Debug proof generation
|
||||
DEBUG=snarkjs npm run generate-proof
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [Circom Documentation](https://docs.circom.io/)
|
||||
- [snarkjs Documentation](https://github.com/iden3/snarkjs)
|
||||
- [ZK Whitepaper](https://eprint.iacr.org/2016/260)
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create feature branch
|
||||
3. Submit pull request with tests
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
For the complete documentation, see the [ZK Circuits documentation](../../docs/apps/crypto/zk-circuits.md).
|
||||
|
||||
Reference in New Issue
Block a user