diff --git a/polkadot/Cargo.lock b/polkadot/Cargo.lock index e7912dd6eb..1b5416c888 100644 --- a/polkadot/Cargo.lock +++ b/polkadot/Cargo.lock @@ -5820,6 +5820,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "rand 0.8.4", "sc-network", "sp-core", @@ -5848,6 +5849,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "rand 0.8.4", "sc-network", "sp-application-crypto", @@ -5928,6 +5930,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-network", "sp-core", "sp-keyring", @@ -5968,6 +5971,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-keystore", "sc-network", "sp-application-crypto", @@ -6033,6 +6037,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-network", "sp-consensus", "sp-core", @@ -6052,6 +6057,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-core", "sp-maybe-compressed-blob", "thiserror", @@ -6080,6 +6086,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", + "polkadot-primitives-test-helpers", "rand_core 0.5.1", "sc-keystore", "schnorrkel", @@ -6115,6 +6122,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-core", "sp-keyring", "thiserror", @@ -6134,6 +6142,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "polkadot-statement-table", "sc-keystore", "sp-application-crypto", @@ -6154,6 +6163,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-keystore", "thiserror", "tracing", @@ -6175,6 +6185,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-parachain", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-core", "sp-keyring", "sp-maybe-compressed-blob", @@ -6226,8 +6237,6 @@ name = "polkadot-node-core-dispute-coordinator" version = "0.9.13" dependencies = [ "assert_matches", - "bitvec", - "derive_more", "futures 0.3.18", "kvdb", "kvdb-memorydb", @@ -6237,6 +6246,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-keystore", "sp-core", "sp-keyring", @@ -6272,6 +6282,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-application-crypto", "sp-keystore", "thiserror", @@ -6324,6 +6335,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sp-api", "sp-authority-discovery", "sp-consensus-babe", @@ -6466,6 +6478,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-overseer", "polkadot-primitives", + "polkadot-primitives-test-helpers", "rand 0.8.4", "sp-application-crypto", "sp-core", @@ -6492,6 +6505,7 @@ dependencies = [ "polkadot-node-subsystem-types", "polkadot-overseer-gen", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-client-api", "sp-api", "sp-core", @@ -6585,6 +6599,16 @@ dependencies = [ "sp-version", ] +[[package]] +name = "polkadot-primitives-test-helpers" +version = "0.9.13" +dependencies = [ + "polkadot-primitives", + "sp-application-crypto", + "sp-keyring", + "sp-runtime", +] + [[package]] name = "polkadot-rpc" version = "0.9.13" @@ -6731,6 +6755,7 @@ dependencies = [ "pallet-vesting", "parity-scale-codec", "polkadot-primitives", + "polkadot-primitives-test-helpers", "polkadot-runtime-parachains", "rustc-hex", "scale-info", @@ -6776,6 +6801,7 @@ dependencies = [ "pallet-vesting", "parity-scale-codec", "polkadot-primitives", + "polkadot-primitives-test-helpers", "rand 0.8.4", "rand_chacha 0.3.1", "rustc-hex", @@ -6968,6 +6994,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", + "polkadot-primitives-test-helpers", "sc-keystore", "sc-network", "sp-application-crypto", diff --git a/polkadot/Cargo.toml b/polkadot/Cargo.toml index 2b3e51e4e8..23c09ee456 100644 --- a/polkadot/Cargo.toml +++ b/polkadot/Cargo.toml @@ -27,6 +27,7 @@ members = [ "core-primitives", "erasure-coding", "primitives", + "primitives/test-helpers", "runtime/common", "runtime/common/slot_range_helper", "runtime/parachains", diff --git a/polkadot/erasure-coding/fuzzer/src/round_trip.rs b/polkadot/erasure-coding/fuzzer/src/round_trip.rs index 754468f992..3d5ea59274 100644 --- a/polkadot/erasure-coding/fuzzer/src/round_trip.rs +++ b/polkadot/erasure-coding/fuzzer/src/round_trip.rs @@ -13,7 +13,7 @@ fn main() { let available_data = AvailableData { pov: Arc::new(pov_block), - validation_data: Default::default(), + validation_data: PersistedValidationData::default(), }; let chunks = obtain_chunks_v1( 10, diff --git a/polkadot/erasure-coding/src/lib.rs b/polkadot/erasure-coding/src/lib.rs index 1d2132048d..4aa0a475cb 100644 --- a/polkadot/erasure-coding/src/lib.rs +++ b/polkadot/erasure-coding/src/lib.rs @@ -370,7 +370,7 @@ impl<'a, I: Iterator> parity_scale_codec::Input for ShardInput< #[cfg(test)] mod tests { use super::*; - use polkadot_primitives::v0::{AvailableData, BlockData, PoVBlock}; + use polkadot_primitives::v0::{AvailableData, BlockData, OmittedValidationData, PoVBlock}; // In order to adequately compute the number of entries in the Merkle // trie, we must account for the fixed 16-ary trie structure. @@ -385,7 +385,8 @@ mod tests { fn round_trip_works() { let pov_block = PoVBlock { block_data: BlockData((0..255).collect()) }; - let available_data = AvailableData { pov_block, omitted_validation: Default::default() }; + let available_data = + AvailableData { pov_block, omitted_validation: OmittedValidationData::default() }; let chunks = obtain_chunks(10, &available_data).unwrap(); assert_eq!(chunks.len(), 10); @@ -413,7 +414,8 @@ mod tests { let pov_block = PoVBlock { block_data: BlockData(vec![2; n_validators / KEY_INDEX_NIBBLE_SIZE]) }; - let available_data = AvailableData { pov_block, omitted_validation: Default::default() }; + let available_data = + AvailableData { pov_block, omitted_validation: OmittedValidationData::default() }; let chunks = obtain_chunks(magnitude as usize, &available_data).unwrap(); diff --git a/polkadot/node/collation-generation/Cargo.toml b/polkadot/node/collation-generation/Cargo.toml index 3b63b08b82..7c07584912 100644 --- a/polkadot/node/collation-generation/Cargo.toml +++ b/polkadot/node/collation-generation/Cargo.toml @@ -19,3 +19,4 @@ parity-scale-codec = { version = "2.3.1", default-features = false, features = [ [dev-dependencies] polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../primitives/test-helpers" } diff --git a/polkadot/node/collation-generation/src/tests.rs b/polkadot/node/collation-generation/src/tests.rs index 5b7667eb94..cf4a6334a1 100644 --- a/polkadot/node/collation-generation/src/tests.rs +++ b/polkadot/node/collation-generation/src/tests.rs @@ -16,6 +16,7 @@ mod handle_new_activations { use super::super::*; + use ::test_helpers::{dummy_hash, dummy_head_data, dummy_validator}; use futures::{ lock::Mutex, task::{Context as FuturesContext, Poll}, @@ -33,13 +34,13 @@ mod handle_new_activations { fn test_collation() -> Collation { Collation { - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: Default::default(), - head_data: Default::default(), + upward_messages: vec![], + horizontal_messages: vec![], + new_validation_code: None, + head_data: dummy_head_data(), proof_of_validity: PoV { block_data: BlockData(Vec::new()) }, - processed_downward_messages: Default::default(), - hrmp_watermark: Default::default(), + processed_downward_messages: 0_u32, + hrmp_watermark: 0_u32.into(), } } @@ -59,7 +60,7 @@ mod handle_new_activations { } fn test_validation_data() -> PersistedValidationData { - let mut persisted_validation_data: PersistedValidationData = Default::default(); + let mut persisted_validation_data = PersistedValidationData::default(); persisted_validation_data.max_pov_size = 1024; persisted_validation_data } @@ -106,7 +107,7 @@ mod handle_new_activations { tx.send(Ok(vec![])).unwrap(); } Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(_hash, RuntimeApiRequest::Validators(tx)))) => { - tx.send(Ok(vec![Default::default(); 3])).unwrap(); + tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); } Some(msg) => panic!("didn't expect any other overseer requests given no availability cores; got {:?}", msg), } @@ -177,13 +178,13 @@ mod handle_new_activations { ), ))) => { overseer_requested_validation_data.lock().await.push(hash); - tx.send(Ok(Default::default())).unwrap(); + tx.send(Ok(None)).unwrap(); }, Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( _hash, RuntimeApiRequest::Validators(tx), ))) => { - tx.send(Ok(vec![Default::default(); 3])).unwrap(); + tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); }, Some(msg) => { panic!("didn't expect any other overseer requests; got {:?}", msg) @@ -254,7 +255,7 @@ mod handle_new_activations { _hash, RuntimeApiRequest::Validators(tx), ))) => { - tx.send(Ok(vec![Default::default(); 3])).unwrap(); + tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); }, Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( _hash, @@ -323,7 +324,7 @@ mod handle_new_activations { collator: config.key.public(), persisted_validation_data_hash: expect_validation_data_hash, pov_hash: expect_pov_hash, - erasure_root: Default::default(), // this isn't something we're checking right now + erasure_root: dummy_hash(), // this isn't something we're checking right now para_head: test_collation().head_data.hash(), validation_code_hash: expect_validation_code_hash, }; diff --git a/polkadot/node/core/approval-voting/Cargo.toml b/polkadot/node/core/approval-voting/Cargo.toml index b8e812cfde..02e1e9fd2a 100644 --- a/polkadot/node/core/approval-voting/Cargo.toml +++ b/polkadot/node/core/approval-voting/Cargo.toml @@ -39,3 +39,4 @@ sp-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } assert_matches = "1.4.0" kvdb-memorydb = "0.10.0" +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/approval-voting/src/approval_checking.rs b/polkadot/node/core/approval-voting/src/approval_checking.rs index d681e67eb8..d41bee800d 100644 --- a/polkadot/node/core/approval-voting/src/approval_checking.rs +++ b/polkadot/node/core/approval-voting/src/approval_checking.rs @@ -457,25 +457,24 @@ pub fn tranches_to_approve( #[cfg(test)] mod tests { use super::*; - - use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0}; + use crate::{approval_db, BTreeMap}; + use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; + use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0, vec::BitVec}; use polkadot_primitives::v1::GroupIndex; - use crate::approval_db; - #[test] fn pending_is_not_approved() { let candidate = approval_db::v1::CandidateEntry { - candidate: Default::default(), + candidate: dummy_candidate_receipt(dummy_hash()), session: 0, - block_assignments: Default::default(), - approvals: Default::default(), + block_assignments: BTreeMap::default(), + approvals: BitVec::default(), } .into(); let approval_entry = approval_db::v1::ApprovalEntry { tranches: Vec::new(), - assignments: Default::default(), + assignments: BitVec::default(), our_assignment: None, our_approval_sig: None, backing_group: GroupIndex(0), @@ -499,9 +498,9 @@ mod tests { #[test] fn exact_takes_only_assignments_up_to() { let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { - candidate: Default::default(), + candidate: dummy_candidate_receipt(dummy_hash()), session: 0, - block_assignments: Default::default(), + block_assignments: BTreeMap::default(), approvals: bitvec![BitOrderLsb0, u8; 0; 10], } .into(); @@ -571,9 +570,9 @@ mod tests { #[test] fn one_honest_node_always_approves() { let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { - candidate: Default::default(), + candidate: dummy_candidate_receipt(dummy_hash()), session: 0, - block_assignments: Default::default(), + block_assignments: BTreeMap::default(), approvals: bitvec![BitOrderLsb0, u8; 0; 10], } .into(); @@ -1031,9 +1030,9 @@ mod tests { let needed_approvals = 3; let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { - candidate: Default::default(), + candidate: dummy_candidate_receipt(dummy_hash()), session: 0, - block_assignments: Default::default(), + block_assignments: BTreeMap::default(), approvals: bitvec![BitOrderLsb0, u8; 0; 3], } .into(); diff --git a/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs index 7ff9bd48fa..e3cb17001a 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs @@ -25,6 +25,8 @@ use kvdb::KeyValueDB; use polkadot_primitives::v1::Id as ParaId; use std::{collections::HashMap, sync::Arc}; +use ::test_helpers::{dummy_candidate_receipt, dummy_candidate_receipt_bad_sig, dummy_hash}; + const DATA_COL: u32 = 0; const NUM_COLUMNS: u32 = 1; @@ -59,7 +61,7 @@ fn make_block_entry( } fn make_candidate(para_id: ParaId, relay_parent: Hash) -> CandidateReceipt { - let mut c = CandidateReceipt::default(); + let mut c = dummy_candidate_receipt(dummy_hash()); c.descriptor.para_id = para_id; c.descriptor.relay_parent = relay_parent; @@ -73,7 +75,7 @@ fn read_write() { let hash_a = Hash::repeat_byte(1); let hash_b = Hash::repeat_byte(2); - let candidate_hash = CandidateReceipt::::default().hash(); + let candidate_hash = dummy_candidate_receipt_bad_sig(dummy_hash(), None).hash(); let range = StoredBlockRange(10, 20); let at_height = vec![hash_a, hash_b]; @@ -82,7 +84,7 @@ fn read_write() { make_block_entry(hash_a, Default::default(), 1, vec![(CoreIndex(0), candidate_hash)]); let candidate_entry = CandidateEntry { - candidate: Default::default(), + candidate: dummy_candidate_receipt_bad_sig(dummy_hash(), None), session: 5, block_assignments: vec![( hash_a, diff --git a/polkadot/node/core/approval-voting/src/criteria.rs b/polkadot/node/core/approval-voting/src/criteria.rs index 21c4bd9f9d..7663ee72da 100644 --- a/polkadot/node/core/approval-voting/src/criteria.rs +++ b/polkadot/node/core/approval-voting/src/criteria.rs @@ -264,7 +264,7 @@ pub(crate) fn compute_assignments( match key { None => { tracing::trace!(target: LOG_TARGET, "No assignment key"); - return Default::default() + return HashMap::new() }, Some(k) => k, } @@ -320,7 +320,7 @@ fn compute_relay_vrf_modulo_assignments( assignments: &mut HashMap, ) { for rvm_sample in 0..config.relay_vrf_modulo_samples { - let mut core = Default::default(); + let mut core = CoreIndex::default(); let maybe_assignment = { // Extra scope to ensure borrowing instead of moving core diff --git a/polkadot/node/core/approval-voting/src/import.rs b/polkadot/node/core/approval-voting/src/import.rs index 111e96f133..7937013882 100644 --- a/polkadot/node/core/approval-voting/src/import.rs +++ b/polkadot/node/core/approval-voting/src/import.rs @@ -575,6 +575,7 @@ pub(crate) async fn handle_new_head( pub(crate) mod tests { use super::*; use crate::approval_db::v1::DbBackend; + use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use assert_matches::assert_matches; use kvdb::KeyValueDB; use merlin::Transcript; @@ -715,7 +716,7 @@ pub(crate) mod tests { let hash = header.hash(); let make_candidate = |para_id| { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt(dummy_hash()); r.descriptor.para_id = para_id; r.descriptor.relay_parent = hash; r @@ -829,7 +830,7 @@ pub(crate) mod tests { let hash = header.hash(); let make_candidate = |para_id| { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt(dummy_hash()); r.descriptor.para_id = para_id; r.descriptor.relay_parent = hash; r @@ -931,7 +932,7 @@ pub(crate) mod tests { let hash = header.hash(); let make_candidate = |para_id| { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt(dummy_hash()); r.descriptor.para_id = para_id; r.descriptor.relay_parent = hash; r @@ -1021,7 +1022,7 @@ pub(crate) mod tests { let hash = header.hash(); let make_candidate = |para_id| { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt(dummy_hash()); r.descriptor.para_id = para_id; r.descriptor.relay_parent = hash; r @@ -1163,7 +1164,7 @@ pub(crate) mod tests { let hash = header.hash(); let make_candidate = |para_id| { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt(dummy_hash()); r.descriptor.para_id = para_id; r.descriptor.relay_parent = hash; r diff --git a/polkadot/node/core/approval-voting/src/tests.rs b/polkadot/node/core/approval-voting/src/tests.rs index af82103932..b746052655 100644 --- a/polkadot/node/core/approval-voting/src/tests.rs +++ b/polkadot/node/core/approval-voting/src/tests.rs @@ -51,6 +51,8 @@ use super::{ }, }; +use ::test_helpers::{dummy_candidate_receipt, dummy_candidate_receipt_bad_sig}; + const SLOT_DURATION_MILLIS: u64 = 5000; #[derive(Clone)] @@ -547,9 +549,8 @@ where } fn make_candidate(para_id: ParaId, hash: &Hash) -> CandidateReceipt { - let mut r = CandidateReceipt::default(); + let mut r = dummy_candidate_receipt_bad_sig(hash.clone(), Some(Default::default())); r.descriptor.para_id = para_id; - r.descriptor.relay_parent = hash.clone(); r } @@ -1132,7 +1133,7 @@ fn subsystem_rejects_approval_if_no_block_entry() { let block_hash = Hash::repeat_byte(0x01); let candidate_index = 0; let validator = ValidatorIndex(0); - let candidate_hash = CandidateReceipt::::default().hash(); + let candidate_hash = dummy_candidate_receipt(block_hash).hash(); let session_index = 1; let rx = check_and_import_approval( @@ -1168,7 +1169,8 @@ fn subsystem_rejects_approval_before_assignment() { let block_hash = Hash::repeat_byte(0x01); let candidate_hash = { - let mut candidate_receipt = CandidateReceipt::::default(); + let mut candidate_receipt = + dummy_candidate_receipt_bad_sig(block_hash, Some(Default::default())); candidate_receipt.descriptor.para_id = 0.into(); candidate_receipt.descriptor.relay_parent = block_hash; candidate_receipt.hash() @@ -1358,7 +1360,8 @@ fn subsystem_accepts_and_imports_approval_after_assignment() { let block_hash = Hash::repeat_byte(0x01); let candidate_hash = { - let mut candidate_receipt = CandidateReceipt::::default(); + let mut candidate_receipt = + dummy_candidate_receipt_bad_sig(block_hash, Some(Default::default())); candidate_receipt.descriptor.para_id = 0.into(); candidate_receipt.descriptor.relay_parent = block_hash; candidate_receipt.hash() @@ -1423,7 +1426,8 @@ fn subsystem_second_approval_import_only_schedules_wakeups() { let block_hash = Hash::repeat_byte(0x01); let candidate_hash = { - let mut candidate_receipt = CandidateReceipt::::default(); + let mut candidate_receipt = + dummy_candidate_receipt_bad_sig(block_hash, Some(Default::default())); candidate_receipt.descriptor.para_id = 0.into(); candidate_receipt.descriptor.relay_parent = block_hash; candidate_receipt.hash() @@ -1886,12 +1890,12 @@ fn subsystem_import_checked_approval_sets_one_block_bit_at_a_time() { let block_hash = Hash::repeat_byte(0x01); let candidate_receipt1 = { - let mut receipt = CandidateReceipt::::default(); + let mut receipt = dummy_candidate_receipt(block_hash); receipt.descriptor.para_id = 1.into(); receipt }; let candidate_receipt2 = { - let mut receipt = CandidateReceipt::::default(); + let mut receipt = dummy_candidate_receipt(block_hash); receipt.descriptor.para_id = 2.into(); receipt }; @@ -2032,9 +2036,8 @@ fn approved_ancestor_test( .iter() .enumerate() .map(|(i, hash)| { - let mut candidate_receipt = CandidateReceipt::::default(); + let mut candidate_receipt = dummy_candidate_receipt(*hash); candidate_receipt.descriptor.para_id = i.into(); - candidate_receipt.descriptor.relay_parent = *hash; candidate_receipt }) .collect(); @@ -2183,7 +2186,7 @@ fn subsystem_process_wakeup_trigger_assignment_launch_approval() { } = test_harness; let block_hash = Hash::repeat_byte(0x01); - let candidate_receipt = CandidateReceipt::::default(); + let candidate_receipt = dummy_candidate_receipt(block_hash); let candidate_hash = candidate_receipt.hash(); let slot = Slot::from(1); let candidate_index = 0; @@ -2317,7 +2320,7 @@ where } = test_harness; let block_hash = Hash::repeat_byte(0x01); - let candidate_receipt = CandidateReceipt::::default(); + let candidate_receipt = dummy_candidate_receipt(block_hash); let candidate_hash = candidate_receipt.hash(); let slot = Slot::from(1); let candidate_index = 0; diff --git a/polkadot/node/core/av-store/Cargo.toml b/polkadot/node/core/av-store/Cargo.toml index f32a616580..7c2bef74f9 100644 --- a/polkadot/node/core/av-store/Cargo.toml +++ b/polkadot/node/core/av-store/Cargo.toml @@ -31,3 +31,4 @@ polkadot-node-subsystem-util = { path = "../../subsystem-util" } polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master" } parking_lot = "0.11.1" +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/av-store/src/tests.rs b/polkadot/node/core/av-store/src/tests.rs index 428ed51aec..bb2ab22bf4 100644 --- a/polkadot/node/core/av-store/src/tests.rs +++ b/polkadot/node/core/av-store/src/tests.rs @@ -21,13 +21,14 @@ use std::convert::TryFrom; use assert_matches::assert_matches; use futures::{channel::oneshot, executor, future, Future}; +use ::test_helpers::TestCandidateBuilder; use parking_lot::Mutex; use polkadot_node_primitives::{AvailableData, BlockData, PoV, Proof}; use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::v1::{ - CandidateDescriptor, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, HeadData, Header, - Id as ParaId, PersistedValidationData, ValidatorId, + CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, HeadData, Header, + PersistedValidationData, ValidatorId, }; use polkadot_subsystem::{ errors::RuntimeApiError, @@ -47,28 +48,6 @@ const TEST_CONFIG: Config = Config { col_data: columns::DATA, col_meta: columns: type VirtualOverseer = test_helpers::TestSubsystemContextHandle; -#[derive(Default)] -struct TestCandidateBuilder { - para_id: ParaId, - pov_hash: Hash, - relay_parent: Hash, - commitments_hash: Hash, -} - -impl TestCandidateBuilder { - fn build(self) -> CandidateReceipt { - CandidateReceipt { - descriptor: CandidateDescriptor { - para_id: self.para_id, - pov_hash: self.pov_hash, - relay_parent: self.relay_parent, - ..Default::default() - }, - commitments_hash: self.commitments_hash, - } - } -} - #[derive(Clone)] struct TestClock { inner: Arc>, diff --git a/polkadot/node/core/backing/Cargo.toml b/polkadot/node/core/backing/Cargo.toml index b4a2ef102b..697634f07d 100644 --- a/polkadot/node/core/backing/Cargo.toml +++ b/polkadot/node/core/backing/Cargo.toml @@ -26,3 +26,4 @@ sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "master futures = { version = "0.3.17", features = ["thread-pool"] } assert_matches = "1.4.0" polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/backing/src/tests.rs b/polkadot/node/core/backing/src/tests.rs index 6c66af0847..c72386171a 100644 --- a/polkadot/node/core/backing/src/tests.rs +++ b/polkadot/node/core/backing/src/tests.rs @@ -15,12 +15,16 @@ // along with Polkadot. If not, see . use super::*; +use ::test_helpers::{ + dummy_candidate_receipt_bad_sig, dummy_collator, dummy_collator_signature, + dummy_committed_candidate_receipt, dummy_hash, dummy_validation_code, +}; use assert_matches::assert_matches; use futures::{future, Future}; use polkadot_node_primitives::{BlockData, InvalidCandidate}; use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_primitives::v1::{ - GroupRotationInfo, HeadData, PersistedValidationData, ScheduledCore, + CollatorId, GroupRotationInfo, HeadData, PersistedValidationData, ScheduledCore, }; use polkadot_subsystem::{ messages::{CollatorProtocolMessage, RuntimeApiMessage, RuntimeApiRequest}, @@ -118,9 +122,9 @@ impl Default for TestState { let validation_data = PersistedValidationData { parent_head: HeadData(vec![7, 8, 9]), - relay_parent_number: Default::default(), + relay_parent_number: 0_u32.into(), max_pov_size: 1024, - relay_parent_storage_root: Default::default(), + relay_parent_storage_root: dummy_hash(), }; Self { @@ -189,9 +193,20 @@ impl TestCandidateBuilder { pov_hash: self.pov_hash, relay_parent: self.relay_parent, erasure_root: self.erasure_root, - ..Default::default() + collator: dummy_collator(), + signature: dummy_collator_signature(), + para_head: dummy_hash(), + validation_code_hash: dummy_validation_code().hash(), + persisted_validation_data_hash: dummy_hash(), + }, + commitments: CandidateCommitments { + head_data: self.head_data, + upward_messages: vec![], + horizontal_messages: vec![], + new_validation_code: None, + processed_downward_messages: 0, + hrmp_watermark: 0_u32, }, - commitments: CandidateCommitments { head_data: self.head_data, ..Default::default() }, } } } @@ -1445,7 +1460,8 @@ fn candidate_backing_reorders_votes() { }; let fake_attestation = |idx: u32| { - let candidate: CommittedCandidateReceipt = Default::default(); + let candidate = + dummy_candidate_receipt_bad_sig(Default::default(), Some(Default::default())); let hash = candidate.hash(); let mut data = vec![0; 64]; data[0..32].copy_from_slice(hash.0.as_bytes()); @@ -1456,7 +1472,7 @@ fn candidate_backing_reorders_votes() { }; let attested = TableAttestedCandidate { - candidate: Default::default(), + candidate: dummy_committed_candidate_receipt(dummy_hash()), validity_votes: vec![ (ValidatorIndex(5), fake_attestation(5)), (ValidatorIndex(3), fake_attestation(3)), diff --git a/polkadot/node/core/bitfield-signing/Cargo.toml b/polkadot/node/core/bitfield-signing/Cargo.toml index e5a2aa551d..db25424fe1 100644 --- a/polkadot/node/core/bitfield-signing/Cargo.toml +++ b/polkadot/node/core/bitfield-signing/Cargo.toml @@ -16,3 +16,4 @@ thiserror = "1.0.30" [dev-dependencies] polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/bitfield-signing/src/tests.rs b/polkadot/node/core/bitfield-signing/src/tests.rs index 194a85051e..d0162d5d70 100644 --- a/polkadot/node/core/bitfield-signing/src/tests.rs +++ b/polkadot/node/core/bitfield-signing/src/tests.rs @@ -18,6 +18,7 @@ use super::*; use futures::{executor::block_on, pin_mut}; use polkadot_node_subsystem::messages::AllMessages; use polkadot_primitives::v1::{CandidateHash, OccupiedCore}; +use test_helpers::dummy_candidate_descriptor; fn occupied_core(para_id: u32, candidate_hash: CandidateHash) -> CoreState { CoreState::Occupied(OccupiedCore { @@ -28,7 +29,7 @@ fn occupied_core(para_id: u32, candidate_hash: CandidateHash) -> CoreState { next_up_on_time_out: None, availability: Default::default(), candidate_hash, - candidate_descriptor: Default::default(), + candidate_descriptor: dummy_candidate_descriptor(Hash::zero()), }) } diff --git a/polkadot/node/core/candidate-validation/Cargo.toml b/polkadot/node/core/candidate-validation/Cargo.toml index 16c7d85008..af66331a9b 100644 --- a/polkadot/node/core/candidate-validation/Cargo.toml +++ b/polkadot/node/core/candidate-validation/Cargo.toml @@ -27,3 +27,4 @@ futures = { version = "0.3.17", features = ["thread-pool"] } assert_matches = "1.4.0" polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/candidate-validation/src/tests.rs b/polkadot/node/core/candidate-validation/src/tests.rs index 74d6fe13db..9eceaa1fe7 100644 --- a/polkadot/node/core/candidate-validation/src/tests.rs +++ b/polkadot/node/core/candidate-validation/src/tests.rs @@ -15,6 +15,7 @@ // along with Polkadot. If not, see . use super::*; +use ::test_helpers::{dummy_hash, make_valid_candidate_descriptor}; use assert_matches::assert_matches; use futures::executor; use polkadot_node_core_pvf::PrepareError; @@ -25,20 +26,6 @@ use polkadot_primitives::v1::{HeadData, UpwardMessage}; use sp_core::testing::TaskExecutor; use sp_keyring::Sr25519Keyring; -fn collator_sign(descriptor: &mut CandidateDescriptor, collator: Sr25519Keyring) { - descriptor.collator = collator.public().into(); - let payload = polkadot_primitives::v1::collator_signature_payload( - &descriptor.relay_parent, - &descriptor.para_id, - &descriptor.persisted_validation_data_hash, - &descriptor.pov_hash, - &descriptor.validation_code_hash, - ); - - descriptor.signature = collator.sign(&payload[..]).into(); - assert!(descriptor.check_collator_signature().is_ok()); -} - #[test] fn correctly_checks_included_assumption() { let validation_data: PersistedValidationData = Default::default(); @@ -48,10 +35,16 @@ fn correctly_checks_included_assumption() { let relay_parent = [2; 32].into(); let para_id = 5.into(); - let mut candidate = CandidateDescriptor::default(); - candidate.relay_parent = relay_parent; - candidate.persisted_validation_data_hash = persisted_validation_data_hash; - candidate.para_id = para_id; + let descriptor = make_valid_candidate_descriptor( + para_id, + relay_parent, + persisted_validation_data_hash, + dummy_hash(), + dummy_hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let pool = TaskExecutor::new(); let (mut ctx, mut ctx_handle) = @@ -59,7 +52,7 @@ fn correctly_checks_included_assumption() { let (check_fut, check_result) = check_assumption_validation_data( ctx.sender(), - &candidate, + &descriptor, OccupiedCoreAssumption::Included, ) .remote_handle(); @@ -114,10 +107,16 @@ fn correctly_checks_timed_out_assumption() { let relay_parent = [2; 32].into(); let para_id = 5.into(); - let mut candidate = CandidateDescriptor::default(); - candidate.relay_parent = relay_parent; - candidate.persisted_validation_data_hash = persisted_validation_data_hash; - candidate.para_id = para_id; + let descriptor = make_valid_candidate_descriptor( + para_id, + relay_parent, + persisted_validation_data_hash, + dummy_hash(), + dummy_hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let pool = TaskExecutor::new(); let (mut ctx, mut ctx_handle) = @@ -125,7 +124,7 @@ fn correctly_checks_timed_out_assumption() { let (check_fut, check_result) = check_assumption_validation_data( ctx.sender(), - &candidate, + &descriptor, OccupiedCoreAssumption::TimedOut, ) .remote_handle(); @@ -178,10 +177,16 @@ fn check_is_bad_request_if_no_validation_data() { let relay_parent = [2; 32].into(); let para_id = 5.into(); - let mut candidate = CandidateDescriptor::default(); - candidate.relay_parent = relay_parent; - candidate.persisted_validation_data_hash = persisted_validation_data_hash; - candidate.para_id = para_id; + let descriptor = make_valid_candidate_descriptor( + para_id, + relay_parent, + persisted_validation_data_hash, + dummy_hash(), + dummy_hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let pool = TaskExecutor::new(); let (mut ctx, mut ctx_handle) = @@ -189,7 +194,7 @@ fn check_is_bad_request_if_no_validation_data() { let (check_fut, check_result) = check_assumption_validation_data( ctx.sender(), - &candidate, + &descriptor, OccupiedCoreAssumption::Included, ) .remote_handle(); @@ -226,10 +231,16 @@ fn check_is_bad_request_if_no_validation_code() { let relay_parent = [2; 32].into(); let para_id = 5.into(); - let mut candidate = CandidateDescriptor::default(); - candidate.relay_parent = relay_parent; - candidate.persisted_validation_data_hash = persisted_validation_data_hash; - candidate.para_id = para_id; + let descriptor = make_valid_candidate_descriptor( + para_id, + relay_parent, + persisted_validation_data_hash, + dummy_hash(), + dummy_hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let pool = TaskExecutor::new(); let (mut ctx, mut ctx_handle) = @@ -237,7 +248,7 @@ fn check_is_bad_request_if_no_validation_code() { let (check_fut, check_result) = check_assumption_validation_data( ctx.sender(), - &candidate, + &descriptor, OccupiedCoreAssumption::TimedOut, ) .remote_handle(); @@ -286,10 +297,16 @@ fn check_does_not_match() { let relay_parent = [2; 32].into(); let para_id = 5.into(); - let mut candidate = CandidateDescriptor::default(); - candidate.relay_parent = relay_parent; - candidate.persisted_validation_data_hash = [3; 32].into(); - candidate.para_id = para_id; + let descriptor = make_valid_candidate_descriptor( + para_id, + relay_parent, + Hash::from([3; 32]), + dummy_hash(), + dummy_hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let pool = TaskExecutor::new(); let (mut ctx, mut ctx_handle) = @@ -297,7 +314,7 @@ fn check_does_not_match() { let (check_fut, check_result) = check_assumption_validation_data( ctx.sender(), - &candidate, + &descriptor, OccupiedCoreAssumption::Included, ) .remote_handle(); @@ -361,11 +378,16 @@ fn candidate_validation_ok_is_ok() { let head_data = HeadData(vec![1, 1, 1]); let validation_code = ValidationCode(vec![2; 16]); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.para_head = head_data.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let check = perform_basic_checks( &descriptor, @@ -412,10 +434,16 @@ fn candidate_validation_bad_return_is_invalid() { let pov = PoV { block_data: BlockData(vec![1; 32]) }; let validation_code = ValidationCode(vec![2; 16]); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let check = perform_basic_checks( &descriptor, @@ -448,10 +476,16 @@ fn candidate_validation_timeout_is_internal_error() { let pov = PoV { block_data: BlockData(vec![1; 32]) }; let validation_code = ValidationCode(vec![2; 16]); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let check = perform_basic_checks( &descriptor, @@ -483,10 +517,16 @@ fn candidate_validation_code_mismatch_is_invalid() { let pov = PoV { block_data: BlockData(vec![1; 32]) }; let validation_code = ValidationCode(vec![2; 16]); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.validation_code_hash = ValidationCode(vec![1; 16]).hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + ValidationCode(vec![1; 16]).hash(), + dummy_hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let check = perform_basic_checks( &descriptor, @@ -523,11 +563,16 @@ fn compressed_code_works() { .map(ValidationCode) .unwrap(); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.para_head = head_data.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let validation_result = WasmValidationResult { head_data, @@ -563,11 +608,16 @@ fn code_decompression_failure_is_invalid() { .map(ValidationCode) .unwrap(); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.para_head = head_data.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let validation_result = WasmValidationResult { head_data, @@ -604,11 +654,16 @@ fn pov_decompression_failure_is_invalid() { let validation_code = ValidationCode(vec![2; 16]); - let mut descriptor = CandidateDescriptor::default(); - descriptor.pov_hash = pov.hash(); - descriptor.para_head = head_data.hash(); - descriptor.validation_code_hash = validation_code.hash(); - collator_sign(&mut descriptor, Sr25519Keyring::Alice); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ); let validation_result = WasmValidationResult { head_data, diff --git a/polkadot/node/core/dispute-coordinator/Cargo.toml b/polkadot/node/core/dispute-coordinator/Cargo.toml index 65f7f21a82..d33f17c2a1 100644 --- a/polkadot/node/core/dispute-coordinator/Cargo.toml +++ b/polkadot/node/core/dispute-coordinator/Cargo.toml @@ -5,12 +5,10 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -bitvec = { version = "0.20.1", default-features = false, features = ["alloc"] } futures = "0.3.17" tracing = "0.1.29" parity-scale-codec = "2" kvdb = "0.10.0" -derive_more = "0.99.17" thiserror = "1.0.30" polkadot-primitives = { path = "../../../primitives" } @@ -27,6 +25,7 @@ sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" } assert_matches = "1.4.0" +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } [features] # If not enabled, the dispute coordinator will do nothing. diff --git a/polkadot/node/core/dispute-coordinator/src/real/db/v1.rs b/polkadot/node/core/dispute-coordinator/src/real/db/v1.rs index 63d06d9101..b7035d593f 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/db/v1.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/db/v1.rs @@ -252,6 +252,7 @@ pub(crate) fn note_current_session( #[cfg(test)] mod tests { use super::*; + use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use polkadot_primitives::v1::{Hash, Id as ParaId}; fn make_db() -> DbBackend { @@ -285,7 +286,7 @@ mod tests { 1, CandidateHash(Hash::repeat_byte(1)), CandidateVotes { - candidate_receipt: Default::default(), + candidate_receipt: dummy_candidate_receipt(dummy_hash()), valid: Vec::new(), invalid: Vec::new(), }, @@ -295,7 +296,7 @@ mod tests { CandidateHash(Hash::repeat_byte(1)), CandidateVotes { candidate_receipt: { - let mut receipt = CandidateReceipt::default(); + let mut receipt = dummy_candidate_receipt(dummy_hash()); receipt.descriptor.para_id = 5.into(); receipt @@ -362,7 +363,7 @@ mod tests { 1, CandidateHash(Hash::repeat_byte(1)), CandidateVotes { - candidate_receipt: Default::default(), + candidate_receipt: dummy_candidate_receipt(dummy_hash()), valid: Vec::new(), invalid: Vec::new(), }, @@ -379,7 +380,7 @@ mod tests { .candidate_receipt .descriptor .para_id, - ParaId::from(0), + ParaId::from(1), ); let mut overlay_db = OverlayedBackend::new(&backend); @@ -388,7 +389,7 @@ mod tests { CandidateHash(Hash::repeat_byte(1)), CandidateVotes { candidate_receipt: { - let mut receipt = CandidateReceipt::default(); + let mut receipt = dummy_candidate_receipt(dummy_hash()); receipt.descriptor.para_id = 5.into(); receipt @@ -427,7 +428,7 @@ mod tests { let very_recent = current_session - 1; let blank_candidate_votes = || CandidateVotes { - candidate_receipt: Default::default(), + candidate_receipt: dummy_candidate_receipt(dummy_hash()), valid: Vec::new(), invalid: Vec::new(), }; diff --git a/polkadot/node/core/dispute-coordinator/src/real/ordering/mod.rs b/polkadot/node/core/dispute-coordinator/src/real/ordering/mod.rs index 80ddce5039..08e79ed987 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/ordering/mod.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/ordering/mod.rs @@ -62,6 +62,7 @@ pub struct OrderingProvider { /// we are already too late. The ordering mechanism here serves to prevent this from happening in /// the first place. #[derive(Copy, Clone)] +#[cfg_attr(test, derive(Debug))] pub struct CandidateComparator { /// Block number of the relay parent. /// @@ -150,7 +151,7 @@ impl OrderingProvider { None => { tracing::warn!( target: LOG_TARGET, - candidate_hash = ?candidate.hash(), + candidate_hash = ?candidate_hash, "Candidate's relay_parent could not be found via chain API, but we saw candidate included?!" ); return Ok(None) diff --git a/polkadot/node/core/dispute-coordinator/src/real/ordering/tests.rs b/polkadot/node/core/dispute-coordinator/src/real/ordering/tests.rs index 50335f22e5..8e10ac9983 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/ordering/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/ordering/tests.rs @@ -22,6 +22,7 @@ use futures::FutureExt; use parity_scale_codec::Encode; use sp_core::testing::TaskExecutor; +use ::test_helpers::{dummy_collator, dummy_collator_signature, dummy_hash}; use polkadot_node_subsystem::{ jaeger, messages::{ @@ -35,8 +36,8 @@ use polkadot_node_subsystem_test_helpers::{ }; use polkadot_node_subsystem_util::reexports::SubsystemContext; use polkadot_primitives::v1::{ - BlakeTwo256, BlockNumber, CandidateEvent, CandidateReceipt, CoreIndex, GroupIndex, Hash, HashT, - HeadData, + BlakeTwo256, BlockNumber, CandidateDescriptor, CandidateEvent, CandidateReceipt, CoreIndex, + GroupIndex, Hash, HashT, HeadData, }; use super::OrderingProvider; @@ -90,12 +91,14 @@ fn launch_virtual_overseer(ctx: &mut impl SubsystemContext, ctx_handle: VirtualO } async fn virtual_overseer(mut ctx_handle: VirtualOverseer) { - let ev = vec![CandidateEvent::CandidateIncluded( - CandidateReceipt::default(), - HeadData::default(), - CoreIndex::from(0), - GroupIndex::from(0), - )]; + let create_ev = |relay_parent: Hash| { + vec![CandidateEvent::CandidateIncluded( + make_candidate_receipt(relay_parent), + HeadData::default(), + CoreIndex::from(0), + GroupIndex::from(0), + )] + }; assert_matches!( ctx_handle.recv().await, @@ -111,17 +114,17 @@ async fn virtual_overseer(mut ctx_handle: VirtualOverseer) { assert_matches!( ctx_handle.recv().await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, + relay_parent, RuntimeApiRequest::CandidateEvents( tx, ) )) => { - tx.send(Ok(ev)).unwrap(); + tx.send(Ok(create_ev(relay_parent))).unwrap(); } ); assert_matches!( ctx_handle.recv().await, - AllMessages::ChainApi(ChainApiMessage::BlockNumber(_, tx)) => { + AllMessages::ChainApi(ChainApiMessage::BlockNumber(_relay_parent, tx)) => { tx.send(Ok(Some(1))).unwrap(); } ); @@ -142,24 +145,39 @@ fn get_block_number_hash(n: BlockNumber) -> Hash { BlakeTwo256::hash(&n.encode()) } +fn make_candidate_receipt(relay_parent: Hash) -> CandidateReceipt { + let zeros = dummy_hash(); + let descriptor = CandidateDescriptor { + para_id: 0.into(), + relay_parent, + collator: dummy_collator(), + persisted_validation_data_hash: zeros, + pov_hash: zeros, + erasure_root: zeros, + signature: dummy_collator_signature(), + para_head: zeros, + validation_code_hash: zeros.into(), + }; + let candidate = CandidateReceipt { descriptor, commitments_hash: zeros }; + candidate +} + #[test] fn ordering_provider_provides_ordering_when_initialized() { + let candidate = make_candidate_receipt(get_block_number_hash(2)); futures::executor::block_on(async { let mut state = TestState::new().await; let r = state .ordering - .candidate_comparator(state.ctx.sender(), &CandidateReceipt::default()) + .candidate_comparator(state.ctx.sender(), &candidate) .await .unwrap(); - assert!(r.is_none()); + assert_matches!(r, None); // After next active leaves update we should have a comparator: state.process_active_leaves_update().await; - let r = state - .ordering - .candidate_comparator(state.ctx.sender(), &CandidateReceipt::default()) - .await - .unwrap(); - assert!(r.is_some()); - assert_eq!(r.unwrap().relay_parent_block_number, 1); + let r = state.ordering.candidate_comparator(state.ctx.sender(), &candidate).await; + assert_matches!(r, Ok(Some(r2)) => { + assert_eq!(r2.relay_parent_block_number, 1); + }); }); } diff --git a/polkadot/node/core/dispute-coordinator/src/real/participation/queues/tests.rs b/polkadot/node/core/dispute-coordinator/src/real/participation/queues/tests.rs index 7618545a1b..45c4dc5ded 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/participation/queues/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/participation/queues/tests.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use assert_matches::assert_matches; -use polkadot_primitives::v1::{BlockNumber, CandidateReceipt, Hash}; +use polkadot_primitives::v1::{BlockNumber, Hash}; use crate::real::ordering::CandidateComparator; @@ -23,7 +24,7 @@ use super::{Error, ParticipationRequest, Queues}; /// Make a `ParticipationRequest` based on the given commitments hash. fn make_participation_request(hash: Hash) -> ParticipationRequest { - let mut receipt = CandidateReceipt::default(); + let mut receipt = dummy_candidate_receipt(dummy_hash()); // make it differ: receipt.commitments_hash = hash; ParticipationRequest::new(receipt, 1, 100) diff --git a/polkadot/node/core/dispute-coordinator/src/real/participation/tests.rs b/polkadot/node/core/dispute-coordinator/src/real/participation/tests.rs index 6d776f456f..75e2baa403 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/participation/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/participation/tests.rs @@ -22,6 +22,9 @@ use std::{sync::Arc, time::Duration}; use sp_core::testing::TaskExecutor; use super::*; +use ::test_helpers::{ + dummy_candidate_commitments, dummy_candidate_receipt_bad_sig, dummy_digest, dummy_hash, +}; use parity_scale_codec::Encode; use polkadot_node_primitives::{AvailableData, BlockData, InvalidCandidate, PoV}; use polkadot_node_subsystem::{ @@ -35,7 +38,9 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers::{ make_subsystem_context, TestSubsystemContext, TestSubsystemContextHandle, }; -use polkadot_primitives::v1::{BlakeTwo256, CandidateCommitments, HashT, Header, ValidationCode}; +use polkadot_primitives::v1::{ + BlakeTwo256, CandidateCommitments, HashT, Header, PersistedValidationData, ValidationCode, +}; type VirtualOverseer = TestSubsystemContextHandle; @@ -62,7 +67,7 @@ async fn participate_with_commitments_hash( commitments_hash: Hash, ) -> Result<()> { let candidate_receipt = { - let mut receipt = CandidateReceipt::default(); + let mut receipt = dummy_candidate_receipt_bad_sig(dummy_hash(), dummy_hash()); receipt.commitments_hash = commitments_hash; receipt }; @@ -82,9 +87,9 @@ async fn activate_leaf( let block_header = Header { parent_hash: BlakeTwo256::hash(&block_number.encode()), number: block_number, - digest: Default::default(), - state_root: Default::default(), - extrinsics_root: Default::default(), + digest: dummy_digest(), + state_root: dummy_hash(), + extrinsics_root: dummy_hash(), }; let block_hash = block_header.hash(); @@ -113,7 +118,7 @@ pub async fn participation_full_happy_path(ctx_handle: &mut VirtualOverseer) { AllMessages::CandidateValidation( CandidateValidationMessage::ValidateFromExhaustive(_, _, _, _, timeout, tx) ) if timeout == APPROVAL_EXECUTION_TIMEOUT => { - tx.send(Ok(ValidationResult::Valid(Default::default(), Default::default()))).unwrap(); + tx.send(Ok(ValidationResult::Valid(dummy_candidate_commitments(None), PersistedValidationData::default()))).unwrap(); }, "overseer did not receive candidate validation message", ); @@ -135,8 +140,10 @@ pub async fn participation_missing_availability(ctx_handle: &mut VirtualOverseer async fn recover_available_data(virtual_overseer: &mut VirtualOverseer) { let pov_block = PoV { block_data: BlockData(Vec::new()) }; - let available_data = - AvailableData { pov: Arc::new(pov_block), validation_data: Default::default() }; + let available_data = AvailableData { + pov: Arc::new(pov_block), + validation_data: PersistedValidationData::default(), + }; assert_matches!( virtual_overseer.recv().await, @@ -456,7 +463,7 @@ fn cast_invalid_vote_if_validation_passes_but_commitments_dont_match() { // this should lead to a commitments hash mismatch commitments.processed_downward_messages = 42; - tx.send(Ok(ValidationResult::Valid(commitments, Default::default()))).unwrap(); + tx.send(Ok(ValidationResult::Valid(commitments, PersistedValidationData::default()))).unwrap(); }, "overseer did not receive candidate validation message", ); @@ -494,7 +501,7 @@ fn cast_valid_vote_if_validation_passes() { AllMessages::CandidateValidation( CandidateValidationMessage::ValidateFromExhaustive(_, _, _, _, timeout, tx) ) if timeout == APPROVAL_EXECUTION_TIMEOUT => { - tx.send(Ok(ValidationResult::Valid(Default::default(), Default::default()))).unwrap(); + tx.send(Ok(ValidationResult::Valid(dummy_candidate_commitments(None), PersistedValidationData::default()))).unwrap(); }, "overseer did not receive candidate validation message", ); diff --git a/polkadot/node/core/dispute-coordinator/src/real/tests.rs b/polkadot/node/core/dispute-coordinator/src/real/tests.rs index bf1b461b97..0303500cf5 100644 --- a/polkadot/node/core/dispute-coordinator/src/real/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/real/tests.rs @@ -44,6 +44,7 @@ use sp_core::testing::TaskExecutor; use sp_keyring::Sr25519Keyring; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; +use ::test_helpers::{dummy_candidate_receipt_bad_sig, dummy_digest, dummy_hash}; use polkadot_node_subsystem::{ jaeger, messages::{AllMessages, BlockDescription, RuntimeApiMessage, RuntimeApiRequest}, @@ -52,7 +53,8 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; use polkadot_primitives::v1::{ BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, CandidateReceipt, Hash, HashT, - Header, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, + Header, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidatorId, + ValidatorIndex, }; use crate::{ @@ -179,9 +181,9 @@ impl TestState { let block_header = Header { parent_hash, number: block_number, - digest: Default::default(), - state_root: Default::default(), - extrinsics_root: Default::default(), + digest: dummy_digest(), + state_root: dummy_hash(), + extrinsics_root: dummy_hash(), }; let block_hash = block_header.hash(); @@ -251,7 +253,11 @@ impl TestState { RuntimeApiRequest::FetchOnChainVotes(tx), )) => { //add some `BackedCandidates` or resolved disputes here as needed - tx.send(Ok(Some(ScrapedOnChainVotes::default()))).unwrap(); + tx.send(Ok(Some(ScrapedOnChainVotes { + session, + backing_validators_per_candidate: Vec::default(), + disputes: MultiDisputeStatementSet::default(), + }))).unwrap(); } ) } @@ -358,14 +364,14 @@ async fn participation_with_distribution( } fn make_valid_candidate_receipt() -> CandidateReceipt { - let mut candidate_receipt = CandidateReceipt::default(); + let mut candidate_receipt = dummy_candidate_receipt_bad_sig(dummy_hash(), dummy_hash()); candidate_receipt.commitments_hash = CandidateCommitments::default().hash(); candidate_receipt } fn make_invalid_candidate_receipt() -> CandidateReceipt { // Commitments hash will be 0, which is not correct: - CandidateReceipt::default() + dummy_candidate_receipt_bad_sig(Default::default(), Some(Default::default())) } #[test] diff --git a/polkadot/node/core/provisioner/Cargo.toml b/polkadot/node/core/provisioner/Cargo.toml index da5b541e0a..96cba550ed 100644 --- a/polkadot/node/core/provisioner/Cargo.toml +++ b/polkadot/node/core/provisioner/Cargo.toml @@ -18,3 +18,4 @@ futures-timer = "3.0.2" sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" } polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/provisioner/src/tests.rs b/polkadot/node/core/provisioner/src/tests.rs index 104a04569f..9e0af0c3a7 100644 --- a/polkadot/node/core/provisioner/src/tests.rs +++ b/polkadot/node/core/provisioner/src/tests.rs @@ -1,4 +1,5 @@ use super::*; +use ::test_helpers::{dummy_candidate_descriptor, dummy_hash}; use bitvec::bitvec; use polkadot_primitives::v1::{OccupiedCore, ScheduledCore}; @@ -10,7 +11,7 @@ pub fn occupied_core(para_id: u32) -> CoreState { time_out_at: 200_u32, next_up_on_time_out: None, availability: bitvec![bitvec::order::Lsb0, u8; 0; 32], - candidate_descriptor: Default::default(), + candidate_descriptor: dummy_candidate_descriptor(dummy_hash()), candidate_hash: Default::default(), }) } @@ -34,13 +35,13 @@ pub fn default_bitvec(n_cores: usize) -> CoreAvailability { } pub fn scheduled_core(id: u32) -> ScheduledCore { - ScheduledCore { para_id: id.into(), ..Default::default() } + ScheduledCore { para_id: id.into(), collator: None } } mod select_availability_bitfields { use super::{super::*, default_bitvec, occupied_core}; use futures::executor::block_on; - use polkadot_primitives::v1::{SigningContext, ValidatorId, ValidatorIndex}; + use polkadot_primitives::v1::{ScheduledCore, SigningContext, ValidatorId, ValidatorIndex}; use sp_application_crypto::AppKey; use sp_keystore::{testing::KeyStore, CryptoStore, SyncCryptoStorePtr}; use std::sync::Arc; @@ -109,8 +110,11 @@ mod select_availability_bitfields { let mut bitvec2 = bitvec.clone(); bitvec2.set(2, true); - let cores = - vec![CoreState::Free, CoreState::Scheduled(Default::default()), occupied_core(2)]; + let cores = vec![ + CoreState::Free, + CoreState::Scheduled(ScheduledCore { para_id: Default::default(), collator: None }), + occupied_core(2), + ]; let bitfields = vec![ block_on(signed_bitfield(&keystore, bitvec0, ValidatorIndex(0))), @@ -189,6 +193,7 @@ mod select_availability_bitfields { mod select_candidates { use super::{super::*, build_occupied_core, default_bitvec, occupied_core, scheduled_core}; + use ::test_helpers::{dummy_candidate_descriptor, dummy_hash}; use polkadot_node_subsystem::messages::{ AllMessages, RuntimeApiMessage, RuntimeApiRequest::{ @@ -197,8 +202,7 @@ mod select_candidates { }; use polkadot_node_subsystem_test_helpers::TestSubsystemSender; use polkadot_primitives::v1::{ - BlockNumber, CandidateCommitments, CandidateDescriptor, CommittedCandidateReceipt, - PersistedValidationData, + BlockNumber, CandidateCommitments, CommittedCandidateReceipt, PersistedValidationData, }; const BLOCK_UNDER_PRODUCTION: BlockNumber = 128; @@ -346,11 +350,10 @@ mod select_candidates { let empty_hash = PersistedValidationData::::default().hash(); + let mut descriptor_template = dummy_candidate_descriptor(dummy_hash()); + descriptor_template.persisted_validation_data_hash = empty_hash; let candidate_template = CandidateReceipt { - descriptor: CandidateDescriptor { - persisted_validation_data_hash: empty_hash, - ..Default::default() - }, + descriptor: descriptor_template, commitments_hash: CandidateCommitments::default().hash(), }; @@ -389,7 +392,7 @@ mod select_candidates { .map(|c| BackedCandidate { candidate: CommittedCandidateReceipt { descriptor: c.descriptor.clone(), - ..Default::default() + commitments: Default::default(), }, validity_votes: Vec::new(), validator_indices: default_bitvec(n_cores), @@ -428,21 +431,21 @@ mod select_candidates { let cores_with_code = [1, 4, 8]; let committed_receipts: Vec<_> = (0..mock_cores.len()) - .map(|i| CommittedCandidateReceipt { - descriptor: CandidateDescriptor { - para_id: i.into(), - persisted_validation_data_hash: empty_hash, - ..Default::default() - }, - commitments: CandidateCommitments { - new_validation_code: if cores_with_code.contains(&i) { - Some(vec![].into()) - } else { - None + .map(|i| { + let mut descriptor = dummy_candidate_descriptor(dummy_hash()); + descriptor.para_id = i.into(); + descriptor.persisted_validation_data_hash = empty_hash; + CommittedCandidateReceipt { + descriptor, + commitments: CandidateCommitments { + new_validation_code: if cores_with_code.contains(&i) { + Some(vec![].into()) + } else { + None + }, + ..Default::default() }, - ..Default::default() - }, - ..Default::default() + } }) .collect(); diff --git a/polkadot/node/core/runtime-api/Cargo.toml b/polkadot/node/core/runtime-api/Cargo.toml index ba0936bb6e..9601f090ba 100644 --- a/polkadot/node/core/runtime-api/Cargo.toml +++ b/polkadot/node/core/runtime-api/Cargo.toml @@ -24,3 +24,4 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } futures = { version = "0.3.17", features = ["thread-pool"] } polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } polkadot-node-primitives = { path = "../../primitives" } +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/core/runtime-api/src/tests.rs b/polkadot/node/core/runtime-api/src/tests.rs index ab21565519..7b50cc5b14 100644 --- a/polkadot/node/core/runtime-api/src/tests.rs +++ b/polkadot/node/core/runtime-api/src/tests.rs @@ -16,9 +16,10 @@ use super::*; +use ::test_helpers::{dummy_committed_candidate_receipt, dummy_validation_code}; use futures::channel::oneshot; use polkadot_node_primitives::{BabeAllowedSlots, BabeEpoch, BabeEpochConfiguration}; -use polkadot_node_subsystem_test_helpers as test_helpers; +use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_primitives::v1::{ AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, @@ -208,7 +209,7 @@ sp_api::mock_impl_runtime_apis! { #[test] fn requests_authorities() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -234,7 +235,7 @@ fn requests_authorities() { #[test] fn requests_validators() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -260,7 +261,7 @@ fn requests_validators() { #[test] fn requests_validator_groups() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -286,7 +287,7 @@ fn requests_validator_groups() { #[test] fn requests_availability_cores() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -312,7 +313,7 @@ fn requests_availability_cores() { #[test] fn requests_persisted_validation_data() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 5.into(); let para_b = 6.into(); @@ -358,7 +359,7 @@ fn requests_persisted_validation_data() { #[test] fn requests_assumed_validation_data() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 5.into(); let para_b = 6.into(); @@ -410,7 +411,7 @@ fn requests_assumed_validation_data() { #[test] fn requests_check_validation_outputs() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let mut runtime_api = MockRuntimeApi::default(); let relay_parent = [1; 32].into(); let para_a = 5.into(); @@ -457,7 +458,7 @@ fn requests_check_validation_outputs() { #[test] fn requests_session_index_for_child() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -481,12 +482,26 @@ fn requests_session_index_for_child() { futures::executor::block_on(future::join(subsystem_task, test_task)); } +fn dummy_session_info() -> SessionInfo { + SessionInfo { + validators: vec![], + discovery_keys: vec![], + assignment_keys: vec![], + validator_groups: vec![], + n_cores: 4u32, + zeroth_delay_tranche_width: 0u32, + relay_vrf_modulo_samples: 0u32, + n_delay_tranches: 2u32, + no_show_slots: 0u32, + needed_approvals: 1u32, + } +} #[test] fn requests_session_info() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let mut runtime_api = MockRuntimeApi::default(); let session_index = 1; - runtime_api.session_info.insert(session_index, Default::default()); + runtime_api.session_info.insert(session_index, dummy_session_info()); let runtime_api = Arc::new(runtime_api); let spawner = sp_core::testing::TaskExecutor::new(); @@ -506,7 +521,7 @@ fn requests_session_info() { }) .await; - assert_eq!(rx.await.unwrap().unwrap(), Some(Default::default())); + assert_eq!(rx.await.unwrap().unwrap(), Some(dummy_session_info())); ctx_handle.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; }; @@ -516,15 +531,16 @@ fn requests_session_info() { #[test] fn requests_validation_code() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 5.into(); let para_b = 6.into(); let spawner = sp_core::testing::TaskExecutor::new(); + let validation_code = dummy_validation_code(); let mut runtime_api = MockRuntimeApi::default(); - runtime_api.validation_code.insert(para_a, Default::default()); + runtime_api.validation_code.insert(para_a, validation_code.clone()); let runtime_api = Arc::new(runtime_api); let subsystem = RuntimeApiSubsystem::new(runtime_api.clone(), Metrics(None), spawner); @@ -541,7 +557,7 @@ fn requests_validation_code() { }) .await; - assert_eq!(rx.await.unwrap().unwrap(), Some(Default::default())); + assert_eq!(rx.await.unwrap().unwrap(), Some(validation_code)); let (tx, rx) = oneshot::channel(); ctx_handle @@ -563,14 +579,17 @@ fn requests_validation_code() { #[test] fn requests_candidate_pending_availability() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 5.into(); let para_b = 6.into(); let spawner = sp_core::testing::TaskExecutor::new(); + let candidate_receipt = dummy_committed_candidate_receipt(relay_parent); let mut runtime_api = MockRuntimeApi::default(); - runtime_api.candidate_pending_availability.insert(para_a, Default::default()); + runtime_api + .candidate_pending_availability + .insert(para_a, candidate_receipt.clone()); let runtime_api = Arc::new(runtime_api); let subsystem = RuntimeApiSubsystem::new(runtime_api.clone(), Metrics(None), spawner); @@ -587,7 +606,7 @@ fn requests_candidate_pending_availability() { }) .await; - assert_eq!(rx.await.unwrap().unwrap(), Some(Default::default())); + assert_eq!(rx.await.unwrap().unwrap(), Some(candidate_receipt)); let (tx, rx) = oneshot::channel(); @@ -610,7 +629,7 @@ fn requests_candidate_pending_availability() { #[test] fn requests_candidate_events() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -636,7 +655,7 @@ fn requests_candidate_events() { #[test] fn requests_dmq_contents() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 5.into(); @@ -684,7 +703,7 @@ fn requests_dmq_contents() { #[test] fn requests_inbound_hrmp_channels_contents() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let relay_parent = [1; 32].into(); let para_a = 99.into(); @@ -741,7 +760,7 @@ fn requests_inbound_hrmp_channels_contents() { #[test] fn requests_validation_code_by_hash() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let spawner = sp_core::testing::TaskExecutor::new(); let (runtime_api, validation_code) = { @@ -784,7 +803,7 @@ fn requests_validation_code_by_hash() { #[test] fn multiple_requests_in_parallel_are_working() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let runtime_api = Arc::new(MockRuntimeApi::default()); let relay_parent = [1; 32].into(); let spawner = sp_core::testing::TaskExecutor::new(); @@ -826,7 +845,7 @@ fn multiple_requests_in_parallel_are_working() { #[test] fn request_babe_epoch() { - let (ctx, mut ctx_handle) = test_helpers::make_subsystem_context(TaskExecutor::new()); + let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new()); let mut runtime_api = MockRuntimeApi::default(); let epoch = BabeEpoch { epoch_index: 100, diff --git a/polkadot/node/network/availability-distribution/Cargo.toml b/polkadot/node/network/availability-distribution/Cargo.toml index c8decbfc0d..3404526741 100644 --- a/polkadot/node/network/availability-distribution/Cargo.toml +++ b/polkadot/node/network/availability-distribution/Cargo.toml @@ -29,3 +29,4 @@ sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "master sc-network = { git = "https://github.com/paritytech/substrate", branch = "master" } futures-timer = "3.0.2" assert_matches = "1.4.0" +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/availability-distribution/src/tests/mock.rs b/polkadot/node/network/availability-distribution/src/tests/mock.rs index fb01e0b2f9..d9e61d9c48 100644 --- a/polkadot/node/network/availability-distribution/src/tests/mock.rs +++ b/polkadot/node/network/availability-distribution/src/tests/mock.rs @@ -27,6 +27,9 @@ use polkadot_primitives::v1::{ GroupIndex, Hash, HeadData, Id as ParaId, OccupiedCore, PersistedValidationData, SessionInfo, ValidatorIndex, }; +use polkadot_primitives_test_helpers::{ + dummy_collator, dummy_collator_signature, dummy_hash, dummy_validation_code, +}; /// Create dummy session info with two validator groups. pub fn make_session_info() -> SessionInfo { @@ -114,7 +117,11 @@ impl TestCandidateBuilder { pov_hash: self.pov_hash, relay_parent: self.relay_parent, erasure_root: self.erasure_root, - ..Default::default() + collator: dummy_collator(), + persisted_validation_data_hash: dummy_hash(), + signature: dummy_collator_signature(), + para_head: dummy_hash(), + validation_code_hash: dummy_validation_code().hash(), }, commitments: CandidateCommitments { head_data: self.head_data, ..Default::default() }, } diff --git a/polkadot/node/network/availability-recovery/Cargo.toml b/polkadot/node/network/availability-recovery/Cargo.toml index c0ceb59ea2..3ac09f2f02 100644 --- a/polkadot/node/network/availability-recovery/Cargo.toml +++ b/polkadot/node/network/availability-recovery/Cargo.toml @@ -31,4 +31,5 @@ sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-network = { git = "https://github.com/paritytech/substrate", branch = "master" } -polkadot-subsystem-testhelpers = { package = "polkadot-node-subsystem-test-helpers", path = "../../subsystem-test-helpers" } +polkadot-subsystem-test-helpers = { package = "polkadot-node-subsystem-test-helpers", path = "../../subsystem-test-helpers" } +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/availability-recovery/src/tests.rs b/polkadot/node/network/availability-recovery/src/tests.rs index 9b545f8fbc..021b7d49a8 100644 --- a/polkadot/node/network/availability-recovery/src/tests.rs +++ b/polkadot/node/network/availability-recovery/src/tests.rs @@ -31,14 +31,15 @@ use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks}; use polkadot_node_primitives::{BlockData, PoV, Proof}; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::v1::{AuthorityDiscoveryId, HeadData, PersistedValidationData}; +use polkadot_primitives_test_helpers::{dummy_candidate_receipt, dummy_hash}; use polkadot_subsystem::{ jaeger, messages::{AllMessages, RuntimeApiMessage, RuntimeApiRequest}, ActivatedLeaf, LeafStatus, }; -use polkadot_subsystem_testhelpers as test_helpers; +use polkadot_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; -type VirtualOverseer = test_helpers::TestSubsystemContextHandle; +type VirtualOverseer = TestSubsystemContextHandle; fn test_harness_fast_path>( test: impl FnOnce(VirtualOverseer, RequestResponseConfig) -> T, @@ -50,7 +51,7 @@ fn test_harness_fast_path, + overseer: &mut TestSubsystemContextHandle, signal: OverseerSignal, ) { delay!(50); @@ -130,7 +131,7 @@ async fn overseer_signal( } async fn overseer_send( - overseer: &mut test_helpers::TestSubsystemContextHandle, + overseer: &mut TestSubsystemContextHandle, msg: AvailabilityRecoveryMessage, ) { tracing::trace!(msg = ?msg, "sending message"); @@ -142,7 +143,7 @@ async fn overseer_send( } async fn overseer_recv( - overseer: &mut test_helpers::TestSubsystemContextHandle, + overseer: &mut TestSubsystemContextHandle, ) -> AllMessages { tracing::trace!("waiting for message ..."); let msg = overseer.recv().timeout(TIMEOUT).await.expect("TIMEOUT is enough to recv."); @@ -212,7 +213,13 @@ impl TestState { discovery_keys: self.validator_authority_id.clone(), // all validators in the same group. validator_groups: vec![(0..self.validators.len()).map(|i| ValidatorIndex(i as _)).collect()], - ..Default::default() + assignment_keys: vec![], + n_cores: 0, + zeroth_delay_tranche_width: 0, + relay_vrf_modulo_samples: 0, + n_delay_tranches: 0, + no_show_slots: 0, + needed_approvals: 0, }))).unwrap(); } ); @@ -416,7 +423,7 @@ impl Default for TestState { let current = Hash::repeat_byte(1); - let mut candidate = CandidateReceipt::default(); + let mut candidate = dummy_candidate_receipt(dummy_hash()); let session_index = 10; @@ -508,7 +515,7 @@ fn availability_is_recovered_from_chunks_if_no_group_provided() { let (tx, rx) = oneshot::channel(); // Test another candidate, send no chunks. - let mut new_candidate = CandidateReceipt::default(); + let mut new_candidate = dummy_candidate_receipt(dummy_hash()); new_candidate.descriptor.relay_parent = test_state.candidate.descriptor.relay_parent; @@ -594,7 +601,7 @@ fn availability_is_recovered_from_chunks_even_if_backing_group_supplied_if_chunk let (tx, rx) = oneshot::channel(); // Test another candidate, send no chunks. - let mut new_candidate = CandidateReceipt::default(); + let mut new_candidate = dummy_candidate_receipt(dummy_hash()); new_candidate.descriptor.relay_parent = test_state.candidate.descriptor.relay_parent; diff --git a/polkadot/node/network/bridge/Cargo.toml b/polkadot/node/network/bridge/Cargo.toml index 750ca560dd..5443a8cb10 100644 --- a/polkadot/node/network/bridge/Cargo.toml +++ b/polkadot/node/network/bridge/Cargo.toml @@ -24,3 +24,4 @@ polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master" } futures-timer = "3" +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/bridge/src/tests.rs b/polkadot/node/network/bridge/src/tests.rs index e3bfa0a32c..3872cac8fc 100644 --- a/polkadot/node/network/bridge/src/tests.rs +++ b/polkadot/node/network/bridge/src/tests.rs @@ -34,6 +34,7 @@ use polkadot_node_subsystem_test_helpers::{ }; use polkadot_node_subsystem_util::metered; use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives_test_helpers::dummy_collator_signature; use polkadot_subsystem::{ jaeger, messages::{ @@ -1158,8 +1159,8 @@ fn send_messages_to_peers() { { let collator_protocol_message = protocol_v1::CollatorProtocolMessage::Declare( Sr25519Keyring::Alice.public().into(), - Default::default(), - Default::default(), + 0_u32.into(), + dummy_collator_signature(), ); let message = diff --git a/polkadot/node/network/collator-protocol/Cargo.toml b/polkadot/node/network/collator-protocol/Cargo.toml index 1501c290e0..46a7f3f7a3 100644 --- a/polkadot/node/network/collator-protocol/Cargo.toml +++ b/polkadot/node/network/collator-protocol/Cargo.toml @@ -33,3 +33,4 @@ sc-network = { git = "https://github.com/paritytech/substrate", branch = "master parity-scale-codec = { version = "2.3.1", features = ["std"] } polkadot-subsystem-testhelpers = { package = "polkadot-node-subsystem-test-helpers", path = "../../subsystem-test-helpers" } +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/collator-protocol/src/collator_side/tests.rs b/polkadot/node/network/collator-protocol/src/collator_side/tests.rs index a506b524ec..e1d6fd093a 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/tests.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/tests.rs @@ -33,9 +33,10 @@ use polkadot_node_network_protocol::{our_view, request_response::IncomingRequest use polkadot_node_primitives::BlockData; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::v1::{ - AuthorityDiscoveryId, CandidateDescriptor, CollatorPair, GroupRotationInfo, ScheduledCore, - SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, + AuthorityDiscoveryId, CollatorPair, GroupRotationInfo, ScheduledCore, SessionIndex, + SessionInfo, ValidatorId, ValidatorIndex, }; +use polkadot_primitives_test_helpers::TestCandidateBuilder; use polkadot_subsystem::{ jaeger, messages::{AllMessages, RuntimeApiMessage, RuntimeApiRequest}, @@ -43,28 +44,6 @@ use polkadot_subsystem::{ }; use polkadot_subsystem_testhelpers as test_helpers; -#[derive(Default)] -struct TestCandidateBuilder { - para_id: ParaId, - pov_hash: Hash, - relay_parent: Hash, - commitments_hash: Hash, -} - -impl TestCandidateBuilder { - fn build(self) -> CandidateReceipt { - CandidateReceipt { - descriptor: CandidateDescriptor { - para_id: self.para_id, - pov_hash: self.pov_hash, - relay_parent: self.relay_parent, - ..Default::default() - }, - commitments_hash: self.commitments_hash, - } - } -} - #[derive(Clone)] struct TestState { para_id: ParaId, @@ -124,7 +103,13 @@ impl Default for TestState { validators: validator_public, discovery_keys, validator_groups, - ..Default::default() + assignment_keys: vec![], + n_cores: 0, + zeroth_delay_tranche_width: 0, + relay_vrf_modulo_samples: 0, + n_delay_tranches: 0, + no_show_slots: 0, + needed_approvals: 0, }, group_rotation_info, validator_peer_id, diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests.rs index e9b184bbfc..5cf2b35280 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests.rs @@ -30,8 +30,11 @@ use polkadot_node_network_protocol::{ use polkadot_node_primitives::BlockData; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::v1::{ - CandidateDescriptor, CollatorPair, CoreState, GroupIndex, GroupRotationInfo, OccupiedCore, - ScheduledCore, ValidatorId, ValidatorIndex, + CollatorPair, CoreState, GroupIndex, GroupRotationInfo, OccupiedCore, ScheduledCore, + ValidatorId, ValidatorIndex, +}; +use polkadot_primitives_test_helpers::{ + dummy_candidate_descriptor, dummy_candidate_receipt_bad_sig, dummy_hash, }; use polkadot_subsystem::messages::{AllMessages, RuntimeApiMessage, RuntimeApiRequest}; use polkadot_subsystem_testhelpers as test_helpers; @@ -89,7 +92,7 @@ impl Default for TestState { group_responsible: GroupIndex(0), candidate_hash: Default::default(), candidate_descriptor: { - let mut d = CandidateDescriptor::default(); + let mut d = dummy_candidate_descriptor(dummy_hash()); d.para_id = chain_ids[1]; d @@ -551,7 +554,8 @@ fn fetch_collations_works() { ); let pov = PoV { block_data: BlockData(vec![]) }; - let mut candidate_a = CandidateReceipt::default(); + let mut candidate_a = + dummy_candidate_receipt_bad_sig(dummy_hash(), Some(Default::default())); candidate_a.descriptor.para_id = test_state.chain_ids[0]; candidate_a.descriptor.relay_parent = test_state.relay_parent; response_channel @@ -643,7 +647,8 @@ fn fetch_collations_works() { .await; let pov = PoV { block_data: BlockData(vec![1]) }; - let mut candidate_a = CandidateReceipt::default(); + let mut candidate_a = + dummy_candidate_receipt_bad_sig(dummy_hash(), Some(Default::default())); candidate_a.descriptor.para_id = test_state.chain_ids[0]; candidate_a.descriptor.relay_parent = second; @@ -767,7 +772,8 @@ fn fetch_next_collation_on_invalid_collation() { .await; let pov = PoV { block_data: BlockData(vec![]) }; - let mut candidate_a = CandidateReceipt::default(); + let mut candidate_a = + dummy_candidate_receipt_bad_sig(dummy_hash(), Some(Default::default())); candidate_a.descriptor.para_id = test_state.chain_ids[0]; candidate_a.descriptor.relay_parent = test_state.relay_parent; response_channel diff --git a/polkadot/node/network/dispute-distribution/Cargo.toml b/polkadot/node/network/dispute-distribution/Cargo.toml index bd4bba81b3..e6ac2bc8cb 100644 --- a/polkadot/node/network/dispute-distribution/Cargo.toml +++ b/polkadot/node/network/dispute-distribution/Cargo.toml @@ -30,3 +30,4 @@ sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "maste futures-timer = "3.0.2" assert_matches = "1.4.0" lazy_static = "1.4.0" +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/dispute-distribution/src/tests/mock.rs b/polkadot/node/network/dispute-distribution/src/tests/mock.rs index 1cca0e2ed0..6ca61f22cf 100644 --- a/polkadot/node/network/dispute-distribution/src/tests/mock.rs +++ b/polkadot/node/network/dispute-distribution/src/tests/mock.rs @@ -33,9 +33,10 @@ use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use polkadot_node_primitives::{DisputeMessage, SignedDisputeStatement}; use polkadot_primitives::v1::{ - AuthorityDiscoveryId, CandidateDescriptor, CandidateHash, CandidateReceipt, Hash, SessionIndex, - SessionInfo, ValidatorId, ValidatorIndex, + AuthorityDiscoveryId, CandidateHash, CandidateReceipt, Hash, SessionIndex, SessionInfo, + ValidatorId, ValidatorIndex, }; +use polkadot_primitives_test_helpers::dummy_candidate_descriptor; pub const MOCK_SESSION_INDEX: SessionIndex = 1; pub const MOCK_NEXT_SESSION_INDEX: SessionIndex = 2; @@ -77,7 +78,14 @@ pub static ref MOCK_SESSION_INFO: SessionInfo = .iter() .map(|k| MOCK_VALIDATORS_DISCOVERY_KEYS.get(&k).unwrap().clone()) .collect(), - ..Default::default() + assignment_keys: vec![], + validator_groups: vec![], + n_cores: 0, + zeroth_delay_tranche_width: 0, + relay_vrf_modulo_samples: 0, + n_delay_tranches: 0, + no_show_slots: 0, + needed_approvals: 0, }; /// `SessionInfo` for the second session. (No more validators, but two more authorities. @@ -88,13 +96,21 @@ pub static ref MOCK_NEXT_SESSION_INFO: SessionInfo = .iter() .map(|k| MOCK_VALIDATORS_DISCOVERY_KEYS.get(&k).unwrap().clone()) .collect(), - ..Default::default() + validators: vec![], + assignment_keys: vec![], + validator_groups: vec![], + n_cores: 0, + zeroth_delay_tranche_width: 0, + relay_vrf_modulo_samples: 0, + n_delay_tranches: 0, + no_show_slots: 0, + needed_approvals: 0, }; } pub fn make_candidate_receipt(relay_parent: Hash) -> CandidateReceipt { CandidateReceipt { - descriptor: CandidateDescriptor { relay_parent, ..Default::default() }, + descriptor: dummy_candidate_descriptor(relay_parent), commitments_hash: Hash::random(), } } diff --git a/polkadot/node/network/statement-distribution/Cargo.toml b/polkadot/node/network/statement-distribution/Cargo.toml index 2d134294b0..75742accc7 100644 --- a/polkadot/node/network/statement-distribution/Cargo.toml +++ b/polkadot/node/network/statement-distribution/Cargo.toml @@ -32,3 +32,4 @@ sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "master sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-network = { git = "https://github.com/paritytech/substrate", branch = "master" } futures-timer = "3.0.2" +polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } diff --git a/polkadot/node/network/statement-distribution/src/tests.rs b/polkadot/node/network/statement-distribution/src/tests.rs index adc423f57f..afe1d59f02 100644 --- a/polkadot/node/network/statement-distribution/src/tests.rs +++ b/polkadot/node/network/statement-distribution/src/tests.rs @@ -28,7 +28,8 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::Statement; use polkadot_node_subsystem_test_helpers::mock::make_ferdie_keystore; -use polkadot_primitives::v1::{CommittedCandidateReceipt, SessionInfo, ValidationCode}; +use polkadot_primitives::v1::{SessionInfo, ValidationCode}; +use polkadot_primitives_test_helpers::{dummy_committed_candidate_receipt, dummy_hash}; use polkadot_subsystem::{ jaeger, messages::{RuntimeApiMessage, RuntimeApiRequest}, @@ -53,21 +54,21 @@ fn active_head_accepts_only_2_seconded_per_validator() { let signing_context = SigningContext { parent_hash, session_index }; let candidate_a = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = parent_hash; c.descriptor.para_id = 1.into(); c }; let candidate_b = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = parent_hash; c.descriptor.para_id = 2.into(); c }; let candidate_c = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = parent_hash; c.descriptor.para_id = 3.into(); c @@ -369,7 +370,7 @@ fn peer_view_update_sends_messages() { let hash_c = Hash::repeat_byte(3); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_c; c.descriptor.para_id = 1.into(); c @@ -547,7 +548,7 @@ fn circulated_statement_goes_to_all_peers_with_view() { let hash_c = Hash::repeat_byte(3); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_b; c.descriptor.para_id = 1.into(); c @@ -677,7 +678,7 @@ fn receiving_from_one_sends_to_another_and_to_candidate_backing() { let hash_a = Hash::repeat_byte(1); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_a; c.descriptor.para_id = 1.into(); c @@ -864,7 +865,7 @@ fn receiving_large_statement_from_one_sends_to_another_and_to_candidate_backing( let hash_b = Hash::repeat_byte(2); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_a; c.descriptor.para_id = 1.into(); c.commitments.new_validation_code = Some(ValidationCode(vec![1, 2, 3])); @@ -1345,7 +1346,7 @@ fn share_prioritizes_backing_group() { let hash_a = Hash::repeat_byte(1); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_a; c.descriptor.para_id = 1.into(); c.commitments.new_validation_code = Some(ValidationCode(vec![1, 2, 3])); @@ -1649,7 +1650,7 @@ fn peer_cant_flood_with_large_statements() { let hash_a = Hash::repeat_byte(1); let candidate = { - let mut c = CommittedCandidateReceipt::default(); + let mut c = dummy_committed_candidate_receipt(dummy_hash()); c.descriptor.relay_parent = hash_a; c.descriptor.para_id = 1.into(); c.commitments.new_validation_code = Some(ValidationCode(vec![1, 2, 3])); diff --git a/polkadot/node/overseer/Cargo.toml b/polkadot/node/overseer/Cargo.toml index 6dda8b4873..66d9f90dd8 100644 --- a/polkadot/node/overseer/Cargo.toml +++ b/polkadot/node/overseer/Cargo.toml @@ -26,6 +26,7 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } futures = { version = "0.3.17", features = ["thread-pool"] } femme = "2.1.1" assert_matches = "1.4.0" +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../primitives/test-helpers" } [features] default = [] diff --git a/polkadot/node/overseer/examples/minimal-example.rs b/polkadot/node/overseer/examples/minimal-example.rs index 41ec666429..966c51f9f2 100644 --- a/polkadot/node/overseer/examples/minimal-example.rs +++ b/polkadot/node/overseer/examples/minimal-example.rs @@ -22,6 +22,7 @@ use futures::{channel::oneshot, pending, pin_mut, select, stream, FutureExt, Str use futures_timer::Delay; use std::time::Duration; +use ::test_helpers::{dummy_candidate_descriptor, dummy_hash}; use polkadot_node_primitives::{BlockData, PoV}; use polkadot_node_subsystem_types::messages::{ CandidateBackingMessage, CandidateValidationMessage, @@ -73,7 +74,7 @@ impl Subsystem1 { let (tx, _) = oneshot::channel(); let msg = CandidateValidationMessage::ValidateFromChainState( - Default::default(), + dummy_candidate_descriptor(dummy_hash()), PoV { block_data: BlockData(Vec::new()) }.into(), Default::default(), tx, diff --git a/polkadot/node/overseer/src/tests.rs b/polkadot/node/overseer/src/tests.rs index 7470028fed..282cc6bebd 100644 --- a/polkadot/node/overseer/src/tests.rs +++ b/polkadot/node/overseer/src/tests.rs @@ -17,6 +17,7 @@ use futures::{executor, pending, pin_mut, poll, select, stream, FutureExt}; use std::{collections::HashMap, sync::atomic, task::Poll}; +use ::test_helpers::{dummy_candidate_descriptor, dummy_candidate_receipt, dummy_hash}; use polkadot_node_network_protocol::{PeerId, UnifiedReputationChange}; use polkadot_node_primitives::{ BlockData, CollationGenerationConfig, CollationResult, DisputeMessage, InvalidDisputeVote, PoV, @@ -110,7 +111,7 @@ where if c < 10 { let (tx, _) = oneshot::channel(); ctx.send_message(CandidateValidationMessage::ValidateFromChainState( - Default::default(), + dummy_candidate_descriptor(dummy_hash()), PoV { block_data: BlockData(Vec::new()) }.into(), Default::default(), tx, @@ -793,9 +794,9 @@ fn test_candidate_validation_msg() -> CandidateValidationMessage { let (sender, _) = oneshot::channel(); let pov = Arc::new(PoV { block_data: BlockData(Vec::new()) }); CandidateValidationMessage::ValidateFromChainState( - Default::default(), + dummy_candidate_descriptor(dummy_hash()), pov, - Default::default(), + Duration::default(), sender, ) } @@ -844,7 +845,7 @@ fn test_statement_distribution_msg() -> StatementDistributionMessage { fn test_availability_recovery_msg() -> AvailabilityRecoveryMessage { let (sender, _) = oneshot::channel(); AvailabilityRecoveryMessage::RecoverAvailableData( - Default::default(), + dummy_candidate_receipt(dummy_hash()), Default::default(), None, sender, @@ -890,7 +891,7 @@ fn test_dispute_coordinator_msg() -> DisputeCoordinatorMessage { fn test_dispute_distribution_msg() -> DisputeDistributionMessage { let dummy_dispute_message = UncheckedDisputeMessage { - candidate_receipt: Default::default(), + candidate_receipt: dummy_candidate_receipt(dummy_hash()), session_index: 0, invalid_vote: InvalidDisputeVote { validator_index: ValidatorIndex(0), diff --git a/polkadot/node/subsystem-util/Cargo.toml b/polkadot/node/subsystem-util/Cargo.toml index c29d161b40..d6977c7470 100644 --- a/polkadot/node/subsystem-util/Cargo.toml +++ b/polkadot/node/subsystem-util/Cargo.toml @@ -37,3 +37,5 @@ futures = { version = "0.3.17", features = ["thread-pool"] } log = "0.4.13" polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } lazy_static = "1.4.0" +polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } + diff --git a/polkadot/node/subsystem-util/src/tests.rs b/polkadot/node/subsystem-util/src/tests.rs index 27a531427e..946485b0ad 100644 --- a/polkadot/node/subsystem-util/src/tests.rs +++ b/polkadot/node/subsystem-util/src/tests.rs @@ -25,6 +25,7 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_test_helpers::{self as test_helpers, make_subsystem_context}; use polkadot_primitives::v1::Hash; +use polkadot_primitives_test_helpers::{dummy_candidate_receipt, dummy_hash}; use std::{ pin::Pin, sync::{ @@ -82,7 +83,7 @@ impl JobTrait for FakeCollatorProtocolJob { sender .send_message(CollatorProtocolMessage::Invalid( Default::default(), - Default::default(), + dummy_candidate_receipt(dummy_hash()), )) .await; } diff --git a/polkadot/parachain/src/primitives.rs b/polkadot/parachain/src/primitives.rs index 1a52a85db6..e3222b6cde 100644 --- a/polkadot/parachain/src/primitives.rs +++ b/polkadot/parachain/src/primitives.rs @@ -41,19 +41,9 @@ pub use polkadot_core_primitives::BlockNumber as RelayChainBlockNumber; /// Parachain head data included in the chain. #[derive( - PartialEq, - Eq, - Clone, - PartialOrd, - Ord, - Encode, - Decode, - RuntimeDebug, - derive_more::From, - TypeInfo, - Default, + PartialEq, Eq, Clone, PartialOrd, Ord, Encode, Decode, RuntimeDebug, derive_more::From, TypeInfo, )] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf, Default))] pub struct HeadData(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec); impl HeadData { @@ -64,9 +54,7 @@ impl HeadData { } /// Parachain validation code. -#[derive( - Default, PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, derive_more::From, TypeInfo, -)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, derive_more::From, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))] pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec); @@ -82,7 +70,7 @@ impl ValidationCode { /// This type is produced by [`ValidationCode::hash`]. /// /// This type makes it easy to enforce that a hash is a validation code hash on the type level. -#[derive(Clone, Copy, Encode, Decode, Default, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)] +#[derive(Clone, Copy, Encode, Decode, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)] #[cfg_attr(feature = "std", derive(MallocSizeOf))] pub struct ValidationCodeHash(Hash); diff --git a/polkadot/primitives/src/v0.rs b/polkadot/primitives/src/v0.rs index 64163d04bd..3ec50cf4eb 100644 --- a/polkadot/primitives/src/v0.rs +++ b/polkadot/primitives/src/v0.rs @@ -107,8 +107,8 @@ impl MallocSizeOf for ValidatorId { } /// Index of the validator is used as a lightweight replacement of the `ValidatorId` when appropriate. -#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo, Debug)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))] +#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf, Debug))] pub struct ValidatorIndex(pub u32); // We should really get https://github.com/paritytech/polkadot/issues/2403 going .. diff --git a/polkadot/primitives/src/v1/mod.rs b/polkadot/primitives/src/v1/mod.rs index c183df37ce..3b6af8c391 100644 --- a/polkadot/primitives/src/v1/mod.rs +++ b/polkadot/primitives/src/v1/mod.rs @@ -327,7 +327,7 @@ fn check_collator_signature>( } /// A unique descriptor of the candidate receipt. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))] pub struct CandidateDescriptor { /// The ID of the para this is a candidate for. @@ -370,7 +370,7 @@ impl> CandidateDescriptor { /// A candidate-receipt. #[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(Debug, Default, MallocSizeOf))] +#[cfg_attr(feature = "std", derive(Debug, MallocSizeOf))] pub struct CandidateReceipt { /// The descriptor of the candidate. pub descriptor: CandidateDescriptor, @@ -395,7 +395,7 @@ impl CandidateReceipt { /// All data pertaining to the execution of a para candidate. #[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(Debug, Default))] +#[cfg_attr(feature = "std", derive(Debug))] pub struct FullCandidateReceipt { /// The inner candidate receipt. pub inner: CandidateReceipt, @@ -407,7 +407,7 @@ pub struct FullCandidateReceipt { } /// A candidate-receipt with commitments directly included. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))] pub struct CommittedCandidateReceipt { /// The descriptor of the candidate. @@ -509,8 +509,8 @@ impl PersistedValidationData { } /// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)] -#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))] +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] +#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf, Default))] pub struct CandidateCommitments { /// Messages destined to be interpreted by the Relay chain itself. pub upward_messages: Vec, @@ -560,7 +560,6 @@ pub type UncheckedSignedAvailabilityBitfields = Vec { /// The candidate referred to. pub candidate: CommittedCandidateReceipt, @@ -669,12 +668,12 @@ impl From for GroupIndex { } /// A claim on authoring the next block for a given parathread. -#[derive(Clone, Encode, Decode, Default, TypeInfo)] +#[derive(Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(PartialEq, Debug))] pub struct ParathreadClaim(pub Id, pub CollatorId); /// An entry tracking a claim to ensure it does not pass the maximum number of retries. -#[derive(Clone, Encode, Decode, Default, TypeInfo)] +#[derive(Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(PartialEq, Debug))] pub struct ParathreadEntry { /// The claim. @@ -819,7 +818,7 @@ impl OccupiedCore { /// Information about a core which is currently occupied. #[derive(Clone, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(Debug, PartialEq, Default, MallocSizeOf))] +#[cfg_attr(feature = "std", derive(Debug, PartialEq, MallocSizeOf))] pub struct ScheduledCore { /// The ID of a para scheduled. pub para_id: Id, @@ -899,7 +898,7 @@ pub enum CandidateEvent { /// Information about validator sets of a session. #[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq, Default, MallocSizeOf))] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] pub struct SessionInfo { /// Validators in canonical ordering. /// @@ -949,7 +948,7 @@ pub struct SessionInfo { /// Scraped runtime backing votes and resolved disputes. #[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq, Default, MallocSizeOf))] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] pub struct ScrapedOnChainVotes { /// The session in which the block was included. pub session: SessionIndex, diff --git a/polkadot/primitives/test-helpers/Cargo.toml b/polkadot/primitives/test-helpers/Cargo.toml new file mode 100644 index 0000000000..6cd01d4043 --- /dev/null +++ b/polkadot/primitives/test-helpers/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "polkadot-primitives-test-helpers" +version = "0.9.13" +authors = ["Parity Technologies "] +edition = "2021" + +[dependencies] +sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master" } +sp-application-crypto = { package = "sp-application-crypto", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" } +polkadot-primitives = { path = "../" } diff --git a/polkadot/primitives/test-helpers/src/lib.rs b/polkadot/primitives/test-helpers/src/lib.rs new file mode 100644 index 0000000000..ccf103d79e --- /dev/null +++ b/polkadot/primitives/test-helpers/src/lib.rs @@ -0,0 +1,226 @@ +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +#![forbid(unused_crate_dependencies)] +#![forbid(unused_extern_crates)] + +//! A set of primitive constructors, to aid in crafting meaningful testcase while reducing repetition. +//! +//! Note that `dummy_` prefixed values are meant to be fillers, that should not matter, and will +//! contain randomness based data. +use polkadot_primitives::v1::{ + CandidateCommitments, CandidateDescriptor, CandidateReceipt, CollatorId, CollatorSignature, + CommittedCandidateReceipt, Hash, HeadData, Id as ParaId, ValidationCode, ValidationCodeHash, + ValidatorId, +}; +use sp_application_crypto::sr25519; +use sp_keyring::Sr25519Keyring; +use sp_runtime::generic::Digest; + +/// Creates a candidate receipt with filler data. +pub fn dummy_candidate_receipt>(relay_parent: H) -> CandidateReceipt { + CandidateReceipt:: { + commitments_hash: dummy_candidate_commitments(dummy_head_data()).hash(), + descriptor: dummy_candidate_descriptor(relay_parent), + } +} + +/// Creates a committed candidate receipt with filler data. +pub fn dummy_committed_candidate_receipt>( + relay_parent: H, +) -> CommittedCandidateReceipt { + CommittedCandidateReceipt:: { + descriptor: dummy_candidate_descriptor::(relay_parent), + commitments: dummy_candidate_commitments(dummy_head_data()), + } +} + +/// Create a candidate receipt with a bogus signature and filler data. Optionally set the commitment +/// hash with the `commitments` arg. +pub fn dummy_candidate_receipt_bad_sig( + relay_parent: Hash, + commitments: impl Into>, +) -> CandidateReceipt { + let commitments_hash = if let Some(commitments) = commitments.into() { + commitments + } else { + dummy_candidate_commitments(dummy_head_data()).hash() + }; + CandidateReceipt:: { + commitments_hash, + descriptor: dummy_candidate_descriptor_bad_sig(relay_parent), + } +} + +/// Create candidate commitments with filler data. +pub fn dummy_candidate_commitments(head_data: impl Into>) -> CandidateCommitments { + CandidateCommitments { + head_data: head_data.into().unwrap_or(dummy_head_data()), + upward_messages: vec![], + new_validation_code: None, + horizontal_messages: vec![], + processed_downward_messages: 0, + hrmp_watermark: 0_u32, + } +} + +/// Create meaningless dummy hash. +pub fn dummy_hash() -> Hash { + Hash::zero() +} + +/// Create meaningless dummy digest. +pub fn dummy_digest() -> Digest { + Digest::default() +} + +/// Create a candidate descriptor with a bogus signature and filler data. +pub fn dummy_candidate_descriptor_bad_sig(relay_parent: Hash) -> CandidateDescriptor { + let zeros = Hash::zero(); + CandidateDescriptor:: { + para_id: 0.into(), + relay_parent, + collator: dummy_collator(), + persisted_validation_data_hash: zeros, + pov_hash: zeros, + erasure_root: zeros, + signature: dummy_collator_signature(), + para_head: zeros, + validation_code_hash: dummy_validation_code().hash(), + } +} + +/// Create a candidate descriptor with filler data. +pub fn dummy_candidate_descriptor>(relay_parent: H) -> CandidateDescriptor { + let collator = sp_keyring::Sr25519Keyring::Ferdie; + let invalid = Hash::zero(); + let descriptor = make_valid_candidate_descriptor( + 1.into(), + relay_parent, + invalid, + invalid, + invalid, + invalid, + invalid, + collator, + ); + descriptor +} + +/// Create meaningless validation code. +pub fn dummy_validation_code() -> ValidationCode { + ValidationCode(vec![1, 2, 3]) +} + +/// Create meaningless head data. +pub fn dummy_head_data() -> HeadData { + HeadData(vec![]) +} + +/// Create a meaningless collator id. +pub fn dummy_collator() -> CollatorId { + CollatorId::from(sr25519::Public::from_raw([0; 32])) +} + +/// Create a meaningless validator id. +pub fn dummy_validator() -> ValidatorId { + ValidatorId::from(sr25519::Public::from_raw([0; 32])) +} + +/// Create a meaningless collator signature. +pub fn dummy_collator_signature() -> CollatorSignature { + CollatorSignature::from(sr25519::Signature([0u8; 64])) +} + +/// Create a new candidate descriptor, and apply a valid signature +/// using the provided `collator` key. +pub fn make_valid_candidate_descriptor>( + para_id: ParaId, + relay_parent: H, + persisted_validation_data_hash: Hash, + pov_hash: Hash, + validation_code_hash: impl Into, + para_head: Hash, + erasure_root: Hash, + collator: Sr25519Keyring, +) -> CandidateDescriptor { + let validation_code_hash = validation_code_hash.into(); + let payload = polkadot_primitives::v1::collator_signature_payload::( + &relay_parent, + ¶_id, + &persisted_validation_data_hash, + &pov_hash, + &validation_code_hash, + ); + + let signature = collator.sign(&payload).into(); + let descriptor = CandidateDescriptor { + para_id, + relay_parent, + collator: collator.public().into(), + persisted_validation_data_hash, + pov_hash, + erasure_root, + signature, + para_head, + validation_code_hash, + }; + + assert!(descriptor.check_collator_signature().is_ok()); + descriptor +} + +/// After manually modifying the candidate descriptor, resign with a defined collator key. +pub fn resign_candidate_descriptor_with_collator>( + descriptor: &mut CandidateDescriptor, + collator: Sr25519Keyring, +) { + descriptor.collator = collator.public().into(); + let payload = polkadot_primitives::v1::collator_signature_payload::( + &descriptor.relay_parent, + &descriptor.para_id, + &descriptor.persisted_validation_data_hash, + &descriptor.pov_hash, + &descriptor.validation_code_hash, + ); + let signature = collator.sign(&payload).into(); + descriptor.signature = signature; +} + +/// Builder for `CandidateReceipt`. +pub struct TestCandidateBuilder { + pub para_id: ParaId, + pub pov_hash: Hash, + pub relay_parent: Hash, + pub commitments_hash: Hash, +} + +impl std::default::Default for TestCandidateBuilder { + fn default() -> Self { + let zeros = Hash::zero(); + Self { para_id: 0.into(), pov_hash: zeros, relay_parent: zeros, commitments_hash: zeros } + } +} + +impl TestCandidateBuilder { + /// Build a `CandidateReceipt`. + pub fn build(self) -> CandidateReceipt { + let mut descriptor = dummy_candidate_descriptor(self.relay_parent); + descriptor.para_id = self.para_id; + descriptor.pov_hash = self.pov_hash; + CandidateReceipt { descriptor, commitments_hash: self.commitments_hash } + } +} diff --git a/polkadot/runtime/common/Cargo.toml b/polkadot/runtime/common/Cargo.toml index a6b693a53c..4b0c8ad2b2 100644 --- a/polkadot/runtime/common/Cargo.toml +++ b/polkadot/runtime/common/Cargo.toml @@ -59,6 +59,7 @@ pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "m sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" } serde_json = "1.0.72" libsecp256k1 = "0.7.0" +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../primitives/test-helpers" } [features] default = ["std"] diff --git a/polkadot/runtime/common/src/assigned_slots.rs b/polkadot/runtime/common/src/assigned_slots.rs index d7d075d9ef..b42c882cdb 100644 --- a/polkadot/runtime/common/src/assigned_slots.rs +++ b/polkadot/runtime/common/src/assigned_slots.rs @@ -543,6 +543,7 @@ mod tests { use super::*; use crate::{assigned_slots, mock::TestRegistrar, slots}; + use ::test_helpers::{dummy_head_data, dummy_validation_code}; use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; @@ -749,8 +750,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(TestRegistrar::::make_parachain(ParaId::from(1))); @@ -769,8 +770,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); // Register lease in current lease period @@ -802,22 +803,22 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(TestRegistrar::::register( 2, ParaId::from(2), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(TestRegistrar::::register( 3, ParaId::from(3), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(AssignedSlots::assign_perm_parachain_slot(Origin::root(), ParaId::from(1),)); @@ -839,8 +840,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_eq!(AssignedSlots::permanent_slot_count(), 0); @@ -910,8 +911,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(TestRegistrar::::make_parachain(ParaId::from(1))); @@ -934,8 +935,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); // Register lease in current lease period @@ -977,8 +978,8 @@ mod tests { assert_ok!(TestRegistrar::::register( n, ParaId::from(n as u32), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(AssignedSlots::assign_temp_parachain_slot( @@ -994,8 +995,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 7, ParaId::from(7), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_noop!( AssignedSlots::assign_temp_parachain_slot( @@ -1016,8 +1017,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_eq!(AssignedSlots::temporary_slots(ParaId::from(1)), None); @@ -1093,8 +1094,8 @@ mod tests { assert_ok!(TestRegistrar::::register( n, ParaId::from(n as u32), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(AssignedSlots::assign_temp_parachain_slot( @@ -1216,8 +1217,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(AssignedSlots::assign_perm_parachain_slot(Origin::root(), ParaId::from(1),)); @@ -1242,8 +1243,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code(), )); assert_ok!(AssignedSlots::assign_temp_parachain_slot( diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index 1a20ba1eca..9bf0c69815 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -655,6 +655,7 @@ impl Pallet { mod tests { use super::*; use crate::{auctions, mock::TestRegistrar}; + use ::test_helpers::{dummy_hash, dummy_head_data, dummy_validation_code}; use frame_support::{ assert_noop, assert_ok, assert_storage_noop, dispatch::DispatchError::BadOrigin, @@ -874,26 +875,26 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, 0.into(), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, 1.into(), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, 2.into(), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, 3.into(), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); }); ext @@ -1472,8 +1473,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, 1337.into(), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(Auctions::bid(Origin::signed(1), 1337.into(), 1, 1, 4, 1)); }); @@ -1603,7 +1604,7 @@ mod tests { new_test_ext().execute_with(|| { EndingPeriod::set(30); SampleLength::set(10); - set_last_random(Default::default(), 0); + set_last_random(dummy_hash(), 0); assert_eq!( Auctions::auction_status(System::block_number()), @@ -1673,7 +1674,7 @@ mod tests { AuctionStatus::::VrfDelay(4) ); - set_last_random(Default::default(), 45); + set_last_random(dummy_hash(), 45); run_to_block(45); assert_eq!( Auctions::auction_status(System::block_number()), diff --git a/polkadot/runtime/common/src/crowdloan.rs b/polkadot/runtime/common/src/crowdloan.rs index d54c676646..8307b5cc26 100644 --- a/polkadot/runtime/common/src/crowdloan.rs +++ b/polkadot/runtime/common/src/crowdloan.rs @@ -828,6 +828,7 @@ mod tests { mock::TestRegistrar, traits::{AuctionStatus, OnSwap}, }; + use ::test_helpers::{dummy_head_data, dummy_validation_code}; use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_runtime::{ testing::Header, @@ -1077,8 +1078,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, para, - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); return para } @@ -1220,8 +1221,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1337, ParaId::from(1234), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); let e = BalancesError::::InsufficientBalance; assert_noop!( diff --git a/polkadot/runtime/common/src/slots.rs b/polkadot/runtime/common/src/slots.rs index 81d5f7da85..dc06b674cd 100644 --- a/polkadot/runtime/common/src/slots.rs +++ b/polkadot/runtime/common/src/slots.rs @@ -497,6 +497,7 @@ mod tests { use super::*; use crate::{mock::TestRegistrar, slots}; + use ::test_helpers::{dummy_head_data, dummy_validation_code}; use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; @@ -628,8 +629,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(Slots::lease_out(1.into(), &1, 1, 1, 1)); @@ -659,8 +660,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(Slots::lease_out(1.into(), &1, 6, 1, 1)); @@ -702,8 +703,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert!(Slots::lease_out(1.into(), &1, 6, 1, 1).is_ok()); @@ -752,8 +753,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert!(Slots::lease_out(1.into(), &1, 4, 1, 1).is_ok()); @@ -787,8 +788,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert!(Slots::lease_out(1.into(), &1, 6, 1, 1).is_ok()); @@ -830,8 +831,8 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); let max_num = 5u32; @@ -866,14 +867,14 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, ParaId::from(2), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); run_to_block(20); @@ -897,20 +898,20 @@ mod tests { assert_ok!(TestRegistrar::::register( 1, ParaId::from(1), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, ParaId::from(2), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); assert_ok!(TestRegistrar::::register( 1, ParaId::from(3), - Default::default(), - Default::default() + dummy_head_data(), + dummy_validation_code() )); // We will directly manipulate leases to emulate some kind of failure in the system. diff --git a/polkadot/runtime/kusama/src/weights/runtime_parachains_paras_inherent.rs b/polkadot/runtime/kusama/src/weights/runtime_parachains_paras_inherent.rs index 65d2e72d82..6f162895b8 100644 --- a/polkadot/runtime/kusama/src/weights/runtime_parachains_paras_inherent.rs +++ b/polkadot/runtime/kusama/src/weights/runtime_parachains_paras_inherent.rs @@ -16,7 +16,7 @@ //! Autogenerated weights for `runtime_parachains::paras_inherent` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-02, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("kusama-dev"), DB CACHE: 128 // Executed Command: @@ -74,9 +74,9 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_variable_disputes(v: u32, ) -> Weight { - (282_901_000 as Weight) - // Standard Error: 13_000 - .saturating_add((49_184_000 as Weight).saturating_mul(v as Weight)) + (484_589_000 as Weight) + // Standard Error: 15_000 + .saturating_add((49_300_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(28 as Weight)) .saturating_add(T::DbWeight::get().writes(17 as Weight)) } @@ -110,7 +110,7 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_bitfields() -> Weight { - (256_399_000 as Weight) + (459_040_000 as Weight) .saturating_add(T::DbWeight::get().reads(25 as Weight)) .saturating_add(T::DbWeight::get().writes(16 as Weight)) } @@ -136,7 +136,6 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: ParaScheduler ParathreadQueue (r:1 w:1) // Storage: ParaScheduler Scheduled (r:1 w:1) // Storage: ParaScheduler ValidatorGroups (r:1 w:0) - // Storage: Paras PastCodeMeta (r:1 w:0) // Storage: Paras CurrentCodeHash (r:1 w:0) // Storage: Ump RelayDispatchQueueSize (r:1 w:0) // Storage: Ump NeedsDispatch (r:1 w:1) @@ -146,10 +145,10 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_backed_candidates_variable(v: u32, ) -> Weight { - (319_740_000 as Weight) - // Standard Error: 26_000 - .saturating_add((49_051_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(29 as Weight)) + (1_134_397_000 as Weight) + // Standard Error: 29_000 + .saturating_add((49_193_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(28 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) } // Storage: ParaInherent Included (r:1 w:1) @@ -174,8 +173,9 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: ParaScheduler ParathreadQueue (r:1 w:1) // Storage: ParaScheduler Scheduled (r:1 w:1) // Storage: ParaScheduler ValidatorGroups (r:1 w:0) - // Storage: Paras PastCodeMeta (r:1 w:0) // Storage: Paras CurrentCodeHash (r:1 w:0) + // Storage: Paras FutureCodeHash (r:1 w:0) + // Storage: Paras UpgradeRestrictionSignal (r:1 w:0) // Storage: Ump RelayDispatchQueueSize (r:1 w:0) // Storage: Ump NeedsDispatch (r:1 w:1) // Storage: Ump NextDispatchRoundStartWith (r:1 w:1) @@ -184,8 +184,8 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_backed_candidate_code_upgrade() -> Weight { - (42_221_346_000 as Weight) - .saturating_add(T::DbWeight::get().reads(29 as Weight)) + (43_202_449_000 as Weight) + .saturating_add(T::DbWeight::get().reads(30 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) } } diff --git a/polkadot/runtime/parachains/Cargo.toml b/polkadot/runtime/parachains/Cargo.toml index b57ae12a1b..e36e87987f 100644 --- a/polkadot/runtime/parachains/Cargo.toml +++ b/polkadot/runtime/parachains/Cargo.toml @@ -49,7 +49,7 @@ hex-literal = "0.3.4" keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "master" } frame-support-test = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" } - +test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../primitives/test-helpers"} [features] default = ["std"] diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 2c6eae5374..05059c5373 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -23,13 +23,13 @@ use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use frame_support::pallet_prelude::*; use primitives::v1::{ collator_signature_payload, AvailabilityBitfield, BackedCandidate, CandidateCommitments, - CandidateDescriptor, CandidateHash, CollatorId, CommittedCandidateReceipt, CompactStatement, - CoreIndex, CoreOccupied, DisputeStatement, DisputeStatementSet, GroupIndex, HeadData, - Id as ParaId, InherentData as ParachainsInherentData, InvalidDisputeStatementKind, + CandidateDescriptor, CandidateHash, CollatorId, CollatorSignature, CommittedCandidateReceipt, + CompactStatement, CoreIndex, CoreOccupied, DisputeStatement, DisputeStatementSet, GroupIndex, + HeadData, Id as ParaId, InherentData as ParachainsInherentData, InvalidDisputeStatementKind, PersistedValidationData, SessionIndex, SigningContext, UncheckedSigned, ValidDisputeStatementKind, ValidationCode, ValidatorId, ValidatorIndex, ValidityAttestation, }; -use sp_core::H256; +use sp_core::{sr25519, H256}; use sp_runtime::{ generic::Digest, traits::{Header as HeaderT, One, Zero}, @@ -37,7 +37,7 @@ use sp_runtime::{ }; use sp_std::{collections::btree_map::BTreeMap, convert::TryInto, prelude::Vec, vec}; -fn dummy_validation_code() -> ValidationCode { +fn mock_validation_code() -> ValidationCode { ValidationCode(vec![1, 2, 3]) } @@ -47,7 +47,7 @@ fn dummy_validation_code() -> ValidationCode { /// "features = runtime-benchmarks". fn account(name: &'static str, index: u32, seed: u32) -> AccountId { let entropy = (name, index, seed).using_encoded(sp_io::hashing::blake2_256); - AccountId::decode(&mut &entropy[..]).unwrap_or_default() + AccountId::decode(&mut &entropy[..]).expect("256 bit input is valid. qed.") } /// Create a 32 byte slice based on the given number. @@ -232,6 +232,25 @@ impl BenchBuilder { (para_id, core_idx, group_idx) } + fn mock_head_data() -> HeadData { + let max_head_size = configuration::Pallet::::config().max_head_data_size; + HeadData(vec![0xFF; max_head_size as usize]) + } + + fn candidate_descriptor_mock() -> CandidateDescriptor { + CandidateDescriptor:: { + para_id: 0.into(), + relay_parent: Default::default(), + collator: CollatorId::from(sr25519::Public::from_raw([42u8; 32])), + persisted_validation_data_hash: Default::default(), + pov_hash: Default::default(), + erasure_root: Default::default(), + signature: CollatorSignature::from(sr25519::Signature([42u8; 64])), + para_head: Default::default(), + validation_code_hash: mock_validation_code().hash(), + } + } + /// Create a mock of `CandidatePendingAvailability`. fn candidate_availability_mock( group_idx: GroupIndex, @@ -240,14 +259,14 @@ impl BenchBuilder { availability_votes: BitVec, ) -> inclusion::CandidatePendingAvailability { inclusion::CandidatePendingAvailability::::new( - core_idx, // core - candidate_hash, // hash - Default::default(), // candidate descriptor - availability_votes, // availability votes - Default::default(), // backers - Zero::zero(), // relay parent - One::one(), // relay chain block this was backed in - group_idx, // backing group + core_idx, // core + candidate_hash, // hash + Self::candidate_descriptor_mock(), // candidate descriptor + availability_votes, // availability votes + Default::default(), // backers + Zero::zero(), // relay parent + One::one(), // relay chain block this was backed in + group_idx, // backing group ) } @@ -269,7 +288,14 @@ impl BenchBuilder { candidate_hash, availability_votes, ); - let commitments = CandidateCommitments::::default(); + let commitments = CandidateCommitments:: { + upward_messages: vec![], + horizontal_messages: vec![], + new_validation_code: None, + head_data: Self::mock_head_data(), + processed_downward_messages: 0, + hrmp_watermark: 0u32.into(), + }; inclusion::PendingAvailability::::insert(para_id, candidate_availability); inclusion::PendingAvailabilityCommitments::::insert(¶_id, commitments); } @@ -315,8 +341,8 @@ impl BenchBuilder { paras::Pallet::::schedule_para_initialize( para_id, paras::ParaGenesisArgs { - genesis_head: Default::default(), - validation_code: dummy_validation_code(), + genesis_head: Self::mock_head_data(), + validation_code: mock_validation_code(), parachain: true, }, ) @@ -464,7 +490,7 @@ impl BenchBuilder { let collator_public = CollatorId::generate_pair(None); let header = Self::header(self.block_number.clone()); let relay_parent = header.hash(); - let head_data: HeadData = Default::default(); + let head_data = Self::mock_head_data(); let persisted_validation_data_hash = PersistedValidationData:: { parent_head: head_data.clone(), relay_parent_number: self.relay_parent_number(), @@ -474,7 +500,7 @@ impl BenchBuilder { .hash(); let pov_hash = Default::default(); - let validation_code_hash = dummy_validation_code().hash(); + let validation_code_hash = mock_validation_code().hash(); let payload = collator_signature_payload( &relay_parent, ¶_id, @@ -509,7 +535,7 @@ impl BenchBuilder { upward_messages: Vec::new(), horizontal_messages: Vec::new(), new_validation_code: includes_code_upgrade - .map(|v| ValidationCode(vec![0u8; v as usize])), + .map(|v| ValidationCode(vec![42u8; v as usize])), head_data, processed_downward_messages: 0, hrmp_watermark: self.relay_parent_number(), diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 025f1ae700..8ef66cbc81 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -71,7 +71,7 @@ pub(crate) enum FullCheck { /// A backed candidate pending availability. #[derive(Encode, Decode, PartialEq, TypeInfo)] -#[cfg_attr(test, derive(Debug, Default))] +#[cfg_attr(test, derive(Debug))] pub struct CandidatePendingAvailability { /// The availability core this is assigned to. core: CoreIndex, diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index a717c6b1bf..73d0bb83b6 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -40,6 +40,10 @@ use primitives::{ use sc_keystore::LocalKeystore; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use std::sync::Arc; +use test_helpers::{ + dummy_candidate_descriptor, dummy_collator, dummy_collator_signature, dummy_hash, + dummy_validation_code, +}; fn default_config() -> HostConfiguration { let mut config = HostConfiguration::default(); @@ -58,7 +62,7 @@ pub(crate) fn genesis_config(paras: Vec<(ParaId, bool)>) -> MockGenesisConfig { id, ParaGenesisArgs { genesis_head: Vec::new().into(), - validation_code: Vec::new().into(), + validation_code: dummy_validation_code(), parachain: is_chain, }, ) @@ -238,7 +242,6 @@ pub(crate) async fn sign_bitfield( .unwrap() } -#[derive(Default)] pub(crate) struct TestCandidateBuilder { pub(crate) para_id: ParaId, pub(crate) head_data: HeadData, @@ -251,6 +254,23 @@ pub(crate) struct TestCandidateBuilder { pub(crate) hrmp_watermark: BlockNumber, } +impl std::default::Default for TestCandidateBuilder { + fn default() -> Self { + let zeros = Hash::zero(); + Self { + para_id: 0.into(), + head_data: Default::default(), + para_head_hash: None, + pov_hash: zeros, + relay_parent: zeros, + persisted_validation_data_hash: zeros, + new_validation_code: None, + validation_code: dummy_validation_code(), + hrmp_watermark: 0u32.into(), + } + } +} + impl TestCandidateBuilder { pub(crate) fn build(self) -> CommittedCandidateReceipt { CommittedCandidateReceipt { @@ -261,7 +281,9 @@ impl TestCandidateBuilder { persisted_validation_data_hash: self.persisted_validation_data_hash, validation_code_hash: self.validation_code.hash(), para_head: self.para_head_hash.unwrap_or_else(|| self.head_data.hash()), - ..Default::default() + erasure_root: Default::default(), + signature: dummy_collator_signature(), + collator: dummy_collator(), }, commitments: CandidateCommitments { head_data: self.head_data, @@ -388,7 +410,13 @@ fn bitfield_checks() { p_id, CandidatePendingAvailability { availability_votes: default_availability_votes(), - ..Default::default() + core: Default::default(), + hash: Default::default(), + descriptor: dummy_candidate_descriptor(dummy_hash()), + backers: Default::default(), + relay_parent_number: Default::default(), + backed_in_number: Default::default(), + backing_group: Default::default(), }, ) } diff --git a/polkadot/runtime/parachains/src/initializer.rs b/polkadot/runtime/parachains/src/initializer.rs index d8be40eb56..a7cb23799e 100644 --- a/polkadot/runtime/parachains/src/initializer.rs +++ b/polkadot/runtime/parachains/src/initializer.rs @@ -339,7 +339,8 @@ mod tests { new_test_ext, Configuration, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, }; - use primitives::v1::Id as ParaId; + use primitives::v1::{HeadData, Id as ParaId}; + use test_helpers::dummy_validation_code; use frame_support::{ assert_ok, @@ -426,8 +427,8 @@ mod tests { let mock_genesis = crate::paras::ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: HeadData(vec![4, 5, 6]), + validation_code: dummy_validation_code(), }; new_test_ext(MockGenesisConfig { diff --git a/polkadot/runtime/parachains/src/paras.rs b/polkadot/runtime/parachains/src/paras.rs index ad84b7bc05..3a2f6191f5 100644 --- a/polkadot/runtime/parachains/src/paras.rs +++ b/polkadot/runtime/parachains/src/paras.rs @@ -456,13 +456,20 @@ pub mod pallet { new_code: ValidationCode, ) -> DispatchResult { ensure_root(origin)?; - let prior_code_hash = ::CurrentCodeHash::get(¶).unwrap_or_default(); + let maybe_prior_code_hash = ::CurrentCodeHash::get(¶); let new_code_hash = new_code.hash(); Self::increase_code_ref(&new_code_hash, &new_code); ::CurrentCodeHash::insert(¶, new_code_hash); let now = frame_system::Pallet::::block_number(); - Self::note_past_code(para, now, now, prior_code_hash); + if let Some(prior_code_hash) = maybe_prior_code_hash { + Self::note_past_code(para, now, now, prior_code_hash); + } else { + log::error!( + "Pallet paras storage is inconsistent, prior code not found {:?}", + ¶ + ); + } Self::deposit_event(Event::CurrentCodeUpdated(para)); Ok(()) } @@ -959,8 +966,13 @@ impl Pallet { ::UpgradeGoAheadSignal::remove(&id); // Both should always be `Some` in this case, since a code upgrade is scheduled. - let new_code_hash = FutureCodeHash::::take(&id).unwrap_or_default(); - let prior_code_hash = CurrentCodeHash::::get(&id).unwrap_or_default(); + let new_code_hash = if let Some(new_code_hash) = FutureCodeHash::::take(&id) { + new_code_hash + } else { + log::error!("Missing future code hash for {:?}", &id); + return T::DbWeight::get().reads_writes(3, 1 + 3) + }; + let prior_code_hash = CurrentCodeHash::::get(&id); CurrentCodeHash::::insert(&id, &new_code_hash); let log = ConsensusLog::ParaUpgradeCode(id, new_code_hash); @@ -969,7 +981,12 @@ impl Pallet { // `now` is only used for registering pruning as part of `fn note_past_code` let now = >::block_number(); - let weight = Self::note_past_code(id, expected_at, now, prior_code_hash); + let weight = if let Some(prior_code_hash) = prior_code_hash { + Self::note_past_code(id, expected_at, now, prior_code_hash) + } else { + log::error!("Missing prior code hash for {:?}", &id); + 0 as Weight + }; // add 1 to writes due to heads update. weight + T::DbWeight::get().reads_writes(3, 1 + 3) @@ -1078,6 +1095,7 @@ mod tests { use super::*; use frame_support::{assert_err, assert_ok}; use primitives::v1::BlockNumber; + use test_helpers::{dummy_head_data, dummy_validation_code}; use crate::{ configuration::HostConfiguration, @@ -1195,7 +1213,7 @@ mod tests { 1000.into(), ParaGenesisArgs { parachain: false, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: ValidationCode(vec![]), } ), @@ -1206,7 +1224,7 @@ mod tests { 1000.into(), ParaGenesisArgs { parachain: false, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: ValidationCode(vec![1]), } )); @@ -1221,16 +1239,16 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: dummy_head_data(), + validation_code: dummy_validation_code(), }, ), ( 1u32.into(), ParaGenesisArgs { parachain: false, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: dummy_head_data(), + validation_code: dummy_validation_code(), }, ), ]; @@ -1248,7 +1266,7 @@ mod tests { let id = ParaId::from(0u32); let at_block: BlockNumber = 10; let included_block: BlockNumber = 12; - let validation_code = ValidationCode(vec![1, 2, 3]); + let validation_code = ValidationCode(vec![4, 5, 6]); Paras::increase_code_ref(&validation_code.hash(), &validation_code); ::PastCodeHash::insert(&(id, at_block), &validation_code.hash()); @@ -1289,8 +1307,8 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: dummy_head_data(), + validation_code: dummy_validation_code(), }, )]; @@ -1306,7 +1324,7 @@ mod tests { new_test_ext(genesis_config).execute_with(|| { let id_a = ParaId::from(0u32); - assert_eq!(Paras::para_head(&id_a), Some(Default::default())); + assert_eq!(Paras::para_head(&id_a), Some(dummy_head_data())); Paras::note_new_head(id_a, vec![1, 2, 3].into(), 0); @@ -1322,16 +1340,16 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: dummy_head_data(), + validation_code: dummy_validation_code(), }, ), ( 1u32.into(), ParaGenesisArgs { parachain: false, - genesis_head: Default::default(), - validation_code: Default::default(), + genesis_head: dummy_head_data(), + validation_code: dummy_validation_code(), }, ), ]; @@ -1375,7 +1393,7 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: original_code.clone(), }, )]; @@ -1482,7 +1500,7 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: original_code.clone(), }, )]; @@ -1570,7 +1588,7 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: vec![1, 2, 3].into(), }, )]; @@ -1625,7 +1643,7 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: original_code.clone(), }, )]; @@ -1808,7 +1826,7 @@ mod tests { 0u32.into(), ParaGenesisArgs { parachain: true, - genesis_head: Default::default(), + genesis_head: dummy_head_data(), validation_code: vec![1, 2, 3].into(), }, )]; diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 519646dab3..2cfd546ff5 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -49,7 +49,7 @@ use crate::{configuration, initializer::SessionChangeNotification, paras}; pub use pallet::*; /// A queued parathread entry, pre-assigned to a core. -#[derive(Encode, Decode, Default, TypeInfo)] +#[derive(Encode, Decode, TypeInfo)] #[cfg_attr(test, derive(PartialEq, Debug))] pub struct QueuedParathread { claim: ParathreadEntry, @@ -57,7 +57,7 @@ pub struct QueuedParathread { } /// The queue of all parathread claims. -#[derive(Encode, Decode, Default, TypeInfo)] +#[derive(Encode, Decode, TypeInfo)] #[cfg_attr(test, derive(PartialEq, Debug))] pub struct ParathreadClaimQueue { queue: Vec, @@ -89,6 +89,12 @@ impl ParathreadClaimQueue { } } +impl Default for ParathreadClaimQueue { + fn default() -> Self { + Self { queue: vec![], next_core_offset: 0 } + } +} + /// Reasons a core might be freed #[derive(Clone, Copy)] pub enum FreedReason { diff --git a/polkadot/runtime/polkadot/src/weights/runtime_parachains_paras_inherent.rs b/polkadot/runtime/polkadot/src/weights/runtime_parachains_paras_inherent.rs index 42f1f48688..4ab5e6cecc 100644 --- a/polkadot/runtime/polkadot/src/weights/runtime_parachains_paras_inherent.rs +++ b/polkadot/runtime/polkadot/src/weights/runtime_parachains_paras_inherent.rs @@ -16,7 +16,7 @@ //! Autogenerated weights for `runtime_parachains::paras_inherent` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-02, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("polkadot-dev"), DB CACHE: 128 // Executed Command: @@ -69,9 +69,9 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_variable_disputes(v: u32, ) -> Weight { - (201_142_000 as Weight) - // Standard Error: 2_000 - .saturating_add((304_000 as Weight).saturating_mul(v as Weight)) + (404_051_000 as Weight) + // Standard Error: 4_000 + .saturating_add((309_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(23 as Weight)) .saturating_add(T::DbWeight::get().writes(14 as Weight)) } @@ -102,7 +102,7 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_bitfields() -> Weight { - (248_756_000 as Weight) + (446_635_000 as Weight) .saturating_add(T::DbWeight::get().reads(23 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) } @@ -126,7 +126,6 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: ParaScheduler ParathreadQueue (r:1 w:1) // Storage: ParaScheduler Scheduled (r:1 w:1) // Storage: ParaScheduler ValidatorGroups (r:1 w:0) - // Storage: Paras PastCodeMeta (r:1 w:0) // Storage: Paras CurrentCodeHash (r:1 w:0) // Storage: Ump RelayDispatchQueueSize (r:1 w:0) // Storage: Ump NeedsDispatch (r:1 w:1) @@ -135,10 +134,10 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_backed_candidates_variable(v: u32, ) -> Weight { - (309_456_000 as Weight) - // Standard Error: 26_000 - .saturating_add((49_003_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(26 as Weight)) + (1_103_699_000 as Weight) + // Standard Error: 29_000 + .saturating_add((49_128_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(25 as Weight)) .saturating_add(T::DbWeight::get().writes(14 as Weight)) } // Storage: ParaInherent Included (r:1 w:1) @@ -161,8 +160,9 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: ParaScheduler ParathreadQueue (r:1 w:1) // Storage: ParaScheduler Scheduled (r:1 w:1) // Storage: ParaScheduler ValidatorGroups (r:1 w:0) - // Storage: Paras PastCodeMeta (r:1 w:0) // Storage: Paras CurrentCodeHash (r:1 w:0) + // Storage: Paras FutureCodeHash (r:1 w:0) + // Storage: Paras UpgradeRestrictionSignal (r:1 w:0) // Storage: Ump RelayDispatchQueueSize (r:1 w:0) // Storage: Ump NeedsDispatch (r:1 w:1) // Storage: Ump NextDispatchRoundStartWith (r:1 w:1) @@ -170,8 +170,8 @@ impl runtime_parachains::paras_inherent::WeightInfo for // Storage: Hrmp HrmpWatermarks (r:0 w:1) // Storage: Paras Heads (r:0 w:1) fn enter_backed_candidate_code_upgrade() -> Weight { - (42_288_295_000 as Weight) - .saturating_add(T::DbWeight::get().reads(26 as Weight)) + (42_700_804_000 as Weight) + .saturating_add(T::DbWeight::get().reads(27 as Weight)) .saturating_add(T::DbWeight::get().writes(14 as Weight)) } }