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::{query, Transaction, TransactionMode},
27    Database, Db, DecodeError, BLOCK_COLUMNS,
28};
29use crate::{
30    availability::{BlockQueryData, QueryableHeader, QueryablePayload},
31    data_source::storage::{ExplorerStorage, NodeStorage},
32    explorer::{
33        self,
34        errors::{self, NotFound},
35        query_data::TransactionDetailResponse,
36        traits::ExplorerHeader,
37        BalanceAmount, BlockDetail, BlockIdentifier, BlockRange, BlockSummary, ExplorerHistograms,
38        ExplorerSummary, GenesisOverview, GetBlockDetailError, GetBlockSummariesError,
39        GetBlockSummariesRequest, GetExplorerSummaryError, GetSearchResultsError,
40        GetTransactionDetailError, GetTransactionSummariesError, GetTransactionSummariesRequest,
41        MonetaryValue, SearchResult, TransactionIdentifier, TransactionRange, TransactionSummary,
42        TransactionSummaryFilter,
43    },
44    types::HeightIndexed,
45    Header, Payload, QueryError, QueryResult, Transaction as HotshotTransaction,
46};
47
48impl From<sqlx::Error> for GetExplorerSummaryError {
49    fn from(err: sqlx::Error) -> Self {
50        Self::from(QueryError::from(err))
51    }
52}
53
54impl From<sqlx::Error> for GetTransactionDetailError {
55    fn from(err: sqlx::Error) -> Self {
56        Self::from(QueryError::from(err))
57    }
58}
59
60impl From<sqlx::Error> for GetTransactionSummariesError {
61    fn from(err: sqlx::Error) -> Self {
62        Self::from(QueryError::from(err))
63    }
64}
65
66impl From<sqlx::Error> for GetBlockDetailError {
67    fn from(err: sqlx::Error) -> Self {
68        Self::from(QueryError::from(err))
69    }
70}
71
72impl From<sqlx::Error> for GetBlockSummariesError {
73    fn from(err: sqlx::Error) -> Self {
74        Self::from(QueryError::from(err))
75    }
76}
77
78impl From<sqlx::Error> for GetSearchResultsError {
79    fn from(err: sqlx::Error) -> Self {
80        Self::from(QueryError::from(err))
81    }
82}
83
84impl<'r, Types> FromRow<'r, <Db as Database>::Row> for BlockSummary<Types>
85where
86    Types: NodeType,
87    Header<Types>: BlockHeader<Types> + ExplorerHeader<Types>,
88    Payload<Types>: QueryablePayload<Types>,
89{
90    fn from_row(row: &'r <Db as Database>::Row) -> sqlx::Result<Self> {
91        BlockQueryData::<Types>::from_row(row)?
92            .try_into()
93            .decode_error("malformed block summary")
94    }
95}
96
97impl<'r, Types> FromRow<'r, <Db as Database>::Row> for BlockDetail<Types>
98where
99    Types: NodeType,
100    Header<Types>: BlockHeader<Types> + ExplorerHeader<Types>,
101    Payload<Types>: QueryablePayload<Types>,
102    BalanceAmount<Types>: Into<MonetaryValue>,
103{
104    fn from_row(row: &'r <Db as Database>::Row) -> sqlx::Result<Self> {
105        BlockQueryData::<Types>::from_row(row)?
106            .try_into()
107            .decode_error("malformed block detail")
108    }
109}
110
111lazy_static::lazy_static! {
112    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_LATEST: String = {
113        format!(
114            "SELECT {BLOCK_COLUMNS}
115                FROM header AS h
116                JOIN payload AS p ON h.height = p.height
117                ORDER BY h.height DESC
118                LIMIT $1"
119            )
120    };
121
122    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_HEIGHT: String = {
123        format!(
124            "SELECT {BLOCK_COLUMNS}
125                FROM header AS h
126                JOIN payload AS p ON h.height = p.height
127                WHERE h.height <= $1
128                ORDER BY h.height DESC
129                LIMIT $2"
130        )
131    };
132
133    // We want to match the blocks starting with the given hash, and working backwards
134    // until we have returned up to the number of requested blocks.  The hash for a
135    // block should be unique, so we should just need to start with identifying the
136    // block height with the given hash, and return all blocks with a height less than
137    // or equal to that height, up to the number of requested blocks.
138    static ref GET_BLOCK_SUMMARIES_QUERY_FOR_HASH: String = {
139        format!(
140            "SELECT {BLOCK_COLUMNS}
141                FROM header AS h
142                JOIN payload AS p ON h.height = p.height
143                WHERE h.height <= (SELECT h1.height FROM header AS h1 WHERE h1.hash = $1)
144                ORDER BY h.height DESC
145                LIMIT $2",
146        )
147    };
148
149    static ref GET_BLOCK_DETAIL_QUERY_FOR_LATEST: String = {
150        format!(
151            "SELECT {BLOCK_COLUMNS}
152                FROM header AS h
153                JOIN payload AS p ON h.height = p.height
154                ORDER BY h.height DESC
155                LIMIT 1"
156        )
157    };
158
159    static ref GET_BLOCK_DETAIL_QUERY_FOR_HEIGHT: String = {
160        format!(
161            "SELECT {BLOCK_COLUMNS}
162                FROM header AS h
163                JOIN payload AS p ON h.height = p.height
164                WHERE h.height = $1
165                ORDER BY h.height DESC
166                LIMIT 1"
167        )
168    };
169
170    static ref GET_BLOCK_DETAIL_QUERY_FOR_HASH: String = {
171        format!(
172            "SELECT {BLOCK_COLUMNS}
173                FROM header AS h
174                JOIN payload AS p ON h.height = p.height
175                WHERE h.hash = $1
176                ORDER BY h.height DESC
177                LIMIT 1"
178        )
179    };
180
181
182    static ref GET_BLOCKS_CONTAINING_TRANSACTIONS_NO_FILTER_QUERY: String = {
183        format!(
184            "SELECT {BLOCK_COLUMNS}
185               FROM header AS h
186               JOIN payload AS p ON h.height = p.height
187               WHERE h.height IN (
188                   SELECT t.block_height
189                       FROM transactions AS t
190                       WHERE (t.block_height, t.ns_id, t.position) <= ($1, $2, $3)
191                       ORDER BY t.block_height DESC, t.ns_id DESC, t.position DESC
192                       LIMIT $4
193               )
194               ORDER BY h.height DESC"
195        )
196    };
197
198    static ref GET_BLOCKS_CONTAINING_TRANSACTIONS_IN_NAMESPACE_QUERY: String = {
199        format!(
200            "SELECT {BLOCK_COLUMNS}
201               FROM header AS h
202               JOIN payload AS p ON h.height = p.height
203               WHERE h.height IN (
204                   SELECT t.block_height
205                       FROM transactions AS t
206                       WHERE (t.block_height, t.ns_id, t.position) <= ($1, $2, $3)
207                         AND t.ns_id = $5
208                       ORDER BY t.block_height DESC, t.ns_id DESC, t.position DESC
209                       LIMIT $4
210               )
211               ORDER BY h.height DESC"
212        )
213    };
214
215    static ref GET_TRANSACTION_SUMMARIES_QUERY_FOR_BLOCK: String = {
216        format!(
217            "SELECT {BLOCK_COLUMNS}
218                FROM header AS h
219                JOIN payload AS p ON h.height = p.height
220                WHERE  h.height = $1
221                ORDER BY h.height DESC"
222        )
223    };
224
225    static ref GET_TRANSACTION_DETAIL_QUERY_FOR_LATEST: String = {
226        format!(
227            "SELECT {BLOCK_COLUMNS}
228                FROM header AS h
229                JOIN payload AS p ON h.height = p.height
230                WHERE h.height = (
231                    SELECT MAX(t1.block_height)
232                        FROM transactions AS t1
233                )
234                ORDER BY h.height DESC"
235        )
236    };
237
238    static ref GET_TRANSACTION_DETAIL_QUERY_FOR_HEIGHT_AND_OFFSET: String = {
239        format!(
240            "SELECT {BLOCK_COLUMNS}
241                FROM header AS h
242                JOIN payload AS p ON h.height = p.height
243                WHERE h.height = (
244                    SELECT t1.block_height
245                        FROM transactions AS t1
246                        WHERE t1.block_height = $1
247                        ORDER BY t1.block_height, t1.ns_id, t1.position
248                        OFFSET $2
249                        LIMIT 1
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.height = p.height
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
528                    p.height = h.height
529                WHERE
530                    h.height IN (SELECT height FROM header ORDER BY height DESC LIMIT $1)
531                ORDER BY h.height
532                ",
533            )
534            .bind((EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES + 1) as i64)
535            .fetch(self.as_mut());
536
537            let mut histograms: ExplorerHistograms = histogram_query_result
538                .map(|row_stream| {
539                    row_stream.map(|row| {
540                        let height: i64 = row.try_get("height")?;
541                        let timestamp: i64 = row.try_get("timestamp")?;
542                        let time: Option<i64> = row.try_get("time")?;
543                        let size: Option<i32> = row.try_get("size")?;
544                        let num_transactions: i32 = row.try_get("transactions")?;
545
546                        Ok((height, timestamp, time, size, num_transactions))
547                    })
548                })
549                .try_fold(
550                    ExplorerHistograms {
551                        block_time: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
552                        block_size: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
553                        block_transactions: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
554                        block_heights: VecDeque::with_capacity(EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES),
555                    },
556                    |mut histograms: ExplorerHistograms,
557                     row: sqlx::Result<(i64, i64, Option<i64>, Option<i32>, i32)>| async {
558                        let (height, _timestamp, time, size, num_transactions) = row?;
559
560                        histograms.block_time.push_back(time.map(|i| i as u64));
561                        histograms.block_size.push_back(size.map(|i| i as u64));
562                        histograms.block_transactions.push_back(num_transactions as u64);
563                        histograms.block_heights.push_back(height as u64);
564                        Ok(histograms)
565                    },
566                )
567                .await?;
568
569            while histograms.block_time.len() > EXPLORER_SUMMARY_HISTOGRAM_NUM_ENTRIES {
570                histograms.block_time.pop_front();
571                histograms.block_size.pop_front();
572                histograms.block_transactions.pop_front();
573                histograms.block_heights.pop_front();
574            }
575
576            histograms
577        };
578
579        let genesis_overview = {
580            let blocks = NodeStorage::<Types>::block_height(self).await? as u64;
581            let transactions =
582                NodeStorage::<Types>::count_transactions_in_range(self, .., None).await? as u64;
583            GenesisOverview {
584                rollups: 0,
585                transactions,
586                blocks,
587            }
588        };
589
590        let latest_block: BlockDetail<Types> =
591            self.get_block_detail(BlockIdentifier::Latest).await?;
592
593        let latest_blocks: Vec<BlockSummary<Types>> = self
594            .get_block_summaries(GetBlockSummariesRequest(BlockRange {
595                target: BlockIdentifier::Latest,
596                num_blocks: NonZeroUsize::new(EXPLORER_SUMMARY_NUM_BLOCKS).unwrap(),
597            }))
598            .await?;
599
600        let latest_transactions: Vec<TransactionSummary<Types>> = self
601            .get_transaction_summaries(GetTransactionSummariesRequest {
602                range: TransactionRange {
603                    target: TransactionIdentifier::Latest,
604                    num_transactions: NonZeroUsize::new(EXPLORER_SUMMARY_NUM_TRANSACTIONS).unwrap(),
605                },
606                filter: TransactionSummaryFilter::None,
607            })
608            .await?;
609
610        Ok(ExplorerSummary {
611            genesis_overview,
612            latest_block,
613            latest_transactions,
614            latest_blocks,
615            histograms,
616        })
617    }
618
619    async fn get_search_results(
620        &mut self,
621        search_query: TaggedBase64,
622    ) -> Result<SearchResult<Types>, GetSearchResultsError> {
623        let search_tag = search_query.tag();
624        let header_tag = Commitment::<Header<Types>>::tag();
625        let tx_tag = Commitment::<HotshotTransaction<Types>>::tag();
626
627        if search_tag != header_tag && search_tag != tx_tag {
628            return Err(GetSearchResultsError::InvalidQuery(errors::BadQuery {}));
629        }
630
631        let search_query_string = search_query.to_string();
632        if search_tag == header_tag {
633            let block_query = format!(
634                "SELECT {BLOCK_COLUMNS}
635                    FROM header AS h
636                    JOIN payload AS p ON h.height = p.height
637                    WHERE h.hash = $1
638                    ORDER BY h.height DESC
639                    LIMIT 1"
640            );
641            let row = query(block_query.as_str())
642                .bind(&search_query_string)
643                .fetch_one(self.as_mut())
644                .await?;
645
646            let block = BlockSummary::from_row(&row)?;
647
648            Ok(SearchResult {
649                blocks: vec![block],
650                transactions: Vec::new(),
651            })
652        } else {
653            let transactions_query = format!(
654                "SELECT {BLOCK_COLUMNS}
655                    FROM header AS h
656                    JOIN payload AS p ON h.height = p.height
657                    JOIN transactions AS t ON h.height = t.block_height
658                    WHERE t.hash = $1
659                    ORDER BY h.height DESC
660                    LIMIT 5"
661            );
662            let transactions_query_rows = query(transactions_query.as_str())
663                .bind(&search_query_string)
664                .fetch(self.as_mut());
665            let transactions_query_result: Vec<TransactionSummary<Types>> = transactions_query_rows
666                .map(|row| -> Result<Vec<TransactionSummary<Types>>, QueryError>{
667                    let block = BlockQueryData::<Types>::from_row(&row?)?;
668                    let transactions = block
669                        .enumerate()
670                        .enumerate()
671                        .filter(|(_, (_, txn))| txn.commit().to_string() == search_query_string)
672                        .map(|(offset, (_, txn))| {
673                            Ok(TransactionSummary::try_from((
674                                &block, offset, txn,
675                            ))?)
676                        })
677                        .try_collect::<TransactionSummary<Types>, Vec<TransactionSummary<Types>>, QueryError>()?;
678                    Ok(transactions)
679                })
680                .try_collect::<Vec<Vec<TransactionSummary<Types>>>>()
681                .await?
682                .into_iter()
683                .flatten()
684                .collect();
685
686            Ok(SearchResult {
687                blocks: Vec::new(),
688                transactions: transactions_query_result,
689            })
690        }
691    }
692}