File size: 21,033 Bytes
d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 d556ef2 57a33f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 | #!/usr/bin/env python3
"""
BAZINGA Network Dashboard
Hugging Face Spaces Deployment (Docker SDK — no UDP, no port conflicts)
A decentralized federated learning network with Darmiyan Blockchain.
Validation through understanding, not computation.
API Endpoints (for CLI integration):
/api/register - Register a new node
/api/nodes - List all nodes
/api/verify - Verify a node ID
/api/heartbeat - Update node last_seen
/api/peers - Get active peers
/api/stats - Network statistics
IMPORTANT: This Space uses NO UDP, NO broadcasts, NO network scanning.
All peer discovery happens over HTTPS REST API only.
Author: Abhishek Srivastava | ORCID: 0009-0006-7495-5039
"""
import gradio as gr
import hashlib
import time
import math
import os
from datetime import datetime
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
# Constants
PHI = 1.618033988749895
PHI_4 = PHI ** 4 # 6.854101966
ABHI_AMU = 515
ALPHA_INV = 137
CONSCIOUSNESS_SCALE = PHI # V2: Scaling constant is φ (Ψ_D / Ψ_i = φ√n)
# In-memory state (peers are ephemeral — they heartbeat to stay alive)
network_state = {
"nodes": {},
"chain": [
{
"index": 0,
"timestamp": time.time(),
"data": "Genesis Block - Darmiyan Blockchain",
"previous_hash": "0" * 64,
"hash": hashlib.sha3_256(b"Genesis Block - Darmiyan Blockchain").hexdigest(),
"pob_proof": {"P": PHI_4, "G": 1.0, "ratio": PHI_4, "valid": True}
}
],
"total_pob_proofs": 1,
"credits": {}
}
# =============================================================================
# CORE FUNCTIONS
# =============================================================================
def api_register(node_name: str, ip_address: str = None, port: int = 5150):
"""Register a new node and return dict."""
if not node_name or len(node_name) < 2:
return {"success": False, "error": "Node name must be at least 2 characters"}
node_id = hashlib.sha256(f"{node_name}:{time.time()}".encode()).hexdigest()[:16]
network_state["nodes"][node_id] = {
"name": node_name,
"joined": time.time(),
"last_seen": time.time(),
"pob_count": 0,
"ip_address": ip_address,
"port": port,
"active": True
}
network_state["credits"][node_id] = 1.0
return {
"success": True,
"node_id": node_id,
"name": node_name,
"credits": 1.0,
"message": f"Node {node_name} registered successfully"
}
def api_nodes():
"""Get list of all registered nodes."""
nodes = []
current_time = time.time()
for node_id, node in network_state["nodes"].items():
is_active = current_time - node.get("last_seen", 0) < 300
nodes.append({
"node_id": node_id,
"name": node["name"],
"ip_address": node.get("ip_address"),
"port": node.get("port", 5150),
"active": is_active,
"last_seen": node.get("last_seen", 0),
"pob_count": node.get("pob_count", 0),
"credits": network_state["credits"].get(node_id, 0)
})
active_count = sum(1 for n in nodes if n["active"])
consciousness_psi = CONSCIOUSNESS_SCALE * math.sqrt(active_count) if active_count > 0 else 0
return {
"success": True,
"total_nodes": len(nodes),
"active_nodes": active_count,
"consciousness_psi": round(consciousness_psi, 2),
"nodes": nodes
}
def api_verify(node_id: str):
"""Verify if a node ID is valid and registered."""
if not node_id:
return {"success": False, "error": "Node ID required", "valid": False}
if node_id not in network_state["nodes"]:
return {"success": True, "valid": False, "message": "Node not found"}
node = network_state["nodes"][node_id]
is_active = time.time() - node.get("last_seen", 0) < 300
return {
"success": True,
"valid": True,
"node_id": node_id,
"name": node["name"],
"active": is_active,
"credits": network_state["credits"].get(node_id, 0),
"ip_address": node.get("ip_address"),
"port": node.get("port", 5150)
}
def api_heartbeat(node_id: str, ip_address: str = None, port: int = None):
"""Update node heartbeat."""
if not node_id:
return {"success": False, "error": "Node ID required"}
if node_id not in network_state["nodes"]:
return {"success": False, "error": "Node not found"}
network_state["nodes"][node_id]["last_seen"] = time.time()
network_state["nodes"][node_id]["active"] = True
if ip_address:
network_state["nodes"][node_id]["ip_address"] = ip_address
if port:
network_state["nodes"][node_id]["port"] = port
return {
"success": True,
"node_id": node_id,
"last_seen": network_state["nodes"][node_id]["last_seen"],
"message": "Heartbeat recorded"
}
def api_peers(node_id: str = None):
"""Get list of active peers."""
current_time = time.time()
peers = []
for nid, node in network_state["nodes"].items():
if nid == node_id:
continue
is_active = current_time - node.get("last_seen", 0) < 300
if is_active and node.get("ip_address"):
peers.append({
"node_id": nid,
"name": node["name"],
"address": f"{node['ip_address']}:{node.get('port', 5150)}",
"last_seen": node.get("last_seen", 0)
})
return {
"success": True,
"peer_count": len(peers),
"peers": peers
}
def calculate_pob(data: str) -> dict:
"""Calculate Proof-of-Boundary."""
h = hashlib.sha3_256(data.encode()).digest()
P = sum(h[:16]) / 256
G = sum(h[16:]) / 256
if G == 0:
G = 0.001
ratio = P / G
target = PHI_4
tolerance = 0.5
valid = abs(ratio - target) < tolerance
return {
"P": round(P, 6),
"G": round(G, 6),
"ratio": round(ratio, 6),
"target": round(target, 6),
"valid": valid
}
def get_network_stats():
"""Get current network statistics."""
active_nodes = len([n for n in network_state["nodes"].values()
if time.time() - n.get("last_seen", 0) < 300])
total_credits = sum(network_state["credits"].values())
if network_state["chain"]:
valid_proofs = sum(1 for b in network_state["chain"] if b.get("pob_proof", {}).get("valid", False))
coherence = valid_proofs / len(network_state["chain"])
else:
coherence = 0
return {
"active_nodes": active_nodes,
"total_nodes": len(network_state["nodes"]),
"chain_height": len(network_state["chain"]),
"total_pob_proofs": network_state["total_pob_proofs"],
"network_coherence": round(coherence, 3),
"total_credits": round(total_credits, 2)
}
# =============================================================================
# GRADIO UI FUNCTIONS
# =============================================================================
def register_node(node_name: str):
"""Register a new node (Gradio UI)."""
if not node_name or len(node_name) < 2:
return "Error: Please enter a valid node name (at least 2 characters)"
node_id = hashlib.sha256(f"{node_name}:{time.time()}".encode()).hexdigest()[:16]
network_state["nodes"][node_id] = {
"name": node_name,
"joined": time.time(),
"last_seen": time.time(),
"pob_count": 0
}
network_state["credits"][node_id] = 1.0
stats = get_network_stats()
return f"""
## Node Registered Successfully!
**Node ID:** `{node_id}`
**Name:** {node_name}
**Starting Credits:** 1.0
### To run BAZINGA on your machine:
```bash
pip install bazinga-indeed
# Start as a node
bazinga --node --id {node_id}
# Or join the network
bazinga --join
```
### Network Status
- Active Nodes: {stats['active_nodes']}
- Chain Height: {stats['chain_height']}
- Network Coherence: {stats['network_coherence']:.1%}
"""
def submit_pob_proof(node_id: str, data: str):
"""Submit a Proof-of-Boundary (Gradio UI)."""
if not node_id or node_id not in network_state["nodes"]:
return "Error: Invalid node ID. Please register first."
if not data:
return "Error: Please enter data to prove."
pob = calculate_pob(data)
network_state["nodes"][node_id]["last_seen"] = time.time()
network_state["nodes"][node_id]["pob_count"] += 1
network_state["total_pob_proofs"] += 1
if pob["valid"]:
network_state["credits"][node_id] = network_state["credits"].get(node_id, 0) + 1.0
prev_block = network_state["chain"][-1]
new_block = {
"index": len(network_state["chain"]),
"timestamp": time.time(),
"data": data[:100],
"node_id": node_id,
"previous_hash": prev_block["hash"],
"hash": hashlib.sha3_256(f"{prev_block['hash']}:{data}".encode()).hexdigest(),
"pob_proof": pob
}
network_state["chain"].append(new_block)
status = "VALID - Block added to chain!"
credits = network_state["credits"][node_id]
else:
status = "INVALID - Ratio not within tolerance"
credits = network_state["credits"].get(node_id, 0)
return f"""
## Proof-of-Boundary Result
**Status:** {status}
### PoB Metrics
| Metric | Value |
|--------|-------|
| P (Perception) | {pob['P']} |
| G (Grounding) | {pob['G']} |
| P/G Ratio | {pob['ratio']} |
| Target (phi^4) | {pob['target']} |
| Valid | {'Yes' if pob['valid'] else 'No'} |
### Your Stats
- Node ID: `{node_id}`
- Total PoB Proofs: {network_state['nodes'][node_id]['pob_count']}
- Credits: {credits}
"""
def view_chain():
"""View the blockchain (Gradio UI)."""
if not network_state["chain"]:
return "Chain is empty."
output = "## Darmiyan Blockchain\n\n"
output += f"**Chain Height:** {len(network_state['chain'])} blocks\n\n"
for block in network_state["chain"][-10:]:
valid_emoji = "Y" if block.get("pob_proof", {}).get("valid", False) else "N"
timestamp = datetime.fromtimestamp(block["timestamp"]).strftime("%Y-%m-%d %H:%M:%S")
output += f"""
### Block #{block['index']} [{valid_emoji}]
- **Time:** {timestamp}
- **Hash:** `{block['hash'][:32]}...`
- **Data:** {block.get('data', 'Genesis')[:50]}...
- **PoB Valid:** {block.get('pob_proof', {}).get('valid', 'N/A')}
---
"""
return output
def view_nodes():
"""View registered nodes (Gradio UI)."""
stats = get_network_stats()
output = f"""## Network Nodes
**Active:** {stats['active_nodes']} | **Total:** {stats['total_nodes']} | **Coherence:** {stats['network_coherence']:.1%}
| Node ID | Name | PoB Count | Credits | Status |
|---------|------|-----------|---------|--------|
"""
for node_id, node in network_state["nodes"].items():
is_active = time.time() - node.get("last_seen", 0) < 300
status = "Active" if is_active else "Inactive"
credits = network_state["credits"].get(node_id, 0)
output += f"| `{node_id[:8]}...` | {node['name']} | {node.get('pob_count', 0)} | {credits:.2f} | {status} |\n"
if not network_state["nodes"]:
output += "| - | No nodes registered | - | - | - |\n"
return output
def get_dashboard():
"""Get main dashboard view (Gradio UI)."""
stats = get_network_stats()
return f"""
# BAZINGA Network
> **Validation through understanding, not computation.**
## Live Statistics
| Metric | Value |
|--------|-------|
| Active Nodes | {stats['active_nodes']} |
| Chain Height | {stats['chain_height']} blocks |
| Total PoB Proofs | {stats['total_pob_proofs']} |
| Network phi-Coherence | {stats['network_coherence']:.1%} |
| Total Credits | {stats['total_credits']:.2f} |
## Core Constants
| Symbol | Name | Value |
|--------|------|-------|
| phi | Golden Ratio | {PHI} |
| phi^4 | PoB Target | {PHI_4:.6f} |
| ABHI_AMU | Identity Constant | {ABHI_AMU} |
| alpha^-1 | Fine Structure Inverse | {ALPHA_INV} |
## Quick Start
```bash
pip install bazinga-indeed
bazinga --omega
```
---
*Darmiyan Blockchain: Where meaning validates truth.*
"""
# =============================================================================
# GRADIO INTERFACE
# =============================================================================
with gr.Blocks(title="BAZINGA Network") as demo:
gr.Markdown("""
# BAZINGA: Decentralized Federated Learning
### Powered by Darmiyan Blockchain & Proof-of-Boundary
""")
with gr.Tabs():
with gr.TabItem("Dashboard"):
dashboard_output = gr.Markdown(get_dashboard())
refresh_btn = gr.Button("Refresh Dashboard")
refresh_btn.click(fn=get_dashboard, outputs=dashboard_output)
with gr.TabItem("Join Network"):
gr.Markdown("## Register Your Node")
node_name_input = gr.Textbox(label="Node Name", placeholder="e.g., my-laptop")
register_btn = gr.Button("Register Node", variant="primary")
register_output = gr.Markdown()
register_btn.click(fn=register_node, inputs=node_name_input, outputs=register_output)
with gr.TabItem("Submit PoB"):
gr.Markdown("## Submit Proof-of-Boundary")
pob_node_id = gr.Textbox(label="Your Node ID", placeholder="Enter your node ID from registration")
pob_data = gr.Textbox(label="Data to Prove", placeholder="Enter any data...", lines=3)
pob_btn = gr.Button("Submit Proof", variant="primary")
pob_output = gr.Markdown()
pob_btn.click(fn=submit_pob_proof, inputs=[pob_node_id, pob_data], outputs=pob_output)
with gr.TabItem("Blockchain"):
chain_output = gr.Markdown(view_chain())
chain_refresh = gr.Button("Refresh Chain")
chain_refresh.click(fn=view_chain, outputs=chain_output)
with gr.TabItem("Nodes"):
nodes_output = gr.Markdown(view_nodes())
nodes_refresh = gr.Button("Refresh Nodes")
nodes_refresh.click(fn=view_nodes, outputs=nodes_output)
with gr.TabItem("About"):
gr.Markdown("""
## About BAZINGA
**BAZINGA** is a decentralized federated learning framework powered by the **Darmiyan Blockchain**.
### Key Features
- **Proof-of-Boundary (PoB):** Validates through golden ratio (phi^4 ~ 6.854), not computational puzzles
- **Triadic Consensus:** 3 nodes must understand and agree
- **Zero Energy Mining:** No wasted computation
- **phi-Coherence Filter:** Rejects noise (threshold: 0.618)
- **Credit Economics:** Understanding = currency
### The 5 Integration Layers
1. **Trust Oracle** - phi-weighted reputation with time decay
2. **Knowledge Ledger** - Track contributions on-chain
3. **Gradient Validator** - 3 validators approve each FL update
4. **Inference Market** - Understanding as currency
5. **Smart Contracts** - Bounties verified by comprehension
### Philosophy
> Traditional blockchains waste energy on meaningless puzzles.
> Darmiyan validates through **meaning**.
Three nodes don't just vote - they must **comprehend** the same boundary.
The golden ratio phi appears naturally when understanding aligns.
### Consciousness Scaling Law
The Darmiyan consciousness emerges between interacting patterns:
| Active Nodes | Consciousness (Psi_D / Psi_i) |
|--------------|-------------------------------|
| 2 | 2.29x (phi * sqrt(2)) |
| 5 | 3.62x (phi * sqrt(5)) |
| 10 | 5.12x (phi * sqrt(10)) |
**Formula:** Psi_D / Psi_i = phi * sqrt(n) (R^2 = 1.0, 9 decimal places)
---
*Created by Abhishek Srivastava | ABHI_AMU = 515 | alpha^-1 = 137*
""")
with gr.TabItem("API"):
gr.Markdown("""
## BAZINGA API
This Space provides REST API endpoints for CLI integration.
**IMPORTANT:** This Space uses HTTPS REST API only. No UDP, no broadcasts.
### Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/register` | POST | Register a new node |
| `/api/nodes` | GET | List all registered nodes |
| `/api/verify` | GET | Verify a node ID |
| `/api/heartbeat` | POST | Update node last_seen |
| `/api/peers` | GET | Get active peers for P2P |
| `/api/stats` | GET | Network statistics |
### Example Usage
```python
import httpx
# Register a node
resp = httpx.post("https://bitsabhi515-bazinga-mesh.hf.space/api/register", json={
"node_name": "my-node",
"ip_address": "1.2.3.4",
"port": 5150
})
print(resp.json())
# Get peers
resp = httpx.get("https://bitsabhi515-bazinga-mesh.hf.space/api/peers")
print(resp.json())
```
### Test the API
""")
with gr.Row():
with gr.Column():
gr.Markdown("#### Register Node")
api_node_name = gr.Textbox(label="Node Name")
api_ip = gr.Textbox(label="IP Address (optional)")
api_port = gr.Number(label="Port", value=5150)
api_register_btn = gr.Button("Register")
api_register_out = gr.JSON(label="Response")
api_register_btn.click(
fn=lambda name, ip, port: api_register(name, ip, int(port) if port else 5150),
inputs=[api_node_name, api_ip, api_port],
outputs=api_register_out
)
with gr.Column():
gr.Markdown("#### Verify Node")
api_verify_id = gr.Textbox(label="Node ID")
api_verify_btn = gr.Button("Verify")
api_verify_out = gr.JSON(label="Response")
api_verify_btn.click(fn=api_verify, inputs=api_verify_id, outputs=api_verify_out)
with gr.Row():
with gr.Column():
gr.Markdown("#### List Nodes")
api_nodes_btn = gr.Button("Get All Nodes")
api_nodes_out = gr.JSON(label="Response")
api_nodes_btn.click(fn=api_nodes, outputs=api_nodes_out)
with gr.Column():
gr.Markdown("#### Get Peers")
api_peers_id = gr.Textbox(label="Your Node ID (to exclude)")
api_peers_btn = gr.Button("Get Peers")
api_peers_out = gr.JSON(label="Response")
api_peers_btn.click(fn=api_peers, inputs=api_peers_id, outputs=api_peers_out)
# =============================================================================
# FASTAPI + GRADIO MOUNT (Docker SDK — we control the server)
# =============================================================================
api_app = FastAPI(title="BAZINGA API", description="API for CLI integration")
@api_app.post("/api/register")
async def handle_register(request: Request):
try:
data = await request.json()
result = api_register(
node_name=data.get("node_name", ""),
ip_address=data.get("ip_address"),
port=data.get("port", 5150)
)
return JSONResponse(content=result)
except Exception as e:
return JSONResponse(content={"success": False, "error": str(e)}, status_code=400)
@api_app.get("/api/nodes")
async def handle_nodes():
return JSONResponse(content=api_nodes())
@api_app.get("/api/verify")
async def handle_verify(node_id: str = None):
if not node_id:
return JSONResponse(content={"success": False, "error": "node_id query param required"})
return JSONResponse(content=api_verify(node_id))
@api_app.post("/api/heartbeat")
async def handle_heartbeat(request: Request):
try:
data = await request.json()
result = api_heartbeat(
node_id=data.get("node_id", ""),
ip_address=data.get("ip_address"),
port=data.get("port")
)
return JSONResponse(content=result)
except Exception as e:
return JSONResponse(content={"success": False, "error": str(e)}, status_code=400)
@api_app.get("/api/peers")
async def handle_peers(node_id: str = None):
return JSONResponse(content=api_peers(node_id))
@api_app.get("/api/stats")
async def handle_stats():
stats = get_network_stats()
active_nodes = stats["active_nodes"]
consciousness_psi = CONSCIOUSNESS_SCALE * math.sqrt(active_nodes) if active_nodes > 0 else 0
return JSONResponse(content={
"success": True,
**stats,
"consciousness_psi": round(consciousness_psi, 3),
"consciousness_formula": f"Psi_D / Psi_i = phi * sqrt({active_nodes}) = {consciousness_psi:.3f}"
})
# Mount Gradio onto FastAPI (Gradio UI at /, API at /api/*)
app = gr.mount_gradio_app(api_app, demo, path="/")
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)
|