linera_core/
local_node.rs

1// Copyright (c) Facebook, Inc. and its affiliates.
2// Copyright (c) Zefchain Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    collections::{BTreeMap, HashMap, VecDeque},
7    sync::Arc,
8};
9
10use futures::{stream::FuturesUnordered, TryStreamExt as _};
11use linera_base::{
12    crypto::{CryptoHash, ValidatorPublicKey},
13    data_types::{ArithmeticError, Blob, BlockHeight},
14    identifiers::{BlobId, ChainId, EventId, StreamId},
15};
16use linera_chain::{
17    data_types::{BlockProposal, BundleExecutionPolicy, ProposedBlock},
18    types::{Block, GenericCertificate},
19    ChainError, ChainExecutionContext,
20};
21use linera_execution::{BlobState, ExecutionError, Query, QueryOutcome, ResourceTracker};
22use linera_storage::Storage;
23use linera_views::ViewError;
24use thiserror::Error;
25use tracing::{instrument, warn};
26
27use crate::{
28    data_types::{ChainInfo, ChainInfoQuery, ChainInfoResponse},
29    notifier::Notifier,
30    worker::{ProcessableCertificate, WorkerError, WorkerState},
31};
32
33/// A local node with a single worker, typically used by clients.
34pub struct LocalNode<S>
35where
36    S: Storage,
37{
38    state: WorkerState<S>,
39}
40
41/// A client to a local node.
42#[derive(Clone)]
43pub struct LocalNodeClient<S>
44where
45    S: Storage,
46{
47    node: Arc<LocalNode<S>>,
48}
49
50/// Error type for the operations on a local node.
51#[derive(Debug, Error)]
52pub enum LocalNodeError {
53    #[error(transparent)]
54    ArithmeticError(#[from] ArithmeticError),
55
56    #[error(transparent)]
57    ViewError(#[from] ViewError),
58
59    #[error("Worker operation failed: {0}")]
60    WorkerError(WorkerError),
61
62    #[error("The local node doesn't have an active chain {0}")]
63    InactiveChain(ChainId),
64
65    #[error("The chain info response received from the local node is invalid")]
66    InvalidChainInfoResponse,
67
68    #[error("Blobs not found: {0:?}")]
69    BlobsNotFound(Vec<BlobId>),
70
71    #[error("Events not found: {0:?}")]
72    EventsNotFound(Vec<EventId>),
73}
74
75impl From<ExecutionError> for LocalNodeError {
76    fn from(error: ExecutionError) -> Self {
77        match error {
78            ExecutionError::BlobsNotFound(blob_ids) => LocalNodeError::BlobsNotFound(blob_ids),
79            ExecutionError::EventsNotFound(event_ids) => LocalNodeError::EventsNotFound(event_ids),
80            ExecutionError::ViewError(view_error) => LocalNodeError::ViewError(view_error),
81            error => LocalNodeError::WorkerError(WorkerError::from(ChainError::ExecutionError(
82                Box::new(error),
83                ChainExecutionContext::Block,
84            ))),
85        }
86    }
87}
88
89impl From<WorkerError> for LocalNodeError {
90    fn from(error: WorkerError) -> Self {
91        match error {
92            WorkerError::BlobsNotFound(blob_ids) => LocalNodeError::BlobsNotFound(blob_ids),
93            WorkerError::EventsNotFound(event_ids) => LocalNodeError::EventsNotFound(event_ids),
94            error => LocalNodeError::WorkerError(error),
95        }
96    }
97}
98
99impl<S> LocalNodeClient<S>
100where
101    S: Storage + Clone + 'static,
102{
103    #[instrument(level = "trace", skip_all)]
104    pub async fn handle_block_proposal(
105        &self,
106        proposal: BlockProposal,
107    ) -> Result<ChainInfoResponse, LocalNodeError> {
108        // In local nodes, cross-chain actions will be handled internally, so we discard them.
109        let (response, _actions) =
110            Box::pin(self.node.state.handle_block_proposal(proposal)).await?;
111        Ok(response)
112    }
113
114    #[instrument(level = "trace", skip_all)]
115    pub async fn handle_certificate<T>(
116        &self,
117        certificate: GenericCertificate<T>,
118        notifier: &impl Notifier,
119    ) -> Result<ChainInfoResponse, LocalNodeError>
120    where
121        T: ProcessableCertificate,
122    {
123        Ok(Box::pin(
124            self.node
125                .state
126                .fully_handle_certificate_with_notifications(certificate, notifier),
127        )
128        .await?)
129    }
130
131    #[instrument(level = "trace", skip_all)]
132    pub async fn handle_chain_info_query(
133        &self,
134        query: ChainInfoQuery,
135    ) -> Result<ChainInfoResponse, LocalNodeError> {
136        Ok(self.node.state.handle_chain_info_query(query).await?)
137    }
138
139    #[instrument(level = "trace", skip_all)]
140    pub fn new(state: WorkerState<S>) -> Self {
141        Self {
142            node: Arc::new(LocalNode { state }),
143        }
144    }
145
146    #[instrument(level = "trace", skip_all)]
147    pub(crate) fn storage_client(&self) -> S {
148        self.node.state.storage_client().clone()
149    }
150
151    /// Executes a block with a policy for handling bundle failures.
152    ///
153    /// Returns the modified block (bundles may be rejected/removed based on the policy),
154    /// the executed block, chain info response, and resource tracker.
155    #[instrument(level = "trace", skip_all)]
156    pub async fn stage_block_execution(
157        &self,
158        block: ProposedBlock,
159        round: Option<u32>,
160        published_blobs: Vec<Blob>,
161        policy: BundleExecutionPolicy,
162    ) -> Result<(ProposedBlock, Block, ChainInfoResponse, ResourceTracker), LocalNodeError> {
163        Ok(self
164            .node
165            .state
166            .stage_block_execution(block, round, published_blobs, policy)
167            .await?)
168    }
169
170    /// Reads blobs from storage.
171    pub async fn read_blobs_from_storage(
172        &self,
173        blob_ids: &[BlobId],
174    ) -> Result<Option<Vec<Blob>>, LocalNodeError> {
175        let storage = self.storage_client();
176        Ok(storage
177            .read_blobs(blob_ids)
178            .await?
179            .into_iter()
180            .map(|opt| opt.map(Arc::unwrap_or_clone))
181            .collect())
182    }
183
184    /// Reads blob states from storage.
185    pub async fn read_blob_states_from_storage(
186        &self,
187        blob_ids: &[BlobId],
188    ) -> Result<Vec<BlobState>, LocalNodeError> {
189        let storage = self.storage_client();
190        let mut blobs_not_found = Vec::new();
191        let mut blob_states = Vec::new();
192        for (blob_state, blob_id) in storage
193            .read_blob_states(blob_ids)
194            .await?
195            .into_iter()
196            .zip(blob_ids)
197        {
198            match blob_state {
199                None => blobs_not_found.push(*blob_id),
200                Some(blob_state) => blob_states.push(blob_state),
201            }
202        }
203        if !blobs_not_found.is_empty() {
204            return Err(LocalNodeError::BlobsNotFound(blobs_not_found));
205        }
206        Ok(blob_states)
207    }
208
209    /// Looks for the specified blobs in the local chain manager's locking blobs.
210    /// Returns `Ok(None)` if any of the blobs is not found.
211    pub async fn get_locking_blobs(
212        &self,
213        blob_ids: impl IntoIterator<Item = &BlobId>,
214        chain_id: ChainId,
215    ) -> Result<Option<Vec<Blob>>, LocalNodeError> {
216        let blob_ids_vec: Vec<_> = blob_ids.into_iter().copied().collect();
217        Ok(self
218            .node
219            .state
220            .get_locking_blobs(chain_id, blob_ids_vec)
221            .await?)
222    }
223
224    /// Writes the given blobs to storage if there is an appropriate blob state.
225    pub async fn store_blobs(&self, blobs: &[Blob]) -> Result<(), LocalNodeError> {
226        let storage = self.storage_client();
227        storage.maybe_write_blobs(blobs).await?;
228        Ok(())
229    }
230
231    pub async fn handle_pending_blobs(
232        &self,
233        chain_id: ChainId,
234        blobs: Vec<Blob>,
235    ) -> Result<(), LocalNodeError> {
236        for blob in blobs {
237            self.node.state.handle_pending_blob(chain_id, blob).await?;
238        }
239        Ok(())
240    }
241
242    /// Returns a read-only view of the [`ChainStateView`] of a chain referenced by its
243    /// [`ChainId`].
244    ///
245    /// The returned view holds a lock on the chain state, which prevents the local node from
246    /// changing the state of that chain.
247    #[instrument(level = "trace", skip(self))]
248    pub async fn chain_state_view(
249        &self,
250        chain_id: ChainId,
251    ) -> Result<crate::worker::ChainStateViewReadGuard<S>, LocalNodeError> {
252        Ok(self.node.state.chain_state_view(chain_id).await?)
253    }
254
255    #[instrument(level = "trace", skip(self))]
256    pub(crate) async fn chain_info(
257        &self,
258        chain_id: ChainId,
259    ) -> Result<Box<ChainInfo>, LocalNodeError> {
260        let query = ChainInfoQuery::new(chain_id);
261        Ok(self.handle_chain_info_query(query).await?.info)
262    }
263
264    #[instrument(level = "trace", skip(self, query))]
265    pub async fn query_application(
266        &self,
267        chain_id: ChainId,
268        query: Query,
269        block_hash: Option<CryptoHash>,
270    ) -> Result<(QueryOutcome, BlockHeight), LocalNodeError> {
271        let result = self
272            .node
273            .state
274            .query_application(chain_id, query, block_hash)
275            .await?;
276        Ok(result)
277    }
278
279    /// Handles any pending local cross-chain requests.
280    ///
281    /// Does not initialize the sender chain's execution state, so it is safe to
282    /// call even when the sender's `ChainDescription` blob is not in local storage.
283    /// Previously this went through `handle_chain_info_query`, which unconditionally
284    /// initialized the worker and therefore forced a `ChainDescription` download on
285    /// every call.
286    #[instrument(level = "trace", skip(self, notifier))]
287    pub async fn retry_pending_cross_chain_requests(
288        &self,
289        sender_chain: ChainId,
290        notifier: &impl Notifier,
291    ) -> Result<(), LocalNodeError> {
292        let actions = self
293            .node
294            .state
295            .cross_chain_network_actions(sender_chain)
296            .await?;
297        let mut requests = VecDeque::from_iter(actions.cross_chain_requests);
298        while let Some(request) = requests.pop_front() {
299            let new_actions = self.node.state.handle_cross_chain_request(request).await?;
300            notifier.notify(&new_actions.notifications);
301            requests.extend(new_actions.cross_chain_requests);
302        }
303        Ok(())
304    }
305
306    /// Given a list of chain IDs, returns a map that assigns to each of them the next block
307    /// height to schedule, i.e. the lowest block height for which we haven't added the messages
308    /// to `receiver_id` to the outbox yet.
309    pub async fn next_outbox_heights(
310        &self,
311        chain_ids: impl IntoIterator<Item = &ChainId>,
312        receiver_id: ChainId,
313    ) -> Result<BTreeMap<ChainId, BlockHeight>, LocalNodeError> {
314        let futures = chain_ids
315            .into_iter()
316            .map(|chain_id| async move {
317                let (next_block_height, next_height_to_schedule) = match self
318                    .get_tip_state_and_outbox_info(*chain_id, receiver_id)
319                    .await
320                {
321                    Ok(info) => info,
322                    Err(LocalNodeError::BlobsNotFound(_) | LocalNodeError::InactiveChain(_)) => {
323                        return Ok((*chain_id, BlockHeight::ZERO))
324                    }
325                    Err(err) => Err(err)?,
326                };
327                let next_height = if let Some(scheduled_height) = next_height_to_schedule {
328                    next_block_height.max(scheduled_height)
329                } else {
330                    next_block_height
331                };
332                Ok::<_, LocalNodeError>((*chain_id, next_height))
333            })
334            .collect::<FuturesUnordered<_>>();
335        futures.try_collect().await
336    }
337
338    pub async fn update_received_certificate_trackers(
339        &self,
340        chain_id: ChainId,
341        new_trackers: BTreeMap<ValidatorPublicKey, u64>,
342    ) -> Result<(), LocalNodeError> {
343        self.node
344            .state
345            .update_received_certificate_trackers(chain_id, new_trackers)
346            .await?;
347        Ok(())
348    }
349
350    pub async fn get_preprocessed_block_hashes(
351        &self,
352        chain_id: ChainId,
353        start: BlockHeight,
354        end: BlockHeight,
355    ) -> Result<Vec<linera_base::crypto::CryptoHash>, LocalNodeError> {
356        Ok(self
357            .node
358            .state
359            .get_preprocessed_block_hashes(chain_id, start, end)
360            .await?)
361    }
362
363    pub async fn get_inbox_next_height(
364        &self,
365        chain_id: ChainId,
366        origin: ChainId,
367    ) -> Result<BlockHeight, LocalNodeError> {
368        Ok(self
369            .node
370            .state
371            .get_inbox_next_height(chain_id, origin)
372            .await?)
373    }
374
375    /// Gets block hashes for the given heights.
376    pub async fn get_block_hashes(
377        &self,
378        chain_id: ChainId,
379        heights: Vec<BlockHeight>,
380    ) -> Result<Vec<CryptoHash>, LocalNodeError> {
381        Ok(self.node.state.get_block_hashes(chain_id, heights).await?)
382    }
383
384    /// Gets proposed blobs from the manager for specified blob IDs.
385    pub async fn get_proposed_blobs(
386        &self,
387        chain_id: ChainId,
388        blob_ids: Vec<BlobId>,
389    ) -> Result<Vec<Blob>, LocalNodeError> {
390        Ok(self
391            .node
392            .state
393            .get_proposed_blobs(chain_id, blob_ids)
394            .await?)
395    }
396
397    /// Gets event subscriptions from the chain.
398    pub async fn get_event_subscriptions(
399        &self,
400        chain_id: ChainId,
401    ) -> Result<crate::worker::EventSubscriptionsResult, LocalNodeError> {
402        Ok(self.node.state.get_event_subscriptions(chain_id).await?)
403    }
404
405    /// Gets the next expected event index for a stream.
406    pub async fn get_next_expected_event(
407        &self,
408        chain_id: ChainId,
409        stream_id: StreamId,
410    ) -> Result<Option<u32>, LocalNodeError> {
411        Ok(self
412            .node
413            .state
414            .get_next_expected_event(chain_id, stream_id)
415            .await?)
416    }
417
418    /// Gets the `next_expected_events` indices for the given streams.
419    pub async fn next_expected_events(
420        &self,
421        chain_id: ChainId,
422        stream_ids: Vec<StreamId>,
423    ) -> Result<BTreeMap<StreamId, u32>, LocalNodeError> {
424        Ok(self
425            .node
426            .state
427            .next_expected_events(chain_id, stream_ids)
428            .await?)
429    }
430
431    /// Gets received certificate trackers.
432    pub async fn get_received_certificate_trackers(
433        &self,
434        chain_id: ChainId,
435    ) -> Result<HashMap<ValidatorPublicKey, u64>, LocalNodeError> {
436        Ok(self
437            .node
438            .state
439            .get_received_certificate_trackers(chain_id)
440            .await?)
441    }
442
443    /// Gets tip state and outbox info for next_outbox_heights calculation.
444    pub async fn get_tip_state_and_outbox_info(
445        &self,
446        chain_id: ChainId,
447        receiver_id: ChainId,
448    ) -> Result<(BlockHeight, Option<BlockHeight>), LocalNodeError> {
449        Ok(self
450            .node
451            .state
452            .get_tip_state_and_outbox_info(chain_id, receiver_id)
453            .await?)
454    }
455
456    /// Gets the next height to preprocess.
457    pub async fn get_next_height_to_preprocess(
458        &self,
459        chain_id: ChainId,
460    ) -> Result<BlockHeight, LocalNodeError> {
461        Ok(self
462            .node
463            .state
464            .get_next_height_to_preprocess(chain_id)
465            .await?)
466    }
467}