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