Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
kylezs committed Oct 22, 2024
1 parent 0d60944 commit 51b497c
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 93 deletions.
10 changes: 10 additions & 0 deletions state-chain/pallets/cf-elections/src/electoral_system_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ pub struct CompositeConsensusVotes<ES: ElectoralSystemRunner> {
pub votes: Vec<CompositeConsensusVote<ES>>,
}

#[cfg(test)]
impl<ES: ElectoralSystemRunner> CompositeConsensusVotes<ES> {
pub fn active_votes(self) -> Vec<<ES::Vote as VoteStorage>::Vote> {
self.votes
.into_iter()
.filter_map(|CompositeConsensusVote { vote, .. }| vote.map(|v| v.1))
.collect()
}
}

pub trait ElectoralSystemRunner: 'static + Sized {
type ValidatorId: Parameter + Member + MaybeSerializeDeserialize;

Expand Down
30 changes: 12 additions & 18 deletions state-chain/pallets/cf-elections/src/electoral_systems/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,32 +144,26 @@ impl ElectoralSystemRunner for MockElectoralSystemRunner {
fn on_finalize(
election_identifiers: Vec<CompositeElectionIdentifierOf<Self>>,
) -> Result<(), CorruptStorageError> {
todo!()
// for id in election_identifiers {
// // Read the current consensus status and save it.
// // Get an election _mut
// let mut election = ElectoralAccess::election_mut(id)?;
// let consensus = election.check_consensus()?;
// Self::set_consensus_status(*id.unique_monotonic(), consensus.clone());
// if consensus.has_consensus().is_some() && Self::should_delete_on_finalize_consensus() {
// election.delete();
// }
// }
for id in election_identifiers {
// Self::set_consensus_status(*id.unique_monotonic(), consensus.clone());
// if consensus.has_consensus().is_some() && Self::should_delete_on_finalize_consensus()
// { election.delete();
// }
}

// Ok(())
Ok(())
}

fn check_consensus(
_election_identifier: CompositeElectionIdentifierOf<Self>,
_previous_consensus: Option<&Self::Consensus>,
consensus_votes: CompositeConsensusVotes<Self>,
) -> Result<Option<Self::Consensus>, CorruptStorageError> {
todo!()
// Ok(if Self::should_assume_consensus() {
// Some(consensus_votes.active_votes().len() as AuthorityCount)
// } else {
// None
// })
Ok(if Self::should_assume_consensus() {
Some(consensus_votes.active_votes().len() as AuthorityCount)
} else {
None
})
}

fn is_vote_desired(
Expand Down
12 changes: 3 additions & 9 deletions state-chain/pallets/cf-elections/src/electoral_systems/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@ impl<ES: ElectoralSystem> TestContext<ES> {
}

pub fn all_election_ids(&self) -> Vec<ElectionIdentifierOf<ES>> {
// self.electoral_access.election_identifiers()
todo!()
MockStorageAccess::election_identifiers::<ES>()
}

/// Update the current consensus without processing any votes.
Expand All @@ -163,14 +162,9 @@ impl<ES: ElectoralSystem> TestContext<ES> {
election_id: ElectionIdentifierOf<ES>,
new_consensus: ConsensusStatus<ES::Consensus>,
) -> Self {
todo!()
// let mut electoral_access = self.electoral_access.clone();
// electoral_access
// .election_mut(election_id)
// .unwrap()
// .set_consensus_status(new_consensus);
MockStorageAccess::set_consensus_status::<ES>(election_id, new_consensus);

// Self { electoral_access, ..self }
self
}

/// Test the finalization of the election.
Expand Down
159 changes: 93 additions & 66 deletions state-chain/pallets/cf-elections/src/electoral_systems/mocks/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ use crate::{
};
use codec::{Decode, Encode};
use core::cell::RefCell;
use frame_support::{
ensure, CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound, StorageHasher, Twox64Concat,
};
use frame_support::{ensure, CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound};
use std::collections::BTreeMap;

// TODO: Create a new() so no need to pass mock storage access in each time. same below.
Expand All @@ -21,14 +19,6 @@ pub struct MockWriteAccess<ES: ElectoralSystem> {
election_identifier: ElectionIdentifierOf<ES>,
}

#[derive(CloneNoBound, DebugNoBound, PartialEqNoBound, EqNoBound)]
pub struct MockElection<ES: ElectoralSystem> {
properties: ES::ElectionProperties,
state: ES::ElectionState,
settings: ES::ElectoralSettings,
consensus_status: ConsensusStatus<ES::Consensus>,
}

#[derive(CloneNoBound, DebugNoBound, PartialEqNoBound, EqNoBound)]
pub struct MockAccess<ES: ElectoralSystem> {
_phantom: core::marker::PhantomData<ES>,
Expand All @@ -45,7 +35,7 @@ macro_rules! impl_read_access {
<Self::ElectoralSystem as ElectoralSystem>::ElectoralSettings,
CorruptStorageError,
> {
self.with_election(|e| e.settings.clone())
Ok(MockStorageAccess::electoral_settings_for_election::<ES>(self.identifier()))
}

fn properties(
Expand All @@ -54,7 +44,7 @@ macro_rules! impl_read_access {
<Self::ElectoralSystem as ElectoralSystem>::ElectionProperties,
CorruptStorageError,
> {
self.with_election(|e| e.properties.clone())
Ok(MockStorageAccess::election_properties::<ES>(self.identifier()))
}

fn state(
Expand All @@ -63,7 +53,7 @@ macro_rules! impl_read_access {
<Self::ElectoralSystem as ElectoralSystem>::ElectionState,
CorruptStorageError,
> {
self.with_election(|e| e.state.clone())
Ok(MockStorageAccess::election_state::<ES>(self.identifier()))
}

fn election_identifier(&self) -> ElectionIdentifierOf<Self::ElectoralSystem> {
Expand All @@ -72,17 +62,6 @@ macro_rules! impl_read_access {
}

impl<ES: ElectoralSystem> $t {
fn with_election<F: FnOnce(&MockElection<ES>) -> R, R>(
&self,
f: F,
) -> Result<R, CorruptStorageError> {
todo!()
// self.electoral_system
// .elections
// .get(&self.identifier())
// .map(f)
// .ok_or_else(CorruptStorageError::new)
}
pub fn identifier(&self) -> ElectionIdentifierOf<ES> {
self.election_identifier
}
Expand All @@ -100,26 +79,11 @@ macro_rules! impl_read_access {
impl_read_access!(MockReadAccess<ES>);
impl_read_access!(MockWriteAccess<ES>);

// impl<ES: ElectoralSystem> MockWriteAccess<'_, ES> {
// fn with_election_mut<F: FnOnce(&mut MockElection<ES>) -> R, R>(
// &self,
// f: F,
// ) -> Result<R, CorruptStorageError> {
// self.electoral_system
// .elections
// .get_mut(&self.identifier())
// .map(f)
// .ok_or_else(CorruptStorageError::new)
// }
// pub fn set_consensus_status(&mut self, consensus_status: ConsensusStatus<ES::Consensus>) {
// self.with_election_mut(|e| e.consensus_status = consensus_status)
// .expect("Cannot set consensus status for non-existent election");
// }
// }

thread_local! {
pub static ELECTION_STATE: RefCell<BTreeMap<Vec<u8>, Vec<u8>>> = const { RefCell::new(BTreeMap::new()) };
pub static ELECTION_PROPERTIES: RefCell<BTreeMap<Vec<u8>, Vec<u8>>> = const { RefCell::new(BTreeMap::new()) };
// The electoral settings for a particular election
pub static ELECTION_SETTINGS: RefCell<BTreeMap<Vec<u8>, Vec<u8>>> = const { RefCell::new(BTreeMap::new()) };
pub static ELECTORAL_UNSYNCHRONISED_SETTINGS: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
pub static ELECTORAL_UNSYNCHRONISED_STATE: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
pub static ELECTORAL_UNSYNCHRONISED_STATE_MAP: RefCell<BTreeMap<Vec<u8>, Option<Vec<u8>>>> = const { RefCell::new(BTreeMap::new()) };
Expand All @@ -139,17 +103,15 @@ impl<ES: ElectoralSystem> ElectionWriteAccess for MockWriteAccess<ES> {
// nothing
}
fn delete(self) {
// self.electoral_system.elections.remove(&self.identifier());
todo!()
MockStorageAccess::delete_election::<ES>(self.identifier());
}
fn refresh(
&mut self,
new_extra: <Self::ElectoralSystem as ElectoralSystem>::ElectionIdentifierExtra,
properties: <Self::ElectoralSystem as ElectoralSystem>::ElectionProperties,
) -> Result<(), CorruptStorageError> {
// clear storage at old identifer?
self.election_identifier = self.election_identifier.with_extra(new_extra);
MockStorageAccess::set_properties::<ES>(self.identifier(), properties);
MockStorageAccess::set_election_properties::<ES>(self.identifier(), properties);
Ok(())
}

Expand Down Expand Up @@ -213,23 +175,10 @@ impl<ES: ElectoralSystem> ElectoralWriteAccess for MockAccess<ES> {
properties: <Self::ElectoralSystem as ElectoralSystem>::ElectionProperties,
state: <Self::ElectoralSystem as ElectoralSystem>::ElectionState,
) -> Result<Self::ElectionWriteAccess, CorruptStorageError> {
todo!()
// let election_identifier = ElectionIdentifier::new(self.next_election_id, extra);
// self.next_election_id = self.next_election_id.next_identifier().unwrap();
// self.elections.insert(
// election_identifier,
// MockElection {
// properties,
// state,
// settings: self.electoral_settings.clone(),
// consensus_status: ConsensusStatus::None,
// },
// );
// self.election_write_access(election_identifier)
Ok(Self::election_mut(MockStorageAccess::new_election::<ES>(extra, properties, state)))
}
fn election_mut(id: ElectionIdentifierOf<Self::ElectoralSystem>) -> Self::ElectionWriteAccess {
// self.election_write_access(id)
todo!()
MockWriteAccess { election_identifier: id }
}
fn set_unsynchronised_state(
unsynchronised_state: <Self::ElectoralSystem as ElectoralSystem>::ElectoralUnsynchronisedState,
Expand All @@ -245,10 +194,8 @@ impl<ES: ElectoralSystem> ElectoralWriteAccess for MockAccess<ES> {
<Self::ElectoralSystem as ElectoralSystem>::ElectoralUnsynchronisedStateMapValue,
>,
) -> Result<(), CorruptStorageError> {
// self.unsynchronised_state_map
// .insert(key.using_encoded(Twox64Concat::hash), value);
// Ok(())
todo!()
MockStorageAccess::set_unsynchronised_state_map::<ES>(key, value);
Ok(())
}
}

Expand All @@ -259,6 +206,37 @@ impl MockStorageAccess {
NEXT_ELECTION_ID.with(|next_id| next_id.borrow().clone())
}

pub fn increment_next_umi() {
NEXT_ELECTION_ID.with(|next_id| {
let mut next_id_ref = next_id.borrow_mut();
*next_id_ref = next_id_ref.next_identifier().unwrap();
});
}

pub fn electoral_settings_for_election<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
) -> <ES as ElectoralSystem>::ElectoralSettings {
ELECTION_SETTINGS.with(|settings| {
let settings_ref = settings.borrow();
settings_ref
.get(&identifier.encode())
.clone()
.map(|v| ES::ElectoralSettings::decode(&mut &v[..]).unwrap())
.unwrap()
})
}

pub fn delete_election<ES: ElectoralSystem>(identifier: ElectionIdentifierOf<ES>) {
ELECTION_PROPERTIES.with(|properties| {
let mut properties_ref = properties.borrow_mut();
properties_ref.remove(&identifier.encode());
});
ELECTION_STATE.with(|state| {
let mut state_ref = state.borrow_mut();
state_ref.remove(&identifier.encode());
});
}

pub fn set_state<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
state: ES::ElectionState,
Expand All @@ -269,7 +247,19 @@ impl MockStorageAccess {
});
}

pub fn set_properties<ES: ElectoralSystem>(
pub fn election_state<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
) -> ES::ElectionState {
ELECTION_STATE.with(|old_state| {
let state_ref = old_state.borrow();
state_ref
.get(&identifier.encode())
.map(|v| ES::ElectionState::decode(&mut &v[..]).unwrap())
.unwrap()
})
}

pub fn set_election_properties<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
properties: ES::ElectionProperties,
) {
Expand All @@ -279,6 +269,18 @@ impl MockStorageAccess {
});
}

pub fn election_properties<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
) -> ES::ElectionProperties {
ELECTION_PROPERTIES.with(|old_properties| {
let properties_ref = old_properties.borrow();
properties_ref
.get(&identifier.encode())
.map(|v| ES::ElectionProperties::decode(&mut &v[..]).unwrap())
.unwrap()
})
}

pub fn set_unsynchronised_state<ES: ElectoralSystem>(
unsynchronised_state: ES::ElectoralUnsynchronisedState,
) {
Expand Down Expand Up @@ -336,6 +338,16 @@ impl MockStorageAccess {
})
}

pub fn set_consensus_status<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
status: ConsensusStatus<ES::Consensus>,
) {
CONSENSUS_STATUS.with(|old_consensus| {
let mut consensus_ref = old_consensus.borrow_mut();
consensus_ref.insert(identifier.encode(), status.encode());
});
}

pub fn consensus_status<ES: ElectoralSystem>(
identifier: ElectionIdentifierOf<ES>,
) -> ConsensusStatus<ES::Consensus> {
Expand All @@ -348,4 +360,19 @@ impl MockStorageAccess {
})
.unwrap()
}

pub fn new_election<ES: ElectoralSystem>(
extra: <ES as ElectoralSystem>::ElectionIdentifierExtra,
properties: <ES as ElectoralSystem>::ElectionProperties,
state: <ES as ElectoralSystem>::ElectionState,
) -> ElectionIdentifierOf<ES> {
let next_umi = Self::next_umi();
let election_identifier = ElectionIdentifier::new(next_umi, extra);
Self::increment_next_umi();

Self::set_election_properties::<ES>(election_identifier, properties);
Self::set_state::<ES>(election_identifier, state);

election_identifier
}
}

0 comments on commit 51b497c

Please sign in to comment.