Skip to content

Commit

Permalink
Fix u256 conversion in BABE (#5994)
Browse files Browse the repository at this point in the history
#5886 (comment)

---------

Co-authored-by: Bastian Köcher <[email protected]>
Co-authored-by: Bastian Köcher <[email protected]>
  • Loading branch information
3 people authored Oct 9, 2024
1 parent 48b56aa commit 292bfac
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
3 changes: 3 additions & 0 deletions prdoc/pr_5994.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
crates:
- name: sc-consensus-babe
bump: none
20 changes: 18 additions & 2 deletions substrate/client/consensus/babe/src/authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ pub(super) fn secondary_slot_author(
}

let rand =
U256::from_little_endian(&(randomness, slot).using_encoded(sp_crypto_hashing::blake2_256));
U256::from_big_endian(&(randomness, slot).using_encoded(sp_crypto_hashing::blake2_256));

let authorities_len = U256::from(authorities.len());
let idx = rand % authorities_len;
Expand Down Expand Up @@ -272,7 +272,9 @@ fn claim_primary_slot(
#[cfg(test)]
mod tests {
use super::*;
use sp_consensus_babe::{AllowedSlots, AuthorityId, BabeEpochConfiguration, Epoch};
use sp_consensus_babe::{
AllowedSlots, AuthorityId, BabeEpochConfiguration, Epoch, RANDOMNESS_LENGTH,
};
use sp_core::{crypto::Pair as _, sr25519::Pair};
use sp_keystore::testing::MemoryKeystore;

Expand Down Expand Up @@ -306,4 +308,18 @@ mod tests {
epoch.authorities.push((valid_public_key.into(), 10));
assert_eq!(claim_slot(10.into(), &epoch, &keystore).unwrap().1, valid_public_key.into());
}

#[test]
fn secondary_slot_author_selection_works() {
let authorities = (0..1000)
.map(|i| (AuthorityId::from(Pair::generate().0.public()), i))
.collect::<Vec<_>>();

let randomness = [3; RANDOMNESS_LENGTH];

assert_eq!(
*secondary_slot_author(100.into(), &authorities, randomness).unwrap(),
authorities[167].0
);
}
}

0 comments on commit 292bfac

Please sign in to comment.