Skip to main content

hyprstream_p2p/
types.rs

1//! Core types for GitTorrent
2
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6/// Canonical CIDv1 envelope for an object-plane key.
7///
8/// The CID carries both the content domain (multicodec) and hash algorithm
9/// (multihash). Keeping the complete envelope at crate boundaries prevents
10/// equal-width digests such as an XET MerkleHash and SHA-256 from being
11/// silently reinterpreted as one another.
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
13#[serde(transparent)]
14pub struct ContentCid(String);
15
16impl ContentCid {
17    /// Parse and validate a canonical CID understood by hyprstream.
18    ///
19    /// The input is re-encoded to the canonical lowercase base32 text before
20    /// being stored: base32 decoding is case-insensitive, so equivalent
21    /// spellings must collapse to one representation — `Eq`/`Hash` and the
22    /// rendezvous derivation all operate on the string form.
23    pub fn new(cid: impl Into<String>) -> crate::Result<Self> {
24        let cid = cid.into();
25        let decoded = hyprstream_rpc::cid::decode_cid(&cid)
26            .map_err(|e| crate::Error::other(format!("invalid content CID: {e}")))?;
27        let canonical = hyprstream_rpc::cid::encode_cid(
28            decoded.codec,
29            decoded.multihash.algo,
30            &decoded.multihash.digest,
31        )
32        .map_err(|e| crate::Error::other(format!("failed to canonicalize content CID: {e}")))?;
33        Ok(Self(canonical))
34    }
35
36    /// Address a raw Git object by its SHA-256 digest.
37    pub fn git_sha256(hash: &Sha256Hash) -> crate::Result<Self> {
38        let digest = hash.to_bytes();
39        let cid = hyprstream_rpc::cid::encode_cid(
40            hyprstream_rpc::cid::Codec::GitRaw,
41            hyprstream_rpc::cid::HashAlgo::Sha2_256,
42            &digest,
43        )
44        .map_err(|e| crate::Error::other(format!("failed to encode Git object CID: {e}")))?;
45        Ok(Self(cid))
46    }
47
48    /// Address a XET file reconstruction DAG by its real keyed-BLAKE3 Merkle hash.
49    pub fn xet_merkle(hash: &[u8]) -> crate::Result<Self> {
50        let cid = hyprstream_rpc::cid::encode_cid(
51            hyprstream_rpc::cid::Codec::XetShard,
52            hyprstream_rpc::cid::HashAlgo::Blake3,
53            hash,
54        )
55        .map_err(|e| crate::Error::other(format!("failed to encode XET Merkle CID: {e}")))?;
56        Ok(Self(cid))
57    }
58
59    /// Return the canonical CID text used for persistence and rendezvous derivation.
60    pub fn as_str(&self) -> &str {
61        &self.0
62    }
63
64    pub(crate) fn decoded(&self) -> crate::Result<hyprstream_rpc::cid::Cid> {
65        hyprstream_rpc::cid::decode_cid(&self.0)
66            .map_err(|e| crate::Error::other(format!("invalid stored content CID: {e}")))
67    }
68}
69
70impl std::fmt::Display for ContentCid {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.write_str(&self.0)
73    }
74}
75
76/// Route deserialization through [`ContentCid::new`] so every ingress path
77/// validates and canonicalizes — a transparent derive would accept arbitrary
78/// strings verbatim.
79impl<'de> Deserialize<'de> for ContentCid {
80    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
81    where
82        D: serde::Deserializer<'de>,
83    {
84        let s = String::deserialize(deserializer)?;
85        ContentCid::new(s).map_err(serde::de::Error::custom)
86    }
87}
88
89/// Fixed-width domain prefixes for DHT key derivation (4 bytes each)
90/// These ensure SHA1 and SHA256 git objects are stored in separate DHT keyspaces
91const DOMAIN_SHA1: &[u8; 4] = b"sha1";
92const DOMAIN_S256: &[u8; 4] = b"s256";
93
94/// A Git object hash - either SHA1 (legacy) or SHA256 (modern)
95///
96/// Git traditionally uses SHA1 (20 bytes / 40 hex chars) for object hashes.
97/// Modern git supports SHA256 (32 bytes / 64 hex chars) but tooling support varies.
98/// This enum supports both, auto-detecting by length when parsing.
99///
100/// For DHT storage, use `to_dht_key()` which derives a 256-bit key with domain
101/// separation per the libp2p Kademlia spec.
102#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
103pub enum GitHash {
104    /// SHA1 hash (20 bytes / 40 hex chars) - legacy git format
105    Sha1([u8; 20]),
106    /// SHA256 hash (32 bytes / 64 hex chars) - modern git format
107    Sha256([u8; 32]),
108}
109
110impl GitHash {
111    /// Parse from hex string (auto-detects algorithm by length)
112    ///
113    /// - 40 hex chars -> SHA1
114    /// - 64 hex chars -> SHA256
115    /// - Other lengths -> Error
116    pub fn from_hex(s: &str) -> crate::Result<Self> {
117        let bytes = hex::decode(s).map_err(|_| crate::Error::InvalidHash(s.to_owned()))?;
118        match bytes.len() {
119            20 => {
120                let mut arr = [0u8; 20];
121                arr.copy_from_slice(&bytes);
122                Ok(GitHash::Sha1(arr))
123            }
124            32 => {
125                let mut arr = [0u8; 32];
126                arr.copy_from_slice(&bytes);
127                Ok(GitHash::Sha256(arr))
128            }
129            _ => Err(crate::Error::InvalidHash(s.to_owned())),
130        }
131    }
132
133    /// Create from raw SHA1 bytes
134    pub fn from_sha1_bytes(bytes: [u8; 20]) -> Self {
135        GitHash::Sha1(bytes)
136    }
137
138    /// Create from raw SHA256 bytes
139    pub fn from_sha256_bytes(bytes: [u8; 32]) -> Self {
140        GitHash::Sha256(bytes)
141    }
142
143    /// Derive DHT key using domain separation per libp2p Kademlia spec
144    ///
145    /// The DHT key is: `sha256(DOMAIN_PREFIX || RAW_HASH_BYTES)`
146    ///
147    /// This ensures:
148    /// - Both SHA1 and SHA256 hashes map to 256-bit DHT keys
149    /// - Keys are in separate DHT namespaces (no collisions)
150    /// - Forward-compatible when git switches to SHA256
151    pub fn to_dht_key(&self) -> [u8; 32] {
152        let mut hasher = Sha256::new();
153        match self {
154            GitHash::Sha1(bytes) => {
155                hasher.update(DOMAIN_SHA1);
156                hasher.update(bytes);
157            }
158            GitHash::Sha256(bytes) => {
159                hasher.update(DOMAIN_S256);
160                hasher.update(bytes);
161            }
162        }
163        hasher.finalize().into()
164    }
165
166    /// Convert to hex string representation
167    pub fn to_hex(&self) -> String {
168        match self {
169            GitHash::Sha1(b) => hex::encode(b),
170            GitHash::Sha256(b) => hex::encode(b),
171        }
172    }
173
174    /// Get the raw bytes
175    pub fn as_bytes(&self) -> &[u8] {
176        match self {
177            GitHash::Sha1(b) => b,
178            GitHash::Sha256(b) => b,
179        }
180    }
181
182    /// Check if this is a SHA256 hash
183    pub fn is_sha256(&self) -> bool {
184        matches!(self, GitHash::Sha256(_))
185    }
186
187    /// Check if this is a SHA1 hash
188    pub fn is_sha1(&self) -> bool {
189        matches!(self, GitHash::Sha1(_))
190    }
191
192    /// Object format (hash algorithm) this hash belongs to.
193    pub fn object_format(&self) -> ObjectFormat {
194        ObjectFormat::from(self)
195    }
196}
197
198/// Git repository object format (hash algorithm).
199///
200/// Git objects that embed references in **binary** form (notably tree
201/// entries) do not self-describe their hash width, so the width must be
202/// carried from the surrounding context (the object's own hash, or the
203/// repository's `extensions.objectFormat`). This enum makes that context
204/// explicit so a SHA-256 repository is not parsed with a hardcoded 20-byte
205/// (SHA-1) OID width.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub enum ObjectFormat {
208    /// SHA1 object format (20-byte raw OIDs) - legacy git format.
209    Sha1,
210    /// SHA256 object format (32-byte raw OIDs) - modern git format.
211    Sha256,
212}
213
214impl ObjectFormat {
215    /// Raw hash width in bytes for this object format (SHA1 = 20, SHA256 = 32).
216    pub const fn hash_len(self) -> usize {
217        match self {
218            ObjectFormat::Sha1 => 20,
219            ObjectFormat::Sha256 => 32,
220        }
221    }
222}
223
224impl From<&GitHash> for ObjectFormat {
225    fn from(hash: &GitHash) -> Self {
226        match hash {
227            GitHash::Sha1(_) => ObjectFormat::Sha1,
228            GitHash::Sha256(_) => ObjectFormat::Sha256,
229        }
230    }
231}
232
233impl std::fmt::Display for GitHash {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        write!(f, "{}", self.to_hex())
236    }
237}
238
239/// A mutable key derived from a public key (SHA256 hash)
240#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
241pub struct MutableKey(pub String);
242
243impl MutableKey {
244    /// Create a new mutable key from a hex string
245    pub fn new(s: impl Into<String>) -> crate::Result<Self> {
246        let s = s.into();
247        if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
248            return Err(crate::Error::InvalidMutableKey(s));
249        }
250        Ok(MutableKey(s))
251    }
252
253    /// Get the hex string representation
254    pub fn as_str(&self) -> &str {
255        &self.0
256    }
257
258    /// Convert to bytes
259    ///
260    /// Returns empty Vec if hex decoding fails (should never happen as
261    /// MutableKey is validated in constructor)
262    pub fn to_bytes(&self) -> Vec<u8> {
263        hex::decode(&self.0).unwrap_or_default()
264    }
265}
266
267/// A Git SHA256 hash (64 hex characters)
268#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
269pub struct Sha256Hash(pub String);
270
271impl Sha256Hash {
272    /// Create a new SHA256 from a hex string
273    pub fn new(s: impl Into<String>) -> crate::Result<Self> {
274        let s = s.into();
275        if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
276            return Err(crate::Error::InvalidSha256(s));
277        }
278        Ok(Sha256Hash(s))
279    }
280
281    /// Create from bytes
282    pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
283        if bytes.len() != 32 {
284            return Err(crate::Error::InvalidSha256(format!(
285                "Expected 32 bytes, got {}",
286                bytes.len()
287            )));
288        }
289        Ok(Sha256Hash(hex::encode(bytes)))
290    }
291
292    /// Get the hex string representation
293    pub fn as_str(&self) -> &str {
294        &self.0
295    }
296
297    /// Convert to bytes
298    ///
299    /// Returns empty Vec if hex decoding fails (should never happen as
300    /// Sha256Hash is validated in constructor)
301    pub fn to_bytes(&self) -> Vec<u8> {
302        hex::decode(&self.0).unwrap_or_default()
303    }
304}
305
306impl std::fmt::Display for Sha256Hash {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        write!(f, "{}", self.0)
309    }
310}
311
312/// A Git reference (branch/tag) with its hash (SHA1 or SHA256)
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct GitRef {
315    pub name: String,
316    pub hash: GitHash,
317}
318
319/// Git references metadata for a repository
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct GitRefs {
322    /// Git references (branches, tags)
323    pub refs: std::collections::HashMap<String, GitHash>,
324    /// Current HEAD reference
325    pub head: String,
326    /// Creation timestamp
327    pub created_at: u64,
328}
329
330/// GitTorrent URL variants
331#[derive(Debug, Clone)]
332pub enum GitTorrentUrl {
333    /// gittorrent://COMMIT_SHA256 (pure commit-based cloning)
334    Commit { hash: Sha256Hash },
335    /// gittorrent://COMMIT_SHA256?refs (commit + references)
336    CommitWithRefs { hash: Sha256Hash },
337    /// gittorrent://server/repo (legacy: uses git:// for discovery)
338    GitServer { server: String, repo: String },
339    /// gittorrent://username (External lookup)
340    Username { username: String },
341}
342
343impl GitTorrentUrl {
344    /// Parse a gittorrent:// URL
345    pub fn parse(url: &str) -> crate::Result<Self> {
346        if !url.starts_with("gittorrent://") {
347            return Err(crate::Error::InvalidUrl(format!(
348                "URL must start with gittorrent://: {url}"
349            )));
350        }
351
352        let url = &url[13..]; // Remove "gittorrent://"
353
354        // Check for query parameters
355        let (main_part, query) = if let Some(q_pos) = url.find('?') {
356            (&url[..q_pos], Some(&url[q_pos + 1..]))
357        } else {
358            (url, None)
359        };
360
361        // Check if it's a 64-char hex string (SHA256 hash)
362        if main_part.len() == 64 && main_part.chars().all(|c| c.is_ascii_hexdigit()) {
363            let hash = Sha256Hash::new(main_part)?;
364
365            // Check for refs parameter
366            if let Some(query_str) = query {
367                if query_str == "refs" {
368                    return Ok(GitTorrentUrl::CommitWithRefs { hash });
369                }
370            }
371
372            return Ok(GitTorrentUrl::Commit { hash });
373        }
374
375        // Handle legacy formats
376        if let Some(slash_pos) = main_part.find('/') {
377            let (server, repo) = main_part.split_at(slash_pos);
378            let repo = &repo[1..]; // Remove leading slash
379
380            Ok(GitTorrentUrl::GitServer {
381                server: server.to_owned(),
382                repo: repo.to_owned(),
383            })
384        } else {
385            // No slash, assume it's a username
386            Ok(GitTorrentUrl::Username {
387                username: main_part.to_owned(),
388            })
389        }
390    }
391
392    /// Get the commit hash if this is a commit-based URL
393    pub fn commit_hash(&self) -> Option<&Sha256Hash> {
394        match self {
395            GitTorrentUrl::Commit { hash } | GitTorrentUrl::CommitWithRefs { hash } => Some(hash),
396            _ => None,
397        }
398    }
399
400    /// Check if this URL includes references
401    pub fn includes_refs(&self) -> bool {
402        matches!(self, GitTorrentUrl::CommitWithRefs { .. })
403    }
404}
405
406impl std::fmt::Display for GitTorrentUrl {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        match self {
409            GitTorrentUrl::Commit { hash } => {
410                write!(f, "gittorrent://{hash}")
411            }
412            GitTorrentUrl::CommitWithRefs { hash } => {
413                write!(f, "gittorrent://{hash}?refs")
414            }
415            GitTorrentUrl::GitServer { server, repo } => {
416                write!(f, "gittorrent://{server}/{repo}")
417            }
418            GitTorrentUrl::Username { username } => {
419                write!(f, "gittorrent://{username}")
420            }
421        }
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    #[test]
430    fn test_content_cid_preserves_xet_merkle_domain() -> crate::Result<()> {
431        let digest = [0x42; 32];
432        let merkle = ContentCid::xet_merkle(&digest)?;
433        let git = ContentCid::git_sha256(&Sha256Hash::from_bytes(&digest)?)?;
434
435        let decoded = merkle.decoded()?;
436        assert_eq!(decoded.codec, hyprstream_rpc::cid::Codec::XetShard);
437        assert_eq!(
438            decoded.multihash.algo,
439            hyprstream_rpc::cid::HashAlgo::Blake3
440        );
441        assert_eq!(decoded.multihash.digest, digest);
442        assert_ne!(
443            merkle, git,
444            "equal-width digest bytes in different domains must not alias"
445        );
446        Ok(())
447    }
448
449    #[test]
450    fn test_content_cid_canonicalizes_spelling_on_new() -> crate::Result<()> {
451        let canonical = ContentCid::xet_merkle(&[0x42; 32])?;
452        // base32 is case-insensitive on decode: an uppercase spelling of the
453        // same CID must collapse to the identical canonical value.
454        let shouted = format!("b{}", canonical.as_str()[1..].to_ascii_uppercase());
455        let reparsed = ContentCid::new(shouted)?;
456        assert_eq!(reparsed, canonical);
457        assert_eq!(reparsed.as_str(), canonical.as_str());
458        Ok(())
459    }
460
461    #[test]
462    fn test_content_cid_deserialize_validates_and_canonicalizes() -> crate::Result<()> {
463        let canonical = ContentCid::git_sha256(&Sha256Hash::new(
464            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
465        )?)?;
466        let shouted = format!("b{}", canonical.as_str()[1..].to_ascii_uppercase());
467        let parsed: ContentCid = serde_json::from_str(&format!("\"{shouted}\""))
468            .map_err(|e| crate::Error::other(e.to_string()))?;
469        assert_eq!(parsed, canonical);
470
471        assert!(serde_json::from_str::<ContentCid>("\"not-a-cid\"").is_err());
472        Ok(())
473    }
474
475    #[test]
476    fn test_sha256_creation() -> crate::error::Result<()> {
477        let sha256 =
478            Sha256Hash::new("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")?;
479        assert_eq!(
480            sha256.as_str(),
481            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
482        );
483        Ok(())
484    }
485
486    #[test]
487    fn test_invalid_sha256() {
488        assert!(Sha256Hash::new("invalid").is_err());
489        assert!(Sha256Hash::new(
490            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg"
491        )
492        .is_err()); // invalid char
493        assert!(
494            Sha256Hash::new("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")
495                .is_err()
496        ); // too short
497    }
498
499    #[test]
500    fn test_gittorrent_url_parsing() -> crate::error::Result<()> {
501        // Test commit hash URL (new format)
502        let url = GitTorrentUrl::parse(
503            "gittorrent://0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
504        )?;
505        match url {
506            GitTorrentUrl::Commit { hash } => {
507                assert_eq!(
508                    hash.as_str(),
509                    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
510                );
511            }
512            _ => panic!("Expected Commit variant"),
513        }
514
515        // Test commit hash with refs URL
516        let url = GitTorrentUrl::parse(
517            "gittorrent://0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef?refs",
518        )?;
519        match url {
520            GitTorrentUrl::CommitWithRefs { hash } => {
521                assert_eq!(
522                    hash.as_str(),
523                    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
524                );
525            }
526            _ => panic!("Expected CommitWithRefs variant"),
527        }
528
529        // Test git server URL (legacy)
530        let url = GitTorrentUrl::parse("gittorrent://github.com/user/repo")?;
531        match url {
532            GitTorrentUrl::GitServer { server, repo } => {
533                assert_eq!(server, "github.com");
534                assert_eq!(repo, "user/repo");
535            }
536            _ => panic!("Expected GitServer variant"),
537        }
538
539        // Test username URL
540        let url = GitTorrentUrl::parse("gittorrent://username")?;
541        match url {
542            GitTorrentUrl::Username { username } => {
543                assert_eq!(username, "username");
544            }
545            _ => panic!("Expected Username variant"),
546        }
547        Ok(())
548    }
549
550    #[test]
551    fn test_gittorrent_url_roundtrip() -> crate::error::Result<()> {
552        let test_hash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
553
554        // Test commit URL
555        let url1 = GitTorrentUrl::parse(&format!("gittorrent://{test_hash}"))?;
556        assert_eq!(url1.to_string(), format!("gittorrent://{test_hash}"));
557
558        // Test commit with refs URL
559        let url2 = GitTorrentUrl::parse(&format!("gittorrent://{test_hash}?refs"))?;
560        assert_eq!(url2.to_string(), format!("gittorrent://{test_hash}?refs"));
561        Ok(())
562    }
563
564    #[test]
565    fn test_git_hash_sha1() -> crate::error::Result<()> {
566        // 40 hex chars = SHA1
567        let sha1_hex = "0123456789abcdef0123456789abcdef01234567";
568        let hash = GitHash::from_hex(sha1_hex)?;
569
570        assert!(hash.is_sha1());
571        assert!(!hash.is_sha256());
572        assert_eq!(hash.to_hex(), sha1_hex);
573        assert_eq!(hash.as_bytes().len(), 20);
574        Ok(())
575    }
576
577    #[test]
578    fn test_git_hash_sha256() -> crate::error::Result<()> {
579        // 64 hex chars = SHA256
580        let sha256_hex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
581        let hash = GitHash::from_hex(sha256_hex)?;
582
583        assert!(hash.is_sha256());
584        assert!(!hash.is_sha1());
585        assert_eq!(hash.to_hex(), sha256_hex);
586        assert_eq!(hash.as_bytes().len(), 32);
587        Ok(())
588    }
589
590    #[test]
591    fn test_git_hash_invalid() {
592        // Too short
593        assert!(GitHash::from_hex("0123456789").is_err());
594        // Too long
595        assert!(GitHash::from_hex(
596            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00"
597        )
598        .is_err());
599        // Invalid hex chars
600        assert!(GitHash::from_hex("ghijklmnopqrstuvwxyz0123456789abcdef01234567").is_err());
601        // Wrong length (not 40 or 64)
602        assert!(GitHash::from_hex("0123456789abcdef0123456789abcdef012345678").is_err());
603        // 41 chars
604    }
605
606    #[test]
607    fn test_git_hash_dht_key_domain_separation() -> crate::error::Result<()> {
608        // Same first 20 bytes, different algorithm -> different DHT keys
609        // SHA1: 40 hex chars, SHA256: 64 hex chars (same prefix + 24 zero chars)
610        let sha1_hex = "0123456789abcdef0123456789abcdef01234567";
611        let sha256_hex = "0123456789abcdef0123456789abcdef01234567000000000000000000000000";
612
613        let sha1_hash = GitHash::from_hex(sha1_hex)?;
614        let sha256_hash = GitHash::from_hex(sha256_hex)?;
615
616        let sha1_dht_key = sha1_hash.to_dht_key();
617        let sha256_dht_key = sha256_hash.to_dht_key();
618
619        // DHT keys should be different due to domain separation
620        assert_ne!(sha1_dht_key, sha256_dht_key);
621
622        // Both DHT keys should be 32 bytes (256-bit)
623        assert_eq!(sha1_dht_key.len(), 32);
624        assert_eq!(sha256_dht_key.len(), 32);
625        Ok(())
626    }
627
628    #[test]
629    fn test_git_hash_dht_key_deterministic() -> crate::error::Result<()> {
630        let sha1_hex = "0123456789abcdef0123456789abcdef01234567";
631        let hash1 = GitHash::from_hex(sha1_hex)?;
632        let hash2 = GitHash::from_hex(sha1_hex)?;
633
634        // Same input -> same DHT key
635        assert_eq!(hash1.to_dht_key(), hash2.to_dht_key());
636        Ok(())
637    }
638
639    #[test]
640    fn test_git_hash_display() -> crate::error::Result<()> {
641        let sha1_hex = "0123456789abcdef0123456789abcdef01234567";
642        let hash = GitHash::from_hex(sha1_hex)?;
643        assert_eq!(format!("{hash}"), sha1_hex);
644        Ok(())
645    }
646
647    #[test]
648    fn test_git_hash_from_bytes() {
649        let sha1_bytes = [0u8; 20];
650        let sha256_bytes = [0u8; 32];
651
652        let sha1 = GitHash::from_sha1_bytes(sha1_bytes);
653        let sha256 = GitHash::from_sha256_bytes(sha256_bytes);
654
655        assert!(sha1.is_sha1());
656        assert!(sha256.is_sha256());
657    }
658}