feat: add fraud detection validator
This commit is contained in:
@@ -6,6 +6,8 @@ replace this adapter later without changing gateway or tracker call sites.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -49,6 +51,33 @@ class ComputeAttribution:
|
||||
return self.layer_count * self.tokens
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValidationEvent:
|
||||
"""Completed inference data consumed by fraud validators."""
|
||||
|
||||
index: int
|
||||
session_id: str
|
||||
model: str
|
||||
messages: list[dict]
|
||||
observed_output: str
|
||||
route_nodes: list[dict]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlashReceipt:
|
||||
"""Local slash transaction receipt."""
|
||||
|
||||
signature: str
|
||||
cluster: str
|
||||
wallet_address: str
|
||||
slash_amount: int
|
||||
stake_before: int
|
||||
stake_after: int
|
||||
strike_count: int
|
||||
banned: bool
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SettlementResult:
|
||||
"""Summary returned by an epoch settlement transaction."""
|
||||
@@ -64,6 +93,8 @@ class _LocalContractState:
|
||||
registry: dict[str, RegistryWallet] = field(default_factory=dict)
|
||||
api_keys: dict[str, ApiKeyBalance] = field(default_factory=dict)
|
||||
attributions: list[ComputeAttribution] = field(default_factory=list)
|
||||
validation_events: list[ValidationEvent] = field(default_factory=list)
|
||||
slash_receipts: list[SlashReceipt] = field(default_factory=list)
|
||||
token_balances: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -98,6 +129,46 @@ class RegistryContract:
|
||||
)
|
||||
return {"signature": f"local-strike-{wallet_address}", "cluster": self._cluster}
|
||||
|
||||
def submit_slash_proof(
|
||||
self,
|
||||
*,
|
||||
wallet_address: str,
|
||||
slash_amount: int,
|
||||
strike_threshold: int = 3,
|
||||
reason: str = "fraudulent inference output",
|
||||
webhook_url: str | None = None,
|
||||
) -> SlashReceipt:
|
||||
if not wallet_address:
|
||||
raise ValueError("wallet_address is required")
|
||||
if slash_amount <= 0:
|
||||
raise ValueError("slash_amount must be positive")
|
||||
if strike_threshold <= 0:
|
||||
raise ValueError("strike_threshold must be positive")
|
||||
|
||||
current = self.get_wallet(wallet_address)
|
||||
stake_after = max(0, current.stake_balance - slash_amount)
|
||||
strike_count = current.strike_count + 1
|
||||
banned = current.banned or strike_count >= strike_threshold
|
||||
self._state.registry[wallet_address] = RegistryWallet(
|
||||
stake_balance=stake_after,
|
||||
strike_count=strike_count,
|
||||
banned=banned,
|
||||
)
|
||||
receipt = SlashReceipt(
|
||||
signature=f"local-slash-{wallet_address}-{len(self._state.slash_receipts) + 1}",
|
||||
cluster=self._cluster,
|
||||
wallet_address=wallet_address,
|
||||
slash_amount=slash_amount,
|
||||
stake_before=current.stake_balance,
|
||||
stake_after=stake_after,
|
||||
strike_count=strike_count,
|
||||
banned=banned,
|
||||
reason=reason,
|
||||
)
|
||||
self._state.slash_receipts.append(receipt)
|
||||
_notify_slash(receipt, webhook_url)
|
||||
return receipt
|
||||
|
||||
def ban_wallet(self, wallet_address: str) -> dict:
|
||||
current = self.get_wallet(wallet_address)
|
||||
self._state.registry[wallet_address] = RegistryWallet(
|
||||
@@ -114,6 +185,49 @@ class RegistryContract:
|
||||
return wallet.stake_balance >= minimum_stake
|
||||
|
||||
|
||||
class ValidationContract:
|
||||
"""Validation event log consumed by the optimistic fraud detector."""
|
||||
|
||||
def __init__(self, state: _LocalContractState) -> None:
|
||||
self._state = state
|
||||
|
||||
def record_completed_inference(
|
||||
self,
|
||||
*,
|
||||
session_id: str,
|
||||
model: str,
|
||||
messages: list[dict],
|
||||
observed_output: str,
|
||||
route_nodes: list[dict],
|
||||
) -> ValidationEvent:
|
||||
if not session_id:
|
||||
raise ValueError("session_id is required")
|
||||
if not model:
|
||||
raise ValueError("model is required")
|
||||
if not isinstance(messages, list):
|
||||
raise ValueError("messages must be a list")
|
||||
if not isinstance(observed_output, str):
|
||||
raise ValueError("observed_output must be a string")
|
||||
if not isinstance(route_nodes, list):
|
||||
raise ValueError("route_nodes must be a list")
|
||||
event = ValidationEvent(
|
||||
index=len(self._state.validation_events),
|
||||
session_id=session_id,
|
||||
model=model,
|
||||
messages=[dict(message) for message in messages],
|
||||
observed_output=observed_output,
|
||||
route_nodes=[dict(node) for node in route_nodes],
|
||||
)
|
||||
self._state.validation_events.append(event)
|
||||
return event
|
||||
|
||||
def list_completed_inferences(self, *, after_index: int = -1) -> list[ValidationEvent]:
|
||||
return [
|
||||
event for event in self._state.validation_events
|
||||
if event.index > after_index
|
||||
]
|
||||
|
||||
|
||||
class PaymentContract:
|
||||
"""Payment wrapper for funded API keys and compute attribution."""
|
||||
|
||||
@@ -297,6 +411,7 @@ class LocalSolanaContracts:
|
||||
self.cluster = cluster
|
||||
self._state = _LocalContractState()
|
||||
self.registry = RegistryContract(self._state, cluster)
|
||||
self.validation = ValidationContract(self._state)
|
||||
self.payment = PaymentContract(self._state, cluster, starting_credit_lamports)
|
||||
self.settlement = SettlementContract(
|
||||
self._state,
|
||||
@@ -305,6 +420,35 @@ class LocalSolanaContracts:
|
||||
)
|
||||
|
||||
|
||||
def _notify_slash(receipt: SlashReceipt, webhook_url: str | None) -> None:
|
||||
message = (
|
||||
f"WARNING: node {receipt.wallet_address} slashed "
|
||||
f"by {receipt.slash_amount} lamports; strikes={receipt.strike_count}; "
|
||||
f"banned={receipt.banned}; reason={receipt.reason}"
|
||||
)
|
||||
print(message, flush=True)
|
||||
if not webhook_url:
|
||||
return
|
||||
payload = json.dumps({
|
||||
"event": "node_slashed",
|
||||
"wallet_address": receipt.wallet_address,
|
||||
"slash_amount": receipt.slash_amount,
|
||||
"strike_count": receipt.strike_count,
|
||||
"banned": receipt.banned,
|
||||
"reason": receipt.reason,
|
||||
}).encode()
|
||||
req = urllib.request.Request(
|
||||
webhook_url,
|
||||
data=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=2).read()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ApiKeyBalance",
|
||||
"ComputeAttribution",
|
||||
@@ -314,4 +458,7 @@ __all__ = [
|
||||
"RegistryWallet",
|
||||
"SettlementContract",
|
||||
"SettlementResult",
|
||||
"SlashReceipt",
|
||||
"ValidationContract",
|
||||
"ValidationEvent",
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user