host-chain-core 0.3.3

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
//! Async username and consumer identity resolution against the Identity and
//! Resources pallets on People chains.
//!
//! Queries `Identity::UsernameInfoOf` and `Resources::Consumers` storage on
//! a People chain via `state_getStorage` JSON-RPC HTTP, then SCALE-decodes the
//! results.
//!
//! Flow for username resolution:
//! 1. Normalise the username (`host_encoding::identity::normalize_username`)
//! 2. Derive the storage key (`username_info_of_key`)
//! 3. Send `state_getStorage` via JSON-RPC HTTP
//! 4. Decode the hex response with `decode_username_info_owner`
//! 5. Return `Ok(Some(hex_account_id))`, `Ok(None)`, or `Err`
//!
//! Flow for consumer identity resolution:
//! 1. Hex-decode the account ID string
//! 2. Derive the storage key (`consumers_key`)
//! 3. Send `state_getStorage` via JSON-RPC HTTP
//! 4. Decode the hex response with `decode_consumer_info`
//! 5. Return `Ok(Some(ConsumerInfo))`, `Ok(None)`, or `Err`

use std::future::Future;
use std::sync::OnceLock;

pub use host_encoding::identity::ConsumerInfo;

use host_encoding::identity::{
    account_id_to_hex, consumers_key, decode_consumer_info, decode_username_info_owner,
    decode_username_owner, normalize_username, username_info_of_key, username_owner_of_key,
};

use crate::chain::ChainId;

// ---------------------------------------------------------------------------
// HTTP endpoint selection
// ---------------------------------------------------------------------------

/// HTTP JSON-RPC endpoint(s) for a given chain, tried in order.
///
/// People chains are the primary targets; other chains fall back to their
/// WSS endpoint converted to HTTPS (best-effort — not all public nodes expose HTTP).
fn http_endpoints(chain: ChainId) -> &'static [&'static str] {
    match chain {
        ChainId::PolkadotPeople => &[
            "https://polkadot-people-rpc.polkadot.io",
            "https://people-polkadot.dotters.network",
        ],
        ChainId::PaseoPeople => &[
            "https://people-paseo.dotters.network",
            "https://sys.ibp.network/people-paseo",
        ],
        ChainId::Individuality => &["https://pop3-testnet.parity-lab.parity.io/people"],
        // For other chains fall back to a single derived HTTPS endpoint so
        // callers are not blocked if they query an unexpected chain.
        _ => &[],
    }
}

// ---------------------------------------------------------------------------
// Shared reqwest client
// ---------------------------------------------------------------------------

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()
        }
    })
}

// ---------------------------------------------------------------------------
// Username resolution — public async API
// ---------------------------------------------------------------------------

/// Resolve a Resources pallet username to an `AccountId32`.
///
/// Queries `Resources::UsernameOwnerOf` on the given People chain via HTTP
/// JSON-RPC.  Returns the 32-byte account ID as a `0x`-prefixed hex string,
/// `Ok(None)` when the username is not registered, or `Err` on network or
/// decode failure.
pub async fn resolve_username(username: &str, chain: ChainId) -> Result<Option<String>, String> {
    let endpoints = http_endpoints(chain);
    if endpoints.is_empty() {
        return Err(format!(
            "no HTTP endpoint configured for chain {chain:?}; \
             use resolve_username_with() to supply a custom transport"
        ));
    }
    resolve_username_with_async(username, chain, |req| {
        let req_owned = req.to_owned();
        async move { http_transport(&req_owned, endpoints).await }
    })
    .await
}

/// Like [`resolve_username`] but drives RPC calls through a caller-supplied
/// async transport instead of the built-in HTTP endpoints.
///
/// `transport` receives a complete JSON-RPC request string and must return the
/// full JSON-RPC response string.
///
/// `chain` is required to select the correct storage key function and decoder:
/// - `Individuality`: `Resources::UsernameOwnerOf` (bare `AccountId32`)
/// - `PaseoPeople`/`PolkadotPeople`: `Identity::UsernameInfoOf` (`{ owner, provider }`)
pub async fn resolve_username_with<F, Fut>(
    username: &str,
    chain: ChainId,
    transport: F,
) -> Result<Option<String>, String>
where
    F: Fn(&str) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    resolve_username_with_async(username, chain, transport).await
}

// ---------------------------------------------------------------------------
// Consumer identity resolution — public async API
// ---------------------------------------------------------------------------

/// Resolve a `Resources::Consumers` entry for the given account ID.
///
/// `account_id` must be a `0x`-prefixed or bare 64-character hex string
/// representing a 32-byte `AccountId32`.
///
/// Returns `Ok(Some(ConsumerInfo))` when the account has a consumer record,
/// `Ok(None)` when the storage slot is absent, or `Err` on network or decode
/// failure.
pub async fn resolve_identity(
    account_id: &str,
    chain: ChainId,
) -> Result<Option<ConsumerInfo>, String> {
    let endpoints = http_endpoints(chain);
    if endpoints.is_empty() {
        return Err(format!(
            "no HTTP endpoint configured for chain {chain:?}; \
             use resolve_identity_with() to supply a custom transport"
        ));
    }
    resolve_identity_with_async(account_id, |req| {
        let req_owned = req.to_owned();
        async move { http_transport(&req_owned, endpoints).await }
    })
    .await
}

/// Like [`resolve_identity`] but drives RPC calls through a caller-supplied
/// async transport instead of the built-in HTTP endpoints.
pub async fn resolve_identity_with<F, Fut>(
    account_id: &str,
    transport: F,
) -> Result<Option<ConsumerInfo>, String>
where
    F: Fn(&str) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    resolve_identity_with_async(account_id, transport).await
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Shared implementation used by both the HTTP and transport variants of
/// username resolution.
///
/// Dispatches the storage key function and response decoder based on `chain`:
/// - `Individuality` uses `Resources::UsernameOwnerOf` (bare `AccountId32`).
/// - `PaseoPeople`/`PolkadotPeople` use `Identity::UsernameInfoOf` (`{ owner, provider }`).
/// - All other chains are rejected with an error.
async fn resolve_username_with_async<F, Fut>(
    username: &str,
    chain: ChainId,
    transport: F,
) -> Result<Option<String>, String>
where
    F: Fn(&str) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    // 1. Normalise username.
    let normalised = normalize_username(username).map_err(|e| e.to_string())?;

    // 2. Derive the storage key and choose the response decoder based on chain.
    //    Individuality stores lite usernames in `Resources::UsernameOwnerOf`
    //    (returns a bare AccountId32); People chains use `Identity::UsernameInfoOf`
    //    (returns `UsernameInformation { owner, provider }`).
    type DecodeFn = fn(&[u8]) -> Result<Option<[u8; 32]>, host_encoding::identity::IdentityError>;
    let (key, decode): (Vec<u8>, DecodeFn) = match chain {
        ChainId::Individuality => (username_owner_of_key(&normalised), decode_username_owner),
        ChainId::PaseoPeople | ChainId::PolkadotPeople => (
            username_info_of_key(&normalised),
            decode_username_info_owner,
        ),
        other => {
            return Err(format!(
                "resolve_username is not supported for chain {other:?}; \
                 only Individuality, PaseoPeople, and PolkadotPeople are supported"
            ));
        }
    };

    let key_hex = host_encoding::hex_encode(&key);

    // 3. Build state_getStorage JSON-RPC request.
    let request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "state_getStorage",
        "params": [key_hex]
    })
    .to_string();

    // 4. Send via transport and parse response.
    let resp_str = transport(&request).await?;
    let raw_bytes = extract_storage_bytes(&resp_str)?;

    match raw_bytes {
        None => Ok(None),
        Some(bytes) => {
            // 5. Decode the account ID using the chain-appropriate decoder.
            let account_opt = decode(&bytes).map_err(|e| e.to_string())?;
            Ok(account_opt.as_ref().map(account_id_to_hex))
        }
    }
}

/// Shared implementation for consumer identity resolution.
async fn resolve_identity_with_async<F, Fut>(
    account_id: &str,
    transport: F,
) -> Result<Option<ConsumerInfo>, String>
where
    F: Fn(&str) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    // 1. Hex-decode account ID and derive Resources::Consumers storage key.
    let account_bytes = host_encoding::hex_decode(account_id)
        .ok_or_else(|| format!("invalid hex account_id: {account_id}"))?;
    if account_bytes.len() != 32 {
        return Err(format!(
            "account_id must be 32 bytes (64 hex chars), got {} bytes",
            account_bytes.len()
        ));
    }
    let mut account_arr = [0u8; 32];
    account_arr.copy_from_slice(&account_bytes);

    let key = consumers_key(&account_arr);
    let key_hex = host_encoding::hex_encode(&key);

    // 2. Build state_getStorage JSON-RPC request.
    let request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "state_getStorage",
        "params": [key_hex]
    })
    .to_string();

    // 3. Send via transport and parse response.
    let resp_str = transport(&request).await?;
    let raw_bytes = extract_storage_bytes(&resp_str)?;

    match raw_bytes {
        None => Ok(None),
        Some(bytes) => {
            // 4. SCALE-decode ConsumerInfo.
            let info = decode_consumer_info(&bytes).map_err(|e| e.to_string())?;
            Ok(Some(info))
        }
    }
}

/// Parse a JSON-RPC `state_getStorage` response and return the decoded bytes,
/// or `None` when the storage slot is absent (result = null).
fn extract_storage_bytes(resp_str: &str) -> Result<Option<Vec<u8>>, String> {
    let body: serde_json::Value = serde_json::from_str(resp_str)
        .map_err(|e| format!("failed to parse JSON-RPC response: {e}"))?;

    if let Some(err) = body.get("error") {
        return Err(format!("JSON-RPC error from node: {err}"));
    }

    match body.get("result") {
        // Missing "result" key indicates a malformed response.
        None => Err("JSON-RPC response missing 'result' field".into()),
        // null result means the storage slot is absent.
        Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::String(hex)) => {
            let bytes = host_encoding::hex_decode(hex).ok_or_else(|| {
                format!(
                    "invalid hex in state_getStorage response ({} chars)",
                    hex.len()
                )
            })?;
            Ok(Some(bytes))
        }
        Some(other) => Err(format!(
            "unexpected result type in state_getStorage response: {other}"
        )),
    }
}

/// Send a JSON-RPC request to a list of HTTP endpoints, returning the first
/// successful response string.
async fn http_transport(request: &str, endpoints: &[&str]) -> Result<String, String> {
    let client = shared_client();

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

        match result {
            Ok(resp) => {
                let bytes = match resp.bytes().await {
                    Ok(b) => b,
                    Err(e) => {
                        log::warn!("[identity] failed to read response from {endpoint}: {e}");
                        continue;
                    }
                };
                match String::from_utf8(bytes.to_vec()) {
                    Ok(s) => return Ok(s),
                    Err(e) => {
                        log::warn!("[identity] non-UTF-8 response from {endpoint}: {e}");
                        continue;
                    }
                }
            }
            Err(e) => {
                log::warn!("[identity] HTTP error for {endpoint}: {e}");
                continue;
            }
        }
    }

    Err("all RPC endpoints failed for identity resolution".into())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use host_encoding::identity::Credibility;

    // -----------------------------------------------------------------------
    // resolve_username_with — PaseoPeople (Identity::UsernameInfoOf path)
    // -----------------------------------------------------------------------

    /// Minimal happy-path test using a mock transport that returns a
    /// well-formed `Option::None` response (PaseoPeople path).
    #[tokio::test]
    async fn test_resolves_none_for_absent_username() {
        let result = resolve_username_with("alice", ChainId::PaseoPeople, |_req| async {
            // null result = storage slot absent = username not registered.
            Ok(r#"{"jsonrpc":"2.0","id":1,"result":null}"#.to_string())
        })
        .await;
        assert_eq!(result, Ok(None));
    }

    /// Mock transport returning a valid `UsernameInformation { owner, provider }`
    /// for the `Identity::UsernameInfoOf` path (PaseoPeople / PolkadotPeople).
    #[tokio::test]
    async fn test_resolves_some_account_id_paseo_people() {
        // Raw UsernameInformation: 32 bytes owner + 1 byte provider (Authority = 0x00).
        // No Option wrapper — the slot is absent (null) or present as raw bytes.
        let hex_payload = format!("0x{}00", "ab".repeat(32));
        let resp = format!(r#"{{"jsonrpc":"2.0","id":1,"result":"{hex_payload}"}}"#);

        let result = resolve_username_with("alice", ChainId::PaseoPeople, move |_req| {
            let resp = resp.clone();
            async move { Ok(resp) }
        })
        .await;

        let expected_hex = format!("0x{}", "ab".repeat(32));
        assert_eq!(result, Ok(Some(expected_hex)));
    }

    /// Mock transport returning a JSON-RPC error object.
    #[tokio::test]
    async fn test_returns_error_on_rpc_error() {
        let result = resolve_username_with("alice", ChainId::PaseoPeople, |_req| async {
            Ok(
                r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"node error"}}"#
                    .to_string(),
            )
        })
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("JSON-RPC error"));
    }

    /// Empty username is rejected before any network call.
    #[tokio::test]
    async fn test_rejects_empty_username_before_network() {
        let result = resolve_username_with("", ChainId::PaseoPeople, |_req| async {
            // This branch must not execute — normalization fails first.
            Ok(r#"{"jsonrpc":"2.0","id":1,"result":null}"#.to_string())
        })
        .await;
        assert!(result.is_err(), "empty username must be rejected");
    }

    /// Username with invalid characters is rejected before any network call.
    #[tokio::test]
    async fn test_rejects_invalid_username_before_network() {
        let result = resolve_username_with("alice!", ChainId::PaseoPeople, |_req| async {
            unreachable!("transport must not be called for invalid username")
        })
        .await;
        assert!(result.is_err());
    }

    /// Mock transport that always fails — errors should propagate cleanly.
    #[tokio::test]
    async fn test_returns_error_when_transport_fails() {
        let result = resolve_username_with("alice", ChainId::PaseoPeople, |_req| async {
            Err("simulated network failure".to_string())
        })
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("simulated network failure"));
    }

    /// No HTTP endpoint configured for a non-People chain.
    #[tokio::test]
    async fn test_returns_error_for_chain_without_endpoint() {
        let result = resolve_username("alice", ChainId::PolkadotAssetHub).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("no HTTP endpoint configured"));
    }

    /// Unsupported chain in `resolve_username_with` is rejected before any
    /// network call with a descriptive error.
    #[tokio::test]
    async fn test_returns_error_for_unsupported_chain_in_with_variant() {
        let result = resolve_username_with("alice", ChainId::PolkadotAssetHub, |_req| async {
            unreachable!("transport must not be called for unsupported chain")
        })
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not supported for chain"));
    }

    // -----------------------------------------------------------------------
    // resolve_username_with — Individuality (Resources::UsernameOwnerOf path)
    // -----------------------------------------------------------------------

    /// Individuality chain: absent username returns `None` (null result).
    #[tokio::test]
    async fn test_individuality_resolves_none_for_absent_username() {
        let result = resolve_username_with("alice", ChainId::Individuality, |_req| async {
            Ok(r#"{"jsonrpc":"2.0","id":1,"result":null}"#.to_string())
        })
        .await;
        assert_eq!(result, Ok(None));
    }

    /// Individuality chain: present username returns `Some(hex_account_id)`.
    ///
    /// `Resources::UsernameOwnerOf` returns a bare `AccountId32` — 32 bytes,
    /// no Option wrapper, no provider byte.
    #[tokio::test]
    async fn test_individuality_resolves_some_account_id() {
        // Bare AccountId32: exactly 32 bytes, no option tag, no provider byte.
        let hex_payload = format!("0x{}", "cd".repeat(32));
        let resp = format!(r#"{{"jsonrpc":"2.0","id":1,"result":"{hex_payload}"}}"#);

        let result = resolve_username_with("alice", ChainId::Individuality, move |_req| {
            let resp = resp.clone();
            async move { Ok(resp) }
        })
        .await;

        let expected_hex = format!("0x{}", "cd".repeat(32));
        assert_eq!(result, Ok(Some(expected_hex)));
    }

    // -----------------------------------------------------------------------
    // resolve_identity_with
    // -----------------------------------------------------------------------

    fn make_consumer_info_bytes() -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0x04u8; 65]); // identifier_key
        buf.push(0x00); // full_username: None
        buf.push(b"alice".len() as u8 * 4); // compact len(5) = 0x14
        buf.extend_from_slice(b"alice"); // lite_username
        buf.push(0x00); // Credibility::Lite
        buf
    }

    #[tokio::test]
    async fn test_resolve_identity_returns_none_for_absent_slot() {
        let account_id = format!("0x{}", "ab".repeat(32));
        let result = resolve_identity_with(&account_id, |_req| async {
            Ok(r#"{"jsonrpc":"2.0","id":1,"result":null}"#.to_string())
        })
        .await;
        assert_eq!(result, Ok(None));
    }

    #[tokio::test]
    async fn test_resolve_identity_decodes_consumer_info() {
        let account_id = format!("0x{}", "ab".repeat(32));
        let payload = make_consumer_info_bytes();
        let hex_payload = host_encoding::hex_encode(&payload);
        let resp = format!(r#"{{"jsonrpc":"2.0","id":1,"result":"{hex_payload}"}}"#);

        let result = resolve_identity_with(&account_id, move |_req| {
            let resp = resp.clone();
            async move { Ok(resp) }
        })
        .await;

        let info = result.unwrap().unwrap();
        assert_eq!(info.lite_username, "alice");
        assert_eq!(info.full_username, None);
        assert_eq!(info.credibility, Credibility::Lite);
        assert_eq!(info.identifier_key, vec![0x04u8; 65]);
    }

    #[tokio::test]
    async fn test_resolve_identity_rejects_invalid_account_id_hex() {
        let result = resolve_identity_with("not-hex", |_req| async {
            unreachable!("transport must not be called for invalid account_id")
        })
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid hex"));
    }

    #[tokio::test]
    async fn test_resolve_identity_rejects_wrong_length_account_id() {
        // Only 16 bytes instead of 32.
        let result = resolve_identity_with(&format!("0x{}", "ab".repeat(16)), |_req| async {
            unreachable!("transport must not be called for invalid account_id")
        })
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("32 bytes"));
    }

    #[tokio::test]
    async fn test_resolve_identity_returns_error_for_chain_without_endpoint() {
        let account_id = format!("0x{}", "ab".repeat(32));
        let result = resolve_identity(&account_id, ChainId::PolkadotAssetHub).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("no HTTP endpoint configured"));
    }
}