Newer
Older
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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/>.
//! Implements a `CandidateBackingSubsystem`.
#![recursion_limit="256"]
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::pin::Pin;
use std::time::Duration;
use bitvec::vec::BitVec;
use log;
use futures::{
select, FutureExt, SinkExt, StreamExt,
channel::{oneshot, mpsc},
future::{self, Either},
task::{Spawn, SpawnError, SpawnExt},
};
use futures_timer::Delay;
use streamunordered::{StreamUnordered, StreamYield};
use primitives::Pair;
use keystore::KeyStorePtr;
use polkadot_primitives::{
Hash,
parachain::{
AbridgedCandidateReceipt, BackedCandidate, Id as ParaId, ValidatorPair, ValidatorId,
ValidatorIndex, HeadData, SigningContext, PoVBlock, OmittedValidationData,
CandidateDescriptor, LocalValidationData, GlobalValidationSchedule, AvailableData,
ErasureChunk,
},
};
use polkadot_node_primitives::{
FromTableMisbehavior, Statement, SignedFullStatement, MisbehaviorReport, ValidationResult,
};
use polkadot_subsystem::{
FromOverseer, OverseerSignal, Subsystem, SubsystemContext, SpawnedSubsystem,
};
use polkadot_subsystem::messages::{
AllMessages, CandidateBackingMessage, CandidateSelectionMessage, SchedulerRoster,
RuntimeApiMessage, RuntimeApiRequest, CandidateValidationMessage, ValidationFailed,
StatementDistributionMessage, NewBackedCandidate, ProvisionerMessage, ProvisionableData,
PoVDistributionMessage, AvailabilityStoreMessage,
};
use statement_table::{
generic::AttestedCandidate as TableAttestedCandidate,
Table, Context as TableContextTrait, Statement as TableStatement,
SignedStatement as TableSignedStatement, Summary as TableSummary,
};
#[derive(Debug, derive_more::From)]
enum Error {
NotInValidatorSet,
CandidateNotFound,
JobNotFound(Hash),
InvalidSignature,
#[from]
Erasure(erasure_coding::Error),
#[from]
ValidationFailed(ValidationFailed),
#[from]
Oneshot(oneshot::Canceled),
#[from]
Mpsc(mpsc::SendError),
#[from]
Spawn(SpawnError),
}
/// Holds all data needed for candidate backing job operation.
struct CandidateBackingJob {
/// The hash of the relay parent on top of which this job is doing it's work.
parent: Hash,
/// Inbound message channel receiving part.
rx_to: mpsc::Receiver<ToJob>,
/// Outbound message channel sending part.
tx_from: mpsc::Sender<FromJob>,
/// `HeadData`s of the parachains that this validator is assigned to.
head_data: HeadData,
/// The `ParaId`s assigned to this validator.
assignment: ParaId,
/// We issued `Valid` or `Invalid` statements on about these candidates.
issued_statements: HashSet<Hash>,
/// `Some(h)` if this job has already issues `Seconded` statemt for some candidate with `h` hash.
seconded: Option<Hash>,
/// We have already reported misbehaviors for these validators.
reported_misbehavior_for: HashSet<ValidatorIndex>,
table: Table<TableContext>,
table_context: TableContext,
}
const fn group_quorum(n_validators: usize) -> usize {
(n_validators / 2) + 1
}
#[derive(Default)]
struct TableContext {
signing_context: SigningContext,
key: Option<ValidatorPair>,
groups: HashMap<ParaId, Vec<ValidatorIndex>>,
validators: Vec<ValidatorId>,
}
impl TableContextTrait for TableContext {
fn is_member_of(&self, authority: ValidatorIndex, group: &ParaId) -> bool {
self.groups.get(group).map_or(false, |g| g.iter().position(|&a| a == authority).is_some())
}
fn requisite_votes(&self, group: &ParaId) -> usize {
self.groups.get(group).map_or(usize::max_value(), |g| group_quorum(g.len()))
}
}
impl TableContext {
fn local_id(&self) -> Option<ValidatorId> {
self.key.as_ref().map(|k| k.public())
}
fn local_index(&self) -> Option<ValidatorIndex> {
self.local_id().and_then(|id|
self.validators
.iter()
.enumerate()
.find(|(_, k)| k == &&id)
.map(|(i, _)| i as ValidatorIndex)
)
}
}
const CHANNEL_CAPACITY: usize = 64;
/// A message type that is sent from `CandidateBackingSubsystem` to `CandidateBackingJob`.
enum ToJob {
/// A `CandidateBackingMessage`.
CandidateBacking(CandidateBackingMessage),
/// Stop working.
Stop,
}
/// A message type that is sent from `CandidateBackingJob` to `CandidateBackingSubsystem`.
enum FromJob {
AvailabilityStore(AvailabilityStoreMessage),
RuntimeApiMessage(RuntimeApiMessage),
CandidateValidation(CandidateValidationMessage),
CandidateSelection(CandidateSelectionMessage),
Provisioner(ProvisionerMessage),
PoVDistribution(PoVDistributionMessage),
StatementDistribution(StatementDistributionMessage),
}
impl From<FromJob> for AllMessages {
fn from(f: FromJob) -> Self {
match f {
FromJob::AvailabilityStore(msg) => AllMessages::AvailabilityStore(msg),
FromJob::RuntimeApiMessage(msg) => AllMessages::RuntimeApi(msg),
FromJob::CandidateValidation(msg) => AllMessages::CandidateValidation(msg),
FromJob::CandidateSelection(msg) => AllMessages::CandidateSelection(msg),
FromJob::StatementDistribution(msg) => AllMessages::StatementDistribution(msg),
FromJob::PoVDistribution(msg) => AllMessages::PoVDistribution(msg),
FromJob::Provisioner(msg) => AllMessages::Provisioner(msg),
}
}
}
// It looks like it's not possible to do an `impl From` given the current state of
// the code. So this does the necessary conversion.
fn primitive_statement_to_table(s: &SignedFullStatement) -> TableSignedStatement {
let statement = match s.payload() {
Statement::Seconded(c) => TableStatement::Candidate(c.clone()),
Statement::Valid(h) => TableStatement::Valid(h.clone()),
Statement::Invalid(h) => TableStatement::Invalid(h.clone()),
};
TableSignedStatement {
statement,
signature: s.signature().clone(),
sender: s.validator_index(),
}
}
// finds the first key we are capable of signing with out of the given set of validators,
// if any.
fn signing_key(validators: &[ValidatorId], keystore: &KeyStorePtr) -> Option<ValidatorPair> {
let keystore = keystore.read();
validators.iter()
.find_map(|v| {
keystore.key_pair::<ValidatorPair>(&v).ok()
})
}
impl CandidateBackingJob {
/// Run asynchronously.
async fn run(mut self) -> Result<(), Error> {
while let Some(msg) = self.rx_to.next().await {
match msg {
ToJob::CandidateBacking(msg) => {
self.process_msg(msg).await?;
}
_ => break,
}
}
Ok(())
}
async fn issue_candidate_invalid_message(
&mut self,
candidate: AbridgedCandidateReceipt,
) -> Result<(), Error> {
self.tx_from.send(FromJob::CandidateSelection(
CandidateSelectionMessage::Invalid(self.parent, candidate)
)).await?;
Ok(())
}
/// Validate the candidate that is requested to be `Second`ed and distribute validation result.
async fn validate_and_second(
&mut self,
candidate: AbridgedCandidateReceipt,
pov: PoVBlock,
) -> Result<ValidationResult, Error> {
let valid = self.request_candidate_validation(candidate.clone(), pov.clone()).await?;
let statement = match valid.0 {
ValidationResult::Valid => {
// make PoV available for later distribution. Send data to the availability
// store to keep. Sign and dispatch `valid` statement to network if we
// have not seconded the given candidate.
self.make_pov_available(pov, valid.1, valid.2).await?;
self.issued_statements.insert(candidate.hash());
Statement::Seconded(candidate)
}
ValidationResult::Invalid => {
let candidate_hash = candidate.hash();
self.issue_candidate_invalid_message(candidate).await?;
Statement::Invalid(candidate_hash)
}
};
if let Some(signed_statement) = self.sign_statement(statement) {
self.import_statement(&signed_statement).await?;
self.distribute_signed_statement(signed_statement).await?;
}
Ok(valid.0)
}
fn get_backed(&self) -> Vec<NewBackedCandidate> {
let proposed = self.table.proposed_candidates(&self.table_context);
let mut res = Vec::with_capacity(proposed.len());
for p in proposed.into_iter() {
let TableAttestedCandidate { candidate, validity_votes, .. } = p;
let (ids, validity_votes): (Vec<_>, Vec<_>) = validity_votes
.into_iter()
.map(|(id, vote)| (id, vote.into()))
.unzip();
let group = match self.table_context.groups.get(&self.assignment) {
Some(group) => group,
None => continue,
};
let mut validator_indices = BitVec::with_capacity(
group.len()
);
validator_indices.resize(group.len(), false);
for id in ids.iter() {
if let Some(position) = group.iter().position(|x| x == id) {
validator_indices.set(position, true);
}
}
let backed = BackedCandidate {
candidate,
validity_votes,
validator_indices,
};
res.push(NewBackedCandidate(backed.clone()));
}
res
}
/// Check if there have happened any new misbehaviors and issue necessary messages.
///
/// TODO: Report multiple misbehaviors (https://github.com/paritytech/polkadot/issues/1387)
async fn issue_new_misbehaviors(&mut self) -> Result<(), Error> {
let mut reports = Vec::new();
for (k, v) in self.table.get_misbehavior().iter() {
if !self.reported_misbehavior_for.contains(k) {
self.reported_misbehavior_for.insert(*k);
let f = FromTableMisbehavior {
id: *k,
report: v.clone(),
signing_context: self.table_context.signing_context.clone(),
key: self.table_context.validators[*k as usize].clone(),
};
if let Ok(report) = MisbehaviorReport::try_from(f) {
let message = ProvisionerMessage::ProvisionableData(
ProvisionableData::MisbehaviorReport(self.parent, report)
);
reports.push(message);
}
}
}
for report in reports.drain(..) {
self.send_to_provisioner(report).await?
}
Ok(())
}
/// Import a statement into the statement table and return the summary of the import.
async fn import_statement(
&mut self,
statement: &SignedFullStatement,
) -> Result<Option<TableSummary>, Error> {
let stmt = primitive_statement_to_table(statement);
let summary = self.table.import_statement(&self.table_context, stmt);
self.issue_new_misbehaviors().await?;
return Ok(summary);
}
async fn process_msg(&mut self, msg: CandidateBackingMessage) -> Result<(), Error> {
match msg {
CandidateBackingMessage::Second(_, candidate, pov) => {
// Sanity check that candidate is from our assignment.
if candidate.parachain_index != self.assignment {
return Ok(());
}
// If the message is a `CandidateBackingMessage::Second`, sign and dispatch a
// Seconded statement only if we have not seconded any other candidate and
// have not signed a Valid statement for the requested candidate.
match self.seconded {
// This job has not seconded a candidate yet.
None => {
let candidate_hash = candidate.hash();
if !self.issued_statements.contains(&candidate_hash) {
if let Ok(ValidationResult::Valid) = self.validate_and_second(
candidate,
pov,
).await {
self.seconded = Some(candidate_hash);
}
}
}
// This job has already seconded a candidate.
Some(_) => {}
}
}
CandidateBackingMessage::Statement(_, statement) => {
self.check_statement_signature(&statement)?;
self.maybe_validate_and_import(statement).await?;
}
CandidateBackingMessage::GetBackedCandidates(_, tx) => {
let backed = self.get_backed();
tx.send(backed).map_err(|_| oneshot::Canceled)?;
}
}
Ok(())
}
/// Kick off validation work and distribute the result as a signed statement.
async fn kick_off_validation_work(
&mut self,
summary: TableSummary,
) -> Result<ValidationResult, Error> {
let candidate = self.table.get_candidate(&summary.candidate).ok_or(Error::CandidateNotFound)?;
let candidate = candidate.clone();
let descriptor = candidate.to_descriptor();
let candidate_hash = candidate.hash();
let pov = self.request_pov_from_distribution(descriptor).await?;
let v = self.request_candidate_validation(candidate, pov).await?;
let statement = match v.0 {
ValidationResult::Valid => {
Statement::Valid(candidate_hash)
}
ValidationResult::Invalid => {
Statement::Invalid(candidate_hash)
}
};
self.issued_statements.insert(candidate_hash);
if let Some(signed_statement) = self.sign_statement(statement) {
self.distribute_signed_statement(signed_statement).await?;
}
Ok(v.0)
}
/// Import the statement and kick off validation work if it is a part of our assignment.
async fn maybe_validate_and_import(
&mut self,
statement: SignedFullStatement,
) -> Result<(), Error> {
if let Some(summary) = self.import_statement(&statement).await? {
if let Statement::Seconded(_) = statement.payload() {
if summary.group_id == self.assignment {
self.kick_off_validation_work(summary).await?;
}
}
}
Ok(())
}
fn sign_statement(&self, statement: Statement) -> Option<SignedFullStatement> {
let local_index = self.table_context.local_index()?;
let signing_key = self.table_context.key.as_ref()?;
let signed_statement = SignedFullStatement::sign(
statement,
&self.table_context.signing_context,
local_index,
signing_key,
);
Some(signed_statement)
}
fn check_statement_signature(&self, statement: &SignedFullStatement) -> Result<(), Error> {
let idx = statement.validator_index() as usize;
if self.table_context.validators.len() > idx {
statement.check_signature(
&self.table_context.signing_context,
&self.table_context.validators[idx],
).map_err(|_| Error::InvalidSignature)?;
} else {
return Err(Error::InvalidSignature);
}
Ok(())
}
async fn send_to_provisioner(&mut self, msg: ProvisionerMessage) -> Result<(), Error> {
self.tx_from.send(FromJob::Provisioner(msg)).await?;
Ok(())
}
async fn request_pov_from_distribution(
&mut self,
descriptor: CandidateDescriptor,
) -> Result<PoVBlock, Error> {
let (tx, rx) = oneshot::channel();
self.tx_from.send(FromJob::PoVDistribution(
PoVDistributionMessage::FetchPoV(self.parent, descriptor, tx)
)).await?;
let pov = rx.await?;
Ok((*pov).clone())
}
async fn request_candidate_validation(
&mut self,
candidate: AbridgedCandidateReceipt,
pov: PoVBlock,
) -> Result<(ValidationResult, GlobalValidationSchedule, LocalValidationData), Error> {
let (tx, rx) = oneshot::channel();
self.tx_from.send(FromJob::CandidateValidation(
CandidateValidationMessage::Validate(
self.parent,
candidate,
self.head_data.clone(),
pov,
tx,
)
)
).await?;
Ok(rx.await??)
}
async fn store_chunk(
&mut self,
id: ValidatorIndex,
chunk: ErasureChunk,
) -> Result<(), Error> {
self.tx_from.send(FromJob::AvailabilityStore(
AvailabilityStoreMessage::StoreChunk(self.parent, id, chunk)
)
).await?;
Ok(())
}
async fn make_pov_available(
&mut self,
pov_block: PoVBlock,
global_validation: GlobalValidationSchedule,
local_validation: LocalValidationData,
) -> Result<(), Error> {
let omitted_validation = OmittedValidationData {
global_validation,
local_validation,
};
let available_data = AvailableData {
pov_block,
omitted_validation,
};
let chunks = erasure_coding::obtain_chunks(
self.table_context.validators.len(),
&available_data,
)?;
let branches = erasure_coding::branches(chunks.as_ref());
for (index, (chunk, proof)) in chunks.iter().zip(branches.map(|(proof, _)| proof)).enumerate() {
let chunk = ErasureChunk {
chunk: chunk.clone(),
index: index as u32,
proof,
};
self.store_chunk(index as ValidatorIndex, chunk).await?;
}
Ok(())
}
async fn distribute_signed_statement(&mut self, s: SignedFullStatement) -> Result<(), Error> {
let smsg = StatementDistributionMessage::Share(self.parent, s);
self.tx_from.send(FromJob::StatementDistribution(smsg)).await?;
Ok(())
}
}
struct JobHandle {
abort_handle: future::AbortHandle,
to_job: mpsc::Sender<ToJob>,
finished: oneshot::Receiver<()>,
su_handle: usize,
}
impl JobHandle {
async fn stop(mut self) {
let _ = self.to_job.send(ToJob::Stop).await;
let stop_timer = Delay::new(Duration::from_secs(1));
match future::select(stop_timer, self.finished).await {
Either::Left((_, _)) => {
},
Either::Right((_, _)) => {
self.abort_handle.abort();
},
}
}
async fn send_msg(&mut self, msg: ToJob) -> Result<(), Error> {
Ok(self.to_job.send(msg).await?)
}
}
struct Jobs<S> {
spawner: S,
running: HashMap<Hash, JobHandle>,
outgoing_msgs: StreamUnordered<mpsc::Receiver<FromJob>>,
}
async fn run_job(
parent: Hash,
keystore: KeyStorePtr,
rx_to: mpsc::Receiver<ToJob>,
mut tx_from: mpsc::Sender<FromJob>,
) -> Result<(), Error> {
let (validators, roster) = futures::try_join!(
request_validators(parent, &mut tx_from).await?,
request_validator_groups(parent, &mut tx_from).await?,
)?;
let key = signing_key(&validators[..], &keystore).ok_or(Error::NotInValidatorSet)?;
let mut groups = HashMap::new();
for assignment in roster.scheduled {
if let Some(g) = roster.validator_groups.get(assignment.group_idx.0 as usize) {
groups.insert(
assignment.para_id,
g.clone(),
);
}
}
let mut assignment = Default::default();
if let Some(idx) = validators.iter().position(|k| *k == key.public()) {
let idx = idx as u32;
for (para_id, group) in groups.iter() {
if group.contains(&idx) {
assignment = *para_id;
break;
}
}
}
let (
head_data,
signing_context,
) = futures::try_join!(
request_head_data(parent, &mut tx_from, assignment).await?,
request_signing_context(parent, &mut tx_from).await?,
)?;
let table_context = TableContext {
signing_context,
key: Some(key),
groups,
validators,
};
let job = CandidateBackingJob {
parent,
rx_to,
tx_from,
head_data,
assignment,
issued_statements: HashSet::new(),
seconded: None,
reported_misbehavior_for: HashSet::new(),
table: Table::default(),
table_context,
};
job.run().await
}
/// Request a validator set from the `RuntimeApi`.
async fn request_validators(
parent: Hash,
s: &mut mpsc::Sender<FromJob>,
) -> Result<oneshot::Receiver<Vec<ValidatorId>>, Error> {
let (tx, rx) = oneshot::channel();
s.send(FromJob::RuntimeApiMessage(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::Validators(tx),
)
)).await?;
Ok(rx)
}
/// Request the scheduler roster from `RuntimeApi`.
async fn request_validator_groups(
parent: Hash,
s: &mut mpsc::Sender<FromJob>,
) -> Result<oneshot::Receiver<SchedulerRoster>, Error> {
let (tx, rx) = oneshot::channel();
s.send(FromJob::RuntimeApiMessage(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::ValidatorGroups(tx),
)
)).await?;
Ok(rx)
}
/// Request a `SigningContext` from the `RuntimeApi`.
async fn request_signing_context(
parent: Hash,
s: &mut mpsc::Sender<FromJob>,
) -> Result<oneshot::Receiver<SigningContext>, Error> {
let (tx, rx) = oneshot::channel();
s.send(FromJob::RuntimeApiMessage(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::SigningContext(tx),
)
)).await?;
Ok(rx)
}
/// Request `HeadData` for some `ParaId` from `RuntimeApi`.
async fn request_head_data(
parent: Hash,
s: &mut mpsc::Sender<FromJob>,
id: ParaId,
) -> Result<oneshot::Receiver<HeadData>, Error> {
let (tx, rx) = oneshot::channel();
s.send(FromJob::RuntimeApiMessage(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::HeadData(id, tx),
)
)).await?;
Ok(rx)
}
impl<S: Spawn> Jobs<S> {
fn new(spawner: S) -> Self {
Self {
spawner,
running: HashMap::default(),
outgoing_msgs: StreamUnordered::new(),
}
}
fn spawn_job(&mut self, parent_hash: Hash, keystore: KeyStorePtr) -> Result<(), Error> {
let (to_job_tx, to_job_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (from_job_tx, from_job_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (future, abort_handle) = future::abortable(async move {
if let Err(e) = run_job(parent_hash, keystore, to_job_rx, from_job_tx).await {
log::error!(
"CandidateBackingJob({}) finished with an error {:?}",
parent_hash,
e,
);
}
});
let (finished_tx, finished) = oneshot::channel();
let future = async move {
let _ = future.await;
let _ = finished_tx.send(());
};
self.spawner.spawn(future)?;
let su_handle = self.outgoing_msgs.push(from_job_rx);
let handle = JobHandle {
abort_handle,
to_job: to_job_tx,
finished,
su_handle,
};
self.running.insert(parent_hash, handle);
Ok(())
}
async fn stop_job(&mut self, parent_hash: Hash) -> Result<(), Error> {
match self.running.remove(&parent_hash) {
Some(handle) => {
Pin::new(&mut self.outgoing_msgs).remove(handle.su_handle);
handle.stop().await;
Ok(())
}
None => Err(Error::JobNotFound(parent_hash))
}
}
async fn send_msg(&mut self, parent_hash: Hash, msg: ToJob) -> Result<(), Error> {
if let Some(job) = self.running.get_mut(&parent_hash) {
job.send_msg(msg).await?;
}
Ok(())
}
async fn next(&mut self) -> Option<FromJob> {
self.outgoing_msgs.next().await.and_then(|(e, _)| match e {
StreamYield::Item(e) => Some(e),
_ => None,
})
}
}
/// An implementation of the Candidate Backing subsystem.
pub struct CandidateBackingSubsystem<S, Context> {
spawner: S,
keystore: KeyStorePtr,
_context: std::marker::PhantomData<Context>,
}
impl<S, Context> CandidateBackingSubsystem<S, Context>
where
S: Spawn + Clone,
Context: SubsystemContext<Message=CandidateBackingMessage>,
{
/// Creates a new `CandidateBackingSubsystem`.
pub fn new(keystore: KeyStorePtr, spawner: S) -> Self {
Self {
spawner,
keystore,
_context: std::marker::PhantomData,
}
}
async fn run(
mut ctx: Context,
keystore: KeyStorePtr,
spawner: S,
) {
let mut jobs = Jobs::new(spawner.clone());
loop {
select! {
incoming = ctx.recv().fuse() => {
match incoming {
Ok(msg) => match msg {
FromOverseer::Signal(OverseerSignal::StartWork(hash)) => {
if let Err(e) = jobs.spawn_job(hash, keystore.clone()) {
log::error!("Failed to spawn a job: {:?}", e);
break;
}
}
FromOverseer::Signal(OverseerSignal::StopWork(hash)) => {
if let Err(e) = jobs.stop_job(hash).await {
log::error!("Failed to spawn a job: {:?}", e);
break;
}
}
FromOverseer::Communication { msg } => {
match msg {
CandidateBackingMessage::Second(hash, _, _) |
CandidateBackingMessage::Statement(hash, _) |
CandidateBackingMessage::GetBackedCandidates(hash, _) => {
let res = jobs.send_msg(
hash.clone(),
ToJob::CandidateBacking(msg),
).await;
if let Err(e) = res {
log::error!(
"Failed to send a message to a job: {:?}",
e,
);
break;
}
}
_ => (),
}
}
_ => (),
},
Err(_) => break,
}
}
outgoing = jobs.next().fuse() => {
match outgoing {
Some(msg) => {
let _ = ctx.send_message(msg.into()).await;
}
None => break,
}
}
complete => break,
}
}
}
}
impl<S, Context> Subsystem<Context> for CandidateBackingSubsystem<S, Context>
where
S: Spawn + Send + Clone + 'static,
Context: SubsystemContext<Message=CandidateBackingMessage>,
{
fn start(self, ctx: Context) -> SpawnedSubsystem {
let keystore = self.keystore.clone();
let spawner = self.spawner.clone();
SpawnedSubsystem(Box::pin(async move {
Self::run(ctx, keystore, spawner).await;
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{Future, executor::{self, ThreadPool}};
use std::collections::HashMap;
use std::sync::Arc;
use sp_keyring::Sr25519Keyring;
use polkadot_primitives::parachain::{
AssignmentKind, CollatorId, CoreAssignment, BlockData, CoreIndex, GroupIndex, ValidityAttestation,
};
use assert_matches::assert_matches;
fn validator_pubkeys(val_ids: &[Sr25519Keyring]) -> Vec<ValidatorId> {
val_ids.iter().map(|v| v.public().into()).collect()
}
struct TestState {
chain_ids: Vec<ParaId>,
keystore: KeyStorePtr,
validators: Vec<Sr25519Keyring>,
validator_public: Vec<ValidatorId>,
global_validation_schedule: GlobalValidationSchedule,
local_validation_data: LocalValidationData,
roster: SchedulerRoster,
head_data: HashMap<ParaId, HeadData>,
signing_context: SigningContext,
relay_parent: Hash,
}
impl Default for TestState {
fn default() -> Self {
let chain_a = ParaId::from(1);
let chain_b = ParaId::from(2);
let thread_a = ParaId::from(3);
let chain_ids = vec![chain_a, chain_b, thread_a];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Sr25519Keyring::Charlie,
Sr25519Keyring::Dave,
Sr25519Keyring::Ferdie,
];
let keystore = keystore::Store::new_in_memory();
// Make sure `Alice` key is in the keystore, so this mocked node will be a parachain validator.
keystore.write().insert_ephemeral_from_seed::<ValidatorPair>(&validators[0].to_seed())
.expect("Insert key into keystore");
let validator_public = validator_pubkeys(&validators);
let chain_a_assignment = CoreAssignment {
core: CoreIndex::from(0),
para_id: chain_a,
kind: AssignmentKind::Parachain,
group_idx: GroupIndex::from(0),
};
let chain_b_assignment = CoreAssignment {
core: CoreIndex::from(1),
para_id: chain_b,
kind: AssignmentKind::Parachain,
group_idx: GroupIndex::from(1),
};
let thread_collator: CollatorId = Sr25519Keyring::Two.public().into();
let thread_a_assignment = CoreAssignment {
core: CoreIndex::from(2),
para_id: thread_a,
kind: AssignmentKind::Parathread(thread_collator.clone(), 0),
group_idx: GroupIndex::from(2),
};
let validator_groups = vec![vec![2, 0, 3], vec![1], vec![4]];
let parent_hash_1 = [1; 32].into();
let roster = SchedulerRoster {
validator_groups,
scheduled: vec![
chain_a_assignment,
chain_b_assignment,
thread_a_assignment,
],
upcoming: vec![],
availability_cores: vec![],
};
let signing_context = SigningContext {
session_index: 1,
parent_hash: parent_hash_1,
};
let mut head_data = HashMap::new();