lib.rs 25.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Copyright 2020 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/>.

//! PoV Distribution Subsystem of Polkadot.
//!
//! This is a gossip implementation of code that is responsible for distributing PoVs
//! among validators.

22
23
24
#![deny(unused_crate_dependencies)]
#![warn(missing_docs)]

25
26
27
use polkadot_primitives::v1::{
	Hash, PoV, CandidateDescriptor, ValidatorId, Id as ParaId, CoreIndex, CoreState,
};
28
use polkadot_subsystem::{
29
	ActiveLeavesUpdate, OverseerSignal, SubsystemContext, SubsystemResult, SubsystemError, Subsystem,
30
	FromOverseer, SpawnedSubsystem,
31
	jaeger,
32
	messages::{
33
		PoVDistributionMessage, AllMessages, NetworkBridgeMessage, NetworkBridgeEvent,
34
	},
35
};
36
37
38
39
40
41
42
43
use polkadot_node_subsystem_util::{
	validator_discovery,
	request_validators_ctx,
	request_validator_groups_ctx,
	request_availability_cores_ctx,
	metrics::{self, prometheus},
};
use polkadot_node_network_protocol::{
44
	peer_set::PeerSet, v1 as protocol_v1, PeerId, OurView, UnifiedReputationChange as Rep,
45
};
46
47
48
49
50
51
52

use futures::prelude::*;
use futures::channel::oneshot;

use std::collections::{hash_map::{Entry, HashMap}, HashSet};
use std::sync::Arc;

53
54
mod error;

55
56
57
#[cfg(test)]
mod tests;

58
59
const COST_APPARENT_FLOOD: Rep = Rep::CostMajor("Peer appears to be flooding us with PoV requests");
const COST_UNEXPECTED_POV: Rep = Rep::CostMajor("Peer sent us an unexpected PoV");
60
const COST_AWAITED_NOT_IN_VIEW: Rep
61
	= Rep::CostMinor("Peer claims to be awaiting something outside of its view");
62

63
64
const BENEFIT_FRESH_POV: Rep = Rep::BenefitMinorFirst("Peer supplied us with an awaited PoV");
const BENEFIT_LATE_POV: Rep = Rep::BenefitMinor("Peer supplied us with an awaited PoV, \
65
66
	but was not the first to do so");

67
68
const LOG_TARGET: &str = "pov_distribution";

69
/// The PoV Distribution Subsystem.
70
71
72
73
pub struct PoVDistribution {
	// Prometheus metrics
	metrics: Metrics,
}
74
75
76
77
78
79
80

impl<C> Subsystem<C> for PoVDistribution
	where C: SubsystemContext<Message = PoVDistributionMessage>
{
	fn start(self, ctx: C) -> SpawnedSubsystem {
		// Swallow error because failure is fatal to the node and we log with more precision
		// within `run`.
81
82
83
		let future = self.run(ctx)
			.map_err(|e| SubsystemError::with_origin("pov-distribution", e))
			.boxed();
84
85
		SpawnedSubsystem {
			name: "pov-distribution-subsystem",
86
			future,
87
		}
88
89
90
	}
}

91
#[derive(Default)]
92
struct State {
93
	/// A state of things going on on a per-relay-parent basis.
94
	relay_parent_state: HashMap<Hash, BlockBasedState>,
95
96

	/// Info on peers.
97
	peer_state: HashMap<PeerId, PeerState>,
98
99

	/// Our own view.
100
	our_view: OurView,
101
102
103
104
105

	/// Connect to relevant groups of validators at different relay parents.
	connection_requests: validator_discovery::ConnectionRequests,

	/// Metrics.
106
	metrics: Metrics,
107
108
109
}

struct BlockBasedState {
110
	known: HashMap<Hash, (Arc<PoV>, protocol_v1::CompressedPoV)>,
111

112
113
114
115
116
	/// All the PoVs we are or were fetching, coupled with channels expecting the data.
	///
	/// This may be an empty list, which indicates that we were once awaiting this PoV but have
	/// received it already.
	fetching: HashMap<Hash, Vec<oneshot::Sender<Arc<PoV>>>>,
117

118
119
120
121
122
123
124
125
126
	n_validators: usize,
}

#[derive(Default)]
struct PeerState {
	/// A set of awaited PoV-hashes for each relay-parent in the peer's view.
	awaited: HashMap<Hash, HashSet<Hash>>,
}

127
128
129
130
131
132
133
134
fn awaiting_message(relay_parent: Hash, awaiting: Vec<Hash>)
	-> protocol_v1::ValidationProtocol
{
	protocol_v1::ValidationProtocol::PoVDistribution(
		protocol_v1::PoVDistributionMessage::Awaiting(relay_parent, awaiting)
	)
}

135
136
137
138
139
fn send_pov_message(
	relay_parent: Hash,
	pov_hash: Hash,
	pov: &protocol_v1::CompressedPoV,
) -> protocol_v1::ValidationProtocol {
140
	protocol_v1::ValidationProtocol::PoVDistribution(
141
		protocol_v1::PoVDistributionMessage::SendPoV(relay_parent, pov_hash, pov.clone())
142
143
144
	)
}

145
146
/// Handles the signal. If successful, returns `true` if the subsystem should conclude,
/// `false` otherwise.
147
#[tracing::instrument(level = "trace", skip(ctx, state), fields(subsystem = LOG_TARGET))]
148
149
150
151
152
153
154
async fn handle_signal(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	signal: OverseerSignal,
) -> SubsystemResult<bool> {
	match signal {
		OverseerSignal::Conclude => Ok(true),
155
		OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { activated, deactivated }) => {
156
157
			let _timer = state.metrics.time_handle_signal();

158
159
160
161
162
			for (relay_parent, span) in activated {
				let _span = span.child_builder("pov-dist")
					.with_stage(jaeger::Stage::PoVDistribution)
					.build();

163
				match request_validators_ctx(relay_parent, ctx).await {
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
					Ok(vals_rx) => {
						let n_validators = match vals_rx.await? {
							Ok(v) => v.len(),
							Err(e) => {
								tracing::warn!(
									target: LOG_TARGET,
									err = ?e,
									"Error fetching validators from runtime API for active leaf",
								);

								// Not adding bookkeeping here might make us behave funny, but we
								// shouldn't take down the node on spurious runtime API errors.
								//
								// and this is "behave funny" as in be bad at our job, but not in any
								// slashable or security-related way.
								continue;
							}
						};

						state.relay_parent_state.insert(relay_parent, BlockBasedState {
							known: HashMap::new(),
							fetching: HashMap::new(),
							n_validators,
						});
					}
189
					Err(e) => {
190
						// continue here also as above.
191
						tracing::warn!(
192
							target: LOG_TARGET,
193
194
							err = ?e,
							"Error fetching validators from runtime API for active leaf",
195
196
						);
					}
197
				}
198
199
200
			}

			for relay_parent in deactivated {
201
				state.connection_requests.remove_all(&relay_parent);
202
203
				state.relay_parent_state.remove(&relay_parent);
			}
204
205
206

			Ok(false)
		}
207
		OverseerSignal::BlockFinalized(..) => Ok(false),
208
209
210
211
212
213
	}
}

/// Notify peers that we are awaiting a given PoV hash.
///
/// This only notifies peers who have the relay parent in their view.
214
#[tracing::instrument(level = "trace", skip(peers, ctx), fields(subsystem = LOG_TARGET))]
215
216
217
218
219
async fn notify_all_we_are_awaiting(
	peers: &mut HashMap<PeerId, PeerState>,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent: Hash,
	pov_hash: Hash,
220
) {
221
222
223
224
225
226
227
228
229
	// We use `awaited` as a proxy for which heads are in the peer's view.
	let peers_to_send: Vec<_> = peers.iter()
		.filter_map(|(peer, state)| if state.awaited.contains_key(&relay_parent) {
			Some(peer.clone())
		} else {
			None
		})
		.collect();

230
231
232
	if peers_to_send.is_empty() {
		return;
	}
233

234
	let payload = awaiting_message(relay_parent, vec![pov_hash]);
235

236
	ctx.send_message(AllMessages::NetworkBridge(NetworkBridgeMessage::SendValidationMessage(
237
238
		peers_to_send,
		payload,
239
	))).await;
240
241
242
}

/// Notify one peer about everything we're awaiting at a given relay-parent.
243
#[tracing::instrument(level = "trace", skip(ctx, relay_parent_state), fields(subsystem = LOG_TARGET))]
244
245
246
247
248
async fn notify_one_we_are_awaiting_many(
	peer: &PeerId,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent_state: &HashMap<Hash, BlockBasedState>,
	relay_parent: Hash,
249
) {
250
251
252
253
254
255
256
	let awaiting_hashes = relay_parent_state.get(&relay_parent).into_iter().flat_map(|s| {
		// Send the peer everything we are fetching at this relay-parent
		s.fetching.iter()
			.filter(|(_, senders)| !senders.is_empty()) // that has not been completed already.
			.map(|(pov_hash, _)| *pov_hash)
	}).collect::<Vec<_>>();

257
258
259
	if awaiting_hashes.is_empty() {
		return;
	}
260

261
	let payload = awaiting_message(relay_parent, awaiting_hashes);
262

263
	ctx.send_message(AllMessages::NetworkBridge(NetworkBridgeMessage::SendValidationMessage(
264
265
		vec![peer.clone()],
		payload,
266
	))).await;
267
268
269
}

/// Distribute a PoV to peers who are awaiting it.
270
#[tracing::instrument(level = "trace", skip(peers, ctx, metrics, pov), fields(subsystem = LOG_TARGET))]
271
272
273
async fn distribute_to_awaiting(
	peers: &mut HashMap<PeerId, PeerState>,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
274
	metrics: &Metrics,
275
276
	relay_parent: Hash,
	pov_hash: Hash,
277
	pov: &protocol_v1::CompressedPoV,
278
) {
279
280
281
282
283
284
285
286
287
288
289
290
291
	// Send to all peers who are awaiting the PoV and have that relay-parent in their view.
	//
	// Also removes it from their awaiting set.
	let peers_to_send: Vec<_> = peers.iter_mut()
		.filter_map(|(peer, state)| state.awaited.get_mut(&relay_parent).and_then(|awaited| {
			if awaited.remove(&pov_hash) {
				Some(peer.clone())
			} else {
				None
			}
		}))
		.collect();

292
	if peers_to_send.is_empty() { return; }
293

294
	let payload = send_pov_message(relay_parent, pov_hash, pov);
295

296
	ctx.send_message(AllMessages::NetworkBridge(NetworkBridgeMessage::SendValidationMessage(
297
298
		peers_to_send,
		payload,
299
	))).await;
300
301

	metrics.on_pov_distributed();
302
303
}

304
305
306
307
308
309
310
/// Connect to relevant validators in case we are not already.
async fn connect_to_relevant_validators(
	connection_requests: &mut validator_discovery::ConnectionRequests,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent: Hash,
	descriptor: &CandidateDescriptor,
) {
311
	let para_id = descriptor.para_id;
312
	if let Ok(Some(relevant_validators)) =
313
		determine_relevant_validators(ctx, relay_parent, para_id).await
314
315
316
317
	{
		// We only need one connection request per (relay_parent, para_id)
		// so here we take this shortcut to avoid calling `connect_to_validators`
		// more than once.
318
		if !connection_requests.contains_request(&relay_parent, para_id) {
319
320
321
322
323
324
325
326
			tracing::debug!(target: LOG_TARGET, validators=?relevant_validators, "connecting to validators");
			match validator_discovery::connect_to_validators(
				ctx,
				relay_parent,
				relevant_validators,
				PeerSet::Validation,
			).await {
				Ok(new_connection_request) => {
327
					connection_requests.put(relay_parent, para_id, new_connection_request);
328
329
330
331
332
333
334
335
336
337
338
339
340
				}
				Err(e) => {
					tracing::debug!(
						target: LOG_TARGET,
						"Failed to create a validator connection request {:?}",
						e,
					);
				}
			}
		}
	}
}

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
/// Get the Id of the Core that is assigned to the para being collated on if any
/// and the total number of cores.
async fn determine_core(
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	para_id: ParaId,
	relay_parent: Hash,
) -> error::Result<Option<(CoreIndex, usize)>> {
	let cores = request_availability_cores_ctx(relay_parent, ctx).await?.await??;

	for (idx, core) in cores.iter().enumerate() {
		if let CoreState::Scheduled(occupied) = core {
			if occupied.para_id == para_id {
				return Ok(Some(((idx as u32).into(), cores.len())));
			}
		}
	}

	Ok(None)
}

/// Figure out a group of validators assigned to a given `ParaId`.
async fn determine_validators_for_core(
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	core_index: CoreIndex,
	num_cores: usize,
	relay_parent: Hash,
) -> error::Result<Option<Vec<ValidatorId>>> {
	let groups = request_validator_groups_ctx(relay_parent, ctx).await?.await??;

	let group_index = groups.1.group_for_core(core_index, num_cores);

	let connect_to_validators = match groups.0.get(group_index.0 as usize) {
		Some(group) => group.clone(),
		None => return Ok(None),
	};

	let validators = request_validators_ctx(relay_parent, ctx).await?.await??;

	let validators = connect_to_validators
		.into_iter()
		.map(|idx| validators[idx as usize].clone())
		.collect();

	Ok(Some(validators))
}

async fn determine_relevant_validators(
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent: Hash,
	para_id: ParaId,
) -> error::Result<Option<Vec<ValidatorId>>> {
	// Determine which core the para_id is assigned to.
	let (core, num_cores) = match determine_core(ctx, para_id, relay_parent).await? {
		Some(core) => core,
		None => {
			tracing::warn!(
				target: LOG_TARGET,
				"Looks like no core is assigned to {:?} at {:?}",
				para_id,
				relay_parent,
			);

			return Ok(None);
		}
	};

	determine_validators_for_core(ctx, core, num_cores, relay_parent).await
}

410
/// Handles a `FetchPoV` message.
411
#[tracing::instrument(level = "trace", skip(ctx, state, response_sender), fields(subsystem = LOG_TARGET))]
412
413
414
415
416
417
async fn handle_fetch(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent: Hash,
	descriptor: CandidateDescriptor,
	response_sender: oneshot::Sender<Arc<PoV>>,
418
) {
419
420
	let _timer = state.metrics.time_handle_fetch();

421
422
	let relay_parent_state = match state.relay_parent_state.get_mut(&relay_parent) {
		Some(s) => s,
423
		None => return,
424
425
	};

426
	if let Some((pov, _)) = relay_parent_state.known.get(&descriptor.pov_hash) {
427
		let _  = response_sender.send(pov.clone());
428
		return;
429
430
431
432
433
434
435
	}

	{
		match relay_parent_state.fetching.entry(descriptor.pov_hash) {
			Entry::Occupied(mut e) => {
				// we are already awaiting this PoV if there is an entry.
				e.get_mut().push(response_sender);
436
				return;
437
438
			}
			Entry::Vacant(e) => {
439
440
				connect_to_relevant_validators(&mut state.connection_requests, ctx, relay_parent, &descriptor).await;
				e.insert(vec![response_sender]);
441
442
443
444
445
			}
		}
	}

	if relay_parent_state.fetching.len() > 2 * relay_parent_state.n_validators {
446
447
448
449
		tracing::warn!(
			relay_parent_state.fetching.len = relay_parent_state.fetching.len(),
			"other subsystems have requested PoV distribution to fetch more PoVs than reasonably expected",
		);
450
		return;
451
452
453
454
455
456
457
458
459
460
461
462
	}

	// Issue an `Awaiting` message to all peers with this in their view.
	notify_all_we_are_awaiting(
		&mut state.peer_state,
		ctx,
		relay_parent,
		descriptor.pov_hash
	).await
}

/// Handles a `DistributePoV` message.
463
#[tracing::instrument(level = "trace", skip(ctx, state, pov), fields(subsystem = LOG_TARGET))]
464
465
466
467
468
469
async fn handle_distribute(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	relay_parent: Hash,
	descriptor: CandidateDescriptor,
	pov: Arc<PoV>,
470
) {
471
472
	let _timer = state.metrics.time_handle_distribute();

473
474
	let relay_parent_state = match state.relay_parent_state.get_mut(&relay_parent) {
		Some(s) => s,
475
		None => return,
476
477
	};

478
479
	connect_to_relevant_validators(&mut state.connection_requests, ctx, relay_parent, &descriptor).await;

480
481
482
483
484
485
486
487
488
489
	if let Some(our_awaited) = relay_parent_state.fetching.get_mut(&descriptor.pov_hash) {
		// Drain all the senders, but keep the entry in the map around intentionally.
		//
		// It signals that we were at one point awaiting this, so we will be able to tell
		// why peers are sending it to us.
		for response_sender in our_awaited.drain(..) {
			let _ = response_sender.send(pov.clone());
		}
	}

490
491
492
493
494
495
496
497
498
499
500
	let encoded_pov = match protocol_v1::CompressedPoV::compress(&*pov) {
		Ok(pov) => pov,
		Err(error) => {
			tracing::debug!(
				target: LOG_TARGET,
				error = ?error,
				"Failed to create `CompressedPov`."
			);
			return
		}
	};
501
502
503
504

	distribute_to_awaiting(
		&mut state.peer_state,
		ctx,
505
		&state.metrics,
506
507
		relay_parent,
		descriptor.pov_hash,
508
509
510
511
		&encoded_pov,
	).await;

	relay_parent_state.known.insert(descriptor.pov_hash, (pov, encoded_pov));
512
513
514
}

/// Report a reputation change for a peer.
515
#[tracing::instrument(level = "trace", skip(ctx), fields(subsystem = LOG_TARGET))]
516
517
518
519
async fn report_peer(
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	peer: PeerId,
	rep: Rep,
520
) {
521
522
523
524
	ctx.send_message(AllMessages::NetworkBridge(NetworkBridgeMessage::ReportPeer(peer, rep))).await
}

/// Handle a notification from a peer that they are awaiting some PoVs.
525
#[tracing::instrument(level = "trace", skip(ctx, state), fields(subsystem = LOG_TARGET))]
526
527
528
529
530
531
async fn handle_awaiting(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	peer: PeerId,
	relay_parent: Hash,
	pov_hashes: Vec<Hash>,
532
) {
533
	if !state.our_view.contains(&relay_parent) {
534
535
		report_peer(ctx, peer, COST_AWAITED_NOT_IN_VIEW).await;
		return;
536
537
538
539
	}

	let relay_parent_state = match state.relay_parent_state.get_mut(&relay_parent) {
		None => {
540
			tracing::warn!("PoV Distribution relay parent state out-of-sync with our view");
541
			return;
542
543
544
545
546
547
548
549
		}
		Some(s) => s,
	};

	let peer_awaiting = match
		state.peer_state.get_mut(&peer).and_then(|s| s.awaited.get_mut(&relay_parent))
	{
		None => {
550
551
			report_peer(ctx, peer, COST_AWAITED_NOT_IN_VIEW).await;
			return;
552
553
554
555
556
557
558
559
560
		}
		Some(a) => a,
	};

	let will_be_awaited = peer_awaiting.len() + pov_hashes.len();
	if will_be_awaited <= 2 * relay_parent_state.n_validators {
		for pov_hash in pov_hashes {
			// For all requested PoV hashes, if we have it, we complete the request immediately.
			// Otherwise, we note that the peer is awaiting the PoV.
561
562
563
			if let Some((_, ref pov)) = relay_parent_state.known.get(&pov_hash) {
				let payload = send_pov_message(relay_parent, pov_hash, pov);

564
565
				ctx.send_message(AllMessages::NetworkBridge(
					NetworkBridgeMessage::SendValidationMessage(vec![peer.clone()], payload)
566
				)).await;
567
568
569
570
571
			} else {
				peer_awaiting.insert(pov_hash);
			}
		}
	} else {
572
		report_peer(ctx, peer, COST_APPARENT_FLOOD).await;
573
574
575
576
577
578
	}
}

/// Handle an incoming PoV from our peer. Reports them if unexpected, rewards them if not.
///
/// Completes any requests awaiting that PoV.
579
#[tracing::instrument(level = "trace", skip(ctx, state, encoded_pov), fields(subsystem = LOG_TARGET))]
580
581
582
583
584
585
async fn handle_incoming_pov(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
	peer: PeerId,
	relay_parent: Hash,
	pov_hash: Hash,
586
	encoded_pov: protocol_v1::CompressedPoV,
587
) {
588
	let relay_parent_state = match state.relay_parent_state.get_mut(&relay_parent) {
589
		None => {
590
591
			report_peer(ctx, peer, COST_UNEXPECTED_POV).await;
			return;
592
593
594
595
		},
		Some(r) => r,
	};

596
597
598
599
600
601
602
603
604
605
606
607
	let pov = match encoded_pov.decompress() {
		Ok(pov) => pov,
		Err(error) => {
			tracing::debug!(
				target: LOG_TARGET,
				error = ?error,
				"Could not extract PoV",
			);
			return;
		}
	};

608
609
610
611
	let pov = {
		// Do validity checks and complete all senders awaiting this PoV.
		let fetching = match relay_parent_state.fetching.get_mut(&pov_hash) {
			None => {
612
613
				report_peer(ctx, peer, COST_UNEXPECTED_POV).await;
				return;
614
615
616
617
618
619
			}
			Some(f) => f,
		};

		let hash = pov.hash();
		if hash != pov_hash {
620
621
			report_peer(ctx, peer, COST_UNEXPECTED_POV).await;
			return;
622
623
624
625
626
627
628
		}

		let pov = Arc::new(pov);

		if fetching.is_empty() {
			// fetching is empty whenever we were awaiting something and
			// it was completed afterwards.
629
			report_peer(ctx, peer.clone(), BENEFIT_LATE_POV).await;
630
631
		} else {
			// fetching is non-empty when the peer just provided us with data we needed.
632
			report_peer(ctx, peer.clone(), BENEFIT_FRESH_POV).await;
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
		}

		for response_sender in fetching.drain(..) {
			let _ = response_sender.send(pov.clone());
		}

		pov
	};

	// make sure we don't consider this peer as awaiting that PoV anymore.
	if let Some(peer_state) = state.peer_state.get_mut(&peer) {
		peer_state.awaited.remove(&pov_hash);
	}

	// distribute the PoV to all other peers who are awaiting it.
	distribute_to_awaiting(
		&mut state.peer_state,
		ctx,
651
		&state.metrics,
652
653
		relay_parent,
		pov_hash,
654
655
656
657
		&encoded_pov,
	).await;

	relay_parent_state.known.insert(pov_hash, (pov, encoded_pov));
658
659
}

660
/// Handles a newly or already connected validator in the context of some relay leaf.
661
662
663
664
fn handle_validator_connected(state: &mut State, peer_id: PeerId) {
	state.peer_state.entry(peer_id).or_default();
}

665
/// Handles a network bridge update.
666
#[tracing::instrument(level = "trace", skip(ctx, state), fields(subsystem = LOG_TARGET))]
667
668
669
async fn handle_network_update(
	state: &mut State,
	ctx: &mut impl SubsystemContext<Message = PoVDistributionMessage>,
670
	update: NetworkBridgeEvent<protocol_v1::PoVDistributionMessage>,
671
) {
672
673
	let _timer = state.metrics.time_handle_network_update();

674
675
	match update {
		NetworkBridgeEvent::PeerConnected(peer, _observed_role) => {
676
			handle_validator_connected(state, peer);
677
678
679
680
681
682
683
		}
		NetworkBridgeEvent::PeerDisconnected(peer) => {
			state.peer_state.remove(&peer);
		}
		NetworkBridgeEvent::PeerViewChange(peer_id, view) => {
			if let Some(peer_state) = state.peer_state.get_mut(&peer_id) {
				// prune anything not in the new view.
684
				peer_state.awaited.retain(|relay_parent, _| view.contains(&relay_parent));
685
686

				// introduce things from the new view.
687
				for relay_parent in view.iter() {
688
689
690
691
692
693
694
695
696
					if let Entry::Vacant(entry) = peer_state.awaited.entry(*relay_parent) {
						entry.insert(HashSet::new());

						// Notify the peer about everything we're awaiting at the new relay-parent.
						notify_one_we_are_awaiting_many(
							&peer_id,
							ctx,
							&state.relay_parent_state,
							*relay_parent,
697
						).await;
698
699
700
701
702
					}
				}
			}

		}
703
704
705
706
		NetworkBridgeEvent::PeerMessage(peer, message) => {
			match message {
				protocol_v1::PoVDistributionMessage::Awaiting(relay_parent, pov_hashes)
					=> handle_awaiting(
707
708
709
710
711
712
						state,
						ctx,
						peer,
						relay_parent,
						pov_hashes,
					).await,
713
714
				protocol_v1::PoVDistributionMessage::SendPoV(relay_parent, pov_hash, pov)
					=> handle_incoming_pov(
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
						state,
						ctx,
						peer,
						relay_parent,
						pov_hash,
						pov,
					).await,
			}
		}
		NetworkBridgeEvent::OurViewChange(view) => {
			state.our_view = view;
		}
	}
}

730
731
732
733
734
impl PoVDistribution {
	/// Create a new instance of `PovDistribution`.
	pub fn new(metrics: Metrics) -> Self {
		Self { metrics }
	}
735

736
	#[tracing::instrument(skip(self, ctx), fields(subsystem = LOG_TARGET))]
737
	async fn run(
738
739
740
741
742
743
744
		self,
		ctx: impl SubsystemContext<Message = PoVDistributionMessage>,
	) -> SubsystemResult<()> {
		self.run_with_state(ctx, State::default()).await
	}

	async fn run_with_state(
745
746
		self,
		mut ctx: impl SubsystemContext<Message = PoVDistributionMessage>,
747
		mut state: State,
748
	) -> SubsystemResult<()> {
749
		state.metrics = self.metrics;
750
751

		loop {
752
753
754
755
			// `select_biased` is used since receiving connection notifications and
			// peer view update messages may be racy and we want connection notifications
			// first.
			futures::select_biased! {
756
				v = state.connection_requests.next().fuse() => handle_validator_connected(&mut state, v.peer_id),
757
758
759
				v = ctx.recv().fuse() => {
					match v? {
						FromOverseer::Signal(signal) => if handle_signal(
760
761
							&mut state,
							&mut ctx,
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
							signal,
						).await? {
							return Ok(());
						}
						FromOverseer::Communication { msg } => match msg {
							PoVDistributionMessage::FetchPoV(relay_parent, descriptor, response_sender) =>
								handle_fetch(
									&mut state,
									&mut ctx,
									relay_parent,
									descriptor,
									response_sender,
								).await,
							PoVDistributionMessage::DistributePoV(relay_parent, descriptor, pov) =>
								handle_distribute(
									&mut state,
									&mut ctx,
									relay_parent,
									descriptor,
									pov,
								).await,
							PoVDistributionMessage::NetworkBridgeUpdateV1(event) =>
								handle_network_update(
									&mut state,
									&mut ctx,
									event,
								).await,
						}
					}
				}
792
			}
793
794
795
796
		}
	}
}

797
798
799
800
801


#[derive(Clone)]
struct MetricsInner {
	povs_distributed: prometheus::Counter<prometheus::U64>,
802
803
804
805
	handle_signal: prometheus::Histogram,
	handle_fetch: prometheus::Histogram,
	handle_distribute: prometheus::Histogram,
	handle_network_update: prometheus::Histogram,
806
807
808
809
810
811
812
813
814
815
816
817
}

/// Availability Distribution metrics.
#[derive(Default, Clone)]
pub struct Metrics(Option<MetricsInner>);

impl Metrics {
	fn on_pov_distributed(&self) {
		if let Some(metrics) = &self.0 {
			metrics.povs_distributed.inc();
		}
	}
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837

	/// Provide a timer for `handle_signal` which observes on drop.
	fn time_handle_signal(&self) -> Option<metrics::prometheus::prometheus::HistogramTimer> {
		self.0.as_ref().map(|metrics| metrics.handle_signal.start_timer())
	}

	/// Provide a timer for `handle_fetch` which observes on drop.
	fn time_handle_fetch(&self) -> Option<metrics::prometheus::prometheus::HistogramTimer> {
		self.0.as_ref().map(|metrics| metrics.handle_fetch.start_timer())
	}

	/// Provide a timer for `handle_distribute` which observes on drop.
	fn time_handle_distribute(&self) -> Option<metrics::prometheus::prometheus::HistogramTimer> {
		self.0.as_ref().map(|metrics| metrics.handle_distribute.start_timer())
	}

	/// Provide a timer for `handle_network_update` which observes on drop.
	fn time_handle_network_update(&self) -> Option<metrics::prometheus::prometheus::HistogramTimer> {
		self.0.as_ref().map(|metrics| metrics.handle_network_update.start_timer())
	}
838
839
840
841
842
843
844
845
846
847
848
849
}

impl metrics::Metrics for Metrics {
	fn try_register(registry: &prometheus::Registry) -> std::result::Result<Self, prometheus::PrometheusError> {
		let metrics = MetricsInner {
			povs_distributed: prometheus::register(
				prometheus::Counter::new(
					"parachain_povs_distributed_total",
					"Number of PoVs distributed to other peers."
				)?,
				registry,
			)?,
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
			handle_signal: prometheus::register(
				prometheus::Histogram::with_opts(
					prometheus::HistogramOpts::new(
						"parachain_pov_distribution_handle_signal",
						"Time spent within `pov_distribution::handle_signal`",
					)
				)?,
				registry,
			)?,
			handle_fetch: prometheus::register(
				prometheus::Histogram::with_opts(
					prometheus::HistogramOpts::new(
						"parachain_pov_distribution_handle_fetch",
						"Time spent within `pov_distribution::handle_fetch`",
					)
				)?,
				registry,
			)?,
			handle_distribute: prometheus::register(
				prometheus::Histogram::with_opts(
					prometheus::HistogramOpts::new(
						"parachain_pov_distribution_handle_distribute",
						"Time spent within `pov_distribution::handle_distribute`",
					)
				)?,
				registry,
			)?,
			handle_network_update: prometheus::register(
				prometheus::Histogram::with_opts(
					prometheus::HistogramOpts::new(
						"parachain_pov_distribution_handle_network_update",
						"Time spent within `pov_distribution::handle_network_update`",
					)
				)?,
				registry,
			)?,
886
887
888
889
		};
		Ok(Metrics(Some(metrics)))
	}
}