diff --git a/apps/tui/src/controller.ts b/apps/tui/src/controller.ts index 5a91ada8..119d7a10 100644 --- a/apps/tui/src/controller.ts +++ b/apps/tui/src/controller.ts @@ -18,7 +18,7 @@ import { jobTimesDir, probeLatest, probeLogs, - probeStatus, + probeMessages, probeStatus, probeVersion, probeWorker, readJobTimes, @@ -89,6 +89,7 @@ export class Controller { void this.refreshLogs(); void this.refreshVersion(); void this.refreshNetwork(); + void this.refreshMessages(); }, 0); const every = (ms: number, fn: () => void) => { const t = setInterval(fn, ms); @@ -104,6 +105,7 @@ export class Controller { every(3000, () => this.refreshWorker()); every(6000, () => this.state.tab === "node" && void this.refreshLogs()); every(30_000, () => void this.refreshStatus()); + every(5 * 60_000, () => void this.refreshMessages()); every(30_000, () => (this.state.tab === "network" ? void this.refreshNetwork() : undefined)); every(120_000, () => (this.state.tab !== "network" ? void this.refreshNetwork() : undefined)); every(60_000, () => void this.refreshAccount()); @@ -185,6 +187,16 @@ export class Controller { }); } + /** Messages people sent to this node (`c0mpute dm read --json`). */ + refreshMessages(): Promise { + return this.once("messages", async () => { + const messages = await probeMessages(c0mputeBin()); + const before = this.state.node.messages?.total ?? 0; + this.set({ node: { ...this.state.node, messages } }); + if (messages.total > before && before > 0) this.toast(`${messages.total - before} new message(s) for this node: m shows them`); + }); + } + refreshVersion(): Promise { return this.once("version", async () => { const bin = c0mputeBin(); @@ -783,6 +795,11 @@ export class Controller { this.set({ nodePanel: this.state.nodePanel === "bench" ? "roles" : "bench" }); } + toggleMessages(): void { + this.set({ nodePanel: this.state.nodePanel === "messages" ? "roles" : "messages" }); + if (this.state.nodePanel === "messages") void this.refreshMessages(); + } + scrollNode(delta: number): void { this.set({ nodeScroll: Math.max(0, this.state.nodeScroll + delta) }); } diff --git a/apps/tui/src/demo.ts b/apps/tui/src/demo.ts index 01c3e2c0..f65a623d 100644 --- a/apps/tui/src/demo.ts +++ b/apps/tui/src/demo.ts @@ -168,6 +168,16 @@ export function demoState(): AppState { { time: "11:59:40", level: "WARN", message: "c0mpute_core::diffusion: load gate: not bidding on diffusion.txt2img" }, ], logSource: "journalctl -u c0mpute-worker", + messages: { + address: "4f1c9a2e7b3d5c8f0a6e2b4d9c1f7a3e5b8d0c2f4a6e8b1d3f5a7c9e2b4d6f8a", + total: 2, + fresh: 1, + messages: [ + { id: "m1", from: "9a1b", name: "9a1b2c3d", text: "Hi! Your node is fast on qwen2.5:7b, thanks for running it.", created_at: Math.floor(NOW / 1000) - 7200, via: "mailbox" }, + { id: "m2", from: "c0ff", name: "riotcoder", text: "Your node fails most inference jobs: the buyer cannot reach it. Is outbound TCP blocked?", created_at: Math.floor(NOW / 1000) - 300, via: "direct" }, + ], + error: null, + }, }, net: { status: { diff --git a/apps/tui/src/keys.ts b/apps/tui/src/keys.ts index 0850899b..34132ff5 100644 --- a/apps/tui/src/keys.ts +++ b/apps/tui/src/keys.ts @@ -68,8 +68,10 @@ export function handleKey(ctl: Controller, e: KeyEvent): "quit" | void { void ctl.refreshStatus(); void ctl.refreshLogs(); void ctl.refreshVersion(); + void ctl.refreshMessages(); ctl.toast("re-checking the node (c0mpute status --json)…"); } else if (is(e, "b")) ctl.toggleBench(); + else if (is(e, "m")) ctl.toggleMessages(); else if (is(e, "up", "k")) ctl.scrollNode(-1); else if (is(e, "down", "j")) ctl.scrollNode(1); else if (is(e, "pageup")) ctl.scrollNode(-10); diff --git a/apps/tui/src/node.ts b/apps/tui/src/node.ts index 5e90e8b2..021f7a3b 100644 --- a/apps/tui/src/node.ts +++ b/apps/tui/src/node.ts @@ -313,6 +313,50 @@ export interface NodeSnapshot { jobTimes: JobTime[]; logs: LogLine[]; logSource: string; + /** Messages people sent to this node (`c0mpute dm read --json`). */ + messages: NodeMessages | null; +} + +/** One message sent to this node. */ +export interface NodeMessage { + id: string; + from: string; + name: string; + text: string; + created_at: number; + via: string; +} + +/** `c0mpute dm read --json`: messages people sent to this node with `c0mpute dm send `. */ +export interface NodeMessages { + address: string | null; + total: number; + fresh: number; + messages: NodeMessage[]; + error: string | null; +} + +export function parseMessagesJson(text: string): NodeMessages | null { + try { + const v = JSON.parse(text.trim().split("\n").filter((l) => l.startsWith("{")).pop() ?? "") as { + address?: string; total?: number; new?: number; messages?: NodeMessage[]; + }; + if (!v || !Array.isArray(v.messages)) return null; + return { address: v.address ?? null, total: v.total ?? v.messages.length, fresh: v.new ?? 0, messages: v.messages, error: null }; + } catch { + return null; + } +} + +export async function probeMessages(bin: string): Promise { + const r = await run(bin, ["dm", "read", "--json", "--limit", "30"], 60_000); + const parsed = r.code === 0 ? parseMessagesJson(r.stdout) : null; + if (parsed) return parsed; + const last = (r.stderr || r.stdout || "").trim().split("\n").slice(-1)[0] ?? ""; + const error = /unrecognized subcommand|unexpected argument/.test(r.stderr) + ? "this c0mpute is older than 0.3.74: c0mpute update adds node messages" + : last || "c0mpute dm read failed"; + return { address: null, total: 0, fresh: 0, messages: [], error }; } export function emptyNode(cliPath = "c0mpute"): NodeSnapshot { @@ -329,6 +373,7 @@ export function emptyNode(cliPath = "c0mpute"): NodeSnapshot { jobTimes: [], logs: [], logSource: "", + messages: null, }; } diff --git a/apps/tui/src/state.ts b/apps/tui/src/state.ts index c794af86..c9f5fdbc 100644 --- a/apps/tui/src/state.ts +++ b/apps/tui/src/state.ts @@ -81,7 +81,7 @@ export interface AppState { jobSel: number; node: NodeSnapshot; bench: BenchState; - nodePanel: "roles" | "bench"; + nodePanel: "roles" | "bench" | "messages"; nodeScroll: number; net: { status: Loadable; nodes: Loadable; pricing: Loadable }; netPanel: "nodes" | "prices"; diff --git a/apps/tui/src/views/app.ts b/apps/tui/src/views/app.ts index 001858f9..efd7ecf2 100644 --- a/apps/tui/src/views/app.ts +++ b/apps/tui/src/views/app.ts @@ -56,6 +56,7 @@ export function tabKeys(state: AppState): { key: string; label: string }[] { return [ { key: "r", label: "re-check" }, { key: "b", label: state.nodePanel === "bench" ? "roles" : "bench" }, + { key: "m", label: state.nodePanel === "messages" ? "roles" : "messages" }, { key: "↑↓", label: "scroll" }, ]; case "network": diff --git a/apps/tui/src/views/node.ts b/apps/tui/src/views/node.ts index c863764f..9f2924ad 100644 --- a/apps/tui/src/views/node.ts +++ b/apps/tui/src/views/node.ts @@ -71,6 +71,16 @@ export function summaryRows(node: NodeSnapshot, state: AppState, theme: Theme): rows.push({ label: "earned", value: `$${Number(me.balance.earned_spendable_usd).toFixed(4)} spendable from your nodes · balance $${Number(me.balance.spendable_usd).toFixed(2)}`, color: theme.accent }); } const b = state.bench.bench; + const msgs = node.messages; + rows.push( + !msgs + ? { label: "messages", value: "checking…", color: theme.muted } + : msgs.error + ? { label: "messages", value: msgs.error, color: theme.muted } + : msgs.total === 0 + ? { label: "messages", value: "none yet · people reach you with c0mpute dm send ", color: theme.muted } + : { label: "messages", value: `${msgs.total}${msgs.fresh ? ` (${msgs.fresh} new)` : ""} · latest from ${msgs.messages[msgs.messages.length - 1]?.name ?? "?"} · m shows them`, color: theme.accent }, + ); rows.push({ label: "bench", value: b ? `score ${b.score.toLocaleString("en-US")}${b.metadata.quick ? " (quick run, not advertised)" : ""} · b shows it` : "no score: c0mpute bench", color: b ? theme.accent : theme.muted }); return rows; } @@ -112,6 +122,38 @@ export function roleLines(node: NodeSnapshot, width: number, theme: Theme): Line return out; } +/** Messages people sent to this node, newest last (`c0mpute dm read`). */ +export function messageLines(node: NodeSnapshot, width: number, theme: Theme, now: number): Line[] { + const m = node.messages; + if (!m) return [{ text: "asking c0mpute dm read…", fg: theme.muted }]; + if (m.error) return wrapBlock(m.error, width, "").map((t) => ({ text: t, fg: theme.warning })); + const out: Line[] = []; + if (m.address) out.push({ text: `this node's DM address ${m.address.slice(0, 16)}…`, fg: theme.muted }); + if (!m.messages.length) { + out.push({ text: "" }); + for (const t of wrapBlock("No messages yet. Anyone can message whoever runs this node with `c0mpute dm send \"...\"`; a contact email (`c0mpute contact `) shows on c0mpute.com/nodes too.", width, "")) + out.push({ text: t, fg: theme.muted }); + return out; + } + for (const msg of m.messages) { + out.push({ text: "" }); + const age = Math.max(0, Math.floor(now / 1000) - msg.created_at); + out.push({ text: `${msg.name} · ${duration(age)} ago · ${msg.via}`, fg: theme.accent, bold: true }); + for (const t of wrapBlock(msg.text, width, " ")) out.push({ text: t, fg: theme.foreground }); + } + out.push({ text: "" }); + out.push({ text: "reply: c0mpute dm send \"...\" · r refreshes · m goes back", fg: theme.muted }); + return out; +} + +function messagesPanel(parent: Container, state: AppState, theme: Theme): void { + panel(parent, theme, "Messages", { subtitle: "m: back · r: refresh" }, (p) => { + p.draw((surface) => { + drawLines(surface, messageLines(state.node, surface.width - 1, theme, state.now), state.nodeScroll, theme, true); + }); + }); +} + function benchPanel(parent: Container, state: AppState, theme: Theme): void { const report = state.bench.bench; panel( @@ -182,7 +224,8 @@ export function renderNode(ui: Container, state: AppState, theme: Theme, h: Node }); const roles = (parent: Container) => { if (state.nodePanel === "bench") return benchPanel(parent, state, theme); - panel(parent, theme, "Roles", { subtitle: "b: bench" }, (p) => { + if (state.nodePanel === "messages") return messagesPanel(parent, state, theme); + panel(parent, theme, "Roles", { subtitle: "b: bench · m: messages" }, (p) => { p.draw((surface) => { drawLines(surface, roleLines(node, surface.width - 1, theme), state.nodeScroll, theme, false); p.ctx.hit({ rect: surface.hitRect(), onScroll: (d) => h.onScrollRoles?.(d * 2) }); diff --git a/apps/web/src/app/nodes/page.tsx b/apps/web/src/app/nodes/page.tsx index 7bb16a92..f3f6d73e 100644 --- a/apps/web/src/app/nodes/page.tsx +++ b/apps/web/src/app/nodes/page.tsx @@ -185,6 +185,16 @@ export default async function NodesPage() { {n.name ? {n.name} : unnamed} {n.id} + {n.contact && /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z0-9-]+$/.test(n.contact) && ( + + {n.contact} + + )} + {n.dm && ( + + c0mpute dm send {n.id} "…" + + )} {n.donates?.includes("crowdgpt") && ( donates idle to CrowdGPT @@ -279,6 +289,13 @@ $ c0mpute name # check what is set`} who gets paid: earnings go to the payout address set on the node (infernet payout set), never to a name. Needs c0mpute 0.2.64 or newer (c0mpute update).

+

+ Add a contact email too, so people who use your node (and the + network's maintainers, if it starts failing jobs) can reach you. + It is optional and shown publicly under your node's name: +

+ {`$ c0mpute contact ops@example.com # set it, then restart the worker +$ curl -fsSL https://c0mpute.com/install.sh | sh -s -- --contact ops@example.com`} {p.operators.length > 0 && ( diff --git a/apps/web/src/lib/nodes.ts b/apps/web/src/lib/nodes.ts index b82c773b..a291f51b 100644 --- a/apps/web/src/lib/nodes.ts +++ b/apps/web/src/lib/nodes.ts @@ -21,6 +21,14 @@ export interface NodeRow { ref: string | null; /** The operator's nickname (`c0mpute name`); absent on nodes older than 0.2.64. */ name?: string | null; + /** + * The email the operator offers for questions about this node (`c0mpute + * contact`), public by their choice; the aggregator passes only plain + * addresses. Absent when unset and on nodes older than 0.3.74. + */ + contact?: string | null; + /** The node's secure-chat address: message whoever runs it with `c0mpute dm send ` (0.3.74+). */ + dm?: string | null; /** The operator's listing; absent on nodes older than 0.2.35. */ pricing?: Pricing | null; /** diff --git a/node/crates/c0mpute-cli/src/dm_cli.rs b/node/crates/c0mpute-cli/src/dm_cli.rs index 3a1b815d..25d2bf90 100644 --- a/node/crates/c0mpute-cli/src/dm_cli.rs +++ b/node/crates/c0mpute-cli/src/dm_cli.rs @@ -44,6 +44,28 @@ struct Session { } impl Session { + /// This node's own DM session (`c0mpute dm read`): the node's key from + /// `node-dm.secret`, no password, and a state file of its own. + fn node() -> Result { + let dir = config::config_dir().context("cannot find the c0mpute config directory")?; + let key = dm::node_chat_key(&dir, false)?; + let state_path = config::data_dir() + .unwrap_or_else(|| std::path::PathBuf::from(".")) + .join("dm") + .join("node-state.enc"); + if let Some(parent) = state_path.parent() { + std::fs::create_dir_all(parent)?; + } + let state = LocalState::load(&state_path, &key)?; + let cfg = Config::load_or_default(&config::default_config_path())?; + Ok(Self { + key, + state, + state_path, + cfg, + }) + } + fn open() -> Result { let path = chat::key_file_path()?; let kf = chat::load_keyfile(&path).with_context(|| "no chat key yet: run `c0mpute dm keygen`".to_string())?; @@ -82,6 +104,21 @@ impl Session { if let Some(id) = self.state.resolve(who) { return Ok(id); } + // A node (its peer id, or the 8-character id c0mpute.com/nodes shows): + // DM whoever runs it, at the node's own address. + if let Some(node) = node_target(who) { + let Some(net) = net else { + bail!("node {node}: messaging a node needs the network"); + }; + let address = node_dm_address(&node).await?; + return match net.lookup(&address).await { + Some(id) => { + self.state.remember(&id); + Ok(id) + } + None => bail!("node {node} has a DM address but its key is not on the network yet: try again in a minute"), + }; + } let Some(net) = net else { bail!("unknown recipient {who}: use an address, fingerprint, contact name, or c0dm1. identity"); }; @@ -100,6 +137,45 @@ impl Session { } } +/// `who` as a node: a full libp2p peer id (12D3KooW...), or the 8-character +/// node id c0mpute.com/nodes shows (its last 8 characters). Returns the +/// 8-character id. Contact names, addresses and fingerprints are never these +/// (addresses and fingerprints are lowercase hex of 64 and 16 characters). +fn node_target(who: &str) -> Option { + let w = who.trim(); + let alnum = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric()); + if w.starts_with("12D3KooW") && w.len() >= 46 && alnum(w) { + return Some(w[w.len() - 8..].to_string()); + } + let has_upper = w.chars().any(|c| c.is_ascii_uppercase()); + (w.len() == 8 && alnum(w) && has_upper).then(|| w.to_string()) +} + +/// A node's DM address from the public node list (c0mpute.com/api/nodes; +/// `C0MPUTE_NODES_URL` overrides it). +async fn node_dm_address(node: &str) -> Result { + let url = std::env::var("C0MPUTE_NODES_URL").unwrap_or_else(|_| "https://c0mpute.com/api/nodes".into()); + let body: serde_json::Value = reqwest::Client::builder() + .timeout(Duration::from_secs(15)) + .build()? + .get(&url) + .send() + .await + .with_context(|| format!("fetch {url}"))? + .error_for_status()? + .json() + .await?; + let found = body["nodes"].as_array().into_iter().flatten().find(|n| n["id"].as_str() == Some(node)); + let Some(n) = found else { + bail!("no node {node} on {url} right now (is it online?)"); + }; + if let Some(addr) = n["dm"].as_str() { + return Ok(addr.to_string()); + } + let contact = n["contact"].as_str().map(|c| format!(" Its operator lists a contact: {c}")).unwrap_or_default(); + bail!("node {node} cannot receive DMs yet: it runs c0mpute older than 0.3.74.{contact}") +} + /// Boot the client node and wait briefly for mailboxes. async fn connect(s: &Session) -> Result { let id_dir = config::data_dir() @@ -163,48 +239,7 @@ pub async fn run_chat(cmd: ChatCmd) -> Result<()> { } ChatCmd::Pull => { let mut s = Session::open()?; - s.register_home(); - let now = unix_now(); - let me = s.key.address(); - let mut new = 0usize; - let mut dropped = 0usize; - let mut bad = 0usize; - // 1. Direct deliveries on this machine's node. - let spool_dir = s.paths().spool; - if spool_dir.exists() { - let mut spool = Mailbox::open(&spool_dir, Limits::default(), now); - for tag in pull_tags(&me, now) { - for (id, bytes) in spool.fetch(&tag, now) { - let res = chat::SealedMessage::parse(&bytes) - .and_then(|m| s.state.receive(&s.key, &m, "direct", now)); - match res { - Ok(r) => { - tally(&r, &mut new, &mut dropped); - spool.ack(&tag, &id, r.ack()); - } - Err(e) => { - bad += 1; - eprintln!("skipped a direct message: {e}"); - } - } - } - } - } - // 2. Mailboxes. - let net = connect(&s).await?; - for f in net.fetch(&me).await { - match s.state.receive(&s.key, &f.msg, "mailbox", unix_now()) { - Ok(r) => { - tally(&r, &mut new, &mut dropped); - net.ack(&f, r.ack()).await; - } - Err(e) => { - bad += 1; - eprintln!("skipped a mailbox message: {e}"); - } - } - } - s.save()?; + let (new, dropped, bad) = pull_all(&mut s).await?; println!( "{new} new message(s){}{}", if dropped > 0 { format!(", {dropped} from blocked senders dropped") } else { String::new() }, @@ -215,6 +250,42 @@ pub async fn run_chat(cmd: ChatCmd) -> Result<()> { } Ok(()) } + ChatCmd::Read { limit, json } => { + let mut s = Session::node()?; + let (new, dropped, bad) = pull_all(&mut s).await?; + let start = s.state.inbox.len().saturating_sub(limit); + if json { + let messages: Vec = s.state.inbox[start..] + .iter() + .map(|m| { + serde_json::json!({ + "id": m.id, "from": m.from, "name": s.state.name_of(&m.from), "text": m.text, + "created_at": m.created_at, "received_at": m.received_at, "via": m.via, + }) + }) + .collect(); + println!( + "{}", + serde_json::json!({ + "address": s.key.address(), "new": new, "dropped": dropped, "rejected": bad, + "total": s.state.inbox.len(), "messages": messages, + }) + ); + } else { + println!("node address: {}", s.key.address()); + println!( + "{new} new message(s){}{}", + if dropped > 0 { format!(", {dropped} from blocked senders dropped") } else { String::new() }, + if bad > 0 { format!(", {bad} rejected") } else { String::new() } + ); + if s.state.inbox.is_empty() { + println!("no messages yet. People reach this node with `c0mpute dm send \"...\"`"); + } else { + print_inbox(&s.state, limit); + } + } + Ok(()) + } ChatCmd::Inbox { limit } => { let s = Session::open()?; if s.state.inbox.is_empty() { @@ -311,6 +382,54 @@ fn tally(r: &Received, new: &mut usize, dropped: &mut usize) { } } +/// Fetch new messages for `s`'s key: direct deliveries in this machine's node +/// spool, then the mailboxes. Saves the state. (new, dropped, rejected). +async fn pull_all(s: &mut Session) -> Result<(usize, usize, usize)> { + s.register_home(); + let now = unix_now(); + let me = s.key.address(); + let mut new = 0usize; + let mut dropped = 0usize; + let mut bad = 0usize; + // 1. Direct deliveries on this machine's node. + let spool_dir = s.paths().spool; + if spool_dir.exists() { + let mut spool = Mailbox::open(&spool_dir, Limits::default(), now); + for tag in pull_tags(&me, now) { + for (id, bytes) in spool.fetch(&tag, now) { + let res = chat::SealedMessage::parse(&bytes) + .and_then(|m| s.state.receive(&s.key, &m, "direct", now)); + match res { + Ok(r) => { + tally(&r, &mut new, &mut dropped); + spool.ack(&tag, &id, r.ack()); + } + Err(e) => { + bad += 1; + eprintln!("skipped a direct message: {e}"); + } + } + } + } + } + // 2. Mailboxes. + let net = connect(&s).await?; + for f in net.fetch(&me).await { + match s.state.receive(&s.key, &f.msg, "mailbox", unix_now()) { + Ok(r) => { + tally(&r, &mut new, &mut dropped); + net.ack(&f, r.ack()).await; + } + Err(e) => { + bad += 1; + eprintln!("skipped a mailbox message: {e}"); + } + } + } + s.save()?; + Ok((new, dropped, bad)) +} + fn print_inbox(state: &LocalState, limit: usize) { let start = state.inbox.len().saturating_sub(limit); for m in &state.inbox[start..] { @@ -391,3 +510,22 @@ fn key_cmd(cmd: KeyCmd) -> Result<()> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn node_ids_are_told_apart_from_people() { + // A full libp2p peer id names the node by its last 8 characters. + assert_eq!(node_target("12D3KooWCMnyGXtT1DvWyVDSZwEqYL45V2UnanXiLpHbmgsu3m6q").as_deref(), Some("mgsu3m6q")); + // The 8-character id c0mpute.com/nodes shows (mixed case). + assert_eq!(node_target("fdxBAdC8").as_deref(), Some("fdxBAdC8")); + // Addresses and fingerprints are lowercase hex; contact names are anything else. + assert_eq!(node_target(&"ab".repeat(32)), None, "a 64-char address is a person"); + assert_eq!(node_target("0123456789abcdef"), None, "a fingerprint is a person"); + assert_eq!(node_target("sergey"), None); + assert_eq!(node_target("deadbeef"), None, "8 lowercase chars stay a contact name"); + assert_eq!(node_target("12D3KooWshort"), None); + } +} diff --git a/node/crates/c0mpute-cli/src/main.rs b/node/crates/c0mpute-cli/src/main.rs index 61988d43..ac92322c 100644 --- a/node/crates/c0mpute-cli/src/main.rs +++ b/node/crates/c0mpute-cli/src/main.rs @@ -131,6 +131,21 @@ enum Cmd { #[arg(long, conflicts_with = "handle")] clear: bool, }, + /// Show or set the contact email for questions about this node. + /// + /// Optional and PUBLIC: it is shown next to your node on + /// c0mpute.com/nodes so callers and the network's maintainers can reach + /// you (say, when your node keeps failing jobs). `c0mpute contact` prints + /// it, `c0mpute contact ` sets it, `--clear` removes it. Stored in + /// `~/.c0mpute/contact` (`C0MPUTE_CONTACT` overrides it). A running worker + /// picks a change up on restart. + Contact { + /// The email to show, e.g. `ops@example.com`. + email: Option, + /// Remove the contact email. + #[arg(long, conflicts_with = "email")] + clear: bool, + }, /// Private mode: serve only your own machines, stay off the public list. /// /// A private node only bids on jobs whose signed publisher is one of the @@ -1484,6 +1499,18 @@ enum ChatCmd { #[arg(long, default_value_t = 50)] limit: usize, }, + /// Read messages sent to this NODE (`c0mpute dm send `): fetch + /// new ones, then show the most recent. No keygen or password: the key is + /// the node's own (`node-dm.secret`). Use sudo if the worker runs as a + /// system service. + Read { + /// Most recent N messages. + #[arg(long, default_value_t = 20)] + limit: usize, + /// Machine-readable output (the TUI uses it). + #[arg(long)] + json: bool, + }, /// Resolve a fingerprint or address to a full public key. Lookup { query: String }, /// Contacts (stored locally, encrypted under your key). Lists by default. @@ -1812,6 +1839,7 @@ async fn run_app(cli: Cli) -> Result<()> { } Cmd::Pricing { cmd } => run_pricing(cmd, &config_path), Cmd::Name { handle, clear } => run_name(handle, clear), + Cmd::Contact { email, clear } => run_contact(email, clear), Cmd::Private { cmd } => run_private(cmd, &config_path), Cmd::Worker { cmd } => run_worker(cmd, &config_path).await, Cmd::Job { cmd } => run_job(cmd).await, @@ -2622,6 +2650,36 @@ fn run_name(handle: Option, clear: bool) -> Result<()> { Ok(()) } +fn run_contact(email: Option, clear: bool) -> Result<()> { + use c0mpute_core::capabilities::{node_contact, node_contact_path, sanitize_contact}; + let path = node_contact_path().context("cannot find a home directory for ~/.c0mpute")?; + let apply = "(apply: c0mpute worker stop && c0mpute worker start -d)"; + if clear { + match std::fs::remove_file(&path) { + Ok(()) => println!("removed {} {apply}", path.display()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => println!("no contact email was set"), + Err(e) => return Err(e).with_context(|| format!("remove {}", path.display())), + } + } else if let Some(raw) = email { + let email = sanitize_contact(&raw) + .with_context(|| format!("{raw:?} is not a plain email address (like ops@example.com)"))?; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(&path, format!("{email}\n")).with_context(|| format!("write {}", path.display()))?; + println!("saved to {} {apply}", path.display()); + } + match node_contact() { + Some(e) => { + let via = if std::env::var_os("C0MPUTE_CONTACT").is_some() { " (from C0MPUTE_CONTACT)" } else { "" }; + println!("contact : {e}{via}"); + println!("shown on : https://c0mpute.com/nodes (public)"); + } + None => println!("contact : (none; add one with `c0mpute contact ` so people can reach you about this node)"), + } + Ok(()) +} + fn run_pricing(cmd: Option, config_path: &std::path::Path) -> Result<()> { use c0mpute_core::pricing::PricingMode; let mut cfg = Config::load_or_default(config_path)?; diff --git a/node/crates/c0mpute-core/src/capabilities.rs b/node/crates/c0mpute-core/src/capabilities.rs index 2a7a420f..03e92026 100644 --- a/node/crates/c0mpute-core/src/capabilities.rs +++ b/node/crates/c0mpute-core/src/capabilities.rs @@ -265,6 +265,13 @@ pub fn hardware_blob(config: &Config) -> serde_json::Value { if let Some(name) = node_name() { blob["name"] = serde_json::Value::String(name); } + if let Some(contact) = node_contact() { + blob["contact"] = serde_json::Value::String(contact); + } + // Where to DM whoever runs this node (`c0mpute dm send `). + if let Some(dm) = crate::dm::node_dm_address() { + blob["dm"] = serde_json::Value::String(dm); + } blob["pricing"] = config.pricing.listing(); if let Some(origin) = announced_gateway(config) { blob["gateway"] = serde_json::Value::String(origin); @@ -348,6 +355,54 @@ pub fn node_name_path() -> Option { c0mpute_home().map(|h| h.join("name")) } +/// The email the operator offers for questions about this node, if any. +/// +/// Optional and PUBLIC: it rides in the capability ad and is shown on +/// c0mpute.com/nodes, so callers and the network's maintainers can reach +/// whoever runs a node that misbehaves (2026-11-15: a node failing 3 in 4 +/// jobs had no way to be contacted). `C0MPUTE_CONTACT` wins; otherwise +/// `~/.c0mpute/contact`, written by `c0mpute contact ` or +/// `install.sh --contact `. Nothing is sent to it automatically. +pub fn node_contact() -> Option { + let raw = std::env::var("C0MPUTE_CONTACT") + .ok() + .filter(|v| !v.trim().is_empty()) + .or_else(|| std::fs::read_to_string(node_contact_path()?).ok())?; + sanitize_contact(&raw) +} + +/// Where `c0mpute contact` stores the email: `$C0MPUTE_HOME/contact`, else +/// `~/.c0mpute/contact`. +pub fn node_contact_path() -> Option { + c0mpute_home().map(|h| h.join("contact")) +} + +/// A plain email address (`local@domain.tld`), lowercased, up to 254 +/// characters, or nothing. No spaces, quotes, angle brackets or display +/// names: it is printed into a public web page as a mailto link. Shared with +/// the status aggregator, which re-checks every ad before it publishes one. +pub fn sanitize_contact(raw: &str) -> Option { + let email = raw.trim().to_ascii_lowercase(); + if email.is_empty() || email.len() > 254 { + return None; + } + let (local, domain) = email.split_once('@')?; + let ok_chars = |s: &str, extra: &[char]| { + !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(&c)) + }; + let ok = local.len() <= 64 + && ok_chars(local, &['.', '_', '%', '+', '-']) + && !local.starts_with('.') + && !local.ends_with('.') + && ok_chars(domain, &['.', '-']) + && domain.contains('.') + && !domain.starts_with(['.', '-']) + && !domain.ends_with(['.', '-']) + && !domain.contains("..") + && !domain.contains('@'); + ok.then_some(email) +} + fn c0mpute_home() -> Option { std::env::var_os("C0MPUTE_HOME") .map(std::path::PathBuf::from) @@ -732,6 +787,16 @@ impl Registry { mod tests { use super::*; + #[test] + fn contact_emails_are_plain_addresses_or_nothing() { + assert_eq!(sanitize_contact(" Sergey@Example.COM \n"), Some("sergey@example.com".into())); + assert_eq!(sanitize_contact("ops+c0mpute@mail.example.co.uk"), Some("ops+c0mpute@mail.example.co.uk".into())); + for bad in ["", "nobody", "a@b", "@example.com", "a@.example.com", "a@example..com", "Name ", + "a b@c.com", "a@b.com\">