session-info: add new fields + migration (#4545)

* session_info: v2 + migration

* use primitives::v2

* use polkadot_primitives::v2

* impl primitives::v2

* fix approval-voting tests

* fix other tests

* hook storage migration up

* backwards compat (1)

* backwards compat (2)

* fmt

* fix tests

* FMT

* do not reexport v1 in v2

* fmt

* set storage version to 1

Co-authored-by: Javier Viola <javier@parity.io>
This commit is contained in:
Andronik Ordian
2021-12-27 09:01:30 +01:00
committed by GitHub
parent 2e360f0aac
commit b342ae11d3
38 changed files with 542 additions and 299 deletions
+3 -2
View File
@@ -19,8 +19,9 @@
//! Provides the [`AbstractClient`] trait that is a super trait that combines all the traits the client implements.
//! There is also the [`Client`] enum that combines all the different clients into one common structure.
use polkadot_primitives::v1::{
AccountId, Balance, Block, BlockNumber, Hash, Header, Nonce, ParachainHost,
use polkadot_primitives::{
v1::{AccountId, Balance, Block, BlockNumber, Hash, Header, Nonce},
v2::ParachainHost,
};
use sc_client_api::{AuxStore, Backend as BackendT, BlockchainEvents, KeyIterator, UsageProvider};
use sc_executor::NativeElseWasmExecutor;
@@ -20,8 +20,9 @@ use parity_scale_codec::{Decode, Encode};
use polkadot_node_primitives::approval::{
self as approval_types, AssignmentCert, AssignmentCertKind, DelayTranche, RelayVRFStory,
};
use polkadot_primitives::v1::{
AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, SessionInfo, ValidatorIndex,
use polkadot_primitives::{
v1::{AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, ValidatorIndex},
v2::SessionInfo,
};
use sc_keystore::LocalKeystore;
use sp_application_crypto::ByteArray;
@@ -582,7 +582,7 @@ pub(crate) mod tests {
use polkadot_node_primitives::approval::{VRFOutput, VRFProof};
use polkadot_node_subsystem::messages::AllMessages;
use polkadot_node_subsystem_test_helpers::make_subsystem_context;
use polkadot_primitives::v1::{SessionInfo, ValidatorIndex};
use polkadot_primitives::{v1::ValidatorIndex, v2::SessionInfo};
pub(crate) use sp_consensus_babe::{
digests::{CompatibleDigestItem, PreDigest, SecondaryVRFPreDigest},
AllowedSlots, BabeEpochConfiguration, Epoch as BabeEpoch,
@@ -685,6 +685,7 @@ pub(crate) mod tests {
n_delay_tranches: index as _,
no_show_slots: index as _,
needed_approvals: index as _,
active_validator_indices: Vec::new(),
}
}
@@ -1140,6 +1141,7 @@ pub(crate) mod tests {
relay_vrf_modulo_samples: irrelevant,
n_delay_tranches: irrelevant,
no_show_slots: irrelevant,
active_validator_indices: Vec::new(),
};
let slot = Slot::from(10);
@@ -50,10 +50,13 @@ use polkadot_node_subsystem_util::{
},
TimeoutExt,
};
use polkadot_primitives::v1::{
ApprovalVote, BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, DisputeStatement,
GroupIndex, Hash, SessionIndex, SessionInfo, ValidDisputeStatementKind, ValidatorId,
ValidatorIndex, ValidatorPair, ValidatorSignature,
use polkadot_primitives::{
v1::{
ApprovalVote, BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt,
DisputeStatement, GroupIndex, Hash, SessionIndex, ValidDisputeStatementKind, ValidatorId,
ValidatorIndex, ValidatorPair, ValidatorSignature,
},
v2::SessionInfo,
};
use sc_keystore::LocalKeystore;
use sp_application_crypto::Pair;
+24 -72
View File
@@ -740,6 +740,22 @@ impl ChainBuilder {
}
}
fn session_info(keys: &[Sr25519Keyring]) -> SessionInfo {
SessionInfo {
validators: keys.iter().map(|v| v.public().into()).collect(),
discovery_keys: keys.iter().map(|v| v.public().into()).collect(),
assignment_keys: keys.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![vec![ValidatorIndex(0)], vec![ValidatorIndex(1)]],
n_cores: keys.len() as _,
needed_approvals: 2,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
active_validator_indices: vec![],
}
}
async fn import_block(
overseer: &mut VirtualOverseer,
hashes: &[(Hash, Header)],
@@ -757,18 +773,7 @@ async fn import_block(
let session_info = config.session_info.clone().unwrap_or({
let validators = vec![Sr25519Keyring::Alice, Sr25519Keyring::Bob];
SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![vec![ValidatorIndex(0)], vec![ValidatorIndex(1)]],
n_cores: validators.len() as _,
needed_approvals: 1,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
}
SessionInfo { needed_approvals: 1, ..session_info(&validators) }
});
overseer_send(
@@ -1452,20 +1457,13 @@ fn subsystem_second_approval_import_only_schedules_wakeups() {
Sr25519Keyring::Eve,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 1,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
// Add block hash 0x01...
@@ -1763,20 +1761,12 @@ fn import_checked_approval_updates_entries_and_schedules() {
Sr25519Keyring::Eve,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
let candidate_descriptor = make_candidate(1.into(), &block_hash);
@@ -1923,20 +1913,12 @@ fn subsystem_import_checked_approval_sets_one_block_bit_at_a_time() {
Sr25519Keyring::Eve,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
ChainBuilder::new()
@@ -2209,20 +2191,12 @@ fn subsystem_validate_approvals_cache() {
Sr25519Keyring::Eve,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
let candidates = Some(vec![(candidate_receipt.clone(), CoreIndex(0), GroupIndex(0))]);
@@ -2422,20 +2396,14 @@ where
Sr25519Keyring::Ferdie,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2), ValidatorIndex(3)],
vec![ValidatorIndex(4), ValidatorIndex(5)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 2,
n_delay_tranches: 50,
no_show_slots,
..session_info(&validators)
};
ChainBuilder::new()
@@ -2740,20 +2708,12 @@ fn pre_covers_dont_stall_approval() {
Sr25519Keyring::One,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2), ValidatorIndex(5)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
let candidate_descriptor = make_candidate(1.into(), &block_hash);
@@ -2920,20 +2880,12 @@ fn waits_until_approving_assignments_are_old_enough() {
Sr25519Keyring::One,
];
let session_info = SessionInfo {
validators: validators.iter().map(|v| v.public().into()).collect(),
validator_groups: vec![
vec![ValidatorIndex(0), ValidatorIndex(1)],
vec![ValidatorIndex(2), ValidatorIndex(5)],
vec![ValidatorIndex(3), ValidatorIndex(4)],
],
needed_approvals: 2,
discovery_keys: validators.iter().map(|v| v.public().into()).collect(),
assignment_keys: validators.iter().map(|v| v.public().into()).collect(),
n_cores: validators.len() as _,
zeroth_delay_tranche_width: 5,
relay_vrf_modulo_samples: 3,
n_delay_tranches: 50,
no_show_slots: 2,
..session_info(&validators)
};
let candidate_descriptor = make_candidate(1.into(), &block_hash);
@@ -39,10 +39,13 @@ use polkadot_node_subsystem::{
use polkadot_node_subsystem_util::rolling_session_window::{
RollingSessionWindow, SessionWindowUpdate,
};
use polkadot_primitives::v1::{
byzantine_threshold, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement,
DisputeStatement, DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex, SessionInfo,
ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature,
use polkadot_primitives::{
v1::{
byzantine_threshold, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement,
DisputeStatement, DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex,
ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature,
},
v2::SessionInfo,
};
use crate::{metrics::Metrics, real::DisputeCoordinatorSubsystem, LOG_TARGET};
@@ -54,10 +54,13 @@ use polkadot_node_subsystem::{
ActivatedLeaf, ActiveLeavesUpdate, LeafStatus,
};
use polkadot_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle};
use polkadot_primitives::v1::{
BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, CandidateReceipt, Hash, HashT,
Header, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidatorId,
ValidatorIndex,
use polkadot_primitives::{
v1::{
BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, CandidateReceipt, Hash,
HashT, Header, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo,
};
use crate::{
@@ -313,6 +316,7 @@ impl TestState {
n_delay_tranches: 100,
no_show_slots: 1,
needed_approvals: 10,
active_validator_indices: Vec::new(),
}
}
+9 -6
View File
@@ -20,12 +20,15 @@ use memory_lru::{MemoryLruCache, ResidentSize};
use parity_util_mem::{MallocSizeOf, MallocSizeOfExt};
use sp_consensus_babe::Epoch;
use polkadot_primitives::v1::{
AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent,
CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash, Id as ParaId,
InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData,
PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent,
CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash, Id as ParaId,
InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption,
PersistedValidationData, ScrapedOnChainVotes, SessionIndex, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
},
v2::{PvfCheckStatement, SessionInfo},
};
const AUTHORITIES_CACHE_SIZE: usize = 128 * 1024;
+40 -3
View File
@@ -23,7 +23,10 @@
#![warn(missing_docs)]
use polkadot_node_subsystem_util::metrics::{self, prometheus};
use polkadot_primitives::v1::{Block, BlockId, Hash, ParachainHost};
use polkadot_primitives::{
v1::{Block, BlockId, Hash},
v2::ParachainHost,
};
use polkadot_subsystem::{
errors::RuntimeApiError,
messages::{RuntimeApiMessage, RuntimeApiRequest as Request},
@@ -429,8 +432,42 @@ where
),
Request::CandidateEvents(sender) =>
query!(CandidateEvents, candidate_events(), ver = 1, sender),
Request::SessionInfo(index, sender) =>
query!(SessionInfo, session_info(index), ver = 1, sender),
Request::SessionInfo(index, sender) => {
use sp_api::ApiExt;
let api = client.runtime_api();
let block_id = BlockId::Hash(relay_parent);
let api_version = api
.api_version::<dyn ParachainHost<Block>>(&BlockId::Hash(relay_parent))
.unwrap_or_default()
.unwrap_or_default();
let res = if api_version >= 2 {
let res =
api.session_info(&block_id, index).map_err(|e| RuntimeApiError::Execution {
runtime_api_name: "SessionInfo",
source: std::sync::Arc::new(e),
});
metrics.on_request(res.is_ok());
res
} else {
#[allow(deprecated)]
let res = api.session_info_before_version_2(&block_id, index).map_err(|e| {
RuntimeApiError::Execution {
runtime_api_name: "SessionInfo",
source: std::sync::Arc::new(e),
}
});
metrics.on_request(res.is_ok());
res.map(|r| r.map(|old| old.into()))
};
let _ = sender.send(res.clone());
res.ok().map(|res| RequestResult::SessionInfo(relay_parent, index, res))
},
Request::DmqContents(id, sender) => query!(DmqContents, dmq_contents(id), ver = 1, sender),
Request::InboundHrmpChannelsContents(id, sender) =>
query!(InboundHrmpChannelsContents, inbound_hrmp_channels_contents(id), ver = 1, sender),
+9 -5
View File
@@ -20,11 +20,14 @@ use ::test_helpers::{dummy_committed_candidate_receipt, dummy_validation_code};
use futures::channel::oneshot;
use polkadot_node_primitives::{BabeAllowedSlots, BabeEpoch, BabeEpochConfiguration};
use polkadot_node_subsystem_test_helpers::make_subsystem_context;
use polkadot_primitives::v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo,
Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption,
PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState,
GroupRotationInfo, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, SessionIndex,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
},
v2::{PvfCheckStatement, SessionInfo},
};
use sp_core::testing::TaskExecutor;
use std::{
@@ -508,6 +511,7 @@ fn dummy_session_info() -> SessionInfo {
n_delay_tranches: 2u32,
no_show_slots: 0u32,
needed_approvals: 1u32,
active_validator_indices: vec![],
}
}
#[test]
@@ -22,10 +22,13 @@ use sp_keyring::Sr25519Keyring;
use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks};
use polkadot_node_primitives::{AvailableData, BlockData, ErasureChunk, PoV, Proof};
use polkadot_primitives::v1::{
CandidateCommitments, CandidateDescriptor, CandidateHash, CommittedCandidateReceipt,
GroupIndex, Hash, HeadData, Id as ParaId, OccupiedCore, PersistedValidationData, SessionInfo,
ValidatorIndex,
use polkadot_primitives::{
v1::{
CandidateCommitments, CandidateDescriptor, CandidateHash, CommittedCandidateReceipt,
GroupIndex, Hash, HeadData, Id as ParaId, OccupiedCore, PersistedValidationData,
ValidatorIndex,
},
v2::SessionInfo,
};
use polkadot_primitives_test_helpers::{
dummy_collator, dummy_collator_signature, dummy_hash, dummy_validation_code,
@@ -61,6 +64,7 @@ pub fn make_session_info() -> SessionInfo {
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: Vec::new(),
}
}
@@ -39,9 +39,9 @@ use polkadot_node_network_protocol::{
request_response::{v1, IncomingRequest, OutgoingRequest, Requests},
};
use polkadot_node_primitives::ErasureChunk;
use polkadot_primitives::v1::{
CandidateHash, CoreState, GroupIndex, Hash, Id as ParaId, ScheduledCore, SessionInfo,
ValidatorIndex,
use polkadot_primitives::{
v1::{CandidateHash, CoreState, GroupIndex, Hash, Id as ParaId, ScheduledCore, ValidatorIndex},
v2::SessionInfo,
};
use polkadot_subsystem::{
messages::{
@@ -48,9 +48,12 @@ use polkadot_node_network_protocol::{
};
use polkadot_node_primitives::{AvailableData, ErasureChunk};
use polkadot_node_subsystem_util::request_session_info;
use polkadot_primitives::v1::{
AuthorityDiscoveryId, BlakeTwo256, BlockNumber, CandidateHash, CandidateReceipt, GroupIndex,
Hash, HashT, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, BlakeTwo256, BlockNumber, CandidateHash, CandidateReceipt,
GroupIndex, Hash, HashT, SessionIndex, ValidatorId, ValidatorIndex,
},
v2::SessionInfo,
};
use polkadot_subsystem::{
errors::RecoveryError,
@@ -220,6 +220,7 @@ impl TestState {
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: vec![],
}))).unwrap();
}
);
@@ -32,9 +32,12 @@ use sp_runtime::traits::AppVerify;
use polkadot_node_network_protocol::{our_view, request_response::IncomingRequest, view};
use polkadot_node_primitives::BlockData;
use polkadot_node_subsystem_util::TimeoutExt;
use polkadot_primitives::v1::{
AuthorityDiscoveryId, CollatorPair, GroupRotationInfo, ScheduledCore, SessionIndex,
SessionInfo, ValidatorId, ValidatorIndex,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, CollatorPair, GroupRotationInfo, ScheduledCore, SessionIndex,
ValidatorId, ValidatorIndex,
},
v2::SessionInfo,
};
use polkadot_primitives_test_helpers::TestCandidateBuilder;
use polkadot_subsystem::{
@@ -110,6 +113,7 @@ impl Default for TestState {
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: vec![],
},
group_rotation_info,
validator_peer_id,
@@ -32,9 +32,12 @@ use sp_keyring::Sr25519Keyring;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use polkadot_node_primitives::{DisputeMessage, SignedDisputeStatement};
use polkadot_primitives::v1::{
AuthorityDiscoveryId, CandidateHash, CandidateReceipt, Hash, SessionIndex, SessionInfo,
ValidatorId, ValidatorIndex,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, CandidateHash, CandidateReceipt, Hash, SessionIndex, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo,
};
use polkadot_primitives_test_helpers::dummy_candidate_descriptor;
@@ -86,6 +89,7 @@ pub static ref MOCK_SESSION_INFO: SessionInfo =
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: vec![],
};
/// `SessionInfo` for the second session. (No more validators, but two more authorities.
@@ -105,6 +109,7 @@ pub static ref MOCK_NEXT_SESSION_INFO: SessionInfo =
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: vec![],
};
}
@@ -41,8 +41,9 @@ use polkadot_node_network_protocol::{
IfDisconnected,
};
use polkadot_node_primitives::{CandidateVotes, UncheckedDisputeMessage};
use polkadot_primitives::v1::{
AuthorityDiscoveryId, CandidateHash, Hash, SessionIndex, SessionInfo,
use polkadot_primitives::{
v1::{AuthorityDiscoveryId, CandidateHash, Hash, SessionIndex},
v2::SessionInfo,
};
use polkadot_subsystem::{
messages::{
@@ -28,7 +28,7 @@ use polkadot_node_network_protocol::{
};
use polkadot_node_primitives::Statement;
use polkadot_node_subsystem_test_helpers::mock::make_ferdie_keystore;
use polkadot_primitives::v1::{SessionInfo, ValidationCode};
use polkadot_primitives::{v1::ValidationCode, v2::SessionInfo};
use polkadot_primitives_test_helpers::{dummy_committed_candidate_receipt, dummy_hash};
use polkadot_subsystem::{
jaeger,
@@ -1851,5 +1851,6 @@ fn make_session_info(validators: Vec<Pair>, groups: Vec<Vec<u32>>) -> SessionInf
n_delay_tranches: 0,
no_show_slots: 0,
needed_approvals: 0,
active_validator_indices: Vec::new(),
}
}
+4 -1
View File
@@ -71,7 +71,10 @@ use futures::{channel::oneshot, future::BoxFuture, select, Future, FutureExt, St
use lru::LruCache;
use client::{BlockImportNotification, BlockchainEvents, FinalityNotification};
use polkadot_primitives::v1::{Block, BlockId, BlockNumber, Hash, ParachainHost};
use polkadot_primitives::{
v1::{Block, BlockId, BlockNumber, Hash},
v2::ParachainHost,
};
use sp_api::{ApiExt, ProvideRuntimeApi};
use polkadot_node_network_protocol::v1 as protocol_v1;
@@ -23,11 +23,11 @@ use thiserror::Error;
use parity_scale_codec::{Decode, Encode};
use polkadot_primitives::v1::{
CandidateReceipt, DisputeStatement, SessionIndex, SessionInfo, ValidatorIndex,
};
use super::{InvalidDisputeVote, SignedDisputeStatement, ValidDisputeVote};
use polkadot_primitives::{
v1::{CandidateReceipt, DisputeStatement, SessionIndex, ValidatorIndex},
v2::SessionInfo,
};
/// A dispute initiating/participating message that is guaranteed to have been built from signed
/// statements.
+1 -1
View File
@@ -53,7 +53,7 @@ pub use sp_core::traits::SpawnNamed;
#[cfg(feature = "full-node")]
pub use {
polkadot_overseer::{Handle, Overseer, OverseerConnector, OverseerHandle},
polkadot_primitives::v1::ParachainHost,
polkadot_primitives::v2::ParachainHost,
relay_chain_selection::SelectRelayChain,
sc_client_api::AuxStore,
sp_authority_discovery::AuthorityDiscoveryApi,
+1 -1
View File
@@ -34,7 +34,7 @@ use polkadot_overseer::{
OverseerConnector, OverseerHandle,
};
use polkadot_primitives::v1::ParachainHost;
use polkadot_primitives::v2::ParachainHost;
use sc_authority_discovery::Service as AuthorityDiscoveryService;
use sc_client_api::AuxStore;
use sc_keystore::LocalKeystore;
+11 -8
View File
@@ -38,14 +38,17 @@ use polkadot_node_primitives::{
CollationSecondedSignal, DisputeMessage, ErasureChunk, PoV, SignedDisputeStatement,
SignedFullStatement, ValidationResult,
};
use polkadot_primitives::v1::{
AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateDescriptor, CandidateEvent,
CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt,
CoreState, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId,
InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet, OccupiedCoreAssumption,
PersistedValidationData, PvfCheckStatement, SessionIndex, SessionInfo,
SignedAvailabilityBitfield, SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash,
ValidatorId, ValidatorIndex, ValidatorSignature,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateDescriptor, CandidateEvent,
CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt,
CoreState, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId,
InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet,
OccupiedCoreAssumption, PersistedValidationData, SessionIndex, SignedAvailabilityBitfield,
SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, ValidatorSignature,
},
v2::{PvfCheckStatement, SessionInfo},
};
use polkadot_statement_table::v1::Misbehavior;
use std::{
+8 -5
View File
@@ -49,11 +49,14 @@ use futures::{
use parity_scale_codec::Encode;
use pin_project::pin_project;
use polkadot_primitives::v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, EncodeAs,
GroupIndex, GroupRotationInfo, Hash, Id as ParaId, OccupiedCoreAssumption,
PersistedValidationData, SessionIndex, SessionInfo, Signed, SigningContext, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
use polkadot_primitives::{
v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, EncodeAs,
GroupIndex, GroupRotationInfo, Hash, Id as ParaId, OccupiedCoreAssumption,
PersistedValidationData, SessionIndex, Signed, SigningContext, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
},
v2::SessionInfo,
};
use sp_application_crypto::AppKey;
use sp_core::{traits::SpawnNamed, ByteArray};
@@ -20,7 +20,10 @@
//! care about the state of particular blocks.
pub use polkadot_node_primitives::{new_session_window_size, SessionWindowSize};
use polkadot_primitives::v1::{Hash, SessionIndex, SessionInfo};
use polkadot_primitives::{
v1::{Hash, SessionIndex},
v2::SessionInfo,
};
use futures::channel::oneshot;
use polkadot_node_subsystem::{
@@ -288,6 +291,7 @@ mod tests {
n_delay_tranches: index as _,
no_show_slots: index as _,
needed_approvals: index as _,
active_validator_indices: Vec::new(),
}
}
@@ -26,10 +26,13 @@ use sp_core::crypto::ByteArray;
use sp_keystore::{CryptoStore, SyncCryptoStorePtr};
use polkadot_node_subsystem::{SubsystemContext, SubsystemSender};
use polkadot_primitives::v1::{
CandidateEvent, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, OccupiedCore,
SessionIndex, SessionInfo, Signed, SigningContext, UncheckedSigned, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex,
use polkadot_primitives::{
v1::{
CandidateEvent, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, OccupiedCore,
SessionIndex, Signed, SigningContext, UncheckedSigned, ValidationCode, ValidationCodeHash,
ValidatorId, ValidatorIndex,
},
v2::SessionInfo,
};
use crate::{
+1
View File
@@ -21,3 +21,4 @@
pub mod v0;
pub mod v1;
pub mod v2;
+1 -106
View File
@@ -19,7 +19,7 @@
use bitvec::vec::BitVec;
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use sp_std::prelude::*;
use application_crypto::KeyTypeId;
use inherents::InherentIdentifier;
@@ -984,86 +984,6 @@ impl ApprovalVote {
}
}
sp_api::decl_runtime_apis! {
/// The API for querying the state of parachains on-chain.
#[api_version(2)]
pub trait ParachainHost<H: Encode + Decode = Hash, N: Encode + Decode = BlockNumber> {
/// Get the current validators.
fn validators() -> Vec<ValidatorId>;
/// Returns the validator groups and rotation info localized based on the hypothetical child
/// of a block whose state this is invoked on. Note that `now` in the `GroupRotationInfo`
/// should be the successor of the number of the block.
fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<N>);
/// Yields information on all availability cores as relevant to the child block.
/// Cores are either free or occupied. Free cores can have paras assigned to them.
fn availability_cores() -> Vec<CoreState<H, N>>;
/// Yields the persisted validation data for the given `ParaId` along with an assumption that
/// should be used if the para currently occupies a core.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
fn persisted_validation_data(para_id: Id, assumption: OccupiedCoreAssumption)
-> Option<PersistedValidationData<H, N>>;
/// Returns the persisted validation data for the given `ParaId` along with the corresponding
/// validation code hash. Instead of accepting assumption about the para, matches the validation
/// data hash against an expected one and yields `None` if they're not equal.
fn assumed_validation_data(
para_id: Id,
expected_persisted_validation_data_hash: Hash,
) -> Option<(PersistedValidationData<H, N>, ValidationCodeHash)>;
/// Checks if the given validation outputs pass the acceptance criteria.
fn check_validation_outputs(para_id: Id, outputs: CandidateCommitments) -> bool;
/// Returns the session index expected at a child of the block.
///
/// This can be used to instantiate a `SigningContext`.
fn session_index_for_child() -> SessionIndex;
/// Get the session info for the given session, if stored.
fn session_info(index: SessionIndex) -> Option<SessionInfo>;
/// Fetch the validation code used by a para, making the given `OccupiedCoreAssumption`.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
fn validation_code(para_id: Id, assumption: OccupiedCoreAssumption)
-> Option<ValidationCode>;
/// Get the receipt of a candidate pending availability. This returns `Some` for any paras
/// assigned to occupied cores in `availability_cores` and `None` otherwise.
fn candidate_pending_availability(para_id: Id) -> Option<CommittedCandidateReceipt<H>>;
/// Get a vector of events concerning candidates that occurred within a block.
fn candidate_events() -> Vec<CandidateEvent<H>>;
/// Get all the pending inbound messages in the downward message queue for a para.
fn dmq_contents(
recipient: Id,
) -> Vec<InboundDownwardMessage<N>>;
/// Get the contents of all channels addressed to the given recipient. Channels that have no
/// messages in them are also included.
fn inbound_hrmp_channels_contents(recipient: Id) -> BTreeMap<Id, Vec<InboundHrmpMessage<N>>>;
/// Get the validation code from its hash.
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode>;
/// Scrape dispute relevant from on-chain, backing votes and resolved disputes.
fn on_chain_votes() -> Option<ScrapedOnChainVotes<H>>;
/// Submits a PVF pre-checking statement into the transaction pool.
fn submit_pvf_check_statement(stmt: PvfCheckStatement, signature: ValidatorSignature);
/// Returns code hashes of PVFs that require pre-checking by validators in the active set.
fn pvfs_require_precheck() -> Vec<ValidationCodeHash>;
}
}
/// Custom validity errors used in Polkadot while validating transactions.
#[repr(u8)]
pub enum ValidityError {
@@ -1393,31 +1313,6 @@ pub struct InherentData<HDR: HeaderT = Header> {
pub parent_header: HDR,
}
/// A statement from the specified validator whether the given validation code passes PVF
/// pre-checking or not anchored to the given session index.
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
pub struct PvfCheckStatement {
/// `true` if the subject passed pre-checking and `false` otherwise.
pub accept: bool,
/// The validation code hash that was checked.
pub subject: ValidationCodeHash,
/// The index of a session during which this statement is considered valid.
pub session_index: SessionIndex,
/// The index of the validator from which this statement originates.
pub validator_index: ValidatorIndex,
}
impl PvfCheckStatement {
/// Produce the payload used for signing this type of statement.
///
/// It is expected that it will be signed by the validator at `validator_index` in the
/// `session_index`.
pub fn signing_payload(&self) -> Vec<u8> {
const MAGIC: [u8; 4] = *b"VCPC"; // for "validation code pre-checking"
(MAGIC, self.accept, self.subject, self.session_index, self.validator_index).encode()
}
}
/// The maximum number of validators `f` which may safely be faulty.
///
/// The total number of validators is `n = 3f + e` where `e in { 1, 2, 3 }`.
+220
View File
@@ -0,0 +1,220 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! `V2` Primitives.
use crate::v1;
use parity_scale_codec::{Decode, Encode};
use primitives::RuntimeDebug;
use scale_info::TypeInfo;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
#[cfg(feature = "std")]
use parity_util_mem::MallocSizeOf;
/// Information about validator sets of a session.
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))]
pub struct SessionInfo {
/****** New in v2 *******/
/// All the validators actively participating in parachain consensus.
/// Indices are into the broader validator set.
pub active_validator_indices: Vec<v1::ValidatorIndex>,
/****** Old fields ******/
/// Validators in canonical ordering.
///
/// NOTE: There might be more authorities in the current session, than `validators` participating
/// in parachain consensus. See
/// [`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<v1::ValidatorId>,
/// Validators' authority discovery keys for the session in canonical ordering.
///
/// NOTE: The first `validators.len()` entries will match the corresponding validators in
/// `validators`, afterwards any remaining authorities can be found. This is any authorities not
/// participating in parachain consensus - see
/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148)
#[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")]
pub discovery_keys: Vec<v1::AuthorityDiscoveryId>,
/// The assignment keys for validators.
///
/// NOTE: There might be more authorities in the current session, than validators participating
/// in parachain consensus. See
/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
///
/// Therefore:
/// ```ignore
/// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
/// ```
pub assignment_keys: Vec<v1::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<v1::ValidatorIndex>>,
/// The number of availability cores used by the protocol during this session.
pub n_cores: u32,
/// The zeroth delay tranche width.
pub zeroth_delay_tranche_width: u32,
/// The number of samples we do of `relay_vrf_modulo`.
pub relay_vrf_modulo_samples: u32,
/// The number of delay tranches in total.
pub n_delay_tranches: u32,
/// How many slots (BABE / SASSAFRAS) must pass before an assignment is considered a
/// no-show.
pub no_show_slots: u32,
/// The number of validators needed to approve a block.
pub needed_approvals: u32,
}
impl From<v1::SessionInfo> for SessionInfo {
fn from(old: v1::SessionInfo) -> SessionInfo {
SessionInfo {
// new fields
active_validator_indices: Vec::new(),
// old fields
validators: old.validators,
discovery_keys: old.discovery_keys,
assignment_keys: old.assignment_keys,
validator_groups: old.validator_groups,
n_cores: old.n_cores,
zeroth_delay_tranche_width: old.zeroth_delay_tranche_width,
relay_vrf_modulo_samples: old.relay_vrf_modulo_samples,
n_delay_tranches: old.n_delay_tranches,
no_show_slots: old.no_show_slots,
needed_approvals: old.needed_approvals,
}
}
}
/// A statement from the specified validator whether the given validation code passes PVF
/// pre-checking or not anchored to the given session index.
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
pub struct PvfCheckStatement {
/// `true` if the subject passed pre-checking and `false` otherwise.
pub accept: bool,
/// The validation code hash that was checked.
pub subject: v1::ValidationCodeHash,
/// The index of a session during which this statement is considered valid.
pub session_index: v1::SessionIndex,
/// The index of the validator from which this statement originates.
pub validator_index: v1::ValidatorIndex,
}
impl PvfCheckStatement {
/// Produce the payload used for signing this type of statement.
///
/// It is expected that it will be signed by the validator at `validator_index` in the
/// `session_index`.
pub fn signing_payload(&self) -> Vec<u8> {
const MAGIC: [u8; 4] = *b"VCPC"; // for "validation code pre-checking"
(MAGIC, self.accept, self.subject, self.session_index, self.validator_index).encode()
}
}
sp_api::decl_runtime_apis! {
/// The API for querying the state of parachains on-chain.
#[api_version(2)]
pub trait ParachainHost<H: Encode + Decode = v1::Hash, N: Encode + Decode = v1::BlockNumber> {
/// Get the current validators.
fn validators() -> Vec<v1::ValidatorId>;
/// Returns the validator groups and rotation info localized based on the hypothetical child
/// of a block whose state this is invoked on. Note that `now` in the `GroupRotationInfo`
/// should be the successor of the number of the block.
fn validator_groups() -> (Vec<Vec<v1::ValidatorIndex>>, v1::GroupRotationInfo<N>);
/// Yields information on all availability cores as relevant to the child block.
/// Cores are either free or occupied. Free cores can have paras assigned to them.
fn availability_cores() -> Vec<v1::CoreState<H, N>>;
/// Yields the persisted validation data for the given `ParaId` along with an assumption that
/// should be used if the para currently occupies a core.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
fn persisted_validation_data(para_id: v1::Id, assumption: v1::OccupiedCoreAssumption)
-> Option<v1::PersistedValidationData<H, N>>;
/// Returns the persisted validation data for the given `ParaId` along with the corresponding
/// validation code hash. Instead of accepting assumption about the para, matches the validation
/// data hash against an expected one and yields `None` if they're not equal.
fn assumed_validation_data(
para_id: v1::Id,
expected_persisted_validation_data_hash: v1::Hash,
) -> Option<(v1::PersistedValidationData<H, N>, v1::ValidationCodeHash)>;
/// Checks if the given validation outputs pass the acceptance criteria.
fn check_validation_outputs(para_id: v1::Id, outputs: v1::CandidateCommitments) -> bool;
/// Returns the session index expected at a child of the block.
///
/// This can be used to instantiate a `SigningContext`.
fn session_index_for_child() -> v1::SessionIndex;
/// Old method to fetch v1 session info.
#[changed_in(2)]
fn session_info(index: v1::SessionIndex) -> Option<v1::SessionInfo>;
/// Fetch the validation code used by a para, making the given `OccupiedCoreAssumption`.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
fn validation_code(para_id: v1::Id, assumption: v1::OccupiedCoreAssumption)
-> Option<v1::ValidationCode>;
/// Get the receipt of a candidate pending availability. This returns `Some` for any paras
/// assigned to occupied cores in `availability_cores` and `None` otherwise.
fn candidate_pending_availability(para_id: v1::Id) -> Option<v1::CommittedCandidateReceipt<H>>;
/// Get a vector of events concerning candidates that occurred within a block.
fn candidate_events() -> Vec<v1::CandidateEvent<H>>;
/// Get all the pending inbound messages in the downward message queue for a para.
fn dmq_contents(
recipient: v1::Id,
) -> Vec<v1::InboundDownwardMessage<N>>;
/// Get the contents of all channels addressed to the given recipient. Channels that have no
/// messages in them are also included.
fn inbound_hrmp_channels_contents(recipient: v1::Id) -> BTreeMap<v1::Id, Vec<v1::InboundHrmpMessage<N>>>;
/// Get the validation code from its hash.
fn validation_code_by_hash(hash: v1::ValidationCodeHash) -> Option<v1::ValidationCode>;
/// Scrape dispute relevant from on-chain, backing votes and resolved disputes.
fn on_chain_votes() -> Option<v1::ScrapedOnChainVotes<H>>;
/***** Added in v2 *****/
/// Get the session info for the given session, if stored.
///
/// NOTE: This function is only available since parachain host version 2.
fn session_info(index: v1::SessionIndex) -> Option<SessionInfo>;
/// Submits a PVF pre-checking statement into the transaction pool.
///
/// NOTE: This function is only available since parachain host version 2.
fn submit_pvf_check_statement(stmt: PvfCheckStatement, signature: v1::ValidatorSignature);
/// Returns code hashes of PVFs that require pre-checking by validators in the active set.
///
/// NOTE: This function is only available since parachain host version 2.
fn pvfs_require_precheck() -> Vec<v1::ValidationCodeHash>;
}
}
+11 -7
View File
@@ -22,11 +22,15 @@
use pallet_transaction_payment::CurrencyAdapter;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
use primitives::{
v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo,
};
use runtime_common::{
auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, slots, xcm_sender,
@@ -1735,7 +1739,7 @@ sp_api::impl_runtime_apis! {
}
}
impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
impl primitives::v2::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> {
parachains_runtime_api_impl::validators::<Runtime>()
}
@@ -1817,7 +1821,7 @@ sp_api::impl_runtime_apis! {
}
fn submit_pvf_check_statement(
stmt: primitives::v1::PvfCheckStatement,
stmt: primitives::v2::PvfCheckStatement,
signature: primitives::v1::ValidatorSignature,
) {
parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
+6 -3
View File
@@ -111,9 +111,12 @@ use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec};
use frame_support::{pallet_prelude::*, traits::EstimateNextSessionRotation};
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{
ConsensusLog, HeadData, Id as ParaId, PvfCheckStatement, SessionIndex, UpgradeGoAhead,
UpgradeRestriction, ValidationCode, ValidationCodeHash, ValidatorSignature,
use primitives::{
v1::{
ConsensusLog, HeadData, Id as ParaId, SessionIndex, UpgradeGoAhead, UpgradeRestriction,
ValidationCode, ValidationCodeHash, ValidatorSignature,
},
v2::PvfCheckStatement,
};
use scale_info::TypeInfo;
use sp_core::RuntimeDebug;
@@ -21,12 +21,15 @@ use crate::{
configuration, dmp, hrmp, inclusion, initializer, paras, paras_inherent, scheduler,
session_info, shared,
};
use primitives::v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied,
CoreState, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, PersistedValidationData,
PvfCheckStatement, ScheduledCore, ScrapedOnChainVotes, SessionIndex, SessionInfo,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
use primitives::{
v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied,
CoreState, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, PersistedValidationData,
ScheduledCore, ScrapedOnChainVotes, SessionIndex, ValidationCode, ValidationCodeHash,
ValidatorId, ValidatorIndex, ValidatorSignature,
},
v2::{PvfCheckStatement, SessionInfo},
};
use sp_runtime::traits::One;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
@@ -24,17 +24,24 @@ use crate::{
util::{take_active_subset, take_active_subset_and_inactive},
};
use frame_support::{pallet_prelude::*, traits::OneSessionHandler};
use primitives::v1::{AssignmentId, AuthorityDiscoveryId, SessionIndex, SessionInfo};
use primitives::{
v1::{AssignmentId, AuthorityDiscoveryId, SessionIndex},
v2::SessionInfo,
};
use sp_std::vec::Vec;
pub use pallet::*;
pub mod migration;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_system::pallet_prelude::BlockNumberFor;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(migration::STORAGE_VERSION)]
pub struct Pallet<T>(_);
#[pallet::config]
@@ -66,6 +73,13 @@ pub mod pallet {
#[pallet::storage]
#[pallet::getter(fn session_info)]
pub(crate) type Sessions<T: Config> = StorageMap<_, Identity, SessionIndex, SessionInfo>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
migration::migrate_to_latest::<T>()
}
}
}
/// An abstraction for the authority discovery pallet
@@ -132,6 +146,7 @@ impl<T: Config> Pallet<T> {
n_delay_tranches,
no_show_slots,
needed_approvals,
active_validator_indices: active_set,
};
Sessions::<T>::insert(&new_session_index, &new_session_info);
}
@@ -0,0 +1,44 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! A module that is responsible for migration of storage.
use crate::session_info::{Config, Pallet, Store};
use frame_support::{pallet_prelude::*, traits::StorageVersion, weights::Weight};
/// The current storage version.
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
/// Migrates the pallet storage to the most recent version, checking and setting the `StorageVersion`.
pub fn migrate_to_latest<T: Config>() -> Weight {
let mut weight = 0;
if StorageVersion::get::<Pallet<T>>() < 1 {
weight += migrate_to_v1::<T>();
StorageVersion::new(1).put::<Pallet<T>>();
}
weight
}
pub fn migrate_to_v1<T: Config>() -> Weight {
let mut vs = 0;
<Pallet<T> as Store>::Sessions::translate_values(|old: primitives::v1::SessionInfo| {
vs += 1;
Some(primitives::v2::SessionInfo::from(old))
});
T::DbWeight::get().reads_writes(vs, vs)
}
+11 -7
View File
@@ -54,11 +54,15 @@ use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
use primitives::{
v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo,
};
use sp_core::{
u32_trait::{_1, _2, _3, _4, _5},
@@ -1702,7 +1706,7 @@ sp_api::impl_runtime_apis! {
}
}
impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
impl primitives::v2::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> {
parachains_runtime_api_impl::validators::<Runtime>()
}
@@ -1784,7 +1788,7 @@ sp_api::impl_runtime_apis! {
}
fn submit_pvf_check_statement(
stmt: primitives::v1::PvfCheckStatement,
stmt: primitives::v2::PvfCheckStatement,
signature: primitives::v1::ValidatorSignature,
) {
parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
+9 -7
View File
@@ -35,12 +35,14 @@ use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment,
Nonce, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes,
SessionInfo as SessionInfoData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, ValidatorSignature,
use primitives::{
v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment,
Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, Signature,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
},
v2::{PvfCheckStatement, SessionInfo as SessionInfoData},
};
use runtime_common::{
assigned_slots, auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper,
@@ -1293,7 +1295,7 @@ sp_api::impl_runtime_apis! {
}
}
impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
impl primitives::v2::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> {
runtime_api_impl::validators::<Runtime>()
}
+11 -8
View File
@@ -44,12 +44,15 @@ use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use polkadot_runtime_parachains::reward_points::RewardValidatorsWithEraPoints;
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
ScrapedOnChainVotes, SessionInfo as SessionInfoData, Signature, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex,
use primitives::{
v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo as SessionInfoData,
};
use runtime_common::{
claims, paras_sudo_wrapper, BlockHashCount, BlockLength, BlockWeights, SlowAdjustingFeeUpdate,
@@ -796,7 +799,7 @@ sp_api::impl_runtime_apis! {
}
}
impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
impl primitives::v2::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> {
runtime_impl::validators::<Runtime>()
}
@@ -876,7 +879,7 @@ sp_api::impl_runtime_apis! {
}
fn submit_pvf_check_statement(
stmt: primitives::v1::PvfCheckStatement,
stmt: primitives::v2::PvfCheckStatement,
signature: primitives::v1::ValidatorSignature,
) {
runtime_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
+11 -7
View File
@@ -22,11 +22,15 @@
use pallet_transaction_payment::CurrencyAdapter;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
use primitives::{
v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
},
v2::SessionInfo,
};
use runtime_common::{
assigned_slots, auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper,
@@ -1306,7 +1310,7 @@ sp_api::impl_runtime_apis! {
}
}
impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
impl primitives::v2::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> {
parachains_runtime_api_impl::validators::<Runtime>()
}
@@ -1388,7 +1392,7 @@ sp_api::impl_runtime_apis! {
}
fn submit_pvf_check_statement(
stmt: primitives::v1::PvfCheckStatement,
stmt: primitives::v2::PvfCheckStatement,
signature: primitives::v1::ValidatorSignature,
) {
parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)