Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ jobs:
# transfer, a deploy and a confidential call (and an RPL-2 invoke where the build has it), and
# compares the explorer's every public number with the node's — including the REST contract
# zusd.money and randprotocol.org read (/bridge, /bridge/assets, /tokens/:index, /envelopes,
# /stats, /supply). It gates: the test skips a sub-check the released binary has no flag for
# /stats, /supply). The same step runs the site-sync case (`chain_view_follows_a_real_node`):
# GET /api/v1/chain equals the node's genesis and head, turns `unreachable` then `stalled` once
# the node is killed (a minute of waiting), and `wrong_chain` with nothing written when the
# explorer is pointed at a second dev chain. It gates: the test skips a sub-check the released binary has no flag for
# (with a printed reason), never the whole run. The wallet proves under the chain's `test` FRI
# profile in its own release binary, so the test itself builds in the default profile.
real-node:
Expand Down Expand Up @@ -129,7 +132,7 @@ jobs:
echo "RAND_NODE_BIN=$RUNNER_TEMP/fullnode/rand-node" >> "$GITHUB_ENV"
echo "RAND_CLI=$RUNNER_TEMP/fullnode/rand" >> "$GITHUB_ENV"

- name: Explorer against the real node
- name: Explorer against the real node (contract + site-sync /chain)
run: cargo test -p randscan-api --test real_node -- --nocapture
env:
DATABASE_URL: postgres://randscan:randscan@localhost:5432/randscan
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ the latest fullnode release on every push and pull request, and gates on it.
| `STATS_INTERVAL_SECS` | `5` | minimum interval between stats refreshes |
| `NODES_INTERVAL_SECS` | `60` | peer list / geolocation refresh interval |
| `NODE_PUBLIC_IP` | auto-detected | public IP of the node the explorer runs on |
| `RANDSCAN_EXPECTED_CHAIN_ID` | `21` | the chain this deployment expects; `/api/v1/chain` classifies against it, and the indexer re-indexes from height 0 only when the node moves to it (any other chain change stops the indexer). Move it, with the frontend's `src/lib/chainPin.ts`, at every chain cut |
| `RANDSCAN_EXPECTED_GENESIS` | chain 21's `ca76c276…ca9a` | the expected chain's genesis hash (hex) |
| `RUST_LOG` | `info` | log filter |
| `COOKIE_SECURE` | `true` | set the session cookie `Secure` (requires https; use `false` for local http) |
| `TRUST_PROXY` | `false` | read the client IP from `X-Forwarded-For` (true behind Caddy/nginx) |
Expand Down
76 changes: 76 additions & 0 deletions crates/randscan-api/src/handlers/chain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use crate::{state::AppState, ApiResult};
use axum::{extract::State, Json};
use randscan_core::{classify, ChainResponse, ChainState, ChainView};
use randscan_db as db;

/// Wall-clock milliseconds, the clock block timestamps are measured against.
pub(crate) fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}

/// The indexed data as a [`ChainView`], plus whether the indexer is halted and whether its last
/// request to the node succeeded. The stored chain is `chain_meta` (falling back to the chain id
/// `indexer_state` recorded, with no genesis, before the first pass); the head is the latest
/// indexed block. While halted, the node's height belongs to another chain, so `node_height`
/// and `lag` are left out rather than compared across chains.
pub(crate) async fn chain_view(state: &AppState) -> db::Result<(ChainView, bool, bool)> {
let pool = state.db.inner();
let meta = db::get_chain_meta(pool).await?;
let (chain_id, genesis_hash) = match meta {
Some(m) => (m.chain_id, Some(m.genesis_hash)),
None => (
db::get_indexer_state(pool).await?.chain_id.unwrap_or(0),
None,
),
};
let head = db::latest_block_head(pool).await?;
let s = state.indexer.get_state().await;
let head_height = head.map(|(h, _)| h).unwrap_or(0);
let (node_height, lag) = if s.halted || s.node_chain_id.is_none() {
(None, None)
} else {
let indexed = head.map(|(h, _)| h).unwrap_or(-1);
(Some(s.node_height), Some((s.node_height - indexed).max(0)))
};
let view = ChainView {
chain_id,
genesis_hash,
head_height,
head_timestamp_ms: head.map(|(_, ts)| ts),
node_height,
lag,
node_chain_id: s.node_chain_id,
node_genesis_hash: s.node_genesis_hash,
};
Ok((view, s.halted, s.is_connected))
}

/// GET /api/v1/chain — the explorer's [`ChainView`] and its state against the configured pin
/// (site-sync design §2–§3). The view classifies as the spec's table says. A node the indexer
/// cannot reach turns a `live` or `behind` view into `unreachable`: the data was current a moment
/// ago but nothing confirms it now. Once the head ages past `STALL_MS` the state is `stalled`,
/// which says more about what the reader is looking at.
pub async fn get_chain(State(state): State<AppState>) -> ApiResult<Json<ChainResponse>> {
let (view, halted, connected) = chain_view(&state).await?;
let expected = state.indexer.expected();
let mut c = classify(Some(&view), expected, now_ms());
if !connected && matches!(c.state, ChainState::Live | ChainState::Behind) {
c.state = ChainState::Unreachable;
c.detail = format!(
"The explorer cannot reach its node; last indexed block #{}.",
view.head_height
);
}
Ok(Json(ChainResponse {
view,
state: c.state,
detail: c.detail,
expected_chain_id: expected.chain_id,
expected_genesis_hash: expected.genesis_hash.clone(),
halted,
node_connected: connected,
}))
}
18 changes: 16 additions & 2 deletions crates/randscan-api/src/handlers/health.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use super::chain::{chain_view, now_ms};
use crate::{state::AppState, ApiResult};
use axum::{extract::State, Json};
use randscan_core::{HealthResponse, IndexerHealth};
use randscan_core::{is_stalled, is_wrong_chain, HealthResponse, IndexerHealth};
use randscan_db as db;

/// GET /api/v1/health
///
/// `status` is `healthy` when the database answers and the indexer is connected, synced, fresh
/// and on the pinned chain; `degraded` when the database answers but any of that fails (a stalled
/// head or the wrong chain included); `unhealthy` without the database.
pub async fn health(State(state): State<AppState>) -> ApiResult<Json<HealthResponse>> {
let db_ok = db::get_network_stats(state.db.inner()).await.is_ok();
let s = state.indexer.get_state().await;
Expand All @@ -15,7 +20,12 @@ pub async fn health(State(state): State<AppState>) -> ApiResult<Json<HealthRespo
node_height: s.node_height,
lag,
};
let status = if db_ok && indexer.connected && indexer.synced {
let view = chain_view(&state).await.ok().map(|(v, _, _)| v);
let stalled = view.as_ref().is_none_or(|v| is_stalled(v, now_ms()));
let wrong_chain = view
.as_ref()
.is_some_and(|v| is_wrong_chain(v, state.indexer.expected()));
let status = if db_ok && indexer.connected && indexer.synced && !stalled && !wrong_chain {
"healthy"
} else if db_ok {
"degraded"
Expand All @@ -27,5 +37,9 @@ pub async fn health(State(state): State<AppState>) -> ApiResult<Json<HealthRespo
version: env!("CARGO_PKG_VERSION").into(),
database: db_ok,
indexer,
genesis_hash: view.as_ref().and_then(|v| v.genesis_hash.clone()),
head_timestamp_ms: view.as_ref().and_then(|v| v.head_timestamp_ms),
stalled,
wrong_chain,
}))
}
2 changes: 2 additions & 0 deletions crates/randscan-api/src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod accounts;
mod auth;
mod blocks;
mod bridge;
mod chain;
mod envelopes;
mod health;
mod keys;
Expand All @@ -18,6 +19,7 @@ pub use accounts::*;
pub use auth::*;
pub use blocks::*;
pub use bridge::*;
pub use chain::get_chain;
pub use envelopes::*;
pub use health::*;
pub use keys::*;
Expand Down
2 changes: 2 additions & 0 deletions crates/randscan-api/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub fn create_router(state: AppState) -> Router {

let api = Router::new()
.route("/health", get(handlers::health))
// Read cross-origin by zusd.money (the CORS layer below covers every /api/v1 route).
.route("/chain", get(handlers::get_chain))
.route("/stats", get(handlers::get_stats))
.route("/blocks", get(handlers::list_blocks))
.route("/blocks/latest", get(handlers::latest_blocks))
Expand Down
207 changes: 207 additions & 0 deletions crates/randscan-api/tests/chain_sync.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
//! `GET /api/v1/chain` and the chain fields of `/api/v1/health` against a scripted node (site-sync
//! design, 2026-10-27): live on the pinned chain, behind by more than `MAX_LAG`, unreachable,
//! stalled, and a node that switches genesis under a running indexer, which stops writing until
//! the node comes back. Live indexer, needs `DATABASE_URL`. One lock: each test resets the shared
//! database to its own chain.

mod common;

use common::mock_node::*;
use common::*;
use randscan_core::ChainPin;
use serde_json::{json, Value};
use std::time::Duration;

const WAIT: Duration = Duration::from_secs(40);

static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// A previous run may have left this exact chain (same genesis) behind, which the first pass
/// would adopt as is; start from nothing.
async fn fresh(live: &LiveApp) {
let mut conn = live.pool.acquire().await.unwrap();
randscan_db::reset_chain_data(&mut conn, 0).await.unwrap();
}

async fn get(live: &LiveApp, path: &str) -> Value {
call(&live.app, json_req("GET", path, None, None)).await.2
}

#[tokio::test]
async fn chain_view_tracks_live_behind_unreachable_and_stalled() {
let _g = LOCK.lock().await;
let mut chain = MockChain::new(40, "sync-a");
for i in 0..3 {
chain.push_block(vec![tx(
40,
&format!("s{i}"),
Some(bundle(&format!("sa{i}"))),
json!({ "kind": "none" }),
)]);
}
chain.go_live();
let genesis = h("block-40-sync-a-0");
let node = start_mock_node(chain).await;
let pin = ChainPin::new(40, &genesis);
let Some(live) = live_app_pinned(test_config(), &node.url, "127.0.0.1", pin).await else {
eprintln!("skipping: DATABASE_URL unset");
return;
};
fresh(&live).await;
live.start();

// Live: the stored genesis is the node's and the pin, the head is the node's head.
let ch = live
.wait_for("/api/v1/chain", WAIT, |c| {
c["head_height"] == 3 && c["state"] == "live"
})
.await;
assert_eq!(ch["chain_id"], 40);
assert_eq!(ch["genesis_hash"], genesis);
assert_eq!(ch["node_genesis_hash"], genesis);
assert_eq!(ch["node_chain_id"], 40);
assert_eq!(ch["node_height"], 3);
assert_eq!(ch["lag"], 0);
assert_eq!(ch["halted"], false);
assert_eq!(ch["node_connected"], true);
assert_eq!(ch["expected_chain_id"], 40);
assert_eq!(ch["expected_genesis_hash"], genesis);
let head_ts = node.with_chain(|c| c.blocks[3]["timestamp_ms"].clone());
assert_eq!(ch["head_timestamp_ms"], head_ts);

let health = live
.wait_for("/api/v1/health", WAIT, |b| b["status"] == "healthy")
.await;
assert_eq!(health["genesis_hash"], genesis);
assert_eq!(health["head_timestamp_ms"], head_ts);
assert_eq!(health["stalled"], false);
assert_eq!(health["wrong_chain"], false);
// The pre-existing fields are unchanged.
assert_eq!(health["database"], true);
assert_eq!(health["indexer"]["current_height"], 3);
assert!(health["version"].is_string());

// zusd.money reads /chain from the browser: it must be readable cross-origin.
let req = axum::http::Request::builder()
.uri("/api/v1/chain")
.header("origin", "https://zusd.money")
.body(axum::body::Body::empty())
.unwrap();
let (status, headers, _) = call(&live.app, req).await;
assert_eq!(status, 200);
assert_eq!(
headers
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok()),
Some("*")
);

// Behind: the node announces 12 blocks it does not serve yet.
node.with_chain(|c| {
c.serve_up_to = Some(3);
for _ in 0..12 {
c.push_block(vec![]);
}
});
let ch = live
.wait_for("/api/v1/chain", WAIT, |c| c["state"] == "behind")
.await;
assert_eq!(ch["lag"], 12, "{ch}");
assert_eq!(ch["node_height"], 15);
assert_eq!(ch["head_height"], 3);

// Caught up again.
node.with_chain(|c| c.serve_up_to = None);
live.wait_for("/api/v1/chain", WAIT, |c| {
c["state"] == "live" && c["head_height"] == 15
})
.await;

// Unreachable: the node stops answering while the indexed head is still fresh.
node.with_chain(|c| c.fail.push(("rand_getHead".into(), None)));
let ch = live
.wait_for("/api/v1/chain", WAIT, |c| c["state"] == "unreachable")
.await;
assert_eq!(ch["node_connected"], false);
assert_eq!(ch["head_height"], 15, "the last good height stays: {ch}");

// Stalled: the same view once the head is older than STALL_MS (aged in the database rather
// than by waiting a minute).
sqlx::query("UPDATE blocks SET timestamp_ms = timestamp_ms - 120000")
.execute(&live.pool)
.await
.unwrap();
let ch = get(&live, "/api/v1/chain").await;
assert_eq!(ch["state"], "stalled", "{ch}");
let health = get(&live, "/api/v1/health").await;
assert_eq!(health["stalled"], true);
assert_eq!(health["status"], "degraded");
}

#[tokio::test]
async fn a_genesis_switch_stops_the_indexer_until_the_node_comes_back() {
let _g = LOCK.lock().await;
let mut chain = MockChain::new(41, "switch-a");
chain.push_block(vec![tx(
41,
"w0",
Some(bundle("wa0")),
json!({ "kind": "none" }),
)]);
chain.go_live();
let genesis_a = h("block-41-switch-a-0");
let node = start_mock_node(chain).await;
let pin = ChainPin::new(41, &genesis_a);
let Some(live) = live_app_pinned(test_config(), &node.url, "127.0.0.1", pin).await else {
eprintln!("skipping: DATABASE_URL unset");
return;
};
fresh(&live).await;
live.start();
live.wait_for("/api/v1/chain", WAIT, |c| {
c["head_height"] == 1 && c["state"] == "live"
})
.await;

// The node is re-pointed at another genesis with the same chain id and a longer chain.
let original = node.with_chain(|c| {
let mut other = MockChain::new(41, "switch-b");
for _ in 0..5 {
other.push_block(vec![]);
}
other.go_live();
std::mem::replace(c, other)
});
let ch = live
.wait_for("/api/v1/chain", WAIT, |c| c["halted"] == true)
.await;
assert_eq!(ch["state"], "wrong_chain");
assert_eq!(ch["genesis_hash"], genesis_a);
assert_eq!(ch["node_genesis_hash"], h("block-41-switch-b-0"));
let health = get(&live, "/api/v1/health").await;
assert_eq!(health["wrong_chain"], true);
assert_eq!(health["status"], "degraded");

tokio::time::sleep(Duration::from_secs(1)).await;
let (count, max): (i64, Option<i64>) =
sqlx::query_as("SELECT COUNT(*), MAX(height) FROM blocks")
.fetch_one(&live.pool)
.await
.unwrap();
assert_eq!((count, max), (2, Some(1)), "no block of the other genesis");
let b0 = get(&live, "/api/v1/blocks/0").await;
assert_eq!(b0["hash"], genesis_a);

// Back on the stored chain, with a new block: indexing resumes where it stopped.
node.with_chain(|c| {
*c = original;
c.push_block(vec![]);
});
let ch = live
.wait_for("/api/v1/chain", WAIT, |c| {
c["halted"] == false && c["head_height"] == 2
})
.await;
assert_eq!(ch["state"], "live", "{ch}");
assert_eq!(ch["genesis_hash"], genesis_a);
}
Loading
Loading