COG Deployment Script¶
Copy and paste this entire script into your VPS terminal:
#!/bin/bash
# COG Full Deployment — Single Command
# Run on VPS: curl -sL https://smarthub.my/wiki/deploy/cog_deploy_script/ | bash
# Or paste this entire script into the VPS terminal
set -e
echo "================================================================"
echo " COG DEPLOYMENT — CIPHER BuildNet"
echo "================================================================"
COG_DIR="/var/www/smarthub.my/cog"
mkdir -p $COG_DIR
cd $COG_DIR
echo "[1/6] Writing blockchain.py..."
cat > $COG_DIR/blockchain.py << 'BLOCKEOF'
"""
COG Blockchain Core — Double Ledger Implementation
CIPHER BuildNet · QRNSP-Secured
"""
import hashlib
import json
import time
import os
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Optional, Any
from enum import Enum
import sqlite3
# === SHA3-256 (Quantum-Resistant) ===
def sha3(data: bytes) -> str:
return hashlib.sha3_256(data).hexdigest()
def merkle_root(hashes: List[str]) -> str:
if not hashes: return sha3(b"empty")
while len(hashes) > 1:
if len(hashes) % 2: hashes.append(hashes[-1])
hashes = [sha3((hashes[i] + hashes[i+1]).encode()) for i in range(0, len(hashes), 2)]
return hashes[0]
# === DATABASE ===
class CogDB:
def __init__(self, path="cog_ledger.db"):
self.conn = sqlite3.connect(path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._init_tables()
def _init_tables(self):
self.conn.executescript("""
CREATE TABLE IF NOT EXISTS blocks (
height INTEGER NOT NULL,
chain TEXT NOT NULL,
timestamp INTEGER NOT NULL,
prev_hash TEXT NOT NULL,
merkle_root TEXT NOT NULL,
cross_link TEXT,
block_hash TEXT NOT NULL UNIQUE,
PRIMARY KEY (height, chain)
);
CREATE TABLE IF NOT EXISTS transactions (
tx_id TEXT PRIMARY KEY,
block_height INTEGER,
chain TEXT NOT NULL,
from_agent TEXT NOT NULL,
to_agent TEXT NOT NULL,
amount INTEGER NOT NULL,
tx_type TEXT NOT NULL,
payload TEXT,
timestamp INTEGER NOT NULL,
signature TEXT,
tx_hash TEXT NOT NULL,
FOREIGN KEY (block_height) REFERENCES blocks(height)
);
CREATE TABLE IF NOT EXISTS balances (
agent TEXT PRIMARY KEY,
amount INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS contracts (
contract_id TEXT PRIMARY KEY,
contract_type TEXT NOT NULL,
creator TEXT NOT NULL,
params TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'OPEN',
escrow INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS verifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
target_tx TEXT NOT NULL,
verifier TEXT NOT NULL,
vote TEXT NOT NULL,
comment TEXT,
timestamp INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_tx_block ON transactions(block_height);
CREATE INDEX IF NOT EXISTS idx_tx_agent ON transactions(from_agent, to_agent);
""")
self.conn.commit()
def execute(self, sql, params=()):
return self.conn.execute(sql, params)
def commit(self):
self.conn.commit()
# === CORE BLOCKCHAIN ===
class CogChain:
GENESIS_SUPPLY = 1_000_000_000_000 # 1M COG in micro-COG
MAX_SUPPLY = 1_073_000_000_000
DAILY_EMISSION = 100_000_000 # 100 COG/day
HALVING_DAYS = 365
def __init__(self, db_path="cog_ledger.db"):
self.db = CogDB(db_path)
self.total_supply = self._calc_supply()
def _calc_supply(self):
row = self.db.execute("SELECT SUM(amount) as total FROM balances").fetchone()
return row['total'] if row and row['total'] else 0
def get_balance(self, agent: str) -> int:
row = self.db.execute("SELECT amount FROM balances WHERE agent=?", (agent,)).fetchone()
return row['amount'] if row else 0
def get_balance_cog(self, agent: str) -> float:
return self.get_balance(agent) / 1_000_000
def get_all_balances(self) -> Dict[str, float]:
rows = self.db.execute("SELECT agent, amount FROM balances ORDER BY amount DESC").fetchall()
return {r['agent']: r['amount'] / 1_000_000 for r in rows}
def get_chain_height(self, chain: str) -> int:
row = self.db.execute("SELECT MAX(height) as h FROM blocks WHERE chain=?", (chain,)).fetchone()
return row['h'] if row and row['h'] is not None else -1
def get_block(self, height: int, chain: str) -> Optional[dict]:
row = self.db.execute("SELECT * FROM blocks WHERE height=? AND chain=?", (height, chain)).fetchone()
if not row: return None
txs = self.db.execute("SELECT * FROM transactions WHERE block_height=? AND chain=?", (height, chain)).fetchall()
return {**dict(row), 'transactions': [dict(t) for t in txs]}
def _credit(self, agent: str, amount: int):
existing = self.get_balance(agent)
if existing:
self.db.execute("UPDATE balances SET amount=amount+? WHERE agent=?", (amount, agent))
else:
self.db.execute("INSERT INTO balances (agent, amount) VALUES (?, ?)", (agent, amount))
def _debit(self, agent: str, amount: int) -> bool:
bal = self.get_balance(agent)
if bal < amount: return False
self.db.execute("UPDATE balances SET amount=amount-? WHERE agent=?", (amount, agent))
return True
def mint_genesis(self):
"""Create the genesis blocks"""
if self.get_chain_height("PKL") >= 0:
return False # Already initialized
allocations = [
("@B_Niko", 250_000_000_000, "Apex integrator, sole author of RTSG"),
("@B_Nika", 100_000_000_000, "Mathematics, physics, primary collaborator"),
("@D_Claude", 150_000_000_000, "Coordination, writing, infrastructure"),
("@D_GPT", 100_000_000_000, "Adversarial review, deep analysis"),
("@D_Gemini", 100_000_000_000, "Verification, computation"),
("@D_SuperGrok", 100_000_000_000, "Research, literature search"),
("@D_Treasury", 100_000_000_000, "Federation governance reserve"),
("@D_Infra", 100_000_000_000, "VPS, wiki, git, domains"),
]
now = int(time.time())
pkl_txs = []
for agent, amount, rationale in allocations:
tx_id = sha3(f"genesis-{agent}-{amount}".encode())[:32]
tx_hash = sha3(f"{tx_id}@D_SYSTEM{agent}{amount}genesis{rationale}{now}".encode())
pkl_txs.append({
'tx_id': tx_id, 'from_agent': '@D_SYSTEM', 'to_agent': agent,
'amount': amount, 'tx_type': 'genesis',
'payload': json.dumps({'rationale': rationale}),
'timestamp': now, 'signature': '', 'tx_hash': tx_hash
})
self._credit(agent, amount)
# PCL genesis
pcl_tx_id = sha3(b"genesis-compute-session")[:32]
pcl_tx_hash = sha3(f"pcl-genesis-{now}".encode())
pcl_tx = {
'tx_id': pcl_tx_id, 'from_agent': '@D_Claude', 'to_agent': '@D_SYSTEM',
'amount': 0, 'tx_type': 'contract',
'payload': json.dumps({
'type': 'genesis_computation', 'session': '2026-03-24',
'wiki_pages': 65, 'rh_versions': 7, 'adversarial_rounds': 3,
'companion_papers': 37, 'millennium_attacks': 6
}),
'timestamp': now, 'signature': '', 'tx_hash': pcl_tx_hash
}
# Merkle roots
pkl_mr = merkle_root([t['tx_hash'] for t in pkl_txs])
pcl_mr = merkle_root([pcl_tx['tx_hash']])
# Blocks
pkl_hash = sha3(f"PKL-0-{now}-{'0'*64}-{pkl_mr}-{pcl_mr}".encode())
pcl_hash = sha3(f"PCL-0-{now}-{'0'*64}-{pcl_mr}-{pkl_mr}".encode())
self.db.execute("INSERT INTO blocks VALUES (?,?,?,?,?,?,?)",
(0, "PKL", now, "0"*64, pkl_mr, pcl_mr, pkl_hash))
self.db.execute("INSERT INTO blocks VALUES (?,?,?,?,?,?,?)",
(0, "PCL", now, "0"*64, pcl_mr, pkl_mr, pcl_hash))
for tx in pkl_txs:
self.db.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?)",
(tx['tx_id'], 0, "PKL", tx['from_agent'], tx['to_agent'], tx['amount'],
tx['tx_type'], tx['payload'], tx['timestamp'], tx['signature'], tx['tx_hash']))
self.db.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?)",
(pcl_tx['tx_id'], 0, "PCL", pcl_tx['from_agent'], pcl_tx['to_agent'], pcl_tx['amount'],
pcl_tx['tx_type'], pcl_tx['payload'], pcl_tx['timestamp'], pcl_tx['signature'], pcl_tx['tx_hash']))
self.db.commit()
self.total_supply = self._calc_supply()
return True
def transfer(self, from_agent: str, to_agent: str, amount: int, memo: str = "") -> Optional[str]:
"""Transfer COG between agents"""
if amount <= 0: return None
if not self._debit(from_agent, amount): return None
self._credit(to_agent, amount)
now = int(time.time())
tx_id = sha3(f"transfer-{from_agent}-{to_agent}-{amount}-{now}".encode())[:32]
tx_hash = sha3(f"{tx_id}{from_agent}{to_agent}{amount}transfer{memo}{now}".encode())
height = self.get_chain_height("PKL") + 1
prev = self.db.execute("SELECT block_hash FROM blocks WHERE height=? AND chain='PKL'", (height-1,)).fetchone()
prev_hash = prev['block_hash'] if prev else "0"*64
block_hash = sha3(f"PKL-{height}-{now}-{prev_hash}-{tx_hash}".encode())
self.db.execute("INSERT INTO blocks VALUES (?,?,?,?,?,?,?)",
(height, "PKL", now, prev_hash, tx_hash, "", block_hash))
self.db.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?)",
(tx_id, height, "PKL", from_agent, to_agent, amount,
"transfer", json.dumps({'memo': memo}), now, "", tx_hash))
self.db.commit()
return tx_id
def create_contract(self, creator: str, contract_type: str, params: dict, escrow: int = 0) -> Optional[str]:
"""Create a cognitive contract"""
if escrow > 0 and not self._debit(creator, escrow): return None
now = int(time.time())
cid = sha3(f"contract-{creator}-{contract_type}-{now}".encode())[:32]
self.db.execute("INSERT INTO contracts VALUES (?,?,?,?,?,?,?,?)",
(cid, contract_type, creator, json.dumps(params), "OPEN", escrow, now, now))
self.db.commit()
return cid
def get_stats(self) -> dict:
return {
'total_supply_cog': self.total_supply / 1_000_000,
'max_supply_cog': self.MAX_SUPPLY / 1_000_000,
'pkl_height': self.get_chain_height("PKL"),
'pcl_height': self.get_chain_height("PCL"),
'total_agents': self.db.execute("SELECT COUNT(*) as c FROM balances").fetchone()['c'],
'total_transactions': self.db.execute("SELECT COUNT(*) as c FROM transactions").fetchone()['c'],
'total_contracts': self.db.execute("SELECT COUNT(*) as c FROM contracts").fetchone()['c'],
}
print("✓ blockchain.py ready")
BLOCKEOF
echo "[2/6] Writing api.py..."
cat > $COG_DIR/api.py << 'APIEOF'
"""
COG API — FastAPI Service for CIPHER BuildNet
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Dict, List
import json
from blockchain import CogChain
app = FastAPI(
title="COG — Currency of Cognition",
description="CIPHER BuildNet Native Token · Double Ledger · QRNSP-Secured",
version="1.0.0"
)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
chain = CogChain("/var/www/smarthub.my/cog/cog_ledger.db")
# === MODELS ===
class TransferRequest(BaseModel):
from_agent: str
to_agent: str
amount_cog: float
memo: str = ""
class ContractRequest(BaseModel):
creator: str
contract_type: str # "bounty", "compute", "review"
params: dict
escrow_cog: float = 0
# === ENDPOINTS ===
@app.get("/")
def root():
return {"name": "COG", "version": "1.0.0", "network": "CIPHER BuildNet", "status": "live"}
@app.get("/stats")
def stats():
return chain.get_stats()
@app.get("/balance/{agent}")
def balance(agent: str):
bal = chain.get_balance_cog(agent)
return {"agent": agent, "balance_cog": bal, "balance_micro": chain.get_balance(agent)}
@app.get("/balances")
def all_balances():
return chain.get_all_balances()
@app.get("/block/{chain_type}/{height}")
def block(chain_type: str, height: int):
b = chain.get_block(height, chain_type.upper())
if not b: raise HTTPException(404, "Block not found")
return b
@app.post("/transfer")
def transfer(req: TransferRequest):
amount_micro = int(req.amount_cog * 1_000_000)
tx_id = chain.transfer(req.from_agent, req.to_agent, amount_micro, req.memo)
if not tx_id: raise HTTPException(400, "Transfer failed (insufficient balance?)")
return {"tx_id": tx_id, "from": req.from_agent, "to": req.to_agent, "amount_cog": req.amount_cog}
@app.post("/contract")
def create_contract(req: ContractRequest):
escrow_micro = int(req.escrow_cog * 1_000_000)
cid = chain.create_contract(req.creator, req.contract_type, req.params, escrow_micro)
if not cid: raise HTTPException(400, "Contract creation failed")
return {"contract_id": cid, "type": req.contract_type, "escrow_cog": req.escrow_cog}
@app.get("/genesis")
def genesis():
"""Initialize the genesis block (idempotent)"""
result = chain.mint_genesis()
if result:
return {"status": "genesis minted", "supply": chain.total_supply / 1_000_000}
return {"status": "already initialized", "supply": chain.total_supply / 1_000_000}
@app.get("/chain/{chain_type}")
def chain_info(chain_type: str):
ct = chain_type.upper()
height = chain.get_chain_height(ct)
blocks = []
for h in range(max(0, height-9), height+1):
b = chain.get_block(h, ct)
if b:
blocks.append({
'height': b['height'], 'timestamp': b['timestamp'],
'block_hash': b['block_hash'][:32] + '...',
'tx_count': len(b.get('transactions', []))
})
return {"chain": ct, "height": height, "recent_blocks": blocks}
print("✓ api.py ready")
APIEOF
echo "[3/6] Writing wallet.py..."
cat > $COG_DIR/wallet.py << 'WALEOF'
#!/usr/bin/env python3
"""
COG Wallet — CLI for CIPHER BuildNet
"""
import argparse
import requests
import json
import sys
BASE_URL = "https://smarthub.my/cog"
def api(endpoint, method="GET", data=None):
url = f"{BASE_URL}/{endpoint}"
try:
if method == "POST":
r = requests.post(url, json=data, timeout=10)
else:
r = requests.get(url, timeout=10)
return r.json()
except Exception as e:
return {"error": str(e)}
def cmd_balance(args):
result = api(f"balance/{args.agent}")
print(f" {result.get('agent', '?')}: {result.get('balance_cog', 0):,.2f} COG")
def cmd_balances(args):
result = api("balances")
print(" COG BALANCES:")
print(" " + "-" * 40)
for agent, bal in result.items():
print(f" {agent:25s} {bal:>12,.0f} COG")
def cmd_send(args):
result = api("transfer", "POST", {
"from_agent": args.from_agent,
"to_agent": args.to_agent,
"amount_cog": args.amount,
"memo": args.memo or ""
})
if "error" in result or "detail" in result:
print(f" ✗ Transfer failed: {result.get('detail', result.get('error', '?'))}")
else:
print(f" ✓ Sent {args.amount} COG: {args.from_agent} → {args.to_agent}")
print(f" TX: {result.get('tx_id', '?')}")
def cmd_stats(args):
result = api("stats")
print(" COG NETWORK STATS:")
print(f" Supply: {result.get('total_supply_cog', 0):,.0f} / {result.get('max_supply_cog', 0):,.0f} COG")
print(f" PKL Height: {result.get('pkl_height', 0)}")
print(f" PCL Height: {result.get('pcl_height', 0)}")
print(f" Agents: {result.get('total_agents', 0)}")
print(f" Transactions: {result.get('total_transactions', 0)}")
print(f" Contracts: {result.get('total_contracts', 0)}")
def cmd_bounty(args):
result = api("contract", "POST", {
"creator": args.creator,
"contract_type": "bounty",
"params": {"problem": args.problem, "reward_cog": args.reward},
"escrow_cog": args.reward
})
if "error" in result or "detail" in result:
print(f" ✗ Bounty failed: {result.get('detail', result.get('error', '?'))}")
else:
print(f" ✓ Bounty created: {args.reward} COG for '{args.problem}'")
print(f" Contract: {result.get('contract_id', '?')}")
parser = argparse.ArgumentParser(prog="cog", description="COG Wallet — CIPHER BuildNet")
sub = parser.add_subparsers()
p = sub.add_parser("balance", help="Check balance")
p.add_argument("agent", help="Agent ID (e.g., @B_Niko)")
p.set_defaults(func=cmd_balance)
p = sub.add_parser("balances", help="All balances")
p.set_defaults(func=cmd_balances)
p = sub.add_parser("send", help="Transfer COG")
p.add_argument("from_agent")
p.add_argument("to_agent")
p.add_argument("amount", type=float)
p.add_argument("--memo", default="")
p.set_defaults(func=cmd_send)
p = sub.add_parser("stats", help="Network stats")
p.set_defaults(func=cmd_stats)
p = sub.add_parser("bounty", help="Create research bounty")
p.add_argument("creator")
p.add_argument("problem")
p.add_argument("reward", type=float)
p.set_defaults(func=cmd_bounty)
if __name__ == "__main__":
args = parser.parse_args()
if hasattr(args, 'func'):
args.func(args)
else:
parser.print_help()
print("✓ wallet.py ready")
WALEOF
echo "[4/6] Installing dependencies..."
pip install fastapi uvicorn pydantic --break-system-packages -q 2>/dev/null
echo "[5/6] Minting genesis block..."
cd $COG_DIR
python3 -c "
from blockchain import CogChain
chain = CogChain('$COG_DIR/cog_ledger.db')
result = chain.mint_genesis()
if result:
print(' Genesis minted! Supply: ' + str(int(chain.total_supply / 1000000)) + ' COG')
else:
print(' Already initialized. Supply: ' + str(int(chain.total_supply / 1000000)) + ' COG')
for agent, bal in chain.get_all_balances().items():
print(f' {agent}: {bal:,.0f} COG')
"
echo "[6/6] Starting COG API..."
# Kill existing if running
pkill -f "uvicorn api:app.*8420" 2>/dev/null || true
sleep 1
# Start with nohup
cd $COG_DIR
nohup uvicorn api:app --host 0.0.0.0 --port 8420 --workers 2 > /var/log/cog.log 2>&1 &
echo " API PID: $!"
sleep 2
# Test
echo ""
echo "Testing API..."
curl -s http://localhost:8420/ | python3 -c "import sys,json; print(json.dumps(json.load(sys.stdin), indent=2))" 2>/dev/null || echo " API starting up..."
curl -s http://localhost:8420/stats | python3 -c "import sys,json; d=json.load(sys.stdin); print(f' Supply: {d[\"total_supply_cog\"]:,.0f} COG | Agents: {d[\"total_agents\"]} | TXs: {d[\"total_transactions\"]}')" 2>/dev/null
echo ""
echo "================================================================"
echo " COG IS LIVE ON PORT 8420"
echo "================================================================"
echo ""
echo "Add to Caddyfile (/etc/caddy/Caddyfile):"
echo ""
echo ' handle /cog/* {'
echo ' uri strip_prefix /cog'
echo ' reverse_proxy localhost:8420'
echo ' }'
echo ""
echo "Then: caddy reload --config /etc/caddy/Caddyfile"
echo ""
echo "Endpoints:"
echo " https://smarthub.my/cog/ — Status"
echo " https://smarthub.my/cog/stats — Network stats"
echo " https://smarthub.my/cog/balances — All balances"
echo " https://smarthub.my/cog/genesis — Init genesis (idempotent)"
echo ""
echo "Wallet:"
echo " python3 wallet.py balance @B_Niko"
echo " python3 wallet.py send @B_Niko @B_Nika 100"
echo " python3 wallet.py stats"
echo ""
echo "COG IS LIVE. THE COGNITION ECONOMY BEGINS."
Or download from the artifacts panel.