1use serde::{Deserialize, Serialize};
99use smallvec::SmallVec;
100use std::borrow::Cow;
101use std::collections::HashMap;
102use std::io;
103use std::net::SocketAddr;
104use std::time::Duration;
105use thiserror::Error;
106
107#[derive(Debug, Error)]
113pub enum P2PError {
114 #[error("Network error: {0}")]
116 Network(#[from] NetworkError),
117
118 #[error("DHT error: {0}")]
120 Dht(#[from] DhtError),
121
122 #[error("Identity error: {0}")]
124 Identity(#[from] IdentityError),
125
126 #[error("Cryptography error: {0}")]
128 Crypto(#[from] CryptoError),
129
130 #[error("Storage error: {0}")]
132 Storage(#[from] StorageError),
133
134 #[error("Transport error: {0}")]
136 Transport(#[from] TransportError),
137
138 #[error("Configuration error: {0}")]
140 Config(#[from] ConfigError),
141
142 #[error("Security error: {0}")]
144 Security(#[from] SecurityError),
145
146 #[error("Bootstrap error: {0}")]
148 Bootstrap(#[from] BootstrapError),
149
150 #[error("IO error: {0}")]
152 Io(#[from] io::Error),
153
154 #[error("Serialization error: {0}")]
156 Serialization(Cow<'static, str>),
157
158 #[error("Validation error: {0}")]
160 Validation(Cow<'static, str>),
161
162 #[error("Operation timed out after {0:?}")]
164 Timeout(Duration),
165
166 #[error("Resource exhausted: {0}")]
168 ResourceExhausted(Cow<'static, str>),
169
170 #[error("Internal error: {0}")]
172 Internal(Cow<'static, str>),
173
174 #[error("Encoding error: {0}")]
176 Encoding(Cow<'static, str>),
177
178 #[error("Record too large: {0} bytes (max 512)")]
180 RecordTooLarge(usize),
181
182 #[error("Time error")]
184 TimeError,
185
186 #[error("Invalid input: {0}")]
188 InvalidInput(String),
189
190 #[error("WebRTC error: {0}")]
192 WebRtcError(String),
193}
194
195#[derive(Debug, Error)]
197pub enum NetworkError {
198 #[error("Connection failed to {addr}: {reason}")]
199 ConnectionFailed {
200 addr: SocketAddr,
201 reason: Cow<'static, str>,
202 },
203
204 #[error("Connection closed unexpectedly for peer: {peer_id}")]
205 ConnectionClosed { peer_id: Cow<'static, str> },
206
207 #[error("Invalid network address: {0}")]
208 InvalidAddress(Cow<'static, str>),
209
210 #[error("Peer not found: {0}")]
211 PeerNotFound(Cow<'static, str>),
212
213 #[error("Peer disconnected - peer: {peer}, reason: {reason}")]
214 PeerDisconnected { peer: String, reason: String },
215
216 #[error("Network timeout")]
217 Timeout,
218
219 #[error("Too many connections")]
220 TooManyConnections,
221
222 #[error("Protocol error: {0}")]
223 ProtocolError(Cow<'static, str>),
224
225 #[error("Bind error: {0}")]
226 BindError(Cow<'static, str>),
227}
228
229#[derive(Debug, Error)]
231pub enum DhtError {
232 #[error("Key not found: {0}")]
233 KeyNotFound(Cow<'static, str>),
234
235 #[error("Store operation failed: {0}")]
236 StoreFailed(Cow<'static, str>),
237
238 #[error("Invalid key format: {0}")]
239 InvalidKey(Cow<'static, str>),
240
241 #[error("Routing table full")]
242 RoutingTableFull,
243
244 #[error("No suitable peers found")]
245 NoPeersFound,
246
247 #[error("Replication failed: {0}")]
248 ReplicationFailed(Cow<'static, str>),
249
250 #[error("Query timeout")]
251 QueryTimeout,
252
253 #[error("Routing error: {0}")]
254 RoutingError(Cow<'static, str>),
255
256 #[error("Storage failed: {0}")]
257 StorageFailed(Cow<'static, str>),
258
259 #[error("Insufficient replicas: {0}")]
260 InsufficientReplicas(Cow<'static, str>),
261}
262
263#[derive(Debug, Error)]
265pub enum IdentityError {
266 #[error("Invalid three-word address: {0}")]
267 InvalidThreeWordAddress(Cow<'static, str>),
268
269 #[error("Invalid four-word address: {0}")]
270 InvalidFourWordAddress(Cow<'static, str>),
271
272 #[error("Identity not found: {0}")]
273 IdentityNotFound(Cow<'static, str>),
274
275 #[error("Identity already exists: {0}")]
276 IdentityExists(Cow<'static, str>),
277
278 #[error("Invalid signature")]
279 InvalidSignature,
280
281 #[error("Invalid canonical bytes")]
282 InvalidCanonicalBytes,
283
284 #[error("Membership conflict")]
285 MembershipConflict,
286
287 #[error("Missing group key")]
288 MissingGroupKey,
289
290 #[error("Website root update refused")]
291 WebsiteRootUpdateRefused,
292
293 #[error("Key derivation failed: {0}")]
294 KeyDerivationFailed(Cow<'static, str>),
295
296 #[error("Permission denied")]
297 PermissionDenied,
298
299 #[error("Invalid peer ID: {0}")]
300 InvalidPeerId(Cow<'static, str>),
301
302 #[error("Invalid format: {0}")]
303 InvalidFormat(Cow<'static, str>),
304
305 #[error("System time error: {0}")]
306 SystemTime(Cow<'static, str>),
307
308 #[error("Not found: {0}")]
309 NotFound(Cow<'static, str>),
310
311 #[error("Verification failed: {0}")]
312 VerificationFailed(Cow<'static, str>),
313
314 #[error("Insufficient entropy")]
315 InsufficientEntropy,
316
317 #[error("Access denied: {0}")]
318 AccessDenied(Cow<'static, str>),
319}
320
321#[derive(Debug, Error)]
323pub enum CryptoError {
324 #[error("Encryption failed: {0}")]
325 EncryptionFailed(Cow<'static, str>),
326
327 #[error("Decryption failed: {0}")]
328 DecryptionFailed(Cow<'static, str>),
329
330 #[error("Invalid key length: expected {expected}, got {actual}")]
331 InvalidKeyLength { expected: usize, actual: usize },
332
333 #[error("Signature verification failed")]
334 SignatureVerificationFailed,
335
336 #[error("Key generation failed: {0}")]
337 KeyGenerationFailed(Cow<'static, str>),
338
339 #[error("Invalid public key")]
340 InvalidPublicKey,
341
342 #[error("Invalid private key")]
343 InvalidPrivateKey,
344
345 #[error("HKDF expansion failed: {0}")]
346 HkdfError(Cow<'static, str>),
347}
348
349#[derive(Debug, Error)]
351pub enum StorageError {
352 #[error("Database error: {0}")]
353 Database(Cow<'static, str>),
354
355 #[error("Disk full")]
356 DiskFull,
357
358 #[error("Corrupt data: {0}")]
359 CorruptData(Cow<'static, str>),
360
361 #[error("Storage path not found: {0}")]
362 PathNotFound(Cow<'static, str>),
363
364 #[error("Permission denied: {0}")]
365 PermissionDenied(Cow<'static, str>),
366
367 #[error("Lock acquisition failed")]
368 LockFailed,
369
370 #[error("Lock poisoned: {0}")]
371 LockPoisoned(Cow<'static, str>),
372
373 #[error("File not found: {0}")]
374 FileNotFound(Cow<'static, str>),
375
376 #[error("Corruption detected: {0}")]
377 CorruptionDetected(Cow<'static, str>),
378}
379
380#[derive(Debug, Error)]
382pub enum TransportError {
383 #[error("QUIC error: {0}")]
384 Quic(Cow<'static, str>),
385
386 #[error("TCP error: {0}")]
387 Tcp(Cow<'static, str>),
388
389 #[error("Invalid transport configuration: {0}")]
390 InvalidConfig(Cow<'static, str>),
391
392 #[error("Transport not supported: {0}")]
393 NotSupported(Cow<'static, str>),
394
395 #[error("Stream error: {0}")]
396 StreamError(Cow<'static, str>),
397
398 #[error("Certificate error: {0}")]
399 CertificateError(Cow<'static, str>),
400
401 #[error("Setup failed: {0}")]
402 SetupFailed(Cow<'static, str>),
403
404 #[error("Connection failed to {addr}: {reason}")]
405 ConnectionFailed {
406 addr: SocketAddr,
407 reason: Cow<'static, str>,
408 },
409
410 #[error("Bind error: {0}")]
411 BindError(Cow<'static, str>),
412
413 #[error("Accept failed: {0}")]
414 AcceptFailed(Cow<'static, str>),
415
416 #[error("Not listening")]
417 NotListening,
418
419 #[error("Not initialized")]
420 NotInitialized,
421}
422
423#[derive(Debug, Error)]
425pub enum ConfigError {
426 #[error("Missing required field: {0}")]
427 MissingField(Cow<'static, str>),
428
429 #[error("Invalid value for {field}: {reason}")]
430 InvalidValue {
431 field: Cow<'static, str>,
432 reason: Cow<'static, str>,
433 },
434
435 #[error("Configuration file not found: {0}")]
436 FileNotFound(Cow<'static, str>),
437
438 #[error("Parse error: {0}")]
439 ParseError(Cow<'static, str>),
440
441 #[error("Validation failed: {0}")]
442 ValidationFailed(Cow<'static, str>),
443
444 #[error("IO error for {path}: {source}")]
445 IoError {
446 path: Cow<'static, str>,
447 #[source]
448 source: std::io::Error,
449 },
450}
451
452#[derive(Debug, Error)]
454pub enum SecurityError {
455 #[error("Authentication failed")]
456 AuthenticationFailed,
457
458 #[error("Authorization denied")]
459 AuthorizationDenied,
460
461 #[error("Invalid credentials")]
462 InvalidCredentials,
463
464 #[error("Certificate error: {0}")]
465 CertificateError(Cow<'static, str>),
466
467 #[error("Encryption failed: {0}")]
468 EncryptionFailed(Cow<'static, str>),
469
470 #[error("Decryption failed: {0}")]
471 DecryptionFailed(Cow<'static, str>),
472
473 #[error("Invalid key: {0}")]
474 InvalidKey(Cow<'static, str>),
475
476 #[error("Signature verification failed: {0}")]
477 SignatureVerificationFailed(Cow<'static, str>),
478
479 #[error("Key generation failed: {0}")]
480 KeyGenerationFailed(Cow<'static, str>),
481
482 #[error("Authorization failed: {0}")]
483 AuthorizationFailed(Cow<'static, str>),
484}
485
486#[derive(Debug, Error)]
488pub enum BootstrapError {
489 #[error("No bootstrap nodes available")]
490 NoBootstrapNodes,
491
492 #[error("Bootstrap failed: {0}")]
493 BootstrapFailed(Cow<'static, str>),
494
495 #[error("Invalid bootstrap node: {0}")]
496 InvalidBootstrapNode(Cow<'static, str>),
497
498 #[error("Bootstrap timeout")]
499 BootstrapTimeout,
500
501 #[error("Cache error: {0}")]
502 CacheError(Cow<'static, str>),
503
504 #[error("Invalid data: {0}")]
505 InvalidData(Cow<'static, str>),
506
507 #[error("Rate limited: {0}")]
508 RateLimited(Cow<'static, str>),
509}
510
511pub type P2pResult<T> = Result<T, P2PError>;
513
514pub trait Recoverable {
518 fn is_transient(&self) -> bool;
520
521 fn suggested_retry_after(&self) -> Option<Duration>;
523
524 fn max_retries(&self) -> usize;
526}
527
528impl Recoverable for P2PError {
529 fn is_transient(&self) -> bool {
530 match self {
531 P2PError::Network(NetworkError::ConnectionFailed { .. }) => true,
532 P2PError::Network(NetworkError::Timeout) => true,
533 P2PError::Transport(TransportError::ConnectionFailed { .. }) => true,
534 P2PError::Dht(DhtError::QueryTimeout) => true,
535 P2PError::Timeout(_) => true,
536 P2PError::ResourceExhausted(_) => true,
537 P2PError::Io(err) => matches!(
538 err.kind(),
539 io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::Interrupted
540 ),
541 _ => false,
542 }
543 }
544
545 fn suggested_retry_after(&self) -> Option<Duration> {
546 match self {
547 P2PError::Network(NetworkError::Timeout) => Some(Duration::from_secs(5)),
548 P2PError::Timeout(duration) => Some(*duration * 2),
549 P2PError::ResourceExhausted(_) => Some(Duration::from_secs(30)),
550 P2PError::Transport(TransportError::ConnectionFailed { .. }) => {
551 Some(Duration::from_secs(1))
552 }
553 _ => None,
554 }
555 }
556
557 fn max_retries(&self) -> usize {
558 match self {
559 P2PError::Network(NetworkError::ConnectionFailed { .. }) => 3,
560 P2PError::Transport(TransportError::ConnectionFailed { .. }) => 3,
561 P2PError::Timeout(_) => 2,
562 P2PError::ResourceExhausted(_) => 1,
563 _ => 0,
564 }
565 }
566}
567
568pub trait ErrorContext<T> {
570 fn context(self, msg: &str) -> Result<T, P2PError>;
572
573 fn with_context<F>(self, f: F) -> Result<T, P2PError>
575 where
576 F: FnOnce() -> String;
577}
578
579impl<T, E> ErrorContext<T> for Result<T, E>
580where
581 E: Into<P2PError>,
582{
583 fn context(self, msg: &str) -> Result<T, P2PError> {
584 self.map_err(|e| {
585 let base_error = e.into();
586 P2PError::Internal(format!("{}: {}", msg, base_error).into())
587 })
588 }
589
590 fn with_context<F>(self, f: F) -> Result<T, P2PError>
591 where
592 F: FnOnce() -> String,
593 {
594 self.map_err(|e| {
595 let base_error = e.into();
596 P2PError::Internal(format!("{}: {}", f(), base_error).into())
597 })
598 }
599}
600
601impl P2PError {
603 pub fn connection_failed(addr: SocketAddr, reason: impl Into<String>) -> Self {
605 P2PError::Network(NetworkError::ConnectionFailed {
606 addr,
607 reason: reason.into().into(),
608 })
609 }
610
611 pub fn timeout(duration: Duration) -> Self {
613 P2PError::Timeout(duration)
614 }
615
616 pub fn validation(msg: impl Into<Cow<'static, str>>) -> Self {
618 P2PError::Validation(msg.into())
619 }
620
621 pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
623 P2PError::Internal(msg.into())
624 }
625}
626
627impl P2PError {
629 pub fn log(&self) {
631 use tracing::{error, warn};
632
633 match self {
634 P2PError::Network(NetworkError::Timeout) | P2PError::Timeout(_) => warn!("{}", self),
635
636 P2PError::Validation(_) | P2PError::Config(_) => warn!("{}", self),
637
638 _ => error!("{}", self),
639 }
640 }
641
642 pub fn log_with_context(&self, context: &str) {
644 use tracing::error;
645 error!("{}: {}", context, self);
646 }
647}
648
649impl From<serde_json::Error> for P2PError {
652 fn from(err: serde_json::Error) -> Self {
653 P2PError::Serialization(err.to_string().into())
654 }
655}
656
657impl From<bincode::Error> for P2PError {
658 fn from(err: bincode::Error) -> Self {
659 P2PError::Serialization(err.to_string().into())
660 }
661}
662
663impl From<std::net::AddrParseError> for P2PError {
664 fn from(err: std::net::AddrParseError) -> Self {
665 P2PError::Network(NetworkError::InvalidAddress(err.to_string().into()))
666 }
667}
668
669impl From<tokio::time::error::Elapsed> for P2PError {
670 fn from(_: tokio::time::error::Elapsed) -> Self {
671 P2PError::Network(NetworkError::Timeout)
672 }
673}
674
675impl From<crate::adaptive::AdaptiveNetworkError> for P2PError {
676 fn from(err: crate::adaptive::AdaptiveNetworkError) -> Self {
677 use crate::adaptive::AdaptiveNetworkError;
678 match err {
679 AdaptiveNetworkError::Network(io_err) => P2PError::Io(io_err),
680 AdaptiveNetworkError::Io(io_err) => P2PError::Io(io_err),
681 AdaptiveNetworkError::Serialization(ser_err) => {
682 P2PError::Serialization(ser_err.to_string().into())
683 }
684 AdaptiveNetworkError::Routing(msg) => {
685 P2PError::Internal(format!("Routing error: {}", msg).into())
686 }
687 AdaptiveNetworkError::Trust(msg) => {
688 P2PError::Internal(format!("Trust error: {}", msg).into())
689 }
690 AdaptiveNetworkError::Learning(msg) => {
691 P2PError::Internal(format!("Learning error: {}", msg).into())
692 }
693 AdaptiveNetworkError::Gossip(msg) => {
694 P2PError::Internal(format!("Gossip error: {}", msg).into())
695 }
696 AdaptiveNetworkError::Other(msg) => P2PError::Internal(msg.into()),
697 }
698 }
699}
700
701#[derive(Debug, Clone, Serialize, Deserialize)]
705pub enum ErrorValue {
706 String(Cow<'static, str>),
707 Number(i64),
708 Bool(bool),
709 Duration(Duration),
710 Address(SocketAddr),
711}
712
713#[derive(Debug, Serialize, Deserialize)]
715pub struct ErrorLog {
716 pub timestamp: i64, pub error_type: &'static str,
718 pub message: Cow<'static, str>,
719 pub context: SmallVec<[(&'static str, ErrorValue); 4]>, pub stack_trace: Option<Cow<'static, str>>,
721}
722
723impl ErrorLog {
724 pub fn from_error(error: &P2PError) -> Self {
726 let mut context = SmallVec::new();
727
728 match error {
730 P2PError::Network(NetworkError::ConnectionFailed { addr, reason }) => {
731 context.push(("address", ErrorValue::Address(*addr)));
732 context.push(("reason", ErrorValue::String(reason.clone())));
733 }
734 P2PError::Timeout(duration) => {
735 context.push(("timeout", ErrorValue::Duration(*duration)));
736 }
737 P2PError::Crypto(CryptoError::InvalidKeyLength { expected, actual }) => {
738 context.push(("expected_length", ErrorValue::Number(*expected as i64)));
739 context.push(("actual_length", ErrorValue::Number(*actual as i64)));
740 }
741 _ => {}
742 }
743
744 ErrorLog {
745 timestamp: chrono::Utc::now().timestamp(),
746 error_type: error_type_name(error),
747 message: error.to_string().into(),
748 context,
749 stack_trace: None,
750 }
751 }
752
753 pub fn with_context(mut self, key: &'static str, value: ErrorValue) -> Self {
754 self.context.push((key, value));
755 self
756 }
757
758 pub fn log(&self) {
759 use log::{error, warn};
760
761 let json = serde_json::to_string(self).unwrap_or_else(|_| self.message.to_string());
762
763 match self.error_type {
764 "Validation" | "Config" => warn!("{}", json),
765 _ => error!("{}", json),
766 }
767 }
768}
769
770fn error_type_name(error: &P2PError) -> &'static str {
771 match error {
772 P2PError::Network(_) => "Network",
773 P2PError::Dht(_) => "DHT",
774 P2PError::Identity(_) => "Identity",
775 P2PError::Crypto(_) => "Crypto",
776 P2PError::Storage(_) => "Storage",
777 P2PError::Transport(_) => "Transport",
778 P2PError::Config(_) => "Config",
779 P2PError::Io(_) => "IO",
780 P2PError::Serialization(_) => "Serialization",
781 P2PError::Validation(_) => "Validation",
782 P2PError::Timeout(_) => "Timeout",
783 P2PError::ResourceExhausted(_) => "ResourceExhausted",
784 P2PError::Internal(_) => "Internal",
785 P2PError::Security(_) => "Security",
786 P2PError::Bootstrap(_) => "Bootstrap",
787 P2PError::Encoding(_) => "Encoding",
788 P2PError::RecordTooLarge(_) => "RecordTooLarge",
789 P2PError::TimeError => "TimeError",
790 P2PError::InvalidInput(_) => "InvalidInput",
791 P2PError::WebRtcError(_) => "WebRTC",
792 }
793}
794
795pub trait ErrorReporting {
797 fn report(&self) -> ErrorLog;
798 fn report_with_context(&self, context: HashMap<String, serde_json::Value>) -> ErrorLog;
799}
800
801impl ErrorReporting for P2PError {
802 fn report(&self) -> ErrorLog {
803 ErrorLog::from_error(self)
804 }
805
806 fn report_with_context(&self, context: HashMap<String, serde_json::Value>) -> ErrorLog {
807 let log = ErrorLog::from_error(self);
808 for (_key, _value) in context {
810 }
814 log
815 }
816}
817
818pub trait IntoAnyhow<T> {
822 fn into_anyhow(self) -> anyhow::Result<T>;
823}
824
825impl<T> IntoAnyhow<T> for P2pResult<T> {
826 fn into_anyhow(self) -> anyhow::Result<T> {
827 self.map_err(|e| anyhow::anyhow!(e))
828 }
829}
830
831pub trait FromAnyhowExt<T> {
832 fn into_p2p_result(self) -> P2pResult<T>;
833}
834
835impl<T> FromAnyhowExt<T> for anyhow::Result<T> {
836 fn into_p2p_result(self) -> P2pResult<T> {
837 self.map_err(|e| P2PError::Internal(e.to_string().into()))
838 }
839}
840
841pub use anyhow::{Context as AnyhowContext, Result as AnyhowResult};
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847
848 #[test]
849 fn test_error_display() {
850 let err =
851 P2PError::connection_failed("127.0.0.1:8080".parse().unwrap(), "Connection refused");
852 assert_eq!(
853 err.to_string(),
854 "Network error: Connection failed to 127.0.0.1:8080: Connection refused"
855 );
856 }
857
858 #[test]
859 fn test_error_context() {
860 let result: Result<(), io::Error> =
861 Err(io::Error::new(io::ErrorKind::NotFound, "file not found"));
862
863 let with_context = crate::error::ErrorContext::context(result, "Failed to load config");
864 assert!(with_context.is_err());
865 assert!(
866 with_context
867 .unwrap_err()
868 .to_string()
869 .contains("Failed to load config")
870 );
871 }
872
873 #[test]
874 fn test_timeout_error() {
875 let err = P2PError::timeout(Duration::from_secs(30));
876 assert_eq!(err.to_string(), "Operation timed out after 30s");
877 }
878
879 #[test]
880 fn test_crypto_error() {
881 let err = P2PError::Crypto(CryptoError::InvalidKeyLength {
882 expected: 32,
883 actual: 16,
884 });
885 assert_eq!(
886 err.to_string(),
887 "Cryptography error: Invalid key length: expected 32, got 16"
888 );
889 }
890
891 #[test]
892 fn test_error_log_serialization() {
893 let error = P2PError::Network(NetworkError::ConnectionFailed {
894 addr: "127.0.0.1:8080".parse().unwrap(),
895 reason: "Connection refused".into(),
896 });
897
898 let log = error
899 .report()
900 .with_context("peer_id", ErrorValue::String("peer123".into()))
901 .with_context("retry_count", ErrorValue::Number(3));
902
903 let json = serde_json::to_string_pretty(&log).unwrap();
904 assert!(json.contains("Network"));
905 assert!(json.contains("127.0.0.1:8080"));
906 assert!(json.contains("peer123"));
907 }
908
909 #[test]
910 fn test_anyhow_conversion() {
911 let p2p_result: P2pResult<()> = Err(P2PError::validation("Invalid input"));
912 let anyhow_result = p2p_result.into_anyhow();
913 assert!(anyhow_result.is_err());
914
915 let anyhow_err = anyhow::anyhow!("Test error");
916 let anyhow_result: anyhow::Result<()> = Err(anyhow_err);
917 let p2p_result = crate::error::FromAnyhowExt::into_p2p_result(anyhow_result);
918 assert!(p2p_result.is_err());
919 match p2p_result.unwrap_err() {
920 P2PError::Internal(msg) => assert!(msg.contains("Test error")),
921 _ => panic!("Expected Internal error"),
922 }
923 }
924}