aleph-types 0.8.1

Definitions for the most commonly used types in the Aleph Cloud network.
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
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryFrom;
use std::fmt::{Display, Formatter};
use thiserror::Error;

/// Newtype for IPFS CIDv0 (base58-encoded, starts with "Qm", 46 characters).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CidV0(String);

/// Newtype for IPFS CIDv1 (multibase-encoded with various encodings).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CidV1(String);

/// Represents an IPFS Content Identifier (CID).
/// Supports both CIDv0 (base58-encoded SHA-256 multihash) and CIDv1 (multibase-encoded).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Cid {
    /// CIDv0: Always a base58-encoded multihash starting with "Qm"
    V0(CidV0),
    /// CIDv1: Multibase-encoded CID with various encodings (base32, base58btc, etc.)
    V1(CidV1),
}

#[derive(Error, Debug)]
pub enum CidError {
    #[error("invalid CID: empty string")]
    EmptyString,
    #[error("invalid CID format: unrecognized version or encoding")]
    InvalidFormat,
    #[error("invalid CIDv0: must start with 'Qm' and be 46 characters")]
    InvalidV0,
}

impl CidV0 {
    /// Creates a new CIDv0 from a string.
    /// CIDv0 must start with "Qm" and be exactly 46 characters long.
    pub fn new(cid: String) -> Result<Self, CidError> {
        if cid.starts_with("Qm") && cid.len() == 46 {
            Ok(CidV0(cid))
        } else {
            Err(CidError::InvalidV0)
        }
    }

    /// Returns the CIDv0 as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the CIDv0 and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl TryFrom<String> for CidV0 {
    type Error = CidError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        CidV0::new(value)
    }
}

impl TryFrom<&str> for CidV0 {
    type Error = CidError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        CidV0::new(value.to_string())
    }
}

impl Display for CidV0 {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl CidV1 {
    /// Creates a new CIDv1 from a string.
    /// CIDv1 typically starts with 'b' (base32) or 'z' (base58btc), but can have other multibase prefixes.
    pub fn new(cid: String) -> Self {
        CidV1(cid)
    }

    /// Returns the CIDv1 as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the CIDv1 and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl From<String> for CidV1 {
    fn from(value: String) -> Self {
        CidV1(value)
    }
}

impl Display for CidV1 {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Cid {
    /// Creates a new CIDv0 variant.
    pub fn v0(cid: CidV0) -> Self {
        Cid::V0(cid)
    }

    /// Creates a new CIDv1 variant.
    pub fn v1(cid: CidV1) -> Self {
        Cid::V1(cid)
    }

    /// Returns the CID as a string slice.
    pub fn as_str(&self) -> &str {
        match self {
            Cid::V0(cid) => cid.as_str(),
            Cid::V1(cid) => cid.as_str(),
        }
    }

    /// Checks if this is a CIDv0.
    pub fn is_v0(&self) -> bool {
        matches!(self, Cid::V0(_))
    }

    /// Checks if this is a CIDv1.
    pub fn is_v1(&self) -> bool {
        matches!(self, Cid::V1(_))
    }
}

impl TryFrom<String> for Cid {
    type Error = CidError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Err(CidError::EmptyString);
        }

        // CIDv0: starts with "Qm" and is 46 characters long
        if value.starts_with("Qm") && value.len() == 46 {
            return Ok(Cid::V0(CidV0(value)));
        }

        // CIDv1: multibase-encoded, typically starts with 'b' (base32) or 'z' (base58btc)
        // Common prefixes: b (base32), B (base32upper), z (base58btc), f (base16), F (base16upper),
        // m (base64), M (base64url), u (base64url), U (base64urlpad)
        if value.len() > 1 {
            let first_char = value.chars().next().unwrap();
            // Check for common multibase prefixes
            if matches!(
                first_char,
                'b' | 'B' | 'z' | 'f' | 'F' | 'm' | 'M' | 'u' | 'U'
            ) {
                return Ok(Cid::V1(CidV1(value)));
            }
        }

        Err(CidError::InvalidFormat)
    }
}

impl TryFrom<&str> for Cid {
    type Error = CidError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Cid::try_from(value.to_string())
    }
}

impl Display for Cid {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl From<CidV0> for Cid {
    fn from(value: CidV0) -> Self {
        Cid::V0(value)
    }
}

impl From<CidV1> for Cid {
    fn from(value: CidV1) -> Self {
        Cid::V1(value)
    }
}

// Custom serialization for Cid
impl Serialize for Cid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

// Custom deserialization for Cid that detects the version
impl<'de> Deserialize<'de> for Cid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Cid::try_from(s).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn test_cidv0_new() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8".to_string();
        let cid = CidV0::new(cid_str.clone()).unwrap();
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cidv0_try_from() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = CidV0::try_from(cid_str).unwrap();
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cidv0_invalid_length() {
        let cid_str = "QmYULJo".to_string();
        let result = CidV0::new(cid_str);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), CidError::InvalidV0));
    }

    #[test]
    fn test_cidv0_invalid_prefix() {
        let cid_str = "XmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8".to_string();
        let result = CidV0::new(cid_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_cidv0_display() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = CidV0::try_from(cid_str).unwrap();
        assert_eq!(format!("{}", cid), cid_str);
    }

    #[test]
    fn test_cidv1_new() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi".to_string();
        let cid = CidV1::new(cid_str.clone());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cidv1_from_string() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi".to_string();
        let cid = CidV1::from(cid_str.clone());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cidv1_display() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
        let cid = CidV1::new(cid_str.to_string());
        assert_eq!(format!("{}", cid), cid_str);
    }

    #[test]
    fn test_cid_from_cidv0() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cidv0 = CidV0::try_from(cid_str).unwrap();
        let cid = Cid::from(cidv0);
        assert!(cid.is_v0());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cid_from_cidv1() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
        let cidv1 = CidV1::new(cid_str.to_string());
        let cid = Cid::from(cidv1);
        assert!(cid.is_v1());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cid_try_from_v0_string() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = Cid::try_from(cid_str).unwrap();
        assert!(cid.is_v0());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cid_try_from_v1_base32() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
        let cid = Cid::try_from(cid_str).unwrap();
        assert!(cid.is_v1());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cid_try_from_v1_base58btc() {
        let cid_str = "zdj7WWeQ43G6JJvLWQWZpyHuAMq6uYWRjkBXFad11vE2LHhQ7";
        let cid = Cid::try_from(cid_str).unwrap();
        assert!(cid.is_v1());
        assert_eq!(cid.as_str(), cid_str);
    }

    #[test]
    fn test_cid_empty_string() {
        let result = Cid::try_from("");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), CidError::EmptyString));
    }

    #[test]
    fn test_cid_invalid_format() {
        let result = Cid::try_from("invalid_cid_format");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), CidError::InvalidFormat));
    }

    #[test]
    fn test_cid_display() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = Cid::try_from(cid_str).unwrap();
        assert_eq!(format!("{}", cid), cid_str);
    }

    #[test]
    fn test_cidv0_serde() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = CidV0::try_from(cid_str).unwrap();

        let json = serde_json::to_string(&cid).unwrap();
        assert_eq!(json, format!("\"{}\"", cid_str));

        let deserialized: CidV0 = serde_json::from_str(&json).unwrap();
        assert_eq!(cid, deserialized);
    }

    #[test]
    fn test_cidv1_serde() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
        let cid = CidV1::new(cid_str.to_string());

        let json = serde_json::to_string(&cid).unwrap();
        assert_eq!(json, format!("\"{}\"", cid_str));

        let deserialized: CidV1 = serde_json::from_str(&json).unwrap();
        assert_eq!(cid, deserialized);
    }

    #[test]
    fn test_cid_serde_v0() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8";
        let cid = Cid::try_from(cid_str).unwrap();

        let json = serde_json::to_string(&cid).unwrap();
        assert_eq!(json, format!("\"{}\"", cid_str));

        let deserialized: Cid = serde_json::from_str(&json).unwrap();
        assert_eq!(cid, deserialized);
        assert!(deserialized.is_v0());
    }

    #[test]
    fn test_cid_serde_v1() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
        let cid = Cid::try_from(cid_str).unwrap();

        let json = serde_json::to_string(&cid).unwrap();
        assert_eq!(json, format!("\"{}\"", cid_str));

        let deserialized: Cid = serde_json::from_str(&json).unwrap();
        assert_eq!(cid, deserialized);
        assert!(deserialized.is_v1());
    }

    #[test]
    fn test_cidv0_into_inner() {
        let cid_str = "QmYULJoNGPDmoRq4WNWTDTUvJGJv1hosox8H6vVd1kCsY8".to_string();
        let cid = CidV0::new(cid_str.clone()).unwrap();
        assert_eq!(cid.into_inner(), cid_str);
    }

    #[test]
    fn test_cidv1_into_inner() {
        let cid_str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi".to_string();
        let cid = CidV1::new(cid_str.clone());
        assert_eq!(cid.into_inner(), cid_str);
    }
}