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

tari-project / tari / 16272458029

14 Jul 2025 04:32PM UTC coverage: 57.167% (-0.9%) from 58.047%
16272458029

push

github

web-flow
feat: modify soft disconnect criteria (#7307)

Description
---
We can be more efficient with soft disconnects when we compare against
expected RPC sessions and substream counts. This PR adds finer
discernment when doing soft peer disconnects.

Motivation and Context
---
The health check opens 2 substreams and 0 PRC sessions - that should
result in a disconnect if those are the only opened resources.

How Has This Been Tested?
---
System-level testing
```rust
2025-07-11 13:52:26.703289300 [comms::connection_manager::peer_connection] TRACE Hard disconnect - requester: 'Health check', peer: `d7c289e9e3c8377705ce599a96`, RPC clients: 0, substreams 2
2025-07-11 13:52:26.705658100 [comms::connection_manager::peer_connection] TRACE Soft disconnect - requester: 'Health check', peer: `0984896e74022c442c1034852c`, RPC clients: 1, substreams 3, NOT disconnecting
2025-07-11 13:52:26.705735900 [comms::connection_manager::peer_connection] TRACE Hard disconnect - requester: 'Health check', peer: `d025bc9e4bd423a9b304c491b8`, RPC clients: 0, substreams 2
2025-07-11 13:52:26.707647400 [comms::connection_manager::peer_connection] TRACE Hard disconnect - requester: 'Health check', peer: `51af08aff11f7129b4681d9950`, RPC clients: 0, substreams 2
```

What process can a PR reviewer use to test or verify this change?
---
Code review

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->


Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->


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

31 of 46 new or added lines in 6 files covered. (67.39%)

1102 existing lines in 27 files now uncovered.

68701 of 120177 relevant lines covered (57.17%)

226749.69 hits per line

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

0.0
/base_layer/core/src/validation/error.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
use tari_common_types::{epoch::VnEpoch, types::HashOutput};
24
use tari_sidechain::SidechainProofValidationError;
25
use tari_utilities::ByteArrayError;
26
use thiserror::Error;
27

28
use crate::{
29
    blocks::{BlockHeaderValidationError, BlockValidationError},
30
    chain_storage::ChainStorageError,
31
    common::{BanPeriod, BanReason},
32
    covenants::CovenantError,
33
    proof_of_work::{monero_rx::MergeMineError, DifficultyError, PowError},
34
    transactions::{
35
        tari_amount::MicroMinotari,
36
        transaction_components::{OutputType, RangeProofType, TransactionError},
37
    },
38
};
39

40
#[derive(Debug, Error)]
41
pub enum ValidationError {
42
    #[error("Serialization failed: {0}")]
43
    SerializationError(String),
44
    #[error("Block header validation failed: {0}")]
45
    BlockHeaderError(#[from] BlockHeaderValidationError),
46
    #[error("Block validation error: {0}")]
47
    BlockError(#[from] BlockValidationError),
48
    #[error("Contains kernels or inputs that are not yet spendable")]
49
    MaturityError,
50
    #[error("The block weight ({actual_weight}) is above the maximum ({max_weight})")]
51
    BlockTooLarge { actual_weight: u64, max_weight: u64 },
52
    #[error("Contains {} unknown inputs", .0.len())]
53
    UnknownInputs(Vec<HashOutput>),
54
    #[error("Contains an unknown input")]
55
    UnknownInput,
56
    #[error("The transaction is invalid: {0}")]
57
    TransactionError(#[from] TransactionError),
58
    #[error("Fatal storage error during validation: {0}")]
59
    FatalStorageError(String),
60
    #[error(
61
        "The total expected supply plus the total accumulated (offset) excess does not equal the sum of all UTXO \
62
         commitments."
63
    )]
64
    InvalidAccountingBalance,
65
    #[error("Transaction contains already spent inputs")]
66
    ContainsSTxO,
67
    #[error("Transaction contains outputs that already exist")]
68
    ContainsTxO,
69
    #[error("Transaction contains an output commitment that already exists")]
70
    ContainsDuplicateUtxoCommitment,
71
    #[error("Final state validation failed: The UTXO set did not balance with the expected emission at height {0}")]
72
    ChainBalanceValidationFailed(u64),
73
    #[error("The total value + fees of the block exceeds the maximum allowance on chain")]
74
    CoinbaseExceedsMaxLimit,
75
    #[error("Proof of work error: {0}")]
76
    ProofOfWorkError(#[from] PowError),
77
    #[error("Attempted to validate genesis block")]
78
    ValidatingGenesis,
79
    #[error("Duplicate or unsorted input found in block body")]
80
    UnsortedOrDuplicateInput,
81
    #[error("Duplicate or unsorted output found in block body")]
82
    UnsortedOrDuplicateOutput,
83
    #[error("Duplicate or unsorted kernel found in block body")]
84
    UnsortedOrDuplicateKernel,
85
    #[error("Error in merge mine data:{0}")]
86
    MergeMineError(#[from] MergeMineError),
87
    #[error("Maximum transaction weight exceeded")]
88
    MaxTransactionWeightExceeded,
89
    #[error("Expected block height to be {expected}, but was {block_height}")]
90
    IncorrectHeight { expected: u64, block_height: u64 },
91
    #[error("Expected block previous hash to be {expected}, but was {block_hash}")]
92
    IncorrectPreviousHash { expected: String, block_hash: String },
93
    #[error("Bad block with hash '{hash}' and reason '{reason}' found")]
94
    BadBlockFound { hash: String, reason: String },
95
    #[error("Script exceeded maximum script size, expected less than {max_script_size} but was {actual_script_size}")]
96
    TariScriptExceedsMaxSize {
97
        max_script_size: usize,
98
        actual_script_size: usize,
99
    },
100
    #[error(
101
        "Encrypted data exceeded maximum encrytped data size, expected less than {max_encrypted_data_size} but was \
102
         {actual_encrypted_data_size}"
103
    )]
104
    EncryptedDataExceedsMaxSize {
105
        max_encrypted_data_size: usize,
106
        actual_encrypted_data_size: usize,
107
    },
108
    #[error("Consensus Error: {0}")]
109
    ConsensusError(String),
110
    #[error("Duplicate kernel Error: {0}")]
111
    DuplicateKernelError(String),
112
    #[error("Covenant failed to validate: {0}")]
113
    CovenantError(#[from] CovenantError),
114
    #[error("Invalid or unsupported blockchain version {version}")]
115
    InvalidBlockchainVersion { version: u16 },
116
    #[error("Contains Invalid Burn: {0}")]
117
    InvalidBurnError(String),
118
    #[error("Output type '{output_type}' is not permitted")]
119
    OutputTypeNotPermitted { output_type: OutputType },
120
    #[error("Range proof type '{range_proof_type}' is not permitted")]
121
    RangeProofTypeNotPermitted { range_proof_type: RangeProofType },
122
    #[error("Output type '{output_type}' is not matched to any range proof type")]
123
    OutputTypeNotMatchedToRangeProofType { output_type: OutputType },
124
    #[error("Validator registration has invalid minimum amount {actual}, must be at least {min}")]
125
    ValidatorNodeRegistrationMinDepositAmount { min: MicroMinotari, actual: MicroMinotari },
126
    #[error("Validator registration has invalid maturity {actual}, must be at least {min}")]
127
    ValidatorNodeRegistrationMinLockHeight { min: u64, actual: u64 },
128
    #[error("Sidechain ID knowledge proof not valid for template registration")]
129
    TemplateInvalidSidechainIdKnowledgeProof,
130
    #[error("Author signature not valid for template registration")]
131
    TemplateAuthorSignatureNotValid,
132
    #[error("Sidechain ID knowledge proof not valid for confidential output")]
133
    ConfidentialOutputSidechainIdKnowledgeProofNotValid,
134
    #[error("Validator node registration signature failed verification")]
135
    InvalidValidatorNodeSignature,
136
    #[error("Sidechain ID knowledge proof not valid for validator node registration")]
137
    ValidatorNodeInvalidSidechainIdKnowledgeProof,
138
    #[error(
139
        "An unexpected number of timestamps were provided to the header validator. THIS IS A BUG. Expected \
140
         {expected}, got {actual}"
141
    )]
142
    IncorrectNumberOfTimestampsProvided { expected: u64, actual: u64 },
143
    #[error("Invalid difficulty: {0}")]
144
    DifficultyError(#[from] DifficultyError),
145
    #[error("Covenant too large. Max size: {max_size}, Actual size: {actual_size}")]
146
    CovenantTooLarge { max_size: usize, actual_size: usize },
147
    #[error("Invalid Serialized Public key: {0}")]
148
    InvalidSerializedPublicKey(String),
149
    #[error("Sidechain proof invalid: `{0}`")]
150
    SidechainProofInvalid(#[from] SidechainProofValidationError),
151
    #[error("Sidechain eviction proof submitted for unregistered validator {validator_pk}")]
152
    SidechainEvictionProofValidatorNotFound { validator_pk: String },
153
    #[error(
154
        "Sidechain eviction proof invalid: given epoch {epoch} is greater than the epoch at tip height {tip_height}"
155
    )]
156
    SidechainEvictionProofInvalidEpoch { epoch: VnEpoch, tip_height: u64 },
157
    #[error("Validator node already registered: {public_key}")]
158
    ValidatorNodeAlreadyRegistered { public_key: String },
159
    #[error("Validator node {public_key} not registered: {details}")]
160
    ValidatorNodeNotRegistered { public_key: String, details: String },
161
    #[error("Validator registration {public_key} invalid: max epoch {max_epoch} < current epoch {current_epoch}")]
162
    ValidatorNodeRegistrationMaxEpoch {
163
        public_key: String,
164
        current_epoch: VnEpoch,
165
        max_epoch: VnEpoch,
166
    },
167
    #[error("{output_type} output rule disallows the spend: {details}")]
168
    OutputSpendRuleDisallow { output_type: OutputType, details: String },
169
    #[error("Output type '{output_type}' does not match sidechain data")]
170
    OutputTypeNotMatchSidechainData { output_type: OutputType, details: String },
171
}
172

173
// ChainStorageError has a ValidationError variant, so to prevent a cyclic dependency we use a string representation in
174
// for storage errors that cause validation failures.
175
impl From<ChainStorageError> for ValidationError {
176
    fn from(err: ChainStorageError) -> Self {
×
177
        Self::FatalStorageError(err.to_string())
×
178
    }
×
179
}
180

181
impl From<ByteArrayError> for ValidationError {
182
    fn from(err: ByteArrayError) -> Self {
×
183
        Self::InvalidSerializedPublicKey(err.to_string())
×
184
    }
×
185
}
186

187
impl ValidationError {
UNCOV
188
    pub fn get_ban_reason(&self) -> Option<BanReason> {
×
UNCOV
189
        match self {
×
190
            ValidationError::ProofOfWorkError(e) => e.get_ban_reason(),
×
191
            err @ ValidationError::SerializationError(_) |
×
192
            err @ ValidationError::BlockHeaderError(_) |
×
193
            err @ ValidationError::BlockError(_) |
×
194
            err @ ValidationError::MaturityError |
×
195
            err @ ValidationError::BlockTooLarge { .. } |
×
196
            err @ ValidationError::UnknownInputs(_) |
×
197
            err @ ValidationError::UnknownInput |
×
198
            err @ ValidationError::TransactionError(_) |
×
199
            err @ ValidationError::InvalidAccountingBalance |
×
200
            err @ ValidationError::ContainsSTxO |
×
201
            err @ ValidationError::ContainsTxO |
×
202
            err @ ValidationError::ContainsDuplicateUtxoCommitment |
×
203
            err @ ValidationError::ChainBalanceValidationFailed(_) |
×
204
            err @ ValidationError::ValidatingGenesis |
×
205
            err @ ValidationError::UnsortedOrDuplicateInput |
×
206
            err @ ValidationError::UnsortedOrDuplicateOutput |
×
207
            err @ ValidationError::UnsortedOrDuplicateKernel |
×
208
            err @ ValidationError::MaxTransactionWeightExceeded |
×
209
            err @ ValidationError::IncorrectHeight { .. } |
×
210
            err @ ValidationError::IncorrectPreviousHash { .. } |
×
211
            err @ ValidationError::BadBlockFound { .. } |
×
212
            err @ ValidationError::TariScriptExceedsMaxSize { .. } |
×
213
            err @ ValidationError::EncryptedDataExceedsMaxSize { .. } |
×
UNCOV
214
            err @ ValidationError::ConsensusError(_) |
×
215
            err @ ValidationError::DuplicateKernelError(_) |
×
216
            err @ ValidationError::CovenantError(_) |
×
217
            err @ ValidationError::InvalidBlockchainVersion { .. } |
×
218
            err @ ValidationError::InvalidBurnError(_) |
×
219
            err @ ValidationError::OutputTypeNotPermitted { .. } |
×
220
            err @ ValidationError::RangeProofTypeNotPermitted { .. } |
×
221
            err @ ValidationError::OutputTypeNotMatchedToRangeProofType { .. } |
×
222
            err @ ValidationError::ValidatorNodeRegistrationMinDepositAmount { .. } |
×
223
            err @ ValidationError::ValidatorNodeRegistrationMinLockHeight { .. } |
×
224
            err @ ValidationError::InvalidValidatorNodeSignature |
×
225
            err @ ValidationError::ValidatorNodeInvalidSidechainIdKnowledgeProof |
×
226
            err @ ValidationError::TemplateInvalidSidechainIdKnowledgeProof |
×
227
            err @ ValidationError::TemplateAuthorSignatureNotValid |
×
228
            err @ ValidationError::ConfidentialOutputSidechainIdKnowledgeProofNotValid |
×
229
            err @ ValidationError::DifficultyError(_) |
×
230
            err @ ValidationError::CoinbaseExceedsMaxLimit |
×
231
            err @ ValidationError::CovenantTooLarge { .. } |
×
232
            err @ ValidationError::InvalidSerializedPublicKey(_) |
×
233
            err @ ValidationError::SidechainEvictionProofValidatorNotFound { .. } |
×
234
            err @ ValidationError::SidechainProofInvalid(_) |
×
235
            err @ ValidationError::SidechainEvictionProofInvalidEpoch { .. } |
×
236
            err @ ValidationError::ValidatorNodeAlreadyRegistered { .. } |
×
237
            err @ ValidationError::ValidatorNodeNotRegistered { .. } |
×
238
            err @ ValidationError::ValidatorNodeRegistrationMaxEpoch { .. } |
×
239
            err @ ValidationError::OutputTypeNotMatchSidechainData { .. } |
×
UNCOV
240
            err @ ValidationError::OutputSpendRuleDisallow { .. } => Some(BanReason {
×
UNCOV
241
                reason: err.to_string(),
×
UNCOV
242
                ban_duration: BanPeriod::Long,
×
UNCOV
243
            }),
×
244
            ValidationError::MergeMineError(e) => e.get_ban_reason(),
×
245
            ValidationError::FatalStorageError(_) | ValidationError::IncorrectNumberOfTimestampsProvided { .. } => None,
×
246
        }
UNCOV
247
    }
×
248
}
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