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

tari-project / tari / 16123384529

07 Jul 2025 05:11PM UTC coverage: 64.327% (-7.6%) from 71.89%
16123384529

push

github

web-flow
chore: new release v4.9.0-pre.0 (#7289)

Description
---
new release esmeralda

77151 of 119935 relevant lines covered (64.33%)

227108.34 hits per line

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

0.0
/base_layer/core/src/base_node/comms_interface/inbound_handlers.rs
1
// Copyright 2019. The Tari Project
2
//
3
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
4
// following conditions are met:
5
//
6
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
7
// disclaimer.
8
//
9
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
10
// following disclaimer in the documentation and/or other materials provided with the distribution.
11
//
12
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
13
// products derived from this software without specific prior written permission.
14
//
15
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
16
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
20
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22

23
#[cfg(feature = "metrics")]
24
use std::convert::{TryFrom, TryInto};
25
use std::{cmp::max, collections::HashSet, sync::Arc, time::Instant};
26

27
use log::*;
28
use strum_macros::Display;
29
use tari_common_types::types::{BlockHash, FixedHash, HashOutput};
30
use tari_comms::{connectivity::ConnectivityRequester, peer_manager::NodeId};
31
use tari_utilities::hex::Hex;
32
use tokio::sync::RwLock;
33

34
#[cfg(feature = "metrics")]
35
use crate::base_node::metrics;
36
use crate::{
37
    base_node::comms_interface::{
38
        comms_response::ValidatorNodeChange,
39
        error::CommsInterfaceError,
40
        local_interface::BlockEventSender,
41
        FetchMempoolTransactionsResponse,
42
        NodeCommsRequest,
43
        NodeCommsResponse,
44
        OutboundNodeCommsInterface,
45
    },
46
    blocks::{Block, BlockBuilder, BlockHeader, BlockHeaderValidationError, ChainBlock, NewBlock, NewBlockTemplate},
47
    chain_storage::{async_db::AsyncBlockchainDb, BlockAddResult, BlockchainBackend, ChainStorageError},
48
    consensus::{ConsensusConstants, ConsensusManager},
49
    mempool::Mempool,
50
    proof_of_work::{
51
        monero_randomx_difficulty,
52
        randomx_factory::RandomXFactory,
53
        sha3x_difficulty,
54
        tari_randomx_difficulty,
55
        Difficulty,
56
        PowAlgorithm,
57
        PowError,
58
    },
59
    transactions::aggregated_body::AggregateBody,
60
    validation::{helpers, tari_rx_vm_key_height, ValidationError},
61
};
62

63
const LOG_TARGET: &str = "c::bn::comms_interface::inbound_handler";
64
const MAX_REQUEST_BY_BLOCK_HASHES: usize = 100;
65
const MAX_REQUEST_BY_KERNEL_EXCESS_SIGS: usize = 100;
66
const MAX_REQUEST_BY_UTXO_HASHES: usize = 100;
67
const MAX_MEMPOOL_TIMEOUT: u64 = 150;
68

69
/// Events that can be published on the Validated Block Event Stream
70
/// Broadcast is to notify subscribers if this is a valid propagated block event
71
#[derive(Debug, Clone, Display)]
72
pub enum BlockEvent {
73
    ValidBlockAdded(Arc<Block>, BlockAddResult),
74
    AddBlockValidationFailed {
75
        block: Arc<Block>,
76
        source_peer: Option<NodeId>,
77
    },
78
    AddBlockErrored {
79
        block: Arc<Block>,
80
    },
81
    BlockSyncComplete(Arc<ChainBlock>, u64),
82
    BlockSyncRewind(Vec<Arc<ChainBlock>>),
83
}
84

85
/// The InboundNodeCommsInterface is used to handle all received inbound requests from remote nodes.
86
pub struct InboundNodeCommsHandlers<B> {
87
    block_event_sender: BlockEventSender,
88
    blockchain_db: AsyncBlockchainDb<B>,
89
    mempool: Mempool,
90
    consensus_manager: ConsensusManager,
91
    list_of_reconciling_blocks: Arc<RwLock<HashSet<HashOutput>>>,
92
    outbound_nci: OutboundNodeCommsInterface,
93
    connectivity: ConnectivityRequester,
94
    randomx_factory: RandomXFactory,
95
}
96

97
impl<B> InboundNodeCommsHandlers<B>
98
where B: BlockchainBackend + 'static
99
{
100
    /// Construct a new InboundNodeCommsInterface.
101
    pub fn new(
×
102
        block_event_sender: BlockEventSender,
×
103
        blockchain_db: AsyncBlockchainDb<B>,
×
104
        mempool: Mempool,
×
105
        consensus_manager: ConsensusManager,
×
106
        outbound_nci: OutboundNodeCommsInterface,
×
107
        connectivity: ConnectivityRequester,
×
108
        randomx_factory: RandomXFactory,
×
109
    ) -> Self {
×
110
        Self {
×
111
            block_event_sender,
×
112
            blockchain_db,
×
113
            mempool,
×
114
            consensus_manager,
×
115
            list_of_reconciling_blocks: Arc::new(RwLock::new(HashSet::new())),
×
116
            outbound_nci,
×
117
            connectivity,
×
118
            randomx_factory,
×
119
        }
×
120
    }
×
121

122
    /// Handle inbound node comms requests from remote nodes and local services.
123
    #[allow(clippy::too_many_lines)]
124
    pub async fn handle_request(&self, request: NodeCommsRequest) -> Result<NodeCommsResponse, CommsInterfaceError> {
×
125
        trace!(target: LOG_TARGET, "Handling remote request {}", request);
×
126
        match request {
×
127
            NodeCommsRequest::GetChainMetadata => Ok(NodeCommsResponse::ChainMetadata(
128
                self.blockchain_db.get_chain_metadata().await?,
×
129
            )),
130
            NodeCommsRequest::GetTargetDifficultyNextBlock(algo) => {
×
131
                let header = self.blockchain_db.fetch_tip_header().await?;
×
132
                let constants = self.consensus_manager.consensus_constants(header.header().height);
×
133
                let target_difficulty = self
×
134
                    .get_target_difficulty_for_next_block(algo, constants, *header.hash())
×
135
                    .await?;
×
136
                Ok(NodeCommsResponse::TargetDifficulty(target_difficulty))
×
137
            },
138
            NodeCommsRequest::FetchHeaders(range) => {
×
139
                let headers = self.blockchain_db.fetch_chain_headers(range).await?;
×
140
                Ok(NodeCommsResponse::BlockHeaders(headers))
×
141
            },
142
            NodeCommsRequest::FetchHeadersByHashes(block_hashes) => {
×
143
                if block_hashes.len() > MAX_REQUEST_BY_BLOCK_HASHES {
×
144
                    return Err(CommsInterfaceError::InvalidRequest {
×
145
                        request: "FetchHeadersByHashes",
×
146
                        details: format!(
×
147
                            "Exceeded maximum block hashes request (max: {}, got:{})",
×
148
                            MAX_REQUEST_BY_BLOCK_HASHES,
×
149
                            block_hashes.len()
×
150
                        ),
×
151
                    });
×
152
                }
×
153
                let mut block_headers = Vec::with_capacity(block_hashes.len());
×
154
                for block_hash in block_hashes {
×
155
                    let block_hex = block_hash.to_hex();
×
156
                    match self.blockchain_db.fetch_chain_header_by_block_hash(block_hash).await? {
×
157
                        Some(block_header) => {
×
158
                            block_headers.push(block_header);
×
159
                        },
×
160
                        None => {
161
                            error!(target: LOG_TARGET, "Could not fetch headers with hashes:{}", block_hex);
×
162
                            return Err(CommsInterfaceError::InternalError(format!(
×
163
                                "Could not fetch headers with hashes:{}",
×
164
                                block_hex
×
165
                            )));
×
166
                        },
167
                    }
168
                }
169
                Ok(NodeCommsResponse::BlockHeaders(block_headers))
×
170
            },
171
            NodeCommsRequest::FetchMatchingUtxos(utxo_hashes) => {
×
172
                let mut res = Vec::with_capacity(utxo_hashes.len());
×
173
                for (output, spent) in (self
×
174
                    .blockchain_db
×
175
                    .fetch_outputs_with_spend_status_at_tip(utxo_hashes)
×
176
                    .await?)
×
177
                    .into_iter()
×
178
                    .flatten()
×
179
                {
180
                    if !spent {
×
181
                        res.push(output);
×
182
                    }
×
183
                }
184
                Ok(NodeCommsResponse::TransactionOutputs(res))
×
185
            },
186
            NodeCommsRequest::FetchMatchingBlocks { range, compact } => {
×
187
                let blocks = self.blockchain_db.fetch_blocks(range, compact).await?;
×
188
                Ok(NodeCommsResponse::HistoricalBlocks(blocks))
×
189
            },
190
            NodeCommsRequest::FetchBlocksByKernelExcessSigs(excess_sigs) => {
×
191
                if excess_sigs.len() > MAX_REQUEST_BY_KERNEL_EXCESS_SIGS {
×
192
                    return Err(CommsInterfaceError::InvalidRequest {
×
193
                        request: "FetchBlocksByKernelExcessSigs",
×
194
                        details: format!(
×
195
                            "Exceeded maximum number of kernel excess sigs in request (max: {}, got:{})",
×
196
                            MAX_REQUEST_BY_KERNEL_EXCESS_SIGS,
×
197
                            excess_sigs.len()
×
198
                        ),
×
199
                    });
×
200
                }
×
201
                let mut blocks = Vec::with_capacity(excess_sigs.len());
×
202
                for sig in excess_sigs {
×
203
                    let sig_hex = sig.get_signature().to_hex();
×
204
                    debug!(
×
205
                        target: LOG_TARGET,
×
206
                        "A peer has requested a block with kernel with sig {}", sig_hex
×
207
                    );
208
                    match self.blockchain_db.fetch_block_with_kernel(sig).await {
×
209
                        Ok(Some(block)) => blocks.push(block),
×
210
                        Ok(None) => warn!(
×
211
                            target: LOG_TARGET,
×
212
                            "Could not provide requested block containing kernel with sig {} to peer because not \
×
213
                             stored",
×
214
                            sig_hex
215
                        ),
216
                        Err(e) => warn!(
×
217
                            target: LOG_TARGET,
×
218
                            "Could not provide requested block containing kernel with sig {} to peer because: {}",
×
219
                            sig_hex,
220
                            e
221
                        ),
222
                    }
223
                }
224
                Ok(NodeCommsResponse::HistoricalBlocks(blocks))
×
225
            },
226
            NodeCommsRequest::FetchBlocksByUtxos(commitments) => {
×
227
                if commitments.len() > MAX_REQUEST_BY_UTXO_HASHES {
×
228
                    return Err(CommsInterfaceError::InvalidRequest {
×
229
                        request: "FetchBlocksByUtxos",
×
230
                        details: format!(
×
231
                            "Exceeded maximum number of utxo hashes in request (max: {}, got:{})",
×
232
                            MAX_REQUEST_BY_UTXO_HASHES,
×
233
                            commitments.len()
×
234
                        ),
×
235
                    });
×
236
                }
×
237
                let mut blocks = Vec::with_capacity(commitments.len());
×
238
                for commitment in commitments {
×
239
                    let commitment_hex = commitment.to_hex();
×
240
                    debug!(
×
241
                        target: LOG_TARGET,
×
242
                        "A peer has requested a block with commitment {}", commitment_hex,
×
243
                    );
244
                    match self.blockchain_db.fetch_block_with_utxo(commitment).await {
×
245
                        Ok(Some(block)) => blocks.push(block),
×
246
                        Ok(None) => warn!(
×
247
                            target: LOG_TARGET,
×
248
                            "Could not provide requested block with commitment {} to peer because not stored",
×
249
                            commitment_hex,
250
                        ),
251
                        Err(e) => warn!(
×
252
                            target: LOG_TARGET,
×
253
                            "Could not provide requested block with commitment {} to peer because: {}",
×
254
                            commitment_hex,
255
                            e
256
                        ),
257
                    }
258
                }
259
                Ok(NodeCommsResponse::HistoricalBlocks(blocks))
×
260
            },
261
            NodeCommsRequest::GetHeaderByHash(hash) => {
×
262
                let header = self.blockchain_db.fetch_chain_header_by_block_hash(hash).await?;
×
263
                Ok(NodeCommsResponse::BlockHeader(header))
×
264
            },
265
            NodeCommsRequest::GetBlockByHash(hash) => {
×
266
                let block = self.blockchain_db.fetch_block_by_hash(hash, false).await?;
×
267
                Ok(NodeCommsResponse::HistoricalBlock(Box::new(block)))
×
268
            },
269
            NodeCommsRequest::GetNewBlockTemplate(request) => {
×
270
                let best_block_header = self.blockchain_db.fetch_tip_header().await?;
×
271
                let mut last_seen_hash = self.mempool.get_last_seen_hash().await?;
×
272
                let mut is_mempool_synced = false;
×
273
                let start = Instant::now();
×
274
                // this will wait a max of 150ms by default before returning anyway with a potential broken template
275
                // We need to ensure the mempool has seen the latest base node height before we can be confident the
276
                // template is correct
277
                while !is_mempool_synced && start.elapsed().as_millis() < MAX_MEMPOOL_TIMEOUT.into() {
×
278
                    if best_block_header.hash() == &last_seen_hash || last_seen_hash == FixedHash::default() {
×
279
                        is_mempool_synced = true;
×
280
                    } else {
×
281
                        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
×
282
                        last_seen_hash = self.mempool.get_last_seen_hash().await?;
×
283
                    }
284
                }
285

286
                if !is_mempool_synced {
×
287
                    warn!(
×
288
                        target: LOG_TARGET,
×
289
                        "Mempool out of sync - last seen hash '{}' does not match the tip hash '{}'. This condition \
×
290
                         should auto correct with the next block template request",
×
291
                        last_seen_hash, best_block_header.hash()
×
292
                    );
293
                }
×
294
                let mut header = BlockHeader::from_previous(best_block_header.header());
×
295
                let constants = self.consensus_manager.consensus_constants(header.height);
×
296
                header.version = constants.blockchain_version();
×
297
                header.pow.pow_algo = request.algo;
×
298

×
299
                let constants_weight = constants.max_block_transaction_weight();
×
300
                let asking_weight = if request.max_weight > constants_weight || request.max_weight == 0 {
×
301
                    constants_weight
×
302
                } else {
303
                    request.max_weight
×
304
                };
305

306
                debug!(
×
307
                    target: LOG_TARGET,
×
308
                    "Fetching transactions with a maximum weight of {} for the template", asking_weight
×
309
                );
310
                let transactions = self
×
311
                    .mempool
×
312
                    .retrieve(asking_weight)
×
313
                    .await?
×
314
                    .into_iter()
×
315
                    .map(|tx| Arc::try_unwrap(tx).unwrap_or_else(|tx| (*tx).clone()))
×
316
                    .collect::<Vec<_>>();
×
317

×
318
                debug!(
×
319
                    target: LOG_TARGET,
×
320
                    "Adding {} transaction(s) to new block template",
×
321
                    transactions.len(),
×
322
                );
323

324
                let prev_hash = header.prev_hash;
×
325
                let height = header.height;
×
326

×
327
                let block = header.into_builder().with_transactions(transactions).build();
×
328
                let block_hash = block.hash();
×
329
                let block_template = NewBlockTemplate::from_block(
×
330
                    block,
×
331
                    self.get_target_difficulty_for_next_block(request.algo, constants, prev_hash)
×
332
                        .await?,
×
333
                    self.consensus_manager.get_block_reward_at(height),
×
334
                    is_mempool_synced,
×
335
                )?;
×
336

337
                debug!(target: LOG_TARGET,
×
338
                    "New block template requested and prepared at height: #{}, target difficulty: {}, block hash: `{}`, weight: {}, {}",
×
339
                    block_template.header.height,
×
340
                    block_template.target_difficulty,
×
341
                    block_hash.to_hex(),
×
342
                    block_template
×
343
                        .body
×
344
                        .calculate_weight(constants.transaction_weight_params())
×
345
                        .map_err(|e| CommsInterfaceError::InternalError(e.to_string()))?,
×
346
                    block_template.body.to_counts_string()
×
347
                );
348

349
                Ok(NodeCommsResponse::NewBlockTemplate(block_template))
×
350
            },
351
            NodeCommsRequest::GetNewBlock(block_template) => {
×
352
                let height = block_template.header.height;
×
353
                let target_difficulty = block_template.target_difficulty;
×
354
                let block = self.blockchain_db.prepare_new_block(block_template).await?;
×
355
                let constants = self.consensus_manager.consensus_constants(block.header.height);
×
356
                debug!(target: LOG_TARGET,
×
357
                    "Prepared block: #{}, target difficulty: {}, block hash: `{}`, weight: {}, {}",
×
358
                    height,
×
359
                    target_difficulty,
×
360
                    block.hash().to_hex(),
×
361
                    block
×
362
                        .body
×
363
                        .calculate_weight(constants.transaction_weight_params())
×
364
                        .map_err(|e| CommsInterfaceError::InternalError(e.to_string()))?,
×
365
                    block.body.to_counts_string()
×
366
                );
367
                Ok(NodeCommsResponse::NewBlock {
×
368
                    success: true,
×
369
                    error: None,
×
370
                    block: Some(block),
×
371
                })
×
372
            },
373
            NodeCommsRequest::GetBlockFromAllChains(hash) => {
×
374
                let block_hex = hash.to_hex();
×
375
                debug!(
×
376
                    target: LOG_TARGET,
×
377
                    "A peer has requested a block with hash {}", block_hex
×
378
                );
379

380
                #[allow(clippy::blocks_in_conditions)]
381
                let maybe_block = match self
×
382
                    .blockchain_db
×
383
                    .fetch_block_by_hash(hash, true)
×
384
                    .await
×
385
                    .unwrap_or_else(|e| {
×
386
                        warn!(
×
387
                            target: LOG_TARGET,
×
388
                            "Could not provide requested block {} to peer because: {}",
×
389
                            block_hex,
390
                            e
391
                        );
392

393
                        None
×
394
                    }) {
×
395
                    None => self.blockchain_db.fetch_orphan(hash).await.map_or_else(
×
396
                        |e| {
×
397
                            warn!(
×
398
                                target: LOG_TARGET,
×
399
                                "Could not provide requested block {} to peer because: {}", block_hex, e,
×
400
                            );
401

402
                            None
×
403
                        },
×
404
                        Some,
×
405
                    ),
×
406
                    Some(block) => Some(block.into_block()),
×
407
                };
408

409
                Ok(NodeCommsResponse::Block(Box::new(maybe_block)))
×
410
            },
411
            NodeCommsRequest::FetchKernelByExcessSig(signature) => {
×
412
                let kernels = match self.blockchain_db.fetch_kernel_by_excess_sig(signature).await {
×
413
                    Ok(Some((kernel, _))) => vec![kernel],
×
414
                    Ok(None) => vec![],
×
415
                    Err(err) => {
×
416
                        error!(target: LOG_TARGET, "Could not fetch kernel {}", err);
×
417
                        return Err(err.into());
×
418
                    },
419
                };
420

421
                Ok(NodeCommsResponse::TransactionKernels(kernels))
×
422
            },
423
            NodeCommsRequest::FetchMempoolTransactionsByExcessSigs { excess_sigs } => {
×
424
                let (transactions, not_found) = self.mempool.retrieve_by_excess_sigs(excess_sigs).await?;
×
425
                Ok(NodeCommsResponse::FetchMempoolTransactionsByExcessSigsResponse(
×
426
                    FetchMempoolTransactionsResponse {
×
427
                        transactions,
×
428
                        not_found,
×
429
                    },
×
430
                ))
×
431
            },
432
            NodeCommsRequest::FetchValidatorNodesKeys {
433
                height,
×
434
                validator_network,
×
435
            } => {
436
                let active_validator_nodes = self
×
437
                    .blockchain_db
×
438
                    .fetch_active_validator_nodes(height, validator_network)
×
439
                    .await?;
×
440
                Ok(NodeCommsResponse::FetchValidatorNodesKeysResponse(
×
441
                    active_validator_nodes,
×
442
                ))
×
443
            },
444
            NodeCommsRequest::GetValidatorNode {
445
                sidechain_id,
×
446
                public_key,
×
447
            } => {
448
                let vn = self.blockchain_db.get_validator_node(sidechain_id, public_key).await?;
×
449
                Ok(NodeCommsResponse::GetValidatorNode(vn))
×
450
            },
451
            NodeCommsRequest::FetchTemplateRegistrations {
452
                start_height,
×
453
                end_height,
×
454
            } => {
455
                let template_registrations = self
×
456
                    .blockchain_db
×
457
                    .fetch_template_registrations(start_height..=end_height)
×
458
                    .await?;
×
459
                Ok(NodeCommsResponse::FetchTemplateRegistrationsResponse(
×
460
                    template_registrations,
×
461
                ))
×
462
            },
463
            NodeCommsRequest::FetchUnspentUtxosInBlock { block_hash } => {
×
464
                let utxos = self.blockchain_db.fetch_outputs_in_block(block_hash).await?;
×
465
                Ok(NodeCommsResponse::TransactionOutputs(utxos))
×
466
            },
467
            NodeCommsRequest::FetchMinedInfoByPayRef(payref) => {
×
468
                let output_info = self.blockchain_db.fetch_mined_info_by_payref(payref).await?;
×
469
                Ok(NodeCommsResponse::MinedInfo(output_info))
×
470
            },
471
            NodeCommsRequest::FetchMinedInfoByOutputHash(output_hash) => {
×
472
                let output_info = self.blockchain_db.fetch_mined_info_by_output_hash(output_hash).await?;
×
473
                Ok(NodeCommsResponse::MinedInfo(output_info))
×
474
            },
475
            NodeCommsRequest::FetchOutputMinedInfo(output_hash) => {
×
476
                let output_info = self.blockchain_db.fetch_output(output_hash).await?;
×
477
                Ok(NodeCommsResponse::OutputMinedInfo(output_info))
×
478
            },
479
            NodeCommsRequest::CheckOutputSpentStatus(output_hash) => {
×
480
                let input_info = self.blockchain_db.fetch_input(output_hash).await?;
×
481
                Ok(NodeCommsResponse::InputMinedInfo(input_info))
×
482
            },
483
            NodeCommsRequest::FetchValidatorNodeChanges { epoch, sidechain_id } => {
×
484
                let added_validators = self
×
485
                    .blockchain_db
×
486
                    .fetch_validators_activating_in_epoch(sidechain_id.clone(), epoch)
×
487
                    .await?;
×
488

489
                let exit_validators = self
×
490
                    .blockchain_db
×
491
                    .fetch_validators_exiting_in_epoch(sidechain_id.clone(), epoch)
×
492
                    .await?;
×
493

494
                info!(
×
495
                    target: LOG_TARGET,
×
496
                    "Fetched {} validators activating and {} validators exiting in epoch {}",
×
497
                    added_validators.len(),
×
498
                    exit_validators.len(),
×
499
                    epoch,
500
                );
501

502
                let mut node_changes = Vec::with_capacity(added_validators.len() + exit_validators.len());
×
503

×
504
                node_changes.extend(added_validators.into_iter().map(|vn| ValidatorNodeChange::Add {
×
505
                    registration: vn.original_registration.into(),
×
506
                    activation_epoch: vn.activation_epoch,
×
507
                    minimum_value_promise: vn.minimum_value_promise,
×
508
                    shard_key: vn.shard_key,
×
509
                }));
×
510

×
511
                node_changes.extend(exit_validators.into_iter().map(|vn| ValidatorNodeChange::Remove {
×
512
                    public_key: vn.public_key,
×
513
                }));
×
514

×
515
                Ok(NodeCommsResponse::FetchValidatorNodeChangesResponse(node_changes))
×
516
            },
517
        }
518
    }
×
519

520
    /// Handles a `NewBlock` message. Only a single `NewBlock` message can be handled at once to prevent extraneous
521
    /// requests for the full block.
522
    /// This may (asynchronously) block until the other request(s) complete or time out and so should typically be
523
    /// executed in a dedicated task.
524
    pub async fn handle_new_block_message(
×
525
        &mut self,
×
526
        new_block: NewBlock,
×
527
        source_peer: NodeId,
×
528
    ) -> Result<(), CommsInterfaceError> {
×
529
        let block_hash = new_block.header.hash();
×
530

×
531
        if self.blockchain_db.inner().is_add_block_disabled() {
×
532
            info!(
×
533
                target: LOG_TARGET,
×
534
                "Ignoring block message ({}) because add_block is locked",
×
535
                block_hash.to_hex()
×
536
            );
537
            return Ok(());
×
538
        }
×
539

×
540
        // Lets check if the block exists before we try and ask for a complete block
×
541
        if self.check_exists_and_not_bad_block(block_hash).await? {
×
542
            return Ok(());
×
543
        }
×
544

×
545
        // lets check that the difficulty at least matches 50% of the tip header. The max difficulty drop is 16%, thus
×
546
        // 50% is way more than that and in order to attack the node, you need 50% of the mining power. We cannot check
×
547
        // the target difficulty as orphan blocks dont have a target difficulty. All we care here is that bad
×
548
        // blocks are not free to make, and that they are more expensive to make then they are to validate. As
×
549
        // soon as a block can be linked to the main chain, a proper full proof of work check will
×
550
        // be done before any other validation.
×
551
        self.check_min_block_difficulty(&new_block).await?;
×
552

553
        {
554
            // we use a double lock to make sure we can only reconcile one unique block at a time. We may receive the
555
            // same block from multiple peer near simultaneously. We should only reconcile each unique block once.
556
            let read_lock = self.list_of_reconciling_blocks.read().await;
×
557
            if read_lock.contains(&block_hash) {
×
558
                debug!(
×
559
                    target: LOG_TARGET,
×
560
                    "Block with hash `{}` is already being reconciled",
×
561
                    block_hash.to_hex()
×
562
                );
563
                return Ok(());
×
564
            }
×
565
        }
566
        {
567
            let mut write_lock = self.list_of_reconciling_blocks.write().await;
×
568
            if self.check_exists_and_not_bad_block(block_hash).await? {
×
569
                return Ok(());
×
570
            }
×
571

×
572
            if !write_lock.insert(block_hash) {
×
573
                debug!(
×
574
                    target: LOG_TARGET,
×
575
                    "Block with hash `{}` is already being reconciled",
×
576
                    block_hash.to_hex()
×
577
                );
578
                return Ok(());
×
579
            }
×
580
        }
×
581

×
582
        debug!(
×
583
            target: LOG_TARGET,
×
584
            "Block with hash `{}` is unknown. Constructing block from known mempool transactions / requesting missing \
×
585
             transactions from peer '{}'.",
×
586
            block_hash.to_hex(),
×
587
            source_peer
588
        );
589

590
        let result = self.reconcile_and_add_block(source_peer.clone(), new_block).await;
×
591

592
        {
593
            let mut write_lock = self.list_of_reconciling_blocks.write().await;
×
594
            write_lock.remove(&block_hash);
×
595
        }
×
596
        result?;
×
597
        Ok(())
×
598
    }
×
599

600
    async fn check_min_block_difficulty(&self, new_block: &NewBlock) -> Result<(), CommsInterfaceError> {
×
601
        let constants = self.consensus_manager.consensus_constants(new_block.header.height);
×
602
        let gen_hash = *self.consensus_manager.get_genesis_block().hash();
×
603
        let mut min_difficulty = constants.min_pow_difficulty(new_block.header.pow.pow_algo);
×
604
        let mut header = self.blockchain_db.fetch_last_chain_header().await?;
×
605
        loop {
606
            if new_block.header.pow_algo() == header.header().pow_algo() {
×
607
                min_difficulty = max(
×
608
                    header
×
609
                        .accumulated_data()
×
610
                        .target_difficulty
×
611
                        .checked_div_u64(2)
×
612
                        .unwrap_or(min_difficulty),
×
613
                    min_difficulty,
×
614
                );
×
615
                break;
×
616
            }
×
617
            if header.height() == 0 {
×
618
                break;
×
619
            }
×
620
            // we have not reached gen block, and the pow algo does not match, so lets go further back
621
            header = self
×
622
                .blockchain_db
×
623
                .fetch_chain_header(header.height().saturating_sub(1))
×
624
                .await?;
×
625
        }
626
        let achieved = match new_block.header.pow_algo() {
×
627
            PowAlgorithm::RandomXM => monero_randomx_difficulty(
×
628
                &new_block.header,
×
629
                &self.randomx_factory,
×
630
                &gen_hash,
×
631
                &self.consensus_manager,
×
632
            )?,
×
633
            PowAlgorithm::Sha3x => sha3x_difficulty(&new_block.header)?,
×
634
            PowAlgorithm::RandomXT => {
635
                let vm_key = *self
×
636
                    .blockchain_db
×
637
                    .fetch_chain_header(tari_rx_vm_key_height(header.height()))
×
638
                    .await?
×
639
                    .hash();
×
640
                tari_randomx_difficulty(&new_block.header, &self.randomx_factory, &vm_key)?
×
641
            },
642
        };
643
        if achieved < min_difficulty {
×
644
            return Err(CommsInterfaceError::InvalidBlockHeader(
×
645
                BlockHeaderValidationError::ProofOfWorkError(PowError::AchievedDifficultyBelowMin),
×
646
            ));
×
647
        }
×
648
        Ok(())
×
649
    }
×
650

651
    async fn check_exists_and_not_bad_block(&self, block: FixedHash) -> Result<bool, CommsInterfaceError> {
×
652
        if self.blockchain_db.chain_header_or_orphan_exists(block).await? {
×
653
            debug!(
×
654
                target: LOG_TARGET,
×
655
                "Block with hash `{}` already stored",
×
656
                block.to_hex()
×
657
            );
658
            return Ok(true);
×
659
        }
×
660
        let (is_bad_block, reason) = self.blockchain_db.bad_block_exists(block).await?;
×
661
        if is_bad_block {
×
662
            debug!(
×
663
                target: LOG_TARGET,
×
664
                "Block with hash `{}` already validated as a bad block due to `{}`",
×
665
                block.to_hex(), reason
×
666
            );
667
            return Err(CommsInterfaceError::ChainStorageError(
×
668
                ChainStorageError::ValidationError {
×
669
                    source: ValidationError::BadBlockFound {
×
670
                        hash: block.to_hex(),
×
671
                        reason,
×
672
                    },
×
673
                },
×
674
            ));
×
675
        }
×
676
        Ok(false)
×
677
    }
×
678

679
    async fn reconcile_and_add_block(
×
680
        &mut self,
×
681
        source_peer: NodeId,
×
682
        new_block: NewBlock,
×
683
    ) -> Result<(), CommsInterfaceError> {
×
684
        let block = self.reconcile_block(source_peer.clone(), new_block).await?;
×
685
        self.handle_block(block, Some(source_peer)).await?;
×
686
        Ok(())
×
687
    }
×
688

689
    #[allow(clippy::too_many_lines)]
690
    async fn reconcile_block(
×
691
        &mut self,
×
692
        source_peer: NodeId,
×
693
        new_block: NewBlock,
×
694
    ) -> Result<Block, CommsInterfaceError> {
×
695
        let NewBlock {
×
696
            header,
×
697
            coinbase_kernels,
×
698
            coinbase_outputs,
×
699
            kernel_excess_sigs: excess_sigs,
×
700
        } = new_block;
×
701
        // If the block is empty, we dont have to ask for the block, as we already have the full block available
×
702
        // to us.
×
703
        if excess_sigs.is_empty() {
×
704
            let block = BlockBuilder::new(header.version)
×
705
                .add_outputs(coinbase_outputs)
×
706
                .add_kernels(coinbase_kernels)
×
707
                .with_header(header)
×
708
                .build();
×
709
            return Ok(block);
×
710
        }
×
711

×
712
        let block_hash = header.hash();
×
713
        // We check the current tip and orphan status of the block because we cannot guarantee that mempool state is
714
        // correct and the mmr root calculation is only valid if the block is building on the tip.
715
        let current_meta = self.blockchain_db.get_chain_metadata().await?;
×
716
        if header.prev_hash != *current_meta.best_block_hash() {
×
717
            debug!(
×
718
                target: LOG_TARGET,
×
719
                "Orphaned block #{}: ({}), current tip is: #{} ({}). We need to fetch the complete block from peer: \
×
720
                 ({})",
×
721
                header.height,
×
722
                block_hash.to_hex(),
×
723
                current_meta.best_block_height(),
×
724
                current_meta.best_block_hash().to_hex(),
×
725
                source_peer,
726
            );
727
            #[allow(clippy::cast_possible_wrap)]
728
            #[cfg(feature = "metrics")]
729
            metrics::compact_block_tx_misses(header.height).set(excess_sigs.len() as i64);
×
730
            let block = self.request_full_block_from_peer(source_peer, block_hash).await?;
×
731
            return Ok(block);
×
732
        }
×
733

734
        // We know that the block is neither and orphan or a coinbase, so lets ask our mempool for the transactions
735
        let (known_transactions, missing_excess_sigs) = self.mempool.retrieve_by_excess_sigs(excess_sigs).await?;
×
736
        let known_transactions = known_transactions.into_iter().map(|tx| (*tx).clone()).collect();
×
737

×
738
        #[allow(clippy::cast_possible_wrap)]
×
739
        #[cfg(feature = "metrics")]
×
740
        metrics::compact_block_tx_misses(header.height).set(missing_excess_sigs.len() as i64);
×
741

×
742
        let mut builder = BlockBuilder::new(header.version)
×
743
            .add_outputs(coinbase_outputs)
×
744
            .add_kernels(coinbase_kernels)
×
745
            .with_transactions(known_transactions);
×
746

×
747
        if missing_excess_sigs.is_empty() {
×
748
            debug!(
×
749
                target: LOG_TARGET,
×
750
                "All transactions for block #{} ({}) found in mempool",
×
751
                header.height,
×
752
                block_hash.to_hex()
×
753
            );
754
        } else {
755
            debug!(
×
756
                target: LOG_TARGET,
×
757
                "Requesting {} unknown transaction(s) from peer '{}'.",
×
758
                missing_excess_sigs.len(),
×
759
                source_peer
760
            );
761

762
            let FetchMempoolTransactionsResponse {
763
                transactions,
×
764
                not_found,
×
765
            } = self
×
766
                .outbound_nci
×
767
                .request_transactions_by_excess_sig(source_peer.clone(), missing_excess_sigs)
×
768
                .await?;
×
769

770
            // Add returned transactions to unconfirmed pool
771
            if !transactions.is_empty() {
×
772
                self.mempool.insert_all(transactions.clone()).await?;
×
773
            }
×
774

775
            if !not_found.is_empty() {
×
776
                warn!(
×
777
                    target: LOG_TARGET,
×
778
                    "Peer {} was not able to return all transactions for block #{} ({}). {} transaction(s) not found. \
×
779
                     Requesting full block.",
×
780
                    source_peer,
×
781
                    header.height,
×
782
                    block_hash.to_hex(),
×
783
                    not_found.len()
×
784
                );
785

786
                #[cfg(feature = "metrics")]
787
                metrics::compact_block_full_misses(header.height).inc();
×
788
                let block = self.request_full_block_from_peer(source_peer, block_hash).await?;
×
789
                return Ok(block);
×
790
            }
×
791

×
792
            builder = builder.with_transactions(
×
793
                transactions
×
794
                    .into_iter()
×
795
                    .map(|tx| Arc::try_unwrap(tx).unwrap_or_else(|tx| (*tx).clone()))
×
796
                    .collect(),
×
797
            );
×
798
        }
×
799

800
        // NB: Add the header last because `with_transactions` etc updates the current header, but we have the final one
801
        // already
802
        builder = builder.with_header(header.clone());
×
803
        let block = builder.build();
×
804

805
        // Perform a sanity check on the reconstructed block, if the MMR roots don't match then it's possible one or
806
        // more transactions in our mempool had the same excess/signature for a *different* transaction.
807
        // This is extremely unlikely, but still possible. In case of a mismatch, request the full block from the peer.
808
        let (block, mmr_roots) = match self.blockchain_db.calculate_mmr_roots(block).await {
×
809
            Err(_) => {
810
                let block = self.request_full_block_from_peer(source_peer, block_hash).await?;
×
811
                return Ok(block);
×
812
            },
813
            Ok(v) => v,
×
814
        };
815
        if let Err(e) = helpers::check_mmr_roots(&header, &mmr_roots) {
×
816
            warn!(
×
817
                target: LOG_TARGET,
×
818
                "Reconstructed block #{} ({}) failed MMR check validation!. Requesting full block. Error: {}",
×
819
                header.height,
×
820
                block_hash.to_hex(),
×
821
                e,
822
            );
823

824
            #[cfg(feature = "metrics")]
825
            metrics::compact_block_mmr_mismatch(header.height).inc();
×
826
            let block = self.request_full_block_from_peer(source_peer, block_hash).await?;
×
827
            return Ok(block);
×
828
        }
×
829

×
830
        Ok(block)
×
831
    }
×
832

833
    async fn request_full_block_from_peer(
×
834
        &mut self,
×
835
        source_peer: NodeId,
×
836
        block_hash: BlockHash,
×
837
    ) -> Result<Block, CommsInterfaceError> {
×
838
        match self
×
839
            .outbound_nci
×
840
            .request_blocks_by_hashes_from_peer(block_hash, Some(source_peer.clone()))
×
841
            .await
×
842
        {
843
            Ok(Some(block)) => Ok(block),
×
844
            Ok(None) => {
845
                debug!(
×
846
                    target: LOG_TARGET,
×
847
                    "Peer `{}` failed to return the block that was requested.", source_peer
×
848
                );
849
                Err(CommsInterfaceError::InvalidPeerResponse(format!(
×
850
                    "Invalid response from peer `{}`: Peer failed to provide the block that was propagated",
×
851
                    source_peer
×
852
                )))
×
853
            },
854
            Err(CommsInterfaceError::UnexpectedApiResponse) => {
855
                debug!(
×
856
                    target: LOG_TARGET,
×
857
                    "Peer `{}` sent unexpected API response.", source_peer
×
858
                );
859
                Err(CommsInterfaceError::UnexpectedApiResponse)
×
860
            },
861
            Err(e) => Err(e),
×
862
        }
863
    }
×
864

865
    /// Handle inbound blocks from remote nodes and local services.
866
    ///
867
    /// ## Arguments
868
    /// block - the block to store
869
    /// new_block_msg - propagate this new block message
870
    /// source_peer - the peer that sent this new block message, or None if the block was generated by a local miner
871
    pub async fn handle_block(
×
872
        &mut self,
×
873
        block: Block,
×
874
        source_peer: Option<NodeId>,
×
875
    ) -> Result<BlockHash, CommsInterfaceError> {
×
876
        let block_hash = block.hash();
×
877
        let block_height = block.header.height;
×
878

×
879
        info!(
×
880
            target: LOG_TARGET,
×
881
            "Block #{} ({}) received from {}",
×
882
            block_height,
×
883
            block_hash.to_hex(),
×
884
            source_peer
×
885
                .as_ref()
×
886
                .map(|p| format!("remote peer: {}", p))
×
887
                .unwrap_or_else(|| "local services".to_string())
×
888
        );
889
        debug!(target: LOG_TARGET, "Incoming block: {}", block);
×
890
        let timer = Instant::now();
×
891
        let block = self.hydrate_block(block).await?;
×
892

893
        let add_block_result = self.blockchain_db.add_block(block.clone()).await;
×
894
        // Create block event on block event stream
895
        match add_block_result {
×
896
            Ok(block_add_result) => {
×
897
                debug!(
×
898
                    target: LOG_TARGET,
×
899
                    "Block #{} ({}) added ({}) to blockchain in {:.2?}",
×
900
                    block_height,
×
901
                    block_hash.to_hex(),
×
902
                    block_add_result,
×
903
                    timer.elapsed()
×
904
                );
905

906
                let should_propagate = match &block_add_result {
×
907
                    BlockAddResult::Ok(_) => true,
×
908
                    BlockAddResult::BlockExists => false,
×
909
                    BlockAddResult::OrphanBlock => false,
×
910
                    BlockAddResult::ChainReorg { .. } => true,
×
911
                };
912

913
                #[cfg(feature = "metrics")]
914
                self.update_block_result_metrics(&block_add_result).await?;
×
915

916
                self.publish_block_event(BlockEvent::ValidBlockAdded(block.clone(), block_add_result));
×
917

×
918
                if should_propagate {
×
919
                    debug!(
×
920
                        target: LOG_TARGET,
×
921
                        "Propagate block ({}) to network.",
×
922
                        block_hash.to_hex()
×
923
                    );
924
                    let exclude_peers = source_peer.into_iter().collect();
×
925
                    let new_block_msg = NewBlock::from(&*block);
×
926
                    if let Err(e) = self.outbound_nci.propagate_block(new_block_msg, exclude_peers).await {
×
927
                        warn!(
×
928
                            target: LOG_TARGET,
×
929
                            "Failed to propagate block ({}) to network: {}.",
×
930
                            block_hash.to_hex(), e
×
931
                        );
932
                    }
×
933
                }
×
934
                Ok(block_hash)
×
935
            },
936

937
            Err(e @ ChainStorageError::ValidationError { .. }) => {
×
938
                #[cfg(feature = "metrics")]
×
939
                {
×
940
                    let block_hash = block.hash();
×
941
                    metrics::rejected_blocks(block.header.height, &block_hash).inc();
×
942
                }
×
943
                warn!(
×
944
                    target: LOG_TARGET,
×
945
                    "Peer {} sent an invalid block: {}",
×
946
                    source_peer
×
947
                        .as_ref()
×
948
                        .map(ToString::to_string)
×
949
                        .unwrap_or_else(|| "<local request>".to_string()),
×
950
                    e
951
                );
952
                self.publish_block_event(BlockEvent::AddBlockValidationFailed { block, source_peer });
×
953
                Err(e.into())
×
954
            },
955

956
            Err(e) => {
×
957
                #[cfg(feature = "metrics")]
×
958
                metrics::rejected_blocks(block.header.height, &block.hash()).inc();
×
959

×
960
                self.publish_block_event(BlockEvent::AddBlockErrored { block });
×
961
                Err(e.into())
×
962
            },
963
        }
964
    }
×
965

966
    async fn hydrate_block(&mut self, block: Block) -> Result<Arc<Block>, CommsInterfaceError> {
×
967
        let block_hash = block.hash();
×
968
        let block_height = block.header.height;
×
969
        if block.body.inputs().is_empty() {
×
970
            debug!(
×
971
                target: LOG_TARGET,
×
972
                "Block #{} ({}) contains no inputs so nothing to hydrate",
×
973
                block_height,
×
974
                block_hash.to_hex(),
×
975
            );
976
            return Ok(Arc::new(block));
×
977
        }
×
978

×
979
        let timer = Instant::now();
×
980
        let (header, mut inputs, outputs, kernels) = block.dissolve();
×
981

982
        let db = self.blockchain_db.inner().db_read_access()?;
×
983
        for input in &mut inputs {
×
984
            if !input.is_compact() {
×
985
                continue;
×
986
            }
×
987

988
            let output_mined_info =
×
989
                db.fetch_output(&input.output_hash())?
×
990
                    .ok_or_else(|| CommsInterfaceError::InvalidFullBlock {
×
991
                        hash: block_hash,
×
992
                        details: format!("Output {} to be spent does not exist in db", input.output_hash()),
×
993
                    })?;
×
994

995
            input.add_output_data(output_mined_info.output);
×
996
        }
997
        debug!(
×
998
            target: LOG_TARGET,
×
999
            "Hydrated block #{} ({}) with {} input(s) in {:.2?}",
×
1000
            block_height,
×
1001
            block_hash.to_hex(),
×
1002
            inputs.len(),
×
1003
            timer.elapsed()
×
1004
        );
1005
        let block = Block::new(header, AggregateBody::new(inputs, outputs, kernels));
×
1006
        Ok(Arc::new(block))
×
1007
    }
×
1008

1009
    fn publish_block_event(&self, event: BlockEvent) {
×
1010
        if let Err(event) = self.block_event_sender.send(Arc::new(event)) {
×
1011
            debug!(target: LOG_TARGET, "No event subscribers. Event {} dropped.", event.0)
×
1012
        }
×
1013
    }
×
1014

1015
    #[cfg(feature = "metrics")]
1016
    async fn update_block_result_metrics(&self, block_add_result: &BlockAddResult) -> Result<(), CommsInterfaceError> {
×
1017
        fn update_target_difficulty(block: &ChainBlock) {
×
1018
            match block.header().pow_algo() {
×
1019
                PowAlgorithm::Sha3x => {
×
1020
                    metrics::target_difficulty_sha()
×
1021
                        .set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
×
1022
                },
×
1023
                PowAlgorithm::RandomXM => {
×
1024
                    metrics::target_difficulty_monero_randomx()
×
1025
                        .set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
×
1026
                },
×
1027
                PowAlgorithm::RandomXT => {
×
1028
                    metrics::target_difficulty_tari_randomx()
×
1029
                        .set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
×
1030
                },
×
1031
            }
1032
        }
×
1033

1034
        match block_add_result {
×
1035
            BlockAddResult::Ok(ref block) => {
×
1036
                update_target_difficulty(block);
×
1037
                #[allow(clippy::cast_possible_wrap)]
×
1038
                metrics::tip_height().set(block.height() as i64);
×
1039
                let utxo_set_size = self.blockchain_db.utxo_count().await?;
×
1040
                metrics::utxo_set_size().set(utxo_set_size.try_into().unwrap_or(i64::MAX));
×
1041
            },
1042
            BlockAddResult::ChainReorg { added, removed } => {
×
1043
                if let Some(fork_height) = added.last().map(|b| b.height()) {
×
1044
                    #[allow(clippy::cast_possible_wrap)]
1045
                    metrics::tip_height().set(fork_height as i64);
×
1046
                    metrics::reorg(fork_height, added.len(), removed.len()).inc();
×
1047

1048
                    let utxo_set_size = self.blockchain_db.utxo_count().await?;
×
1049
                    metrics::utxo_set_size().set(utxo_set_size.try_into().unwrap_or(i64::MAX));
×
1050
                }
×
1051
                for block in added {
×
1052
                    update_target_difficulty(block);
×
1053
                }
×
1054
            },
1055
            BlockAddResult::OrphanBlock => {
×
1056
                metrics::orphaned_blocks().inc();
×
1057
            },
×
1058
            _ => {},
×
1059
        }
1060
        Ok(())
×
1061
    }
×
1062

1063
    async fn get_target_difficulty_for_next_block(
×
1064
        &self,
×
1065
        pow_algo: PowAlgorithm,
×
1066
        constants: &ConsensusConstants,
×
1067
        current_block_hash: HashOutput,
×
1068
    ) -> Result<Difficulty, CommsInterfaceError> {
×
1069
        let target_difficulty = self
×
1070
            .blockchain_db
×
1071
            .fetch_target_difficulty_for_next_block(pow_algo, current_block_hash)
×
1072
            .await?;
×
1073

1074
        let target = target_difficulty.calculate(
×
1075
            constants.min_pow_difficulty(pow_algo),
×
1076
            constants.max_pow_difficulty(pow_algo),
×
1077
        );
×
1078
        trace!(target: LOG_TARGET, "Target difficulty {} for PoW {}", target, pow_algo);
×
1079
        Ok(target)
×
1080
    }
×
1081

1082
    pub async fn get_last_seen_hash(&self) -> Result<FixedHash, CommsInterfaceError> {
×
1083
        self.mempool.get_last_seen_hash().await.map_err(|e| e.into())
×
1084
    }
×
1085
}
1086

1087
impl<B> Clone for InboundNodeCommsHandlers<B> {
1088
    fn clone(&self) -> Self {
×
1089
        Self {
×
1090
            block_event_sender: self.block_event_sender.clone(),
×
1091
            blockchain_db: self.blockchain_db.clone(),
×
1092
            mempool: self.mempool.clone(),
×
1093
            consensus_manager: self.consensus_manager.clone(),
×
1094
            list_of_reconciling_blocks: self.list_of_reconciling_blocks.clone(),
×
1095
            outbound_nci: self.outbound_nci.clone(),
×
1096
            connectivity: self.connectivity.clone(),
×
1097
            randomx_factory: self.randomx_factory.clone(),
×
1098
        }
×
1099
    }
×
1100
}
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