Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Massively improve xor computation
  • Loading branch information
timorl committed Nov 9, 2022
commit 1980bbdea25e0bca0ce9a4b8a8abc63c63a90d62
23 changes: 8 additions & 15 deletions finality-aleph/src/validator_network/manager/direction.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::collections::{HashMap, HashSet};
use std::{
collections::{HashMap, HashSet},
ops::BitXor,
};

use aleph_primitives::AuthorityId;

Expand All @@ -12,24 +15,14 @@ pub struct DirectedPeers<A: Data> {
incoming: HashSet<AuthorityId>,
}

fn bit_xor_sum_parity((a, b): (u8, u8)) -> u8 {
let mut result = 0;
for i in 0..8 {
result += ((a >> i) ^ (b >> i)) % 2;
}
result % 2
}

/// Whether we should call the remote or the other way around. We xor the peer ids and based on the
/// parity of the sum of bits of the result decide whether the caller should be the smaller or
/// greated lexicographically. They are never equal, because cryptography.
fn should_we_call(own_id: &[u8], remote_id: &[u8]) -> bool {
let xor_sum_parity: u8 = own_id
.iter()
.cloned()
.zip(remote_id.iter().cloned())
.map(bit_xor_sum_parity)
.fold(0u8, |a, b| (a + b) % 2);
let xor_sum_parity = (own_id.iter().fold(0u8, BitXor::bitxor)
^ remote_id.iter().fold(0u8, BitXor::bitxor))
.count_ones()
% 2;
match xor_sum_parity == 0 {
true => own_id < remote_id,
false => own_id > remote_id,
Expand Down
3 changes: 2 additions & 1 deletion finality-aleph/src/validator_network/protocols/v1/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ pub async fn outgoing<D: Data, S: Splittable>(
}

/// Performs the incoming handshake, and then manages a connection sending and receiving data.
/// Exits on parent request, or in case of broken or dead network connection.
/// Exits on parent request (when the data source is dropped), or in case of broken or dead
/// network connection.
pub async fn incoming<D: Data, S: Splittable>(
stream: S,
authority_pen: AuthorityPen,
Expand Down