1use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
13#[serde(transparent)]
14pub struct ContentCid(String);
15
16impl ContentCid {
17 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 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 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 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
76impl<'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
89const DOMAIN_SHA1: &[u8; 4] = b"sha1";
92const DOMAIN_S256: &[u8; 4] = b"s256";
93
94#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
103pub enum GitHash {
104 Sha1([u8; 20]),
106 Sha256([u8; 32]),
108}
109
110impl GitHash {
111 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 pub fn from_sha1_bytes(bytes: [u8; 20]) -> Self {
135 GitHash::Sha1(bytes)
136 }
137
138 pub fn from_sha256_bytes(bytes: [u8; 32]) -> Self {
140 GitHash::Sha256(bytes)
141 }
142
143 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 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 pub fn as_bytes(&self) -> &[u8] {
176 match self {
177 GitHash::Sha1(b) => b,
178 GitHash::Sha256(b) => b,
179 }
180 }
181
182 pub fn is_sha256(&self) -> bool {
184 matches!(self, GitHash::Sha256(_))
185 }
186
187 pub fn is_sha1(&self) -> bool {
189 matches!(self, GitHash::Sha1(_))
190 }
191
192 pub fn object_format(&self) -> ObjectFormat {
194 ObjectFormat::from(self)
195 }
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub enum ObjectFormat {
208 Sha1,
210 Sha256,
212}
213
214impl ObjectFormat {
215 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
241pub struct MutableKey(pub String);
242
243impl MutableKey {
244 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 pub fn as_str(&self) -> &str {
255 &self.0
256 }
257
258 pub fn to_bytes(&self) -> Vec<u8> {
263 hex::decode(&self.0).unwrap_or_default()
264 }
265}
266
267#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
269pub struct Sha256Hash(pub String);
270
271impl Sha256Hash {
272 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 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 pub fn as_str(&self) -> &str {
294 &self.0
295 }
296
297 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#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct GitRef {
315 pub name: String,
316 pub hash: GitHash,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct GitRefs {
322 pub refs: std::collections::HashMap<String, GitHash>,
324 pub head: String,
326 pub created_at: u64,
328}
329
330#[derive(Debug, Clone)]
332pub enum GitTorrentUrl {
333 Commit { hash: Sha256Hash },
335 CommitWithRefs { hash: Sha256Hash },
337 GitServer { server: String, repo: String },
339 Username { username: String },
341}
342
343impl GitTorrentUrl {
344 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..]; 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 if main_part.len() == 64 && main_part.chars().all(|c| c.is_ascii_hexdigit()) {
363 let hash = Sha256Hash::new(main_part)?;
364
365 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 if let Some(slash_pos) = main_part.find('/') {
377 let (server, repo) = main_part.split_at(slash_pos);
378 let repo = &repo[1..]; Ok(GitTorrentUrl::GitServer {
381 server: server.to_owned(),
382 repo: repo.to_owned(),
383 })
384 } else {
385 Ok(GitTorrentUrl::Username {
387 username: main_part.to_owned(),
388 })
389 }
390 }
391
392 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 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 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()); assert!(
494 Sha256Hash::new("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")
495 .is_err()
496 ); }
498
499 #[test]
500 fn test_gittorrent_url_parsing() -> crate::error::Result<()> {
501 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 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 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 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 let url1 = GitTorrentUrl::parse(&format!("gittorrent://{test_hash}"))?;
556 assert_eq!(url1.to_string(), format!("gittorrent://{test_hash}"));
557
558 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 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 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 assert!(GitHash::from_hex("0123456789").is_err());
594 assert!(GitHash::from_hex(
596 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00"
597 )
598 .is_err());
599 assert!(GitHash::from_hex("ghijklmnopqrstuvwxyz0123456789abcdef01234567").is_err());
601 assert!(GitHash::from_hex("0123456789abcdef0123456789abcdef012345678").is_err());
603 }
605
606 #[test]
607 fn test_git_hash_dht_key_domain_separation() -> crate::error::Result<()> {
608 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 assert_ne!(sha1_dht_key, sha256_dht_key);
621
622 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 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}