• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tari-project / tari / 17212794510

25 Aug 2025 03:08PM UTC coverage: 60.274% (+0.03%) from 60.24%
17212794510

push

github

web-flow
chore: new release v5.0.0-pre.7 (#7442)

Description
---
new release

71314 of 118316 relevant lines covered (60.27%)

230312.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/base_layer/core/src/base_node/rpc/query_service.rs
1
// Copyright 2025 The Tari Project
2
// SPDX-License-Identifier: BSD-3-Clause
3

4
use std::cmp;
5

6
use log::trace;
7
use serde_valid::{validation, Validate};
8
use tari_common_types::{types, types::FixedHashSizeError};
9
use tari_transaction_components::{
10
    rpc::{
11
        models,
12
        models::{
13
            BlockUtxoInfo,
14
            GetUtxosByBlockRequest,
15
            GetUtxosByBlockResponse,
16
            MinimalUtxoSyncInfo,
17
            SyncUtxosByBlockRequest,
18
            SyncUtxosByBlockResponse,
19
            TipInfoResponse,
20
            TxLocation,
21
            TxQueryResponse,
22
        },
23
    },
24
    transaction_components::TransactionOutput,
25
};
26
use tari_utilities::{hex::Hex, ByteArray, ByteArrayError};
27
use thiserror::Error;
28

29
use crate::{
30
    base_node::{rpc::BaseNodeWalletQueryService, state_machine_service::states::StateInfo, StateMachineHandle},
31
    chain_storage::{async_db::AsyncBlockchainDb, BlockchainBackend, ChainStorageError},
32
    mempool::{service::MempoolHandle, MempoolServiceError, TxStorageResponse},
33
};
34
const LOG_TARGET: &str = "c::bn::rpc::query_service";
35

36
#[derive(Debug, Error)]
37
pub enum Error {
38
    #[error("Failed to get chain metadata: {0}")]
39
    FailedToGetChainMetadata(#[from] ChainStorageError),
40
    #[error("Header not found at height: {height}")]
41
    HeaderNotFound { height: u64 },
42
    #[error("Signature conversion error: {0}")]
43
    SignatureConversion(ByteArrayError),
44
    #[error("Mempool service error: {0}")]
45
    MempoolService(#[from] MempoolServiceError),
46
    #[error("Serde validation error: {0}")]
47
    SerdeValidation(#[from] validation::Errors),
48
    #[error("Hash conversion error: {0}")]
49
    HashConversion(#[from] FixedHashSizeError),
50
    #[error("Start header hash not found")]
51
    StartHeaderHashNotFound,
52
    #[error("End header hash not found")]
53
    EndHeaderHashNotFound,
54
    #[error("Header hash not found")]
55
    HeaderHashNotFound,
56
    #[error("Start header height {start_height} cannot be greater than the end header height {end_height}")]
57
    HeaderHeightMismatch { start_height: u64, end_height: u64 },
58
}
59

60
pub struct Service<B> {
61
    db: AsyncBlockchainDb<B>,
62
    state_machine: StateMachineHandle,
63
    mempool: MempoolHandle,
64
}
65

66
impl<B: BlockchainBackend + 'static> Service<B> {
67
    pub fn new(db: AsyncBlockchainDb<B>, state_machine: StateMachineHandle, mempool: MempoolHandle) -> Self {
×
68
        Self {
×
69
            db,
×
70
            state_machine,
×
71
            mempool,
×
72
        }
×
73
    }
×
74

75
    fn state_machine(&self) -> StateMachineHandle {
×
76
        self.state_machine.clone()
×
77
    }
×
78

79
    fn db(&self) -> &AsyncBlockchainDb<B> {
×
80
        &self.db
×
81
    }
×
82

83
    fn mempool(&self) -> MempoolHandle {
×
84
        self.mempool.clone()
×
85
    }
×
86

87
    async fn fetch_kernel(&self, signature: types::CompressedSignature) -> Result<TxQueryResponse, Error> {
×
88
        let db = self.db();
×
89

×
90
        match db.fetch_kernel_by_excess_sig(signature.clone()).await? {
×
91
            None => (),
×
92
            Some((_, block_hash)) => match db.fetch_header_by_block_hash(block_hash).await? {
×
93
                None => (),
×
94
                Some(header) => {
×
95
                    let response = TxQueryResponse {
×
96
                        location: TxLocation::Mined,
×
97
                        mined_header_hash: Some(block_hash.to_vec()),
×
98
                        mined_height: Some(header.height),
×
99
                        mined_timestamp: Some(header.timestamp.as_u64()),
×
100
                    };
×
101
                    return Ok(response);
×
102
                },
103
            },
104
        };
105

106
        // If not in a block then check the mempool
107
        let mut mempool = self.mempool();
×
108
        let mempool_response = match mempool.get_tx_state_by_excess_sig(signature.clone()).await? {
×
109
            TxStorageResponse::UnconfirmedPool => TxQueryResponse {
×
110
                location: TxLocation::InMempool,
×
111
                mined_header_hash: None,
×
112
                mined_height: None,
×
113
                mined_timestamp: None,
×
114
            },
×
115
            TxStorageResponse::ReorgPool |
116
            TxStorageResponse::NotStoredOrphan |
117
            TxStorageResponse::NotStoredTimeLocked |
118
            TxStorageResponse::NotStoredAlreadySpent |
119
            TxStorageResponse::NotStoredConsensus |
120
            TxStorageResponse::NotStored |
121
            TxStorageResponse::NotStoredFeeTooLow |
122
            TxStorageResponse::NotStoredAlreadyMined => TxQueryResponse {
×
123
                location: TxLocation::NotStored,
×
124
                mined_timestamp: None,
×
125
                mined_height: None,
×
126
                mined_header_hash: None,
×
127
            },
×
128
        };
129

130
        Ok(mempool_response)
×
131
    }
×
132

133
    async fn fetch_utxos_by_block(&self, request: GetUtxosByBlockRequest) -> Result<GetUtxosByBlockResponse, Error> {
×
134
        request.validate()?;
×
135

136
        let hash = request.header_hash.clone().try_into()?;
×
137

138
        let header = self
×
139
            .db()
×
140
            .fetch_header_by_block_hash(hash)
×
141
            .await?
×
142
            .ok_or_else(|| Error::HeaderHashNotFound)?;
×
143

144
        // fetch utxos
145
        let outputs_with_statuses = self.db.fetch_outputs_in_block_with_spend_state(hash, None).await?;
×
146

147
        let outputs = outputs_with_statuses
×
148
            .into_iter()
×
149
            .map(|(output, _spent)| output)
×
150
            .collect::<Vec<TransactionOutput>>();
×
151

×
152
        // if its empty, we need to send an empty vec of outputs.
×
153
        let utxo_block_response = GetUtxosByBlockResponse {
×
154
            outputs,
×
155
            height: header.height,
×
156
            header_hash: hash.to_vec(),
×
157
            mined_timestamp: header.timestamp.as_u64(),
×
158
        };
×
159

×
160
        Ok(utxo_block_response)
×
161
    }
×
162

163
    #[allow(clippy::too_many_lines)]
164
    async fn fetch_utxos(&self, request: SyncUtxosByBlockRequest) -> Result<SyncUtxosByBlockResponse, Error> {
×
165
        // validate and fetch inputs
×
166
        request.validate()?;
×
167

168
        let hash = request.start_header_hash.clone().try_into()?;
×
169

170
        let start_header = self
×
171
            .db()
×
172
            .fetch_header_by_block_hash(hash)
×
173
            .await?
×
174
            .ok_or_else(|| Error::StartHeaderHashNotFound)?;
×
175

176
        let tip_header = self.db.fetch_tip_header().await?;
×
177
        // we only allow wallets to ask for a max of 100 blocks at a time and we want to cache the queries to ensure
178
        // they are in batch of 100 and we want to ensure they request goes to the nearest 100 block height so
179
        // we can cache all wallet's queries
180
        let increase = ((start_header.height + 100) / 100) * 100;
×
181
        let end_height = cmp::min(tip_header.header().height, increase);
×
182

×
183
        // pagination
×
184
        let start_header_height = start_header.height + (request.page * request.limit);
×
185
        let start_header = self
×
186
            .db
×
187
            .fetch_header(start_header_height)
×
188
            .await?
×
189
            .ok_or_else(|| Error::HeaderNotFound {
×
190
                height: start_header_height,
×
191
            })?;
×
192

193
        if start_header.height > tip_header.header().height {
×
194
            return Err(Error::HeaderHeightMismatch {
×
195
                start_height: start_header.height,
×
196
                end_height: tip_header.header().height,
×
197
            });
×
198
        }
×
199

×
200
        // fetch utxos
×
201
        let mut utxos = vec![];
×
202
        let mut current_header = start_header;
×
203
        let mut fetched_utxos = 0;
×
204
        let next_header_to_request;
205
        loop {
206
            let current_header_hash = current_header.hash();
×
207

×
208
            trace!(
×
209
                target: LOG_TARGET,
×
210
                "current header = {} ({})",
×
211
                current_header.height,
×
212
                current_header_hash.to_hex()
×
213
            );
214

215
            let outputs_with_statuses = self
×
216
                .db
×
217
                .fetch_outputs_in_block_with_spend_state(current_header.hash(), None)
×
218
                .await?;
×
219
            let mut inputs = self
×
220
                .db
×
221
                .fetch_inputs_in_block(current_header.hash())
×
222
                .await?
×
223
                .into_iter()
×
224
                .map(|input| input.output_hash().to_vec())
×
225
                .collect::<Vec<Vec<u8>>>();
×
226

×
227
            let outputs = outputs_with_statuses
×
228
                .into_iter()
×
229
                .map(|(output, _spent)| output)
×
230
                .collect::<Vec<TransactionOutput>>();
×
231

232
            for output_chunk in outputs.chunks(2000) {
×
233
                let inputs_to_send = if inputs.is_empty() {
×
234
                    Vec::new()
×
235
                } else {
236
                    let num_to_drain = inputs.len().min(2000);
×
237
                    inputs.drain(..num_to_drain).collect()
×
238
                };
239

240
                let output_block_response = BlockUtxoInfo {
×
241
                    outputs: output_chunk
×
242
                        .iter()
×
243
                        .map(|output| MinimalUtxoSyncInfo {
×
244
                            output_hash: output.hash().to_vec(),
×
245
                            commitment: output.commitment().to_vec(),
×
246
                            encrypted_data: output.encrypted_data().as_bytes().to_vec(),
×
247
                            sender_offset_public_key: output.sender_offset_public_key.to_vec(),
×
248
                        })
×
249
                        .collect(),
×
250
                    inputs: inputs_to_send,
×
251
                    height: current_header.height,
×
252
                    header_hash: current_header_hash.to_vec(),
×
253
                    mined_timestamp: current_header.timestamp.as_u64(),
×
254
                };
×
255
                utxos.push(output_block_response);
×
256
            }
×
257
            // We might still have inputs left to send if they are more than the outputs
258
            for input_chunk in inputs.chunks(2000) {
×
259
                let output_block_response = BlockUtxoInfo {
×
260
                    outputs: Vec::new(),
×
261
                    inputs: input_chunk.to_vec(),
×
262
                    height: current_header.height,
×
263
                    header_hash: current_header_hash.to_vec(),
×
264
                    mined_timestamp: current_header.timestamp.as_u64(),
×
265
                };
×
266
                utxos.push(output_block_response);
×
267
            }
×
268

269
            fetched_utxos += 1;
×
270

×
271
            if current_header.height >= tip_header.header().height {
×
272
                next_header_to_request = vec![];
×
273
                break;
×
274
            }
×
275
            if fetched_utxos >= request.limit {
×
276
                next_header_to_request = current_header.hash().to_vec();
×
277
                break;
×
278
            }
×
279

280
            current_header =
×
281
                self.db
×
282
                    .fetch_header(current_header.height + 1)
×
283
                    .await?
×
284
                    .ok_or_else(|| Error::HeaderNotFound {
×
285
                        height: current_header.height + 1,
×
286
                    })?;
×
287
            if current_header.height == end_height {
×
288
                next_header_to_request = current_header.hash().to_vec();
×
289
                break; // Stop if we reach the end height}
×
290
            }
×
291
        }
292

293
        let has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
×
294

×
295
        Ok(SyncUtxosByBlockResponse {
×
296
            blocks: utxos,
×
297
            has_next_page,
×
298
            next_header_to_scan: next_header_to_request,
×
299
        })
×
300
    }
×
301
}
302

303
#[async_trait::async_trait]
304
impl<B: BlockchainBackend + 'static> BaseNodeWalletQueryService for Service<B> {
305
    type Error = Error;
306

307
    async fn get_tip_info(&self) -> Result<TipInfoResponse, Self::Error> {
×
308
        let state_machine = self.state_machine();
×
309
        let status_watch = state_machine.get_status_info_watch();
×
310
        let is_synced = match status_watch.borrow().state_info {
×
311
            StateInfo::Listening(li) => li.is_synced(),
×
312
            _ => false,
×
313
        };
314

315
        let metadata = self.db.get_chain_metadata().await?;
×
316

317
        Ok(TipInfoResponse {
×
318
            metadata: Some(metadata),
×
319
            is_synced,
×
320
        })
×
321
    }
×
322

323
    async fn get_header_by_height(&self, height: u64) -> Result<models::BlockHeader, Self::Error> {
×
324
        let result = self
×
325
            .db
×
326
            .fetch_header(height)
×
327
            .await?
×
328
            .ok_or(Error::HeaderNotFound { height })?
×
329
            .into();
×
330
        Ok(result)
×
331
    }
×
332

333
    async fn get_height_at_time(&self, epoch_time: u64) -> Result<u64, Self::Error> {
×
334
        trace!(target: LOG_TARGET, "requested_epoch_time: {}", epoch_time);
×
335
        let tip_header = self.db.fetch_tip_header().await?;
×
336

337
        let mut left_height = 0u64;
×
338
        let mut right_height = tip_header.height();
×
339

340
        while left_height <= right_height {
×
341
            let mut mid_height = (left_height + right_height) / 2;
×
342

×
343
            if mid_height == 0 {
×
344
                return Ok(0u64);
×
345
            }
×
346
            // If the two bounds are adjacent then perform the test between the right and left sides
×
347
            if left_height == mid_height {
×
348
                mid_height = right_height;
×
349
            }
×
350

351
            let mid_header = self
×
352
                .db
×
353
                .fetch_header(mid_height)
×
354
                .await?
×
355
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height })?;
×
356
            let before_mid_header = self
×
357
                .db
×
358
                .fetch_header(mid_height - 1)
×
359
                .await?
×
360
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height - 1 })?;
×
361
            trace!(
×
362
                target: LOG_TARGET,
×
363
                "requested_epoch_time: {}, left: {}, mid: {}/{} ({}/{}), right: {}",
×
364
                epoch_time,
×
365
                left_height,
×
366
                mid_height,
×
367
                mid_height-1,
×
368
                mid_header.timestamp.as_u64(),
×
369
                before_mid_header.timestamp.as_u64(),
×
370
                right_height
371
            );
372
            if epoch_time < mid_header.timestamp.as_u64() && epoch_time >= before_mid_header.timestamp.as_u64() {
×
373
                trace!(
×
374
                    target: LOG_TARGET,
×
375
                    "requested_epoch_time: {}, selected height: {}",
×
376
                    epoch_time, before_mid_header.height
377
                );
378
                return Ok(before_mid_header.height);
×
379
            } else if mid_height == right_height {
×
380
                trace!(
×
381
                    target: LOG_TARGET,
×
382
                    "requested_epoch_time: {epoch_time}, selected height: {right_height}"
×
383
                );
384
                return Ok(right_height);
×
385
            } else if epoch_time <= mid_header.timestamp.as_u64() {
×
386
                right_height = mid_height;
×
387
            } else {
×
388
                left_height = mid_height;
×
389
            }
×
390
        }
391

392
        Ok(0u64)
×
393
    }
×
394

395
    async fn transaction_query(
396
        &self,
397
        signature: crate::base_node::rpc::models::Signature,
398
    ) -> Result<TxQueryResponse, Self::Error> {
×
399
        let signature = signature.try_into().map_err(Error::SignatureConversion)?;
×
400

401
        let response = self.fetch_kernel(signature).await?;
×
402

403
        Ok(response)
×
404
    }
×
405

406
    async fn sync_utxos_by_block(
407
        &self,
408
        request: SyncUtxosByBlockRequest,
409
    ) -> Result<SyncUtxosByBlockResponse, Self::Error> {
×
410
        self.fetch_utxos(request).await
×
411
    }
×
412

413
    async fn get_utxos_by_block(
414
        &self,
415
        request: GetUtxosByBlockRequest,
416
    ) -> Result<GetUtxosByBlockResponse, Self::Error> {
×
417
        self.fetch_utxos_by_block(request).await
×
418
    }
×
419

420
    async fn get_utxos_mined_info(
421
        &self,
422
        request: models::GetUtxosMinedInfoRequest,
423
    ) -> Result<models::GetUtxosMinedInfoResponse, Self::Error> {
×
424
        request.validate()?;
×
425

426
        let mut utxos = vec![];
×
427

428
        let tip_header = self.db().fetch_tip_header().await?;
×
429
        for hash in request.hashes {
×
430
            let hash = hash.try_into()?;
×
431
            let output = self.db().fetch_output(hash).await?;
×
432
            if let Some(output) = output {
×
433
                utxos.push(models::MinedUtxoInfo {
×
434
                    utxo_hash: hash.to_vec(),
×
435
                    mined_in_hash: output.header_hash.to_vec(),
×
436
                    mined_in_height: output.mined_height,
×
437
                    mined_in_timestamp: output.mined_timestamp,
×
438
                });
×
439
            }
×
440
        }
441

442
        Ok(models::GetUtxosMinedInfoResponse {
×
443
            utxos,
×
444
            best_block_hash: tip_header.hash().to_vec(),
×
445
            best_block_height: tip_header.height(),
×
446
        })
×
447
    }
×
448

449
    async fn get_utxos_deleted_info(
450
        &self,
451
        request: models::GetUtxosDeletedInfoRequest,
452
    ) -> Result<models::GetUtxosDeletedInfoResponse, Self::Error> {
×
453
        request.validate()?;
×
454

455
        let mut utxos = vec![];
×
456

457
        let must_include_header = request.must_include_header.clone().try_into()?;
×
458
        if self
×
459
            .db()
×
460
            .fetch_header_by_block_hash(must_include_header)
×
461
            .await?
×
462
            .is_none()
×
463
        {
464
            return Err(Error::HeaderHashNotFound);
×
465
        }
×
466

467
        let tip_header = self.db().fetch_tip_header().await?;
×
468
        for hash in request.hashes {
×
469
            let hash = hash.try_into()?;
×
470
            let output = self.db().fetch_output(hash).await?;
×
471

472
            if let Some(output) = output {
×
473
                // is it still unspent?
474
                let input = self.db().fetch_input(hash).await?;
×
475
                if let Some(i) = input {
×
476
                    utxos.push(models::DeletedUtxoInfo {
×
477
                        utxo_hash: hash.to_vec(),
×
478
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
479
                        spent_in_header: Some((i.spent_height, i.header_hash.to_vec())),
×
480
                    });
×
481
                } else {
×
482
                    utxos.push(models::DeletedUtxoInfo {
×
483
                        utxo_hash: hash.to_vec(),
×
484
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
485
                        spent_in_header: None,
×
486
                    });
×
487
                }
×
488
            } else {
×
489
                utxos.push(models::DeletedUtxoInfo {
×
490
                    utxo_hash: hash.to_vec(),
×
491
                    found_in_header: None,
×
492
                    spent_in_header: None,
×
493
                });
×
494
            }
×
495
        }
496

497
        Ok(models::GetUtxosDeletedInfoResponse {
×
498
            utxos,
×
499
            best_block_hash: tip_header.hash().to_vec(),
×
500
            best_block_height: tip_header.height(),
×
501
        })
×
502
    }
×
503
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc