#![allow(missing_docs)]
use std::mem::size_of;
use ed25519_dalek::{Signature, SigningKey, VerifyingKey, Signer};
use subtle::ConstantTimeEq;
pub type VertexId = u16;
pub type EdgeId = u16;
pub type FixedWeight = u32;
pub type TileId = u8;
pub type LogEValue = i32;
pub const MAX_PATCH_VERTICES: usize = 256;
pub const MAX_PATCH_EDGES: usize = 1024;
pub const MAX_DEGREE: usize = 32;
pub const SYNDROME_BUFFER_DEPTH: usize = 1024;
pub const MAX_BOUNDARY_CANDIDATES: usize = 64;
const CACHE_LINE_SIZE: usize = 64;
const LOG_E_STRONG: LogEValue = 282944;
const LOG_E_VERY_STRONG: LogEValue = 436906;
pub const NUM_WORKERS: usize = 255;
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct SyndromeDelta {
pub source: VertexId,
pub target: VertexId,
pub value: u16,
pub flags: u16,
}
impl SyndromeDelta {
pub const FLAG_EDGE_ADD: u16 = 0x0001;
pub const FLAG_EDGE_REMOVE: u16 = 0x0002;
pub const FLAG_WEIGHT_UPDATE: u16 = 0x0004;
pub const FLAG_SYNDROME: u16 = 0x0008;
pub const FLAG_BOUNDARY: u16 = 0x0010;
#[inline]
pub const fn new(source: VertexId, target: VertexId, value: u16) -> Self {
Self {
source,
target,
value,
flags: Self::FLAG_SYNDROME,
}
}
#[inline]
pub const fn edge_add(source: VertexId, target: VertexId, weight: u16) -> Self {
Self {
source,
target,
value: weight,
flags: Self::FLAG_EDGE_ADD,
}
}
#[inline]
pub const fn edge_remove(source: VertexId, target: VertexId) -> Self {
Self {
source,
target,
value: 0,
flags: Self::FLAG_EDGE_REMOVE,
}
}
#[inline]
pub const fn is_syndrome(&self) -> bool {
self.flags & Self::FLAG_SYNDROME != 0
}
#[inline]
pub const fn is_edge_modification(&self) -> bool {
self.flags & (Self::FLAG_EDGE_ADD | Self::FLAG_EDGE_REMOVE | Self::FLAG_WEIGHT_UPDATE) != 0
}
}
#[derive(Debug, Clone, Copy, Default)]
#[repr(C, align(8))]
pub struct Vertex {
pub degree: u8,
pub flags: u8,
pub component: u16,
pub adj_start: u16,
pub syndrome_acc: u16,
}
impl Vertex {
pub const FLAG_ACTIVE: u8 = 0x01;
pub const FLAG_BOUNDARY: u8 = 0x02;
pub const FLAG_UNHEALTHY: u8 = 0x04;
pub const FLAG_GHOST: u8 = 0x08;
#[inline]
pub const fn new() -> Self {
Self {
degree: 0,
flags: Self::FLAG_ACTIVE,
component: 0,
adj_start: 0xFFFF,
syndrome_acc: 0,
}
}
#[inline(always)]
pub const fn is_active(&self) -> bool {
self.flags & Self::FLAG_ACTIVE != 0
}
#[inline(always)]
pub const fn is_boundary(&self) -> bool {
self.flags & Self::FLAG_BOUNDARY != 0
}
}
#[derive(Debug, Clone, Copy, Default)]
#[repr(C, align(8))]
pub struct Edge {
pub source: VertexId,
pub target: VertexId,
pub weight: FixedWeight,
}
impl Edge {
#[inline]
pub const fn new(source: VertexId, target: VertexId, weight: FixedWeight) -> Self {
Self { source, target, weight }
}
}
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct AdjEntry {
pub neighbor: VertexId,
pub edge_id: EdgeId,
}
#[derive(Debug)]
#[repr(C, align(64))]
pub struct PatchGraph {
pub num_vertices: u16,
pub num_edges: u16,
pub num_components: u16,
pub generation: u16,
pub status: u16,
pub free_edge_head: u16,
_pad: [u8; 52],
pub vertices: [Vertex; MAX_PATCH_VERTICES],
pub edges: [Edge; MAX_PATCH_EDGES],
pub adjacency: [[AdjEntry; MAX_DEGREE]; MAX_PATCH_VERTICES],
}
impl Default for PatchGraph {
fn default() -> Self {
Self::new()
}
}
impl PatchGraph {
pub const STATUS_VALID: u16 = 0x0001;
pub const STATUS_DIRTY: u16 = 0x0002;
pub const STATUS_CONNECTED: u16 = 0x0004;
pub const STATUS_BOUNDARY_MOVED: u16 = 0x0008;
pub const fn new() -> Self {
Self {
num_vertices: 0,
num_edges: 0,
num_components: 0,
generation: 0,
status: Self::STATUS_VALID,
free_edge_head: 0xFFFF,
_pad: [0; 52],
vertices: [Vertex {
degree: 0,
flags: 0,
component: 0,
adj_start: 0xFFFF,
syndrome_acc: 0,
}; MAX_PATCH_VERTICES],
edges: [Edge {
source: 0,
target: 0,
weight: 0,
}; MAX_PATCH_EDGES],
adjacency: [[AdjEntry { neighbor: 0, edge_id: 0 }; MAX_DEGREE]; MAX_PATCH_VERTICES],
}
}
pub fn apply_delta(&mut self, delta: &SyndromeDelta) {
if delta.flags & SyndromeDelta::FLAG_EDGE_ADD != 0 {
self.add_edge(delta.source, delta.target, delta.value as FixedWeight);
} else if delta.flags & SyndromeDelta::FLAG_EDGE_REMOVE != 0 {
self.remove_edge(delta.source, delta.target);
} else if delta.flags & SyndromeDelta::FLAG_WEIGHT_UPDATE != 0 {
self.update_weight(delta.source, delta.target, delta.value as FixedWeight);
} else if delta.flags & SyndromeDelta::FLAG_SYNDROME != 0 {
if (delta.source as usize) < MAX_PATCH_VERTICES {
self.ensure_vertex(delta.source);
self.vertices[delta.source as usize].syndrome_acc =
self.vertices[delta.source as usize].syndrome_acc.wrapping_add(delta.value);
}
}
}
pub fn ensure_vertex(&mut self, v: VertexId) -> bool {
if v as usize >= MAX_PATCH_VERTICES {
return false;
}
if !self.vertices[v as usize].is_active() {
self.vertices[v as usize].flags = Vertex::FLAG_ACTIVE;
self.vertices[v as usize].degree = 0;
self.vertices[v as usize].component = 0;
self.num_vertices += 1;
self.status |= Self::STATUS_DIRTY;
}
true
}
pub fn add_edge(&mut self, source: VertexId, target: VertexId, weight: FixedWeight) -> Option<EdgeId> {
if source as usize >= MAX_PATCH_VERTICES || target as usize >= MAX_PATCH_VERTICES {
return None;
}
if source == target {
return None;
}
self.ensure_vertex(source);
self.ensure_vertex(target);
if self.vertices[source as usize].degree as usize >= MAX_DEGREE
|| self.vertices[target as usize].degree as usize >= MAX_DEGREE
{
return None;
}
let edge_id = self.allocate_edge()?;
self.edges[edge_id as usize] = Edge::new(source, target, weight);
let src_deg = self.vertices[source as usize].degree as usize;
self.adjacency[source as usize][src_deg] = AdjEntry { neighbor: target, edge_id };
self.vertices[source as usize].degree += 1;
let tgt_deg = self.vertices[target as usize].degree as usize;
self.adjacency[target as usize][tgt_deg] = AdjEntry { neighbor: source, edge_id };
self.vertices[target as usize].degree += 1;
self.num_edges += 1;
self.status |= Self::STATUS_DIRTY;
self.generation = self.generation.wrapping_add(1);
Some(edge_id)
}
pub fn remove_edge(&mut self, source: VertexId, target: VertexId) -> bool {
if let Some(edge_id) = self.find_edge(source, target) {
self.remove_from_adj(source, target, edge_id);
self.remove_from_adj(target, source, edge_id);
self.free_edge(edge_id);
self.num_edges = self.num_edges.saturating_sub(1);
self.status |= Self::STATUS_DIRTY;
self.generation = self.generation.wrapping_add(1);
true
} else {
false
}
}
pub fn update_weight(&mut self, source: VertexId, target: VertexId, new_weight: FixedWeight) -> bool {
if let Some(edge_id) = self.find_edge(source, target) {
self.edges[edge_id as usize].weight = new_weight;
self.status |= Self::STATUS_DIRTY;
true
} else {
false
}
}
pub fn find_edge(&self, source: VertexId, target: VertexId) -> Option<EdgeId> {
if source as usize >= MAX_PATCH_VERTICES {
return None;
}
let v = &self.vertices[source as usize];
if !v.is_active() {
return None;
}
for i in 0..v.degree as usize {
if self.adjacency[source as usize][i].neighbor == target {
return Some(self.adjacency[source as usize][i].edge_id);
}
}
None
}
pub fn estimate_local_cut(&self) -> f64 {
let mut min_degree = u8::MAX;
let mut total_weight: u64 = 0;
let mut degree_count = 0u32;
for v in &self.vertices[..MAX_PATCH_VERTICES] {
if v.is_active() && v.degree > 0 {
if v.degree < min_degree {
min_degree = v.degree;
}
degree_count += 1;
}
}
for e in &self.edges[..self.num_edges as usize] {
total_weight += e.weight as u64;
}
if degree_count == 0 || min_degree == u8::MAX {
return 0.0;
}
let avg_weight = total_weight as f64 / (self.num_edges.max(1) as f64);
(min_degree as f64) * avg_weight
}
pub fn identify_boundary_candidates(&self, out: &mut [EdgeId]) -> usize {
let mut count = 0;
let max_out = out.len().min(MAX_BOUNDARY_CANDIDATES);
let mut edges_with_weights: [(EdgeId, FixedWeight); MAX_BOUNDARY_CANDIDATES] =
[(0, u32::MAX); MAX_BOUNDARY_CANDIDATES];
for (i, e) in self.edges[..self.num_edges as usize].iter().enumerate() {
if e.weight > 0 {
for j in 0..max_out {
if e.weight < edges_with_weights[j].1 {
for k in (j + 1..max_out).rev() {
edges_with_weights[k] = edges_with_weights[k - 1];
}
edges_with_weights[j] = (i as EdgeId, e.weight);
break;
}
}
}
}
for (eid, weight) in edges_with_weights.iter() {
if *weight < u32::MAX {
out[count] = *eid;
count += 1;
}
}
count
}
pub fn recompute_components(&mut self) -> u16 {
let mut parent = [0u16; MAX_PATCH_VERTICES];
let mut rank = [0u8; MAX_PATCH_VERTICES];
for i in 0..MAX_PATCH_VERTICES {
parent[i] = i as u16;
}
#[inline(always)]
fn find(parent: &mut [u16; MAX_PATCH_VERTICES], mut x: u16) -> u16 {
let mut root = x;
while parent[root as usize] != root {
root = parent[root as usize];
}
while x != root {
let next = parent[x as usize];
parent[x as usize] = root;
x = next;
}
root
}
#[inline(always)]
fn union(parent: &mut [u16; MAX_PATCH_VERTICES], rank: &mut [u8; MAX_PATCH_VERTICES], x: u16, y: u16) {
let px = find(parent, x);
let py = find(parent, y);
if px == py {
return;
}
if rank[px as usize] < rank[py as usize] {
parent[px as usize] = py;
} else if rank[px as usize] > rank[py as usize] {
parent[py as usize] = px;
} else {
parent[py as usize] = px;
rank[px as usize] += 1;
}
}
for i in 0..self.num_edges as usize {
let e = &self.edges[i];
if e.weight > 0 {
union(&mut parent, &mut rank, e.source, e.target);
}
}
let mut component_count = 0u16;
let mut component_map = [0xFFFFu16; MAX_PATCH_VERTICES];
for i in 0..MAX_PATCH_VERTICES {
if self.vertices[i].is_active() {
let root = find(&mut parent, i as u16);
if component_map[root as usize] == 0xFFFF {
component_map[root as usize] = component_count;
self.vertices[i].component = component_count;
component_count += 1;
} else {
self.vertices[i].component = component_map[root as usize];
}
}
}
self.num_components = component_count;
if component_count <= 1 && self.num_vertices > 0 {
self.status |= Self::STATUS_CONNECTED;
} else {
self.status &= !Self::STATUS_CONNECTED;
}
self.status &= !Self::STATUS_DIRTY;
component_count
}
pub fn clear(&mut self) {
for v in &mut self.vertices {
v.flags = 0;
v.degree = 0;
}
self.num_vertices = 0;
self.num_edges = 0;
self.num_components = 0;
self.free_edge_head = 0xFFFF;
self.status = Self::STATUS_VALID | Self::STATUS_DIRTY;
self.generation = self.generation.wrapping_add(1);
}
fn allocate_edge(&mut self) -> Option<EdgeId> {
if self.free_edge_head != 0xFFFF {
let id = self.free_edge_head;
self.free_edge_head = self.edges[id as usize].source;
return Some(id);
}
for i in 0..MAX_PATCH_EDGES {
if self.edges[i].weight == 0 && self.edges[i].source == 0 && self.edges[i].target == 0 {
return Some(i as EdgeId);
}
}
None
}
fn free_edge(&mut self, edge_id: EdgeId) {
self.edges[edge_id as usize].source = self.free_edge_head;
self.edges[edge_id as usize].target = 0;
self.edges[edge_id as usize].weight = 0;
self.free_edge_head = edge_id;
}
fn remove_from_adj(&mut self, v: VertexId, neighbor: VertexId, edge_id: EdgeId) {
if v as usize >= MAX_PATCH_VERTICES {
return;
}
let degree = self.vertices[v as usize].degree as usize;
for i in 0..degree {
if self.adjacency[v as usize][i].neighbor == neighbor
&& self.adjacency[v as usize][i].edge_id == edge_id
{
if i < degree - 1 {
self.adjacency[v as usize][i] = self.adjacency[v as usize][degree - 1];
}
self.vertices[v as usize].degree -= 1;
return;
}
}
}
pub const fn memory_size() -> usize {
size_of::<Self>()
}
}
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct SyndromeEntry {
pub round: u32,
pub syndrome: [u8; 8],
pub flags: u32,
}
#[derive(Debug)]
#[repr(C, align(64))]
pub struct SyndromBuffer {
pub entries: [SyndromeEntry; SYNDROME_BUFFER_DEPTH],
pub head: u16,
pub count: u16,
pub current_round: u32,
_pad: [u8; 56],
}
impl Default for SyndromBuffer {
fn default() -> Self {
Self::new()
}
}
impl SyndromBuffer {
pub const fn new() -> Self {
Self {
entries: [SyndromeEntry {
round: 0,
syndrome: [0; 8],
flags: 0,
}; SYNDROME_BUFFER_DEPTH],
head: 0,
count: 0,
current_round: 0,
_pad: [0; 56],
}
}
pub fn append(&mut self, entry: SyndromeEntry) {
self.entries[self.head as usize] = entry;
self.head = ((self.head as usize + 1) % SYNDROME_BUFFER_DEPTH) as u16;
if (self.count as usize) < SYNDROME_BUFFER_DEPTH {
self.count += 1;
}
self.current_round = entry.round;
}
pub fn recent(&self, count: usize) -> impl Iterator<Item = &SyndromeEntry> {
let count = count.min(self.count as usize);
let start = if self.head as usize >= count {
self.head as usize - count
} else {
SYNDROME_BUFFER_DEPTH - (count - self.head as usize)
};
(0..count).map(move |i| {
let idx = (start + i) % SYNDROME_BUFFER_DEPTH;
&self.entries[idx]
})
}
pub fn clear(&mut self) {
self.head = 0;
self.count = 0;
self.current_round = 0;
}
pub const fn memory_size() -> usize {
size_of::<Self>()
}
}
#[derive(Debug, Clone, Copy)]
#[repr(C, align(64))]
pub struct EvidenceAccumulator {
pub log_e_value: LogEValue,
pub obs_count: u32,
pub rejected_count: u16,
pub status: u16,
_pad: [u8; 48],
}
impl Default for EvidenceAccumulator {
fn default() -> Self {
Self::new()
}
}
impl EvidenceAccumulator {
pub const STATUS_ACTIVE: u16 = 0x0001;
pub const STATUS_HAS_REJECTION: u16 = 0x0002;
pub const STATUS_SIGNIFICANT: u16 = 0x0004;
pub const fn new() -> Self {
Self {
log_e_value: 0,
obs_count: 0,
rejected_count: 0,
status: Self::STATUS_ACTIVE,
_pad: [0; 48],
}
}
pub fn observe(&mut self, log_lr: LogEValue) {
self.log_e_value = self.log_e_value.saturating_add(log_lr);
self.obs_count += 1;
if self.log_e_value > LOG_E_STRONG {
self.status |= Self::STATUS_SIGNIFICANT;
}
if self.log_e_value > LOG_E_VERY_STRONG {
self.rejected_count += 1;
self.status |= Self::STATUS_HAS_REJECTION;
}
}
pub fn e_value(&self) -> f64 {
let log2_val = (self.log_e_value as f64) / 65536.0;
f64::exp2(log2_val)
}
pub fn is_significant(&self) -> bool {
self.status & Self::STATUS_SIGNIFICANT != 0
}
pub fn reset(&mut self) {
self.log_e_value = 0;
self.obs_count = 0;
self.rejected_count = 0;
self.status = Self::STATUS_ACTIVE;
}
}
#[derive(Debug, Clone)]
#[repr(C, align(64))]
pub struct LocalCutState {
pub cut_value: f64,
pub prev_cut_value: f64,
pub boundary_candidates: [EdgeId; MAX_BOUNDARY_CANDIDATES],
pub num_candidates: u16,
pub generation: u16,
pub boundary_moved: bool,
_pad: [u8; 51],
}
impl Default for LocalCutState {
fn default() -> Self {
Self::new()
}
}
impl LocalCutState {
pub const fn new() -> Self {
Self {
cut_value: 0.0,
prev_cut_value: 0.0,
boundary_candidates: [0; MAX_BOUNDARY_CANDIDATES],
num_candidates: 0,
generation: 0,
boundary_moved: false,
_pad: [0; 51],
}
}
pub fn update_from_graph(&mut self, graph: &PatchGraph) {
self.prev_cut_value = self.cut_value;
self.cut_value = graph.estimate_local_cut();
self.num_candidates = graph.identify_boundary_candidates(&mut self.boundary_candidates) as u16;
let delta = (self.cut_value - self.prev_cut_value).abs();
self.boundary_moved = delta > 0.1 * self.prev_cut_value.max(1.0);
self.generation = self.generation.wrapping_add(1);
}
pub fn candidates(&self) -> &[EdgeId] {
&self.boundary_candidates[..self.num_candidates as usize]
}
}
#[derive(Debug, Clone, Copy)]
#[repr(C, align(64))]
pub struct TileReport {
pub tile_id: TileId,
pub status: u8,
pub generation: u16,
pub tick: u32,
pub local_cut: f64,
pub boundary_candidates: [EdgeId; 8],
pub shift_score: f64,
pub e_value: f64,
pub num_vertices: u16,
pub num_edges: u16,
pub num_components: u16,
pub boundary_moved: bool,
_reserved: u8,
}
impl Default for TileReport {
fn default() -> Self {
Self::new(0)
}
}
impl TileReport {
pub const STATUS_VALID: u8 = 0x01;
pub const STATUS_ERROR: u8 = 0x02;
pub const STATUS_BOUNDARY_MOVED: u8 = 0x04;
pub const fn new(tile_id: TileId) -> Self {
Self {
tile_id,
status: Self::STATUS_VALID,
generation: 0,
tick: 0,
local_cut: 0.0,
boundary_candidates: [0; 8],
shift_score: 0.0,
e_value: 1.0,
num_vertices: 0,
num_edges: 0,
num_components: 0,
boundary_moved: false,
_reserved: 0,
}
}
}
#[derive(Debug)]
#[repr(C)]
pub struct WorkerTile {
pub tile_id: TileId,
pub tick: u32,
pub generation: u16,
pub status: u8,
_reserved: u8,
pub patch_graph: PatchGraph,
pub syndrome_buffer: SyndromBuffer,
pub evidence: EvidenceAccumulator,
pub local_cut_state: LocalCutState,
}
impl WorkerTile {
pub fn new(tile_id: TileId) -> Self {
debug_assert!(tile_id != 0, "TileId 0 is reserved for TileZero");
Self {
tile_id,
tick: 0,
generation: 0,
status: 0,
_reserved: 0,
patch_graph: PatchGraph::new(),
syndrome_buffer: SyndromBuffer::new(),
evidence: EvidenceAccumulator::new(),
local_cut_state: LocalCutState::new(),
}
}
pub fn tick(&mut self, delta: &SyndromeDelta) -> TileReport {
self.tick += 1;
self.patch_graph.apply_delta(delta);
if delta.is_syndrome() {
let entry = SyndromeEntry {
round: self.tick,
syndrome: [
(delta.value & 0xFF) as u8,
((delta.value >> 8) & 0xFF) as u8,
0, 0, 0, 0, 0, 0,
],
flags: delta.flags as u32,
};
self.syndrome_buffer.append(entry);
}
if self.patch_graph.status & PatchGraph::STATUS_DIRTY != 0 {
self.patch_graph.recompute_components();
}
self.local_cut_state.update_from_graph(&self.patch_graph);
if delta.is_syndrome() {
let log_lr = if delta.value > 128 {
(delta.value as LogEValue - 128) * 256 } else {
(128 - delta.value as LogEValue) * 256 };
self.evidence.observe(-log_lr); }
let shift_score = self.compute_shift_score();
let mut report = TileReport::new(self.tile_id);
report.tick = self.tick;
report.generation = self.generation;
report.local_cut = self.local_cut_state.cut_value;
report.shift_score = shift_score;
report.e_value = self.evidence.e_value();
report.num_vertices = self.patch_graph.num_vertices;
report.num_edges = self.patch_graph.num_edges;
report.num_components = self.patch_graph.num_components;
report.boundary_moved = self.local_cut_state.boundary_moved;
if report.boundary_moved {
report.status |= TileReport::STATUS_BOUNDARY_MOVED;
}
let candidates = self.local_cut_state.candidates();
let count = candidates.len().min(8);
report.boundary_candidates[..count].copy_from_slice(&candidates[..count]);
self.generation = self.generation.wrapping_add(1);
report
}
#[inline]
fn compute_shift_score(&self) -> f64 {
if (self.syndrome_buffer.count as usize) < 32 {
return 0.0;
}
let mut count = 0u64;
let mut sum: u64 = 0;
let mut sum_sq: u64 = 0;
for entry in self.syndrome_buffer.recent(32) {
let val = entry.syndrome[0] as u64;
sum += val;
sum_sq += val * val;
count += 1;
}
if count < 32 {
return 0.0;
}
let n = count as f64;
let mean = sum as f64 / n;
let variance = (sum_sq as f64 / n) - (mean * mean);
(variance / 128.0).min(1.0)
}
pub fn reset(&mut self) {
self.tick = 0;
self.generation = 0;
self.status = 0;
self.patch_graph.clear();
self.syndrome_buffer.clear();
self.evidence.reset();
self.local_cut_state = LocalCutState::new();
}
pub const fn memory_size() -> usize {
size_of::<Self>()
}
}
#[derive(Debug, Clone, Copy)]
pub struct GateThresholds {
pub structural_min_cut: f64,
pub shift_max: f64,
pub tau_deny: f64,
pub tau_permit: f64,
pub permit_ttl_ns: u64,
}
impl Default for GateThresholds {
fn default() -> Self {
Self {
structural_min_cut: 5.0,
shift_max: 0.5,
tau_deny: 0.01,
tau_permit: 100.0,
permit_ttl_ns: 4_000_000, }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum GateDecision {
Permit = 0,
Defer = 1,
Deny = 2,
}
impl GateDecision {
pub const fn is_permit(&self) -> bool {
matches!(self, GateDecision::Permit)
}
pub const fn is_deny(&self) -> bool {
matches!(self, GateDecision::Deny)
}
}
#[derive(Debug, Clone)]
pub struct PermitToken {
pub decision: GateDecision,
pub sequence: u64,
pub timestamp: u64,
pub ttl_ns: u64,
pub witness_hash: [u8; 32],
pub signature: [u8; 64],
}
impl PermitToken {
pub fn is_valid(&self, now_ns: u64) -> bool {
self.decision == GateDecision::Permit
&& now_ns >= self.timestamp && now_ns <= self.timestamp.saturating_add(self.ttl_ns) }
pub fn signature_message(&self) -> [u8; 81] {
let mut msg = [0u8; 81];
msg[0] = self.decision as u8;
msg[1..9].copy_from_slice(&self.sequence.to_le_bytes());
msg[9..17].copy_from_slice(&self.timestamp.to_le_bytes());
msg[17..25].copy_from_slice(&self.ttl_ns.to_le_bytes());
msg[25..57].copy_from_slice(&self.witness_hash);
msg
}
pub fn verify_signature(&self, public_key: &[u8; 32]) -> bool {
let zero_sig = [0u8; 64];
if self.signature.ct_eq(&zero_sig).into() {
return false;
}
let verifying_key = match VerifyingKey::from_bytes(public_key) {
Ok(key) => key,
Err(_) => return false,
};
let sig_bytes: [u8; 64] = self.signature;
let signature = Signature::from_bytes(&sig_bytes);
let message = self.signature_message();
let hash = blake3::hash(&message);
verifying_key.verify_strict(hash.as_bytes(), &signature).is_ok()
}
}
#[derive(Debug, Clone)]
pub struct ReceiptEntry {
pub sequence: u64,
pub decision: GateDecision,
pub timestamp: u64,
pub witness_hash: [u8; 32],
pub previous_hash: [u8; 32],
pub hash: [u8; 32],
}
#[derive(Debug, Clone, Default)]
pub struct ReceiptLog {
entries: Vec<ReceiptEntry>,
last_hash: [u8; 32],
}
impl ReceiptLog {
pub fn new() -> Self {
Self {
entries: Vec::new(),
last_hash: [0u8; 32],
}
}
pub fn append(&mut self, decision: GateDecision, sequence: u64, timestamp: u64, witness_hash: [u8; 32]) {
let mut hasher = blake3::Hasher::new();
hasher.update(&self.last_hash);
hasher.update(&sequence.to_le_bytes());
hasher.update(&[decision as u8]);
hasher.update(×tamp.to_le_bytes());
hasher.update(&witness_hash);
let hash: [u8; 32] = *hasher.finalize().as_bytes();
let entry = ReceiptEntry {
sequence,
decision,
timestamp,
witness_hash,
previous_hash: self.last_hash,
hash,
};
self.last_hash = hash;
self.entries.push(entry);
}
pub fn verify_chain(&self) -> bool {
if self.entries.is_empty() {
return true;
}
let mut expected_prev = [0u8; 32];
for entry in &self.entries {
if !bool::from(entry.previous_hash.ct_eq(&expected_prev)) {
return false;
}
let mut hasher = blake3::Hasher::new();
hasher.update(&entry.previous_hash);
hasher.update(&entry.sequence.to_le_bytes());
hasher.update(&[entry.decision as u8]);
hasher.update(&entry.timestamp.to_le_bytes());
hasher.update(&entry.witness_hash);
let computed_hash: [u8; 32] = *hasher.finalize().as_bytes();
if !bool::from(entry.hash.ct_eq(&computed_hash)) {
return false;
}
expected_prev = entry.hash;
}
bool::from(self.last_hash.ct_eq(&expected_prev))
}
pub fn last_hash(&self) -> [u8; 32] {
self.last_hash
}
pub fn get(&self, sequence: u64) -> Option<&ReceiptEntry> {
self.entries.iter().find(|e| e.sequence == sequence)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
#[derive(Debug)]
pub struct TileZero {
pub thresholds: GateThresholds,
worker_reports: Vec<TileReport>,
pub receipt_log: ReceiptLog,
sequence: u64,
signing_key: Option<SigningKey>,
}
impl TileZero {
pub fn new(thresholds: GateThresholds) -> Self {
Self {
thresholds,
worker_reports: Vec::with_capacity(NUM_WORKERS),
receipt_log: ReceiptLog::new(),
sequence: 0,
signing_key: None,
}
}
pub fn with_signing_key(thresholds: GateThresholds, signing_key: SigningKey) -> Self {
Self {
thresholds,
worker_reports: Vec::with_capacity(NUM_WORKERS),
receipt_log: ReceiptLog::new(),
sequence: 0,
signing_key: Some(signing_key),
}
}
pub fn with_random_key(thresholds: GateThresholds) -> Self {
use rand::rngs::OsRng;
let signing_key = SigningKey::generate(&mut OsRng);
Self::with_signing_key(thresholds, signing_key)
}
pub fn verifying_key(&self) -> Option<VerifyingKey> {
self.signing_key.as_ref().map(|sk| sk.verifying_key())
}
pub fn has_signing_key(&self) -> bool {
self.signing_key.is_some()
}
pub fn merge_reports(&mut self, reports: Vec<TileReport>) -> GateDecision {
self.worker_reports = reports;
let (global_cut, shift_pressure, e_aggregate) = self.aggregate_metrics();
let decision = self.evaluate_filters(global_cut, shift_pressure, e_aggregate);
let witness_hash = self.compute_witness_hash();
let timestamp = self.sequence * 1_000_000;
self.receipt_log.append(decision, self.sequence, timestamp, witness_hash);
self.sequence += 1;
decision
}
pub fn issue_permit(&self, decision: &GateDecision) -> PermitToken {
let timestamp = self.receipt_log.last_hash()[0..8]
.try_into()
.map(u64::from_le_bytes)
.unwrap_or(0);
let witness_hash = self.compute_witness_hash();
let mut token = PermitToken {
decision: *decision,
sequence: self.sequence.saturating_sub(1),
timestamp,
ttl_ns: self.thresholds.permit_ttl_ns,
witness_hash,
signature: [0u8; 64],
};
if let Some(ref signing_key) = self.signing_key {
let message = token.signature_message();
let hash = blake3::hash(&message);
let signature = signing_key.sign(hash.as_bytes());
token.signature = signature.to_bytes();
} else {
token.signature[0..8].copy_from_slice(&token.sequence.to_le_bytes());
token.signature[8..16].copy_from_slice(×tamp.to_le_bytes());
token.signature[16..48].copy_from_slice(&witness_hash);
token.signature[63] = 0xFF;
}
token
}
pub fn verify_token(&self, token: &PermitToken) -> Option<bool> {
let verifying_key = self.verifying_key()?;
Some(token.verify_signature(&verifying_key.to_bytes()))
}
#[inline]
fn aggregate_metrics(&self) -> (f64, f64, f64) {
if self.worker_reports.is_empty() {
return (f64::MAX, 0.0, 1.0);
}
let mut min_cut = f64::MAX;
let mut total_shift = 0.0;
let mut log_e_sum = 0.0;
for report in &self.worker_reports {
if report.local_cut < min_cut && report.local_cut > 0.0 {
min_cut = report.local_cut;
}
if report.shift_score > total_shift {
total_shift = report.shift_score;
}
log_e_sum += f64::log2(report.e_value.max(1e-10));
}
let e_aggregate = f64::exp2(log_e_sum / self.worker_reports.len() as f64);
(min_cut, total_shift, e_aggregate)
}
#[inline]
fn evaluate_filters(&self, global_cut: f64, shift_pressure: f64, e_aggregate: f64) -> GateDecision {
if global_cut < self.thresholds.structural_min_cut {
return GateDecision::Deny;
}
if shift_pressure >= self.thresholds.shift_max {
return GateDecision::Defer;
}
if e_aggregate < self.thresholds.tau_deny {
return GateDecision::Deny;
}
if e_aggregate < self.thresholds.tau_permit {
return GateDecision::Defer;
}
GateDecision::Permit
}
fn compute_witness_hash(&self) -> [u8; 32] {
let mut hash = [0u8; 32];
let mut idx = 0;
for report in self.worker_reports.iter().take(6) {
if idx + 5 > 32 {
break;
}
hash[idx] = report.tile_id;
idx += 1;
let cut_bytes = report.local_cut.to_le_bytes();
hash[idx..idx + 4].copy_from_slice(&cut_bytes[0..4]);
idx += 4;
}
hash
}
pub fn reports(&self) -> &[TileReport] {
&self.worker_reports
}
}
#[cfg(test)]
mod size_assertions {
use super::*;
#[test]
fn test_patch_graph_size() {
let size = PatchGraph::memory_size();
assert!(size <= 65536, "PatchGraph exceeds 64KB: {} bytes", size);
}
#[test]
fn test_syndrome_buffer_size() {
let size = SyndromBuffer::memory_size();
assert!(size <= 32768, "SyndromBuffer exceeds 32KB: {} bytes", size);
}
#[test]
fn test_worker_tile_size() {
let size = WorkerTile::memory_size();
assert!(size <= 131072, "WorkerTile exceeds 128KB: {} bytes", size);
}
#[test]
fn test_tile_report_alignment() {
assert_eq!(core::mem::align_of::<TileReport>(), 64);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_worker_tile_creation() {
let tile = WorkerTile::new(42);
assert_eq!(tile.tile_id, 42);
assert_eq!(tile.tick, 0);
}
#[test]
fn test_worker_tile_tick() {
let mut tile = WorkerTile::new(1);
let delta = SyndromeDelta::new(0, 1, 100);
let report = tile.tick(&delta);
assert_eq!(report.tile_id, 1);
assert_eq!(report.tick, 1);
}
#[test]
fn test_patch_graph_add_edge() {
let mut graph = PatchGraph::new();
let edge_id = graph.add_edge(0, 1, 100);
assert!(edge_id.is_some());
assert_eq!(graph.num_edges, 1);
assert_eq!(graph.num_vertices, 2);
}
#[test]
fn test_patch_graph_remove_edge() {
let mut graph = PatchGraph::new();
graph.add_edge(0, 1, 100);
assert!(graph.remove_edge(0, 1));
assert_eq!(graph.num_edges, 0);
}
#[test]
fn test_gate_decision_permit() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::new(thresholds);
let reports: Vec<TileReport> = (1..=10)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
assert_eq!(decision, GateDecision::Permit);
}
#[test]
fn test_gate_decision_deny_structural() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::new(thresholds);
let reports: Vec<TileReport> = (1..=10)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 1.0; report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
assert_eq!(decision, GateDecision::Deny);
}
#[test]
fn test_gate_decision_defer_shift() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::new(thresholds);
let reports: Vec<TileReport> = (1..=10)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.8; report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
assert_eq!(decision, GateDecision::Defer);
}
#[test]
fn test_receipt_log_chaining() {
let mut log = ReceiptLog::new();
log.append(GateDecision::Permit, 0, 1000, [0u8; 32]);
log.append(GateDecision::Permit, 1, 2000, [1u8; 32]);
log.append(GateDecision::Deny, 2, 3000, [2u8; 32]);
assert_eq!(log.len(), 3);
let entry1 = log.get(1).unwrap();
let entry2 = log.get(2).unwrap();
assert_eq!(entry2.previous_hash, entry1.hash);
}
#[test]
fn test_evidence_accumulator() {
let mut evidence = EvidenceAccumulator::new();
for _ in 0..10 {
evidence.observe(10000); }
assert!(evidence.e_value() > 1.0);
assert!(evidence.obs_count == 10);
}
#[test]
fn test_syndrome_buffer() {
let mut buffer = SyndromBuffer::new();
for i in 0..100 {
let entry = SyndromeEntry {
round: i,
syndrome: [i as u8; 8],
flags: 0,
};
buffer.append(entry);
}
assert_eq!(buffer.count, 100);
assert_eq!(buffer.current_round, 99);
let recent: Vec<_> = buffer.recent(10).collect();
assert_eq!(recent.len(), 10);
}
#[test]
fn test_local_cut_state() {
let mut graph = PatchGraph::new();
graph.add_edge(0, 1, 100);
graph.add_edge(1, 2, 100);
graph.add_edge(2, 0, 100);
graph.recompute_components();
let mut cut_state = LocalCutState::new();
cut_state.update_from_graph(&graph);
assert!(cut_state.cut_value > 0.0);
}
#[test]
fn test_permit_token_validity() {
let token = PermitToken {
decision: GateDecision::Permit,
sequence: 0,
timestamp: 1000,
ttl_ns: 500,
witness_hash: [0u8; 32],
signature: [1u8; 64], };
assert!(token.is_valid(1200));
assert!(!token.is_valid(1600));
assert!(!token.is_valid(500));
}
#[test]
fn test_permit_token_signature_verification() {
let token = PermitToken {
decision: GateDecision::Permit,
sequence: 0,
timestamp: 1000,
ttl_ns: 500,
witness_hash: [0u8; 32],
signature: [0u8; 64], };
let dummy_pubkey = [0u8; 32];
assert!(!token.verify_signature(&dummy_pubkey));
}
#[test]
fn test_receipt_log_chain_verification() {
let mut log = ReceiptLog::new();
log.append(GateDecision::Permit, 0, 1000, [0u8; 32]);
log.append(GateDecision::Permit, 1, 2000, [1u8; 32]);
log.append(GateDecision::Deny, 2, 3000, [2u8; 32]);
assert!(log.verify_chain());
}
#[test]
fn test_tilezero_with_signing_key() {
use rand::rngs::OsRng;
use ed25519_dalek::SigningKey;
let thresholds = GateThresholds::default();
let tilezero = TileZero::with_random_key(thresholds);
assert!(tilezero.has_signing_key());
assert!(tilezero.verifying_key().is_some());
}
#[test]
fn test_permit_token_real_signature() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::with_random_key(thresholds);
let reports: Vec<TileReport> = (1..=5)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
assert_eq!(decision, GateDecision::Permit);
let token = tilezero.issue_permit(&decision);
assert_ne!(token.signature[63], 0xFF, "Token has placeholder signature");
let verifying_key = tilezero.verifying_key().expect("Should have verifying key");
let is_valid = token.verify_signature(&verifying_key.to_bytes());
assert!(is_valid, "Token signature should be valid");
let result = tilezero.verify_token(&token);
assert_eq!(result, Some(true), "verify_token should return Some(true)");
}
#[test]
fn test_permit_token_placeholder_signature() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::new(thresholds);
assert!(!tilezero.has_signing_key());
assert!(tilezero.verifying_key().is_none());
let reports: Vec<TileReport> = (1..=5)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
let token = tilezero.issue_permit(&decision);
assert_eq!(token.signature[63], 0xFF, "Token should have placeholder signature marker");
assert_eq!(tilezero.verify_token(&token), None);
}
#[test]
fn test_token_signature_tampering_detected() {
let thresholds = GateThresholds::default();
let mut tilezero = TileZero::with_random_key(thresholds);
let reports: Vec<TileReport> = (1..=5)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision = tilezero.merge_reports(reports);
let mut token = tilezero.issue_permit(&decision);
token.sequence += 1;
let verifying_key = tilezero.verifying_key().unwrap();
let is_valid = token.verify_signature(&verifying_key.to_bytes());
assert!(!is_valid, "Tampered token signature should be invalid");
}
#[test]
fn test_different_keys_different_signatures() {
let thresholds = GateThresholds::default();
let mut tilezero1 = TileZero::with_random_key(thresholds.clone());
let mut tilezero2 = TileZero::with_random_key(thresholds);
let reports: Vec<TileReport> = (1..=3)
.map(|i| {
let mut report = TileReport::new(i);
report.local_cut = 10.0;
report.shift_score = 0.1;
report.e_value = 200.0;
report
})
.collect();
let decision1 = tilezero1.merge_reports(reports.clone());
let decision2 = tilezero2.merge_reports(reports);
let token1 = tilezero1.issue_permit(&decision1);
let token2 = tilezero2.issue_permit(&decision2);
assert_ne!(token1.signature, token2.signature);
let key1 = tilezero1.verifying_key().unwrap();
let key2 = tilezero2.verifying_key().unwrap();
assert!(token1.verify_signature(&key1.to_bytes()));
assert!(!token1.verify_signature(&key2.to_bytes())); assert!(!token2.verify_signature(&key1.to_bytes())); assert!(token2.verify_signature(&key2.to_bytes()));
}
}