chie_core/
lib.rs

1//! Core protocol logic for CHIE Protocol.
2//!
3//! This crate provides the main node implementation and content management for the
4//! CHIE (Collective Hybrid Intelligence Ecosystem) protocol - a decentralized content
5//! distribution system with incentive mechanisms.
6//!
7//! # Overview
8//!
9//! The chie-core crate contains the fundamental building blocks for running a CHIE node:
10//!
11//! - **Node Management** ([`node`]): Core node implementation for handling content and proofs
12//! - **Storage** ([`storage`]): Chunk-based storage system with encryption support
13//! - **Protocol** ([`protocol`]): Bandwidth proof protocol and validation
14//! - **Content Management** ([`content`]): Content metadata caching and management
15//! - **Cryptography** ([`chunk_encryption`]): Per-chunk encryption utilities
16//! - **Analytics** ([`analytics`]): Performance metrics and statistics tracking
17//! - **Utilities** ([`utils`]): Helper functions for common operations
18//!
19//! # Quick Start
20//!
21//! ```no_run
22//! use chie_core::{ContentNode, NodeConfig, PinnedContent};
23//! use std::path::PathBuf;
24//!
25//! #[tokio::main]
26//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
27//!     // Create a node with storage
28//!     let config = NodeConfig {
29//!         storage_path: PathBuf::from("./chie-data"),
30//!         max_storage_bytes: 50 * 1024 * 1024 * 1024, // 50 GB
31//!         max_bandwidth_bps: 100 * 1024 * 1024 / 8,   // 100 Mbps
32//!         coordinator_url: "https://coordinator.chie.network".to_string(),
33//!     };
34//!
35//!     let mut node = ContentNode::with_storage(config).await?;
36//!
37//!     // Pin content for distribution
38//!     let content = PinnedContent {
39//!         cid: "QmExample123".to_string(),
40//!         size_bytes: 1024 * 1024,
41//!         encryption_key: [0u8; 32],
42//!         predicted_revenue_per_gb: 10.0,
43//!     };
44//!     node.pin_content(content);
45//!
46//!     println!("Node public key: {:?}", node.public_key());
47//!     println!("Pinned content count: {}", node.pinned_count());
48//!
49//!     Ok(())
50//! }
51//! ```
52//!
53//! # Features
54//!
55//! ## Content Storage
56//!
57//! The storage system splits content into chunks, encrypts each chunk individually,
58//! and stores them with cryptographic verification:
59//!
60//! ```no_run
61//! use chie_core::{ChunkStorage, split_into_chunks};
62//! use chie_crypto::{generate_key, generate_nonce};
63//! use std::path::PathBuf;
64//!
65//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
66//! let storage_path = PathBuf::from("./storage");
67//! let max_bytes = 10 * 1024 * 1024 * 1024; // 10 GB
68//!
69//! let mut storage = ChunkStorage::new(storage_path, max_bytes).await?;
70//!
71//! // Split and store content
72//! let data = b"Hello, CHIE Protocol!";
73//! let chunks = split_into_chunks(data, 1024);
74//! let key = generate_key();
75//! let nonce = generate_nonce();
76//!
77//! storage.pin_content("QmTest", &chunks, &key, &nonce).await?;
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! ## Bandwidth Proof Protocol
83//!
84//! Nodes earn rewards by serving content and generating cryptographically-signed
85//! bandwidth proofs:
86//!
87//! ```no_run
88//! use chie_core::{create_chunk_request, create_bandwidth_proof};
89//! use chie_crypto::KeyPair;
90//!
91//! # fn example() {
92//! let requester_keypair = KeyPair::generate();
93//! let provider_keypair = KeyPair::generate();
94//!
95//! // Create a chunk request with challenge nonce
96//! let request = create_chunk_request(
97//!     "QmContent123".to_string(),
98//!     0, // chunk index
99//!     "requester-peer-id".to_string(),
100//!     requester_keypair.public_key(),
101//! );
102//!
103//! // Provider serves chunk and signs response
104//! // Requester verifies and co-signs
105//! // Both submit dual-signed proof to coordinator
106//! # }
107//! ```
108//!
109//! ## Performance Optimization
110//!
111//! The crate includes several performance optimization features:
112//!
113//! - **Chunk Prefetching** ([`prefetch`]): Predict and preload chunks based on access patterns
114//! - **Tiered Storage** ([`tiered_storage`]): Hot/warm/cold storage tiers for cost optimization
115//! - **Rate Limiting** ([`ratelimit`]): Per-peer bandwidth throttling
116//! - **Content Deduplication** ([`dedup`]): Avoid storing duplicate chunks
117//! - **Garbage Collection** ([`gc`]): Remove unprofitable content automatically
118//!
119//! # Module Overview
120//!
121//! - [`adaptive_ratelimit`] - Adaptive rate limiting with dynamic adjustments
122//! - [`analytics`] - Performance metrics and earnings tracking
123//! - [`anomaly`] - Anomaly detection for fraud prevention
124//! - [`auto_repair`] - Automatic data integrity repair for corrupted chunks
125//! - [`backup`] - Storage backup and recovery utilities
126//! - [`batch`] - Batch processing utilities
127//! - [`cache`] - Advanced caching with TTL and memory management
128//! - [`cache_invalidation`] - Distributed cache invalidation notifications
129//! - [`chunk_encryption`] - Encrypted chunk data structures
130//! - [`circuit_breaker`] - Circuit breaker pattern for resilient service calls
131//! - [`compression`] - Content compression utilities
132//! - [`connection_multiplexing`] - HTTP connection pooling and multiplexing for coordinator communication
133//! - [`content`] - Content metadata management
134//! - [`content_aware_cache`] - Content-aware cache sizing with intelligent management
135//! - [`content_router`] - Content routing optimizer
136//! - [`custom_exporters`] - Custom metrics exporters (StatsD, InfluxDB)
137//! - [`dedup`] - Content deduplication
138//! - [`gc`] - Garbage collection for storage
139//! - [`health`] - Health check system for node monitoring
140//! - [`http_pool`] - HTTP connection pooling utilities
141//! - [`integrity`] - Content integrity verification
142//! - [`lifecycle`] - Content lifecycle events and webhooks
143//! - [`metrics`] - Prometheus-compatible metrics exporter
144//! - [`network_diag`] - Network diagnostics and monitoring
145//! - [`node`] - Core node implementation
146//! - [`peer_selection`] - Intelligent peer selection and ranking
147//! - [`pinning`] - Selective pinning optimizer
148//! - [`popularity`] - Content popularity tracking
149//! - [`prefetch`] - Chunk prefetching
150//! - [`profiler`] - Performance profiling and timing utilities
151//! - [`proof_submit`] - Proof submission with retry logic
152//! - [`protocol`] - Bandwidth proof protocol
153//! - [`qos`] - Quality of Service with priority-based scheduling
154//! - [`quic_transport`] - QUIC transport integration for modern, efficient networking
155//! - [`ratelimit`] - Rate limiting
156//! - [`reputation`] - Peer reputation tracking
157//! - [`resource_mgmt`] - Advanced resource management and monitoring
158//! - [`storage`] - Chunk storage backend
159//! - [`storage_health`] - Storage health monitoring with predictive failure detection
160//! - [`streaming`] - Streaming utilities for large content
161//! - [`tiered_storage`] - Multi-tier storage system
162//! - [`tracing`] - OpenTelemetry tracing integration for distributed observability
163//! - [`utils`] - Utility functions
164//! - [`validation`] - Content and proof validation utilities
165
166pub mod adaptive_ratelimit;
167pub mod adaptive_retry;
168pub mod alerting;
169pub mod analytics;
170pub mod anomaly;
171pub mod auto_repair;
172pub mod backup;
173pub mod bandwidth_estimation;
174pub mod batch;
175pub mod cache;
176pub mod cache_admission;
177pub mod cache_invalidation;
178pub mod cache_warming;
179pub mod checkpoint;
180pub mod chunk_encryption;
181pub mod circuit_breaker;
182pub mod compression;
183pub mod config;
184pub mod connection_multiplexing;
185pub mod content;
186pub mod content_aware_cache;
187pub mod content_router;
188pub mod custom_exporters;
189pub mod dashboard;
190pub mod dedup;
191pub mod degradation;
192pub mod events;
193pub mod expiration;
194pub mod forecasting;
195pub mod gc;
196pub mod geo_selection;
197pub mod health;
198pub mod http_pool;
199pub mod integrity;
200pub mod lifecycle;
201pub mod logging;
202pub mod metrics;
203pub mod metrics_exporter;
204pub mod network_diag;
205pub mod node;
206pub mod orchestrator;
207pub mod partial_chunk;
208pub mod peer_selection;
209pub mod pinning;
210pub mod popularity;
211pub mod prefetch;
212pub mod priority_eviction;
213pub mod profiler;
214pub mod proof_submit;
215pub mod protocol;
216pub mod qos;
217pub mod quic_transport;
218pub mod ratelimit;
219pub mod reputation;
220pub mod request_pipeline;
221pub mod resource_mgmt;
222mod serde_helpers;
223pub mod storage;
224pub mod storage_health;
225pub mod streaming;
226pub mod streaming_verification;
227pub mod system_coordinator;
228pub mod test_utils;
229pub mod tier_migration;
230pub mod tiered_cache;
231pub mod tiered_storage;
232pub mod tracing;
233pub mod transaction;
234pub mod utils;
235pub mod validation;
236pub mod wal;
237
238pub use adaptive_ratelimit::*;
239pub use adaptive_retry::*;
240pub use alerting::*;
241pub use analytics::*;
242pub use anomaly::*;
243pub use auto_repair::*;
244pub use backup::*;
245// bandwidth_estimation module available via `chie_core::bandwidth_estimation::`
246// (not glob re-exported to avoid conflict with ratelimit::BandwidthStats)
247pub use batch::*;
248pub use cache::*;
249pub use cache_admission::*;
250pub use cache_invalidation::*;
251pub use cache_warming::*;
252pub use checkpoint::*;
253pub use chunk_encryption::*;
254pub use circuit_breaker::*;
255pub use compression::*;
256pub use config::*;
257pub use connection_multiplexing::*;
258pub use content::*;
259pub use content_aware_cache::*;
260pub use content_router::*;
261// custom_exporters module available via `chie_core::custom_exporters::`
262// (not glob re-exported to avoid conflict with metrics_exporter::MetricValue)
263pub use dashboard::*;
264pub use dedup::*;
265pub use degradation::*;
266pub use events::*;
267pub use expiration::*;
268pub use forecasting::*;
269pub use gc::*;
270pub use geo_selection::*;
271pub use health::*;
272pub use http_pool::*;
273pub use integrity::*;
274pub use lifecycle::*;
275pub use logging::*;
276pub use metrics::*;
277pub use metrics_exporter::*;
278pub use network_diag::*;
279pub use node::*;
280pub use orchestrator::*;
281pub use partial_chunk::*;
282pub use peer_selection::*;
283pub use pinning::*;
284pub use popularity::*;
285pub use prefetch::*;
286pub use priority_eviction::*;
287pub use profiler::*;
288pub use proof_submit::*;
289pub use protocol::*;
290pub use qos::*;
291// quic_transport module available via `chie_core::quic_transport::`
292// (not glob re-exported to avoid type conflicts with network modules)
293pub use ratelimit::*;
294pub use reputation::*;
295pub use request_pipeline::*;
296pub use resource_mgmt::*;
297pub use storage::*;
298pub use storage_health::*;
299pub use streaming::*;
300pub use streaming_verification::*;
301// system_coordinator module available via `chie_core::system_coordinator::`
302// (not glob re-exported to avoid conflict with dashboard::SystemStatus)
303pub use test_utils::*;
304// tiered_cache module available via `chie_core::tiered_cache::`
305// (not glob re-exported to avoid conflict with cache::TieredCache)
306pub use tier_migration::*;
307pub use tiered_storage::*;
308// tracing module available via `chie_core::tracing::`
309// (not glob re-exported to avoid conflicts)
310pub use transaction::*;
311pub use utils::*;
312pub use validation::*;
313pub use wal::*;