-
Notifications
You must be signed in to change notification settings - Fork 279
/
main_loop.rs
1791 lines (1600 loc) · 66.6 KB
/
main_loop.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
//! The main event loop that powers sumeragi.
use std::{collections::BTreeSet, ops::Deref, sync::mpsc};
use iroha_crypto::{HashOf, KeyPair};
use iroha_data_model::{block::*, events::pipeline::PipelineEventBox, peer::PeerId};
use iroha_futures::supervisor::ShutdownSignal;
use iroha_p2p::UpdateTopology;
use tracing::{span, Level};
use super::{view_change::ProofBuilder, *};
use crate::{block::*, queue::TransactionGuard, sumeragi::tracing::instrument};
/// `Sumeragi` is the implementation of the consensus.
pub struct Sumeragi {
/// Unique id of the blockchain. Used for simple replay attack protection.
pub chain_id: ChainId,
/// The pair of keys used for communication given this Sumeragi instance.
pub key_pair: KeyPair,
/// Address of queue
pub queue: Arc<Queue>,
/// The peer id of myself.
pub peer_id: PeerId,
/// An actor that sends events
pub events_sender: EventsSender,
/// Kura instance used for IO
pub kura: Arc<Kura>,
/// [`iroha_p2p::Network`] actor address
pub network: IrohaNetwork,
/// Receiver channel, for control flow messages.
pub control_message_receiver: mpsc::Receiver<ControlFlowMessage>,
/// Receiver channel.
pub message_receiver: mpsc::Receiver<BlockMessage>,
/// Only used in testing. Causes the genesis peer to withhold blocks when it
/// is the proxy tail.
pub debug_force_soft_fork: bool,
/// The current network topology.
pub topology: Topology,
/// In order to *be fast*, we must minimize communication with
/// other subsystems where we can. This way the performance of
/// sumeragi is more dependent on the code that is internal to the
/// subsystem.
pub transaction_cache: Vec<TransactionGuard>,
/// Metrics for reporting number of view changes in current round
pub view_changes_metric: iroha_telemetry::metrics::ViewChangesGauge,
/// Was there a commit in previous round?
pub was_commit: bool,
/// Instant when the current round started
// NOTE: Round is only restarted on a block commit, so that in the case of
// a view change a new block is immediately created by the leader
pub round_start_time: Instant,
}
#[allow(clippy::missing_fields_in_debug)]
impl Debug for Sumeragi {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Sumeragi")
.field("public_key", &self.key_pair.public_key())
.field("peer_id", &self.peer_id)
.finish()
}
}
impl Sumeragi {
fn role(&self) -> Role {
self.topology.role(&self.peer_id)
}
/// Send a sumeragi packet over the network to the specified `peer`.
/// # Errors
/// Fails if network sending fails
#[instrument(skip(self, packet))]
fn post_packet_to(&self, packet: BlockMessage, peer: &PeerId) {
if peer == &self.peer_id {
return;
}
let post = iroha_p2p::Post {
data: NetworkMessage::SumeragiBlock(Box::new(packet)),
peer_id: peer.clone(),
};
self.network.post(post);
}
#[allow(clippy::needless_pass_by_value)]
fn broadcast_packet_to<'peer_id, I: IntoIterator<Item = &'peer_id PeerId> + Send>(
&self,
msg: impl Into<BlockMessage>,
ids: I,
) {
let msg = msg.into();
for peer_id in ids {
self.post_packet_to(msg.clone(), peer_id);
}
}
fn broadcast_packet(&self, msg: impl Into<BlockMessage>) {
let broadcast = iroha_p2p::Broadcast {
data: NetworkMessage::SumeragiBlock(Box::new(msg.into())),
};
self.network.broadcast(broadcast);
}
fn broadcast_control_flow_packet(&self, msg: ControlFlowMessage) {
let broadcast = iroha_p2p::Broadcast {
data: NetworkMessage::SumeragiControlFlow(Box::new(msg)),
};
self.network.broadcast(broadcast);
}
/// Connect or disconnect peers according to the current network topology.
fn connect_peers(&self, topology: &Topology) {
let peers = topology.iter().cloned().collect();
self.network.update_topology(UpdateTopology(peers));
}
fn send_event(&self, event: impl Into<EventBox>) {
let _ = self.events_sender.send(event.into());
}
fn receive_network_packet(
&self,
latest_block: HashOf<BlockHeader>,
view_change_proof_chain: &mut ProofChain,
) -> (Option<BlockMessage>, bool) {
const MAX_CONTROL_MSG_IN_A_ROW: usize = 25;
let mut should_sleep = true;
for _ in 0..MAX_CONTROL_MSG_IN_A_ROW {
if let Ok(msg) = self
.control_message_receiver
.try_recv()
.map_err(|recv_error| {
assert!(
recv_error != mpsc::TryRecvError::Disconnected,
"INTERNAL ERROR: Sumeragi control message pump disconnected"
)
})
{
should_sleep = false;
if let Err(error) = view_change_proof_chain.insert_proof(
msg.view_change_proof,
&self.topology,
latest_block,
) {
trace!(%error, "Failed to add proof into view change proof chain")
}
} else {
break;
}
}
let block_msg =
self.receive_block_message_network_packet(latest_block, view_change_proof_chain);
should_sleep &= block_msg.is_none();
(block_msg, should_sleep)
}
fn receive_block_message_network_packet(
&self,
latest_block: HashOf<BlockHeader>,
view_change_proof_chain: &ProofChain,
) -> Option<BlockMessage> {
let current_view_change_index =
view_change_proof_chain.verify_with_state(&self.topology, latest_block);
loop {
let block_msg = self
.message_receiver
.try_recv()
.map_err(|recv_error| {
assert!(
recv_error != mpsc::TryRecvError::Disconnected,
"INTERNAL ERROR: Sumeragi message pump disconnected"
)
})
.ok()?;
match &block_msg {
BlockMessage::BlockCreated(bc) => {
if (bc.block.header().view_change_index as usize) < current_view_change_index {
trace!(
ty="BlockCreated",
block=%bc.block.hash(),
"Discarding message due to outdated view change index",
);
// ignore block_message
continue;
}
}
// Signed and Committed contain no block.
// Block sync updates are exempt from early pruning.
BlockMessage::BlockSigned(_)
| BlockMessage::BlockCommitted(_)
| BlockMessage::BlockSyncUpdate(_) => {}
}
return Some(block_msg);
}
}
fn init_listen_for_genesis(
&mut self,
genesis_account: &AccountId,
state: &State,
shutdown_signal: &ShutdownSignal,
) -> Result<(), EarlyReturn> {
info!(
peer_id=%self.peer_id,
role=%self.role(),
"Listening for genesis..."
);
loop {
std::thread::sleep(Duration::from_millis(50));
if shutdown_signal.is_sent() {
info!("Shutdown signal received, shutting down Sumeragi...");
return Err(EarlyReturn::ShutdownMessageReceived);
}
match self.message_receiver.try_recv() {
Ok(message) => {
let block = match message {
BlockMessage::BlockCreated(BlockCreated { block })
| BlockMessage::BlockSyncUpdate(BlockSyncUpdate { block }) => block,
msg => {
trace!(?msg, "Not handling the message, waiting for genesis...");
continue;
}
};
let mut state_block = state.block();
state_block.world.genesis_creation_time_ms =
Some(block.header().creation_time_ms);
let block = match ValidBlock::validate(
block,
&self.topology,
&self.chain_id,
genesis_account,
&mut state_block,
)
.unpack(|e| self.send_event(e))
.and_then(|block| {
block
.commit(&self.topology)
.unpack(|e| self.send_event(e))
.map_err(|(block, error)| (block.into(), error))
}) {
Ok(block) => block,
Err(error) => {
error!(
peer_id=%self.peer_id,
?error,
"Received invalid genesis block"
);
continue;
}
};
if block.as_ref().transactions().any(|tx| tx.error.is_some()) {
error!(
peer_id=%self.peer_id,
role=%self.role(),
"Genesis contains invalid transactions"
);
continue;
}
// NOTE: By this time genesis block is executed and list of trusted peers is updated
self.topology = Topology::new(state_block.world.trusted_peers_ids.clone());
self.commit_block(block, state_block);
return Ok(());
}
Err(mpsc::TryRecvError::Disconnected) => return Err(EarlyReturn::Disconnected),
_ => (),
}
}
}
fn init_commit_genesis(
&mut self,
GenesisBlock(genesis): GenesisBlock,
genesis_account: &AccountId,
state: &State,
) {
std::thread::sleep(Duration::from_millis(250)); // TODO: Why this sleep?
{
let state_view = state.view();
assert_eq!(state_view.height(), 0);
assert_eq!(state_view.latest_block_hash(), None);
}
let mut state_block = state.block();
state_block.world.genesis_creation_time_ms = Some(genesis.header().creation_time_ms);
let msg = BlockCreated::from(&genesis);
self.broadcast_packet(msg);
let genesis = ValidBlock::validate(
genesis,
&self.topology,
&self.chain_id,
genesis_account,
&mut state_block,
)
.unpack(|e| self.send_event(e))
.expect("Genesis invalid");
assert!(
!genesis.as_ref().transactions().any(|tx| tx.error.is_some()),
"Genesis contains invalid transactions"
);
// NOTE: By this time genesis block is executed and list of trusted peers is updated
self.topology = Topology::new(state_block.world.trusted_peers_ids.clone());
let genesis = genesis
.commit(&self.topology)
.unpack(|e| self.send_event(e))
.expect("Genesis invalid");
self.commit_block(genesis, state_block);
}
fn commit_block(&mut self, block: CommittedBlock, state_block: StateBlock<'_>) {
self.update_state::<NewBlockStrategy>(block, state_block);
}
fn replace_top_block(&mut self, block: CommittedBlock, state_block: StateBlock<'_>) {
self.update_state::<ReplaceTopBlockStrategy>(block, state_block);
}
fn update_state<Strategy: ApplyBlockStrategy>(
&mut self,
block: CommittedBlock,
mut state_block: StateBlock<'_>,
) {
let prev_role = self.role();
self.topology
.block_committed(state_block.world.peers().cloned());
let state_events =
state_block.apply_without_execution(&block, self.topology.as_ref().to_owned());
self.cache_transaction(&state_block);
self.connect_peers(&self.topology);
let block_hash = block.as_ref().hash();
let block_height = block.as_ref().header().height();
Strategy::kura_store_block(&self.kura, block);
// Commit new block making it's effect visible for the rest of application
state_block.commit();
info!(
peer_id=%self.peer_id,
%prev_role,
next_role=%self.role(),
block_hash=%block_hash,
new_height=%block_height,
"{}", Strategy::LOG_MESSAGE,
);
#[cfg(debug_assertions)]
iroha_logger::info!(
peer_id=%self.peer_id,
role=%self.role(),
topology=?self.topology,
"Topology after commit"
);
// NOTE: This sends `BlockStatus::Applied` event,
// so it should be done AFTER public facing state update
state_events.into_iter().for_each(|e| self.send_event(e));
self.round_start_time = Instant::now();
self.was_commit = true;
}
fn cache_transaction(&mut self, state_block: &StateBlock<'_>) {
self.transaction_cache.retain(|tx| {
!state_block.has_transaction(tx.as_ref().hash()) && !self.queue.is_expired(tx)
});
}
fn validate_block<'state>(
&self,
block: SignedBlock,
state: &'state State,
topology: &Topology,
genesis_account: &AccountId,
existing_voting_block: &mut Option<VotingBlock>,
) -> Option<VotingBlock<'state>> {
assert!(!block.header().is_genesis());
ValidBlock::validate_keep_voting_block(
block,
topology,
&self.chain_id,
genesis_account,
state,
existing_voting_block,
false,
)
.unpack(|e| self.send_event(e))
.map(|(block, state_block)| VotingBlock::new(block, state_block))
.map_err(|(block, error)| {
warn!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
?error,
"Block validation failed"
);
})
.ok()
}
fn prune_view_change_proofs_and_calculate_current_index(
&self,
latest_block: HashOf<BlockHeader>,
view_change_proof_chain: &mut ProofChain,
) -> usize {
view_change_proof_chain.prune(latest_block);
view_change_proof_chain.verify_with_state(&self.topology, latest_block)
}
#[allow(clippy::too_many_lines)]
#[allow(clippy::too_many_arguments)]
fn handle_message<'state>(
&mut self,
message: BlockMessage,
state: &'state State,
voting_block: &mut Option<VotingBlock<'state>>,
view_change_index: usize,
genesis_account: &AccountId,
voting_signatures: &mut BTreeSet<BlockSignature>,
#[cfg_attr(not(debug_assertions), allow(unused_variables))] is_genesis_peer: bool,
) {
#[allow(clippy::suspicious_operation_groupings)]
match (message, self.role()) {
(BlockMessage::BlockSyncUpdate(BlockSyncUpdate { block }), _) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
"Block sync update received"
);
let block_sync_type = categorize_block_sync(&block, &state.view());
match handle_categorized_block_sync(
&self.chain_id,
block,
state,
genesis_account,
&|e| self.send_event(e),
block_sync_type,
voting_block,
) {
Ok(BlockSyncOk::CommitBlock(block, state_block, topology)) => {
self.topology = topology;
self.commit_block(block, state_block);
}
Ok(BlockSyncOk::ReplaceTopBlock(block, state_block, topology)) => {
let latest_block = state_block
.latest_block()
.expect("INTERNAL BUG: No latest block");
warn!(
peer_id=%self.peer_id,
role=%self.role(),
peer_latest_block_hash=?state_block.latest_block_hash(),
peer_latest_block_view_change_index=%latest_block.header().view_change_index,
consensus_latest_block=%block.as_ref().hash(),
consensus_latest_block_view_change_index=%block.as_ref().header().view_change_index,
"Soft fork occurred: peer in inconsistent state. Rolling back and replacing top block."
);
self.topology = topology;
self.replace_top_block(block, state_block);
}
Err((block, BlockSyncError::BlockNotValid(error))) => {
error!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
?error,
"Block not valid."
);
}
Err((block, BlockSyncError::SoftForkBlockNotValid(error))) => {
error!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
?error,
"Soft-fork block not valid."
);
}
Err((
block,
BlockSyncError::SoftForkBlockSmallViewChangeIndex {
peer_view_change_index,
block_view_change_index,
},
)) => {
debug!(
peer_id=%self.peer_id,
role=%self.role(),
peer_latest_block_hash=?state.view().latest_block_hash(),
peer_latest_block_view_change_index=?peer_view_change_index,
consensus_latest_block=%block.hash(),
consensus_latest_block_view_change_index=%block_view_change_index,
"Soft fork didn't occur: block has the same or smaller view change index"
);
}
Err((
block,
BlockSyncError::BlockNotProperHeight {
peer_height,
block_height,
},
)) => {
warn!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
%block_height,
%peer_height,
"Received irrelevant or outdated block (neither `peer_height` nor `peer_height + 1`)."
);
}
}
}
(BlockMessage::BlockCreated(BlockCreated { block }), Role::ValidatingPeer) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
"Block received"
);
let topology = &self
.topology
.is_consensus_required()
.expect("INTERNAL BUG: Consensus required for validating peer");
if let Some(mut v_block) =
self.validate_block(block, state, topology, genesis_account, voting_block)
{
v_block.block.sign(&self.key_pair, topology);
let msg = BlockSigned::from(&v_block.block);
self.broadcast_packet_to(msg, [topology.proxy_tail()]);
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%v_block.block.as_ref().hash(),
"Voted for the block"
);
*voting_block = Some(v_block);
}
}
(BlockMessage::BlockCreated(BlockCreated { block }), Role::ObservingPeer) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
"Block received"
);
let topology = &self
.topology
.is_consensus_required()
.expect("INTERNAL BUG: Consensus required for observing peer");
if let Some(mut v_block) =
self.validate_block(block, state, topology, genesis_account, voting_block)
{
if view_change_index >= 1 {
v_block.block.sign(&self.key_pair, topology);
let msg = BlockSigned::from(&v_block.block);
self.broadcast_packet_to(msg, [topology.proxy_tail()]);
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%v_block.block.as_ref().hash(),
"Voted for the block"
);
}
*voting_block = Some(v_block);
}
}
(BlockMessage::BlockCreated(BlockCreated { block }), Role::ProxyTail) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%block.hash(),
"Block received"
);
if let Some(mut valid_block) =
self.validate_block(block, state, &self.topology, genesis_account, voting_block)
{
// NOTE: Up until this point it was unknown which block is expected to be received,
// therefore all the signatures (of any hash) were collected and will now be pruned
for signature in core::mem::take(voting_signatures) {
if let Err(error) =
valid_block.block.add_signature(signature, &self.topology)
{
debug!(?error, "Signature not valid");
}
}
*voting_block = self.try_commit_block(valid_block, is_genesis_peer);
}
}
(BlockMessage::BlockSigned(BlockSigned { hash, signature }), Role::ProxyTail) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%hash,
"Received block signatures"
);
if let Ok(signatory_idx) = usize::try_from(signature.0) {
let signatory = &self.topology.as_ref()[signatory_idx];
match self.topology.role(signatory) {
Role::Leader => error!(
peer_id=%self.peer_id,
role=%self.role(),
"Signatory is leader"
),
Role::Undefined => error!(
peer_id=%self.peer_id,
role=%self.role(),
"Unknown signatory"
),
Role::ObservingPeer if view_change_index == 0 => error!(
peer_id=%self.peer_id,
role=%self.role(),
"Signatory is observing peer"
),
Role::ProxyTail => error!(
peer_id=%self.peer_id,
role=%self.role(),
"Signatory is proxy tail"
),
_ => {
if let Some(mut voted_block) = voting_block.take() {
let actual_hash = voted_block.block.as_ref().hash();
if hash != actual_hash {
error!(
peer_id=%self.peer_id,
role=%self.role(),
expected_hash=?hash,
?actual_hash,
"Block hash mismatch"
);
*voting_block = Some(voted_block);
} else if let Err(err) =
voted_block.block.add_signature(signature, &self.topology)
{
error!(
peer_id=%self.peer_id,
role=%self.role(),
?err,
"Signature not valid"
);
*voting_block = Some(voted_block);
} else {
*voting_block =
self.try_commit_block(voted_block, is_genesis_peer);
}
} else {
// NOTE: Due to the nature of distributed systems, signatures can sometimes be received before
// the block (sent by the leader). Collect the signatures and wait for the block to be received
if !voting_signatures.insert(signature) {
error!(
peer_id=%self.peer_id,
role=%self.role(),
"Duplicate signature"
);
}
}
}
}
} else {
error!(
peer_id=%self.peer_id,
role=%self.role(),
"Signatory index exceeds usize::MAX"
);
}
}
(BlockMessage::BlockCommitted(BlockCommitted { .. }), Role::Leader)
if self.topology.is_consensus_required().is_none() => {}
(
BlockMessage::BlockCommitted(BlockCommitted { hash, signatures }),
Role::Leader | Role::ValidatingPeer | Role::ObservingPeer,
) => {
info!(
peer_id=%self.peer_id,
role=%self.role(),
block=%hash,
"Received block committed",
);
if let Some(mut voted_block) = voting_block.take() {
let actual_hash = voted_block.block.as_ref().hash();
if actual_hash == hash {
match voted_block
.block
// NOTE: The manipulation of the topology relies upon all peers seeing the same signature set.
// Therefore we must clear the signatures and accept what the proxy tail has giveth.
.replace_signatures(signatures, &self.topology)
.unpack(|e| self.send_event(e))
{
Ok(prev_signatures) => {
match voted_block
.block
.commit(&self.topology)
.unpack(|e| self.send_event(e))
{
Ok(committed_block) => {
self.commit_block(committed_block, voted_block.state_block)
}
Err((mut block, error)) => {
error!(
peer_id=%self.peer_id,
role=%self.role(),
?error,
"Block failed to be committed"
);
block
.replace_signatures(prev_signatures, &self.topology)
.unpack(|e| self.send_event(e))
.expect("INTERNAL BUG: Failed to replace signatures");
voted_block.block = block;
*voting_block = Some(voted_block);
}
}
}
Err(error) => {
error!(
peer_id=%self.peer_id,
role=%self.role(),
?error,
"Received incorrect signatures"
);
*voting_block = Some(voted_block);
}
}
} else {
error!(
peer_id=%self.peer_id,
role=%self.role(),
expected_hash=?hash,
?actual_hash,
"Block hash mismatch"
);
}
} else {
error!(
peer_id=%self.peer_id,
role=%self.role(),
"Peer missing voting block"
);
}
}
(msg, _) => {
trace!(
role=%self.role(),
peer_id=%self.peer_id,
?msg,
"message not handled"
);
}
}
}
/// Commits block if there are enough votes
fn try_commit_block<'state>(
&mut self,
mut voting_block: VotingBlock<'state>,
#[cfg_attr(not(debug_assertions), allow(unused_variables))] is_genesis_peer: bool,
) -> Option<VotingBlock<'state>> {
assert_eq!(self.role(), Role::ProxyTail);
let votes_count = voting_block.block.as_ref().signatures().len();
if votes_count + 1 >= self.topology.min_votes_for_commit() {
voting_block.block.sign(&self.key_pair, &self.topology);
let committed_block = voting_block
.block
.commit(&self.topology)
.unpack(|e| self.send_event(e))
.expect("INTERNAL BUG: Proxy tail failed to commit block");
#[cfg(debug_assertions)]
if is_genesis_peer && self.debug_force_soft_fork {
let pipeline_time = voting_block
.state_block
.world
.parameters()
.sumeragi
.pipeline_time(
self.topology.view_change_index(),
self.topology.max_faults() + 1,
);
std::thread::sleep(pipeline_time * 2);
} else {
let msg = BlockCommitted::from(&committed_block);
self.broadcast_packet(msg);
}
#[cfg(not(debug_assertions))]
{
let msg = BlockCommitted::from(&committed_block);
self.broadcast_packet(msg);
}
self.commit_block(committed_block, voting_block.state_block);
return None;
}
Some(voting_block)
}
#[allow(clippy::too_many_lines)]
fn try_create_block<'state>(
&mut self,
state: &'state State,
voting_block: &mut Option<VotingBlock<'state>>,
) {
assert_eq!(self.role(), Role::Leader);
let max_transactions: NonZeroUsize = state
.world
.view()
.parameters
.block
.max_transactions
.try_into()
.expect("INTERNAL BUG: transactions in block exceed usize::MAX");
let tx_cache_full = self.transaction_cache.len() >= max_transactions.get();
let view_change_in_progress = self.topology.view_change_index() > 0;
let block_time = state.world.view().parameters.sumeragi.block_time();
let deadline_reached = self.round_start_time.elapsed() > block_time;
let tx_cache_non_empty = !self.transaction_cache.is_empty();
if tx_cache_full || tx_cache_non_empty && (view_change_in_progress || deadline_reached) {
let transactions = self
.transaction_cache
.iter()
.map(|tx| tx.deref().clone())
.collect::<Vec<_>>();
let mut state_block = state.block();
let unverified_block = BlockBuilder::new(transactions)
.chain(self.topology.view_change_index(), &mut state_block)
.sign(self.key_pair.private_key())
.unpack(|e| self.send_event(e));
info!(
peer_id=%self.peer_id,
block_hash=%unverified_block.header.hash(),
txns=%unverified_block.transactions.len(),
view_change_index=%self.topology.view_change_index(),
"Block created"
);
if self.topology.is_consensus_required().is_some() {
let msg = BlockCreated::from(&unverified_block);
self.broadcast_packet(msg);
}
let block = unverified_block
.categorize(&mut state_block)
.unpack(|e| self.send_event(e));
*voting_block = if self.topology.is_consensus_required().is_some() {
Some(VotingBlock::new(block, state_block))
} else {
let committed_block = block
.commit(&self.topology)
.unpack(|e| self.send_event(e))
.expect("INTERNAL BUG: Leader failed to commit block");
let msg = BlockCommitted::from(&committed_block);
self.broadcast_packet(msg);
self.commit_block(committed_block, state_block);
None
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn reset_state(
peer_id: &PeerId,
pipeline_time: Duration,
view_change_index: usize,
was_commit: &mut bool,
topology: &mut Topology,
voting_block: &mut Option<VotingBlock>,
voting_signatures: &mut BTreeSet<BlockSignature>,
last_view_change_time: &mut Instant,
view_change_time: &mut Duration,
) {
let mut was_commit_or_view_change = *was_commit;
let prev_role = topology.role(peer_id);
if topology.view_change_index() < view_change_index {
let new_rotations = topology.nth_rotation(view_change_index);
error!(
%peer_id,
%prev_role,
next_role=%topology.role(peer_id),
n=%new_rotations,
%view_change_index,
"Topology rotated n times"
);
#[cfg(debug_assertions)]
iroha_logger::info!(
%peer_id,
role=%topology.role(peer_id),
topology=?topology,
"Topology after rotation"
);
was_commit_or_view_change = true;
}
// Reset state for the next round.
if was_commit_or_view_change {
*voting_block = None;
voting_signatures.clear();
*last_view_change_time = Instant::now();
*view_change_time = pipeline_time;
*was_commit = false;
}
}
#[iroha_logger::log(name = "consensus", skip_all)]
/// Execute the main loop of [`Sumeragi`]
pub(crate) fn run(
genesis_network: GenesisWithPubKey,
mut sumeragi: Sumeragi,
shutdown_signal: &ShutdownSignal,
state: Arc<State>,
) {
// Connect peers with initial topology
sumeragi.connect_peers(&sumeragi.topology);
let genesis_account = AccountId::new(
iroha_genesis::GENESIS_DOMAIN_ID.clone(),
genesis_network.public_key.clone(),
);
let span = span!(tracing::Level::TRACE, "genesis").entered();
let is_genesis_peer =
if state.view().height() == 0 || state.view().latest_block_hash().is_none() {
if let Some(genesis) = genesis_network.genesis {
sumeragi.init_commit_genesis(genesis, &genesis_account, &state);
true
} else {
if let Err(err) =
sumeragi.init_listen_for_genesis(&genesis_account, &state, shutdown_signal)
{
info!(?err, "Sumeragi Thread is being shut down.");
return;
}
false
}
} else {
false
};
span.exit();
info!(
peer_id=%sumeragi.peer_id,
role=%sumeragi.role(),
"Sumeragi initialized",
);