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

tari-project / tari / 24143284219

08 Apr 2026 03:18PM UTC coverage: 60.482% (+0.03%) from 60.453%
24143284219

push

github

web-flow
feat: update the api for deleted block info (#7735)

Description
---
Add the timestamp of the deleted utxo info

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

21 existing lines in 8 files now uncovered.

69800 of 115407 relevant lines covered (60.48%)

429756.44 hits per line

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

19.5
/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::{Validate, validation};
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::{ByteArray, ByteArrayError, hex::Hex};
32
use thiserror::Error;
33

34
use crate::{
35
    base_node::{StateMachineHandle, rpc::BaseNodeWalletQueryService, state_machine_service::states::StateInfo},
36
    chain_storage::{BlockchainBackend, ChainStorageError, async_db::AsyncBlockchainDb},
37
    mempool::{MempoolServiceError, TxStorageResponse, service::MempoolHandle},
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 {
2✔
88
        Self {
2✔
89
            db,
2✔
90
            state_machine,
2✔
91
            mempool,
2✔
92
            max_utxo_chunk_size: MAX_UTXO_CHUNK_SIZE,
2✔
93
        }
2✔
94
    }
2✔
95

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

100
    fn db(&self) -> &AsyncBlockchainDb<B> {
3✔
101
        &self.db
3✔
102
    }
3✔
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> {
2✔
186
        // validate and fetch inputs
187
        request.validate()?;
2✔
188

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

196
        let tip_header = self.db.fetch_tip_header().await?;
1✔
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) *
1✔
201
            WALLET_MAX_BLOCKS_PER_REQUEST;
1✔
202
        let end_height = cmp::min(tip_header.header().height, increase);
1✔
203
        // pagination
204
        let start_header_height = start_header.height + (request.page * request.limit);
1✔
205
        if start_header_height > tip_header.header().height {
1✔
206
            return Err(Error::HeaderHeightMismatch {
1✔
207
                start_height: start_header.height,
1✔
208
                end_height: tip_header.header().height,
1✔
209
            });
1✔
210
        }
×
211
        let start_header = self
×
212
            .db
×
213
            .fetch_header(start_header_height)
×
214
            .await?
×
215
            .ok_or_else(|| Error::HeaderNotFound {
×
216
                height: start_header_height,
×
217
            })?;
×
218
        // fetch utxos
219
        let mut utxos = vec![];
×
220
        let next_page_start_height = start_header.height.saturating_add(request.limit);
×
221
        let mut current_header = start_header;
×
222
        let mut fetched_chunks = 0;
×
223
        let spending_end_header_hash = self
×
224
            .db
×
225
            .fetch_header(
×
226
                tip_header
×
227
                    .header()
×
228
                    .height
×
229
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
×
230
            )
×
231
            .await?
×
232
            .ok_or_else(|| Error::HeaderNotFound {
×
233
                height: tip_header
×
234
                    .header()
×
235
                    .height
×
236
                    .saturating_sub(SYNC_UTXOS_SPEND_TIP_SAFETY_LIMIT),
×
237
            })?
×
238
            .hash();
×
239
        let next_header_to_request;
240
        let mut has_next_page = true;
×
241
        loop {
242
            let current_header_hash = current_header.hash();
×
243
            trace!(
×
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 {
×
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
×
259
                    .fetch_outputs_in_block_with_spend_state(current_header_hash, None)
×
260
                    .await?
×
261
                    .into_iter()
×
262
                    .map(|(output, _spent)| output)
×
263
                    .collect::<Vec<TransactionOutput>>()
×
264
            };
265
            let mut inputs = if request.exclude_inputs {
×
266
                Vec::new()
×
267
            } else {
268
                self.db
×
269
                    .fetch_inputs_in_block(current_header_hash)
×
270
                    .await?
×
271
                    .into_iter()
×
272
                    .map(|input| input.output_hash())
×
273
                    .collect::<Vec<FixedHash>>()
×
274
            };
275
            if outputs.is_empty() && inputs.is_empty() {
×
276
                // No outputs or inputs in this block, put empty placeholder here so wallet knows this height has been
×
277
                // scanned This can happen if all the outputs are spent and exclude_spent is true
×
278
                let block_response = BlockUtxoInfo {
×
279
                    outputs: Vec::new(),
×
280
                    inputs: Vec::new(),
×
281
                    height: current_header.height,
×
282
                    header_hash: current_header_hash.to_vec(),
×
283
                    mined_timestamp: current_header.timestamp.as_u64(),
×
284
                };
×
285
                utxos.push(block_response);
×
286
            }
×
287
            for output_chunk in outputs.chunks(self.max_utxo_chunk_size) {
×
288
                let inputs_to_send = if inputs.is_empty() {
×
289
                    Vec::new()
×
290
                } else {
291
                    let num_to_drain = inputs.len().min(self.max_utxo_chunk_size);
×
292
                    inputs.drain(..num_to_drain).map(|h| h.to_vec()).collect()
×
293
                };
294

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

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

370
            if current_header.height == next_page_start_height {
×
371
                // we are on the limit, stop here
372
                next_header_to_request = current_header.hash().to_vec();
×
373
                has_next_page = (end_height.saturating_sub(current_header.height)) > 0;
×
374
                break;
×
375
            }
×
376
        }
377
        Ok(SyncUtxosByBlockResponseV0 {
×
378
            blocks: utxos,
×
379
            has_next_page,
×
380
            next_header_to_scan: next_header_to_request,
×
381
        })
×
382
    }
2✔
383
}
384

385
#[async_trait::async_trait]
386
impl<B: BlockchainBackend + 'static> BaseNodeWalletQueryService for Service<B> {
387
    type Error = Error;
388

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

397
        let metadata = self.db.get_chain_metadata().await?;
×
398

399
        Ok(TipInfoResponse {
×
400
            metadata: Some(metadata),
×
401
            is_synced,
×
402
        })
×
403
    }
×
404

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

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

419
        let mut left_height = 0u64;
×
420
        let mut right_height = tip_header.height();
×
421

422
        while left_height <= right_height {
×
423
            let mut mid_height = (left_height + right_height) / 2;
×
424

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

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

474
        Ok(0u64)
×
475
    }
×
476

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

483
        let response = self.fetch_kernel(signature).await?;
×
484

485
        Ok(response)
×
486
    }
×
487

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

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

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

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

516
        let mut utxos = vec![];
×
517
        let mut unmined_hashes = vec![];
×
518

519
        let tip_header = self.db().fetch_tip_header().await?;
×
520
        for hash in request.hashes {
×
521
            let hash: types::HashOutput = hash.try_into()?;
×
522
            let output = self.db().fetch_output(hash).await?;
×
523
            if let Some(output) = output {
×
524
                utxos.push(models::MinedUtxoInfo {
×
525
                    utxo_hash: hash.to_vec(),
×
526
                    mined_in_hash: output.header_hash.to_vec(),
×
527
                    mined_in_height: output.mined_height,
×
528
                    mined_in_timestamp: output.mined_timestamp,
×
529
                });
×
530
            } else {
×
531
                unmined_hashes.push(hash);
×
532
            }
×
533
        }
534

535
        // Version 2: also check mempool for unmined outputs
536
        let mempool_utxos = if request.version >= 2 && !unmined_hashes.is_empty() {
×
537
            let mut mempool = self.mempool();
×
538
            mempool
×
539
                .filter_outputs_in_mempool(unmined_hashes)
×
540
                .await?
×
541
                .into_iter()
×
542
                .map(|h| h.to_vec())
×
543
                .collect()
×
544
        } else {
545
            vec![]
×
546
        };
547

548
        Ok(models::GetUtxosMinedInfoResponse {
×
549
            utxos,
×
550
            best_block_hash: tip_header.hash().to_vec(),
×
551
            best_block_height: tip_header.height(),
×
552
            mempool_utxos,
×
553
        })
×
554
    }
×
555

556
    async fn get_utxos_deleted_info(
557
        &self,
558
        request: models::GetUtxosDeletedInfoRequest,
559
    ) -> Result<models::GetUtxosDeletedInfoResponse, Self::Error> {
×
560
        request.validate()?;
×
561

562
        let mut utxos = vec![];
×
563

564
        let must_include_header = request.must_include_header.clone().try_into()?;
×
565
        if self
×
566
            .db()
×
567
            .fetch_header_by_block_hash(must_include_header)
×
568
            .await?
×
569
            .is_none()
×
570
        {
571
            return Err(Error::HeaderHashNotFound);
×
572
        }
×
573

574
        let tip_header = self.db().fetch_tip_header().await?;
×
575
        for hash in request.hashes {
×
576
            let hash = hash.try_into()?;
×
577
            let output = self.db().fetch_output(hash).await?;
×
578

579
            if let Some(output) = output {
×
580
                // is it still unspent?
581
                let input = self.db().fetch_input(hash).await?;
×
582
                if let Some(i) = input {
×
583
                    utxos.push(models::DeletedUtxoInfo {
×
584
                        utxo_hash: hash.to_vec(),
×
585
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
586
                        spent_in_header: Some((i.spent_height, i.header_hash.to_vec())),
×
587
                    });
×
588
                } else {
×
589
                    utxos.push(models::DeletedUtxoInfo {
×
590
                        utxo_hash: hash.to_vec(),
×
591
                        found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
592
                        spent_in_header: None,
×
593
                    });
×
594
                }
×
595
            } else {
×
596
                utxos.push(models::DeletedUtxoInfo {
×
597
                    utxo_hash: hash.to_vec(),
×
598
                    found_in_header: None,
×
599
                    spent_in_header: None,
×
600
                });
×
601
            }
×
602
        }
603

604
        Ok(models::GetUtxosDeletedInfoResponse {
×
605
            utxos,
×
606
            best_block_hash: tip_header.hash().to_vec(),
×
607
            best_block_height: tip_header.height(),
×
608
        })
×
609
    }
×
610

611
    async fn get_utxos_deleted_info_v1(
612
        &self,
613
        request: models::GetUtxosDeletedInfoRequest,
NEW
614
    ) -> Result<models::GetUtxosDeletedInfoResponseV1, Self::Error> {
×
NEW
615
        request.validate()?;
×
616

NEW
617
        let mut utxos = Vec::with_capacity(request.hashes.len());
×
618

NEW
619
        let must_include_header = request.must_include_header.clone().try_into()?;
×
NEW
620
        if self
×
NEW
621
            .db()
×
NEW
622
            .fetch_header_by_block_hash(must_include_header)
×
NEW
623
            .await?
×
NEW
624
            .is_none()
×
625
        {
NEW
626
            return Err(Error::HeaderHashNotFound);
×
NEW
627
        }
×
628

NEW
629
        let tip_header = self.db().fetch_tip_header().await?;
×
NEW
630
        for hash in request.hashes {
×
NEW
631
            let hash = hash.try_into()?;
×
NEW
632
            let output = self.db().fetch_output(hash).await?;
×
633

NEW
634
            let utxo_info = if let Some(output) = output {
×
NEW
635
                let input = self.db().fetch_input(hash).await?;
×
636
                models::DeletedUtxoInfoV1 {
NEW
637
                    utxo_hash: hash.to_vec(),
×
NEW
638
                    found_in_header: Some((output.mined_height, output.header_hash.to_vec())),
×
NEW
639
                    spent_in_header: input.as_ref().map(|i| (i.spent_height, i.header_hash.to_vec())),
×
NEW
640
                    spent_timestamp: input.as_ref().map(|i| i.spent_timestamp),
×
641
                }
642
            } else {
NEW
643
                models::DeletedUtxoInfoV1 {
×
NEW
644
                    utxo_hash: hash.to_vec(),
×
NEW
645
                    found_in_header: None,
×
NEW
646
                    spent_in_header: None,
×
NEW
647
                    spent_timestamp: None,
×
NEW
648
                }
×
649
            };
NEW
650
            utxos.push(utxo_info);
×
651
        }
652

NEW
653
        Ok(models::GetUtxosDeletedInfoResponseV1 {
×
NEW
654
            utxos,
×
NEW
655
            best_block_hash: tip_header.hash().to_vec(),
×
NEW
656
            best_block_height: tip_header.height(),
×
NEW
657
        })
×
NEW
658
    }
×
659

660
    async fn generate_kernel_merkle_proof(
661
        &self,
662
        excess_sig: types::CompressedSignature,
663
    ) -> Result<GenerateKernelMerkleProofResponse, Self::Error> {
×
664
        let proof = self.db().generate_kernel_merkle_proof(excess_sig).await?;
×
665
        Ok(GenerateKernelMerkleProofResponse {
666
            encoded_merkle_proof: bincode::serialize(&proof.merkle_proof).map_err(Error::general)?,
×
667
            block_hash: proof.block_hash,
×
668
            leaf_index: proof.leaf_index.value() as u64,
×
669
        })
670
    }
×
671

672
    async fn get_utxo(&self, request: models::GetUtxoRequest) -> Result<Option<TransactionOutput>, Self::Error> {
×
673
        let hash: FixedHash = request.output_hash.try_into().map_err(Error::general)?;
×
674
        let outputs = self.db().fetch_outputs_with_spend_status_at_tip(vec![hash]).await?;
×
675
        let output = match outputs.first() {
×
676
            Some(Some((output, _spent))) => Some(output.clone()),
×
677
            _ => return Err(Error::OutputNotFound),
×
678
        };
679
        Ok(output)
×
680
    }
×
681

682
    async fn get_mempool_fee_per_gram_stats(&self, count: usize) -> Result<Vec<models::FeePerGramStat>, Self::Error> {
×
683
        if count > 20 {
×
684
            return Err(Error::general(anyhow::anyhow!(
×
685
                "count must be less than or equal to 20"
×
686
            )));
×
687
        }
×
688

689
        let metadata = self.db.get_chain_metadata().await?;
×
690
        let stats = self
×
691
            .mempool()
×
692
            .get_fee_per_gram_stats(count, metadata.best_block_height())
×
693
            .await
×
694
            .map_err(Error::general)?;
×
695

696
        Ok(stats)
×
697
    }
×
698
}
699

700
#[cfg(test)]
701
mod tests {
702
    #![allow(clippy::indexing_slicing)]
703
    use tari_common::configuration::Network;
704
    use tari_shutdown::Shutdown;
705

706
    use super::*;
707
    use crate::test_helpers::blockchain::create_new_blockchain_with_network;
708
    fn make_state_machine_handle() -> StateMachineHandle {
2✔
709
        use tokio::sync::{broadcast, watch};
710
        let (state_tx, _state_rx) = broadcast::channel(10);
2✔
711
        let (_status_tx, status_rx) =
2✔
712
            watch::channel(crate::base_node::state_machine_service::states::StatusInfo::new());
2✔
713
        let shutdown = Shutdown::new();
2✔
714
        StateMachineHandle::new(state_tx, status_rx, shutdown.to_signal())
2✔
715
    }
2✔
716

717
    fn make_mempool_handle() -> MempoolHandle {
2✔
718
        use crate::mempool::test_utils::mock::create_mempool_service_mock;
719
        let (handle, _state) = create_mempool_service_mock();
2✔
720
        handle
2✔
721
    }
2✔
722

723
    async fn make_service() -> Service<crate::test_helpers::blockchain::TempDatabase> {
2✔
724
        let db = create_new_blockchain_with_network(Network::LocalNet);
2✔
725
        let adb = AsyncBlockchainDb::from(db);
2✔
726
        let state_machine = make_state_machine_handle();
2✔
727
        let mempool = make_mempool_handle();
2✔
728
        Service::new(adb, state_machine, mempool)
2✔
729
    }
2✔
730

731
    #[tokio::test]
732
    async fn fetch_utxos_start_header_not_found() {
1✔
733
        let service = make_service().await;
1✔
734
        let req = SyncUtxosByBlockRequest {
1✔
735
            start_header_hash: vec![0xAB; 32],
1✔
736
            limit: 4,
1✔
737
            page: 0,
1✔
738
            exclude_spent: false,
1✔
739
            exclude_inputs: false,
1✔
740
            version: 0,
1✔
741
        };
1✔
742
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
743
        match err {
1✔
744
            Error::StartHeaderHashNotFound => {},
1✔
745
            other => panic!("unexpected error: {other:?}"),
1✔
746
        }
1✔
747
    }
1✔
748

749
    #[tokio::test]
750
    async fn fetch_utxos_header_height_mismatch() {
1✔
751
        let service = make_service().await;
1✔
752
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
753
        // page * limit moves start height beyond tip (0)
754
        let req = SyncUtxosByBlockRequest {
1✔
755
            start_header_hash: genesis.hash().to_vec(),
1✔
756
            limit: 1,
1✔
757
            page: 1,
1✔
758
            exclude_spent: false,
1✔
759
            exclude_inputs: false,
1✔
760
            version: 0,
1✔
761
        };
1✔
762
        let err = service.fetch_utxos(req).await.unwrap_err();
1✔
763
        match err {
1✔
764
            Error::HeaderHeightMismatch { .. } => {},
1✔
765
            other => panic!("unexpected error: {other:?}"),
1✔
766
        }
1✔
767
    }
1✔
768

769
    #[tokio::test]
770
    async fn fetch_utxos_paginates_results() {
1✔
771
        use crate::test_helpers::blockchain::create_main_chain;
772

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

777
        // Construct the service over this DB
778
        let adb = AsyncBlockchainDb::from(db);
1✔
779
        let state_machine = make_state_machine_handle();
1✔
780
        let mempool = make_mempool_handle();
1✔
781
        let service = Service::new(adb, state_machine, mempool);
1✔
782

783
        // Use genesis as the start header hash
784
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
785
        let g_hash = genesis.hash().to_vec();
×
786

787
        // Page 0, limit 1: should return only A (height 1) and next header should be B
788
        // genesis block in local net has 0 inputs and outputs
789
        let resp0 = service
×
790
            .fetch_utxos(SyncUtxosByBlockRequest {
×
791
                start_header_hash: g_hash.clone(),
×
792
                limit: 1,
×
793
                page: 0,
×
794
                exclude_spent: false,
×
795
                exclude_inputs: false,
×
796
                version: 0,
×
797
            })
×
798
            .await
×
799
            .expect("fetch_utxos page 0 should succeed");
×
800

801
        assert_eq!(resp0.blocks.len(), 1, "expected exactly one block in first page");
×
802
        assert_eq!(resp0.blocks[0].height, 0, "first page should start at genesis height");
×
803

804
        // Expect next_header_to_scan to be the hash of block A (height 1)
805
        let a_hash = chain.get("A").unwrap().hash().to_vec();
×
806
        assert_eq!(resp0.next_header_to_scan, a_hash, "next header should point to A");
×
807

808
        // Page 1, limit 1: should return only block A (height 1) and next header should be B
809
        let resp1 = service
×
810
            .fetch_utxos(SyncUtxosByBlockRequest {
×
811
                start_header_hash: g_hash.clone(),
×
812
                limit: 1,
×
813
                page: 1,
×
814
                exclude_spent: false,
×
815
                exclude_inputs: false,
×
816
                version: 0,
×
817
            })
×
818
            .await
×
819
            .expect("fetch_utxos page 1 should succeed");
×
820

821
        assert_eq!(resp1.blocks.len(), 1, "expected exactly one block in second page");
×
822
        assert_eq!(resp1.blocks[0].height, 1, "second page should start at height 1 (A)");
×
823

824
        // Expect next_header_to_scan to be the hash of block B (height 2)
825
        let b_hash = chain.get("B").unwrap().hash().to_vec();
×
826
        assert_eq!(resp1.next_header_to_scan, b_hash, "next header should point to B");
×
827

828
        // Page 2, limit 1: should return only block B (height 2) and next header should be C
829
        let resp2 = service
×
830
            .fetch_utxos(SyncUtxosByBlockRequest {
×
831
                start_header_hash: g_hash.clone(),
×
832
                limit: 1,
×
833
                page: 2,
×
834
                exclude_spent: false,
×
835
                exclude_inputs: false,
×
836
                version: 0,
×
837
            })
×
838
            .await
×
839
            .expect("fetch_utxos page 2 should succeed");
×
840

841
        assert_eq!(resp2.blocks.len(), 1, "expected exactly one block in third page");
×
842
        assert_eq!(resp2.blocks[0].height, 2, "third page should start at height 2 (B)");
×
843
        let c_hash = chain.get("C").unwrap().hash().to_vec();
×
844
        assert_eq!(resp2.next_header_to_scan, c_hash, "next header should point to C");
×
845

846
        // Page 3, limit 1: should return only block C (height 3) and next header should be empty (tip reached)
847
        let resp3 = service
×
848
            .fetch_utxos(SyncUtxosByBlockRequest {
×
849
                start_header_hash: g_hash.clone(),
×
850
                limit: 1,
×
851
                page: 3,
×
852
                exclude_spent: false,
×
853
                exclude_inputs: false,
×
854
                version: 0,
×
855
            })
×
856
            .await
×
857
            .expect("fetch_utxos page 3 should succeed");
×
858

859
        assert_eq!(resp3.blocks.len(), 1, "expected exactly one block in fourth page");
×
860
        assert_eq!(resp3.blocks[0].height, 3, "fourth page should start at height 3 (C)");
×
861
        let d_hash = chain.get("D").unwrap().hash().to_vec();
×
862
        assert_eq!(resp3.next_header_to_scan, d_hash, "next header should point to D");
×
863

864
        // Page 4, limit 1: should return only block C (height 3) and next header should be empty (tip reached)
865
        let resp4 = service
×
866
            .fetch_utxos(SyncUtxosByBlockRequest {
×
867
                start_header_hash: g_hash.clone(),
×
868
                limit: 1,
×
869
                page: 4,
×
870
                exclude_spent: false,
×
871
                exclude_inputs: false,
×
872
                version: 0,
×
873
            })
×
874
            .await
×
875
            .expect("fetch_utxos page 3 should succeed");
×
876

877
        assert_eq!(resp4.blocks.len(), 1, "expected exactly one block in fourth page");
×
878
        assert_eq!(resp4.blocks[0].height, 4, "fourth page should start at height 4 (D)");
×
879
        assert!(resp4.next_header_to_scan.is_empty(), "no next header at tip");
×
880
        let resp5 = service
×
881
            .fetch_utxos(SyncUtxosByBlockRequest {
×
882
                start_header_hash: g_hash,
×
883
                limit: 2,
×
884
                page: 0,
×
885
                exclude_spent: false,
×
886
                exclude_inputs: false,
×
887
                version: 0,
×
888
            })
×
889
            .await
×
890
            .expect("fetch_utxos should succeed");
×
891

892
        assert_eq!(resp5.blocks.len(), 2, "expected 2 blocks");
×
893
        assert_eq!(resp5.blocks[0].height, 0, "Should be block (GB)");
×
894
        assert_eq!(resp5.blocks[1].height, 1, "Should be block (A)");
×
895
        let b_hash = chain.get("B").unwrap().hash().to_vec();
×
896
        assert_eq!(resp5.next_header_to_scan, b_hash, "next header should point to B");
×
897
        assert!(resp5.has_next_page, "Should have more pages");
×
898
    }
1✔
899

900
    #[tokio::test]
901
    async fn large_fetch_utxo_paginates_results() {
1✔
902
        use crate::test_helpers::blockchain::create_main_chain;
903

904
        // Build a small chain: GB -> A -> B -> C
905
        let db = create_new_blockchain_with_network(Network::LocalNet);
1✔
906
        let (_names, chain) = create_main_chain(
1✔
907
            &db,
1✔
908
            block_specs!(
1✔
909
                ["1->GB"],
1✔
910
                ["2->1"],
1✔
911
                ["3->2"],
1✔
912
                ["4->3"],
1✔
913
                ["5->4"],
1✔
914
                ["6->5"],
1✔
915
                ["7->6"],
1✔
916
                ["8->7"],
1✔
917
                ["9->8"],
1✔
918
                ["10->9"],
1✔
919
                ["11->10"],
1✔
920
                ["12->11"]
1✔
921
            ),
1✔
922
        );
1✔
923

924
        // Construct the service over this DB
925
        let adb = AsyncBlockchainDb::from(db);
1✔
926
        let state_machine = make_state_machine_handle();
1✔
927
        let mempool = make_mempool_handle();
1✔
928
        let service = Service::new(adb, state_machine, mempool);
1✔
929

930
        // Use genesis as the start header hash
931
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
932
        let g_hash = genesis.hash().to_vec();
×
933

934
        let resp = service
×
935
            .fetch_utxos(SyncUtxosByBlockRequest {
×
936
                start_header_hash: g_hash.clone(),
×
937
                limit: 10,
×
938
                page: 0,
×
939
                exclude_spent: false,
×
940
                exclude_inputs: false,
×
941
                version: 0,
×
942
            })
×
943
            .await
×
944
            .expect("fetch_utxos should succeed");
×
945

946
        assert_eq!(resp.blocks.len(), 10, "expected 10 blocks");
×
947
        assert_eq!(resp.blocks[0].height, 0, "Should be block (0)");
×
948
        assert_eq!(resp.blocks[1].height, 1, "Should be block (1)");
×
949
        assert_eq!(resp.blocks[2].height, 2, "Should be block (2)");
×
950
        assert_eq!(resp.blocks[3].height, 3, "Should be block (3)");
×
951
        assert_eq!(resp.blocks[4].height, 4, "Should be block (4)");
×
952
        assert_eq!(resp.blocks[5].height, 5, "Should be block (5)");
×
953
        assert_eq!(resp.blocks[6].height, 6, "Should be block (6)");
×
954
        assert_eq!(resp.blocks[7].height, 7, "Should be block (7)");
×
955
        assert_eq!(resp.blocks[8].height, 8, "Should be block (8)");
×
956
        assert_eq!(resp.blocks[9].height, 9, "Should be block (9)");
×
957
        let next_hash = chain.get("10").unwrap().hash().to_vec();
×
958
        assert_eq!(resp.next_header_to_scan, next_hash, "next header should point to 10");
×
959
        assert!(resp.has_next_page, "Should have more pages");
×
960
        let resp = service
×
961
            .fetch_utxos(SyncUtxosByBlockRequest {
×
962
                start_header_hash: g_hash,
×
963
                limit: 10,
×
964
                page: 1,
×
965
                exclude_spent: false,
×
966
                exclude_inputs: false,
×
967
                version: 0,
×
968
            })
×
969
            .await
×
970
            .expect("fetch_utxos should succeed");
×
971
        assert_eq!(resp.blocks.len(), 3, "expected 3 blocks");
×
972
        assert_eq!(resp.blocks[0].height, 10, "Should be block (10)");
×
973
        assert_eq!(resp.blocks[1].height, 11, "Should be block (11)");
×
974
        assert_eq!(resp.blocks[2].height, 12, "Should be block (12)");
×
975
        assert!(resp.next_header_to_scan.is_empty(), "Should be empty");
×
976
        assert!(!resp.has_next_page, "Should not have more pages");
×
977
    }
1✔
978

979
    // this will only run and work in esmeralda
980
    #[cfg(tari_target_network_testnet)]
981
    #[tokio::test]
982
    async fn large_utxo_handled_correctly() {
1✔
983
        use crate::test_helpers::blockchain::create_main_chain;
984

985
        // Build a small chain: GB -> A -> B -> C
986
        let db = create_new_blockchain_with_network(Network::Esmeralda);
1✔
987
        let (_names, _chain) = create_main_chain(
1✔
988
            &db,
1✔
989
            block_specs!(
1✔
990
                ["1->GB"],
1✔
991
                ["2->1"],
1✔
992
                ["3->2"],
1✔
993
                ["4->3"],
1✔
994
                ["5->4"],
1✔
995
                ["6->5"],
1✔
996
                ["7->6"],
1✔
997
                ["8->7"],
1✔
998
                ["9->8"],
1✔
999
                ["10->9"],
1✔
1000
            ),
1✔
1001
        );
1✔
1002

1003
        // Construct the service over this DB
1004
        let adb = AsyncBlockchainDb::from(db);
1✔
1005
        let state_machine = make_state_machine_handle();
1✔
1006
        let mempool = make_mempool_handle();
1✔
1007
        let mut service = Service::new(adb, state_machine, mempool);
1✔
1008
        service.max_utxo_chunk_size = 500; // set small chunk size for testing
1✔
1009

1010
        // Use genesis as the start header hash
1011
        let genesis = service.db().fetch_header(0).await.unwrap().unwrap();
1✔
1012
        let g_hash = genesis.hash().to_vec();
×
1013

1014
        let resp = service
×
1015
            .fetch_utxos(SyncUtxosByBlockRequest {
×
1016
                start_header_hash: g_hash.clone(),
×
1017
                limit: 5,
×
1018
                page: 0,
×
1019
                exclude_spent: false,
×
1020
                exclude_inputs: false,
×
1021
                version: 0,
×
1022
            })
×
1023
            .await
×
1024
            .expect("fetch_utxos should succeed");
×
1025

1026
        assert_eq!(resp.blocks.len(), 5, "expected 5 blocks");
×
1027
        assert_eq!(resp.blocks[0].height, 0, "Should be block (0)");
×
1028
        assert_eq!(resp.blocks[1].height, 0, "Should be block (0)");
×
1029
        assert_eq!(resp.blocks[2].height, 1, "Should be block (1)");
×
1030
        assert_eq!(resp.blocks[3].height, 2, "Should be block (2)");
×
1031
        assert_eq!(resp.blocks[4].height, 3, "Should be block (3)");
×
1032
        let header_4 = service.db().fetch_header(4).await.unwrap().unwrap();
×
1033
        assert_eq!(
×
1034
            header_4.hash().to_vec(),
×
1035
            resp.next_header_to_scan,
1036
            "next header should point to 4"
1037
        );
1038
        assert!(!resp.has_next_page, "Should have no more pages");
×
1039
    }
1✔
1040
}
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