Skip to main content

aura_core/effects/
transport.rs

1//! Transport effects trait definitions
2//!
3//! This module defines the trait interface for transport layer operations that form the final
4//! step in the guard chain sequence. TransportEffects handles actual network packet emission
5//! after authorization, flow budget charging, leakage recording, and journal fact merging.
6//!
7//! # Effect Classification
8//!
9//! - **Category**: Infrastructure Effect
10//! - **Implementation**: `aura-effects` (Layer 3)
11//! - **Usage**: Guard chain final step (actual network transmission after all checks pass)
12//!
13//! This is an infrastructure effect that must be implemented in `aura-effects`
14//! with stateless handlers. Integrates with guard chain in aura-protocol.
15
16use crate::{AuraError, AuthorityId, ContextId};
17use async_trait::async_trait;
18use serde::{Deserialize, Serialize};
19
20pub const MAX_TRANSPORT_SIGNATURE_BYTES: usize = 512;
21pub const MAX_TRANSPORT_PAYLOAD_BYTES: usize = 65_536;
22
23/// Receipt produced by successful guard chain execution
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct TransportReceipt {
26    /// Context this receipt applies to
27    pub context: ContextId,
28    /// Source authority that generated the receipt
29    pub src: AuthorityId,
30    /// Destination authority for the message
31    pub dst: AuthorityId,
32    /// Epoch during which the receipt was generated
33    pub epoch: u64,
34    /// Flow budget cost charged for this operation
35    pub cost: u32,
36    /// Unique nonce to prevent replay
37    pub nonce: u64,
38    /// Hash chain linking to previous receipt
39    pub prev: [u8; 32],
40    /// Signature over receipt data
41    pub sig: Vec<u8>,
42}
43
44/// Envelope containing the actual message data and metadata for transport
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct TransportEnvelope {
47    /// Destination authority identifier
48    pub destination: AuthorityId,
49    /// Source authority identifier
50    pub source: AuthorityId,
51    /// Context identifier for this message
52    pub context: ContextId,
53    /// Encrypted message payload
54    pub payload: Vec<u8>,
55    /// Message metadata (content-type, version, etc.)
56    pub metadata: std::collections::HashMap<String, String>,
57    /// Receipt proving guard chain execution
58    pub receipt: Option<TransportReceipt>,
59}
60
61/// Transport operation errors
62#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
63pub enum TransportError {
64    /// Failed to send message to destination
65    #[error("Transport send failed to {destination}: {reason}")]
66    SendFailed {
67        destination: AuthorityId,
68        reason: String,
69    },
70    /// Failed to receive message
71    #[error("Transport receive failed: {reason}")]
72    ReceiveFailed { reason: String },
73    /// No message available for receive
74    #[error("No message available")]
75    NoMessage,
76    /// Invalid envelope format
77    #[error("Invalid envelope: {reason}")]
78    InvalidEnvelope { reason: String },
79    /// Receipt validation failed
80    #[error("Receipt validation failed: {reason}")]
81    ReceiptValidationFailed { reason: String },
82    /// Destination unreachable
83    #[error("Destination unreachable: {destination}")]
84    DestinationUnreachable { destination: AuthorityId },
85    /// Transport protocol error
86    #[error("Transport protocol error: {details}")]
87    ProtocolError { details: String },
88    /// Channel not established
89    #[error("Secure channel not established for context {context}")]
90    ChannelNotEstablished { context: ContextId },
91}
92
93impl From<TransportError> for AuraError {
94    fn from(err: TransportError) -> Self {
95        AuraError::network(err.to_string())
96    }
97}
98
99/// Transport effects trait for network packet emission
100///
101/// This trait represents the final step in the guard chain sequence. It handles actual
102/// network communication after all authorization, flow budget, leakage, and journal
103/// constraints have been satisfied.
104///
105/// The transport layer operates on encrypted envelopes that have passed through the
106/// complete guard chain. It is responsible for reliable delivery over secure channels
107/// established through rendezvous or other channel establishment protocols.
108///
109/// ## Guard Chain Integration
110///
111/// TransportEffects is invoked only after successful execution of:
112/// 1. CapGuard - Authorization and capability verification
113/// 2. FlowGuard - Flow budget charging and receipt generation  
114/// 3. LeakageGuard - Privacy leakage budget accounting
115/// 4. JournalCoupler - Atomic fact commitment to journals
116///
117/// ## Channel Management
118///
119/// Transport operations assume that secure channels have been established through
120/// rendezvous protocols. Each context has at most one active channel per peer pair.
121/// Channel establishment is handled by higher-level protocols.
122///
123/// ## Receipt Handling
124///
125/// Receipts prove that the sender executed the complete guard chain sequence.
126/// Recipients can validate receipts to ensure proper authorization and charging.
127/// Receipt chains provide audit trails for multi-hop forwarding scenarios.
128#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
129#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
130pub trait TransportEffects: Send + Sync {
131    /// Send an envelope to a destination authority
132    ///
133    /// This method assumes:
134    /// - Authorization has been verified by CapGuard
135    /// - Flow budget has been charged by FlowGuard  
136    /// - Leakage budget has been accounted by LeakageGuard
137    /// - Facts have been committed by JournalCoupler
138    /// - Secure channel exists for the context
139    ///
140    /// The envelope contains the encrypted payload and receipt proving guard chain execution.
141    /// Transport implementations handle reliable delivery over the established secure channel.
142    async fn send_envelope(&self, envelope: TransportEnvelope) -> Result<(), TransportError>;
143
144    /// Receive the next available envelope
145    ///
146    /// Returns an envelope from any established secure channel. The envelope includes
147    /// the encrypted payload and any attached receipts. Higher-level protocols handle
148    /// decryption and receipt validation.
149    async fn receive_envelope(&self) -> Result<TransportEnvelope, TransportError>;
150
151    /// Receive envelope from a specific authority within a context
152    ///
153    /// Filters received envelopes to match the specified source authority and context.
154    /// Returns `NoMessage` error if no matching envelope is available.
155    async fn receive_envelope_from(
156        &self,
157        source: AuthorityId,
158        context: ContextId,
159    ) -> Result<TransportEnvelope, TransportError>;
160
161    /// Check if a secure channel is established for the given context and peer
162    async fn is_channel_established(&self, context: ContextId, peer: AuthorityId) -> bool;
163
164    /// Get statistics about transport operation
165    async fn get_transport_stats(&self) -> TransportStats;
166}
167
168/// Statistics about transport layer operations
169#[derive(Debug, Clone, Serialize, Deserialize, Default)]
170pub struct TransportStats {
171    /// Number of envelopes sent successfully
172    pub envelopes_sent: u64,
173    /// Number of envelopes received successfully  
174    pub envelopes_received: u64,
175    /// Number of send failures
176    pub send_failures: u64,
177    /// Number of receive failures
178    pub receive_failures: u64,
179    /// Number of active secure channels
180    pub active_channels: u32,
181    /// Average envelope size in bytes
182    pub avg_envelope_size: u32,
183}