andromeda-std 1.0.0

The standard library for creating an Andromeda Digital Object
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
use crate::{ado_base::ownership::OwnershipMessage, amp::AndrAddr, error::ContractError};
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::{ensure, Addr, Api, QuerierWrapper};
use regex::Regex;

pub const COMPONENT_NAME_REGEX: &str = r"^[A-Za-z0-9.\-_]{2,80}$";
pub const USERNAME_REGEX: &str = r"^[a-z0-9]{2,30}$";

pub const PATH_REGEX: &str = r"^(~[a-z0-9]{2,}|/(lib|home))(/[A-Za-z0-9.\-_]{2,80}?)*(/)?$";
pub const PROTOCOL_PATH_REGEX: &str = r"^((([A-Za-z0-9]+://)?([A-Za-z0-9.\-_]{2,80}/)))?((~[a-z0-9]{2,}|(lib|home))(/[A-Za-z0-9.\-_]{2,80}?)*(/)?)$";

pub fn convert_component_name(path: &str) -> String {
    path.trim()
        .replace(' ', "_")
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '.' || *c == '-' || *c == '_')
        .collect::<String>()
        .to_lowercase()
}

pub fn validate_component_name(path: String) -> Result<bool, ContractError> {
    ensure!(
        path.chars().any(|c| c.is_alphanumeric()),
        ContractError::InvalidPathname {
            error: Some("Pathname must contain at least one alphanumeric character".to_string())
        }
    );
    let re = Regex::new(COMPONENT_NAME_REGEX).unwrap();

    ensure!(
        re.is_match(&path),
        ContractError::InvalidPathname {
            error: Some("Pathname includes an invalid character".to_string())
        }
    );

    Ok(true)
}

/// Validates a username against specific criteria.
///
/// This function checks if a given username meets the following conditions:
/// - It must contain at least three characters
/// - It must only contain alphanumeric characters
///
/// # Arguments
///
/// * `username` - A `String` representing the username to be validated.
///
/// # Returns
///
/// * `Result<bool, ContractError>` - Returns `Ok(true)` if the username is valid, otherwise returns an `Err` with a `ContractError` detailing the reason for invalidity.
///
/// # Examples
///
/// ```
//// let valid_username = validate_username("validuser123".to_string()).unwrap();
//// assert_eq!(valid_username, true);
///
//// let invalid_username = validate_username("".to_string()).is_err();
//// assert!(invalid_username);
/// ```
pub fn validate_username(username: String) -> Result<bool, ContractError> {
    // Ensure the username is not empty.
    ensure!(
        !username.is_empty(),
        ContractError::InvalidUsername {
            error: Some("Username cannot be empty.".to_string())
        }
    );

    // Compile the regex for validating alphanumeric characters.
    let re = Regex::new(USERNAME_REGEX).unwrap();
    // Ensure the username matches the alphanumeric regex pattern.
    ensure!(
        re.is_match(&username),
        ContractError::InvalidPathname {
            error: Some(
                "Username contains invalid characters. All characters must be alphanumeric."
                    .to_string()
            )
        }
    );
    // Return true if all validations pass.
    Ok(true)
}

pub fn validate_path_name(api: &dyn Api, path: String) -> Result<(), ContractError> {
    let andr_addr = AndrAddr::from_string(path.clone());
    let is_path_reference = path.contains('/');
    let includes_protocol = andr_addr.get_protocol().is_some();

    // Path is of the form /user/... or /lib/... or prot://...
    if is_path_reference {
        // Alter regex if path includes a protocol
        let regex_str = if includes_protocol {
            PROTOCOL_PATH_REGEX
        } else {
            PATH_REGEX
        };

        let re = Regex::new(regex_str).unwrap();
        ensure!(
            re.is_match(&path),
            ContractError::InvalidPathname {
                error: Some("Pathname includes an invalid character".to_string())
            }
        );

        return Ok(());
    }

    // Path is either a username or address
    if !is_path_reference {
        let path = path.strip_prefix('~').unwrap_or(&path);
        let is_address = api.addr_validate(path).is_ok();

        if is_address {
            return Ok(());
        }

        let is_username = validate_username(path.to_string()).is_ok();

        if is_username {
            return Ok(());
        }

        return Err(ContractError::InvalidPathname {
            error: Some(
                "Provided address is neither a valid username nor a valid address".to_string(),
            ),
        });
    }

    // Does not fit any valid conditions
    Err(ContractError::InvalidPathname { error: None })
}

#[cw_serde]
pub struct InstantiateMsg {
    /// Address of the Kernel contract on chain
    pub kernel_address: String,
    pub owner: Option<String>,
}

#[cw_serde]
pub struct PathDetails {
    name: String,
    address: Addr,
}

impl PathDetails {
    pub fn new(name: impl Into<String>, address: Addr) -> PathDetails {
        PathDetails {
            name: name.into(),
            address,
        }
    }
}

#[cw_serde]
pub enum ExecuteMsg {
    AddPath {
        #[schemars(regex = "COMPONENT_NAME_REGEX")]
        name: String,
        address: Addr,
        parent_address: Option<AndrAddr>,
    },
    AddSymlink {
        #[schemars(regex = "COMPONENT_NAME_REGEX")]
        name: String,
        symlink: AndrAddr,
        parent_address: Option<AndrAddr>,
    },
    // Registers a child, currently only accessible by an App Contract
    AddChild {
        #[schemars(regex = "COMPONENT_NAME_REGEX")]
        name: String,
        parent_address: AndrAddr,
    },
    RegisterUser {
        #[schemars(regex = "USERNAME_REGEX", length(min = 3, max = 30))]
        username: String,
        address: Option<Addr>,
    },
    // Restricted to VFS owner/Kernel
    RegisterLibrary {
        lib_name: String,
        lib_address: Addr,
    },
    RegisterUserCrossChain {
        chain: String,
        address: String,
    },
    // Base message
    Ownership(OwnershipMessage),
}

#[cw_serde]
pub struct SubDirBound {
    address: Addr,
    name: String,
}
impl From<SubDirBound> for (Addr, String) {
    fn from(val: SubDirBound) -> Self {
        (val.address, val.name)
    }
}

#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(Addr)]
    ResolvePath { path: AndrAddr },
    #[returns(Vec<PathDetails>)]
    SubDir {
        path: AndrAddr,
        min: Option<SubDirBound>,
        max: Option<SubDirBound>,
        limit: Option<u32>,
    },
    #[returns(Vec<String>)]
    Paths { addr: Addr },
    #[returns(String)]
    GetUsername { address: Addr },
    #[returns(String)]
    GetLibrary { address: Addr },
    #[returns(AndrAddr)]
    ResolveSymlink { path: AndrAddr },
    // Base queries
    #[returns(crate::ado_base::version::VersionResponse)]
    Version {},
    #[returns(crate::ado_base::ado_type::TypeResponse)]
    Type {},
    #[returns(crate::ado_base::ownership::ContractOwnerResponse)]
    Owner {},
    #[returns(crate::ado_base::kernel_address::KernelAddressResponse)]
    KernelAddress {},
}

/// Queries the provided VFS contract address to resolve the given path
pub fn vfs_resolve_path(
    path: impl Into<String>,
    vfs_contract: impl Into<String>,
    querier: &QuerierWrapper,
) -> Result<Addr, ContractError> {
    let query = QueryMsg::ResolvePath {
        path: AndrAddr::from_string(path.into()),
    };
    let addr = querier.query_wasm_smart::<Addr>(vfs_contract, &query);
    match addr {
        Ok(addr) => Ok(addr),
        Err(_) => Err(ContractError::InvalidAddress {}),
    }
}

/// Queries the provided VFS contract address to resolve the given path
pub fn vfs_resolve_symlink(
    path: impl Into<String>,
    vfs_contract: impl Into<String>,
    querier: &QuerierWrapper,
) -> Result<AndrAddr, ContractError> {
    let query = QueryMsg::ResolveSymlink {
        path: AndrAddr::from_string(path.into()),
    };
    let addr = querier.query_wasm_smart::<AndrAddr>(vfs_contract, &query)?;
    Ok(addr)
}

#[cfg(test)]
mod test {
    use cosmwasm_std::testing::mock_dependencies;

    use super::*;

    struct ValidateComponentNameTestCase {
        name: &'static str,
        input: &'static str,
        should_err: bool,
    }

    #[test]
    fn test_validate_component_name() {
        let test_cases: Vec<ValidateComponentNameTestCase> = vec![
            ValidateComponentNameTestCase {
                name: "standard component name",
                input: "component1",
                should_err: false
            },
            ValidateComponentNameTestCase {
                name: "component with hyphen",
                input: "component-2",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component with underscore",
                input: "component_2",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component with period",
                input: ".component2",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component with invalid character",
                input: "component$2",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component with spaces",
                input: "component 2",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "empty component name",
                input: "",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name too long",
                input: "somereallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongname",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name with only special characters",
                input: "!@#$%^&*()",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name with leading and trailing spaces",
                input: "  component2  ",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name with only numbers",
                input: "123456",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component name one letter",
                input: "a",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name two letters",
                input: "ab",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component with hyphen at the start",
                input: "-component-2",
                should_err: false,
            },
            ValidateComponentNameTestCase {
                name: "component with forward slash",
                input: "component-2/",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component with backward slash",
                input: r"component-2\",
                should_err: true,
            },
            ValidateComponentNameTestCase {
                name: "component name with upper case letters",
                input: "ComponentName",
                should_err: false,
            }
        ];

        for test in test_cases {
            let res = validate_component_name(test.input.to_string());
            assert_eq!(res.is_err(), test.should_err, "Test case: {}", test.name);
        }
    }

    struct ValidatePathNameTestCase {
        name: &'static str,
        path: &'static str,
        should_err: bool,
    }

    #[test]
    fn test_validate_path_name() {
        let test_cases: Vec<ValidatePathNameTestCase> = vec![
            ValidatePathNameTestCase {
                name: "Simple app path",
                path: "./username/app",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Root path",
                path: "/",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Relative path with parent directory",
                path: "../username/app",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Tilde username reference",
                // Username must be short to circumvent it being mistaken as an address
                path: "~usr",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Tilde address reference",
                path: "~cosmos1abcde",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Tilde username reference with directory",
                path: "~usr/app/splitter",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Invalid tilde username reference",
                path: "~/username",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Absolute path with tilde",
                path: "~/home/username",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Invalid user path",
                path: "/user/un",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Valid user path",
                path: "/home/usr",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Invalid home path (address)",
                path: "/user/cosmos1abcde",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Valid home path (address)",
                path: "/home/cosmos1abcde",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Valid lib path",
                path: "/lib/library",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Complex invalid path",
                path: "/home/username/dir1/../dir2/./file",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with invalid characters",
                path: "/home/username/dir1/|file",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with space",
                path: "/home/ username/dir1/file",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Empty path",
                path: "",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with only special characters",
                path: "///",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with only special characters and spaces",
                path: "/// /  /// //",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Valid ibc protocol path",
                path: "ibc://chain/home/username/dir1/file",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Invalid ibc protocol path",
                path: "ibc:///home/username/dir1/file",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Standard address",
                path: "cosmos1abcde",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Only periods",
                path: "/../../../..",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with newline character",
                path: "/home/username/dir1\n/file",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with tab character",
                path: "/home/username/dir1\t/dir2",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with null character",
                path: "/home/username\0/dir1",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with emoji",
                path: "/home/username/😊",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with Cyrillic characters",
                path: "/home/пользователь/dir1",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with Arabic characters",
                path: "/home/مستخدم/dir1",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with Chinese characters",
                path: "/home/用户/dir1",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Path with very long name",
                path: "/home/username/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                should_err: true,
            },
            ValidatePathNameTestCase {
                name: "Valid path with multiple subdirectories",
                path: "/home/username/dir1/dir2/dir3/dir4",
                should_err: false,
            },
            ValidatePathNameTestCase {
                name: "Path with unprintable ASCII character",
                path: "/home/username/\x07file",
                should_err: true,
            },
            // This case should fail but due to the restriction of mock dependencies we cannot validate it correctly! It is partially validated in test_validate_username
            // ValidatePathNameTestCase {
            //     name: "Really long username",
            //     path: "~somereallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongname",
            //     should_err: true,
            // },
            // This case should fail but due to the restriction of mock dependencies we cannot validate it correctly!
            // ValidatePathNameTestCase {
            //     name: "Standard address with backslash",
            //     path: r"\cosmos\1abcde\",
            //     should_err: true,
            // },
        ];

        for test in test_cases {
            let deps = mock_dependencies();
            let res = validate_path_name(&deps.api, test.path.to_string());
            assert_eq!(res.is_err(), test.should_err, "Test case: {}", test.name);
        }
    }

    struct ConvertComponentNameTestCase {
        name: &'static str,
        input: &'static str,
        expected: &'static str,
    }

    #[test]
    fn test_convert_component_name() {
        let test_cases: Vec<ConvertComponentNameTestCase> = vec![
            ConvertComponentNameTestCase {
                name: "Standard name with spaces",
                input: "Some Component Name",
                expected: "some_component_name",
            },
            ConvertComponentNameTestCase {
                name: "Name with hyphens",
                input: "Some-Component-Name",
                expected: "some-component-name",
            },
            ConvertComponentNameTestCase {
                name: "Name with uppercase letters",
                input: "SomeCOMPONENTName",
                expected: "somecomponentname",
            },
            ConvertComponentNameTestCase {
                name: "Name with numbers",
                input: "Component123",
                expected: "component123",
            },
            ConvertComponentNameTestCase {
                name: "Name with special characters",
                input: "Component!@#",
                expected: "component",
            },
            ConvertComponentNameTestCase {
                name: "Empty name",
                input: "",
                expected: "",
            },
            ConvertComponentNameTestCase {
                name: "Name with leading and trailing spaces",
                input: "  Some Component Name  ",
                expected: "some_component_name",
            },
            ConvertComponentNameTestCase {
                name: "Name with multiple spaces",
                input: "Some    Component    Name",
                expected: "some____component____name",
            },
        ];

        for test in test_cases {
            assert_eq!(
                convert_component_name(test.input),
                test.expected,
                "Test case: {}",
                test.name
            )
        }
    }

    struct ValidateUsernameTestCase {
        name: &'static str,
        username: &'static str,
        should_err: bool,
    }

    #[test]
    fn test_validate_username() {
        let test_cases: Vec<ValidateUsernameTestCase> = vec![
            ValidateUsernameTestCase {
                name: "Valid lowercase username",
                username: "validusername",
                should_err: false,
            },
            ValidateUsernameTestCase {
                name: "Valid numeric username",
                username: "123456",
                should_err: false,
            },
            ValidateUsernameTestCase {
                name: "Username with uppercase letters",
                username: "InvalidUsername",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with special characters",
                username: "user!@#",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Empty username",
                username: "",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with underscore",
                username: "valid_username",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with hyphen",
                username: "valid-username",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with period",
                username: "valid.username",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with leading numbers",
                username: "123validusername",
                should_err: false,
            },
            ValidateUsernameTestCase {
                name: "Username with only three characters",
                username: "usr",
                should_err: false,
            },
            ValidateUsernameTestCase {
                name: "Username with only one character",
                username: "a",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with whitespace",
                username: "valid username",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with leading whitespace",
                username: " validusername",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with trailing whitespace",
                username: "validusername ",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with mixed case letters",
                username: "ValidUserName",
                should_err: true,
            },
            ValidateUsernameTestCase {
                name: "Username with all uppercase letters",
                username: "VALIDUSERNAME",
                should_err: true,
            },
        ];

        for test in test_cases {
            assert_eq!(
                validate_username(test.username.to_string()).is_err(),
                test.should_err,
                "Test case: {}",
                test.name
            )
        }
    }
}