Skip to main content

ab_node_rpc_server/
lib.rs

1//! RPC API for the farmer
2
3// TODO: Ed25519 uses SHA-512, whose `sha3` target feature intrinsics (enabled on macOS on aarch64)
4//  are not supported by Miri: https://github.com/rust-lang/miri/issues/3172
5#[cfg(all(test, not(all(miri, target_feature = "sha3"))))]
6mod tests;
7
8use ab_archiving::archiver::NewArchivedSegment;
9use ab_client_api::{BeaconChainInfo, ChainSyncStatus};
10use ab_client_archiving::recreate::{
11    RecreateSegmentError, recreate_genesis_segment, recreate_segment,
12};
13use ab_client_block_authoring::slot_worker::{
14    BlockSealNotification, NewSlotInfo, NewSlotNotification,
15};
16use ab_client_consensus_common::ConsensusConstants;
17use ab_core_primitives::block::header::OwnedBlockHeaderSeal;
18use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
19use ab_core_primitives::hashes::Blake3Hash;
20use ab_core_primitives::pieces::{Piece, PieceIndex};
21use ab_core_primitives::pot::SlotNumber;
22use ab_core_primitives::segments::{
23    HistorySize, LocalSegmentIndex, SegmentIndex, SuperSegment, SuperSegmentHeader,
24    SuperSegmentIndex,
25};
26use ab_core_primitives::shard::ShardIndex;
27use ab_core_primitives::solutions::Solution;
28use ab_erasure_coding::ErasureCoding;
29use ab_farmer_components::FarmerProtocolInfo;
30use ab_farmer_rpc_primitives::{
31    BlockSealInfo, BlockSealResponse, FarmerAppInfo, FarmerShardMembershipInfo,
32    MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST, SHARD_MEMBERSHIP_EXPIRATION, SlotInfo, SolutionResponse,
33};
34use ab_networking::libp2p::Multiaddr;
35use async_lock::Mutex as AsyncMutex;
36use futures::channel::{mpsc, oneshot};
37use futures::{FutureExt, SinkExt, StreamExt, select};
38use jsonrpsee::core::{SubscriptionResult, async_trait};
39use jsonrpsee::proc_macros::rpc;
40use jsonrpsee::server::{Server, ServerConfig};
41use jsonrpsee::tokio::task::{JoinError, spawn_blocking};
42use jsonrpsee::tokio::time::MissedTickBehavior;
43use jsonrpsee::types::{ErrorObject, ErrorObjectOwned};
44use jsonrpsee::{
45    ConnectionId, Extensions, PendingSubscriptionSink, SubscriptionSink, TrySendError,
46};
47use parking_lot::Mutex;
48use schnellru::{ByLength, LruMap};
49use std::collections::{HashMap, VecDeque};
50use std::io;
51use std::net::SocketAddr;
52use std::time::{Duration, Instant};
53use tracing::{error, info, warn};
54use triomphe::Arc;
55
56const CACHED_SUPER_SEGMENTS_CAPACITY: usize = 5;
57const CACHED_ARCHIVED_SEGMENT_TIMEOUT: Duration = Duration::from_mins(1);
58
59/// Top-level error type for the RPC handler
60#[derive(Debug, thiserror::Error)]
61pub enum FarmerRpcApiError {
62    /// Solution was ignored
63    #[error("Solution was ignored for slot {slot}")]
64    SolutionWasIgnored {
65        /// Slot number
66        slot: SlotNumber,
67    },
68    /// Super segment headers length exceeded the limit
69    #[error(
70        "Super segment headers length exceeded the limit: \
71        {actual}/{MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST}"
72    )]
73    SuperSegmentHeadersLengthExceeded {
74        /// Requested number of super segment headers/indices
75        actual: usize,
76    },
77    /// Failed to recreate segment
78    #[error("Failed to recreate segment: {0}")]
79    FailedToRecreateSegment(#[from] RecreateSegmentError),
80    /// Blocking task join error
81    #[error("Blocking task join error: {0}")]
82    BlockingTaskJoinError(#[from] JoinError),
83    /// Invalid block seal
84    #[error(
85        "Invalid block seal for pre-seal hash {pre_seal_hash} and public key hash \
86        {public_key_hash}"
87    )]
88    InvalidBlockSeal {
89        /// Pre-seal hash
90        pre_seal_hash: Blake3Hash,
91        /// Public key hash of the seal
92        public_key_hash: Blake3Hash,
93    },
94}
95
96impl From<FarmerRpcApiError> for ErrorObjectOwned {
97    fn from(error: FarmerRpcApiError) -> Self {
98        #[expect(
99            clippy::rest_pattern_accessible_field,
100            reason = "Only extracting error code"
101        )]
102        let code = match &error {
103            FarmerRpcApiError::SolutionWasIgnored { .. } => 0,
104            FarmerRpcApiError::SuperSegmentHeadersLengthExceeded { .. } => 1,
105            FarmerRpcApiError::FailedToRecreateSegment(_) => 2,
106            FarmerRpcApiError::BlockingTaskJoinError(_) => 3,
107            FarmerRpcApiError::InvalidBlockSeal { .. } => 4,
108        };
109
110        ErrorObject::owned(code, error.to_string(), None::<()>)
111    }
112}
113
114/// Provides rpc methods for interacting with the farmer
115#[rpc(server)]
116pub trait FarmerRpcApi {
117    /// Get metadata necessary for farmer operation
118    #[method(name = "getFarmerAppInfo")]
119    fn get_farmer_app_info(&self) -> Result<FarmerAppInfo, FarmerRpcApiError>;
120
121    #[method(name = "submitSolutionResponse")]
122    fn submit_solution_response(
123        &self,
124        solution_response: SolutionResponse,
125    ) -> Result<(), FarmerRpcApiError>;
126
127    /// Slot info subscription
128    #[subscription(
129        name = "subscribeSlotInfo" => "slot_info",
130        unsubscribe = "unsubscribeSlotInfo",
131        item = SlotInfo,
132    )]
133    async fn subscribe_slot_info(&self) -> SubscriptionResult;
134
135    /// Sign block subscription
136    #[subscription(
137        name = "subscribeBlockSealing" => "block_seal",
138        unsubscribe = "unsubscribeBlockSealing",
139        item = BlockSealInfo,
140    )]
141    async fn subscribe_block_seal(&self) -> SubscriptionResult;
142
143    #[method(name = "submitBlockSeal")]
144    fn submit_block_seal(&self, block_seal: BlockSealResponse) -> Result<(), FarmerRpcApiError>;
145
146    /// New super segment header subscription
147    #[subscription(
148        name = "subscribeNewSuperSegmentHeader" => "new_super_segment_header",
149        unsubscribe = "unsubscribeNewSuperSegmentHeader",
150        item = SuperSegmentHeader,
151    )]
152    async fn subscribe_new_super_segment_header(&self) -> SubscriptionResult;
153
154    #[method(name = "superSegmentHeaders")]
155    async fn super_segment_headers(
156        &self,
157        super_segment_indices: Vec<SuperSegmentIndex>,
158    ) -> Result<Vec<Option<SuperSegmentHeader>>, FarmerRpcApiError>;
159
160    #[method(name = "lastSuperSegmentHeaders")]
161    async fn last_super_segment_headers(
162        &self,
163        limit: u32,
164    ) -> Result<Vec<Option<SuperSegmentHeader>>, FarmerRpcApiError>;
165
166    #[method(name = "superSegmentHeaderForSegmentIndex")]
167    async fn super_segment_header_for_segment_index(
168        &self,
169        segment_index: SegmentIndex,
170    ) -> Result<Option<SuperSegmentHeader>, FarmerRpcApiError>;
171
172    #[method(name = "piece")]
173    async fn piece(&self, piece_index: PieceIndex) -> Result<Option<Piece>, FarmerRpcApiError>;
174
175    #[method(name = "updateShardMembershipInfo", with_extensions)]
176    async fn update_shard_membership_info(
177        &self,
178        info: Vec<FarmerShardMembershipInfo>,
179    ) -> Result<(), FarmerRpcApiError>;
180}
181
182#[derive(Debug, Default)]
183struct BlockSignatureSenders {
184    current_pre_seal_hash: Blake3Hash,
185    /// Public key hash that seals for the current pre-seal hash must be created with
186    current_public_key_hash: Blake3Hash,
187    senders: Vec<oneshot::Sender<OwnedBlockHeaderSeal>>,
188}
189
190impl BlockSignatureSenders {
191    /// Send a seal for the current pre-seal hash to one of the senders.
192    ///
193    /// Seals for other pre-seal hashes are ignored with a warning. A seal of another public key or
194    /// with an invalid signature results in an error, and the senders are kept for a valid seal.
195    fn submit_seal(&mut self, block_seal: BlockSealResponse) -> Result<(), FarmerRpcApiError> {
196        let BlockSealResponse {
197            pre_seal_hash,
198            seal,
199        } = block_seal;
200
201        if self.current_pre_seal_hash != pre_seal_hash {
202            warn!(
203                %pre_seal_hash,
204                current_pre_seal_hash = %self.current_pre_seal_hash,
205                "Received block seal for unexpected pre-seal hash"
206            );
207
208            return Ok(());
209        }
210
211        let public_key_hash = seal.as_ref().public_key_hash();
212        if public_key_hash != self.current_public_key_hash
213            || !seal.as_ref().is_seal_valid(&pre_seal_hash)
214        {
215            warn!(
216                %pre_seal_hash,
217                %public_key_hash,
218                expected_public_key_hash = %self.current_public_key_hash,
219                "Received invalid block seal"
220            );
221
222            return Err(FarmerRpcApiError::InvalidBlockSeal {
223                pre_seal_hash,
224                public_key_hash,
225            });
226        }
227
228        if let Some(sender) = self.senders.pop() {
229            let _: Result<(), _> = sender.send(seal);
230        }
231
232        Ok(())
233    }
234}
235
236#[derive(Debug)]
237struct CachedSuperSegments {
238    super_segments: VecDeque<SuperSegment>,
239}
240
241impl Default for CachedSuperSegments {
242    fn default() -> Self {
243        Self {
244            super_segments: VecDeque::with_capacity(CACHED_SUPER_SEGMENTS_CAPACITY),
245        }
246    }
247}
248
249impl CachedSuperSegments {
250    fn get_for_segment_index(&self, segment_index: SegmentIndex) -> Option<&SuperSegment> {
251        self.super_segments.iter().find(|super_segment| {
252            super_segment
253                .header
254                .segment_position(segment_index)
255                .is_some()
256        })
257    }
258
259    fn add(&mut self, super_segment: SuperSegment) {
260        if self.super_segments.len() == CACHED_SUPER_SEGMENTS_CAPACITY {
261            self.super_segments.pop_front();
262        }
263
264        self.super_segments.push_back(super_segment);
265    }
266}
267
268/// Temporary in-memory cache of the last archived segment
269#[derive(Debug)]
270struct CachedArchivedSegment {
271    segment_index: SegmentIndex,
272    segment: NewArchivedSegment,
273    last_used_at: Instant,
274}
275
276#[derive(Debug)]
277struct ShardMembershipConnectionsState {
278    last_update: Instant,
279    info: Vec<FarmerShardMembershipInfo>,
280}
281
282#[derive(Debug, Default)]
283struct ShardMembershipConnections {
284    connections: HashMap<ConnectionId, ShardMembershipConnectionsState>,
285}
286
287/// Farmer RPC configuration
288#[derive(Debug)]
289pub struct FarmerRpcConfig<BCI, CSS> {
290    /// IP and port (TCP) on which to listen for farmer RPC requests
291    pub listen_on: SocketAddr,
292    /// Genesis beacon chain block
293    pub genesis_block: OwnedBeaconChainBlock,
294    /// Consensus constants
295    pub consensus_constants: ConsensusConstants,
296    /// Max pieces in a sector
297    pub max_pieces_in_sector: u16,
298    /// New slot notifications
299    pub new_slot_notification_receiver: mpsc::Receiver<NewSlotNotification>,
300    /// Block sealing notifications
301    pub block_sealing_notification_receiver: mpsc::Receiver<BlockSealNotification>,
302    /// Super segment notifications
303    pub new_super_segment_notification_receiver: mpsc::Receiver<SuperSegment>,
304    /// Shard membership updates
305    pub shard_membership_updates_sender: mpsc::Sender<Vec<FarmerShardMembershipInfo>>,
306    /// DSN bootstrap nodes
307    pub dsn_bootstrap_nodes: Vec<Multiaddr>,
308    /// Beacon chain info
309    pub beacon_chain_info: BCI,
310    /// Chain sync status
311    pub chain_sync_status: CSS,
312    /// Erasure coding instance
313    pub erasure_coding: ErasureCoding,
314}
315
316/// Worker that drives RPC server tasks
317#[derive(Debug)]
318pub struct FarmerRpcWorker<BCI, CSS>
319where
320    BCI: BeaconChainInfo,
321    CSS: ChainSyncStatus,
322{
323    server: Option<Server>,
324    rpc: Option<FarmerRpc<BCI, CSS>>,
325    new_slot_notification_receiver: mpsc::Receiver<NewSlotNotification>,
326    block_sealing_notification_receiver: mpsc::Receiver<BlockSealNotification>,
327    new_super_segment_notification_receiver: mpsc::Receiver<SuperSegment>,
328    solution_response_senders: Arc<Mutex<LruMap<SlotNumber, mpsc::Sender<Solution>>>>,
329    block_sealing_senders: Arc<Mutex<BlockSignatureSenders>>,
330    slot_info_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
331    block_sealing_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
332    new_super_segment_header_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
333    cached_archived_segment: Arc<AsyncMutex<Option<CachedArchivedSegment>>>,
334    cached_super_segments: Arc<Mutex<CachedSuperSegments>>,
335}
336
337impl<BCI, CSS> FarmerRpcWorker<BCI, CSS>
338where
339    BCI: BeaconChainInfo,
340    CSS: ChainSyncStatus,
341{
342    /// Creates a new farmer RPC worker
343    pub async fn new(config: FarmerRpcConfig<BCI, CSS>) -> io::Result<Self> {
344        let server = Server::builder()
345            .set_config(ServerConfig::builder().ws_only().build())
346            .build(config.listen_on)
347            .await?;
348
349        let address = server.local_addr()?;
350        info!(%address, "Started farmer RPC server");
351
352        let block_authoring_delay = u64::from(config.consensus_constants.block_authoring_delay);
353        let block_authoring_delay = usize::try_from(block_authoring_delay)
354            .expect("Block authoring delay will never exceed usize on any platform; qed");
355        let solution_response_senders_capacity = u32::try_from(block_authoring_delay)
356            .expect("Always a tiny constant in the protocol; qed");
357
358        let slot_info_subscriptions = Arc::default();
359        let block_sealing_subscriptions = Arc::default();
360
361        let solution_response_senders = Arc::new(Mutex::new(LruMap::new(ByLength::new(
362            solution_response_senders_capacity,
363        ))));
364        let block_sealing_senders = Arc::default();
365        let new_super_segment_header_subscriptions = Arc::default();
366        let cached_archived_segment = Arc::default();
367        let cached_super_segments = Arc::default();
368
369        let rpc = FarmerRpc {
370            genesis_block: config.genesis_block,
371            solution_response_senders: Arc::clone(&solution_response_senders),
372            block_sealing_senders: Arc::clone(&block_sealing_senders),
373            dsn_bootstrap_nodes: config.dsn_bootstrap_nodes,
374            beacon_chain_info: config.beacon_chain_info,
375            chain_sync_status: config.chain_sync_status,
376            consensus_constants: config.consensus_constants,
377            max_pieces_in_sector: config.max_pieces_in_sector,
378            slot_info_subscriptions: Arc::clone(&slot_info_subscriptions),
379            block_sealing_subscriptions: Arc::clone(&block_sealing_subscriptions),
380            new_super_segment_header_subscriptions: Arc::clone(
381                &new_super_segment_header_subscriptions,
382            ),
383            cached_archived_segment: Arc::clone(&cached_archived_segment),
384            cached_super_segments: Arc::clone(&cached_super_segments),
385            shard_membership_connections: Arc::default(),
386            shard_membership_updates_sender: config.shard_membership_updates_sender,
387            erasure_coding: config.erasure_coding,
388        };
389
390        Ok(Self {
391            server: Some(server),
392            rpc: Some(rpc),
393            new_slot_notification_receiver: config.new_slot_notification_receiver,
394            block_sealing_notification_receiver: config.block_sealing_notification_receiver,
395            new_super_segment_notification_receiver: config.new_super_segment_notification_receiver,
396            solution_response_senders,
397            block_sealing_senders,
398            slot_info_subscriptions,
399            block_sealing_subscriptions,
400            new_super_segment_header_subscriptions,
401            cached_archived_segment,
402            cached_super_segments,
403        })
404    }
405
406    /// Drive RPC server tasks
407    pub async fn run(mut self) {
408        let server = self.server.take().expect("Called only once from here; qed");
409        let rpc = self.rpc.take().expect("Called only once from here; qed");
410        let mut server_fut = server.start(rpc.into_rpc()).stopped().boxed().fuse();
411
412        // Also send periodic updates in addition to the subscription response
413        let mut archived_segment_cache_cleanup_interval =
414            tokio::time::interval(CACHED_ARCHIVED_SEGMENT_TIMEOUT);
415        archived_segment_cache_cleanup_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
416
417        loop {
418            select! {
419                () = server_fut => {}
420                maybe_new_slot_notification = self.new_slot_notification_receiver.next() => {
421                    let Some(new_slot_notification) = maybe_new_slot_notification else {
422                        break;
423                    };
424
425                    self.handle_new_slot_notification(new_slot_notification);
426                }
427                maybe_block_sealing_notification = self.block_sealing_notification_receiver.next() => {
428                    let Some(block_sealing_notification) = maybe_block_sealing_notification else {
429                        break;
430                    };
431
432                    self.handle_block_sealing_notification(block_sealing_notification);
433                }
434                maybe_new_super_segment = self.new_super_segment_notification_receiver.next() => {
435                    let Some(new_super_segment) = maybe_new_super_segment else {
436                        break;
437                    };
438
439                    self.handle_new_super_segment(new_super_segment);
440                }
441                _ = archived_segment_cache_cleanup_interval.tick().fuse() => {
442                    if let Some(mut maybe_cached_archived_segment) = self.cached_archived_segment.try_lock()
443                        && let Some(cached_archived_segment) = maybe_cached_archived_segment.as_ref()
444                        && cached_archived_segment.last_used_at.elapsed() >= CACHED_ARCHIVED_SEGMENT_TIMEOUT
445                    {
446                        maybe_cached_archived_segment.take();
447                    }
448                }
449            }
450        }
451    }
452
453    fn handle_new_slot_notification(&mut self, new_slot_notification: NewSlotNotification) {
454        let NewSlotNotification {
455            new_slot_info,
456            solution_sender,
457        } = new_slot_notification;
458
459        let NewSlotInfo {
460            slot,
461            proof_of_time,
462            solution_range,
463            shard_membership_entropy,
464            num_shards,
465        } = new_slot_info;
466
467        // Store solution sender so that we can retrieve it when solution comes from
468        // the farmer
469        let mut solution_response_senders = self.solution_response_senders.lock();
470        if solution_response_senders.peek(&slot).is_none() {
471            solution_response_senders.insert(slot, solution_sender);
472        }
473
474        let global_challenge = proof_of_time.derive_global_challenge(slot);
475
476        // This will be sent to the farmer
477        let slot_info = SlotInfo {
478            slot,
479            global_challenge,
480            solution_range: solution_range.to_leaf_shard(num_shards),
481            shard_membership_entropy,
482            num_shards,
483        };
484        let slot_info = serde_json::value::to_raw_value(&slot_info)
485            .expect("Serialization of slot info never fails; qed");
486
487        self.slot_info_subscriptions.lock().retain_mut(|sink| {
488            match sink.try_send(slot_info.clone()) {
489                Ok(()) => true,
490                Err(error) => match error {
491                    TrySendError::Closed(_) => {
492                        // Remove closed receivers
493                        false
494                    }
495                    TrySendError::Full(_) => {
496                        warn!(
497                            subscription_id = ?sink.subscription_id(),
498                            "Slot info receiver is too slow, dropping notification"
499                        );
500                        true
501                    }
502                },
503            }
504        });
505    }
506
507    fn handle_block_sealing_notification(
508        &mut self,
509        block_sealing_notification: BlockSealNotification,
510    ) {
511        let BlockSealNotification {
512            pre_seal_hash,
513            public_key_hash,
514            seal_sender,
515        } = block_sealing_notification;
516
517        // Store signature sender so that we can retrieve it when a solution comes from the farmer
518        {
519            let mut block_sealing_senders = self.block_sealing_senders.lock();
520
521            if block_sealing_senders.current_pre_seal_hash != pre_seal_hash {
522                block_sealing_senders.current_pre_seal_hash = pre_seal_hash;
523                block_sealing_senders.current_public_key_hash = public_key_hash;
524                block_sealing_senders.senders.clear();
525            }
526
527            block_sealing_senders.senders.push(seal_sender);
528        }
529
530        // This will be sent to the farmer
531        let block_seal_info = BlockSealInfo {
532            pre_seal_hash,
533            public_key_hash,
534        };
535        let block_seal_info = serde_json::value::to_raw_value(&block_seal_info)
536            .expect("Serialization of block seal info never fails; qed");
537
538        self.block_sealing_subscriptions.lock().retain_mut(|sink| {
539            match sink.try_send(block_seal_info.clone()) {
540                Ok(()) => true,
541                Err(error) => match error {
542                    TrySendError::Closed(_) => {
543                        // Remove closed receivers
544                        false
545                    }
546                    TrySendError::Full(_) => {
547                        warn!(
548                            subscription_id = ?sink.subscription_id(),
549                            "Block seal info receiver is too slow, dropping notification"
550                        );
551                        true
552                    }
553                },
554            }
555        });
556    }
557
558    fn handle_new_super_segment(&mut self, super_segment: SuperSegment) {
559        // This will be sent to the farmer
560        let super_segment_header = serde_json::value::to_raw_value(&super_segment.header)
561            .expect("Serialization of super segment info never fails; qed");
562
563        self.cached_super_segments.lock().add(super_segment);
564
565        self.new_super_segment_header_subscriptions
566            .lock()
567            .retain_mut(|sink| {
568                let subscription_id = sink.subscription_id();
569
570                match sink.try_send(super_segment_header.clone()) {
571                    Ok(()) => true,
572                    Err(error) => match error {
573                        TrySendError::Closed(_) => false,
574                        TrySendError::Full(_) => {
575                            warn!(
576                                ?subscription_id,
577                                "Super segment receiver is too slow, dropping notification"
578                            );
579                            true
580                        }
581                    },
582                }
583            });
584    }
585}
586
587/// Implements the [`FarmerRpcApiServer`] trait for a farmer to connect to
588#[derive(Debug)]
589struct FarmerRpc<BCI, CSS>
590where
591    BCI: BeaconChainInfo,
592    CSS: ChainSyncStatus,
593{
594    genesis_block: OwnedBeaconChainBlock,
595    solution_response_senders: Arc<Mutex<LruMap<SlotNumber, mpsc::Sender<Solution>>>>,
596    block_sealing_senders: Arc<Mutex<BlockSignatureSenders>>,
597    dsn_bootstrap_nodes: Vec<Multiaddr>,
598    beacon_chain_info: BCI,
599    chain_sync_status: CSS,
600    consensus_constants: ConsensusConstants,
601    max_pieces_in_sector: u16,
602    slot_info_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
603    block_sealing_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
604    new_super_segment_header_subscriptions: Arc<Mutex<Vec<SubscriptionSink>>>,
605    cached_archived_segment: Arc<AsyncMutex<Option<CachedArchivedSegment>>>,
606    cached_super_segments: Arc<Mutex<CachedSuperSegments>>,
607    shard_membership_connections: Arc<Mutex<ShardMembershipConnections>>,
608    shard_membership_updates_sender: mpsc::Sender<Vec<FarmerShardMembershipInfo>>,
609    erasure_coding: ErasureCoding,
610}
611
612#[async_trait]
613impl<BCI, CSS> FarmerRpcApiServer for FarmerRpc<BCI, CSS>
614where
615    BCI: BeaconChainInfo,
616    CSS: ChainSyncStatus,
617{
618    fn get_farmer_app_info(&self) -> Result<FarmerAppInfo, FarmerRpcApiError> {
619        let max_segment_index = self
620            .beacon_chain_info
621            .last_super_segment_header()
622            .map_or(SegmentIndex::ZERO, |super_segment_header| {
623                super_segment_header.max_segment_index.as_inner()
624            });
625
626        let consensus_constants = &self.consensus_constants;
627        let protocol_info = FarmerProtocolInfo {
628            history_size: HistorySize::from(max_segment_index),
629            max_pieces_in_sector: self.max_pieces_in_sector,
630            recent_segments: consensus_constants.recent_segments,
631            recent_history_fraction: consensus_constants.recent_history_fraction,
632            min_sector_lifetime: consensus_constants.min_sector_lifetime,
633        };
634
635        let farmer_app_info = FarmerAppInfo {
636            genesis_root: *self.genesis_block.header.root(),
637            dsn_bootstrap_nodes: self.dsn_bootstrap_nodes.clone(),
638            syncing: self.chain_sync_status.is_syncing(),
639            farming_timeout: consensus_constants
640                .slot_duration
641                .as_duration()
642                .mul_f64(u64::from(consensus_constants.block_authoring_delay) as f64),
643            protocol_info,
644        };
645
646        Ok(farmer_app_info)
647    }
648
649    fn submit_solution_response(
650        &self,
651        solution_response: SolutionResponse,
652    ) -> Result<(), FarmerRpcApiError> {
653        let slot = solution_response.slot_number;
654        let public_key_hash = solution_response.solution.public_key_hash;
655        let sector_index = solution_response.solution.sector_index;
656        let mut solution_response_senders = self.solution_response_senders.lock();
657
658        let success = solution_response_senders
659            .peek_mut(&slot)
660            .and_then(|sender| sender.try_send(solution_response.solution).ok())
661            .is_some();
662
663        if !success {
664            warn!(
665                %slot,
666                %sector_index,
667                %public_key_hash,
668                "Solution was ignored, likely because farmer was too slow"
669            );
670
671            return Err(FarmerRpcApiError::SolutionWasIgnored { slot });
672        }
673
674        Ok(())
675    }
676
677    async fn subscribe_slot_info(
678        &self,
679        subscription_sink: PendingSubscriptionSink,
680    ) -> SubscriptionResult {
681        let subscription = subscription_sink.accept().await?;
682        self.slot_info_subscriptions.lock().push(subscription);
683
684        Ok(())
685    }
686
687    async fn subscribe_block_seal(
688        &self,
689        subscription_sink: PendingSubscriptionSink,
690    ) -> SubscriptionResult {
691        let subscription = subscription_sink.accept().await?;
692        self.block_sealing_subscriptions.lock().push(subscription);
693
694        Ok(())
695    }
696
697    fn submit_block_seal(&self, block_seal: BlockSealResponse) -> Result<(), FarmerRpcApiError> {
698        self.block_sealing_senders.lock().submit_seal(block_seal)
699    }
700
701    async fn subscribe_new_super_segment_header(
702        &self,
703        subscription_sink: PendingSubscriptionSink,
704    ) -> SubscriptionResult {
705        let subscription = subscription_sink.accept().await?;
706        self.new_super_segment_header_subscriptions
707            .lock()
708            .push(subscription);
709
710        Ok(())
711    }
712
713    async fn super_segment_headers(
714        &self,
715        super_segment_indices: Vec<SuperSegmentIndex>,
716    ) -> Result<Vec<Option<SuperSegmentHeader>>, FarmerRpcApiError> {
717        if super_segment_indices.len() > MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST {
718            error!(
719                "`super_segment_indices` length exceed the limit: {} ",
720                super_segment_indices.len()
721            );
722
723            return Err(FarmerRpcApiError::SuperSegmentHeadersLengthExceeded {
724                actual: super_segment_indices.len(),
725            });
726        }
727
728        Ok(super_segment_indices
729            .into_iter()
730            .map(|super_segment_index| {
731                self.beacon_chain_info
732                    .get_super_segment_header(super_segment_index)
733            })
734            .collect())
735    }
736
737    async fn last_super_segment_headers(
738        &self,
739        limit: u32,
740    ) -> Result<Vec<Option<SuperSegmentHeader>>, FarmerRpcApiError> {
741        if limit as usize > MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST {
742            error!(
743                "Request limit ({}) exceed the server limit: {} ",
744                limit, MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST
745            );
746
747            return Err(FarmerRpcApiError::SuperSegmentHeadersLengthExceeded {
748                actual: limit as usize,
749            });
750        }
751
752        let last_super_segment_index = self
753            .beacon_chain_info
754            .last_super_segment_header()
755            .map_or(SuperSegmentIndex::ZERO, |super_segment_header| {
756                super_segment_header.index.as_inner()
757            });
758
759        let mut last_super_segment_headers = (SuperSegmentIndex::ZERO..=last_super_segment_index)
760            .rev()
761            .take(limit as usize)
762            .map(|super_segment_index| {
763                self.beacon_chain_info
764                    .get_super_segment_header(super_segment_index)
765            })
766            .collect::<Vec<_>>();
767
768        last_super_segment_headers.reverse();
769
770        Ok(last_super_segment_headers)
771    }
772
773    async fn super_segment_header_for_segment_index(
774        &self,
775        segment_index: SegmentIndex,
776    ) -> Result<Option<SuperSegmentHeader>, FarmerRpcApiError> {
777        Ok(self
778            .beacon_chain_info
779            .get_super_segment_header_for_segment_index(segment_index))
780    }
781
782    // The segment of the last requested piece is cached. On a cache miss, the genesis segment is
783    // recreated from the genesis block, and other segments from blocks, but only if they belong to
784    // one of the last `CACHED_SUPER_SEGMENTS_CAPACITY` super segments. The cache is cleared once
785    // it has not been used for `CACHED_ARCHIVED_SEGMENT_TIMEOUT`.
786    async fn piece(&self, piece_index: PieceIndex) -> Result<Option<Piece>, FarmerRpcApiError> {
787        let segment_index = piece_index.segment_index();
788        let cached_archived_segment = &mut *self.cached_archived_segment.lock().await;
789
790        if let Some(cached_archived_segment) = cached_archived_segment
791            && cached_archived_segment.segment_index == segment_index
792        {
793            cached_archived_segment.last_used_at = Instant::now();
794
795            return Ok(cached_archived_segment
796                .segment
797                .pieces
798                .pieces()
799                .nth(usize::from(piece_index.position())));
800        }
801
802        if segment_index == SegmentIndex::ZERO {
803            let segment = spawn_blocking({
804                let genesis_block = self.genesis_block.clone();
805                let erasure_coding = self.erasure_coding.clone();
806
807                move || recreate_genesis_segment(&genesis_block, erasure_coding)
808            })
809            .await?;
810            let cached_archived_segment = cached_archived_segment.insert(CachedArchivedSegment {
811                segment_index: SegmentIndex::ZERO,
812                segment,
813                last_used_at: Instant::now(),
814            });
815
816            return Ok(cached_archived_segment
817                .segment
818                .pieces
819                .pieces()
820                .nth(usize::from(piece_index.position())));
821        }
822
823        let (shard_segment_root_with_position, segment_proof) = {
824            let cached_super_segments = self.cached_super_segments.lock();
825            let Some(super_segment) = cached_super_segments.get_for_segment_index(segment_index)
826            else {
827                return Ok(None);
828            };
829
830            let Some(shard_segment_root_with_position) = super_segment
831                .header
832                .segment_position(segment_index)
833                .and_then(|segment_position| {
834                    super_segment
835                        .segment_roots
836                        .get(u32::from(segment_position) as usize)
837                })
838                .copied()
839            else {
840                error!(
841                    %piece_index,
842                    %segment_index,
843                    super_segment_header = ?super_segment.header,
844                    "Failed to find segment index inside super segment, this should never happen"
845                );
846                return Ok(None);
847            };
848
849            let segment_position = shard_segment_root_with_position.segment_position;
850
851            let Some(segment_proof) = super_segment.proof_for_segment(segment_position) else {
852                error!(
853                    %piece_index,
854                    %segment_index,
855                    %segment_position,
856                    super_segment_header = ?super_segment.header,
857                    "Failed to get segment proof for segment position, this should never happen"
858                );
859
860                return Ok(None);
861            };
862
863            (shard_segment_root_with_position, segment_proof)
864        };
865
866        if shard_segment_root_with_position.shard_index != ShardIndex::BEACON_CHAIN {
867            // TODO: There will be a need for chain info instances of all live shards to re-derive
868            //  segments here, but there is just a beacon chain here for now
869            unimplemented!("Shard segments for non-beacon chain shards are not supported yet");
870        }
871
872        let last_archived_segment = shard_segment_root_with_position
873            .local_segment_index
874            .checked_sub(LocalSegmentIndex::ONE)
875            .and_then(|last_segment_index| {
876                self.beacon_chain_info
877                    .get_segment_header(last_segment_index)
878            });
879
880        let maybe_segment = recreate_segment(
881            last_archived_segment,
882            &self.beacon_chain_info,
883            self.erasure_coding.clone(),
884            &segment_proof,
885            |_| Vec::new(),
886        )
887        .await?;
888
889        let Some(segment) = maybe_segment else {
890            return Ok(None);
891        };
892
893        let cached_archived_segment = cached_archived_segment.insert(CachedArchivedSegment {
894            segment_index,
895            segment,
896            last_used_at: Instant::now(),
897        });
898
899        Ok(cached_archived_segment
900            .segment
901            .pieces
902            .pieces()
903            .nth(usize::from(piece_index.position())))
904    }
905
906    async fn update_shard_membership_info(
907        &self,
908        ext: &Extensions,
909        info: Vec<FarmerShardMembershipInfo>,
910    ) -> Result<(), FarmerRpcApiError> {
911        let connection_id = ext
912            .get::<ConnectionId>()
913            .expect("`ConnectionId` is always present; qed");
914
915        let shard_membership = {
916            let mut shard_membership_connections = self.shard_membership_connections.lock();
917
918            // TODO: This is a workaround for https://github.com/paritytech/jsonrpsee/issues/1617
919            //  and should be replaced with cleanup on disconnection once that issue is resolved
920            shard_membership_connections
921                .connections
922                .retain(|_connection_id, state| {
923                    state.last_update.elapsed() < SHARD_MEMBERSHIP_EXPIRATION
924                });
925
926            shard_membership_connections.connections.insert(
927                *connection_id,
928                ShardMembershipConnectionsState {
929                    last_update: Instant::now(),
930                    info,
931                },
932            );
933
934            shard_membership_connections
935                .connections
936                .values()
937                .flat_map(|state| state.info.clone())
938                .collect::<Vec<_>>()
939        };
940
941        if let Err(error) = self
942            .shard_membership_updates_sender
943            .clone()
944            .send(shard_membership)
945            .await
946        {
947            warn!(%error, "Failed to send shard membership update");
948        }
949
950        Ok(())
951    }
952}