chore: initialize monorepo with project scaffolding, configs, and CI setup

This commit is contained in:
oib
2025-09-27 06:05:25 +02:00
commit c1926136fb
171 changed files with 13708 additions and 0 deletions

View File

@ -0,0 +1,5 @@
"""AITBC blockchain node package."""
from .app import create_app
__all__ = ["create_app"]

View File

@ -0,0 +1,33 @@
from __future__ import annotations
from contextlib import asynccontextmanager
from fastapi import APIRouter, FastAPI
from fastapi.responses import PlainTextResponse
from .config import settings
from .database import init_db
from .metrics import metrics_registry
from .rpc.router import router as rpc_router
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
def create_app() -> FastAPI:
app = FastAPI(title="AITBC Blockchain Node", version="0.1.0", lifespan=lifespan)
app.include_router(rpc_router, prefix="/rpc", tags=["rpc"])
metrics_router = APIRouter()
@metrics_router.get("/metrics", response_class=PlainTextResponse, tags=["metrics"], summary="Prometheus metrics")
async def metrics() -> str:
return metrics_registry.render_prometheus()
app.include_router(metrics_router)
return app
app = create_app()

View File

@ -0,0 +1,30 @@
from __future__ import annotations
from pathlib import Path
from typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
class ChainSettings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=False)
chain_id: str = "ait-devnet"
db_path: Path = Path("./data/chain.db")
rpc_bind_host: str = "127.0.0.1"
rpc_bind_port: int = 8080
p2p_bind_host: str = "0.0.0.0"
p2p_bind_port: int = 7070
proposer_id: str = "ait-devnet-proposer"
proposer_key: Optional[str] = None
mint_per_unit: int = 1000
coordinator_ratio: float = 0.05
block_time_seconds: int = 2
settings = ChainSettings()

View File

@ -0,0 +1,5 @@
from __future__ import annotations
from .poa import PoAProposer, ProposerConfig
__all__ = ["PoAProposer", "ProposerConfig"]

View File

@ -0,0 +1,140 @@
from __future__ import annotations
import asyncio
import hashlib
from dataclasses import dataclass
from datetime import datetime
from typing import Callable, ContextManager, Optional
from sqlmodel import Session, select
from ..logging import get_logger
from ..metrics import metrics_registry
from ..models import Block
@dataclass
class ProposerConfig:
chain_id: str
proposer_id: str
interval_seconds: int
class PoAProposer:
def __init__(
self,
*,
config: ProposerConfig,
session_factory: Callable[[], ContextManager[Session]],
) -> None:
self._config = config
self._session_factory = session_factory
self._logger = get_logger(__name__)
self._stop_event = asyncio.Event()
self._task: Optional[asyncio.Task[None]] = None
async def start(self) -> None:
if self._task is not None:
return
self._logger.info("Starting PoA proposer loop", extra={"interval": self._config.interval_seconds})
self._ensure_genesis_block()
self._stop_event.clear()
self._task = asyncio.create_task(self._run_loop(), name="poa-proposer-loop")
async def stop(self) -> None:
if self._task is None:
return
self._logger.info("Stopping PoA proposer loop")
self._stop_event.set()
await self._task
self._task = None
async def _run_loop(self) -> None:
while not self._stop_event.is_set():
await self._wait_until_next_slot()
if self._stop_event.is_set():
break
try:
self._propose_block()
except Exception as exc: # pragma: no cover - defensive logging
self._logger.exception("Failed to propose block", extra={"error": str(exc)})
async def _wait_until_next_slot(self) -> None:
head = self._fetch_chain_head()
if head is None:
return
now = datetime.utcnow()
elapsed = (now - head.timestamp).total_seconds()
sleep_for = max(self._config.interval_seconds - elapsed, 0)
if sleep_for <= 0:
return
try:
await asyncio.wait_for(self._stop_event.wait(), timeout=sleep_for)
except asyncio.TimeoutError:
return
def _propose_block(self) -> None:
with self._session_factory() as session:
head = session.exec(select(Block).order_by(Block.height.desc()).limit(1)).first()
next_height = 0
parent_hash = "0x00"
if head is not None:
next_height = head.height + 1
parent_hash = head.hash
timestamp = datetime.utcnow()
block_hash = self._compute_block_hash(next_height, parent_hash, timestamp)
block = Block(
height=next_height,
hash=block_hash,
parent_hash=parent_hash,
proposer=self._config.proposer_id,
timestamp=timestamp,
tx_count=0,
state_root=None,
)
session.add(block)
session.commit()
metrics_registry.increment("blocks_proposed_total")
metrics_registry.set_gauge("chain_head_height", float(next_height))
self._logger.info(
"Proposed block",
extra={
"height": next_height,
"hash": block_hash,
"parent_hash": parent_hash,
"timestamp": timestamp.isoformat(),
},
)
def _ensure_genesis_block(self) -> None:
with self._session_factory() as session:
head = session.exec(select(Block).order_by(Block.height.desc()).limit(1)).first()
if head is not None:
return
timestamp = datetime.utcnow()
genesis_hash = self._compute_block_hash(0, "0x00", timestamp)
genesis = Block(
height=0,
hash=genesis_hash,
parent_hash="0x00",
proposer=self._config.proposer_id,
timestamp=timestamp,
tx_count=0,
state_root=None,
)
session.add(genesis)
session.commit()
self._logger.info("Created genesis block", extra={"hash": genesis_hash})
def _fetch_chain_head(self) -> Optional[Block]:
with self._session_factory() as session:
return session.exec(select(Block).order_by(Block.height.desc()).limit(1)).first()
def _compute_block_hash(self, height: int, parent_hash: str, timestamp: datetime) -> str:
payload = f"{self._config.chain_id}|{height}|{parent_hash}|{timestamp.isoformat()}".encode()
return "0x" + hashlib.sha256(payload).hexdigest()

View File

@ -0,0 +1,20 @@
from __future__ import annotations
from contextlib import contextmanager
from sqlmodel import Session, SQLModel, create_engine
from .config import settings
_engine = create_engine(f"sqlite:///{settings.db_path}", echo=False)
def init_db() -> None:
settings.db_path.parent.mkdir(parents=True, exist_ok=True)
SQLModel.metadata.create_all(_engine)
@contextmanager
def session_scope() -> Session:
with Session(_engine) as session:
yield session

View File

@ -0,0 +1,71 @@
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any, Optional
import json
class JsonFormatter(logging.Formatter):
RESERVED = {
"name",
"msg",
"args",
"levelname",
"levelno",
"pathname",
"filename",
"module",
"exc_info",
"exc_text",
"stack_info",
"lineno",
"funcName",
"created",
"msecs",
"relativeCreated",
"thread",
"threadName",
"process",
"processName",
}
def format(self, record: logging.LogRecord) -> str: # type: ignore[override]
payload: dict[str, Any] = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
for key, value in record.__dict__.items():
if key in self.RESERVED or key.startswith("_"):
continue
payload[key] = value
if record.exc_info:
payload["exc_info"] = self.formatException(record.exc_info)
if record.stack_info:
payload["stack"] = record.stack_info
return json.dumps(payload, default=str)
def configure_logging(level: Optional[str] = None) -> None:
log_level = getattr(logging, (level or "INFO").upper(), logging.INFO)
root = logging.getLogger()
if root.handlers:
return
handler = logging.StreamHandler()
formatter = JsonFormatter()
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(log_level)
def get_logger(name: str) -> logging.Logger:
if not logging.getLogger().handlers:
configure_logging()
return logging.getLogger(name)

View File

@ -0,0 +1,72 @@
from __future__ import annotations
import asyncio
from contextlib import asynccontextmanager
from typing import Optional
from .config import settings
from .consensus import PoAProposer, ProposerConfig
from .database import init_db, session_scope
from .logging import get_logger
logger = get_logger(__name__)
class BlockchainNode:
def __init__(self) -> None:
self._stop_event = asyncio.Event()
self._proposer: Optional[PoAProposer] = None
async def start(self) -> None:
logger.info("Starting blockchain node", extra={"chain_id": settings.chain_id})
init_db()
self._start_proposer()
try:
await self._stop_event.wait()
finally:
await self._shutdown()
async def stop(self) -> None:
logger.info("Stopping blockchain node")
self._stop_event.set()
await self._shutdown()
def _start_proposer(self) -> None:
if self._proposer is not None:
return
proposer_config = ProposerConfig(
chain_id=settings.chain_id,
proposer_id=settings.proposer_id,
interval_seconds=settings.block_time_seconds,
)
self._proposer = PoAProposer(config=proposer_config, session_factory=session_scope)
asyncio.create_task(self._proposer.start())
async def _shutdown(self) -> None:
if self._proposer is None:
return
await self._proposer.stop()
self._proposer = None
@asynccontextmanager
async def node_app() -> asyncio.AbstractAsyncContextManager[BlockchainNode]: # type: ignore[override]
node = BlockchainNode()
try:
yield node
finally:
await node.stop()
def run() -> None:
asyncio.run(_run())
async def _run() -> None:
async with node_app() as node:
await node.start()
if __name__ == "__main__": # pragma: no cover
run()

View File

@ -0,0 +1,47 @@
from __future__ import annotations
import hashlib
import json
import time
from dataclasses import dataclass
from threading import Lock
from typing import Any, Dict, List
from .metrics import metrics_registry
@dataclass(frozen=True)
class PendingTransaction:
tx_hash: str
content: Dict[str, Any]
received_at: float
class InMemoryMempool:
def __init__(self) -> None:
self._lock = Lock()
self._transactions: Dict[str, PendingTransaction] = {}
def add(self, tx: Dict[str, Any]) -> str:
tx_hash = self._compute_hash(tx)
entry = PendingTransaction(tx_hash=tx_hash, content=tx, received_at=time.time())
with self._lock:
self._transactions[tx_hash] = entry
metrics_registry.set_gauge("mempool_size", float(len(self._transactions)))
return tx_hash
def list_transactions(self) -> List[PendingTransaction]:
with self._lock:
return list(self._transactions.values())
def _compute_hash(self, tx: Dict[str, Any]) -> str:
canonical = json.dumps(tx, sort_keys=True, separators=(",", ":")).encode()
digest = hashlib.sha256(canonical).hexdigest()
return f"0x{digest}"
_MEMPOOL = InMemoryMempool()
def get_mempool() -> InMemoryMempool:
return _MEMPOOL

View File

@ -0,0 +1,40 @@
from __future__ import annotations
from dataclasses import dataclass
from threading import Lock
from typing import Dict
@dataclass
class MetricValue:
name: str
value: float
class MetricsRegistry:
def __init__(self) -> None:
self._counters: Dict[str, float] = {}
self._gauges: Dict[str, float] = {}
self._lock = Lock()
def increment(self, name: str, amount: float = 1.0) -> None:
with self._lock:
self._counters[name] = self._counters.get(name, 0.0) + amount
def set_gauge(self, name: str, value: float) -> None:
with self._lock:
self._gauges[name] = value
def render_prometheus(self) -> str:
with self._lock:
lines: list[str] = []
for name, value in sorted(self._counters.items()):
lines.append(f"# TYPE {name} counter")
lines.append(f"{name} {value}")
for name, value in sorted(self._gauges.items()):
lines.append(f"# TYPE {name} gauge")
lines.append(f"{name} {value}")
return "\n".join(lines) + "\n"
metrics_registry = MetricsRegistry()

View File

@ -0,0 +1,116 @@
from __future__ import annotations
from datetime import datetime
import re
from typing import List, Optional
from pydantic import field_validator
from sqlalchemy import Column
from sqlalchemy.types import JSON
from sqlmodel import Field, Relationship, SQLModel
_HEX_PATTERN = re.compile(r"^(0x)?[0-9a-fA-F]+$")
def _validate_hex(value: str, field_name: str) -> str:
if not _HEX_PATTERN.fullmatch(value):
raise ValueError(f"{field_name} must be a hex-encoded string")
return value.lower()
def _validate_optional_hex(value: Optional[str], field_name: str) -> Optional[str]:
if value is None:
return value
return _validate_hex(value, field_name)
class Block(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
height: int = Field(index=True, unique=True)
hash: str = Field(index=True, unique=True)
parent_hash: str
proposer: str
timestamp: datetime = Field(default_factory=datetime.utcnow, index=True)
tx_count: int = 0
state_root: Optional[str] = None
transactions: List["Transaction"] = Relationship(back_populates="block")
receipts: List["Receipt"] = Relationship(back_populates="block")
@field_validator("hash", mode="before")
@classmethod
def _hash_is_hex(cls, value: str) -> str:
return _validate_hex(value, "Block.hash")
@field_validator("parent_hash", mode="before")
@classmethod
def _parent_hash_is_hex(cls, value: str) -> str:
return _validate_hex(value, "Block.parent_hash")
@field_validator("state_root", mode="before")
@classmethod
def _state_root_is_hex(cls, value: Optional[str]) -> Optional[str]:
return _validate_optional_hex(value, "Block.state_root")
class Transaction(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
tx_hash: str = Field(index=True, unique=True)
block_height: Optional[int] = Field(
default=None,
index=True,
foreign_key="block.height",
)
sender: str
recipient: str
payload: dict = Field(
default_factory=dict,
sa_column=Column(JSON, nullable=False),
)
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
block: Optional[Block] = Relationship(back_populates="transactions")
@field_validator("tx_hash", mode="before")
@classmethod
def _tx_hash_is_hex(cls, value: str) -> str:
return _validate_hex(value, "Transaction.tx_hash")
class Receipt(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
job_id: str = Field(index=True)
receipt_id: str = Field(index=True, unique=True)
block_height: Optional[int] = Field(
default=None,
index=True,
foreign_key="block.height",
)
payload: dict = Field(
default_factory=dict,
sa_column=Column(JSON, nullable=False),
)
miner_signature: dict = Field(
default_factory=dict,
sa_column=Column(JSON, nullable=False),
)
coordinator_attestations: list[dict] = Field(
default_factory=list,
sa_column=Column(JSON, nullable=False),
)
minted_amount: Optional[int] = None
recorded_at: datetime = Field(default_factory=datetime.utcnow, index=True)
block: Optional[Block] = Relationship(back_populates="receipts")
@field_validator("receipt_id", mode="before")
@classmethod
def _receipt_id_is_hex(cls, value: str) -> str:
return _validate_hex(value, "Receipt.receipt_id")
class Account(SQLModel, table=True):
address: str = Field(primary_key=True)
balance: int = 0
nonce: int = 0
updated_at: datetime = Field(default_factory=datetime.utcnow)

View File

@ -0,0 +1,184 @@
from __future__ import annotations
import json
from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field, model_validator
from sqlmodel import select
from ..database import session_scope
from ..mempool import get_mempool
from ..metrics import metrics_registry
from ..models import Account, Block, Receipt, Transaction
router = APIRouter()
def _serialize_receipt(receipt: Receipt) -> Dict[str, Any]:
return {
"receipt_id": receipt.receipt_id,
"job_id": receipt.job_id,
"payload": receipt.payload,
"miner_signature": receipt.miner_signature,
"coordinator_attestations": receipt.coordinator_attestations,
"minted_amount": receipt.minted_amount,
"recorded_at": receipt.recorded_at.isoformat(),
}
class TransactionRequest(BaseModel):
type: str = Field(description="Transaction type, e.g. TRANSFER or RECEIPT_CLAIM")
sender: str
nonce: int
fee: int = Field(ge=0)
payload: Dict[str, Any]
sig: Optional[str] = Field(default=None, description="Signature payload")
@model_validator(mode="after")
def normalize_type(self) -> "TransactionRequest": # type: ignore[override]
normalized = self.type.upper()
if normalized not in {"TRANSFER", "RECEIPT_CLAIM"}:
raise ValueError(f"unsupported transaction type: {self.type}")
self.type = normalized
return self
class ReceiptSubmissionRequest(BaseModel):
sender: str
nonce: int
fee: int = Field(ge=0)
payload: Dict[str, Any]
sig: Optional[str] = None
class EstimateFeeRequest(BaseModel):
type: Optional[str] = None
payload: Dict[str, Any] = Field(default_factory=dict)
class MintFaucetRequest(BaseModel):
address: str
amount: int = Field(gt=0)
@router.get("/head", summary="Get current chain head")
async def get_head() -> Dict[str, Any]:
with session_scope() as session:
result = session.exec(select(Block).order_by(Block.height.desc()).limit(1)).first()
if result is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no blocks yet")
return {
"height": result.height,
"hash": result.hash,
"timestamp": result.timestamp.isoformat(),
"tx_count": result.tx_count,
}
@router.get("/blocks/{height}", summary="Get block by height")
async def get_block(height: int) -> Dict[str, Any]:
with session_scope() as session:
block = session.exec(select(Block).where(Block.height == height)).first()
if block is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="block not found")
return {
"height": block.height,
"hash": block.hash,
"parent_hash": block.parent_hash,
"timestamp": block.timestamp.isoformat(),
"tx_count": block.tx_count,
"state_root": block.state_root,
}
@router.get("/tx/{tx_hash}", summary="Get transaction by hash")
async def get_transaction(tx_hash: str) -> Dict[str, Any]:
with session_scope() as session:
tx = session.exec(select(Transaction).where(Transaction.tx_hash == tx_hash)).first()
if tx is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="transaction not found")
return {
"tx_hash": tx.tx_hash,
"block_height": tx.block_height,
"sender": tx.sender,
"recipient": tx.recipient,
"payload": tx.payload,
"created_at": tx.created_at.isoformat(),
}
@router.get("/receipts/{receipt_id}", summary="Get receipt by ID")
async def get_receipt(receipt_id: str) -> Dict[str, Any]:
with session_scope() as session:
receipt = session.exec(select(Receipt).where(Receipt.receipt_id == receipt_id)).first()
if receipt is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="receipt not found")
return _serialize_receipt(receipt)
@router.get("/getBalance/{address}", summary="Get account balance")
async def get_balance(address: str) -> Dict[str, Any]:
with session_scope() as session:
account = session.get(Account, address)
if account is None:
return {"address": address, "balance": 0, "nonce": 0}
return {
"address": account.address,
"balance": account.balance,
"nonce": account.nonce,
"updated_at": account.updated_at.isoformat(),
}
@router.post("/sendTx", summary="Submit a new transaction")
async def send_transaction(request: TransactionRequest) -> Dict[str, Any]:
mempool = get_mempool()
tx_dict = request.model_dump()
tx_hash = mempool.add(tx_dict)
metrics_registry.increment("rpc_send_tx_total")
return {"tx_hash": tx_hash}
@router.post("/submitReceipt", summary="Submit receipt claim transaction")
async def submit_receipt(request: ReceiptSubmissionRequest) -> Dict[str, Any]:
tx_payload = {
"type": "RECEIPT_CLAIM",
"sender": request.sender,
"nonce": request.nonce,
"fee": request.fee,
"payload": request.payload,
"sig": request.sig,
}
tx_request = TransactionRequest.model_validate(tx_payload)
metrics_registry.increment("rpc_submit_receipt_total")
return await send_transaction(tx_request)
@router.post("/estimateFee", summary="Estimate transaction fee")
async def estimate_fee(request: EstimateFeeRequest) -> Dict[str, Any]:
base_fee = 10
per_byte = 1
payload_bytes = len(json.dumps(request.payload, sort_keys=True, separators=(",", ":")).encode())
estimated_fee = base_fee + per_byte * payload_bytes
tx_type = (request.type or "TRANSFER").upper()
return {
"type": tx_type,
"base_fee": base_fee,
"payload_bytes": payload_bytes,
"estimated_fee": estimated_fee,
}
@router.post("/admin/mintFaucet", summary="Mint devnet funds to an address")
async def mint_faucet(request: MintFaucetRequest) -> Dict[str, Any]:
with session_scope() as session:
account = session.get(Account, request.address)
if account is None:
account = Account(address=request.address, balance=request.amount)
session.add(account)
else:
account.balance += request.amount
session.commit()
updated_balance = account.balance
return {"address": request.address, "balance": updated_balance}