coldstar-validation 0.2.0

Input validation for device paths, addresses, passwords, and amounts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Input validation and sanitization for ColdStar.
//!
//! Provides security-focused validation functions ported from the Python
//! `security_validation.py` module. Every validator returns `Result<(), ValidationError>`
//! (or a sanitized value) so callers get structured, actionable errors.

use regex::Regex;
use std::path::Path;
use thiserror::Error;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Minimum acceptable password length.
pub const MIN_PASSWORD_LENGTH: usize = 12;

/// Upper-bound balance in SOL (greater than total supply).
pub const MAX_BALANCE_SOL: u64 = 1_000_000_000;

/// Lamports per SOL.
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Structured validation errors with context.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ValidationError {
    #[error("Device path cannot be empty")]
    DevicePathEmpty,

    #[error("Invalid device path: contains path traversal sequences")]
    DevicePathTraversal,

    #[error("Invalid device path: contains null bytes")]
    DevicePathNullByte,

    #[error("Invalid device path: must start with /dev/")]
    DevicePathNotDev,

    #[error("Invalid device path: unexpected device name format")]
    DevicePathBadFormat,

    #[error("Invalid device path: must be a drive letter (e.g., D:)")]
    DevicePathNotDriveLetter,

    #[error("Mount point cannot be empty")]
    MountPointEmpty,

    #[error("Invalid mount point: contains path traversal")]
    MountPointTraversal,

    #[error("Invalid mount point: contains null bytes")]
    MountPointNullByte,

    #[error("Invalid mount point: not under an allowed prefix for {0}")]
    MountPointDisallowed(Platform),

    #[error("Password cannot be empty")]
    PasswordEmpty,

    #[error("Password must be at least {0} characters long")]
    PasswordTooShort(usize),

    #[error("Password must contain at least one uppercase letter")]
    PasswordNoUppercase,

    #[error("Password must contain at least one lowercase letter")]
    PasswordNoLowercase,

    #[error("Password must contain at least one number")]
    PasswordNoDigit,

    #[error("Password is too common. Please choose a stronger password")]
    PasswordCommon,

    #[error("Address cannot be empty")]
    AddressEmpty,

    #[error("Invalid address length")]
    AddressLength,

    #[error("Invalid characters in address (must be base58)")]
    AddressBadChars,

    #[error("Invalid Solana address: decoded key is not 32 bytes")]
    AddressBadDecode,

    #[error("Balance must be non-negative")]
    BalanceNegative,

    #[error("Balance exceeds maximum possible value ({0} SOL)")]
    BalanceTooLarge(u64),

    #[error("Amount must be greater than 0")]
    AmountNotPositive,

    #[error("Amount exceeds maximum ({0} SOL)")]
    AmountTooLarge(u64),

    #[error("Amount exceeds available balance")]
    AmountExceedsBalance,

    #[error("Amount has too many decimal places (max 9)")]
    AmountPrecision,

    #[error("RPC URL cannot be empty")]
    RpcUrlEmpty,

    #[error("RPC URL must start with http:// or https://")]
    RpcUrlBadScheme,

    #[error("Invalid RPC URL format")]
    RpcUrlBadFormat,
}

/// Optional warning returned alongside a successful validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationWarning {
    /// The RPC URL uses plain HTTP (not HTTPS) on a non-localhost host.
    InsecureHttp,
}

// ---------------------------------------------------------------------------
// Platform enum
// ---------------------------------------------------------------------------

/// Target operating system for platform-specific validations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    Linux,
    Darwin,
    Windows,
}

impl std::fmt::Display for Platform {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Platform::Linux => write!(f, "Linux"),
            Platform::Darwin => write!(f, "Darwin"),
            Platform::Windows => write!(f, "Windows"),
        }
    }
}

// ---------------------------------------------------------------------------
// Device path validation
// ---------------------------------------------------------------------------

/// Validate a device path for the given platform.
///
/// Rejects path-traversal sequences (`..`, `//`), null bytes, and
/// platform-inappropriate formats.
pub fn validate_device_path(path: &str, platform: Platform) -> Result<(), ValidationError> {
    if path.is_empty() {
        return Err(ValidationError::DevicePathEmpty);
    }

    if path.contains("..") || path.contains("//") {
        return Err(ValidationError::DevicePathTraversal);
    }

    if path.contains('\0') {
        return Err(ValidationError::DevicePathNullByte);
    }

    match platform {
        Platform::Linux | Platform::Darwin => {
            if !path.starts_with("/dev/") {
                return Err(ValidationError::DevicePathNotDev);
            }

            let re = Regex::new(
                r"^/dev/(sd[a-z]\d*|disk\d+s?\d*|mmcblk\d+p?\d*|nvme\d+|nvme\d+n\d+p?\d*)$",
            )
            .expect("device path regex is valid");

            if !re.is_match(path) {
                return Err(ValidationError::DevicePathBadFormat);
            }
        }
        Platform::Windows => {
            let re = Regex::new(r"(?i)^[A-Z]:\\?$").expect("windows drive regex is valid");
            if !re.is_match(path) {
                return Err(ValidationError::DevicePathNotDriveLetter);
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Mount point validation
// ---------------------------------------------------------------------------

/// Validate a mount-point path for the given platform.
///
/// Ensures the path lives under an OS-appropriate directory tree.
pub fn validate_mount_point(mount_point: &str, platform: Platform) -> Result<(), ValidationError> {
    if mount_point.is_empty() {
        return Err(ValidationError::MountPointEmpty);
    }

    if mount_point.contains("..") {
        return Err(ValidationError::MountPointTraversal);
    }

    if mount_point.contains('\0') {
        return Err(ValidationError::MountPointNullByte);
    }

    let resolved = Path::new(mount_point)
        .to_str()
        .unwrap_or(mount_point);

    match platform {
        Platform::Linux => {
            let allowed = ["/media/", "/mnt/", "/run/media/", "/tmp/solana_usb_"];
            if !allowed.iter().any(|prefix| resolved.starts_with(prefix)) {
                return Err(ValidationError::MountPointDisallowed(Platform::Linux));
            }
        }
        Platform::Darwin => {
            if !resolved.starts_with("/Volumes/") {
                return Err(ValidationError::MountPointDisallowed(Platform::Darwin));
            }
        }
        Platform::Windows => {
            let re =
                Regex::new(r"(?i)^[A-Z]:\\").expect("windows mount point regex is valid");
            if !re.is_match(resolved) {
                return Err(ValidationError::MountPointDisallowed(Platform::Windows));
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Password strength
// ---------------------------------------------------------------------------

/// Validate that a password meets ColdStar's minimum strength requirements.
///
/// Rules: at least 12 characters, at least one uppercase, one lowercase,
/// one digit, and not in a common-password blocklist.
pub fn validate_password_strength(password: &str) -> Result<(), ValidationError> {
    if password.is_empty() {
        return Err(ValidationError::PasswordEmpty);
    }

    if password.len() < MIN_PASSWORD_LENGTH {
        return Err(ValidationError::PasswordTooShort(MIN_PASSWORD_LENGTH));
    }

    if !password.chars().any(|c| c.is_ascii_uppercase()) {
        return Err(ValidationError::PasswordNoUppercase);
    }

    if !password.chars().any(|c| c.is_ascii_lowercase()) {
        return Err(ValidationError::PasswordNoLowercase);
    }

    if !password.chars().any(|c| c.is_ascii_digit()) {
        return Err(ValidationError::PasswordNoDigit);
    }

    const COMMON: &[&str] = &[
        "password",
        "12345678",
        "123456789",
        "1234567890",
        "qwerty",
        "abc123",
        "password123",
        "admin",
        "letmein",
        "welcome",
        "monkey",
        "1234",
        "password1",
        "123456",
        "qwerty123",
        "password123456",
        "qwerty123456",
    ];

    let lower = password.to_ascii_lowercase();
    if COMMON.iter().any(|&common| lower == common) {
        return Err(ValidationError::PasswordCommon);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Solana address
// ---------------------------------------------------------------------------

/// Validate a base58-encoded Solana public-key address.
///
/// Checks character set and decoded byte length (must be exactly 32 bytes).
pub fn validate_solana_address(address: &str) -> Result<(), ValidationError> {
    if address.is_empty() {
        return Err(ValidationError::AddressEmpty);
    }

    if address.len() < 32 || address.len() > 44 {
        return Err(ValidationError::AddressLength);
    }

    // Base58 alphabet (Bitcoin variant, used by Solana)
    const BASE58_CHARS: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    if !address.chars().all(|c| BASE58_CHARS.contains(c)) {
        return Err(ValidationError::AddressBadChars);
    }

    // Decode and verify 32 bytes
    let decoded = bs58::decode(address)
        .into_vec()
        .map_err(|_| ValidationError::AddressBadDecode)?;

    if decoded.len() != 32 {
        return Err(ValidationError::AddressBadDecode);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Balance / amount
// ---------------------------------------------------------------------------

/// Validate a balance value (in SOL, as `f64`) is within `[0, MAX_BALANCE_SOL]`.
pub fn validate_balance_value(balance: f64) -> Result<(), ValidationError> {
    if balance < 0.0 {
        return Err(ValidationError::BalanceNegative);
    }

    if balance > MAX_BALANCE_SOL as f64 {
        return Err(ValidationError::BalanceTooLarge(MAX_BALANCE_SOL));
    }

    Ok(())
}

/// Validate a transfer amount in SOL.
///
/// The amount must be positive, must not exceed `max_balance` (if provided),
/// and must be representable at lamport precision (9 decimal places).
pub fn validate_amount_sol(amount: f64, max_balance: Option<f64>) -> Result<(), ValidationError> {
    if amount <= 0.0 {
        return Err(ValidationError::AmountNotPositive);
    }

    if amount > MAX_BALANCE_SOL as f64 {
        return Err(ValidationError::AmountTooLarge(MAX_BALANCE_SOL));
    }

    if let Some(max) = max_balance {
        if amount > max {
            return Err(ValidationError::AmountExceedsBalance);
        }
    }

    // Precision check: round-trip through lamports
    let lamports = (amount * LAMPORTS_PER_SOL as f64) as u64;
    let reconstructed = lamports as f64 / LAMPORTS_PER_SOL as f64;
    if (amount - reconstructed).abs() > 1e-9 {
        return Err(ValidationError::AmountPrecision);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Filename sanitization
// ---------------------------------------------------------------------------

/// Sanitize a filename to prevent path traversal and injection attacks.
///
/// Strips directory components, null bytes, and non-`[a-zA-Z0-9._-]`
/// characters. Prevents hidden files (leading dot) and enforces a maximum
/// length while preserving the file extension.
pub fn sanitize_filename(name: &str, max_length: usize) -> String {
    if name.is_empty() {
        return "unnamed".to_string();
    }

    // Strip directory components (take the last segment after / or \)
    let basename = name
        .rsplit(|c| c == '/' || c == '\\')
        .next()
        .unwrap_or(name);

    // Remove null bytes
    let no_nulls: String = basename.chars().filter(|&c| c != '\0').collect();

    // Replace everything that isn't word-char, dot, or dash with underscore
    let re = Regex::new(r"[^\w.\-]").expect("sanitize regex is valid");
    let mut sanitized = re.replace_all(&no_nulls, "_").to_string();

    // Prevent hidden files
    if sanitized.starts_with('.') {
        sanitized = format!("_{}", &sanitized[1..]);
    }

    // Truncate while preserving extension
    if sanitized.len() > max_length {
        if let Some(dot_pos) = sanitized.rfind('.') {
            let ext = &sanitized[dot_pos..];
            let name_budget = max_length.saturating_sub(ext.len());
            sanitized = format!("{}{}", &sanitized[..name_budget], ext);
        } else {
            sanitized.truncate(max_length);
        }
    }

    if sanitized.is_empty() || sanitized == "." {
        return "unnamed".to_string();
    }

    sanitized
}

// ---------------------------------------------------------------------------
// RPC URL validation
// ---------------------------------------------------------------------------

/// Validate an RPC URL.
///
/// Returns `Ok(None)` for a clean HTTPS URL, `Ok(Some(InsecureHttp))` when
/// plain HTTP is used on a non-localhost host, or an appropriate
/// `Err(ValidationError)` on failure.
pub fn validate_rpc_url(url_str: &str) -> Result<Option<ValidationWarning>, ValidationError> {
    if url_str.is_empty() {
        return Err(ValidationError::RpcUrlEmpty);
    }

    if !url_str.starts_with("http://") && !url_str.starts_with("https://") {
        return Err(ValidationError::RpcUrlBadScheme);
    }

    let re = Regex::new(
        r"^https?://(?:[A-Za-z0-9\-]+\.)*[A-Za-z0-9\-]+(?::\d{1,5})?(?:/.*)?$",
    )
    .expect("rpc url regex is valid");

    if !re.is_match(url_str) {
        return Err(ValidationError::RpcUrlBadFormat);
    }

    // Warn about non-localhost HTTP
    if url_str.starts_with("http://")
        && !url_str.starts_with("http://localhost")
        && !url_str.starts_with("http://127.0.0.1")
    {
        return Ok(Some(ValidationWarning::InsecureHttp));
    }

    Ok(None)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- Device path --

    #[test]
    fn device_path_valid_linux_sd() {
        assert!(validate_device_path("/dev/sda", Platform::Linux).is_ok());
        assert!(validate_device_path("/dev/sda1", Platform::Linux).is_ok());
        assert!(validate_device_path("/dev/sdb", Platform::Linux).is_ok());
    }

    #[test]
    fn device_path_valid_linux_nvme() {
        assert!(validate_device_path("/dev/nvme0", Platform::Linux).is_ok());
        assert!(validate_device_path("/dev/nvme0n1", Platform::Linux).is_ok());
        assert!(validate_device_path("/dev/nvme0n1p1", Platform::Linux).is_ok());
    }

    #[test]
    fn device_path_valid_linux_mmcblk() {
        assert!(validate_device_path("/dev/mmcblk0", Platform::Linux).is_ok());
        assert!(validate_device_path("/dev/mmcblk0p1", Platform::Linux).is_ok());
    }

    #[test]
    fn device_path_valid_darwin() {
        assert!(validate_device_path("/dev/disk2", Platform::Darwin).is_ok());
        assert!(validate_device_path("/dev/disk2s1", Platform::Darwin).is_ok());
    }

    #[test]
    fn device_path_valid_windows() {
        assert!(validate_device_path("D:", Platform::Windows).is_ok());
        assert!(validate_device_path("D:\\", Platform::Windows).is_ok());
        assert!(validate_device_path("E:", Platform::Windows).is_ok());
    }

    #[test]
    fn device_path_empty() {
        assert_eq!(
            validate_device_path("", Platform::Linux),
            Err(ValidationError::DevicePathEmpty)
        );
    }

    #[test]
    fn device_path_traversal() {
        assert_eq!(
            validate_device_path("/dev/../etc/passwd", Platform::Linux),
            Err(ValidationError::DevicePathTraversal)
        );
        assert_eq!(
            validate_device_path("/dev//sda", Platform::Linux),
            Err(ValidationError::DevicePathTraversal)
        );
    }

    #[test]
    fn device_path_null_byte() {
        assert_eq!(
            validate_device_path("/dev/sda\0", Platform::Linux),
            Err(ValidationError::DevicePathNullByte)
        );
    }

    #[test]
    fn device_path_not_dev() {
        assert_eq!(
            validate_device_path("/tmp/sda", Platform::Linux),
            Err(ValidationError::DevicePathNotDev)
        );
    }

    #[test]
    fn device_path_bad_format() {
        assert_eq!(
            validate_device_path("/dev/foo", Platform::Linux),
            Err(ValidationError::DevicePathBadFormat)
        );
    }

    #[test]
    fn device_path_windows_bad() {
        assert_eq!(
            validate_device_path("/dev/sda", Platform::Windows),
            Err(ValidationError::DevicePathNotDriveLetter)
        );
    }

    // -- Mount point --

    #[test]
    fn mount_point_valid_linux() {
        assert!(validate_mount_point("/media/usb", Platform::Linux).is_ok());
        assert!(validate_mount_point("/mnt/data", Platform::Linux).is_ok());
        assert!(validate_mount_point("/run/media/user/stick", Platform::Linux).is_ok());
        assert!(validate_mount_point("/tmp/solana_usb_abc", Platform::Linux).is_ok());
    }

    #[test]
    fn mount_point_valid_darwin() {
        assert!(validate_mount_point("/Volumes/USB", Platform::Darwin).is_ok());
    }

    #[test]
    fn mount_point_valid_windows() {
        assert!(validate_mount_point("D:\\MyUSB", Platform::Windows).is_ok());
    }

    #[test]
    fn mount_point_empty() {
        assert_eq!(
            validate_mount_point("", Platform::Linux),
            Err(ValidationError::MountPointEmpty)
        );
    }

    #[test]
    fn mount_point_traversal() {
        assert_eq!(
            validate_mount_point("/media/../etc", Platform::Linux),
            Err(ValidationError::MountPointTraversal)
        );
    }

    #[test]
    fn mount_point_null_byte() {
        assert_eq!(
            validate_mount_point("/media/usb\0", Platform::Linux),
            Err(ValidationError::MountPointNullByte)
        );
    }

    #[test]
    fn mount_point_disallowed_linux() {
        assert_eq!(
            validate_mount_point("/home/user", Platform::Linux),
            Err(ValidationError::MountPointDisallowed(Platform::Linux))
        );
    }

    #[test]
    fn mount_point_disallowed_darwin() {
        assert_eq!(
            validate_mount_point("/tmp/usb", Platform::Darwin),
            Err(ValidationError::MountPointDisallowed(Platform::Darwin))
        );
    }

    #[test]
    fn mount_point_disallowed_windows() {
        assert_eq!(
            validate_mount_point("/media/usb", Platform::Windows),
            Err(ValidationError::MountPointDisallowed(Platform::Windows))
        );
    }

    // -- Password strength --

    #[test]
    fn password_valid() {
        assert!(validate_password_strength("Str0ngP@ssw0rd!").is_ok());
        assert!(validate_password_strength("MySecure1Pass").is_ok());
    }

    #[test]
    fn password_empty() {
        assert_eq!(
            validate_password_strength(""),
            Err(ValidationError::PasswordEmpty)
        );
    }

    #[test]
    fn password_too_short() {
        assert_eq!(
            validate_password_strength("Short1A"),
            Err(ValidationError::PasswordTooShort(MIN_PASSWORD_LENGTH))
        );
    }

    #[test]
    fn password_no_uppercase() {
        assert_eq!(
            validate_password_strength("alllowercase1"),
            Err(ValidationError::PasswordNoUppercase)
        );
    }

    #[test]
    fn password_no_lowercase() {
        assert_eq!(
            validate_password_strength("ALLUPPERCASE1"),
            Err(ValidationError::PasswordNoLowercase)
        );
    }

    #[test]
    fn password_no_digit() {
        assert_eq!(
            validate_password_strength("NoDigitsHereAB"),
            Err(ValidationError::PasswordNoDigit)
        );
    }

    #[test]
    fn password_common() {
        // "Password123456" lowered = "password123456" which is in the blocklist.
        // It's 14 chars, has upper + lower + digit -- passes all other checks.
        assert_eq!(
            validate_password_strength("Password123456"),
            Err(ValidationError::PasswordCommon)
        );
        // "Qwerty123456" lowered = "qwerty123456", also in blocklist.
        assert_eq!(
            validate_password_strength("Qwerty123456"),
            Err(ValidationError::PasswordCommon)
        );
    }

    // -- Solana address --

    #[test]
    fn address_valid_system_program() {
        // The System Program address is 32 '1's
        assert!(validate_solana_address("11111111111111111111111111111111").is_ok());
    }

    #[test]
    fn address_valid_typical() {
        // Known Token Program address
        assert!(validate_solana_address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").is_ok());
    }

    #[test]
    fn address_empty() {
        assert_eq!(
            validate_solana_address(""),
            Err(ValidationError::AddressEmpty)
        );
    }

    #[test]
    fn address_too_short() {
        assert_eq!(
            validate_solana_address("abc"),
            Err(ValidationError::AddressLength)
        );
    }

    #[test]
    fn address_bad_chars() {
        // '0' (zero) and 'O' (capital oh) are not in base58
        assert_eq!(
            validate_solana_address("0OlI111111111111111111111111111111"),
            Err(ValidationError::AddressBadChars)
        );
    }

    // -- Balance --

    #[test]
    fn balance_valid() {
        assert!(validate_balance_value(0.0).is_ok());
        assert!(validate_balance_value(100.5).is_ok());
        assert!(validate_balance_value(MAX_BALANCE_SOL as f64).is_ok());
    }

    #[test]
    fn balance_negative() {
        assert_eq!(
            validate_balance_value(-1.0),
            Err(ValidationError::BalanceNegative)
        );
    }

    #[test]
    fn balance_too_large() {
        assert_eq!(
            validate_balance_value(MAX_BALANCE_SOL as f64 + 1.0),
            Err(ValidationError::BalanceTooLarge(MAX_BALANCE_SOL))
        );
    }

    // -- Amount SOL --

    #[test]
    fn amount_valid() {
        assert!(validate_amount_sol(1.0, None).is_ok());
        assert!(validate_amount_sol(0.000000001, None).is_ok()); // 1 lamport
        assert!(validate_amount_sol(5.0, Some(10.0)).is_ok());
    }

    #[test]
    fn amount_not_positive() {
        assert_eq!(
            validate_amount_sol(0.0, None),
            Err(ValidationError::AmountNotPositive)
        );
        assert_eq!(
            validate_amount_sol(-1.0, None),
            Err(ValidationError::AmountNotPositive)
        );
    }

    #[test]
    fn amount_too_large() {
        assert_eq!(
            validate_amount_sol(MAX_BALANCE_SOL as f64 + 1.0, None),
            Err(ValidationError::AmountTooLarge(MAX_BALANCE_SOL))
        );
    }

    #[test]
    fn amount_exceeds_balance() {
        assert_eq!(
            validate_amount_sol(10.0, Some(5.0)),
            Err(ValidationError::AmountExceedsBalance)
        );
    }

    // -- Sanitize filename --

    #[test]
    fn sanitize_empty() {
        assert_eq!(sanitize_filename("", 255), "unnamed");
    }

    #[test]
    fn sanitize_path_traversal() {
        let result = sanitize_filename("../../etc/passwd", 255);
        assert!(!result.contains(".."));
        assert!(!result.contains('/'));
        // Should strip directory components, keeping only "passwd"
        assert_eq!(result, "passwd");
    }

    #[test]
    fn sanitize_null_bytes() {
        let result = sanitize_filename("file\0name.txt", 255);
        assert!(!result.contains('\0'));
    }

    #[test]
    fn sanitize_hidden_file() {
        let result = sanitize_filename(".hidden", 255);
        assert!(!result.starts_with('.'));
        assert_eq!(result, "_hidden");
    }

    #[test]
    fn sanitize_special_chars() {
        let result = sanitize_filename("file<>name|test.txt", 255);
        assert!(result
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == '-'));
    }

    #[test]
    fn sanitize_truncate_with_extension() {
        let result = sanitize_filename("very_long_name.txt", 10);
        assert!(result.len() <= 10);
        assert!(result.ends_with(".txt"));
    }

    #[test]
    fn sanitize_normal_filename() {
        assert_eq!(sanitize_filename("report.pdf", 255), "report.pdf");
    }

    // -- RPC URL --

    #[test]
    fn rpc_url_valid_https() {
        assert_eq!(
            validate_rpc_url("https://api.mainnet-beta.solana.com"),
            Ok(None)
        );
    }

    #[test]
    fn rpc_url_valid_localhost() {
        assert_eq!(validate_rpc_url("http://localhost:8899"), Ok(None));
        assert_eq!(validate_rpc_url("http://127.0.0.1:8899"), Ok(None));
    }

    #[test]
    fn rpc_url_insecure_http() {
        assert_eq!(
            validate_rpc_url("http://example.com:8899"),
            Ok(Some(ValidationWarning::InsecureHttp))
        );
    }

    #[test]
    fn rpc_url_empty() {
        assert_eq!(validate_rpc_url(""), Err(ValidationError::RpcUrlEmpty));
    }

    #[test]
    fn rpc_url_bad_scheme() {
        assert_eq!(
            validate_rpc_url("ftp://example.com"),
            Err(ValidationError::RpcUrlBadScheme)
        );
    }

    #[test]
    fn rpc_url_bad_format() {
        assert_eq!(
            validate_rpc_url("http://"),
            Err(ValidationError::RpcUrlBadFormat)
        );
    }
}