nautilus_model/defi/
validation.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Validation utilities for blockchain data types.
17//!
18//! This module provides validation functions for ensuring the correctness and integrity
19//! of blockchain-related data, particularly Ethereum addresses and other EVM-compatible
20//! blockchain identifiers.
21
22use std::str::FromStr;
23
24use alloy_primitives::Address;
25
26/// Validates an Ethereum address format, checksum, and returns the parsed address.
27///
28/// # Errors
29///
30/// Returns an error if:
31/// - The address does not start with '0x' prefix.
32/// - The address has invalid length (must be 42 characters including '0x').
33/// - The address contains invalid hexadecimal characters.
34/// - The address has an incorrect checksum (for checksummed addresses).
35pub fn validate_address(address: &str) -> anyhow::Result<Address> {
36    // Check if the address starts with "0x"
37    if !address.starts_with("0x") {
38        anyhow::bail!("Ethereum address must start with '0x': {address}");
39    }
40
41    // Check if the address is valid
42    let parsed_address = Address::from_str(address)
43        .map_err(|e| anyhow::anyhow!("Blockchain address '{address}' is incorrect: {e}"))?;
44
45    // Check if checksum is valid
46    Address::parse_checksummed(address, None)
47        .map_err(|_| anyhow::anyhow!("Blockchain address '{address}' has incorrect checksum"))?;
48
49    Ok(parsed_address)
50}
51
52#[cfg(test)]
53mod tests {
54    use rstest::rstest;
55
56    use super::*;
57
58    #[rstest]
59    fn test_validate_address_invalid_prefix() {
60        let invalid_address = "742d35Cc6634C0532925a3b844Bc454e4438f44e";
61        let result = validate_address(invalid_address);
62        assert!(result.is_err());
63        assert_eq!(
64            result.unwrap_err().to_string(),
65            "Ethereum address must start with '0x': 742d35Cc6634C0532925a3b844Bc454e4438f44e"
66        );
67    }
68
69    #[rstest]
70    fn test_validate_invalid_address_format() {
71        let invalid_length_address = "0x1233";
72        let invalid_characters_address = "0xZZZd35Cc6634C0532925a3b844Bc454e4438f44e";
73
74        assert_eq!(
75            validate_address(invalid_length_address)
76                .unwrap_err()
77                .to_string(),
78            "Blockchain address '0x1233' is incorrect: invalid string length"
79        );
80        assert_eq!(
81            validate_address(invalid_characters_address)
82                .unwrap_err()
83                .to_string(),
84            "Blockchain address '0xZZZd35Cc6634C0532925a3b844Bc454e4438f44e' is incorrect: invalid character 'Z' at position 0"
85        );
86    }
87
88    #[rstest]
89    fn test_validate_invalid_checksum() {
90        let invalid_checksum_address = "0x742d35cc6634c0532925a3b844bc454e4438f44e";
91        assert_eq!(
92            validate_address(invalid_checksum_address)
93                .unwrap_err()
94                .to_string(),
95            "Blockchain address '0x742d35cc6634c0532925a3b844bc454e4438f44e' has incorrect checksum"
96        );
97    }
98}