pot-o-validator 0.10.0

PoT-O (Proof of Tensor Optimizations) Validator Service
Documentation
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
use std::sync::Arc;

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    middleware,
    response::IntoResponse,
    routing::{get, post},
    Json, Router,
};
use hexchain_p2p::hex_consensus::HexProof;
use hexchain_p2p::lattice_geometry::HCPCoord;
use hexchain_p2p::lattice_store::LatticeSnapshot;
use serde::Deserialize;

use crate::consensus::{accept_block, rollback_ledger_to, AppState, RELAYED_BLOCKS_MAX};
use crate::rate_limit::{rate_limit_middleware, RateLimiter};

type HexApiResponse = (StatusCode, Json<serde_json::Value>);

pub fn hex_routes(state: Arc<AppState>) -> Router {
    let hex_submit_limiter = RateLimiter::new(3, 1);

    let hex_submit_route = Router::new()
        .route("/hexchain/submit", post(post_hex_submit))
        .layer(middleware::from_fn(rate_limit_middleware))
        .layer(axum::Extension(hex_submit_limiter));

    Router::new()
        .route("/hexchain/challenge", post(post_hex_challenge))
        .route("/hexchain/status", get(get_hex_status))
        .route("/hexchain/lattice", get(get_hex_lattice_all))
        .route("/hexchain/lattice/sync", post(post_hex_lattice_sync))
        .route("/hexchain/lattice/{q}/{r}/{s}", get(get_hex_lattice_coord))
        .route("/hexchain/block/{height}", get(get_hex_block_by_height))
        .route("/hexchain/blocks", get(get_hex_blocks_batch))
        .merge(hex_submit_route)
        .with_state(state)
}

#[derive(Deserialize)]
struct HexChallengeRequest {
    slot: u64,
    slot_hash: String,
}

async fn post_hex_challenge(
    State(state): State<Arc<AppState>>,
    Json(body): Json<HexChallengeRequest>,
) -> impl IntoResponse {
    tracing::debug!(slot = body.slot, "POST /hexchain/challenge");
    let challenge = state
        .hex_consensus
        .generate_challenge(body.slot, &body.slot_hash);
    {
        let mut current = state.hex_current_challenge.write().await;
        *current = Some(challenge.clone());
    }
    tracing::info!(
        challenge_id = %challenge.id,
        coord = ?challenge.coord,
        "POST /hexchain/challenge issued"
    );
    (
        StatusCode::OK,
        Json(serde_json::to_value(&challenge).unwrap_or_default()),
    )
}

async fn post_hex_submit(
    State(state): State<Arc<AppState>>,
    Json(proof): Json<HexProof>,
) -> impl IntoResponse {
    tracing::debug!(challenge_id = %proof.challenge_id, "POST /hexchain/submit");

    match state.hex_consensus.verify_proof(&proof) {
        Ok(true) => match state.hex_consensus.submit_block(&proof) {
            Ok(depth) => {
                if state.extensions.tribechain_enabled {
                    let mempool = state.extensions.mempool.as_deref();
                    let block_store = state.extensions.block_store.as_deref();
                    let mut ledger = state.extensions.ledger.write().await;
                    if let Err(e) = accept_block(&proof.block, &mut ledger, mempool, block_store) {
                        tracing::warn!(error = %e, "Tribechain block acceptance failed");
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(
                                serde_json::json!({ "accepted": false, "error": "internal error" }),
                            ),
                        );
                    }
                    *state.canonical_tip_height.write().await += 1;
                    drop(ledger);
                    relay_block(&state, &proof).await;
                }
                // Persist lattice immediately so restarts never lose accepted blocks
                if let Err(e) = state.hex_consensus.store.save_to_file() {
                    tracing::warn!(error = %e, "Hex lattice post-submit persist failed (non-fatal)");
                }
                tracing::info!(
                    challenge_id = %proof.challenge_id,
                    coord = ?proof.block.coord,
                    depth = depth,
                    "POST /hexchain/submit accepted"
                );
                (
                    StatusCode::OK,
                    Json(serde_json::json!({
                        "accepted": true,
                        "depth": depth,
                        "block_hash": hex::encode(proof.block.pow_hash()),
                    })),
                )
            }
            Err(e) => {
                tracing::warn!(error = ?e, "POST /hexchain/submit block insertion failed");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({ "accepted": false, "error": "internal error" })),
                )
            }
        },
        Ok(false) => {
            tracing::info!(challenge_id = %proof.challenge_id, "POST /hexchain/submit rejected (genesis mode, no validation)");
            match state.hex_consensus.submit_block(&proof) {
                Ok(depth) => {
                    if state.extensions.tribechain_enabled {
                        let mempool = state.extensions.mempool.as_deref();
                        let block_store = state.extensions.block_store.as_deref();
                        let mut ledger = state.extensions.ledger.write().await;
                        if let Err(e) =
                            accept_block(&proof.block, &mut ledger, mempool, block_store)
                        {
                            tracing::warn!(error = %e, "Tribechain genesis block acceptance failed");
                            return (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                Json(
                                    serde_json::json!({ "accepted": false, "error": "internal error" }),
                                ),
                            );
                        }
                        *state.canonical_tip_height.write().await += 1;
                        drop(ledger);
                        relay_block(&state, &proof).await;
                    }
                    // Persist lattice immediately (genesis mode)
                    if let Err(e) = state.hex_consensus.store.save_to_file() {
                        tracing::warn!(error = %e, "Hex lattice genesis persist failed (non-fatal)");
                    }
                    (
                        StatusCode::OK,
                        Json(serde_json::json!({
                            "accepted": true,
                            "depth": depth,
                            "block_hash": hex::encode(proof.block.pow_hash()),
                        })),
                    )
                }
                Err(e) => {
                    tracing::warn!(error = ?e, "POST /hexchain/submit genesis block insertion failed");
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(serde_json::json!({
                            "accepted": false, "error": "internal error"
                        })),
                    )
                }
            }
        }
        Err(e) => {
            tracing::warn!(error = ?e, "POST /hexchain/submit verification failed");
            (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({ "accepted": false, "error": "verification failed" })),
            )
        }
    }
}

async fn get_hex_status(State(state): State<Arc<AppState>>) -> HexApiResponse {
    let occupied = state.hex_consensus.store.all_coords().len();
    let all_blocks = state.hex_consensus.store.all_blocks();
    let latest_depth = all_blocks
        .iter()
        .filter_map(|(_, h)| state.hex_consensus.store.depth_of(h))
        .max();
    let current_challenge = state.hex_current_challenge.read().await.clone();

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "occupied_coords": occupied,
            "latest_depth": latest_depth,
            "current_challenge": current_challenge,
        })),
    )
}

async fn get_hex_lattice_all(State(state): State<Arc<AppState>>) -> HexApiResponse {
    let coords: Vec<HCPCoord> = state.hex_consensus.store.all_coords().into_iter().collect();
    let blocks: Vec<serde_json::Value> = coords
        .iter()
        .filter_map(|c| {
            let hash = state.hex_consensus.store.hash_at(*c)?;
            let depth = state.hex_consensus.store.depth_of(&hash)?;
            Some(serde_json::json!({
                "coord": c,
                "block_hash": hex::encode(hash),
                "depth": depth,
            }))
        })
        .collect();
    (
        StatusCode::OK,
        Json(serde_json::json!({ "blocks": blocks })),
    )
}

async fn post_hex_lattice_sync(
    State(state): State<Arc<AppState>>,
    Json(snapshot): Json<LatticeSnapshot>,
) -> HexApiResponse {
    let before = state.hex_consensus.store.all_coords().len();
    state.hex_consensus.store.merge_snapshot(&snapshot);
    let after = state.hex_consensus.store.all_coords().len();
    let merged = after.saturating_sub(before);
    if let Err(e) = state.hex_consensus.store.save_to_file() {
        tracing::warn!(error = %e, "POST /hexchain/lattice/sync persist failed");
    }

    if state.extensions.tribechain_enabled {
        let new_max_depth = state
            .hex_consensus
            .store
            .all_blocks()
            .iter()
            .filter_map(|(_, h)| state.hex_consensus.store.depth_of(h))
            .max()
            .unwrap_or(0) as i64;
        let canonical_height = *state.canonical_tip_height.read().await as i64;
        if new_max_depth < canonical_height {
            tracing::warn!(
                old_height = canonical_height,
                new_height = new_max_depth,
                "Chain reorg detected, rolling back ledger"
            );
            if let Some(block_store) = &state.extensions.block_store {
                let mut ledger = state.extensions.ledger.write().await;
                let mut tip_height = state.canonical_tip_height.write().await;
                if let Err(e) = rollback_ledger_to(
                    &mut ledger,
                    block_store.as_ref(),
                    new_max_depth as u64,
                    &mut tip_height,
                ) {
                    tracing::error!(error = %e, "Ledger rollback failed");
                }
            }
        }
    }

    tracing::info!(merged, total = after, "POST /hexchain/lattice/sync");
    (
        StatusCode::OK,
        Json(serde_json::json!({
            "accepted": true,
            "merged": merged,
            "total_coords": after,
        })),
    )
}

async fn get_hex_lattice_coord(
    State(state): State<Arc<AppState>>,
    Path((q, r, s)): Path<(i32, i32, i32)>,
) -> HexApiResponse {
    let coord = HCPCoord { q, r, s };
    match state.hex_consensus.store.hash_at(coord) {
        Some(hash) => {
            let depth = state.hex_consensus.store.depth_of(&hash);
            (
                StatusCode::OK,
                Json(serde_json::json!({
                    "coord": coord,
                    "block_hash": hex::encode(hash),
                    "depth": depth,
                })),
            )
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "No block at this coordinate" })),
        ),
    }
}

async fn get_hex_block_by_height(
    State(state): State<Arc<AppState>>,
    Path(height): Path<u64>,
) -> HexApiResponse {
    let block_store = match &state.extensions.block_store {
        Some(bs) => bs,
        None => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({"error": "block store not available"})),
            )
        }
    };

    let stored = match block_store.at_height(height) {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({"error": "No block at this height"})),
            )
        }
    };

    let block: hexchain_p2p::block::HexBlock = match serde_json::from_str(&stored.block_json) {
        Ok(b) => b,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to parse stored block");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "internal error"})),
            );
        }
    };

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "height": stored.height,
            "hash": hex::encode(stored.hash),
            "block": block,
        })),
    )
}

#[derive(Deserialize)]
struct BlocksBatchQuery {
    from_height: Option<u64>,
    limit: Option<usize>,
}

async fn get_hex_blocks_batch(
    State(state): State<Arc<AppState>>,
    Query(query): Query<BlocksBatchQuery>,
) -> HexApiResponse {
    let block_store = match &state.extensions.block_store {
        Some(bs) => bs,
        None => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({"error": "block store not available"})),
            )
        }
    };

    let from_height = query.from_height.unwrap_or(0);
    let limit = query.limit.unwrap_or(50).min(200);
    let latest = block_store.latest_height();

    let mut blocks = Vec::new();
    for h in from_height..=latest {
        if blocks.len() >= limit {
            break;
        }
        if let Some(stored) = block_store.at_height(h) {
            blocks.push(serde_json::json!({
                "height": stored.height,
                "hash": hex::encode(stored.hash),
                "block_json": stored.block_json,
            }));
        }
    }

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "blocks": blocks,
            "count": blocks.len(),
        })),
    )
}

async fn relay_block(state: &AppState, proof: &HexProof) {
    let block_hash = proof.block.pow_hash();
    {
        let mut relayed = state.relayed_blocks.write().await;
        if relayed.contains(&block_hash) {
            return;
        }
        relayed.push_back(block_hash);
        while relayed.len() > RELAYED_BLOCKS_MAX {
            relayed.pop_front();
        }
    }

    let network = state.extensions.network.clone();
    let proof_json = match serde_json::to_value(proof) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to serialize block for relay");
            return;
        }
    };
    let block_height = proof.block.height;

    tokio::spawn(async move {
        match network.broadcast_block(&proof_json).await {
            Ok(n) if n > 0 => {
                tracing::info!(peers = n, height = block_height, "Block relayed to peers");
            }
            Ok(_) => {}
            Err(e) => {
                tracing::warn!(error = %e, "Block relay to peers failed");
            }
        }
    });
}