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
use std::fmt::Debug;

use crate::sm::*;

mod benchmark;
use benchmark::Benchmark;
pub use benchmark::{BenchmarkResults, Measurements};

/// Emulates running protocol between local parties
///
/// Takes parties (every party is instance of [StateMachine](crate::sm::StateMachine)) and
/// executes protocol between them. It logs whole process (changing state of party, receiving
/// messages, etc.) in stdout.
///
/// Compared to [AsyncSimulation](super::AsyncSimulation), it's lightweight (doesn't require
/// async runtime), and, more importantly, executes everything in straight order (sequently, without
/// any parallelism). It makes this sumaltion more useful for writing benchmarks that detect
/// performance regression.
///
/// ## Limitations
/// * Currently, it's a bit silly and doesn't support specific [StateMachine](crate::sm::StateMachine)
///   implementations (e.g. it'll panic if SM wants to [proceed](crate::sm::StateMachine::wants_to_proceed),
///   but there are some messages sent by other parties which should be handled)
/// * No proper error handling. It should attach a context to returning error (like current round,
///   what we was doing when error occurred, etc.). The only way to determine error context is to
///   look at stdout and find out what happened from logs.
/// * Logs everything to stdout. No choice.
///
/// ## Example
/// ```no_run
/// # use round_based::StateMachine;
/// # use round_based::dev::Simulation;
/// # trait Builder { fn new(party_i: u16, party_n: u16) -> Self; }
/// # fn is_valid<T>(_: &T) -> bool { true }
/// # fn _test<Party: StateMachine + Builder>() -> Result<(), Party::Err>
/// # where Party: std::fmt::Debug,
/// #       Party::Err: std::fmt::Debug,
/// #       Party::MessageBody: std::fmt::Debug + Clone,
/// # {
/// let results = Simulation::new()
///     .add_party(Party::new(1, 3))    
///     .add_party(Party::new(2, 3))    
///     .add_party(Party::new(3, 3))
///     .run()?;   
/// assert!(results.into_iter().all(|r| is_valid(&r)));
/// # Ok(())
/// # }
/// ```
pub struct Simulation<P> {
    /// Parties running a protocol
    ///
    /// Field is exposed mainly to allow examining parties state after simulation is completed.
    pub parties: Vec<P>,
    benchmark: Option<Benchmark>,
}

impl<P> Simulation<P> {
    /// Creates new simulation
    pub fn new() -> Self {
        Self {
            parties: vec![],
            benchmark: None,
        }
    }

    /// Adds protocol participant
    pub fn add_party(&mut self, party: P) -> &mut Self {
        self.parties.push(party);
        self
    }

    /// Enables benchmarks so they can be [retrieved](Simulation::benchmark_results) after simulation
    /// is completed
    pub fn enable_benchmarks(&mut self, enable: bool) -> &mut Self {
        if enable {
            self.benchmark = Some(Benchmark::new())
        } else {
            self.benchmark = None
        }
        self
    }

    /// Returns benchmark results if they were [enabled](Simulation::enable_benchmarks)
    ///
    /// Benchmarks show how much time (in average) [proceed](StateMachine::proceed) method takes for
    /// proceeding particular rounds. Benchmarks might help to find out which rounds are cheap to
    /// proceed, and which of them are expensive to compute.
    pub fn benchmark_results(&self) -> Option<&BenchmarkResults> {
        self.benchmark.as_ref().map(|b| b.results())
    }
}

impl<P> Simulation<P>
where
    P: StateMachine,
    // Needed for logging:
    P: Debug,
    P::Err: Debug,
    P::MessageBody: Debug,
    // Needed to transmit a single broadcast message to every party:
    P::MessageBody: Clone,
{
    /// Runs a simulation
    ///
    /// ## Returns
    /// Returns either Vec of protocol outputs (one output for each one party) or first
    /// occurred critical error.
    ///
    /// ## Panics
    /// * Number of parties is less than 2
    /// * Party behaves unexpectedly (see [limitations](Simulation#limitations))
    pub fn run(&mut self) -> Result<Vec<P::Output>, P::Err> {
        assert!(self.parties.len() >= 2, "at least two parties required");

        println!("Simulation starts");
        loop {
            let mut msgs: Vec<Msg<P::MessageBody>> = vec![];
            for party in &mut self.parties {
                if party.wants_to_proceed() {
                    println!("Party {} wants to proceed", party.party_ind());
                    println!("  - before: {:?}", party);

                    let round_old = party.current_round();
                    let stopwatch = self.benchmark.as_mut().map(|b| b.start());
                    match party.proceed() {
                        Ok(()) => (),
                        Err(err) if err.is_critical() => return Err(err),
                        Err(err) => {
                            println!("Non-critical error encountered: {:?}", err);
                        }
                    }
                    let round_new = party.current_round();
                    let duration = stopwatch
                        .filter(|_| round_old + 1 == round_new)
                        .map(|s| s.stop_and_save(round_old));

                    println!("  - after : {:?}", party);
                    println!("  - time  : {:?}", duration);
                }

                println!(
                    "Party {} sends {} message(s)",
                    party.party_ind(),
                    party.message_queue().len()
                );
                msgs.append(party.message_queue())
            }

            for party in &mut self.parties {
                let party_i = party.party_ind();
                let msgs = msgs.iter().filter(|m| {
                    m.sender != party_i && (m.receiver.is_none() || m.receiver == Some(party_i))
                });

                for msg in msgs {
                    assert!(
                        !party.wants_to_proceed(),
                        "simulation is silly and doesn't expect party \
                         to wanna proceed at the middle of message handling"
                    );
                    println!(
                        "Party {} got message from={}, broadcast={}: {:?}",
                        party.party_ind(),
                        msg.sender,
                        msg.receiver.is_none(),
                        msg,
                    );
                    println!("  - before: {:?}", party);
                    match party.handle_incoming(msg.clone()) {
                        Ok(()) => (),
                        Err(err) if err.is_critical() => return Err(err),
                        Err(err) => {
                            println!("Non-critical error encountered: {:?}", err);
                        }
                    }
                    println!("  - after : {:?}", party);
                }
            }

            let is_finished = self.parties[0].is_finished();
            let same_answer_for_all_parties =
                self.parties.iter().all(|p| p.is_finished() == is_finished);
            assert!(same_answer_for_all_parties);

            if is_finished {
                let mut results = vec![];
                for party in &mut self.parties {
                    results.push(
                        party
                            .pick_output()
                            .expect("is_finished == true, but pick_output == None")?,
                    )
                }

                break Ok(results);
            }
        }
    }
}