Skip to main content

datex_core/network/com_hub/
mod.rs

1//! This module contains the implementation of the Communication Hub (ComHub) for DATEX, which is responsible for managing network communication.
2use crate::{
3    channel::mpsc::UnboundedSender,
4    collections::HashMap,
5    global::protocol_structures::{
6        block_header::BlockType, routing_header::SignatureType,
7    },
8    network::com_hub::{
9        errors::{ComHubError, SocketEndpointRegistrationError},
10        managers::com_interface_manager::ComInterfaceManager,
11        network_response::{
12            Response, ResponseError, ResponseOptions,
13            ResponseResolutionStrategy,
14        },
15        options::ComHubOptions,
16    },
17    task,
18};
19
20use crate::prelude::*;
21
22pub mod managers;
23
24pub mod metadata;
25use crate::network::com_hub::managers::socket_manager::{
26    ComInterfaceSocketManager, SocketCloseReceiver, SocketData,
27};
28
29pub mod errors;
30pub mod network_response;
31
32pub mod network_tracing;
33use crate::network::com_interfaces::com_interface::socket::ComInterfaceSocketUUID;
34use core::{
35    cell::{RefCell, UnsafeCell},
36    cmp::PartialEq,
37    fmt::{Debug, Formatter},
38    panic,
39    pin::Pin,
40    result::Result,
41};
42use itertools::Itertools;
43use log::{debug, error, info, warn};
44use serde::{Deserialize, Serialize};
45
46pub mod options;
47use crate::{
48    global::dxb_block::DXBBlock,
49    network::{
50        block_handler::{BlockHandler, BlockHistoryData},
51        com_hub::network_tracing::{
52            NetworkTraceHop, NetworkTraceHopDirection, NetworkTraceHopSocket,
53        },
54    },
55    values::core_values::endpoint::Endpoint,
56};
57pub mod com_hub_interface;
58mod com_hub_socket;
59#[cfg(test)]
60pub mod test_utils;
61use strum_macros::Display;
62
63use crate::{
64    collections::HashSet,
65    crypto::CryptoImpl,
66    global::dxb_block::{BlockId, SignatureValidationError},
67    network::{
68        block_handler::IncomingSectionSender,
69        com_hub::managers::com_interface_manager::{
70            InterfaceCloseInfo, InterfaceCloseReceiver, InterfaceInfo,
71        },
72        com_interfaces::{
73            block_collector::BlockCollector,
74            com_interface::{
75                ComInterfaceUUID,
76                factory::{
77                    CloseAsyncCallback, ComInterfaceConfiguration,
78                    SendCallback, SendFailure, SendSuccess, SocketDataIterator,
79                    SocketProperties,
80                },
81                properties::InterfaceDirection,
82            },
83        },
84    },
85    runtime::Runtime,
86    task::sleep,
87    time::now_ms,
88    utils::{
89        async_iterators::async_next_pin_box,
90        maybe_async::{MaybeAsync, MaybeAsyncResult},
91        task_manager::TaskManager,
92        uuid::UUID,
93    },
94    values::value::Value,
95};
96use async_select::select;
97use datex_crypto_facade::crypto::Crypto;
98use datex_macros_internal::Datex;
99use futures::channel::{oneshot, oneshot::Sender};
100use futures_util::FutureExt;
101
102/// Represents the direction of a block, either incoming or outgoing, used in the block interceptor callback.
103#[derive(Datex, Debug, Clone, Copy, Display)]
104#[datex(structural)]
105pub enum BlockDirection {
106    Incoming,
107    Outgoing,
108}
109
110/// Represents a captured block along with its associated socket UUID and direction (incoming or outgoing).
111#[derive(Debug, Clone)]
112pub struct CapturedBlock<'a> {
113    pub block: &'a DXBBlock,
114    pub socket_uuid: &'a ComInterfaceSocketUUID,
115    pub direction: BlockDirection,
116}
117
118pub struct BlockInterceptor {
119    callback: Box<RefCell<dyn FnMut(CapturedBlock) + 'static>>,
120    include_debug_blocks: bool,
121}
122
123impl BlockInterceptor {
124    pub fn new<F>(callback: F, include_debug_blocks: bool) -> Self
125    where
126        F: FnMut(CapturedBlock) + 'static,
127    {
128        BlockInterceptor {
129            callback: Box::new(RefCell::new(callback)),
130            include_debug_blocks,
131        }
132    }
133
134    /// Captures a block and invokes the interceptor's callback if the block is not a debug block or if debug blocks are included.
135    pub fn capture_block(
136        &self,
137        block: &DXBBlock,
138        socket_uuid: &ComInterfaceSocketUUID,
139        direction: BlockDirection,
140    ) {
141        if !self.include_debug_blocks
142            && block.block_header.flags_and_timestamp.is_debug_block()
143        {
144            return;
145        }
146        (self.callback.borrow_mut())(CapturedBlock {
147            block,
148            socket_uuid,
149            direction,
150        });
151    }
152}
153
154#[derive(Debug, Clone)]
155pub enum ComInterfaceReconnectRequest {
156    /// Request removing a currently registered interface and trying to reconnect
157    RegisteredInterface { uuid: ComInterfaceUUID },
158    /// Request reconnection loop for a new interface
159    NewInterface {
160        interface_type: String,
161        setup_data: Box<Value>,
162        priority: InterfacePriority,
163    },
164}
165impl ComInterfaceReconnectRequest {
166    pub fn new(
167        interface_type: String,
168        setup_data: Value,
169        priority: InterfacePriority,
170    ) -> Self {
171        ComInterfaceReconnectRequest::NewInterface {
172            interface_type,
173            setup_data: Box::new(setup_data),
174            priority,
175        }
176    }
177    pub fn new_registered(uuid: ComInterfaceUUID) -> Self {
178        ComInterfaceReconnectRequest::RegisteredInterface { uuid }
179    }
180}
181
182pub struct ComHub {
183    /// the runtime endpoint of the hub (@me)
184    pub endpoint: UnsafeCell<Endpoint>,
185
186    /// ComHub configuration options
187    pub options: ComHubOptions,
188
189    socket_manager: ComInterfaceSocketManager,
190    interfaces_manager: ComInterfaceManager,
191
192    pub block_handler: BlockHandler,
193
194    block_interceptors: RefCell<HashMap<UUID, BlockInterceptor>>,
195    /// Sender that requests reconnect task to be spawned on this [ComHub] - requests are spawned externally with by calling [Self::try_reconnect_interface] with an [Rc<ComHub>]
196    pub reconnect_interface_sender:
197        RefCell<UnboundedSender<ComInterfaceReconnectRequest>>,
198
199    /// List of interfaces that are currently being reconnected, only used for debugging purposes
200    reconnecting_interfaces: RefCell<HashMap<ComInterfaceUUID, InterfaceInfo>>,
201
202    pub task_manager: TaskManager,
203
204    /// Optional runtime for the ComHub, required for network tracing. TODO: find a better solution, comhub should not need to reference runtime
205    pub(crate) runtime: RefCell<Option<Runtime>>,
206}
207
208impl Debug for ComHub {
209    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
210        f.debug_struct("ComHub")
211            .field("endpoint", &self.endpoint)
212            .field("options", &self.options)
213            .finish()
214    }
215}
216
217#[derive(
218    Datex,
219    Debug,
220    Clone,
221    Copy,
222    Ord,
223    PartialOrd,
224    Eq,
225    PartialEq,
226    Serialize,
227    Deserialize,
228)]
229#[datex(structural)]
230/// The priority of an interface, which determines the order in which interfaces are used for routing fallback logic.
231pub enum InterfacePriority {
232    /// The interface will not be used for fallback routing if no other interface is available
233    /// This is useful for interfaces which cannot communicate with the outside world or are not
234    /// capable of redirecting large amounts of data
235    None,
236    /// The interface will be used for fallback routing if no other interface is available,
237    /// depending on the defined priority
238    /// A higher number means a higher priority
239    Priority(u16),
240}
241
242impl From<Option<u16>> for InterfacePriority {
243    fn from(value: Option<u16>) -> Self {
244        match value {
245            Some(priority) => InterfacePriority::Priority(priority),
246            None => InterfacePriority::default(),
247        }
248    }
249}
250
251impl Default for InterfacePriority {
252    fn default() -> Self {
253        InterfacePriority::Priority(0)
254    }
255}
256
257pub struct ReceiveBlockPreprocessResult {
258    relayed_block: Option<DXBBlock>,
259    own_received_block: Option<DXBBlock>,
260    block_id_for_history: Option<BlockId>,
261    is_for_own: bool,
262}
263
264pub type BlockSendSyncOrAsyncResult<F> =
265    MaybeAsyncResult<Option<Vec<Vec<u8>>>, Vec<Endpoint>, F>;
266
267pub type PrepareOwnBlockFuture<'a> =
268    Pin<Box<dyn Future<Output = Result<DXBBlock, ComHubError>> + 'a>>;
269
270pub type PrepareOwnBlockResult<'a> =
271    MaybeAsyncResult<DXBBlock, ComHubError, PrepareOwnBlockFuture<'a>>;
272
273pub type ReceiveBlockResult =
274    Result<Option<DXBBlock>, SignatureValidationError>;
275
276impl ComHub {
277    pub fn create(
278        endpoint: impl Into<Endpoint>,
279        incoming_sections_sender: IncomingSectionSender,
280        com_interface_reconnect_request_sender: UnboundedSender<
281            ComInterfaceReconnectRequest,
282        >,
283        block_history_capacity: usize,
284    ) -> (Rc<ComHub>, impl Future<Output = ()>) {
285        let (task_manager, task_future) = TaskManager::create();
286
287        let block_handler = BlockHandler::init(
288            incoming_sections_sender,
289            block_history_capacity,
290        );
291
292        let com_hub = Rc::new(ComHub {
293            endpoint: UnsafeCell::new(endpoint.into()),
294            options: ComHubOptions::default(),
295            block_handler,
296            socket_manager: ComInterfaceSocketManager::new(),
297            interfaces_manager: ComInterfaceManager::default(),
298            block_interceptors: RefCell::new(HashMap::new()),
299            reconnect_interface_sender: RefCell::new(
300                com_interface_reconnect_request_sender,
301            ),
302            reconnecting_interfaces: RefCell::new(HashMap::new()),
303            task_manager,
304            runtime: RefCell::new(None),
305        });
306
307        (com_hub, task_future)
308    }
309
310    /// Registers the handle_sockets_task for the given ComInterfaceConfiguration
311    pub(crate) fn register_com_interface_handler(
312        self: Rc<Self>,
313        com_interface_configuration: ComInterfaceConfiguration,
314        priority: InterfacePriority,
315        close_receiver: InterfaceCloseReceiver,
316    ) -> Option<impl Future<Output = Result<(), ()>>> {
317        let (socket_ready_senders, socket_ready_fut) =
318            if com_interface_configuration.has_single_socket {
319                let (r, f) = ComHub::get_ready_senders();
320                (Some(r), Some(f))
321            } else {
322                (None, None)
323            };
324
325        self.task_manager
326            .register_task(self.clone().handle_sockets_task(
327                com_interface_configuration,
328                priority,
329                close_receiver,
330                socket_ready_senders,
331            ));
332        socket_ready_fut
333    }
334
335    pub fn endpoint(&self) -> &Endpoint {
336        unsafe { &*self.endpoint.get() }
337    }
338
339    /// Sets up two oneshot receivers:
340    /// The first one should resolve once the socket is fully connected, meaning the peer endpoint of the socket is known
341    /// The second one should resolve once the local endpoint has sent a Hello block
342    /// Returns a future that resolves once both oneshot receivers have resolved
343    fn get_ready_senders() -> (
344        (Sender<Result<(), ()>>, Sender<Result<(), ()>>),
345        impl Future<Output = Result<(), ()>>,
346    ) {
347        let (socket_ready_sender, socket_ready_receiver) = oneshot::channel();
348        let (socket_hello_sent_sender, socket_hello_sent_receiver) =
349            oneshot::channel();
350        let fut = async move {
351            match socket_ready_receiver.await {
352                Ok(Ok(())) => match socket_hello_sent_receiver.await {
353                    Ok(Ok(())) => Ok(()),
354                    Ok(Err(())) => Err(()),
355                    Err(_) => Err(()),
356                },
357                Ok(Err(())) => Err(()),
358                Err(_) => Err(()),
359            }
360        };
361        ((socket_ready_sender, socket_hello_sent_sender), fut)
362    }
363
364    /// Iterates over the given NewSocketsIterator for an interface and handles each socket
365    async fn handle_sockets_task(
366        self: Rc<Self>,
367        com_interface_configuration: ComInterfaceConfiguration,
368        interface_priority: InterfacePriority,
369        interface_close_receiver: InterfaceCloseReceiver,
370        ready_senders: Option<(Sender<Result<(), ()>>, Sender<Result<(), ()>>)>,
371    ) {
372        let com_interface_uuid = com_interface_configuration.uuid();
373        let mut iterator = com_interface_configuration.new_sockets_iterator;
374        let com_interface_properties =
375            com_interface_configuration.properties.clone();
376        let cleanup_callback = com_interface_configuration.close_async_callback;
377
378        let (mut socket_ready_sender, mut hello_sent_sender) =
379            match ready_senders {
380                Some((x, y)) => (Some(x), Some(y)),
381                None => (None, None),
382            };
383
384        let close_info = select!(
385            _ = async {
386                while let Some(socket) = async_next_pin_box(&mut iterator).await {
387
388                    if !self.interfaces_manager.has_interface(&com_interface_uuid) {
389                        info!("Interface {} was removed while waiting for new socket connections, stopping socket handler task", com_interface_uuid);
390                        break;
391                    }
392
393                    match socket {
394                        Ok(socket_configuration) => {
395                            let socket_iterator = socket_configuration.iterator;
396                            let send_callback = socket_configuration.send_callback;
397                            let cleanup_callback = socket_configuration.close_async_callback;
398                            let socket_properties = socket_configuration.properties;
399                            let _socket_uuid = socket_properties.uuid();
400                            let _socket_direction = socket_properties.direction.clone();
401                            let (socket_close_sender, socket_close_receiver) = oneshot::channel();
402
403                            // store socket info
404                            let _res = self.socket_manager.register_socket(
405                                SocketData {
406                                    socket_properties: socket_properties.clone(),
407                                    interface_uuid: com_interface_uuid.clone(),
408                                    interface_properties: com_interface_properties
409                                        .clone(),
410                                    send_callback,
411                                    endpoints: HashSet::new(),
412                                    close_sender: Some(socket_close_sender),
413                                    socket_ready_sender: socket_ready_sender.take(),
414                                    interface_has_single_socket: com_interface_configuration.has_single_socket,
415                                },
416                                interface_priority,
417                            );
418                            // TODO #729: handle error
419
420                            let self_clone = self.clone();
421                            if let Some(socket_iterator) = socket_iterator {
422                                self_clone.task_manager.register_task(
423                                    self_clone.clone().handle_socket_task(
424                                        socket_properties,
425                                        socket_iterator,
426                                        com_interface_uuid.clone(),
427                                        com_interface_properties.auto_identify,
428                                        socket_close_receiver,
429                                        cleanup_callback,
430                                        hello_sent_sender.take()
431                                    ),
432                                );
433                            }
434                        }
435                        Err(e) => {
436                            error!("Error creating socket from iterator: {:?}", e);
437                            break;
438                        }
439                    }
440                }
441            } => {
442                None
443            },
444            sender = interface_close_receiver => {
445                Some(sender.unwrap())
446            }
447        );
448
449        // call cleanup callback for interface if defined
450        if let Some(cleanup_callback) = cleanup_callback {
451            cleanup_callback().await;
452        }
453
454        // only if interface still exists
455        if self.interfaces_manager.has_interface(&com_interface_uuid) {
456            // indicate that interface is no longer waiting for new socket connections (e.g. for single socket interfaces)
457            self.interfaces_manager
458                .set_interface_waiting_for_socket_connections(
459                    &com_interface_uuid,
460                    false,
461                );
462
463            // if interface has no sockets, it can be destroyed
464            if !self
465                .socket_manager
466                .are_sockets_registered_for_interface(&com_interface_uuid)
467            {
468                self.interfaces_manager
469                    .cleanup_interface(&com_interface_uuid)
470                    .unwrap();
471                info!(
472                    "Destroyed interface {} as it has no sockets registered",
473                    com_interface_uuid
474                );
475            }
476        }
477
478        if let Some(InterfaceCloseInfo { closed_sender }) = close_info {
479            let _ = closed_sender.send(()); // ignore if close receiver was dropped
480        }
481
482        // if socket_ready_sender is still Some, socket was never connected, send Error
483        if let Some(socket_ready_sender) = socket_ready_sender {
484            let _ = socket_ready_sender.send(Err(()));
485        }
486        // if hello_sent_sender is still Some, hello was never sent, send Error
487        if let Some(hello_sent_sender) = hello_sent_sender {
488            let _ = hello_sent_sender.send(Err(()));
489        }
490    }
491
492    /// Sends a hello block via the given socket if the socket direction allows sending and auto_identify is enabled for the interface
493    async fn send_socket_hello(
494        self: Rc<Self>,
495        socket_uuid: ComInterfaceSocketUUID,
496        socket_direction: InterfaceDirection,
497        auto_identify: bool,
498        hello_sent_sender: Option<Sender<Result<(), ()>>>,
499    ) {
500        let send_hello = socket_direction.can_send() && auto_identify; // Only send hello if auto_identify is enabled
501
502        if send_hello {
503            info!("Saying hello to {}", socket_uuid);
504            if let Err(err) = self.send_hello_block(socket_uuid).await {
505                error!("Failed to send hello block: {:?}", err);
506                hello_sent_sender.map(|sender| sender.send(Err(())));
507            } else {
508                hello_sent_sender.map(|sender| sender.send(Ok(())));
509            }
510        } else {
511            hello_sent_sender.map(|sender| sender.send(Ok(())));
512        }
513    }
514
515    /// Handles incoming data from the given SocketDataIterator
516    async fn handle_socket_task(
517        self: Rc<Self>,
518        socket_properties: SocketProperties,
519        mut socket_iterator: SocketDataIterator,
520        com_interface_uuid: ComInterfaceUUID,
521        auto_identify: bool,
522        close_receiver: SocketCloseReceiver,
523        cleanup_callback: Option<CloseAsyncCallback>,
524        hello_sent_sender: Option<Sender<Result<(), ()>>>,
525    ) {
526        // send hello block in background task
527        self.task_manager
528            .register_task(self.clone().send_socket_hello(
529                socket_properties.uuid(),
530                socket_properties.direction.clone(),
531                auto_identify,
532                hello_sent_sender,
533            ));
534
535        let (mut bytes_sender, block_iterator) = BlockCollector::create();
536        let mut block_iterator = Box::pin(block_iterator);
537
538        let closed_sender = select!(
539            _ = async {
540                loop {
541                    select! {
542                        // receive new block data from socket
543                        data = async_next_pin_box(&mut socket_iterator).fuse() => {
544                            match data {
545
546                                // next data block
547                                Some(Ok(data)) => {
548                                    // send data to block collector
549                                    if let Err(e) = bytes_sender.start_send(data) {
550                                        error!("Error sending data to BlockCollector: {:?}", e);
551                                        break;
552                                    }
553                                }
554
555                                // got error
556                                Some(Err(_)) => {
557                                    error!("Socket {} closed, removing socket", socket_properties.uuid());
558                                    break;
559                                }
560
561                                // no more data, gracefull exit
562                                None => {
563                                    error!("Socket {} closed (iterator finished), removing socket", socket_properties.uuid());
564                                    break;
565                                }
566                            }
567                        },
568                        // receive new blocks from block collector
569                        Some(block) = async_next_pin_box(&mut block_iterator).fuse() => {
570                            // spawn as separate task to handle incoming block
571                            // this improves performance as multiple blocks can be handled in parallel
572                            // it's also required because the size of this future gets to big for embedded targets (heap allocation fails)
573                            self.clone().handle_incoming_block_async(block, socket_properties.uuid()).await;
574                        },
575
576                        complete => break,
577                    }
578                }
579            } => None,
580            closed_sender = close_receiver => {
581                info!("received socket close signal for socket removing socket");
582                Some(closed_sender.unwrap())
583            }
584        );
585
586        // call cleanup callback for socket if defined
587        if let Some(cleanup_callback) = cleanup_callback {
588            cleanup_callback().await;
589        }
590
591        // socket closed, remove
592        self.socket_manager
593            .cleanup_socket(&socket_properties.uuid());
594
595        // only if interface still exists
596        if self.interfaces_manager.has_interface(&com_interface_uuid)
597            && !self
598                .interfaces_manager
599                .is_interface_waiting_for_socket_connections(
600                    &com_interface_uuid,
601                )
602        {
603            // try to reconnect if single socket interface
604            if let Some(InterfaceInfo {
605                is_waiting_for_socket_connections: false,
606                ..
607            }) = &self
608                .interfaces_manager
609                .try_get_interface_info_by_uuid(&com_interface_uuid)
610            {
611                info!("Closing interface {}", com_interface_uuid);
612                self.reconnect_interface_sender
613                    .borrow_mut()
614                    .start_send(ComInterfaceReconnectRequest::new_registered(
615                        com_interface_uuid.clone(),
616                    ))
617                    .unwrap();
618            }
619            // this should normally not happen, but in case a multi socket ("server") interface is stopped here, just remove it
620            else {
621                self.interfaces_manager
622                    .cleanup_interface(&com_interface_uuid)
623                    .unwrap();
624                info!(
625                    "Destroyed interface {} as it is no longer waiting for socket connections",
626                    com_interface_uuid
627                );
628            }
629        }
630
631        if let Some(closed_sender) = closed_sender {
632            closed_sender.send(()).unwrap();
633        }
634    }
635
636    /// Handles an incoming block from a socket (async)
637    async fn handle_incoming_block_async(
638        self: Rc<Self>,
639        block: DXBBlock,
640        socket_uuid: ComInterfaceSocketUUID,
641    ) {
642        // handle incoming block
643        let receive_block_result = self
644            .clone()
645            .receive_block(block, socket_uuid)
646            .into_future()
647            .await;
648
649        let own_received_block = match receive_block_result {
650            Ok(own_received_block) => own_received_block,
651            Err(e) => {
652                error!("Failed to validate block signature: {:?}", e);
653                return;
654            }
655        };
656
657        // handle own block if some
658        if let Some(own_received_block) = own_received_block {
659            self.block_handler.handle_incoming_block(own_received_block);
660        }
661    }
662
663    /// Checks if the given endpoint is the local endpoint, matching instances as well
664    pub fn is_local_endpoint_exact(&self, endpoint: &Endpoint) -> bool {
665        endpoint.is_local_or_equals_endpoint(self.endpoint())
666    }
667
668    /// Register a block interceptor for incoming and outgoing blocks.
669    /// Returns the UUID of the registered interceptor, which can be used to unregister it later.
670    pub fn register_block_interceptor(
671        &self,
672        interceptor: BlockInterceptor,
673    ) -> UUID {
674        let uuid = UUID::new();
675        self.block_interceptors
676            .borrow_mut()
677            .insert(uuid.clone(), interceptor);
678        uuid
679    }
680
681    /// Unregisters a block interceptor by its UUID, returning the removed interceptor if it existed
682    pub fn unregister_block_interceptor(
683        &self,
684        uuid: &UUID,
685    ) -> Option<BlockInterceptor> {
686        self.block_interceptors.borrow_mut().remove(uuid)
687    }
688
689    /// Receives a block from a socket and handles it accordingly
690    /// Returns a MaybeAsync which is async in the following cases:
691    /// * the block signature is validated because the block is for own endpoint and signature is set
692    /// * the block needs to be relayed to other endpoints or is a trace block, which requires async handling for the relay/trace logic
693    ///   The MaybeAsync returns the own received block if the block is for own endpoint and signature is valid, otherwise None
694    // FIXME #732: this seams to generate a very big future which causes heap allocation to fail on embedded targets (!?)
695    pub(crate) fn receive_block(
696        self: Rc<Self>,
697        block: DXBBlock,
698        socket_uuid: ComInterfaceSocketUUID,
699    ) -> MaybeAsync<ReceiveBlockResult, impl Future<Output = ReceiveBlockResult>>
700    {
701        // preprocess the block and get relay receivers and own received block if any
702        let preprocess_result =
703            self.receive_block_preprocess(&socket_uuid, block);
704
705        let self_clone = self.clone();
706
707        // validate block signature if sent to own endpoint
708        let validation_result = match preprocess_result.own_received_block {
709            // if block is for own endpoint, validate signature if set
710            Some(block) => block
711                .validate_signature()
712                .map(|validation| validation.map(Some)),
713            // if block is not for own endpoint, don't validate signature and don't return own received block
714            None => MaybeAsync::Sync(Ok(None)),
715        };
716
717        validation_result
718            .map(move |validation_result| {
719                // handle async logic for received blocks if needed
720                let own_received_block = match validation_result {
721                    Ok(block) => block,
722                    Err(e) => return MaybeAsync::Sync(Err(e)),
723                };
724
725                let (trace_block, own_block) = match own_received_block {
726                    Some(block) => {
727                        let block_type = block.block_type();
728                        match block_type {
729                            BlockType::Trace | BlockType::TraceBack => {
730                                (Some(block), None)
731                            }
732                            _ => (None, Some(block)),
733                        }
734                    }
735                    None => (None, None),
736                };
737
738                if preprocess_result.relayed_block.is_some()
739                    || trace_block.is_some()
740                {
741                    MaybeAsync::Async(async move {
742                        self_clone
743                            .receive_block_async(
744                                trace_block,
745                                preprocess_result.relayed_block,
746                                preprocess_result.block_id_for_history,
747                                socket_uuid,
748                                preprocess_result.is_for_own,
749                            )
750                            .await;
751
752                        Ok(own_block)
753                    })
754                }
755                // otherwise, return directly without async handler
756                else {
757                    MaybeAsync::Sync(Ok(own_block))
758                }
759            })
760            .flatten()
761    }
762
763    /// Preprocesses a received block and returns relay receivers and own received block if any
764    fn receive_block_preprocess(
765        &self,
766        socket_uuid: &ComInterfaceSocketUUID,
767        block: DXBBlock,
768    ) -> ReceiveBlockPreprocessResult {
769        info!("{} received block: {}", self.endpoint(), block);
770
771        for interceptor in self.block_interceptors.borrow().values() {
772            interceptor.capture_block(
773                &block,
774                socket_uuid,
775                BlockDirection::Incoming,
776            );
777        }
778
779        let block_type = block.block_header.flags_and_timestamp.block_type();
780
781        // register in block history
782        let is_new_block = !self.block_handler.is_block_in_history(&block);
783
784        // assign endpoint to socket if none is assigned
785        // only if a new block and the sender in not the local endpoint
786        if is_new_block
787            && !self.is_local_endpoint_exact(&block.routing_header.sender)
788        {
789            self.register_socket_endpoint_from_incoming_block(
790                socket_uuid.clone(),
791                &block,
792            );
793        }
794
795        let all_receivers = block.receiver_endpoints();
796        let (relayed_block, own_received_block, is_for_own) = if !all_receivers
797            .is_empty()
798        {
799            let is_for_own = all_receivers.iter().any(|e| {
800                self.is_local_endpoint_exact(e)
801                    || e == &Endpoint::ANY
802                    || e == &Endpoint::ANY_ALL_INSTANCES
803            });
804
805            // handle blocks for own endpoint
806            let own_received_block =
807                if is_for_own && block_type != BlockType::Hello {
808                    info!("Block is for this endpoint ({})", self.endpoint());
809
810                    Some(block.clone()) // FIXME #733: no clone
811                } else {
812                    None
813                };
814
815            // TODO #177: handle this via TTL, not explicitly for Hello blocks
816            let relay_receivers = {
817                let should_relay =
818                    // don't relay "Hello" blocks sent to own endpoint
819                    !(
820                        is_for_own && block_type == BlockType::Hello
821                    );
822
823                // relay the block to other endpoints
824                if should_relay {
825                    let relay_receivers = if is_for_own {
826                        // get all receivers that the block must be relayed to
827                        self.get_remote_receivers(&all_receivers)
828                    } else {
829                        all_receivers
830                    };
831                    if relay_receivers.is_empty() {
832                        None
833                    } else {
834                        Some(relay_receivers)
835                    }
836                } else {
837                    None
838                }
839            };
840
841            let relayed_block = relay_receivers
842                .map(|receivers| block.clone_with_new_receivers(receivers));
843
844            (relayed_block, own_received_block, is_for_own)
845        } else {
846            (None, None, false)
847        };
848
849        // add to block history
850        let block_id_for_history = if is_new_block {
851            Some(block.get_block_id())
852        } else {
853            None
854        };
855
856        ReceiveBlockPreprocessResult {
857            relayed_block,
858            own_received_block,
859            block_id_for_history,
860            is_for_own,
861        }
862    }
863
864    /// Handles async logic for received blocks (trace blocks, redirects to other endpoints)
865    pub(crate) async fn receive_block_async(
866        self: Rc<Self>,
867        trace_block: Option<DXBBlock>,
868        relayed_block: Option<DXBBlock>,
869        block_id_for_history: Option<BlockId>,
870        socket_uuid: ComInterfaceSocketUUID,
871        is_for_own: bool,
872    ) {
873        // handle trace block asynchronously
874        if let Some(block) = trace_block {
875            info!("Handling trace block asynchronously");
876
877            match block.block_type() {
878                BlockType::Trace => {
879                    self.handle_trace_block(&block, socket_uuid.clone()).await;
880                }
881                BlockType::TraceBack => {
882                    self.handle_trace_back_block(&block, socket_uuid.clone());
883                }
884                _ => unreachable!(), // not a trace block, should never happen
885            }
886        }
887
888        // redirect block to other endpoints
889        if let Some(block) = relayed_block {
890            match block.block_type() {
891                BlockType::Trace | BlockType::TraceBack => {
892                    self.redirect_trace_block(
893                        block,
894                        socket_uuid.clone(),
895                        is_for_own,
896                    )
897                    .await;
898                }
899                _ => {
900                    if let Err(e) = self
901                        .redirect_block(block, socket_uuid.clone(), is_for_own)
902                        .await
903                    {
904                        error!("Failed to redirect block to endpoints {:?}", e);
905                        // TODO #734: handle error
906                    }
907                }
908            }
909        }
910
911        // add to block history
912        if let Some(block_id) = block_id_for_history {
913            self.block_handler
914                .add_block_id_to_history(block_id, Some(socket_uuid));
915        }
916    }
917
918    /// Returns a list of all receivers from a given ReceiverEndpoints
919    /// excluding the local endpoint
920    fn get_remote_receivers(
921        &self,
922        receiver_endpoints: &[Endpoint],
923    ) -> Vec<Endpoint> {
924        receiver_endpoints
925            .iter()
926            .filter(|e| !self.is_local_endpoint_exact(e))
927            .cloned()
928            .collect::<Vec<_>>()
929    }
930
931    /// Registers the socket endpoint from an incoming block
932    /// if the endpoint is not already registered for the socket
933    fn register_socket_endpoint_from_incoming_block(
934        &self,
935        socket_uuid: ComInterfaceSocketUUID,
936        block: &DXBBlock,
937    ) {
938        let mut socket =
939            self.socket_manager.get_socket_by_uuid_mut(&socket_uuid);
940
941        let distance = block.routing_header.distance;
942        let sender = block.routing_header.sender.clone();
943
944        // set as direct endpoint if distance = 0
945        if socket.socket_properties.direct_endpoint.is_none() && distance == 1 {
946            info!(
947                "Setting direct endpoint for socket {}: {}",
948                socket.socket_properties.uuid(),
949                sender
950            );
951            socket.socket_properties.direct_endpoint = Some(sender.clone());
952        }
953        let uuid = socket.socket_properties.uuid().clone();
954
955        drop(socket);
956
957        match self.socket_manager.register_socket_endpoint(
958            uuid,
959            sender.clone(),
960            distance,
961        ) {
962            Err(SocketEndpointRegistrationError::SocketEndpointAlreadyRegistered) => {
963                debug!(
964                    "Socket already registered for endpoint {sender}",
965                );
966            }
967            Ok(_) => { }
968        }
969    }
970
971    /// Prepares a block and relays it to the given receivers.
972    /// The routing distance is incremented by 1.
973    pub(crate) async fn redirect_block(
974        &self,
975        mut block: DXBBlock,
976        incoming_socket: ComInterfaceSocketUUID,
977        // only for debugging traces
978        forked: bool,
979    ) -> Result<(), Vec<Endpoint>> {
980        let receivers = block.receiver_endpoints();
981
982        // check if block has already passed this endpoint (-> bounced back block)
983        // and add to blacklist for all receiver endpoints
984        let history_block_data =
985            self.block_handler.get_block_data_from_history(&block);
986        if history_block_data.is_some() {
987            for receiver in &receivers {
988                if !self.is_local_endpoint_exact(receiver) {
989                    info!(
990                        "{}: Adding socket {} to blacklist for receiver {}",
991                        self.endpoint(),
992                        incoming_socket,
993                        receiver
994                    );
995                    self.socket_manager.add_to_endpoint_blocklist(
996                        receiver.clone(),
997                        &incoming_socket,
998                    );
999                }
1000            }
1001        }
1002
1003        // increment distance for next hop
1004        block.routing_header.distance += 1;
1005
1006        // ensure ttl is >= 1
1007        // decrease TTL by 1
1008        if block.routing_header.ttl > 1 {
1009            block.routing_header.ttl -= 1;
1010        }
1011        // if ttl becomes 0 after decrement drop the block
1012        else if block.routing_header.ttl == 1 {
1013            block.routing_header.ttl -= 1;
1014            warn!("Block TTL expired. Dropping block...");
1015            return Ok(());
1016        // else ttl must be zero
1017        } else {
1018            warn!("Block TTL expired. Dropping block...");
1019            return Ok(());
1020        }
1021
1022        let mut prefer_incoming_socket_for_bounce_back = false;
1023        // if we are the original sender of the block, don't send again (prevent loop) and send
1024        // bounce back block with all receivers
1025        let res = {
1026            if self.is_local_endpoint_exact(&block.routing_header.sender) {
1027                // if not bounce back block, directly send back to incoming socket (prevent loop)
1028                prefer_incoming_socket_for_bounce_back =
1029                    !block.is_bounce_back();
1030                Err(receivers.to_vec())
1031            } else {
1032                let mut excluded_sockets = vec![incoming_socket.clone()];
1033                if let Some(BlockHistoryData {
1034                    original_socket_uuid: Some(original_socket_uuid),
1035                }) = &history_block_data
1036                {
1037                    excluded_sockets.push(original_socket_uuid.clone())
1038                }
1039                self.send_block_async(block.clone(), excluded_sockets, forked)
1040                    .await
1041            }
1042        };
1043
1044        // send block for unreachable endpoints back to the sender
1045        let res = if let Err(unreachable_endpoints) = res {
1046            // try to send back to original socket
1047            // if already in history, get original socket from history
1048            // otherwise, directly send back to the incoming socket
1049            let send_back_socket = if !prefer_incoming_socket_for_bounce_back
1050                && let Some(history_block_data) = history_block_data
1051            {
1052                history_block_data.original_socket_uuid
1053            } else {
1054                Some(incoming_socket.clone())
1055            };
1056
1057            // If a send_back_socket is set, the original block is not from this endpoint,
1058            // so we can send it back to the original socket
1059            if let Some(send_back_socket_uuid) = send_back_socket {
1060                // never send a bounce back block back again to the incoming socket
1061                if block.is_bounce_back()
1062                    && send_back_socket_uuid == incoming_socket
1063                {
1064                    warn!(
1065                        "{}: Tried to send bounce back block back to incoming socket, but this is not allowed",
1066                        self.endpoint()
1067                    );
1068                    Ok(())
1069                } else if let Some(socket) = self
1070                    .socket_manager
1071                    .get_socket_by_uuid(&send_back_socket_uuid)
1072                    && socket.socket_properties.direction.can_send()
1073                {
1074                    drop(socket);
1075                    block.set_bounce_back(true);
1076                    info!(
1077                        "Sending undeliverable block for receivers {:?} back to original incoming socket {}",
1078                        unreachable_endpoints, send_back_socket_uuid
1079                    );
1080                    self
1081                        .send_block_to_endpoints_via_socket(
1082                            block,
1083                            send_back_socket_uuid.clone(),
1084                            unreachable_endpoints.clone(),
1085                            if forked { Some(0) } else { None },
1086                        )
1087                        .into_error_future()
1088                        .await
1089                    .map_or(Ok(()), |e| {
1090                        error!(
1091                            "{}: Failed to send bounce back block to socket: {:?}",
1092                            self.endpoint(), e
1093                        );
1094                        Err(unreachable_endpoints)
1095                    })
1096                } else {
1097                    error!(
1098                        "Tried to send bounce back block, but cannot send back to incoming socket"
1099                    );
1100                    Err(unreachable_endpoints)
1101                }
1102            }
1103            // Otherwise, the block originated from this endpoint, we can just call send again
1104            // and try to send it via other remaining sockets that are not on the blacklist for the
1105            // block receiver
1106            else {
1107                self.send_block_async(block, vec![], forked).await.map_or(Ok(()), |e| {
1108                    error!(
1109                        "{}: Failed to send bounce back block to socket: {:?}",
1110                        self.endpoint(), e
1111                    );
1112                    Err(unreachable_endpoints)
1113                })
1114            }
1115        } else {
1116            Ok(())
1117        };
1118
1119        // clear socket from endpoint blacklists again
1120        for receiver in &receivers {
1121            if !self.is_local_endpoint_exact(receiver) {
1122                self.socket_manager.remove_socket_from_endpoint_blocklist(
1123                    receiver,
1124                    &incoming_socket,
1125                );
1126            }
1127        }
1128
1129        res
1130    }
1131
1132    /// Prepares an own block for sending by setting sender, timestamp, distance and signing if needed.
1133    /// Will return either synchronously or asynchronously depending on the signature type.
1134    pub fn prepare_own_block(
1135        &self,
1136        mut block: DXBBlock,
1137    ) -> PrepareOwnBlockResult<'_> {
1138        /// Updates the sender and timestamp of the block
1139        fn update_sender_and_timestamp(
1140            mut block: DXBBlock,
1141            endpoint: Endpoint,
1142        ) -> Result<DXBBlock, ComHubError> {
1143            let now = now_ms();
1144            block.routing_header.sender = endpoint;
1145            block
1146                .block_header
1147                .flags_and_timestamp
1148                .set_creation_timestamp(now);
1149            block.routing_header.distance = 1;
1150            Ok(block)
1151        }
1152
1153        match block.routing_header.flags.signature_type() {
1154            // SignatureType::None can be handled synchronously
1155            SignatureType::None => MaybeAsyncResult::Sync(
1156                update_sender_and_timestamp(block, self.endpoint().clone()),
1157            ),
1158
1159            // SignatureType::Unencrypted and SignatureType::Encrypted require async signing
1160            sig_ty => {
1161                let endpoint = self.endpoint().clone();
1162
1163                MaybeAsyncResult::Async(Box::pin(async move {
1164                    let (pub_key, pri_key) = CryptoImpl::gen_ed25519()
1165                        .await
1166                        .map_err(|_| ComHubError::SignatureCreationError)?;
1167
1168                    let raw_signed =
1169                        [pub_key.clone(), block.body.clone()].concat();
1170
1171                    let hashed_signed = CryptoImpl::hash_sha256(&raw_signed)
1172                        .await
1173                        .map_err(|_| ComHubError::SignatureCreationError)?;
1174
1175                    let signature =
1176                        CryptoImpl::sig_ed25519(&pri_key, &hashed_signed)
1177                            .await
1178                            .map_err(|_| ComHubError::SignatureCreationError)?;
1179
1180                    let sig_bytes: Vec<u8> = match sig_ty {
1181                        SignatureType::Unencrypted => signature.to_vec(),
1182
1183                        SignatureType::Encrypted => {
1184                            let hash =
1185                                CryptoImpl::hkdf_sha256(&pub_key, &[0u8; 16])
1186                                    .await
1187                                    .map_err(|_| {
1188                                        ComHubError::SignatureCreationError
1189                                    })?;
1190
1191                            CryptoImpl::aes_ctr_encrypt(
1192                                &hash, &[0u8; 16], &signature,
1193                            )
1194                            .await
1195                            .map_err(|_| ComHubError::SignatureCreationError)?
1196                            .to_vec()
1197                        }
1198
1199                        SignatureType::None => unreachable!("handled above"),
1200                    };
1201
1202                    block.signature = Some([sig_bytes, pub_key].concat());
1203                    update_sender_and_timestamp(block, endpoint)
1204                }))
1205            }
1206        }
1207    }
1208
1209    /// Public method to send an outgoing block from this endpoint. Called by the runtime.
1210    pub async fn send_own_block_async(
1211        &self,
1212        mut block: DXBBlock,
1213    ) -> Result<(), Vec<Endpoint>> {
1214        block = self
1215            .prepare_own_block(block)
1216            .into_result()
1217            .await
1218            .unwrap_or_else(|e| {
1219                panic!("Error preparing own block for sending: {:?}", e)
1220            });
1221
1222        // add own outgoing block to history
1223        self.block_handler
1224            .add_block_id_to_history(block.get_block_id(), None);
1225        self.send_block_async(block, vec![], false).await
1226    }
1227
1228    /// Sends a block from this endpoint synchronously.
1229    /// If any endpoint can not be reached synchronously, an Err with the list of all endpoints is returned.
1230    /// Otherwise, Ok with optional list of responses is returned.
1231    pub fn send_own_block(
1232        &self,
1233        mut block: DXBBlock,
1234    ) -> Result<Option<Vec<Vec<u8>>>, Vec<Endpoint>> {
1235        let receivers = block.receiver_endpoints();
1236        block = match self.prepare_own_block(block) {
1237            MaybeAsyncResult::Sync(res) => res.unwrap_or_else(|e| {
1238                panic!("Error preparing own block for sending: {:?}", e)
1239            }),
1240            MaybeAsyncResult::Async(_) => {
1241                return Err(receivers);
1242            }
1243        };
1244        self.block_handler
1245            .add_block_id_to_history(block.get_block_id(), None);
1246        match self.send_block(block, vec![], false) {
1247            BlockSendSyncOrAsyncResult::Sync(res) => res,
1248            BlockSendSyncOrAsyncResult::Async(_) => Err(receivers),
1249        }
1250    }
1251
1252    /// Sends a block and wait for a response block.
1253    /// Fix number of exact endpoints -> Expected responses are known at send time.
1254    /// TODO #189: make sure that mutating blocks are always send to specific endpoint instances (@jonas/0001), not generic endpoints like @jonas.
1255    /// @jonas -> response comes from a specific instance of @jonas/0001
1256    pub async fn send_own_block_await_response(
1257        &self,
1258        block: DXBBlock,
1259        options: ResponseOptions,
1260    ) -> Vec<Result<Response, ResponseError>> {
1261        let context_id = block.block_header.context_id;
1262        let section_index = block.block_header.section_index;
1263
1264        let mut rx = self
1265            .block_handler
1266            .register_incoming_block_observer(context_id, section_index);
1267
1268        let has_exact_receiver_count = block.has_exact_receiver_count();
1269        let receivers = block.receiver_endpoints();
1270
1271        let res = self.send_own_block_async(block).await;
1272        let failed_endpoints = res.err().unwrap_or_default();
1273
1274        let timeout = options
1275            .timeout
1276            .unwrap_or_default(self.options.default_receive_timeout);
1277
1278        // return fixed number of responses
1279        if has_exact_receiver_count {
1280            // if resolution strategy is ReturnOnAnyError or ReturnOnFirstResult, directly return if any endpoint failed
1281            if (options.resolution_strategy
1282                == ResponseResolutionStrategy::ReturnOnAnyError
1283                || options.resolution_strategy
1284                    == ResponseResolutionStrategy::ReturnOnFirstResult)
1285                && !failed_endpoints.is_empty()
1286            {
1287                // for each failed endpoint, set NotReachable error, for all others EarlyAbort
1288                return receivers
1289                    .iter()
1290                    .map(|receiver| {
1291                        if failed_endpoints.contains(receiver) {
1292                            Err(ResponseError::NotReachable(receiver.clone()))
1293                        } else {
1294                            Err(ResponseError::EarlyAbort(receiver.clone()))
1295                        }
1296                    })
1297                    .collect::<Vec<_>>();
1298            }
1299
1300            // store received responses in map for all receivers
1301            let mut responses = HashMap::new();
1302            let mut missing_response_count = receivers.len();
1303            for receiver in &receivers {
1304                responses.insert(
1305                    receiver.clone(),
1306                    if failed_endpoints.contains(receiver) {
1307                        Err(ResponseError::NotReachable(receiver.clone()))
1308                    } else {
1309                        Err(ResponseError::NoResponseAfterTimeout(
1310                            receiver.clone(),
1311                            timeout,
1312                        ))
1313                    },
1314                );
1315            }
1316            // directly subtract number of already failed endpoints from missing responses
1317            missing_response_count -= failed_endpoints.len();
1318
1319            info!(
1320                "Waiting for responses from receivers {}",
1321                receivers
1322                    .iter()
1323                    .map(|e| e.to_string())
1324                    .collect::<Vec<_>>()
1325                    .join(",")
1326            );
1327
1328            let res = task::timeout(timeout, async {
1329                while let Some(section) = rx.next().await {
1330                    let mut received_response = false;
1331                    // get sender
1332                    let mut sender = section.get_sender();
1333                    // add to response for exactly matching endpoint instance
1334                    if let Some(response) = responses.get_mut(&sender) {
1335                        // check if the receiver is already set (= current set response is Err)
1336                        if response.is_err() {
1337                            *response = Ok(Response::ExactResponse(sender.clone(), section));
1338                            missing_response_count -= 1;
1339                            info!("Received expected response from {sender}");
1340                            received_response = true;
1341                        }
1342                        // already received a response from this exact sender - this should not happen
1343                        else {
1344                            error!("Received multiple responses from the same sender: {sender}");
1345                        }
1346                    }
1347                    // add to response for matching endpoint
1348                    else if let Some(matches_endpoint) = self.try_match_sender(&mut responses, &sender) {
1349                        let response = responses.get_mut(&matches_endpoint).unwrap();
1350                        info!("Received resolved response from {} -> {}", sender, sender.any_instance());
1351                        sender = sender.any_instance();
1352                        // check if the receiver is already set (= current set response is Err)
1353                        if response.is_err() {
1354                            *response = Ok(Response::ResolvedResponse(sender.clone(), section));
1355                            missing_response_count -= 1;
1356                            received_response = true;
1357                        }
1358                        // already received a response from a matching endpoint - ignore
1359                        else {
1360                            info!("Received multiple resolved responses from the {}", sender);
1361                        }
1362                    }
1363                    // response from unexpected sender
1364                    else {
1365                        error!("Received response from unexpected sender: {}", sender);
1366                    }
1367
1368                    // if resolution strategy is ReturnOnFirstResult, break if any response is received
1369                    if received_response && options.resolution_strategy == ResponseResolutionStrategy::ReturnOnFirstResult {
1370                        // set all other responses to EarlyAbort
1371                        for (receiver, response) in responses.iter_mut() {
1372                            if receiver != &sender {
1373                                *response = Err(ResponseError::EarlyAbort(receiver.clone()));
1374                            }
1375                        }
1376                        break;
1377                    }
1378
1379                    // if all responses are received, break
1380                    if missing_response_count == 0 {
1381                        break;
1382                    }
1383                }
1384            }).await;
1385
1386            if res.is_err() {
1387                error!("Timeout waiting for responses");
1388            }
1389
1390            // return responses as vector
1391            responses.into_values().collect::<Vec<_>>()
1392        }
1393        // return all received responses
1394        else {
1395            let mut responses = vec![];
1396
1397            let res = task::timeout(timeout, async {
1398                let mut rx =
1399                    self.block_handler.register_incoming_block_observer(
1400                        context_id,
1401                        section_index,
1402                    );
1403                while let Some(section) = rx.next().await {
1404                    // get sender
1405                    let sender = section.get_sender();
1406                    info!("Received response from {sender}");
1407                    // add to response for exactly matching endpoint instance
1408                    responses.push(Ok(Response::UnspecifiedResponse(section)));
1409
1410                    // if resolution strategy is ReturnOnFirstResult, break if any response is received
1411                    if options.resolution_strategy
1412                        == ResponseResolutionStrategy::ReturnOnFirstResult
1413                    {
1414                        break;
1415                    }
1416                }
1417            })
1418            .await;
1419
1420            if res.is_err() {
1421                info!("Timeout waiting for responses");
1422            }
1423
1424            responses
1425        }
1426    }
1427
1428    /// Tries to match the sender endpoint to a more generic endpoint in the responses map (e.g., @jonas/0001 -> @jonas or @@local/0001 -> @xyz) and returns the matching endpoint if found.
1429    fn try_match_sender(
1430        &self,
1431        responses: &mut HashMap<Endpoint, Result<Response, ResponseError>>,
1432        sender: &Endpoint,
1433    ) -> Option<Endpoint> {
1434        let matches = gen {
1435            // match sender but with any wildcard instance
1436            yield sender.any_instance();
1437            // match @@local if endpoint is local endpoint
1438            if self.is_local_endpoint_exact(sender) {
1439                yield Endpoint::LOCAL;
1440                yield Endpoint::LOCAL_ALL_INSTANCES;
1441            }
1442        }
1443        .collect::<Vec<Endpoint>>();
1444        for try_match_sender in matches {
1445            let res = responses.get(&try_match_sender);
1446            if let Some(_response) = res {
1447                return Some(try_match_sender);
1448            }
1449        }
1450        None
1451    }
1452
1453    /// Sends a block to all endpoints specified in the block header.
1454    /// Awaits the result if any block was sent via an async interface.
1455    /// See `send_block` for details.
1456    pub async fn send_block_async(
1457        &self,
1458        block: DXBBlock,
1459        exclude_sockets: Vec<ComInterfaceSocketUUID>,
1460        forked: bool,
1461    ) -> Result<(), Vec<Endpoint>> {
1462        match self.send_block(block, exclude_sockets, forked) {
1463            MaybeAsyncResult::Sync(res) => {
1464                // TODO #735: handle received blocks
1465                res.map(|_| ())
1466            }
1467            MaybeAsyncResult::Async(fut) => fut.await.map(|_| ()),
1468        }
1469    }
1470
1471    /// Sends a block to all endpoints specified in the block header.
1472    /// The routing algorithm decides which sockets are used to send the block, based on the endpoint.
1473    /// A block can be sent to multiple endpoints at the same time over a socket or to multiple sockets for each endpoint.
1474    /// The original_socket parameter is used to prevent sending the block back to the sender.
1475    /// When this method is called, the block is queued in the send queue.
1476    /// Returns a SyncOrAsyncResult:
1477    ///  - if all blocks were sent via sync interfaces, returns Sync with Ok containing an optional vector of received blocks (if any), or Err with a list of unreachable endpoints
1478    ///  - if any block was sent via an async interface, returns Async with a Future that resolves to Ok(()) or Err with a list of unreachable endpoints
1479    pub fn send_block(
1480        &self,
1481        mut block: DXBBlock,
1482        exclude_sockets: Vec<ComInterfaceSocketUUID>,
1483        forked: bool,
1484    ) -> BlockSendSyncOrAsyncResult<
1485        impl Future<Output = Result<Option<Vec<Vec<u8>>>, Vec<Endpoint>>>,
1486    > {
1487        let outbound_receiver_groups =
1488            self.socket_manager.get_outbound_receiver_groups(
1489                self.endpoint(),
1490                &block.receiver_endpoints(),
1491                exclude_sockets,
1492            );
1493
1494        if outbound_receiver_groups.is_none() {
1495            error!("No outbound receiver groups found for block");
1496            return MaybeAsyncResult::Sync(Err(vec![]));
1497        }
1498
1499        let outbound_receiver_groups = outbound_receiver_groups.unwrap();
1500
1501        let mut unreachable_endpoints = vec![];
1502
1503        // currently only used for trace debugging (TODO: put behind debug flag)
1504        // if more than one addressed block is sent, the block is forked, thus the fork count is set to 0
1505        // for each forked block, the fork count is incremented
1506        // if only one block is sent, the block is just moved and not forked
1507        let mut fork_count = if forked || outbound_receiver_groups.len() > 1 {
1508            Some(0)
1509        } else {
1510            None
1511        };
1512
1513        block.set_bounce_back(false);
1514
1515        let mut results = Vec::new();
1516
1517        for (receiver_socket, endpoints) in outbound_receiver_groups {
1518            if let Some(socket_uuid) = receiver_socket {
1519                results.push((
1520                    endpoints.clone(),
1521                    self.send_block_to_endpoints_via_socket(
1522                        block.clone(),
1523                        socket_uuid,
1524                        endpoints,
1525                        fork_count,
1526                    ),
1527                ));
1528            } else {
1529                error!(
1530                    "{}: cannot send block, no receiver sockets found for endpoints {:?}",
1531                    self.endpoint(),
1532                    endpoints.iter().map(|e| e.to_string()).collect::<Vec<_>>()
1533                );
1534                unreachable_endpoints.extend(endpoints);
1535            }
1536            // increment fork_count if Some
1537            if let Some(count) = fork_count {
1538                fork_count = Some(count + 1);
1539            }
1540        }
1541
1542        // return error if any unreachable endpoints
1543        if !unreachable_endpoints.is_empty() {
1544            return MaybeAsyncResult::Sync(Err(unreachable_endpoints));
1545        }
1546
1547        // if all results are sync, return sync
1548        if results
1549            .iter()
1550            .all(|(_, res)| matches!(res, MaybeAsyncResult::Sync(_)))
1551        {
1552            let mut received_blocks = Vec::new();
1553            for (endpoints, res) in results {
1554                match res {
1555                    MaybeAsyncResult::Sync(r) => {
1556                        match r {
1557                            Ok(Some(data)) => {
1558                                received_blocks.push(data); // TODO #736: already DXBBlocks here?
1559                            }
1560                            Ok(None) => { /* no data */ }
1561                            Err(_) => {
1562                                unreachable_endpoints.extend(endpoints);
1563                            }
1564                        }
1565                    }
1566                    _ => unreachable!(),
1567                }
1568            }
1569            if !unreachable_endpoints.is_empty() {
1570                MaybeAsyncResult::Sync(Err(unreachable_endpoints))
1571            } else {
1572                MaybeAsyncResult::Sync(Ok(Some(received_blocks)))
1573            }
1574        }
1575        // otherwise return async
1576        else {
1577            MaybeAsyncResult::Async(async move {
1578                let futures =
1579                    results.into_iter().map(|(endpoints, res)| async move {
1580                        match res {
1581                            MaybeAsyncResult::Sync(r) => {
1582                                // TODO #737 directly process received blocks
1583                                r.map(|_data| ()).map_err(|_| endpoints)
1584                            }
1585                            MaybeAsyncResult::Async(fut) => {
1586                                fut.await.map(|_data| ()).map_err(|_| endpoints)
1587                            }
1588                        }
1589                    });
1590
1591                let res = futures::future::join_all(futures).await;
1592                // merge all unreachable endpoints and return err if any
1593                let all_unreachable_endpoints = res
1594                    .into_iter()
1595                    .filter_map(|r| r.err())
1596                    .flatten()
1597                    .collect::<Vec<_>>();
1598                if !all_unreachable_endpoints.is_empty() {
1599                    Err(all_unreachable_endpoints)
1600                } else {
1601                    Ok(None)
1602                }
1603            })
1604        }
1605    }
1606
1607    /// Sends a block via a socket to a list of endpoints.
1608    /// Before the block is sent, it is modified to include the list of endpoints as receivers.
1609    fn send_block_to_endpoints_via_socket(
1610        &self,
1611        mut block: DXBBlock,
1612        socket_uuid: ComInterfaceSocketUUID,
1613        endpoints: Vec<Endpoint>,
1614        // currently only used for trace debugging (TODO: put behind debug flag)
1615        fork_count: Option<usize>,
1616    ) -> MaybeAsyncResult<
1617        Option<Vec<u8>>,
1618        SendFailure,
1619        impl Future<Output = Result<Option<Vec<u8>>, SendFailure>>,
1620    > {
1621        block.set_receivers(&endpoints);
1622
1623        let socket_data =
1624            match self.socket_manager.get_socket_by_uuid(&socket_uuid) {
1625                Some(socket_data) => socket_data,
1626                None => {
1627                    return MaybeAsyncResult::Sync(Err(SendFailure(Box::new(
1628                        block,
1629                    ))));
1630                }
1631            };
1632
1633        // assuming the distance was already increment during redirect, we
1634        // effectively decrement the block distance by 1 if it is a bounce back
1635        if block.is_bounce_back() {
1636            block.routing_header.distance -= 2;
1637        }
1638
1639        // if type is Trace or TraceBack, add the outgoing socket to the hops
1640        // NOTE: the block body is modified here for trace blocks, which would invalidate any signature
1641        // generated for the block. However, trace blocks are only used for debugging purposes and not expected to be signed.
1642        match block.block_header.flags_and_timestamp.block_type() {
1643            BlockType::Trace | BlockType::TraceBack => {
1644                let distance = block.routing_header.distance;
1645                let new_fork_nr = self.calculate_fork_nr(&block, fork_count);
1646                let bounce_back = block.is_bounce_back();
1647
1648                self.add_hop_to_block_trace_data(
1649                    &mut block,
1650                    NetworkTraceHop {
1651                        endpoint: self.endpoint().clone(),
1652                        distance,
1653                        socket: NetworkTraceHopSocket::new(
1654                            &socket_data.interface_properties,
1655                            socket_uuid.clone(),
1656                        ),
1657                        direction: NetworkTraceHopDirection::Outgoing,
1658                        fork_nr: new_fork_nr,
1659                        bounce_back,
1660                    },
1661                );
1662            }
1663            _ => {}
1664        }
1665
1666        let is_broadcast = endpoints
1667            .iter()
1668            .any(|e| e == &Endpoint::ANY_ALL_INSTANCES || e == &Endpoint::ANY);
1669
1670        // Break loop and don't relay broadcast blocks back to socket with direct endpoint set to self
1671        if is_broadcast
1672            && let Some(direct_endpoint) =
1673                &socket_data.socket_properties.direct_endpoint
1674            && self.is_local_endpoint_exact(direct_endpoint)
1675        {
1676            return MaybeAsyncResult::Sync(Ok(None));
1677        }
1678        for interceptor in self.block_interceptors.borrow().values() {
1679            interceptor.capture_block(
1680                &block,
1681                &socket_uuid,
1682                BlockDirection::Outgoing,
1683            );
1684        }
1685        info!(
1686            "Sending block to socket {} ({})",
1687            socket_uuid,
1688            endpoints.iter().map(|e| e.to_string()).join(", ")
1689        );
1690
1691        // TODO #190: resend block if socket failed to send
1692        if let Some(send_callback) = socket_data.send_callback.clone() {
1693            drop(socket_data);
1694
1695            match send_callback {
1696                SendCallback::Sync(callback)
1697                | SendCallback::SyncOnce(callback) => MaybeAsyncResult::Sync(
1698                    callback(block).map(|send_success| match send_success {
1699                        SendSuccess::SentWithNewIncomingData(data) => {
1700                            Some(data)
1701                        }
1702                        _ => None,
1703                    }),
1704                ),
1705                SendCallback::Async(callback) => {
1706                    MaybeAsyncResult::Async(async move {
1707                        callback.call(block).await.map(|_| None)
1708                    })
1709                }
1710            }
1711            .map(move |res| {
1712                if res.is_err() {
1713                    self.handle_socket_send_failure(&socket_uuid);
1714                }
1715                res
1716            })
1717        } else {
1718            panic!("No send callback registered for socket {}", socket_uuid);
1719        }
1720    }
1721
1722    // if socket interface is single socket interface, close the interface (with potential reconnect)
1723    fn handle_socket_send_failure(&self, socket_uuid: &ComInterfaceSocketUUID) {
1724        if let Some(SocketData {
1725            interface_uuid,
1726            interface_has_single_socket: true,
1727            ..
1728        }) = &self.socket_manager.get_socket_by_uuid(socket_uuid)
1729        {
1730            info!(
1731                "Closing interface {} because of send failure on single socket",
1732                interface_uuid
1733            );
1734            self.reconnect_interface_sender
1735                .borrow_mut()
1736                .start_send(ComInterfaceReconnectRequest::new_registered(
1737                    interface_uuid.clone(),
1738                ))
1739                .unwrap();
1740        }
1741    }
1742
1743    /// Completely removes an existing interface and tries to reconnect
1744    pub async fn try_reconnect_interface(
1745        self: Rc<ComHub>,
1746        reconnect_request: ComInterfaceReconnectRequest,
1747    ) {
1748        let interface_info = match reconnect_request {
1749            ComInterfaceReconnectRequest::RegisteredInterface { uuid } => {
1750                // TODO handle the case, where the interface might not exist or has already been removed
1751                self.remove_interface(&uuid).await.unwrap()
1752            }
1753            ComInterfaceReconnectRequest::NewInterface {
1754                interface_type,
1755                setup_data,
1756                priority,
1757            } => {
1758                let default_properties = self
1759                    .interfaces_manager
1760                    .get_interface_default_properties(&interface_type)
1761                    .unwrap();
1762                InterfaceInfo {
1763                    properties: Rc::new(default_properties),
1764                    priority,
1765                    is_waiting_for_socket_connections: false,
1766                    original_setup_data: Some(*setup_data),
1767                    close_sender: None,
1768                }
1769            }
1770        };
1771
1772        let reconnection_config = self
1773            .interfaces_manager
1774            .get_reconnection_config(&interface_info.properties.interface_type);
1775
1776        // generate new temp uuid
1777        let temp_uuid = ComInterfaceUUID::new();
1778
1779        if let Some(reconnect_attempts) =
1780            reconnection_config.get_reconnect_attempts()
1781        {
1782            let setup_data = interface_info.original_setup_data.clone();
1783            let interface_type =
1784                interface_info.properties.interface_type.clone();
1785            let priority = interface_info.priority;
1786
1787            // only for debugging purposes: store in reconnecting_interfaces
1788            self.reconnecting_interfaces
1789                .borrow_mut()
1790                .insert(temp_uuid.clone(), interface_info);
1791
1792            let mut attempts = 0;
1793
1794            if let Some(setup_data) = setup_data {
1795                info!("Trying to reconnect to {}", interface_type);
1796                loop {
1797                    sleep(reconnect_attempts.interval).await;
1798                    // abort when max attempts reached
1799                    if let Some(max_reconnect_attempts) =
1800                        reconnect_attempts.max_attempts
1801                        && attempts > max_reconnect_attempts
1802                    {
1803                        warn!(
1804                            "Max reconnect attempts of {} reached for interface {}, aborting reconnect",
1805                            max_reconnect_attempts, interface_type
1806                        );
1807                        break;
1808                    }
1809
1810                    let res = self
1811                        .clone()
1812                        .create_interface(
1813                            &interface_type,
1814                            setup_data.clone(),
1815                            priority,
1816                        )
1817                        .await;
1818                    match res {
1819                        Err(err) => {
1820                            error!(
1821                                "Failed to reconnect to \"{}\": {}",
1822                                interface_type, err
1823                            );
1824                            attempts += 1;
1825                        }
1826                        Ok((_, ready_receiver)) => {
1827                            if let Some(ready_receiver) = ready_receiver {
1828                                let _ = ready_receiver.await;
1829                            }
1830                            break;
1831                        }
1832                    }
1833                }
1834            } else {
1835                info!(
1836                    "Closed interface {}, cannot reconnect because of missing setup data",
1837                    interface_type
1838                );
1839            }
1840
1841            self.reconnecting_interfaces.borrow_mut().remove(&temp_uuid);
1842        }
1843    }
1844
1845    /// Sends a hello block via the specified socket.
1846    /// Returns Ok(()) if the block was sent successfully, or Err(SendFailure) if sending failed.
1847    pub async fn send_hello_block(
1848        &self,
1849        socket_uuid: ComInterfaceSocketUUID,
1850    ) -> Result<(), SendFailure> {
1851        let mut block: DXBBlock = DXBBlock::default();
1852        block
1853            .block_header
1854            .flags_and_timestamp
1855            .set_block_type(BlockType::Hello);
1856        // TODO #182 include fingerprint of the own public key into body
1857
1858        let block = self
1859            .prepare_own_block(block)
1860            .into_result()
1861            .await
1862            .unwrap_or_else(|e| {
1863                panic!("Error preparing own block for sending: {:?}", e)
1864            });
1865
1866        self.send_block_to_endpoints_via_socket(
1867            block,
1868            socket_uuid.clone(),
1869            vec![Endpoint::ANY],
1870            None,
1871        )
1872        .into_future()
1873        .await
1874        .map(|_| ())
1875    }
1876
1877    pub fn clear_endpoint_blacklist(&self) {
1878        self.socket_manager
1879            .endpoint_sockets_blacklist
1880            .borrow_mut()
1881            .clear();
1882    }
1883
1884    pub fn interfaces_manager(&self) -> &ComInterfaceManager {
1885        &self.interfaces_manager
1886    }
1887
1888    pub fn socket_manager(&self) -> &ComInterfaceSocketManager {
1889        &self.socket_manager
1890    }
1891}
1892
1893#[cfg(test)]
1894#[cfg(feature = "crypto_enabled")]
1895pub mod tests {
1896    use crate::{
1897        channel::mpsc::{
1898            UnboundedReceiver, UnboundedSender, create_unbounded_channel,
1899        },
1900        global::{
1901            dxb_block::{DXBBlock, IncomingSection},
1902            protocol_structures::{
1903                block_header::{BlockHeader, FlagsAndTimestamp},
1904                routing_header::RoutingHeader,
1905            },
1906        },
1907        network::{
1908            block_handler::{
1909                BlockHandler, IncomingSectionReceiver,
1910                create_incoming_sections_channel,
1911            },
1912            com_hub::{
1913                ComHub, ComInterfaceReconnectRequest, InterfacePriority,
1914                errors::ComInterfaceCreateError,
1915                managers::com_interface_manager::{
1916                    ComInterfaceAsyncFactoryResult, ComInterfaceManager,
1917                },
1918                test_utils::{
1919                    TEST_ENDPOINT_A, TEST_ENDPOINT_B, TEST_ENDPOINT_C,
1920                    get_endpoints_from_com_hub_metadata,
1921                    run_with_coupled_com_hubs,
1922                },
1923            },
1924            com_interfaces::com_interface::{
1925                factory::{
1926                    ComInterfaceAsyncFactory, ComInterfaceConfiguration,
1927                    ComInterfaceSyncFactory, SendCallback, SendSuccess,
1928                    SocketConfiguration, SocketProperties,
1929                },
1930                properties::{ComInterfaceProperties, InterfaceDirection},
1931            },
1932        },
1933        prelude::*,
1934        std_sync::Mutex,
1935        values::core_values::endpoint::Endpoint,
1936    };
1937    use alloc::rc::Rc;
1938    use async_select::select;
1939    use datex_macros_internal::Datex;
1940    use futures_util::FutureExt;
1941    use log::info;
1942
1943    /// Creates a mock ComHub for testing without a connected channel
1944    async fn run_with_com_hub<AppReturn, AppFuture>(
1945        app_logic: impl FnOnce(
1946            Rc<ComHub>,
1947            IncomingSectionReceiver,
1948            UnboundedReceiver<ComInterfaceReconnectRequest>,
1949        ) -> AppFuture,
1950    ) -> AppReturn
1951    where
1952        AppFuture: Future<Output = AppReturn>,
1953    {
1954        let (incoming_section_sender, incoming_section_receiver) =
1955            create_incoming_sections_channel();
1956        let (
1957            com_interface_reconnect_request_sender,
1958            com_interface_reconnect_request_receiver,
1959        ) = create_unbounded_channel();
1960        let (com_hub, com_hub_future) = ComHub::create(
1961            TEST_ENDPOINT_A.clone(),
1962            incoming_section_sender,
1963            com_interface_reconnect_request_sender,
1964            BlockHandler::DEFAULT_HISTORY_CAPACITY,
1965        );
1966        select! {
1967            app_result = app_logic(com_hub, incoming_section_receiver, com_interface_reconnect_request_receiver).fuse() => app_result,
1968            _ = com_hub_future.fuse() => panic!("ComHub future should not complete during the test"),
1969        }
1970    }
1971
1972    async fn add_proxy_interface_to_com_hub(
1973        com_hub: Rc<ComHub>,
1974        endpoint: Endpoint,
1975    ) -> (UnboundedSender<Vec<u8>>, UnboundedReceiver<DXBBlock>) {
1976        let (outgoing_block_sender, outgoing_block_receiver) =
1977            create_unbounded_channel();
1978        let (incoming_data_sender, mut incoming_data_receiver) =
1979            create_unbounded_channel::<Vec<u8>>();
1980        let outgoing_block_sender = Rc::new(Mutex::new(outgoing_block_sender));
1981
1982        let proxy_interface_configuration =
1983            ComInterfaceConfiguration::new_single_socket(
1984                ComInterfaceProperties {
1985                    interface_type: "proxy".to_string(),
1986                    channel: "proxy".to_string(),
1987                    name: Some("proxy".to_string()),
1988                    ..Default::default()
1989                },
1990                SocketConfiguration::new_in_out(
1991                    SocketProperties::new_with_direct_endpoint(
1992                        InterfaceDirection::InOut,
1993                        1,
1994                        endpoint,
1995                    ),
1996                    async gen move {
1997                        while let Some(block) =
1998                            incoming_data_receiver.next().await
1999                        {
2000                            yield Ok(block)
2001                        }
2002                    },
2003                    SendCallback::new_sync(move |block| {
2004                        outgoing_block_sender
2005                            .try_lock()
2006                            .unwrap()
2007                            .start_send(block)
2008                            .unwrap();
2009                        Ok(SendSuccess::Sent)
2010                    }),
2011                ),
2012            );
2013        com_hub
2014            .clone()
2015            .add_interface_from_configuration(
2016                proxy_interface_configuration,
2017                InterfacePriority::None,
2018            )
2019            .unwrap()
2020            .unwrap()
2021            .await
2022            .unwrap();
2023
2024        (incoming_data_sender, outgoing_block_receiver)
2025    }
2026
2027    async fn run_with_com_hub_and_proxy_interface<AppReturn, AppFuture>(
2028        app_logic: impl FnOnce(
2029            Rc<ComHub>,
2030            UnboundedSender<Vec<u8>>,
2031            UnboundedReceiver<DXBBlock>,
2032            IncomingSectionReceiver,
2033            UnboundedReceiver<ComInterfaceReconnectRequest>,
2034        ) -> AppFuture,
2035    ) -> AppReturn
2036    where
2037        AppFuture: Future<Output = AppReturn>,
2038    {
2039        run_with_com_hub(
2040            |com_hub,
2041             incoming_sections_receiver,
2042             com_interface_reconnect_request_receiver| async move {
2043                let (incoming_data_sender, outgoing_block_receiver) =
2044                    add_proxy_interface_to_com_hub(
2045                        com_hub.clone(),
2046                        TEST_ENDPOINT_B.clone(),
2047                    )
2048                    .await;
2049                app_logic(
2050                    com_hub,
2051                    incoming_data_sender,
2052                    outgoing_block_receiver,
2053                    incoming_sections_receiver,
2054                    com_interface_reconnect_request_receiver,
2055                )
2056                .await
2057            },
2058        )
2059        .await
2060    }
2061
2062    async fn send_blocks_to_endpoint(
2063        com_hub: Rc<ComHub>,
2064        incoming_data_sender: &mut UnboundedSender<Vec<u8>>,
2065        endpoint: Endpoint,
2066        blocks: &mut Vec<DXBBlock>,
2067    ) {
2068        for block in blocks {
2069            block.set_receivers(vec![endpoint.clone()]);
2070
2071            *block = com_hub
2072                .prepare_own_block(block.clone())
2073                .into_result()
2074                .await
2075                .unwrap();
2076
2077            let block_bytes = block.to_bytes();
2078            incoming_data_sender
2079                .start_send(block_bytes.as_slice().to_vec())
2080                .unwrap();
2081        }
2082    }
2083
2084    #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2085    pub enum CollectedBlockType {
2086        #[default]
2087        All,
2088        SingleBocks,
2089        BlockStream,
2090    }
2091
2092    impl CollectedBlockType {
2093        pub fn matches_section(&self, section: &IncomingSection) -> bool {
2094            match self {
2095                CollectedBlockType::SingleBocks => {
2096                    matches!(section, IncomingSection::SingleBlock(_))
2097                }
2098                CollectedBlockType::BlockStream => {
2099                    matches!(section, IncomingSection::BlockStream(_))
2100                }
2101                CollectedBlockType::All => true,
2102            }
2103        }
2104    }
2105
2106    pub async fn get_collected_received_blocks_from_receiver(
2107        sections_receiver: &mut IncomingSectionReceiver,
2108        collected_type: CollectedBlockType,
2109        count: usize,
2110    ) -> Vec<DXBBlock> {
2111        let mut blocks = vec![];
2112
2113        let mut received_count = 0;
2114
2115        while let Some(section) = sections_receiver.next().await {
2116            if !collected_type.matches_section(&section) {
2117                panic!(
2118                    "Received section does not match collected block type {:?}",
2119                    collected_type
2120                );
2121            }
2122
2123            match section {
2124                IncomingSection::SingleBlock((Some(block), ..)) => {
2125                    blocks.push(block.clone());
2126                    received_count += 1;
2127                    info!("Received single block");
2128                }
2129                IncomingSection::BlockStream((Some(mut block_stream), ..)) => {
2130                    info!("[START] block stream");
2131                    while let Some(block) = block_stream.next().await {
2132                        received_count += 1;
2133                        blocks.push(block.clone());
2134                        info!("Received block from stream");
2135
2136                        if received_count >= count {
2137                            break;
2138                        }
2139                    }
2140                    info!("[END] receiving block stream");
2141                }
2142                _ => {
2143                    panic!("Received section does not contain a block");
2144                }
2145            }
2146
2147            if received_count >= count {
2148                break;
2149            }
2150        }
2151
2152        if blocks.len() != count {
2153            panic!(
2154                "Expected to receive {} blocks, but got {}",
2155                count,
2156                blocks.len()
2157            );
2158        }
2159
2160        blocks
2161    }
2162
2163    #[derive(Datex, Debug, Clone)]
2164    #[datex(structural)]
2165    struct MockupInterfaceSetupData {
2166        pub name: String,
2167    }
2168    impl MockupInterfaceSetupData {
2169        pub fn new(name: &str) -> Self {
2170            Self {
2171                name: name.to_string(),
2172            }
2173        }
2174    }
2175
2176    impl ComInterfaceSyncFactory for MockupInterfaceSetupData {
2177        fn create_interface(
2178            self,
2179        ) -> Result<ComInterfaceConfiguration, ComInterfaceCreateError>
2180        {
2181            Ok(ComInterfaceConfiguration::new_single_socket(
2182                ComInterfaceProperties::default(),
2183                SocketConfiguration::new_in_out(
2184                    SocketProperties::new(InterfaceDirection::InOut, 1),
2185                    async gen move {
2186                        loop {
2187                            yield Ok(vec![]);
2188                        }
2189                    },
2190                    SendCallback::new_sync(|_| Ok(SendSuccess::Sent)),
2191                ),
2192            ))
2193        }
2194
2195        fn get_default_properties() -> ComInterfaceProperties {
2196            ComInterfaceProperties {
2197                name: Some("mockup".to_string()),
2198                ..Default::default()
2199            }
2200        }
2201    }
2202
2203    impl ComInterfaceAsyncFactory for MockupInterfaceSetupData {
2204        fn create_interface(self) -> ComInterfaceAsyncFactoryResult {
2205            Box::pin(
2206                async move { ComInterfaceSyncFactory::create_interface(self) },
2207            )
2208        }
2209        fn get_default_properties() -> ComInterfaceProperties {
2210            <MockupInterfaceSetupData as ComInterfaceSyncFactory>::get_default_properties()
2211        }
2212    }
2213
2214    #[tokio::test]
2215    pub async fn create_from_sync_factory() {
2216        run_with_com_hub(|com_hub, _, _| async move {
2217            let interface_configuration =
2218                ComInterfaceManager::create_interface_sync_from_setup_data(
2219                    MockupInterfaceSetupData::new("test"),
2220                )
2221                .unwrap();
2222            let uuid = interface_configuration.uuid().clone();
2223
2224            com_hub
2225                .clone()
2226                .add_interface_from_configuration(
2227                    interface_configuration,
2228                    InterfacePriority::default(),
2229                )
2230                .unwrap();
2231
2232            assert!(com_hub.remove_interface(&uuid).await.is_ok());
2233        })
2234        .await;
2235    }
2236
2237    #[tokio::test]
2238    pub async fn create_from_async_factory() {
2239        run_with_com_hub(|com_hub, _, _| async move {
2240            let interface_configuration =
2241                ComInterfaceManager::create_interface_async_from_setup_data(
2242                    MockupInterfaceSetupData::new("test"),
2243                )
2244                .await
2245                .unwrap();
2246            let uuid = interface_configuration.uuid().clone();
2247
2248            com_hub
2249                .clone()
2250                .add_interface_from_configuration(
2251                    interface_configuration,
2252                    InterfacePriority::default(),
2253                )
2254                .unwrap();
2255
2256            assert!(com_hub.remove_interface(&uuid).await.is_ok());
2257        })
2258        .await;
2259    }
2260
2261    #[tokio::test]
2262    async fn create_hello_connection() {
2263        run_with_coupled_com_hubs(async |a, b| {
2264            let com_hub_a_sockets =
2265                get_endpoints_from_com_hub_metadata(a.com_hub.get_metadata());
2266            assert!(
2267                com_hub_a_sockets
2268                    .contains(&(Some(TEST_ENDPOINT_B.clone()), Some(1)))
2269            );
2270
2271            let com_hub_b_sockets =
2272                get_endpoints_from_com_hub_metadata(b.com_hub.get_metadata());
2273            assert!(
2274                com_hub_b_sockets
2275                    .contains(&(Some(TEST_ENDPOINT_A.clone()), Some(1)))
2276            );
2277        })
2278        .await;
2279    }
2280
2281    #[tokio::test]
2282    pub async fn send() {
2283        run_with_com_hub_and_proxy_interface(
2284            async move |com_hub, _, mut outgoing_block_receiver, _, _| {
2285                // send block via com hub to proxy interface
2286                let mut block = DXBBlock::new_with_body(b"Hello world!");
2287                block.set_receivers(vec![TEST_ENDPOINT_B.clone()]);
2288                com_hub.send_own_block_async(block).await.unwrap();
2289
2290                // hello block, skip
2291                outgoing_block_receiver.next().await.unwrap();
2292
2293                // get next outgoing block that was sent via the proxy interface
2294                let outgoing_block =
2295                    outgoing_block_receiver.next().await.unwrap();
2296                assert_eq!(outgoing_block.body, b"Hello world!");
2297            },
2298        )
2299        .await;
2300    }
2301
2302    #[tokio::test]
2303    pub async fn send_between_com_hubs() {
2304        run_with_coupled_com_hubs(async |a, mut b| {
2305            // send block via com hub to proxy interface
2306            let mut block = DXBBlock::new_with_body(b"Hello world!");
2307            block.set_receivers(vec![TEST_ENDPOINT_B.clone()]);
2308            a.com_hub.send_own_block_async(block).await.unwrap();
2309
2310            // get received single block on com hub b
2311            let next_block = b.incoming_sections_receiver.next().await.unwrap();
2312            if let IncomingSection::SingleBlock((Some(block), _)) = next_block {
2313                assert_eq!(block.body, b"Hello world!");
2314            } else {
2315                panic!("Expected single block section");
2316            }
2317        })
2318        .await;
2319    }
2320
2321    #[tokio::test]
2322    pub async fn send_block_to_invalid_receiver() {
2323        run_with_com_hub_and_proxy_interface(
2324            async move |com_hub, _, _, _, _| {
2325                let mut block = DXBBlock::new_with_body(b"Hello world!");
2326                // cannot send to endpoint c, since only interface is not a fallback interface and only knows endpoint b
2327                block.set_receivers(vec![TEST_ENDPOINT_C.clone()]);
2328                let res = com_hub.send_own_block_async(block).await;
2329                assert!(res.is_err());
2330            },
2331        )
2332        .await;
2333    }
2334
2335    #[tokio::test]
2336    pub async fn send_block_via_multiple_interfaces() {
2337        run_with_com_hub(|com_hub, _, _| async move {
2338            let (_sender_b, mut outgoing_block_receiver_b) =
2339                add_proxy_interface_to_com_hub(
2340                    com_hub.clone(),
2341                    TEST_ENDPOINT_B.clone(),
2342                )
2343                .await;
2344            let (_sender_c, mut outgoing_block_receiver_c) =
2345                add_proxy_interface_to_com_hub(
2346                    com_hub.clone(),
2347                    TEST_ENDPOINT_C.clone(),
2348                )
2349                .await;
2350            com_hub.print_metadata();
2351
2352            let mut block = DXBBlock::new_with_body(b"Hello world!");
2353            block.set_receivers(vec![
2354                TEST_ENDPOINT_B.clone(),
2355                TEST_ENDPOINT_C.clone(),
2356            ]);
2357            com_hub.send_own_block_async(block).await.unwrap();
2358
2359            // skip hello blocks
2360            outgoing_block_receiver_b.next().await.unwrap();
2361            outgoing_block_receiver_c.next().await.unwrap();
2362
2363            // block should be sent via both interfaces
2364            let outgoing_block_b =
2365                outgoing_block_receiver_b.next().await.unwrap();
2366            let outgoing_block_c =
2367                outgoing_block_receiver_c.next().await.unwrap();
2368
2369            info!("block sender b: {}", outgoing_block_b.sender());
2370            info!("block sender c: {}", outgoing_block_c.sender());
2371            assert_eq!(outgoing_block_b.body, b"Hello world!");
2372            assert_eq!(outgoing_block_c.body, b"Hello world!");
2373        })
2374        .await
2375    }
2376
2377    #[tokio::test]
2378    pub async fn receive() {
2379        flexi_logger::init();
2380        run_with_com_hub_and_proxy_interface(
2381            async move |com_hub,
2382                        mut incoming_data_sender,
2383                        _,
2384                        mut incoming_sections_receiver,
2385                        _| {
2386                // create block and send it via the incoming data sender to the com hub
2387                let mut block = DXBBlock::new_with_body(b"Hello world!");
2388                block.set_receivers(vec![TEST_ENDPOINT_A.clone()]);
2389
2390                let block = com_hub
2391                    .prepare_own_block(block)
2392                    .into_result()
2393                    .await
2394                    .unwrap();
2395
2396                let block_bytes = block.to_bytes();
2397                incoming_data_sender
2398                    .start_send(block_bytes.as_slice().to_vec())
2399                    .unwrap();
2400
2401                let incoming_section =
2402                    incoming_sections_receiver.next().await.unwrap();
2403                if let IncomingSection::SingleBlock((Some(block), _)) =
2404                    incoming_section
2405                {
2406                    assert_eq!(block.raw_bytes.clone().unwrap(), block_bytes);
2407                } else {
2408                    panic!("Expected single block section");
2409                }
2410            },
2411        )
2412        .await;
2413    }
2414
2415    #[tokio::test]
2416    pub async fn receive_multiple_blocks_single_section() {
2417        run_with_com_hub_and_proxy_interface(
2418            async move |com_hub,
2419                        mut incoming_data_sender,
2420                        _,
2421                        mut incoming_sections_receiver,
2422                        _| {
2423                let mut blocks = vec![
2424                    DXBBlock {
2425                        routing_header: RoutingHeader::default(),
2426                        block_header: BlockHeader {
2427                            section_index: 0,
2428                            block_number: 0,
2429                            flags_and_timestamp: FlagsAndTimestamp::new()
2430                                .with_is_end_of_section(false)
2431                                .with_is_end_of_context(false),
2432                            ..Default::default()
2433                        },
2434                        ..Default::default()
2435                    },
2436                    DXBBlock {
2437                        routing_header: RoutingHeader::default(),
2438                        block_header: BlockHeader {
2439                            section_index: 0,
2440                            block_number: 1,
2441                            flags_and_timestamp: FlagsAndTimestamp::new()
2442                                .with_is_end_of_section(false)
2443                                .with_is_end_of_context(false),
2444                            ..Default::default()
2445                        },
2446                        ..Default::default()
2447                    },
2448                    DXBBlock {
2449                        routing_header: RoutingHeader::default(),
2450                        block_header: BlockHeader {
2451                            section_index: 0,
2452                            block_number: 2,
2453                            flags_and_timestamp: FlagsAndTimestamp::new()
2454                                .with_is_end_of_section(true)
2455                                .with_is_end_of_context(true),
2456                            ..Default::default()
2457                        },
2458                        ..Default::default()
2459                    },
2460                ];
2461                let blocks_count = blocks.len();
2462
2463                send_blocks_to_endpoint(
2464                    com_hub.clone(),
2465                    &mut incoming_data_sender,
2466                    TEST_ENDPOINT_A.clone(),
2467                    &mut blocks,
2468                )
2469                .await;
2470
2471                let incoming_blocks =
2472                    get_collected_received_blocks_from_receiver(
2473                        &mut incoming_sections_receiver,
2474                        CollectedBlockType::BlockStream,
2475                        blocks_count,
2476                    )
2477                    .await;
2478
2479                for (incoming_block, block) in
2480                    incoming_blocks.iter().zip(blocks.iter())
2481                {
2482                    assert_eq!(
2483                        incoming_block.raw_bytes.clone().unwrap(),
2484                        block.to_bytes()
2485                    );
2486                }
2487            },
2488        )
2489        .await;
2490    }
2491
2492    #[tokio::test]
2493    pub async fn receive_multiple_separate_blocks() {
2494        run_with_com_hub_and_proxy_interface(
2495            async move |com_hub,
2496                        mut incoming_data_sender,
2497                        _,
2498                        mut incoming_sections_receiver,
2499                        _| {
2500                let mut blocks = vec![
2501                    DXBBlock {
2502                        routing_header: RoutingHeader::default(),
2503                        block_header: BlockHeader {
2504                            section_index: 1,
2505                            block_number: 0,
2506                            ..Default::default()
2507                        },
2508                        ..Default::default()
2509                    },
2510                    DXBBlock {
2511                        routing_header: RoutingHeader::default(),
2512                        block_header: BlockHeader {
2513                            section_index: 2,
2514                            block_number: 0,
2515                            ..Default::default()
2516                        },
2517                        ..Default::default()
2518                    },
2519                    DXBBlock {
2520                        routing_header: RoutingHeader::default(),
2521                        block_header: BlockHeader {
2522                            section_index: 3,
2523                            block_number: 0,
2524                            ..Default::default()
2525                        },
2526                        ..Default::default()
2527                    },
2528                ];
2529                let blocks_count = blocks.len();
2530
2531                send_blocks_to_endpoint(
2532                    com_hub.clone(),
2533                    &mut incoming_data_sender,
2534                    TEST_ENDPOINT_A.clone(),
2535                    &mut blocks,
2536                )
2537                .await;
2538
2539                let incoming_blocks =
2540                    get_collected_received_blocks_from_receiver(
2541                        &mut incoming_sections_receiver,
2542                        CollectedBlockType::SingleBocks,
2543                        blocks_count,
2544                    )
2545                    .await;
2546
2547                for (incoming_block, block) in
2548                    incoming_blocks.iter().zip(blocks.iter())
2549                {
2550                    assert_eq!(
2551                        incoming_block.raw_bytes.clone().unwrap(),
2552                        block.to_bytes()
2553                    );
2554                }
2555            },
2556        )
2557        .await;
2558    }
2559
2560    // #[async_test]
2561    // pub async fn unencrypted_signature_prepare_block_com_hub() {
2562    //     let (com_hub, interface_proxy, mut incoming_sections_receiver) =
2563    //         get_default_mock_setup_with_com_hub().await;
2564    //
2565    //     // receive block
2566    //     let mut block = DXBBlock {
2567    //         body: vec![0x01, 0x02, 0x03],
2568    //         encrypted_header: EncryptedHeader {
2569    //             flags: encrypted_header::Flags::new()
2570    //                 .with_user_agent(encrypted_header::UserAgent::Unused11),
2571    //             ..Default::default()
2572    //         },
2573    //         ..DXBBlock::default()
2574    //     };
2575    //     block.set_receivers(vec![TEST_ENDPOINT_ORIGIN.clone()]);
2576    //     block.recalculate_struct();
2577    //     block
2578    //         .routing_header
2579    //         .flags
2580    //         .set_signature_type(SignatureType::Unencrypted);
2581    //     block = com_hub.prepare_own_block(block).await.unwrap();
2582    //     let block_bytes = block.to_bytes();
2583    //
2584    //     let (_, mut incoming_blocks_sender) =
2585    //         interface_proxy.create_and_init_socket(InterfaceDirection::In, 0);
2586    //     yield_now().await;
2587    //
2588    //     incoming_blocks_sender
2589    //         .start_send(block_bytes.as_slice().to_vec())
2590    //         .unwrap();
2591    //
2592    //     yield_now().await;
2593    //
2594    //     let last_block = get_next_received_single_block_from_receiver(
2595    //         &mut incoming_sections_receiver,
2596    //     )
2597    //     .await;
2598    //     assert_eq!(last_block.raw_bytes.clone().unwrap(), block_bytes);
2599    //     assert_eq!(block.signature, last_block.signature);
2600    //
2601    //     assert!(com_hub.validate_block(&last_block).await.unwrap());
2602    // }
2603    //
2604    // #[async_test]
2605    // pub async fn encrypted_signature_prepare_block_com_hub() {
2606    //     let (com_hub, interface_proxy, mut incoming_sections_receiver) =
2607    //         get_default_mock_setup_with_com_hub().await;
2608    //
2609    //     // receive block
2610    //     let mut block = DXBBlock {
2611    //         body: vec![0x01, 0x02, 0x03],
2612    //         encrypted_header: EncryptedHeader {
2613    //             flags: encrypted_header::Flags::new()
2614    //                 .with_user_agent(encrypted_header::UserAgent::Unused11),
2615    //             ..Default::default()
2616    //         },
2617    //         ..DXBBlock::default()
2618    //     };
2619    //
2620    //     block.set_receivers(vec![TEST_ENDPOINT_ORIGIN.clone()]);
2621    //     block.recalculate_struct();
2622    //
2623    //     block
2624    //         .routing_header
2625    //         .flags
2626    //         .set_signature_type(SignatureType::Encrypted);
2627    //     block = com_hub.prepare_own_block(block).await.unwrap();
2628    //     let block_bytes = block.to_bytes();
2629    //
2630    //     let (_, mut incoming_blocks_sender) =
2631    //         interface_proxy.create_and_init_socket(InterfaceDirection::In, 0);
2632    //     yield_now().await;
2633    //
2634    //     incoming_blocks_sender
2635    //         .start_send(block_bytes.as_slice().to_vec())
2636    //         .unwrap();
2637    //
2638    //     yield_now().await;
2639    //
2640    //     let last_block = get_next_received_single_block_from_receiver(
2641    //         &mut incoming_sections_receiver,
2642    //     )
2643    //     .await;
2644    //     assert_eq!(last_block.raw_bytes.clone().unwrap(), block_bytes);
2645    //     assert_eq!(block.signature, last_block.signature);
2646    //
2647    //     assert!(com_hub.validate_block(&last_block).await.unwrap());
2648    // }
2649    //
2650    //
2651    //
2652    // #[async_test]
2653    // pub async fn reconnect() {
2654    //     let com_hub = create_mock_com_hub();
2655    //
2656    //     // TODO #738: refactor using proxy
2657    //
2658    //     // create a new interface, open it and add it to the com_hub
2659    //     let (base_interface, interface_with_receivers) =
2660    //         ComInterfaceProxy::create_interface(ComInterfaceProperties::default());
2661    //
2662    //     // add base_interface to com_hub
2663    //     com_hub
2664    //         ._register_com_interface(
2665    //             interface_with_receivers,
2666    //             InterfacePriority::default(),
2667    //         )
2668    //         .unwrap();
2669    //
2670    //     // check that the interface is connected
2671    //     assert_eq!(
2672    //         base_interface.state.lock().unwrap().get(),
2673    //         ComInterfaceState::Connected
2674    //     );
2675    //
2676    //     // check that the interface is in the com_hub
2677    //     assert_eq!(com_hub.interface_manager().borrow().interfaces.len(), 2); // loopback + base_interface
2678    //     assert!(com_hub.has_interface(&base_interface.uuid));
2679    //
2680    //     // simulate a disconnection by closing the interface
2681    //     // This action is normally done by the interface itself
2682    //     // but we do it manually here to test the reconnection
2683    //     // TODO #739: reconnect
2684    //     // // check that the interface is not connected
2685    //     // // and that the close_timestamp is set
2686    //     // assert_eq!(
2687    //     //     base_interface.state.lock().unwrap().get(),
2688    //     //     ComInterfaceState::NotConnected
2689    //     // );
2690    //     //
2691    //     // assert!(
2692    //     //     base_interface
2693    //     //         .com_interface
2694    //     //         .properties()
2695    //     //         .close_timestamp
2696    //     //         .is_some()
2697    //     // );
2698    //     //
2699    //     // // the interface should not be reconnected yet
2700    //     // yield_now().await;
2701    //     //
2702    //     // assert_eq!(
2703    //     //     base_interface.com_interface.current_state(),
2704    //     //     ComInterfaceState::NotConnected
2705    //     // );
2706    //     //
2707    //     // // wait for the reconnection to happen
2708    //     // tokio::time::sleep(Duration::from_secs(1)).await;
2709    //     //
2710    //     // // check that the interface is connected again
2711    //     // // and that the close_timestamp is reset
2712    //     // yield_now().await;
2713    //     //
2714    //     // assert_eq!(
2715    //     //     base_interface.com_interface.current_state(),
2716    //     //     ComInterfaceState::Connected
2717    //     // );
2718    // }
2719}