Skip to main content

qualia_core_db/q42/volume/
magnet.rs

1//! WebTorrent magnets for unified `.q42` files and volume-set snapshots.
2//!
3//! One artifact → one SHA-1 info-hash (BEP 9 `urn:btih:`). A volume root
4//! publishes its own magnet plus one magnet per child segment. The daemon
5//! web-seeds each file at `/torrent/webseed/{info_hash}`.
6//!
7//! Magnets are Permissive Commons *transport*, not a default. Personal,
8//! medical, bilateral, and unmarked volumes are denied here; they travel
9//! on SocialWebNet or stay in Sanctuary.
10
11use std::fs;
12use std::io::{self, Read};
13use std::path::Path;
14
15use serde::Serialize;
16use sha1::{Digest, Sha1};
17
18use super::super::Q42Volume;
19use super::publication::{
20    classify_q42_path, classify_q42_volume_set, deny_public_publication, PublicationIntent,
21};
22
23/// A single-file magnet for one immutable Q42 artifact.
24#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
25pub struct Q42Magnet {
26    pub path: String,
27    pub display_name: String,
28    pub info_hash_sha1: String,
29    pub byte_length: u64,
30    pub magnet_uri: String,
31}
32
33/// Root + children, each with its own magnet (one info-hash per file).
34#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
35pub struct Q42VolumeSetMagnets {
36    pub root: Q42Magnet,
37    pub children: Vec<Q42Magnet>,
38}
39
40impl Q42Magnet {
41    /// Builds a magnet for the volume at `path` with optional webseed.
42    pub fn for_path(path: &Path, webseed: Option<&str>) -> io::Result<Self> {
43        Self::for_path_with_intent(path, webseed, PublicationIntent::Default)
44    }
45
46    /// Builds a magnet for `path` under an explicit display name.
47    pub fn for_path_named(
48        path: &Path,
49        display_name: &str,
50        webseed: Option<&str>,
51    ) -> io::Result<Self> {
52        Self::for_path_named_with_intent(path, display_name, webseed, PublicationIntent::Default)
53    }
54
55    /// Builds a magnet for `path` with an intent tag.
56    pub fn for_path_with_intent(
57        path: &Path,
58        webseed: Option<&str>,
59        intent: PublicationIntent,
60    ) -> io::Result<Self> {
61        let display = path
62            .file_name()
63            .and_then(|n| n.to_str())
64            .unwrap_or("volume.q42")
65            .to_string();
66        Self::for_path_named_with_intent(path, &display, webseed, intent)
67    }
68
69    /// Builds a named magnet with an intent tag.
70    pub fn for_path_named_with_intent(
71        path: &Path,
72        display_name: &str,
73        webseed: Option<&str>,
74        intent: PublicationIntent,
75    ) -> io::Result<Self> {
76        deny_public_publication(&classify_q42_path(path, intent)?)?;
77        let meta = fs::metadata(path)?;
78        if !meta.is_file() {
79            return Err(io::Error::new(
80                io::ErrorKind::InvalidInput,
81                "Q42 magnet requires a file",
82            ));
83        }
84        let info_hash_sha1 = sha1_hex_file(path)?;
85        let magnet_uri = compose_magnet(&info_hash_sha1, display_name, meta.len(), webseed);
86        Ok(Self {
87            path: path.display().to_string(),
88            display_name: display_name.to_string(),
89            info_hash_sha1,
90            byte_length: meta.len(),
91            magnet_uri,
92        })
93    }
94
95    /// Loopback daemon web-seed (`ws=`). Still fail-closed on Sanctuary volumes.
96    pub fn for_daemon_seed(path: &Path, display_name: &str, daemon_port: u16) -> io::Result<Self> {
97        Self::for_daemon_seed_with_intent(
98            path,
99            display_name,
100            daemon_port,
101            PublicationIntent::Default,
102        )
103    }
104
105    /// Builds a magnet referencing a daemon seed with intent.
106    pub fn for_daemon_seed_with_intent(
107        path: &Path,
108        display_name: &str,
109        daemon_port: u16,
110        intent: PublicationIntent,
111    ) -> io::Result<Self> {
112        let hash = sha1_hex_file(path)?;
113        let ws = format!("http://127.0.0.1:{daemon_port}/torrent/webseed/{hash}");
114        Self::for_path_named_with_intent(path, display_name, Some(&ws), intent)
115    }
116}
117
118impl Q42VolumeSetMagnets {
119    /// Builds per-volume magnets for every volume under `root`.
120    pub fn for_root(path: &Path, webseed_base: Option<&str>) -> io::Result<Self> {
121        Self::for_root_with_intent(path, webseed_base, PublicationIntent::Default)
122    }
123
124    /// Builds per-volume magnets under `root` with an intent tag.
125    pub fn for_root_with_intent(
126        path: &Path,
127        webseed_base: Option<&str>,
128        intent: PublicationIntent,
129    ) -> io::Result<Self> {
130        deny_public_publication(&classify_q42_volume_set(path, intent)?)?;
131        let root_vol = Q42Volume::open(path)?;
132        let root_ws = webseed_for(path, webseed_base)?;
133        let root = Q42Magnet::for_path(path, root_ws.as_deref())?;
134        let Some(manifest) = root_vol.volume_manifest()? else {
135            return Ok(Self {
136                root,
137                children: Vec::new(),
138            });
139        };
140        let parent = path.parent().unwrap_or(Path::new("."));
141        let mut children = Vec::new();
142        for entry in &manifest.segments {
143            let child = parent.join(&entry.locator);
144            let ws = webseed_for(&child, webseed_base)?;
145            children.push(Q42Magnet::for_path_with_intent(
146                &child,
147                ws.as_deref(),
148                intent,
149            )?);
150        }
151        Ok(Self { root, children })
152    }
153}
154
155/// Composes a magnet URI from components.
156pub fn compose_magnet(
157    info_hash_sha1: &str,
158    display_name: &str,
159    byte_length: u64,
160    webseed: Option<&str>,
161) -> String {
162    let hash = info_hash_sha1.trim().to_ascii_lowercase();
163    let dn = urlencoding::encode(display_name);
164    let mut uri = format!("magnet:?xt=urn:btih:{hash}&dn={dn}&xl={byte_length}");
165    if let Some(ws) = webseed {
166        uri.push_str("&ws=");
167        uri.push_str(&urlencoding::encode(ws));
168        uri.push_str("&xs=");
169        uri.push_str(&urlencoding::encode(ws));
170    }
171    uri
172}
173
174/// Streaming SHA-1 hex digest of a file.
175pub fn sha1_hex_file(path: &Path) -> io::Result<String> {
176    let mut file = fs::File::open(path)?;
177    let mut hasher = Sha1::new();
178    let mut buf = [0u8; 64 * 1024];
179    loop {
180        let n = file.read(&mut buf)?;
181        if n == 0 {
182            break;
183        }
184        hasher.update(&buf[..n]);
185    }
186    Ok(hasher
187        .finalize()
188        .iter()
189        .map(|b| format!("{b:02x}"))
190        .collect())
191}
192
193fn webseed_for(path: &Path, base: Option<&str>) -> io::Result<Option<String>> {
194    let Some(base) = base else {
195        return Ok(None);
196    };
197    if base.contains("{hash}") {
198        let hash = sha1_hex_file(path)?;
199        return Ok(Some(base.replace("{hash}", &hash)));
200    }
201    Ok(Some(base.trim_end_matches('/').to_string()))
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use crate::q42_volume::write_unified_volume;
208    use crate::NQuin;
209    use std::collections::HashMap;
210
211    #[test]
212    fn unmarked_volume_cannot_mint_a_magnet() {
213        let file = tempfile::NamedTempFile::new().unwrap();
214        write_unified_volume(
215            file.path(),
216            &HashMap::new(),
217            &[(3, 3)],
218            &[vec![NQuin {
219                subject: 1,
220                predicate: 2,
221                object: 3,
222                context: 0,
223                metadata: 0,
224                parity: 0,
225            }]],
226        )
227        .unwrap();
228        let err = Q42Magnet::for_daemon_seed(file.path(), "demo.q42", 4242).unwrap_err();
229        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
230        assert!(err.to_string().contains("publication denied"));
231    }
232
233    #[test]
234    fn commons_catalog_magnet_has_btih_xl_and_webseed() {
235        let file = tempfile::NamedTempFile::new().unwrap();
236        write_unified_volume(
237            file.path(),
238            &HashMap::new(),
239            &[(3, 3)],
240            &[vec![NQuin {
241                subject: 1,
242                predicate: 2,
243                object: 3,
244                context: 0,
245                metadata: 0,
246                parity: 0,
247            }]],
248        )
249        .unwrap();
250        let magnet = Q42Magnet::for_daemon_seed_with_intent(
251            file.path(),
252            "demo.q42",
253            4242,
254            PublicationIntent::CommonsCatalog,
255        )
256        .unwrap();
257        assert!(magnet.magnet_uri.starts_with("magnet:?xt=urn:btih:"));
258        assert!(magnet.magnet_uri.contains("&dn=demo.q42"));
259        assert!(magnet
260            .magnet_uri
261            .contains(&format!("&xl={}", magnet.byte_length)));
262        assert!(magnet.magnet_uri.contains("webseed"));
263        assert_eq!(magnet.info_hash_sha1.len(), 40);
264    }
265}