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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! Instruments for executing protocol in async environment

use std::fmt::{self, Debug};
use std::future::Future;

use futures::future::{Either, FutureExt};
use futures::sink::Sink;
use futures::stream::{self, FusedStream, Stream, StreamExt};
use futures::SinkExt;
use tokio::time::{self, timeout_at};

use crate::{IsCritical, Msg, StateMachine};
use watcher::{BlindWatcher, ProtocolWatcher, When};

pub mod watcher;

/// Executes protocol in async environment using [tokio] backend
///
/// In the most simple setting, you just provide protocol initial state, stream of incoming
/// messages, and sink for outcoming messages, and you're able to easily execute it:
/// ```no_run
/// # use futures::stream::{self, Stream, FusedStream};
/// # use futures::sink::{self, Sink, SinkExt};
/// # use round_based::{Msg, StateMachine, AsyncProtocol};
/// # struct M;
/// # #[derive(Debug)] struct Error;
/// # impl From<std::convert::Infallible> for Error {
/// #    fn from(_: std::convert::Infallible) -> Error { Error }
/// # }
/// # trait Constructable { fn initial() -> Self; }
/// fn incoming() -> impl Stream<Item=Result<Msg<M>, Error>> + FusedStream + Unpin {
///     // ...
/// # stream::pending()
/// }
/// fn outcoming() -> impl Sink<Msg<M>, Error=Error> + Unpin {
///     // ...
/// # sink::drain().with(|x| futures::future::ok(x))
/// }
/// # async fn execute_protocol<State>() -> Result<(), round_based::async_runtime::Error<State::Err, Error, Error>>
/// # where State: StateMachine<MessageBody = M, Err = Error> + Constructable + Send + 'static
/// # {
/// let output: State::Output = AsyncProtocol::new(State::initial(), incoming(), outcoming())
///     .run().await?;
/// // ...
/// # let _ = output; Ok(())
/// # }
/// ```
///
/// Note that in most cases it's your responsibility to provide a secure P2P channels to every
/// party.
pub struct AsyncProtocol<SM, I, O, W = BlindWatcher> {
    state: Option<SM>,
    incoming: I,
    outcoming: O,
    deadline: Option<time::Instant>,
    current_round: Option<u16>,
    watcher: W,
}

impl<SM, I, O> AsyncProtocol<SM, I, O, BlindWatcher> {
    /// Construct new executor from protocol initial state, channels of incoming and outcoming
    /// messages
    pub fn new(state: SM, incoming: I, outcoming: O) -> Self {
        Self {
            state: Some(state),
            incoming,
            outcoming,
            deadline: None,
            current_round: None,
            watcher: BlindWatcher,
        }
    }
}

impl<SM, I, O, W> AsyncProtocol<SM, I, O, W> {
    /// Sets new protocol watcher
    ///
    /// Protocol watcher looks after protocol execution. See list of observable events in
    /// [ProtocolWatcher] trait.
    ///
    /// Default watcher: [BlindWatcher] that does nothing with received events. For development
    /// purposes it's convenient to pick [StderrWatcher](watcher::StderrWatcher).
    pub fn set_watcher<WR>(self, watcher: WR) -> AsyncProtocol<SM, I, O, WR> {
        AsyncProtocol {
            state: self.state,
            incoming: self.incoming,
            outcoming: self.outcoming,
            deadline: self.deadline,
            current_round: self.current_round,
            watcher,
        }
    }
}

impl<SM, I, O, IErr, W> AsyncProtocol<SM, I, O, W>
where
    SM: StateMachine,
    SM::Err: Send,
    SM: Send + 'static,
    I: Stream<Item = Result<Msg<SM::MessageBody>, IErr>> + FusedStream + Unpin,
    O: Sink<Msg<SM::MessageBody>> + Unpin,
    W: ProtocolWatcher<SM>,
{
    /// Executes the protocol
    ///
    /// Returns protocol output or first occurred critical error
    pub async fn run(&mut self) -> Result<SM::Output, Error<SM::Err, IErr, O::Error>> {
        if self.current_round.is_some() {
            return Err(Error::Exhausted);
        }

        self.refresh_timer()?;
        self.proceed_if_needed().await?;
        self.send_outcoming().await?;
        self.refresh_timer()?;

        if let Some(result) = self.finish_if_possible() {
            return result;
        }

        loop {
            self.handle_incoming().await?;
            self.send_outcoming().await?;
            self.refresh_timer()?;

            self.proceed_if_needed().await?;
            self.send_outcoming().await?;
            self.refresh_timer()?;

            if let Some(result) = self.finish_if_possible() {
                return result;
            }
        }
    }

    async fn handle_incoming(&mut self) -> Result<(), Error<SM::Err, IErr, O::Error>> {
        let state = self.state.as_mut().ok_or(InternalError::MissingState)?;
        match Self::enforce_timeout(self.deadline, self.incoming.next()).await {
            Ok(Some(Ok(msg))) => match state.handle_incoming(msg) {
                Ok(()) => (),
                Err(err) if err.is_critical() => return Err(Error::HandleIncoming(err)),
                Err(err) => self
                    .watcher
                    .caught_non_critical_error(When::HandleIncoming, err),
            },
            Ok(Some(Err(err))) => return Err(Error::Recv(err)),
            Ok(None) => return Err(Error::RecvEof),
            Err(_) => {
                let err = state.round_timeout_reached();
                return Err(Error::HandleIncomingTimeout(err));
            }
        }
        Ok(())
    }

    async fn proceed_if_needed(&mut self) -> Result<(), Error<SM::Err, IErr, O::Error>> {
        let mut state = self.state.take().ok_or(InternalError::MissingState)?;
        if state.wants_to_proceed() {
            let (result, s) = tokio::task::spawn_blocking(move || (state.proceed(), state))
                .await
                .map_err(Error::ProceedPanicked)?;
            state = s;

            match result {
                Ok(()) => (),
                Err(err) if err.is_critical() => return Err(Error::Proceed(err)),
                Err(err) => self.watcher.caught_non_critical_error(When::Proceed, err),
            }
        }
        self.state = Some(state);
        Ok(())
    }

    async fn send_outcoming(&mut self) -> Result<(), Error<SM::Err, IErr, O::Error>> {
        let state = self.state.as_mut().ok_or(InternalError::MissingState)?;

        if !state.message_queue().is_empty() {
            let mut msgs = stream::iter(state.message_queue().drain(..).map(Ok));
            self.outcoming
                .send_all(&mut msgs)
                .await
                .map_err(Error::Send)?;
        }

        Ok(())
    }

    fn finish_if_possible(&mut self) -> Option<Result<SM::Output, Error<SM::Err, IErr, O::Error>>> {
        let state = match self.state.as_mut() {
            Some(s) => s,
            None => return Some(Err(InternalError::MissingState.into())),
        };
        if !state.is_finished() {
            None
        } else {
            match state.pick_output() {
                Some(Ok(result)) => Some(Ok(result)),
                Some(Err(err)) => Some(Err(Error::Finish(err))),
                None => Some(Err(
                    BadStateMachineReason::ProtocolFinishedButNoResult.into()
                )),
            }
        }
    }

    fn refresh_timer(&mut self) -> Result<(), Error<SM::Err, IErr, O::Error>> {
        let state = self.state.as_mut().ok_or(InternalError::MissingState)?;
        let round_n = state.current_round();
        if self.current_round != Some(round_n) {
            self.current_round = Some(round_n);
            self.deadline = match state.round_timeout() {
                Some(timeout) => Some(time::Instant::now() + timeout),
                None => None,
            }
        }

        Ok(())
    }
    fn enforce_timeout<F>(
        deadline: Option<time::Instant>,
        f: F,
    ) -> impl Future<Output = Result<F::Output, time::error::Elapsed>>
    where
        F: Future,
    {
        match deadline {
            Some(deadline) => Either::Right(timeout_at(deadline, f)),
            None => Either::Left(f.map(Ok)),
        }
    }
}

/// Represents error that can occur while executing protocol
#[derive(Debug)]
#[non_exhaustive]
pub enum Error<E, RE, SE> {
    /// Receiving next incoming message returned error
    Recv(RE),
    /// Incoming channel closed (got EOF)
    RecvEof,
    /// Sending outcoming message resulted in error
    Send(SE),
    /// [Handling incoming](crate::StateMachine::handle_incoming) message produced critical error
    HandleIncoming(E),
    /// Round timeout exceed when executor was waiting for new messages from other parties
    HandleIncomingTimeout(E),
    /// [Proceed method](crate::StateMachine::proceed) panicked
    ProceedPanicked(tokio::task::JoinError),
    /// State machine [proceeding](crate::StateMachine::proceed) produced critical error
    Proceed(E),
    /// StateMachine's [pick_output](crate::StateMachine::pick_output) method return error
    Finish(E),
    /// AsyncProtocol already executed protocol (or at least, tried to) and tired. You need to
    /// construct new executor!
    Exhausted,
    /// Buggy StateMachine implementation
    BadStateMachine(BadStateMachineReason),
    /// Buggy AsyncProtocol implementation!
    ///
    /// If you've got this error, please, report bug.
    InternalError(InternalError),
}

impl<E, RE, SE> From<BadStateMachineReason> for Error<E, RE, SE> {
    fn from(reason: BadStateMachineReason) -> Self {
        Error::BadStateMachine(reason)
    }
}

impl<E, RE, SE> From<InternalError> for Error<E, RE, SE> {
    fn from(err: InternalError) -> Self {
        Error::InternalError(err)
    }
}

impl<E, RE, SE> fmt::Display for Error<E, RE, SE>
where
    E: fmt::Display,
    RE: fmt::Display,
    SE: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Recv(err) => {
                write!(f, "receive next message: {}", err)
            }
            Self::RecvEof => {
                write!(f, "receive next message: unexpected eof")
            }
            Self::Send(err) => {
                write!(f, "send a message: {}", err)
            }
            Self::HandleIncoming(err) => {
                write!(f, "handle received message: {}", err)
            }
            Self::HandleIncomingTimeout(err) => {
                write!(f, "round timeout reached: {}", err)
            }
            Self::ProceedPanicked(err) => {
                write!(f, "proceed round panicked: {}", err)
            }
            Self::Proceed(err) => {
                write!(f, "round proceed error: {}", err)
            }
            Self::Finish(err) => {
                write!(f, "couldn't finish protocol: {}", err)
            }
            Self::Exhausted => {
                write!(f, "async runtime is exhausted")
            }
            Self::BadStateMachine(err) => {
                write!(f, "buggy state machine implementation: {}", err)
            }
            Self::InternalError(err) => {
                write!(f, "internal error: {:?}", err)
            }
        }
    }
}

impl<E, RE, SE> std::error::Error for Error<E, RE, SE>
where
    E: std::error::Error + 'static,
    RE: std::error::Error + 'static,
    SE: std::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Recv(err) => Some(err),
            Self::Send(err) => Some(err),
            Self::HandleIncoming(err) => Some(err),
            Self::HandleIncomingTimeout(err) => Some(err),
            Self::ProceedPanicked(err) => Some(err),
            Self::Proceed(err) => Some(err),
            Self::Finish(err) => Some(err),
            Self::RecvEof => None,
            Self::Exhausted => None,
            Self::BadStateMachine(_) => None,
            Self::InternalError(_) => None,
        }
    }
}

/// Reason why StateMachine implementation looks buggy
#[derive(Debug)]
#[non_exhaustive]
pub enum BadStateMachineReason {
    /// [StateMachine::is_finished](crate::StateMachine::is_finished) returned `true`,
    /// but [StateMachine::pick_output](crate::StateMachine::pick_output) returned `None`
    ProtocolFinishedButNoResult,
}

impl fmt::Display for BadStateMachineReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ProtocolFinishedButNoResult => write!(
                f,
                "couldn't obtain protocol output although it is completed"
            ),
        }
    }
}

/// Describes internal errors that could occur
#[derive(Debug)]
#[non_exhaustive]
pub enum InternalError {
    MissingState,
}