linera-rpc 0.15.16

RPC schemas and networking library for the Linera protocol.
Documentation
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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
    future::Future,
    iter,
    sync::{
        atomic::{AtomicU32, Ordering},
        Arc,
    },
};

use futures::{future, stream, StreamExt};
use linera_base::{
    crypto::CryptoHash,
    data_types::{BlobContent, BlockHeight, NetworkDescription},
    ensure,
    identifiers::{BlobId, ChainId, StreamId},
    time::{Duration, Instant},
};
use linera_chain::{
    data_types::{self},
    types::{
        self, Certificate, ConfirmedBlock, ConfirmedBlockCertificate, GenericCertificate,
        LiteCertificate, Timeout, ValidatedBlock,
    },
};
#[cfg(with_metrics)]
mod metrics {
    use std::sync::LazyLock;

    use linera_base::prometheus_util::register_int_counter_vec;
    use prometheus::IntCounterVec;

    pub static VALIDATOR_SUBSCRIPTION_ERRORS: LazyLock<IntCounterVec> = LazyLock::new(|| {
        register_int_counter_vec(
            "validator_subscription_errors",
            "Number of notification subscription stream errors per validator",
            &["address"],
        )
    });
}

use linera_core::{
    data_types::{CertificatesByHeightRequest, ChainInfoResponse},
    node::{CrossChainMessageDelivery, NodeError, NotificationStream, ValidatorNode},
    worker::Notification,
};
use linera_version::VersionInfo;
use tonic::{Code, IntoRequest, Request, Status};
use tracing::{debug, instrument, trace, Level};

use super::{
    api::{self, validator_node_client::ValidatorNodeClient, SubscriptionRequest},
    transport, GRPC_MAX_MESSAGE_SIZE,
};

/// Maximum number of stream IDs per `previous_event_blocks` request, to avoid exceeding
/// the gRPC message size limit in the response. See [`tests::max_stream_ids_fits`].
pub(crate) const MAX_STREAM_IDS_PER_REQUEST: usize = 10_000;
#[cfg(feature = "opentelemetry")]
use crate::propagation::{get_context_with_traffic_type, inject_context};
use crate::{
    grpc::api::RawCertificate, HandleConfirmedCertificateRequest, HandleLiteCertRequest,
    HandleTimeoutCertificateRequest, HandleValidatedCertificateRequest,
};

#[derive(Clone)]
pub struct GrpcClient {
    address: String,
    client: ValidatorNodeClient<transport::Channel>,
    retry_delay: Duration,
    max_retries: u32,
    max_backoff: Duration,
    /// Shared across all `GrpcClient` instances created by the same `GrpcNodeProvider`.
    /// Tracks when each validator address last had a subscription failure, so that
    /// other chains don't independently retry the same dead validator.
    subscription_cooldowns: papaya::HashMap<String, Instant>,
}

impl GrpcClient {
    pub fn new(
        address: String,
        channel: transport::Channel,
        retry_delay: Duration,
        max_retries: u32,
        max_backoff: Duration,
        subscription_cooldowns: papaya::HashMap<String, Instant>,
    ) -> Self {
        let client = ValidatorNodeClient::new(channel)
            .max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE)
            .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
        Self {
            address,
            client,
            retry_delay,
            max_retries,
            max_backoff,
            subscription_cooldowns,
        }
    }

    pub fn address(&self) -> &str {
        &self.address
    }

    /// Returns whether this gRPC status means the server stream should be reconnected to, or not.
    /// Logs a warning on unexpected status codes.
    fn is_retryable(status: &Status) -> bool {
        match status.code() {
            Code::DeadlineExceeded | Code::Aborted | Code::Unavailable | Code::Unknown => {
                trace!("gRPC request interrupted: {status:?}; retrying");
                true
            }
            Code::Ok | Code::Cancelled | Code::ResourceExhausted => {
                trace!("Unexpected gRPC status: {status:?}; retrying");
                true
            }
            Code::Internal if status.message().contains("h2 protocol error") => {
                // HTTP/2 connection reset errors are transient network issues, not real
                // internal errors. This happens when the server restarts and the
                // connection is forcibly closed.
                trace!("gRPC connection reset: {status:?}; retrying");
                true
            }
            Code::Internal if status.message().contains("502 Bad Gateway") => {
                // When a proxy/ingress returns HTTP 502 (e.g. during rolling restarts),
                // tonic's frame decoder fails on the non-gRPC response body before the
                // HTTP-to-gRPC status mapping can run, producing Code::Internal instead
                // of Code::Unavailable. Per the gRPC spec, HTTP 502 maps to UNAVAILABLE
                // which is retryable. This works around tonic#2365.
                trace!("gRPC proxy error (502): {status:?}; retrying");
                true
            }
            Code::NotFound => false, // This code is used if e.g. the validator is missing blobs.
            Code::InvalidArgument
            | Code::AlreadyExists
            | Code::PermissionDenied
            | Code::FailedPrecondition
            | Code::OutOfRange
            | Code::Unimplemented
            | Code::Internal
            | Code::DataLoss
            | Code::Unauthenticated => {
                trace!("Unexpected gRPC status: {status:?}");
                false
            }
        }
    }

    async fn delegate<F, Fut, R, S>(
        &self,
        f: F,
        request: impl TryInto<R> + fmt::Debug + Clone,
        handler: &str,
    ) -> Result<S, NodeError>
    where
        F: Fn(ValidatorNodeClient<transport::Channel>, Request<R>) -> Fut,
        Fut: Future<Output = Result<tonic::Response<S>, Status>>,
        R: IntoRequest<R> + Clone,
    {
        let mut retry_count = 0;
        let request_inner = request.try_into().map_err(|_| NodeError::GrpcError {
            error: "could not convert request to proto".to_string(),
        })?;
        loop {
            #[allow(unused_mut)]
            let mut request = Request::new(request_inner.clone());
            // Inject OpenTelemetry context (trace context + baggage) into gRPC metadata.
            // This uses get_context_with_traffic_type() to also check the LINERA_TRAFFIC_TYPE
            // environment variable, allowing benchmark tools to mark their traffic as synthetic.
            #[cfg(feature = "opentelemetry")]
            inject_context(&get_context_with_traffic_type(), request.metadata_mut());
            match f(self.client.clone(), request).await {
                Err(s) if Self::is_retryable(&s) && retry_count < self.max_retries => {
                    let delay = crate::jittered_backoff_delay(
                        self.retry_delay,
                        retry_count,
                        self.max_backoff,
                    );
                    retry_count += 1;
                    linera_base::time::timer::sleep(delay).await;
                    continue;
                }
                Err(s) => {
                    return Err(NodeError::GrpcError {
                        error: format!("remote request [{handler}] failed with status: {s:?}"),
                    });
                }
                Ok(result) => return Ok(result.into_inner()),
            };
        }
    }

    fn try_into_chain_info(
        result: api::ChainInfoResult,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        let inner = result.inner.ok_or_else(|| NodeError::GrpcError {
            error: "missing body from response".to_string(),
        })?;
        match inner {
            api::chain_info_result::Inner::ChainInfoResponse(response) => {
                Ok(response.try_into().map_err(|err| NodeError::GrpcError {
                    error: format!("failed to unmarshal response: {}", err),
                })?)
            }
            api::chain_info_result::Inner::Error(error) => Err(bincode::deserialize(&error)
                .map_err(|err| NodeError::GrpcError {
                    error: format!("failed to unmarshal error message: {}", err),
                })?),
        }
    }
}

impl TryFrom<api::PendingBlobResult> for BlobContent {
    type Error = NodeError;

    fn try_from(result: api::PendingBlobResult) -> Result<Self, Self::Error> {
        let inner = result.inner.ok_or_else(|| NodeError::GrpcError {
            error: "missing body from response".to_string(),
        })?;
        match inner {
            api::pending_blob_result::Inner::Blob(blob) => {
                Ok(blob.try_into().map_err(|err| NodeError::GrpcError {
                    error: format!("failed to unmarshal response: {}", err),
                })?)
            }
            api::pending_blob_result::Inner::Error(error) => Err(bincode::deserialize(&error)
                .map_err(|err| NodeError::GrpcError {
                    error: format!("failed to unmarshal error message: {}", err),
                })?),
        }
    }
}

macro_rules! client_delegate {
    ($self:ident, $handler:ident, $req:ident) => {{
        debug!(
            handler = stringify!($handler),
            request = ?$req,
            "sending gRPC request"
        );
        $self
            .delegate(
                |mut client, req| async move { client.$handler(req).await },
                $req,
                stringify!($handler),
            )
            .await
    }};
}

impl ValidatorNode for GrpcClient {
    type NotificationStream = NotificationStream;

    fn address(&self) -> String {
        self.address.clone()
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_block_proposal(
        &self,
        proposal: data_types::BlockProposal,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        GrpcClient::try_into_chain_info(client_delegate!(self, handle_block_proposal, proposal)?)
    }

    #[instrument(target = "grpc_client", skip_all, fields(address = self.address))]
    async fn handle_lite_certificate(
        &self,
        certificate: types::LiteCertificate<'_>,
        delivery: CrossChainMessageDelivery,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        let wait_for_outgoing_messages = delivery.wait_for_outgoing_messages();
        let request = HandleLiteCertRequest {
            certificate,
            wait_for_outgoing_messages,
        };
        GrpcClient::try_into_chain_info(client_delegate!(self, handle_lite_certificate, request)?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_confirmed_certificate(
        &self,
        certificate: GenericCertificate<ConfirmedBlock>,
        delivery: CrossChainMessageDelivery,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        let wait_for_outgoing_messages: bool = delivery.wait_for_outgoing_messages();
        let request = HandleConfirmedCertificateRequest {
            certificate,
            wait_for_outgoing_messages,
        };
        GrpcClient::try_into_chain_info(client_delegate!(
            self,
            handle_confirmed_certificate,
            request
        )?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_validated_certificate(
        &self,
        certificate: GenericCertificate<ValidatedBlock>,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        let request = HandleValidatedCertificateRequest { certificate };
        GrpcClient::try_into_chain_info(client_delegate!(
            self,
            handle_validated_certificate,
            request
        )?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_timeout_certificate(
        &self,
        certificate: GenericCertificate<Timeout>,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        let request = HandleTimeoutCertificateRequest { certificate };
        GrpcClient::try_into_chain_info(client_delegate!(
            self,
            handle_timeout_certificate,
            request
        )?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_chain_info_query(
        &self,
        query: linera_core::data_types::ChainInfoQuery,
    ) -> Result<linera_core::data_types::ChainInfoResponse, NodeError> {
        GrpcClient::try_into_chain_info(client_delegate!(self, handle_chain_info_query, query)?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn subscribe(&self, chains: Vec<ChainId>) -> Result<Self::NotificationStream, NodeError> {
        let retry_delay = self.retry_delay;
        let max_retries = self.max_retries;
        let max_backoff = self.max_backoff;
        let address = self.address.clone();
        let subscription_cooldowns = self.subscription_cooldowns.clone();

        // Fast-fail if another subscription to this address recently failed.
        // Prevents N chains from independently retrying the same dead validator.
        {
            let pinned = subscription_cooldowns.pin();
            if let Some(&last_failure) = pinned.get(&address) {
                if last_failure.elapsed() < max_backoff {
                    return Err(NodeError::SubscriptionFailed {
                        status: format!(
                            "validator {} on cooldown after recent subscription failure",
                            address
                        ),
                    });
                }
            }
        }

        // Use shared atomic counter so unfold can reset it on successful reconnection.
        let retry_count = Arc::new(AtomicU32::new(0));
        let subscription_request = SubscriptionRequest {
            chain_ids: chains.into_iter().map(|chain| chain.into()).collect(),
        };
        let mut client = self.client.clone();

        // Make the first connection attempt before returning from this method.
        let mut stream = Some(
            client
                .subscribe(subscription_request.clone())
                .await
                .map_err(|status| {
                    subscription_cooldowns
                        .pin()
                        .insert(address.clone(), Instant::now());
                    NodeError::SubscriptionFailed {
                        status: status.to_string(),
                    }
                })?
                .into_inner(),
        );

        // A stream of `Result<grpc::Notification, tonic::Status>` that keeps calling
        // `client.subscribe(request)` endlessly and without delay.
        let retry_count_for_unfold = retry_count.clone();
        let cooldowns_for_unfold = subscription_cooldowns.clone();
        let address_for_unfold = address.clone();
        let endlessly_retrying_notification_stream = stream::unfold((), move |()| {
            let mut client = client.clone();
            let subscription_request = subscription_request.clone();
            let mut stream = stream.take();
            let retry_count = retry_count_for_unfold.clone();
            let cooldowns = cooldowns_for_unfold.clone();
            let cooldown_address = address_for_unfold.clone();
            async move {
                let stream = if let Some(stream) = stream.take() {
                    future::Either::Right(stream)
                } else {
                    match client.subscribe(subscription_request.clone()).await {
                        Err(err) => future::Either::Left(stream::iter(iter::once(Err(err)))),
                        Ok(response) => {
                            // Reset retry count on successful reconnection.
                            retry_count.store(0, Ordering::Relaxed);
                            cooldowns.pin().remove(&cooldown_address);
                            trace!("Successfully reconnected subscription stream");
                            future::Either::Right(response.into_inner())
                        }
                    }
                };
                Some((stream, ()))
            }
        })
        .flatten();

        let span = tracing::info_span!("notification stream");
        #[cfg(with_metrics)]
        let address_for_metrics = address.clone();
        let cooldowns_for_take_while = subscription_cooldowns;
        let address_for_take_while = address.clone();
        // The stream of `Notification`s that inserts increasing delays after retriable errors, and
        // terminates after unexpected or fatal errors.
        let notification_stream = endlessly_retrying_notification_stream
            .map(|result| {
                Option::<Notification>::try_from(result?).map_err(|err| {
                    let message = format!("Could not deserialize notification: {}", err);
                    tonic::Status::new(Code::Internal, message)
                })
            })
            .take_while(move |result| {
                let Err(status) = result else {
                    retry_count.store(0, Ordering::Relaxed);
                    return future::Either::Left(future::ready(true));
                };

                #[cfg(with_metrics)]
                metrics::VALIDATOR_SUBSCRIPTION_ERRORS
                    .with_label_values(&[&address_for_metrics])
                    .inc();

                let current_retry_count = retry_count.load(Ordering::Relaxed);
                if !span.in_scope(|| Self::is_retryable(status))
                    || current_retry_count >= max_retries
                {
                    cooldowns_for_take_while
                        .pin()
                        .insert(address_for_take_while.clone(), Instant::now());
                    return future::Either::Left(future::ready(false));
                }
                let delay =
                    crate::jittered_backoff_delay(retry_delay, current_retry_count, max_backoff);
                retry_count.fetch_add(1, Ordering::Relaxed);
                future::Either::Right(async move {
                    linera_base::time::timer::sleep(delay).await;
                    true
                })
            })
            .filter_map(move |result| {
                future::ready(match result {
                    Ok(notification @ Some(_)) => notification,
                    Ok(None) => None,
                    Err(err) => {
                        debug!(%address, "{}", err);
                        None
                    }
                })
            });

        Ok(Box::pin(notification_stream))
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn get_version_info(&self) -> Result<VersionInfo, NodeError> {
        let req = ();
        Ok(client_delegate!(self, get_version_info, req)?.into())
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn get_network_description(&self) -> Result<NetworkDescription, NodeError> {
        let req = ();
        Ok(client_delegate!(self, get_network_description, req)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn upload_blob(&self, content: BlobContent) -> Result<BlobId, NodeError> {
        Ok(client_delegate!(self, upload_blob, content)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn download_blob(&self, blob_id: BlobId) -> Result<BlobContent, NodeError> {
        Ok(client_delegate!(self, download_blob, blob_id)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn download_pending_blob(
        &self,
        chain_id: ChainId,
        blob_id: BlobId,
    ) -> Result<BlobContent, NodeError> {
        let req = (chain_id, blob_id);
        client_delegate!(self, download_pending_blob, req)?.try_into()
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn handle_pending_blob(
        &self,
        chain_id: ChainId,
        blob: BlobContent,
    ) -> Result<ChainInfoResponse, NodeError> {
        let req = (chain_id, blob);
        GrpcClient::try_into_chain_info(client_delegate!(self, handle_pending_blob, req)?)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn download_certificate(
        &self,
        hash: CryptoHash,
    ) -> Result<ConfirmedBlockCertificate, NodeError> {
        ConfirmedBlockCertificate::try_from(Certificate::try_from(client_delegate!(
            self,
            download_certificate,
            hash
        )?)?)
        .map_err(|_| NodeError::UnexpectedCertificateValue)
    }

    #[instrument(target = "grpc_client", skip_all, err(level = Level::DEBUG), fields(address = self.address))]
    async fn download_certificates(
        &self,
        hashes: Vec<CryptoHash>,
    ) -> Result<Vec<ConfirmedBlockCertificate>, NodeError> {
        let mut missing_hashes = hashes;
        let mut certs_collected = Vec::with_capacity(missing_hashes.len());
        while !missing_hashes.is_empty() {
            // Macro doesn't compile if we pass `missing_hashes.clone()` directly to `client_delegate!`.
            let missing = missing_hashes.clone();
            let mut received: Vec<ConfirmedBlockCertificate> = Vec::<Certificate>::try_from(
                client_delegate!(self, download_certificates, missing)?,
            )?
            .into_iter()
            .map(|cert| {
                ConfirmedBlockCertificate::try_from(cert)
                    .map_err(|_| NodeError::UnexpectedCertificateValue)
            })
            .collect::<Result<_, _>>()?;

            // In the case of the server not returning any certificates, we break the loop.
            if received.is_empty() {
                break;
            }

            // Honest validator should return certificates in the same order as the requested hashes.
            missing_hashes = missing_hashes[received.len()..].to_vec();
            certs_collected.append(&mut received);
        }
        ensure!(
            missing_hashes.is_empty(),
            NodeError::MissingCertificates(missing_hashes)
        );
        Ok(certs_collected)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn download_certificates_by_heights(
        &self,
        chain_id: ChainId,
        heights: Vec<BlockHeight>,
    ) -> Result<Vec<ConfirmedBlockCertificate>, NodeError> {
        let mut missing: BTreeSet<BlockHeight> = heights.into_iter().collect();
        let mut certs_collected = vec![];
        while !missing.is_empty() {
            let request = CertificatesByHeightRequest {
                chain_id,
                heights: missing.iter().copied().collect(),
            };
            let mut received: Vec<ConfirmedBlockCertificate> =
                client_delegate!(self, download_raw_certificates_by_heights, request)?
                    .certificates
                    .into_iter()
                    .map(
                        |RawCertificate {
                             lite_certificate,
                             confirmed_block,
                         }| {
                            let cert = bcs::from_bytes::<LiteCertificate>(&lite_certificate)
                                .map_err(|_| NodeError::UnexpectedCertificateValue)?;

                            let block = bcs::from_bytes::<ConfirmedBlock>(&confirmed_block)
                                .map_err(|_| NodeError::UnexpectedCertificateValue)?;

                            cert.with_value(block)
                                .ok_or(NodeError::UnexpectedCertificateValue)
                        },
                    )
                    .collect::<Result<_, _>>()?;

            if received.is_empty() {
                break;
            }

            // Remove only the heights we actually received from missing set.
            for cert in &received {
                missing.remove(&cert.inner().height());
            }
            certs_collected.append(&mut received);
        }
        certs_collected.sort_by_key(|cert| cert.inner().height());
        Ok(certs_collected)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn blob_last_used_by(&self, blob_id: BlobId) -> Result<CryptoHash, NodeError> {
        Ok(client_delegate!(self, blob_last_used_by, blob_id)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn missing_blob_ids(&self, blob_ids: Vec<BlobId>) -> Result<Vec<BlobId>, NodeError> {
        Ok(client_delegate!(self, missing_blob_ids, blob_ids)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::WARN), fields(address = self.address))]
    async fn blob_last_used_by_certificate(
        &self,
        blob_id: BlobId,
    ) -> Result<ConfirmedBlockCertificate, NodeError> {
        Ok(client_delegate!(self, blob_last_used_by_certificate, blob_id)?.try_into()?)
    }

    #[instrument(target = "grpc_client", skip(self), err(level = Level::DEBUG), fields(address = self.address))]
    async fn previous_event_blocks(
        &self,
        chain_id: ChainId,
        stream_ids: Vec<StreamId>,
    ) -> Result<BTreeMap<StreamId, (BlockHeight, CryptoHash)>, NodeError> {
        let mut result = BTreeMap::new();
        for chunk in stream_ids.chunks(MAX_STREAM_IDS_PER_REQUEST) {
            let request = (chain_id, chunk.to_vec());
            let response: api::PreviousEventBlocksResponse =
                client_delegate!(self, previous_event_blocks, request)?;
            let entries: BTreeMap<StreamId, (BlockHeight, CryptoHash)> = response.try_into()?;
            result.extend(entries);
        }
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use linera_base::{
        crypto::CryptoHash,
        data_types::BlockHeight,
        identifiers::{ApplicationId, GenericApplicationId, StreamId, StreamName},
    };

    use super::{api, GRPC_MAX_MESSAGE_SIZE, MAX_STREAM_IDS_PER_REQUEST};

    /// Verifies that a response with `MAX_STREAM_IDS_PER_REQUEST` entries fits within
    /// the gRPC message size limit, even with large stream IDs.
    #[test]
    fn max_stream_ids_fits() {
        let large_stream_id = api::StreamId {
            bytes: bincode::serialize(&StreamId {
                application_id: GenericApplicationId::User(ApplicationId::new(
                    CryptoHash::test_hash("app"),
                )),
                stream_name: StreamName(vec![0xFF; 256]),
            })
            .unwrap(),
        };
        let response = api::PreviousEventBlocksResponse {
            previous_event_blocks: (0..MAX_STREAM_IDS_PER_REQUEST)
                .map(|_| api::PreviousEventBlock {
                    stream_id: Some(large_stream_id.clone()),
                    block_height: Some(BlockHeight::MAX.into()),
                    crypto_hash: Some(CryptoHash::test_hash("hash").into()),
                })
                .collect(),
        };
        let size = prost::Message::encoded_len(&response);
        assert!(
            size < GRPC_MAX_MESSAGE_SIZE,
            "Response with {MAX_STREAM_IDS_PER_REQUEST} entries is {size} bytes, \
             exceeding the {GRPC_MAX_MESSAGE_SIZE}-byte gRPC limit"
        );
    }
}