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

tari-project / tari / 21040354003

15 Jan 2026 05:29PM UTC coverage: 60.837% (+0.3%) from 60.51%
21040354003

push

github

SWvheerden
chore: v5.2.1-pre.2

70585 of 116024 relevant lines covered (60.84%)

225875.3 hits per line

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

60.93
/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
const WALLET_MAX_BLOCKS_PER_REQUEST: u64 = 100;
43
const MAX_UTXO_CHUNK_SIZE: usize = 2000;
44

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

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

79
pub struct Service<B> {
80
    db: AsyncBlockchainDb<B>,
81
    state_machine: StateMachineHandle,
82
    mempool: MempoolHandle,
83
    max_utxo_chunk_size: usize,
84
}
85

86
impl<B: BlockchainBackend + 'static> Service<B> {
87
    pub fn new(db: AsyncBlockchainDb<B>, state_machine: StateMachineHandle, mempool: MempoolHandle) -> Self {
5✔
88
        Self {
5✔
89
            db,
5✔
90
            state_machine,
5✔
91
            mempool,
5✔
92
            max_utxo_chunk_size: MAX_UTXO_CHUNK_SIZE,
5✔
93
        }
5✔
94
    }
5✔
95

96
    fn state_machine(&self) -> StateMachineHandle {
×
97
        self.state_machine.clone()
×
98
    }
×
99

100
    fn db(&self) -> &AsyncBlockchainDb<B> {
16✔
101
        &self.db
16✔
102
    }
16✔
103

104
    fn mempool(&self) -> MempoolHandle {
×
105
        self.mempool.clone()
×
106
    }
×
107

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

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

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

151
        Ok(mempool_response)
×
152
    }
×
153

154
    async fn fetch_utxos_by_block(&self, request: GetUtxosByBlockRequest) -> Result<GetUtxosByBlockResponse, Error> {
×
155
        request.validate()?;
×
156

157
        let hash = request.header_hash.clone().try_into()?;
×
158

159
        let header = self
×
160
            .db()
×
161
            .fetch_header_by_block_hash(hash)
×
162
            .await?
×
163
            .ok_or_else(|| Error::HeaderHashNotFound)?;
×
164

165
        // fetch utxos
166
        let outputs_with_statuses = self.db.fetch_outputs_in_block_with_spend_state(hash, None).await?;
×
167

168
        let outputs = outputs_with_statuses
×
169
            .into_iter()
×
170
            .map(|(output, _spent)| output)
×
171
            .collect::<Vec<TransactionOutput>>();
×
172

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

181
        Ok(utxo_block_response)
×
182
    }
×
183

184
    #[allow(clippy::too_many_lines)]
185
    async fn fetch_utxos(&self, request: SyncUtxosByBlockRequest) -> Result<SyncUtxosByBlockResponseV0, Error> {
11✔
186
        // validate and fetch inputs
187
        request.validate()?;
11✔
188

189
        let hash = request.start_header_hash.clone().try_into()?;
11✔
190
        let start_header = self
11✔
191
            .db()
11✔
192
            .fetch_header_by_block_hash(hash)
11✔
193
            .await?
11✔
194
            .ok_or_else(|| Error::StartHeaderHashNotFound)?;
11✔
195

196
        let tip_header = self.db.fetch_tip_header().await?;
10✔
197
        // we only allow wallets to ask for a max of 100 blocks at a time and we want to cache the queries to ensure
198
        // they are in batch of 100 and we want to ensure they request goes to the nearest 100 block height so
199
        // we can cache all wallet's queries
200
        let increase = ((start_header.height + WALLET_MAX_BLOCKS_PER_REQUEST) / WALLET_MAX_BLOCKS_PER_REQUEST) *
10✔
201
            WALLET_MAX_BLOCKS_PER_REQUEST;
10✔
202
        let end_height = cmp::min(tip_header.header().height, increase);
10✔
203
        // pagination
204
        let start_header_height = start_header.height + (request.page * request.limit);
10✔
205
        if start_header_height > tip_header.header().height {
10✔
206
            return Err(Error::HeaderHeightMismatch {
1✔
207
                start_height: start_header.height,
1✔
208
                end_height: tip_header.header().height,
1✔
209
            });
1✔
210
        }
9✔
211
        let start_header = self
9✔
212
            .db
9✔
213
            .fetch_header(start_header_height)
9✔
214
            .await?
9✔
215
            .ok_or_else(|| Error::HeaderNotFound {
9✔
216
                height: start_header_height,
×
217
            })?;
×
218
        // fetch utxos
219
        let mut utxos = vec![];
9✔
220
        let next_page_start_height = start_header.height.saturating_add(request.limit);
9✔
221
        let mut current_header = start_header;
9✔
222
        let mut fetched_chunks = 0;
9✔
223
        let spending_end_header_hash = self
9✔
224
            .db
9✔
225
            .fetch_header(
9✔
226
                tip_header
9✔
227
                    .header()
9✔
228
                    .height
9✔
229
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
9✔
230
            )
9✔
231
            .await?
9✔
232
            .ok_or_else(|| Error::HeaderNotFound {
9✔
233
                height: tip_header
×
234
                    .header()
×
235
                    .height
×
236
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
×
237
            })?
×
238
            .hash();
9✔
239
        let next_header_to_request;
240
        let mut has_next_page = true;
9✔
241
        loop {
242
            let current_header_hash = current_header.hash();
25✔
243
            trace!(
25✔
244
                target: LOG_TARGET,
×
245
                "current header = {} ({})",
×
246
                current_header.height,
247
                current_header_hash.to_hex()
×
248
            );
249
            let outputs = if request.exclude_spent {
25✔
250
                self.db
×
251
                    .fetch_outputs_in_block_with_spend_state(current_header_hash, Some(spending_end_header_hash))
×
252
                    .await?
×
253
                    .into_iter()
×
254
                    .filter(|(_, spent)| !spent)
×
255
                    .map(|(output, _spent)| output)
×
256
                    .collect::<Vec<TransactionOutput>>()
×
257
            } else {
258
                self.db
25✔
259
                    .fetch_outputs_in_block_with_spend_state(current_header_hash, None)
25✔
260
                    .await?
25✔
261
                    .into_iter()
25✔
262
                    .map(|(output, _spent)| output)
25✔
263
                    .collect::<Vec<TransactionOutput>>()
25✔
264
            };
265
            let mut inputs = self
25✔
266
                .db
25✔
267
                .fetch_inputs_in_block(current_header_hash)
25✔
268
                .await?
25✔
269
                .into_iter()
25✔
270
                .map(|input| input.output_hash())
313✔
271
                .collect::<Vec<FixedHash>>();
25✔
272
            if outputs.is_empty() && inputs.is_empty() {
25✔
273
                // No outputs or inputs in this block, put empty placeholder here so wallet knows this height has been
3✔
274
                // scanned This can happen if all the outputs are spent and exclude_spent is true
3✔
275
                let block_response = BlockUtxoInfo {
3✔
276
                    outputs: Vec::new(),
3✔
277
                    inputs: Vec::new(),
3✔
278
                    height: current_header.height,
3✔
279
                    header_hash: current_header_hash.to_vec(),
3✔
280
                    mined_timestamp: current_header.timestamp.as_u64(),
3✔
281
                };
3✔
282
                utxos.push(block_response);
3✔
283
            }
22✔
284
            for output_chunk in outputs.chunks(self.max_utxo_chunk_size) {
25✔
285
                let inputs_to_send = if inputs.is_empty() {
23✔
286
                    Vec::new()
22✔
287
                } else {
288
                    let num_to_drain = inputs.len().min(self.max_utxo_chunk_size);
1✔
289
                    inputs.drain(..num_to_drain).map(|h| h.to_vec()).collect()
313✔
290
                };
291

292
                let output_block_response = BlockUtxoInfo {
23✔
293
                    outputs: output_chunk
23✔
294
                        .iter()
23✔
295
                        .map(|output| MinimalUtxoSyncInfo {
23✔
296
                            output_hash: output.hash().to_vec(),
815✔
297
                            commitment: output.commitment().to_vec(),
815✔
298
                            encrypted_data: output.encrypted_data().as_bytes().to_vec(),
815✔
299
                            sender_offset_public_key: output.sender_offset_public_key.to_vec(),
815✔
300
                        })
815✔
301
                        .collect(),
23✔
302
                    inputs: inputs_to_send,
23✔
303
                    height: current_header.height,
23✔
304
                    header_hash: current_header_hash.to_vec(),
23✔
305
                    mined_timestamp: current_header.timestamp.as_u64(),
23✔
306
                };
307
                utxos.push(output_block_response);
23✔
308
                fetched_chunks += 1;
23✔
309
            }
310
            // We might still have inputs left to send if they are more than the outputs
311
            for input_chunk in inputs.chunks(self.max_utxo_chunk_size) {
25✔
312
                let output_block_response = BlockUtxoInfo {
×
313
                    outputs: Vec::new(),
×
314
                    inputs: input_chunk.iter().map(|h| h.to_vec()).collect::<Vec<_>>().to_vec(),
×
315
                    height: current_header.height,
×
316
                    header_hash: current_header_hash.to_vec(),
×
317
                    mined_timestamp: current_header.timestamp.as_u64(),
×
318
                };
319
                utxos.push(output_block_response);
×
320
                fetched_chunks += 1;
×
321
            }
322

323
            if current_header.height >= tip_header.header().height {
25✔
324
                next_header_to_request = vec![];
2✔
325
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
2✔
326
                break;
2✔
327
            }
23✔
328
            if fetched_chunks > request.limit {
23✔
329
                next_header_to_request = current_header_hash.to_vec();
1✔
330
                // This is a special edge case, our request has reached the page limit, but we are also not done with
331
                // the block. We also dont want to split up the block over two requests. So we need to ensure that we
332
                // remove the partial block we added so that it can be requested fully in the next request. We also dont
333
                // want to get in a loop where the block cannot fit into the page limit, so if the block is the same as
334
                // the first one, we just send it as is, partial. If not we remove it and let it be sent in the next
335
                // request.
336
                if utxos.first().ok_or(Error::General(anyhow::anyhow!("No utxos founds")))? // should never happen as we always add at least one block
1✔
337
                    .header_hash ==
338
                    current_header_hash.to_vec()
1✔
339
                {
340
                    // special edge case where the first block is also the last block we can send, so we just send it as
341
                    // is, partial
342
                    break;
×
343
                }
1✔
344
                while !utxos.is_empty() &&
2✔
345
                    utxos.last().ok_or(Error::General(anyhow::anyhow!("No utxos found")))? // should never happen as we always add at least one block
2✔
346
                    .header_hash ==
347
                        current_header_hash.to_vec()
2✔
348
                {
1✔
349
                    utxos.pop();
1✔
350
                }
1✔
351
                has_next_page = false;
1✔
352
                break;
1✔
353
            }
22✔
354
            if current_header.height + 1 > end_height {
22✔
355
                next_header_to_request = current_header.hash().to_vec();
×
356
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
×
357
                break; // Stop if we reach the end height
×
358
            }
22✔
359
            current_header =
22✔
360
                self.db
22✔
361
                    .fetch_header(current_header.height + 1)
22✔
362
                    .await?
22✔
363
                    .ok_or_else(|| Error::HeaderNotFound {
22✔
364
                        height: current_header.height + 1,
×
365
                    })?;
×
366

367
            if current_header.height == next_page_start_height {
22✔
368
                // we are on the limit, stop here
369
                next_header_to_request = current_header.hash().to_vec();
6✔
370
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
6✔
371
                break;
6✔
372
            }
16✔
373
        }
374
        Ok(SyncUtxosByBlockResponseV0 {
9✔
375
            blocks: utxos,
9✔
376
            has_next_page,
9✔
377
            next_header_to_scan: next_header_to_request,
9✔
378
        })
9✔
379
    }
11✔
380
}
381

382
#[async_trait::async_trait]
383
impl<B: BlockchainBackend + 'static> BaseNodeWalletQueryService for Service<B> {
384
    type Error = Error;
385

386
    async fn get_tip_info(&self) -> Result<TipInfoResponse, Self::Error> {
×
387
        let state_machine = self.state_machine();
×
388
        let status_watch = state_machine.get_status_info_watch();
×
389
        let is_synced = match status_watch.borrow().state_info {
×
390
            StateInfo::Listening(li) => li.is_synced(),
×
391
            _ => false,
×
392
        };
393

394
        let metadata = self.db.get_chain_metadata().await?;
×
395

396
        Ok(TipInfoResponse {
×
397
            metadata: Some(metadata),
×
398
            is_synced,
×
399
        })
×
400
    }
×
401

402
    async fn get_header_by_height(&self, height: u64) -> Result<models::BlockHeader, Self::Error> {
×
403
        let result = self
×
404
            .db
×
405
            .fetch_header(height)
×
406
            .await?
×
407
            .ok_or(Error::HeaderNotFound { height })?
×
408
            .into();
×
409
        Ok(result)
×
410
    }
×
411

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

416
        let mut left_height = 0u64;
×
417
        let mut right_height = tip_header.height();
×
418

419
        while left_height <= right_height {
×
420
            let mut mid_height = (left_height + right_height) / 2;
×
421

422
            if mid_height == 0 {
×
423
                return Ok(0u64);
×
424
            }
×
425
            // If the two bounds are adjacent then perform the test between the right and left sides
426
            if left_height == mid_height {
×
427
                mid_height = right_height;
×
428
            }
×
429

430
            let mid_header = self
×
431
                .db
×
432
                .fetch_header(mid_height)
×
433
                .await?
×
434
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height })?;
×
435
            let before_mid_header = self
×
436
                .db
×
437
                .fetch_header(mid_height - 1)
×
438
                .await?
×
439
                .ok_or_else(|| Error::HeaderNotFound { height: mid_height - 1 })?;
×
440
            trace!(
×
441
                target: LOG_TARGET,
×
442
                "requested_epoch_time: {}, left: {}, mid: {}/{} ({}/{}), right: {}",
×
443
                epoch_time,
444
                left_height,
445
                mid_height,
446
                mid_height-1,
×
447
                mid_header.timestamp.as_u64(),
×
448
                before_mid_header.timestamp.as_u64(),
×
449
                right_height
450
            );
451
            if epoch_time < mid_header.timestamp.as_u64() && epoch_time >= before_mid_header.timestamp.as_u64() {
×
452
                trace!(
×
453
                    target: LOG_TARGET,
×
454
                    "requested_epoch_time: {}, selected height: {}",
×
455
                    epoch_time, before_mid_header.height
456
                );
457
                return Ok(before_mid_header.height);
×
458
            } else if mid_height == right_height {
×
459
                trace!(
×
460
                    target: LOG_TARGET,
×
461
                    "requested_epoch_time: {epoch_time}, selected height: {right_height}"
×
462
                );
463
                return Ok(right_height);
×
464
            } else if epoch_time <= mid_header.timestamp.as_u64() {
×
465
                right_height = mid_height;
×
466
            } else {
×
467
                left_height = mid_height;
×
468
            }
×
469
        }
470

471
        Ok(0u64)
×
472
    }
×
473

474
    async fn transaction_query(
475
        &self,
476
        signature: crate::base_node::rpc::models::Signature,
477
    ) -> Result<TxQueryResponse, Self::Error> {
×
478
        let signature = signature.try_into().map_err(Error::SignatureConversion)?;
×
479

480
        let response = self.fetch_kernel(signature).await?;
×
481

482
        Ok(response)
×
483
    }
×
484

485
    async fn sync_utxos_by_block_v0(
486
        &self,
487
        request: SyncUtxosByBlockRequest,
488
    ) -> Result<SyncUtxosByBlockResponseV0, Self::Error> {
×
489
        self.fetch_utxos(request).await
×
490
    }
×
491

492
    async fn sync_utxos_by_block_v1(
493
        &self,
494
        request: SyncUtxosByBlockRequest,
495
    ) -> Result<SyncUtxosByBlockResponseV1, Self::Error> {
×
496
        let v1 = self.fetch_utxos(request).await?;
×
497
        Ok(v1.into())
×
498
    }
×
499

500
    async fn get_utxos_by_block(
501
        &self,
502
        request: GetUtxosByBlockRequest,
503
    ) -> Result<GetUtxosByBlockResponse, Self::Error> {
×
504
        self.fetch_utxos_by_block(request).await
×
505
    }
×
506

507
    async fn get_utxos_mined_info(
508
        &self,
509
        request: models::GetUtxosMinedInfoRequest,
510
    ) -> Result<models::GetUtxosMinedInfoResponse, Self::Error> {
×
511
        request.validate()?;
×
512

513
        let mut utxos = vec![];
×
514

515
        let tip_header = self.db().fetch_tip_header().await?;
×
516
        for hash in request.hashes {
×
517
            let hash = hash.try_into()?;
×
518
            let output = self.db().fetch_output(hash).await?;
×
519
            if let Some(output) = output {
×
520
                utxos.push(models::MinedUtxoInfo {
×
521
                    utxo_hash: hash.to_vec(),
×
522
                    mined_in_hash: output.header_hash.to_vec(),
×
523
                    mined_in_height: output.mined_height,
×
524
                    mined_in_timestamp: output.mined_timestamp,
×
525
                });
×
526
            }
×
527
        }
528

529
        Ok(models::GetUtxosMinedInfoResponse {
×
530
            utxos,
×
531
            best_block_hash: tip_header.hash().to_vec(),
×
532
            best_block_height: tip_header.height(),
×
533
        })
×
534
    }
×
535

536
    async fn get_utxos_deleted_info(
537
        &self,
538
        request: models::GetUtxosDeletedInfoRequest,
539
    ) -> Result<models::GetUtxosDeletedInfoResponse, Self::Error> {
×
540
        request.validate()?;
×
541

542
        let mut utxos = vec![];
×
543

544
        let must_include_header = request.must_include_header.clone().try_into()?;
×
545
        if self
×
546
            .db()
×
547
            .fetch_header_by_block_hash(must_include_header)
×
548
            .await?
×
549
            .is_none()
×
550
        {
551
            return Err(Error::HeaderHashNotFound);
×
552
        }
×
553

554
        let tip_header = self.db().fetch_tip_header().await?;
×
555
        for hash in request.hashes {
×
556
            let hash = hash.try_into()?;
×
557
            let output = self.db().fetch_output(hash).await?;
×
558

559
            if let Some(output) = output {
×
560
                // is it still unspent?
561
                let input = self.db().fetch_input(hash).await?;
×
562
                if let Some(i) = input {
×
563
                    utxos.push(models::DeletedUtxoInfo {
×
564
                        utxo_hash: hash.to_vec(),
×
565
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
566
                        spent_in_header: Some((i.spent_height, i.header_hash.to_vec())),
×
567
                    });
×
568
                } else {
×
569
                    utxos.push(models::DeletedUtxoInfo {
×
570
                        utxo_hash: hash.to_vec(),
×
571
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
572
                        spent_in_header: None,
×
573
                    });
×
574
                }
×
575
            } else {
×
576
                utxos.push(models::DeletedUtxoInfo {
×
577
                    utxo_hash: hash.to_vec(),
×
578
                    found_in_header: None,
×
579
                    spent_in_header: None,
×
580
                });
×
581
            }
×
582
        }
583

584
        Ok(models::GetUtxosDeletedInfoResponse {
×
585
            utxos,
×
586
            best_block_hash: tip_header.hash().to_vec(),
×
587
            best_block_height: tip_header.height(),
×
588
        })
×
589
    }
×
590

591
    async fn generate_kernel_merkle_proof(
592
        &self,
593
        excess_sig: types::CompressedSignature,
594
    ) -> Result<GenerateKernelMerkleProofResponse, Self::Error> {
×
595
        let proof = self.db().generate_kernel_merkle_proof(excess_sig).await?;
×
596
        Ok(GenerateKernelMerkleProofResponse {
597
            encoded_merkle_proof: bincode::serialize(&proof.merkle_proof).map_err(Error::general)?,
×
598
            block_hash: proof.block_hash,
×
599
            leaf_index: proof.leaf_index.value() as u64,
×
600
        })
601
    }
×
602

603
    async fn get_utxo(&self, request: models::GetUtxoRequest) -> Result<Option<TransactionOutput>, Self::Error> {
×
604
        let hash: FixedHash = request.output_hash.try_into().map_err(Error::general)?;
×
605
        let outputs = self.db().fetch_outputs_with_spend_status_at_tip(vec![hash]).await?;
×
606
        let output = match outputs.first() {
×
607
            Some(Some((output, _spent))) => Some(output.clone()),
×
608
            _ => return Err(Error::OutputNotFound),
×
609
        };
610
        Ok(output)
×
611
    }
×
612
}
613

614
#[cfg(test)]
615
mod tests {
616
    #![allow(clippy::indexing_slicing)]
617
    use tari_common::configuration::Network;
618
    use tari_shutdown::Shutdown;
619

620
    use super::*;
621
    use crate::test_helpers::blockchain::create_new_blockchain_with_network;
622
    fn make_state_machine_handle() -> StateMachineHandle {
5✔
623
        use tokio::sync::{broadcast, watch};
624
        let (state_tx, _state_rx) = broadcast::channel(10);
5✔
625
        let (_status_tx, status_rx) =
5✔
626
            watch::channel(crate::base_node::state_machine_service::states::StatusInfo::new());
5✔
627
        let shutdown = Shutdown::new();
5✔
628
        StateMachineHandle::new(state_tx, status_rx, shutdown.to_signal())
5✔
629
    }
5✔
630

631
    fn make_mempool_handle() -> MempoolHandle {
5✔
632
        use crate::mempool::test_utils::mock::create_mempool_service_mock;
633
        let (handle, _state) = create_mempool_service_mock();
5✔
634
        handle
5✔
635
    }
5✔
636

637
    async fn make_service() -> Service<crate::test_helpers::blockchain::TempDatabase> {
2✔
638
        let db = create_new_blockchain_with_network(Network::LocalNet);
2✔
639
        let adb = AsyncBlockchainDb::from(db);
2✔
640
        let state_machine = make_state_machine_handle();
2✔
641
        let mempool = make_mempool_handle();
2✔
642
        Service::new(adb, state_machine, mempool)
2✔
643
    }
2✔
644

645
    #[tokio::test]
646
    async fn fetch_utxos_start_header_not_found() {
1✔
647
        let service = make_service().await;
1✔
648
        let req = SyncUtxosByBlockRequest {
1✔
649
            start_header_hash: vec![0xAB; 32],
1✔
650
            limit: 4,
1✔
651
            page: 0,
1✔
652
            exclude_spent: false,
1✔
653
            version: 0,
1✔
654
        };
1✔
655
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
656
        match err {
1✔
657
            Error::StartHeaderHashNotFound => {},
1✔
658
            other => panic!("unexpected error: {other:?}"),
1✔
659
        }
1✔
660
    }
1✔
661

662
    #[tokio::test]
663
    async fn fetch_utxos_header_height_mismatch() {
1✔
664
        let service = make_service().await;
1✔
665
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
666
        // page * limit moves start height beyond tip (0)
667
        let req = SyncUtxosByBlockRequest {
1✔
668
            start_header_hash: genesis.hash().to_vec(),
1✔
669
            limit: 1,
1✔
670
            page: 1,
1✔
671
            exclude_spent: false,
1✔
672
            version: 0,
1✔
673
        };
1✔
674
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
675
        match err {
1✔
676
            Error::HeaderHeightMismatch { .. } => {},
1✔
677
            other => panic!("unexpected error: {other:?}"),
1✔
678
        }
1✔
679
    }
1✔
680

681
    #[tokio::test]
682
    async fn fetch_utxos_paginates_results() {
1✔
683
        use crate::test_helpers::blockchain::create_main_chain;
684

685
        // Build a small chain: GB -> A -> B -> C
686
        let db = create_new_blockchain_with_network(Network::LocalNet);
1✔
687
        let (_names, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"], ["C->B"], ["D->C"]));
1✔
688

689
        // Construct the service over this DB
690
        let adb = AsyncBlockchainDb::from(db);
1✔
691
        let state_machine = make_state_machine_handle();
1✔
692
        let mempool = make_mempool_handle();
1✔
693
        let service = Service::new(adb, state_machine, mempool);
1✔
694

695
        // Use genesis as the start header hash
696
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
697
        let g_hash = genesis.hash().to_vec();
1✔
698

699
        // Page 0, limit 1: should return only A (height 1) and next header should be B
700
        // genesis block in local net has 0 inputs and outputs
701
        let resp0 = service
1✔
702
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
703
                start_header_hash: g_hash.clone(),
1✔
704
                limit: 1,
1✔
705
                page: 0,
1✔
706
                exclude_spent: false,
1✔
707
                version: 0,
1✔
708
            })
1✔
709
            .await
1✔
710
            .expect("fetch_utxos page 0 should succeed");
1✔
711

712
        assert_eq!(resp0.blocks.len(), 1, "expected exactly one block in first page");
1✔
713
        assert_eq!(resp0.blocks[0].height, 0, "first page should start at genesis height");
1✔
714

715
        // Expect next_header_to_scan to be the hash of block A (height 1)
716
        let a_hash = chain.get("A").unwrap().hash().to_vec();
1✔
717
        assert_eq!(resp0.next_header_to_scan, a_hash, "next header should point to A");
1✔
718

719
        // Page 1, limit 1: should return only block A (height 1) and next header should be B
720
        let resp1 = service
1✔
721
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
722
                start_header_hash: g_hash.clone(),
1✔
723
                limit: 1,
1✔
724
                page: 1,
1✔
725
                exclude_spent: false,
1✔
726
                version: 0,
1✔
727
            })
1✔
728
            .await
1✔
729
            .expect("fetch_utxos page 1 should succeed");
1✔
730

731
        assert_eq!(resp1.blocks.len(), 1, "expected exactly one block in second page");
1✔
732
        assert_eq!(resp1.blocks[0].height, 1, "second page should start at height 1 (A)");
1✔
733

734
        // Expect next_header_to_scan to be the hash of block B (height 2)
735
        let b_hash = chain.get("B").unwrap().hash().to_vec();
1✔
736
        assert_eq!(resp1.next_header_to_scan, b_hash, "next header should point to B");
1✔
737

738
        // Page 2, limit 1: should return only block B (height 2) and next header should be C
739
        let resp2 = service
1✔
740
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
741
                start_header_hash: g_hash.clone(),
1✔
742
                limit: 1,
1✔
743
                page: 2,
1✔
744
                exclude_spent: false,
1✔
745
                version: 0,
1✔
746
            })
1✔
747
            .await
1✔
748
            .expect("fetch_utxos page 2 should succeed");
1✔
749

750
        assert_eq!(resp2.blocks.len(), 1, "expected exactly one block in third page");
1✔
751
        assert_eq!(resp2.blocks[0].height, 2, "third page should start at height 2 (B)");
1✔
752
        let c_hash = chain.get("C").unwrap().hash().to_vec();
1✔
753
        assert_eq!(resp2.next_header_to_scan, c_hash, "next header should point to C");
1✔
754

755
        // Page 3, limit 1: should return only block C (height 3) and next header should be empty (tip reached)
756
        let resp3 = service
1✔
757
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
758
                start_header_hash: g_hash.clone(),
1✔
759
                limit: 1,
1✔
760
                page: 3,
1✔
761
                exclude_spent: false,
1✔
762
                version: 0,
1✔
763
            })
1✔
764
            .await
1✔
765
            .expect("fetch_utxos page 3 should succeed");
1✔
766

767
        assert_eq!(resp3.blocks.len(), 1, "expected exactly one block in fourth page");
1✔
768
        assert_eq!(resp3.blocks[0].height, 3, "fourth page should start at height 3 (C)");
1✔
769
        let d_hash = chain.get("D").unwrap().hash().to_vec();
1✔
770
        assert_eq!(resp3.next_header_to_scan, d_hash, "next header should point to D");
1✔
771

772
        // Page 4, limit 1: should return only block C (height 3) and next header should be empty (tip reached)
773
        let resp4 = service
1✔
774
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
775
                start_header_hash: g_hash.clone(),
1✔
776
                limit: 1,
1✔
777
                page: 4,
1✔
778
                exclude_spent: false,
1✔
779
                version: 0,
1✔
780
            })
1✔
781
            .await
1✔
782
            .expect("fetch_utxos page 3 should succeed");
1✔
783

784
        assert_eq!(resp4.blocks.len(), 1, "expected exactly one block in fourth page");
1✔
785
        assert_eq!(resp4.blocks[0].height, 4, "fourth page should start at height 4 (D)");
1✔
786
        assert!(resp4.next_header_to_scan.is_empty(), "no next header at tip");
1✔
787
        let resp5 = service
1✔
788
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
789
                start_header_hash: g_hash,
1✔
790
                limit: 2,
1✔
791
                page: 0,
1✔
792
                exclude_spent: false,
1✔
793
                version: 0,
1✔
794
            })
1✔
795
            .await
1✔
796
            .expect("fetch_utxos should succeed");
1✔
797

798
        assert_eq!(resp5.blocks.len(), 2, "expected 2 blocks");
1✔
799
        assert_eq!(resp5.blocks[0].height, 0, "Should be block (GB)");
1✔
800
        assert_eq!(resp5.blocks[1].height, 1, "Should be block (A)");
1✔
801
        let b_hash = chain.get("B").unwrap().hash().to_vec();
1✔
802
        assert_eq!(resp5.next_header_to_scan, b_hash, "next header should point to B");
1✔
803
        assert!(resp5.has_next_page, "Should have more pages");
1✔
804
    }
1✔
805

806
    #[tokio::test]
807
    async fn large_fetch_utxo_paginates_results() {
1✔
808
        use crate::test_helpers::blockchain::create_main_chain;
809

810
        // Build a small chain: GB -> A -> B -> C
811
        let db = create_new_blockchain_with_network(Network::LocalNet);
1✔
812
        let (_names, chain) = create_main_chain(
1✔
813
            &db,
1✔
814
            block_specs!(
1✔
815
                ["1->GB"],
1✔
816
                ["2->1"],
1✔
817
                ["3->2"],
1✔
818
                ["4->3"],
1✔
819
                ["5->4"],
1✔
820
                ["6->5"],
1✔
821
                ["7->6"],
1✔
822
                ["8->7"],
1✔
823
                ["9->8"],
1✔
824
                ["10->9"],
1✔
825
                ["11->10"],
1✔
826
                ["12->11"]
1✔
827
            ),
1✔
828
        );
1✔
829

830
        // Construct the service over this DB
831
        let adb = AsyncBlockchainDb::from(db);
1✔
832
        let state_machine = make_state_machine_handle();
1✔
833
        let mempool = make_mempool_handle();
1✔
834
        let service = Service::new(adb, state_machine, mempool);
1✔
835

836
        // Use genesis as the start header hash
837
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
838
        let g_hash = genesis.hash().to_vec();
1✔
839

840
        let resp = service
1✔
841
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
842
                start_header_hash: g_hash.clone(),
1✔
843
                limit: 10,
1✔
844
                page: 0,
1✔
845
                exclude_spent: false,
1✔
846
                version: 0,
1✔
847
            })
1✔
848
            .await
1✔
849
            .expect("fetch_utxos should succeed");
1✔
850

851
        assert_eq!(resp.blocks.len(), 10, "expected 10 blocks");
1✔
852
        assert_eq!(resp.blocks[0].height, 0, "Should be block (0)");
1✔
853
        assert_eq!(resp.blocks[1].height, 1, "Should be block (1)");
1✔
854
        assert_eq!(resp.blocks[2].height, 2, "Should be block (2)");
1✔
855
        assert_eq!(resp.blocks[3].height, 3, "Should be block (3)");
1✔
856
        assert_eq!(resp.blocks[4].height, 4, "Should be block (4)");
1✔
857
        assert_eq!(resp.blocks[5].height, 5, "Should be block (5)");
1✔
858
        assert_eq!(resp.blocks[6].height, 6, "Should be block (6)");
1✔
859
        assert_eq!(resp.blocks[7].height, 7, "Should be block (7)");
1✔
860
        assert_eq!(resp.blocks[8].height, 8, "Should be block (8)");
1✔
861
        assert_eq!(resp.blocks[9].height, 9, "Should be block (9)");
1✔
862
        let next_hash = chain.get("10").unwrap().hash().to_vec();
1✔
863
        assert_eq!(resp.next_header_to_scan, next_hash, "next header should point to 10");
1✔
864
        assert!(resp.has_next_page, "Should have more pages");
1✔
865
        let resp = service
1✔
866
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
867
                start_header_hash: g_hash,
1✔
868
                limit: 10,
1✔
869
                page: 1,
1✔
870
                exclude_spent: false,
1✔
871
                version: 0,
1✔
872
            })
1✔
873
            .await
1✔
874
            .expect("fetch_utxos should succeed");
1✔
875
        assert_eq!(resp.blocks.len(), 3, "expected 3 blocks");
1✔
876
        assert_eq!(resp.blocks[0].height, 10, "Should be block (10)");
1✔
877
        assert_eq!(resp.blocks[1].height, 11, "Should be block (11)");
1✔
878
        assert_eq!(resp.blocks[2].height, 12, "Should be block (12)");
1✔
879
        assert!(resp.next_header_to_scan.is_empty(), "Should be empty");
1✔
880
        assert!(!resp.has_next_page, "Should not have more pages");
1✔
881
    }
1✔
882

883
    // this will only run and work in esmeralda
884
    #[cfg(tari_target_network_testnet)]
885
    #[tokio::test]
886
    async fn large_utxo_handled_correctly() {
1✔
887
        use crate::test_helpers::blockchain::create_main_chain;
888

889
        // Build a small chain: GB -> A -> B -> C
890
        let db = create_new_blockchain_with_network(Network::Esmeralda);
1✔
891
        let (_names, _chain) = create_main_chain(
1✔
892
            &db,
1✔
893
            block_specs!(
1✔
894
                ["1->GB"],
1✔
895
                ["2->1"],
1✔
896
                ["3->2"],
1✔
897
                ["4->3"],
1✔
898
                ["5->4"],
1✔
899
                ["6->5"],
1✔
900
                ["7->6"],
1✔
901
                ["8->7"],
1✔
902
                ["9->8"],
1✔
903
                ["10->9"],
1✔
904
            ),
1✔
905
        );
1✔
906

907
        // Construct the service over this DB
908
        let adb = AsyncBlockchainDb::from(db);
1✔
909
        let state_machine = make_state_machine_handle();
1✔
910
        let mempool = make_mempool_handle();
1✔
911
        let mut service = Service::new(adb, state_machine, mempool);
1✔
912
        service.max_utxo_chunk_size = 500; // set small chunk size for testing
1✔
913

914
        // Use genesis as the start header hash
915
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
916
        let g_hash = genesis.hash().to_vec();
1✔
917

918
        let resp = service
1✔
919
            .fetch_utxos(SyncUtxosByBlockRequest {
1✔
920
                start_header_hash: g_hash.clone(),
1✔
921
                limit: 5,
1✔
922
                page: 0,
1✔
923
                exclude_spent: false,
1✔
924
                version: 0,
1✔
925
            })
1✔
926
            .await
1✔
927
            .expect("fetch_utxos should succeed");
1✔
928

929
        assert_eq!(resp.blocks.len(), 5, "expected 5 blocks");
1✔
930
        assert_eq!(resp.blocks[0].height, 0, "Should be block (0)");
1✔
931
        assert_eq!(resp.blocks[1].height, 0, "Should be block (0)");
1✔
932
        assert_eq!(resp.blocks[2].height, 1, "Should be block (1)");
1✔
933
        assert_eq!(resp.blocks[3].height, 2, "Should be block (2)");
1✔
934
        assert_eq!(resp.blocks[4].height, 3, "Should be block (3)");
1✔
935
        let header_4 = service.db().fetch_header(4).await.unwrap().unwrap();
1✔
936
        assert_eq!(
1✔
937
            header_4.hash().to_vec(),
1✔
938
            resp.next_header_to_scan,
939
            "next header should point to 4"
×
940
        );
941
        assert!(!resp.has_next_page, "Should have no more pages");
1✔
942
    }
1✔
943
}
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