splinter 0.6.14

Splinter is a privacy-focused platform for distributed applications that provides a blockchain-inspired networking environment for communication and transactions between organizations.
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
// Copyright 2018-2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Version 2 of the two-phase commit (2PC) consensus algorithm
//!
//! This is a bully algorithm where the coordinator for a proposal is determined as the node with
//! the lowest ID in the set of verifiers (peers). Only one proposal is considered at a time, and
//! only the coordinator creates new proposals.
//!
//! # Known limitations of this 2PC implementation
//!
//! A limitation of this implementation is that it is not fully resilient to crashes; for instance,
//! if the coordinator commits a proposal but crashes before it is able to send the `APPLY` message
//! to the other nodes, the network will be out of sync because the coordinator does not know to
//! send the message when it restarts. This limitation will be solved by re-implementing 2PC as a
//! stateless algorithm.
//!
//! # Differences from previous version
//!
//! This version of the 2PC implementation differs from the previous version in the following ways:
//!
//! * A custom list of verifiers may no longer be provided by the proposal manager; the verifiers
//!   for each proposal will be the list of all peers + the local node. This means that there is
//!   only one coordinator for all proposals, which solves one of the known limitations of version
//!   1.
//! * Only the coordinator creates new proposals. Because the coordinator determines the order in
//!   which proposals are evaluated and is responsible for determining when to accept them, it is
//!   the only node that can reliably produce proposals that are based on the most current state.

mod timing;

use std::collections::{HashSet, VecDeque};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::Duration;

use protobuf::Message;

use crate::consensus::{
    ConsensusEngine, ConsensusEngineError, ConsensusMessage, ConsensusNetworkSender, PeerId,
    ProposalId, ProposalManager, ProposalUpdate, StartupState,
};
use crate::protos::two_phase::{
    TwoPhaseMessage, TwoPhaseMessage_ProposalResult, TwoPhaseMessage_ProposalVerificationResponse,
    TwoPhaseMessage_Type,
};

use self::timing::Timeout;

const MESSAGE_RECV_TIMEOUT_MILLIS: u64 = 100;
const PROPOSAL_RECV_TIMEOUT_MILLIS: u64 = 100;

#[derive(Debug)]
enum State {
    Idle,
    AwaitingProposal,
    EvaluatingProposal(TwoPhaseProposal),
}

impl State {
    pub fn is_idle(&self) -> bool {
        matches!(self, Self::Idle)
    }

    pub fn is_awaiting_proposal(&self) -> bool {
        matches!(self, Self::AwaitingProposal)
    }

    pub fn is_evaluating_proposal_with_id(&self, proposal_id: &ProposalId) -> bool {
        matches!(
            self,
            Self::EvaluatingProposal(tpc_proposal) if tpc_proposal.proposal_id() == proposal_id,
        )
    }
}

/// Contains information about a proposal that two phase consensus needs to keep track of
#[derive(Debug)]
struct TwoPhaseProposal {
    proposal_id: ProposalId,
    peers_verified: HashSet<PeerId>,
}

impl TwoPhaseProposal {
    fn new(proposal_id: ProposalId) -> Self {
        TwoPhaseProposal {
            proposal_id,
            peers_verified: HashSet::new(),
        }
    }

    fn proposal_id(&self) -> &ProposalId {
        &self.proposal_id
    }

    fn peers_verified(&self) -> &HashSet<PeerId> {
        &self.peers_verified
    }

    fn add_verified_peer(&mut self, id: PeerId) {
        self.peers_verified.insert(id);
    }
}

pub struct TwoPhaseEngine {
    id: PeerId,
    verifiers: HashSet<PeerId>,
    state: State,
    coordinator_timeout: Timeout,
    proposals_received: HashSet<ProposalId>,
    verification_request_backlog: VecDeque<ProposalId>,
}

impl TwoPhaseEngine {
    pub fn new(coordinator_timeout_duration: Duration) -> Self {
        TwoPhaseEngine {
            id: PeerId::default(),
            verifiers: HashSet::new(),
            state: State::Idle,
            coordinator_timeout: Timeout::new(coordinator_timeout_duration),
            proposals_received: HashSet::new(),
            verification_request_backlog: VecDeque::new(),
        }
    }

    /// Determines if this node is the coordinator.
    fn is_coordinator(&self) -> bool {
        &self.id == self.coordinator_id()
    }

    /// Gets the ID of the coordinator. The coordinator is the node with the lowest ID in the set of
    /// verifiers.
    fn coordinator_id(&self) -> &PeerId {
        self.verifiers
            .iter()
            .min()
            .expect("2PC always has at least one verifier (self)")
    }

    fn handle_consensus_msg(
        &mut self,
        consensus_msg: ConsensusMessage,
        network_sender: &dyn ConsensusNetworkSender,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        let two_phase_msg: TwoPhaseMessage = Message::parse_from_bytes(&consensus_msg.message)?;
        let proposal_id = ProposalId::from(two_phase_msg.get_proposal_id());

        match two_phase_msg.get_message_type() {
            TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST => {
                debug!("Proposal verification request received: {}", proposal_id);

                if self.state.is_evaluating_proposal_with_id(&proposal_id) {
                    debug!(
                        "Proposal already in progress, backlogging verification request: {}",
                        proposal_id
                    );
                    self.verification_request_backlog.push_back(proposal_id);
                } else {
                    // Try to get the proposal from the backlog
                    if self.proposals_received.remove(&proposal_id) {
                        debug!("Checking proposal {}", proposal_id);
                        proposal_manager.check_proposal(&proposal_id)?;
                        self.state = State::EvaluatingProposal(TwoPhaseProposal::new(proposal_id));
                    } else {
                        debug!(
                            "Proposal not yet received, backlogging verification request: \
                             {}",
                            proposal_id
                        );
                        self.verification_request_backlog.push_back(proposal_id);
                    }
                }
            }
            TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE => {
                if !self.state.is_evaluating_proposal_with_id(&proposal_id) {
                    warn!(
                        "Received unexpected verification response for proposal {}",
                        proposal_id
                    );
                    return Ok(());
                }

                match two_phase_msg.get_proposal_verification_response() {
                    TwoPhaseMessage_ProposalVerificationResponse::VERIFIED => {
                        debug!(
                            "Proposal {} verified by peer {}",
                            proposal_id, consensus_msg.origin_id
                        );
                        // Already checked state above in self.state.is_evaluating_proposal_with_id
                        if let State::EvaluatingProposal(tpc_proposal) = &mut self.state {
                            tpc_proposal.add_verified_peer(consensus_msg.origin_id);

                            if tpc_proposal.peers_verified() == &self.verifiers {
                                debug!(
                                    "All verifiers have approved; accepting proposal {}",
                                    proposal_id
                                );
                                self.complete_coordination(
                                    proposal_id,
                                    TwoPhaseMessage_ProposalResult::APPLY,
                                    network_sender,
                                    proposal_manager,
                                )?;
                            }
                        }
                    }
                    TwoPhaseMessage_ProposalVerificationResponse::FAILED => {
                        debug!(
                            "Proposal failed by peer {}; rejecting proposal {}",
                            consensus_msg.origin_id, proposal_id
                        );
                        self.complete_coordination(
                            proposal_id,
                            TwoPhaseMessage_ProposalResult::REJECT,
                            network_sender,
                            proposal_manager,
                        )?;
                    }
                    TwoPhaseMessage_ProposalVerificationResponse::UNSET_VERIFICATION_RESPONSE => {
                        warn!(
                            "Ignoring improperly specified proposal verification response from {}",
                            consensus_msg.origin_id
                        )
                    }
                }
            }
            TwoPhaseMessage_Type::PROPOSAL_RESULT => match two_phase_msg.get_proposal_result() {
                TwoPhaseMessage_ProposalResult::APPLY => {
                    if self.state.is_evaluating_proposal_with_id(&proposal_id) {
                        debug!("Accepting proposal {}", proposal_id);
                        proposal_manager.accept_proposal(&proposal_id, None)?;
                        self.state = State::Idle;
                    } else {
                        warn!(
                            "Received unexpected apply result for proposal {}",
                            proposal_id
                        );
                    }
                }
                TwoPhaseMessage_ProposalResult::REJECT => {
                    debug!("Rejecting proposal {}", proposal_id);
                    proposal_manager.reject_proposal(&proposal_id)?;

                    // Only update state if this was the currently evaluating proposal
                    if self.state.is_evaluating_proposal_with_id(&proposal_id) {
                        self.state = State::Idle;
                    }
                }
                TwoPhaseMessage_ProposalResult::UNSET_RESULT => warn!(
                    "Ignoring improperly specified proposal result from {}",
                    consensus_msg.origin_id
                ),
            },
            TwoPhaseMessage_Type::UNSET_TYPE => warn!(
                "Ignoring improperly specified two-phase message from {}",
                consensus_msg.origin_id
            ),
        }

        Ok(())
    }

    fn handle_proposal_update(
        &mut self,
        update: ProposalUpdate,
        network_sender: &dyn ConsensusNetworkSender,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        let is_coordinator = self.is_coordinator();
        match update {
            ProposalUpdate::ProposalCreated(_) if !self.is_coordinator() => {
                warn!("Received ProposalCreated message, but this node is not the coordinator");
            }
            ProposalUpdate::ProposalCreated(_) if !self.state.is_awaiting_proposal() => {
                warn!("Received unexpected ProposalCreated message");
            }
            ProposalUpdate::ProposalCreated(None) => {
                if self.state.is_awaiting_proposal() {
                    self.state = State::Idle;
                }
            }
            ProposalUpdate::ProposalCreated(Some(proposal)) => {
                debug!("Proposal created, starting coordination: {}", proposal.id);
                self.start_coordination(proposal.id, network_sender, proposal_manager)?;
            }
            ProposalUpdate::ProposalReceived(_, peer_id) if &peer_id != self.coordinator_id() => {
                warn!(
                    "Received proposal from a node that is not the coordinator: {}",
                    peer_id
                );
            }
            ProposalUpdate::ProposalReceived(proposal, _) => {
                debug!("Proposal received: {}", proposal.id);
                self.proposals_received.insert(proposal.id);
            }
            ProposalUpdate::ProposalValid(proposal_id) => match &mut self.state {
                State::EvaluatingProposal(tpc_proposal)
                    if tpc_proposal.proposal_id() == &proposal_id =>
                {
                    debug!("Proposal valid: {}", proposal_id);

                    if is_coordinator {
                        tpc_proposal.add_verified_peer(self.id.clone());

                        debug!("Requesting verification of proposal {}", proposal_id);

                        let mut request = TwoPhaseMessage::new();
                        request
                            .set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST);
                        request.set_proposal_id(proposal_id.into());

                        network_sender.broadcast(request.write_to_bytes()?)?;
                    } else {
                        debug!("Sending verified response for proposal {}", proposal_id);

                        let mut response = TwoPhaseMessage::new();
                        response
                            .set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE);
                        response.set_proposal_id(proposal_id.into());
                        response.set_proposal_verification_response(
                            TwoPhaseMessage_ProposalVerificationResponse::VERIFIED,
                        );

                        network_sender
                            .send_to(self.coordinator_id(), response.write_to_bytes()?)?;
                    }
                }
                _ => warn!("Got valid message for unknown proposal: {}", proposal_id),
            },
            ProposalUpdate::ProposalInvalid(proposal_id) => {
                if self.state.is_evaluating_proposal_with_id(&proposal_id) {
                    debug!("Proposal invalid: {}", proposal_id);

                    if is_coordinator {
                        debug!("Rejecting proposal {}", proposal_id);
                        self.complete_coordination(
                            proposal_id,
                            TwoPhaseMessage_ProposalResult::REJECT,
                            network_sender,
                            proposal_manager,
                        )?;
                    } else {
                        debug!("Sending failed response for proposal {}", proposal_id);

                        let mut response = TwoPhaseMessage::new();
                        response
                            .set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE);
                        response.set_proposal_id(proposal_id.into());
                        response.set_proposal_verification_response(
                            TwoPhaseMessage_ProposalVerificationResponse::FAILED,
                        );

                        network_sender
                            .send_to(self.coordinator_id(), response.write_to_bytes()?)?;
                    }
                } else {
                    warn!("Got invalid message for unknown proposal: {}", proposal_id);
                }
            }
            ProposalUpdate::ProposalAccepted(proposal_id) => {
                info!("proposal accepted: {}", proposal_id);
            }
            ProposalUpdate::ProposalAcceptFailed(proposal_id, err) => {
                error!(
                    "failed to accept proposal {} due to error: {}",
                    proposal_id, err
                );
            }
            other => {
                debug!("ignoring update: {:?}", other);
            }
        }

        Ok(())
    }

    fn start_coordination(
        &mut self,
        proposal_id: ProposalId,
        network_sender: &dyn ConsensusNetworkSender,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        debug!("Checking proposal {}", proposal_id);
        match proposal_manager.check_proposal(&proposal_id) {
            Ok(_) => {
                self.state = State::EvaluatingProposal(TwoPhaseProposal::new(proposal_id));
                self.coordinator_timeout.start();
            }
            Err(err) => {
                debug!(
                    "Rejecting proposal {}; failed to check proposal due to err: {}",
                    proposal_id, err
                );
                self.complete_coordination(
                    proposal_id,
                    TwoPhaseMessage_ProposalResult::REJECT,
                    network_sender,
                    proposal_manager,
                )?;
            }
        }
        Ok(())
    }

    fn complete_coordination(
        &mut self,
        proposal_id: ProposalId,
        proposal_result: TwoPhaseMessage_ProposalResult,
        network_sender: &dyn ConsensusNetworkSender,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        match proposal_result {
            TwoPhaseMessage_ProposalResult::APPLY => {
                proposal_manager.accept_proposal(&proposal_id, None)?;
            }
            TwoPhaseMessage_ProposalResult::REJECT => {
                proposal_manager.reject_proposal(&proposal_id)?;
            }
            TwoPhaseMessage_ProposalResult::UNSET_RESULT => {
                warn!(
                    "Unset proposal result when completing proposal {}",
                    proposal_id
                );
                return Ok(());
            }
        }

        self.state = State::Idle;
        self.coordinator_timeout.stop();

        let mut result = TwoPhaseMessage::new();
        result.set_message_type(TwoPhaseMessage_Type::PROPOSAL_RESULT);
        result.set_proposal_id(proposal_id.into());
        result.set_proposal_result(proposal_result);

        network_sender.broadcast(result.write_to_bytes()?)?;

        Ok(())
    }

    /// If the coordinator timeout has expired, abort the current proposal.
    fn abort_proposal_if_timed_out(
        &mut self,
        network_sender: &dyn ConsensusNetworkSender,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        if let State::EvaluatingProposal(ref tpc_proposal) = self.state {
            if self.coordinator_timeout.check_expired() {
                warn!(
                    "Proposal timed out; rejecting: {}",
                    tpc_proposal.proposal_id()
                );
                let proposal_id = tpc_proposal.proposal_id().clone();
                self.complete_coordination(
                    proposal_id,
                    TwoPhaseMessage_ProposalResult::REJECT,
                    network_sender,
                    proposal_manager,
                )?;
            }
        }

        Ok(())
    }

    /// If not doing anything, see if there are any backlogged verification requests that this node
    /// has received a proposal for, and evaluate that proposal.
    fn handle_backlogged_verification_request(
        &mut self,
        proposal_manager: &dyn ProposalManager,
    ) -> Result<(), ConsensusEngineError> {
        if self.state.is_idle() {
            if let Some(idx) = self
                .verification_request_backlog
                .iter()
                .position(|proposal_id| self.proposals_received.contains(proposal_id))
            {
                let proposal_id = self.verification_request_backlog.remove(idx).unwrap();
                self.proposals_received.remove(&proposal_id);

                debug!("Checking proposal from backlog: {}", proposal_id);
                proposal_manager.check_proposal(&proposal_id)?;
                self.state = State::EvaluatingProposal(TwoPhaseProposal::new(proposal_id));
            }
        }

        Ok(())
    }

    /// If this node is the coordinator and it's not doing anything, try to get the next proposal.
    fn get_next_proposal(&mut self, proposal_manager: &dyn ProposalManager) {
        if self.is_coordinator() && self.state.is_idle() {
            match proposal_manager.create_proposal(None, vec![]) {
                Ok(()) => self.state = State::AwaitingProposal,
                Err(err) => debug!("Error while creating proposal: {}", err),
            }
        }
    }
}

impl ConsensusEngine for TwoPhaseEngine {
    fn name(&self) -> &str {
        "two-phase"
    }

    fn version(&self) -> &str {
        "0.1"
    }

    fn additional_protocols(&self) -> Vec<(String, String)> {
        vec![]
    }

    fn run(
        &mut self,
        consensus_messages: Receiver<ConsensusMessage>,
        proposal_updates: Receiver<ProposalUpdate>,
        network_sender: Box<dyn ConsensusNetworkSender>,
        proposal_manager: Box<dyn ProposalManager>,
        startup_state: StartupState,
    ) -> Result<(), ConsensusEngineError> {
        let message_timeout = Duration::from_millis(MESSAGE_RECV_TIMEOUT_MILLIS);
        let proposal_timeout = Duration::from_millis(PROPOSAL_RECV_TIMEOUT_MILLIS);

        self.id = startup_state.id;
        self.verifiers.insert(self.id.clone()); // This node is a verifier

        for id in startup_state.peer_ids {
            self.verifiers.insert(id);
        }

        loop {
            if let Err(err) = self.abort_proposal_if_timed_out(&*network_sender, &*proposal_manager)
            {
                error!("Failed to abort timed-out proposal: {}", err);
            }

            if let Err(err) = self.handle_backlogged_verification_request(&*proposal_manager) {
                error!("Failed to handle backlogged verification request: {}", err);
            }

            self.get_next_proposal(&*proposal_manager);

            // Get and handle a consensus message if there is one
            match consensus_messages.recv_timeout(message_timeout) {
                Ok(consensus_message) => {
                    if let Err(err) = self.handle_consensus_msg(
                        consensus_message,
                        &*network_sender,
                        &*proposal_manager,
                    ) {
                        error!("error while handling consensus message: {}", err);
                    }
                }
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) => {
                    info!("consensus message receiver disconnected");
                    break;
                }
            }

            // Get and handle a proposal update if there is one
            match proposal_updates.recv_timeout(proposal_timeout) {
                Ok(ProposalUpdate::Shutdown) => {
                    info!("received shutdown");
                    break;
                }
                Ok(update) => {
                    if let Err(err) =
                        self.handle_proposal_update(update, &*network_sender, &*proposal_manager)
                    {
                        error!("error while handling proposal update: {}", err);
                    }
                }
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) => {
                    info!("proposal update receiver disconnected");
                    break;
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;

    use std::iter::FromIterator;
    use std::sync::mpsc::channel;

    use crate::consensus::tests::{MockConsensusNetworkSender, MockProposalManager};
    use crate::consensus::Proposal;

    const COORDINATOR_TIMEOUT_MILLIS: u64 = 5000;

    /// Verify that the engine properly shuts down when it receives the Shutdown update.
    #[test]
    fn test_shutdown() {
        let (update_tx, update_rx) = channel();
        let (_, consensus_msg_rx) = channel();

        let manager = MockProposalManager::new(update_tx.clone());
        let network = MockConsensusNetworkSender::new();
        let startup_state = StartupState {
            id: vec![0].into(),
            peer_ids: vec![vec![1].into()],
            last_proposal: None,
        };

        let mut engine = TwoPhaseEngine::new(Duration::from_millis(COORDINATOR_TIMEOUT_MILLIS));
        let thread = std::thread::spawn(move || {
            engine
                .run(
                    consensus_msg_rx,
                    update_rx,
                    Box::new(network),
                    Box::new(manager),
                    startup_state,
                )
                .expect("engine failed")
        });

        update_tx
            .send(ProposalUpdate::Shutdown)
            .expect("failed to send shutdown");
        thread.join().expect("failed to join engine thread");
    }

    /// Verify the `coordinator_id` and `is_coordinator` methods work correctly.
    #[test]
    fn test_coordinator_check() {
        let peer_ids: Vec<PeerId> = vec![vec![0].into(), vec![1].into(), vec![2].into()];
        let peer_ids_hashset = HashSet::from_iter(peer_ids.iter().cloned());

        let coordinator = TwoPhaseEngine {
            id: peer_ids[0].clone(),
            verifiers: peer_ids_hashset.clone(),
            state: State::Idle,
            coordinator_timeout: Timeout::new(Duration::from_millis(COORDINATOR_TIMEOUT_MILLIS)),
            proposals_received: HashSet::new(),
            verification_request_backlog: VecDeque::new(),
        };
        assert_eq!(coordinator.coordinator_id(), &peer_ids[0]);
        assert!(coordinator.is_coordinator());

        let other_node = TwoPhaseEngine {
            id: peer_ids[1].clone(),
            verifiers: peer_ids_hashset,
            state: State::Idle,
            coordinator_timeout: Timeout::new(Duration::from_millis(COORDINATOR_TIMEOUT_MILLIS)),
            proposals_received: HashSet::new(),
            verification_request_backlog: VecDeque::new(),
        };
        assert_eq!(other_node.coordinator_id(), &peer_ids[0]);
        assert!(!other_node.is_coordinator());
    }

    /// Test the coordinator (leader) of a 3 node network by simulating the flow of a valid
    /// proposal (both participants verify the proposal) and a failed proposal (one participant
    /// fails the proposal).
    #[test]
    fn test_coordinator() {
        let (update_tx, update_rx) = channel();
        let (consensus_msg_tx, consensus_msg_rx) = channel();

        let manager = MockProposalManager::new(update_tx.clone());
        let network = MockConsensusNetworkSender::new();
        let startup_state = StartupState {
            id: vec![0].into(),
            peer_ids: vec![vec![1].into(), vec![2].into()],
            last_proposal: None,
        };

        let mut engine = TwoPhaseEngine::new(Duration::from_millis(COORDINATOR_TIMEOUT_MILLIS));
        let network_clone = network.clone();
        let manager_clone = manager.clone();
        let thread = std::thread::spawn(move || {
            engine
                .run(
                    consensus_msg_rx,
                    update_rx,
                    Box::new(network_clone),
                    Box::new(manager_clone),
                    startup_state,
                )
                .expect("engine failed")
        });

        // Check that verification request is sent for the first proposal
        loop {
            if let Some(msg) = network.broadcast_messages().get(0) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST
                );
                assert_eq!(msg.get_proposal_id(), vec![1].as_slice());
                break;
            }
        }

        // Receive the verification responses
        let mut response = TwoPhaseMessage::new();
        response.set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE);
        response.set_proposal_id(vec![1]);
        response.set_proposal_verification_response(
            TwoPhaseMessage_ProposalVerificationResponse::VERIFIED,
        );
        let message_bytes = response
            .write_to_bytes()
            .expect("failed to write failed response to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes.clone(), vec![1].into()))
            .expect("failed to send 1st response");
        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![2].into()))
            .expect("failed to send 2nd response");

        // Verify the Apply message is sent for the proposal
        loop {
            if let Some(msg) = network.broadcast_messages().get(1) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_RESULT
                );
                assert_eq!(
                    msg.get_proposal_result(),
                    TwoPhaseMessage_ProposalResult::APPLY
                );
                assert_eq!(msg.get_proposal_id(), vec![1].as_slice());
                break;
            }
        }

        // Verify the proposal was accepted
        loop {
            if let Some((id, _)) = manager.accepted_proposals().get(0) {
                assert_eq!(id, &vec![1].into());
                break;
            }
        }

        // Check that verification request is sent for the second proposal
        loop {
            if let Some(msg) = network.broadcast_messages().get(2) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST
                );
                assert_eq!(msg.get_proposal_id(), vec![2].as_slice());
                break;
            }
        }

        // Receive the verification responses
        let mut response = TwoPhaseMessage::new();
        response.set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE);
        response.set_proposal_id(vec![2]);
        response.set_proposal_verification_response(
            TwoPhaseMessage_ProposalVerificationResponse::VERIFIED,
        );
        let message_bytes = response
            .write_to_bytes()
            .expect("failed to write failed response to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![1].into()))
            .expect("failed to send 1st response");

        let mut response = TwoPhaseMessage::new();
        response.set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE);
        response.set_proposal_id(vec![2]);
        response.set_proposal_verification_response(
            TwoPhaseMessage_ProposalVerificationResponse::FAILED,
        );
        let message_bytes = response
            .write_to_bytes()
            .expect("failed to write failed response to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![2].into()))
            .expect("failed to send 2nd response");

        // Verify the Reject message is sent for the proposal
        loop {
            if let Some(msg) = network.broadcast_messages().get(3) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_RESULT
                );
                assert_eq!(
                    msg.get_proposal_result(),
                    TwoPhaseMessage_ProposalResult::REJECT
                );
                assert_eq!(msg.get_proposal_id(), vec![2].as_slice());
                break;
            }
        }

        // Verify the proposal was rejected
        loop {
            if let Some(id) = manager.rejected_proposals().get(0) {
                assert_eq!(id, &vec![2].into());
                break;
            }
        }

        update_tx
            .send(ProposalUpdate::Shutdown)
            .expect("failed to send shutdown");
        thread.join().expect("failed to join engine thread");
    }

    /// Test a participant (follower) by simulating the flow of a valid and a failed proposal.
    #[test]
    fn test_participant() {
        let (update_tx, update_rx) = channel();
        let (consensus_msg_tx, consensus_msg_rx) = channel();

        let manager = MockProposalManager::new(update_tx.clone());
        manager.set_return_proposal(false);
        let network = MockConsensusNetworkSender::new();
        let startup_state = StartupState {
            id: vec![1].into(),
            peer_ids: vec![vec![0].into()],
            last_proposal: None,
        };

        let mut engine = TwoPhaseEngine::new(Duration::from_millis(COORDINATOR_TIMEOUT_MILLIS));
        let network_clone = network.clone();
        let manager_clone = manager.clone();
        let thread = std::thread::spawn(move || {
            engine
                .run(
                    consensus_msg_rx,
                    update_rx,
                    Box::new(network_clone),
                    Box::new(manager_clone),
                    startup_state,
                )
                .expect("engine failed")
        });

        // Receive the first proposal
        let mut proposal = Proposal::default();
        proposal.id = vec![1].into();
        update_tx
            .send(ProposalUpdate::ProposalReceived(proposal, vec![0].into()))
            .expect("failed to send 1st proposal");

        // Receive the first verification request
        let mut request = TwoPhaseMessage::new();
        request.set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST);
        request.set_proposal_id(vec![1]);
        let message_bytes = request
            .write_to_bytes()
            .expect("failed to write request to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![0].into()))
            .expect("failed to send 1st verification request");

        // Check that the Verified verification response is sent
        loop {
            if let Some((msg, peer_id)) = network.sent_messages().get(0) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(peer_id, &vec![0].into());
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE
                );
                assert_eq!(
                    msg.get_proposal_verification_response(),
                    TwoPhaseMessage_ProposalVerificationResponse::VERIFIED
                );
                assert_eq!(msg.get_proposal_id(), vec![1].as_slice());
                break;
            }
        }

        // Receive the Apply result
        let mut result = TwoPhaseMessage::new();
        result.set_message_type(TwoPhaseMessage_Type::PROPOSAL_RESULT);
        result.set_proposal_id(vec![1]);
        result.set_proposal_result(TwoPhaseMessage_ProposalResult::APPLY);
        let message_bytes = result
            .write_to_bytes()
            .expect("failed to write apply result to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![0].into()))
            .expect("failed to send apply result");

        // Verify the proposal was accepted
        loop {
            if let Some((id, _)) = manager.accepted_proposals().get(0) {
                assert_eq!(id, &vec![1].into());
                break;
            }
        }

        // Receive the second proposal
        let mut proposal = Proposal::default();
        proposal.id = vec![2].into();
        update_tx
            .send(ProposalUpdate::ProposalReceived(proposal, vec![0].into()))
            .expect("failed to send 2nd proposal");

        // Receive the second verification request (the manager will say this proposal is invalid)
        manager.set_next_proposal_valid(false);

        let mut request = TwoPhaseMessage::new();
        request.set_message_type(TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST);
        request.set_proposal_id(vec![2]);
        let message_bytes = request
            .write_to_bytes()
            .expect("failed to write request to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![0].into()))
            .expect("failed to send 2nd verification request");

        // Check that the Failed verification response is sent
        loop {
            if let Some((msg, peer_id)) = network.sent_messages().get(1) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(peer_id, &vec![0].into());
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_RESPONSE
                );
                assert_eq!(
                    msg.get_proposal_verification_response(),
                    TwoPhaseMessage_ProposalVerificationResponse::FAILED
                );
                assert_eq!(msg.get_proposal_id(), vec![2].as_slice());
                break;
            }
        }

        // Receive the Reject result
        let mut result = TwoPhaseMessage::new();
        result.set_message_type(TwoPhaseMessage_Type::PROPOSAL_RESULT);
        result.set_proposal_id(vec![2]);
        result.set_proposal_result(TwoPhaseMessage_ProposalResult::REJECT);
        let message_bytes = result
            .write_to_bytes()
            .expect("failed to write reject result to bytes");

        consensus_msg_tx
            .send(ConsensusMessage::new(message_bytes, vec![0].into()))
            .expect("failed to send reject result");

        // Verify the proposal was rejected
        loop {
            if let Some(id) = manager.rejected_proposals().get(0) {
                assert_eq!(id, &vec![2].into());
                break;
            }
        }

        update_tx
            .send(ProposalUpdate::Shutdown)
            .expect("failed to send shutdown");
        thread.join().expect("failed to join engine thread");
    }

    /// Test that the coordinator will abort a commit if the coordinator timeout expires while
    /// evaluating the commit.
    #[test]
    fn test_coordinator_timeout() {
        let (update_tx, update_rx) = channel();
        let (_consensus_msg_tx, consensus_msg_rx) = channel();

        let manager = MockProposalManager::new(update_tx.clone());
        let network = MockConsensusNetworkSender::new();
        let startup_state = StartupState {
            id: vec![0].into(),
            peer_ids: vec![vec![1].into(), vec![2].into()],
            last_proposal: None,
        };

        // Start engine with a very short coordinator timeout
        let mut engine = TwoPhaseEngine::new(Duration::from_millis(10));
        let network_clone = network.clone();
        let manager_clone = manager.clone();
        let thread = std::thread::spawn(move || {
            engine
                .run(
                    consensus_msg_rx,
                    update_rx,
                    Box::new(network_clone),
                    Box::new(manager_clone),
                    startup_state,
                )
                .expect("engine failed")
        });

        // Check that a proposal verification request is sent
        loop {
            if let Some(msg) = network.broadcast_messages().get(0) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_VERIFICATION_REQUEST
                );
                assert_eq!(msg.get_proposal_id(), vec![1].as_slice());
                break;
            }
        }

        // Verify the Reject message is sent for the proposal (due to the timeout)
        loop {
            if let Some(msg) = network.broadcast_messages().get(1) {
                let msg: TwoPhaseMessage =
                    Message::parse_from_bytes(msg).expect("failed to parse message");
                assert_eq!(
                    msg.get_message_type(),
                    TwoPhaseMessage_Type::PROPOSAL_RESULT
                );
                assert_eq!(
                    msg.get_proposal_result(),
                    TwoPhaseMessage_ProposalResult::REJECT
                );
                assert_eq!(msg.get_proposal_id(), vec![1].as_slice());
                break;
            }
        }

        // Verify the proposal was rejected
        loop {
            if let Some(id) = manager.rejected_proposals().get(0) {
                assert_eq!(id, &vec![1].into());
                break;
            }
        }

        update_tx
            .send(ProposalUpdate::Shutdown)
            .expect("failed to send shutdown");
        thread.join().expect("failed to join engine thread");
    }
}