Skip to main content

tightbeam/
lib.rs

1//! ```text
2//!     ╔════════════════════════════════════════════════════════════════╗
3//!     ║                        T I G H T B E A M                       ║
4//!     ║             Efficient Exchange-Compute Interconnect            ║
5//!     ╚════════════════════════════════════════════════════════════════╝
6//!
7//!                              ┌─────────────┐
8//!                              │   CLUSTER   │
9//!                              │  Controller │
10//!                              └──────┬──────┘
11//!                                     │
12//!                     ┌───────────────┼───────────────┐
13//!                     │               │               │
14//!               ┌─────▼─────┐    ┌────▼────┐    ┌─────▼─────┐
15//!               │   HIVE    │    │  DRONE  │    │   HIVE    │
16//!               │ Orchestr. │    │ Morpher │    │ Orchestr. │
17//!               └─────┬─────┘    └────┬────┘    └────┬──────┘
18//!                     │               │              │
19//!          ┌──────────┼──────────┐    │    ┌─────────┼──────────┐
20//!          │          │          │    │    │         │          │
21//!     ┌────▼───┐  ┌───▼────┐ ┌───▼────▼────▼───┐ ┌───▼────┐ ┌───▼────┐
22//!     │Servlet │  │Servlet │ │     Active      │ │Servlet │ │Servlet │
23//!     │  :8001 │  │  :8002 │ │     Servlet     │ │  :8003 │ │  :8004 │
24//!     └────┬───┘  └────┬───┘ └────────┬────────┘ └───┬────┘ └───┬────┘
25//!          │           │              │              │          │
26//!    ┌─────┴─────┬─────┴─────┬─────┬──┴──┬─────┬─────┴─────┬────┴┬─────┐
27//!    │     │     │     │     │     │     │     │     │     │     │     │
28//!  ┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐┌─▼──┐
29//!  │Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr││Wrkr│
30//!  └────┘└────┘└────┘└────┘└────┘└────┘└────┘└────┘└────┘└────┘└────┘└────┘
31//! ┌──┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌─┐┌──┐
32//! │Wr││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││W││Wr│
33//! └──┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└─┘└──┘
34//!
35//! ╔════════════════════════════════════════════════════════════════════════╗
36//! ║   Protocol-Agnostic • Zero-Copy • Zero-Panic • ASN.1 DER • RustCrypto  ║
37//! ╚════════════════════════════════════════════════════════════════════════╝
38//!
39//!         ┌──────────────────────────────────────────────────────┐
40//!         │  🔐 Security Model: Sign-Then-Encrypt                │
41//!         │  ├─ Hash:    Integrity verification on plaintext     │
42//!         │  ├─ Sign:    Non-repudiation & authentication        │
43//!         │  └─ Encrypt: Confidentiality of transmitted data     │
44//!         └──────────────────────────────────────────────────────┘
45//!
46//!         ┌──────────────────────────────────────────────────────┐
47//!         │  📦 Protocol Versions                                │
48//!         │  ├─ V0: Core metadata (id, order, message)           │
49//!         │  ├─ V1: + integrity, confidentiality, signature      │
50//!         │  ├─ V2: + priority, TTL, previous_frame chaining     │
51//!         │  └─ V3: + matrix control                             │
52//!         └──────────────────────────────────────────────────────┘
53//!
54//!         ┌──────────────────────────────────────────────────────┐
55//!         │  🕸️  Efficient Exchange-Compute Interconnect (EECI)  |
56//!         │  ├─ Hives:    Multi-servlet orchestrators            │
57//!         │  ├─ Drones:   Single-servlet morphers                │
58//!         │  ├─ Servlets: Self-contained message processors      │
59//!         │  └─ Cluster:  Centralized control & routing          │
60//!         └──────────────────────────────────────────────────────┘
61//!
62//!         ┌──────────────────────────────────────────────────────┐
63//!         │  ⚡ Features                                          │
64//!         │  ├─ Protocol-agnostic transport layer                │
65//!         │  ├─ Dynamic port allocation (OS-managed)             │
66//!         │  ├─ Policy-driven message gates                      │
67//!         │  ├─ Lifecycle management (start/stop/join)           │
68//!         │  └─ Service discovery & health monitoring            │
69//!         └──────────────────────────────────────────────────────┘
70//!
71//!    ┌────────────────────────────────────────────────────────────────┐
72//!    │  Quick Start Example                                           │
73//!    ├────────────────────────────────────────────────────────────────┤
74//!    │  use tightbeam::{Message, Beamable, compose};                  │
75//!    │  use tightbeam::der::Sequence;                                 │
76//!    │                                                                │
77//!    │  #[derive(Beamable, Clone, Debug, Sequence)]                   │
78//!    │  struct MyMessage { value: u64 }                               │
79//!    │                                                                │
80//!    │  let frame = compose! {                                        │
81//!    │      V0: id: "msg-001", order: 1, message: MyMessage { .. }    │
82//!    │  }?;                                                           │
83//!    │                                                                │
84//!    │  let decode: MyMessage = tightbeam::decode(&frame.message)?;   │
85//!    └────────────────────────────────────────────────────────────────┘
86//! ```
87//!
88//! # TightBeam Protocol
89//!
90//! A lightweight, versioned messaging protocol with cryptographic primitives
91//! built on ASN.1 DER encoding.
92
93#![deny(unsafe_code)]
94#![cfg_attr(test, allow(clippy::clone_on_ref_ptr))]
95#![cfg_attr(not(feature = "std"), no_std)]
96
97#[cfg(not(feature = "std"))]
98#[macro_use]
99extern crate alloc;
100#[cfg(all(not(feature = "std"), feature = "zeroize"))]
101use alloc::vec::Vec;
102
103// Before other modules so `compose!` is in crate-wide textual scope.
104#[cfg(feature = "builder")]
105#[macro_use]
106mod compose;
107
108pub(crate) mod frame;
109/// The Version is a fundamental constraint
110pub(crate) mod version;
111
112pub mod asn1;
113pub mod constants;
114pub mod core;
115pub mod error;
116pub mod flags;
117pub mod helpers;
118pub mod matrix;
119pub mod oids;
120pub mod prelude;
121#[cfg(feature = "std")]
122pub mod runtime;
123#[cfg(any(test, feature = "testing"))]
124pub mod trace;
125pub mod utils;
126
127#[cfg(feature = "instrument")]
128pub mod instrumentation;
129
130#[cfg(feature = "builder")]
131pub mod builder;
132#[cfg(feature = "colony")]
133pub mod colony;
134#[cfg(feature = "compress")]
135pub mod compress;
136#[cfg(feature = "crypto")]
137pub mod crypto;
138#[cfg(feature = "doc")]
139pub mod doc;
140pub mod macros;
141#[cfg(feature = "policy")]
142pub mod policy;
143#[cfg(feature = "random")]
144pub mod random;
145#[cfg(feature = "router")]
146pub mod router;
147#[cfg(feature = "standards")]
148pub mod standards;
149#[cfg(feature = "transport")]
150pub mod transport;
151#[cfg(feature = "rayon")]
152pub use rayon;
153#[cfg(feature = "zeroize")]
154pub use zeroize;
155
156// Re-export
157pub use asn1::*;
158pub use cms;
159pub use der;
160pub use paste;
161pub use pkcs12;
162pub use spki;
163
164#[cfg(feature = "hex")]
165pub use hex_literal::hex;
166#[cfg(all(feature = "std", not(feature = "tokio")))]
167pub use std::sync::mpsc;
168#[cfg(feature = "time")]
169pub use time;
170#[cfg(feature = "tokio")]
171pub use tokio::sync::mpsc;
172#[cfg(feature = "x509")]
173pub use x509_cert as x509;
174
175pub use utils::{decode, encode};
176
177#[cfg(feature = "derive")]
178pub use tightbeam_derive::{Beamable, Errorizable, Flaggable};
179
180extern crate self as tightbeam;
181
182pub use crate::core::*;
183pub use crate::error::TightBeamError;
184
185#[cfg(any(test, feature = "testing"))]
186pub mod testing;
187
188/// Secure bytes type
189#[cfg(feature = "zeroize")]
190pub type ZeroizingBytes = zeroize::Zeroizing<Vec<u8>>;
191#[cfg(feature = "zeroize")]
192pub type ZeroizingArray<const N: usize> = zeroize::Zeroizing<[u8; N]>;
193
194#[cfg(test)]
195mod tests {
196	use super::*;
197
198	#[test]
199	fn frame_size_calc() -> Result<(), Box<dyn std::error::Error>> {
200		use crate::asn1::*;
201		use crate::cms::cert::IssuerAndSerialNumber;
202		use crate::cms::compressed_data::CompressedData;
203		use crate::cms::content_info::CmsVersion;
204		use crate::cms::enveloped_data::EncryptedContentInfo;
205		use crate::cms::signed_data::{EncapsulatedContentInfo, SignerIdentifier, SignerInfo};
206		use crate::der::{Decode, Encode};
207		use crate::oids::*;
208		use crate::pkcs12::digest_info::DigestInfo;
209		use crate::spki::AlgorithmIdentifier;
210		use crate::x509::name::Name;
211		use crate::x509::serial_number::SerialNumber;
212
213		// Create a square matrix with all zeros (data length must equal n*n)
214		let matrix_size: u8 = 16;
215		let matrix = Asn1Matrix { n: matrix_size, data: vec![0; (matrix_size as usize) * (matrix_size as usize)] };
216
217		// Create metadata with all optional fields
218		let metadata = Metadata {
219			id: vec![0; 16], // 16-byte ID
220			order: 0,
221			compactness: Some(CompressedData {
222				version: CmsVersion::V0,
223				compression_alg: AlgorithmIdentifier { oid: COMPRESSION_ZLIB, parameters: None },
224				encap_content_info: EncapsulatedContentInfo {
225					econtent_type: DATA,
226					econtent: Some(der::Any::from_der(&der::asn1::OctetString::new(vec![0; 10])?.to_der()?)?),
227				},
228			}),
229			integrity: Some(DigestInfo {
230				algorithm: AlgorithmIdentifier { oid: HASH_SHA3_256, parameters: None },
231				digest: der::asn1::OctetString::new(vec![0; 32])?,
232			}),
233			confidentiality: Some(EncryptedContentInfo {
234				content_type: DATA,
235				content_enc_alg: AlgorithmIdentifier { oid: COMPRESSION_ZLIB, parameters: None },
236				encrypted_content: Some(der::asn1::OctetString::new(vec![0; 50])?),
237			}),
238			priority: Some(MessagePriority::Standard),
239			lifetime: Some(3600),
240			previous_frame: Some(DigestInfo {
241				algorithm: AlgorithmIdentifier { oid: HASH_SHA3_256, parameters: None },
242				digest: der::asn1::OctetString::new(vec![0; 32])?,
243			}),
244			matrix: Some(matrix),
245		};
246
247		// Create frame with empty message
248		// Compile-time validation built into Frame: V3 must support matrix since metadata has matrix
249		// This will fail to compile if V3 doesn't support matrix
250		const _: () = {
251			const VERSION: Version = Version::V3;
252			const HAS_MATRIX: bool = true; // metadata has matrix
253								  // Use Frame's built-in compile-time validation method
254			[(); 1][!Frame::const_validate_version_fields(VERSION, HAS_MATRIX) as usize];
255		};
256
257		let frame = Frame {
258			version: Version::V3,
259			metadata,
260			message: vec![], // empty message
261			integrity: Some(DigestInfo {
262				algorithm: AlgorithmIdentifier { oid: HASH_SHA3_256, parameters: None },
263				digest: der::asn1::OctetString::new(vec![0; 32])?,
264			}),
265			nonrepudiation: Some(SignerInfo {
266				version: CmsVersion::V1,
267				sid: SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
268					issuer: Name::default(),
269					serial_number: SerialNumber::new(&[0; 8])?,
270				}),
271				digest_alg: AlgorithmIdentifier { oid: HASH_SHA3_256, parameters: None },
272				signed_attrs: None,
273				signature_algorithm: AlgorithmIdentifier { oid: SIGNER_ECDSA_WITH_SHA3_256, parameters: None },
274				signature: der::asn1::OctetString::new(vec![0; 64])?,
275				unsigned_attrs: None,
276			}),
277		};
278
279		// Encode to DER
280		let der_bytes = der::Encode::to_der(&frame)?;
281		println!("DER-encoded frame size: {} bytes", der_bytes.len());
282		assert!(!der_bytes.is_empty());
283		Ok(())
284	}
285}