Skip to main content

rns_net/common/
event.rs

1//! Event types for the driver loop — generic over the writer type.
2
3use std::fmt;
4use std::net::IpAddr;
5use std::sync::mpsc;
6use std::time::Duration;
7
8use rns_core::announce::ValidatedAnnounce;
9use rns_core::transport::announce_verify_queue::AnnounceVerifyKey;
10use rns_core::transport::types::{InterfaceId, InterfaceInfo};
11
12/// Policy for handling incoming direct-connect proposals.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum HolePunchPolicy {
15    /// Reject all proposals.
16    Reject,
17    /// Accept all proposals automatically.
18    AcceptAll,
19    /// Ask the application callback.
20    AskApp,
21}
22
23impl Default for HolePunchPolicy {
24    fn default() -> Self {
25        HolePunchPolicy::AcceptAll
26    }
27}
28
29/// Scalar runtime-config value.
30#[derive(Debug, Clone, PartialEq)]
31pub enum RuntimeConfigValue {
32    Int(i64),
33    Float(f64),
34    Bool(bool),
35    String(String),
36    Null,
37}
38
39/// Source of a runtime-config value.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum RuntimeConfigSource {
42    Startup,
43    RuntimeOverride,
44}
45
46/// How a runtime-config change applies.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum RuntimeConfigApplyMode {
49    Immediate,
50    NewConnectionsOnly,
51    NextReconnect,
52    RestartRequired,
53}
54
55/// A runtime-config entry exposed by the daemon.
56#[derive(Debug, Clone, PartialEq)]
57pub struct RuntimeConfigEntry {
58    pub key: String,
59    pub value: RuntimeConfigValue,
60    pub default: RuntimeConfigValue,
61    pub source: RuntimeConfigSource,
62    pub apply_mode: RuntimeConfigApplyMode,
63    pub description: Option<String>,
64}
65
66/// Runtime-config mutation error.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct RuntimeConfigError {
69    pub code: RuntimeConfigErrorCode,
70    pub message: String,
71}
72
73/// Category of runtime-config mutation error.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum RuntimeConfigErrorCode {
76    UnknownKey,
77    InvalidType,
78    InvalidValue,
79    Unsupported,
80    NotFound,
81    ApplyFailed,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum LifecycleState {
86    Active,
87    Draining,
88    Stopping,
89    Stopped,
90}
91
92#[derive(Debug, Clone, PartialEq)]
93pub struct DrainStatus {
94    pub state: LifecycleState,
95    pub drain_age_seconds: Option<f64>,
96    pub deadline_remaining_seconds: Option<f64>,
97    pub drain_complete: bool,
98    pub interface_writer_queued_frames: usize,
99    pub provider_backlog_events: usize,
100    pub provider_consumer_queued_events: usize,
101    pub detail: Option<String>,
102}
103
104/// Events sent to the driver thread.
105///
106/// `W` is the writer type (e.g. `Box<dyn Writer>` for sync,
107/// or a channel sender for async).
108pub enum Event<W: Send> {
109    /// A decoded frame arrived from an interface.
110    Frame {
111        interface_id: InterfaceId,
112        data: Vec<u8>,
113    },
114    /// (Internal) An announce was verified off-thread and is ready for driver-side processing.
115    AnnounceVerified {
116        key: AnnounceVerifyKey,
117        validated: ValidatedAnnounce,
118        sig_cache_key: [u8; 32],
119    },
120    /// (Internal) An announce failed off-thread verification.
121    AnnounceVerifyFailed {
122        key: AnnounceVerifyKey,
123        sig_cache_key: [u8; 32],
124    },
125    /// An interface came online after (re)connecting.
126    /// Carries a new writer if the connection was re-established.
127    /// Carries InterfaceInfo if this is a new dynamic interface (e.g. TCP server client).
128    InterfaceUp(InterfaceId, Option<W>, Option<InterfaceInfo>),
129    /// An interface went offline (socket closed, error).
130    InterfaceDown(InterfaceId),
131    /// Periodic maintenance tick (1s interval).
132    Tick,
133    /// Enter drain mode and stop admitting new work.
134    BeginDrain { timeout: Duration },
135    /// Shut down the driver loop.
136    Shutdown,
137    /// Send an outbound packet.
138    SendOutbound {
139        raw: Vec<u8>,
140        dest_type: u8,
141        attached_interface: Option<InterfaceId>,
142    },
143    /// Register a local destination.
144    RegisterDestination { dest_hash: [u8; 16], dest_type: u8 },
145    /// Remember the latest explicit SINGLE announce for shared-client replay.
146    StoreSharedAnnounce {
147        dest_hash: [u8; 16],
148        name_hash: [u8; 10],
149        identity_prv_key: [u8; 64],
150        app_data: Option<Vec<u8>>,
151    },
152    /// Deregister a local destination.
153    DeregisterDestination { dest_hash: [u8; 16] },
154    /// Deregister a link destination (stop accepting incoming links).
155    DeregisterLinkDestination { dest_hash: [u8; 16] },
156    /// Query driver state. Response is sent via the provided channel.
157    Query(QueryRequest, mpsc::Sender<QueryResponse>),
158    /// Register a link destination (accepts incoming LINKREQUEST).
159    RegisterLinkDestination {
160        dest_hash: [u8; 16],
161        sig_prv_bytes: [u8; 32],
162        sig_pub_bytes: [u8; 32],
163        resource_strategy: u8,
164    },
165    /// Register a request handler for a path on established links.
166    RegisterRequestHandler {
167        path: String,
168        allowed_list: Option<Vec<[u8; 16]>>,
169        handler: Box<
170            dyn Fn([u8; 16], &str, &[u8], Option<&([u8; 16], [u8; 64])>) -> Option<Vec<u8>> + Send,
171        >,
172    },
173    /// Create an outbound link. Response sends (link_id) back.
174    CreateLink {
175        dest_hash: [u8; 16],
176        dest_sig_pub_bytes: [u8; 32],
177        response_tx: mpsc::Sender<[u8; 16]>,
178    },
179    /// Send a request on an established link.
180    SendRequest {
181        link_id: [u8; 16],
182        path: String,
183        data: Vec<u8>,
184    },
185    /// Identify on a link (send identity to remote peer).
186    IdentifyOnLink {
187        link_id: [u8; 16],
188        identity_prv_key: [u8; 64],
189    },
190    /// Tear down a link.
191    TeardownLink { link_id: [u8; 16] },
192    /// Send a resource on a link.
193    SendResource {
194        link_id: [u8; 16],
195        data: Vec<u8>,
196        metadata: Option<Vec<u8>>,
197    },
198    /// Set the resource acceptance strategy for a link.
199    SetResourceStrategy { link_id: [u8; 16], strategy: u8 },
200    /// Accept or reject a pending resource (for AcceptApp strategy).
201    AcceptResource {
202        link_id: [u8; 16],
203        resource_hash: Vec<u8>,
204        accept: bool,
205    },
206    /// Send a channel message on a link.
207    SendChannelMessage {
208        link_id: [u8; 16],
209        msgtype: u16,
210        payload: Vec<u8>,
211        response_tx: mpsc::Sender<Result<(), String>>,
212    },
213    /// Send generic data on a link with a given context.
214    SendOnLink {
215        link_id: [u8; 16],
216        data: Vec<u8>,
217        context: u8,
218    },
219    /// Request a path to a destination from the network.
220    RequestPath { dest_hash: [u8; 16] },
221    /// Register a proof strategy for a destination.
222    RegisterProofStrategy {
223        dest_hash: [u8; 16],
224        strategy: rns_core::types::ProofStrategy,
225        /// Full identity private key (64 bytes) for signing proofs.
226        signing_key: Option<[u8; 64]>,
227    },
228    /// Propose a direct connection to a peer via hole punching.
229    ProposeDirectConnect { link_id: [u8; 16] },
230    /// Set the direct-connect policy.
231    SetDirectConnectPolicy { policy: HolePunchPolicy },
232    /// (Internal) Probe result arrived from a worker thread.
233    HolePunchProbeResult {
234        link_id: [u8; 16],
235        session_id: [u8; 16],
236        observed_addr: std::net::SocketAddr,
237        socket: std::net::UdpSocket,
238        /// The probe server that responded successfully.
239        probe_server: std::net::SocketAddr,
240    },
241    /// (Internal) Probe failed.
242    HolePunchProbeFailed {
243        link_id: [u8; 16],
244        session_id: [u8; 16],
245    },
246    /// An interface's configuration changed (placeholder for future use).
247    InterfaceConfigChanged(InterfaceId),
248    /// A backbone server accepted a new inbound peer connection.
249    BackbonePeerConnected {
250        server_interface_id: InterfaceId,
251        peer_interface_id: InterfaceId,
252        peer_ip: IpAddr,
253        peer_port: u16,
254    },
255    /// A backbone peer connection closed for any reason.
256    BackbonePeerDisconnected {
257        server_interface_id: InterfaceId,
258        peer_interface_id: InterfaceId,
259        peer_ip: IpAddr,
260        peer_port: u16,
261        connected_for: Duration,
262        had_received_data: bool,
263    },
264    /// A backbone peer was disconnected for idling without sending data.
265    BackbonePeerIdleTimeout {
266        server_interface_id: InterfaceId,
267        peer_interface_id: InterfaceId,
268        peer_ip: IpAddr,
269        peer_port: u16,
270        connected_for: Duration,
271    },
272    /// A backbone peer was disconnected because its writer stalled.
273    BackbonePeerWriteStall {
274        server_interface_id: InterfaceId,
275        peer_interface_id: InterfaceId,
276        peer_ip: IpAddr,
277        peer_port: u16,
278        connected_for: Duration,
279    },
280    /// A backbone peer IP was penalized due to abusive behavior.
281    BackbonePeerPenalty {
282        server_interface_id: InterfaceId,
283        peer_ip: IpAddr,
284        penalty_level: u8,
285        blacklist_for: Duration,
286    },
287    /// Load a WASM hook at runtime.
288    LoadHook {
289        name: String,
290        wasm_bytes: Vec<u8>,
291        attach_point: String,
292        priority: i32,
293        response_tx: mpsc::Sender<Result<(), String>>,
294    },
295    /// Unload a WASM hook at runtime.
296    UnloadHook {
297        name: String,
298        attach_point: String,
299        response_tx: mpsc::Sender<Result<(), String>>,
300    },
301    /// Reload a WASM hook at runtime (detach + recompile + reattach with same priority).
302    ReloadHook {
303        name: String,
304        attach_point: String,
305        wasm_bytes: Vec<u8>,
306        response_tx: mpsc::Sender<Result<(), String>>,
307    },
308    /// Enable or disable a loaded WASM hook at runtime.
309    SetHookEnabled {
310        name: String,
311        attach_point: String,
312        enabled: bool,
313        response_tx: mpsc::Sender<Result<(), String>>,
314    },
315    /// Update the priority of a loaded WASM hook at runtime.
316    SetHookPriority {
317        name: String,
318        attach_point: String,
319        priority: i32,
320        response_tx: mpsc::Sender<Result<(), String>>,
321    },
322    /// List all loaded hooks.
323    ListHooks {
324        response_tx: mpsc::Sender<Vec<HookInfo>>,
325    },
326}
327
328/// Information about a loaded hook program.
329#[derive(Debug, Clone)]
330pub struct HookInfo {
331    pub name: String,
332    pub attach_point: String,
333    pub priority: i32,
334    pub enabled: bool,
335    pub consecutive_traps: u32,
336}
337
338/// Live behavioral state for a backbone peer IP.
339#[derive(Debug, Clone, PartialEq)]
340pub struct BackbonePeerStateEntry {
341    pub interface_name: String,
342    pub peer_ip: IpAddr,
343    pub connected_count: usize,
344    pub blacklisted_remaining_secs: Option<f64>,
345    pub blacklist_reason: Option<String>,
346    pub reject_count: u64,
347}
348
349/// Hook-visible snapshot of a backbone peer lifecycle event.
350#[derive(Debug, Clone, PartialEq, Eq)]
351pub struct BackbonePeerHookEvent {
352    pub server_interface_id: InterfaceId,
353    pub peer_interface_id: Option<InterfaceId>,
354    pub peer_ip: IpAddr,
355    pub peer_port: u16,
356    pub connected_for: Duration,
357    pub had_received_data: bool,
358    pub penalty_level: u8,
359    pub blacklist_for: Duration,
360}
361
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct BackboneInterfaceEntry {
364    pub interface_id: InterfaceId,
365    pub interface_name: String,
366}
367
368#[derive(Debug, Clone, PartialEq)]
369pub struct KnownDestinationEntry {
370    pub dest_hash: [u8; 16],
371    pub identity_hash: [u8; 16],
372    pub public_key: [u8; 64],
373    pub app_data: Option<Vec<u8>>,
374    pub hops: u8,
375    pub received_at: f64,
376    pub receiving_interface: InterfaceId,
377    pub was_used: bool,
378    pub last_used_at: Option<f64>,
379    pub retained: bool,
380}
381
382#[derive(Debug, Clone, PartialEq, Eq)]
383pub struct ProviderBridgeConsumerStats {
384    pub id: u64,
385    pub connected: bool,
386    pub queue_len: usize,
387    pub queued_bytes: usize,
388    pub dropped_pending: u64,
389    pub dropped_total: u64,
390    pub queue_max_events: usize,
391    pub queue_max_bytes: usize,
392}
393
394#[derive(Debug, Clone, PartialEq, Eq)]
395pub struct ProviderBridgeStats {
396    pub connected: bool,
397    pub consumer_count: usize,
398    pub queue_max_events: usize,
399    pub queue_max_bytes: usize,
400    pub backlog_len: usize,
401    pub backlog_bytes: usize,
402    pub backlog_dropped_pending: u64,
403    pub backlog_dropped_total: u64,
404    pub total_disconnect_count: u64,
405    pub consumers: Vec<ProviderBridgeConsumerStats>,
406}
407
408/// Queries that can be sent to the driver.
409#[derive(Debug)]
410pub enum QueryRequest {
411    /// Get interface statistics and transport info.
412    InterfaceStats,
413    /// Get path table entries, optionally filtered by max hops.
414    PathTable { max_hops: Option<u8> },
415    /// Get rate table entries.
416    RateTable,
417    /// Look up the next hop for a destination.
418    NextHop { dest_hash: [u8; 16] },
419    /// Look up the next hop interface name for a destination.
420    NextHopIfName { dest_hash: [u8; 16] },
421    /// Get link table entry count.
422    LinkCount,
423    /// Drop a specific path.
424    DropPath { dest_hash: [u8; 16] },
425    /// Drop all paths that route via a given transport hash.
426    DropAllVia { transport_hash: [u8; 16] },
427    /// Drop all announce queues.
428    DropAnnounceQueues,
429    /// Get the transport identity hash.
430    TransportIdentity,
431    /// Get all blackholed identities.
432    GetBlackholed,
433    /// Add an identity to the blackhole list.
434    BlackholeIdentity {
435        identity_hash: [u8; 16],
436        duration_hours: Option<f64>,
437        reason: Option<String>,
438    },
439    /// Remove an identity from the blackhole list.
440    UnblackholeIdentity { identity_hash: [u8; 16] },
441    /// Check if a path exists to a destination.
442    HasPath { dest_hash: [u8; 16] },
443    /// Get hop count to a destination.
444    HopsTo { dest_hash: [u8; 16] },
445    /// Recall identity info for a destination.
446    RecallIdentity { dest_hash: [u8; 16] },
447    /// List known-destination lifecycle state.
448    KnownDestinations,
449    /// Get locally registered destinations.
450    LocalDestinations,
451    /// Get active links.
452    Links,
453    /// Get active resource transfers.
454    Resources,
455    /// Inject a path entry into the path table.
456    InjectPath {
457        dest_hash: [u8; 16],
458        next_hop: [u8; 16],
459        hops: u8,
460        expires: f64,
461        interface_name: String,
462        packet_hash: [u8; 32],
463    },
464    /// Inject an identity into the known destinations cache.
465    InjectIdentity {
466        dest_hash: [u8; 16],
467        identity_hash: [u8; 16],
468        public_key: [u8; 64],
469        app_data: Option<Vec<u8>>,
470        hops: u8,
471        received_at: f64,
472    },
473    /// Restore a known destination with full lifecycle state.
474    RestoreKnownDestination(KnownDestinationEntry),
475    /// Mark a known destination as explicitly retained.
476    RetainKnownDestination { dest_hash: [u8; 16] },
477    /// Clear the retained flag on a known destination.
478    UnretainKnownDestination { dest_hash: [u8; 16] },
479    /// Mark a known destination as used.
480    MarkKnownDestinationUsed { dest_hash: [u8; 16] },
481    /// Get discovered interfaces.
482    DiscoveredInterfaces {
483        only_available: bool,
484        only_transport: bool,
485    },
486    /// Send a probe packet to a destination and return (packet_hash, hops).
487    SendProbe {
488        dest_hash: [u8; 16],
489        payload_size: usize,
490    },
491    /// Check if a proof was received for a probe packet.
492    CheckProof { packet_hash: [u8; 32] },
493    /// List runtime-config entries currently supported by the daemon.
494    ListRuntimeConfig,
495    /// Get a single runtime-config entry by key.
496    GetRuntimeConfig { key: String },
497    /// Set a runtime-config value by key.
498    SetRuntimeConfig {
499        key: String,
500        value: RuntimeConfigValue,
501    },
502    /// Reset a runtime-config value to its startup/default value.
503    ResetRuntimeConfig { key: String },
504    /// List live backbone peer state, optionally filtered to one interface.
505    BackbonePeerState { interface_name: Option<String> },
506    /// List registered backbone server interfaces.
507    BackboneInterfaces,
508    /// Report live provider-bridge queue/drop state.
509    ProviderBridgeStats,
510    /// Report current lifecycle/drain status.
511    DrainStatus,
512    /// Clear live backbone peer state for one interface/IP pair.
513    ClearBackbonePeerState {
514        interface_name: String,
515        peer_ip: IpAddr,
516    },
517    /// Blacklist a backbone peer IP for a duration.
518    BlacklistBackbonePeer {
519        interface_name: String,
520        peer_ip: IpAddr,
521        duration: Duration,
522        reason: String,
523        penalty_level: u8,
524    },
525}
526
527/// Responses to queries.
528#[derive(Debug)]
529pub enum QueryResponse {
530    InterfaceStats(InterfaceStatsResponse),
531    PathTable(Vec<PathTableEntry>),
532    RateTable(Vec<RateTableEntry>),
533    NextHop(Option<NextHopResponse>),
534    NextHopIfName(Option<String>),
535    LinkCount(usize),
536    DropPath(bool),
537    DropAllVia(usize),
538    DropAnnounceQueues,
539    TransportIdentity(Option<[u8; 16]>),
540    Blackholed(Vec<BlackholeInfo>),
541    BlackholeResult(bool),
542    UnblackholeResult(bool),
543    HasPath(bool),
544    HopsTo(Option<u8>),
545    RecallIdentity(Option<crate::common::destination::AnnouncedIdentity>),
546    KnownDestinations(Vec<KnownDestinationEntry>),
547    LocalDestinations(Vec<LocalDestinationEntry>),
548    Links(Vec<LinkInfoEntry>),
549    Resources(Vec<ResourceInfoEntry>),
550    InjectPath(bool),
551    InjectIdentity(bool),
552    RestoreKnownDestination(bool),
553    RetainKnownDestination(bool),
554    UnretainKnownDestination(bool),
555    MarkKnownDestinationUsed(bool),
556    /// List of discovered interfaces.
557    DiscoveredInterfaces(Vec<crate::common::discovery::DiscoveredInterface>),
558    /// Probe sent: (packet_hash, hops) or None if identity unknown.
559    SendProbe(Option<([u8; 32], u8)>),
560    /// Proof check: RTT if received, None if still pending.
561    CheckProof(Option<f64>),
562    /// Runtime-config entries currently supported by the daemon.
563    RuntimeConfigList(Vec<RuntimeConfigEntry>),
564    /// A specific runtime-config entry, or None if the key is unknown.
565    RuntimeConfigEntry(Option<RuntimeConfigEntry>),
566    /// Result of setting a runtime-config value.
567    RuntimeConfigSet(Result<RuntimeConfigEntry, RuntimeConfigError>),
568    /// Result of resetting a runtime-config value.
569    RuntimeConfigReset(Result<RuntimeConfigEntry, RuntimeConfigError>),
570    /// Live backbone peer state entries.
571    BackbonePeerState(Vec<BackbonePeerStateEntry>),
572    /// Registered backbone server interfaces.
573    BackboneInterfaces(Vec<BackboneInterfaceEntry>),
574    /// Live provider-bridge queue/drop state if enabled.
575    ProviderBridgeStats(Option<ProviderBridgeStats>),
576    /// Current lifecycle/drain status.
577    DrainStatus(DrainStatus),
578    /// Result of clearing one backbone peer state entry.
579    ClearBackbonePeerState(bool),
580    /// Result of blacklisting a backbone peer.
581    BlacklistBackbonePeer(bool),
582}
583
584/// Interface statistics response.
585#[derive(Debug, Clone)]
586pub struct InterfaceStatsResponse {
587    pub interfaces: Vec<SingleInterfaceStat>,
588    pub transport_id: Option<[u8; 16]>,
589    pub transport_enabled: bool,
590    pub transport_uptime: f64,
591    /// Total received bytes across all interfaces.
592    pub total_rxb: u64,
593    /// Total transmitted bytes across all interfaces.
594    pub total_txb: u64,
595    /// Probe responder destination hash (if enabled).
596    pub probe_responder: Option<[u8; 16]>,
597    /// Outbound Backbone peer-pool state, if enabled.
598    pub backbone_peer_pool: Option<BackbonePeerPoolStatus>,
599}
600
601/// Runtime status for the outbound Backbone peer pool.
602#[derive(Debug, Clone)]
603pub struct BackbonePeerPoolStatus {
604    pub max_connected: usize,
605    pub active_count: usize,
606    pub standby_count: usize,
607    pub cooldown_count: usize,
608    pub members: Vec<BackbonePeerPoolMemberStatus>,
609}
610
611/// Runtime status for one outbound Backbone peer-pool member.
612#[derive(Debug, Clone)]
613pub struct BackbonePeerPoolMemberStatus {
614    pub name: String,
615    pub remote: String,
616    pub state: String,
617    pub interface_id: Option<u64>,
618    pub failure_count: usize,
619    pub last_error: Option<String>,
620    pub cooldown_remaining_seconds: Option<f64>,
621}
622
623/// Statistics for a single interface.
624#[derive(Debug, Clone)]
625pub struct SingleInterfaceStat {
626    pub id: u64,
627    pub name: String,
628    pub status: bool,
629    pub mode: u8,
630    pub rxb: u64,
631    pub txb: u64,
632    pub rx_packets: u64,
633    pub tx_packets: u64,
634    pub bitrate: Option<u64>,
635    pub ifac_size: Option<usize>,
636    pub started: f64,
637    /// Incoming announce frequency (per second).
638    pub ia_freq: f64,
639    /// Outgoing announce frequency (per second).
640    pub oa_freq: f64,
641    /// Human-readable interface type string (e.g. "TCPClientInterface").
642    pub interface_type: String,
643}
644
645/// A locally registered destination.
646#[derive(Debug, Clone)]
647pub struct LocalDestinationEntry {
648    pub hash: [u8; 16],
649    pub dest_type: u8,
650}
651
652/// Information about an active link.
653#[derive(Debug, Clone)]
654pub struct LinkInfoEntry {
655    pub link_id: [u8; 16],
656    pub state: String,
657    pub is_initiator: bool,
658    pub dest_hash: [u8; 16],
659    pub remote_identity: Option<[u8; 16]>,
660    pub rtt: Option<f64>,
661    pub channel_window: Option<u16>,
662    pub channel_outstanding: Option<usize>,
663    pub pending_channel_packets: usize,
664    pub channel_send_ok: u64,
665    pub channel_send_not_ready: u64,
666    pub channel_send_too_big: u64,
667    pub channel_send_other_error: u64,
668    pub channel_messages_received: u64,
669    pub channel_proofs_sent: u64,
670    pub channel_proofs_received: u64,
671}
672
673/// Information about an active resource transfer.
674#[derive(Debug, Clone)]
675pub struct ResourceInfoEntry {
676    pub link_id: [u8; 16],
677    pub direction: String,
678    pub total_parts: usize,
679    pub transferred_parts: usize,
680    pub complete: bool,
681}
682
683/// A single path table entry for query responses.
684#[derive(Debug, Clone)]
685pub struct PathTableEntry {
686    pub hash: [u8; 16],
687    pub timestamp: f64,
688    pub via: [u8; 16],
689    pub hops: u8,
690    pub expires: f64,
691    pub interface: InterfaceId,
692    pub interface_name: String,
693}
694
695/// A single rate table entry for query responses.
696#[derive(Debug, Clone)]
697pub struct RateTableEntry {
698    pub hash: [u8; 16],
699    pub last: f64,
700    pub rate_violations: u32,
701    pub blocked_until: f64,
702    pub timestamps: Vec<f64>,
703}
704
705/// A blackholed identity for query responses.
706#[derive(Debug, Clone)]
707pub struct BlackholeInfo {
708    pub identity_hash: [u8; 16],
709    pub created: f64,
710    pub expires: f64,
711    pub reason: Option<String>,
712}
713
714/// Next hop lookup result.
715#[derive(Debug, Clone)]
716pub struct NextHopResponse {
717    pub next_hop: [u8; 16],
718    pub hops: u8,
719    pub interface: InterfaceId,
720}
721
722impl<W: Send> fmt::Debug for Event<W> {
723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724        match self {
725            Event::Frame { interface_id, data } => f
726                .debug_struct("Frame")
727                .field("interface_id", interface_id)
728                .field("data_len", &data.len())
729                .finish(),
730            Event::AnnounceVerified { key, .. } => f
731                .debug_struct("AnnounceVerified")
732                .field("destination_hash", &key.destination_hash)
733                .field("received_from", &key.received_from)
734                .finish(),
735            Event::AnnounceVerifyFailed { key, .. } => f
736                .debug_struct("AnnounceVerifyFailed")
737                .field("destination_hash", &key.destination_hash)
738                .field("received_from", &key.received_from)
739                .finish(),
740            Event::InterfaceUp(id, writer, info) => f
741                .debug_tuple("InterfaceUp")
742                .field(id)
743                .field(&writer.is_some())
744                .field(&info.is_some())
745                .finish(),
746            Event::InterfaceDown(id) => f.debug_tuple("InterfaceDown").field(id).finish(),
747            Event::Tick => write!(f, "Tick"),
748            Event::BeginDrain { timeout } => f
749                .debug_struct("BeginDrain")
750                .field("timeout", timeout)
751                .finish(),
752            Event::Shutdown => write!(f, "Shutdown"),
753            Event::SendOutbound { raw, dest_type, .. } => f
754                .debug_struct("SendOutbound")
755                .field("raw_len", &raw.len())
756                .field("dest_type", dest_type)
757                .finish(),
758            Event::RegisterDestination {
759                dest_hash,
760                dest_type,
761            } => f
762                .debug_struct("RegisterDestination")
763                .field("dest_hash", dest_hash)
764                .field("dest_type", dest_type)
765                .finish(),
766            Event::StoreSharedAnnounce {
767                dest_hash,
768                name_hash,
769                app_data,
770                ..
771            } => f
772                .debug_struct("StoreSharedAnnounce")
773                .field("dest_hash", dest_hash)
774                .field("name_hash", name_hash)
775                .field("app_data_len", &app_data.as_ref().map(|d| d.len()))
776                .finish(),
777            Event::DeregisterDestination { dest_hash } => f
778                .debug_struct("DeregisterDestination")
779                .field("dest_hash", dest_hash)
780                .finish(),
781            Event::DeregisterLinkDestination { dest_hash } => f
782                .debug_struct("DeregisterLinkDestination")
783                .field("dest_hash", dest_hash)
784                .finish(),
785            Event::Query(req, _) => f.debug_tuple("Query").field(req).finish(),
786            Event::RegisterLinkDestination { dest_hash, .. } => f
787                .debug_struct("RegisterLinkDestination")
788                .field("dest_hash", dest_hash)
789                .finish(),
790            Event::RegisterRequestHandler { path, .. } => f
791                .debug_struct("RegisterRequestHandler")
792                .field("path", path)
793                .finish(),
794            Event::CreateLink { dest_hash, .. } => f
795                .debug_struct("CreateLink")
796                .field("dest_hash", dest_hash)
797                .finish(),
798            Event::SendRequest { link_id, path, .. } => f
799                .debug_struct("SendRequest")
800                .field("link_id", link_id)
801                .field("path", path)
802                .finish(),
803            Event::IdentifyOnLink { link_id, .. } => f
804                .debug_struct("IdentifyOnLink")
805                .field("link_id", link_id)
806                .finish(),
807            Event::TeardownLink { link_id } => f
808                .debug_struct("TeardownLink")
809                .field("link_id", link_id)
810                .finish(),
811            Event::SendResource { link_id, data, .. } => f
812                .debug_struct("SendResource")
813                .field("link_id", link_id)
814                .field("data_len", &data.len())
815                .finish(),
816            Event::SetResourceStrategy { link_id, strategy } => f
817                .debug_struct("SetResourceStrategy")
818                .field("link_id", link_id)
819                .field("strategy", strategy)
820                .finish(),
821            Event::AcceptResource {
822                link_id, accept, ..
823            } => f
824                .debug_struct("AcceptResource")
825                .field("link_id", link_id)
826                .field("accept", accept)
827                .finish(),
828            Event::SendChannelMessage {
829                link_id,
830                msgtype,
831                payload,
832                ..
833            } => f
834                .debug_struct("SendChannelMessage")
835                .field("link_id", link_id)
836                .field("msgtype", msgtype)
837                .field("payload_len", &payload.len())
838                .finish(),
839            Event::SendOnLink {
840                link_id,
841                data,
842                context,
843            } => f
844                .debug_struct("SendOnLink")
845                .field("link_id", link_id)
846                .field("data_len", &data.len())
847                .field("context", context)
848                .finish(),
849            Event::RequestPath { dest_hash } => f
850                .debug_struct("RequestPath")
851                .field("dest_hash", dest_hash)
852                .finish(),
853            Event::RegisterProofStrategy {
854                dest_hash,
855                strategy,
856                ..
857            } => f
858                .debug_struct("RegisterProofStrategy")
859                .field("dest_hash", dest_hash)
860                .field("strategy", strategy)
861                .finish(),
862            Event::ProposeDirectConnect { link_id } => f
863                .debug_struct("ProposeDirectConnect")
864                .field("link_id", link_id)
865                .finish(),
866            Event::SetDirectConnectPolicy { .. } => {
867                write!(f, "SetDirectConnectPolicy")
868            }
869            Event::HolePunchProbeResult {
870                link_id,
871                session_id,
872                observed_addr,
873                probe_server,
874                ..
875            } => f
876                .debug_struct("HolePunchProbeResult")
877                .field("link_id", link_id)
878                .field("session_id", session_id)
879                .field("observed_addr", observed_addr)
880                .field("probe_server", probe_server)
881                .finish(),
882            Event::HolePunchProbeFailed {
883                link_id,
884                session_id,
885            } => f
886                .debug_struct("HolePunchProbeFailed")
887                .field("link_id", link_id)
888                .field("session_id", session_id)
889                .finish(),
890            Event::InterfaceConfigChanged(id) => {
891                f.debug_tuple("InterfaceConfigChanged").field(id).finish()
892            }
893            Event::BackbonePeerConnected {
894                server_interface_id,
895                peer_interface_id,
896                peer_ip,
897                peer_port,
898            } => f
899                .debug_struct("BackbonePeerConnected")
900                .field("server_interface_id", server_interface_id)
901                .field("peer_interface_id", peer_interface_id)
902                .field("peer_ip", peer_ip)
903                .field("peer_port", peer_port)
904                .finish(),
905            Event::BackbonePeerDisconnected {
906                server_interface_id,
907                peer_interface_id,
908                peer_ip,
909                peer_port,
910                connected_for,
911                had_received_data,
912            } => f
913                .debug_struct("BackbonePeerDisconnected")
914                .field("server_interface_id", server_interface_id)
915                .field("peer_interface_id", peer_interface_id)
916                .field("peer_ip", peer_ip)
917                .field("peer_port", peer_port)
918                .field("connected_for", connected_for)
919                .field("had_received_data", had_received_data)
920                .finish(),
921            Event::BackbonePeerIdleTimeout {
922                server_interface_id,
923                peer_interface_id,
924                peer_ip,
925                peer_port,
926                connected_for,
927            } => f
928                .debug_struct("BackbonePeerIdleTimeout")
929                .field("server_interface_id", server_interface_id)
930                .field("peer_interface_id", peer_interface_id)
931                .field("peer_ip", peer_ip)
932                .field("peer_port", peer_port)
933                .field("connected_for", connected_for)
934                .finish(),
935            Event::BackbonePeerWriteStall {
936                server_interface_id,
937                peer_interface_id,
938                peer_ip,
939                peer_port,
940                connected_for,
941            } => f
942                .debug_struct("BackbonePeerWriteStall")
943                .field("server_interface_id", server_interface_id)
944                .field("peer_interface_id", peer_interface_id)
945                .field("peer_ip", peer_ip)
946                .field("peer_port", peer_port)
947                .field("connected_for", connected_for)
948                .finish(),
949            Event::BackbonePeerPenalty {
950                server_interface_id,
951                peer_ip,
952                penalty_level,
953                blacklist_for,
954            } => f
955                .debug_struct("BackbonePeerPenalty")
956                .field("server_interface_id", server_interface_id)
957                .field("peer_ip", peer_ip)
958                .field("penalty_level", penalty_level)
959                .field("blacklist_for", blacklist_for)
960                .finish(),
961            Event::LoadHook {
962                name,
963                attach_point,
964                priority,
965                ..
966            } => f
967                .debug_struct("LoadHook")
968                .field("name", name)
969                .field("attach_point", attach_point)
970                .field("priority", priority)
971                .finish(),
972            Event::UnloadHook {
973                name, attach_point, ..
974            } => f
975                .debug_struct("UnloadHook")
976                .field("name", name)
977                .field("attach_point", attach_point)
978                .finish(),
979            Event::ReloadHook {
980                name, attach_point, ..
981            } => f
982                .debug_struct("ReloadHook")
983                .field("name", name)
984                .field("attach_point", attach_point)
985                .finish(),
986            Event::SetHookEnabled {
987                name,
988                attach_point,
989                enabled,
990                ..
991            } => f
992                .debug_struct("SetHookEnabled")
993                .field("name", name)
994                .field("attach_point", attach_point)
995                .field("enabled", enabled)
996                .finish(),
997            Event::SetHookPriority {
998                name,
999                attach_point,
1000                priority,
1001                ..
1002            } => f
1003                .debug_struct("SetHookPriority")
1004                .field("name", name)
1005                .field("attach_point", attach_point)
1006                .field("priority", priority)
1007                .finish(),
1008            Event::ListHooks { .. } => write!(f, "ListHooks"),
1009        }
1010    }
1011}