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
use sc_client_api::{BlockBackend, BlockchainEvents, UsageProvider};
use sc_consensus::import_queue::{ImportQueue, IncomingBlock};
use sp_consensus::{BlockOrigin, BlockStatus};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT, NumberFor},
};
use polkadot_node_primitives::{AvailableData, POV_BOMB_LIMIT};
use polkadot_overseer::Handle as OverseerHandle;
use polkadot_primitives::v2::{
CandidateReceipt, CommittedCandidateReceipt, Id as ParaId, SessionIndex,
};
use cumulus_primitives_core::ParachainBlockData;
use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};
use codec::Decode;
use futures::{select, stream::FuturesUnordered, Future, FutureExt, Stream, StreamExt};
use futures_timer::Delay;
use rand::{thread_rng, Rng};
use std::{
collections::{HashMap, VecDeque},
pin::Pin,
sync::Arc,
time::Duration,
};
mod active_candidate_recovery;
use active_candidate_recovery::ActiveCandidateRecovery;
const LOG_TARGET: &str = "cumulus-pov-recovery";
struct PendingCandidate<Block: BlockT> {
receipt: CandidateReceipt,
session_index: SessionIndex,
block_number: NumberFor<Block>,
}
#[derive(Clone, Copy)]
pub enum RecoveryDelay {
WithMax { max: Duration },
WithMinAndMax { min: Duration, max: Duration },
}
impl RecoveryDelay {
fn as_delay(self) -> Delay {
match self {
Self::WithMax { max } => Delay::new(max.mul_f64(thread_rng().gen())),
Self::WithMinAndMax { min, max } =>
Delay::new(min + max.saturating_sub(min).mul_f64(thread_rng().gen())),
}
}
}
pub struct PoVRecovery<Block: BlockT, PC, IQ, RC> {
pending_candidates: HashMap<Block::Hash, PendingCandidate<Block>>,
next_candidate_to_recover: FuturesUnordered<Pin<Box<dyn Future<Output = Block::Hash> + Send>>>,
active_candidate_recovery: ActiveCandidateRecovery<Block>,
waiting_for_parent: HashMap<Block::Hash, Vec<Block>>,
recovery_delay: RecoveryDelay,
parachain_client: Arc<PC>,
parachain_import_queue: IQ,
relay_chain_interface: RC,
para_id: ParaId,
}
impl<Block: BlockT, PC, IQ, RCInterface> PoVRecovery<Block, PC, IQ, RCInterface>
where
PC: BlockBackend<Block> + BlockchainEvents<Block> + UsageProvider<Block>,
RCInterface: RelayChainInterface + Clone,
IQ: ImportQueue<Block>,
{
pub fn new(
overseer_handle: OverseerHandle,
recovery_delay: RecoveryDelay,
parachain_client: Arc<PC>,
parachain_import_queue: IQ,
relay_chain_interface: RCInterface,
para_id: ParaId,
) -> Self {
Self {
pending_candidates: HashMap::new(),
next_candidate_to_recover: Default::default(),
active_candidate_recovery: ActiveCandidateRecovery::new(overseer_handle),
recovery_delay,
waiting_for_parent: HashMap::new(),
parachain_client,
parachain_import_queue,
relay_chain_interface,
para_id,
}
}
fn handle_pending_candidate(
&mut self,
receipt: CommittedCandidateReceipt,
session_index: SessionIndex,
) {
let header = match Block::Header::decode(&mut &receipt.commitments.head_data.0[..]) {
Ok(header) => header,
Err(e) => {
tracing::warn!(
target: LOG_TARGET,
error = ?e,
"Failed to decode parachain header from pending candidate",
);
return
},
};
if *header.number() <= self.parachain_client.usage_info().chain.finalized_number {
return
}
let hash = header.hash();
match self.parachain_client.block_status(&BlockId::Hash(hash)) {
Ok(BlockStatus::Unknown) => (),
Ok(_) => return,
Err(e) => {
tracing::debug!(
target: "cumulus-consensus",
error = ?e,
block_hash = ?hash,
"Failed to get block status",
);
return
},
}
if self
.pending_candidates
.insert(
hash,
PendingCandidate {
block_number: *header.number(),
receipt: receipt.to_plain(),
session_index,
},
)
.is_some()
{
return
}
let delay = self.recovery_delay.as_delay();
self.next_candidate_to_recover.push(
async move {
delay.await;
hash
}
.boxed(),
);
}
fn handle_block_imported(&mut self, hash: &Block::Hash) {
self.pending_candidates.remove(hash);
}
fn handle_block_finalized(&mut self, block_number: NumberFor<Block>) {
self.pending_candidates.retain(|_, pc| pc.block_number > block_number);
}
async fn recover_candidate(&mut self, block_hash: Block::Hash) {
let pending_candidate = match self.pending_candidates.remove(&block_hash) {
Some(pending_candidate) => pending_candidate,
None => return,
};
self.active_candidate_recovery
.recover_candidate(block_hash, pending_candidate)
.await;
}
fn clear_waiting_for_parent(&mut self, hash: Block::Hash) {
let mut blocks_to_delete = vec![hash];
while let Some(delete) = blocks_to_delete.pop() {
if let Some(childs) = self.waiting_for_parent.remove(&delete) {
blocks_to_delete.extend(childs.iter().map(BlockT::hash));
}
}
}
async fn handle_candidate_recovered(
&mut self,
block_hash: Block::Hash,
available_data: Option<AvailableData>,
) {
let available_data = match available_data {
Some(data) => data,
None => {
self.clear_waiting_for_parent(block_hash);
return
},
};
let raw_block_data = match sp_maybe_compressed_blob::decompress(
&available_data.pov.block_data.0,
POV_BOMB_LIMIT,
) {
Ok(r) => r,
Err(error) => {
tracing::debug!(target: LOG_TARGET, ?error, "Failed to decompress PoV");
self.clear_waiting_for_parent(block_hash);
return
},
};
let block_data = match ParachainBlockData::<Block>::decode(&mut &raw_block_data[..]) {
Ok(d) => d,
Err(error) => {
tracing::warn!(
target: LOG_TARGET,
?error,
"Failed to decode parachain block data from recovered PoV",
);
self.clear_waiting_for_parent(block_hash);
return
},
};
let block = block_data.into_block();
let parent = *block.header().parent_hash();
match self.parachain_client.block_status(&BlockId::hash(parent)) {
Ok(BlockStatus::Unknown) => {
if self.active_candidate_recovery.is_being_recovered(&parent) {
tracing::debug!(
target: "cumulus-consensus",
?block_hash,
parent_hash = ?parent,
"Parent is still being recovered, waiting.",
);
self.waiting_for_parent.entry(parent).or_default().push(block);
return
} else {
tracing::debug!(
target: "cumulus-consensus",
?block_hash,
parent_hash = ?parent,
"Parent not found while trying to import recovered block.",
);
self.clear_waiting_for_parent(block_hash);
return
}
},
Err(error) => {
tracing::debug!(
target: "cumulus-consensus",
block_hash = ?parent,
?error,
"Error while checking block status",
);
self.clear_waiting_for_parent(block_hash);
return
},
_ => (),
}
self.import_block(block).await;
}
async fn import_block(&mut self, block: Block) {
let mut blocks = VecDeque::new();
blocks.push_back(block);
let mut incoming_blocks = Vec::new();
while let Some(block) = blocks.pop_front() {
let block_hash = block.hash();
let (header, body) = block.deconstruct();
incoming_blocks.push(IncomingBlock {
hash: block_hash,
header: Some(header),
body: Some(body),
import_existing: false,
allow_missing_state: false,
justifications: None,
origin: None,
skip_execution: false,
state: None,
indexed_body: None,
});
if let Some(waiting) = self.waiting_for_parent.remove(&block_hash) {
blocks.extend(waiting);
}
}
self.parachain_import_queue
.import_blocks(BlockOrigin::ConsensusBroadcast, incoming_blocks);
}
pub async fn run(mut self) {
let mut imported_blocks = self.parachain_client.import_notification_stream().fuse();
let mut finalized_blocks = self.parachain_client.finality_notification_stream().fuse();
let pending_candidates =
match pending_candidates(self.relay_chain_interface.clone(), self.para_id).await {
Ok(pending_candidate_stream) => pending_candidate_stream.fuse(),
Err(err) => {
tracing::error!(target: LOG_TARGET, error = ?err, "Unable to retrieve pending candidate stream.");
return
},
};
futures::pin_mut!(pending_candidates);
loop {
select! {
pending_candidate = pending_candidates.next() => {
if let Some((receipt, session_index)) = pending_candidate {
self.handle_pending_candidate(receipt, session_index);
} else {
tracing::debug!(
target: LOG_TARGET,
"Pending candidates stream ended",
);
return;
}
},
imported = imported_blocks.next() => {
if let Some(imported) = imported {
self.handle_block_imported(&imported.hash);
} else {
tracing::debug!(
target: LOG_TARGET,
"Imported blocks stream ended",
);
return;
}
},
finalized = finalized_blocks.next() => {
if let Some(finalized) = finalized {
self.handle_block_finalized(*finalized.header.number());
} else {
tracing::debug!(
target: LOG_TARGET,
"Finalized blocks stream ended",
);
return;
}
},
next_to_recover = self.next_candidate_to_recover.next() => {
if let Some(block_hash) = next_to_recover {
self.recover_candidate(block_hash).await;
}
},
(block_hash, available_data) =
self.active_candidate_recovery.wait_for_recovery().fuse() =>
{
self.handle_candidate_recovered(block_hash, available_data).await;
},
}
}
}
}
async fn pending_candidates(
relay_chain_client: impl RelayChainInterface + Clone,
para_id: ParaId,
) -> RelayChainResult<impl Stream<Item = (CommittedCandidateReceipt, SessionIndex)>> {
let import_notification_stream = relay_chain_client.import_notification_stream().await?;
let filtered_stream = import_notification_stream.filter_map(move |n| {
let client_for_closure = relay_chain_client.clone();
async move {
let hash = n.hash();
let pending_availability_result = client_for_closure
.candidate_pending_availability(hash, para_id)
.await
.map_err(|e| {
tracing::error!(
target: LOG_TARGET,
error = ?e,
"Failed to fetch pending candidates.",
)
});
let session_index_result =
client_for_closure.session_index_for_child(hash).await.map_err(|e| {
tracing::error!(
target: LOG_TARGET,
error = ?e,
"Failed to fetch session index.",
)
});
if let Ok(Some(candidate)) = pending_availability_result {
session_index_result.map(|session_index| (candidate, session_index)).ok()
} else {
None
}
}
});
Ok(filtered_stream)
}