world-id-primitives 0.9.0

Contains the raw base primitives (without implementations) for the World ID Protocol.
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
//! Serialization utilities for numeric API values across the protocol.
//!
//! Convention used by helpers in this module:
//! - serialization always emits `0x`-prefixed hex strings;
//! - deserialization accepts either decimal (no prefix) or hex (`0x`/`0X` prefix).

#![allow(clippy::missing_errors_doc)]

use ruint::aliases::U256;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};

fn parse_radix_and_digits(input: &str) -> Result<(u64, &str), String> {
    let s = input.trim();
    if s.is_empty() {
        return Err("empty numeric string".to_string());
    }

    if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        if rest.is_empty() {
            return Err("missing digits after 0x prefix".to_string());
        }
        Ok((16, rest))
    } else {
        Ok((10, s))
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256 {
    use super::*;

    /// Serialize a `U256` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &U256, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `U256` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        U256::from_str_radix(digits, radix)
            .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
    }
}

/// Serialize as optional `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_opt {
    use super::*;

    /// Serialize an `Option<U256>` as an optional `0x`-prefixed hex string.
    pub fn serialize<S>(value: &Option<U256>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(v) => serializer.serialize_some(&format!("{v:#x}")),
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an `Option<U256>` from an optional numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<U256>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                let v = U256::from_str_radix(digits, radix)
                    .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))?;
                Ok(Some(v))
            }
            None => Ok(None),
        }
    }
}

/// Serialize as `0x`-prefixed hex strings and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_vec {
    use super::*;

    /// Serialize a `Vec<U256>` as a vector of `0x`-prefixed hex strings.
    pub fn serialize<S>(values: &[U256], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_strings: Vec<String> = values.iter().map(|v| format!("{v:#x}")).collect();
        hex_strings.serialize(serializer)
    }

    /// Deserialize a `Vec<U256>` from a vector of numeric strings.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<U256>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let strings: Vec<String> = Vec::deserialize(deserializer)?;
        strings
            .into_iter()
            .map(|s| {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                U256::from_str_radix(digits, radix)
                    .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
            })
            .collect()
    }
}

/// Serialize as optional `0x`-prefixed hex strings and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_opt_vec {
    use super::*;

    /// Serialize a `Vec<Option<U256>>` as a vector of optional `0x`-prefixed hex strings.
    pub fn serialize<S>(values: &[Option<U256>], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_strings: Vec<Option<String>> = values
            .iter()
            .map(|value| value.as_ref().map(|v| format!("{v:#x}")))
            .collect();
        hex_strings.serialize(serializer)
    }

    /// Deserialize a `Vec<Option<U256>>` from a vector of optional numeric strings.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Option<U256>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let strings: Vec<Option<String>> = Vec::deserialize(deserializer)?;
        strings
            .into_iter()
            .map(|value| match value {
                Some(s) => {
                    let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                    U256::from_str_radix(digits, radix)
                        .map(Some)
                        .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
                }
                None => Ok(None),
            })
            .collect()
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u64 {
    use super::*;

    /// Serialize a `u64` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `u64` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        u64::from_str_radix(digits, radix as u32)
            .map_err(|e| D::Error::custom(format!("invalid numeric u64: {e}")))
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u32 {
    use super::*;

    /// Serialize a `u32` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &u32, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `u32` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<u32, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        u32::from_str_radix(digits, radix as u32)
            .map_err(|e| D::Error::custom(format!("invalid numeric u32: {e}")))
    }
}

/// Serialize as optional `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u32_opt {
    use super::*;

    /// Serialize an `Option<u32>` as an optional `0x`-prefixed hex string.
    pub fn serialize<S>(value: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(v) => serializer.serialize_some(&format!("{v:#x}")),
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an `Option<u32>` from an optional numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                let v = u32::from_str_radix(digits, radix as u32)
                    .map_err(|e| D::Error::custom(format!("invalid numeric u32: {e}")))?;
                Ok(Some(v))
            }
            None => Ok(None),
        }
    }
}

/// Serialize an `alloy_primitives::Signature` as a `0x`-prefixed hex string (65 bytes: `r || s || v`).
pub mod hex_signature {
    use alloy_primitives::Signature;
    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
    use std::str::FromStr;

    /// Serialize a `Signature` as a `0x`-prefixed hex string.
    pub fn serialize<S>(sig: &Signature, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&sig.to_string())
    }

    /// Deserialize a `Signature` from a `0x`-prefixed hex string.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Signature, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Signature::from_str(&s).map_err(D::Error::custom)
    }
}

/// Serializes an optional byte array as a `0x`-prefixed hex string if using a human-readable serializer
pub mod hex_bytes_opt {
    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};

    /// Serialize a byte array.
    ///
    /// - For human-readable serializers, this is emitted as a `0x`-prefixed hex string.
    /// - For non-human-readable serializers, this is emitted as raw bytes.
    pub fn serialize<S>(v: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match v {
            Some(v) => {
                if serializer.is_human_readable() {
                    serializer.serialize_some(&format!("0x{}", hex::encode(v)))
                } else {
                    serializer.serialize_some(v)
                }
            }
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize a byte array.
    ///
    /// - For human-readable serializers, this is expected as a `0x`-prefixed hex string.
    /// - For non-human-readable serializers, this is expected as raw bytes.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let s = Option::<String>::deserialize(deserializer)?;
            s.map(|s| {
                let s = s
                    .strip_prefix("0x")
                    .or_else(|| s.strip_prefix("0X"))
                    .unwrap_or(&s);
                hex::decode(s).map_err(D::Error::custom)
            })
            .transpose()
        } else {
            Option::<Vec<u8>>::deserialize(deserializer)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct Test {
        #[serde(with = "hex_u256")]
        u256_val: U256,
        #[serde(with = "hex_u64")]
        u64_val: u64,
    }

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct TestOptVec {
        #[serde(with = "hex_u256_opt_vec")]
        values: Vec<Option<U256>>,
    }

    #[test]
    fn test_hex_roundtrip() {
        let original = Test {
            u256_val: U256::from(0xdead_beef_u64),
            u64_val: 42,
        };
        let json = serde_json::to_string(&original).unwrap();
        assert!(json.contains("0xdeadbeef"));
        assert!(json.contains("0x2a"));

        let parsed: Test = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_deserialize_decimal_without_prefix() {
        let parsed: Test = serde_json::from_str(r#"{"u256_val":"42","u64_val":"42"}"#).unwrap();
        assert_eq!(parsed.u256_val, U256::from(42));
        assert_eq!(parsed.u64_val, 42);
    }

    #[test]
    fn test_deserialize_hex_with_prefix() {
        let parsed: Test = serde_json::from_str(r#"{"u256_val":"0x2a","u64_val":"0x2a"}"#).unwrap();
        assert_eq!(parsed.u256_val, U256::from(42));
        assert_eq!(parsed.u64_val, 42);
    }

    #[test]
    fn test_unprefixed_hex_like_value_is_rejected() {
        let err = serde_json::from_str::<Test>(r#"{"u256_val":"ff","u64_val":"255"}"#).unwrap_err();
        assert!(err.to_string().contains("invalid numeric U256"));
    }

    #[test]
    fn test_u256_opt_vec_roundtrip() {
        let original = TestOptVec {
            values: vec![Some(U256::from(1)), None, Some(U256::from(255))],
        };
        let json = serde_json::to_string(&original).unwrap();
        assert_eq!(json, r#"{"values":["0x1",null,"0xff"]}"#);

        let parsed: TestOptVec = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_u256_opt_vec_deserialize_decimal_and_null() {
        let parsed: TestOptVec = serde_json::from_str(r#"{"values":["42",null,"0x2a"]}"#).unwrap();
        assert_eq!(
            parsed.values,
            vec![Some(U256::from(42)), None, Some(U256::from(42))]
        );
    }

    #[test]
    fn test_hex_signature_roundtrip() {
        use alloy_primitives::Signature;

        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct S {
            #[serde(with = "hex_signature")]
            sig: Signature,
        }

        let sig = Signature::new(U256::from(1), U256::from(2), false);
        let s = S { sig };

        let json = serde_json::to_string(&s).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let hex_str = value["sig"].as_str().expect("signature should be a string");
        assert!(hex_str.starts_with("0x"), "should be 0x-prefixed");
        assert_eq!(hex_str.len(), 132, "0x + 130 hex chars (65 bytes)");

        let parsed: S = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, s);
    }
}