host-chain-core 0.3.2

WASM-compatible DotNS resolution, IPFS fetching, and CAR parsing (async, reqwest + ruzstd)
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Async DOTNS (DOT Name Service) on-chain resolution.
//!
//! Resolves `.dot` domain names to IPFS content hashes by querying the
//! DOTNS content resolver contract on Asset Hub Paseo via `state_call`.
//! Uses `reqwest` for HTTP — same code on native (rustls-tls) and WASM
//! (browser fetch via web-sys).
//!
//! Flow:
//! 1. ENS-style namehash of the domain (keccak256)
//! 2. ABI-encode the `contenthash(bytes32)` call
//! 3. SCALE-encode `ReviveApi::call()` parameters
//! 4. Send `state_call("ReviveApi_call", params)` via JSON-RPC HTTP
//! 5. Decode the response to extract the IPFS CID
//! 6. Fetch the CID from the IPFS gateway as a CARv1 file
//! 7. Parse the CAR file into a flat filename → bytes map

use crate::car::{is_car_file, parse_car_to_assets};
use std::collections::{HashMap, HashSet};
use std::error::Error as _;
use std::sync::OnceLock;

fn shared_client() -> &'static reqwest::Client {
    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
    CLIENT.get_or_init(|| {
        #[cfg(not(target_arch = "wasm32"))]
        {
            reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(30))
                .build()
                .expect("failed to build reqwest client")
        }
        #[cfg(target_arch = "wasm32")]
        {
            reqwest::Client::new()
        }
    })
}

// Pure encoding/decoding functions — delegated to host-encoding crate.
pub use host_encoding::dotns::{
    base32_encode, contenthash_to_cid, decode_abi_bytes, decode_contract_result,
    decode_scale_compact, decode_unsigned_varint, encode_contenthash_call, hex_addr, hex_decode,
    hex_encode, hex_nibble, keccak256, namehash, scale_compact_len, scale_compact_u64,
    scale_encode_revive_call,
};

/// DOTNS content resolver contract on Asset Hub Paseo.
pub const CONTENT_RESOLVER: [u8; 20] = hex_addr("7756DF72CBc7f062e7403cD59e45fBc78bed1cD7");

/// DOTNS registry contract on Asset Hub Paseo.
pub const REGISTRY: [u8; 20] = hex_addr("4Da0d37aBe96C06ab19963F31ca2DC0412057a6f");

/// Solidity function selector for `owner(bytes32)` on the DOTNS registry.
/// keccak256("owner(bytes32)")[:4]
pub const OWNER_SELECTOR: [u8; 4] = [0x02, 0x57, 0x1b, 0xe3];

/// JSON-RPC endpoints for Asset Hub Paseo (tried in order).
const RPC_ENDPOINTS: &[&str] = &[
    "https://sys.ibp.network/asset-hub-paseo",
    "https://asset-hub-paseo.dotters.network",
];

/// IPFS gateway for fetching resolved content.
pub const IPFS_GATEWAY: &str = "https://paseo-ipfs.polkadot.io";

/// The IPFS gateway URL used for fetching content.
pub fn ipfs_gateway() -> &'static str {
    IPFS_GATEWAY
}

/// Result of a full DOTNS resolution — includes the CID for verification display.
pub struct DotnsResolution {
    /// The IPFS CID that was resolved on-chain.
    pub cid: String,
    /// On-chain owner/addr associated with this name (if resolvable).
    pub owner: Option<String>,
    /// Fetched assets from IPFS.
    pub assets: HashMap<String, Vec<u8>>,
}

/// Send a `state_call` JSON-RPC request via HTTP (async, reqwest).
pub async fn rpc_state_call(method: &str, params_hex: &str) -> Result<Vec<u8>, String> {
    let payload = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "state_call",
        "params": [method, params_hex]
    });
    let payload_str = payload.to_string();

    let client = shared_client();

    for endpoint in RPC_ENDPOINTS {
        log::info!("[dotns] trying RPC: {endpoint}");
        let result = client
            .post(*endpoint)
            .header("Content-Type", "application/json")
            .body(payload_str.clone())
            .send()
            .await;

        match result {
            Ok(resp) => {
                let resp_bytes = match resp.bytes().await {
                    Ok(b) => b,
                    Err(e) => {
                        log::warn!("[dotns] failed to read response from {endpoint}: {e}");
                        continue;
                    }
                };
                let body: serde_json::Value = match serde_json::from_slice(&resp_bytes) {
                    Ok(v) => v,
                    Err(e) => {
                        log::warn!("[dotns] failed to parse response from {endpoint}: {e}");
                        continue;
                    }
                };
                let body_str = body.to_string();
                log::debug!(
                    "[dotns] response: {}",
                    if body_str.len() > 200 {
                        &body_str[..200]
                    } else {
                        &body_str
                    }
                );
                if let Some(err) = body.get("error") {
                    log::warn!("[dotns] RPC error from {endpoint}: {err}");
                    continue;
                }
                if let Some(result) = body.get("result").and_then(|v| v.as_str()) {
                    return hex_decode(result)
                        .ok_or_else(|| format!("invalid hex in RPC response: {result}"));
                }
                log::warn!("[dotns] unexpected response from {endpoint}: {body}");
                continue;
            }
            Err(e) => {
                log::warn!("[dotns] HTTP error for {endpoint}: {e}");
                continue;
            }
        }
    }

    Err("all RPC endpoints failed".into())
}

/// Resolve a `.dot` domain name to an IPFS CID via DOTNS on-chain lookup (async).
///
/// Returns the CID string (e.g. "bafybeig...") or an error.
pub async fn resolve_dotns(name: &str) -> Result<String, String> {
    let domain = if name.ends_with(".dot") {
        name.to_string()
    } else {
        format!("{name}.dot")
    };

    log::info!("[dotns] resolving: {domain}");

    // 1. Compute namehash
    let node = namehash(&domain);
    log::info!("[dotns] namehash: {}", hex_encode(&node));

    // 2. ABI-encode contenthash(bytes32) call
    let call_data = encode_contenthash_call(&node);
    log::info!("[dotns] call_data encoded ({} bytes)", call_data.len());

    // 3. SCALE-encode ReviveApi::call() params
    let params = scale_encode_revive_call(&CONTENT_RESOLVER, &call_data)?;
    let params_hex = hex_encode(&params);
    log::info!(
        "[dotns] params encoded ({} hex chars), calling RPC...",
        params_hex.len()
    );

    // 4. RPC state_call
    let response = rpc_state_call("ReviveApi_call", &params_hex).await?;
    log::info!("[dotns] got response: {} bytes", response.len());

    // 5. Decode ContractResult → return data
    let return_data = decode_contract_result(&response)?;
    log::info!("[dotns] contract return data: {} bytes", return_data.len());

    if return_data.is_empty() {
        return Err("domain not registered (empty return data)".into());
    }

    // 6. Decode ABI-encoded bytes
    let contenthash = decode_abi_bytes(&return_data)?;
    log::info!("[dotns] contenthash: {} bytes", contenthash.len());

    if contenthash.is_empty() {
        return Err("domain has no contenthash set".into());
    }

    // 7. Parse contenthash → CID
    let cid = contenthash_to_cid(&contenthash)?;
    log::info!("[dotns] resolved CID: {cid}");

    Ok(cid)
}

/// Resolve the owner of a .dot name by calling `owner(bytes32)` on the DOTNS registry (async).
/// Returns the H160 address as a `0x`-prefixed hex string, or `None` on failure.
pub async fn resolve_owner(name: &str) -> Option<String> {
    let domain = if name.ends_with(".dot") {
        name.to_string()
    } else {
        format!("{name}.dot")
    };
    let node = namehash(&domain);

    let mut call_data = Vec::with_capacity(36);
    call_data.extend_from_slice(&OWNER_SELECTOR);
    call_data.extend_from_slice(&node);

    let params = scale_encode_revive_call(&REGISTRY, &call_data).ok()?;
    let params_hex = hex_encode(&params);

    let response = rpc_state_call("ReviveApi_call", &params_hex).await.ok()?;
    let return_data = decode_contract_result(&response).ok()?;

    // ABI-encoded address: 32 bytes, address right-aligned (bytes 12..32).
    if return_data.len() < 32 {
        return None;
    }
    let addr_bytes = &return_data[12..32];
    if addr_bytes.iter().all(|&b| b == 0) {
        return None;
    }
    Some(format!(
        "0x{}",
        addr_bytes
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>()
    ))
}

/// Fetch an IPFS URL with a configurable byte limit (async, reqwest).
pub async fn fetch_ipfs_url_with_limit(
    url: &str,
    max_bytes: usize,
) -> Result<(String, Vec<u8>), String> {
    #[allow(unused_mut)]
    let mut resp = shared_client().get(url).send().await.map_err(|e| {
        let mut msg = format!("IPFS fetch failed: {e}");
        let mut source: Option<&dyn std::error::Error> = e.source();
        while let Some(cause) = source {
            msg.push_str(&format!("{cause}"));
            source = cause.source();
        }
        msg
    })?;

    let content_type = resp
        .headers()
        .get("Content-Type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();

    // Early rejection based on Content-Length header.
    if let Some(cl) = resp.content_length() {
        if cl > max_bytes as u64 {
            return Err(format!(
                "IPFS response too large: Content-Length {cl} > {max_bytes}"
            ));
        }
    }

    // Read the body, enforcing the size limit.
    // On native, use chunk() for streaming; on WASM, use bytes() (no streaming API).
    #[cfg(not(target_arch = "wasm32"))]
    let bytes = {
        let mut buf = Vec::new();
        while let Some(chunk) = resp
            .chunk()
            .await
            .map_err(|e| format!("IPFS read failed: {e}"))?
        {
            buf.extend_from_slice(&chunk);
            if buf.len() > max_bytes {
                return Err(format!(
                    "IPFS response too large: {} > {max_bytes}",
                    buf.len()
                ));
            }
        }
        buf
    };
    #[cfg(target_arch = "wasm32")]
    let bytes = {
        let buf = resp
            .bytes()
            .await
            .map_err(|e| format!("IPFS read failed: {e}"))?;
        if buf.len() > max_bytes {
            return Err(format!(
                "IPFS response too large: {} > {max_bytes}",
                buf.len()
            ));
        }
        buf.to_vec()
    };

    Ok((content_type, bytes))
}

async fn fetch_ipfs_url(url: &str) -> Result<(String, Vec<u8>), String> {
    fetch_ipfs_url_with_limit(url, 10 * 1024 * 1024).await
}

async fn fetch_ipfs_url_large(url: &str) -> Result<(String, Vec<u8>), String> {
    fetch_ipfs_url_with_limit(url, 64 * 1024 * 1024).await
}

fn looks_like_directory_listing(body: &[u8]) -> bool {
    let s = std::str::from_utf8(body).unwrap_or("");
    s.contains("Index of /ipfs")
        || s.contains("<title>Index of")
        || (s.contains("Index of") && s.contains("/ipfs/"))
}

/// Fetch content from IPFS and return a map of filename → bytes (async).
///
/// Strategy:
/// 1. Request the entire directory tree as a CARv1 file via `?format=car`.
///    Single round-trip; the parser handles both standard UnixFS and
///    zstd-compressed leaves.
/// 2. Request directory listing via `Accept: text/html` + `?format=html` query
///    param (forces gateway to return listing instead of index.html).
/// 3. If that works, parse filenames from listing and fetch each file.
/// 4. If the CID is a single file (not a directory), treat it as index.html.
pub async fn fetch_ipfs(cid: &str) -> Result<HashMap<String, Vec<u8>>, String> {
    log::info!("[dotns] fetching IPFS: {cid}");

    // Try CAR format first — single roundtrip, returns entire directory tree.
    let car_url = format!("{IPFS_GATEWAY}/ipfs/{cid}?format=car");
    if let Ok((ct, body)) = fetch_ipfs_url_large(&car_url).await {
        if ct.contains("vnd.ipld.car") || is_car_file(&body) {
            log::info!(
                "[dotns] got CAR response ({} bytes), parsing...",
                body.len()
            );
            return parse_car_to_assets(&body);
        }
    }

    // Try to get a directory listing.
    let listing_url = format!("{IPFS_GATEWAY}/ipfs/{cid}/?format=html&noResolve");
    if let Ok((ct, body)) = fetch_ipfs_url(&listing_url).await {
        if ct.contains("text/html") && looks_like_directory_listing(&body) {
            log::info!("[dotns] got directory listing for {cid}");
            return fetch_ipfs_directory(cid, &body).await;
        }
    }

    // Fallback: try trailing-slash request.
    let dir_url = format!("{IPFS_GATEWAY}/ipfs/{cid}/");
    if let Ok((content_type, body)) = fetch_ipfs_url_large(&dir_url).await {
        if content_type.contains("octet-stream") && body.len() > 60 && is_car_file(&body) {
            log::info!(
                "[dotns] detected CAR file from dir request ({} bytes)",
                body.len()
            );
            return parse_car_to_assets(&body);
        }
        if content_type.contains("text/html") && looks_like_directory_listing(&body) {
            return fetch_ipfs_directory(cid, &body).await;
        }
        // Gateway served index.html directly — parse HTML for referenced local assets.
        let mut assets = HashMap::new();
        let referenced = extract_local_references(&body);
        let futs: Vec<_> = referenced
            .iter()
            .map(|path| {
                let url = format!("{IPFS_GATEWAY}/ipfs/{cid}/{path}");
                let path = path.clone();
                async move {
                    log::info!("[dotns] fetching referenced asset: {path}");
                    fetch_ipfs_url(&url).await.map(|(_, b)| (path, b))
                }
            })
            .collect();
        let results = futures::future::join_all(futs).await;
        for result in results {
            match result {
                Ok((path, file_body)) => {
                    assets.insert(path, file_body);
                }
                Err(e) => {
                    log::warn!("[dotns] failed to fetch asset: {e}");
                }
            }
        }
        assets.insert("index.html".into(), body);
        return Ok(assets);
    }

    // Last resort: fetch without trailing slash — might be a single file or CAR.
    let url = format!("{IPFS_GATEWAY}/ipfs/{cid}");
    let (content_type, body) = fetch_ipfs_url_large(&url).await?;

    if content_type.contains("octet-stream") && body.len() > 60 && is_car_file(&body) {
        log::info!(
            "[dotns] detected CAR file ({} bytes), parsing...",
            body.len()
        );
        return parse_car_to_assets(&body);
    }

    let mut assets = HashMap::new();
    assets.insert("index.html".into(), body);
    Ok(assets)
}

/// Extract local asset paths referenced in HTML (src="...", href="...").
fn extract_local_references(html_bytes: &[u8]) -> Vec<String> {
    let html = std::str::from_utf8(html_bytes).unwrap_or("");
    let mut paths: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    for attr in &["src=\"", "href=\""] {
        for segment in html.split(attr).skip(1) {
            if let Some(end) = segment.find('"') {
                let path = &segment[..end];
                if path.is_empty()
                    || path.starts_with("http://")
                    || path.starts_with("https://")
                    || path.starts_with("//")
                    || path.starts_with("data:")
                    || path.starts_with('#')
                    || path.starts_with("javascript:")
                {
                    continue;
                }
                let clean = path.trim_start_matches("./");
                if !clean.is_empty() && !clean.contains("..") && seen.insert(clean.to_string()) {
                    paths.push(clean.to_string());
                }
            }
        }
    }
    paths
}

async fn fetch_ipfs_directory(
    cid: &str,
    listing_html: &[u8],
) -> Result<HashMap<String, Vec<u8>>, String> {
    let mut assets = HashMap::new();
    fetch_ipfs_directory_recursive(cid, "", listing_html, &mut assets, 0).await?;
    if assets.is_empty() {
        return Err("directory listing contained no files".into());
    }
    Ok(assets)
}

/// Recursively fetch IPFS directory contents, using `futures::future::join_all`
/// for parallel file fetches (replaces `std::thread::scope`).
// Note: this function is async and recursive. On WASM there is no thread::spawn,
// but async recursion works fine. We use Box::pin to satisfy the type checker for
// indirect recursion (async fn → BoxFuture).
// The future is NOT marked Send because reqwest's WASM backend uses Rc internally.
fn fetch_ipfs_directory_recursive<'a>(
    cid: &'a str,
    prefix: &'a str,
    listing_html: &'a [u8],
    assets: &'a mut HashMap<String, Vec<u8>>,
    depth: u8,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + 'a>> {
    Box::pin(async move {
        if depth > 8 {
            log::warn!("[dotns] recursion depth limit reached at prefix={prefix}");
            return Ok(());
        }
        let html = std::str::from_utf8(listing_html).map_err(|e| format!("invalid UTF-8: {e}"))?;

        let cid_prefix = format!("/ipfs/{cid}/");
        let mut seen_names: HashSet<String> = HashSet::new();
        let mut names: Vec<String> = Vec::new();
        for segment in html.split("<a href=\"") {
            if let Some(end) = segment.find('"') {
                let href = &segment[..end];
                if let Some(name) = href.strip_prefix(&cid_prefix) {
                    let clean = name.trim_end_matches('/');
                    if !clean.is_empty()
                        && !clean.contains('/')
                        && !clean.contains("..")
                        && seen_names.insert(clean.to_string())
                    {
                        names.push(clean.to_string());
                    }
                }
            }
        }

        // Separate subdirectories (must be handled sequentially to mutably borrow assets)
        // from plain files (fetched in parallel).
        let mut file_entries: Vec<(String, String)> = Vec::new(); // (path, url)

        for name in &names {
            let path = if prefix.is_empty() {
                name.clone()
            } else {
                format!("{prefix}/{name}")
            };

            let sub_cid = extract_sub_cid(html, name);
            if let Some(ref sc) = sub_cid {
                let dir_url = format!("{IPFS_GATEWAY}/ipfs/{sc}/?format=html&noResolve");
                match fetch_ipfs_url(&dir_url).await {
                    Ok((_, body)) => {
                        if looks_like_directory_listing(&body) {
                            log::info!("[dotns] recursing into subdirectory: {path}");
                            fetch_ipfs_directory_recursive(sc, &path, &body, assets, depth + 1)
                                .await?;
                            continue;
                        }
                    }
                    Err(e) => {
                        log::warn!("[dotns] failed to list subdir {path}: {e}");
                    }
                }
            }

            let url = format!("{IPFS_GATEWAY}/ipfs/{cid}/{name}");
            file_entries.push((path, url));
        }

        // Fetch plain files concurrently (join_all, bounded by browser / tokio scheduler).
        const BATCH_SIZE: usize = 6;
        for chunk in file_entries.chunks(BATCH_SIZE) {
            let futs: Vec<_> = chunk
                .iter()
                .map(|(path, url)| {
                    let path = path.clone();
                    let url = url.clone();
                    async move {
                        log::info!("[dotns] fetching: {path}");
                        fetch_ipfs_url_large(&url)
                            .await
                            .map(|(_, body)| (path, body))
                    }
                })
                .collect();
            let results = futures::future::join_all(futs).await;
            for result in results {
                match result {
                    Ok((path, body)) => {
                        assets.insert(path, body);
                    }
                    Err(e) => {
                        log::warn!("[dotns] failed to fetch file: {e}");
                    }
                }
            }
        }

        Ok(())
    })
}

/// Extract the CID for a subdirectory from the directory listing HTML.
fn extract_sub_cid(html: &str, name: &str) -> Option<String> {
    let needle = format!("?filename={name}");
    for segment in html.split("href=\"") {
        if let Some(end) = segment.find('"') {
            let href = &segment[..end];
            if href.ends_with(&needle) {
                let without_query = href.strip_suffix(&needle)?;
                let sub_cid = without_query.strip_prefix("/ipfs/")?;
                return Some(sub_cid.to_string());
            }
        }
    }
    None
}

/// Full resolution pipeline: DOTNS lookup → IPFS fetch → asset map (async).
pub async fn resolve_and_fetch(name: &str) -> Result<HashMap<String, Vec<u8>>, String> {
    let r = resolve_and_fetch_full(name).await?;
    Ok(r.assets)
}

/// Full resolution pipeline with metadata: DOTNS lookup → IPFS fetch → resolution struct (async).
///
/// Owner lookup and IPFS fetch run concurrently via `futures::join!`.
pub async fn resolve_and_fetch_full(name: &str) -> Result<DotnsResolution, String> {
    let cid = resolve_dotns(name).await?;

    // Run owner lookup and IPFS fetch concurrently.
    let name_for_owner = name.to_string();
    let (owner, assets) = futures::join!(resolve_owner(&name_for_owner), fetch_ipfs(&cid));

    let assets = assets?;
    log::info!("[dotns] owner for {}: {:?}", name, owner);

    Ok(DotnsResolution { cid, owner, assets })
}