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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
#![cfg(feature = "full-node")]
use super::{HeaderProvider, HeaderProviderProvider};
use consensus_common::{Error as ConsensusError, SelectChain};
use futures::channel::oneshot;
use polkadot_node_primitives::MAX_FINALITY_LAG as PRIMITIVES_MAX_FINALITY_LAG;
use polkadot_node_subsystem::messages::{
ApprovalVotingMessage, ChainSelectionMessage, DisputeCoordinatorMessage,
HighestApprovedAncestorBlock,
};
use polkadot_node_subsystem_util::metrics::{self, prometheus};
use polkadot_overseer::{AllMessages, Handle};
use polkadot_primitives::v2::{
Block as PolkadotBlock, BlockNumber, Hash, Header as PolkadotHeader,
};
use std::sync::Arc;
const MAX_FINALITY_LAG: polkadot_primitives::v2::BlockNumber = PRIMITIVES_MAX_FINALITY_LAG;
const LOG_TARGET: &str = "parachain::chain-selection";
#[derive(Debug, Default, Clone)]
pub struct Metrics(Option<MetricsInner>);
#[derive(Debug, Clone)]
struct MetricsInner {
approval_checking_finality_lag: prometheus::Gauge<prometheus::U64>,
disputes_finality_lag: prometheus::Gauge<prometheus::U64>,
}
impl metrics::Metrics for Metrics {
fn try_register(registry: &prometheus::Registry) -> Result<Self, prometheus::PrometheusError> {
let metrics = MetricsInner {
approval_checking_finality_lag: prometheus::register(
prometheus::Gauge::with_opts(
prometheus::Opts::new(
"polkadot_parachain_approval_checking_finality_lag",
"How far behind the head of the chain the Approval Checking protocol wants to vote",
)
)?,
registry,
)?,
disputes_finality_lag: prometheus::register(
prometheus::Gauge::with_opts(
prometheus::Opts::new(
"polkadot_parachain_disputes_finality_lag",
"How far behind the head of the chain the Disputes protocol wants to vote",
)
)?,
registry,
)?,
};
Ok(Metrics(Some(metrics)))
}
}
impl Metrics {
fn note_approval_checking_finality_lag(&self, lag: BlockNumber) {
if let Some(ref metrics) = self.0 {
metrics.approval_checking_finality_lag.set(lag as _);
}
}
fn note_disputes_finality_lag(&self, lag: BlockNumber) {
if let Some(ref metrics) = self.0 {
metrics.disputes_finality_lag.set(lag as _);
}
}
}
enum IsDisputesAwareWithOverseer<B: sc_client_api::Backend<PolkadotBlock>> {
Yes(SelectRelayChainInner<B, Handle>),
No,
}
impl<B> Clone for IsDisputesAwareWithOverseer<B>
where
B: sc_client_api::Backend<PolkadotBlock>,
SelectRelayChainInner<B, Handle>: Clone,
{
fn clone(&self) -> Self {
match self {
Self::Yes(ref inner) => Self::Yes(inner.clone()),
Self::No => Self::No,
}
}
}
pub struct SelectRelayChain<B: sc_client_api::Backend<PolkadotBlock>> {
longest_chain: sc_consensus::LongestChain<B, PolkadotBlock>,
selection: IsDisputesAwareWithOverseer<B>,
}
impl<B> Clone for SelectRelayChain<B>
where
B: sc_client_api::Backend<PolkadotBlock>,
SelectRelayChainInner<B, Handle>: Clone,
{
fn clone(&self) -> Self {
Self { longest_chain: self.longest_chain.clone(), selection: self.selection.clone() }
}
}
impl<B> SelectRelayChain<B>
where
B: sc_client_api::Backend<PolkadotBlock> + 'static,
{
pub fn new_longest_chain(backend: Arc<B>) -> Self {
gum::debug!(target: LOG_TARGET, "Using {} chain selection algorithm", "longest");
Self {
longest_chain: sc_consensus::LongestChain::new(backend.clone()),
selection: IsDisputesAwareWithOverseer::No,
}
}
pub fn new_with_overseer(backend: Arc<B>, overseer: Handle, metrics: Metrics) -> Self {
gum::debug!(target: LOG_TARGET, "Using dispute aware relay-chain selection algorithm",);
SelectRelayChain {
longest_chain: sc_consensus::LongestChain::new(backend.clone()),
selection: IsDisputesAwareWithOverseer::Yes(SelectRelayChainInner::new(
backend, overseer, metrics,
)),
}
}
pub fn as_longest_chain(&self) -> &sc_consensus::LongestChain<B, PolkadotBlock> {
&self.longest_chain
}
}
#[async_trait::async_trait]
impl<B> SelectChain<PolkadotBlock> for SelectRelayChain<B>
where
B: sc_client_api::Backend<PolkadotBlock> + 'static,
{
async fn leaves(&self) -> Result<Vec<Hash>, ConsensusError> {
match self.selection {
IsDisputesAwareWithOverseer::Yes(ref selection) => selection.leaves().await,
IsDisputesAwareWithOverseer::No => self.longest_chain.leaves().await,
}
}
async fn best_chain(&self) -> Result<PolkadotHeader, ConsensusError> {
match self.selection {
IsDisputesAwareWithOverseer::Yes(ref selection) => selection.best_chain().await,
IsDisputesAwareWithOverseer::No => self.longest_chain.best_chain().await,
}
}
async fn finality_target(
&self,
target_hash: Hash,
maybe_max_number: Option<BlockNumber>,
) -> Result<Hash, ConsensusError> {
let longest_chain_best =
self.longest_chain.finality_target(target_hash, maybe_max_number).await?;
if let IsDisputesAwareWithOverseer::Yes(ref selection) = self.selection {
selection
.finality_target_with_longest_chain(
target_hash,
longest_chain_best,
maybe_max_number,
)
.await
} else {
Ok(longest_chain_best)
}
}
}
pub struct SelectRelayChainInner<B, OH> {
backend: Arc<B>,
overseer: OH,
metrics: Metrics,
}
impl<B, OH> SelectRelayChainInner<B, OH>
where
B: HeaderProviderProvider<PolkadotBlock>,
OH: OverseerHandleT,
{
pub fn new(backend: Arc<B>, overseer: OH, metrics: Metrics) -> Self {
SelectRelayChainInner { backend, overseer, metrics }
}
fn block_header(&self, hash: Hash) -> Result<PolkadotHeader, ConsensusError> {
match HeaderProvider::header(self.backend.header_provider(), hash) {
Ok(Some(header)) => Ok(header),
Ok(None) =>
Err(ConsensusError::ChainLookup(format!("Missing header with hash {:?}", hash,))),
Err(e) => Err(ConsensusError::ChainLookup(format!(
"Lookup failed for header with hash {:?}: {:?}",
hash, e,
))),
}
}
fn block_number(&self, hash: Hash) -> Result<BlockNumber, ConsensusError> {
match HeaderProvider::number(self.backend.header_provider(), hash) {
Ok(Some(number)) => Ok(number),
Ok(None) =>
Err(ConsensusError::ChainLookup(format!("Missing number with hash {:?}", hash,))),
Err(e) => Err(ConsensusError::ChainLookup(format!(
"Lookup failed for number with hash {:?}: {:?}",
hash, e,
))),
}
}
}
impl<B, OH> Clone for SelectRelayChainInner<B, OH>
where
B: HeaderProviderProvider<PolkadotBlock> + Send + Sync,
OH: OverseerHandleT,
{
fn clone(&self) -> Self {
SelectRelayChainInner {
backend: self.backend.clone(),
overseer: self.overseer.clone(),
metrics: self.metrics.clone(),
}
}
}
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("Request for leaves from chain selection got canceled")]
LeavesCanceled(oneshot::Canceled),
#[error("Request for leaves from chain selection got canceled")]
BestLeafContainingCanceled(oneshot::Canceled),
#[error("Request for determining the undisputed chain from DisputeCoordinator got canceled")]
DetermineUndisputedChainCanceled(oneshot::Canceled),
#[error("Request approved ancestor from approval voting got canceled")]
ApprovedAncestorCanceled(oneshot::Canceled),
#[error("ChainSelection returned no leaves")]
EmptyLeaves,
}
#[async_trait::async_trait]
pub trait OverseerHandleT: Clone + Send + Sync {
async fn send_msg<M: Send + Into<AllMessages>>(&mut self, msg: M, origin: &'static str);
}
#[async_trait::async_trait]
impl OverseerHandleT for Handle {
async fn send_msg<M: Send + Into<AllMessages>>(&mut self, msg: M, origin: &'static str) {
Handle::send_msg(self, msg, origin).await
}
}
impl<B, OH> SelectRelayChainInner<B, OH>
where
B: HeaderProviderProvider<PolkadotBlock>,
OH: OverseerHandleT,
{
async fn leaves(&self) -> Result<Vec<Hash>, ConsensusError> {
let (tx, rx) = oneshot::channel();
self.overseer
.clone()
.send_msg(ChainSelectionMessage::Leaves(tx), std::any::type_name::<Self>())
.await;
let leaves = rx
.await
.map_err(Error::LeavesCanceled)
.map_err(|e| ConsensusError::Other(Box::new(e)))?;
gum::trace!(target: LOG_TARGET, ?leaves, "Chain selection leaves");
Ok(leaves)
}
async fn best_chain(&self) -> Result<PolkadotHeader, ConsensusError> {
let best_leaf = self
.leaves()
.await?
.first()
.ok_or_else(|| ConsensusError::Other(Box::new(Error::EmptyLeaves)))?
.clone();
gum::trace!(target: LOG_TARGET, ?best_leaf, "Best chain");
self.block_header(best_leaf)
}
pub(crate) async fn finality_target_with_longest_chain(
&self,
target_hash: Hash,
best_leaf: Hash,
maybe_max_number: Option<BlockNumber>,
) -> Result<Hash, ConsensusError> {
let mut overseer = self.overseer.clone();
gum::trace!(target: LOG_TARGET, ?best_leaf, "Longest chain");
let subchain_head = {
let (tx, rx) = oneshot::channel();
overseer
.send_msg(
ChainSelectionMessage::BestLeafContaining(target_hash, tx),
std::any::type_name::<Self>(),
)
.await;
let best = rx
.await
.map_err(Error::BestLeafContainingCanceled)
.map_err(|e| ConsensusError::Other(Box::new(e)))?;
gum::trace!(target: LOG_TARGET, ?best, "Best leaf containing");
match best {
None => return Ok(target_hash),
Some(best) => best,
}
};
let target_number = self.block_number(target_hash)?;
let subchain_head = match maybe_max_number {
None => subchain_head,
Some(max) => {
if max <= target_number {
if max < target_number {
gum::warn!(
LOG_TARGET,
max_number = max,
target_number,
"`finality_target` max number is less than target number",
);
}
return Ok(target_hash)
}
let subchain_header = self.block_header(subchain_head)?;
if subchain_header.number <= max {
gum::trace!(target: LOG_TARGET, ?best_leaf, "Constrained sub-chain head",);
subchain_head
} else {
let (ancestor_hash, _) =
crate::grandpa_support::walk_backwards_to_target_block(
self.backend.header_provider(),
max,
&subchain_header,
)
.map_err(|e| ConsensusError::ChainLookup(format!("{:?}", e)))?;
gum::trace!(
target: LOG_TARGET,
?ancestor_hash,
"Grandpa walk backwards sub-chain head"
);
ancestor_hash
}
},
};
let initial_leaf = subchain_head;
let initial_leaf_number = self.block_number(initial_leaf)?;
let (subchain_head, subchain_number, subchain_block_descriptions) = {
let (tx, rx) = oneshot::channel();
overseer
.send_msg(
ApprovalVotingMessage::ApprovedAncestor(subchain_head, target_number, tx),
std::any::type_name::<Self>(),
)
.await;
match rx
.await
.map_err(Error::ApprovedAncestorCanceled)
.map_err(|e| ConsensusError::Other(Box::new(e)))?
{
None => (target_hash, target_number, Vec::new()),
Some(HighestApprovedAncestorBlock { number, hash, descriptions }) =>
(hash, number, descriptions),
}
};
gum::trace!(target: LOG_TARGET, ?subchain_head, "Ancestor approval restriction applied",);
let lag = initial_leaf_number.saturating_sub(subchain_number);
self.metrics.note_approval_checking_finality_lag(lag);
let (lag, subchain_head) = {
if Some(subchain_block_descriptions.len() as _) !=
subchain_number.checked_sub(target_number)
{
gum::error!(
LOG_TARGET,
present_block_descriptions = subchain_block_descriptions.len(),
target_number,
subchain_number,
"Mismatch of anticipated block descriptions and block number difference.",
);
return Ok(target_hash)
}
let (tx, rx) = oneshot::channel();
overseer
.send_msg(
DisputeCoordinatorMessage::DetermineUndisputedChain {
base: (target_number, target_hash),
block_descriptions: subchain_block_descriptions,
tx,
},
std::any::type_name::<Self>(),
)
.await;
let (lag, subchain_head) =
match rx.await.map_err(Error::DetermineUndisputedChainCanceled) {
Ok((subchain_number, subchain_head)) => {
let lag_disputes = initial_leaf_number.saturating_sub(subchain_number);
self.metrics.note_disputes_finality_lag(lag_disputes);
(lag_disputes, subchain_head)
},
Err(e) => {
gum::error!(
target: LOG_TARGET,
error = ?e,
"Call to `DetermineUndisputedChain` failed",
);
return Ok(target_hash)
},
};
(lag, subchain_head)
};
gum::trace!(
target: LOG_TARGET,
?subchain_head,
"Disputed blocks in ancestry restriction applied",
);
if lag > MAX_FINALITY_LAG {
let safe_target = initial_leaf_number - MAX_FINALITY_LAG;
if safe_target <= target_number {
gum::warn!(target: LOG_TARGET, ?target_hash, "Safeguard enforced finalization");
Ok(target_hash)
} else {
let initial_leaf_header = self.block_header(initial_leaf)?;
let (forced_target, _) = crate::grandpa_support::walk_backwards_to_target_block(
self.backend.header_provider(),
safe_target,
&initial_leaf_header,
)
.map_err(|e| ConsensusError::ChainLookup(format!("{:?}", e)))?;
gum::warn!(
target: LOG_TARGET,
?forced_target,
"Safeguard enforced finalization of child"
);
Ok(forced_target)
}
} else {
Ok(subchain_head)
}
}
}