hotshot_query_service/data_source/storage/sql/queries/
explorer.rs

1// Copyright (c) 2022 Espresso Systems (espressosys.com)
2// This file is part of the HotShot Query Service library.
3//
4// This program is free software: you can redistribute it and/or modify it under the terms of the GNU
5// General Public License as published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9// General Public License for more details.
10// You should have received a copy of the GNU General Public License along with this program. If not,
11// see <https://www.gnu.org/licenses/>.
12
13//! Explorer storage implementation for a database query engine.
14
15use std::{collections::VecDeque, num::NonZeroUsize};
16
17use async_trait::async_trait;
18use committable::{Commitment, Committable};
19use futures::stream::{self, StreamExt, TryStreamExt};
20use hotshot_types::traits::{block_contents::BlockHeader, node_implementation::NodeType};
21use itertools::Itertools;
22use sqlx::{FromRow, Row};
23use tagged_base64::{Tagged, TaggedBase64};
24
25use super::{
26    super::transaction::{Transaction, TransactionMode, query},
27    BLOCK_COLUMNS, Database, Db, DecodeError,
28};
29use crate::{
30    Header, Payload, QueryError, QueryResult, Transaction as HotshotTransaction,
31    availability::{BlockQueryData, QueryableHeader, QueryablePayload},
32    data_source::storage::{ExplorerStorage, NodeStorage},
33    explorer::{
34        self, BalanceAmount, BlockDetail, BlockIdentifier, BlockRange, BlockSummary,
35        ExplorerHistograms, ExplorerSummary, GenesisOverview, GetBlockDetailError,
36        GetBlockSummariesError, GetBlockSummariesRequest, GetExplorerSummaryError,
37        GetSearchResultsError, GetTransactionDetailError, GetTransactionSummariesError,
38        GetTransactionSummariesRequest, MonetaryValue, SearchResult, TransactionIdentifier,
39        TransactionRange, TransactionSummary, TransactionSummaryFilter,
40        errors::{self, NotFound},
41        query_data::TransactionDetailResponse,
42        traits::ExplorerHeader,
43    },
44    types::HeightIndexed,
45};
46
47impl From<sqlx::Error> for GetExplorerSummaryError {
48    fn from(err: sqlx::Error) -> Self {
49        Self::from(QueryError::from(err))
50    }
51}
52
53impl From<sqlx::Error> for GetTransactionDetailError {
54    fn from(err: sqlx::Error) -> Self {
55        Self::from(QueryError::from(err))
56    }
57}
58
59impl From<sqlx::Error> for GetTransactionSummariesError {
60    fn from(err: sqlx::Error) -> Self {
61        Self::from(QueryError::from(err))
62    }
63}
64
65impl From<sqlx::Error> for GetBlockDetailError {
66    fn from(err: sqlx::Error) -> Self {
67        Self::from(QueryError::from(err))
68    }
69}
70
71impl From<sqlx::Error> for GetBlockSummariesError {
72    fn from(err: sqlx::Error) -> Self {
73        Self::from(QueryError::from(err))
74    }
75}
76
77impl From<sqlx::Error> for GetSearchResultsError {
78    fn from(err: sqlx::Error) -> Self {
79        Self::from(QueryError::from(err))
80    }
81}
82
83impl<'r, Types> FromRow<'r, <Db as Database>::Row> for BlockSummary<Types>
84where
85    Types: NodeType,
86    Header<Types>: BlockHeader<Types> + ExplorerHeader<Types>,
87    Payload<Types>: QueryablePayload<Types>,
88{
89    fn from_row(row: &'r <Db as Database>::Row) -> sqlx::Result<Self> {
90        BlockQueryData::<Types>::from_row(row)?
91            .try_into()
92            .decode_error("malformed block summary")
93    }
94}
95
96impl<'r, Types> FromRow<'r, <Db as Database>::Row> for BlockDetail<Types>
97where
98    Types: NodeType,
99    Header<Types>: BlockHeader<Types> + ExplorerHeader<Types>,
100    Payload<Types>: QueryablePayload<Types>,
101    BalanceAmount<Types>: Into<MonetaryValue>,
102{
103    fn from_row(row: &'r <Db as Database>::Row) -> sqlx::Result<Self> {
104        BlockQueryData::<Types>::from_row(row)?
105            .try_into()
106            .decode_error("malformed block detail")
107    }
108}
109
110lazy_static::lazy_static! {
111    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_LATEST: String = {
112        format!(
113            "SELECT {BLOCK_COLUMNS}
114                FROM header AS h
115                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
116                ORDER BY h.height DESC
117                LIMIT $1"
118            )
119    };
120
121    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_HEIGHT: String = {
122        format!(
123            "SELECT {BLOCK_COLUMNS}
124                FROM header AS h
125                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
126                WHERE h.height <= $1
127                ORDER BY h.height DESC
128                LIMIT $2"
129        )
130    };
131
132    // We want to match the blocks starting with the given hash, and working backwards
133    // until we have returned up to the number of requested blocks.  The hash for a
134    // block should be unique, so we should just need to start with identifying the
135    // block height with the given hash, and return all blocks with a height less than
136    // or equal to that height, up to the number of requested blocks.
137    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_HASH: String = {
138        format!(
139            "SELECT {BLOCK_COLUMNS}
140                FROM header AS h
141                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
142                WHERE h.height <= (SELECT h1.height FROM header AS h1 WHERE h1.hash = $1)
143                ORDER BY h.height DESC
144                LIMIT $2",
145        )
146    };
147
148    static ref GET_BLOCK_DETAIL_QUERY_FOR_LATEST: String = {
149        format!(
150            "SELECT {BLOCK_COLUMNS}
151                FROM header AS h
152                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
153                ORDER BY h.height DESC
154                LIMIT 1"
155        )
156    };
157
158    static ref GET_BLOCK_DETAIL_QUERY_FOR_HEIGHT: String = {
159        format!(
160            "SELECT {BLOCK_COLUMNS}
161                FROM header AS h
162                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
163                WHERE h.height = $1
164                ORDER BY h.height DESC
165                LIMIT 1"
166        )
167    };
168
169    static ref GET_BLOCK_DETAIL_QUERY_FOR_HASH: String = {
170        format!(
171            "SELECT {BLOCK_COLUMNS}
172                FROM header AS h
173                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
174                WHERE h.hash = $1
175                ORDER BY h.height DESC
176                LIMIT 1"
177        )
178    };
179
180
181    static ref GET_BLOCKS_CONTAINING_TRANSACTIONS_NO_FILTER_QUERY: String = {
182        format!(
183            "SELECT {BLOCK_COLUMNS}
184               FROM header AS h
185               JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
186               WHERE h.height IN (
187                   SELECT t.block_height
188                       FROM transactions AS t
189                       WHERE (t.block_height, t.ns_id, t.position) <= ($1, $2, $3)
190                       ORDER BY t.block_height DESC, t.ns_id DESC, t.position DESC
191                       LIMIT $4
192               )
193               ORDER BY h.height DESC"
194        )
195    };
196
197    static ref GET_BLOCKS_CONTAINING_TRANSACTIONS_IN_NAMESPACE_QUERY: String = {
198        format!(
199            "SELECT {BLOCK_COLUMNS}
200               FROM header AS h
201               JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
202               WHERE h.height IN (
203                   SELECT t.block_height
204                       FROM transactions AS t
205                       WHERE (t.block_height, t.ns_id, t.position) <= ($1, $2, $3)
206                         AND t.ns_id = $5
207                       ORDER BY t.block_height DESC, t.ns_id DESC, t.position DESC
208                       LIMIT $4
209               )
210               ORDER BY h.height DESC"
211        )
212    };
213
214    static ref GET_TRANSACTION_SUMMARIES_QUERY_FOR_BLOCK: String = {
215        format!(
216            "SELECT {BLOCK_COLUMNS}
217                FROM header AS h
218                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
219                WHERE  h.height = $1
220                ORDER BY h.height DESC"
221        )
222    };
223
224    static ref GET_TRANSACTION_DETAIL_QUERY_FOR_LATEST: String = {
225        format!(
226            "SELECT {BLOCK_COLUMNS}
227                FROM header AS h
228                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
229                WHERE h.height = (
230                    SELECT MAX(t1.block_height)
231                        FROM transactions AS t1
232                )
233                ORDER BY h.height DESC"
234        )
235    };
236
237    static ref GET_TRANSACTION_DETAIL_QUERY_FOR_HEIGHT_AND_OFFSET: String = {
238        format!(
239            "SELECT {BLOCK_COLUMNS}
240                FROM header AS h
241                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
242                WHERE h.height = (
243                    SELECT t1.block_height
244                        FROM transactions AS t1
245                        WHERE t1.block_height = $1
246                        ORDER BY t1.block_height, t1.ns_id, t1.position
247                        LIMIT 1
248                        OFFSET $2
249                       
250                )
251                ORDER BY h.height DESC",
252        )
253    };
254
255    static ref GET_TRANSACTION_DETAIL_QUERY_FOR_HASH: String = {
256        format!(
257            "SELECT {BLOCK_COLUMNS}
258                FROM header AS h
259                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
260                WHERE h.height = (
261                    SELECT t1.block_height
262                        FROM transactions AS t1
263                        WHERE t1.hash = $1
264                        ORDER BY t1.block_height DESC, t1.ns_id DESC, t1.position DESC
265                        LIMIT 1
266                )
267                ORDER BY h.height DESC"
268        )
269    };
270}
271
272/// [EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES] is the number of entries we want
273/// to return in our histogram summary.
274const EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES: usize = 50;
275
276/// [EXPLORER_SUMMARY_NUM_BLOCKS] is the number of blocks we want to return in
277/// our explorer summary.
278const EXPLORER_SUMMARY_NUM_BLOCKS: usize = 10;
279
280/// [EXPLORER_SUMMARY_NUM_TRANSACTIONS] is the number of transactions we want
281/// to return in our explorer summary.
282const EXPLORER_SUMMARY_NUM_TRANSACTIONS: usize = 10;
283
284#[async_trait]
285impl<Mode, Types> ExplorerStorage<Types> for Transaction<Mode>
286where
287    Mode: TransactionMode,
288    Types: NodeType,
289    Payload<Types>: QueryablePayload<Types>,
290    Header<Types>: QueryableHeader<Types> + ExplorerHeader<Types>,
291    crate::Transaction<Types>: explorer::traits::ExplorerTransaction<Types>,
292    BalanceAmount<Types>: Into<explorer::monetary_value::MonetaryValue>,
293{
294    async fn get_block_summaries(
295        &mut self,
296        request: GetBlockSummariesRequest<Types>,
297    ) -> Result<Vec<BlockSummary<Types>>, GetBlockSummariesError> {
298        let request = &request.0;
299
300        let query_stmt = match request.target {
301            BlockIdentifier::Latest => {
302                query(&GET_BLOCK_SUMMARIES_QUERY_FOR_LATEST).bind(request.num_blocks.get() as i64)
303            },
304            BlockIdentifier::Height(height) => query(&GET_BLOCK_SUMMARIES_QUERY_FOR_HEIGHT)
305                .bind(height as i64)
306                .bind(request.num_blocks.get() as i64),
307            BlockIdentifier::Hash(hash) => query(&GET_BLOCK_SUMMARIES_QUERY_FOR_HASH)
308                .bind(hash.to_string())
309                .bind(request.num_blocks.get() as i64),
310        };
311
312        let row_stream = query_stmt.fetch(self.as_mut());
313        let result = row_stream.map(|row| BlockSummary::from_row(&row?));
314
315        Ok(result.try_collect().await?)
316    }
317
318    async fn get_block_detail(
319        &mut self,
320        request: BlockIdentifier<Types>,
321    ) -> Result<BlockDetail<Types>, GetBlockDetailError> {
322        let query_stmt = match request {
323            BlockIdentifier::Latest => query(&GET_BLOCK_DETAIL_QUERY_FOR_LATEST),
324            BlockIdentifier::Height(height) => {
325                query(&GET_BLOCK_DETAIL_QUERY_FOR_HEIGHT).bind(height as i64)
326            },
327            BlockIdentifier::Hash(hash) => {
328                query(&GET_BLOCK_DETAIL_QUERY_FOR_HASH).bind(hash.to_string())
329            },
330        };
331
332        let query_result = query_stmt.fetch_one(self.as_mut()).await?;
333        let block = BlockDetail::from_row(&query_result)?;
334
335        Ok(block)
336    }
337
338    async fn get_transaction_summaries(
339        &mut self,
340        request: GetTransactionSummariesRequest<Types>,
341    ) -> Result<Vec<TransactionSummary<Types>>, GetTransactionSummariesError> {
342        let range = &request.range;
343        let target = &range.target;
344        let filter = &request.filter;
345
346        // We need to figure out the transaction target we are going to start
347        // returned results based on.
348        let transaction_target_query = match target {
349            TransactionIdentifier::Latest => query(
350                "SELECT block_height AS height, ns_id, position FROM transactions ORDER BY \
351                 block_height DESC, ns_id DESC, position DESC LIMIT 1",
352            ),
353            TransactionIdentifier::HeightAndOffset(height, _) => query(
354                "SELECT block_height AS height, ns_id, position FROM transactions WHERE \
355                 block_height = $1 ORDER BY ns_id DESC, position DESC LIMIT 1",
356            )
357            .bind(*height as i64),
358            TransactionIdentifier::Hash(hash) => query(
359                "SELECT block_height AS height, ns_id, position FROM transactions WHERE hash = $1 \
360                 ORDER BY block_height DESC, ns_id DESC, position DESC LIMIT 1",
361            )
362            .bind(hash.to_string()),
363        };
364        let Some(transaction_target) = transaction_target_query
365            .fetch_optional(self.as_mut())
366            .await?
367        else {
368            // If nothing is found, then we want to return an empty summary list as it means there
369            // is either no transaction, or the targeting criteria fails to identify any transaction
370            return Ok(vec![]);
371        };
372
373        let block_height = transaction_target.get::<i64, _>("height") as usize;
374        let namespace = transaction_target.get::<i64, _>("ns_id");
375        let position = transaction_target.get::<i64, _>("position");
376        let offset = if let TransactionIdentifier::HeightAndOffset(_, offset) = target {
377            *offset
378        } else {
379            0
380        };
381
382        // Our block_stream is more-or-less always the same, the only difference
383        // is a an additional filter on the identified transactions being found
384        // In general, we use our `transaction_target` to identify the starting
385        // `block_height` and `namespace`, and `position`, and we grab up to `limit`
386        // transactions from that point.  We then grab only the blocks for those
387        // identified transactions, as only those blocks are needed to pull all
388        // of the relevant transactions.
389        let query_stmt = match filter {
390            TransactionSummaryFilter::RollUp(ns) => {
391                query(&GET_BLOCKS_CONTAINING_TRANSACTIONS_IN_NAMESPACE_QUERY)
392                    .bind(block_height as i64)
393                    .bind(namespace)
394                    .bind(position)
395                    .bind((range.num_transactions.get() + offset) as i64)
396                    .bind((*ns).into())
397            },
398            TransactionSummaryFilter::None => {
399                query(&GET_BLOCKS_CONTAINING_TRANSACTIONS_NO_FILTER_QUERY)
400                    .bind(block_height as i64)
401                    .bind(namespace)
402                    .bind(position)
403                    .bind((range.num_transactions.get() + offset) as i64)
404            },
405
406            TransactionSummaryFilter::Block(block) => {
407                query(&GET_TRANSACTION_SUMMARIES_QUERY_FOR_BLOCK).bind(*block as i64)
408            },
409        };
410
411        let block_stream = query_stmt
412            .fetch(self.as_mut())
413            .map(|row| BlockQueryData::from_row(&row?));
414
415        let transaction_summary_stream = block_stream.flat_map(|row| match row {
416            Ok(block) => {
417                tracing::info!(height = block.height(), "selected block");
418                stream::iter(
419                    block
420                        .enumerate()
421                        .filter(|(ix, _)| {
422                            if let TransactionSummaryFilter::RollUp(ns) = filter {
423                                let tx_ns = QueryableHeader::<Types>::namespace_id(
424                                    block.header(),
425                                    &ix.ns_index,
426                                );
427                                tx_ns.as_ref() == Some(ns)
428                            } else {
429                                true
430                            }
431                        })
432                        .enumerate()
433                        .map(|(index, (_, txn))| {
434                            TransactionSummary::try_from((&block, index, txn)).map_err(|err| {
435                                QueryError::Error {
436                                    message: err.to_string(),
437                                }
438                            })
439                        })
440                        .collect::<Vec<QueryResult<TransactionSummary<Types>>>>()
441                        .into_iter()
442                        .rev()
443                        .collect::<Vec<QueryResult<TransactionSummary<Types>>>>(),
444                )
445            },
446            Err(err) => stream::iter(vec![Err(err.into())]),
447        });
448
449        let transaction_summary_vec = transaction_summary_stream
450            .try_collect::<Vec<TransactionSummary<Types>>>()
451            .await?;
452
453        Ok(transaction_summary_vec
454            .into_iter()
455            .skip(offset)
456            .skip_while(|txn| {
457                if let TransactionIdentifier::Hash(hash) = target {
458                    txn.hash != *hash
459                } else {
460                    false
461                }
462            })
463            .take(range.num_transactions.get())
464            .collect::<Vec<TransactionSummary<Types>>>())
465    }
466
467    async fn get_transaction_detail(
468        &mut self,
469        request: TransactionIdentifier<Types>,
470    ) -> Result<TransactionDetailResponse<Types>, GetTransactionDetailError> {
471        let target = request;
472
473        let query_stmt = match target {
474            TransactionIdentifier::Latest => query(&GET_TRANSACTION_DETAIL_QUERY_FOR_LATEST),
475            TransactionIdentifier::HeightAndOffset(height, offset) => {
476                query(&GET_TRANSACTION_DETAIL_QUERY_FOR_HEIGHT_AND_OFFSET)
477                    .bind(height as i64)
478                    .bind(offset as i64)
479            },
480            TransactionIdentifier::Hash(hash) => {
481                query(&GET_TRANSACTION_DETAIL_QUERY_FOR_HASH).bind(hash.to_string())
482            },
483        };
484
485        let query_row = query_stmt.fetch_one(self.as_mut()).await?;
486        let block = BlockQueryData::<Types>::from_row(&query_row)?;
487
488        let txns = block.enumerate().map(|(_, txn)| txn).collect::<Vec<_>>();
489
490        let (offset, txn) = match target {
491            TransactionIdentifier::Latest => txns.into_iter().enumerate().next_back().ok_or(
492                GetTransactionDetailError::TransactionNotFound(NotFound {
493                    key: "Latest".to_string(),
494                }),
495            ),
496            TransactionIdentifier::HeightAndOffset(height, offset) => {
497                txns.into_iter().enumerate().nth(offset).ok_or(
498                    GetTransactionDetailError::TransactionNotFound(NotFound {
499                        key: format!("at {height} and {offset}"),
500                    }),
501                )
502            },
503            TransactionIdentifier::Hash(hash) => txns
504                .into_iter()
505                .enumerate()
506                .find(|(_, txn)| txn.commit() == hash)
507                .ok_or(GetTransactionDetailError::TransactionNotFound(NotFound {
508                    key: format!("hash {hash}"),
509                })),
510        }?;
511
512        Ok(TransactionDetailResponse::try_from((&block, offset, txn))?)
513    }
514
515    async fn get_explorer_summary(
516        &mut self,
517    ) -> Result<ExplorerSummary<Types>, GetExplorerSummaryError> {
518        let histograms = {
519            let histogram_query_result = query(
520                "SELECT
521                    h.height AS height,
522                    h.timestamp AS timestamp,
523                    h.timestamp - lead(timestamp) OVER (ORDER BY h.height DESC) AS time,
524                    p.size AS size,
525                    p.num_transactions AS transactions
526                FROM header AS h
527                JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
528                WHERE
529                    h.height IN (SELECT height FROM header ORDER BY height DESC LIMIT $1)
530                ORDER BY h.height
531                ",
532            )
533            .bind((EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES + 1) as i64)
534            .fetch(self.as_mut());
535
536            let mut histograms: ExplorerHistograms = histogram_query_result
537                .map(|row_stream| {
538                    row_stream.map(|row| {
539                        let height: i64 = row.try_get("height")?;
540                        let timestamp: i64 = row.try_get("timestamp")?;
541                        let time: Option<i64> = row.try_get("time")?;
542                        let size: Option<i32> = row.try_get("size")?;
543                        let num_transactions: i32 = row.try_get("transactions")?;
544
545                        Ok((height, timestamp, time, size, num_transactions))
546                    })
547                })
548                .try_fold(
549                    ExplorerHistograms {
550                        block_time: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
551                        block_size: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
552                        block_transactions: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
553                        block_heights: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
554                    },
555                    |mut histograms: ExplorerHistograms,
556                     row: sqlx::Result<(i64, i64, Option<i64>, Option<i32>, i32)>| async {
557                        let (height, _timestamp, time, size, num_transactions) = row?;
558
559                        histograms.block_time.push_back(time.map(|i| i as u64));
560                        histograms.block_size.push_back(size.map(|i| i as u64));
561                        histograms.block_transactions.push_back(num_transactions as u64);
562                        histograms.block_heights.push_back(height as u64);
563                        Ok(histograms)
564                    },
565                )
566                .await?;
567
568            while histograms.block_time.len() > EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES {
569                histograms.block_time.pop_front();
570                histograms.block_size.pop_front();
571                histograms.block_transactions.pop_front();
572                histograms.block_heights.pop_front();
573            }
574
575            histograms
576        };
577
578        let genesis_overview = {
579            let blocks = NodeStorage::<Types>::block_height(self).await? as u64;
580            let transactions =
581                NodeStorage::<Types>::count_transactions_in_range(self, .., None).await? as u64;
582            GenesisOverview {
583                rollups: 0,
584                transactions,
585                blocks,
586            }
587        };
588
589        let latest_block: BlockDetail<Types> =
590            self.get_block_detail(BlockIdentifier::Latest).await?;
591
592        let latest_blocks: Vec<BlockSummary<Types>> = self
593            .get_block_summaries(GetBlockSummariesRequest(BlockRange {
594                target: BlockIdentifier::Latest,
595                num_blocks: NonZeroUsize::new(EXPLORER_SUMMARY_NUM_BLOCKS).unwrap(),
596            }))
597            .await?;
598
599        let latest_transactions: Vec<TransactionSummary<Types>> = self
600            .get_transaction_summaries(GetTransactionSummariesRequest {
601                range: TransactionRange {
602                    target: TransactionIdentifier::Latest,
603                    num_transactions: NonZeroUsize::new(EXPLORER_SUMMARY_NUM_TRANSACTIONS).unwrap(),
604                },
605                filter: TransactionSummaryFilter::None,
606            })
607            .await?;
608
609        Ok(ExplorerSummary {
610            genesis_overview,
611            latest_block,
612            latest_transactions,
613            latest_blocks,
614            histograms,
615        })
616    }
617
618    async fn get_search_results(
619        &mut self,
620        search_query: TaggedBase64,
621    ) -> Result<SearchResult<Types>, GetSearchResultsError> {
622        let search_tag = search_query.tag();
623        let header_tag = Commitment::<Header<Types>>::tag();
624        let tx_tag = Commitment::<HotshotTransaction<Types>>::tag();
625
626        if search_tag != header_tag && search_tag != tx_tag {
627            return Err(GetSearchResultsError::InvalidQuery(errors::BadQuery {}));
628        }
629
630        let search_query_string = search_query.to_string();
631        if search_tag == header_tag {
632            let block_query = format!(
633                "SELECT {BLOCK_COLUMNS}
634                    FROM header AS h
635                    JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
636                    WHERE h.hash = $1
637                    ORDER BY h.height DESC
638                    LIMIT 1"
639            );
640            let row = query(block_query.as_str())
641                .bind(&search_query_string)
642                .fetch_one(self.as_mut())
643                .await?;
644
645            let block = BlockSummary::from_row(&row)?;
646
647            Ok(SearchResult {
648                blocks: vec![block],
649                transactions: Vec::new(),
650            })
651        } else {
652            let transactions_query = format!(
653                "SELECT {BLOCK_COLUMNS}
654                    FROM header AS h
655                    JOIN payload AS p ON (h.payload_hash, h.ns_table) = (p.hash, p.ns_table)
656                    JOIN transactions AS t ON h.height = t.block_height
657                    WHERE t.hash = $1
658                    ORDER BY h.height DESC
659                    LIMIT 5"
660            );
661            let transactions_query_rows = query(transactions_query.as_str())
662                .bind(&search_query_string)
663                .fetch(self.as_mut());
664            let transactions_query_result: Vec<TransactionSummary<Types>> = transactions_query_rows
665                .map(|row| -> Result<Vec<TransactionSummary<Types>>, QueryError>{
666                    let block = BlockQueryData::<Types>::from_row(&row?)?;
667                    let transactions = block
668                        .enumerate()
669                        .enumerate()
670                        .filter(|(_, (_, txn))| txn.commit().to_string() == search_query_string)
671                        .map(|(offset, (_, txn))| {
672                            Ok(TransactionSummary::try_from((
673                                &block, offset, txn,
674                            ))?)
675                        })
676                        .try_collect::<TransactionSummary<Types>, Vec<TransactionSummary<Types>>, QueryError>()?;
677                    Ok(transactions)
678                })
679                .try_collect::<Vec<Vec<TransactionSummary<Types>>>>()
680                .await?
681                .into_iter()
682                .flatten()
683                .collect();
684
685            Ok(SearchResult {
686                blocks: Vec::new(),
687                transactions: transactions_query_result,
688            })
689        }
690    }
691}