dig_peer/lib.rs
1//! # dig-peer — the DIG Network peer client
2//!
3//! [`DigPeer`] is the one client every consumer uses to talk to a DIG Network peer. You describe the
4//! peer once ([`PeerTarget`]) and get back a connected [`DigPeer`]; it drives [`dig-nat`](dig_nat)'s
5//! full traversal ladder (direct → UPnP → NAT-PMP → PCP → hole-punch → relayed, IPv6-first) under the
6//! hood, so the caller never chooses a transport. On top of that mutually-authenticated (mTLS)
7//! connection it exposes **typed RPC** over [`dig-rpc-protocol`](dig_rpc_protocol) and seals
8//! **directed** calls end-to-end to the peer's verified BLS-G1 identity (§5.4). [`DigPeer::disconnect`]
9//! tears the connection down cleanly.
10//!
11//! dig-peer is the **client mirror** of `dig-rpc`'s server. It wraps a [`dig_nat::PeerConnection`]
12//! (point-to-point) — NOT `dig-gossip`, which is the mesh/broadcast layer. It is also **not** a
13//! `ChiaPeer`: DigPeer connects to DIG Network peers over dig-nat mTLS + dig-rpc-protocol; it pulls in
14//! zero Chia full-node protocol.
15//!
16//! ## Reaching a SPECIFIC peer requires its `peer_id` (security)
17//!
18//! [`DigPeer::connect`] takes a [`PeerTarget`] carrying the peer's **`peer_id`** (`SHA-256(SPKI DER)`)
19//! and pins the mTLS handshake to it (via dig-nat / dig-tls). Chaining to the DigNetwork CA alone
20//! authorizes *a* DIG peer, never a *specific* one — so a caller that means to reach peer X MUST
21//! supply X's `peer_id`, or a different CA-valid peer could answer in its place. This is enforced, not
22//! advisory: connect fails if the peer that answers does not present the expected `peer_id`.
23//!
24//! ## Directed calls are sealed, fail-closed (§5.4)
25//!
26//! Control RPCs that carry peer-specific content (`getNetworkInfo`, `getPeers`, `announce`) are
27//! DIRECTED: dig-peer seals their payload to the peer's captured BLS-G1 key before sending, so an
28//! intermediary that terminates TLS (a relay) forwards ciphertext it cannot read. A directed call is
29//! **refused** (never downgraded to plaintext) if the peer presented no verified BLS-G1 key or no
30//! local sealing identity is configured — set one with [`DigPeer::with_sealing_identity`].
31//!
32//! Public-read/availability calls (`health`, `getAvailability`, byte-range fetch) carry
33//! public-by-nature, merkle-verified content and are NOT directed (§5.4 sensible-scope exemption):
34//! they ride mTLS unsealed.
35//!
36//! ## Example
37//!
38//! ```no_run
39//! # use std::sync::Arc;
40//! # use dig_peer::{DigPeer, PeerTarget, NodeCert, PeerId};
41//! # async fn run(node: Arc<NodeCert>, peer_id: PeerId, addr: std::net::SocketAddr) -> Result<(), dig_peer::DigPeerError> {
42//! let target = PeerTarget::with_addr(peer_id, addr, "DIG_MAINNET");
43//! let mut peer = DigPeer::connect(&target, &node).await?;
44//! let health = peer.health().await?;
45//! println!("peer status: {}", health.status);
46//! peer.disconnect().await;
47//! # Ok(()) }
48//! ```
49
50#![forbid(unsafe_code)]
51#![warn(missing_docs)]
52
53pub mod error;
54pub mod rpc;
55pub mod seal;
56pub mod state;
57
58use std::sync::Arc;
59
60use dig_nat::{connect_with_runtime, NatConfig, NatRuntime, PeerConnection, PeerId as NatPeerId};
61use dig_rpc_protocol::envelope::{JsonRpcRequest, RequestId};
62use dig_rpc_protocol::types::{
63 AnnounceAck, AnnounceParams, Health, Methods, NetworkInfo, PeersList,
64};
65use dig_rpc_protocol::{JsonRpcResponse, Method};
66use serde::de::DeserializeOwned;
67use serde::Serialize;
68
69pub use dig_nat::{AvailabilityItem, AvailabilityResponse, PeerStream, PeerTarget, RangeRequest};
70pub use dig_tls::{NodeCert, PeerId};
71
72pub use error::{DigPeerError, Result};
73pub use seal::SealingIdentity;
74pub use state::PeerState;
75
76/// A connected DIG Network peer — the client every consumer uses.
77///
78/// Obtain one with [`DigPeer::connect`]. It owns the underlying mTLS [`PeerConnection`], the local and
79/// remote `peer_id`s, the peer's captured BLS-G1 key (the seal target), and an optional
80/// [`SealingIdentity`] for directed calls. Each RPC opens a fresh multiplexed stream, so calls are
81/// naturally concurrent-safe against the mux; the `&mut self` receiver serializes them per client.
82pub struct DigPeer {
83 /// This node's own `peer_id` — the sender identity for directed seals.
84 local_peer_id: PeerId,
85 /// The verified remote `peer_id` (== the [`PeerTarget::peer_id`] asked for).
86 peer_id: PeerId,
87 /// The peer's verified BLS-G1 identity (48-byte compressed), captured from the cert binding.
88 /// `None` for a legacy/unbound peer — directed sealed calls are then refused (fail-closed).
89 peer_bls_pub: Option<[u8; 48]>,
90 /// The multiplexed mTLS connection.
91 conn: PeerConnection,
92 /// The local sealing identity for directed calls; `None` until [`Self::with_sealing_identity`].
93 sealing: Option<SealingIdentity>,
94 /// The connection lifecycle state.
95 state: PeerState,
96 /// The next JSON-RPC request id.
97 next_id: u64,
98}
99
100impl std::fmt::Debug for DigPeer {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 f.debug_struct("DigPeer")
103 .field("peer_id", &self.peer_id)
104 .field("state", &self.state)
105 .field("sealable", &self.peer_bls_pub.is_some())
106 .field("has_sealing_identity", &self.sealing.is_some())
107 .finish()
108 }
109}
110
111impl DigPeer {
112 /// Connect to `peer`, driving the Direct traversal tier only (the convenience entry point for a
113 /// publicly-reachable peer / loopback). A NAT'd peer needing the full ladder uses
114 /// [`Self::connect_with_runtime`].
115 ///
116 /// `tls` is this node's mTLS [`NodeCert`]; the handshake pins the remote to
117 /// [`PeerTarget::peer_id`] (see the crate-level security note). Captures the peer's BLS-G1 key for
118 /// sealing.
119 ///
120 /// # Errors
121 /// [`DigPeerError::Transport`] if the peer is unreachable or the `peer_id` pin fails.
122 pub async fn connect(peer: &PeerTarget, tls: &Arc<NodeCert>) -> Result<Self> {
123 Self::connect_with_runtime(peer, tls, &NatConfig::default(), &NatRuntime::default()).await
124 }
125
126 /// Connect to `peer`, auto-composing the **full** NAT-traversal ladder from `config` + the live
127 /// `runtime` handles (direct → UPnP → NAT-PMP → PCP → hole-punch → relayed, IPv6-first). The
128 /// caller never chooses the method — dig-nat picks the first tier that establishes a
129 /// `peer_id`-verified mTLS connection.
130 ///
131 /// # Errors
132 /// [`DigPeerError::Transport`] if no tier could be composed or every composed tier failed.
133 pub async fn connect_with_runtime(
134 peer: &PeerTarget,
135 tls: &Arc<NodeCert>,
136 config: &NatConfig,
137 runtime: &NatRuntime,
138 ) -> Result<Self> {
139 let conn = connect_with_runtime(peer, tls, config, runtime).await?;
140 verify_pinned_peer_id(peer.peer_id, conn.peer_id)?;
141 Ok(Self::from_connection(tls.peer_id(), conn))
142 }
143
144 /// Wrap an already-established [`PeerConnection`] as a [`DigPeer`], recording this node's own
145 /// `peer_id` (`local_peer_id`, the sender identity for directed seals).
146 ///
147 /// Useful for a serving node that accepted an inbound dig-nat connection and wants the typed-RPC
148 /// client surface over it, without re-dialing.
149 ///
150 /// Unlike [`Self::connect_with_runtime`], this does NOT run the [`verify_pinned_peer_id`]
151 /// defense-in-depth check: an *accepted inbound* connection has no caller-pinned target to compare
152 /// against — its remote `peer_id` is *captured* from the verified handshake (`conn.peer_id`),
153 /// not *pinned* by this node. The mTLS handshake still authenticated that identity; there is simply
154 /// no expected value to assert equality against.
155 #[must_use]
156 pub fn from_connection(local_peer_id: NatPeerId, conn: PeerConnection) -> Self {
157 Self {
158 local_peer_id,
159 peer_id: conn.peer_id,
160 peer_bls_pub: conn.peer_bls_pub,
161 conn,
162 sealing: None,
163 state: PeerState::Connected,
164 next_id: 1,
165 }
166 }
167
168 /// Attach a [`SealingIdentity`] so this client can make **directed** (sealed) RPC calls. Without
169 /// one, directed calls fail with [`DigPeerError::NoSealingIdentity`].
170 #[must_use]
171 pub fn with_sealing_identity(mut self, sealing: SealingIdentity) -> Self {
172 self.sealing = Some(sealing);
173 self
174 }
175
176 /// The verified remote `peer_id`.
177 #[must_use]
178 pub fn peer_id(&self) -> PeerId {
179 self.peer_id
180 }
181
182 /// The peer's verified BLS-G1 identity (the seal target), or `None` for an unbound peer.
183 #[must_use]
184 pub fn peer_bls_pub(&self) -> Option<[u8; 48]> {
185 self.peer_bls_pub
186 }
187
188 /// The connection lifecycle state.
189 #[must_use]
190 pub fn state(&self) -> PeerState {
191 self.state
192 }
193
194 /// Whether directed sealed RPC is possible right now (the peer is bound AND a sealing identity is
195 /// configured).
196 #[must_use]
197 pub fn is_sealable(&self) -> bool {
198 self.peer_bls_pub.is_some() && self.sealing.is_some()
199 }
200
201 // ---- Typed RPC methods ---------------------------------------------------------------------
202
203 /// `dig.health` — liveness + capability summary. Public-read (unsealed).
204 ///
205 /// # Errors
206 /// [`DigPeerError`] on transport/protocol failure or a peer RPC error.
207 pub async fn health(&mut self) -> Result<Health> {
208 self.call_public(Method::Health, &serde_json::Value::Null)
209 .await
210 }
211
212 /// `dig.methods` — the method names this peer implements (agent self-describe). Public-read.
213 ///
214 /// # Errors
215 /// [`DigPeerError`] on transport/protocol failure or a peer RPC error.
216 pub async fn methods(&mut self) -> Result<Methods> {
217 self.call_public(Method::Methods, &serde_json::Value::Null)
218 .await
219 }
220
221 /// `dig.getNetworkInfo` — this peer's own network posture. **Directed** (sealed §5.4).
222 ///
223 /// # Errors
224 /// [`DigPeerError::PeerNotSealable`]/[`DigPeerError::NoSealingIdentity`] if sealing is impossible;
225 /// otherwise transport/protocol/seal failures or a peer RPC error.
226 pub async fn get_network_info(&mut self) -> Result<NetworkInfo> {
227 self.call_directed(Method::GetNetworkInfo, &serde_json::Value::Null)
228 .await
229 }
230
231 /// `dig.getPeers` — the peers this peer knows (peer exchange). **Directed** (sealed §5.4).
232 ///
233 /// # Errors
234 /// As [`Self::get_network_info`].
235 pub async fn get_peers(&mut self) -> Result<PeersList> {
236 self.call_directed(Method::GetPeers, &serde_json::Value::Null)
237 .await
238 }
239
240 /// `dig.announce` — announce this node's presence to the peer. **Directed** (sealed §5.4).
241 ///
242 /// # Errors
243 /// As [`Self::get_network_info`].
244 pub async fn announce(&mut self, params: &AnnounceParams) -> Result<AnnounceAck> {
245 self.call_directed(Method::Announce, params).await
246 }
247
248 /// `dig.getAvailability` — batch presence pre-check across stores/roots/capsules. Public content
249 /// presence (unsealed §5.4 exemption); delegates to the dig-nat mux availability primitive.
250 ///
251 /// # Errors
252 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
253 pub async fn get_availability(
254 &mut self,
255 items: Vec<AvailabilityItem>,
256 ) -> Result<AvailabilityResponse> {
257 self.ensure_usable()?;
258 Ok(self.conn.query_availability(items).await?)
259 }
260
261 /// `dig.fetchRange` — open a byte-range stream for `req` (public merkle-verified content, unsealed
262 /// §5.4 exemption); delegates to the dig-nat mux range primitive. Returns the raw stream the
263 /// caller reads [`dig_nat::RangeFrame`]s from.
264 ///
265 /// # Errors
266 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
267 pub async fn fetch_range(&mut self, req: &RangeRequest) -> Result<dig_nat::PeerStream> {
268 self.ensure_usable()?;
269 Ok(self.conn.open_range_stream(req).await?)
270 }
271
272 /// Open a generic **raw** multiplexed stream over the (already-established, mTLS-authenticated)
273 /// connection and hand it to the caller — the **unsealed raw-stream escape hatch** for a consumer
274 /// that carries its OWN wire framing rather than dig-peer's typed RPC methods.
275 ///
276 /// This is the same authenticated mux path [`Self::fetch_range`] and the internal RPC calls ride;
277 /// it performs NO framing, NO JSON, and NO sealing — the bytes on the wire are entirely the
278 /// caller's. It exists because a same-level (L20) consumer (e.g. `dig-dht`, whose `DhtRequest`
279 /// dig-peer cannot typed-wrap without an illegal same-level dependency) must encode/decode its own
280 /// frame over the authenticated connection.
281 ///
282 /// **Unsealed, by design.** Like content/[`Self::fetch_range`], the stream rides mTLS but is NOT
283 /// end-to-end sealed. Directed/secret messages MUST use the sealed typed methods
284 /// ([`Self::get_network_info`], [`Self::get_peers`], [`Self::announce`]) — never this escape hatch.
285 /// A caller that puts recipient-specific secret content on this stream is responsible for its own
286 /// §5.4 sealing; dig-peer does not seal it.
287 ///
288 /// # Errors
289 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
290 pub async fn open_stream(&mut self) -> Result<PeerStream> {
291 self.ensure_usable()?;
292 Ok(self.conn.open_stream().await?)
293 }
294
295 /// Cleanly tear down the connection. Once closed, RPCs fail with [`DigPeerError::InvalidState`].
296 /// Dropping the underlying session ends the mux driver and closes the mTLS byte stream.
297 pub async fn disconnect(mut self) {
298 self.state = PeerState::Closed;
299 // Dropping `self` (and thus `conn`/its `PeerSession`) closes the mux command channel, which
300 // ends the driver task and tears down the underlying byte stream. The explicit state flip is
301 // for symmetry + any post-teardown hooks; the drop does the real work.
302 }
303
304 // ---- Internal call plumbing ----------------------------------------------------------------
305
306 /// Issue an UNSEALED (public-read) JSON-RPC call over a fresh stream.
307 async fn call_public<P, R>(&mut self, method: Method, params: &P) -> Result<R>
308 where
309 P: Serialize,
310 R: DeserializeOwned,
311 {
312 self.ensure_usable()?;
313 let request = self.build_request(method, params)?;
314 let body = rpc::to_json(&request)?;
315
316 let mut stream = self.conn.open_stream().await?;
317 rpc::write_framed(&mut stream, &body).await?;
318 let response_bytes = rpc::read_framed(&mut stream).await?;
319 Self::decode_result(&response_bytes)
320 }
321
322 /// Issue a DIRECTED (sealed §5.4) JSON-RPC call over a fresh stream — fail-closed if the peer is
323 /// unbound or no sealing identity is configured.
324 async fn call_directed<P, R>(&mut self, method: Method, params: &P) -> Result<R>
325 where
326 P: Serialize,
327 R: DeserializeOwned,
328 {
329 self.ensure_usable()?;
330 let peer_bls_pub = self.peer_bls_pub.ok_or(DigPeerError::PeerNotSealable)?;
331 if self.sealing.is_none() {
332 return Err(DigPeerError::NoSealingIdentity);
333 }
334
335 let request = self.build_request(method, params)?;
336 let plaintext = rpc::to_json(&request)?;
337
338 let (local_peer_id, peer_id) = (self.local_peer_id, self.peer_id);
339 let sealing = self.sealing.as_mut().expect("checked is_some above");
340 let (sealed_request, correlation) =
341 sealing.seal_request(local_peer_id, peer_id, &peer_bls_pub, &plaintext)?;
342
343 let mut stream = self.conn.open_stream().await?;
344 rpc::write_framed(&mut stream, &sealed_request).await?;
345 let sealed_response = rpc::read_framed(&mut stream).await?;
346
347 let sealing = self.sealing.as_mut().expect("checked is_some above");
348 let plaintext_response =
349 sealing.open_response(&peer_bls_pub, correlation, &sealed_response)?;
350 Self::decode_result(&plaintext_response)
351 }
352
353 /// Build a typed JSON-RPC request envelope with the next correlation id.
354 fn build_request<P: Serialize>(
355 &mut self,
356 method: Method,
357 params: &P,
358 ) -> Result<JsonRpcRequest<serde_json::Value>> {
359 let params_value =
360 serde_json::to_value(params).map_err(|e| DigPeerError::Codec(e.to_string()))?;
361 let id = self.next_id;
362 self.next_id = self.next_id.wrapping_add(1);
363 Ok(JsonRpcRequest {
364 jsonrpc: dig_rpc_protocol::Version,
365 id: RequestId::Num(id),
366 method: method.name().to_string(),
367 params: Some(params_value),
368 })
369 }
370
371 /// Decode a JSON-RPC response body into `R`, mapping a peer error envelope to
372 /// [`DigPeerError::Rpc`].
373 fn decode_result<R: DeserializeOwned>(bytes: &[u8]) -> Result<R> {
374 let response: JsonRpcResponse<serde_json::Value> = rpc::from_json(bytes)?;
375 if let Some(error) = response.as_error() {
376 return Err(DigPeerError::Rpc(Box::new(error.clone())));
377 }
378 match response.as_result() {
379 Some(value) => serde_json::from_value(value.clone())
380 .map_err(|e| DigPeerError::Codec(e.to_string())),
381 None => Err(DigPeerError::Codec(
382 "response carried neither result nor error".into(),
383 )),
384 }
385 }
386
387 /// Reject an operation if the connection is not usable (post-disconnect).
388 ///
389 /// Defensive guard. Today the [`PeerState::Closed`] branch is effectively **unreachable through the
390 /// public API**: the only transition to `Closed` is [`Self::disconnect`], which consumes `self`, so
391 /// a caller cannot hold a `DigPeer` and issue an RPC after closing it (use-after-close is prevented
392 /// at the type level, not merely by this runtime check). The branch is retained as an explicit
393 /// invariant so that a future non-consuming close / opportunistic re-dial (a documented follow-up)
394 /// stays fail-closed by construction rather than by accident.
395 fn ensure_usable(&self) -> Result<()> {
396 if self.state.is_usable() {
397 Ok(())
398 } else {
399 Err(DigPeerError::InvalidState(self.state))
400 }
401 }
402}
403
404/// Verify the connection's authenticated remote `peer_id` matches the one the caller pinned in the
405/// [`PeerTarget`]. `dig-nat`/`dig-tls` already enforce this pin during the mTLS handshake (a peer that
406/// presents the wrong `peer_id` is rejected before a connection is ever returned), so this check is
407/// **defense-in-depth**: if a future transport regression returned a connection to a different peer
408/// than requested, dig-peer fails closed with [`DigPeerError::PeerIdMismatch`] rather than silently
409/// handing back the wrong peer.
410fn verify_pinned_peer_id(expected: PeerId, actual: PeerId) -> Result<()> {
411 if expected == actual {
412 Ok(())
413 } else {
414 Err(DigPeerError::PeerIdMismatch { expected, actual })
415 }
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use dig_rpc_protocol::error::{ErrorCode, ErrorOrigin, RpcError};
422
423 /// **Proves:** a JSON-RPC success body decodes into the typed result.
424 #[test]
425 fn decode_result_returns_the_typed_result() {
426 let response = JsonRpcResponse::success(RequestId::Num(1), serde_json::json!({"n": 7}));
427 let bytes = serde_json::to_vec(&response).unwrap();
428 let value: serde_json::Value = DigPeer::decode_result(&bytes).expect("decodes");
429 assert_eq!(value["n"], 7);
430 }
431
432 /// **Proves:** a JSON-RPC error body maps to [`DigPeerError::Rpc`] carrying the peer's error.
433 #[test]
434 fn decode_result_maps_a_peer_error_envelope() {
435 let rpc_error = RpcError::new(
436 ErrorCode::MethodNotFound,
437 "method not found",
438 ErrorOrigin::Node,
439 );
440 let response: JsonRpcResponse = JsonRpcResponse::error(RequestId::Num(1), rpc_error);
441 let bytes = serde_json::to_vec(&response).unwrap();
442 let result: Result<serde_json::Value> = DigPeer::decode_result(&bytes);
443 assert!(matches!(result, Err(DigPeerError::Rpc(_))));
444 }
445
446 /// **Proves:** a body that is neither result nor error is a `Codec` failure, not a silent success.
447 #[test]
448 fn decode_result_rejects_a_bodyless_response() {
449 let result: Result<serde_json::Value> = DigPeer::decode_result(b"garbage");
450 assert!(matches!(result, Err(DigPeerError::Codec(_))));
451 }
452
453 /// **Proves:** the defense-in-depth pin check accepts a connection whose `peer_id` matches the
454 /// pinned target.
455 #[test]
456 fn verify_pinned_peer_id_accepts_a_match() {
457 let id = PeerId::from_bytes([0x11; 32]);
458 assert!(verify_pinned_peer_id(id, id).is_ok());
459 }
460
461 /// **Proves:** the defense-in-depth pin check fails CLOSED (`PeerIdMismatch`) when the answering
462 /// peer's `peer_id` differs from the pinned target — dig-peer never hands back the wrong peer even
463 /// if the transport's own pin regressed.
464 /// **Catches:** a regression that dropped the belt-and-suspenders check and trusted the transport
465 /// to have upheld the pin (the check silently accepting any peer).
466 #[test]
467 fn verify_pinned_peer_id_rejects_a_mismatch() {
468 let expected = PeerId::from_bytes([0x11; 32]);
469 let actual = PeerId::from_bytes([0x22; 32]);
470 assert!(matches!(
471 verify_pinned_peer_id(expected, actual),
472 Err(DigPeerError::PeerIdMismatch { .. })
473 ));
474 }
475}