titan-types 0.1.33

Types for Titan bitcoin and runes indexer
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
use bitcoin::{hashes::Hash, Txid};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use std::{
    fmt::Display,
    io::{Read, Result, Write},
    str::FromStr,
};

#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct SerializedTxid(pub [u8; 32]);

impl SerializedTxid {
    pub fn new(txid: &[u8]) -> Self {
        Self(txid.try_into().unwrap())
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    pub fn all_zeros() -> Self {
        Self([0; 32])
    }
}

impl AsRef<[u8]> for SerializedTxid {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<[u8; 32]> for SerializedTxid {
    fn from(txid: [u8; 32]) -> Self {
        Self(txid)
    }
}

impl From<&[u8]> for SerializedTxid {
    fn from(txid: &[u8]) -> Self {
        Self(txid.try_into().unwrap())
    }
}

impl TryFrom<Box<[u8]>> for SerializedTxid {
    type Error = std::array::TryFromSliceError;

    fn try_from(txid: Box<[u8]>) -> std::result::Result<Self, Self::Error> {
        let array: [u8; 32] = (*txid).try_into()?;
        Ok(Self(array))
    }
}

impl From<Txid> for SerializedTxid {
    fn from(txid: Txid) -> Self {
        Self(*txid.as_raw_hash().as_byte_array())
    }
}

impl From<&Txid> for SerializedTxid {
    fn from(txid: &Txid) -> Self {
        Self(*txid.as_raw_hash().as_byte_array())
    }
}

impl From<&&Txid> for SerializedTxid {
    fn from(txid: &&Txid) -> Self {
        Self(*txid.as_raw_hash().as_byte_array())
    }
}

impl From<SerializedTxid> for Txid {
    fn from(txid: SerializedTxid) -> Self {
        Self::from_raw_hash(Hash::from_slice(&txid.0).unwrap())
    }
}

impl From<&SerializedTxid> for Txid {
    fn from(txid: &SerializedTxid) -> Self {
        Self::from_raw_hash(Hash::from_slice(&txid.0).unwrap())
    }
}

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

impl Display for SerializedTxid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Display as hex string (reversed bytes like bitcoin::Txid)
        let mut reversed = self.0;
        reversed.reverse();
        write!(f, "{}", hex::encode(reversed))
    }
}

impl FromStr for SerializedTxid {
    type Err = hex::FromHexError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        // Parse hex string and reverse bytes (bitcoin txids are displayed in reverse order)
        let mut bytes = hex::decode(s)?;
        if bytes.len() != 32 {
            return Err(hex::FromHexError::InvalidStringLength);
        }
        bytes.reverse();
        Ok(Self(bytes.try_into().unwrap()))
    }
}

impl BorshSerialize for SerializedTxid {
    fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Serialize the raw 32 bytes
        BorshSerialize::serialize(&self.0, writer)
    }
}

impl BorshDeserialize for SerializedTxid {
    fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
        let bytes = <[u8; 32]>::deserialize_reader(reader)?;
        Ok(Self(bytes))
    }
}

impl Serialize for SerializedTxid {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Serialize as hex string with reversed bytes (same as bitcoin::Txid)
        let mut reversed = self.0;
        reversed.reverse();
        let hex_string = hex::encode(reversed);
        serializer.serialize_str(&hex_string)
    }
}

impl<'de> Deserialize<'de> for SerializedTxid {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let hex_string = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_str(&hex_string).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::{hashes::Hash, Txid};
    use borsh::{BorshDeserialize, BorshSerialize};

    /// Helper function to test borsh serialization roundtrip
    fn test_borsh_roundtrip<T>(original: &T) -> T
    where
        T: BorshSerialize + BorshDeserialize + std::fmt::Debug + PartialEq,
    {
        let serialized = borsh::to_vec(original).expect("Failed to serialize");
        let deserialized = borsh::from_slice(&serialized).expect("Failed to deserialize");
        assert_eq!(original, &deserialized, "Borsh roundtrip failed");
        deserialized
    }

    /// Helper function to test serde serialization roundtrip
    fn test_serde_roundtrip<T>(original: &T) -> T
    where
        T: serde::Serialize + for<'de> serde::Deserialize<'de> + std::fmt::Debug + PartialEq,
    {
        let serialized = serde_json::to_string(original).expect("Failed to serialize");
        let deserialized = serde_json::from_str(&serialized).expect("Failed to deserialize");
        assert_eq!(original, &deserialized, "Serde roundtrip failed");
        deserialized
    }

    fn create_test_txid() -> SerializedTxid {
        SerializedTxid::from([42u8; 32])
    }

    fn create_zero_txid() -> SerializedTxid {
        SerializedTxid::all_zeros()
    }

    fn create_max_txid() -> SerializedTxid {
        SerializedTxid::from([255u8; 32])
    }

    #[test]
    fn test_serialized_txid_new() {
        let bytes = [42u8; 32];
        let txid = SerializedTxid::new(&bytes);
        assert_eq!(txid.as_bytes(), &bytes);
    }

    #[test]
    fn test_serialized_txid_borsh_roundtrip() {
        let original = create_test_txid();
        test_borsh_roundtrip(&original);
    }

    #[test]
    fn test_serialized_txid_serde_roundtrip() {
        let original = create_test_txid();
        test_serde_roundtrip(&original);
    }

    #[test]
    fn test_serialized_txid_zero_values() {
        let original = create_zero_txid();
        test_borsh_roundtrip(&original);
        test_serde_roundtrip(&original);
    }

    #[test]
    fn test_serialized_txid_max_values() {
        let original = create_max_txid();
        test_borsh_roundtrip(&original);
        test_serde_roundtrip(&original);
    }

    #[test]
    fn test_serialized_txid_all_zeros() {
        let txid = SerializedTxid::all_zeros();
        assert_eq!(txid.as_bytes(), &[0u8; 32]);
    }

    #[test]
    fn test_serialized_txid_as_bytes() {
        let bytes = [123u8; 32];
        let txid = SerializedTxid::from(bytes);
        assert_eq!(txid.as_bytes(), &bytes);
    }

    #[test]
    fn test_serialized_txid_as_ref() {
        let bytes = [99u8; 32];
        let txid = SerializedTxid::from(bytes);
        let as_ref: &[u8] = txid.as_ref();
        assert_eq!(as_ref, &bytes);
    }

    #[test]
    fn test_serialized_txid_from_array() {
        let array = [77u8; 32];
        let txid = SerializedTxid::from(array);
        assert_eq!(txid.as_bytes(), &array);
    }

    #[test]
    fn test_serialized_txid_from_slice() {
        let array = [88u8; 32];
        let slice = array.as_slice();
        let txid = SerializedTxid::from(slice);
        assert_eq!(txid.as_bytes(), &array);
    }

    #[test]
    fn test_serialized_txid_try_from_box() {
        let boxed: Box<[u8]> = Box::new([44u8; 32]);
        let txid = SerializedTxid::try_from(boxed).expect("Should convert from Box<[u8]>");
        assert_eq!(txid.as_bytes(), &[44u8; 32]);
    }

    #[test]
    fn test_serialized_txid_try_from_box_invalid_length() {
        let boxed: Box<[u8]> = Box::new([44u8; 31]); // Wrong length
        let result = SerializedTxid::try_from(boxed);
        assert!(result.is_err(), "Should fail with invalid length");
    }

    #[test]
    fn test_serialized_txid_from_bitcoin_txid() {
        let bitcoin_txid = Txid::from_raw_hash(Hash::from_slice(&[100u8; 32]).unwrap());
        let serialized_txid = SerializedTxid::from(bitcoin_txid);
        assert_eq!(
            serialized_txid.as_bytes(),
            bitcoin_txid.as_raw_hash().as_byte_array()
        );
    }

    #[test]
    fn test_serialized_txid_from_bitcoin_txid_ref() {
        let bitcoin_txid = Txid::from_raw_hash(Hash::from_slice(&[101u8; 32]).unwrap());
        let serialized_txid = SerializedTxid::from(&bitcoin_txid);
        assert_eq!(
            serialized_txid.as_bytes(),
            bitcoin_txid.as_raw_hash().as_byte_array()
        );
    }

    #[test]
    fn test_serialized_txid_from_bitcoin_txid_double_ref() {
        let bitcoin_txid = Txid::from_raw_hash(Hash::from_slice(&[102u8; 32]).unwrap());
        let serialized_txid = SerializedTxid::from(&&bitcoin_txid);
        assert_eq!(
            serialized_txid.as_bytes(),
            bitcoin_txid.as_raw_hash().as_byte_array()
        );
    }

    #[test]
    fn test_serialized_txid_to_bitcoin_txid() {
        let bytes = [103u8; 32];
        let serialized_txid = SerializedTxid::from(bytes);
        let bitcoin_txid: Txid = serialized_txid.into();
        assert_eq!(bitcoin_txid.as_raw_hash().as_byte_array(), &bytes);
    }

    #[test]
    fn test_serialized_txid_to_bitcoin_txid_ref() {
        let bytes = [104u8; 32];
        let serialized_txid = SerializedTxid::from(bytes);
        let bitcoin_txid: Txid = (&serialized_txid).into();
        assert_eq!(bitcoin_txid.as_raw_hash().as_byte_array(), &bytes);
    }

    #[test]
    fn test_serialized_txid_display() {
        let bytes = [1u8; 32];
        let txid = SerializedTxid::from(bytes);
        let display_str = txid.to_string();

        // The display should show the reversed hex string (Bitcoin convention)
        assert_eq!(display_str.len(), 64); // 32 bytes * 2 hex chars
        assert!(display_str.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_serialized_txid_from_str() {
        // Test with a known pattern
        let hex_str = "0101010101010101010101010101010101010101010101010101010101010101";
        let txid = SerializedTxid::from_str(hex_str).expect("Should parse valid hex string");

        // Verify roundtrip
        let back_to_string = txid.to_string();
        assert_eq!(hex_str, back_to_string);
    }

    #[test]
    fn test_serialized_txid_from_str_invalid_length() {
        let invalid_hex = "0101"; // Too short
        let result = SerializedTxid::from_str(invalid_hex);
        assert!(result.is_err(), "Should fail with invalid length");
    }

    #[test]
    fn test_serialized_txid_from_str_invalid_hex() {
        let invalid_hex = "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg";
        let result = SerializedTxid::from_str(invalid_hex);
        assert!(result.is_err(), "Should fail with invalid hex characters");
    }

    #[test]
    fn test_serialized_txid_consistency() {
        let original = create_test_txid();

        // Test that multiple serializations produce the same result
        let serialized1 = borsh::to_vec(&original).unwrap();
        let serialized2 = borsh::to_vec(&original).unwrap();
        assert_eq!(serialized1, serialized2);

        // Test that deserialization produces the same value
        let deserialized1 = borsh::from_slice::<SerializedTxid>(&serialized1).unwrap();
        let deserialized2 = borsh::from_slice::<SerializedTxid>(&serialized2).unwrap();
        assert_eq!(deserialized1, deserialized2);
        assert_eq!(original, deserialized1);
    }

    #[test]
    fn test_serialized_txid_hash_and_eq() {
        let txid1 = create_test_txid();
        let txid2 = create_test_txid();
        let txid3 = create_zero_txid();

        assert_eq!(txid1, txid2);
        assert_ne!(txid1, txid3);

        // Test that equal values have the same hash
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        txid1.hash(&mut hasher1);
        txid2.hash(&mut hasher2);
        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[test]
    fn test_serialized_txid_clone_copy() {
        let original = create_test_txid();
        let cloned = original.clone();
        let copied = original;

        assert_eq!(original, cloned);
        assert_eq!(original, copied);
    }

    #[test]
    fn test_serialized_txid_debug() {
        let txid = create_test_txid();
        let debug_str = format!("{:?}", txid);
        assert!(debug_str.contains("SerializedTxid"));
    }

    #[test]
    fn test_serialized_txid_patterns() {
        // Test various bit patterns
        let patterns = [
            [0u8; 32],
            [255u8; 32],
            {
                let mut pattern = [0u8; 32];
                pattern[0] = 255;
                pattern
            },
            {
                let mut pattern = [0u8; 32];
                pattern[31] = 255;
                pattern
            },
            {
                let mut pattern = [0u8; 32];
                for i in 0..32 {
                    pattern[i] = i as u8;
                }
                pattern
            },
        ];

        for pattern in patterns {
            let txid = SerializedTxid::from(pattern);
            test_borsh_roundtrip(&txid);
            test_serde_roundtrip(&txid);

            // Test string roundtrip
            let hex_str = txid.to_string();
            let from_str = SerializedTxid::from_str(&hex_str).unwrap();
            assert_eq!(txid, from_str);
        }
    }

    #[test]
    fn test_serialized_txid_bitcoin_interop() {
        // Test interoperability with Bitcoin txids
        let test_cases = [[0u8; 32], [1u8; 32], [255u8; 32]];

        for bytes in test_cases {
            let serialized_txid = SerializedTxid::from(bytes);

            // Convert to Bitcoin Txid and back
            let bitcoin_txid: Txid = serialized_txid.into();
            let back_to_serialized: SerializedTxid = bitcoin_txid.into();

            assert_eq!(serialized_txid, back_to_serialized);
        }
    }
}