referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

#![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::{
	vstaging::{
		CandidateDescriptorV2, CandidateReceiptV2, CommittedCandidateReceiptV2, MutateDescriptorV2,
	},
	CandidateCommitments, CandidateDescriptor, CandidateReceipt, CollatorId, CollatorSignature,
	CommittedCandidateReceipt, CoreIndex, Hash, HeadData, Id as ParaId, PersistedValidationData,
	SessionIndex, ValidationCode, ValidationCodeHash, ValidatorId,
};
pub use rand;
use sp_application_crypto::{sr25519, ByteArray};
use sp_keyring::Sr25519Keyring;
use sp_runtime::generic::Digest;

const MAX_POV_SIZE: u32 = 1_000_000;

/// Creates a candidate receipt with filler data.
pub fn dummy_candidate_receipt<H: AsRef<[u8]>>(relay_parent: H) -> CandidateReceipt<H> {
	CandidateReceipt::<H> {
		commitments_hash: dummy_candidate_commitments(dummy_head_data()).hash(),
		descriptor: dummy_candidate_descriptor(relay_parent),
	}
}

/// Creates a v2 candidate receipt with filler data.
pub fn dummy_candidate_receipt_v2<H: AsRef<[u8]> + Copy>(relay_parent: H) -> CandidateReceiptV2<H> {
	CandidateReceiptV2::<H> {
		commitments_hash: dummy_candidate_commitments(dummy_head_data()).hash(),
		descriptor: dummy_candidate_descriptor_v2(relay_parent),
	}
}

/// Creates a committed candidate receipt with filler data.
pub fn dummy_committed_candidate_receipt<H: AsRef<[u8]>>(
	relay_parent: H,
) -> CommittedCandidateReceipt<H> {
	CommittedCandidateReceipt::<H> {
		descriptor: dummy_candidate_descriptor::<H>(relay_parent),
		commitments: dummy_candidate_commitments(dummy_head_data()),
	}
}

/// Creates a v2 committed candidate receipt with filler data.
pub fn dummy_committed_candidate_receipt_v2<H: AsRef<[u8]> + Copy>(
	relay_parent: H,
) -> CommittedCandidateReceiptV2<H> {
	CommittedCandidateReceiptV2 {
		descriptor: dummy_candidate_descriptor_v2::<H>(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<Option<Hash>>,
) -> CandidateReceipt<Hash> {
	let commitments_hash = if let Some(commitments) = commitments.into() {
		commitments
	} else {
		dummy_candidate_commitments(dummy_head_data()).hash()
	};
	CandidateReceipt::<Hash> {
		commitments_hash,
		descriptor: dummy_candidate_descriptor_bad_sig(relay_parent),
	}
}

/// 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_v2_bad_sig(
	relay_parent: Hash,
	commitments: impl Into<Option<Hash>>,
) -> CandidateReceiptV2<Hash> {
	let commitments_hash = if let Some(commitments) = commitments.into() {
		commitments
	} else {
		dummy_candidate_commitments(dummy_head_data()).hash()
	};
	CandidateReceiptV2::<Hash> {
		commitments_hash,
		descriptor: dummy_candidate_descriptor_bad_sig(relay_parent).into(),
	}
}

/// Create candidate commitments with filler data.
pub fn dummy_candidate_commitments(head_data: impl Into<Option<HeadData>>) -> CandidateCommitments {
	CandidateCommitments {
		head_data: head_data.into().unwrap_or(dummy_head_data()),
		upward_messages: vec![].try_into().expect("empty vec fits within bounds"),
		new_validation_code: None,
		horizontal_messages: vec![].try_into().expect("empty vec fits within bounds"),
		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<Hash> {
	let zeros = Hash::zero();
	CandidateDescriptor::<Hash> {
		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<H: AsRef<[u8]>>(relay_parent: H) -> CandidateDescriptor<H> {
	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 a v2 candidate descriptor with filler data.
pub fn dummy_candidate_descriptor_v2<H: AsRef<[u8]> + Copy>(
	relay_parent: H,
) -> CandidateDescriptorV2<H> {
	let invalid = Hash::zero();
	let descriptor = make_valid_candidate_descriptor_v2(
		1.into(),
		relay_parent,
		CoreIndex(1),
		1,
		invalid,
		invalid,
		invalid,
		invalid,
		invalid,
	);
	descriptor
}

/// Create meaningless validation code.
pub fn dummy_validation_code() -> ValidationCode {
	ValidationCode(vec![1, 2, 3, 4, 5, 6, 7, 8, 9])
}

/// Create meaningless head data.
pub fn dummy_head_data() -> HeadData {
	HeadData(vec![])
}

/// Create a meaningless validator id.
pub fn dummy_validator() -> ValidatorId {
	ValidatorId::from(sr25519::Public::default())
}

/// Create a meaningless collator id.
pub fn dummy_collator() -> CollatorId {
	CollatorId::from(sr25519::Public::default())
}

/// Create a meaningless collator signature. It is important to not be 0, as we'd confuse
/// v1 and v2 descriptors.
pub fn dummy_collator_signature() -> CollatorSignature {
	CollatorSignature::from_slice(&mut (0..64).into_iter().collect::<Vec<_>>().as_slice())
		.expect("64 bytes; qed")
}

/// Create a zeroed collator signature.
pub fn zero_collator_signature() -> CollatorSignature {
	CollatorSignature::from(sr25519::Signature::default())
}

/// Create a meaningless persisted validation data.
pub fn dummy_pvd(parent_head: HeadData, relay_parent_number: u32) -> PersistedValidationData {
	PersistedValidationData {
		parent_head,
		relay_parent_number,
		max_pov_size: MAX_POV_SIZE,
		relay_parent_storage_root: dummy_hash(),
	}
}

/// Creates a meaningless signature
pub fn dummy_signature() -> polkadot_primitives::ValidatorSignature {
	sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64])
}

/// Create a meaningless candidate, returning its receipt and PVD.
pub fn make_candidate(
	relay_parent_hash: Hash,
	relay_parent_number: u32,
	para_id: ParaId,
	parent_head: HeadData,
	head_data: HeadData,
	validation_code_hash: ValidationCodeHash,
) -> (CommittedCandidateReceiptV2, PersistedValidationData) {
	let pvd = dummy_pvd(parent_head, relay_parent_number);
	let commitments = CandidateCommitments {
		head_data,
		horizontal_messages: Default::default(),
		upward_messages: Default::default(),
		new_validation_code: None,
		processed_downward_messages: 0,
		hrmp_watermark: relay_parent_number,
	};

	let mut candidate =
		dummy_candidate_receipt_bad_sig(relay_parent_hash, Some(Default::default()));
	candidate.commitments_hash = commitments.hash();
	candidate.descriptor.para_id = para_id;
	candidate.descriptor.persisted_validation_data_hash = pvd.hash();
	candidate.descriptor.validation_code_hash = validation_code_hash;
	let candidate =
		CommittedCandidateReceiptV2 { descriptor: candidate.descriptor.into(), commitments };

	(candidate, pvd)
}

/// Create a meaningless v2 candidate, returning its receipt and PVD.
pub fn make_candidate_v2(
	relay_parent_hash: Hash,
	relay_parent_number: u32,
	para_id: ParaId,
	parent_head: HeadData,
	head_data: HeadData,
	validation_code_hash: ValidationCodeHash,
) -> (CommittedCandidateReceiptV2, PersistedValidationData) {
	let pvd = dummy_pvd(parent_head, relay_parent_number);
	let commitments = CandidateCommitments {
		head_data,
		horizontal_messages: Default::default(),
		upward_messages: Default::default(),
		new_validation_code: None,
		processed_downward_messages: 0,
		hrmp_watermark: relay_parent_number,
	};

	let mut descriptor = dummy_candidate_descriptor_v2(relay_parent_hash);
	descriptor.set_para_id(para_id);
	descriptor.set_persisted_validation_data_hash(pvd.hash());
	descriptor.set_validation_code_hash(validation_code_hash);
	let candidate = CommittedCandidateReceiptV2 { descriptor, commitments };

	(candidate, pvd)
}

/// Create a new candidate descriptor, and apply a valid signature
/// using the provided `collator` key.
pub fn make_valid_candidate_descriptor<H: AsRef<[u8]>>(
	para_id: ParaId,
	relay_parent: H,
	persisted_validation_data_hash: Hash,
	pov_hash: Hash,
	validation_code_hash: impl Into<ValidationCodeHash>,
	para_head: Hash,
	erasure_root: Hash,
	collator: Sr25519Keyring,
) -> CandidateDescriptor<H> {
	let validation_code_hash = validation_code_hash.into();
	let payload = polkadot_primitives::collator_signature_payload::<H>(
		&relay_parent,
		&para_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
}

/// Create a v2 candidate descriptor.
pub fn make_valid_candidate_descriptor_v2<H: AsRef<[u8]> + Copy>(
	para_id: ParaId,
	relay_parent: H,
	core_index: CoreIndex,
	session_index: SessionIndex,
	persisted_validation_data_hash: Hash,
	pov_hash: Hash,
	validation_code_hash: impl Into<ValidationCodeHash>,
	para_head: Hash,
	erasure_root: Hash,
) -> CandidateDescriptorV2<H> {
	let validation_code_hash = validation_code_hash.into();

	let descriptor = CandidateDescriptorV2::new(
		para_id,
		relay_parent,
		core_index,
		session_index,
		persisted_validation_data_hash,
		pov_hash,
		erasure_root,
		para_head,
		validation_code_hash,
	);

	descriptor
}
/// After manually modifying the candidate descriptor, resign with a defined collator key.
pub fn resign_candidate_descriptor_with_collator<H: AsRef<[u8]>>(
	descriptor: &mut CandidateDescriptor<H>,
	collator: Sr25519Keyring,
) {
	descriptor.collator = collator.public().into();
	let payload = polkadot_primitives::collator_signature_payload::<H>(
		&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;
}

/// Extracts validators's public keys (`ValidatorId`) from `Sr25519Keyring`
pub fn validator_pubkeys(val_ids: &[Sr25519Keyring]) -> Vec<ValidatorId> {
	val_ids.iter().map(|v| v.public().into()).collect()
}

/// 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) -> CandidateReceiptV2 {
		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 }.into()
	}
}

/// A special `Rng` that always returns zero for testing something that implied
/// to be random but should not be random in the tests
pub struct AlwaysZeroRng;

impl Default for AlwaysZeroRng {
	fn default() -> Self {
		Self {}
	}
}
impl rand::RngCore for AlwaysZeroRng {
	fn next_u32(&mut self) -> u32 {
		0_u32
	}

	fn next_u64(&mut self) -> u64 {
		0_u64
	}

	fn fill_bytes(&mut self, dest: &mut [u8]) {
		for element in dest.iter_mut() {
			*element = 0_u8;
		}
	}

	fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
		self.fill_bytes(dest);
		Ok(())
	}
}