From fbda0f46a7059e1d61c4209da1b0d5ec748fdbbc Mon Sep 17 00:00:00 2001 From: cjus Date: Thu, 5 Nov 2026 10:46:55 -0700 Subject: [PATCH] Net: documentation, resources in initialize, the wire key cnp (network play, step 6) - Book chapter 22, "Network play": the open-port problem, fingerprint pinning, pairing, the idle timeout that couldn't exist, limits, discovery and its abuse, how to try it, exercises. - README section for using cb2026 from another computer; design doc and status brought up to date. - The CNP pin moves to the specification that now has the network transport (sections 3.2 and 3.3) and `resources` in initialize (cjus/chess-node-protocol#24). initialize now reports the node's threads and hash (--threads, --hash), tested through the real binary. - The pairing and discovery messages use the key "cnp" instead of "cb2026", as the spec has them, so another node or client can use them. - Needs-carlos issue #263: a try between two real computers, and whether releases carry the feature. No functional change. Bench: 767812 Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 4 +- Cargo.toml | 4 +- README.md | 18 +++ book/src/SUMMARY.md | 4 + book/src/ch22-network.md | 227 ++++++++++++++++++++++++++++++++++ crates/cli/tests/cnp.rs | 34 +++++ crates/cnp/src/lib.rs | 43 ++++++- crates/net/src/client.rs | 4 +- crates/net/src/discovery.rs | 16 +-- crates/net/src/lib.rs | 4 +- crates/net/tests/discovery.rs | 4 +- crates/net/tests/tls.rs | 6 +- docs/network-play.md | 25 ++-- docs/status.md | 9 +- 14 files changed, 369 insertions(+), 33 deletions(-) create mode 100644 book/src/ch22-network.md diff --git a/Cargo.lock b/Cargo.lock index 21be812..b2e34c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,7 +297,7 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "cnp" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=62744203c4a92a505c79579c5ad094c5f46e6833#62744203c4a92a505c79579c5ad094c5f46e6833" +source = "git+https://github.com/cjus/chess-node-protocol?rev=ba9e0ce5293154cedbae0477d29255513a4fb2fc#ba9e0ce5293154cedbae0477d29255513a4fb2fc" dependencies = [ "serde", "serde_json", @@ -306,7 +306,7 @@ dependencies = [ [[package]] name = "cnp-conformance" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=62744203c4a92a505c79579c5ad094c5f46e6833#62744203c4a92a505c79579c5ad094c5f46e6833" +source = "git+https://github.com/cjus/chess-node-protocol?rev=ba9e0ce5293154cedbae0477d29255513a4fb2fc#ba9e0ce5293154cedbae0477d29255513a4fb2fc" dependencies = [ "cnp", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 359a529..bfa9023 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,8 +43,8 @@ cb2026-tools = { path = "crates/tools" } cb2026-trainer = { path = "crates/trainer" } # The Chess Node Protocol, how Solrac talks to cb2026 (`crates/cnp`), and its conformance # sessions (Solrac Chess AI #98). Pinned to a commit; bump both together. -cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "62744203c4a92a505c79579c5ad094c5f46e6833" } -cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "62744203c4a92a505c79579c5ad094c5f46e6833" } +cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "ba9e0ce5293154cedbae0477d29255513a4fb2fc" } +cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "ba9e0ce5293154cedbae0477d29255513a4fb2fc" } # Lints shared by every crate (each crate opts in with `[lints] workspace = true`). [workspace.lints.rust] diff --git a/README.md b/README.md index e113c83..5b7dbff 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,24 @@ for clocks), ask for a `hint`, see its thinking depth by depth, look up the book tablebases, and switch its techniques on and off (`set nullmove off`, `set evalfile none`) to see what each one does. To run it as a Lichess bot, see [`docs/lichess.md`](docs/lichess.md). +## From another computer + +cb2026 can serve its processors to a chess program on another computer on your network, over +the Chess Node Protocol, encrypted and only for clients you approve. It is **off by default and +not in the release downloads yet**: build it with `cargo build --release -p cb2026 --features net`. + +``` +cb2026 --serve 0.0.0.0:4026 --discover --name "the study" --threads 8 --hash 2048 +cb2026 --pair # approve a new client: shows this engine's fingerprint and a one-time code +``` + +A client compares the fingerprint with the one `--pair` shows, then types the code; after that +it connects with no code, and deleting its line in `approved-clients.txt` revokes it. `--discover` +lets a client find the engine without an address. Chapter 22 of the book explains how it works +and why, and section 3 of the [Chess Node Protocol +specification](https://github.com/cjus/chess-node-protocol/blob/main/spec/cnp.md) is the +transport a client implements. + ## Learning from it The book in `book/`, *Building a Chess Engine in Rust*, has a chapter for each stage, from the diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index c14d076..872a7a1 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -46,3 +46,7 @@ # Part V: Neural networks - [NNUE](ch21-nnue.md) + +# Part VI: Beyond one computer + +- [Network play](ch22-network.md) diff --git a/book/src/ch22-network.md b/book/src/ch22-network.md new file mode 100644 index 0000000..2f9c763 --- /dev/null +++ b/book/src/ch22-network.md @@ -0,0 +1,227 @@ +# Network play + +*Opt-in, off by default · code in `crates/net`, `crates/cnp` and `crates/cli/src/main.rs` · +the protocol's rules are section 3 of the Chess Node Protocol specification* + +Everything so far ran on one computer. This chapter lets one computer use another's processors: +you run cb2026 on a fast machine, and a chess GUI on your laptop plays with it. It is also the +chapter where cb2026 first **opens a port**, so most of it is about who gets to use that port, +and what happens when someone who shouldn't tries. + +Nothing here changes how the engine searches. The listener is a thin adapter: it moves lines of +the Chess Node Protocol (CNP, from the previous chapters' JSON mode) between a network +connection and the same `cb2026-cnp` node that serves a program started on standard input. A +search means exactly what it meant before; this crate only decides who may talk to the node, +when, and for how long. + +## The problem with an open port + +A listening program is a door. On your own network the people who might knock are your +family's phones, a guest's laptop and anything that got onto the Wi-Fi by accident. And the +door is expensive: whoever gets in can ask your processors to search for as long as they like. + +The usual answers don't fit a program people download. SSH needs accounts and keys. A password +typed into the GUI and sent over the network has to be sent *somewhere safe*, and the program +has nothing to make a connection safe with. A certificate authority is what browsers use, and +asking a home user to run one is asking too much. + +So cb2026 does the whole job itself, with nothing to install and nothing to type twice. + +## Encryption without an authority: pin the fingerprint + +The connection is **TLS 1.3**, the same encryption as `https`, with two unusual choices. + +**Both sides have a certificate, and both are self-signed.** The first time cb2026 serves, it +makes a certificate and keeps it, with its key, in its own folder. A client makes one too. A +certificate that anyone can make proves nothing about *who* made it, so cb2026 doesn't ask what +is in it. It asks for its **fingerprint**: the SHA-256 of the certificate's bytes, written as 32 +pairs of hex digits: + +```text +3F:A9:0C:... (32 pairs) +``` + +A fingerprint can't be faked without the private key, because the TLS handshake includes a +signature that only the key's holder can make. cb2026 checks that signature in both +directions. This matters more than it sounds: certificates cross the wire in every handshake, +so anyone watching the network has your approved client's certificate. Without the signature +check, they could present it as their own. One of the tests builds exactly that attack, a +copied certificate with a different key, and requires the handshake to fail; breaking the +check on purpose makes that test fail, which is how we know the test looks at the right thing. + +What the fingerprint *means* is up to each side's memory. The client remembers the engine's, +and refuses any other. The engine keeps a list of the clients' fingerprints it has approved, +and closes the connection of any other. Nobody trusts a name; everybody trusts a thing they +have seen before. Browsers call this "trust on first use", and SSH's `known_hosts` is the same +idea. The only hard moment is the *first* time, which is pairing. + +## Pairing: one code, and one comparison + +The first time a client connects, the engine doesn't know it. A person who is standing at the +engine's computer lets it in: + +```text +$ cb2026 --pair +Pairing: approve one new client. + +1. On the client, choose this computer. It shows a fingerprint; check that + it is the same as this one: + + 3F:A9:0C:5E:... + ... + +2. Only if they match, type this code into the client: + + 4821 0937 + +The code works once and for 5 minutes, and closes after 3 wrong tries. +``` + +There are two secrets here and they defend against different people. + +- **The code** proves that someone at the engine's keyboard let *this* client in. A stranger on + the network can try to pair, but has to guess eight digits, and the window closes after three + wrong tries, so a guesser has roughly three chances in a hundred million. +- **The fingerprint comparison** proves the client is talking to *this* engine and not to a + program in the middle that is relaying everything. Such a program can't produce the engine's + certificate, so its fingerprint differs; if the person compares the two screens, the attack + is visible. A client that sent the code first and compared later would hand the code to the + attacker. The specification therefore says the client must show the fingerprint and wait for + the person before it sends the code. + +After pairing the client's fingerprint is a line in a text file, `approved-clients.txt`. +Revoking a client means deleting its line, and it is refused at its next connection, with no +restart, because the listener reads the file for every connection. `cb2026 --pair` and +`cb2026 --serve` are separate programs that only share those files. + +A client that isn't on the list may send exactly one thing, a pairing request of at most 1 KiB. +Anything else, a wrong code, no open window, gets the connection closed with **no reply**. A +helpful error message ("wrong code", "not approved") would tell a guesser which part to +work on. + +## One client at a time + +CNP runs one search at a time, so the listener serves one client at a time. A second approved +client is told `Busy` and disconnected. Each client gets a **new engine**: nothing of the last +client's hash table, options or game survives. When a client's connection ends for any reason +the search is cancelled, and nothing resumes on the next connection, so an answer can never +reach the wrong person. + +That rule has a consequence that is easy to miss. Strangers shouldn't be able to occupy the one +place, and a handshake takes time, so connections are *greeted* on threads of their own, and +only a client that is approved reaches the place at all. A stranger can waste a few threads for +a few seconds, and the next section is about stopping even that. + +## The timeout we couldn't have + +The first design had an idle timeout: close a connection that says nothing for five minutes. +Building it showed it could not exist. A client waiting for a long search sends nothing for as +long as the search runs, and from the listener's side that silence is identical to a client +that walked away. A timeout would kill real searches. + +What the listener can do is attack the two cases that really hurt: + +- A connection that **never gets going** has ten seconds to finish its handshake and send its + first message. The ten seconds cover the whole thing, not each read, because a client that + sends one byte every nine seconds would otherwise stay forever. The limit is applied where the + bytes come in (a small wrapper around the socket's read), so it holds however many reads TLS + needs to assemble one record. +- A client that **vanished** (its Wi-Fi dropped, nothing said goodbye) is found by TCP + keepalive, after about a minute of silence and a few probes. + +A client that is connected, alive and silent may keep its place. That is by design, and a test +says so: another approved client is told `Busy`. + +## Limits that don't ask permission + +Whoever owns the engine's computer sets the limits (`--threads`, `--hash`, and the numbers +below); a client can't raise them, and CNP has no request that can change them. The engine now +*says* them in `initialize`, in an optional `resources` object, so a program choosing among +several machines can tell one with 64 threads from one with 1. + +| What | Limit | +| --- | --- | +| One message | 1 MiB (a stdio node reads 16) | +| First message | 10 s, the whole message | +| One write to a client | 30 s | +| Connections greeted at once | 16 in all, 4 from one address | +| An address that fails 8 times in 10 s | ignored for 30 s | + +The tests for these send what an attacker would: a message two bytes at a time, 100,000 nested +brackets, a ten-thousand-digit id, bytes that aren't text, a message past the limit, a flood of +150 silent connections, a client that never reads the answers (the listener must still stop), +a cancel followed at once by a new search (the cancelled search must never answer with a +move). None of them needed a change to the CNP node, which answered every bad message with an +error and carried on. The one thing they found is the stalled client above, which holds the +place by design. + +## Finding the engine: a question shouted at the network + +Typing `192.168.1.23:4026` is fine for people who know their network. For everyone else, a +client can **ask the network** whether a cb2026 is there. It sends a small UDP datagram to the +broadcast address, which every machine on the local network receives, and any engine that has +been told to (`--discover`) answers. + +```text +→ {"cnp": "probe", "v": 1} (padded to 320 bytes) +← {"cnp": "here", "v": 1, "name": "the study", "protocol": "1.0", "port": 4026, + "fingerprint": "3F:A9:...", "pairing": false} +``` + +Shouting at a network invites a particular abuse. UDP has no handshake, so the sender's address +in a datagram can be forged. Someone could send probes that claim to come from a victim, and +every engine would send its answer to the victim. If the answer were bigger than the probe, +that would multiply the attacker's traffic. So the probe is padded to a fixed 320 bytes and a +reply is never longer, and an engine answers at most four probes a second to one address. +Datagrams of any other size get nothing at all. + +Nothing private is in the answer: no computer name, no user name, no hardware. The name is one +the owner chose. And the answer is **a hint, not a credential**: it says where an engine +*claims* to be. A client connects there and checks the fingerprint the way it always does, so a +forged answer can only send a client to a machine that fails the check. + +Broadcast has limits you should know. It reaches only the local network segment; many Wi-Fi +routers stop devices seeing each other; a firewall can block the port. That is why typing an +address stays a full feature, and why a client must always offer it. + +## Try it + +You need a cb2026 built with `--features net` (the release downloads don't have it yet; the +chapter's code is off by default): + +```text +cargo build --release -p cb2026 --features net +``` + +On the fast computer: + +```text +cb2026 --serve 0.0.0.0:4026 --discover --name "the study" --threads 8 --hash 2048 +``` + +It prints its fingerprint. In another terminal on the same computer: + +```text +cb2026 --pair +``` + +Then, from the other computer, a client finds the engine (or you type its address), shows you the +fingerprint, and asks for the code. The reference client in `crates/net/src/client.rs` is a short +file and is what the tests use: read it to see exactly what a client does. + +Your operating system may ask once whether to allow incoming connections for the program; say +yes for private networks. + +## Exercises + +1. Run `cb2026 --pair`, then pair a client with a wrong code three times and watch the window + close. What does the client see each time? What would a client learn if the engine said + "wrong code" instead? +2. Open `approved-clients.txt` after a successful pairing and delete the line. Reconnect with + the same client. Why doesn't the engine need restarting? +3. The probe is 320 bytes and the reply must never be longer. Change the reply's longest field + and find the test that notices. What is the longest name that fits, in bytes? +4. Find the test that connects 150 times from one address. Why does it count the connections + that are *still open* rather than the ones that were refused? +5. There is no idle timeout. Write down a way to add one that doesn't kill a long search. + (Hint: the client can say that it is waiting.) What would the protocol need? diff --git a/crates/cli/tests/cnp.rs b/crates/cli/tests/cnp.rs index 3171b43..bab9e72 100644 --- a/crates/cli/tests/cnp.rs +++ b/crates/cli/tests/cnp.rs @@ -175,3 +175,37 @@ fn bad_threads_or_hash_are_refused_before_anything_starts() { assert!(output.stdout.is_empty(), "{args:?}"); } } + +#[test] +fn initialize_reports_the_threads_and_hash_the_node_was_started_with() { + use std::io::{BufRead, BufReader, Write}; + use std::process::{Command, Stdio}; + + for (args, resources) in [ + ( + &["--cnp", "--threads", "3", "--hash", "32"][..], + r#""resources":{"hashMb":32,"threads":3}"#, + ), + (&["--cnp"][..], r#""resources":{"hashMb":16,"threads":1}"#), + ] { + let mut node = Command::new(env!("CARGO_BIN_EXE_cb2026")) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("cb2026 starts"); + let mut stdin = node.stdin.take().expect("its input"); + writeln!( + stdin, + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocol":"1.0","client":{{"name":"test","version":"0"}}}}}}"# + ) + .expect("initialize is sent"); + drop(stdin); + let mut answer = String::new(); + BufReader::new(node.stdout.take().expect("its output")) + .read_line(&mut answer) + .expect("cb2026 answers"); + node.wait().expect("cb2026 ends when its input does"); + assert!(answer.contains(resources), "{args:?}: {answer}"); + } +} diff --git a/crates/cnp/src/lib.rs b/crates/cnp/src/lib.rs index 423e8bc..75a3546 100644 --- a/crates/cnp/src/lib.rs +++ b/crates/cnp/src/lib.rs @@ -139,7 +139,7 @@ use cnp::engine::{ }; use cnp::lifecycle::{ CancelRequest, Capabilities, IncompatibleVersionData, Initialize, InitializeResult, - Limits as NodeLimits, NodeInfo, PROTOCOL_VERSION, Ping, Shutdown, negotiate, + Limits as NodeLimits, NodeInfo, PROTOCOL_VERSION, Ping, Resources, Shutdown, negotiate, }; use cnp::stdio::{ReadError, read_message, write_message}; use cnp::{Id, Message, Notification, Request, RequestMethod, Response, ResponseError, code}; @@ -534,6 +534,13 @@ impl Node { max_tree_plies: Some(MAX_TREE_PLIES), max_concurrent_trees: Some(1), }, + // What this node was started with (`--threads`, `--hash`), so a client that + // chooses among nodes can tell a big one from a small one. No search runs yet, so + // the engine is here to ask. + resources: self.engine.as_ref().map(|engine| Resources { + threads: u32::try_from(engine.threads).ok(), + hash_mb: u64::try_from(engine.tt.megabytes()).ok(), + }), }; Response::ok::(id, &result) } @@ -1354,6 +1361,40 @@ mod tests { assert_eq!(prepare(¶ms).unwrap().techniques.len(), 1); } + #[test] + fn initialize_says_the_threads_and_hash_the_node_runs_with() { + let answer = |engine: Engine| { + let mut node = Node::new( + Arc::new(Mutex::new(Box::new(io::sink()))), + engine, + Config { + license: "MIT OR Apache-2.0", + message_bytes: None, + }, + ); + let params = cnp::lifecycle::InitializeParams { + protocol: PROTOCOL_VERSION, + client: cnp::lifecycle::Software { + name: "test".to_string(), + version: "0".to_string(), + }, + }; + let request = Request::new::(1, ¶ms); + node.initialize(&request) + .result::() + .expect("an answer") + }; + // The defaults of an engine nobody configured: one thread and 16 MB. + let plain = answer(Engine::new()).resources.expect("resources"); + assert_eq!((plain.threads, plain.hash_mb), (Some(1), Some(16))); + // What `--threads` and `--hash` set, as the CLI sets them. + let mut engine = Engine::new(); + engine.threads = 4; + engine.set_hash_size(64); + let set = answer(engine).resources.expect("resources"); + assert_eq!((set.threads, set.hash_mb), (Some(4), Some(64))); + } + #[test] fn levels_run_from_0_to_full_strength_with_their_ratings() { let levels = levels(); diff --git a/crates/net/src/client.rs b/crates/net/src/client.rs index b630f21..35fe387 100644 --- a/crates/net/src/client.rs +++ b/crates/net/src/client.rs @@ -113,11 +113,11 @@ impl Connection { /// for this client (kept in the node's approved list). Whether the node said yes. The /// connection is over after this either way. pub fn pair(&mut self, code: &str, name: &str) -> io::Result { - let request = serde_json::json!({ "cb2026": "pair", "code": code, "name": name }); + let request = serde_json::json!({ "cnp": "pair", "code": code, "name": name }); self.send_line(&request.to_string())?; let answer = self.read_line()?; Ok(answer.is_some_and(|line| { - serde_json::from_str::(&line).is_ok_and(|v| v["cb2026"] == "paired") + serde_json::from_str::(&line).is_ok_and(|v| v["cnp"] == "paired") })) } } diff --git a/crates/net/src/discovery.rs b/crates/net/src/discovery.rs index 8d97a34..dac9eba 100644 --- a/crates/net/src/discovery.rs +++ b/crates/net/src/discovery.rs @@ -8,9 +8,9 @@ //! //! ## The messages //! -//! - **Probe:** a datagram of exactly [`PROBE_BYTES`] bytes: the JSON `{"cb2026":"probe","v":1}` +//! - **Probe:** a datagram of exactly [`PROBE_BYTES`] bytes: the JSON `{"cnp":"probe","v":1}` //! padded with spaces. Anything else, in size or content, is ignored without a reply. -//! - **Reply:** one JSON line, sent to whoever sent the probe: `{"cb2026":"here","v":1, +//! - **Reply:** one JSON line, sent to whoever sent the probe: `{"cnp":"here","v":1, //! "name":…,"protocol":"1.0","port":4026,"fingerprint":"AB:CD:…","pairing":false}`: the name //! its owner gave the node (`--name`), the CNP version, the TCP port, the certificate //! fingerprint, and whether a pairing window is open. @@ -79,7 +79,7 @@ const VERSION: u64 = 1; /// The probe datagram: its JSON, padded to [`PROBE_BYTES`]. pub fn probe() -> Vec { - let mut datagram = json!({ "cb2026": "probe", "v": VERSION }) + let mut datagram = json!({ "cnp": "probe", "v": VERSION }) .to_string() .into_bytes(); datagram.resize(PROBE_BYTES, b' '); @@ -90,7 +90,7 @@ pub fn probe() -> Vec { fn is_probe(datagram: &[u8]) -> bool { datagram.len() == PROBE_BYTES && serde_json::from_slice::(datagram) - .is_ok_and(|v| v["cb2026"] == "probe" && v["v"] == VERSION) + .is_ok_and(|v| v["cnp"] == "probe" && v["v"] == VERSION) } /// What an engine says about itself in a reply. @@ -113,7 +113,7 @@ impl Announcement { /// the name make impossible). fn encode(&self) -> Option> { let reply = json!({ - "cb2026": "here", + "cnp": "here", "v": VERSION, "name": self.name, "protocol": self.protocol, @@ -133,7 +133,7 @@ impl Announcement { return None; } let v: Value = serde_json::from_slice(datagram).ok()?; - if v["cb2026"] != "here" || v["v"] != VERSION { + if v["cnp"] != "here" || v["v"] != VERSION { return None; } let name = v["name"].as_str()?; @@ -315,10 +315,10 @@ mod tests { assert!(!is_probe(&long), "too long"); assert!(!is_probe(&[b' '; PROBE_BYTES]), "blank"); assert!(!is_probe(&[0xFF; PROBE_BYTES]), "noise"); - let mut other = br#"{"cb2026":"here","v":1}"#.to_vec(); + let mut other = br#"{"cnp":"here","v":1}"#.to_vec(); other.resize(PROBE_BYTES, b' '); assert!(!is_probe(&other), "another message"); - let mut future = br#"{"cb2026":"probe","v":2}"#.to_vec(); + let mut future = br#"{"cnp":"probe","v":2}"#.to_vec(); future.resize(PROBE_BYTES, b' '); assert!(!is_probe(&future), "another version"); } diff --git a/crates/net/src/lib.rs b/crates/net/src/lib.rs index 4ed10d2..9d6da0b 100644 --- a/crates/net/src/lib.rs +++ b/crates/net/src/lib.rs @@ -628,7 +628,7 @@ fn pair( let Ok(request) = serde_json::from_str::(&line) else { return false; }; - if request["cb2026"] != "pair" { + if request["cnp"] != "pair" { return false; } let (Some(code), name) = ( @@ -644,7 +644,7 @@ fn pair( Ok(Paired::Yes) ); if paired { - let _ = writeln!(output, r#"{{"cb2026":"paired"}}"#); + let _ = writeln!(output, r#"{{"cnp":"paired"}}"#); } paired } diff --git a/crates/net/tests/discovery.rs b/crates/net/tests/discovery.rs index 693cc73..b91d190 100644 --- a/crates/net/tests/discovery.rs +++ b/crates/net/tests/discovery.rs @@ -152,7 +152,7 @@ fn a_datagram_that_is_not_exactly_a_probe_gets_no_answer() { let good = discovery::probe(); let mut long = good.clone(); long.push(b' '); - let mut other = br#"{"cb2026":"here","v":1}"#.to_vec(); + let mut other = br#"{"cnp":"here","v":1}"#.to_vec(); other.resize(PROBE_BYTES, b' '); let bad = vec![ good[..PROBE_BYTES - 1].to_vec(), @@ -209,7 +209,7 @@ fn the_reply_says_nothing_private() { assert_eq!( keys, [ - "cb2026", + "cnp", "fingerprint", "name", "pairing", diff --git a/crates/net/tests/tls.rs b/crates/net/tests/tls.rs index 19ba227..8bc557a 100644 --- a/crates/net/tests/tls.rs +++ b/crates/net/tests/tls.rs @@ -492,9 +492,9 @@ fn an_oversized_or_malformed_pairing_request_is_closed_on() { for request in [ "x".repeat(5_000), "not json".to_string(), - r#"{"cb2026":"other","code":"1"}"#.to_string(), - r#"{"cb2026":"pair"}"#.to_string(), - format!(r#"{{"cb2026":"pair","code":{code}}}"#), // a number, not a string + r#"{"cnp":"other","code":"1"}"#.to_string(), + r#"{"cnp":"pair"}"#.to_string(), + format!(r#"{{"cnp":"pair","code":{code}}}"#), // a number, not a string ] { let mut c = client::connect(node.address, &me, None).unwrap(); c.send_line(&request).ok(); diff --git a/docs/network-play.md b/docs/network-play.md index e2aa006..be1ec98 100644 --- a/docs/network-play.md +++ b/docs/network-play.md @@ -1,11 +1,11 @@ # Network play: a design for the opt-in listener (#209) -**Status: steps 1–5 built, 6–7 to do.** The listener, TLS and pairing exist in a build with +**Status: steps 1–6 built, 7 later.** The listener, TLS and pairing exist in a build with `--features net`, which is off by default; an ordinary run opens no port. Carlos answered the five decisions on 2026-11-05 (cjus/chessengine#255; [Decisions](#decisions)): pairing with both sides pinning each other, one client at a time, discovery by UDP broadcast, limits set on the engine's machine, and a separate `crates/net`. [How it would be built](#how-it-would-be-built) says what -each step did. Written 2026-11-05; steps 3 to 5 added the same day. +each step did. Written 2026-11-05; steps 3 to 6 added the same day. ## What this is for @@ -205,9 +205,9 @@ search runs, and the listener can't tell that silence from idleness, so a timeou searches. A client that has *gone* (its network dropped, no goodbye) is the real danger to the one place, and keepalive finds it. A client that is connected, alive and idle may keep its place. -The CNP node reports the effective message limit in `initialize` now (`maxMessageBytes`). Its -threads and hash can't be reported yet: `initialize`'s result is the protocol crate's own -type, so that is a specification change, still to do (step 1's note). +The CNP node reports the effective message limit in `initialize` (`maxMessageBytes`), and, since +step 6, the threads and hash it runs with, in a new optional `resources` object +(`{"threads": 8, "hashMb": 1024}`), added to the CNP specification for this (section 5.1). ### Where it lives (Decision 5) @@ -295,8 +295,7 @@ Each step is its own PR with a green CI, and none changes the search: MB`, N from 1 to 256 and MB from 1 to 65,536 as UCI's options are, refused with exit code 2 with any other mode. Without them a node keeps one thread and 16 MB. **A search request can't change them**: the node's owner chooses them, which is the cap the design wants. - Still to do: `initialize` can't report them, since its result is the Chess Node Protocol - crate's own type; that is a change to that specification, made with step 2's work. + `initialize` reports them (step 6: `resources` in the specification). 2. **`crates/net`: framing, limits and a loopback listener** (done 2026-11-05): plaintext on loopback only (any other address is refused), the one-client rule with `Busy` for the rest, a fresh engine for each client, a disconnect cancelling the search, a client's `shutdown` @@ -343,8 +342,16 @@ Each step is its own PR with a green CI, and none changes the search: through a message keeps its place until it disconnects or keepalive finds it dead (there is no idle timeout, because a long search is silent too); another approved client is told `Busy`. **Not done:** fuzzing the listener's input with `cargo fuzz`, and a test across a real network. -6. **Documentation:** a chapter in the book, a README section, a transport section for the CNP - specification, and the licence notices. +6. **Documentation and the specification** (done 2026-11-05): book chapter 22 ("Network play"), a + README section, and, in the Chess Node Protocol repository (cjus/chess-node-protocol#24), + section 3.2 (TLS over TCP, pairing, one client at a time, deadlines), section 3.3 (the + discovery probe and reply), section 10, and `resources` in `initialize`'s result, with a test + that checks the spec's transport examples. The wire messages use the key `"cnp"`, not + `"cb2026"`, so that another node or client can use them. The licence notices need no change + (`scripts/notices.sh` includes `ring`, rustls and the rest). The spec's additions are optional + and went into the 1.0 draft as pondering did; Carlos can ask for 1.1 instead. + **Waiting on Carlos:** a try between two real computers and the decision whether releases carry + the feature (#263). 7. **Later, if wanted:** dial-out mode, isolated per-client engines, IPv6 multicast and mDNS. The Solrac side (a client connection, the pairing screen, the engine list, the discovery probe) diff --git a/docs/status.md b/docs/status.md index 62713a4..5446de3 100644 --- a/docs/status.md +++ b/docs/status.md @@ -224,8 +224,11 @@ Windows and an Intel Mac, and a connection between two real computers (Carlos). rate limited, nothing private; `cb2026_net::client::discover` for a client); **step 5 is done** (4 greetings at once from one address, 8 failures in 10 s earn a 30 s ban, and 14 negative end-to-end tests on the plain and the TLS listener: no change to the CNP node was needed); -step 6 (the book chapter, README section, CNP transport section and notices) is next. No -functional change.* +**step 6 is done** (book chapter 22, a README section, the CNP specification's sections 3.2 and 3.3 +and `resources` in `initialize`, cjus/chess-node-protocol#24, and the pin moved to it; the wire +messages use the key `cnp`); network play now waits only on Carlos: a try between two computers and the +decision whether releases carry the feature (#263); step 7 (dial-out, per-client engines, IPv6) +is for later. No functional change.* ## Stages @@ -594,6 +597,8 @@ The open [`needs-carlos` issues](https://github.com/cjus/chessengine/issues?q=is nets"): output buckets, a second layer and king buckets, each by SPRT on gen3's records. - #191: the Lichess bot's two games, now that v1.0.0 is out (#199 and #183 closed 2026-11-05). - #88: whether macOS honours the search threads' QoS outside Claude Code. +- #263: try network play between two computers, and decide whether the release binaries are built + with `--features net`. On hold: #61, running long tests on AWS Batch (closed 2026-10-12; reopen it if the M3 can't keep up with the test queue).