The network page said 5,669,940 QTC sits in the vesting pot and stopped there, which is the largest economic fact about this chain rendered as a single number. `/:chain/vesting` now carries the schedules, the release curve and the evidence. It is the only forward-looking page on the site and it is exact rather than projected: the runtime vests nothing before a grant's cliff, the whole grant from its end, and linearly between, so summing that across the schedules is arithmetic on chain state. `blackbeard-core::vesting` restates those three branches with tests, because until 2027 nothing on chain will contradict them — covering the cliff, the mid-window, the `end` branch that makes the final figure exactly `total` rather than `total` less a rounding crumb, the `start < cliff` case that unlocks a chunk at once, and a grant large enough that `total × elapsed` would wrap a `u128` if the product were not split. Decoded by field name against the metadata, never by offset. The figures that justified building this were read positionally out of 89 bytes and summed to the pot exactly — good evidence the layout was guessed right, and exactly the shortcut this repository forbids elsewhere. A captured mainnet entry now pins the names, so a reordered struct fails the build rather than quietly paying the wrong address. It also retires a weak claim. "Held in the vesting pot" rested on an eight-byte `PalletId` spelling `qvesting` and a `type PalletId` line read from a source tree that may not be the deployed commit. `matches_pot` replaces that with arithmetic: the grants sum to the pot's balance to within the existential deposit, and if a grant is ended or the pot topped up the page says the two have parted company rather than going on describing one as the other. Measured: 48 grants, 5,669,940.000 QTC scheduled against 5,669,940.001 held, nothing claimed, first unlock 2027-09-09, fully vested 2030-09-08. `Field` becomes one component instead of four. Going to add a fourth copy found that the three had already parted company — two rendered `note` as a visible caption, the third passed it to `title` as a hover — so the shared one takes both as separate props rather than silently changing a page. The same lesson `isStandings` records, found the same way. Closes #21 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
702 lines
28 KiB
Rust
702 lines
28 KiB
Rust
//! Per-chain runtime state, and the fanout to connected browsers.
|
|
//!
|
|
//! ## Locking
|
|
//!
|
|
//! [`ChainRuntime::inner`] is a `std::sync::RwLock`, not tokio's, and it is
|
|
//! **never held across an `.await`**. Everything under it is CPU work on
|
|
//! in-memory collections; making it async would add a scheduling hop to every
|
|
//! read for no benefit, and the tokio variant is the one that makes it *easy*
|
|
//! to accidentally hold a lock across an await and stall a worker.
|
|
//!
|
|
//! ## Fanout
|
|
//!
|
|
//! Messages are serialised **once**, at broadcast time, and every connected
|
|
//! socket writes the same `Arc<str>`. With a few hundred watchers and a
|
|
//! leaderboard every few seconds, serialising per client would be the single
|
|
//! largest cost in the process.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
use std::sync::{Arc, RwLock};
|
|
|
|
use blackbeard_core::attribution::Attributor;
|
|
use blackbeard_core::hashrate::{self, Interval};
|
|
use blackbeard_core::runtime::Runtime;
|
|
use blackbeard_core::window::RollingWindow;
|
|
use blackbeard_data::rpc::RpcClient;
|
|
use blackbeard_data::store::Store;
|
|
use blackbeard_data::telemetry::TelemetryFeed;
|
|
use blackbeard_entities::{
|
|
ChainId, ChainInfo, ChainStatus, ChainSummary, ClientVersion, LeaderboardRow, MinerId,
|
|
RecentBlock, ServerMessage, Tracking, Window,
|
|
};
|
|
use chrono::{DateTime, Utc};
|
|
use primitive_types::U512;
|
|
use tokio::sync::broadcast;
|
|
|
|
use crate::registry::ChainSpec;
|
|
|
|
/// One serialised message on its way to every subscriber of a chain.
|
|
#[derive(Debug)]
|
|
pub struct Broadcast {
|
|
/// The window this message is about, when it is window-specific.
|
|
///
|
|
/// A client watching the six-hour standings has no use for the week's, so
|
|
/// the socket task drops anything tagged with a window that is not the
|
|
/// one it subscribed to. `None` means "everyone gets this".
|
|
pub window: Option<Window>,
|
|
/// The message, already JSON.
|
|
pub json: Arc<str>,
|
|
}
|
|
|
|
/// How many messages a slow browser may fall behind before it is disconnected.
|
|
///
|
|
/// A tab that has been backgrounded on a bad connection must not make the
|
|
/// server buffer without limit. Lagging out is the right outcome: the client
|
|
/// reconnects and gets a fresh snapshot, which is cheaper and more correct than
|
|
/// replaying a queue of stale deltas.
|
|
const BROADCAST_CAPACITY: usize = 256;
|
|
|
|
/// Everything mutable about one chain.
|
|
#[derive(Debug)]
|
|
pub struct ChainInner {
|
|
/// Rolling window, sized to the longest selectable window.
|
|
pub window: RollingWindow,
|
|
/// Telemetry attribution votes.
|
|
pub attributor: Attributor,
|
|
/// The live block ticker, newest last.
|
|
pub ticker: std::collections::VecDeque<RecentBlock>,
|
|
/// Cached standings per window, with when each was computed.
|
|
///
|
|
/// The timestamp is what stops a REST-only caller reading a table that was
|
|
/// cached once and never refreshed: the recompute timer only runs for
|
|
/// windows a socket is watching, so without an age check a `curl` of the
|
|
/// leaderboard would return the same rows forever.
|
|
pub leaderboards: HashMap<Window, (std::time::Instant, Vec<LeaderboardRow>)>,
|
|
/// Current reachability.
|
|
pub status: ChainStatus,
|
|
/// Genesis hash, once the node has answered.
|
|
pub genesis: Option<String>,
|
|
/// Token ticker.
|
|
pub token_symbol: Option<String>,
|
|
/// Token decimals.
|
|
pub token_decimals: Option<u8>,
|
|
/// Parsed metadata per `spec_version`, so a block is decoded against the
|
|
/// runtime that produced it without re-parsing 100 KiB every time. Small:
|
|
/// one entry per runtime upgrade the observer has seen.
|
|
pub runtimes: HashMap<u32, Arc<Runtime>>,
|
|
/// The runtime the chain is on now, as of the last poll.
|
|
pub spec_version: Option<u32>,
|
|
/// Its `spec_name`. Carried rather than assumed: the whole approach here is
|
|
/// that the runtime names itself, and hardcoding `quantus-runtime` would be
|
|
/// the one line in this crate that knows which chain it is looking at.
|
|
pub spec_name: Option<String>,
|
|
/// Current difficulty.
|
|
pub difficulty: Option<U512>,
|
|
/// Ceiling difficulty.
|
|
pub max_difficulty: Option<U512>,
|
|
/// Whether the node is still importing history.
|
|
pub syncing: bool,
|
|
/// Best height seen.
|
|
pub height: Option<u64>,
|
|
/// When the last block was observed, for the ticker's gap figure.
|
|
pub last_block_at: Option<DateTime<Utc>>,
|
|
/// Nodes on this chain, from the telemetry directory.
|
|
pub node_count: Option<u32>,
|
|
/// The chain's name as the site shows it.
|
|
///
|
|
/// For a tracked chain this is the operator's name from config, not
|
|
/// telemetry's: config is intent, and a chain we run a node for should not
|
|
/// rename itself under the operator because someone edited a node's
|
|
/// `--name` upstream.
|
|
pub display_name: String,
|
|
}
|
|
|
|
/// A block waiting for the telemetry feed to settle before its author can be
|
|
/// attributed.
|
|
///
|
|
/// Lives beside the runtime rather than inside `ChainInner` because it is
|
|
/// touched on a different cadence — appended by ingest on every block, drained
|
|
/// by housekeeping once a second — and pairing it with the leaderboard's lock
|
|
/// would put both behind the same contention.
|
|
#[derive(Debug)]
|
|
pub struct PendingAttribution {
|
|
/// Block hash, the key the telemetry feed reports imports under.
|
|
pub hash: String,
|
|
/// Its author.
|
|
pub miner: blackbeard_entities::MinerId,
|
|
/// When to next ask the feed who reported this block first.
|
|
pub due: tokio::time::Instant,
|
|
/// When to stop asking and record an abstention.
|
|
///
|
|
/// The feed runs behind the chain by however much it is behind — measured
|
|
/// on mainnet at ~57 blocks, about a minute — so a single look at a fixed
|
|
/// offset asks before the answer exists and misses every time. This is
|
|
/// retried until the feed catches up or the block is too old to matter.
|
|
pub give_up: tokio::time::Instant,
|
|
}
|
|
|
|
impl ChainInner {
|
|
/// The parsed runtime for the version now in force, if its metadata has
|
|
/// been fetched. `None` before the first poll, and after a decode failure
|
|
/// clears `spec_version` to force a re-check.
|
|
pub fn current_runtime(&self) -> Option<Arc<Runtime>> {
|
|
self.runtimes.get(&self.spec_version?).cloned()
|
|
}
|
|
}
|
|
|
|
/// One chain, live.
|
|
#[derive(Debug)]
|
|
pub struct ChainRuntime {
|
|
/// How this chain is identified and reached.
|
|
pub spec: ChainSpec,
|
|
/// JSON-RPC client for this chain's node. Every runtime has one — a chain
|
|
/// with no endpoint gets no runtime, only a listing.
|
|
pub rpc: RpcClient,
|
|
/// Telemetry feed. Unconnected and inert when no URL is configured.
|
|
pub telemetry: TelemetryFeed,
|
|
/// Mutable state.
|
|
pub inner: RwLock<ChainInner>,
|
|
/// Fanout to connected browsers.
|
|
pub events: broadcast::Sender<Arc<Broadcast>>,
|
|
/// The chain's named accounts, and when they were last computed.
|
|
///
|
|
/// Computing them walks every plain storage entry and enumerates genesis,
|
|
/// which is dozens of RPC round trips — fine once, pathological on every
|
|
/// account page view. Constants change only with the runtime, state
|
|
/// assignments almost never, and genesis never, so a few minutes stale is
|
|
/// indistinguishable from fresh.
|
|
///
|
|
/// A tokio lock, not the `std` one `inner` uses: this is held across the
|
|
/// awaits that fill it, which is exactly what `inner` must never do.
|
|
pub roles: tokio::sync::RwLock<Option<(std::time::Instant, blackbeard_entities::ChainRoles)>>,
|
|
/// Concentration, cached the same way and for the same reason: computing it
|
|
/// walks every account on the chain, which is four round trips rather than
|
|
/// one and has no business happening on a page load.
|
|
pub concentration:
|
|
tokio::sync::RwLock<Option<(std::time::Instant, blackbeard_entities::Concentration)>>,
|
|
/// The vesting schedules and what they have released, cached the same way.
|
|
pub vesting:
|
|
tokio::sync::RwLock<Option<(std::time::Instant, blackbeard_entities::VestingSummary)>>,
|
|
/// Blocks awaiting their telemetry attribution.
|
|
pub pending_attributions: std::sync::Mutex<std::collections::VecDeque<PendingAttribution>>,
|
|
/// Live subscriber count per window, so the recompute timer can skip a
|
|
/// window nobody is looking at. A week window is a hundred thousand entries
|
|
/// to re-tally; computing all four every few seconds for an empty site
|
|
/// would be the daemon's largest cost while doing nothing for anyone.
|
|
subscribers: [AtomicUsize; 4],
|
|
}
|
|
|
|
impl ChainRuntime {
|
|
/// Build a runtime for a chain. Does no I/O.
|
|
pub fn new(spec: ChainSpec, rpc: RpcClient) -> Self {
|
|
let (events, _) = broadcast::channel(BROADCAST_CAPACITY);
|
|
Self {
|
|
inner: RwLock::new(ChainInner {
|
|
// Sized to the longest window: every shorter one is then a tail
|
|
// of the same buffer rather than separate state to keep in sync.
|
|
window: RollingWindow::new(Window::B100800.blocks() as usize),
|
|
attributor: Attributor::new(),
|
|
ticker: std::collections::VecDeque::new(),
|
|
leaderboards: HashMap::new(),
|
|
// Not `Unreachable`: nothing has failed yet, and a chain that
|
|
// has not launched must not read as broken.
|
|
status: ChainStatus::Awaiting,
|
|
token_symbol: None,
|
|
token_decimals: None,
|
|
runtimes: HashMap::new(),
|
|
spec_version: None,
|
|
spec_name: None,
|
|
difficulty: None,
|
|
max_difficulty: None,
|
|
syncing: false,
|
|
height: None,
|
|
last_block_at: None,
|
|
node_count: None,
|
|
display_name: spec.display_name.clone(),
|
|
genesis: spec.genesis.clone(),
|
|
}),
|
|
spec,
|
|
rpc,
|
|
telemetry: TelemetryFeed::new(),
|
|
events,
|
|
roles: tokio::sync::RwLock::new(None),
|
|
concentration: tokio::sync::RwLock::new(None),
|
|
vesting: tokio::sync::RwLock::new(None),
|
|
pending_attributions: std::sync::Mutex::new(std::collections::VecDeque::new()),
|
|
subscribers: Default::default(),
|
|
}
|
|
}
|
|
|
|
/// The chain's id on the wire: its slug.
|
|
pub fn id(&self) -> ChainId {
|
|
ChainId(self.spec.slug.clone())
|
|
}
|
|
|
|
/// Record the chain's node population, from the telemetry directory.
|
|
pub fn set_node_count(&self, count: Option<u32>) {
|
|
self.write().node_count = count;
|
|
}
|
|
|
|
/// What this observer can show for the chain.
|
|
pub fn tracking(&self) -> Tracking {
|
|
self.spec.tracking()
|
|
}
|
|
|
|
fn slot(window: Window) -> usize {
|
|
match window {
|
|
Window::B600 => 0,
|
|
Window::B3600 => 1,
|
|
Window::B14400 => 2,
|
|
Window::B100800 => 3,
|
|
}
|
|
}
|
|
|
|
/// Register interest in a window. Returns a guard that deregisters on drop,
|
|
/// so a dropped socket cannot leak a permanent subscriber.
|
|
pub fn watch(self: &Arc<Self>, window: Window) -> WindowGuard {
|
|
self.subscribers[Self::slot(window)].fetch_add(1, Ordering::Relaxed);
|
|
WindowGuard {
|
|
chain: Arc::clone(self),
|
|
window,
|
|
}
|
|
}
|
|
|
|
/// Windows currently worth computing.
|
|
pub fn watched_windows(&self) -> Vec<Window> {
|
|
Window::all()
|
|
.into_iter()
|
|
.filter(|w| self.subscribers[Self::slot(*w)].load(Ordering::Relaxed) > 0)
|
|
.collect()
|
|
}
|
|
|
|
/// Serialise and fan out a message.
|
|
///
|
|
/// A send with no receivers is not an error — an idle site is the normal
|
|
/// case, and there is nothing to do about it.
|
|
pub fn broadcast(&self, message: &ServerMessage, window: Option<Window>) {
|
|
let json = match serde_json::to_string(message) {
|
|
Ok(j) => j,
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "a server message failed to serialise");
|
|
return;
|
|
}
|
|
};
|
|
let _ = self.events.send(Arc::new(Broadcast {
|
|
window,
|
|
json: Arc::from(json.as_str()),
|
|
}));
|
|
}
|
|
|
|
/// The chain's current identity and reachability.
|
|
pub fn info(&self) -> ChainInfo {
|
|
let inner = self.read();
|
|
ChainInfo {
|
|
id: self.id(),
|
|
display_name: inner.display_name.clone(),
|
|
node_count: inner.node_count,
|
|
tracking: self.tracking(),
|
|
mainnet: self.spec.mainnet,
|
|
genesis: inner.genesis.clone(),
|
|
token_symbol: inner.token_symbol.clone(),
|
|
token_decimals: inner.token_decimals,
|
|
target_block_time_seconds: self.spec.target_block_time_seconds,
|
|
status: inner.status,
|
|
}
|
|
}
|
|
|
|
/// The interval to divide difficulty by, and whether it is nominal.
|
|
///
|
|
/// A measured interval is only used when the node is following the tip. A
|
|
/// syncing node imports history at disk speed, and dividing by *that*
|
|
/// yields a hashrate wrong by orders of magnitude while looking entirely
|
|
/// plausible on a chart.
|
|
fn interval(&self, inner: &ChainInner) -> Interval {
|
|
match inner.window.measured_interval() {
|
|
// Our own measurement, from blocks this observer watched arrive,
|
|
// over a window it controls. Preferred whenever it exists.
|
|
Some(measured) if !inner.syncing => Interval::Measured(measured),
|
|
// Telemetry's own average, until we have enough tip samples of our
|
|
// own. Still a measurement, just not ours — so it is not flagged
|
|
// nominal, but our own is preferred the moment it exists.
|
|
_ if !inner.syncing => match self.telemetry.average_block_time() {
|
|
Some(avg) => Interval::Measured(avg),
|
|
None => Interval::Target(self.spec.target_block_time_seconds),
|
|
},
|
|
_ => Interval::Target(self.spec.target_block_time_seconds),
|
|
}
|
|
}
|
|
|
|
/// The headline numbers.
|
|
pub fn summary(&self) -> ChainSummary {
|
|
let inner = self.read();
|
|
let interval = self.interval(&inner);
|
|
let (tallies, total) = inner.window.tally(Window::B3600.blocks() as usize);
|
|
ChainSummary {
|
|
chain: self.id(),
|
|
// A chain with no node of ours still has a height — telemetry's,
|
|
// which is the whole network's best block rather than one node's.
|
|
height: inner.height.or_else(|| self.telemetry.best_height()),
|
|
difficulty: inner.difficulty.map(hashrate::u512_to_dec),
|
|
max_difficulty: inner.max_difficulty.map(hashrate::u512_to_dec),
|
|
network_hashrate: inner
|
|
.difficulty
|
|
.map(|d| hashrate::network_hashrate(d, interval)),
|
|
hashrate_from_target: interval.is_nominal(),
|
|
block_interval_seconds: inner
|
|
.window
|
|
.measured_interval()
|
|
.or_else(|| self.telemetry.average_block_time()),
|
|
target_block_time_seconds: self.spec.target_block_time_seconds,
|
|
window_blocks: total,
|
|
distinct_miners: tallies.len() as u32,
|
|
telemetry_nodes: inner.node_count.or_else(|| self.telemetry.node_count()),
|
|
telemetry_connected: self.telemetry.connected(),
|
|
tracking: self.tracking(),
|
|
finalized_height: self.telemetry.finalized_height(),
|
|
client_versions: self
|
|
.telemetry
|
|
.versions()
|
|
.into_iter()
|
|
.map(|(version, nodes)| ClientVersion { version, nodes })
|
|
.collect(),
|
|
spec_version: inner.spec_version,
|
|
spec_name: inner.spec_name.clone(),
|
|
updated_at: Utc::now(),
|
|
}
|
|
}
|
|
|
|
/// Recompute the standings for `window` and cache them.
|
|
///
|
|
/// Returns the rows, and whether they differ from what was cached — the
|
|
/// caller broadcasts only on a change, so a quiet chain produces no traffic
|
|
/// rather than an identical table every few seconds.
|
|
pub fn recompute_leaderboard(&self, window: Window) -> (Vec<LeaderboardRow>, bool) {
|
|
let mut inner = self.write();
|
|
let (tallies, total) = inner.window.tally(window.blocks() as usize);
|
|
// The denominator of every share on the board, against what the window
|
|
// actually holds. See #13: these disagreed with the warm-start count by
|
|
// two orders of magnitude and nothing on the page said so.
|
|
tracing::debug!(
|
|
chain = %self.id(), window = ?window, asked = window.blocks(),
|
|
held = inner.window.len(), tallied = total,
|
|
"leaderboard recomputed"
|
|
);
|
|
// The window's own duration, by the chain's clock. Every per-miner
|
|
// hashrate is its summed work over this — not its share of the current
|
|
// network, which credits a miner that won while the network was small
|
|
// with a share of what the network is now.
|
|
let span = inner.window.span_seconds(window.blocks() as usize);
|
|
|
|
// Split the borrow: the tally is done, and `leaderboard` needs a mutable
|
|
// attributor while it walks the rows.
|
|
let ChainInner {
|
|
attributor,
|
|
leaderboards,
|
|
..
|
|
} = &mut *inner;
|
|
let telemetry = &self.telemetry;
|
|
let rows = blackbeard_core::window::leaderboard(&tallies, total, span, |miner| {
|
|
let a = attributor.attribute(miner, |key| telemetry.name_of(key));
|
|
(a.display, a.address, a.source, a.confidence, a.votes)
|
|
});
|
|
|
|
let changed = leaderboards.get(&window).map(|(_, cached)| cached) != Some(&rows);
|
|
leaderboards.insert(window, (std::time::Instant::now(), rows.clone()));
|
|
(rows, changed)
|
|
}
|
|
|
|
/// What a window actually spanned, by the chain's own clock.
|
|
///
|
|
/// The authored-time span of exactly the blocks the board tallied — the same
|
|
/// number that is already the denominator of every per-miner hashrate. The
|
|
/// label is built from this rather than from `blocks x interval`, which
|
|
/// describes the rate *now* and is wrong by however much the chain's rate
|
|
/// has moved since the oldest block in the window.
|
|
pub fn window_span_seconds(&self, window: Window) -> Option<f64> {
|
|
self.read().window.span_seconds(window.blocks() as usize)
|
|
}
|
|
|
|
/// The standings for a window, recomputing them if the cache has aged out.
|
|
pub fn leaderboard(&self, window: Window, max_age: std::time::Duration) -> Vec<LeaderboardRow> {
|
|
if let Some((computed_at, rows)) = self.read().leaderboards.get(&window)
|
|
&& computed_at.elapsed() < max_age
|
|
{
|
|
// What the reader is actually served, against what it was computed
|
|
// from. See #13: the recompute and the response disagreed by a
|
|
// factor of three and only the recompute was visible.
|
|
tracing::debug!(
|
|
chain = %self.id(), window = ?window, rows = rows.len(),
|
|
blocks = rows.iter().map(|r| r.blocks).sum::<u32>(),
|
|
age_ms = computed_at.elapsed().as_millis() as u64,
|
|
"leaderboard served from cache"
|
|
);
|
|
return rows.clone();
|
|
}
|
|
self.recompute_leaderboard(window).0
|
|
}
|
|
|
|
/// What to call one miner, resolved the same way the leaderboard does.
|
|
///
|
|
/// Takes the write lock because the attributor caches its vote tallies, and
|
|
/// the caller gets one name rather than a whole board it would throw away.
|
|
/// CPU-only work on in-memory collections, like everything else under this
|
|
/// lock, and never held across an await.
|
|
pub fn attribute(&self, miner: &MinerId) -> blackbeard_core::attribution::Attribution {
|
|
let mut inner = self.write();
|
|
let telemetry = &self.telemetry;
|
|
inner
|
|
.attributor
|
|
.attribute(miner, |key| telemetry.name_of(key))
|
|
}
|
|
|
|
/// The live ticker, oldest first.
|
|
pub fn ticker(&self) -> Vec<RecentBlock> {
|
|
self.read().ticker.iter().cloned().collect()
|
|
}
|
|
|
|
/// Read the mutable state.
|
|
pub fn read(&self) -> std::sync::RwLockReadGuard<'_, ChainInner> {
|
|
self.inner.read().unwrap_or_else(|e| e.into_inner())
|
|
}
|
|
|
|
/// Write the mutable state.
|
|
pub fn write(&self) -> std::sync::RwLockWriteGuard<'_, ChainInner> {
|
|
self.inner.write().unwrap_or_else(|e| e.into_inner())
|
|
}
|
|
}
|
|
|
|
/// Keeps a window counted as watched for as long as it is held.
|
|
pub struct WindowGuard {
|
|
chain: Arc<ChainRuntime>,
|
|
window: Window,
|
|
}
|
|
|
|
impl Drop for WindowGuard {
|
|
fn drop(&mut self) {
|
|
self.chain.subscribers[ChainRuntime::slot(self.window)].fetch_sub(1, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// Everything the HTTP handlers need.
|
|
#[derive(Clone)]
|
|
pub struct AppState {
|
|
/// The chain set: what exists, and which of it we can track.
|
|
pub registry: Arc<crate::registry::Registry>,
|
|
/// Postgres.
|
|
pub store: Store,
|
|
/// When the process started, for the health endpoint.
|
|
pub started: DateTime<Utc>,
|
|
/// How stale a cached leaderboard may be before a REST request rebuilds it.
|
|
pub leaderboard_max_age: std::time::Duration,
|
|
}
|
|
|
|
impl AppState {
|
|
/// Find a tracked chain by slug or genesis. `None` for a chain that is
|
|
/// listed but has no endpoint — those are not navigable.
|
|
pub fn chain(&self, id: &str) -> Option<Arc<ChainRuntime>> {
|
|
self.registry.get(id)
|
|
}
|
|
|
|
/// Every chain, tracked and not, ordered by node count descending.
|
|
pub fn chain_infos(&self) -> Vec<ChainInfo> {
|
|
self.registry.infos()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::time::Duration;
|
|
|
|
fn runtime() -> Arc<ChainRuntime> {
|
|
Arc::new(ChainRuntime::new(
|
|
ChainSpec {
|
|
slug: "planck".into(),
|
|
display_name: "Planck".into(),
|
|
genesis: None,
|
|
mainnet: false,
|
|
rpc_urls: vec!["http://127.0.0.1:9944".into()],
|
|
ws_urls: vec!["ws://127.0.0.1:9944".into()],
|
|
target_block_time_seconds: 6.0,
|
|
warm_start_blocks: 100,
|
|
max_gap_fill_blocks: 100,
|
|
},
|
|
RpcClient::new("http://127.0.0.1:9944", Duration::from_secs(5)).unwrap(),
|
|
))
|
|
}
|
|
|
|
/// The board must divide by what the window holds, not by a fraction of it.
|
|
///
|
|
/// #13: warm start logged `held=20058` and the board it served divided every
|
|
/// share by ~1,150. This drives the real path — push, then
|
|
/// `recompute_leaderboard` — rather than `RollingWindow` alone, because the
|
|
/// window's own arithmetic is already pinned in `blackbeard-core` and it is
|
|
/// the wiring that is in question.
|
|
#[test]
|
|
fn the_board_divides_by_the_whole_restored_window() {
|
|
use blackbeard_core::window::Observed;
|
|
|
|
let c = runtime();
|
|
{
|
|
let mut inner = c.write();
|
|
for h in 1..=20_058u64 {
|
|
inner.window.push(
|
|
Observed {
|
|
height: h,
|
|
miner: blackbeard_entities::MinerId(format!("m{}", h % 5)),
|
|
observed_at: chrono::Utc::now(),
|
|
authored_at: Some(chrono::Utc::now()),
|
|
difficulty: Some(1.0),
|
|
},
|
|
false,
|
|
);
|
|
}
|
|
assert_eq!(inner.window.len(), 20_058, "the restore has to land");
|
|
}
|
|
|
|
let (rows, _) = c.recompute_leaderboard(Window::B100800);
|
|
let served: u32 = rows.iter().map(|r| r.blocks).sum();
|
|
assert_eq!(
|
|
served, 20_058,
|
|
"the board divided by {served} of {} blocks held",
|
|
20_058
|
|
);
|
|
|
|
let (rows, _) = c.recompute_leaderboard(Window::B3600);
|
|
let served: u32 = rows.iter().map(|r| r.blocks).sum();
|
|
assert_eq!(
|
|
served, 3_600,
|
|
"a six-hour board over a full window is 3,600"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn nothing_is_computed_for_a_window_nobody_is_watching() {
|
|
let c = runtime();
|
|
assert!(c.watched_windows().is_empty());
|
|
let guard = c.watch(Window::B3600);
|
|
assert_eq!(c.watched_windows(), vec![Window::B3600]);
|
|
drop(guard);
|
|
// A dropped socket must not leave its window pinned forever.
|
|
assert!(c.watched_windows().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn several_watchers_of_one_window_all_have_to_leave() {
|
|
let c = runtime();
|
|
let a = c.watch(Window::B14400);
|
|
let b = c.watch(Window::B14400);
|
|
drop(a);
|
|
assert_eq!(c.watched_windows(), vec![Window::B14400]);
|
|
drop(b);
|
|
assert!(c.watched_windows().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_chain_that_has_never_answered_is_awaiting_not_unreachable() {
|
|
// Mainnet is configured before it launches. "Unreachable" would read as
|
|
// a broken deployment for weeks.
|
|
assert_eq!(runtime().info().status, ChainStatus::Awaiting);
|
|
}
|
|
|
|
#[test]
|
|
fn hashrate_is_nominal_until_the_node_is_at_the_tip() {
|
|
let c = runtime();
|
|
{
|
|
let mut inner = c.write();
|
|
inner.difficulty = Some(U512::from(1_200_000_000u64));
|
|
inner.syncing = true;
|
|
for h in 1..=20u64 {
|
|
inner.window.push(
|
|
blackbeard_core::window::Observed {
|
|
authored_at: None,
|
|
difficulty: None,
|
|
height: h,
|
|
miner: blackbeard_entities::MinerId(format!("0x{:064x}", 1)),
|
|
observed_at: Utc::now(),
|
|
},
|
|
true,
|
|
);
|
|
}
|
|
}
|
|
let summary = c.summary();
|
|
// Twenty blocks imported in well under a second would otherwise read as
|
|
// an astronomical hashrate.
|
|
assert!(summary.hashrate_from_target);
|
|
assert_eq!(summary.network_hashrate, Some(200_000_000.0));
|
|
}
|
|
|
|
#[test]
|
|
fn identical_standings_report_no_change() {
|
|
let c = runtime();
|
|
{
|
|
let mut inner = c.write();
|
|
for h in 1..=10u64 {
|
|
inner.window.push(
|
|
blackbeard_core::window::Observed {
|
|
authored_at: None,
|
|
difficulty: None,
|
|
height: h,
|
|
miner: blackbeard_entities::MinerId(format!("0x{:064x}", h % 3)),
|
|
observed_at: Utc::now(),
|
|
},
|
|
true,
|
|
);
|
|
}
|
|
}
|
|
assert!(
|
|
c.recompute_leaderboard(Window::B600).1,
|
|
"first compute is a change"
|
|
);
|
|
assert!(
|
|
!c.recompute_leaderboard(Window::B600).1,
|
|
"an unchanged table must not be rebroadcast every few seconds"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_stale_cache_is_recomputed_rather_than_served() {
|
|
// Only windows a socket is watching get refreshed by the timer, so
|
|
// without an age check a REST caller would read the same rows forever.
|
|
let c = runtime();
|
|
{
|
|
let mut inner = c.write();
|
|
inner.window.push(
|
|
blackbeard_core::window::Observed {
|
|
authored_at: None,
|
|
difficulty: None,
|
|
height: 1,
|
|
miner: blackbeard_entities::MinerId(format!("0x{:064x}", 1)),
|
|
observed_at: Utc::now(),
|
|
},
|
|
true,
|
|
);
|
|
}
|
|
assert_eq!(
|
|
c.leaderboard(Window::B600, Duration::from_secs(60)).len(),
|
|
1
|
|
);
|
|
{
|
|
let mut inner = c.write();
|
|
inner.window.push(
|
|
blackbeard_core::window::Observed {
|
|
authored_at: None,
|
|
difficulty: None,
|
|
height: 2,
|
|
miner: blackbeard_entities::MinerId(format!("0x{:064x}", 2)),
|
|
observed_at: Utc::now(),
|
|
},
|
|
true,
|
|
);
|
|
}
|
|
// A cache still inside its age is served as-is...
|
|
assert_eq!(
|
|
c.leaderboard(Window::B600, Duration::from_secs(60)).len(),
|
|
1
|
|
);
|
|
// ...and one past it is rebuilt.
|
|
assert_eq!(c.leaderboard(Window::B600, Duration::ZERO).len(), 2);
|
|
}
|
|
}
|