Migrate polkadot-primitives to v6 (#1543)

- Async-backing related primitives are stable `primitives::v6`
- Async-backing API is now part of `api_version(7)`
- It's enabled on Rococo and Westend runtimes

---------

Signed-off-by: Andrei Sandu <andrei-mihail@parity.io>
Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>
This commit is contained in:
Chris Sosnin
2023-09-27 13:32:02 +03:00
committed by GitHub
parent 5a2833cceb
commit 7cbe0c76ef
107 changed files with 2410 additions and 2792 deletions
+3 -27
View File
@@ -110,7 +110,7 @@ zombienet-polkadot-smoke-0001-parachains-smoke-test:
- .zombienet-polkadot-common - .zombienet-polkadot-common
before_script: before_script:
- export ZOMBIENET_INTEGRATION_TEST_IMAGE="${POLKADOT_IMAGE}":${PIPELINE_IMAGE_TAG} - export ZOMBIENET_INTEGRATION_TEST_IMAGE="${POLKADOT_IMAGE}":${PIPELINE_IMAGE_TAG}
- export COL_IMAGE="docker.io/paritypr/colander:4519" # The collator image is fixed - export COL_IMAGE="${COLANDER_IMAGE}":${PIPELINE_IMAGE_TAG}
- echo "Zombienet Tests Config" - echo "Zombienet Tests Config"
- echo "gh-dir ${GH_DIR}" - echo "gh-dir ${GH_DIR}"
- echo "local-dir ${LOCAL_DIR}" - echo "local-dir ${LOCAL_DIR}"
@@ -127,12 +127,12 @@ zombienet-polkadot-smoke-0002-parachains-parachains-upgrade-smoke:
- .zombienet-polkadot-common - .zombienet-polkadot-common
before_script: before_script:
- export ZOMBIENET_INTEGRATION_TEST_IMAGE="${POLKADOT_IMAGE}":${PIPELINE_IMAGE_TAG} - export ZOMBIENET_INTEGRATION_TEST_IMAGE="${POLKADOT_IMAGE}":${PIPELINE_IMAGE_TAG}
- export COL_IMAGE="docker.io/parity/polkadot-collator:latest" # Use cumulus lastest image - export CUMULUS_IMAGE="docker.io/paritypr/polkadot-parachain-debug:${DOCKER_IMAGES_VERSION}"
- echo "Zombienet Tests Config" - echo "Zombienet Tests Config"
- echo "gh-dir ${GH_DIR}" - echo "gh-dir ${GH_DIR}"
- echo "local-dir ${LOCAL_DIR}" - echo "local-dir ${LOCAL_DIR}"
- echo "polkadot image ${ZOMBIENET_INTEGRATION_TEST_IMAGE}" - echo "polkadot image ${ZOMBIENET_INTEGRATION_TEST_IMAGE}"
- echo "colander image ${COL_IMAGE}" - echo "polkadot-parachain image ${CUMULUS_IMAGE}"
- echo "malus image ${MALUS_IMAGE}" - echo "malus image ${MALUS_IMAGE}"
script: script:
- /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh
@@ -193,27 +193,3 @@ zombienet-polkadot-malus-0001-dispute-valid:
- /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh
--local-dir="${LOCAL_DIR}/integrationtests" --local-dir="${LOCAL_DIR}/integrationtests"
--test="0001-dispute-valid-block.zndsl" --test="0001-dispute-valid-block.zndsl"
zombienet-polkadot-async-backing-compatibility:
extends:
- .zombienet-polkadot-common
script:
- /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh
--local-dir="${LOCAL_DIR}/async_backing"
--test="001-async-backing-compatibility.zndsl"
zombienet-polkadot-async-backing-runtime-upgrade:
extends:
- .zombienet-polkadot-common
script:
- /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh
--local-dir="${LOCAL_DIR}/async_backing"
--test="002-async-backing-runtime-upgrade.zndsl"
zombienet-polkadot-async-backing-collator-mix:
extends:
- .zombienet-polkadot-common
script:
- /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh
--local-dir="${LOCAL_DIR}/async_backing"
--test="003-async-backing-collator-mix.zndsl"
@@ -52,7 +52,7 @@ pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// This is a copy-paste from the cumulus repo's `parachains-common` crate. /// This is a copy-paste from the cumulus repo's `parachains-common` crate.
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_SECOND, 0) const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_SECOND, 0)
.saturating_div(2) .saturating_div(2)
.set_proof_size(polkadot_primitives::v5::MAX_POV_SIZE as u64); .set_proof_size(polkadot_primitives::MAX_POV_SIZE as u64);
/// All cumulus bridge hubs assume that about 5 percent of the block weight is consumed by /// All cumulus bridge hubs assume that about 5 percent of the block weight is consumed by
/// `on_initialize` handlers. This is used to limit the maximal weight of a single extrinsic. /// `on_initialize` handlers. This is used to limit the maximal weight of a single extrinsic.
@@ -41,6 +41,3 @@ metered = { package = "prioritized-metered-channel", version = "0.5.1", default-
# Cumulus # Cumulus
cumulus-test-service = { path = "../../test/service" } cumulus-test-service = { path = "../../test/service" }
[features]
network-protocol-staging = [ "polkadot-service/network-protocol-staging" ]
@@ -41,7 +41,3 @@ tracing = "0.1.37"
async-trait = "0.1.73" async-trait = "0.1.73"
futures = "0.3.28" futures = "0.3.28"
[features]
network-protocol-staging = [
"polkadot-node-network-protocol/network-protocol-staging",
]
@@ -22,8 +22,8 @@ use futures::{Stream, StreamExt};
use polkadot_core_primitives::{Block, BlockNumber, Hash, Header}; use polkadot_core_primitives::{Block, BlockNumber, Hash, Header};
use polkadot_overseer::RuntimeApiSubsystemClient; use polkadot_overseer::RuntimeApiSubsystemClient;
use polkadot_primitives::{ use polkadot_primitives::{
async_backing::{AsyncBackingParams, BackingState},
slashing, slashing,
vstaging::{AsyncBackingParams, BackingState},
}; };
use sc_authority_discovery::{AuthorityDiscovery, Error as AuthorityDiscoveryError}; use sc_authority_discovery::{AuthorityDiscovery, Error as AuthorityDiscoveryError};
use sp_api::{ApiError, RuntimeApiInfo}; use sp_api::{ApiError, RuntimeApiInfo};
@@ -346,16 +346,16 @@ impl RuntimeApiSubsystemClient for BlockChainRpcClient {
Ok(self.rpc_client.parachain_host_minimum_backing_votes(at, session_index).await?) Ok(self.rpc_client.parachain_host_minimum_backing_votes(at, session_index).await?)
} }
async fn staging_async_backing_params(&self, at: Hash) -> Result<AsyncBackingParams, ApiError> { async fn async_backing_params(&self, at: Hash) -> Result<AsyncBackingParams, ApiError> {
Ok(self.rpc_client.parachain_host_staging_async_backing_params(at).await?) Ok(self.rpc_client.parachain_host_async_backing_params(at).await?)
} }
async fn staging_para_backing_state( async fn para_backing_state(
&self, &self,
at: Hash, at: Hash,
para_id: cumulus_primitives_core::ParaId, para_id: cumulus_primitives_core::ParaId,
) -> Result<Option<BackingState>, ApiError> { ) -> Result<Option<BackingState>, ApiError> {
Ok(self.rpc_client.parachain_host_staging_para_backing_state(at, para_id).await?) Ok(self.rpc_client.parachain_host_para_backing_state(at, para_id).await?)
} }
} }
@@ -30,7 +30,7 @@ use polkadot_node_network_protocol::{
peer_set::PeerSetProtocolNames, peer_set::PeerSetProtocolNames,
request_response::{ request_response::{
v1::{self, AvailableDataFetchingRequest}, v1::{self, AvailableDataFetchingRequest},
vstaging, IncomingRequestReceiver, ReqProtocolNames, v2, IncomingRequestReceiver, ReqProtocolNames,
}, },
}; };
use polkadot_node_subsystem_util::metrics::{prometheus::Registry, Metrics}; use polkadot_node_subsystem_util::metrics::{prometheus::Registry, Metrics};
@@ -63,9 +63,8 @@ pub(crate) struct CollatorOverseerGenArgs<'a> {
pub authority_discovery_service: AuthorityDiscoveryService, pub authority_discovery_service: AuthorityDiscoveryService,
/// Receiver for collation request protocol v1. /// Receiver for collation request protocol v1.
pub collation_req_receiver_v1: IncomingRequestReceiver<v1::CollationFetchingRequest>, pub collation_req_receiver_v1: IncomingRequestReceiver<v1::CollationFetchingRequest>,
/// Receiver for collation request protocol vstaging. /// Receiver for collation request protocol v2.
pub collation_req_receiver_vstaging: pub collation_req_receiver_v2: IncomingRequestReceiver<v2::CollationFetchingRequest>,
IncomingRequestReceiver<vstaging::CollationFetchingRequest>,
/// Receiver for availability request protocol /// Receiver for availability request protocol
pub available_data_req_receiver: IncomingRequestReceiver<AvailableDataFetchingRequest>, pub available_data_req_receiver: IncomingRequestReceiver<AvailableDataFetchingRequest>,
/// Prometheus registry, commonly used for production systems, less so for test. /// Prometheus registry, commonly used for production systems, less so for test.
@@ -88,7 +87,7 @@ fn build_overseer(
sync_oracle, sync_oracle,
authority_discovery_service, authority_discovery_service,
collation_req_receiver_v1, collation_req_receiver_v1,
collation_req_receiver_vstaging, collation_req_receiver_v2,
available_data_req_receiver, available_data_req_receiver,
registry, registry,
spawner, spawner,
@@ -121,7 +120,7 @@ fn build_overseer(
peer_id: network_service.local_peer_id(), peer_id: network_service.local_peer_id(),
collator_pair, collator_pair,
request_receiver_v1: collation_req_receiver_v1, request_receiver_v1: collation_req_receiver_v1,
request_receiver_vstaging: collation_req_receiver_vstaging, request_receiver_v2: collation_req_receiver_v2,
metrics: Metrics::register(registry)?, metrics: Metrics::register(registry)?,
}; };
CollatorProtocolSubsystem::new(side) CollatorProtocolSubsystem::new(side)
@@ -23,7 +23,7 @@ use polkadot_network_bridge::{peer_sets_info, IsAuthority};
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
peer_set::PeerSetProtocolNames, peer_set::PeerSetProtocolNames,
request_response::{ request_response::{
v1, vstaging, IncomingRequest, IncomingRequestReceiver, Protocol, ReqProtocolNames, v1, v2, IncomingRequest, IncomingRequestReceiver, Protocol, ReqProtocolNames,
}, },
}; };
@@ -182,7 +182,7 @@ async fn new_minimal_relay_chain(
} }
let request_protocol_names = ReqProtocolNames::new(genesis_hash, config.chain_spec.fork_id()); let request_protocol_names = ReqProtocolNames::new(genesis_hash, config.chain_spec.fork_id());
let (collation_req_receiver_v1, collation_req_receiver_vstaging, available_data_req_receiver) = let (collation_req_receiver_v1, collation_req_receiver_v2, available_data_req_receiver) =
build_request_response_protocol_receivers(&request_protocol_names, &mut net_config); build_request_response_protocol_receivers(&request_protocol_names, &mut net_config);
let best_header = relay_chain_rpc_client let best_header = relay_chain_rpc_client
@@ -212,7 +212,7 @@ async fn new_minimal_relay_chain(
sync_oracle, sync_oracle,
authority_discovery_service, authority_discovery_service,
collation_req_receiver_v1, collation_req_receiver_v1,
collation_req_receiver_vstaging, collation_req_receiver_v2,
available_data_req_receiver, available_data_req_receiver,
registry: prometheus_registry.as_ref(), registry: prometheus_registry.as_ref(),
spawner: task_manager.spawn_handle(), spawner: task_manager.spawn_handle(),
@@ -234,13 +234,13 @@ fn build_request_response_protocol_receivers(
config: &mut FullNetworkConfiguration, config: &mut FullNetworkConfiguration,
) -> ( ) -> (
IncomingRequestReceiver<v1::CollationFetchingRequest>, IncomingRequestReceiver<v1::CollationFetchingRequest>,
IncomingRequestReceiver<vstaging::CollationFetchingRequest>, IncomingRequestReceiver<v2::CollationFetchingRequest>,
IncomingRequestReceiver<v1::AvailableDataFetchingRequest>, IncomingRequestReceiver<v1::AvailableDataFetchingRequest>,
) { ) {
let (collation_req_receiver_v1, cfg) = let (collation_req_receiver_v1, cfg) =
IncomingRequest::get_config_receiver(request_protocol_names); IncomingRequest::get_config_receiver(request_protocol_names);
config.add_request_response_protocol(cfg); config.add_request_response_protocol(cfg);
let (collation_req_receiver_vstaging, cfg) = let (collation_req_receiver_v2, cfg) =
IncomingRequest::get_config_receiver(request_protocol_names); IncomingRequest::get_config_receiver(request_protocol_names);
config.add_request_response_protocol(cfg); config.add_request_response_protocol(cfg);
let (available_data_req_receiver, cfg) = let (available_data_req_receiver, cfg) =
@@ -248,5 +248,5 @@ fn build_request_response_protocol_receivers(
config.add_request_response_protocol(cfg); config.add_request_response_protocol(cfg);
let cfg = Protocol::ChunkFetchingV1.get_outbound_only_config(request_protocol_names); let cfg = Protocol::ChunkFetchingV1.get_outbound_only_config(request_protocol_names);
config.add_request_response_protocol(cfg); config.add_request_response_protocol(cfg);
(collation_req_receiver_v1, collation_req_receiver_vstaging, available_data_req_receiver) (collation_req_receiver_v1, collation_req_receiver_v2, available_data_req_receiver)
} }
@@ -30,9 +30,8 @@ use parity_scale_codec::{Decode, Encode};
use cumulus_primitives_core::{ use cumulus_primitives_core::{
relay_chain::{ relay_chain::{
slashing, async_backing::{AsyncBackingParams, BackingState},
vstaging::{AsyncBackingParams, BackingState}, slashing, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash,
BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash,
CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo,
Hash as RelayHash, Header as RelayHeader, InboundHrmpMessage, OccupiedCoreAssumption, Hash as RelayHash, Header as RelayHeader, InboundHrmpMessage, OccupiedCoreAssumption,
PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode,
@@ -599,30 +598,22 @@ impl RelayChainRpcClient {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub async fn parachain_host_staging_async_backing_params( pub async fn parachain_host_async_backing_params(
&self, &self,
at: RelayHash, at: RelayHash,
) -> Result<AsyncBackingParams, RelayChainError> { ) -> Result<AsyncBackingParams, RelayChainError> {
self.call_remote_runtime_function( self.call_remote_runtime_function("ParachainHost_async_backing_params", at, None::<()>)
"ParachainHost_staging_async_backing_params", .await
at,
None::<()>,
)
.await
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub async fn parachain_host_staging_para_backing_state( pub async fn parachain_host_para_backing_state(
&self, &self,
at: RelayHash, at: RelayHash,
para_id: ParaId, para_id: ParaId,
) -> Result<Option<BackingState>, RelayChainError> { ) -> Result<Option<BackingState>, RelayChainError> {
self.call_remote_runtime_function( self.call_remote_runtime_function("ParachainHost_para_backing_state", at, Some(para_id))
"ParachainHost_staging_para_backing_state", .await
at,
Some(para_id),
)
.await
} }
fn send_register_message_to_worker( fn send_register_message_to_worker(
-5
View File
@@ -40,8 +40,3 @@ cumulus-relay-chain-interface = { path = "../relay-chain-interface" }
cumulus-relay-chain-inprocess-interface = { path = "../relay-chain-inprocess-interface" } cumulus-relay-chain-inprocess-interface = { path = "../relay-chain-inprocess-interface" }
cumulus-relay-chain-minimal-node = { path = "../relay-chain-minimal-node" } cumulus-relay-chain-minimal-node = { path = "../relay-chain-minimal-node" }
[features]
network-protocol-staging = [
"cumulus-relay-chain-inprocess-interface/network-protocol-staging",
"cumulus-relay-chain-minimal-node/network-protocol-staging",
]
+1 -1
View File
@@ -1447,7 +1447,7 @@ impl<T: Config> Pallet<T> {
hrmp_max_message_num_per_candidate: 2, hrmp_max_message_num_per_candidate: 2,
validation_upgrade_cooldown: 2, validation_upgrade_cooldown: 2,
validation_upgrade_delay: 2, validation_upgrade_delay: 2,
async_backing_params: relay_chain::vstaging::AsyncBackingParams { async_backing_params: relay_chain::AsyncBackingParams {
allowed_ancestry_len: 0, allowed_ancestry_len: 0,
max_candidate_depth: 0, max_candidate_depth: 0,
}, },
+1 -4
View File
@@ -89,7 +89,4 @@ try-runtime = [
"polkadot-cli/try-runtime", "polkadot-cli/try-runtime",
"sp-runtime/try-runtime", "sp-runtime/try-runtime",
] ]
network-protocol-staging = [
"cumulus-client-service/network-protocol-staging",
"polkadot-cli/network-protocol-staging",
]
@@ -64,7 +64,7 @@ decl_test_relay_chains! {
Hrmp: kusama_runtime::Hrmp, Hrmp: kusama_runtime::Hrmp,
} }
}, },
#[api_version(6)] #[api_version(7)]
pub struct Westend { pub struct Westend {
genesis = westend::genesis(), genesis = westend::genesis(),
on_init = (), on_init = (),
@@ -79,7 +79,7 @@ decl_test_relay_chains! {
Balances: westend_runtime::Balances, Balances: westend_runtime::Balances,
} }
}, },
#[api_version(5)] #[api_version(7)]
pub struct Rococo { pub struct Rococo {
genesis = rococo::genesis(), genesis = rococo::genesis(),
on_init = (), on_init = (),
@@ -94,7 +94,7 @@ decl_test_relay_chains! {
Balances: rococo_runtime::Balances, Balances: rococo_runtime::Balances,
} }
}, },
#[api_version(5)] #[api_version(7)]
pub struct Wococo { pub struct Wococo {
genesis = rococo::genesis(), genesis = rococo::genesis(),
on_init = (), on_init = (),
+1 -1
View File
@@ -63,7 +63,7 @@ impl Default for RelayStateSproofBuilder {
hrmp_max_message_num_per_candidate: 5, hrmp_max_message_num_per_candidate: 5,
validation_upgrade_cooldown: 6, validation_upgrade_cooldown: 6,
validation_upgrade_delay: 6, validation_upgrade_delay: 6,
async_backing_params: relay_chain::vstaging::AsyncBackingParams { async_backing_params: relay_chain::AsyncBackingParams {
allowed_ancestry_len: 0, allowed_ancestry_len: 0,
max_candidate_depth: 0, max_candidate_depth: 0,
}, },
-1
View File
@@ -68,7 +68,6 @@ jemalloc-allocator = [
# Enables timeout-based tests supposed to be run only in CI environment as they may be flaky # Enables timeout-based tests supposed to be run only in CI environment as they may be flaky
# when run locally depending on system load # when run locally depending on system load
ci-only-tests = [ "polkadot-node-core-pvf/ci-only-tests" ] ci-only-tests = [ "polkadot-node-core-pvf/ci-only-tests" ]
network-protocol-staging = [ "polkadot-cli/network-protocol-staging" ]
# Configuration for building a .deb package - for use with `cargo-deb` # Configuration for building a .deb package - for use with `cargo-deb`
[package.metadata.deb] [package.metadata.deb]
-1
View File
@@ -76,4 +76,3 @@ runtime-metrics = [
"polkadot-node-metrics/runtime-metrics", "polkadot-node-metrics/runtime-metrics",
"service/runtime-metrics", "service/runtime-metrics",
] ]
network-protocol-staging = [ "service/network-protocol-staging" ]
@@ -43,9 +43,8 @@ use polkadot_node_subsystem::{
SubsystemContext, SubsystemError, SubsystemResult, SubsystemContext, SubsystemError, SubsystemResult,
}; };
use polkadot_node_subsystem_util::{ use polkadot_node_subsystem_util::{
request_availability_cores, request_persisted_validation_data, request_async_backing_params, request_availability_cores, request_persisted_validation_data,
request_staging_async_backing_params, request_validation_code, request_validation_code_hash, request_validation_code, request_validation_code_hash, request_validators,
request_validators,
}; };
use polkadot_primitives::{ use polkadot_primitives::{
collator_signature_payload, CandidateCommitments, CandidateDescriptor, CandidateReceipt, collator_signature_payload, CandidateCommitments, CandidateDescriptor, CandidateReceipt,
@@ -208,7 +207,7 @@ async fn handle_new_activations<Context>(
let (availability_cores, validators, async_backing_params) = join!( let (availability_cores, validators, async_backing_params) = join!(
request_availability_cores(relay_parent, ctx.sender()).await, request_availability_cores(relay_parent, ctx.sender()).await,
request_validators(relay_parent, ctx.sender()).await, request_validators(relay_parent, ctx.sender()).await,
request_staging_async_backing_params(relay_parent, ctx.sender()).await, request_async_backing_params(relay_parent, ctx.sender()).await,
); );
let availability_cores = availability_cores??; let availability_cores = availability_cores??;
@@ -153,7 +153,7 @@ fn requests_availability_per_relay_parent() {
} }
Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(
_hash, _hash,
RuntimeApiRequest::StagingAsyncBackingParams( RuntimeApiRequest::AsyncBackingParams(
tx, tx,
), ),
))) => { ))) => {
@@ -235,7 +235,7 @@ fn requests_validation_data_for_scheduled_matches() {
}, },
Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(
_hash, _hash,
RuntimeApiRequest::StagingAsyncBackingParams(tx), RuntimeApiRequest::AsyncBackingParams(tx),
))) => { ))) => {
tx.send(Err(RuntimeApiError::NotSupported { tx.send(Err(RuntimeApiError::NotSupported {
runtime_api_name: "doesnt_matter", runtime_api_name: "doesnt_matter",
@@ -332,7 +332,7 @@ fn sends_distribute_collation_message() {
}, },
Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(
_hash, _hash,
RuntimeApiRequest::StagingAsyncBackingParams(tx), RuntimeApiRequest::AsyncBackingParams(tx),
))) => { ))) => {
tx.send(Err(RuntimeApiError::NotSupported { tx.send(Err(RuntimeApiError::NotSupported {
runtime_api_name: "doesnt_matter", runtime_api_name: "doesnt_matter",
@@ -494,7 +494,7 @@ fn fallback_when_no_validation_code_hash_api() {
}, },
Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(
_hash, _hash,
RuntimeApiRequest::StagingAsyncBackingParams(tx), RuntimeApiRequest::AsyncBackingParams(tx),
))) => { ))) => {
tx.send(Err(RuntimeApiError::NotSupported { tx.send(Err(RuntimeApiError::NotSupported {
runtime_api_name: "doesnt_matter", runtime_api_name: "doesnt_matter",
+1 -1
View File
@@ -237,7 +237,7 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == test_state.relay_parent => { ) if parent == test_state.relay_parent => {
tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap();
} }
@@ -20,12 +20,12 @@ use polkadot_node_subsystem::{
messages::{ChainApiMessage, FragmentTreeMembership}, messages::{ChainApiMessage, FragmentTreeMembership},
ActivatedLeaf, TimeoutExt, ActivatedLeaf, TimeoutExt,
}; };
use polkadot_primitives::{vstaging as vstaging_primitives, BlockNumber, Header, OccupiedCore}; use polkadot_primitives::{AsyncBackingParams, BlockNumber, Header, OccupiedCore};
use super::*; use super::*;
const ASYNC_BACKING_PARAMETERS: vstaging_primitives::AsyncBackingParams = const ASYNC_BACKING_PARAMETERS: AsyncBackingParams =
vstaging_primitives::AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 }; AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 };
struct TestLeaf { struct TestLeaf {
activated: ActivatedLeaf, activated: ActivatedLeaf,
@@ -56,7 +56,7 @@ async fn activate_leaf(
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == leaf_hash => { ) if parent == leaf_hash => {
tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap(); tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap();
} }
@@ -43,7 +43,7 @@ use polkadot_node_subsystem_util::runtime::{
self, key_ownership_proof, submit_report_dispute_lost, RuntimeInfo, self, key_ownership_proof, submit_report_dispute_lost, RuntimeInfo,
}; };
use polkadot_primitives::{ use polkadot_primitives::{
vstaging, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement, DisputeStatement, slashing, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement, DisputeStatement,
DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex, ValidDisputeStatementKind, DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex, ValidDisputeStatementKind,
ValidatorId, ValidatorIndex, ValidatorId, ValidatorIndex,
}; };
@@ -385,7 +385,7 @@ impl Initialized {
&mut self, &mut self,
ctx: &mut Context, ctx: &mut Context,
relay_parent: Hash, relay_parent: Hash,
unapplied_slashes: Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>, unapplied_slashes: Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>,
) { ) {
for (session_index, candidate_hash, pending) in unapplied_slashes { for (session_index, candidate_hash, pending) in unapplied_slashes {
gum::info!( gum::info!(
@@ -422,11 +422,9 @@ impl Initialized {
match res { match res {
Ok(Some(key_ownership_proof)) => { Ok(Some(key_ownership_proof)) => {
key_ownership_proofs.push(key_ownership_proof); key_ownership_proofs.push(key_ownership_proof);
let time_slot = vstaging::slashing::DisputesTimeSlot::new( let time_slot =
session_index, slashing::DisputesTimeSlot::new(session_index, candidate_hash);
candidate_hash, let dispute_proof = slashing::DisputeProof {
);
let dispute_proof = vstaging::slashing::DisputeProof {
time_slot, time_slot,
kind: pending.kind, kind: pending.kind,
validator_index: *validator_index, validator_index: *validator_index,
@@ -96,10 +96,10 @@ use std::{
use super::LOG_TARGET; use super::LOG_TARGET;
use bitvec::prelude::*; use bitvec::prelude::*;
use polkadot_node_subsystem_util::inclusion_emulator::staging::{ use polkadot_node_subsystem_util::inclusion_emulator::{
ConstraintModifications, Constraints, Fragment, ProspectiveCandidate, RelayChainBlockInfo, ConstraintModifications, Constraints, Fragment, ProspectiveCandidate, RelayChainBlockInfo,
}; };
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
BlockNumber, CandidateHash, CommittedCandidateReceipt, Hash, HeadData, Id as ParaId, BlockNumber, CandidateHash, CommittedCandidateReceipt, Hash, HeadData, Id as ParaId,
PersistedValidationData, PersistedValidationData,
}; };
@@ -981,10 +981,8 @@ impl FragmentNode {
mod tests { mod tests {
use super::*; use super::*;
use assert_matches::assert_matches; use assert_matches::assert_matches;
use polkadot_node_subsystem_util::inclusion_emulator::staging::InboundHrmpLimitations; use polkadot_node_subsystem_util::inclusion_emulator::InboundHrmpLimitations;
use polkadot_primitives::vstaging::{ use polkadot_primitives::{BlockNumber, CandidateCommitments, CandidateDescriptor, HeadData};
BlockNumber, CandidateCommitments, CandidateDescriptor, HeadData,
};
use polkadot_primitives_test_helpers as test_helpers; use polkadot_primitives_test_helpers as test_helpers;
fn make_constraints( fn make_constraints(
@@ -22,7 +22,7 @@
//! backing phases of parachain consensus. //! backing phases of parachain consensus.
//! //!
//! This is primarily an implementation of "Fragment Trees", as described in //! This is primarily an implementation of "Fragment Trees", as described in
//! [`polkadot_node_subsystem_util::inclusion_emulator::staging`]. //! [`polkadot_node_subsystem_util::inclusion_emulator`].
//! //!
//! This subsystem also handles concerns such as the relay-chain being forkful and session changes. //! This subsystem also handles concerns such as the relay-chain being forkful and session changes.
@@ -42,13 +42,14 @@ use polkadot_node_subsystem::{
overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError, overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError,
}; };
use polkadot_node_subsystem_util::{ use polkadot_node_subsystem_util::{
inclusion_emulator::staging::{Constraints, RelayChainBlockInfo}, inclusion_emulator::{Constraints, RelayChainBlockInfo},
request_session_index_for_child, request_session_index_for_child,
runtime::{prospective_parachains_mode, ProspectiveParachainsMode}, runtime::{prospective_parachains_mode, ProspectiveParachainsMode},
}; };
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
BlockNumber, CandidateHash, CandidatePendingAvailability, CommittedCandidateReceipt, CoreState, async_backing::CandidatePendingAvailability, BlockNumber, CandidateHash,
Hash, HeadData, Header, Id as ParaId, PersistedValidationData, CommittedCandidateReceipt, CoreState, Hash, HeadData, Header, Id as ParaId,
PersistedValidationData,
}; };
use crate::{ use crate::{
@@ -792,7 +793,7 @@ async fn fetch_backing_state<Context>(
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
ctx.send_message(RuntimeApiMessage::Request( ctx.send_message(RuntimeApiMessage::Request(
relay_parent, relay_parent,
RuntimeApiRequest::StagingParaBackingState(para_id, tx), RuntimeApiRequest::ParaBackingState(para_id, tx),
)) ))
.await; .await;
@@ -25,7 +25,7 @@ use polkadot_node_subsystem::{
}; };
use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_test_helpers as test_helpers;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging::{AsyncBackingParams, BackingState, Constraints, InboundHrmpLimitations}, async_backing::{AsyncBackingParams, BackingState, Constraints, InboundHrmpLimitations},
CommittedCandidateReceipt, HeadData, Header, PersistedValidationData, ScheduledCore, CommittedCandidateReceipt, HeadData, Header, PersistedValidationData, ScheduledCore,
ValidationCodeHash, ValidationCodeHash,
}; };
@@ -219,7 +219,7 @@ async fn handle_leaf_activation(
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == *hash => { ) if parent == *hash => {
tx.send(Ok(async_backing_params)).unwrap(); tx.send(Ok(async_backing_params)).unwrap();
} }
@@ -284,7 +284,7 @@ async fn handle_leaf_activation(
let para_id = match message { let para_id = match message {
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
_, _,
RuntimeApiRequest::StagingParaBackingState(p_id, _), RuntimeApiRequest::ParaBackingState(p_id, _),
)) => p_id, )) => p_id,
_ => panic!("received unexpected message {:?}", message), _ => panic!("received unexpected message {:?}", message),
}; };
@@ -303,7 +303,7 @@ async fn handle_leaf_activation(
assert_matches!( assert_matches!(
message, message,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingParaBackingState(p_id, tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::ParaBackingState(p_id, tx))
) if parent == *hash && p_id == para_id => { ) if parent == *hash && p_id == para_id => {
tx.send(Ok(Some(backing_state))).unwrap(); tx.send(Ok(Some(backing_state))).unwrap();
} }
@@ -499,7 +499,7 @@ fn should_do_no_work_if_async_backing_disabled_for_leaf() {
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == hash => { ) if parent == hash => {
tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap();
} }
@@ -1569,7 +1569,7 @@ fn uses_ancestry_only_within_session() {
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == hash => { ) if parent == hash => {
tx.send(Ok(AsyncBackingParams { max_candidate_depth: 0, allowed_ancestry_len: ancestry_len })).unwrap(); tx.send(Ok(AsyncBackingParams { max_candidate_depth: 0, allowed_ancestry_len: ancestry_len })).unwrap();
} }
+35 -39
View File
@@ -20,12 +20,12 @@ use schnellru::{ByLength, LruMap};
use sp_consensus_babe::Epoch; use sp_consensus_babe::Epoch;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging, AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, async_backing, slashing, AuthorityDiscoveryId, BlockNumber, CandidateCommitments,
CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState,
GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, ExecutorParams, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement,
SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash,
ValidatorSignature, ValidatorId, ValidatorIndex, ValidatorSignature,
}; };
/// For consistency we have the same capacity for all caches. We use 128 as we'll only need that /// For consistency we have the same capacity for all caches. We use 128 as we'll only need that
@@ -61,14 +61,11 @@ pub(crate) struct RequestResultCache {
LruMap<(Hash, ParaId, OccupiedCoreAssumption), Option<ValidationCodeHash>>, LruMap<(Hash, ParaId, OccupiedCoreAssumption), Option<ValidationCodeHash>>,
version: LruMap<Hash, u32>, version: LruMap<Hash, u32>,
disputes: LruMap<Hash, Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)>>, disputes: LruMap<Hash, Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)>>,
unapplied_slashes: unapplied_slashes: LruMap<Hash, Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>>,
LruMap<Hash, Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>>, key_ownership_proof: LruMap<(Hash, ValidatorId), Option<slashing::OpaqueKeyOwnershipProof>>,
key_ownership_proof:
LruMap<(Hash, ValidatorId), Option<vstaging::slashing::OpaqueKeyOwnershipProof>>,
minimum_backing_votes: LruMap<SessionIndex, u32>, minimum_backing_votes: LruMap<SessionIndex, u32>,
para_backing_state: LruMap<(Hash, ParaId), Option<async_backing::BackingState>>,
staging_para_backing_state: LruMap<(Hash, ParaId), Option<vstaging::BackingState>>, async_backing_params: LruMap<Hash, async_backing::AsyncBackingParams>,
staging_async_backing_params: LruMap<Hash, vstaging::AsyncBackingParams>,
} }
impl Default for RequestResultCache { impl Default for RequestResultCache {
@@ -100,8 +97,8 @@ impl Default for RequestResultCache {
key_ownership_proof: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), key_ownership_proof: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
minimum_backing_votes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), minimum_backing_votes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
staging_para_backing_state: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), para_backing_state: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
staging_async_backing_params: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), async_backing_params: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
} }
} }
} }
@@ -401,14 +398,14 @@ impl RequestResultCache {
pub(crate) fn unapplied_slashes( pub(crate) fn unapplied_slashes(
&mut self, &mut self,
relay_parent: &Hash, relay_parent: &Hash,
) -> Option<&Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>> { ) -> Option<&Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>> {
self.unapplied_slashes.get(relay_parent).map(|v| &*v) self.unapplied_slashes.get(relay_parent).map(|v| &*v)
} }
pub(crate) fn cache_unapplied_slashes( pub(crate) fn cache_unapplied_slashes(
&mut self, &mut self,
relay_parent: Hash, relay_parent: Hash,
value: Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>, value: Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>,
) { ) {
self.unapplied_slashes.insert(relay_parent, value); self.unapplied_slashes.insert(relay_parent, value);
} }
@@ -416,14 +413,14 @@ impl RequestResultCache {
pub(crate) fn key_ownership_proof( pub(crate) fn key_ownership_proof(
&mut self, &mut self,
key: (Hash, ValidatorId), key: (Hash, ValidatorId),
) -> Option<&Option<vstaging::slashing::OpaqueKeyOwnershipProof>> { ) -> Option<&Option<slashing::OpaqueKeyOwnershipProof>> {
self.key_ownership_proof.get(&key).map(|v| &*v) self.key_ownership_proof.get(&key).map(|v| &*v)
} }
pub(crate) fn cache_key_ownership_proof( pub(crate) fn cache_key_ownership_proof(
&mut self, &mut self,
key: (Hash, ValidatorId), key: (Hash, ValidatorId),
value: Option<vstaging::slashing::OpaqueKeyOwnershipProof>, value: Option<slashing::OpaqueKeyOwnershipProof>,
) { ) {
self.key_ownership_proof.insert(key, value); self.key_ownership_proof.insert(key, value);
} }
@@ -431,7 +428,7 @@ impl RequestResultCache {
// This request is never cached, hence always returns `None`. // This request is never cached, hence always returns `None`.
pub(crate) fn submit_report_dispute_lost( pub(crate) fn submit_report_dispute_lost(
&mut self, &mut self,
_key: (Hash, vstaging::slashing::DisputeProof, vstaging::slashing::OpaqueKeyOwnershipProof), _key: (Hash, slashing::DisputeProof, slashing::OpaqueKeyOwnershipProof),
) -> Option<&Option<()>> { ) -> Option<&Option<()>> {
None None
} }
@@ -448,34 +445,34 @@ impl RequestResultCache {
self.minimum_backing_votes.insert(session_index, minimum_backing_votes); self.minimum_backing_votes.insert(session_index, minimum_backing_votes);
} }
pub(crate) fn staging_para_backing_state( pub(crate) fn para_backing_state(
&mut self, &mut self,
key: (Hash, ParaId), key: (Hash, ParaId),
) -> Option<&Option<vstaging::BackingState>> { ) -> Option<&Option<async_backing::BackingState>> {
self.staging_para_backing_state.get(&key).map(|v| &*v) self.para_backing_state.get(&key).map(|v| &*v)
} }
pub(crate) fn cache_staging_para_backing_state( pub(crate) fn cache_para_backing_state(
&mut self, &mut self,
key: (Hash, ParaId), key: (Hash, ParaId),
value: Option<vstaging::BackingState>, value: Option<async_backing::BackingState>,
) { ) {
self.staging_para_backing_state.insert(key, value); self.para_backing_state.insert(key, value);
} }
pub(crate) fn staging_async_backing_params( pub(crate) fn async_backing_params(
&mut self, &mut self,
key: &Hash, key: &Hash,
) -> Option<&vstaging::AsyncBackingParams> { ) -> Option<&async_backing::AsyncBackingParams> {
self.staging_async_backing_params.get(key).map(|v| &*v) self.async_backing_params.get(key).map(|v| &*v)
} }
pub(crate) fn cache_staging_async_backing_params( pub(crate) fn cache_async_backing_params(
&mut self, &mut self,
key: Hash, key: Hash,
value: vstaging::AsyncBackingParams, value: async_backing::AsyncBackingParams,
) { ) {
self.staging_async_backing_params.insert(key, value); self.async_backing_params.insert(key, value);
} }
} }
@@ -515,16 +512,15 @@ pub(crate) enum RequestResult {
ValidationCodeHash(Hash, ParaId, OccupiedCoreAssumption, Option<ValidationCodeHash>), ValidationCodeHash(Hash, ParaId, OccupiedCoreAssumption, Option<ValidationCodeHash>),
Version(Hash, u32), Version(Hash, u32),
Disputes(Hash, Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)>), Disputes(Hash, Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)>),
UnappliedSlashes(Hash, Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>), UnappliedSlashes(Hash, Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>),
KeyOwnershipProof(Hash, ValidatorId, Option<vstaging::slashing::OpaqueKeyOwnershipProof>), KeyOwnershipProof(Hash, ValidatorId, Option<slashing::OpaqueKeyOwnershipProof>),
// This is a request with side-effects. // This is a request with side-effects.
SubmitReportDisputeLost( SubmitReportDisputeLost(
Hash, Hash,
vstaging::slashing::DisputeProof, slashing::DisputeProof,
vstaging::slashing::OpaqueKeyOwnershipProof, slashing::OpaqueKeyOwnershipProof,
Option<()>, Option<()>,
), ),
ParaBackingState(Hash, ParaId, Option<async_backing::BackingState>),
StagingParaBackingState(Hash, ParaId, Option<vstaging::BackingState>), AsyncBackingParams(Hash, async_backing::AsyncBackingParams),
StagingAsyncBackingParams(Hash, vstaging::AsyncBackingParams),
} }
+14 -19
View File
@@ -166,12 +166,11 @@ where
.requests_cache .requests_cache
.cache_key_ownership_proof((relay_parent, validator_id), key_ownership_proof), .cache_key_ownership_proof((relay_parent, validator_id), key_ownership_proof),
SubmitReportDisputeLost(_, _, _, _) => {}, SubmitReportDisputeLost(_, _, _, _) => {},
ParaBackingState(relay_parent, para_id, constraints) => self
StagingParaBackingState(relay_parent, para_id, constraints) => self
.requests_cache .requests_cache
.cache_staging_para_backing_state((relay_parent, para_id), constraints), .cache_para_backing_state((relay_parent, para_id), constraints),
StagingAsyncBackingParams(relay_parent, params) => AsyncBackingParams(relay_parent, params) =>
self.requests_cache.cache_staging_async_backing_params(relay_parent, params), self.requests_cache.cache_async_backing_params(relay_parent, params),
} }
} }
@@ -297,13 +296,10 @@ where
Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender)
}, },
), ),
Request::ParaBackingState(para, sender) => query!(para_backing_state(para), sender)
Request::StagingParaBackingState(para, sender) => .map(|sender| Request::ParaBackingState(para, sender)),
query!(staging_para_backing_state(para), sender) Request::AsyncBackingParams(sender) => query!(async_backing_params(), sender)
.map(|sender| Request::StagingParaBackingState(para, sender)), .map(|sender| Request::AsyncBackingParams(sender)),
Request::StagingAsyncBackingParams(sender) =>
query!(staging_async_backing_params(), sender)
.map(|sender| Request::StagingAsyncBackingParams(sender)),
Request::MinimumBackingVotes(index, sender) => { Request::MinimumBackingVotes(index, sender) => {
if let Some(value) = self.requests_cache.minimum_backing_votes(index) { if let Some(value) = self.requests_cache.minimum_backing_votes(index) {
self.metrics.on_cached_request(); self.metrics.on_cached_request();
@@ -569,19 +565,18 @@ where
ver = Request::MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT, ver = Request::MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT,
sender sender
), ),
Request::ParaBackingState(para, sender) => {
Request::StagingParaBackingState(para, sender) => {
query!( query!(
StagingParaBackingState, ParaBackingState,
staging_para_backing_state(para), para_backing_state(para),
ver = Request::STAGING_BACKING_STATE, ver = Request::STAGING_BACKING_STATE,
sender sender
) )
}, },
Request::StagingAsyncBackingParams(sender) => { Request::AsyncBackingParams(sender) => {
query!( query!(
StagingAsyncBackingParams, AsyncBackingParams,
staging_async_backing_params(), async_backing_params(),
ver = Request::STAGING_BACKING_STATE, ver = Request::STAGING_BACKING_STATE,
sender sender
) )
+11 -11
View File
@@ -20,9 +20,9 @@ use polkadot_node_primitives::{BabeAllowedSlots, BabeEpoch, BabeEpochConfigurati
use polkadot_node_subsystem::SpawnGlue; use polkadot_node_subsystem::SpawnGlue;
use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_node_subsystem_test_helpers::make_subsystem_context;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging, AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, async_backing, slashing, AuthorityDiscoveryId, BlockNumber, CandidateCommitments,
CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState,
GroupRotationInfo, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, ExecutorParams, GroupRotationInfo, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes,
SessionIndex, SessionInfo, Slot, ValidationCode, ValidationCodeHash, ValidatorId, SessionIndex, SessionInfo, Slot, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, ValidatorSignature, ValidatorIndex, ValidatorSignature,
@@ -213,7 +213,7 @@ impl RuntimeApiSubsystemClient for MockSubsystemClient {
async fn unapplied_slashes( async fn unapplied_slashes(
&self, &self,
_: Hash, _: Hash,
) -> Result<Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>, ApiError> { ) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>, ApiError> {
todo!("Not required for tests") todo!("Not required for tests")
} }
@@ -221,15 +221,15 @@ impl RuntimeApiSubsystemClient for MockSubsystemClient {
&self, &self,
_: Hash, _: Hash,
_: ValidatorId, _: ValidatorId,
) -> Result<Option<vstaging::slashing::OpaqueKeyOwnershipProof>, ApiError> { ) -> Result<Option<slashing::OpaqueKeyOwnershipProof>, ApiError> {
todo!("Not required for tests") todo!("Not required for tests")
} }
async fn submit_report_dispute_lost( async fn submit_report_dispute_lost(
&self, &self,
_: Hash, _: Hash,
_: vstaging::slashing::DisputeProof, _: slashing::DisputeProof,
_: vstaging::slashing::OpaqueKeyOwnershipProof, _: slashing::OpaqueKeyOwnershipProof,
) -> Result<Option<()>, ApiError> { ) -> Result<Option<()>, ApiError> {
todo!("Not required for tests") todo!("Not required for tests")
} }
@@ -250,18 +250,18 @@ impl RuntimeApiSubsystemClient for MockSubsystemClient {
Ok(self.authorities.clone()) Ok(self.authorities.clone())
} }
async fn staging_async_backing_params( async fn async_backing_params(
&self, &self,
_: Hash, _: Hash,
) -> Result<vstaging::AsyncBackingParams, ApiError> { ) -> Result<async_backing::AsyncBackingParams, ApiError> {
todo!("Not required for tests") todo!("Not required for tests")
} }
async fn staging_para_backing_state( async fn para_backing_state(
&self, &self,
_: Hash, _: Hash,
_: ParaId, _: ParaId,
) -> Result<Option<vstaging::BackingState>, ApiError> { ) -> Result<Option<async_backing::BackingState>, ApiError> {
todo!("Not required for tests") todo!("Not required for tests")
} }
@@ -26,8 +26,8 @@ use polkadot_node_network_protocol::{
self as net_protocol, self as net_protocol,
grid_topology::{RandomRouting, RequiredRouting, SessionGridTopologies, SessionGridTopology}, grid_topology::{RandomRouting, RequiredRouting, SessionGridTopologies, SessionGridTopology},
peer_set::{ValidationVersion, MAX_NOTIFICATION_SIZE}, peer_set::{ValidationVersion, MAX_NOTIFICATION_SIZE},
v1 as protocol_v1, vstaging as protocol_vstaging, PeerId, UnifiedReputationChange as Rep, v1 as protocol_v1, v2 as protocol_v2, PeerId, UnifiedReputationChange as Rep, Versioned,
Versioned, VersionedValidationProtocol, View, VersionedValidationProtocol, View,
}; };
use polkadot_node_primitives::approval::{ use polkadot_node_primitives::approval::{
AssignmentCert, BlockApprovalMeta, IndirectAssignmentCert, IndirectSignedApprovalVote, AssignmentCert, BlockApprovalMeta, IndirectAssignmentCert, IndirectSignedApprovalVote,
@@ -602,9 +602,7 @@ impl State {
{ {
match msg { match msg {
Versioned::V1(protocol_v1::ApprovalDistributionMessage::Assignments(assignments)) | Versioned::V1(protocol_v1::ApprovalDistributionMessage::Assignments(assignments)) |
Versioned::VStaging(protocol_vstaging::ApprovalDistributionMessage::Assignments( Versioned::V2(protocol_v2::ApprovalDistributionMessage::Assignments(assignments)) => {
assignments,
)) => {
gum::trace!( gum::trace!(
target: LOG_TARGET, target: LOG_TARGET,
peer_id = %peer_id, peer_id = %peer_id,
@@ -644,9 +642,7 @@ impl State {
} }
}, },
Versioned::V1(protocol_v1::ApprovalDistributionMessage::Approvals(approvals)) | Versioned::V1(protocol_v1::ApprovalDistributionMessage::Approvals(approvals)) |
Versioned::VStaging(protocol_vstaging::ApprovalDistributionMessage::Approvals( Versioned::V2(protocol_v2::ApprovalDistributionMessage::Approvals(approvals)) => {
approvals,
)) => {
gum::trace!( gum::trace!(
target: LOG_TARGET, target: LOG_TARGET,
peer_id = %peer_id, peer_id = %peer_id,
@@ -1060,7 +1056,7 @@ impl State {
route_random route_random
}; };
let (v1_peers, vstaging_peers) = { let (v1_peers, v2_peers) = {
let peer_data = &self.peer_data; let peer_data = &self.peer_data;
let peers = entry let peers = entry
.known_by .known_by
@@ -1090,9 +1086,9 @@ impl State {
} }
let v1_peers = filter_peers_by_version(&peers, ValidationVersion::V1); let v1_peers = filter_peers_by_version(&peers, ValidationVersion::V1);
let vstaging_peers = filter_peers_by_version(&peers, ValidationVersion::VStaging); let v2_peers = filter_peers_by_version(&peers, ValidationVersion::V2);
(v1_peers, vstaging_peers) (v1_peers, v2_peers)
}; };
if !v1_peers.is_empty() { if !v1_peers.is_empty() {
@@ -1103,10 +1099,10 @@ impl State {
.await; .await;
} }
if !vstaging_peers.is_empty() { if !v2_peers.is_empty() {
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
vstaging_peers, v2_peers,
versioned_assignments_packet(ValidationVersion::VStaging, assignments.clone()), versioned_assignments_packet(ValidationVersion::V2, assignments.clone()),
)) ))
.await; .await;
} }
@@ -1395,7 +1391,7 @@ impl State {
in_topology || knowledge.sent.contains(message_subject, MessageKind::Assignment) in_topology || knowledge.sent.contains(message_subject, MessageKind::Assignment)
}; };
let (v1_peers, vstaging_peers) = { let (v1_peers, v2_peers) = {
let peer_data = &self.peer_data; let peer_data = &self.peer_data;
let peers = entry let peers = entry
.known_by .known_by
@@ -1425,9 +1421,9 @@ impl State {
} }
let v1_peers = filter_peers_by_version(&peers, ValidationVersion::V1); let v1_peers = filter_peers_by_version(&peers, ValidationVersion::V1);
let vstaging_peers = filter_peers_by_version(&peers, ValidationVersion::VStaging); let v2_peers = filter_peers_by_version(&peers, ValidationVersion::V2);
(v1_peers, vstaging_peers) (v1_peers, v2_peers)
}; };
let approvals = vec![vote]; let approvals = vec![vote];
@@ -1440,10 +1436,10 @@ impl State {
.await; .await;
} }
if !vstaging_peers.is_empty() { if !v2_peers.is_empty() {
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
vstaging_peers, v2_peers,
versioned_approvals_packet(ValidationVersion::VStaging, approvals), versioned_approvals_packet(ValidationVersion::V2, approvals),
)) ))
.await; .await;
} }
@@ -2017,9 +2013,9 @@ fn versioned_approvals_packet(
Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution(
protocol_v1::ApprovalDistributionMessage::Approvals(approvals), protocol_v1::ApprovalDistributionMessage::Approvals(approvals),
)), )),
ValidationVersion::VStaging => ValidationVersion::V2 =>
Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( Versioned::V2(protocol_v2::ValidationProtocol::ApprovalDistribution(
protocol_vstaging::ApprovalDistributionMessage::Approvals(approvals), protocol_v2::ApprovalDistributionMessage::Approvals(approvals),
)), )),
} }
} }
@@ -2033,9 +2029,9 @@ fn versioned_assignments_packet(
Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution(
protocol_v1::ApprovalDistributionMessage::Assignments(assignments), protocol_v1::ApprovalDistributionMessage::Assignments(assignments),
)), )),
ValidationVersion::VStaging => ValidationVersion::V2 =>
Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( Versioned::V2(protocol_v2::ValidationProtocol::ApprovalDistribution(
protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments), protocol_v2::ApprovalDistributionMessage::Assignments(assignments),
)), )),
} }
} }
@@ -2388,9 +2388,9 @@ fn import_versioned_approval() {
let _ = test_harness(state, |mut virtual_overseer| async move { let _ = test_harness(state, |mut virtual_overseer| async move {
let overseer = &mut virtual_overseer; let overseer = &mut virtual_overseer;
// All peers are aware of relay parent. // All peers are aware of relay parent.
setup_peer_with_view(overseer, &peer_a, ValidationVersion::VStaging, view![hash]).await; setup_peer_with_view(overseer, &peer_a, ValidationVersion::V2, view![hash]).await;
setup_peer_with_view(overseer, &peer_b, ValidationVersion::V1, view![hash]).await; setup_peer_with_view(overseer, &peer_b, ValidationVersion::V1, view![hash]).await;
setup_peer_with_view(overseer, &peer_c, ValidationVersion::VStaging, view![hash]).await; setup_peer_with_view(overseer, &peer_c, ValidationVersion::V2, view![hash]).await;
// new block `hash_a` with 1 candidates // new block `hash_a` with 1 candidates
let meta = BlockApprovalMeta { let meta = BlockApprovalMeta {
@@ -2431,8 +2431,8 @@ fn import_versioned_approval() {
overseer_recv(overseer).await, overseer_recv(overseer).await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( Versioned::V2(protocol_v2::ValidationProtocol::ApprovalDistribution(
protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments) protocol_v2::ApprovalDistributionMessage::Assignments(assignments)
)) ))
)) => { )) => {
assert_eq!(peers.len(), 2); assert_eq!(peers.len(), 2);
@@ -2450,8 +2450,8 @@ fn import_versioned_approval() {
validator: validator_index, validator: validator_index,
signature: dummy_signature(), signature: dummy_signature(),
}; };
let msg = protocol_vstaging::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); let msg = protocol_v2::ApprovalDistributionMessage::Approvals(vec![approval.clone()]);
send_message_from_peer(overseer, &peer_a, Versioned::VStaging(msg)).await; send_message_from_peer(overseer, &peer_a, Versioned::V2(msg)).await;
assert_matches!( assert_matches!(
overseer_recv(overseer).await, overseer_recv(overseer).await,
@@ -2483,8 +2483,8 @@ fn import_versioned_approval() {
overseer_recv(overseer).await, overseer_recv(overseer).await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( Versioned::V2(protocol_v2::ValidationProtocol::ApprovalDistribution(
protocol_vstaging::ApprovalDistributionMessage::Approvals(approvals) protocol_v2::ApprovalDistributionMessage::Approvals(approvals)
)) ))
)) => { )) => {
assert_eq!(peers, vec![peer_c]); assert_eq!(peers, vec![peer_c]);
@@ -31,8 +31,8 @@ use polkadot_node_network_protocol::{
GridNeighbors, RandomRouting, RequiredRouting, SessionBoundGridTopologyStorage, GridNeighbors, RandomRouting, RequiredRouting, SessionBoundGridTopologyStorage,
}, },
peer_set::{ProtocolVersion, ValidationVersion}, peer_set::{ProtocolVersion, ValidationVersion},
v1 as protocol_v1, vstaging as protocol_vstaging, OurView, PeerId, v1 as protocol_v1, v2 as protocol_v2, OurView, PeerId, UnifiedReputationChange as Rep,
UnifiedReputationChange as Rep, Versioned, View, Versioned, View,
}; };
use polkadot_node_subsystem::{ use polkadot_node_subsystem::{
jaeger, messages::*, overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, PerLeafSpan, jaeger, messages::*, overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, PerLeafSpan,
@@ -96,8 +96,8 @@ impl BitfieldGossipMessage {
self.relay_parent, self.relay_parent,
self.signed_availability.into(), self.signed_availability.into(),
)), )),
Some(ValidationVersion::VStaging) => Some(ValidationVersion::V2) =>
Versioned::VStaging(protocol_vstaging::BitfieldDistributionMessage::Bitfield( Versioned::V2(protocol_v2::BitfieldDistributionMessage::Bitfield(
self.relay_parent, self.relay_parent,
self.signed_availability.into(), self.signed_availability.into(),
)), )),
@@ -502,8 +502,7 @@ async fn relay_message<Context>(
}; };
let v1_interested_peers = filter_by_version(&interested_peers, ValidationVersion::V1); let v1_interested_peers = filter_by_version(&interested_peers, ValidationVersion::V1);
let vstaging_interested_peers = let v2_interested_peers = filter_by_version(&interested_peers, ValidationVersion::V2);
filter_by_version(&interested_peers, ValidationVersion::VStaging);
if !v1_interested_peers.is_empty() { if !v1_interested_peers.is_empty() {
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
@@ -513,10 +512,10 @@ async fn relay_message<Context>(
.await; .await;
} }
if !vstaging_interested_peers.is_empty() { if !v2_interested_peers.is_empty() {
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
vstaging_interested_peers, v2_interested_peers,
message.into_validation_protocol(ValidationVersion::VStaging.into()), message.into_validation_protocol(ValidationVersion::V2.into()),
)) ))
.await .await
} }
@@ -538,7 +537,7 @@ async fn process_incoming_peer_message<Context>(
relay_parent, relay_parent,
bitfield, bitfield,
)) => (relay_parent, bitfield), )) => (relay_parent, bitfield),
Versioned::VStaging(protocol_vstaging::BitfieldDistributionMessage::Bitfield( Versioned::V2(protocol_v2::BitfieldDistributionMessage::Bitfield(
relay_parent, relay_parent,
bitfield, bitfield,
)) => (relay_parent, bitfield), )) => (relay_parent, bitfield),
@@ -1111,9 +1111,9 @@ fn network_protocol_versioning() {
let peer_c = PeerId::random(); let peer_c = PeerId::random();
let peers = [ let peers = [
(peer_a, ValidationVersion::VStaging), (peer_a, ValidationVersion::V2),
(peer_b, ValidationVersion::V1), (peer_b, ValidationVersion::V1),
(peer_c, ValidationVersion::VStaging), (peer_c, ValidationVersion::V2),
]; ];
// validator 0 key pair // validator 0 key pair
@@ -1173,7 +1173,7 @@ fn network_protocol_versioning() {
&Default::default(), &Default::default(),
NetworkBridgeEvent::PeerMessage( NetworkBridgeEvent::PeerMessage(
peer_a, peer_a,
msg.clone().into_network_message(ValidationVersion::VStaging.into()), msg.clone().into_network_message(ValidationVersion::V2.into()),
), ),
&mut rng, &mut rng,
)); ));
@@ -1201,14 +1201,14 @@ fn network_protocol_versioning() {
} }
); );
// vstaging gossip // v2 gossip
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::NetworkBridgeTx( AllMessages::NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage(peers, send_msg), NetworkBridgeTxMessage::SendValidationMessage(peers, send_msg),
) => { ) => {
assert_eq!(peers, vec![peer_c]); assert_eq!(peers, vec![peer_c]);
assert_eq!(send_msg, msg.clone().into_validation_protocol(ValidationVersion::VStaging.into())); assert_eq!(send_msg, msg.clone().into_validation_protocol(ValidationVersion::V2.into()));
} }
); );
+21 -23
View File
@@ -33,7 +33,7 @@ use polkadot_node_network_protocol::{
CollationVersion, PeerSet, PeerSetProtocolNames, PerPeerSet, ProtocolVersion, CollationVersion, PeerSet, PeerSetProtocolNames, PerPeerSet, ProtocolVersion,
ValidationVersion, ValidationVersion,
}, },
v1 as protocol_v1, vstaging as protocol_vstaging, ObservedRole, OurView, PeerId, v1 as protocol_v1, v2 as protocol_v2, ObservedRole, OurView, PeerId,
UnifiedReputationChange as Rep, View, UnifiedReputationChange as Rep, View,
}; };
@@ -262,13 +262,13 @@ where
), ),
&metrics, &metrics,
), ),
ValidationVersion::VStaging => send_message( ValidationVersion::V2 => send_message(
&mut network_service, &mut network_service,
vec![peer], vec![peer],
PeerSet::Validation, PeerSet::Validation,
version, version,
&peerset_protocol_names, &peerset_protocol_names,
WireMessage::<protocol_vstaging::ValidationProtocol>::ViewUpdate( WireMessage::<protocol_v2::ValidationProtocol>::ViewUpdate(
local_view, local_view,
), ),
&metrics, &metrics,
@@ -304,13 +304,13 @@ where
), ),
&metrics, &metrics,
), ),
CollationVersion::VStaging => send_message( CollationVersion::V2 => send_message(
&mut network_service, &mut network_service,
vec![peer], vec![peer],
PeerSet::Collation, PeerSet::Collation,
version, version,
&peerset_protocol_names, &peerset_protocol_names,
WireMessage::<protocol_vstaging::CollationProtocol>::ViewUpdate( WireMessage::<protocol_v2::CollationProtocol>::ViewUpdate(
local_view, local_view,
), ),
&metrics, &metrics,
@@ -465,9 +465,9 @@ where
&metrics, &metrics,
) )
} else if expected_versions[PeerSet::Validation] == } else if expected_versions[PeerSet::Validation] ==
Some(ValidationVersion::VStaging.into()) Some(ValidationVersion::V2.into())
{ {
handle_peer_messages::<protocol_vstaging::ValidationProtocol, _>( handle_peer_messages::<protocol_v2::ValidationProtocol, _>(
remote, remote,
PeerSet::Validation, PeerSet::Validation,
&mut shared.0.lock().validation_peers, &mut shared.0.lock().validation_peers,
@@ -507,9 +507,9 @@ where
&metrics, &metrics,
) )
} else if expected_versions[PeerSet::Collation] == } else if expected_versions[PeerSet::Collation] ==
Some(CollationVersion::VStaging.into()) Some(CollationVersion::V2.into())
{ {
handle_peer_messages::<protocol_vstaging::CollationProtocol, _>( handle_peer_messages::<protocol_v2::CollationProtocol, _>(
remote, remote,
PeerSet::Collation, PeerSet::Collation,
&mut shared.0.lock().collation_peers, &mut shared.0.lock().collation_peers,
@@ -813,10 +813,8 @@ fn update_our_view<Net, Context>(
let v1_validation_peers = filter_by_version(&validation_peers, ValidationVersion::V1.into()); let v1_validation_peers = filter_by_version(&validation_peers, ValidationVersion::V1.into());
let v1_collation_peers = filter_by_version(&collation_peers, CollationVersion::V1.into()); let v1_collation_peers = filter_by_version(&collation_peers, CollationVersion::V1.into());
let vstaging_validation_peers = let v2_validation_peers = filter_by_version(&validation_peers, ValidationVersion::V2.into());
filter_by_version(&validation_peers, ValidationVersion::VStaging.into()); let v2_collation_peers = filter_by_version(&collation_peers, ValidationVersion::V2.into());
let vstaging_collation_peers =
filter_by_version(&collation_peers, ValidationVersion::VStaging.into());
send_validation_message_v1( send_validation_message_v1(
net, net,
@@ -834,17 +832,17 @@ fn update_our_view<Net, Context>(
metrics, metrics,
); );
send_validation_message_vstaging( send_validation_message_v2(
net, net,
vstaging_validation_peers, v2_validation_peers,
peerset_protocol_names, peerset_protocol_names,
WireMessage::ViewUpdate(new_view.clone()), WireMessage::ViewUpdate(new_view.clone()),
metrics, metrics,
); );
send_collation_message_vstaging( send_collation_message_v2(
net, net,
vstaging_collation_peers, v2_collation_peers,
peerset_protocol_names, peerset_protocol_names,
WireMessage::ViewUpdate(new_view), WireMessage::ViewUpdate(new_view),
metrics, metrics,
@@ -955,36 +953,36 @@ fn send_collation_message_v1(
); );
} }
fn send_validation_message_vstaging( fn send_validation_message_v2(
net: &mut impl Network, net: &mut impl Network,
peers: Vec<PeerId>, peers: Vec<PeerId>,
protocol_names: &PeerSetProtocolNames, protocol_names: &PeerSetProtocolNames,
message: WireMessage<protocol_vstaging::ValidationProtocol>, message: WireMessage<protocol_v2::ValidationProtocol>,
metrics: &Metrics, metrics: &Metrics,
) { ) {
send_message( send_message(
net, net,
peers, peers,
PeerSet::Validation, PeerSet::Validation,
ValidationVersion::VStaging.into(), ValidationVersion::V2.into(),
protocol_names, protocol_names,
message, message,
metrics, metrics,
); );
} }
fn send_collation_message_vstaging( fn send_collation_message_v2(
net: &mut impl Network, net: &mut impl Network,
peers: Vec<PeerId>, peers: Vec<PeerId>,
protocol_names: &PeerSetProtocolNames, protocol_names: &PeerSetProtocolNames,
message: WireMessage<protocol_vstaging::CollationProtocol>, message: WireMessage<protocol_v2::CollationProtocol>,
metrics: &Metrics, metrics: &Metrics,
) { ) {
send_message( send_message(
net, net,
peers, peers,
PeerSet::Collation, PeerSet::Collation,
CollationVersion::VStaging.into(), CollationVersion::V2.into(),
protocol_names, protocol_names,
message, message,
metrics, metrics,
+12 -17
View File
@@ -1216,10 +1216,10 @@ fn network_protocol_versioning_view_update() {
let peer_ids: Vec<_> = (0..4).map(|_| PeerId::random()).collect(); let peer_ids: Vec<_> = (0..4).map(|_| PeerId::random()).collect();
let peers = [ let peers = [
(peer_ids[0], PeerSet::Validation, ValidationVersion::VStaging), (peer_ids[0], PeerSet::Validation, ValidationVersion::V2),
(peer_ids[1], PeerSet::Collation, ValidationVersion::V1), (peer_ids[1], PeerSet::Collation, ValidationVersion::V1),
(peer_ids[2], PeerSet::Validation, ValidationVersion::V1), (peer_ids[2], PeerSet::Validation, ValidationVersion::V1),
(peer_ids[3], PeerSet::Collation, ValidationVersion::VStaging), (peer_ids[3], PeerSet::Collation, ValidationVersion::V2),
]; ];
let head = Hash::repeat_byte(1); let head = Hash::repeat_byte(1);
@@ -1245,8 +1245,8 @@ fn network_protocol_versioning_view_update() {
ValidationVersion::V1 => ValidationVersion::V1 =>
WireMessage::<protocol_v1::ValidationProtocol>::ViewUpdate(view.clone()) WireMessage::<protocol_v1::ValidationProtocol>::ViewUpdate(view.clone())
.encode(), .encode(),
ValidationVersion::VStaging => ValidationVersion::V2 =>
WireMessage::<protocol_vstaging::ValidationProtocol>::ViewUpdate(view.clone()) WireMessage::<protocol_v2::ValidationProtocol>::ViewUpdate(view.clone())
.encode(), .encode(),
}; };
assert_network_actions_contains( assert_network_actions_contains(
@@ -1268,12 +1268,7 @@ fn network_protocol_versioning_subsystem_msg() {
let peer = PeerId::random(); let peer = PeerId::random();
network_handle network_handle
.connect_peer( .connect_peer(peer, ValidationVersion::V2, PeerSet::Validation, ObservedRole::Full)
peer,
ValidationVersion::VStaging,
PeerSet::Validation,
ObservedRole::Full,
)
.await; .await;
// bridge will inform about all connected peers. // bridge will inform about all connected peers.
@@ -1282,7 +1277,7 @@ fn network_protocol_versioning_subsystem_msg() {
NetworkBridgeEvent::PeerConnected( NetworkBridgeEvent::PeerConnected(
peer, peer,
ObservedRole::Full, ObservedRole::Full,
ValidationVersion::VStaging.into(), ValidationVersion::V2.into(),
None, None,
), ),
&mut virtual_overseer, &mut virtual_overseer,
@@ -1297,9 +1292,9 @@ fn network_protocol_versioning_subsystem_msg() {
} }
let approval_distribution_message = let approval_distribution_message =
protocol_vstaging::ApprovalDistributionMessage::Approvals(Vec::new()); protocol_v2::ApprovalDistributionMessage::Approvals(Vec::new());
let msg = protocol_vstaging::ValidationProtocol::ApprovalDistribution( let msg = protocol_v2::ValidationProtocol::ApprovalDistribution(
approval_distribution_message.clone(), approval_distribution_message.clone(),
); );
@@ -1315,7 +1310,7 @@ fn network_protocol_versioning_subsystem_msg() {
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::ApprovalDistribution( AllMessages::ApprovalDistribution(
ApprovalDistributionMessage::NetworkBridgeUpdate( ApprovalDistributionMessage::NetworkBridgeUpdate(
NetworkBridgeEvent::PeerMessage(p, Versioned::VStaging(m)) NetworkBridgeEvent::PeerMessage(p, Versioned::V2(m))
) )
) => { ) => {
assert_eq!(p, peer); assert_eq!(p, peer);
@@ -1330,10 +1325,10 @@ fn network_protocol_versioning_subsystem_msg() {
signature: sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64]), signature: sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64]),
}; };
let statement_distribution_message = let statement_distribution_message =
protocol_vstaging::StatementDistributionMessage::V1Compatibility( protocol_v2::StatementDistributionMessage::V1Compatibility(
protocol_v1::StatementDistributionMessage::LargeStatement(metadata), protocol_v1::StatementDistributionMessage::LargeStatement(metadata),
); );
let msg = protocol_vstaging::ValidationProtocol::StatementDistribution( let msg = protocol_v2::ValidationProtocol::StatementDistribution(
statement_distribution_message.clone(), statement_distribution_message.clone(),
); );
@@ -1349,7 +1344,7 @@ fn network_protocol_versioning_subsystem_msg() {
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::StatementDistribution( AllMessages::StatementDistribution(
StatementDistributionMessage::NetworkBridgeUpdate( StatementDistributionMessage::NetworkBridgeUpdate(
NetworkBridgeEvent::PeerMessage(p, Versioned::VStaging(m)) NetworkBridgeEvent::PeerMessage(p, Versioned::V2(m))
) )
) => { ) => {
assert_eq!(p, peer); assert_eq!(p, peer);
+13 -15
View File
@@ -20,7 +20,7 @@ use super::*;
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
peer_set::{CollationVersion, PeerSet, PeerSetProtocolNames, ValidationVersion}, peer_set::{CollationVersion, PeerSet, PeerSetProtocolNames, ValidationVersion},
request_response::ReqProtocolNames, request_response::ReqProtocolNames,
v1 as protocol_v1, vstaging as protocol_vstaging, PeerId, Versioned, v1 as protocol_v1, v2 as protocol_v2, PeerId, Versioned,
}; };
use polkadot_node_subsystem::{ use polkadot_node_subsystem::{
@@ -198,7 +198,7 @@ where
WireMessage::ProtocolMessage(msg), WireMessage::ProtocolMessage(msg),
&metrics, &metrics,
), ),
Versioned::VStaging(msg) => send_validation_message_vstaging( Versioned::V2(msg) => send_validation_message_v2(
&mut network_service, &mut network_service,
peers, peers,
peerset_protocol_names, peerset_protocol_names,
@@ -223,7 +223,7 @@ where
WireMessage::ProtocolMessage(msg), WireMessage::ProtocolMessage(msg),
&metrics, &metrics,
), ),
Versioned::VStaging(msg) => send_validation_message_vstaging( Versioned::V2(msg) => send_validation_message_v2(
&mut network_service, &mut network_service,
peers, peers,
peerset_protocol_names, peerset_protocol_names,
@@ -248,7 +248,7 @@ where
WireMessage::ProtocolMessage(msg), WireMessage::ProtocolMessage(msg),
&metrics, &metrics,
), ),
Versioned::VStaging(msg) => send_collation_message_vstaging( Versioned::V2(msg) => send_collation_message_v2(
&mut network_service, &mut network_service,
peers, peers,
peerset_protocol_names, peerset_protocol_names,
@@ -273,7 +273,7 @@ where
WireMessage::ProtocolMessage(msg), WireMessage::ProtocolMessage(msg),
&metrics, &metrics,
), ),
Versioned::VStaging(msg) => send_collation_message_vstaging( Versioned::V2(msg) => send_collation_message_v2(
&mut network_service, &mut network_service,
peers, peers,
peerset_protocol_names, peerset_protocol_names,
@@ -296,13 +296,11 @@ where
Requests::AvailableDataFetchingV1(_) => Requests::AvailableDataFetchingV1(_) =>
metrics.on_message("available_data_fetching_v1"), metrics.on_message("available_data_fetching_v1"),
Requests::CollationFetchingV1(_) => metrics.on_message("collation_fetching_v1"), Requests::CollationFetchingV1(_) => metrics.on_message("collation_fetching_v1"),
Requests::CollationFetchingVStaging(_) => Requests::CollationFetchingV2(_) => metrics.on_message("collation_fetching_v2"),
metrics.on_message("collation_fetching_vstaging"),
Requests::PoVFetchingV1(_) => metrics.on_message("pov_fetching_v1"), Requests::PoVFetchingV1(_) => metrics.on_message("pov_fetching_v1"),
Requests::DisputeSendingV1(_) => metrics.on_message("dispute_sending_v1"), Requests::DisputeSendingV1(_) => metrics.on_message("dispute_sending_v1"),
Requests::StatementFetchingV1(_) => metrics.on_message("statement_fetching_v1"), Requests::StatementFetchingV1(_) => metrics.on_message("statement_fetching_v1"),
Requests::AttestedCandidateVStaging(_) => Requests::AttestedCandidateV2(_) => metrics.on_message("attested_candidate_v2"),
metrics.on_message("attested_candidate_vstaging"),
} }
network_service network_service
@@ -425,36 +423,36 @@ fn send_collation_message_v1(
); );
} }
fn send_validation_message_vstaging( fn send_validation_message_v2(
net: &mut impl Network, net: &mut impl Network,
peers: Vec<PeerId>, peers: Vec<PeerId>,
protocol_names: &PeerSetProtocolNames, protocol_names: &PeerSetProtocolNames,
message: WireMessage<protocol_vstaging::ValidationProtocol>, message: WireMessage<protocol_v2::ValidationProtocol>,
metrics: &Metrics, metrics: &Metrics,
) { ) {
send_message( send_message(
net, net,
peers, peers,
PeerSet::Validation, PeerSet::Validation,
ValidationVersion::VStaging.into(), ValidationVersion::V2.into(),
protocol_names, protocol_names,
message, message,
metrics, metrics,
); );
} }
fn send_collation_message_vstaging( fn send_collation_message_v2(
net: &mut impl Network, net: &mut impl Network,
peers: Vec<PeerId>, peers: Vec<PeerId>,
protocol_names: &PeerSetProtocolNames, protocol_names: &PeerSetProtocolNames,
message: WireMessage<protocol_vstaging::CollationProtocol>, message: WireMessage<protocol_v2::CollationProtocol>,
metrics: &Metrics, metrics: &Metrics,
) { ) {
send_message( send_message(
net, net,
peers, peers,
PeerSet::Collation, PeerSet::Collation,
CollationVersion::VStaging.into(), CollationVersion::V2.into(),
protocol_names, protocol_names,
message, message,
metrics, metrics,
+9 -10
View File
@@ -341,10 +341,10 @@ fn network_protocol_versioning_send() {
let peer_ids: Vec<_> = (0..4).map(|_| PeerId::random()).collect(); let peer_ids: Vec<_> = (0..4).map(|_| PeerId::random()).collect();
let peers = [ let peers = [
(peer_ids[0], PeerSet::Validation, ValidationVersion::VStaging), (peer_ids[0], PeerSet::Validation, ValidationVersion::V2),
(peer_ids[1], PeerSet::Collation, ValidationVersion::V1), (peer_ids[1], PeerSet::Collation, ValidationVersion::V1),
(peer_ids[2], PeerSet::Validation, ValidationVersion::V1), (peer_ids[2], PeerSet::Validation, ValidationVersion::V1),
(peer_ids[3], PeerSet::Collation, ValidationVersion::VStaging), (peer_ids[3], PeerSet::Collation, ValidationVersion::V2),
]; ];
for &(peer_id, peer_set, version) in &peers { for &(peer_id, peer_set, version) in &peers {
@@ -359,9 +359,9 @@ fn network_protocol_versioning_send() {
{ {
let approval_distribution_message = let approval_distribution_message =
protocol_vstaging::ApprovalDistributionMessage::Approvals(Vec::new()); protocol_v2::ApprovalDistributionMessage::Approvals(Vec::new());
let msg = protocol_vstaging::ValidationProtocol::ApprovalDistribution( let msg = protocol_v2::ValidationProtocol::ApprovalDistribution(
approval_distribution_message.clone(), approval_distribution_message.clone(),
); );
@@ -372,7 +372,7 @@ fn network_protocol_versioning_send() {
.send(FromOrchestra::Communication { .send(FromOrchestra::Communication {
msg: NetworkBridgeTxMessage::SendValidationMessage( msg: NetworkBridgeTxMessage::SendValidationMessage(
receivers.clone(), receivers.clone(),
Versioned::VStaging(msg.clone()), Versioned::V2(msg.clone()),
), ),
}) })
.timeout(TIMEOUT) .timeout(TIMEOUT)
@@ -398,15 +398,14 @@ fn network_protocol_versioning_send() {
// send a collation protocol message. // send a collation protocol message.
{ {
let collator_protocol_message = protocol_vstaging::CollatorProtocolMessage::Declare( let collator_protocol_message = protocol_v2::CollatorProtocolMessage::Declare(
Sr25519Keyring::Alice.public().into(), Sr25519Keyring::Alice.public().into(),
0_u32.into(), 0_u32.into(),
dummy_collator_signature(), dummy_collator_signature(),
); );
let msg = protocol_vstaging::CollationProtocol::CollatorProtocol( let msg =
collator_protocol_message.clone(), protocol_v2::CollationProtocol::CollatorProtocol(collator_protocol_message.clone());
);
let receivers = vec![peer_ids[1], peer_ids[2]]; let receivers = vec![peer_ids[1], peer_ids[2]];
@@ -414,7 +413,7 @@ fn network_protocol_versioning_send() {
.send(FromOrchestra::Communication { .send(FromOrchestra::Communication {
msg: NetworkBridgeTxMessage::SendCollationMessages(vec![( msg: NetworkBridgeTxMessage::SendCollationMessages(vec![(
receivers.clone(), receivers.clone(),
Versioned::VStaging(msg.clone()), Versioned::V2(msg.clone()),
)]), )]),
}) })
.await; .await;
@@ -22,8 +22,7 @@ use futures::{future::BoxFuture, stream::FuturesUnordered};
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
request_response::{ request_response::{
incoming::OutgoingResponse, v1 as protocol_v1, vstaging as protocol_vstaging, incoming::OutgoingResponse, v1 as protocol_v1, v2 as protocol_v2, IncomingRequest,
IncomingRequest,
}, },
PeerId, PeerId,
}; };
@@ -89,7 +88,7 @@ pub struct WaitingCollationFetches {
/// Backwards-compatible wrapper for incoming collations requests. /// Backwards-compatible wrapper for incoming collations requests.
pub enum VersionedCollationRequest { pub enum VersionedCollationRequest {
V1(IncomingRequest<protocol_v1::CollationFetchingRequest>), V1(IncomingRequest<protocol_v1::CollationFetchingRequest>),
VStaging(IncomingRequest<protocol_vstaging::CollationFetchingRequest>), V2(IncomingRequest<protocol_v2::CollationFetchingRequest>),
} }
impl From<IncomingRequest<protocol_v1::CollationFetchingRequest>> for VersionedCollationRequest { impl From<IncomingRequest<protocol_v1::CollationFetchingRequest>> for VersionedCollationRequest {
@@ -98,11 +97,9 @@ impl From<IncomingRequest<protocol_v1::CollationFetchingRequest>> for VersionedC
} }
} }
impl From<IncomingRequest<protocol_vstaging::CollationFetchingRequest>> impl From<IncomingRequest<protocol_v2::CollationFetchingRequest>> for VersionedCollationRequest {
for VersionedCollationRequest fn from(req: IncomingRequest<protocol_v2::CollationFetchingRequest>) -> Self {
{ Self::V2(req)
fn from(req: IncomingRequest<protocol_vstaging::CollationFetchingRequest>) -> Self {
Self::VStaging(req)
} }
} }
@@ -111,7 +108,7 @@ impl VersionedCollationRequest {
pub fn para_id(&self) -> ParaId { pub fn para_id(&self) -> ParaId {
match self { match self {
VersionedCollationRequest::V1(req) => req.payload.para_id, VersionedCollationRequest::V1(req) => req.payload.para_id,
VersionedCollationRequest::VStaging(req) => req.payload.para_id, VersionedCollationRequest::V2(req) => req.payload.para_id,
} }
} }
@@ -119,7 +116,7 @@ impl VersionedCollationRequest {
pub fn relay_parent(&self) -> Hash { pub fn relay_parent(&self) -> Hash {
match self { match self {
VersionedCollationRequest::V1(req) => req.payload.relay_parent, VersionedCollationRequest::V1(req) => req.payload.relay_parent,
VersionedCollationRequest::VStaging(req) => req.payload.relay_parent, VersionedCollationRequest::V2(req) => req.payload.relay_parent,
} }
} }
@@ -127,7 +124,7 @@ impl VersionedCollationRequest {
pub fn peer_id(&self) -> PeerId { pub fn peer_id(&self) -> PeerId {
match self { match self {
VersionedCollationRequest::V1(req) => req.peer, VersionedCollationRequest::V1(req) => req.peer,
VersionedCollationRequest::VStaging(req) => req.peer, VersionedCollationRequest::V2(req) => req.peer,
} }
} }
@@ -138,7 +135,7 @@ impl VersionedCollationRequest {
) -> Result<(), ()> { ) -> Result<(), ()> {
match self { match self {
VersionedCollationRequest::V1(req) => req.send_outgoing_response(response), VersionedCollationRequest::V1(req) => req.send_outgoing_response(response),
VersionedCollationRequest::VStaging(req) => req.send_outgoing_response(response), VersionedCollationRequest::V2(req) => req.send_outgoing_response(response),
} }
} }
} }
@@ -31,10 +31,10 @@ use polkadot_node_network_protocol::{
peer_set::{CollationVersion, PeerSet}, peer_set::{CollationVersion, PeerSet},
request_response::{ request_response::{
incoming::{self, OutgoingResponse}, incoming::{self, OutgoingResponse},
v1 as request_v1, vstaging as request_vstaging, IncomingRequestReceiver, v1 as request_v1, v2 as request_v2, IncomingRequestReceiver,
}, },
v1 as protocol_v1, vstaging as protocol_vstaging, OurView, PeerId, v1 as protocol_v1, v2 as protocol_v2, OurView, PeerId, UnifiedReputationChange as Rep,
UnifiedReputationChange as Rep, Versioned, View, Versioned, View,
}; };
use polkadot_node_primitives::{CollationSecondedSignal, PoV, Statement}; use polkadot_node_primitives::{CollationSecondedSignal, PoV, Statement};
use polkadot_node_subsystem::{ use polkadot_node_subsystem::{
@@ -577,7 +577,7 @@ async fn determine_our_validators<Context>(
fn declare_message( fn declare_message(
state: &mut State, state: &mut State,
version: CollationVersion, version: CollationVersion,
) -> Option<Versioned<protocol_v1::CollationProtocol, protocol_vstaging::CollationProtocol>> { ) -> Option<Versioned<protocol_v1::CollationProtocol, protocol_v2::CollationProtocol>> {
let para_id = state.collating_on?; let para_id = state.collating_on?;
Some(match version { Some(match version {
CollationVersion::V1 => { CollationVersion::V1 => {
@@ -590,17 +590,15 @@ fn declare_message(
); );
Versioned::V1(protocol_v1::CollationProtocol::CollatorProtocol(wire_message)) Versioned::V1(protocol_v1::CollationProtocol::CollatorProtocol(wire_message))
}, },
CollationVersion::VStaging => { CollationVersion::V2 => {
let declare_signature_payload = let declare_signature_payload =
protocol_vstaging::declare_signature_payload(&state.local_peer_id); protocol_v2::declare_signature_payload(&state.local_peer_id);
let wire_message = protocol_vstaging::CollatorProtocolMessage::Declare( let wire_message = protocol_v2::CollatorProtocolMessage::Declare(
state.collator_pair.public(), state.collator_pair.public(),
para_id, para_id,
state.collator_pair.sign(&declare_signature_payload), state.collator_pair.sign(&declare_signature_payload),
); );
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(wire_message))
wire_message,
))
}, },
}) })
} }
@@ -706,15 +704,13 @@ async fn advertise_collation<Context>(
collation.status.advance_to_advertised(); collation.status.advance_to_advertised();
let collation_message = match protocol_version { let collation_message = match protocol_version {
CollationVersion::VStaging => { CollationVersion::V2 => {
let wire_message = protocol_vstaging::CollatorProtocolMessage::AdvertiseCollation { let wire_message = protocol_v2::CollatorProtocolMessage::AdvertiseCollation {
relay_parent, relay_parent,
candidate_hash: *candidate_hash, candidate_hash: *candidate_hash,
parent_head_data_hash: collation.parent_head_data_hash, parent_head_data_hash: collation.parent_head_data_hash,
}; };
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(wire_message))
wire_message,
))
}, },
CollationVersion::V1 => { CollationVersion::V1 => {
let wire_message = let wire_message =
@@ -837,7 +833,7 @@ async fn send_collation(
let candidate_hash = receipt.hash(); let candidate_hash = receipt.hash();
// The response payload is the same for both versions of protocol // The response payload is the same for both versions of protocol
// and doesn't have vstaging alias for simplicity. // and doesn't have v2 alias for simplicity.
let response = OutgoingResponse { let response = OutgoingResponse {
result: Ok(request_v1::CollationFetchingResponse::Collation(receipt, pov)), result: Ok(request_v1::CollationFetchingResponse::Collation(receipt, pov)),
reputation_changes: Vec::new(), reputation_changes: Vec::new(),
@@ -868,16 +864,13 @@ async fn handle_incoming_peer_message<Context>(
runtime: &mut RuntimeInfo, runtime: &mut RuntimeInfo,
state: &mut State, state: &mut State,
origin: PeerId, origin: PeerId,
msg: Versioned< msg: Versioned<protocol_v1::CollatorProtocolMessage, protocol_v2::CollatorProtocolMessage>,
protocol_v1::CollatorProtocolMessage,
protocol_vstaging::CollatorProtocolMessage,
>,
) -> Result<()> { ) -> Result<()> {
use protocol_v1::CollatorProtocolMessage as V1; use protocol_v1::CollatorProtocolMessage as V1;
use protocol_vstaging::CollatorProtocolMessage as VStaging; use protocol_v2::CollatorProtocolMessage as V2;
match msg { match msg {
Versioned::V1(V1::Declare(..)) | Versioned::VStaging(VStaging::Declare(..)) => { Versioned::V1(V1::Declare(..)) | Versioned::V2(V2::Declare(..)) => {
gum::trace!( gum::trace!(
target: LOG_TARGET, target: LOG_TARGET,
?origin, ?origin,
@@ -888,8 +881,7 @@ async fn handle_incoming_peer_message<Context>(
ctx.send_message(NetworkBridgeTxMessage::DisconnectPeer(origin, PeerSet::Collation)) ctx.send_message(NetworkBridgeTxMessage::DisconnectPeer(origin, PeerSet::Collation))
.await; .await;
}, },
Versioned::V1(V1::AdvertiseCollation(_)) | Versioned::V1(V1::AdvertiseCollation(_)) | Versioned::V2(V2::AdvertiseCollation { .. }) => {
Versioned::VStaging(VStaging::AdvertiseCollation { .. }) => {
gum::trace!( gum::trace!(
target: LOG_TARGET, target: LOG_TARGET,
?origin, ?origin,
@@ -904,7 +896,7 @@ async fn handle_incoming_peer_message<Context>(
.await; .await;
}, },
Versioned::V1(V1::CollationSeconded(relay_parent, statement)) | Versioned::V1(V1::CollationSeconded(relay_parent, statement)) |
Versioned::VStaging(VStaging::CollationSeconded(relay_parent, statement)) => { Versioned::V2(V2::CollationSeconded(relay_parent, statement)) => {
if !matches!(statement.unchecked_payload(), Statement::Seconded(_)) { if !matches!(statement.unchecked_payload(), Statement::Seconded(_)) {
gum::warn!( gum::warn!(
target: LOG_TARGET, target: LOG_TARGET,
@@ -1006,7 +998,7 @@ async fn handle_incoming_request<Context>(
let collation = match &req { let collation = match &req {
VersionedCollationRequest::V1(_) if !mode.is_enabled() => VersionedCollationRequest::V1(_) if !mode.is_enabled() =>
per_relay_parent.collations.values_mut().next(), per_relay_parent.collations.values_mut().next(),
VersionedCollationRequest::VStaging(req) => VersionedCollationRequest::V2(req) =>
per_relay_parent.collations.get_mut(&req.payload.candidate_hash), per_relay_parent.collations.get_mut(&req.payload.candidate_hash),
_ => { _ => {
gum::warn!( gum::warn!(
@@ -1322,7 +1314,7 @@ pub(crate) async fn run<Context>(
local_peer_id: PeerId, local_peer_id: PeerId,
collator_pair: CollatorPair, collator_pair: CollatorPair,
req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>, req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>,
req_v2_receiver: IncomingRequestReceiver<request_vstaging::CollationFetchingRequest>, req_v2_receiver: IncomingRequestReceiver<request_v2::CollationFetchingRequest>,
metrics: Metrics, metrics: Metrics,
) -> std::result::Result<(), FatalError> { ) -> std::result::Result<(), FatalError> {
run_inner( run_inner(
@@ -1344,7 +1336,7 @@ async fn run_inner<Context>(
local_peer_id: PeerId, local_peer_id: PeerId,
collator_pair: CollatorPair, collator_pair: CollatorPair,
mut req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>, mut req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>,
mut req_v2_receiver: IncomingRequestReceiver<request_vstaging::CollationFetchingRequest>, mut req_v2_receiver: IncomingRequestReceiver<request_v2::CollationFetchingRequest>,
metrics: Metrics, metrics: Metrics,
reputation: ReputationAggregator, reputation: ReputationAggregator,
reputation_interval: Duration, reputation_interval: Duration,
@@ -1425,7 +1417,7 @@ async fn run_inner<Context>(
(ProspectiveParachainsMode::Disabled, VersionedCollationRequest::V1(_)) => { (ProspectiveParachainsMode::Disabled, VersionedCollationRequest::V1(_)) => {
per_relay_parent.collations.values().next() per_relay_parent.collations.values().next()
}, },
(ProspectiveParachainsMode::Enabled { .. }, VersionedCollationRequest::VStaging(req)) => { (ProspectiveParachainsMode::Enabled { .. }, VersionedCollationRequest::V2(req)) => {
per_relay_parent.collations.get(&req.payload.candidate_hash) per_relay_parent.collations.get(&req.payload.candidate_hash)
}, },
_ => { _ => {
@@ -1476,7 +1468,7 @@ async fn run_inner<Context>(
log_error( log_error(
handle_incoming_request(&mut ctx, &mut state, request).await, handle_incoming_request(&mut ctx, &mut state, request).await,
"Handling incoming collation fetch request VStaging" "Handling incoming collation fetch request V2"
)?; )?;
} }
} }
@@ -198,7 +198,7 @@ impl TestState {
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
relay_parent, relay_parent,
RuntimeApiRequest::StagingAsyncBackingParams(tx) RuntimeApiRequest::AsyncBackingParams(tx)
)) => { )) => {
assert_eq!(relay_parent, self.relay_parent); assert_eq!(relay_parent, self.relay_parent);
tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap();
@@ -212,7 +212,7 @@ type VirtualOverseer = test_helpers::TestSubsystemContextHandle<CollatorProtocol
struct TestHarness { struct TestHarness {
virtual_overseer: VirtualOverseer, virtual_overseer: VirtualOverseer,
req_v1_cfg: sc_network::config::RequestResponseConfig, req_v1_cfg: sc_network::config::RequestResponseConfig,
req_vstaging_cfg: sc_network::config::RequestResponseConfig, req_v2_cfg: sc_network::config::RequestResponseConfig,
} }
fn test_harness<T: Future<Output = TestHarness>>( fn test_harness<T: Future<Output = TestHarness>>(
@@ -236,7 +236,7 @@ fn test_harness<T: Future<Output = TestHarness>>(
let (collation_req_receiver, req_v1_cfg) = let (collation_req_receiver, req_v1_cfg) =
IncomingRequest::get_config_receiver(&req_protocol_names); IncomingRequest::get_config_receiver(&req_protocol_names);
let (collation_req_vstaging_receiver, req_vstaging_cfg) = let (collation_req_v2_receiver, req_v2_cfg) =
IncomingRequest::get_config_receiver(&req_protocol_names); IncomingRequest::get_config_receiver(&req_protocol_names);
let subsystem = async { let subsystem = async {
run_inner( run_inner(
@@ -244,7 +244,7 @@ fn test_harness<T: Future<Output = TestHarness>>(
local_peer_id, local_peer_id,
collator_pair, collator_pair,
collation_req_receiver, collation_req_receiver,
collation_req_vstaging_receiver, collation_req_v2_receiver,
Default::default(), Default::default(),
reputation, reputation,
REPUTATION_CHANGE_TEST_INTERVAL, REPUTATION_CHANGE_TEST_INTERVAL,
@@ -253,7 +253,7 @@ fn test_harness<T: Future<Output = TestHarness>>(
.unwrap(); .unwrap();
}; };
let test_fut = test(TestHarness { virtual_overseer, req_v1_cfg, req_vstaging_cfg }); let test_fut = test(TestHarness { virtual_overseer, req_v1_cfg, req_v2_cfg });
futures::pin_mut!(test_fut); futures::pin_mut!(test_fut);
futures::pin_mut!(subsystem); futures::pin_mut!(subsystem);
@@ -330,7 +330,7 @@ async fn setup_system(virtual_overseer: &mut VirtualOverseer, test_state: &TestS
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
relay_parent, relay_parent,
RuntimeApiRequest::StagingAsyncBackingParams(tx) RuntimeApiRequest::AsyncBackingParams(tx)
)) => { )) => {
assert_eq!(relay_parent, test_state.relay_parent); assert_eq!(relay_parent, test_state.relay_parent);
tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap();
@@ -545,7 +545,7 @@ async fn expect_declare_msg(
/// Check that the next received message is a collation advertisement message. /// Check that the next received message is a collation advertisement message.
/// ///
/// Expects vstaging message if `expected_candidate_hashes` is `Some`, v1 otherwise. /// Expects v2 message if `expected_candidate_hashes` is `Some`, v1 otherwise.
async fn expect_advertise_collation_msg( async fn expect_advertise_collation_msg(
virtual_overseer: &mut VirtualOverseer, virtual_overseer: &mut VirtualOverseer,
peer: &PeerId, peer: &PeerId,
@@ -579,13 +579,13 @@ async fn expect_advertise_collation_msg(
}, },
( (
Some(candidate_hashes), Some(candidate_hashes),
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(
wire_message, wire_message,
)), )),
) => { ) => {
assert_matches!( assert_matches!(
wire_message, wire_message,
protocol_vstaging::CollatorProtocolMessage::AdvertiseCollation { protocol_v2::CollatorProtocolMessage::AdvertiseCollation {
relay_parent, relay_parent,
candidate_hash, candidate_hash,
.. ..
@@ -634,7 +634,7 @@ fn advertise_and_send_collation() {
|test_harness| async move { |test_harness| async move {
let mut virtual_overseer = test_harness.virtual_overseer; let mut virtual_overseer = test_harness.virtual_overseer;
let mut req_v1_cfg = test_harness.req_v1_cfg; let mut req_v1_cfg = test_harness.req_v1_cfg;
let req_vstaging_cfg = test_harness.req_vstaging_cfg; let req_v2_cfg = test_harness.req_v2_cfg;
setup_system(&mut virtual_overseer, &test_state).await; setup_system(&mut virtual_overseer, &test_state).await;
@@ -789,7 +789,7 @@ fn advertise_and_send_collation() {
None, None,
) )
.await; .await;
TestHarness { virtual_overseer, req_v1_cfg, req_vstaging_cfg } TestHarness { virtual_overseer, req_v1_cfg, req_v2_cfg }
}, },
); );
} }
@@ -807,7 +807,7 @@ fn delay_reputation_change() {
|test_harness| async move { |test_harness| async move {
let mut virtual_overseer = test_harness.virtual_overseer; let mut virtual_overseer = test_harness.virtual_overseer;
let mut req_v1_cfg = test_harness.req_v1_cfg; let mut req_v1_cfg = test_harness.req_v1_cfg;
let req_vstaging_cfg = test_harness.req_vstaging_cfg; let req_v2_cfg = test_harness.req_v2_cfg;
setup_system(&mut virtual_overseer, &test_state).await; setup_system(&mut virtual_overseer, &test_state).await;
@@ -903,15 +903,15 @@ fn delay_reputation_change() {
); );
} }
TestHarness { virtual_overseer, req_v1_cfg, req_vstaging_cfg } TestHarness { virtual_overseer, req_v1_cfg, req_v2_cfg }
}, },
); );
} }
/// Tests that collator side works with vstaging network protocol /// Tests that collator side works with v2 network protocol
/// before async backing is enabled. /// before async backing is enabled.
#[test] #[test]
fn advertise_collation_vstaging_protocol() { fn advertise_collation_v2_protocol() {
let test_state = TestState::default(); let test_state = TestState::default();
let local_peer_id = test_state.local_peer_id; let local_peer_id = test_state.local_peer_id;
let collator_pair = test_state.collator_pair.clone(); let collator_pair = test_state.collator_pair.clone();
@@ -941,21 +941,16 @@ fn advertise_collation_vstaging_protocol() {
Some(validators[0].clone()), Some(validators[0].clone()),
) )
.await; .await;
// The rest with vstaging. // The rest with v2.
for (val, peer) in validators.iter().zip(peer_ids.iter()).skip(1) { for (val, peer) in validators.iter().zip(peer_ids.iter()).skip(1) {
connect_peer( connect_peer(virtual_overseer, *peer, CollationVersion::V2, Some(val.clone()))
virtual_overseer, .await;
*peer,
CollationVersion::VStaging,
Some(val.clone()),
)
.await;
} }
// Declare messages. // Declare messages.
expect_declare_msg(virtual_overseer, &test_state, &peer_ids[0]).await; expect_declare_msg(virtual_overseer, &test_state, &peer_ids[0]).await;
for peer_id in peer_ids.iter().skip(1) { for peer_id in peer_ids.iter().skip(1) {
prospective_parachains::expect_declare_msg_vstaging( prospective_parachains::expect_declare_msg_v2(
virtual_overseer, virtual_overseer,
&test_state, &test_state,
&peer_id, &peer_id,
@@ -981,7 +976,7 @@ fn advertise_collation_vstaging_protocol() {
virtual_overseer, virtual_overseer,
peer_id, peer_id,
test_state.relay_parent, test_state.relay_parent,
Some(vec![candidate.hash()]), // This is `Some`, advertisement is vstaging. Some(vec![candidate.hash()]), // This is `Some`, advertisement is v2.
) )
.await; .await;
} }
@@ -1405,7 +1400,7 @@ fn connect_to_buffered_groups() {
|test_harness| async move { |test_harness| async move {
let mut virtual_overseer = test_harness.virtual_overseer; let mut virtual_overseer = test_harness.virtual_overseer;
let mut req_cfg = test_harness.req_v1_cfg; let mut req_cfg = test_harness.req_v1_cfg;
let req_vstaging_cfg = test_harness.req_vstaging_cfg; let req_v2_cfg = test_harness.req_v2_cfg;
setup_system(&mut virtual_overseer, &test_state).await; setup_system(&mut virtual_overseer, &test_state).await;
@@ -1510,7 +1505,7 @@ fn connect_to_buffered_groups() {
} }
); );
TestHarness { virtual_overseer, req_v1_cfg: req_cfg, req_vstaging_cfg } TestHarness { virtual_overseer, req_v1_cfg: req_cfg, req_v2_cfg }
}, },
); );
} }
@@ -19,10 +19,10 @@
use super::*; use super::*;
use polkadot_node_subsystem::messages::{ChainApiMessage, ProspectiveParachainsMessage}; use polkadot_node_subsystem::messages::{ChainApiMessage, ProspectiveParachainsMessage};
use polkadot_primitives::{vstaging as vstaging_primitives, Header, OccupiedCore}; use polkadot_primitives::{AsyncBackingParams, Header, OccupiedCore};
const ASYNC_BACKING_PARAMETERS: vstaging_primitives::AsyncBackingParams = const ASYNC_BACKING_PARAMETERS: AsyncBackingParams =
vstaging_primitives::AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 }; AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 };
fn get_parent_hash(hash: Hash) -> Hash { fn get_parent_hash(hash: Hash) -> Hash {
Hash::from_low_u64_be(hash.to_low_u64_be() + 1) Hash::from_low_u64_be(hash.to_low_u64_be() + 1)
@@ -52,7 +52,7 @@ async fn update_view(
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
parent, parent,
RuntimeApiRequest::StagingAsyncBackingParams(tx), RuntimeApiRequest::AsyncBackingParams(tx),
)) => { )) => {
tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap(); tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap();
(parent, new_view.get(&parent).copied().expect("Unknown parent requested")) (parent, new_view.get(&parent).copied().expect("Unknown parent requested"))
@@ -124,7 +124,7 @@ async fn update_view(
} }
/// Check that the next received message is a `Declare` message. /// Check that the next received message is a `Declare` message.
pub(super) async fn expect_declare_msg_vstaging( pub(super) async fn expect_declare_msg_v2(
virtual_overseer: &mut VirtualOverseer, virtual_overseer: &mut VirtualOverseer,
test_state: &TestState, test_state: &TestState,
peer: &PeerId, peer: &PeerId,
@@ -133,20 +133,20 @@ pub(super) async fn expect_declare_msg_vstaging(
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendCollationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendCollationMessage(
to, to,
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(
wire_message, wire_message,
)), )),
)) => { )) => {
assert_eq!(to[0], *peer); assert_eq!(to[0], *peer);
assert_matches!( assert_matches!(
wire_message, wire_message,
protocol_vstaging::CollatorProtocolMessage::Declare( protocol_v2::CollatorProtocolMessage::Declare(
collator_id, collator_id,
para_id, para_id,
signature, signature,
) => { ) => {
assert!(signature.verify( assert!(signature.verify(
&*protocol_vstaging::declare_signature_payload(&test_state.local_peer_id), &*protocol_v2::declare_signature_payload(&test_state.local_peer_id),
&collator_id), &collator_id),
); );
assert_eq!(collator_id, test_state.collator_pair.public()); assert_eq!(collator_id, test_state.collator_pair.public());
@@ -203,13 +203,12 @@ fn distribute_collation_from_implicit_view() {
.into_iter() .into_iter()
.zip(validator_peer_ids.clone()) .zip(validator_peer_ids.clone())
{ {
connect_peer(virtual_overseer, peer, CollationVersion::VStaging, Some(val.clone())) connect_peer(virtual_overseer, peer, CollationVersion::V2, Some(val.clone())).await;
.await;
} }
// Collator declared itself to each peer. // Collator declared itself to each peer.
for peer_id in &validator_peer_ids { for peer_id in &validator_peer_ids {
expect_declare_msg_vstaging(virtual_overseer, &test_state, peer_id).await; expect_declare_msg_v2(virtual_overseer, &test_state, peer_id).await;
} }
let pov = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pov = PoV { block_data: BlockData(vec![1, 2, 3]) };
@@ -386,7 +385,7 @@ fn advertise_and_send_collation_by_hash() {
|test_harness| async move { |test_harness| async move {
let mut virtual_overseer = test_harness.virtual_overseer; let mut virtual_overseer = test_harness.virtual_overseer;
let req_v1_cfg = test_harness.req_v1_cfg; let req_v1_cfg = test_harness.req_v1_cfg;
let mut req_vstaging_cfg = test_harness.req_vstaging_cfg; let mut req_v2_cfg = test_harness.req_v2_cfg;
let head_a = Hash::from_low_u64_be(128); let head_a = Hash::from_low_u64_be(128);
let head_a_num: u32 = 64; let head_a_num: u32 = 64;
@@ -435,11 +434,11 @@ fn advertise_and_send_collation_by_hash() {
connect_peer( connect_peer(
&mut virtual_overseer, &mut virtual_overseer,
peer, peer,
CollationVersion::VStaging, CollationVersion::V2,
Some(validator_id.clone()), Some(validator_id.clone()),
) )
.await; .await;
expect_declare_msg_vstaging(&mut virtual_overseer, &test_state, &peer).await; expect_declare_msg_v2(&mut virtual_overseer, &test_state, &peer).await;
// Head `b` is not a leaf, but both advertisements are still relevant. // Head `b` is not a leaf, but both advertisements are still relevant.
send_peer_view_change(&mut virtual_overseer, &peer, vec![head_b]).await; send_peer_view_change(&mut virtual_overseer, &peer, vec![head_b]).await;
@@ -449,13 +448,13 @@ fn advertise_and_send_collation_by_hash() {
for (candidate, pov_block) in candidates { for (candidate, pov_block) in candidates {
let (pending_response, rx) = oneshot::channel(); let (pending_response, rx) = oneshot::channel();
req_vstaging_cfg req_v2_cfg
.inbound_queue .inbound_queue
.as_mut() .as_mut()
.unwrap() .unwrap()
.send(RawIncomingRequest { .send(RawIncomingRequest {
peer, peer,
payload: request_vstaging::CollationFetchingRequest { payload: request_v2::CollationFetchingRequest {
relay_parent: head_b, relay_parent: head_b,
para_id: test_state.para_id, para_id: test_state.para_id,
candidate_hash: candidate.hash(), candidate_hash: candidate.hash(),
@@ -469,7 +468,7 @@ fn advertise_and_send_collation_by_hash() {
assert_matches!( assert_matches!(
rx.await, rx.await,
Ok(full_response) => { Ok(full_response) => {
// Response is the same for vstaging. // Response is the same for v2.
let request_v1::CollationFetchingResponse::Collation(receipt, pov): request_v1::CollationFetchingResponse let request_v1::CollationFetchingResponse::Collation(receipt, pov): request_v1::CollationFetchingResponse
= request_v1::CollationFetchingResponse::decode( = request_v1::CollationFetchingResponse::decode(
&mut full_response.result &mut full_response.result
@@ -482,7 +481,7 @@ fn advertise_and_send_collation_by_hash() {
); );
} }
TestHarness { virtual_overseer, req_v1_cfg, req_vstaging_cfg } TestHarness { virtual_overseer, req_v1_cfg, req_v2_cfg }
}, },
) )
} }
@@ -552,11 +551,11 @@ fn advertise_core_occupied() {
connect_peer( connect_peer(
virtual_overseer, virtual_overseer,
peer_ids[0], peer_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
Some(validators[0].clone()), Some(validators[0].clone()),
) )
.await; .await;
expect_declare_msg_vstaging(virtual_overseer, &test_state, &peer_ids[0]).await; expect_declare_msg_v2(virtual_overseer, &test_state, &peer_ids[0]).await;
// Peer is aware of the leaf. // Peer is aware of the leaf.
send_peer_view_change(virtual_overseer, &peer_ids[0], vec![head_a]).await; send_peer_view_change(virtual_overseer, &peer_ids[0], vec![head_a]).await;
@@ -32,7 +32,7 @@ use polkadot_node_subsystem_util::reputation::ReputationAggregator;
use sp_keystore::KeystorePtr; use sp_keystore::KeystorePtr;
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
request_response::{v1 as request_v1, vstaging as protocol_vstaging, IncomingRequestReceiver}, request_response::{v1 as request_v1, v2 as protocol_v2, IncomingRequestReceiver},
PeerId, UnifiedReputationChange as Rep, PeerId, UnifiedReputationChange as Rep,
}; };
use polkadot_primitives::CollatorPair; use polkadot_primitives::CollatorPair;
@@ -83,9 +83,8 @@ pub enum ProtocolSide {
collator_pair: CollatorPair, collator_pair: CollatorPair,
/// Receiver for v1 collation fetching requests. /// Receiver for v1 collation fetching requests.
request_receiver_v1: IncomingRequestReceiver<request_v1::CollationFetchingRequest>, request_receiver_v1: IncomingRequestReceiver<request_v1::CollationFetchingRequest>,
/// Receiver for vstaging collation fetching requests. /// Receiver for v2 collation fetching requests.
request_receiver_vstaging: request_receiver_v2: IncomingRequestReceiver<protocol_v2::CollationFetchingRequest>,
IncomingRequestReceiver<protocol_vstaging::CollationFetchingRequest>,
/// Metrics. /// Metrics.
metrics: collator_side::Metrics, metrics: collator_side::Metrics,
}, },
@@ -121,14 +120,14 @@ impl<Context> CollatorProtocolSubsystem {
peer_id, peer_id,
collator_pair, collator_pair,
request_receiver_v1, request_receiver_v1,
request_receiver_vstaging, request_receiver_v2,
metrics, metrics,
} => collator_side::run( } => collator_side::run(
ctx, ctx,
peer_id, peer_id,
collator_pair, collator_pair,
request_receiver_v1, request_receiver_v1,
request_receiver_vstaging, request_receiver_v2,
metrics, metrics,
) )
.map_err(|e| SubsystemError::with_origin("collator-protocol", e)) .map_err(|e| SubsystemError::with_origin("collator-protocol", e))
@@ -119,7 +119,7 @@ impl PendingCollation {
} }
} }
/// vstaging advertisement that was rejected by the backing /// v2 advertisement that was rejected by the backing
/// subsystem. Validator may fetch it later if its fragment /// subsystem. Validator may fetch it later if its fragment
/// membership gets recognized before relay parent goes out of view. /// membership gets recognized before relay parent goes out of view.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -34,10 +34,10 @@ use polkadot_node_network_protocol::{
peer_set::{CollationVersion, PeerSet}, peer_set::{CollationVersion, PeerSet},
request_response::{ request_response::{
outgoing::{Recipient, RequestError}, outgoing::{Recipient, RequestError},
v1 as request_v1, vstaging as request_vstaging, OutgoingRequest, Requests, v1 as request_v1, v2 as request_v2, OutgoingRequest, Requests,
}, },
v1 as protocol_v1, vstaging as protocol_vstaging, OurView, PeerId, v1 as protocol_v1, v2 as protocol_v2, OurView, PeerId, UnifiedReputationChange as Rep,
UnifiedReputationChange as Rep, Versioned, View, Versioned, View,
}; };
use polkadot_node_primitives::{SignedFullStatement, Statement}; use polkadot_node_primitives::{SignedFullStatement, Statement};
use polkadot_node_subsystem::{ use polkadot_node_subsystem::{
@@ -624,13 +624,9 @@ async fn notify_collation_seconded(
CollationVersion::V1 => Versioned::V1(protocol_v1::CollationProtocol::CollatorProtocol( CollationVersion::V1 => Versioned::V1(protocol_v1::CollationProtocol::CollatorProtocol(
protocol_v1::CollatorProtocolMessage::CollationSeconded(relay_parent, statement), protocol_v1::CollatorProtocolMessage::CollationSeconded(relay_parent, statement),
)), )),
CollationVersion::VStaging => CollationVersion::V2 => Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( protocol_v2::CollatorProtocolMessage::CollationSeconded(relay_parent, statement),
protocol_vstaging::CollatorProtocolMessage::CollationSeconded( )),
relay_parent,
statement,
),
)),
}; };
sender sender
.send_message(NetworkBridgeTxMessage::SendCollationMessage(vec![peer_id], wire_message)) .send_message(NetworkBridgeTxMessage::SendCollationMessage(vec![peer_id], wire_message))
@@ -694,16 +690,12 @@ async fn request_collation(
let requests = Requests::CollationFetchingV1(req); let requests = Requests::CollationFetchingV1(req);
(requests, response_recv.boxed()) (requests, response_recv.boxed())
}, },
(CollationVersion::VStaging, Some(ProspectiveCandidate { candidate_hash, .. })) => { (CollationVersion::V2, Some(ProspectiveCandidate { candidate_hash, .. })) => {
let (req, response_recv) = OutgoingRequest::new( let (req, response_recv) = OutgoingRequest::new(
Recipient::Peer(peer_id), Recipient::Peer(peer_id),
request_vstaging::CollationFetchingRequest { request_v2::CollationFetchingRequest { relay_parent, para_id, candidate_hash },
relay_parent,
para_id,
candidate_hash,
},
); );
let requests = Requests::CollationFetchingVStaging(req); let requests = Requests::CollationFetchingV2(req);
(requests, response_recv.boxed()) (requests, response_recv.boxed())
}, },
_ => return Err(FetchError::ProtocolMismatch), _ => return Err(FetchError::ProtocolMismatch),
@@ -758,18 +750,15 @@ async fn process_incoming_peer_message<Context>(
ctx: &mut Context, ctx: &mut Context,
state: &mut State, state: &mut State,
origin: PeerId, origin: PeerId,
msg: Versioned< msg: Versioned<protocol_v1::CollatorProtocolMessage, protocol_v2::CollatorProtocolMessage>,
protocol_v1::CollatorProtocolMessage,
protocol_vstaging::CollatorProtocolMessage,
>,
) { ) {
use protocol_v1::CollatorProtocolMessage as V1; use protocol_v1::CollatorProtocolMessage as V1;
use protocol_vstaging::CollatorProtocolMessage as VStaging; use protocol_v2::CollatorProtocolMessage as V2;
use sp_runtime::traits::AppVerify; use sp_runtime::traits::AppVerify;
match msg { match msg {
Versioned::V1(V1::Declare(collator_id, para_id, signature)) | Versioned::V1(V1::Declare(collator_id, para_id, signature)) |
Versioned::VStaging(VStaging::Declare(collator_id, para_id, signature)) => { Versioned::V2(V2::Declare(collator_id, para_id, signature)) => {
if collator_peer_id(&state.peer_data, &collator_id).is_some() { if collator_peer_id(&state.peer_data, &collator_id).is_some() {
modify_reputation( modify_reputation(
&mut state.reputation, &mut state.reputation,
@@ -881,7 +870,7 @@ async fn process_incoming_peer_message<Context>(
modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await; modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await;
} }
}, },
Versioned::VStaging(VStaging::AdvertiseCollation { Versioned::V2(V2::AdvertiseCollation {
relay_parent, relay_parent,
candidate_hash, candidate_hash,
parent_head_data_hash, parent_head_data_hash,
@@ -901,15 +890,14 @@ async fn process_incoming_peer_message<Context>(
?relay_parent, ?relay_parent,
?candidate_hash, ?candidate_hash,
error = ?err, error = ?err,
"Rejected vstaging advertisement", "Rejected v2 advertisement",
); );
if let Some(rep) = err.reputation_changes() { if let Some(rep) = err.reputation_changes() {
modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await; modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await;
} }
}, },
Versioned::V1(V1::CollationSeconded(..)) | Versioned::V1(V1::CollationSeconded(..)) | Versioned::V2(V2::CollationSeconded(..)) => {
Versioned::VStaging(VStaging::CollationSeconded(..)) => {
gum::warn!( gum::warn!(
target: LOG_TARGET, target: LOG_TARGET,
peer_id = ?origin, peer_id = ?origin,
@@ -1074,7 +1062,7 @@ where
}; };
if relay_parent_mode.is_enabled() && prospective_candidate.is_none() { if relay_parent_mode.is_enabled() && prospective_candidate.is_none() {
// Expected vstaging advertisement. // Expected v2 advertisement.
return Err(AdvertisementError::ProtocolMismatch) return Err(AdvertisementError::ProtocolMismatch)
} }
@@ -357,7 +357,7 @@ async fn assert_fetch_collation_request(
), ),
Some(candidate_hash) => assert_matches!( Some(candidate_hash) => assert_matches!(
req, req,
Requests::CollationFetchingVStaging(req) => { Requests::CollationFetchingV2(req) => {
let payload = req.payload; let payload = req.payload;
assert_eq!(payload.relay_parent, relay_parent); assert_eq!(payload.relay_parent, relay_parent);
assert_eq!(payload.para_id, para_id); assert_eq!(payload.para_id, para_id);
@@ -394,12 +394,11 @@ async fn connect_and_declare_collator(
para_id, para_id,
collator.sign(&protocol_v1::declare_signature_payload(&peer)), collator.sign(&protocol_v1::declare_signature_payload(&peer)),
)), )),
CollationVersion::VStaging => CollationVersion::V2 => Versioned::V2(protocol_v2::CollatorProtocolMessage::Declare(
Versioned::VStaging(protocol_vstaging::CollatorProtocolMessage::Declare( collator.public(),
collator.public(), para_id,
para_id, collator.sign(&protocol_v1::declare_signature_payload(&peer)),
collator.sign(&protocol_v1::declare_signature_payload(&peer)), )),
)),
}; };
overseer_send( overseer_send(
@@ -421,7 +420,7 @@ async fn advertise_collation(
) { ) {
let wire_message = match candidate { let wire_message = match candidate {
Some((candidate_hash, parent_head_data_hash)) => Some((candidate_hash, parent_head_data_hash)) =>
Versioned::VStaging(protocol_vstaging::CollatorProtocolMessage::AdvertiseCollation { Versioned::V2(protocol_v2::CollatorProtocolMessage::AdvertiseCollation {
relay_parent, relay_parent,
candidate_hash, candidate_hash,
parent_head_data_hash, parent_head_data_hash,
@@ -444,7 +443,7 @@ async fn assert_async_backing_params_request(virtual_overseer: &mut VirtualOvers
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
relay_parent, relay_parent,
RuntimeApiRequest::StagingAsyncBackingParams(tx) RuntimeApiRequest::AsyncBackingParams(tx)
)) => { )) => {
assert_eq!(relay_parent, hash); assert_eq!(relay_parent, hash);
tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap();
@@ -499,10 +498,10 @@ fn act_on_advertisement() {
}); });
} }
/// Tests that validator side works with vstaging network protocol /// Tests that validator side works with v2 network protocol
/// before async backing is enabled. /// before async backing is enabled.
#[test] #[test]
fn act_on_advertisement_vstaging() { fn act_on_advertisement_v2() {
let test_state = TestState::default(); let test_state = TestState::default();
test_harness(ReputationAggregator::new(|_| true), |test_harness| async move { test_harness(ReputationAggregator::new(|_| true), |test_harness| async move {
@@ -529,13 +528,13 @@ fn act_on_advertisement_vstaging() {
peer_b, peer_b,
pair.clone(), pair.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
let candidate_hash = CandidateHash::default(); let candidate_hash = CandidateHash::default();
let parent_head_data_hash = Hash::zero(); let parent_head_data_hash = Hash::zero();
// vstaging advertisement. // v2 advertisement.
advertise_collation( advertise_collation(
&mut virtual_overseer, &mut virtual_overseer,
peer_b, peer_b,
@@ -20,12 +20,12 @@ use super::*;
use polkadot_node_subsystem::messages::ChainApiMessage; use polkadot_node_subsystem::messages::ChainApiMessage;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging as vstaging_primitives, BlockNumber, CandidateCommitments, CommittedCandidateReceipt, AsyncBackingParams, BlockNumber, CandidateCommitments, CommittedCandidateReceipt, Header,
Header, SigningContext, ValidatorId, SigningContext, ValidatorId,
}; };
const ASYNC_BACKING_PARAMETERS: vstaging_primitives::AsyncBackingParams = const ASYNC_BACKING_PARAMETERS: AsyncBackingParams =
vstaging_primitives::AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 }; AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 };
fn get_parent_hash(hash: Hash) -> Hash { fn get_parent_hash(hash: Hash) -> Hash {
Hash::from_low_u64_be(hash.to_low_u64_be() + 1) Hash::from_low_u64_be(hash.to_low_u64_be() + 1)
@@ -97,7 +97,7 @@ async fn update_view(
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request( AllMessages::RuntimeApi(RuntimeApiMessage::Request(
parent, parent,
RuntimeApiRequest::StagingAsyncBackingParams(tx), RuntimeApiRequest::AsyncBackingParams(tx),
)) => { )) => {
tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap(); tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap();
(parent, new_view.get(&parent).copied().expect("Unknown parent requested")) (parent, new_view.get(&parent).copied().expect("Unknown parent requested"))
@@ -226,8 +226,8 @@ async fn assert_collation_seconded(
overseer_recv(virtual_overseer).await, overseer_recv(virtual_overseer).await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendCollationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendCollationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::CollationProtocol::CollatorProtocol( Versioned::V2(protocol_v2::CollationProtocol::CollatorProtocol(
protocol_vstaging::CollatorProtocolMessage::CollationSeconded( protocol_v2::CollatorProtocolMessage::CollationSeconded(
_relay_parent, _relay_parent,
.., ..,
), ),
@@ -306,7 +306,7 @@ fn accept_advertisements_from_implicit_view() {
peer_a, peer_a,
pair_a.clone(), pair_a.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
connect_and_declare_collator( connect_and_declare_collator(
@@ -314,7 +314,7 @@ fn accept_advertisements_from_implicit_view() {
peer_b, peer_b,
pair_b.clone(), pair_b.clone(),
test_state.chain_ids[1], test_state.chain_ids[1],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -406,7 +406,7 @@ fn second_multiple_candidates_per_relay_parent() {
peer_a, peer_a,
pair.clone(), pair.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -457,7 +457,7 @@ fn second_multiple_candidates_per_relay_parent() {
let pov = PoV { block_data: BlockData(vec![1]) }; let pov = PoV { block_data: BlockData(vec![1]) };
response_channel response_channel
.send(Ok(request_vstaging::CollationFetchingResponse::Collation( .send(Ok(request_v2::CollationFetchingResponse::Collation(
candidate.clone(), candidate.clone(),
pov.clone(), pov.clone(),
) )
@@ -514,7 +514,7 @@ fn second_multiple_candidates_per_relay_parent() {
peer_b, peer_b,
pair_b.clone(), pair_b.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -562,7 +562,7 @@ fn fetched_collation_sanity_check() {
peer_a, peer_a,
pair.clone(), pair.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -611,7 +611,7 @@ fn fetched_collation_sanity_check() {
let pov = PoV { block_data: BlockData(vec![1]) }; let pov = PoV { block_data: BlockData(vec![1]) };
response_channel response_channel
.send(Ok(request_vstaging::CollationFetchingResponse::Collation( .send(Ok(request_v2::CollationFetchingResponse::Collation(
candidate.clone(), candidate.clone(),
pov.clone(), pov.clone(),
) )
@@ -668,7 +668,7 @@ fn advertisement_spam_protection() {
peer_a, peer_a,
pair_a.clone(), pair_a.clone(),
test_state.chain_ids[1], test_state.chain_ids[1],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -748,7 +748,7 @@ fn backed_candidate_unblocks_advertisements() {
peer_a, peer_a,
pair_a.clone(), pair_a.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
connect_and_declare_collator( connect_and_declare_collator(
@@ -756,7 +756,7 @@ fn backed_candidate_unblocks_advertisements() {
peer_b, peer_b,
pair_b.clone(), pair_b.clone(),
test_state.chain_ids[1], test_state.chain_ids[1],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
@@ -856,7 +856,7 @@ fn active_leave_unblocks_advertisements() {
*peer_id, *peer_id,
peer.clone(), peer.clone(),
test_state.chain_ids[0], test_state.chain_ids[0],
CollationVersion::VStaging, CollationVersion::V2,
) )
.await; .await;
} }
@@ -452,7 +452,7 @@ where
// match void -> LLVM unreachable // match void -> LLVM unreachable
match message { match message {
Versioned::V1(m) => match m {}, Versioned::V1(m) => match m {},
Versioned::VStaging(m) => match m {}, Versioned::V2(m) => match m {},
} }
}, },
} }
@@ -27,6 +27,3 @@ bitvec = "1"
[dev-dependencies] [dev-dependencies]
rand_chacha = "0.3.1" rand_chacha = "0.3.1"
[features]
network-protocol-staging = []
+30 -32
View File
@@ -253,26 +253,25 @@ impl View {
/// A protocol-versioned type. /// A protocol-versioned type.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Versioned<V1, VStaging> { pub enum Versioned<V1, V2> {
/// V1 type. /// V1 type.
V1(V1), V1(V1),
/// VStaging type. /// V2 type.
VStaging(VStaging), V2(V2),
} }
impl<V1: Clone, VStaging: Clone> Versioned<&'_ V1, &'_ VStaging> { impl<V1: Clone, V2: Clone> Versioned<&'_ V1, &'_ V2> {
/// Convert to a fully-owned version of the message. /// Convert to a fully-owned version of the message.
pub fn clone_inner(&self) -> Versioned<V1, VStaging> { pub fn clone_inner(&self) -> Versioned<V1, V2> {
match *self { match *self {
Versioned::V1(inner) => Versioned::V1(inner.clone()), Versioned::V1(inner) => Versioned::V1(inner.clone()),
Versioned::VStaging(inner) => Versioned::VStaging(inner.clone()), Versioned::V2(inner) => Versioned::V2(inner.clone()),
} }
} }
} }
/// All supported versions of the validation protocol message. /// All supported versions of the validation protocol message.
pub type VersionedValidationProtocol = pub type VersionedValidationProtocol = Versioned<v1::ValidationProtocol, v2::ValidationProtocol>;
Versioned<v1::ValidationProtocol, vstaging::ValidationProtocol>;
impl From<v1::ValidationProtocol> for VersionedValidationProtocol { impl From<v1::ValidationProtocol> for VersionedValidationProtocol {
fn from(v1: v1::ValidationProtocol) -> Self { fn from(v1: v1::ValidationProtocol) -> Self {
@@ -280,14 +279,14 @@ impl From<v1::ValidationProtocol> for VersionedValidationProtocol {
} }
} }
impl From<vstaging::ValidationProtocol> for VersionedValidationProtocol { impl From<v2::ValidationProtocol> for VersionedValidationProtocol {
fn from(vstaging: vstaging::ValidationProtocol) -> Self { fn from(v2: v2::ValidationProtocol) -> Self {
VersionedValidationProtocol::VStaging(vstaging) VersionedValidationProtocol::V2(v2)
} }
} }
/// All supported versions of the collation protocol message. /// All supported versions of the collation protocol message.
pub type VersionedCollationProtocol = Versioned<v1::CollationProtocol, vstaging::CollationProtocol>; pub type VersionedCollationProtocol = Versioned<v1::CollationProtocol, v2::CollationProtocol>;
impl From<v1::CollationProtocol> for VersionedCollationProtocol { impl From<v1::CollationProtocol> for VersionedCollationProtocol {
fn from(v1: v1::CollationProtocol) -> Self { fn from(v1: v1::CollationProtocol) -> Self {
@@ -295,9 +294,9 @@ impl From<v1::CollationProtocol> for VersionedCollationProtocol {
} }
} }
impl From<vstaging::CollationProtocol> for VersionedCollationProtocol { impl From<v2::CollationProtocol> for VersionedCollationProtocol {
fn from(vstaging: vstaging::CollationProtocol) -> Self { fn from(v2: v2::CollationProtocol) -> Self {
VersionedCollationProtocol::VStaging(vstaging) VersionedCollationProtocol::V2(v2)
} }
} }
@@ -307,7 +306,7 @@ macro_rules! impl_versioned_full_protocol_from {
fn from(versioned_from: $from) -> $out { fn from(versioned_from: $from) -> $out {
match versioned_from { match versioned_from {
Versioned::V1(x) => Versioned::V1(x.into()), Versioned::V1(x) => Versioned::V1(x.into()),
Versioned::VStaging(x) => Versioned::VStaging(x.into()), Versioned::V2(x) => Versioned::V2(x.into()),
} }
} }
} }
@@ -321,7 +320,7 @@ macro_rules! impl_versioned_try_from {
$from:ty, $from:ty,
$out:ty, $out:ty,
$v1_pat:pat => $v1_out:expr, $v1_pat:pat => $v1_out:expr,
$vstaging_pat:pat => $vstaging_out:expr $v2_pat:pat => $v2_out:expr
) => { ) => {
impl TryFrom<$from> for $out { impl TryFrom<$from> for $out {
type Error = crate::WrongVariant; type Error = crate::WrongVariant;
@@ -330,7 +329,7 @@ macro_rules! impl_versioned_try_from {
#[allow(unreachable_patterns)] // when there is only one variant #[allow(unreachable_patterns)] // when there is only one variant
match x { match x {
Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out)), Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out)),
Versioned::VStaging($vstaging_pat) => Ok(Versioned::VStaging($vstaging_out)), Versioned::V2($v2_pat) => Ok(Versioned::V2($v2_out)),
_ => Err(crate::WrongVariant), _ => Err(crate::WrongVariant),
} }
} }
@@ -343,8 +342,7 @@ macro_rules! impl_versioned_try_from {
#[allow(unreachable_patterns)] // when there is only one variant #[allow(unreachable_patterns)] // when there is only one variant
match x { match x {
Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out.clone())), Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out.clone())),
Versioned::VStaging($vstaging_pat) => Versioned::V2($v2_pat) => Ok(Versioned::V2($v2_out.clone())),
Ok(Versioned::VStaging($vstaging_out.clone())),
_ => Err(crate::WrongVariant), _ => Err(crate::WrongVariant),
} }
} }
@@ -354,7 +352,7 @@ macro_rules! impl_versioned_try_from {
/// Version-annotated messages used by the bitfield distribution subsystem. /// Version-annotated messages used by the bitfield distribution subsystem.
pub type BitfieldDistributionMessage = pub type BitfieldDistributionMessage =
Versioned<v1::BitfieldDistributionMessage, vstaging::BitfieldDistributionMessage>; Versioned<v1::BitfieldDistributionMessage, v2::BitfieldDistributionMessage>;
impl_versioned_full_protocol_from!( impl_versioned_full_protocol_from!(
BitfieldDistributionMessage, BitfieldDistributionMessage,
VersionedValidationProtocol, VersionedValidationProtocol,
@@ -364,12 +362,12 @@ impl_versioned_try_from!(
VersionedValidationProtocol, VersionedValidationProtocol,
BitfieldDistributionMessage, BitfieldDistributionMessage,
v1::ValidationProtocol::BitfieldDistribution(x) => x, v1::ValidationProtocol::BitfieldDistribution(x) => x,
vstaging::ValidationProtocol::BitfieldDistribution(x) => x v2::ValidationProtocol::BitfieldDistribution(x) => x
); );
/// Version-annotated messages used by the statement distribution subsystem. /// Version-annotated messages used by the statement distribution subsystem.
pub type StatementDistributionMessage = pub type StatementDistributionMessage =
Versioned<v1::StatementDistributionMessage, vstaging::StatementDistributionMessage>; Versioned<v1::StatementDistributionMessage, v2::StatementDistributionMessage>;
impl_versioned_full_protocol_from!( impl_versioned_full_protocol_from!(
StatementDistributionMessage, StatementDistributionMessage,
VersionedValidationProtocol, VersionedValidationProtocol,
@@ -379,12 +377,12 @@ impl_versioned_try_from!(
VersionedValidationProtocol, VersionedValidationProtocol,
StatementDistributionMessage, StatementDistributionMessage,
v1::ValidationProtocol::StatementDistribution(x) => x, v1::ValidationProtocol::StatementDistribution(x) => x,
vstaging::ValidationProtocol::StatementDistribution(x) => x v2::ValidationProtocol::StatementDistribution(x) => x
); );
/// Version-annotated messages used by the approval distribution subsystem. /// Version-annotated messages used by the approval distribution subsystem.
pub type ApprovalDistributionMessage = pub type ApprovalDistributionMessage =
Versioned<v1::ApprovalDistributionMessage, vstaging::ApprovalDistributionMessage>; Versioned<v1::ApprovalDistributionMessage, v2::ApprovalDistributionMessage>;
impl_versioned_full_protocol_from!( impl_versioned_full_protocol_from!(
ApprovalDistributionMessage, ApprovalDistributionMessage,
VersionedValidationProtocol, VersionedValidationProtocol,
@@ -394,13 +392,13 @@ impl_versioned_try_from!(
VersionedValidationProtocol, VersionedValidationProtocol,
ApprovalDistributionMessage, ApprovalDistributionMessage,
v1::ValidationProtocol::ApprovalDistribution(x) => x, v1::ValidationProtocol::ApprovalDistribution(x) => x,
vstaging::ValidationProtocol::ApprovalDistribution(x) => x v2::ValidationProtocol::ApprovalDistribution(x) => x
); );
/// Version-annotated messages used by the gossip-support subsystem (this is void). /// Version-annotated messages used by the gossip-support subsystem (this is void).
pub type GossipSupportNetworkMessage = pub type GossipSupportNetworkMessage =
Versioned<v1::GossipSupportNetworkMessage, vstaging::GossipSupportNetworkMessage>; Versioned<v1::GossipSupportNetworkMessage, v2::GossipSupportNetworkMessage>;
// This is a void enum placeholder, so never gets sent over the wire. // This is a void enum placeholder, so never gets sent over the wire.
impl TryFrom<VersionedValidationProtocol> for GossipSupportNetworkMessage { impl TryFrom<VersionedValidationProtocol> for GossipSupportNetworkMessage {
type Error = WrongVariant; type Error = WrongVariant;
@@ -418,7 +416,7 @@ impl<'a> TryFrom<&'a VersionedValidationProtocol> for GossipSupportNetworkMessag
/// Version-annotated messages used by the bitfield distribution subsystem. /// Version-annotated messages used by the bitfield distribution subsystem.
pub type CollatorProtocolMessage = pub type CollatorProtocolMessage =
Versioned<v1::CollatorProtocolMessage, vstaging::CollatorProtocolMessage>; Versioned<v1::CollatorProtocolMessage, v2::CollatorProtocolMessage>;
impl_versioned_full_protocol_from!( impl_versioned_full_protocol_from!(
CollatorProtocolMessage, CollatorProtocolMessage,
VersionedCollationProtocol, VersionedCollationProtocol,
@@ -428,7 +426,7 @@ impl_versioned_try_from!(
VersionedCollationProtocol, VersionedCollationProtocol,
CollatorProtocolMessage, CollatorProtocolMessage,
v1::CollationProtocol::CollatorProtocol(x) => x, v1::CollationProtocol::CollatorProtocol(x) => x,
vstaging::CollationProtocol::CollatorProtocol(x) => x v2::CollationProtocol::CollatorProtocol(x) => x
); );
/// v1 notification protocol types. /// v1 notification protocol types.
@@ -589,12 +587,12 @@ pub mod v1 {
} }
} }
/// vstaging network protocol types. /// v2 network protocol types.
pub mod vstaging { pub mod v2 {
use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec}; use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec};
use parity_scale_codec::{Decode, Encode}; use parity_scale_codec::{Decode, Encode};
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
CandidateHash, CandidateIndex, CollatorId, CollatorSignature, GroupIndex, Hash, CandidateHash, CandidateIndex, CollatorId, CollatorSignature, GroupIndex, Hash,
Id as ParaId, UncheckedSignedAvailabilityBitfield, UncheckedSignedStatement, Id as ParaId, UncheckedSignedAvailabilityBitfield, UncheckedSignedStatement,
}; };
+8 -15
View File
@@ -118,16 +118,9 @@ impl PeerSet {
/// Networking layer relies on `get_main_version()` being the version /// Networking layer relies on `get_main_version()` being the version
/// of the main protocol name reported by [`PeerSetProtocolNames::get_main_name()`]. /// of the main protocol name reported by [`PeerSetProtocolNames::get_main_name()`].
pub fn get_main_version(self) -> ProtocolVersion { pub fn get_main_version(self) -> ProtocolVersion {
#[cfg(not(feature = "network-protocol-staging"))]
match self { match self {
PeerSet::Validation => ValidationVersion::V1.into(), PeerSet::Validation => ValidationVersion::V2.into(),
PeerSet::Collation => CollationVersion::V1.into(), PeerSet::Collation => CollationVersion::V2.into(),
}
#[cfg(feature = "network-protocol-staging")]
match self {
PeerSet::Validation => ValidationVersion::VStaging.into(),
PeerSet::Collation => CollationVersion::VStaging.into(),
} }
} }
@@ -152,7 +145,7 @@ impl PeerSet {
PeerSet::Validation => PeerSet::Validation =>
if version == ValidationVersion::V1.into() { if version == ValidationVersion::V1.into() {
Some("validation/1") Some("validation/1")
} else if version == ValidationVersion::VStaging.into() { } else if version == ValidationVersion::V2.into() {
Some("validation/2") Some("validation/2")
} else { } else {
None None
@@ -160,7 +153,7 @@ impl PeerSet {
PeerSet::Collation => PeerSet::Collation =>
if version == CollationVersion::V1.into() { if version == CollationVersion::V1.into() {
Some("collation/1") Some("collation/1")
} else if version == CollationVersion::VStaging.into() { } else if version == CollationVersion::V2.into() {
Some("collation/2") Some("collation/2")
} else { } else {
None None
@@ -223,8 +216,8 @@ impl From<ProtocolVersion> for u32 {
pub enum ValidationVersion { pub enum ValidationVersion {
/// The first version. /// The first version.
V1 = 1, V1 = 1,
/// The staging version. /// The second version.
VStaging = 2, V2 = 2,
} }
/// Supported collation protocol versions. Only versions defined here must be used in the codebase. /// Supported collation protocol versions. Only versions defined here must be used in the codebase.
@@ -232,8 +225,8 @@ pub enum ValidationVersion {
pub enum CollationVersion { pub enum CollationVersion {
/// The first version. /// The first version.
V1 = 1, V1 = 1,
/// The staging version. /// The second version.
VStaging = 2, V2 = 2,
} }
/// Marker indicating the version is unknown. /// Marker indicating the version is unknown.
@@ -55,7 +55,7 @@ pub use outgoing::{OutgoingRequest, OutgoingResult, Recipient, Requests, Respons
pub mod v1; pub mod v1;
/// Actual versioned requests and responses that are sent over the wire. /// Actual versioned requests and responses that are sent over the wire.
pub mod vstaging; pub mod v2;
/// A protocol per subsystem seems to make the most sense, this way we don't need any dispatching /// A protocol per subsystem seems to make the most sense, this way we don't need any dispatching
/// within protocols. /// within protocols.
@@ -66,7 +66,7 @@ pub enum Protocol {
/// Protocol for fetching collations from collators. /// Protocol for fetching collations from collators.
CollationFetchingV1, CollationFetchingV1,
/// Protocol for fetching collations from collators when async backing is enabled. /// Protocol for fetching collations from collators when async backing is enabled.
CollationFetchingVStaging, CollationFetchingV2,
/// Protocol for fetching seconded PoVs from validators of the same group. /// Protocol for fetching seconded PoVs from validators of the same group.
PoVFetchingV1, PoVFetchingV1,
/// Protocol for fetching available data. /// Protocol for fetching available data.
@@ -78,7 +78,7 @@ pub enum Protocol {
/// Protocol for requesting candidates with attestations in statement distribution /// Protocol for requesting candidates with attestations in statement distribution
/// when async backing is enabled. /// when async backing is enabled.
AttestedCandidateVStaging, AttestedCandidateV2,
} }
/// Minimum bandwidth we expect for validators - 500Mbit/s is the recommendation, so approximately /// Minimum bandwidth we expect for validators - 500Mbit/s is the recommendation, so approximately
@@ -147,7 +147,7 @@ const POV_RESPONSE_SIZE: u64 = MAX_POV_SIZE as u64 + 10_000;
/// This is `MAX_CODE_SIZE` plus some additional space for protocol overhead. /// This is `MAX_CODE_SIZE` plus some additional space for protocol overhead.
const STATEMENT_RESPONSE_SIZE: u64 = MAX_CODE_SIZE as u64 + 10_000; const STATEMENT_RESPONSE_SIZE: u64 = MAX_CODE_SIZE as u64 + 10_000;
/// Maximum response sizes for `AttestedCandidateVStaging`. /// Maximum response sizes for `AttestedCandidateV2`.
/// ///
/// This is `MAX_CODE_SIZE` plus some additional space for protocol overhead and /// This is `MAX_CODE_SIZE` plus some additional space for protocol overhead and
/// additional backing statements. /// additional backing statements.
@@ -199,7 +199,7 @@ impl Protocol {
request_timeout: CHUNK_REQUEST_TIMEOUT, request_timeout: CHUNK_REQUEST_TIMEOUT,
inbound_queue: tx, inbound_queue: tx,
}, },
Protocol::CollationFetchingV1 | Protocol::CollationFetchingVStaging => Protocol::CollationFetchingV1 | Protocol::CollationFetchingV2 =>
RequestResponseConfig { RequestResponseConfig {
name, name,
fallback_names, fallback_names,
@@ -254,7 +254,7 @@ impl Protocol {
request_timeout: DISPUTE_REQUEST_TIMEOUT, request_timeout: DISPUTE_REQUEST_TIMEOUT,
inbound_queue: tx, inbound_queue: tx,
}, },
Protocol::AttestedCandidateVStaging => RequestResponseConfig { Protocol::AttestedCandidateV2 => RequestResponseConfig {
name, name,
fallback_names, fallback_names,
max_request_size: 1_000, max_request_size: 1_000,
@@ -275,7 +275,7 @@ impl Protocol {
// as well. // as well.
Protocol::ChunkFetchingV1 => 100, Protocol::ChunkFetchingV1 => 100,
// 10 seems reasonable, considering group sizes of max 10 validators. // 10 seems reasonable, considering group sizes of max 10 validators.
Protocol::CollationFetchingV1 | Protocol::CollationFetchingVStaging => 10, Protocol::CollationFetchingV1 | Protocol::CollationFetchingV2 => 10,
// 10 seems reasonable, considering group sizes of max 10 validators. // 10 seems reasonable, considering group sizes of max 10 validators.
Protocol::PoVFetchingV1 => 10, Protocol::PoVFetchingV1 => 10,
// Validators are constantly self-selecting to request available data which may lead // Validators are constantly self-selecting to request available data which may lead
@@ -307,7 +307,7 @@ impl Protocol {
// failure, so having a good value here is mostly about performance tuning. // failure, so having a good value here is mostly about performance tuning.
Protocol::DisputeSendingV1 => 100, Protocol::DisputeSendingV1 => 100,
Protocol::AttestedCandidateVStaging => { Protocol::AttestedCandidateV2 => {
// We assume we can utilize up to 70% of the available bandwidth for statements. // We assume we can utilize up to 70% of the available bandwidth for statements.
// This is just a guess/estimate, with the following considerations: If we are // This is just a guess/estimate, with the following considerations: If we are
// faster than that, queue size will stay low anyway, even if not - requesters will // faster than that, queue size will stay low anyway, even if not - requesters will
@@ -344,8 +344,8 @@ impl Protocol {
Protocol::DisputeSendingV1 => Some("/polkadot/send_dispute/1"), Protocol::DisputeSendingV1 => Some("/polkadot/send_dispute/1"),
// Introduced after legacy names became legacy. // Introduced after legacy names became legacy.
Protocol::AttestedCandidateVStaging => None, Protocol::AttestedCandidateV2 => None,
Protocol::CollationFetchingVStaging => None, Protocol::CollationFetchingV2 => None,
} }
} }
} }
@@ -402,8 +402,8 @@ impl ReqProtocolNames {
Protocol::StatementFetchingV1 => "/req_statement/1", Protocol::StatementFetchingV1 => "/req_statement/1",
Protocol::DisputeSendingV1 => "/send_dispute/1", Protocol::DisputeSendingV1 => "/send_dispute/1",
Protocol::CollationFetchingVStaging => "/req_collation/2", Protocol::CollationFetchingV2 => "/req_collation/2",
Protocol::AttestedCandidateVStaging => "/req_attested_candidate/2", Protocol::AttestedCandidateV2 => "/req_attested_candidate/2",
}; };
format!("{}{}", prefix, short_name).into() format!("{}{}", prefix, short_name).into()
@@ -23,7 +23,7 @@ use sc_network::PeerId;
use polkadot_primitives::AuthorityDiscoveryId; use polkadot_primitives::AuthorityDiscoveryId;
use super::{v1, vstaging, IsRequest, Protocol}; use super::{v1, v2, IsRequest, Protocol};
/// All requests that can be sent to the network bridge via `NetworkBridgeTxMessage::SendRequest`. /// All requests that can be sent to the network bridge via `NetworkBridgeTxMessage::SendRequest`.
#[derive(Debug)] #[derive(Debug)]
@@ -42,10 +42,10 @@ pub enum Requests {
DisputeSendingV1(OutgoingRequest<v1::DisputeRequest>), DisputeSendingV1(OutgoingRequest<v1::DisputeRequest>),
/// Request a candidate and attestations. /// Request a candidate and attestations.
AttestedCandidateVStaging(OutgoingRequest<vstaging::AttestedCandidateRequest>), AttestedCandidateV2(OutgoingRequest<v2::AttestedCandidateRequest>),
/// Fetch a collation from a collator which previously announced it. /// Fetch a collation from a collator which previously announced it.
/// Compared to V1 it requires specifying which candidate is requested by its hash. /// Compared to V1 it requires specifying which candidate is requested by its hash.
CollationFetchingVStaging(OutgoingRequest<vstaging::CollationFetchingRequest>), CollationFetchingV2(OutgoingRequest<v2::CollationFetchingRequest>),
} }
impl Requests { impl Requests {
@@ -54,12 +54,12 @@ impl Requests {
match self { match self {
Self::ChunkFetchingV1(_) => Protocol::ChunkFetchingV1, Self::ChunkFetchingV1(_) => Protocol::ChunkFetchingV1,
Self::CollationFetchingV1(_) => Protocol::CollationFetchingV1, Self::CollationFetchingV1(_) => Protocol::CollationFetchingV1,
Self::CollationFetchingVStaging(_) => Protocol::CollationFetchingVStaging, Self::CollationFetchingV2(_) => Protocol::CollationFetchingV2,
Self::PoVFetchingV1(_) => Protocol::PoVFetchingV1, Self::PoVFetchingV1(_) => Protocol::PoVFetchingV1,
Self::AvailableDataFetchingV1(_) => Protocol::AvailableDataFetchingV1, Self::AvailableDataFetchingV1(_) => Protocol::AvailableDataFetchingV1,
Self::StatementFetchingV1(_) => Protocol::StatementFetchingV1, Self::StatementFetchingV1(_) => Protocol::StatementFetchingV1,
Self::DisputeSendingV1(_) => Protocol::DisputeSendingV1, Self::DisputeSendingV1(_) => Protocol::DisputeSendingV1,
Self::AttestedCandidateVStaging(_) => Protocol::AttestedCandidateVStaging, Self::AttestedCandidateV2(_) => Protocol::AttestedCandidateV2,
} }
} }
@@ -74,12 +74,12 @@ impl Requests {
match self { match self {
Self::ChunkFetchingV1(r) => r.encode_request(), Self::ChunkFetchingV1(r) => r.encode_request(),
Self::CollationFetchingV1(r) => r.encode_request(), Self::CollationFetchingV1(r) => r.encode_request(),
Self::CollationFetchingVStaging(r) => r.encode_request(), Self::CollationFetchingV2(r) => r.encode_request(),
Self::PoVFetchingV1(r) => r.encode_request(), Self::PoVFetchingV1(r) => r.encode_request(),
Self::AvailableDataFetchingV1(r) => r.encode_request(), Self::AvailableDataFetchingV1(r) => r.encode_request(),
Self::StatementFetchingV1(r) => r.encode_request(), Self::StatementFetchingV1(r) => r.encode_request(),
Self::DisputeSendingV1(r) => r.encode_request(), Self::DisputeSendingV1(r) => r.encode_request(),
Self::AttestedCandidateVStaging(r) => r.encode_request(), Self::AttestedCandidateV2(r) => r.encode_request(),
} }
} }
} }
@@ -18,13 +18,13 @@
use parity_scale_codec::{Decode, Encode}; use parity_scale_codec::{Decode, Encode};
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
CandidateHash, CommittedCandidateReceipt, Hash, Id as ParaId, PersistedValidationData, CandidateHash, CommittedCandidateReceipt, Hash, Id as ParaId, PersistedValidationData,
UncheckedSignedStatement, UncheckedSignedStatement,
}; };
use super::{IsRequest, Protocol}; use super::{IsRequest, Protocol};
use crate::vstaging::StatementFilter; use crate::v2::StatementFilter;
/// Request a candidate with statements. /// Request a candidate with statements.
#[derive(Debug, Clone, Encode, Decode)] #[derive(Debug, Clone, Encode, Decode)]
@@ -56,7 +56,7 @@ pub struct AttestedCandidateResponse {
impl IsRequest for AttestedCandidateRequest { impl IsRequest for AttestedCandidateRequest {
type Response = AttestedCandidateResponse; type Response = AttestedCandidateResponse;
const PROTOCOL: Protocol = Protocol::AttestedCandidateVStaging; const PROTOCOL: Protocol = Protocol::AttestedCandidateV2;
} }
/// Responses as sent by collators. /// Responses as sent by collators.
@@ -76,5 +76,5 @@ pub struct CollationFetchingRequest {
impl IsRequest for CollationFetchingRequest { impl IsRequest for CollationFetchingRequest {
// The response is the same as for V1. // The response is the same as for V1.
type Response = CollationFetchingResponse; type Response = CollationFetchingResponse;
const PROTOCOL: Protocol = Protocol::CollationFetchingVStaging; const PROTOCOL: Protocol = Protocol::CollationFetchingV2;
} }
@@ -21,8 +21,7 @@ use polkadot_node_network_protocol::{
grid_topology::{GridNeighbors, RequiredRouting, SessionBoundGridTopologyStorage}, grid_topology::{GridNeighbors, RequiredRouting, SessionBoundGridTopologyStorage},
peer_set::{IsAuthority, PeerSet, ValidationVersion}, peer_set::{IsAuthority, PeerSet, ValidationVersion},
v1::{self as protocol_v1, StatementMetadata}, v1::{self as protocol_v1, StatementMetadata},
vstaging as protocol_vstaging, IfDisconnected, PeerId, UnifiedReputationChange as Rep, v2 as protocol_v2, IfDisconnected, PeerId, UnifiedReputationChange as Rep, Versioned, View,
Versioned, View,
}; };
use polkadot_node_primitives::{ use polkadot_node_primitives::{
SignedFullStatement, Statement, StatementWithPVD, UncheckedSignedFullStatement, SignedFullStatement, Statement, StatementWithPVD, UncheckedSignedFullStatement,
@@ -1062,7 +1061,7 @@ async fn circulate_statement<'a, Context>(
"We filter out duplicates above. qed.", "We filter out duplicates above. qed.",
); );
let (v1_peers_to_send, vstaging_peers_to_send) = peers_to_send let (v1_peers_to_send, v2_peers_to_send) = peers_to_send
.into_iter() .into_iter()
.map(|peer_id| { .map(|peer_id| {
let peer_data = let peer_data =
@@ -1074,7 +1073,7 @@ async fn circulate_statement<'a, Context>(
}) })
.partition::<Vec<_>, _>(|(_, _, version)| match version { .partition::<Vec<_>, _>(|(_, _, version)| match version {
ValidationVersion::V1 => true, ValidationVersion::V1 => true,
ValidationVersion::VStaging => false, ValidationVersion::V2 => false,
}); // partition is handy here but not if we add more protocol versions }); // partition is handy here but not if we add more protocol versions
let payload = v1_statement_message(relay_parent, stored.statement.clone(), metrics); let payload = v1_statement_message(relay_parent, stored.statement.clone(), metrics);
@@ -1094,24 +1093,24 @@ async fn circulate_statement<'a, Context>(
)) ))
.await; .await;
} }
if !vstaging_peers_to_send.is_empty() { if !v2_peers_to_send.is_empty() {
gum::trace!( gum::trace!(
target: LOG_TARGET, target: LOG_TARGET,
?vstaging_peers_to_send, ?v2_peers_to_send,
?relay_parent, ?relay_parent,
statement = ?stored.statement, statement = ?stored.statement,
"Sending statement to vstaging peers", "Sending statement to v2 peers",
); );
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
vstaging_peers_to_send.iter().map(|(p, _, _)| *p).collect(), v2_peers_to_send.iter().map(|(p, _, _)| *p).collect(),
compatible_v1_message(ValidationVersion::VStaging, payload.clone()).into(), compatible_v1_message(ValidationVersion::V2, payload.clone()).into(),
)) ))
.await; .await;
} }
v1_peers_to_send v1_peers_to_send
.into_iter() .into_iter()
.chain(vstaging_peers_to_send) .chain(v2_peers_to_send)
.filter_map(|(peer, needs_dependent, _)| if needs_dependent { Some(peer) } else { None }) .filter_map(|(peer, needs_dependent, _)| if needs_dependent { Some(peer) } else { None })
.collect() .collect()
} }
@@ -1443,10 +1442,8 @@ async fn handle_incoming_message<'a, Context>(
let message = match message { let message = match message {
Versioned::V1(m) => m, Versioned::V1(m) => m,
Versioned::VStaging(protocol_vstaging::StatementDistributionMessage::V1Compatibility( Versioned::V2(protocol_v2::StatementDistributionMessage::V1Compatibility(m)) => m,
m, Versioned::V2(_) => {
)) => m,
Versioned::VStaging(_) => {
// The higher-level subsystem code is supposed to filter out // The higher-level subsystem code is supposed to filter out
// all non v1 messages. // all non v1 messages.
gum::debug!( gum::debug!(
@@ -2170,8 +2167,7 @@ fn compatible_v1_message(
) -> net_protocol::StatementDistributionMessage { ) -> net_protocol::StatementDistributionMessage {
match version { match version {
ValidationVersion::V1 => Versioned::V1(message), ValidationVersion::V1 => Versioned::V1(message),
ValidationVersion::VStaging => Versioned::VStaging( ValidationVersion::V2 =>
protocol_vstaging::StatementDistributionMessage::V1Compatibility(message), Versioned::V2(protocol_v2::StatementDistributionMessage::V1Compatibility(message)),
),
} }
} }
@@ -793,7 +793,7 @@ fn receiving_from_one_sends_to_another_and_to_candidate_backing() {
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == hash_a if r == hash_a
=> { => {
@@ -1033,7 +1033,7 @@ fn receiving_large_statement_from_one_sends_to_another_and_to_candidate_backing(
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == hash_a if r == hash_a
=> { => {
@@ -1563,7 +1563,7 @@ fn delay_reputation_changes() {
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == hash_a if r == hash_a
=> { => {
@@ -2043,7 +2043,7 @@ fn share_prioritizes_backing_group() {
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == hash_a if r == hash_a
=> { => {
@@ -2365,7 +2365,7 @@ fn peer_cant_flood_with_large_statements() {
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == hash_a if r == hash_a
=> { => {
@@ -2590,7 +2590,7 @@ fn handle_multiple_seconded_statements() {
assert_matches!( assert_matches!(
handle.recv().await, handle.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(r, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(r, RuntimeApiRequest::AsyncBackingParams(tx))
) )
if r == relay_parent_hash if r == relay_parent_hash
=> { => {
@@ -26,10 +26,8 @@ use error::{log_error, FatalResult};
use std::time::Duration; use std::time::Duration;
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
request_response::{ request_response::{v1 as request_v1, v2::AttestedCandidateRequest, IncomingRequestReceiver},
v1 as request_v1, vstaging::AttestedCandidateRequest, IncomingRequestReceiver, v2 as protocol_v2, Versioned,
},
vstaging as protocol_vstaging, Versioned,
}; };
use polkadot_node_primitives::StatementWithPVD; use polkadot_node_primitives::StatementWithPVD;
use polkadot_node_subsystem::{ use polkadot_node_subsystem::{
@@ -60,7 +58,7 @@ use legacy_v1::{
ResponderMessage as V1ResponderMessage, ResponderMessage as V1ResponderMessage,
}; };
mod vstaging; mod v2;
const LOG_TARGET: &str = "parachain::statement-distribution"; const LOG_TARGET: &str = "parachain::statement-distribution";
@@ -104,9 +102,9 @@ enum MuxedMessage {
/// Messages from spawned v1 (legacy) responder background task. /// Messages from spawned v1 (legacy) responder background task.
V1Responder(Option<V1ResponderMessage>), V1Responder(Option<V1ResponderMessage>),
/// Messages from candidate responder background task. /// Messages from candidate responder background task.
Responder(Option<vstaging::ResponderMessage>), Responder(Option<v2::ResponderMessage>),
/// Messages from answered requests. /// Messages from answered requests.
Response(vstaging::UnhandledResponse), Response(v2::UnhandledResponse),
/// Message that a request is ready to be retried. This just acts as a signal that we should /// Message that a request is ready to be retried. This just acts as a signal that we should
/// dispatch all pending requests again. /// dispatch all pending requests again.
RetryRequest(()), RetryRequest(()),
@@ -116,10 +114,10 @@ enum MuxedMessage {
impl MuxedMessage { impl MuxedMessage {
async fn receive<Context>( async fn receive<Context>(
ctx: &mut Context, ctx: &mut Context,
state: &mut vstaging::State, state: &mut v2::State,
from_v1_requester: &mut mpsc::Receiver<V1RequesterMessage>, from_v1_requester: &mut mpsc::Receiver<V1RequesterMessage>,
from_v1_responder: &mut mpsc::Receiver<V1ResponderMessage>, from_v1_responder: &mut mpsc::Receiver<V1ResponderMessage>,
from_responder: &mut mpsc::Receiver<vstaging::ResponderMessage>, from_responder: &mut mpsc::Receiver<v2::ResponderMessage>,
) -> MuxedMessage { ) -> MuxedMessage {
let (request_manager, response_manager) = state.request_and_response_managers(); let (request_manager, response_manager) = state.request_and_response_managers();
// We are only fusing here to make `select` happy, in reality we will quit if one of those // We are only fusing here to make `select` happy, in reality we will quit if one of those
@@ -128,8 +126,8 @@ impl MuxedMessage {
let from_v1_requester = from_v1_requester.next(); let from_v1_requester = from_v1_requester.next();
let from_v1_responder = from_v1_responder.next(); let from_v1_responder = from_v1_responder.next();
let from_responder = from_responder.next(); let from_responder = from_responder.next();
let receive_response = vstaging::receive_response(response_manager).fuse(); let receive_response = v2::receive_response(response_manager).fuse();
let retry_request = vstaging::next_retry(request_manager).fuse(); let retry_request = v2::next_retry(request_manager).fuse();
futures::pin_mut!( futures::pin_mut!(
from_orchestra, from_orchestra,
from_v1_requester, from_v1_requester,
@@ -182,7 +180,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
let mut reputation_delay = new_reputation_delay(); let mut reputation_delay = new_reputation_delay();
let mut legacy_v1_state = crate::legacy_v1::State::new(self.keystore.clone()); let mut legacy_v1_state = crate::legacy_v1::State::new(self.keystore.clone());
let mut state = crate::vstaging::State::new(self.keystore.clone()); let mut state = crate::v2::State::new(self.keystore.clone());
// Sender/Receiver for getting news from our statement fetching tasks. // Sender/Receiver for getting news from our statement fetching tasks.
let (v1_req_sender, mut v1_req_receiver) = mpsc::channel(1); let (v1_req_sender, mut v1_req_receiver) = mpsc::channel(1);
@@ -206,7 +204,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
ctx.spawn( ctx.spawn(
"candidate-responder", "candidate-responder",
vstaging::respond_task( v2::respond_task(
self.req_receiver.take().expect("Mandatory argument to new. qed"), self.req_receiver.take().expect("Mandatory argument to new. qed"),
res_sender.clone(), res_sender.clone(),
) )
@@ -280,14 +278,13 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
)?; )?;
}, },
MuxedMessage::Responder(result) => { MuxedMessage::Responder(result) => {
vstaging::answer_request( v2::answer_request(
&mut state, &mut state,
result.ok_or(FatalError::RequesterReceiverFinished)?, result.ok_or(FatalError::RequesterReceiverFinished)?,
); );
}, },
MuxedMessage::Response(result) => { MuxedMessage::Response(result) => {
vstaging::handle_response(&mut ctx, &mut state, result, &mut self.reputation) v2::handle_response(&mut ctx, &mut state, result, &mut self.reputation).await;
.await;
}, },
MuxedMessage::RetryRequest(()) => { MuxedMessage::RetryRequest(()) => {
// A pending request is ready to retry. This is only a signal to call // A pending request is ready to retry. This is only a signal to call
@@ -296,7 +293,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
}, },
}; };
vstaging::dispatch_requests(&mut ctx, &mut state).await; v2::dispatch_requests(&mut ctx, &mut state).await;
} }
Ok(()) Ok(())
} }
@@ -304,7 +301,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
async fn handle_subsystem_message<Context>( async fn handle_subsystem_message<Context>(
&mut self, &mut self,
ctx: &mut Context, ctx: &mut Context,
state: &mut vstaging::State, state: &mut v2::State,
legacy_v1_state: &mut legacy_v1::State, legacy_v1_state: &mut legacy_v1::State,
v1_req_sender: &mpsc::Sender<V1RequesterMessage>, v1_req_sender: &mpsc::Sender<V1RequesterMessage>,
message: FromOrchestra<StatementDistributionMessage>, message: FromOrchestra<StatementDistributionMessage>,
@@ -318,11 +315,11 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
})) => { })) => {
let _timer = metrics.time_active_leaves_update(); let _timer = metrics.time_active_leaves_update();
// vstaging should handle activated first because of implicit view. // v2 should handle activated first because of implicit view.
if let Some(ref activated) = activated { if let Some(ref activated) = activated {
let mode = prospective_parachains_mode(ctx.sender(), activated.hash).await?; let mode = prospective_parachains_mode(ctx.sender(), activated.hash).await?;
if let ProspectiveParachainsMode::Enabled { .. } = mode { if let ProspectiveParachainsMode::Enabled { .. } = mode {
vstaging::handle_active_leaves_update(ctx, state, activated, mode).await?; v2::handle_active_leaves_update(ctx, state, activated, mode).await?;
} else if let ProspectiveParachainsMode::Disabled = mode { } else if let ProspectiveParachainsMode::Disabled = mode {
for deactivated in &deactivated { for deactivated in &deactivated {
crate::legacy_v1::handle_deactivate_leaf(legacy_v1_state, *deactivated); crate::legacy_v1::handle_deactivate_leaf(legacy_v1_state, *deactivated);
@@ -339,7 +336,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
for deactivated in &deactivated { for deactivated in &deactivated {
crate::legacy_v1::handle_deactivate_leaf(legacy_v1_state, *deactivated); crate::legacy_v1::handle_deactivate_leaf(legacy_v1_state, *deactivated);
} }
vstaging::handle_deactivate_leaves(state, &deactivated); v2::handle_deactivate_leaves(state, &deactivated);
} }
}, },
FromOrchestra::Signal(OverseerSignal::BlockFinalized(..)) => { FromOrchestra::Signal(OverseerSignal::BlockFinalized(..)) => {
@@ -362,7 +359,7 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
) )
.await?; .await?;
} else { } else {
vstaging::share_local_statement( v2::share_local_statement(
ctx, ctx,
state, state,
relay_parent, relay_parent,
@@ -399,11 +396,11 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
let target = match &event { let target = match &event {
NetworkBridgeEvent::PeerMessage(_, message) => match message { NetworkBridgeEvent::PeerMessage(_, message) => match message {
Versioned::VStaging( Versioned::V2(
protocol_vstaging::StatementDistributionMessage::V1Compatibility(_), protocol_v2::StatementDistributionMessage::V1Compatibility(_),
) => VersionTarget::Legacy, ) => VersionTarget::Legacy,
Versioned::V1(_) => VersionTarget::Legacy, Versioned::V1(_) => VersionTarget::Legacy,
Versioned::VStaging(_) => VersionTarget::Current, Versioned::V2(_) => VersionTarget::Current,
}, },
_ => VersionTarget::Both, _ => VersionTarget::Both,
}; };
@@ -422,14 +419,12 @@ impl<R: rand::Rng> StatementDistributionSubsystem<R> {
} }
if target.targets_current() { if target.targets_current() {
// pass to vstaging. // pass to v2.
vstaging::handle_network_update(ctx, state, event, &mut self.reputation) v2::handle_network_update(ctx, state, event, &mut self.reputation).await;
.await;
} }
}, },
StatementDistributionMessage::Backed(candidate_hash) => { StatementDistributionMessage::Backed(candidate_hash) => {
crate::vstaging::handle_backed_candidate_message(ctx, state, candidate_hash) crate::v2::handle_backed_candidate_message(ctx, state, candidate_hash).await;
.await;
}, },
}, },
} }
@@ -27,7 +27,7 @@
use polkadot_node_network_protocol::PeerId; use polkadot_node_network_protocol::PeerId;
use polkadot_node_subsystem::messages::HypotheticalCandidate; use polkadot_node_subsystem::messages::HypotheticalCandidate;
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
CandidateHash, CommittedCandidateReceipt, GroupIndex, Hash, Id as ParaId, CandidateHash, CommittedCandidateReceipt, GroupIndex, Hash, Id as ParaId,
PersistedValidationData, PersistedValidationData,
}; };
@@ -55,7 +55,7 @@
//! and to keep track of what we have sent to other validators in the group and what we may //! and to keep track of what we have sent to other validators in the group and what we may
//! continue to send them. //! continue to send them.
use polkadot_primitives::vstaging::{CandidateHash, CompactStatement, ValidatorIndex}; use polkadot_primitives::{CandidateHash, CompactStatement, ValidatorIndex};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@@ -459,7 +459,7 @@ pub enum RejectOutgoing {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use polkadot_primitives::vstaging::Hash; use polkadot_primitives::Hash;
#[test] #[test]
fn rejects_incoming_outside_of_group() { fn rejects_incoming_outside_of_group() {
@@ -60,12 +60,8 @@
//! - which has sent a `BackedCandidateAcknowledgement` //! - which has sent a `BackedCandidateAcknowledgement`
//! - 1st-hop nodes do the same thing //! - 1st-hop nodes do the same thing
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{grid_topology::SessionGridTopology, v2::StatementFilter};
grid_topology::SessionGridTopology, vstaging::StatementFilter, use polkadot_primitives::{CandidateHash, CompactStatement, GroupIndex, Hash, ValidatorIndex};
};
use polkadot_primitives::vstaging::{
CandidateHash, CompactStatement, GroupIndex, Hash, ValidatorIndex,
};
use std::collections::{ use std::collections::{
hash_map::{Entry, HashMap}, hash_map::{Entry, HashMap},
@@ -17,8 +17,7 @@
//! A utility for tracking groups and their members within a session. //! A utility for tracking groups and their members within a session.
use polkadot_primitives::{ use polkadot_primitives::{
effective_minimum_backing_votes, effective_minimum_backing_votes, GroupIndex, IndexedVec, ValidatorIndex,
vstaging::{GroupIndex, IndexedVec, ValidatorIndex},
}; };
use std::collections::HashMap; use std::collections::HashMap;
@@ -23,11 +23,11 @@ use polkadot_node_network_protocol::{
peer_set::ValidationVersion, peer_set::ValidationVersion,
request_response::{ request_response::{
incoming::OutgoingResponse, incoming::OutgoingResponse,
vstaging::{AttestedCandidateRequest, AttestedCandidateResponse}, v2::{AttestedCandidateRequest, AttestedCandidateResponse},
IncomingRequest, IncomingRequestReceiver, Requests, IncomingRequest, IncomingRequestReceiver, Requests,
MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS, MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS,
}, },
vstaging::{self as protocol_vstaging, StatementFilter}, v2::{self as protocol_v2, StatementFilter},
IfDisconnected, PeerId, UnifiedReputationChange as Rep, Versioned, View, IfDisconnected, PeerId, UnifiedReputationChange as Rep, Versioned, View,
}; };
use polkadot_node_primitives::{ use polkadot_node_primitives::{
@@ -45,7 +45,7 @@ use polkadot_node_subsystem_util::{
reputation::ReputationAggregator, reputation::ReputationAggregator,
runtime::{request_min_backing_votes, ProspectiveParachainsMode}, runtime::{request_min_backing_votes, ProspectiveParachainsMode},
}; };
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
AuthorityDiscoveryId, CandidateHash, CompactStatement, CoreIndex, CoreState, GroupIndex, AuthorityDiscoveryId, CandidateHash, CompactStatement, CoreIndex, CoreState, GroupIndex,
GroupRotationInfo, Hash, Id as ParaId, IndexedVec, SessionIndex, SessionInfo, SignedStatement, GroupRotationInfo, Hash, Id as ParaId, IndexedVec, SessionIndex, SessionInfo, SignedStatement,
SigningContext, UncheckedSignedStatement, ValidatorId, ValidatorIndex, SigningContext, UncheckedSignedStatement, ValidatorId, ValidatorIndex,
@@ -323,7 +323,7 @@ pub(crate) async fn handle_network_update<Context>(
NetworkBridgeEvent::PeerConnected(peer_id, role, protocol_version, mut authority_ids) => { NetworkBridgeEvent::PeerConnected(peer_id, role, protocol_version, mut authority_ids) => {
gum::trace!(target: LOG_TARGET, ?peer_id, ?role, ?protocol_version, "Peer connected"); gum::trace!(target: LOG_TARGET, ?peer_id, ?role, ?protocol_version, "Peer connected");
if protocol_version != ValidationVersion::VStaging.into() { if protocol_version != ValidationVersion::V2.into() {
return return
} }
@@ -381,19 +381,19 @@ pub(crate) async fn handle_network_update<Context>(
}, },
NetworkBridgeEvent::PeerMessage(peer_id, message) => match message { NetworkBridgeEvent::PeerMessage(peer_id, message) => match message {
net_protocol::StatementDistributionMessage::V1(_) => return, net_protocol::StatementDistributionMessage::V1(_) => return,
net_protocol::StatementDistributionMessage::VStaging( net_protocol::StatementDistributionMessage::V2(
protocol_vstaging::StatementDistributionMessage::V1Compatibility(_), protocol_v2::StatementDistributionMessage::V1Compatibility(_),
) => return, ) => return,
net_protocol::StatementDistributionMessage::VStaging( net_protocol::StatementDistributionMessage::V2(
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) => ) =>
handle_incoming_statement(ctx, state, peer_id, relay_parent, statement, reputation) handle_incoming_statement(ctx, state, peer_id, relay_parent, statement, reputation)
.await, .await,
net_protocol::StatementDistributionMessage::VStaging( net_protocol::StatementDistributionMessage::V2(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(inner), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(inner),
) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation).await, ) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation).await,
net_protocol::StatementDistributionMessage::VStaging( net_protocol::StatementDistributionMessage::V2(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(inner), protocol_v2::StatementDistributionMessage::BackedCandidateKnown(inner),
) => handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation).await, ) => handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation).await,
}, },
NetworkBridgeEvent::PeerViewChange(peer_id, view) => NetworkBridgeEvent::PeerViewChange(peer_id, view) =>
@@ -727,10 +727,8 @@ fn pending_statement_network_message(
statement_store statement_store
.validator_statement(originator, compact) .validator_statement(originator, compact)
.map(|s| s.as_unchecked().clone()) .map(|s| s.as_unchecked().clone())
.map(|signed| { .map(|signed| protocol_v2::StatementDistributionMessage::Statement(relay_parent, signed))
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, signed) .map(|msg| (vec![*peer], Versioned::V2(msg).into()))
})
.map(|msg| (vec![*peer], Versioned::VStaging(msg).into()))
} }
/// Send a peer all pending cluster statements for a relay parent. /// Send a peer all pending cluster statements for a relay parent.
@@ -823,7 +821,7 @@ async fn send_pending_grid_messages<Context>(
match kind { match kind {
grid::ManifestKind::Full => { grid::ManifestKind::Full => {
let manifest = protocol_vstaging::BackedCandidateManifest { let manifest = protocol_v2::BackedCandidateManifest {
relay_parent, relay_parent,
candidate_hash, candidate_hash,
group_index, group_index,
@@ -847,8 +845,8 @@ async fn send_pending_grid_messages<Context>(
messages.push(( messages.push((
vec![*peer_id], vec![*peer_id],
Versioned::VStaging( Versioned::V2(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest, manifest,
), ),
) )
@@ -1192,7 +1190,7 @@ async fn circulate_statement<Context>(
ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage(
statement_to, statement_to,
Versioned::VStaging(protocol_vstaging::StatementDistributionMessage::Statement( Versioned::V2(protocol_v2::StatementDistributionMessage::Statement(
relay_parent, relay_parent,
statement.as_unchecked().clone(), statement.as_unchecked().clone(),
)) ))
@@ -1672,7 +1670,7 @@ async fn provide_candidate_to_grid<Context>(
filter.clone(), filter.clone(),
); );
let manifest = protocol_vstaging::BackedCandidateManifest { let manifest = protocol_v2::BackedCandidateManifest {
relay_parent, relay_parent,
candidate_hash, candidate_hash,
group_index, group_index,
@@ -1680,16 +1678,15 @@ async fn provide_candidate_to_grid<Context>(
parent_head_data_hash: confirmed_candidate.parent_head_data_hash(), parent_head_data_hash: confirmed_candidate.parent_head_data_hash(),
statement_knowledge: filter.clone(), statement_knowledge: filter.clone(),
}; };
let acknowledgement = protocol_vstaging::BackedCandidateAcknowledgement { let acknowledgement = protocol_v2::BackedCandidateAcknowledgement {
candidate_hash, candidate_hash,
statement_knowledge: filter.clone(), statement_knowledge: filter.clone(),
}; };
let manifest_message = Versioned::VStaging( let manifest_message =
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), Versioned::V2(protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest));
); let ack_message = Versioned::V2(
let ack_message = Versioned::VStaging( protocol_v2::StatementDistributionMessage::BackedCandidateKnown(acknowledgement),
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(acknowledgement),
); );
let mut manifest_peers = Vec::new(); let mut manifest_peers = Vec::new();
@@ -2062,8 +2059,8 @@ fn post_acknowledgement_statement_messages(
statement.payload(), statement.payload(),
); );
messages.push(Versioned::VStaging( messages.push(Versioned::V2(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
relay_parent, relay_parent,
statement.as_unchecked().clone(), statement.as_unchecked().clone(),
) )
@@ -2079,7 +2076,7 @@ async fn handle_incoming_manifest<Context>(
ctx: &mut Context, ctx: &mut Context,
state: &mut State, state: &mut State,
peer: PeerId, peer: PeerId,
manifest: net_protocol::vstaging::BackedCandidateManifest, manifest: net_protocol::v2::BackedCandidateManifest,
reputation: &mut ReputationAggregator, reputation: &mut ReputationAggregator,
) { ) {
gum::debug!( gum::debug!(
@@ -2183,14 +2180,14 @@ fn acknowledgement_and_statement_messages(
Some(l) => l, Some(l) => l,
}; };
let acknowledgement = protocol_vstaging::BackedCandidateAcknowledgement { let acknowledgement = protocol_v2::BackedCandidateAcknowledgement {
candidate_hash, candidate_hash,
statement_knowledge: local_knowledge.clone(), statement_knowledge: local_knowledge.clone(),
}; };
let msg = Versioned::VStaging( let msg = Versioned::V2(protocol_v2::StatementDistributionMessage::BackedCandidateKnown(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(acknowledgement), acknowledgement,
); ));
let mut messages = vec![(vec![peer], msg.into())]; let mut messages = vec![(vec![peer], msg.into())];
@@ -2221,7 +2218,7 @@ async fn handle_incoming_acknowledgement<Context>(
ctx: &mut Context, ctx: &mut Context,
state: &mut State, state: &mut State,
peer: PeerId, peer: PeerId,
acknowledgement: net_protocol::vstaging::BackedCandidateAcknowledgement, acknowledgement: net_protocol::v2::BackedCandidateAcknowledgement,
reputation: &mut ReputationAggregator, reputation: &mut ReputationAggregator,
) { ) {
// The key difference between acknowledgments and full manifests is that only // The key difference between acknowledgments and full manifests is that only
@@ -2521,7 +2518,7 @@ pub(crate) async fn dispatch_requests<Context>(ctx: &mut Context, state: &mut St
) { ) {
// Peer is supposedly connected. // Peer is supposedly connected.
ctx.send_message(NetworkBridgeTxMessage::SendRequests( ctx.send_message(NetworkBridgeTxMessage::SendRequests(
vec![Requests::AttestedCandidateVStaging(request)], vec![Requests::AttestedCandidateV2(request)],
IfDisconnected::ImmediateError, IfDisconnected::ImmediateError,
)) ))
.await; .await;
@@ -39,14 +39,14 @@ use crate::LOG_TARGET;
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
request_response::{ request_response::{
outgoing::{Recipient as RequestRecipient, RequestError}, outgoing::{Recipient as RequestRecipient, RequestError},
vstaging::{AttestedCandidateRequest, AttestedCandidateResponse}, v2::{AttestedCandidateRequest, AttestedCandidateResponse},
OutgoingRequest, OutgoingResult, MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS, OutgoingRequest, OutgoingResult, MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS,
}, },
vstaging::StatementFilter, v2::StatementFilter,
PeerId, UnifiedReputationChange as Rep, PeerId, UnifiedReputationChange as Rep,
}; };
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
CandidateHash, CommittedCandidateReceipt, CompactStatement, GroupIndex, Hash, ParaId, CandidateHash, CommittedCandidateReceipt, CompactStatement, GroupIndex, Hash, Id as ParaId,
PersistedValidationData, SessionIndex, SignedStatement, SigningContext, ValidatorId, PersistedValidationData, SessionIndex, SignedStatement, SigningContext, ValidatorId,
ValidatorIndex, ValidatorIndex,
}; };
@@ -24,8 +24,8 @@
//! groups, and views based on the validators themselves. //! groups, and views based on the validators themselves.
use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec};
use polkadot_node_network_protocol::vstaging::StatementFilter; use polkadot_node_network_protocol::v2::StatementFilter;
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
CandidateHash, CompactStatement, GroupIndex, SignedStatement, ValidatorIndex, CandidateHash, CompactStatement, GroupIndex, SignedStatement, ValidatorIndex,
}; };
use std::collections::hash_map::{Entry as HEntry, HashMap}; use std::collections::hash_map::{Entry as HEntry, HashMap};
@@ -103,8 +103,8 @@ fn share_seconded_circulated_to_cluster() {
overseer.recv().await, overseer.recv().await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -173,7 +173,7 @@ fn cluster_valid_statement_before_seconded_ignored() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
relay_parent, relay_parent,
signed_valid.as_unchecked().clone(), signed_valid.as_unchecked().clone(),
), ),
@@ -252,7 +252,7 @@ fn cluster_statement_bad_signature() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
relay_parent, relay_parent,
statement.clone(), statement.clone(),
), ),
@@ -327,7 +327,7 @@ fn useful_cluster_statement_from_non_cluster_peer_rejected() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -388,7 +388,7 @@ fn statement_from_non_cluster_originator_unexpected() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -465,7 +465,7 @@ fn seconded_statement_leads_to_request() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -593,8 +593,8 @@ fn cluster_statements_shared_seconded_first() {
assert_matches!( assert_matches!(
&messages[0].1, &messages[0].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -604,8 +604,8 @@ fn cluster_statements_shared_seconded_first() {
assert_matches!( assert_matches!(
&messages[1].1, &messages[1].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -699,8 +699,8 @@ fn cluster_accounts_for_implicit_view() {
overseer.recv().await, overseer.recv().await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -749,8 +749,8 @@ fn cluster_accounts_for_implicit_view() {
&messages[0], &messages[0],
( (
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -836,10 +836,7 @@ fn cluster_messages_imported_after_confirmed_candidate_importable_check() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -971,10 +968,7 @@ fn cluster_messages_imported_after_new_leaf_importable_check() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -1191,7 +1185,7 @@ fn ensure_seconding_limit_is_respected() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1216,7 +1210,7 @@ fn ensure_seconding_limit_is_respected() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1241,7 +1235,7 @@ fn ensure_seconding_limit_is_respected() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -17,9 +17,7 @@
use super::*; use super::*;
use bitvec::order::Lsb0; use bitvec::order::Lsb0;
use polkadot_node_network_protocol::vstaging::{ use polkadot_node_network_protocol::v2::{BackedCandidateAcknowledgement, BackedCandidateManifest};
BackedCandidateAcknowledgement, BackedCandidateManifest,
};
use polkadot_node_subsystem::messages::CandidateBackingMessage; use polkadot_node_subsystem::messages::CandidateBackingMessage;
use polkadot_primitives_test_helpers::make_candidate; use polkadot_primitives_test_helpers::make_candidate;
@@ -156,7 +154,7 @@ fn backed_candidate_leads_to_advertisement() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -181,7 +179,7 @@ fn backed_candidate_leads_to_advertisement() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_b.clone(), peer_b.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -210,9 +208,9 @@ fn backed_candidate_leads_to_advertisement() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
), ),
), ),
) )
@@ -349,7 +347,7 @@ fn received_advertisement_before_confirmation_leads_to_request() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
) )
.await; .await;
@@ -534,7 +532,7 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -603,9 +601,9 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(ack), protocol_v2::StatementDistributionMessage::BackedCandidateKnown(ack),
), ),
), ),
) )
@@ -629,7 +627,7 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_d.clone(), peer_d.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -654,8 +652,8 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() {
assert_matches!( assert_matches!(
&messages[0].1, &messages[0].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(ack) protocol_v2::StatementDistributionMessage::BackedCandidateKnown(ack)
)) if *ack == expected_ack )) if *ack == expected_ack
); );
} }
@@ -782,7 +780,7 @@ fn received_advertisement_after_confirmation_before_backing() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -842,7 +840,7 @@ fn received_advertisement_after_confirmation_before_backing() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_d.clone(), peer_d.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -951,7 +949,7 @@ fn additional_statements_are_shared_after_manifest_exchange() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -1066,9 +1064,9 @@ fn additional_statements_are_shared_after_manifest_exchange() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(ack), protocol_v2::StatementDistributionMessage::BackedCandidateKnown(ack),
), ),
), ),
) )
@@ -1104,7 +1102,7 @@ fn additional_statements_are_shared_after_manifest_exchange() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_d.clone(), peer_d.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -1130,15 +1128,15 @@ fn additional_statements_are_shared_after_manifest_exchange() {
assert_matches!( assert_matches!(
&messages[0].1, &messages[0].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(ack) protocol_v2::StatementDistributionMessage::BackedCandidateKnown(ack)
)) if *ack == expected_ack )) if *ack == expected_ack
); );
assert_matches!( assert_matches!(
&messages[1].1, &messages[1].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement(r, s) protocol_v2::StatementDistributionMessage::Statement(r, s)
)) if *r == relay_parent && s.unchecked_payload() == &CompactStatement::Seconded(candidate_hash) && s.unchecked_validator_index() == v_e )) if *r == relay_parent && s.unchecked_payload() == &CompactStatement::Seconded(candidate_hash) && s.unchecked_validator_index() == v_e
); );
} }
@@ -1281,7 +1279,7 @@ fn advertisement_sent_when_peer_enters_relay_parent_view() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1306,7 +1304,7 @@ fn advertisement_sent_when_peer_enters_relay_parent_view() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_b.clone(), peer_b.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1357,8 +1355,8 @@ fn advertisement_sent_when_peer_enters_relay_parent_view() {
assert_matches!( assert_matches!(
&messages[0].1, &messages[0].1,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest) protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest)
)) => { )) => {
assert_eq!(*manifest, expected_manifest); assert_eq!(*manifest, expected_manifest);
} }
@@ -1504,7 +1502,7 @@ fn advertisement_not_re_sent_when_peer_re_enters_view() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1529,7 +1527,7 @@ fn advertisement_not_re_sent_when_peer_re_enters_view() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_b.clone(), peer_b.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1558,9 +1556,9 @@ fn advertisement_not_re_sent_when_peer_re_enters_view() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
), ),
), ),
) )
@@ -1692,7 +1690,7 @@ fn grid_statements_imported_to_backing() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -1907,7 +1905,7 @@ fn advertisements_rejected_from_incorrect_peers() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -1925,7 +1923,7 @@ fn advertisements_rejected_from_incorrect_peers() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_b.clone(), peer_b.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
) )
.await; .await;
@@ -2029,7 +2027,7 @@ fn manifest_rejected_with_unknown_relay_parent() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -2131,7 +2129,7 @@ fn manifest_rejected_when_not_a_validator() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -2238,7 +2236,7 @@ fn manifest_rejected_when_group_does_not_match_para() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -2370,7 +2368,7 @@ fn peer_reported_for_advertisement_conflicting_with_confirmed_candidate() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -2439,7 +2437,7 @@ fn peer_reported_for_advertisement_conflicting_with_confirmed_candidate() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
) )
.await; .await;
@@ -31,7 +31,7 @@ use polkadot_node_subsystem::messages::{
}; };
use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_test_helpers as test_helpers;
use polkadot_node_subsystem_util::TimeoutExt; use polkadot_node_subsystem_util::TimeoutExt;
use polkadot_primitives::vstaging::{ use polkadot_primitives::{
AssignmentPair, AsyncBackingParams, BlockNumber, CommittedCandidateReceipt, CoreState, AssignmentPair, AsyncBackingParams, BlockNumber, CommittedCandidateReceipt, CoreState,
GroupRotationInfo, HeadData, Header, IndexedVec, PersistedValidationData, ScheduledCore, GroupRotationInfo, HeadData, Header, IndexedVec, PersistedValidationData, ScheduledCore,
SessionIndex, SessionInfo, ValidatorPair, SessionIndex, SessionInfo, ValidatorPair,
@@ -380,7 +380,7 @@ async fn handle_leaf_activation(
assert_matches!( assert_matches!(
virtual_overseer.recv().await, virtual_overseer.recv().await,
AllMessages::RuntimeApi( AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::StagingAsyncBackingParams(tx)) RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx))
) if parent == *hash => { ) if parent == *hash => {
tx.send(Ok(test_state.config.async_backing_params.unwrap_or(DEFAULT_ASYNC_BACKING_PARAMETERS))).unwrap(); tx.send(Ok(test_state.config.async_backing_params.unwrap_or(DEFAULT_ASYNC_BACKING_PARAMETERS))).unwrap();
} }
@@ -479,7 +479,7 @@ async fn handle_sent_request(
assert_eq!(requests.len(), 1); assert_eq!(requests.len(), 1);
assert_matches!( assert_matches!(
requests.pop().unwrap(), requests.pop().unwrap(),
Requests::AttestedCandidateVStaging(outgoing) => { Requests::AttestedCandidateV2(outgoing) => {
assert_eq!(outgoing.peer, Recipient::Peer(peer)); assert_eq!(outgoing.peer, Recipient::Peer(peer));
assert_eq!(outgoing.payload.candidate_hash, candidate_hash); assert_eq!(outgoing.payload.candidate_hash, candidate_hash);
assert_eq!(outgoing.payload.mask, mask); assert_eq!(outgoing.payload.mask, mask);
@@ -537,7 +537,7 @@ async fn connect_peer(
NetworkBridgeEvent::PeerConnected( NetworkBridgeEvent::PeerConnected(
peer, peer,
ObservedRole::Authority, ObservedRole::Authority,
ValidationVersion::VStaging.into(), ValidationVersion::V2.into(),
authority_ids, authority_ids,
), ),
), ),
@@ -570,12 +570,12 @@ async fn send_peer_view_change(virtual_overseer: &mut VirtualOverseer, peer: Pee
async fn send_peer_message( async fn send_peer_message(
virtual_overseer: &mut VirtualOverseer, virtual_overseer: &mut VirtualOverseer,
peer: PeerId, peer: PeerId,
message: protocol_vstaging::StatementDistributionMessage, message: protocol_v2::StatementDistributionMessage,
) { ) {
virtual_overseer virtual_overseer
.send(FromOrchestra::Communication { .send(FromOrchestra::Communication {
msg: StatementDistributionMessage::NetworkBridgeUpdate( msg: StatementDistributionMessage::NetworkBridgeUpdate(
NetworkBridgeEvent::PeerMessage(peer, Versioned::VStaging(message)), NetworkBridgeEvent::PeerMessage(peer, Versioned::V2(message)),
), ),
}) })
.await; .await;
@@ -19,7 +19,7 @@ use super::*;
use bitvec::order::Lsb0; use bitvec::order::Lsb0;
use parity_scale_codec::{Decode, Encode}; use parity_scale_codec::{Decode, Encode};
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
request_response::vstaging as request_vstaging, vstaging::BackedCandidateManifest, request_response::v2 as request_v2, v2::BackedCandidateManifest,
}; };
use polkadot_primitives_test_helpers::make_candidate; use polkadot_primitives_test_helpers::make_candidate;
use sc_network::config::{ use sc_network::config::{
@@ -109,10 +109,7 @@ fn cluster_peer_allowed_to_send_incomplete_statements() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -164,9 +161,9 @@ fn cluster_peer_allowed_to_send_incomplete_statements() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement(hash, statement), protocol_v2::StatementDistributionMessage::Statement(hash, statement),
), ),
), ),
) )
@@ -304,7 +301,7 @@ fn peer_reported_for_providing_statements_meant_to_be_masked_out() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -376,7 +373,7 @@ fn peer_reported_for_providing_statements_meant_to_be_masked_out() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -453,7 +450,7 @@ fn peer_reported_for_providing_statements_meant_to_be_masked_out() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -568,9 +565,7 @@ fn peer_reported_for_not_enough_statements() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest.clone()),
manifest.clone(),
),
) )
.await; .await;
@@ -752,10 +747,7 @@ fn peer_reported_for_duplicate_statements() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -812,9 +804,9 @@ fn peer_reported_for_duplicate_statements() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement(hash, statement), protocol_v2::StatementDistributionMessage::Statement(hash, statement),
), ),
), ),
) )
@@ -916,10 +908,7 @@ fn peer_reported_for_providing_statements_with_invalid_signatures() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -1058,10 +1047,7 @@ fn peer_reported_for_providing_statements_with_wrong_validator_id() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded),
relay_parent,
a_seconded,
),
) )
.await; .await;
@@ -1191,7 +1177,7 @@ fn local_node_sanity_checks_incoming_requests() {
.send(RawIncomingRequest { .send(RawIncomingRequest {
// Request from peer that received manifest. // Request from peer that received manifest.
peer: peer_c, peer: peer_c,
payload: request_vstaging::AttestedCandidateRequest { payload: request_v2::AttestedCandidateRequest {
candidate_hash: candidate.hash(), candidate_hash: candidate.hash(),
mask: mask.clone(), mask: mask.clone(),
} }
@@ -1225,8 +1211,8 @@ fn local_node_sanity_checks_incoming_requests() {
overseer.recv().await, overseer.recv().await,
AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging(protocol_vstaging::ValidationProtocol::StatementDistribution( Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
r, r,
s, s,
) )
@@ -1250,7 +1236,7 @@ fn local_node_sanity_checks_incoming_requests() {
.send(RawIncomingRequest { .send(RawIncomingRequest {
// Request from peer that received manifest. // Request from peer that received manifest.
peer: peer_d, peer: peer_d,
payload: request_vstaging::AttestedCandidateRequest { payload: request_v2::AttestedCandidateRequest {
candidate_hash: candidate.hash(), candidate_hash: candidate.hash(),
mask: mask.clone(), mask: mask.clone(),
} }
@@ -1269,10 +1255,7 @@ fn local_node_sanity_checks_incoming_requests() {
let response = state let response = state
.send_request( .send_request(
peer_c, peer_c,
request_vstaging::AttestedCandidateRequest { request_v2::AttestedCandidateRequest { candidate_hash: candidate.hash(), mask },
candidate_hash: candidate.hash(),
mask,
},
) )
.await .await
.await; .await;
@@ -1296,7 +1279,7 @@ fn local_node_sanity_checks_incoming_requests() {
let response = state let response = state
.send_request( .send_request(
peer_c, peer_c,
request_vstaging::AttestedCandidateRequest { request_v2::AttestedCandidateRequest {
candidate_hash: candidate.hash(), candidate_hash: candidate.hash(),
mask: mask.clone(), mask: mask.clone(),
}, },
@@ -1455,7 +1438,7 @@ fn local_node_respects_statement_mask() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_a.clone(), peer_a.clone(),
protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement),
) )
.await; .await;
@@ -1479,7 +1462,7 @@ fn local_node_respects_statement_mask() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_b.clone(), peer_b.clone(),
protocol_vstaging::StatementDistributionMessage::Statement( protocol_v2::StatementDistributionMessage::Statement(
relay_parent, relay_parent,
statement_b.clone(), statement_b.clone(),
), ),
@@ -1511,9 +1494,9 @@ fn local_node_respects_statement_mask() {
AllMessages:: NetworkBridgeTx( AllMessages:: NetworkBridgeTx(
NetworkBridgeTxMessage::SendValidationMessage( NetworkBridgeTxMessage::SendValidationMessage(
peers, peers,
Versioned::VStaging( Versioned::V2(
protocol_vstaging::ValidationProtocol::StatementDistribution( protocol_v2::ValidationProtocol::StatementDistribution(
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest),
), ),
), ),
) )
@@ -1547,19 +1530,16 @@ fn local_node_respects_statement_mask() {
let response = state let response = state
.send_request( .send_request(
peer_c, peer_c,
request_vstaging::AttestedCandidateRequest { request_v2::AttestedCandidateRequest { candidate_hash: candidate.hash(), mask },
candidate_hash: candidate.hash(),
mask,
},
) )
.await .await
.await; .await;
let expected_statements = vec![statement_b]; let expected_statements = vec![statement_b];
assert_matches!(response, full_response => { assert_matches!(response, full_response => {
// Response is the same for vstaging. // Response is the same for v2.
let request_vstaging::AttestedCandidateResponse { candidate_receipt, persisted_validation_data, statements } = let request_v2::AttestedCandidateResponse { candidate_receipt, persisted_validation_data, statements } =
request_vstaging::AttestedCandidateResponse::decode( request_v2::AttestedCandidateResponse::decode(
&mut full_response.result.expect("We should have a proper answer").as_ref(), &mut full_response.result.expect("We should have a proper answer").as_ref(),
).expect("Decoding should work"); ).expect("Decoding should work");
assert_eq!(candidate_receipt, candidate); assert_eq!(candidate_receipt, candidate);
@@ -1683,7 +1663,7 @@ fn should_delay_before_retrying_dropped_requests() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
@@ -1696,7 +1676,7 @@ fn should_delay_before_retrying_dropped_requests() {
assert_eq!(requests.len(), 1); assert_eq!(requests.len(), 1);
assert_matches!( assert_matches!(
requests.pop().unwrap(), requests.pop().unwrap(),
Requests::AttestedCandidateVStaging(outgoing) => { Requests::AttestedCandidateV2(outgoing) => {
assert_eq!(outgoing.peer, Recipient::Peer(peer_c)); assert_eq!(outgoing.peer, Recipient::Peer(peer_c));
assert_eq!(outgoing.payload.candidate_hash, candidate_hash_1); assert_eq!(outgoing.payload.candidate_hash, candidate_hash_1);
assert_eq!(outgoing.payload.mask, mask); assert_eq!(outgoing.payload.mask, mask);
@@ -1729,7 +1709,7 @@ fn should_delay_before_retrying_dropped_requests() {
send_peer_message( send_peer_message(
&mut overseer, &mut overseer,
peer_c.clone(), peer_c.clone(),
protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(
manifest.clone(), manifest.clone(),
), ),
) )
-4
View File
@@ -223,7 +223,3 @@ runtime-metrics = [
"rococo-runtime?/runtime-metrics", "rococo-runtime?/runtime-metrics",
"westend-runtime?/runtime-metrics", "westend-runtime?/runtime-metrics",
] ]
network-protocol-staging = [
"polkadot-node-network-protocol/network-protocol-staging",
]
+4 -4
View File
@@ -854,7 +854,7 @@ pub fn new_full<OverseerGenerator: OverseerGen>(
let (collation_req_v1_receiver, cfg) = let (collation_req_v1_receiver, cfg) =
IncomingRequest::get_config_receiver(&req_protocol_names); IncomingRequest::get_config_receiver(&req_protocol_names);
net_config.add_request_response_protocol(cfg); net_config.add_request_response_protocol(cfg);
let (collation_req_vstaging_receiver, cfg) = let (collation_req_v2_receiver, cfg) =
IncomingRequest::get_config_receiver(&req_protocol_names); IncomingRequest::get_config_receiver(&req_protocol_names);
net_config.add_request_response_protocol(cfg); net_config.add_request_response_protocol(cfg);
let (available_data_req_receiver, cfg) = let (available_data_req_receiver, cfg) =
@@ -862,7 +862,7 @@ pub fn new_full<OverseerGenerator: OverseerGen>(
net_config.add_request_response_protocol(cfg); net_config.add_request_response_protocol(cfg);
let (statement_req_receiver, cfg) = IncomingRequest::get_config_receiver(&req_protocol_names); let (statement_req_receiver, cfg) = IncomingRequest::get_config_receiver(&req_protocol_names);
net_config.add_request_response_protocol(cfg); net_config.add_request_response_protocol(cfg);
let (candidate_req_vstaging_receiver, cfg) = let (candidate_req_v2_receiver, cfg) =
IncomingRequest::get_config_receiver(&req_protocol_names); IncomingRequest::get_config_receiver(&req_protocol_names);
net_config.add_request_response_protocol(cfg); net_config.add_request_response_protocol(cfg);
let (dispute_req_receiver, cfg) = IncomingRequest::get_config_receiver(&req_protocol_names); let (dispute_req_receiver, cfg) = IncomingRequest::get_config_receiver(&req_protocol_names);
@@ -1051,10 +1051,10 @@ pub fn new_full<OverseerGenerator: OverseerGen>(
pov_req_receiver, pov_req_receiver,
chunk_req_receiver, chunk_req_receiver,
collation_req_v1_receiver, collation_req_v1_receiver,
collation_req_vstaging_receiver, collation_req_v2_receiver,
available_data_req_receiver, available_data_req_receiver,
statement_req_receiver, statement_req_receiver,
candidate_req_vstaging_receiver, candidate_req_v2_receiver,
dispute_req_receiver, dispute_req_receiver,
registry: prometheus_registry.as_ref(), registry: prometheus_registry.as_ref(),
spawner, spawner,
+8 -10
View File
@@ -28,7 +28,7 @@ use polkadot_node_core_dispute_coordinator::Config as DisputeCoordinatorConfig;
use polkadot_node_network_protocol::{ use polkadot_node_network_protocol::{
peer_set::PeerSetProtocolNames, peer_set::PeerSetProtocolNames,
request_response::{ request_response::{
v1 as request_v1, vstaging as request_vstaging, IncomingRequestReceiver, ReqProtocolNames, v1 as request_v1, v2 as request_v2, IncomingRequestReceiver, ReqProtocolNames,
}, },
}; };
#[cfg(any(feature = "malus", test))] #[cfg(any(feature = "malus", test))]
@@ -104,17 +104,15 @@ where
pub chunk_req_receiver: IncomingRequestReceiver<request_v1::ChunkFetchingRequest>, pub chunk_req_receiver: IncomingRequestReceiver<request_v1::ChunkFetchingRequest>,
/// Collations request receiver for network protocol v1. /// Collations request receiver for network protocol v1.
pub collation_req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>, pub collation_req_v1_receiver: IncomingRequestReceiver<request_v1::CollationFetchingRequest>,
/// Collations request receiver for network protocol vstaging. /// Collations request receiver for network protocol v2.
pub collation_req_vstaging_receiver: pub collation_req_v2_receiver: IncomingRequestReceiver<request_v2::CollationFetchingRequest>,
IncomingRequestReceiver<request_vstaging::CollationFetchingRequest>,
/// Receiver for available data requests. /// Receiver for available data requests.
pub available_data_req_receiver: pub available_data_req_receiver:
IncomingRequestReceiver<request_v1::AvailableDataFetchingRequest>, IncomingRequestReceiver<request_v1::AvailableDataFetchingRequest>,
/// Receiver for incoming large statement requests. /// Receiver for incoming large statement requests.
pub statement_req_receiver: IncomingRequestReceiver<request_v1::StatementFetchingRequest>, pub statement_req_receiver: IncomingRequestReceiver<request_v1::StatementFetchingRequest>,
/// Receiver for incoming candidate requests. /// Receiver for incoming candidate requests.
pub candidate_req_vstaging_receiver: pub candidate_req_v2_receiver: IncomingRequestReceiver<request_v2::AttestedCandidateRequest>,
IncomingRequestReceiver<request_vstaging::AttestedCandidateRequest>,
/// Receiver for incoming disputes. /// Receiver for incoming disputes.
pub dispute_req_receiver: IncomingRequestReceiver<request_v1::DisputeRequest>, pub dispute_req_receiver: IncomingRequestReceiver<request_v1::DisputeRequest>,
/// Prometheus registry, commonly used for production systems, less so for test. /// Prometheus registry, commonly used for production systems, less so for test.
@@ -158,10 +156,10 @@ pub fn prepared_overseer_builder<Spawner, RuntimeClient>(
pov_req_receiver, pov_req_receiver,
chunk_req_receiver, chunk_req_receiver,
collation_req_v1_receiver, collation_req_v1_receiver,
collation_req_vstaging_receiver, collation_req_v2_receiver,
available_data_req_receiver, available_data_req_receiver,
statement_req_receiver, statement_req_receiver,
candidate_req_vstaging_receiver, candidate_req_v2_receiver,
dispute_req_receiver, dispute_req_receiver,
registry, registry,
spawner, spawner,
@@ -288,7 +286,7 @@ where
peer_id: network_service.local_peer_id(), peer_id: network_service.local_peer_id(),
collator_pair, collator_pair,
request_receiver_v1: collation_req_v1_receiver, request_receiver_v1: collation_req_v1_receiver,
request_receiver_vstaging: collation_req_vstaging_receiver, request_receiver_v2: collation_req_v2_receiver,
metrics: Metrics::register(registry)?, metrics: Metrics::register(registry)?,
}, },
IsParachainNode::FullNode => ProtocolSide::None, IsParachainNode::FullNode => ProtocolSide::None,
@@ -309,7 +307,7 @@ where
.statement_distribution(StatementDistributionSubsystem::new( .statement_distribution(StatementDistributionSubsystem::new(
keystore.clone(), keystore.clone(),
statement_req_receiver, statement_req_receiver,
candidate_req_vstaging_receiver, candidate_req_v2_receiver,
Metrics::register(registry)?, Metrics::register(registry)?,
rand::rngs::StdRng::from_entropy(), rand::rngs::StdRng::from_entropy(),
)) ))
+10 -14
View File
@@ -39,12 +39,12 @@ use polkadot_node_primitives::{
ValidationResult, ValidationResult,
}; };
use polkadot_primitives::{ use polkadot_primitives::{
slashing, vstaging as vstaging_primitives, AuthorityDiscoveryId, BackedCandidate, BlockNumber, async_backing, slashing, AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateEvent,
CandidateEvent, CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt,
CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupIndex, CoreState, DisputeState, ExecutorParams, GroupIndex, GroupRotationInfo, Hash,
GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId, InboundDownwardMessage, Header as BlockHeader, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
InboundHrmpMessage, MultiDisputeStatementSet, OccupiedCoreAssumption, PersistedValidationData, MultiDisputeStatementSet, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement,
PvfCheckStatement, PvfExecTimeoutKind, SessionIndex, SessionInfo, SignedAvailabilityBitfield, PvfExecTimeoutKind, SessionIndex, SessionInfo, SignedAvailabilityBitfield,
SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
ValidatorSignature, ValidatorSignature,
}; };
@@ -695,14 +695,12 @@ pub enum RuntimeApiRequest {
), ),
/// Get the minimum required backing votes. /// Get the minimum required backing votes.
MinimumBackingVotes(SessionIndex, RuntimeApiSender<u32>), MinimumBackingVotes(SessionIndex, RuntimeApiSender<u32>),
/// Get the backing state of the given para. /// Get the backing state of the given para.
/// This is a staging API that will not be available on production runtimes. ParaBackingState(ParaId, RuntimeApiSender<Option<async_backing::BackingState>>),
StagingParaBackingState(ParaId, RuntimeApiSender<Option<vstaging_primitives::BackingState>>),
/// Get candidate's acceptance limitations for asynchronous backing for a relay parent. /// Get candidate's acceptance limitations for asynchronous backing for a relay parent.
/// ///
/// If it's not supported by the Runtime, the async backing is said to be disabled. /// If it's not supported by the Runtime, the async backing is said to be disabled.
StagingAsyncBackingParams(RuntimeApiSender<vstaging_primitives::AsyncBackingParams>), AsyncBackingParams(RuntimeApiSender<async_backing::AsyncBackingParams>),
} }
impl RuntimeApiRequest { impl RuntimeApiRequest {
@@ -726,10 +724,8 @@ impl RuntimeApiRequest {
/// `MinimumBackingVotes` /// `MinimumBackingVotes`
pub const MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT: u32 = 6; pub const MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT: u32 = 6;
/// Minimum version for backing state, required for async backing. /// Minimum version to enable asynchronous backing: `AsyncBackingParams` and `ParaBackingState`.
/// pub const STAGING_BACKING_STATE: u32 = 7;
/// 99 for now, should be adjusted to VSTAGING/actual runtime version once released.
pub const STAGING_BACKING_STATE: u32 = 99;
} }
/// A message to the Runtime API subsystem. /// A message to the Runtime API subsystem.
@@ -16,9 +16,9 @@
use async_trait::async_trait; use async_trait::async_trait;
use polkadot_primitives::{ use polkadot_primitives::{
runtime_api::ParachainHost, vstaging, Block, BlockNumber, CandidateCommitments, CandidateEvent, async_backing, runtime_api::ParachainHost, slashing, Block, BlockNumber, CandidateCommitments,
CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState,
GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, ExecutorParams, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage,
OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes,
SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
ValidatorSignature, ValidatorSignature,
@@ -190,7 +190,7 @@ pub trait RuntimeApiSubsystemClient {
async fn unapplied_slashes( async fn unapplied_slashes(
&self, &self,
at: Hash, at: Hash,
) -> Result<Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>, ApiError>; ) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>, ApiError>;
/// Returns a merkle proof of a validator session key in a past session. /// Returns a merkle proof of a validator session key in a past session.
/// ///
@@ -199,7 +199,7 @@ pub trait RuntimeApiSubsystemClient {
&self, &self,
at: Hash, at: Hash,
validator_id: ValidatorId, validator_id: ValidatorId,
) -> Result<Option<vstaging::slashing::OpaqueKeyOwnershipProof>, ApiError>; ) -> Result<Option<slashing::OpaqueKeyOwnershipProof>, ApiError>;
/// Submits an unsigned extrinsic to slash validators who lost a dispute about /// Submits an unsigned extrinsic to slash validators who lost a dispute about
/// a candidate of a past session. /// a candidate of a past session.
@@ -208,8 +208,8 @@ pub trait RuntimeApiSubsystemClient {
async fn submit_report_dispute_lost( async fn submit_report_dispute_lost(
&self, &self,
at: Hash, at: Hash,
dispute_proof: vstaging::slashing::DisputeProof, dispute_proof: slashing::DisputeProof,
key_ownership_proof: vstaging::slashing::OpaqueKeyOwnershipProof, key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
) -> Result<Option<()>, ApiError>; ) -> Result<Option<()>, ApiError>;
// === BABE API === // === BABE API ===
@@ -232,7 +232,7 @@ pub trait RuntimeApiSubsystemClient {
session_index: SessionIndex, session_index: SessionIndex,
) -> Result<Option<ExecutorParams>, ApiError>; ) -> Result<Option<ExecutorParams>, ApiError>;
// === STAGING v6 === // === v6 ===
/// Get the minimum number of backing votes. /// Get the minimum number of backing votes.
async fn minimum_backing_votes( async fn minimum_backing_votes(
&self, &self,
@@ -240,21 +240,21 @@ pub trait RuntimeApiSubsystemClient {
session_index: SessionIndex, session_index: SessionIndex,
) -> Result<u32, ApiError>; ) -> Result<u32, ApiError>;
// === Asynchronous backing API === // === v7: Asynchronous backing API ===
/// Returns candidate's acceptance limitations for asynchronous backing for a relay parent. /// Returns candidate's acceptance limitations for asynchronous backing for a relay parent.
async fn staging_async_backing_params( async fn async_backing_params(
&self, &self,
at: Hash, at: Hash,
) -> Result<polkadot_primitives::vstaging::AsyncBackingParams, ApiError>; ) -> Result<polkadot_primitives::AsyncBackingParams, ApiError>;
/// Returns the state of parachain backing for a given para. /// Returns the state of parachain backing for a given para.
/// This is a staging method! Do not use on production runtimes! /// This is a staging method! Do not use on production runtimes!
async fn staging_para_backing_state( async fn para_backing_state(
&self, &self,
at: Hash, at: Hash,
para_id: Id, para_id: Id,
) -> Result<Option<polkadot_primitives::vstaging::BackingState>, ApiError>; ) -> Result<Option<async_backing::BackingState>, ApiError>;
} }
/// Default implementation of [`RuntimeApiSubsystemClient`] using the client. /// Default implementation of [`RuntimeApiSubsystemClient`] using the client.
@@ -454,7 +454,7 @@ where
async fn unapplied_slashes( async fn unapplied_slashes(
&self, &self,
at: Hash, at: Hash,
) -> Result<Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>, ApiError> { ) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>, ApiError> {
self.client.runtime_api().unapplied_slashes(at) self.client.runtime_api().unapplied_slashes(at)
} }
@@ -462,15 +462,15 @@ where
&self, &self,
at: Hash, at: Hash,
validator_id: ValidatorId, validator_id: ValidatorId,
) -> Result<Option<vstaging::slashing::OpaqueKeyOwnershipProof>, ApiError> { ) -> Result<Option<slashing::OpaqueKeyOwnershipProof>, ApiError> {
self.client.runtime_api().key_ownership_proof(at, validator_id) self.client.runtime_api().key_ownership_proof(at, validator_id)
} }
async fn submit_report_dispute_lost( async fn submit_report_dispute_lost(
&self, &self,
at: Hash, at: Hash,
dispute_proof: vstaging::slashing::DisputeProof, dispute_proof: slashing::DisputeProof,
key_ownership_proof: vstaging::slashing::OpaqueKeyOwnershipProof, key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
) -> Result<Option<()>, ApiError> { ) -> Result<Option<()>, ApiError> {
let mut runtime_api = self.client.runtime_api(); let mut runtime_api = self.client.runtime_api();
@@ -489,19 +489,19 @@ where
self.client.runtime_api().minimum_backing_votes(at) self.client.runtime_api().minimum_backing_votes(at)
} }
async fn staging_para_backing_state( async fn para_backing_state(
&self, &self,
at: Hash, at: Hash,
para_id: Id, para_id: Id,
) -> Result<Option<polkadot_primitives::vstaging::BackingState>, ApiError> { ) -> Result<Option<async_backing::BackingState>, ApiError> {
self.client.runtime_api().staging_para_backing_state(at, para_id) self.client.runtime_api().para_backing_state(at, para_id)
} }
/// Returns candidate's acceptance limitations for asynchronous backing for a relay parent. /// Returns candidate's acceptance limitations for asynchronous backing for a relay parent.
async fn staging_async_backing_params( async fn async_backing_params(
&self, &self,
at: Hash, at: Hash,
) -> Result<polkadot_primitives::vstaging::AsyncBackingParams, ApiError> { ) -> Result<async_backing::AsyncBackingParams, ApiError> {
self.client.runtime_api().staging_async_backing_params(at) self.client.runtime_api().async_backing_params(at)
} }
} }
@@ -20,7 +20,7 @@ use polkadot_node_subsystem::{
messages::{ChainApiMessage, ProspectiveParachainsMessage}, messages::{ChainApiMessage, ProspectiveParachainsMessage},
SubsystemSender, SubsystemSender,
}; };
use polkadot_primitives::vstaging::{BlockNumber, Hash, Id as ParaId}; use polkadot_primitives::{BlockNumber, Hash, Id as ParaId};
use std::collections::HashMap; use std::collections::HashMap;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -43,7 +43,7 @@ use futures::channel::{mpsc, oneshot};
use parity_scale_codec::Encode; use parity_scale_codec::Encode;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging as vstaging_primitives, AuthorityDiscoveryId, CandidateEvent, CandidateHash, AsyncBackingParams, AuthorityDiscoveryId, CandidateEvent, CandidateHash,
CommittedCandidateReceipt, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, CommittedCandidateReceipt, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash,
Id as ParaId, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, Id as ParaId, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
SessionIndex, SessionInfo, Signed, SigningContext, ValidationCode, ValidationCodeHash, SessionIndex, SessionInfo, Signed, SigningContext, ValidationCode, ValidationCodeHash,
@@ -227,7 +227,7 @@ specialize_requests! {
fn request_key_ownership_proof(validator_id: ValidatorId) -> Option<slashing::OpaqueKeyOwnershipProof>; KeyOwnershipProof; fn request_key_ownership_proof(validator_id: ValidatorId) -> Option<slashing::OpaqueKeyOwnershipProof>; KeyOwnershipProof;
fn request_submit_report_dispute_lost(dp: slashing::DisputeProof, okop: slashing::OpaqueKeyOwnershipProof) -> Option<()>; SubmitReportDisputeLost; fn request_submit_report_dispute_lost(dp: slashing::DisputeProof, okop: slashing::OpaqueKeyOwnershipProof) -> Option<()>; SubmitReportDisputeLost;
fn request_staging_async_backing_params() -> vstaging_primitives::AsyncBackingParams; StagingAsyncBackingParams; fn request_async_backing_params() -> AsyncBackingParams; AsyncBackingParams;
} }
/// Requests executor parameters from the runtime effective at given relay-parent. First obtains /// Requests executor parameters from the runtime effective at given relay-parent. First obtains
+14 -15
View File
@@ -30,16 +30,16 @@ use polkadot_node_subsystem::{
}; };
use polkadot_node_subsystem_types::UnpinHandle; use polkadot_node_subsystem_types::UnpinHandle;
use polkadot_primitives::{ use polkadot_primitives::{
vstaging, CandidateEvent, CandidateHash, CoreState, EncodeAs, ExecutorParams, GroupIndex, slashing, AsyncBackingParams, CandidateEvent, CandidateHash, CoreState, EncodeAs,
GroupRotationInfo, Hash, IndexedVec, OccupiedCore, ScrapedOnChainVotes, SessionIndex, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, IndexedVec, OccupiedCore,
SessionInfo, Signed, SigningContext, UncheckedSigned, ValidationCode, ValidationCodeHash, ScrapedOnChainVotes, SessionIndex, SessionInfo, Signed, SigningContext, UncheckedSigned,
ValidatorId, ValidatorIndex, LEGACY_MIN_BACKING_VOTES, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, LEGACY_MIN_BACKING_VOTES,
}; };
use crate::{ use crate::{
request_availability_cores, request_candidate_events, request_from_runtime, request_async_backing_params, request_availability_cores, request_candidate_events,
request_key_ownership_proof, request_on_chain_votes, request_session_executor_params, request_from_runtime, request_key_ownership_proof, request_on_chain_votes,
request_session_index_for_child, request_session_info, request_staging_async_backing_params, request_session_executor_params, request_session_index_for_child, request_session_info,
request_submit_report_dispute_lost, request_unapplied_slashes, request_validation_code_by_hash, request_submit_report_dispute_lost, request_unapplied_slashes, request_validation_code_by_hash,
request_validator_groups, request_validator_groups,
}; };
@@ -377,7 +377,7 @@ where
pub async fn get_unapplied_slashes<Sender>( pub async fn get_unapplied_slashes<Sender>(
sender: &mut Sender, sender: &mut Sender,
relay_parent: Hash, relay_parent: Hash,
) -> Result<Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>> ) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>>
where where
Sender: SubsystemSender<RuntimeApiMessage>, Sender: SubsystemSender<RuntimeApiMessage>,
{ {
@@ -392,7 +392,7 @@ pub async fn key_ownership_proof<Sender>(
sender: &mut Sender, sender: &mut Sender,
relay_parent: Hash, relay_parent: Hash,
validator_id: ValidatorId, validator_id: ValidatorId,
) -> Result<Option<vstaging::slashing::OpaqueKeyOwnershipProof>> ) -> Result<Option<slashing::OpaqueKeyOwnershipProof>>
where where
Sender: SubsystemSender<RuntimeApiMessage>, Sender: SubsystemSender<RuntimeApiMessage>,
{ {
@@ -403,8 +403,8 @@ where
pub async fn submit_report_dispute_lost<Sender>( pub async fn submit_report_dispute_lost<Sender>(
sender: &mut Sender, sender: &mut Sender,
relay_parent: Hash, relay_parent: Hash,
dispute_proof: vstaging::slashing::DisputeProof, dispute_proof: slashing::DisputeProof,
key_ownership_proof: vstaging::slashing::OpaqueKeyOwnershipProof, key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
) -> Result<Option<()>> ) -> Result<Option<()>>
where where
Sender: SubsystemSender<RuntimeApiMessage>, Sender: SubsystemSender<RuntimeApiMessage>,
@@ -429,7 +429,7 @@ where
pub enum ProspectiveParachainsMode { pub enum ProspectiveParachainsMode {
/// Runtime API without support of `async_backing_params`: no prospective parachains. /// Runtime API without support of `async_backing_params`: no prospective parachains.
Disabled, Disabled,
/// vstaging runtime API: prospective parachains. /// v6 runtime API: prospective parachains.
Enabled { Enabled {
/// The maximum number of para blocks between the para head in a relay parent /// The maximum number of para blocks between the para head in a relay parent
/// and a new candidate. Restricts nodes from building arbitrary long chains /// and a new candidate. Restricts nodes from building arbitrary long chains
@@ -457,8 +457,7 @@ pub async fn prospective_parachains_mode<Sender>(
where where
Sender: SubsystemSender<RuntimeApiMessage>, Sender: SubsystemSender<RuntimeApiMessage>,
{ {
let result = let result = recv_runtime(request_async_backing_params(relay_parent, sender).await).await;
recv_runtime(request_staging_async_backing_params(relay_parent, sender).await).await;
if let Err(error::Error::RuntimeRequest(RuntimeApiError::NotSupported { runtime_api_name })) = if let Err(error::Error::RuntimeRequest(RuntimeApiError::NotSupported { runtime_api_name })) =
&result &result
@@ -472,7 +471,7 @@ where
Ok(ProspectiveParachainsMode::Disabled) Ok(ProspectiveParachainsMode::Disabled)
} else { } else {
let vstaging::AsyncBackingParams { max_candidate_depth, allowed_ancestry_len } = result?; let AsyncBackingParams { max_candidate_depth, allowed_ancestry_len } = result?;
Ok(ProspectiveParachainsMode::Enabled { Ok(ProspectiveParachainsMode::Enabled {
max_candidate_depth: max_candidate_depth as _, max_candidate_depth: max_candidate_depth as _,
allowed_ancestry_len: allowed_ancestry_len as _, allowed_ancestry_len: allowed_ancestry_len as _,
@@ -39,6 +39,3 @@ sc-service = { path = "../../../../../substrate/client/service" }
sp-keyring = { path = "../../../../../substrate/primitives/keyring" } sp-keyring = { path = "../../../../../substrate/primitives/keyring" }
tokio = { version = "1.24.2", features = ["macros"] } tokio = { version = "1.24.2", features = ["macros"] }
[features]
network-protocol-staging = [ "polkadot-cli/network-protocol-staging" ]
+16 -15
View File
@@ -19,8 +19,8 @@
#![warn(missing_docs)] #![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
// `v5` is currently the latest stable version of the runtime API. // `v6` is currently the latest stable version of the runtime API.
pub mod v5; pub mod v6;
// The 'staging' version is special - it contains primitives which are // The 'staging' version is special - it contains primitives which are
// still in development. Once they are considered stable, they will be // still in development. Once they are considered stable, they will be
@@ -33,20 +33,21 @@ pub mod runtime_api;
// Current primitives not requiring versioning are exported here. // Current primitives not requiring versioning are exported here.
// Primitives requiring versioning must not be exported and must be referred by an exact version. // Primitives requiring versioning must not be exported and must be referred by an exact version.
pub use v5::{ pub use v6::{
byzantine_threshold, check_candidate_backing, collator_signature_payload, async_backing, byzantine_threshold, check_candidate_backing, collator_signature_payload,
effective_minimum_backing_votes, metric_definitions, slashing, supermajority_threshold, effective_minimum_backing_votes, metric_definitions, slashing, supermajority_threshold,
well_known_keys, AbridgedHostConfiguration, AbridgedHrmpChannel, AccountId, AccountIndex, well_known_keys, AbridgedHostConfiguration, AbridgedHrmpChannel, AccountId, AccountIndex,
AccountPublic, ApprovalVote, AssignmentId, AuthorityDiscoveryId, AvailabilityBitfield, AccountPublic, ApprovalVote, AssignmentId, AsyncBackingParams, AuthorityDiscoveryId,
BackedCandidate, Balance, BlakeTwo256, Block, BlockId, BlockNumber, CandidateCommitments, AvailabilityBitfield, BackedCandidate, Balance, BlakeTwo256, Block, BlockId, BlockNumber,
CandidateDescriptor, CandidateEvent, CandidateHash, CandidateIndex, CandidateReceipt, CandidateCommitments, CandidateDescriptor, CandidateEvent, CandidateHash, CandidateIndex,
CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CollatorId, CollatorSignature, CandidateReceipt, CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CollatorId,
CommittedCandidateReceipt, CompactStatement, ConsensusLog, CoreIndex, CoreState, DisputeState, CollatorSignature, CommittedCandidateReceipt, CompactStatement, ConsensusLog, CoreIndex,
DisputeStatement, DisputeStatementSet, DownwardMessage, EncodeAs, ExecutorParam, CoreState, DisputeState, DisputeStatement, DisputeStatementSet, DownwardMessage, EncodeAs,
ExecutorParams, ExecutorParamsHash, ExplicitDisputeStatement, GroupIndex, GroupRotationInfo, ExecutorParam, ExecutorParams, ExecutorParamsHash, ExplicitDisputeStatement, GroupIndex,
Hash, HashT, HeadData, Header, HrmpChannelId, Id, InboundDownwardMessage, InboundHrmpMessage, GroupRotationInfo, Hash, HashT, HeadData, Header, HorizontalMessages, HrmpChannelId, Id,
IndexedVec, InherentData, InvalidDisputeStatementKind, Moment, MultiDisputeStatementSet, Nonce, InboundDownwardMessage, InboundHrmpMessage, IndexedVec, InherentData,
OccupiedCore, OccupiedCoreAssumption, OutboundHrmpMessage, ParathreadClaim, ParathreadEntry, InvalidDisputeStatementKind, Moment, MultiDisputeStatementSet, Nonce, OccupiedCore,
OccupiedCoreAssumption, OutboundHrmpMessage, ParathreadClaim, ParathreadEntry,
PersistedValidationData, PvfCheckStatement, PvfExecTimeoutKind, PvfPrepTimeoutKind, PersistedValidationData, PvfCheckStatement, PvfExecTimeoutKind, PvfPrepTimeoutKind,
RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues, RuntimeMetricLabels, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues, RuntimeMetricLabels,
RuntimeMetricOp, RuntimeMetricUpdate, ScheduledCore, ScrapedOnChainVotes, SessionIndex, RuntimeMetricOp, RuntimeMetricUpdate, ScheduledCore, ScrapedOnChainVotes, SessionIndex,
@@ -61,4 +62,4 @@ pub use v5::{
}; };
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub use v5::{AssignmentPair, CollatorPair, ValidatorPair}; pub use v6::{AssignmentPair, CollatorPair, ValidatorPair};
+15 -15
View File
@@ -114,10 +114,11 @@
//! separated from the stable primitives. //! separated from the stable primitives.
use crate::{ use crate::{
vstaging, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, async_backing, slashing, AsyncBackingParams, BlockNumber, CandidateCommitments, CandidateEvent,
CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams,
OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, GroupRotationInfo, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement,
SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, ValidatorSignature, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex,
ValidatorSignature,
}; };
use parity_scale_codec::{Decode, Encode}; use parity_scale_codec::{Decode, Encode};
use polkadot_core_primitives as pcp; use polkadot_core_primitives as pcp;
@@ -224,38 +225,37 @@ sp_api::decl_runtime_apis! {
/// Returns a list of validators that lost a past session dispute and need to be slashed. /// Returns a list of validators that lost a past session dispute and need to be slashed.
/// NOTE: This function is only available since parachain host version 5. /// NOTE: This function is only available since parachain host version 5.
fn unapplied_slashes() -> Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>; fn unapplied_slashes() -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>;
/// Returns a merkle proof of a validator session key. /// Returns a merkle proof of a validator session key.
/// NOTE: This function is only available since parachain host version 5. /// NOTE: This function is only available since parachain host version 5.
fn key_ownership_proof( fn key_ownership_proof(
validator_id: ValidatorId, validator_id: ValidatorId,
) -> Option<vstaging::slashing::OpaqueKeyOwnershipProof>; ) -> Option<slashing::OpaqueKeyOwnershipProof>;
/// Submit an unsigned extrinsic to slash validators who lost a dispute about /// Submit an unsigned extrinsic to slash validators who lost a dispute about
/// a candidate of a past session. /// a candidate of a past session.
/// NOTE: This function is only available since parachain host version 5. /// NOTE: This function is only available since parachain host version 5.
fn submit_report_dispute_lost( fn submit_report_dispute_lost(
dispute_proof: vstaging::slashing::DisputeProof, dispute_proof: slashing::DisputeProof,
key_ownership_proof: vstaging::slashing::OpaqueKeyOwnershipProof, key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
) -> Option<()>; ) -> Option<()>;
/***** Staging *****/ /***** Added in v6 *****/
/// Get the minimum number of backing votes for a parachain candidate. /// Get the minimum number of backing votes for a parachain candidate.
/// This is a staging method! Do not use on production runtimes! /// This is a staging method! Do not use on production runtimes!
#[api_version(6)] #[api_version(6)]
fn minimum_backing_votes() -> u32; fn minimum_backing_votes() -> u32;
/***** Asynchronous backing *****/ /***** Added in v7: Asynchronous backing *****/
/// Returns the state of parachain backing for a given para. /// Returns the state of parachain backing for a given para.
/// This is a staging method! Do not use on production runtimes! #[api_version(7)]
#[api_version(99)] fn para_backing_state(_: ppp::Id) -> Option<async_backing::BackingState<H, N>>;
fn staging_para_backing_state(_: ppp::Id) -> Option<vstaging::BackingState<H, N>>;
/// Returns candidate's acceptance limitations for asynchronous backing for a relay parent. /// Returns candidate's acceptance limitations for asynchronous backing for a relay parent.
#[api_version(99)] #[api_version(7)]
fn staging_async_backing_params() -> vstaging::AsyncBackingParams; fn async_backing_params() -> AsyncBackingParams;
} }
} }
+132
View File
@@ -0,0 +1,132 @@
// Copyright (C) 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/>.
//! Asynchronous backing primitives.
use super::*;
use parity_scale_codec::{Decode, Encode};
use primitives::RuntimeDebug;
use scale_info::TypeInfo;
/// Candidate's acceptance limitations for asynchronous backing per relay parent.
#[derive(
RuntimeDebug,
Copy,
Clone,
PartialEq,
Encode,
Decode,
TypeInfo,
serde::Serialize,
serde::Deserialize,
)]
pub struct AsyncBackingParams {
/// The maximum number of para blocks between the para head in a relay parent
/// and a new candidate. Restricts nodes from building arbitrary long chains
/// and spamming other validators.
///
/// When async backing is disabled, the only valid value is 0.
pub max_candidate_depth: u32,
/// How many ancestors of a relay parent are allowed to build candidates on top
/// of.
///
/// When async backing is disabled, the only valid value is 0.
pub allowed_ancestry_len: u32,
}
/// Constraints on inbound HRMP channels.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct InboundHrmpLimitations<N = BlockNumber> {
/// An exhaustive set of all valid watermarks, sorted ascending.
///
/// It's only expected to contain block numbers at which messages were
/// previously sent to a para, excluding most recent head.
pub valid_watermarks: Vec<N>,
}
/// Constraints on outbound HRMP channels.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct OutboundHrmpChannelLimitations {
/// The maximum bytes that can be written to the channel.
pub bytes_remaining: u32,
/// The maximum messages that can be written to the channel.
pub messages_remaining: u32,
}
/// Constraints on the actions that can be taken by a new parachain
/// block. These limitations are implicitly associated with some particular
/// parachain, which should be apparent from usage.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct Constraints<N = BlockNumber> {
/// The minimum relay-parent number accepted under these constraints.
pub min_relay_parent_number: N,
/// The maximum Proof-of-Validity size allowed, in bytes.
pub max_pov_size: u32,
/// The maximum new validation code size allowed, in bytes.
pub max_code_size: u32,
/// The amount of UMP messages remaining.
pub ump_remaining: u32,
/// The amount of UMP bytes remaining.
pub ump_remaining_bytes: u32,
/// The maximum number of UMP messages allowed per candidate.
pub max_ump_num_per_candidate: u32,
/// Remaining DMP queue. Only includes sent-at block numbers.
pub dmp_remaining_messages: Vec<N>,
/// The limitations of all registered inbound HRMP channels.
pub hrmp_inbound: InboundHrmpLimitations<N>,
/// The limitations of all registered outbound HRMP channels.
pub hrmp_channels_out: Vec<(Id, OutboundHrmpChannelLimitations)>,
/// The maximum number of HRMP messages allowed per candidate.
pub max_hrmp_num_per_candidate: u32,
/// The required parent head-data of the parachain.
pub required_parent: HeadData,
/// The expected validation-code-hash of this parachain.
pub validation_code_hash: ValidationCodeHash,
/// The code upgrade restriction signal as-of this parachain.
pub upgrade_restriction: Option<UpgradeRestriction>,
/// The future validation code hash, if any, and at what relay-parent
/// number the upgrade would be minimally applied.
pub future_validation_code: Option<(N, ValidationCodeHash)>,
}
/// A candidate pending availability.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct CandidatePendingAvailability<H = Hash, N = BlockNumber> {
/// The hash of the candidate.
pub candidate_hash: CandidateHash,
/// The candidate's descriptor.
pub descriptor: CandidateDescriptor<H>,
/// The commitments of the candidate.
pub commitments: CandidateCommitments,
/// The candidate's relay parent's number.
pub relay_parent_number: N,
/// The maximum Proof-of-Validity size allowed, in bytes.
pub max_pov_size: u32,
}
/// The per-parachain state of the backing system, including
/// state-machine constraints and candidates pending availability.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct BackingState<H = Hash, N = BlockNumber> {
/// The state-machine constraints of the parachain.
pub constraints: Constraints<N>,
/// The candidates pending availability. These should be ordered, i.e. they should form
/// a sub-chain, where the first candidate builds on top of the required parent of the
/// constraints and each subsequent builds on top of the previous head-data.
pub pending_availability: Vec<CandidatePendingAvailability<H, N>>,
}
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>. // along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! `V2` Primitives. //! `V6` Primitives.
use bitvec::vec::BitVec; use bitvec::vec::BitVec;
use parity_scale_codec::{Decode, Encode}; use parity_scale_codec::{Decode, Encode};
@@ -57,8 +57,13 @@ pub use sp_staking::SessionIndex;
mod signed; mod signed;
pub use signed::{EncodeAs, Signed, UncheckedSigned}; pub use signed::{EncodeAs, Signed, UncheckedSigned};
pub mod async_backing;
pub mod executor_params;
pub mod slashing; pub mod slashing;
pub use async_backing::AsyncBackingParams;
pub use executor_params::{ExecutorParam, ExecutorParams, ExecutorParamsHash};
mod metrics; mod metrics;
pub use metrics::{ pub use metrics::{
metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues, metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues,
@@ -1116,7 +1121,7 @@ pub struct AbridgedHostConfiguration {
/// The delay, in blocks, before a validation upgrade is applied. /// The delay, in blocks, before a validation upgrade is applied.
pub validation_upgrade_delay: BlockNumber, pub validation_upgrade_delay: BlockNumber,
/// Asynchronous backing parameters. /// Asynchronous backing parameters.
pub async_backing_params: super::vstaging::AsyncBackingParams, pub async_backing_params: AsyncBackingParams,
} }
/// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be /// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be
@@ -1803,9 +1808,6 @@ pub enum PvfExecTimeoutKind {
Approval, Approval,
} }
pub mod executor_params;
pub use executor_params::{ExecutorParam, ExecutorParams, ExecutorParamsHash};
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
-118
View File
@@ -17,121 +17,3 @@
//! Staging Primitives. //! Staging Primitives.
// Put any primitives used by staging APIs functions here // Put any primitives used by staging APIs functions here
pub use crate::v5::*;
use sp_std::prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::RuntimeDebug;
use scale_info::TypeInfo;
/// Useful type alias for Para IDs.
pub type ParaId = Id;
/// Candidate's acceptance limitations for asynchronous backing per relay parent.
#[derive(
RuntimeDebug,
Copy,
Clone,
PartialEq,
Encode,
Decode,
TypeInfo,
serde::Serialize,
serde::Deserialize,
)]
pub struct AsyncBackingParams {
/// The maximum number of para blocks between the para head in a relay parent
/// and a new candidate. Restricts nodes from building arbitrary long chains
/// and spamming other validators.
///
/// When async backing is disabled, the only valid value is 0.
pub max_candidate_depth: u32,
/// How many ancestors of a relay parent are allowed to build candidates on top
/// of.
///
/// When async backing is disabled, the only valid value is 0.
pub allowed_ancestry_len: u32,
}
/// Constraints on inbound HRMP channels.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct InboundHrmpLimitations<N = BlockNumber> {
/// An exhaustive set of all valid watermarks, sorted ascending.
///
/// It's only expected to contain block numbers at which messages were
/// previously sent to a para, excluding most recent head.
pub valid_watermarks: Vec<N>,
}
/// Constraints on outbound HRMP channels.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct OutboundHrmpChannelLimitations {
/// The maximum bytes that can be written to the channel.
pub bytes_remaining: u32,
/// The maximum messages that can be written to the channel.
pub messages_remaining: u32,
}
/// Constraints on the actions that can be taken by a new parachain
/// block. These limitations are implicitly associated with some particular
/// parachain, which should be apparent from usage.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct Constraints<N = BlockNumber> {
/// The minimum relay-parent number accepted under these constraints.
pub min_relay_parent_number: N,
/// The maximum Proof-of-Validity size allowed, in bytes.
pub max_pov_size: u32,
/// The maximum new validation code size allowed, in bytes.
pub max_code_size: u32,
/// The amount of UMP messages remaining.
pub ump_remaining: u32,
/// The amount of UMP bytes remaining.
pub ump_remaining_bytes: u32,
/// The maximum number of UMP messages allowed per candidate.
pub max_ump_num_per_candidate: u32,
/// Remaining DMP queue. Only includes sent-at block numbers.
pub dmp_remaining_messages: Vec<N>,
/// The limitations of all registered inbound HRMP channels.
pub hrmp_inbound: InboundHrmpLimitations<N>,
/// The limitations of all registered outbound HRMP channels.
pub hrmp_channels_out: Vec<(ParaId, OutboundHrmpChannelLimitations)>,
/// The maximum number of HRMP messages allowed per candidate.
pub max_hrmp_num_per_candidate: u32,
/// The required parent head-data of the parachain.
pub required_parent: HeadData,
/// The expected validation-code-hash of this parachain.
pub validation_code_hash: ValidationCodeHash,
/// The code upgrade restriction signal as-of this parachain.
pub upgrade_restriction: Option<UpgradeRestriction>,
/// The future validation code hash, if any, and at what relay-parent
/// number the upgrade would be minimally applied.
pub future_validation_code: Option<(N, ValidationCodeHash)>,
}
/// A candidate pending availability.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct CandidatePendingAvailability<H = Hash, N = BlockNumber> {
/// The hash of the candidate.
pub candidate_hash: CandidateHash,
/// The candidate's descriptor.
pub descriptor: CandidateDescriptor<H>,
/// The commitments of the candidate.
pub commitments: CandidateCommitments,
/// The candidate's relay parent's number.
pub relay_parent_number: N,
/// The maximum Proof-of-Validity size allowed, in bytes.
pub max_pov_size: u32,
}
/// The per-parachain state of the backing system, including
/// state-machine constraints and candidates pending availability.
#[derive(RuntimeDebug, Clone, PartialEq, Encode, Decode, TypeInfo)]
pub struct BackingState<H = Hash, N = BlockNumber> {
/// The state-machine constraints of the parachain.
pub constraints: Constraints<N>,
/// The candidates pending availability. These should be ordered, i.e. they should form
/// a sub-chain, where the first candidate builds on top of the required parent of the
/// constraints and each subsequent builds on top of the previous head-data.
pub pending_availability: Vec<CandidatePendingAvailability<H, N>>,
}
@@ -122,7 +122,7 @@ prospective validation data. This is unlikely to change.
### Outgoing ### Outgoing
- `RuntimeApiRequest::StagingParaBackingState` - `RuntimeApiRequest::ParaBackingState`
- Gets the backing state of the given para (the constraints of the para and - Gets the backing state of the given para (the constraints of the para and
candidates pending availability). candidates pending availability).
- `RuntimeApiRequest::AvailabilityCores` - `RuntimeApiRequest::AvailabilityCores`
+1 -1
View File
@@ -46,7 +46,7 @@ use runtime_parachains::{
inclusion::{AggregateMessageOrigin, UmpQueueId}, inclusion::{AggregateMessageOrigin, UmpQueueId},
initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
runtime_api_impl::v5 as parachains_runtime_api_impl, runtime_api_impl::v7 as parachains_runtime_api_impl,
scheduler as parachains_scheduler, session_info as parachains_session_info, scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, shared as parachains_shared,
}; };
@@ -28,7 +28,7 @@ use crate::{
}; };
use frame_support::{assert_noop, assert_ok, error::BadOrigin}; use frame_support::{assert_noop, assert_ok, error::BadOrigin};
use pallet_balances::Error as BalancesError; use pallet_balances::Error as BalancesError;
use primitives::{v5::ValidationCode, BlockNumber, SessionIndex}; use primitives::{BlockNumber, SessionIndex, ValidationCode};
use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_map::BTreeMap;
fn schedule_blank_para(id: ParaId, parakind: ParaKind) { fn schedule_blank_para(id: ParaId, parakind: ParaKind) {
@@ -26,7 +26,7 @@ use polkadot_parachain_primitives::primitives::{
MAX_HORIZONTAL_MESSAGE_NUM, MAX_UPWARD_MESSAGE_NUM, MAX_HORIZONTAL_MESSAGE_NUM, MAX_UPWARD_MESSAGE_NUM,
}; };
use primitives::{ use primitives::{
vstaging::AsyncBackingParams, Balance, ExecutorParams, SessionIndex, LEGACY_MIN_BACKING_VOTES, AsyncBackingParams, Balance, ExecutorParams, SessionIndex, LEGACY_MIN_BACKING_VOTES,
MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
}; };
use sp_runtime::{traits::Zero, Perbill}; use sp_runtime::{traits::Zero, Perbill};
@@ -21,7 +21,7 @@ use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::BlockNumberFor; use frame_system::pallet_prelude::BlockNumberFor;
use sp_std::vec::Vec; use sp_std::vec::Vec;
use primitives::{vstaging::AsyncBackingParams, Balance, ExecutorParams, SessionIndex}; use primitives::{AsyncBackingParams, Balance, ExecutorParams, SessionIndex};
#[cfg(feature = "try-runtime")] #[cfg(feature = "try-runtime")]
use sp_std::prelude::*; use sp_std::prelude::*;
@@ -23,7 +23,7 @@ use frame_support::{
weights::Weight, weights::Weight,
}; };
use frame_system::pallet_prelude::BlockNumberFor; use frame_system::pallet_prelude::BlockNumberFor;
use primitives::{vstaging::AsyncBackingParams, Balance, ExecutorParams, SessionIndex}; use primitives::{AsyncBackingParams, Balance, ExecutorParams, SessionIndex};
use sp_std::vec::Vec; use sp_std::vec::Vec;
use frame_support::traits::OnRuntimeUpgrade; use frame_support::traits::OnRuntimeUpgrade;
@@ -24,8 +24,7 @@ use frame_support::{
}; };
use frame_system::pallet_prelude::BlockNumberFor; use frame_system::pallet_prelude::BlockNumberFor;
use primitives::{ use primitives::{
vstaging::AsyncBackingParams, Balance, ExecutorParams, SessionIndex, AsyncBackingParams, Balance, ExecutorParams, SessionIndex, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
}; };
use sp_runtime::Perbill; use sp_runtime::Perbill;
use sp_std::vec::Vec; use sp_std::vec::Vec;
@@ -51,7 +51,7 @@ use frame_support::{
use frame_system::pallet_prelude::BlockNumberFor; use frame_system::pallet_prelude::BlockNumberFor;
use primitives::{ use primitives::{
vstaging::slashing::{DisputeProof, DisputesTimeSlot, PendingSlashes, SlashingOffenceKind}, slashing::{DisputeProof, DisputesTimeSlot, PendingSlashes, SlashingOffenceKind},
CandidateHash, SessionIndex, ValidatorId, ValidatorIndex, CandidateHash, SessionIndex, ValidatorId, ValidatorIndex,
}; };
use scale_info::TypeInfo; use scale_info::TypeInfo;
@@ -25,5 +25,6 @@
//! 1. Bump the version of the stable module (e.g. `v2` becomes `v3`) //! 1. Bump the version of the stable module (e.g. `v2` becomes `v3`)
//! 2. Move methods from `vstaging` to `v3`. The new stable version should include all methods from //! 2. Move methods from `vstaging` to `v3`. The new stable version should include all methods from
//! `vstaging` tagged with the new version number (e.g. all `v3` methods). //! `vstaging` tagged with the new version number (e.g. all `v3` methods).
pub mod v5;
pub mod v7;
pub mod vstaging; pub mod vstaging;
@@ -18,12 +18,16 @@
//! functions. //! functions.
use crate::{ use crate::{
disputes, dmp, hrmp, inclusion, initializer, paras, paras_inherent, configuration, disputes, dmp, hrmp, inclusion, initializer, paras, paras_inherent,
scheduler::{self, CoreOccupied}, scheduler::{self, CoreOccupied},
session_info, shared, session_info, shared,
}; };
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
use primitives::{ use primitives::{
async_backing::{
AsyncBackingParams, BackingState, CandidatePendingAvailability, Constraints,
InboundHrmpLimitations, OutboundHrmpChannelLimitations,
},
slashing, AuthorityDiscoveryId, CandidateEvent, CandidateHash, CommittedCandidateReceipt, slashing, AuthorityDiscoveryId, CandidateEvent, CandidateHash, CommittedCandidateReceipt,
CoreIndex, CoreState, DisputeState, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, CoreIndex, CoreState, DisputeState, ExecutorParams, GroupIndex, GroupRotationInfo, Hash,
Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption,
@@ -395,3 +399,100 @@ pub fn submit_unsigned_slashing_report<T: disputes::slashing::Config>(
key_ownership_proof, key_ownership_proof,
) )
} }
/// Return the min backing votes threshold from the configuration.
pub fn minimum_backing_votes<T: initializer::Config>() -> u32 {
<configuration::Pallet<T>>::config().minimum_backing_votes
}
/// Implementation for `ParaBackingState` function from the runtime API
pub fn backing_state<T: initializer::Config>(
para_id: ParaId,
) -> Option<BackingState<T::Hash, BlockNumberFor<T>>> {
let config = <configuration::Pallet<T>>::config();
// Async backing is only expected to be enabled with a tracker capacity of 1.
// Subsequent configuration update gets applied on new session, which always
// clears the buffer.
//
// Thus, minimum relay parent is ensured to have asynchronous backing enabled.
let now = <frame_system::Pallet<T>>::block_number();
let min_relay_parent_number = <shared::Pallet<T>>::allowed_relay_parents()
.hypothetical_earliest_block_number(now, config.async_backing_params.allowed_ancestry_len);
let required_parent = <paras::Pallet<T>>::para_head(para_id)?;
let validation_code_hash = <paras::Pallet<T>>::current_code_hash(para_id)?;
let upgrade_restriction = <paras::Pallet<T>>::upgrade_restriction_signal(para_id);
let future_validation_code =
<paras::Pallet<T>>::future_code_upgrade_at(para_id).and_then(|block_num| {
// Only read the storage if there's a pending upgrade.
Some(block_num).zip(<paras::Pallet<T>>::future_code_hash(para_id))
});
let (ump_msg_count, ump_total_bytes) =
<inclusion::Pallet<T>>::relay_dispatch_queue_size(para_id);
let ump_remaining = config.max_upward_queue_count - ump_msg_count;
let ump_remaining_bytes = config.max_upward_queue_size - ump_total_bytes;
let dmp_remaining_messages = <dmp::Pallet<T>>::dmq_contents(para_id)
.into_iter()
.map(|msg| msg.sent_at)
.collect();
let valid_watermarks = <hrmp::Pallet<T>>::valid_watermarks(para_id);
let hrmp_inbound = InboundHrmpLimitations { valid_watermarks };
let hrmp_channels_out = <hrmp::Pallet<T>>::outbound_remaining_capacity(para_id)
.into_iter()
.map(|(para, (messages_remaining, bytes_remaining))| {
(para, OutboundHrmpChannelLimitations { messages_remaining, bytes_remaining })
})
.collect();
let constraints = Constraints {
min_relay_parent_number,
max_pov_size: config.max_pov_size,
max_code_size: config.max_code_size,
ump_remaining,
ump_remaining_bytes,
max_ump_num_per_candidate: config.max_upward_message_num_per_candidate,
dmp_remaining_messages,
hrmp_inbound,
hrmp_channels_out,
max_hrmp_num_per_candidate: config.hrmp_max_message_num_per_candidate,
required_parent,
validation_code_hash,
upgrade_restriction,
future_validation_code,
};
let pending_availability = {
// Note: the API deals with a `Vec` as it is future-proof for cases
// where there may be multiple candidates pending availability at a time.
// But at the moment only one candidate can be pending availability per
// parachain.
crate::inclusion::PendingAvailability::<T>::get(&para_id)
.and_then(|pending| {
let commitments =
crate::inclusion::PendingAvailabilityCommitments::<T>::get(&para_id);
commitments.map(move |c| (pending, c))
})
.map(|(pending, commitments)| {
CandidatePendingAvailability {
candidate_hash: pending.candidate_hash(),
descriptor: pending.candidate_descriptor().clone(),
commitments,
relay_parent_number: pending.relay_parent_number(),
max_pov_size: constraints.max_pov_size, // assume always same in session.
}
})
.into_iter()
.collect()
};
Some(BackingState { constraints, pending_availability })
}
/// Implementation for `AsyncBackingParams` function from the runtime API
pub fn async_backing_params<T: configuration::Config>() -> AsyncBackingParams {
<configuration::Pallet<T>>::config().async_backing_params
}
@@ -15,111 +15,3 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>. // along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Put implementations of functions from staging APIs here. //! Put implementations of functions from staging APIs here.
use crate::{configuration, dmp, hrmp, inclusion, initializer, paras, shared};
use frame_system::pallet_prelude::BlockNumberFor;
use primitives::{
vstaging::{
AsyncBackingParams, BackingState, CandidatePendingAvailability, Constraints,
InboundHrmpLimitations, OutboundHrmpChannelLimitations,
},
Id as ParaId,
};
use sp_std::prelude::*;
/// Implementation for `StagingParaBackingState` function from the runtime API
pub fn backing_state<T: initializer::Config>(
para_id: ParaId,
) -> Option<BackingState<T::Hash, BlockNumberFor<T>>> {
let config = <configuration::Pallet<T>>::config();
// Async backing is only expected to be enabled with a tracker capacity of 1.
// Subsequent configuration update gets applied on new session, which always
// clears the buffer.
//
// Thus, minimum relay parent is ensured to have asynchronous backing enabled.
let now = <frame_system::Pallet<T>>::block_number();
let min_relay_parent_number = <shared::Pallet<T>>::allowed_relay_parents()
.hypothetical_earliest_block_number(now, config.async_backing_params.allowed_ancestry_len);
let required_parent = <paras::Pallet<T>>::para_head(para_id)?;
let validation_code_hash = <paras::Pallet<T>>::current_code_hash(para_id)?;
let upgrade_restriction = <paras::Pallet<T>>::upgrade_restriction_signal(para_id);
let future_validation_code =
<paras::Pallet<T>>::future_code_upgrade_at(para_id).and_then(|block_num| {
// Only read the storage if there's a pending upgrade.
Some(block_num).zip(<paras::Pallet<T>>::future_code_hash(para_id))
});
let (ump_msg_count, ump_total_bytes) =
<inclusion::Pallet<T>>::relay_dispatch_queue_size(para_id);
let ump_remaining = config.max_upward_queue_count - ump_msg_count;
let ump_remaining_bytes = config.max_upward_queue_size - ump_total_bytes;
let dmp_remaining_messages = <dmp::Pallet<T>>::dmq_contents(para_id)
.into_iter()
.map(|msg| msg.sent_at)
.collect();
let valid_watermarks = <hrmp::Pallet<T>>::valid_watermarks(para_id);
let hrmp_inbound = InboundHrmpLimitations { valid_watermarks };
let hrmp_channels_out = <hrmp::Pallet<T>>::outbound_remaining_capacity(para_id)
.into_iter()
.map(|(para, (messages_remaining, bytes_remaining))| {
(para, OutboundHrmpChannelLimitations { messages_remaining, bytes_remaining })
})
.collect();
let constraints = Constraints {
min_relay_parent_number,
max_pov_size: config.max_pov_size,
max_code_size: config.max_code_size,
ump_remaining,
ump_remaining_bytes,
max_ump_num_per_candidate: config.max_upward_message_num_per_candidate,
dmp_remaining_messages,
hrmp_inbound,
hrmp_channels_out,
max_hrmp_num_per_candidate: config.hrmp_max_message_num_per_candidate,
required_parent,
validation_code_hash,
upgrade_restriction,
future_validation_code,
};
let pending_availability = {
// Note: the API deals with a `Vec` as it is future-proof for cases
// where there may be multiple candidates pending availability at a time.
// But at the moment only one candidate can be pending availability per
// parachain.
crate::inclusion::PendingAvailability::<T>::get(&para_id)
.and_then(|pending| {
let commitments =
crate::inclusion::PendingAvailabilityCommitments::<T>::get(&para_id);
commitments.map(move |c| (pending, c))
})
.map(|(pending, commitments)| {
CandidatePendingAvailability {
candidate_hash: pending.candidate_hash(),
descriptor: pending.candidate_descriptor().clone(),
commitments,
relay_parent_number: pending.relay_parent_number(),
max_pov_size: constraints.max_pov_size, // assume always same in session.
}
})
.into_iter()
.collect()
};
Some(BackingState { constraints, pending_availability })
}
/// Implementation for `StagingAsyncBackingParams` function from the runtime API
pub fn async_backing_params<T: configuration::Config>() -> AsyncBackingParams {
<configuration::Pallet<T>>::config().async_backing_params
}
/// Return the min backing votes threshold from the configuration.
pub fn minimum_backing_votes<T: initializer::Config>() -> u32 {
<configuration::Pallet<T>>::config().minimum_backing_votes
}
+1 -1
View File
@@ -34,7 +34,7 @@ use runtime_parachains::{
inclusion::{AggregateMessageOrigin, UmpQueueId}, inclusion::{AggregateMessageOrigin, UmpQueueId},
initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
runtime_api_impl::v5 as parachains_runtime_api_impl, runtime_api_impl::v7 as parachains_runtime_api_impl,
scheduler as parachains_scheduler, session_info as parachains_session_info, scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, shared as parachains_shared,
}; };
+14 -1
View File
@@ -46,7 +46,7 @@ use runtime_parachains::{
inclusion::{AggregateMessageOrigin, UmpQueueId}, inclusion::{AggregateMessageOrigin, UmpQueueId},
initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, paras_inherent as parachains_paras_inherent,
runtime_api_impl::v5 as parachains_runtime_api_impl, runtime_api_impl::v7 as parachains_runtime_api_impl,
scheduler as parachains_scheduler, session_info as parachains_session_info, scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, shared as parachains_shared,
}; };
@@ -1724,6 +1724,7 @@ sp_api::impl_runtime_apis! {
} }
} }
#[api_version(7)]
impl primitives::runtime_api::ParachainHost<Block, Hash, BlockNumber> for Runtime { impl primitives::runtime_api::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> { fn validators() -> Vec<ValidatorId> {
parachains_runtime_api_impl::validators::<Runtime>() parachains_runtime_api_impl::validators::<Runtime>()
@@ -1854,6 +1855,18 @@ sp_api::impl_runtime_apis! {
key_ownership_proof, key_ownership_proof,
) )
} }
fn minimum_backing_votes() -> u32 {
parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
}
fn para_backing_state(para_id: ParaId) -> Option<primitives::async_backing::BackingState> {
parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
}
fn async_backing_params() -> primitives::AsyncBackingParams {
parachains_runtime_api_impl::async_backing_params::<Runtime>()
}
} }
#[api_version(3)] #[api_version(3)]
+1 -1
View File
@@ -30,7 +30,7 @@ use polkadot_runtime_parachains::{
disputes::slashing as parachains_slashing, dmp as parachains_dmp, hrmp as parachains_hrmp, disputes::slashing as parachains_slashing, dmp as parachains_dmp, hrmp as parachains_hrmp,
inclusion as parachains_inclusion, initializer as parachains_initializer, inclusion as parachains_inclusion, initializer as parachains_initializer,
origin as parachains_origin, paras as parachains_paras, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, runtime_api_impl::v5 as runtime_impl, paras_inherent as parachains_paras_inherent, runtime_api_impl::v7 as runtime_impl,
scheduler as parachains_scheduler, session_info as parachains_session_info, scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, shared as parachains_shared,
}; };
+11 -5
View File
@@ -65,9 +65,7 @@ use runtime_parachains::{
inclusion::{AggregateMessageOrigin, UmpQueueId}, inclusion::{AggregateMessageOrigin, UmpQueueId},
initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
runtime_api_impl::{ runtime_api_impl::v7 as parachains_runtime_api_impl,
v5 as parachains_runtime_api_impl, vstaging as parachains_staging_runtime_api_impl,
},
scheduler as parachains_scheduler, session_info as parachains_session_info, scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, shared as parachains_shared,
}; };
@@ -1582,7 +1580,7 @@ sp_api::impl_runtime_apis! {
} }
} }
#[api_version(6)] #[api_version(7)]
impl primitives::runtime_api::ParachainHost<Block, Hash, BlockNumber> for Runtime { impl primitives::runtime_api::ParachainHost<Block, Hash, BlockNumber> for Runtime {
fn validators() -> Vec<ValidatorId> { fn validators() -> Vec<ValidatorId> {
parachains_runtime_api_impl::validators::<Runtime>() parachains_runtime_api_impl::validators::<Runtime>()
@@ -1715,7 +1713,15 @@ sp_api::impl_runtime_apis! {
} }
fn minimum_backing_votes() -> u32 { fn minimum_backing_votes() -> u32 {
parachains_staging_runtime_api_impl::minimum_backing_votes::<Runtime>() parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
}
fn para_backing_state(para_id: ParaId) -> Option<primitives::async_backing::BackingState> {
parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
}
fn async_backing_params() -> primitives::AsyncBackingParams {
parachains_runtime_api_impl::async_backing_params::<Runtime>()
} }
} }
@@ -1,34 +0,0 @@
[settings]
timeout = 1000
[relaychain]
default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}"
chain = "rococo-local"
default_command = "polkadot"
[relaychain.default_resources]
limits = { memory = "4G", cpu = "2" }
requests = { memory = "2G", cpu = "1" }
[[relaychain.nodes]]
name = "alice"
args = [ "-lparachain=debug,runtime=debug"]
[[relaychain.nodes]]
name = "bob"
image = "{{ZOMBIENET_INTEGRATION_TEST_SECONDARY_IMAGE}}"
args = [ "-lparachain=debug,runtime=debug"]
[[parachains]]
id = 100
[parachains.collator]
name = "collator01"
image = "{{COL_IMAGE}}"
command = "undying-collator"
args = ["-lparachain=debug"]
[types.Header]
number = "u64"
parent_hash = "Hash"
post_state = "Hash"

Some files were not shown because too many files have changed in this diff Show More