Skip to main content

zebra_rpc/indexer/
methods.rs

1//! Implements `Indexer` methods on the `IndexerRPC` type
2
3use std::{collections::HashSet, pin::Pin, time::Duration};
4
5use futures::Stream;
6use tokio_stream::wrappers::ReceiverStream;
7use tonic::{Response, Status};
8use tower::util::ServiceExt;
9
10use tracing::Span;
11use zebra_chain::{block, chain_tip::ChainTip, serialization::BytesInDisplayOrder};
12use zebra_node_services::mempool::MempoolChangeKind;
13use zebra_state::{
14    ReadRequest, ReadResponse, ReadState, MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS,
15};
16
17use super::{
18    indexer_server::Indexer, server::IndexerRPC, BlockAndHash, BlockHashAndHeight, BlockRequest,
19    Empty, MempoolChangeMessage, NonFinalizedStateChangeRequest,
20};
21
22/// The maximum number of messages that can be queued to be streamed to a client.
23const RESPONSE_BUFFER_SIZE: usize = 64;
24
25/// How long to wait for a backpressured send before treating the consumer as hung and dropping
26/// the subscription.
27///
28/// All three indexer streams apply backpressure so a slow consumer doesn't miss notifications,
29/// but without a bound a consumer whose connection is half-open (dead TCP not yet detected) would
30/// block the listener task indefinitely.
31const SEND_TIMEOUT: Duration = Duration::from_secs(60);
32
33#[tonic::async_trait]
34impl<ReadStateService, Tip> Indexer for IndexerRPC<ReadStateService, Tip>
35where
36    ReadStateService: ReadState,
37    Tip: ChainTip + Clone + Send + Sync + 'static,
38{
39    type ChainTipChangeStream =
40        Pin<Box<dyn Stream<Item = Result<BlockHashAndHeight, Status>> + Send>>;
41    type NonFinalizedStateChangeStream =
42        Pin<Box<dyn Stream<Item = Result<BlockAndHash, Status>> + Send>>;
43    type MempoolChangeStream =
44        Pin<Box<dyn Stream<Item = Result<MempoolChangeMessage, Status>> + Send>>;
45
46    async fn chain_tip_change(
47        &self,
48        _: tonic::Request<Empty>,
49    ) -> Result<Response<Self::ChainTipChangeStream>, Status> {
50        let span = Span::current();
51        let (response_sender, response_receiver) = tokio::sync::mpsc::channel(RESPONSE_BUFFER_SIZE);
52        let response_stream = ReceiverStream::new(response_receiver);
53        let mut chain_tip_change = self.chain_tip_change.clone();
54
55        tokio::spawn(async move {
56            // Notify the client of chain tip changes until the channel is closed
57            while let Ok(()) = chain_tip_change.best_tip_changed().await {
58                let Some((tip_height, tip_hash)) = chain_tip_change.best_tip_height_and_hash()
59                else {
60                    continue;
61                };
62
63                let send = response_sender.send(Ok(BlockHashAndHeight::new(tip_hash, tip_height)));
64                match tokio::time::timeout(SEND_TIMEOUT, send).await {
65                    Ok(Ok(())) => {}
66                    Ok(Err(_)) => {
67                        span.in_scope(|| {
68                            tracing::info!("client disconnected, dropping chain_tip_change task");
69                        });
70                        return;
71                    }
72                    Err(_) => {
73                        span.in_scope(|| {
74                            tracing::warn!(
75                                "slow consumer, dropping chain_tip_change stream after \
76                                 send timed out"
77                            );
78                        });
79                        return;
80                    }
81                }
82            }
83
84            span.in_scope(|| {
85                tracing::warn!("chain_tip_change channel has closed");
86            });
87
88            let _ = response_sender
89                .send(Err(Status::unavailable(
90                    "chain_tip_change channel has closed",
91                )))
92                .await;
93        });
94
95        Ok(Response::new(Box::pin(response_stream)))
96    }
97
98    async fn non_finalized_state_change(
99        &self,
100        request: tonic::Request<NonFinalizedStateChangeRequest>,
101    ) -> Result<Response<Self::NonFinalizedStateChangeStream>, Status> {
102        let span = Span::current();
103        let read_state = self.read_state.clone();
104        let (response_sender, response_receiver) = tokio::sync::mpsc::channel(RESPONSE_BUFFER_SIZE);
105        let response_stream = ReceiverStream::new(response_receiver);
106
107        // The caller may provide the hashes of the chain tips it already has so the server only
108        // streams blocks after those tips. Malformed hashes (wrong length) are rejected up front.
109        let known_chain_tips = decode_known_chain_tips(request.into_inner().chain_tip_hashes)?;
110
111        tokio::spawn(async move {
112            let mut non_finalized_state_change = match read_state
113                .oneshot(ReadRequest::NonFinalizedBlocksListener { known_chain_tips })
114                .await
115            {
116                Ok(ReadResponse::NonFinalizedBlocksListener(listener)) => listener.unwrap(),
117                Ok(_) => unreachable!("unexpected response type from ReadStateService"),
118                Err(error) => {
119                    span.in_scope(|| {
120                        tracing::error!(
121                            ?error,
122                            "failed to subscribe to non-finalized state changes"
123                        );
124                    });
125
126                    let _ = response_sender
127                        .send(Err(Status::unavailable(
128                            "failed to subscribe to non-finalized state changes",
129                        )))
130                        .await;
131                    return;
132                }
133            };
134
135            loop {
136                let Some((hash, block)) = non_finalized_state_change.recv().await else {
137                    break;
138                };
139
140                let send = response_sender.send(Ok(BlockAndHash::new(hash, block)));
141                match tokio::time::timeout(SEND_TIMEOUT, send).await {
142                    Ok(Ok(())) => {}
143                    Ok(Err(_)) => {
144                        span.in_scope(|| {
145                            tracing::info!(
146                                "client disconnected, dropping non_finalized_state_change task"
147                            );
148                        });
149                        return;
150                    }
151                    Err(_) => {
152                        span.in_scope(|| {
153                            tracing::warn!(
154                                "slow consumer, dropping non_finalized_state_change stream after \
155                                 send timed out"
156                            );
157                        });
158                        return;
159                    }
160                }
161            }
162
163            span.in_scope(|| {
164                tracing::warn!("non-finalized state change channel has closed");
165            });
166
167            let _ = response_sender
168                .send(Err(Status::unavailable(
169                    "non-finalized state change channel has closed",
170                )))
171                .await;
172        });
173
174        Ok(Response::new(Box::pin(response_stream)))
175    }
176
177    async fn mempool_change(
178        &self,
179        _: tonic::Request<Empty>,
180    ) -> Result<Response<Self::MempoolChangeStream>, Status> {
181        let span = Span::current();
182        let (response_sender, response_receiver) = tokio::sync::mpsc::channel(RESPONSE_BUFFER_SIZE);
183        let response_stream = ReceiverStream::new(response_receiver);
184        let mut mempool_change = self.mempool_change.subscribe();
185
186        tokio::spawn(async move {
187            // Notify the client of chain tip changes until the channel is closed
188            while let Ok(change) = mempool_change.recv().await {
189                for tx_id in change.tx_ids() {
190                    span.in_scope(|| {
191                        tracing::debug!("mempool change: {:?}", change);
192                    });
193
194                    let msg = Ok(MempoolChangeMessage {
195                        change_type: match change.kind() {
196                            MempoolChangeKind::Added => 0,
197                            MempoolChangeKind::Invalidated => 1,
198                            MempoolChangeKind::Mined => 2,
199                        },
200                        tx_hash: tx_id.mined_id().bytes_in_display_order().to_vec(),
201                        auth_digest: tx_id
202                            .auth_digest()
203                            .map(|d| d.bytes_in_display_order().to_vec())
204                            .unwrap_or_default(),
205                    });
206
207                    let send = response_sender.send(msg);
208                    match tokio::time::timeout(SEND_TIMEOUT, send).await {
209                        Ok(Ok(())) => {}
210                        Ok(Err(_)) => {
211                            span.in_scope(|| {
212                                tracing::info!("client disconnected, dropping mempool_change task");
213                            });
214                            return;
215                        }
216                        Err(_) => {
217                            span.in_scope(|| {
218                                tracing::warn!(
219                                    "slow consumer, dropping mempool_change stream after \
220                                     send timed out"
221                                );
222                            });
223                            return;
224                        }
225                    }
226                }
227            }
228
229            span.in_scope(|| {
230                tracing::warn!("mempool_change channel has closed");
231            });
232
233            let _ = response_sender
234                .send(Err(Status::unavailable(
235                    "mempool_change channel has closed",
236                )))
237                .await;
238        });
239
240        Ok(Response::new(Box::pin(response_stream)))
241    }
242
243    async fn get_block(
244        &self,
245        request: tonic::Request<BlockRequest>,
246    ) -> Result<Response<BlockAndHash>, Status> {
247        // The request carries a single `hash_or_height` byte string: a 32-byte block hash in
248        // display order, or a 4-byte big-endian block height. The length tells the two apart.
249        let hash_or_height = request.into_inner().hash_or_height;
250        let hash_or_height = match hash_or_height.len() {
251            32 => zebra_state::HashOrHeight::Hash(hash_from_display_bytes(hash_or_height)?),
252            4 => {
253                let height = u32::from_be_bytes(
254                    hash_or_height
255                        .try_into()
256                        .expect("a 4-byte vec always converts to a [u8; 4]"),
257                );
258                let height = block::Height::try_from(height).map_err(|_| {
259                    Status::invalid_argument(format!("block height out of range: {height}"))
260                })?;
261                zebra_state::HashOrHeight::Height(height)
262            }
263            len => {
264                return Err(Status::invalid_argument(format!(
265                    "block request must be a 32-byte hash or a 4-byte height, got {len} bytes"
266                )));
267            }
268        };
269
270        match self
271            .read_state
272            .clone()
273            .oneshot(ReadRequest::Block(hash_or_height))
274            .await
275        {
276            Ok(ReadResponse::Block(Some(block))) => {
277                Ok(Response::new(BlockAndHash::new(block.hash(), block)))
278            }
279            Ok(ReadResponse::Block(None)) => Err(Status::not_found("block not found")),
280            Ok(_) => unreachable!("unexpected response type from ReadStateService"),
281            Err(error) => Err(Status::unavailable(format!(
282                "failed to read block: {error}"
283            ))),
284        }
285    }
286}
287
288/// Decodes the chain tip hashes from a [`NonFinalizedStateChangeRequest`] into a set of
289/// [`block::Hash`]es.
290///
291/// Each hash is expected to be 32 bytes in display order, matching the encoding used when the
292/// server streams [`BlockAndHash`] messages back to the caller.
293///
294/// # Errors
295///
296/// Returns an [`invalid_argument`](Status::invalid_argument) status if there are more hashes than
297/// the non-finalized state can hold chains ([`MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS`]), or
298/// if any hash is not exactly 32 bytes long.
299fn decode_known_chain_tips(chain_tip_hashes: Vec<Vec<u8>>) -> Result<HashSet<block::Hash>, Status> {
300    // Test networks keep the most chains, so a caller can't legitimately send more tips than that.
301    // Bound the untrusted input before allocating.
302    if chain_tip_hashes.len() > MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS {
303        return Err(Status::invalid_argument(format!(
304            "too many chain tip hashes: got {}, expected at most {}",
305            chain_tip_hashes.len(),
306            MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS,
307        )));
308    }
309
310    chain_tip_hashes
311        .into_iter()
312        .map(hash_from_display_bytes)
313        .collect()
314}
315
316/// Decodes a 32-byte block hash in display order, rejecting wrong-length input.
317fn hash_from_display_bytes(hash: Vec<u8>) -> Result<block::Hash, Status> {
318    let bytes: [u8; 32] = hash.try_into().map_err(|hash: Vec<u8>| {
319        Status::invalid_argument(format!(
320            "invalid block hash length: expected 32 bytes, got {}",
321            hash.len()
322        ))
323    })?;
324
325    Ok(block::Hash::from_bytes_in_display_order(&bytes))
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use tonic::Code;
332
333    fn hash(byte: u8) -> block::Hash {
334        block::Hash::from_bytes_in_display_order(&[byte; 32])
335    }
336
337    #[test]
338    fn decode_known_chain_tips_round_trips_display_order() {
339        let hashes = [hash(1), hash(2), hash(3)];
340        let encoded = hashes
341            .iter()
342            .map(|h| h.bytes_in_display_order().to_vec())
343            .collect();
344
345        let decoded = decode_known_chain_tips(encoded).expect("valid hashes should decode");
346
347        assert_eq!(decoded, hashes.into_iter().collect());
348    }
349
350    #[test]
351    fn decode_known_chain_tips_accepts_empty() {
352        assert!(decode_known_chain_tips(Vec::new())
353            .expect("empty input should decode")
354            .is_empty());
355    }
356
357    #[test]
358    fn decode_known_chain_tips_dedups() {
359        let encoded = vec![
360            hash(7).bytes_in_display_order().to_vec(),
361            hash(7).bytes_in_display_order().to_vec(),
362        ];
363
364        let decoded = decode_known_chain_tips(encoded).expect("duplicate hashes should decode");
365
366        assert_eq!(decoded, std::iter::once(hash(7)).collect());
367    }
368
369    #[test]
370    fn decode_known_chain_tips_rejects_wrong_length() {
371        let status = decode_known_chain_tips(vec![vec![0; 31]])
372            .expect_err("a 31-byte hash should be rejected");
373
374        assert_eq!(status.code(), Code::InvalidArgument);
375    }
376
377    #[test]
378    fn decode_known_chain_tips_accepts_test_network_forks() {
379        let encoded = (0..MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS as u8)
380            .map(|b| hash(b).bytes_in_display_order().to_vec())
381            .collect();
382
383        let tips = decode_known_chain_tips(encoded)
384            .expect("as many hashes as test networks keep chains should be accepted");
385
386        assert!(tips.len() > zebra_state::MAX_NON_FINALIZED_CHAIN_FORKS);
387    }
388
389    #[test]
390    fn decode_known_chain_tips_rejects_too_many() {
391        let encoded = (0..=MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS as u8)
392            .map(|b| hash(b).bytes_in_display_order().to_vec())
393            .collect();
394
395        let status = decode_known_chain_tips(encoded).expect_err(
396            "more than MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS hashes should be rejected",
397        );
398
399        assert_eq!(status.code(), Code::InvalidArgument);
400    }
401}