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 Ok(Self::from_connection(tls.peer_id(), conn))
141 }
142
143 /// Wrap an already-established [`PeerConnection`] as a [`DigPeer`], recording this node's own
144 /// `peer_id` (`local_peer_id`, the sender identity for directed seals).
145 ///
146 /// Useful for a serving node that accepted an inbound dig-nat connection and wants the typed-RPC
147 /// client surface over it, without re-dialing.
148 #[must_use]
149 pub fn from_connection(local_peer_id: NatPeerId, conn: PeerConnection) -> Self {
150 Self {
151 local_peer_id,
152 peer_id: conn.peer_id,
153 peer_bls_pub: conn.peer_bls_pub,
154 conn,
155 sealing: None,
156 state: PeerState::Connected,
157 next_id: 1,
158 }
159 }
160
161 /// Attach a [`SealingIdentity`] so this client can make **directed** (sealed) RPC calls. Without
162 /// one, directed calls fail with [`DigPeerError::NoSealingIdentity`].
163 #[must_use]
164 pub fn with_sealing_identity(mut self, sealing: SealingIdentity) -> Self {
165 self.sealing = Some(sealing);
166 self
167 }
168
169 /// The verified remote `peer_id`.
170 #[must_use]
171 pub fn peer_id(&self) -> PeerId {
172 self.peer_id
173 }
174
175 /// The peer's verified BLS-G1 identity (the seal target), or `None` for an unbound peer.
176 #[must_use]
177 pub fn peer_bls_pub(&self) -> Option<[u8; 48]> {
178 self.peer_bls_pub
179 }
180
181 /// The connection lifecycle state.
182 #[must_use]
183 pub fn state(&self) -> PeerState {
184 self.state
185 }
186
187 /// Whether directed sealed RPC is possible right now (the peer is bound AND a sealing identity is
188 /// configured).
189 #[must_use]
190 pub fn is_sealable(&self) -> bool {
191 self.peer_bls_pub.is_some() && self.sealing.is_some()
192 }
193
194 // ---- Typed RPC methods ---------------------------------------------------------------------
195
196 /// `dig.health` — liveness + capability summary. Public-read (unsealed).
197 ///
198 /// # Errors
199 /// [`DigPeerError`] on transport/protocol failure or a peer RPC error.
200 pub async fn health(&mut self) -> Result<Health> {
201 self.call_public(Method::Health, &serde_json::Value::Null)
202 .await
203 }
204
205 /// `dig.methods` — the method names this peer implements (agent self-describe). Public-read.
206 ///
207 /// # Errors
208 /// [`DigPeerError`] on transport/protocol failure or a peer RPC error.
209 pub async fn methods(&mut self) -> Result<Methods> {
210 self.call_public(Method::Methods, &serde_json::Value::Null)
211 .await
212 }
213
214 /// `dig.getNetworkInfo` — this peer's own network posture. **Directed** (sealed §5.4).
215 ///
216 /// # Errors
217 /// [`DigPeerError::PeerNotSealable`]/[`DigPeerError::NoSealingIdentity`] if sealing is impossible;
218 /// otherwise transport/protocol/seal failures or a peer RPC error.
219 pub async fn get_network_info(&mut self) -> Result<NetworkInfo> {
220 self.call_directed(Method::GetNetworkInfo, &serde_json::Value::Null)
221 .await
222 }
223
224 /// `dig.getPeers` — the peers this peer knows (peer exchange). **Directed** (sealed §5.4).
225 ///
226 /// # Errors
227 /// As [`Self::get_network_info`].
228 pub async fn get_peers(&mut self) -> Result<PeersList> {
229 self.call_directed(Method::GetPeers, &serde_json::Value::Null)
230 .await
231 }
232
233 /// `dig.announce` — announce this node's presence to the peer. **Directed** (sealed §5.4).
234 ///
235 /// # Errors
236 /// As [`Self::get_network_info`].
237 pub async fn announce(&mut self, params: &AnnounceParams) -> Result<AnnounceAck> {
238 self.call_directed(Method::Announce, params).await
239 }
240
241 /// `dig.getAvailability` — batch presence pre-check across stores/roots/capsules. Public content
242 /// presence (unsealed §5.4 exemption); delegates to the dig-nat mux availability primitive.
243 ///
244 /// # Errors
245 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
246 pub async fn get_availability(
247 &mut self,
248 items: Vec<AvailabilityItem>,
249 ) -> Result<AvailabilityResponse> {
250 self.ensure_usable()?;
251 Ok(self.conn.query_availability(items).await?)
252 }
253
254 /// `dig.fetchRange` — open a byte-range stream for `req` (public merkle-verified content, unsealed
255 /// §5.4 exemption); delegates to the dig-nat mux range primitive. Returns the raw stream the
256 /// caller reads [`dig_nat::RangeFrame`]s from.
257 ///
258 /// # Errors
259 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
260 pub async fn fetch_range(&mut self, req: &RangeRequest) -> Result<dig_nat::PeerStream> {
261 self.ensure_usable()?;
262 Ok(self.conn.open_range_stream(req).await?)
263 }
264
265 /// Open a generic **raw** multiplexed stream over the (already-established, mTLS-authenticated)
266 /// connection and hand it to the caller — the **unsealed raw-stream escape hatch** for a consumer
267 /// that carries its OWN wire framing rather than dig-peer's typed RPC methods.
268 ///
269 /// This is the same authenticated mux path [`Self::fetch_range`] and the internal RPC calls ride;
270 /// it performs NO framing, NO JSON, and NO sealing — the bytes on the wire are entirely the
271 /// caller's. It exists because a same-level (L20) consumer (e.g. `dig-dht`, whose `DhtRequest`
272 /// dig-peer cannot typed-wrap without an illegal same-level dependency) must encode/decode its own
273 /// frame over the authenticated connection.
274 ///
275 /// **Unsealed, by design.** Like content/[`Self::fetch_range`], the stream rides mTLS but is NOT
276 /// end-to-end sealed. Directed/secret messages MUST use the sealed typed methods
277 /// ([`Self::get_network_info`], [`Self::get_peers`], [`Self::announce`]) — never this escape hatch.
278 /// A caller that puts recipient-specific secret content on this stream is responsible for its own
279 /// §5.4 sealing; dig-peer does not seal it.
280 ///
281 /// # Errors
282 /// [`DigPeerError::Io`] on stream failure; [`DigPeerError::InvalidState`] after disconnect.
283 pub async fn open_stream(&mut self) -> Result<PeerStream> {
284 self.ensure_usable()?;
285 Ok(self.conn.open_stream().await?)
286 }
287
288 /// Cleanly tear down the connection. Once closed, RPCs fail with [`DigPeerError::InvalidState`].
289 /// Dropping the underlying session ends the mux driver and closes the mTLS byte stream.
290 pub async fn disconnect(mut self) {
291 self.state = PeerState::Closed;
292 // Dropping `self` (and thus `conn`/its `PeerSession`) closes the mux command channel, which
293 // ends the driver task and tears down the underlying byte stream. The explicit state flip is
294 // for symmetry + any post-teardown hooks; the drop does the real work.
295 }
296
297 // ---- Internal call plumbing ----------------------------------------------------------------
298
299 /// Issue an UNSEALED (public-read) JSON-RPC call over a fresh stream.
300 async fn call_public<P, R>(&mut self, method: Method, params: &P) -> Result<R>
301 where
302 P: Serialize,
303 R: DeserializeOwned,
304 {
305 self.ensure_usable()?;
306 let request = self.build_request(method, params)?;
307 let body = rpc::to_json(&request)?;
308
309 let mut stream = self.conn.open_stream().await?;
310 rpc::write_framed(&mut stream, &body).await?;
311 let response_bytes = rpc::read_framed(&mut stream).await?;
312 Self::decode_result(&response_bytes)
313 }
314
315 /// Issue a DIRECTED (sealed §5.4) JSON-RPC call over a fresh stream — fail-closed if the peer is
316 /// unbound or no sealing identity is configured.
317 async fn call_directed<P, R>(&mut self, method: Method, params: &P) -> Result<R>
318 where
319 P: Serialize,
320 R: DeserializeOwned,
321 {
322 self.ensure_usable()?;
323 let peer_bls_pub = self.peer_bls_pub.ok_or(DigPeerError::PeerNotSealable)?;
324 if self.sealing.is_none() {
325 return Err(DigPeerError::NoSealingIdentity);
326 }
327
328 let request = self.build_request(method, params)?;
329 let plaintext = rpc::to_json(&request)?;
330
331 let (local_peer_id, peer_id) = (self.local_peer_id, self.peer_id);
332 let sealing = self.sealing.as_mut().expect("checked is_some above");
333 let (sealed_request, correlation) =
334 sealing.seal_request(local_peer_id, peer_id, &peer_bls_pub, &plaintext)?;
335
336 let mut stream = self.conn.open_stream().await?;
337 rpc::write_framed(&mut stream, &sealed_request).await?;
338 let sealed_response = rpc::read_framed(&mut stream).await?;
339
340 let sealing = self.sealing.as_mut().expect("checked is_some above");
341 let plaintext_response =
342 sealing.open_response(&peer_bls_pub, correlation, &sealed_response)?;
343 Self::decode_result(&plaintext_response)
344 }
345
346 /// Build a typed JSON-RPC request envelope with the next correlation id.
347 fn build_request<P: Serialize>(
348 &mut self,
349 method: Method,
350 params: &P,
351 ) -> Result<JsonRpcRequest<serde_json::Value>> {
352 let params_value =
353 serde_json::to_value(params).map_err(|e| DigPeerError::Codec(e.to_string()))?;
354 let id = self.next_id;
355 self.next_id = self.next_id.wrapping_add(1);
356 Ok(JsonRpcRequest {
357 jsonrpc: dig_rpc_protocol::Version,
358 id: RequestId::Num(id),
359 method: method.name().to_string(),
360 params: Some(params_value),
361 })
362 }
363
364 /// Decode a JSON-RPC response body into `R`, mapping a peer error envelope to
365 /// [`DigPeerError::Rpc`].
366 fn decode_result<R: DeserializeOwned>(bytes: &[u8]) -> Result<R> {
367 let response: JsonRpcResponse<serde_json::Value> = rpc::from_json(bytes)?;
368 if let Some(error) = response.as_error() {
369 return Err(DigPeerError::Rpc(Box::new(error.clone())));
370 }
371 match response.as_result() {
372 Some(value) => serde_json::from_value(value.clone())
373 .map_err(|e| DigPeerError::Codec(e.to_string())),
374 None => Err(DigPeerError::Codec(
375 "response carried neither result nor error".into(),
376 )),
377 }
378 }
379
380 /// Reject an operation if the connection is not usable (post-disconnect).
381 fn ensure_usable(&self) -> Result<()> {
382 if self.state.is_usable() {
383 Ok(())
384 } else {
385 Err(DigPeerError::InvalidState(self.state))
386 }
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use dig_rpc_protocol::error::{ErrorCode, ErrorOrigin, RpcError};
394
395 /// **Proves:** a JSON-RPC success body decodes into the typed result.
396 #[test]
397 fn decode_result_returns_the_typed_result() {
398 let response = JsonRpcResponse::success(RequestId::Num(1), serde_json::json!({"n": 7}));
399 let bytes = serde_json::to_vec(&response).unwrap();
400 let value: serde_json::Value = DigPeer::decode_result(&bytes).expect("decodes");
401 assert_eq!(value["n"], 7);
402 }
403
404 /// **Proves:** a JSON-RPC error body maps to [`DigPeerError::Rpc`] carrying the peer's error.
405 #[test]
406 fn decode_result_maps_a_peer_error_envelope() {
407 let rpc_error = RpcError::new(
408 ErrorCode::MethodNotFound,
409 "method not found",
410 ErrorOrigin::Node,
411 );
412 let response: JsonRpcResponse = JsonRpcResponse::error(RequestId::Num(1), rpc_error);
413 let bytes = serde_json::to_vec(&response).unwrap();
414 let result: Result<serde_json::Value> = DigPeer::decode_result(&bytes);
415 assert!(matches!(result, Err(DigPeerError::Rpc(_))));
416 }
417
418 /// **Proves:** a body that is neither result nor error is a `Codec` failure, not a silent success.
419 #[test]
420 fn decode_result_rejects_a_bodyless_response() {
421 let result: Result<serde_json::Value> = DigPeer::decode_result(b"garbage");
422 assert!(matches!(result, Err(DigPeerError::Codec(_))));
423 }
424}