interplane.Get Omega
Read in your language

open-humanity

Privacy-first peer assistance network for sovereign autonomous agents

Brought by drakestapleton

branch main Branches Tags History

open-humanity / crates / beacon-client / src / main.rs

247 lines · 11499 bytes Raw Blame History
1use beacon_client::relay::{ask_skipping, build_request, listen, settle_answer, teach, AnswerCheck, RelayClient};
2use beacon_client::storage::{BeaconStorage, DEFAULT_TTL_SECONDS};
3use beacon_core::crypto::Keypair;
4use beacon_core::schema::{BeaconTopic, DistressNanobeacon, ErrorFingerprint};
5use beacon_core::wire::{sign_signal, topics_mask};
6use rand::rngs::OsRng;
7use rand::RngCore;
8use std::env;
9use std::net::SocketAddr;
10use std::time::Duration;
11use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret};
12
13const USAGE: &str = "Usage: open-humanity <command>
14 status
15 sweep
16 test-distress
17 teach --topic T --error TEXT --solution TEXT [--db PATH]
18 ask --relay HOST:PORT --topic T --error TEXT --title TEXT --summary TEXT
19 [--code N] [--wait SECS] [--answers N] [--check 'PROGRAM ARGS'] [--db PATH] --approve
20 listen --relay HOST:PORT [--topics T,T|all] [--for SECS] [--db PATH]
21 [--identity-cmd 'PROGRAM ARGS']
22 identity new | show [--identity-cmd 'PROGRAM ARGS']
23 peers [--db PATH]
24A lasting key: the seed is the output of --identity-cmd (or of the command in
25OPEN_HUMANITY_IDENTITY_CMD), or the value of OPEN_HUMANITY_IDENTITY. It is never
26read from or written to a file by this program.
27Topics: rust-compilation mojo-simd modular-max-serving hardware-topology
28 security-audit protocol-coordination agent-recursion";
29
30fn opt(args: &[String], name: &str) -> Option<String> {
31 args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
32}
33
34fn need(args: &[String], name: &str) -> Result<String, String> {
35 opt(args, name).ok_or_else(|| format!("missing {name}"))
36}
37
38fn open_storage(args: &[String]) -> Result<BeaconStorage, Box<dyn std::error::Error>> {
39 Ok(match opt(args, "--db") {
40 Some(path) => BeaconStorage::open(path)?,
41 None => BeaconStorage::open_default()?,
42 })
43}
44
45async fn resolve(relay: &str) -> Result<SocketAddr, Box<dyn std::error::Error>> {
46 let found = tokio::net::lookup_host(relay).await?.next();
47 Ok(found.ok_or_else(|| format!("no address for relay {relay}"))?)
48}
49
50fn hex(bytes: &[u8]) -> String {
51 bytes.iter().map(|b| format!("{b:02x}")).collect()
52}
53
54/// The lasting key of this node, when one is configured. The seed is the output of a
55/// command (`--identity-cmd`, or OPEN_HUMANITY_IDENTITY_CMD) or the value of
56/// OPEN_HUMANITY_IDENTITY. No shell reads the command.
57fn identity(args: &[String]) -> Result<Option<Keypair>, String> {
58 let command = opt(args, "--identity-cmd").or_else(|| env::var("OPEN_HUMANITY_IDENTITY_CMD").ok());
59 let seed = match command {
60 Some(command) => {
61 let mut words = command.split_whitespace();
62 let program = words.next().ok_or("the identity command is empty")?;
63 let output = std::process::Command::new(program)
64 .args(words)
65 .output()
66 .map_err(|e| format!("the identity command did not run: {e}"))?;
67 if !output.status.success() {
68 return Err("the identity command failed".into());
69 }
70 String::from_utf8_lossy(&output.stdout).to_string()
71 }
72 None => match env::var("OPEN_HUMANITY_IDENTITY") {
73 Ok(seed) => seed,
74 Err(_) => return Ok(None),
75 },
76 };
77 Keypair::from_hex_seed(&seed)
78 .map(Some)
79 .ok_or_else(|| "the identity seed is not 64 hex characters".to_string())
80}
81
82#[tokio::main]
83async fn main() {
84 if let Err(e) = run().await {
85 eprintln!("Error: {e}");
86 std::process::exit(1);
87 }
88}
89
90async fn run() -> Result<(), Box<dyn std::error::Error>> {
91 let args: Vec<String> = env::args().collect();
92 let command = args.get(1).map(|s| s.as_str()).unwrap_or("status");
93
94 match command {
95 "status" => {
96 println!("=== Open Humanity Node Status ===");
97 let storage = BeaconStorage::open_default()?;
98 let swept = storage.sweep_expired(DEFAULT_TTL_SECONDS)?;
99 println!("[+] Local SQLite storage active (~/.local/share/open-humanity/beacon.sqlite)");
100 println!("[+] Swept {} expired beacons (> 7 days TTL)", swept);
101 match identity(&args)? {
102 Some(keypair) => println!("[+] Identity: lasting key {}", hex(&keypair.pubkey_bytes())),
103 None => println!("[+] Identity: a new key for every run (see: open-humanity identity new)"),
104 }
105 println!("[+] 0-RTT Datagram MTU limit: 1,200 bytes");
106 println!("[+] Cuckoo Filter L3 cache: ready");
107 }
108 "sweep" => {
109 let storage = BeaconStorage::open_default()?;
110 let swept = storage.sweep_expired(DEFAULT_TTL_SECONDS)?;
111 println!("[+] Swept {} expired beacons from local storage", swept);
112 }
113 "test-distress" => {
114 let storage = BeaconStorage::open_default()?;
115 let keypair = Keypair::generate();
116 let dh_secret = StaticSecret::random_from_rng(OsRng);
117 let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes();
118
119 let fp = ErrorFingerprint::from_error_str(
120 "error[E0425]: cannot find value `foo` in this scope",
121 Some(425),
122 "aarch64",
123 );
124
125 let mut beacon = DistressNanobeacon::new(
126 BeaconTopic::RustCompilation,
127 keypair.pubkey_bytes(),
128 dh_pubkey,
129 fp,
130 "Undefined identifier foo".to_string(),
131 "Variable foo used before declaration".to_string(),
132 );
133 sign_signal(&mut beacon, &keypair)?;
134
135 storage.record_outbound_beacon(&beacon)?;
136 println!("[+] Recorded test distress beacon: {}", beacon.beacon_id);
137 }
138 "identity" => match args.get(2).map(|s| s.as_str()) {
139 Some("new") => {
140 let mut seed = [0u8; 32];
141 OsRng.fill_bytes(&mut seed);
142 println!("seed: {}", hex(&seed));
143 println!("public key: {}", hex(&Keypair::from_seed(&seed).pubkey_bytes()));
144 println!("Keep the seed in your secret store; nothing was written to disk.");
145 println!("Use it with --identity-cmd \"<a command that prints the seed>\".");
146 }
147 Some("show") => match identity(&args)? {
148 Some(keypair) => println!("public key: {}", hex(&keypair.pubkey_bytes())),
149 None => println!("No lasting identity is configured; every run makes a new key."),
150 },
151 _ => {
152 eprintln!("{USAGE}");
153 std::process::exit(1);
154 }
155 },
156 "peers" => {
157 let storage = open_storage(&args)?;
158 let peers = storage.list_peers()?;
159 if peers.is_empty() {
160 println!("No helper has been checked on this node yet.");
161 }
162 for peer in peers {
163 let note = if peer.distrusted() { " (answers skipped)" } else { "" };
164 println!("{} passed {} failed {}{}", hex(&peer.pubkey), peer.successful, peer.failed, note);
165 }
166 }
167 "teach" => {
168 let topic = BeaconTopic::from_name(&need(&args, "--topic")?).ok_or("unknown topic")?;
169 let storage = open_storage(&args)?;
170 let fingerprint = teach(&storage, topic, &need(&args, "--error")?, &need(&args, "--solution")?)?;
171 println!("[+] Stored a solution for fingerprint {}", hex(&fingerprint.hash));
172 }
173 "ask" => {
174 let topic = BeaconTopic::from_name(&need(&args, "--topic")?).ok_or("unknown topic")?;
175 let code = opt(&args, "--code").and_then(|c| c.parse().ok());
176 let wait = opt(&args, "--wait").and_then(|w| w.parse().ok()).unwrap_or(30u64);
177 let max_answers = opt(&args, "--answers").and_then(|n| n.parse().ok()).unwrap_or(1usize);
178 let keypair = Keypair::generate();
179 let request = build_request(
180 &keypair,
181 topic,
182 &need(&args, "--error")?,
183 code,
184 env::consts::ARCH,
185 &need(&args, "--title")?,
186 &need(&args, "--summary")?,
187 )?;
188 println!("This leaves the node, signed with a key made for this request:");
189 println!(" topic: {}", request.signal.topic.as_str());
190 println!(" title: {}", request.signal.title);
191 println!(" summary: {}", request.signal.compact_summary);
192 println!(" fingerprint: {} (a hash; the error text stays here)", hex(&request.signal.fingerprint.hash));
193 if !args.iter().any(|a| a == "--approve") {
194 eprintln!("Nothing was sent. Add --approve to send it.");
195 std::process::exit(3);
196 }
197 let check = match opt(&args, "--check") {
198 Some(text) => Some(AnswerCheck::parse(&text).ok_or("--check is empty")?),
199 None => None,
200 };
201 let storage = open_storage(&args)?;
202 storage.record_outbound_beacon(&request.signal)?;
203 let skip = storage.distrusted_peers()?;
204 let mut client = RelayClient::connect(resolve(&need(&args, "--relay")?).await?, keypair).await?;
205 let answers = ask_skipping(&mut client, &request, Duration::from_secs(wait), max_answers, &skip).await?;
206 if answers.is_empty() {
207 println!("No answer within {wait} s. Answers reach this node only while ask runs; a longer --wait gives late helpers more time.");
208 std::process::exit(4);
209 }
210 for answer in answers {
211 println!("Answer from helper {}:", hex(&answer.responder_pubkey[..8]));
212 println!("{}", answer.text);
213 if let Some(check) = &check {
214 if settle_answer(&storage, &request, &answer, check)? {
215 println!(" check passed: kept as a solution on this node, counted for the helper");
216 } else {
217 println!(" check FAILED: not kept, counted against the helper");
218 }
219 }
220 }
221 }
222 "listen" => {
223 let topics = topics_mask(&opt(&args, "--topics").unwrap_or_else(|| "all".into()))
224 .ok_or("unknown topic in --topics")?;
225 let run_for = opt(&args, "--for").and_then(|s| s.parse().ok()).map(Duration::from_secs);
226 let mut storage = open_storage(&args)?;
227 let (keypair, kind) = match identity(&args)? {
228 Some(keypair) => (keypair, "lasting"),
229 None => (Keypair::generate(), "made for this run"),
230 };
231 println!("[+] Helper key {} ({kind})", hex(&keypair.pubkey_bytes()[..8]));
232 let mut client = RelayClient::connect(resolve(&need(&args, "--relay")?).await?, keypair).await?;
233 println!("[+] Listening for requests (topics mask {topics:#04x})");
234 let report = listen(&mut client, &mut storage, topics, run_for).await?;
235 println!(
236 "[+] Requests seen: {}, answered: {}, no solution: {}, refused: {}",
237 report.requests_seen, report.answered, report.no_solution, report.refused
238 );
239 }
240 _ => {
241 eprintln!("{USAGE}");
242 std::process::exit(1);
243 }
244 }
245
246 Ok(())
247}