1use crate::SubspaceLink;
19use crate::archiver::SegmentHeadersStore;
20use futures::channel::mpsc;
21use futures::{StreamExt, TryFutureExt};
22use sc_client_api::AuxStore;
23use sc_consensus::block_import::{BlockImportParams, StateAction};
24use sc_consensus::{BoxBlockImport, JustificationSyncLink, StorageChanges};
25use sc_consensus_slots::{
26 BackoffAuthoringBlocksStrategy, SimpleSlotWorker, SlotInfo, SlotLenienceType, SlotProportion,
27};
28use sc_proof_of_time::PotSlotWorker;
29use sc_proof_of_time::source::pot_next_slot_input;
30use sc_proof_of_time::verifier::PotVerifier;
31use sc_telemetry::TelemetryHandle;
32use sc_transaction_pool_api::OffchainTransactionPoolFactory;
33use sc_utils::mpsc::{TracingUnboundedSender, tracing_unbounded};
34use schnorrkel::context::SigningContext;
35use sp_api::{ApiError, ApiExt, ProvideRuntimeApi};
36use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata};
37use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, SyncOracle};
38use sp_consensus_slots::Slot;
39use sp_consensus_subspace::digests::{
40 CompatibleDigestItem, PreDigest, PreDigestPotInfo, extract_pre_digest,
41};
42use sp_consensus_subspace::{
43 PotNextSlotInput, SignedVote, SubspaceApi, SubspaceJustification, Vote,
44};
45use sp_core::H256;
46use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One, Saturating, Zero};
47use sp_runtime::{DigestItem, Justification, Justifications};
48use std::collections::BTreeMap;
49use std::future::Future;
50use std::marker::PhantomData;
51use std::pin::Pin;
52use std::sync::Arc;
53use std::sync::atomic::{AtomicBool, Ordering};
54use subspace_core_primitives::pot::{PotCheckpoints, PotOutput};
55use subspace_core_primitives::sectors::SectorId;
56use subspace_core_primitives::solutions::{RewardSignature, Solution, SolutionRange};
57use subspace_core_primitives::{BlockNumber, PublicKey, REWARD_SIGNING_CONTEXT};
58use subspace_proof_of_space::Table;
59use subspace_verification::{
60 PieceCheckParams, VerifySolutionParams, check_reward_signature, verify_solution,
61};
62use tracing::{debug, error, info, warn};
63
64const PENDING_SOLUTIONS_CHANNEL_CAPACITY: usize = 10;
66
67#[derive(Debug, Clone)]
75pub struct SubspaceSyncOracle<SO>
76where
77 SO: SyncOracle + Send + Sync,
78{
79 force_authoring: bool,
80 pause_sync: Arc<AtomicBool>,
81 inner: SO,
82}
83
84impl<SO> SyncOracle for SubspaceSyncOracle<SO>
85where
86 SO: SyncOracle + Send + Sync,
87{
88 fn is_major_syncing(&self) -> bool {
89 (!self.force_authoring && self.inner.is_major_syncing())
93 || self.pause_sync.load(Ordering::Acquire)
94 }
95
96 fn is_offline(&self) -> bool {
97 self.inner.is_offline()
98 }
99}
100
101impl<SO> SubspaceSyncOracle<SO>
102where
103 SO: SyncOracle + Send + Sync,
104{
105 pub fn new(
107 force_authoring: bool,
108 pause_sync: Arc<AtomicBool>,
109 substrate_sync_oracle: SO,
110 ) -> Self {
111 Self {
112 force_authoring,
113 pause_sync,
114 inner: substrate_sync_oracle,
115 }
116 }
117}
118
119#[derive(Debug, Copy, Clone)]
121pub struct NewSlotInfo {
122 pub slot: Slot,
124 pub proof_of_time: PotOutput,
126 pub solution_range: SolutionRange,
128 pub voting_solution_range: SolutionRange,
130}
131
132#[derive(Debug, Clone)]
134pub struct NewSlotNotification {
135 pub new_slot_info: NewSlotInfo,
137 pub solution_sender: mpsc::Sender<Solution<PublicKey>>,
139}
140#[derive(Debug, Clone)]
142pub struct RewardSigningNotification {
143 pub hash: H256,
145 pub public_key: PublicKey,
147 pub signature_sender: TracingUnboundedSender<RewardSignature>,
149}
150
151pub struct SubspaceSlotWorkerOptions<Block, Client, E, SO, L, BS, AS>
153where
154 Block: BlockT,
155 SO: SyncOracle + Send + Sync,
156{
157 pub client: Arc<Client>,
159 pub env: E,
161 pub block_import: BoxBlockImport<Block>,
165 pub sync_oracle: SubspaceSyncOracle<SO>,
167 pub justification_sync_link: L,
169 pub force_authoring: bool,
171 pub backoff_authoring_blocks: Option<BS>,
173 pub subspace_link: SubspaceLink<Block>,
175 pub segment_headers_store: SegmentHeadersStore<AS>,
177 pub block_proposal_slot_portion: SlotProportion,
183 pub max_block_proposal_slot_portion: Option<SlotProportion>,
186 pub telemetry: Option<TelemetryHandle>,
188 pub offchain_tx_pool_factory: OffchainTransactionPoolFactory<Block>,
192 pub pot_verifier: PotVerifier,
194}
195
196pub struct SubspaceSlotWorker<PosTable, Block, Client, E, SO, L, BS, AS>
198where
199 Block: BlockT,
200 SO: SyncOracle + Send + Sync,
201{
202 client: Arc<Client>,
203 block_import: BoxBlockImport<Block>,
204 env: E,
205 sync_oracle: SubspaceSyncOracle<SO>,
206 justification_sync_link: L,
207 force_authoring: bool,
208 backoff_authoring_blocks: Option<BS>,
209 subspace_link: SubspaceLink<Block>,
210 reward_signing_context: SigningContext,
211 block_proposal_slot_portion: SlotProportion,
212 max_block_proposal_slot_portion: Option<SlotProportion>,
213 telemetry: Option<TelemetryHandle>,
214 offchain_tx_pool_factory: OffchainTransactionPoolFactory<Block>,
215 segment_headers_store: SegmentHeadersStore<AS>,
216 pending_solutions: BTreeMap<Slot, mpsc::Receiver<Solution<PublicKey>>>,
219 pot_checkpoints: BTreeMap<Slot, PotCheckpoints>,
221 pot_verifier: PotVerifier,
222 _pos_table: PhantomData<PosTable>,
223}
224
225impl<PosTable, Block, Client, E, SO, L, BS, AS> PotSlotWorker<Block>
226 for SubspaceSlotWorker<PosTable, Block, Client, E, SO, L, BS, AS>
227where
228 Block: BlockT,
229 Client: HeaderBackend<Block> + ProvideRuntimeApi<Block>,
230 Client::Api: SubspaceApi<Block, PublicKey>,
231 SO: SyncOracle + Send + Sync,
232{
233 fn on_proof(&mut self, slot: Slot, checkpoints: PotCheckpoints) {
234 let oldest_claimable_slot =
236 slot.saturating_sub(self.subspace_link.chain_constants().block_authoring_delay());
237
238 self.pot_checkpoints.retain(|&stored_slot, _checkpoints| {
241 (oldest_claimable_slot..slot).contains(&stored_slot)
242 });
243 self.pending_solutions
245 .retain(|&stored_slot, _solution_receiver| stored_slot >= oldest_claimable_slot);
246
247 self.pot_checkpoints.insert(slot, checkpoints);
248
249 if self.sync_oracle.is_major_syncing() {
250 debug!("Skipping farming slot {slot} due to sync");
251 return;
252 }
253
254 let maybe_root_plot_public_key = self
255 .client
256 .runtime_api()
257 .root_plot_public_key(self.client.info().best_hash)
258 .ok()
259 .flatten();
260 if maybe_root_plot_public_key.is_some() && !self.force_authoring {
261 debug!(
262 "Skipping farming slot {slot} due to root public key present and force authoring \
263 not enabled"
264 );
265 return;
266 }
267
268 let proof_of_time = checkpoints.output();
269
270 let best_hash = self.client.info().best_hash;
273 let (solution_range, voting_solution_range) =
274 match extract_solution_ranges_for_block(self.client.as_ref(), best_hash) {
275 Ok(solution_ranges) => solution_ranges,
276 Err(error) => {
277 warn!(
278 %slot,
279 %best_hash,
280 %error,
281 "Failed to extract solution ranges for block"
282 );
283 return;
284 }
285 };
286
287 let new_slot_info = NewSlotInfo {
288 slot,
289 proof_of_time,
290 solution_range,
291 voting_solution_range,
292 };
293 let (solution_sender, solution_receiver) =
294 mpsc::channel(PENDING_SOLUTIONS_CHANNEL_CAPACITY);
295
296 self.subspace_link
297 .new_slot_notification_sender
298 .notify(|| NewSlotNotification {
299 new_slot_info,
300 solution_sender,
301 });
302
303 self.pending_solutions.insert(slot, solution_receiver);
304 }
305}
306
307#[async_trait::async_trait]
308impl<PosTable, Block, Client, E, Error, SO, L, BS, AS> SimpleSlotWorker<Block>
309 for SubspaceSlotWorker<PosTable, Block, Client, E, SO, L, BS, AS>
310where
311 PosTable: Table,
312 Block: BlockT,
313 Client: ProvideRuntimeApi<Block>
314 + HeaderBackend<Block>
315 + HeaderMetadata<Block, Error = ClientError>
316 + AuxStore
317 + 'static,
318 Client::Api: SubspaceApi<Block, PublicKey>,
319 E: Environment<Block, Error = Error> + Send + Sync,
320 E::Proposer: Proposer<Block, Error = Error>,
321 SO: SyncOracle + Send + Sync,
322 L: JustificationSyncLink<Block>,
323 BS: BackoffAuthoringBlocksStrategy<NumberFor<Block>> + Send + Sync,
324 Error: std::error::Error + Send + From<ConsensusError> + 'static,
325 AS: AuxStore + Send + Sync + 'static,
326 BlockNumber: From<NumberFor<Block>>,
327{
328 type BlockImport = BoxBlockImport<Block>;
329 type SyncOracle = SubspaceSyncOracle<SO>;
330 type JustificationSyncLink = L;
331 type CreateProposer =
332 Pin<Box<dyn Future<Output = Result<E::Proposer, ConsensusError>> + Send + 'static>>;
333 type Proposer = E::Proposer;
334 type Claim = (PreDigest<PublicKey>, SubspaceJustification);
335 type AuxData = ();
336
337 fn logging_target(&self) -> &'static str {
338 "subspace"
339 }
340
341 fn block_import(&mut self) -> &mut Self::BlockImport {
342 &mut self.block_import
343 }
344
345 fn aux_data(
346 &self,
347 _parent: &Block::Header,
348 _slot: Slot,
349 ) -> Result<Self::AuxData, ConsensusError> {
350 Ok(())
351 }
352
353 fn authorities_len(&self, _epoch_data: &Self::AuxData) -> Option<usize> {
354 Some(2)
358 }
359
360 async fn claim_slot(
361 &mut self,
362 parent_header: &Block::Header,
363 slot: Slot,
364 _aux_data: &Self::AuxData,
365 ) -> Option<Self::Claim> {
366 let parent_pre_digest = match extract_pre_digest(parent_header) {
367 Ok(pre_digest) => pre_digest,
368 Err(error) => {
369 error!(
370 %error,
371 "Failed to parse pre-digest out of parent header"
372 );
373
374 return None;
375 }
376 };
377 let parent_slot = parent_pre_digest.slot();
378
379 if slot <= parent_slot {
380 debug!(
381 "Skipping claiming slot {slot} it must be higher than parent slot {parent_slot}",
382 );
383
384 return None;
385 } else {
386 debug!(%slot, "Attempting to claim slot");
387 }
388
389 let chain_constants = self.subspace_link.chain_constants();
390
391 let parent_hash = parent_header.hash();
392 let runtime_api = self.client.runtime_api();
393
394 let (solution_range, voting_solution_range) =
395 extract_solution_ranges_for_block(self.client.as_ref(), parent_hash).ok()?;
396
397 let maybe_root_plot_public_key = runtime_api.root_plot_public_key(parent_hash).ok()?;
398
399 let parent_pot_parameters = runtime_api.pot_parameters(parent_hash).ok()?;
400 let parent_future_slot = if parent_header.number().is_zero() {
401 parent_slot
402 } else {
403 parent_slot + chain_constants.block_authoring_delay()
404 };
405
406 let (proof_of_time, future_proof_of_time, pot_justification) = {
407 let proof_of_time = self.pot_checkpoints.get(&slot)?.output();
408
409 let future_slot = slot + chain_constants.block_authoring_delay();
411
412 let pot_input = pot_next_slot_input::<Block>(
413 parent_header.number(),
414 parent_slot,
415 &parent_pot_parameters,
416 self.pot_verifier.genesis_seed(),
417 parent_pre_digest.pot_info().proof_of_time(),
418 );
419
420 if !self.pot_verifier.is_output_valid(
422 pot_input,
423 slot - parent_slot,
424 proof_of_time,
425 parent_pot_parameters.next_parameters_change(),
426 ) {
427 warn!(
428 %slot,
429 ?pot_input,
430 ?parent_pot_parameters,
431 "Proof of time is invalid, skipping block authoring at slot"
432 );
433 return None;
434 }
435
436 let mut checkpoints_pot_input = if parent_header.number().is_zero() {
437 PotNextSlotInput {
438 slot: parent_slot + Slot::from(1),
439 slot_iterations: parent_pot_parameters.slot_iterations(),
440 seed: self.pot_verifier.genesis_seed(),
441 }
442 } else {
443 let parent_pot_info = parent_pre_digest.pot_info();
444
445 PotNextSlotInput::derive(
446 parent_pot_parameters.slot_iterations(),
447 parent_future_slot,
448 parent_pot_info.future_proof_of_time(),
449 &parent_pot_parameters.next_parameters_change(),
450 )
451 };
452 let seed = checkpoints_pot_input.seed;
453
454 let mut checkpoints = Vec::with_capacity((*future_slot - *parent_future_slot) as usize);
455
456 for slot in *parent_future_slot + 1..=*future_slot {
457 let slot = Slot::from(slot);
458 let maybe_slot_checkpoints = self.pot_verifier.get_checkpoints(
459 checkpoints_pot_input.slot_iterations,
460 checkpoints_pot_input.seed,
461 );
462 let Some(slot_checkpoints) = maybe_slot_checkpoints else {
463 warn!("Proving failed during block authoring");
464 return None;
465 };
466
467 checkpoints.push(slot_checkpoints);
468
469 checkpoints_pot_input = PotNextSlotInput::derive(
470 checkpoints_pot_input.slot_iterations,
471 slot,
472 slot_checkpoints.output(),
473 &parent_pot_parameters.next_parameters_change(),
474 );
475 }
476
477 let future_proof_of_time = checkpoints
478 .last()
479 .expect("Never empty, there is at least one slot between blocks; qed")
480 .output();
481
482 let pot_justification = SubspaceJustification::PotCheckpoints { seed, checkpoints };
483
484 (proof_of_time, future_proof_of_time, pot_justification)
485 };
486
487 let mut solution_receiver = {
488 let mut solution_receiver = self.pending_solutions.remove(&slot)?;
489 solution_receiver.close();
491 solution_receiver
492 };
493
494 let mut maybe_pre_digest = None;
495
496 while let Some(solution) = solution_receiver.next().await {
497 if let Some(root_plot_public_key) = &maybe_root_plot_public_key
498 && &solution.public_key != root_plot_public_key
499 {
500 continue;
503 }
504
505 let sector_id = SectorId::new(
506 solution.public_key.hash(),
507 solution.sector_index,
508 solution.history_size,
509 );
510
511 let history_size = runtime_api.history_size(parent_hash).ok()?;
512 let max_pieces_in_sector = runtime_api.max_pieces_in_sector(parent_hash).ok()?;
513
514 let segment_index = sector_id
515 .derive_piece_index(
516 solution.piece_offset,
517 solution.history_size,
518 max_pieces_in_sector,
519 chain_constants.recent_segments(),
520 chain_constants.recent_history_fraction(),
521 )
522 .segment_index();
523 let maybe_segment_commitment = self
524 .segment_headers_store
525 .get_segment_header(segment_index)
526 .map(|segment_header| segment_header.segment_commitment());
527
528 let segment_commitment = match maybe_segment_commitment {
529 Some(segment_commitment) => segment_commitment,
530 None => {
531 warn!(
532 %slot,
533 %segment_index,
534 "Segment commitment not found",
535 );
536 continue;
537 }
538 };
539 let sector_expiration_check_segment_index = match solution
540 .history_size
541 .sector_expiration_check(chain_constants.min_sector_lifetime())
542 {
543 Some(sector_expiration_check) => sector_expiration_check.segment_index(),
544 None => {
545 continue;
546 }
547 };
548 let sector_expiration_check_segment_commitment = self
549 .segment_headers_store
550 .get_segment_header(sector_expiration_check_segment_index)
551 .map(|segment_header| segment_header.segment_commitment());
552
553 let solution_verification_result = verify_solution::<PosTable, _>(
554 &solution,
555 slot.into(),
556 &VerifySolutionParams {
557 proof_of_time,
558 solution_range: voting_solution_range,
559 piece_check_params: Some(PieceCheckParams {
560 max_pieces_in_sector,
561 segment_commitment,
562 recent_segments: chain_constants.recent_segments(),
563 recent_history_fraction: chain_constants.recent_history_fraction(),
564 min_sector_lifetime: chain_constants.min_sector_lifetime(),
565 current_history_size: history_size,
566 sector_expiration_check_segment_commitment,
567 }),
568 },
569 &self.subspace_link.kzg,
570 );
571
572 match solution_verification_result {
573 Ok(solution_distance) => {
574 if solution_distance <= solution_range / 2 {
577 if maybe_pre_digest.is_none() {
578 info!(%slot, "🚜 Claimed block at slot");
579 maybe_pre_digest.replace(PreDigest::V0 {
580 slot,
581 solution,
582 pot_info: PreDigestPotInfo::V0 {
583 proof_of_time,
584 future_proof_of_time,
585 },
586 });
587 } else {
588 info!(
589 %slot,
590 "Skipping solution that has quality sufficient for block because \
591 block pre-digest was already created",
592 );
593 }
594 } else if !parent_header.number().is_zero() {
595 info!(%slot, "🗳️ Claimed vote at slot");
598
599 self.create_vote(
600 parent_header,
601 slot,
602 solution,
603 proof_of_time,
604 future_proof_of_time,
605 )
606 .await;
607 }
608 }
609 Err(error @ subspace_verification::Error::OutsideSolutionRange { .. }) => {
610 if runtime_api
613 .solution_ranges(parent_hash)
614 .ok()
615 .and_then(|solution_ranges| solution_ranges.next)
616 .is_some()
617 {
618 debug!(
619 %slot,
620 %error,
621 "Invalid solution received",
622 );
623 } else {
624 warn!(
625 %slot,
626 %error,
627 "Invalid solution received",
628 );
629 }
630 }
631 Err(error) => {
632 warn!(
633 %slot,
634 %error,
635 "Invalid solution received",
636 );
637 }
638 }
639 }
640
641 maybe_pre_digest.map(|pre_digest| (pre_digest, pot_justification))
642 }
643
644 fn pre_digest_data(
645 &self,
646 _slot: Slot,
647 (pre_digest, _justification): &Self::Claim,
648 ) -> Vec<DigestItem> {
649 vec![DigestItem::subspace_pre_digest(pre_digest)]
650 }
651
652 async fn block_import_params(
653 &self,
654 header: Block::Header,
655 header_hash: &Block::Hash,
656 body: Vec<Block::Extrinsic>,
657 storage_changes: sc_consensus_slots::StorageChanges<Block>,
658 (pre_digest, justification): Self::Claim,
659 _aux_data: Self::AuxData,
660 ) -> Result<BlockImportParams<Block>, ConsensusError> {
661 let signature = self
662 .sign_reward(
663 H256::from_slice(header_hash.as_ref()),
664 pre_digest.solution().public_key,
665 )
666 .await?;
667
668 let digest_item = DigestItem::subspace_seal(signature);
669
670 let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
671 import_block.post_digests.push(digest_item);
672 import_block.body = Some(body);
673 import_block.state_action =
674 StateAction::ApplyChanges(StorageChanges::Changes(storage_changes));
675 import_block
676 .justifications
677 .replace(Justifications::from(Justification::from(justification)));
678
679 Ok(import_block)
680 }
681
682 fn force_authoring(&self) -> bool {
683 self.force_authoring
684 }
685
686 fn should_backoff(&self, slot: Slot, chain_head: &Block::Header) -> bool {
687 if let Some(strategy) = &self.backoff_authoring_blocks
688 && let Ok(chain_head_slot) = extract_pre_digest(chain_head).map(|digest| digest.slot())
689 {
690 return strategy.should_backoff(
691 *chain_head.number(),
692 chain_head_slot,
693 self.client.info().finalized_number,
694 slot,
695 self.logging_target(),
696 );
697 }
698 false
699 }
700
701 fn sync_oracle(&mut self) -> &mut Self::SyncOracle {
702 &mut self.sync_oracle
703 }
704
705 fn justification_sync_link(&mut self) -> &mut Self::JustificationSyncLink {
706 &mut self.justification_sync_link
707 }
708
709 fn proposer(&mut self, block: &Block::Header) -> Self::CreateProposer {
710 Box::pin(
711 self.env
712 .init(block)
713 .map_err(|e| ConsensusError::ClientImport(e.to_string())),
714 )
715 }
716
717 fn telemetry(&self) -> Option<TelemetryHandle> {
718 self.telemetry.clone()
719 }
720
721 fn proposing_remaining_duration(&self, slot_info: &SlotInfo<Block>) -> std::time::Duration {
722 let parent_slot = extract_pre_digest(&slot_info.chain_head)
723 .ok()
724 .map(|d| d.slot());
725
726 sc_consensus_slots::proposing_remaining_duration(
727 parent_slot,
728 slot_info,
729 &self.block_proposal_slot_portion,
730 self.max_block_proposal_slot_portion.as_ref(),
731 SlotLenienceType::Exponential,
732 self.logging_target(),
733 )
734 }
735}
736
737impl<PosTable, Block, Client, E, Error, SO, L, BS, AS>
738 SubspaceSlotWorker<PosTable, Block, Client, E, SO, L, BS, AS>
739where
740 PosTable: Table,
741 Block: BlockT,
742 Client: ProvideRuntimeApi<Block>
743 + HeaderBackend<Block>
744 + HeaderMetadata<Block, Error = ClientError>
745 + AuxStore
746 + 'static,
747 Client::Api: SubspaceApi<Block, PublicKey>,
748 E: Environment<Block, Error = Error> + Send + Sync,
749 E::Proposer: Proposer<Block, Error = Error>,
750 SO: SyncOracle + Send + Sync,
751 L: JustificationSyncLink<Block>,
752 BS: BackoffAuthoringBlocksStrategy<NumberFor<Block>> + Send + Sync,
753 Error: std::error::Error + Send + From<ConsensusError> + 'static,
754 AS: AuxStore + Send + Sync + 'static,
755 BlockNumber: From<NumberFor<Block>>,
756{
757 pub fn new(
759 SubspaceSlotWorkerOptions {
760 client,
761 env,
762 block_import,
763 sync_oracle,
764 justification_sync_link,
765 force_authoring,
766 backoff_authoring_blocks,
767 subspace_link,
768 segment_headers_store,
769 block_proposal_slot_portion,
770 max_block_proposal_slot_portion,
771 telemetry,
772 offchain_tx_pool_factory,
773 pot_verifier,
774 }: SubspaceSlotWorkerOptions<Block, Client, E, SO, L, BS, AS>,
775 ) -> Self {
776 Self {
777 client: client.clone(),
778 block_import,
779 env,
780 sync_oracle,
781 justification_sync_link,
782 force_authoring,
783 backoff_authoring_blocks,
784 subspace_link,
785 reward_signing_context: schnorrkel::context::signing_context(REWARD_SIGNING_CONTEXT),
786 block_proposal_slot_portion,
787 max_block_proposal_slot_portion,
788 telemetry,
789 offchain_tx_pool_factory,
790 segment_headers_store,
791 pending_solutions: Default::default(),
792 pot_checkpoints: Default::default(),
793 pot_verifier,
794 _pos_table: PhantomData::<PosTable>,
795 }
796 }
797
798 async fn create_vote(
799 &self,
800 parent_header: &Block::Header,
801 slot: Slot,
802 solution: Solution<PublicKey>,
803 proof_of_time: PotOutput,
804 future_proof_of_time: PotOutput,
805 ) {
806 let parent_hash = parent_header.hash();
807 let mut runtime_api = self.client.runtime_api();
808 runtime_api.register_extension(
810 self.offchain_tx_pool_factory
811 .offchain_transaction_pool(parent_hash),
812 );
813
814 if self.should_backoff(slot, parent_header) {
815 return;
816 }
817
818 let vote = Vote::V0 {
820 height: parent_header.number().saturating_add(One::one()),
821 parent_hash: parent_header.hash(),
822 slot,
823 solution: solution.clone(),
824 proof_of_time,
825 future_proof_of_time,
826 };
827
828 let signature = match self.sign_reward(vote.hash(), solution.public_key).await {
829 Ok(signature) => signature,
830 Err(error) => {
831 error!(
832 %slot,
833 %error,
834 "Failed to submit vote",
835 );
836 return;
837 }
838 };
839
840 let signed_vote = SignedVote { vote, signature };
841
842 if let Err(error) = runtime_api.submit_vote_extrinsic(parent_hash, signed_vote) {
843 error!(
844 %slot,
845 %error,
846 "Failed to submit vote",
847 );
848 }
849 }
850
851 async fn sign_reward(
852 &self,
853 hash: H256,
854 public_key: PublicKey,
855 ) -> Result<RewardSignature, ConsensusError> {
856 let (signature_sender, mut signature_receiver) =
857 tracing_unbounded("subspace_signature_signing_stream", 100);
858
859 self.subspace_link
860 .reward_signing_notification_sender
861 .notify(|| RewardSigningNotification {
862 hash,
863 public_key,
864 signature_sender,
865 });
866
867 while let Some(signature) = signature_receiver.next().await {
868 if check_reward_signature(
869 hash.as_ref(),
870 &signature,
871 &public_key,
872 &self.reward_signing_context,
873 )
874 .is_err()
875 {
876 warn!(
877 %hash,
878 "Received invalid signature for reward"
879 );
880 continue;
881 }
882
883 return Ok(signature);
884 }
885
886 Err(ConsensusError::CannotSign(format!(
887 "Farmer didn't sign reward. Key: {public_key:?}"
888 )))
889 }
890}
891
892pub(crate) fn extract_solution_ranges_for_block<Block, Client>(
894 client: &Client,
895 parent_hash: Block::Hash,
896) -> Result<(u64, u64), ApiError>
897where
898 Block: BlockT,
899 Client: ProvideRuntimeApi<Block>,
900 Client::Api: SubspaceApi<Block, PublicKey>,
901{
902 client
903 .runtime_api()
904 .solution_ranges(parent_hash)
905 .map(|solution_ranges| {
906 (
907 solution_ranges.next.unwrap_or(solution_ranges.current),
908 solution_ranges
909 .voting_next
910 .unwrap_or(solution_ranges.voting_current),
911 )
912 })
913}