1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright (c) 2021 Open Community Project Association https://ocpa.ch
// This software is published under the AGPLv3 license.

//! # Qaul Messaging Behaviour
//!
//! This module is a libp2p swarm-behaviour module.
//! It manages and defines the messaging exchange protocol.

pub mod protocol;
pub mod types;

use libp2p::{
    core::{connection::ConnectionId, Multiaddr, PeerId},
    swarm::{
        NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, OneShotHandler, PollParameters,
    },
};
use std::{
    collections::VecDeque,
    task::{Context, Poll},
};

pub use crate::types::{QaulMessagingData, QaulMessagingReceived, QaulMessagingSend};
use protocol::QaulMessagingProtocol;

/// Network behaviour that handles the qaul_messaging protocol.
pub struct QaulMessaging {
    /// Events that need to be handed to the outside when polling.
    events: VecDeque<
        NetworkBehaviourAction<
            QaulMessagingEvent,
            <QaulMessaging as NetworkBehaviour>::ConnectionHandler,
        >,
    >,
    #[allow(dead_code)]
    config: QaulMessagingConfig,
}

impl QaulMessaging {
    /// Creates a `QaulMessaging` with default configuration.
    pub fn new(local_peer_id: PeerId) -> Self {
        Self::from_config(QaulMessagingConfig::new(local_peer_id))
    }

    /// Creates a `QaulMessaging` with the given configuration.
    pub fn from_config(config: QaulMessagingConfig) -> Self {
        QaulMessaging {
            events: VecDeque::new(),
            config,
        }
    }

    /// Send a QaulMessagingMessage to a specific node
    pub fn send_qaul_messaging_message(&mut self, node_id: PeerId, data: Vec<u8>) {
        // create event message
        let message = QaulMessagingData { data };

        // Schedule message for sending
        self.events
            .push_back(NetworkBehaviourAction::NotifyHandler {
                peer_id: node_id,
                handler: NotifyHandler::Any,
                event: message,
            });
    }
}

impl NetworkBehaviour for QaulMessaging {
    type ConnectionHandler = OneShotHandler<QaulMessagingProtocol, QaulMessagingData, InnerMessage>;
    type OutEvent = QaulMessagingEvent;

    fn new_handler(&mut self) -> Self::ConnectionHandler {
        Default::default()
    }

    fn addresses_of_peer(&mut self, _id: &PeerId) -> Vec<Multiaddr> {
        Vec::new()
    }

    fn inject_connection_established(
        &mut self,
        _peer_id: &PeerId,
        _connection_id: &ConnectionId,
        _endpoint: &libp2p::core::ConnectedPoint,
        _failed_addresses: Option<&Vec<Multiaddr>>,
        _other_established: usize,
    ) {
        // should we inform qaul messaging?
    }

    fn inject_connection_closed(
        &mut self,
        _: &PeerId,
        _: &ConnectionId,
        _: &libp2p::core::ConnectedPoint,
        _: <Self::ConnectionHandler as libp2p::swarm::IntoConnectionHandler>::Handler,
        _remaining_established: usize,
    ) {
        // should we inform qaul messaging?
    }

    fn inject_event(
        &mut self,
        received_from: PeerId,
        _connection: ConnectionId,
        event: InnerMessage,
    ) {
        // We received one of the following event notification
        let qaul_messaging_data = match event {
            // only process a received message
            InnerMessage::Received(event) => event,
            // ignore the sent event
            InnerMessage::Sent => return,
        };

        // forward the message to the user
        self.events.push_back(NetworkBehaviourAction::GenerateEvent(
            QaulMessagingEvent::Message(QaulMessagingReceived {
                received_from,
                data: qaul_messaging_data.data,
            }),
        ));
    }

    fn poll(
        &mut self,
        _: &mut Context<'_>,
        _: &mut impl PollParameters,
    ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
        if let Some(event) = self.events.pop_front() {
            return Poll::Ready(event);
        }

        Poll::Pending
    }
}

/// Transmission between the `OneShotHandler` of the protocols handler
/// and the `QaulMessagingHandler`.
#[derive(Debug)]
pub enum InnerMessage {
    /// We received an QaulMessagingMessage from a remote.
    Received(QaulMessagingData),
    /// We successfully sent an QaulMessagingMessage request.
    Sent,
}

impl From<QaulMessagingData> for InnerMessage {
    #[inline]
    fn from(remote: QaulMessagingData) -> InnerMessage {
        InnerMessage::Received(remote)
    }
}

impl From<()> for InnerMessage {
    #[inline]
    fn from(_: ()) -> InnerMessage {
        InnerMessage::Sent
    }
}

/// Event that can happen on the qaul_messaging behaviour.
#[derive(Debug)]
pub enum QaulMessagingEvent {
    /// A message has been received.
    Message(QaulMessagingReceived),
}

/// Configuration options for the qaul messaging behaviour
pub struct QaulMessagingConfig {
    /// Peer id of the local node. Used for the source of the messages that we publish.
    pub local_peer_id: PeerId,
}

impl QaulMessagingConfig {
    pub fn new(local_peer_id: PeerId) -> Self {
        Self { local_peer_id }
    }
}