Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
41a64b8
typed-index crate
tifecool Apr 23, 2022
53ede12
Implementation of TypeIndex for validators (TypeInfo implementation p…
tifecool Apr 27, 2022
927900f
Merge branch 'paritytech:master' into fix2403
tifecool Apr 27, 2022
0531b9d
Temporary Fix
tifecool Apr 27, 2022
4db6034
Temp
tifecool Apr 29, 2022
5b5875a
Merge branch 'paritytech:master' into fix2403
tifecool Apr 29, 2022
1864bfd
Util methods updated
tifecool May 4, 2022
ea5ff34
Merge remote-tracking branch 'origin/fix2403' into fix2403
tifecool May 4, 2022
9cf63d2
Removed Into trait
tifecool May 8, 2022
e0c332f
Updated Tests
tifecool May 8, 2022
3fd4e1c
Fixed split_active_subset function
tifecool May 9, 2022
4f8f464
Added TypeVec implementation for validator_groups and updated tests.
tifecool May 11, 2022
8d89add
nightly fmt
tifecool May 11, 2022
1ca2a12
Merge branch 'master' into fix2403
tifecool May 11, 2022
3525a4e
Merge branch 'master' into fix2403
tifecool May 14, 2022
731bd7a
TypeVec From Vec consumes vector
tifecool May 14, 2022
72087ec
_usize & _u32 implementation over as implementation
tifecool May 15, 2022
176800c
minor adjustments
tifecool May 15, 2022
8d9a856
Fixes and nightly fmt
tifecool May 15, 2022
49ebd7a
Struct and function documentation
tifecool May 15, 2022
6e459e1
Merge branch 'master' into fix2403
tifecool May 17, 2022
d3ebca9
update
tifecool May 17, 2022
a601db8
fmt
tifecool May 17, 2022
d51852f
reward_points.rs updated
tifecool May 17, 2022
d4a584c
Merge branch 'master' into fix2403
tifecool May 19, 2022
ff5a99e
Cargo.lock fix
tifecool May 19, 2022
c51ca88
polkadot lib.rs fix
tifecool May 19, 2022
6343736
polkadot lib.rs fix
tifecool May 19, 2022
dcd6e8e
Merge remote-tracking branch 'origin/fix2403' into fix2403
tifecool May 19, 2022
e441256
fmt
tifecool May 19, 2022
5ff6d05
Merge branch 'master' into fix2403
tifecool May 20, 2022
6ed1f84
FromVec update
tifecool May 20, 2022
42883ec
MallocSizeOf update
tifecool May 25, 2022
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
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions node/core/approval-voting/src/criteria.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ use polkadot_node_primitives::approval::{
self as approval_types, AssignmentCert, AssignmentCertKind, DelayTranche, RelayVRFStory,
};
use polkadot_primitives::v2::{
AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, SessionInfo, ValidatorIndex,
AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, SessionInfo, TypeVec,
ValidatorIndex,
};
use sc_keystore::LocalKeystore;
use sp_application_crypto::ByteArray;
Expand Down Expand Up @@ -138,7 +139,7 @@ pub(crate) struct Config {
/// The assignment public keys for validators.
assignment_keys: Vec<AssignmentId>,
/// The groups of validators assigned to each core.
validator_groups: Vec<Vec<ValidatorIndex>>,
validator_groups: TypeVec<GroupIndex, Vec<ValidatorIndex>>,
/// The number of availability cores used by the protocol during this session.
n_cores: u32,
/// The zeroth delay tranche width.
Expand Down Expand Up @@ -631,10 +632,10 @@ mod tests {
Sr25519Keyring::Bob,
Sr25519Keyring::Charlie,
]),
validator_groups: vec![
validator_groups: TypeVec::from(vec![
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should consider adding a custom macro that resembles the ergonomy of vec![..]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't write macros.

vec![ValidatorIndex(0)],
vec![ValidatorIndex(1), ValidatorIndex(2)],
],
]),
n_cores: 2,
zeroth_delay_tranche_width: 10,
relay_vrf_modulo_samples: 3,
Expand Down Expand Up @@ -666,10 +667,10 @@ mod tests {
Sr25519Keyring::Bob,
Sr25519Keyring::Charlie,
]),
validator_groups: vec![
validator_groups: TypeVec::from(vec![
vec![ValidatorIndex(0)],
vec![ValidatorIndex(1), ValidatorIndex(2)],
],
]),
n_cores: 2,
zeroth_delay_tranche_width: 10,
relay_vrf_modulo_samples: 3,
Expand All @@ -696,7 +697,7 @@ mod tests {
Sr25519Keyring::Bob,
Sr25519Keyring::Charlie,
]),
validator_groups: vec![],
validator_groups: TypeVec::from(vec![]),
n_cores: 0,
zeroth_delay_tranche_width: 10,
relay_vrf_modulo_samples: 3,
Expand Down Expand Up @@ -733,7 +734,7 @@ mod tests {
&[Sr25519Keyring::Alice],
n_validators - 1,
),
validator_groups: basic_groups(n_validators, n_cores),
validator_groups: TypeVec::from(basic_groups(n_validators, n_cores)),
n_cores: n_cores as u32,
zeroth_delay_tranche_width: 10,
relay_vrf_modulo_samples: 3,
Expand Down
15 changes: 9 additions & 6 deletions node/core/approval-voting/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use polkadot_node_subsystem_util::{
};
use polkadot_primitives::v2::{
BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, ConsensusLog, CoreIndex,
GroupIndex, Hash, Header, SessionIndex,
GroupIndex, Hash, Header, SessionIndex, TypeVec,
};
use sc_keystore::LocalKeystore;
use sp_consensus_slots::Slot;
Expand Down Expand Up @@ -612,7 +612,7 @@ pub(crate) mod tests {
use polkadot_node_subsystem::messages::AllMessages;
use polkadot_node_subsystem_test_helpers::make_subsystem_context;
use polkadot_node_subsystem_util::database::Database;
use polkadot_primitives::v2::{SessionInfo, ValidatorIndex};
use polkadot_primitives::v2::{SessionInfo, TypeVec, ValidatorIndex};
pub(crate) use sp_consensus_babe::{
digests::{CompatibleDigestItem, PreDigest, SecondaryVRFPreDigest},
AllowedSlots, BabeEpochConfiguration, Epoch as BabeEpoch,
Expand Down Expand Up @@ -705,10 +705,10 @@ pub(crate) mod tests {

fn dummy_session_info(index: SessionIndex) -> SessionInfo {
SessionInfo {
validators: Vec::new(),
validators: TypeVec::new(),
discovery_keys: Vec::new(),
assignment_keys: Vec::new(),
validator_groups: Vec::new(),
validator_groups: TypeVec::new(),
n_cores: index as _,
zeroth_delay_tranche_width: index as _,
relay_vrf_modulo_samples: index as _,
Expand Down Expand Up @@ -1163,10 +1163,13 @@ pub(crate) mod tests {
let session = 5;
let irrelevant = 666;
let session_info = SessionInfo {
validators: vec![Sr25519Keyring::Alice.public().into(); 6],
validators: TypeVec::from(vec![Sr25519Keyring::Alice.public().into(); 6]),
discovery_keys: Vec::new(),
assignment_keys: Vec::new(),
validator_groups: vec![vec![ValidatorIndex(0); 5], vec![ValidatorIndex(0); 2]],
validator_groups: TypeVec::from(vec![
vec![ValidatorIndex(0); 5],
vec![ValidatorIndex(0); 2],
]),
n_cores: 6,
needed_approvals: 2,
zeroth_delay_tranche_width: irrelevant,
Expand Down
8 changes: 4 additions & 4 deletions node/network/statement-distribution/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ use polkadot_node_subsystem_util::{self as util, rand, MIN_GOSSIP_PEERS};

use polkadot_primitives::v2::{
AuthorityDiscoveryId, CandidateHash, CommittedCandidateReceipt, CompactStatement, Hash,
SignedStatement, SigningContext, UncheckedSignedStatement, ValidatorId, ValidatorIndex,
ValidatorSignature,
SignedStatement, SigningContext, TypeVec, UncheckedSignedStatement, ValidatorId,
ValidatorIndex, ValidatorSignature,
};
use polkadot_subsystem::{
jaeger,
Expand Down Expand Up @@ -668,7 +668,7 @@ struct ActiveHeadData {
/// Large statements we are waiting for with associated meta data.
waiting_large_statements: HashMap<CandidateHash, LargeStatementStatus>,
/// The parachain validators at the head's child session index.
validators: Vec<ValidatorId>,
validators: TypeVec<ValidatorIndex, ValidatorId>,
/// The current session index of this fork.
session_index: sp_staking::SessionIndex,
/// How many `Seconded` statements we've seen per validator.
Expand All @@ -679,7 +679,7 @@ struct ActiveHeadData {

impl ActiveHeadData {
fn new(
validators: Vec<ValidatorId>,
validators: TypeVec<ValidatorIndex, ValidatorId>,
session_index: sp_staking::SessionIndex,
span: PerLeafSpan,
) -> Self {
Expand Down
6 changes: 3 additions & 3 deletions node/subsystem-util/src/rolling_session_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,17 +276,17 @@ mod tests {
use assert_matches::assert_matches;
use polkadot_node_subsystem::messages::{AllMessages, AvailabilityRecoveryMessage};
use polkadot_node_subsystem_test_helpers::make_subsystem_context;
use polkadot_primitives::v2::Header;
use polkadot_primitives::v2::{Header, TypeVec};
use sp_core::testing::TaskExecutor;

pub const TEST_WINDOW_SIZE: SessionWindowSize = new_session_window_size!(6);

fn dummy_session_info(index: SessionIndex) -> SessionInfo {
SessionInfo {
validators: Vec::new(),
validators: TypeVec::new(),
discovery_keys: Vec::new(),
assignment_keys: Vec::new(),
validator_groups: Vec::new(),
validator_groups: TypeVec::new(),
n_cores: index as _,
zeroth_delay_tranche_width: index as _,
relay_vrf_modulo_samples: index as _,
Expand Down
2 changes: 2 additions & 0 deletions primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"

[dependencies]
typed-index-collections = { version = "3.0.3", default-features = false, features = ["alloc","serde","serde-alloc"] }
serde = { version = "1.0.137", optional = true, features = ["derive"] }
scale-info = { version = "2.1.1", default-features = false, features = ["bit-vec", "derive"] }
parity-scale-codec = { version = "3.1.2", default-features = false, features = ["bit-vec", "derive"] }
Expand Down Expand Up @@ -54,5 +55,6 @@ std = [
"polkadot-core-primitives/std",
"bitvec/std",
"frame-system/std",
"typed-index-collections/std"
]
runtime-benchmarks = []
110 changes: 98 additions & 12 deletions primitives/src/v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
//! `V1` Primitives.

use bitvec::vec::BitVec;
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use parity_scale_codec::{Decode, Encode, WrapperTypeDecode, WrapperTypeEncode};
use scale_info::{Type, TypeInfo};
use sp_std::prelude::*;
use std::ops::{Deref, DerefMut};
use typed_index_collections::TiVec;

use application_crypto::KeyTypeId;
use inherents::InherentIdentifier;
Expand Down Expand Up @@ -53,9 +55,11 @@ pub use sp_staking::SessionIndex;

/// Signed data.
mod signed;

pub use signed::{EncodeAs, Signed, UncheckedSigned};

mod metrics;

pub use metrics::{
metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues,
RuntimeMetricLabels, RuntimeMetricOp, RuntimeMetricUpdate,
Expand Down Expand Up @@ -135,6 +139,20 @@ impl From<u32> for ValidatorIndex {
}
}

impl From<ValidatorIndex> for usize {
fn from(n: ValidatorIndex) -> Self {
n.0 as usize
}
}

impl From<usize> for ValidatorIndex {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need an impl for From<usize> if it's not guaranteed to be ok? Wouldn't a From<u32> not make more sense and leave it to the user to decide what to do on errors instead of generating a garbage ValidatorIndex? TryFrom<usize> and From<u32> seem more reasonable to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While working on this, the error:

the trait bound `K: From<usize>` is not satisfied
    --> primitives/src/v2/mod.rs:1616:17
     |
1616 | #[derive(Clone, RuntimeDebug)]
     |                 ^^^^^^^^^^^^ the trait `From<usize>` is not implemented for `K`

came up. This is why I likely implemented the From<usize> trait.

fn from(n: usize) -> Self {
// can't panic, so need to truncate
let n = n.try_into().unwrap_or(u32::MAX);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

debug_assert would be good.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would I implement this?

ValidatorIndex(n)
}
}

application_crypto::with_pair! {
/// A Parachain validator keypair.
pub type ValidatorPair = validator_app::Pair;
Expand Down Expand Up @@ -790,6 +808,14 @@ impl From<u32> for GroupIndex {
}
}

impl From<usize> for GroupIndex {
fn from(n: usize) -> Self {
// can't panic, so need to truncate
let n = n.try_into().unwrap_or(u32::MAX);
GroupIndex(n)
}
}

/// A claim on authoring the next block for a given parathread.
#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(PartialEq))]
Expand Down Expand Up @@ -1394,9 +1420,11 @@ pub type CheckedMultiDisputeStatementSet = Vec<CheckedDisputeStatementSet>;
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, TypeInfo)]
pub struct DisputeState<N = BlockNumber> {
/// A bitfield indicating all validators for the candidate.
pub validators_for: BitVec<u8, bitvec::order::Lsb0>, // one bit per validator.
pub validators_for: BitVec<u8, bitvec::order::Lsb0>,
// one bit per validator.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please revert unrelated formatting changes, we're using a specific nightly version for fmt

/// A bitfield indicating all validators against the candidate.
pub validators_against: BitVec<u8, bitvec::order::Lsb0>, // one bit per validator.
pub validators_against: BitVec<u8, bitvec::order::Lsb0>,
// one bit per validator.
/// The block number at which the dispute started on-chain.
pub start: N,
/// The block number at which the dispute concluded on-chain.
Expand Down Expand Up @@ -1582,6 +1610,64 @@ pub fn supermajority_threshold(n: usize) -> usize {
n - byzantine_threshold(n)
}

#[derive(Clone, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct TypeVec<K: From<usize>, V: Clone>(TiVec<K, V>);

impl<K: From<usize>, V: Clone> TypeVec<K, V> {
pub fn new() -> Self {
TypeVec::<K, V> { 0: TiVec::<K, V>::new() }
}
}

impl<K: From<usize>, V: Clone> From<Vec<V>> for TypeVec<K, V> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
impl<K: From<usize>, V: Clone> From<Vec<V>> for TypeVec<K, V> {
impl<K: From<usize>, V: Clone, I: IntoIterator<Item=V>> From<I> for TypeVec<K, V> {

fn from(vec: Vec<V>) -> Self {
let mut type_vec: TypeVec<K, V> = TypeVec::new();
for value in vec.iter() {
type_vec.0.push(value.clone())
}
type_vec
}
}

#[cfg(feature = "std")]
impl<K: From<usize>, V: Clone> MallocSizeOf for TypeVec<K, V> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

incorrect, should delegate to Vec impl

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Attempting this is causing issues.

Copy link
Copy Markdown
Contributor Author

@tifecool tifecool May 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#[cfg(feature = "std")]
has to be implemented in numerous places to trait bound generic type V

Copy link
Copy Markdown
Contributor Author

@tifecool tifecool May 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Attempted implementation:

#[cfg(feature = "std")]
impl<K: From<usize>, V: Clone> MallocSizeOf for TypeVec<K, V> {
	fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
		self.to_vec().size_of(ops)
	}
}

}
fn constant_size() -> Option<usize> {
Some(0)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

incorrect, shouldn't be implemented

}
}

impl<K: From<usize>, V: Clone> Deref for TypeVec<K, V> {
type Target = Vec<V>;

fn deref(&self) -> &Self::Target {
&self.0.raw
}
}

impl<K: From<usize>, V: Clone> DerefMut for TypeVec<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0.raw
}
}

impl<K: From<usize>, V: Clone> WrapperTypeEncode for TypeVec<K, V> {}

impl<K: From<usize>, V: Clone> WrapperTypeDecode for TypeVec<K, V> {
type Wrapped = Vec<V>;
}

impl<K: From<usize>, V: Clone> TypeInfo for TypeVec<K, V> {
type Identity = ();

fn type_info() -> Type {
todo!()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Must be fixed before merge

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not quite sure how to implement this trait.

}
}

/// Information about validator sets of a session.
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))]
Expand All @@ -1603,7 +1689,7 @@ pub struct SessionInfo {
/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
///
/// `SessionInfo::validators` will be limited to to `max_validators` when set.
pub validators: Vec<ValidatorId>,
pub validators: TypeVec<ValidatorIndex, ValidatorId>,
/// Validators' authority discovery keys for the session in canonical ordering.
///
/// NOTE: The first `validators.len()` entries will match the corresponding validators in
Expand All @@ -1620,13 +1706,13 @@ pub struct SessionInfo {
///
/// Therefore:
/// ```ignore
/// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
/// ```
/// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
/// ```
pub assignment_keys: Vec<AssignmentId>,
/// Validators in shuffled ordering - these are the validator groups as produced
/// by the `Scheduler` module for the session and are typically referred to by
/// `GroupIndex`.
pub validator_groups: Vec<Vec<ValidatorIndex>>,
pub validator_groups: TypeVec<GroupIndex, Vec<ValidatorIndex>>,
/// The number of availability cores used by the protocol during this session.
pub n_cores: u32,
/// The zeroth delay tranche width.
Expand Down Expand Up @@ -1679,7 +1765,7 @@ pub struct OldV1SessionInfo {
/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
///
/// `SessionInfo::validators` will be limited to to `max_validators` when set.
pub validators: Vec<ValidatorId>,
pub validators: TypeVec<ValidatorIndex, ValidatorId>,
/// Validators' authority discovery keys for the session in canonical ordering.
///
/// NOTE: The first `validators.len()` entries will match the corresponding validators in
Expand All @@ -1696,13 +1782,13 @@ pub struct OldV1SessionInfo {
///
/// Therefore:
/// ```ignore
/// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
/// ```
/// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
/// ```
pub assignment_keys: Vec<AssignmentId>,
/// Validators in shuffled ordering - these are the validator groups as produced
/// by the `Scheduler` module for the session and are typically referred to by
/// `GroupIndex`.
pub validator_groups: Vec<Vec<ValidatorIndex>>,
pub validator_groups: TypeVec<GroupIndex, Vec<ValidatorIndex>>,
/// The number of availability cores used by the protocol during this session.
pub n_cores: u32,
/// The zeroth delay tranche width.
Expand Down
Loading