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

tari-project / tari / 19920181775

04 Dec 2025 06:43AM UTC coverage: 60.517% (-0.3%) from 60.819%
19920181775

push

github

web-flow
feat: improve scanning feedback (#7622)

Description
---
Improve the scanning feddback

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Chores**
* Enhanced state inspection and logging for UTXO processing in wallet
server operations, including mined and deletion status tracking.
* Added Display formatting for transaction types to support improved
debugging and logging output.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

0 of 26 new or added lines in 1 file covered. (0.0%)

532 existing lines in 21 files now uncovered.

70369 of 116280 relevant lines covered (60.52%)

299331.58 hits per line

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

18.47
/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::{
9
    types,
10
    types::{FixedHash, FixedHashSizeError},
11
};
12
use tari_transaction_components::{
13
    rpc::{
14
        models,
15
        models::{
16
            BlockUtxoInfo,
17
            GenerateKernelMerkleProofResponse,
18
            GetUtxosByBlockRequest,
19
            GetUtxosByBlockResponse,
20
            MinimalUtxoSyncInfo,
21
            SyncUtxosByBlockRequest,
22
            SyncUtxosByBlockResponseV0,
23
            SyncUtxosByBlockResponseV1,
24
            TipInfoResponse,
25
            TxLocation,
26
            TxQueryResponse,
27
        },
28
    },
29
    transaction_components::TransactionOutput,
30
};
31
use tari_utilities::{hex::Hex, ByteArray, ByteArrayError};
32
use thiserror::Error;
33

34
use crate::{
35
    base_node::{rpc::BaseNodeWalletQueryService, state_machine_service::states::StateInfo, StateMachineHandle},
36
    chain_storage::{async_db::AsyncBlockchainDb, BlockchainBackend, ChainStorageError},
37
    mempool::{service::MempoolHandle, MempoolServiceError, TxStorageResponse},
38
};
39

40
const LOG_TARGET: &str = "c::bn::rpc::query_service";
41
const SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT: u64 = 1000;
42

43
#[derive(Debug, Error)]
44
pub enum Error {
45
    #[error("Failed to get chain metadata: {0}")]
46
    FailedToGetChainMetadata(#[from] ChainStorageError),
47
    #[error("Header not found at height: {height}")]
48
    HeaderNotFound { height: u64 },
49
    #[error("Signature conversion error: {0}")]
50
    SignatureConversion(ByteArrayError),
51
    #[error("Mempool service error: {0}")]
52
    MempoolService(#[from] MempoolServiceError),
53
    #[error("Serde validation error: {0}")]
54
    SerdeValidation(#[from] validation::Errors),
55
    #[error("Hash conversion error: {0}")]
56
    HashConversion(#[from] FixedHashSizeError),
57
    #[error("Start header hash not found")]
58
    StartHeaderHashNotFound,
59
    #[error("End header hash not found")]
60
    EndHeaderHashNotFound,
61
    #[error("Header hash not found")]
62
    HeaderHashNotFound,
63
    #[error("Start header height {start_height} cannot be greater than the end header height {end_height}")]
64
    HeaderHeightMismatch { start_height: u64, end_height: u64 },
65
    #[error("Output not found")]
66
    OutputNotFound,
67
    #[error("A general error occurred: {0}")]
68
    General(anyhow::Error),
69
}
70

71
impl Error {
72
    fn general(err: impl Into<anyhow::Error>) -> Self {
×
73
        Error::General(err.into())
×
UNCOV
74
    }
×
75
}
76

77
pub struct Service<B> {
78
    db: AsyncBlockchainDb<B>,
79
    state_machine: StateMachineHandle,
80
    mempool: MempoolHandle,
81
}
82

83
impl<B: BlockchainBackend + 'static> Service<B> {
84
    pub fn new(db: AsyncBlockchainDb<B>, state_machine: StateMachineHandle, mempool: MempoolHandle) -> Self {
2✔
85
        Self {
2✔
86
            db,
2✔
87
            state_machine,
2✔
88
            mempool,
2✔
89
        }
2✔
90
    }
2✔
91

92
    fn state_machine(&self) -> StateMachineHandle {
×
93
        self.state_machine.clone()
×
UNCOV
94
    }
×
95

96
    fn db(&self) -> &AsyncBlockchainDb<B> {
3✔
97
        &self.db
3✔
98
    }
3✔
99

100
    fn mempool(&self) -> MempoolHandle {
×
101
        self.mempool.clone()
×
UNCOV
102
    }
×
103

104
    async fn fetch_kernel(&self, signature: types::CompressedSignature) -> Result<TxQueryResponse, Error> {
×
UNCOV
105
        let db = self.db();
×
106

107
        match db.fetch_kernel_by_excess_sig(signature.clone()).await? {
×
108
            None => (),
×
109
            Some((_, block_hash)) => match db.fetch_header_by_block_hash(block_hash).await? {
×
110
                None => (),
×
111
                Some(header) => {
×
112
                    let response = TxQueryResponse {
×
113
                        location: TxLocation::Mined,
×
114
                        mined_header_hash: Some(block_hash.to_vec()),
×
115
                        mined_height: Some(header.height),
×
116
                        mined_timestamp: Some(header.timestamp.as_u64()),
×
117
                    };
×
UNCOV
118
                    return Ok(response);
×
119
                },
120
            },
121
        };
122

123
        // If not in a block then check the mempool
124
        let mut mempool = self.mempool();
×
125
        let mempool_response = match mempool.get_tx_state_by_excess_sig(signature.clone()).await? {
×
126
            TxStorageResponse::UnconfirmedPool => TxQueryResponse {
×
127
                location: TxLocation::InMempool,
×
128
                mined_header_hash: None,
×
129
                mined_height: None,
×
130
                mined_timestamp: None,
×
UNCOV
131
            },
×
132
            TxStorageResponse::ReorgPool |
133
            TxStorageResponse::NotStoredOrphan |
134
            TxStorageResponse::NotStoredTimeLocked |
135
            TxStorageResponse::NotStoredAlreadySpent |
136
            TxStorageResponse::NotStoredConsensus |
137
            TxStorageResponse::NotStored |
138
            TxStorageResponse::NotStoredFeeTooLow |
139
            TxStorageResponse::NotStoredAlreadyMined => TxQueryResponse {
×
140
                location: TxLocation::NotStored,
×
141
                mined_timestamp: None,
×
142
                mined_height: None,
×
143
                mined_header_hash: None,
×
UNCOV
144
            },
×
145
        };
146

147
        Ok(mempool_response)
×
UNCOV
148
    }
×
149

150
    async fn fetch_utxos_by_block(&self, request: GetUtxosByBlockRequest) -> Result<GetUtxosByBlockResponse, Error> {
×
UNCOV
151
        request.validate()?;
×
152

UNCOV
153
        let hash = request.header_hash.clone().try_into()?;
×
154

155
        let header = self
×
156
            .db()
×
157
            .fetch_header_by_block_hash(hash)
×
158
            .await?
×
UNCOV
159
            .ok_or_else(|| Error::HeaderHashNotFound)?;
×
160

161
        // fetch utxos
UNCOV
162
        let outputs_with_statuses = self.db.fetch_outputs_in_block_with_spend_state(hash, None).await?;
×
163

164
        let outputs = outputs_with_statuses
×
165
            .into_iter()
×
166
            .map(|(output, _spent)| output)
×
UNCOV
167
            .collect::<Vec<TransactionOutput>>();
×
168

169
        // if its empty, we need to send an empty vec of outputs.
170
        let utxo_block_response = GetUtxosByBlockResponse {
×
171
            outputs,
×
172
            height: header.height,
×
173
            header_hash: hash.to_vec(),
×
174
            mined_timestamp: header.timestamp.as_u64(),
×
UNCOV
175
        };
×
176

177
        Ok(utxo_block_response)
×
UNCOV
178
    }
×
179

180
    #[allow(clippy::too_many_lines)]
181
    async fn fetch_utxos(&self, request: SyncUtxosByBlockRequest) -> Result<SyncUtxosByBlockResponseV0, Error> {
2✔
182
        // validate and fetch inputs
183
        request.validate()?;
2✔
184

185
        let hash = request.start_header_hash.clone().try_into()?;
2✔
186
        let start_header = self
2✔
187
            .db()
2✔
188
            .fetch_header_by_block_hash(hash)
2✔
189
            .await?
2✔
190
            .ok_or_else(|| Error::StartHeaderHashNotFound)?;
2✔
191

192
        let tip_header = self.db.fetch_tip_header().await?;
1✔
193
        // we only allow wallets to ask for a max of 100 blocks at a time and we want to cache the queries to ensure
194
        // they are in batch of 100 and we want to ensure they request goes to the nearest 100 block height so
195
        // we can cache all wallet's queries
196
        let increase = ((start_header.height + 100) / 100) * 100;
1✔
197
        let end_height = cmp::min(tip_header.header().height, increase);
1✔
198

199
        // pagination
200
        let start_header_height = start_header.height + (request.page * request.limit);
1✔
201
        if start_header_height > tip_header.header().height {
1✔
202
            return Err(Error::HeaderHeightMismatch {
1✔
203
                start_height: start_header.height,
1✔
204
                end_height: tip_header.header().height,
1✔
205
            });
1✔
206
        }
×
207
        let start_header = self
×
208
            .db
×
209
            .fetch_header(start_header_height)
×
210
            .await?
×
211
            .ok_or_else(|| Error::HeaderNotFound {
×
212
                height: start_header_height,
×
UNCOV
213
            })?;
×
214
        // fetch utxos
215
        let mut utxos = vec![];
×
216
        let mut current_header = start_header;
×
217
        let mut fetched_chunks = 0;
×
218
        let spending_end_header_hash = self
×
219
            .db
×
220
            .fetch_header(
×
221
                tip_header
×
222
                    .header()
×
223
                    .height
×
224
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
×
225
            )
×
226
            .await?
×
227
            .ok_or_else(|| Error::HeaderNotFound {
×
228
                height: tip_header
×
229
                    .header()
×
230
                    .height
×
231
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
×
232
            })?
×
UNCOV
233
            .hash();
×
234
        let next_header_to_request;
UNCOV
235
        let mut has_next_page = false;
×
236
        loop {
237
            let current_header_hash = current_header.hash();
×
238
            trace!(
×
239
                target: LOG_TARGET,
×
UNCOV
240
                "current header = {} ({})",
×
241
                current_header.height,
UNCOV
242
                current_header_hash.to_hex()
×
243
            );
244
            let outputs = if request.exclude_spent {
×
245
                self.db
×
246
                    .fetch_outputs_in_block_with_spend_state(current_header_hash, Some(spending_end_header_hash))
×
247
                    .await?
×
248
                    .into_iter()
×
249
                    .filter(|(_, spent)| !spent)
×
250
                    .map(|(output, _spent)| output)
×
UNCOV
251
                    .collect::<Vec<TransactionOutput>>()
×
252
            } else {
253
                self.db
×
254
                    .fetch_outputs_in_block_with_spend_state(current_header_hash, None)
×
255
                    .await?
×
256
                    .into_iter()
×
257
                    .map(|(output, _spent)| output)
×
UNCOV
258
                    .collect::<Vec<TransactionOutput>>()
×
259
            };
260
            let mut inputs = self
×
261
                .db
×
262
                .fetch_inputs_in_block(current_header_hash)
×
263
                .await?
×
264
                .into_iter()
×
265
                .map(|input| input.output_hash())
×
266
                .collect::<Vec<FixedHash>>();
×
267
            for output_chunk in outputs.chunks(2000) {
×
268
                let inputs_to_send = if inputs.is_empty() {
×
UNCOV
269
                    Vec::new()
×
270
                } else {
271
                    let num_to_drain = inputs.len().min(2000);
×
UNCOV
272
                    inputs.drain(..num_to_drain).map(|h| h.to_vec()).collect()
×
273
                };
274

275
                let output_block_response = BlockUtxoInfo {
×
276
                    outputs: output_chunk
×
277
                        .iter()
×
278
                        .map(|output| MinimalUtxoSyncInfo {
×
279
                            output_hash: output.hash().to_vec(),
×
280
                            commitment: output.commitment().to_vec(),
×
281
                            encrypted_data: output.encrypted_data().as_bytes().to_vec(),
×
282
                            sender_offset_public_key: output.sender_offset_public_key.to_vec(),
×
283
                        })
×
284
                        .collect(),
×
285
                    inputs: inputs_to_send,
×
286
                    height: current_header.height,
×
287
                    header_hash: current_header_hash.to_vec(),
×
UNCOV
288
                    mined_timestamp: current_header.timestamp.as_u64(),
×
289
                };
290
                utxos.push(output_block_response);
×
UNCOV
291
                fetched_chunks += 1;
×
292
            }
293
            // We might still have inputs left to send if they are more than the outputs
294
            for input_chunk in inputs.chunks(2000) {
×
295
                let output_block_response = BlockUtxoInfo {
×
296
                    outputs: Vec::new(),
×
297
                    inputs: input_chunk.iter().map(|h| h.to_vec()).collect::<Vec<_>>().to_vec(),
×
298
                    height: current_header.height,
×
299
                    header_hash: current_header_hash.to_vec(),
×
UNCOV
300
                    mined_timestamp: current_header.timestamp.as_u64(),
×
301
                };
302
                utxos.push(output_block_response);
×
UNCOV
303
                fetched_chunks += 1;
×
304
            }
305

306
            if current_header.height >= tip_header.header().height {
×
307
                next_header_to_request = vec![];
×
308
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
×
309
                break;
×
310
            }
×
311
            if fetched_chunks > request.limit {
×
UNCOV
312
                next_header_to_request = current_header_hash.to_vec();
×
313
                // This is a special edge case, our request has reached the page limit, but we are also not done with
314
                // the block. We also dont want to split up the block over two requests. So we need to ensure that we
315
                // remove the partial block we added so that it can be requested fully in the next request. We also dont
316
                // want to get in a loop where the block cannot fit into the page limit, so if the block is the same as
317
                // the first one, we just send it as is, partial. If not we remove it and let it be sent in the next
318
                // request.
UNCOV
319
                if utxos.first().ok_or(Error::General(anyhow::anyhow!("No utxos founds")))? // should never happen as we always add at least one block
×
320
                    .header_hash ==
UNCOV
321
                    current_header_hash.to_vec()
×
322
                {
323
                    // special edge case where the first block is also the last block we can send, so we just send it as
324
                    // is, partial
325
                    break;
×
326
                }
×
327
                while !utxos.is_empty() &&
×
UNCOV
328
                    utxos.last().ok_or(Error::General(anyhow::anyhow!("No utxos found")))? // should never happen as we always add at least one block
×
329
                    .header_hash ==
330
                        current_header_hash.to_vec()
×
331
                {
×
332
                    utxos.pop();
×
333
                }
×
334
                break;
×
UNCOV
335
            }
×
336

337
            current_header =
×
338
                self.db
×
339
                    .fetch_header(current_header.height + 1)
×
340
                    .await?
×
341
                    .ok_or_else(|| Error::HeaderNotFound {
×
342
                        height: current_header.height + 1,
×
343
                    })?;
×
344
            if current_header.height == end_height {
×
345
                next_header_to_request = current_header.hash().to_vec();
×
346
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
×
347
                break; // Stop if we reach the end height
×
UNCOV
348
            }
×
349
        }
350

351
        Ok(SyncUtxosByBlockResponseV0 {
×
352
            blocks: utxos,
×
353
            has_next_page,
×
354
            next_header_to_scan: next_header_to_request,
×
UNCOV
355
        })
×
356
    }
2✔
357
}
358

359
#[async_trait::async_trait]
360
impl<B: BlockchainBackend + 'static> BaseNodeWalletQueryService for Service<B> {
361
    type Error = Error;
362

363
    async fn get_tip_info(&self) -> Result<TipInfoResponse, Self::Error> {
×
364
        let state_machine = self.state_machine();
×
365
        let status_watch = state_machine.get_status_info_watch();
×
366
        let is_synced = match status_watch.borrow().state_info {
×
367
            StateInfo::Listening(li) => li.is_synced(),
×
UNCOV
368
            _ => false,
×
369
        };
370

UNCOV
371
        let metadata = self.db.get_chain_metadata().await?;
×
372

373
        Ok(TipInfoResponse {
×
374
            metadata: Some(metadata),
×
375
            is_synced,
×
376
        })
×
UNCOV
377
    }
×
378

379
    async fn get_header_by_height(&self, height: u64) -> Result<models::BlockHeader, Self::Error> {
×
380
        let result = self
×
381
            .db
×
382
            .fetch_header(height)
×
383
            .await?
×
384
            .ok_or(Error::HeaderNotFound { height })?
×
385
            .into();
×
386
        Ok(result)
×
UNCOV
387
    }
×
388

389
    async fn get_height_at_time(&self, epoch_time: u64) -> Result<u64, Self::Error> {
×
390
        trace!(target: LOG_TARGET, "requested_epoch_time: {}", epoch_time);
×
UNCOV
391
        let tip_header = self.db.fetch_tip_header().await?;
×
392

393
        let mut left_height = 0u64;
×
UNCOV
394
        let mut right_height = tip_header.height();
×
395

396
        while left_height <= right_height {
×
UNCOV
397
            let mut mid_height = (left_height + right_height) / 2;
×
398

399
            if mid_height == 0 {
×
400
                return Ok(0u64);
×
UNCOV
401
            }
×
402
            // If the two bounds are adjacent then perform the test between the right and left sides
403
            if left_height == mid_height {
×
404
                mid_height = right_height;
×
UNCOV
405
            }
×
406

407
            let mid_header = self
×
408
                .db
×
409
                .fetch_header(mid_height)
×
410
                .await?
×
411
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height })?;
×
412
            let before_mid_header = self
×
413
                .db
×
414
                .fetch_header(mid_height - 1)
×
415
                .await?
×
416
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height - 1 })?;
×
417
            trace!(
×
418
                target: LOG_TARGET,
×
UNCOV
419
                "requested_epoch_time: {}, left: {}, mid: {}/{} ({}/{}), right: {}",
×
420
                epoch_time,
421
                left_height,
422
                mid_height,
423
                mid_height-1,
×
424
                mid_header.timestamp.as_u64(),
×
UNCOV
425
                before_mid_header.timestamp.as_u64(),
×
426
                right_height
427
            );
428
            if epoch_time < mid_header.timestamp.as_u64() && epoch_time >= before_mid_header.timestamp.as_u64() {
×
429
                trace!(
×
430
                    target: LOG_TARGET,
×
UNCOV
431
                    "requested_epoch_time: {}, selected height: {}",
×
432
                    epoch_time, before_mid_header.height
433
                );
434
                return Ok(before_mid_header.height);
×
435
            } else if mid_height == right_height {
×
436
                trace!(
×
437
                    target: LOG_TARGET,
×
UNCOV
438
                    "requested_epoch_time: {epoch_time}, selected height: {right_height}"
×
439
                );
440
                return Ok(right_height);
×
441
            } else if epoch_time <= mid_header.timestamp.as_u64() {
×
442
                right_height = mid_height;
×
443
            } else {
×
444
                left_height = mid_height;
×
UNCOV
445
            }
×
446
        }
447

448
        Ok(0u64)
×
UNCOV
449
    }
×
450

451
    async fn transaction_query(
452
        &self,
453
        signature: crate::base_node::rpc::models::Signature,
454
    ) -> Result<TxQueryResponse, Self::Error> {
×
UNCOV
455
        let signature = signature.try_into().map_err(Error::SignatureConversion)?;
×
456

UNCOV
457
        let response = self.fetch_kernel(signature).await?;
×
458

459
        Ok(response)
×
UNCOV
460
    }
×
461

462
    async fn sync_utxos_by_block_v0(
463
        &self,
464
        request: SyncUtxosByBlockRequest,
465
    ) -> Result<SyncUtxosByBlockResponseV0, Self::Error> {
×
466
        self.fetch_utxos(request).await
×
UNCOV
467
    }
×
468

469
    async fn sync_utxos_by_block_v1(
470
        &self,
471
        request: SyncUtxosByBlockRequest,
472
    ) -> Result<SyncUtxosByBlockResponseV1, Self::Error> {
×
473
        let v1 = self.fetch_utxos(request).await?;
×
UNCOV
474
        Ok(v1.into())
×
UNCOV
475
    }
×
476

477
    async fn get_utxos_by_block(
478
        &self,
479
        request: GetUtxosByBlockRequest,
UNCOV
480
    ) -> Result<GetUtxosByBlockResponse, Self::Error> {
×
481
        self.fetch_utxos_by_block(request).await
×
UNCOV
482
    }
×
483

484
    async fn get_utxos_mined_info(
485
        &self,
486
        request: models::GetUtxosMinedInfoRequest,
487
    ) -> Result<models::GetUtxosMinedInfoResponse, Self::Error> {
×
488
        request.validate()?;
×
489

490
        let mut utxos = vec![];
×
491

492
        let tip_header = self.db().fetch_tip_header().await?;
×
493
        for hash in request.hashes {
×
494
            let hash = hash.try_into()?;
×
UNCOV
495
            let output = self.db().fetch_output(hash).await?;
×
UNCOV
496
            if let Some(output) = output {
×
497
                utxos.push(models::MinedUtxoInfo {
×
498
                    utxo_hash: hash.to_vec(),
×
499
                    mined_in_hash: output.header_hash.to_vec(),
×
500
                    mined_in_height: output.mined_height,
×
501
                    mined_in_timestamp: output.mined_timestamp,
×
502
                });
×
UNCOV
503
            }
×
504
        }
505

UNCOV
506
        Ok(models::GetUtxosMinedInfoResponse {
×
507
            utxos,
×
508
            best_block_hash: tip_header.hash().to_vec(),
×
UNCOV
509
            best_block_height: tip_header.height(),
×
510
        })
×
UNCOV
511
    }
×
512

513
    async fn get_utxos_deleted_info(
514
        &self,
515
        request: models::GetUtxosDeletedInfoRequest,
516
    ) -> Result<models::GetUtxosDeletedInfoResponse, Self::Error> {
×
517
        request.validate()?;
×
518

519
        let mut utxos = vec![];
×
520

UNCOV
521
        let must_include_header = request.must_include_header.clone().try_into()?;
×
522
        if self
×
523
            .db()
×
524
            .fetch_header_by_block_hash(must_include_header)
×
525
            .await?
×
UNCOV
526
            .is_none()
×
527
        {
UNCOV
528
            return Err(Error::HeaderHashNotFound);
×
529
        }
×
530

531
        let tip_header = self.db().fetch_tip_header().await?;
×
532
        for hash in request.hashes {
×
533
            let hash = hash.try_into()?;
×
534
            let output = self.db().fetch_output(hash).await?;
×
535

536
            if let Some(output) = output {
×
537
                // is it still unspent?
538
                let input = self.db().fetch_input(hash).await?;
×
539
                if let Some(i) = input {
×
540
                    utxos.push(models::DeletedUtxoInfo {
×
541
                        utxo_hash: hash.to_vec(),
×
542
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
543
                        spent_in_header: Some((i.spent_height, i.header_hash.to_vec())),
×
544
                    });
×
545
                } else {
×
546
                    utxos.push(models::DeletedUtxoInfo {
×
547
                        utxo_hash: hash.to_vec(),
×
548
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
549
                        spent_in_header: None,
×
UNCOV
550
                    });
×
UNCOV
551
                }
×
552
            } else {
×
553
                utxos.push(models::DeletedUtxoInfo {
×
554
                    utxo_hash: hash.to_vec(),
×
555
                    found_in_header: None,
×
556
                    spent_in_header: None,
×
557
                });
×
UNCOV
558
            }
×
559
        }
560

UNCOV
561
        Ok(models::GetUtxosDeletedInfoResponse {
×
562
            utxos,
×
563
            best_block_hash: tip_header.hash().to_vec(),
×
UNCOV
564
            best_block_height: tip_header.height(),
×
565
        })
×
566
    }
×
567

568
    async fn generate_kernel_merkle_proof(
569
        &self,
570
        excess_sig: types::CompressedSignature,
571
    ) -> Result<GenerateKernelMerkleProofResponse, Self::Error> {
×
572
        let proof = self.db().generate_kernel_merkle_proof(excess_sig).await?;
×
573
        Ok(GenerateKernelMerkleProofResponse {
574
            encoded_merkle_proof: bincode::serialize(&proof.merkle_proof).map_err(Error::general)?,
×
575
            block_hash: proof.block_hash,
×
576
            leaf_index: proof.leaf_index.value() as u64,
×
577
        })
578
    }
×
579

UNCOV
580
    async fn get_utxo(&self, request: models::GetUtxoRequest) -> Result<Option<TransactionOutput>, Self::Error> {
×
UNCOV
581
        let hash: FixedHash = request.output_hash.try_into().map_err(Error::general)?;
×
UNCOV
582
        let outputs = self.db().fetch_outputs_with_spend_status_at_tip(vec![hash]).await?;
×
UNCOV
583
        let output = match outputs.first() {
×
UNCOV
584
            Some(Some((output, _spent))) => Some(output.clone()),
×
UNCOV
585
            _ => return Err(Error::OutputNotFound),
×
586
        };
UNCOV
587
        Ok(output)
×
UNCOV
588
    }
×
589
}
590

591
#[cfg(test)]
592
mod tests {
593
    use tari_common::configuration::Network;
594
    use tari_shutdown::Shutdown;
595

596
    use super::*;
597
    use crate::test_helpers::blockchain::create_new_blockchain_with_network;
598
    fn make_state_machine_handle() -> StateMachineHandle {
2✔
599
        use tokio::sync::{broadcast, watch};
600
        let (state_tx, _state_rx) = broadcast::channel(10);
2✔
601
        let (_status_tx, status_rx) =
2✔
602
            watch::channel(crate::base_node::state_machine_service::states::StatusInfo::new());
2✔
603
        let shutdown = Shutdown::new();
2✔
604
        StateMachineHandle::new(state_tx, status_rx, shutdown.to_signal())
2✔
605
    }
2✔
606

607
    fn make_mempool_handle() -> MempoolHandle {
2✔
608
        use crate::mempool::test_utils::mock::create_mempool_service_mock;
609
        let (handle, _state) = create_mempool_service_mock();
2✔
610
        handle
2✔
611
    }
2✔
612

613
    async fn make_service() -> Service<crate::test_helpers::blockchain::TempDatabase> {
2✔
614
        let db = create_new_blockchain_with_network(Network::LocalNet);
2✔
615
        let adb = AsyncBlockchainDb::from(db);
2✔
616
        let state_machine = make_state_machine_handle();
2✔
617
        let mempool = make_mempool_handle();
2✔
618
        Service::new(adb, state_machine, mempool)
2✔
619
    }
2✔
620

621
    #[tokio::test]
622
    async fn fetch_utxos_start_header_not_found() {
1✔
623
        let service = make_service().await;
1✔
624
        let req = SyncUtxosByBlockRequest {
1✔
625
            start_header_hash: vec![0xAB; 32],
1✔
626
            limit: 4,
1✔
627
            page: 0,
1✔
628
            exclude_spent: false,
1✔
629
            version: 0,
1✔
630
        };
1✔
631
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
632
        match err {
1✔
633
            Error::StartHeaderHashNotFound => {},
1✔
634
            other => panic!("unexpected error: {other:?}"),
1✔
635
        }
1✔
636
    }
1✔
637

638
    #[tokio::test]
639
    async fn fetch_utxos_header_height_mismatch() {
1✔
640
        let service = make_service().await;
1✔
641
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
642
        // page * limit moves start height beyond tip (0)
643
        let req = SyncUtxosByBlockRequest {
1✔
644
            start_header_hash: genesis.hash().to_vec(),
1✔
645
            limit: 1,
1✔
646
            page: 1,
1✔
647
            exclude_spent: false,
1✔
648
            version: 0,
1✔
649
        };
1✔
650
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
651
        match err {
1✔
652
            Error::HeaderHeightMismatch { .. } => {},
1✔
653
            other => panic!("unexpected error: {other:?}"),
1✔
654
        }
1✔
655
    }
1✔
656
}
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