-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathround_manager_test.rs
2271 lines (2099 loc) · 70.5 KB
/
round_manager_test.rs
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
// Copyright © Aptos Foundation
// Parts of the project are originally copyright © Meta Platforms, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::{BlockReader, BlockStore},
liveness::{
proposal_generator::{
ChainHealthBackoffConfig, PipelineBackpressureConfig, ProposalGenerator,
},
proposer_election::ProposerElection,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, RoundState},
},
metrics_safety_rules::MetricsSafetyRules,
network::{IncomingBlockRetrievalRequest, NetworkSender},
network_interface::{CommitMessage, ConsensusMsg, ConsensusNetworkClient, DIRECT_SEND, RPC},
network_tests::{NetworkPlayground, TwinId},
payload_manager::PayloadManager,
persistent_liveness_storage::RecoveryData,
pipeline::buffer_manager::OrderedBlocks,
round_manager::RoundManager,
test_utils::{
consensus_runtime, create_vec_signed_transactions, timed_block_on, MockPayloadManager,
MockStateComputer, MockStorage, TreeInserter,
},
util::time_service::{ClockTimeService, TimeService},
};
use aptos_channels::{self, aptos_channel, message_queues::QueueStyle};
use aptos_config::{
config::{ConsensusConfig, QcAggregatorType},
network_id::{NetworkId, PeerNetworkId},
};
use aptos_consensus_types::{
block::{
block_test_utils::{certificate_for_genesis, gen_test_certificate},
Block,
},
block_retrieval::{BlockRetrievalRequest, BlockRetrievalStatus},
common::{Author, Payload, Round},
pipeline::commit_decision::CommitDecision,
proposal_msg::ProposalMsg,
sync_info::SyncInfo,
timeout_2chain::{TwoChainTimeout, TwoChainTimeoutWithPartialSignatures},
vote_msg::VoteMsg,
};
use aptos_crypto::HashValue;
use aptos_infallible::Mutex;
use aptos_logger::prelude::info;
use aptos_network::{
application::interface::NetworkClient,
peer_manager::{conn_notifs_channel, ConnectionRequestSender, PeerManagerRequestSender},
protocols::{
network,
network::{Event, NetworkEvents, NewNetworkEvents, NewNetworkSender},
wire::handshake::v1::ProtocolIdSet,
},
transport::ConnectionMetadata,
ProtocolId,
};
use aptos_safety_rules::{PersistentSafetyStorage, SafetyRulesManager};
use aptos_secure_storage::Storage;
use aptos_types::{
epoch_state::EpochState,
jwks::QuorumCertifiedUpdate,
ledger_info::LedgerInfo,
on_chain_config::{
ConsensusAlgorithmConfig, ConsensusConfigV1, FeatureFlag, Features, OnChainConsensusConfig,
ValidatorTxnConfig,
},
transaction::SignedTransaction,
validator_signer::ValidatorSigner,
validator_txn::ValidatorTransaction,
validator_verifier::{generate_validator_verifier, random_validator_verifier},
waypoint::Waypoint,
};
use futures::{
channel::{mpsc, oneshot},
executor::block_on,
stream::select,
FutureExt, Stream, StreamExt,
};
use futures_channel::mpsc::unbounded;
use maplit::hashmap;
use std::{
iter::FromIterator,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tokio::{
runtime::{Handle, Runtime},
task::JoinHandle,
time::timeout,
};
/// Auxiliary struct that is setting up node environment for the test.
pub struct NodeSetup {
block_store: Arc<BlockStore>,
round_manager: RoundManager,
storage: Arc<MockStorage>,
signer: ValidatorSigner,
proposers: Vec<Author>,
safety_rules_manager: SafetyRulesManager,
pending_network_events: Vec<Event<ConsensusMsg>>,
all_network_events: Box<dyn Stream<Item = Event<ConsensusMsg>> + Send + Unpin>,
ordered_blocks_events: mpsc::UnboundedReceiver<OrderedBlocks>,
mock_state_computer: Arc<MockStateComputer>,
_state_sync_receiver: mpsc::UnboundedReceiver<Vec<SignedTransaction>>,
id: usize,
onchain_consensus_config: OnChainConsensusConfig,
local_consensus_config: ConsensusConfig,
features: Features,
}
impl NodeSetup {
fn create_round_state(time_service: Arc<dyn TimeService>) -> RoundState {
let base_timeout = Duration::new(60, 0);
let time_interval = Box::new(ExponentialTimeInterval::fixed(base_timeout));
let (round_timeout_sender, _) = aptos_channels::new_test(1_024);
let (delayed_qc_tx, _) = unbounded();
RoundState::new(
time_interval,
time_service,
round_timeout_sender,
delayed_qc_tx,
QcAggregatorType::NoDelay,
)
}
fn create_proposer_election(proposers: Vec<Author>) -> Arc<dyn ProposerElection + Send + Sync> {
Arc::new(RotatingProposer::new(proposers, 1))
}
fn create_nodes(
playground: &mut NetworkPlayground,
executor: Handle,
num_nodes: usize,
proposer_indices: Option<Vec<usize>>,
onchain_consensus_config: Option<OnChainConsensusConfig>,
local_consensus_config: Option<ConsensusConfig>,
features: Option<Features>,
) -> Vec<Self> {
let onchain_consensus_config = onchain_consensus_config.unwrap_or_default();
let local_consensus_config = local_consensus_config.unwrap_or_default();
let (signers, validators) = random_validator_verifier(num_nodes, None, false);
let proposers = proposer_indices
.unwrap_or_else(|| vec![0])
.iter()
.map(|i| signers[*i].author())
.collect::<Vec<_>>();
let validator_set = (&validators).into();
let waypoint =
Waypoint::new_epoch_boundary(&LedgerInfo::mock_genesis(Some(validator_set))).unwrap();
let mut nodes = vec![];
// pre-initialize the mapping to avoid race conditions (peer try to broadcast to someone not added yet)
let peers_and_metadata = playground.peer_protocols();
for signer in signers.iter().take(num_nodes) {
let peer_id = signer.author();
let mut conn_meta = ConnectionMetadata::mock(peer_id);
conn_meta.application_protocols = ProtocolIdSet::from_iter([
ProtocolId::ConsensusDirectSendJson,
ProtocolId::ConsensusDirectSendBcs,
ProtocolId::ConsensusRpcBcs,
]);
let peer_network_id = PeerNetworkId::new(NetworkId::Validator, peer_id);
peers_and_metadata
.insert_connection_metadata(peer_network_id, conn_meta)
.unwrap();
}
for (id, signer) in signers.iter().take(num_nodes).enumerate() {
let (initial_data, storage) = MockStorage::start_for_testing((&validators).into());
let safety_storage = PersistentSafetyStorage::initialize(
Storage::from(aptos_secure_storage::InMemoryStorage::new()),
signer.author(),
signer.private_key().clone(),
waypoint,
true,
);
let safety_rules_manager = SafetyRulesManager::new_local(safety_storage);
nodes.push(Self::new(
playground,
executor.clone(),
signer.to_owned(),
proposers.clone(),
storage,
initial_data,
safety_rules_manager,
id,
onchain_consensus_config.clone(),
local_consensus_config.clone(),
features.clone().unwrap_or_default(),
));
}
nodes
}
fn new(
playground: &mut NetworkPlayground,
executor: Handle,
signer: ValidatorSigner,
proposers: Vec<Author>,
storage: Arc<MockStorage>,
initial_data: RecoveryData,
safety_rules_manager: SafetyRulesManager,
id: usize,
onchain_consensus_config: OnChainConsensusConfig,
local_consensus_config: ConsensusConfig,
features: Features,
) -> Self {
let _entered_runtime = executor.enter();
let epoch_state = Arc::new(EpochState {
epoch: 1,
verifier: storage.get_validator_set().into(),
});
let validators = epoch_state.verifier.clone();
let (network_reqs_tx, network_reqs_rx) = aptos_channel::new(QueueStyle::FIFO, 8, None);
let (connection_reqs_tx, _) = aptos_channel::new(QueueStyle::FIFO, 8, None);
let (consensus_tx, consensus_rx) = aptos_channel::new(QueueStyle::FIFO, 8, None);
let (_conn_mgr_reqs_tx, conn_mgr_reqs_rx) = aptos_channels::new_test(8);
let (_, conn_status_rx) = conn_notifs_channel::new();
let network_sender = network::NetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
);
let network_client = NetworkClient::new(
DIRECT_SEND.into(),
RPC.into(),
hashmap! {NetworkId::Validator => network_sender},
playground.peer_protocols(),
);
let consensus_network_client = ConsensusNetworkClient::new(network_client);
let network_events = NetworkEvents::new(consensus_rx, conn_status_rx, None);
let author = signer.author();
let twin_id = TwinId { id, author };
playground.add_node(twin_id, consensus_tx, network_reqs_rx, conn_mgr_reqs_rx);
let (self_sender, self_receiver) = aptos_channels::new_test(1000);
let network = Arc::new(NetworkSender::new(
author,
consensus_network_client,
self_sender,
validators,
));
let all_network_events = Box::new(select(network_events, self_receiver));
let last_vote_sent = initial_data.last_vote();
let (ordered_blocks_tx, ordered_blocks_events) = mpsc::unbounded::<OrderedBlocks>();
let (state_sync_client, _state_sync_receiver) = mpsc::unbounded();
let mock_state_computer = Arc::new(MockStateComputer::new(
state_sync_client,
ordered_blocks_tx,
Arc::clone(&storage),
));
let time_service = Arc::new(ClockTimeService::new(executor));
let block_store = Arc::new(BlockStore::new(
storage.clone(),
initial_data,
mock_state_computer.clone(),
10, // max pruned blocks in mem
time_service.clone(),
10,
Arc::from(PayloadManager::DirectMempool),
));
let proposer_election = Self::create_proposer_election(proposers.clone());
let proposal_generator = ProposalGenerator::new(
author,
block_store.clone(),
Arc::new(MockPayloadManager::new(None)),
time_service.clone(),
Duration::ZERO,
10,
1000,
10,
PipelineBackpressureConfig::new_no_backoff(),
ChainHealthBackoffConfig::new_no_backoff(),
false,
onchain_consensus_config.effective_validator_txn_config(),
);
let round_state = Self::create_round_state(time_service);
let mut safety_rules =
MetricsSafetyRules::new(safety_rules_manager.client(), storage.clone());
safety_rules.perform_initialize().unwrap();
let (round_manager_tx, _) = aptos_channel::new(QueueStyle::LIFO, 1, None);
let mut round_manager = RoundManager::new(
epoch_state,
Arc::clone(&block_store),
round_state,
proposer_election,
proposal_generator,
Arc::new(Mutex::new(safety_rules)),
network,
storage.clone(),
onchain_consensus_config.clone(),
round_manager_tx,
local_consensus_config.clone(),
features.clone(),
);
block_on(round_manager.init(last_vote_sent));
Self {
block_store,
round_manager,
storage,
signer,
proposers,
safety_rules_manager,
pending_network_events: Vec::new(),
all_network_events,
ordered_blocks_events,
mock_state_computer,
_state_sync_receiver,
id,
onchain_consensus_config,
local_consensus_config,
features,
}
}
pub fn restart(self, playground: &mut NetworkPlayground, executor: Handle) -> Self {
let recover_data = self
.storage
.try_start()
.unwrap_or_else(|e| panic!("fail to restart due to: {}", e));
Self::new(
playground,
executor,
self.signer,
self.proposers,
self.storage,
recover_data,
self.safety_rules_manager,
self.id,
self.onchain_consensus_config.clone(),
self.local_consensus_config.clone(),
self.features,
)
}
pub fn identity_desc(&self) -> String {
format!("{} [{}]", self.id, self.signer.author())
}
fn poll_next_network_event(&mut self) -> Option<Event<ConsensusMsg>> {
if !self.pending_network_events.is_empty() {
Some(self.pending_network_events.remove(0))
} else {
self.all_network_events
.next()
.now_or_never()
.map(|v| v.unwrap())
}
}
pub async fn next_network_event(&mut self) -> Event<ConsensusMsg> {
if !self.pending_network_events.is_empty() {
self.pending_network_events.remove(0)
} else {
self.all_network_events.next().await.unwrap()
}
}
pub async fn next_network_message(&mut self) -> ConsensusMsg {
match self.next_network_event().await {
Event::Message(_, msg) => msg,
Event::RpcRequest(_, msg, _, _) if matches!(msg, ConsensusMsg::CommitMessage(_)) => msg,
Event::RpcRequest(_, msg, _, _) => {
panic!(
"Unexpected event, got RpcRequest, expected Message: {:?} on node {}",
msg,
self.identity_desc()
)
},
_ => panic!("Unexpected Network Event"),
}
}
pub fn no_next_msg(&mut self) {
match self.poll_next_network_event() {
Some(Event::RpcRequest(_, msg, _, _)) | Some(Event::Message(_, msg)) => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
Some(_) => panic!("Unexpected Network Event"),
None => {},
}
}
pub async fn next_proposal(&mut self) -> ProposalMsg {
match self.next_network_message().await {
ConsensusMsg::ProposalMsg(p) => *p,
msg => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
}
}
pub async fn next_vote(&mut self) -> VoteMsg {
match self.next_network_message().await {
ConsensusMsg::VoteMsg(v) => *v,
msg => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
}
}
pub async fn next_commit_decision(&mut self) -> CommitDecision {
match self.next_network_message().await {
ConsensusMsg::CommitDecisionMsg(v) => *v,
ConsensusMsg::CommitMessage(d) if matches!(*d, CommitMessage::Decision(_)) => {
match *d {
CommitMessage::Decision(d) => d,
_ => unreachable!(),
}
},
msg => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
}
}
pub async fn poll_block_retreival(&mut self) -> Option<IncomingBlockRetrievalRequest> {
match self.poll_next_network_event() {
Some(Event::RpcRequest(_, msg, protocol, response_sender)) => match msg {
ConsensusMsg::BlockRetrievalRequest(v) => Some(IncomingBlockRetrievalRequest {
req: *v,
protocol,
response_sender,
}),
msg => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
},
Some(Event::Message(_, msg)) => panic!(
"Unexpected Consensus Message: {:?} on node {}",
msg,
self.identity_desc()
),
Some(_) => panic!("Unexpected Network Event"),
None => None,
}
}
pub fn no_next_ordered(&mut self) {
if self.ordered_blocks_events.next().now_or_never().is_some() {
panic!("Unexpected Ordered Blocks Event");
}
}
pub async fn commit_next_ordered(&mut self, expected_rounds: &[Round]) {
info!(
"Starting commit_next_ordered to wait for {:?} on node {:?}",
expected_rounds,
self.identity_desc()
);
let ordered_blocks = self.ordered_blocks_events.next().await.unwrap();
let rounds = ordered_blocks
.ordered_blocks
.iter()
.map(|b| b.round())
.collect::<Vec<_>>();
assert_eq!(&rounds, expected_rounds);
self.mock_state_computer
.commit_to_storage(ordered_blocks)
.await
.unwrap();
}
}
fn start_replying_to_block_retreival(nodes: Vec<NodeSetup>) -> ReplyingRPCHandle {
let done = Arc::new(AtomicBool::new(false));
let mut handles = Vec::new();
for mut node in nodes.into_iter() {
let done_clone = done.clone();
handles.push(tokio::spawn(async move {
while !done_clone.load(Ordering::Relaxed) {
info!("Asking for RPC request on {:?}", node.identity_desc());
let maybe_request = node.poll_block_retreival().await;
if let Some(request) = maybe_request {
info!(
"RPC request received: {:?} on {:?}",
request,
node.identity_desc()
);
node.block_store
.process_block_retrieval(request)
.await
.unwrap();
} else {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
node
}));
}
ReplyingRPCHandle { handles, done }
}
struct ReplyingRPCHandle {
handles: Vec<JoinHandle<NodeSetup>>,
done: Arc<AtomicBool>,
}
impl ReplyingRPCHandle {
async fn join(self) -> Vec<NodeSetup> {
self.done.store(true, Ordering::Relaxed);
let mut result = Vec::new();
for handle in self.handles.into_iter() {
result.push(handle.await.unwrap());
}
info!(
"joined nodes in order: {:?}",
result.iter().map(|v| v.id).collect::<Vec<_>>()
);
result
}
}
fn process_and_vote_on_proposal(
runtime: &Runtime,
nodes: &mut [NodeSetup],
next_proposer: usize,
down_nodes: &[usize],
process_votes: bool,
apply_commit_prev_proposer: Option<usize>,
apply_commit_on_votes: bool,
expected_round: u64,
expected_qc_ordered_round: u64,
expected_qc_committed_round: u64,
) {
info!(
"Called {} with current {} and apply commit prev {:?}",
expected_round, next_proposer, apply_commit_prev_proposer
);
let mut num_votes = 0;
for node in nodes.iter_mut() {
info!("Waiting on next_proposal on node {}", node.identity_desc());
if down_nodes.contains(&node.id) {
// Drop the proposal on down nodes
timed_block_on(runtime, node.next_proposal());
info!("Dropping proposal on down node {}", node.identity_desc());
} else {
// Proccess proposal on other nodes
let proposal_msg = timed_block_on(runtime, node.next_proposal());
info!("Processing proposal on {}", node.identity_desc());
assert_eq!(proposal_msg.proposal().round(), expected_round);
assert_eq!(
proposal_msg.sync_info().highest_ordered_round(),
expected_qc_ordered_round
);
assert_eq!(
proposal_msg.sync_info().highest_commit_round(),
expected_qc_committed_round
);
timed_block_on(
runtime,
node.round_manager.process_proposal_msg(proposal_msg),
)
.unwrap();
info!("Finish process proposal on {}", node.identity_desc());
num_votes += 1;
if let Some(prev_proposer) = apply_commit_prev_proposer {
if prev_proposer != node.id && expected_round > 2 {
info!(
"Applying commit {} on node {}",
expected_round - 2,
node.identity_desc()
);
timed_block_on(runtime, node.commit_next_ordered(&[expected_round - 2]));
}
}
}
}
let proposer_node = nodes.get_mut(next_proposer).unwrap();
info!(
"Fetching {} votes in round {} on node {}",
num_votes,
expected_round,
proposer_node.identity_desc()
);
let mut votes = Vec::new();
for _ in 0..num_votes {
votes.push(timed_block_on(runtime, proposer_node.next_vote()));
}
info!("Processing votes on node {}", proposer_node.identity_desc());
if process_votes {
for vote_msg in votes {
timed_block_on(
runtime,
proposer_node.round_manager.process_vote_msg(vote_msg),
)
.unwrap();
}
if apply_commit_prev_proposer.is_some() && expected_round > 1 && apply_commit_on_votes {
info!(
"Applying next commit {} on proposer node {}",
expected_round - 2,
proposer_node.identity_desc()
);
timed_block_on(
runtime,
proposer_node.commit_next_ordered(&[expected_round - 1]),
);
}
}
}
#[test]
fn new_round_on_quorum_cert() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
);
let node = &mut nodes[0];
let genesis = node.block_store.ordered_root();
timed_block_on(&runtime, async {
// round 1 should start
let proposal_msg = node.next_proposal().await;
assert_eq!(
proposal_msg.proposal().quorum_cert().certified_block().id(),
genesis.id()
);
let b1_id = proposal_msg.proposal().id();
assert_eq!(proposal_msg.proposer(), node.signer.author());
node.round_manager
.process_proposal_msg(proposal_msg)
.await
.unwrap();
let vote_msg = node.next_vote().await;
// Adding vote to form a QC
node.round_manager.process_vote_msg(vote_msg).await.unwrap();
// round 2 should start
let proposal_msg = node.next_proposal().await;
let proposal = proposal_msg.proposal();
assert_eq!(proposal.round(), 2);
assert_eq!(proposal.parent_id(), b1_id);
assert_eq!(proposal.quorum_cert().certified_block().id(), b1_id);
});
}
#[test]
/// If the proposal is valid, a vote should be sent
fn vote_on_successful_proposal() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
// In order to observe the votes we're going to check proposal processing on the non-proposer
// node (which will send the votes to the proposer).
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
);
let node = &mut nodes[0];
let genesis_qc = certificate_for_genesis();
timed_block_on(&runtime, async {
// Start round 1 and clear the message queue
node.next_proposal().await;
let proposal = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
let proposal_id = proposal.id();
node.round_manager.process_proposal(proposal).await.unwrap();
let vote_msg = node.next_vote().await;
assert_eq!(vote_msg.vote().author(), node.signer.author());
assert_eq!(vote_msg.vote().vote_data().proposed().id(), proposal_id);
let consensus_state = node.round_manager.consensus_state();
assert_eq!(consensus_state.epoch(), 1);
assert_eq!(consensus_state.last_voted_round(), 1);
assert_eq!(consensus_state.preferred_round(), 0);
assert!(consensus_state.in_validator_set());
});
}
#[test]
/// In back pressure mode, verify that the proposals are processed after we get out of back pressure.
fn delay_proposal_processing_in_sync_only() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
// In order to observe the votes we're going to check proposal processing on the non-proposer
// node (which will send the votes to the proposer).
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
);
let node = &mut nodes[0];
let genesis_qc = certificate_for_genesis();
timed_block_on(&runtime, async {
// Start round 1 and clear the message queue
node.next_proposal().await;
// Set sync only to true so that new proposal processing is delayed.
node.round_manager
.block_store
.set_back_pressure_for_test(true);
let proposal = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
let proposal_id = proposal.id();
node.round_manager
.process_proposal(proposal.clone())
.await
.unwrap();
// Wait for some time to ensure that the proposal was not processed
timeout(Duration::from_millis(200), node.next_vote())
.await
.unwrap_err();
// Clear the sync only mode and process verified proposal and ensure it is processed now
node.round_manager
.block_store
.set_back_pressure_for_test(false);
node.round_manager
.process_verified_proposal(proposal)
.await
.unwrap();
let vote_msg = node.next_vote().await;
assert_eq!(vote_msg.vote().author(), node.signer.author());
assert_eq!(vote_msg.vote().vote_data().proposed().id(), proposal_id);
let consensus_state = node.round_manager.consensus_state();
assert_eq!(consensus_state.epoch(), 1);
assert_eq!(consensus_state.last_voted_round(), 1);
assert_eq!(consensus_state.preferred_round(), 0);
assert!(consensus_state.in_validator_set());
});
}
#[test]
/// If the proposal does not pass voting rules,
/// No votes are sent, but the block is still added to the block tree.
fn no_vote_on_old_proposal() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
// In order to observe the votes we're going to check proposal processing on the non-proposer
// node (which will send the votes to the proposer).
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
);
let node = &mut nodes[0];
let genesis_qc = certificate_for_genesis();
let new_block = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
let new_block_id = new_block.id();
let old_block = Block::new_proposal(
Payload::empty(false),
1,
2,
genesis_qc,
&node.signer,
Vec::new(),
)
.unwrap();
timed_block_on(&runtime, async {
// clear the message queue
node.next_proposal().await;
node.round_manager
.process_proposal(new_block)
.await
.unwrap();
node.round_manager
.process_proposal(old_block)
.await
.unwrap_err();
let vote_msg = node.next_vote().await;
assert_eq!(vote_msg.vote().vote_data().proposed().id(), new_block_id);
});
}
#[test]
/// We don't vote for proposals that 'skips' rounds
/// After that when we then receive proposal for correct round, we vote for it
/// Basically it checks that adversary can not send proposal and skip rounds violating round_state
/// rules
fn no_vote_on_mismatch_round() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
// In order to observe the votes we're going to check proposal processing on the non-proposer
// node (which will send the votes to the proposer).
let mut node = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
)
.pop()
.unwrap();
let genesis_qc = certificate_for_genesis();
let correct_block = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
let block_skip_round = Block::new_proposal(
Payload::empty(false),
2,
2,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
timed_block_on(&runtime, async {
let bad_proposal = ProposalMsg::new(
block_skip_round,
SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None),
);
assert!(node
.round_manager
.process_proposal_msg(bad_proposal)
.await
.is_err());
let good_proposal = ProposalMsg::new(
correct_block.clone(),
SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None),
);
node.round_manager
.process_proposal_msg(good_proposal)
.await
.unwrap();
});
}
#[test]
/// Ensure that after the vote messages are broadcasted upon timeout, the receivers
/// have the highest quorum certificate (carried by the SyncInfo of the vote message)
fn sync_info_carried_on_timeout_vote() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
1,
None,
None,
None,
None,
);
let mut node = nodes.pop().unwrap();
timed_block_on(&runtime, async {
let proposal_msg = node.next_proposal().await;
let block_0 = proposal_msg.proposal().clone();
node.round_manager
.process_proposal_msg(proposal_msg)
.await
.unwrap();
node.next_vote().await;
let parent_block_info = block_0.quorum_cert().certified_block();
// Populate block_0 and a quorum certificate for block_0 on non_proposer
let block_0_quorum_cert = gen_test_certificate(
&[node.signer.clone()],
// Follow MockStateComputer implementation
block_0.gen_block_info(
parent_block_info.executed_state_id(),
parent_block_info.version(),
parent_block_info.next_epoch_state().cloned(),
),
parent_block_info.clone(),
None,
);
node.block_store
.insert_single_quorum_cert(block_0_quorum_cert.clone())
.unwrap();
node.round_manager
.round_state
.process_certificates(SyncInfo::new(
block_0_quorum_cert.clone(),
block_0_quorum_cert.clone(),
None,
));
node.round_manager
.process_local_timeout(2)
.await
.unwrap_err();
let vote_msg_on_timeout = node.next_vote().await;
assert!(vote_msg_on_timeout.vote().is_timeout());
assert_eq!(
*vote_msg_on_timeout.sync_info().highest_quorum_cert(),
block_0_quorum_cert
);
});
}
#[test]
/// We don't vote for proposals that comes from proposers that are not valid proposers for round
fn no_vote_on_invalid_proposer() {
let runtime = consensus_runtime();
let mut playground = NetworkPlayground::new(runtime.handle().clone());
// In order to observe the votes we're going to check proposal processing on the non-proposer
// node (which will send the votes to the proposer).
let mut nodes = NodeSetup::create_nodes(
&mut playground,
runtime.handle().clone(),
2,
None,
None,
None,
None,
);
let incorrect_proposer = nodes.pop().unwrap();
let mut node = nodes.pop().unwrap();
let genesis_qc = certificate_for_genesis();
let correct_block = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),
&node.signer,
Vec::new(),
)
.unwrap();
let block_incorrect_proposer = Block::new_proposal(
Payload::empty(false),
1,
1,
genesis_qc.clone(),