host-chain-core 0.3.11

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
//! Mock-transport integration tests for chain identity and DOTNS resolution.
//!
//! These tests exercise the full resolution pipelines in `identity` and `dotns`
//! without making real HTTP calls.  They use the `_with` transport variants that
//! accept a caller-supplied async closure in place of the built-in reqwest
//! transport, injecting canned JSON-RPC responses to verify encoding, decoding,
//! and error propagation end-to-end.
//!
//! # Coverage
//!
//! - `identity::resolve_username_with` — PaseoPeople, PolkadotPeople, Individuality paths
//! - `identity::resolve_identity_with` — ConsumerInfo decode path
//! - `dotns::resolve_dotns_with` — CID extraction pipeline
//! - `dotns::resolve_owner_with` — H160 address extraction pipeline

#![cfg(not(target_arch = "wasm32"))]

use host_chain_core::chain::ChainId;
use host_chain_core::dotns::{
    contenthash_to_cid, decode_abi_bytes, decode_contract_result, decode_scale_compact, hex_encode,
    resolve_dotns_with, resolve_owner_with, scale_compact_len, scale_compact_u64,
};
use host_chain_core::identity::{resolve_identity_with, resolve_username_with};
use host_encoding::identity::Credibility;

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Build a minimal valid pallet-revive `ContractResult` buffer whose
/// `ExecReturnValue::data` field contains `payload`.
///
/// Layout (from `decode_contract_result` in host-encoding):
/// - gas_consumed:  Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
/// - gas_required:  Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
/// - storage_deposit: StorageDeposit (1 byte variant + u128)
/// - Option<Balance>: None (1 byte)
/// - plain Balance:   u128 (16 bytes)
/// - debug_message:   Vec<u8> (compact len 0)
/// - flags:           u32 (4 bytes)
/// - data:            Vec<u8> (compact len + bytes)
fn build_contract_result(payload: &[u8]) -> Vec<u8> {
    let mut buf = Vec::new();

    // gas_consumed
    scale_compact_u64(&mut buf, 0);
    scale_compact_u64(&mut buf, 0);

    // gas_required
    scale_compact_u64(&mut buf, 0);
    scale_compact_u64(&mut buf, 0);

    // storage_deposit: variant 0 (Charge) + u128 = 0
    buf.push(0x00);
    buf.extend_from_slice(&0u128.to_le_bytes());

    // Option<Balance> = None
    buf.push(0x00);

    // plain Balance = 0
    buf.extend_from_slice(&0u128.to_le_bytes());

    // debug_message: empty Vec<u8>
    scale_compact_len(&mut buf, 0).expect("compact len 0 must succeed");

    // ExecReturnValue { flags: 0, data: payload }
    buf.extend_from_slice(&0u32.to_le_bytes());
    scale_compact_len(&mut buf, payload.len()).expect("payload len compact must succeed");
    buf.extend_from_slice(payload);

    buf
}

/// Build ABI-encoded `bytes` return value for a given raw byte slice.
///
/// Solidity ABI encoding of `bytes`:
/// - bytes 0..32:  offset = 0x20 (big-endian)
/// - bytes 32..64: length (big-endian)
/// - bytes 64..:   data (not padded; `decode_abi_bytes` only reads `length` bytes)
fn build_abi_bytes(data: &[u8]) -> Vec<u8> {
    let mut out = vec![0u8; 64];
    // offset = 0x20 (32)
    out[31] = 0x20;
    // length
    let len = data.len() as u32;
    out[60..64].copy_from_slice(&len.to_be_bytes());
    out.extend_from_slice(data);
    out
}

/// Build a minimal IPFS contenthash byte slice for a given 32-byte sha2-256 digest.
///
/// Format (EIP-1577, IPFS dag-pb CIDv1):
/// `0xe3 0x01` (IPFS namespace varint) `0x01` (CIDv1) `0x70` (dag-pb)
/// `0x12` (sha2-256) `0x20` (32 bytes) <digest>
fn build_ipfs_contenthash(digest: &[u8; 32]) -> Vec<u8> {
    let mut ch = vec![0xe3u8, 0x01, 0x01, 0x70, 0x12, 0x20];
    ch.extend_from_slice(digest);
    ch
}

/// Build a full `ContractResult` whose data is a valid IPFS CID ABI-encoded return.
///
/// Returns `(contract_result_bytes, expected_cid_string)`.
fn build_cid_contract_result() -> (Vec<u8>, String) {
    // Fixed digest — any non-zero 32 bytes produces a valid CIDv1.
    let digest = [0xabu8; 32];
    let contenthash = build_ipfs_contenthash(&digest);
    let expected_cid =
        contenthash_to_cid(&contenthash).expect("test contenthash must produce a valid CID");

    let abi_payload = build_abi_bytes(&contenthash);
    let contract_bytes = build_contract_result(&abi_payload);

    (contract_bytes, expected_cid)
}

/// Build a full `ContractResult` whose data is an ABI-encoded H160 address.
///
/// The address is ABI-encoded as a 32-byte word with the 20-byte address
/// right-aligned (bytes 12..32).
fn build_owner_contract_result(addr: &[u8; 20]) -> Vec<u8> {
    let mut abi_word = vec![0u8; 32];
    abi_word[12..32].copy_from_slice(addr);
    build_contract_result(&abi_word)
}

// ---------------------------------------------------------------------------
// identity::resolve_username_with — PaseoPeople / PolkadotPeople path
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_resolve_username_returns_address() {
    // PaseoPeople uses `Identity::UsernameInfoOf`: 32-byte owner + 1 provider byte.
    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 = format!("0x{}", "ab".repeat(32));
    assert_eq!(result, Ok(Some(expected)));
}

#[tokio::test]
async fn test_resolve_username_returns_none_for_unknown() {
    // Null result means the username is not registered.
    let result = resolve_username_with("unknown.user", ChainId::PaseoPeople, |_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_username_returns_address_polkadot_people() {
    // PolkadotPeople also uses `Identity::UsernameInfoOf` — same wire format.
    let hex_payload = format!("0x{}00", "cd".repeat(32));
    let resp = format!(r#"{{"jsonrpc":"2.0","id":1,"result":"{hex_payload}"}}"#);

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

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

#[tokio::test]
async fn test_resolve_username_propagates_rpc_error() {
    // A JSON-RPC error object must be surfaced as `Err`.
    let result = resolve_username_with("alice", ChainId::PaseoPeople, |_req| async {
        Ok(
            r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"node overloaded"}}"#
                .to_string(),
        )
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("JSON-RPC error"));
}

#[tokio::test]
async fn test_resolve_username_propagates_transport_failure() {
    // Transport failures must propagate cleanly without panic.
    let result = resolve_username_with("alice", ChainId::PaseoPeople, |_req| async {
        Err("connection refused".to_string())
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("connection refused"));
}

// ---------------------------------------------------------------------------
// identity::resolve_username_with — Individuality path
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_resolve_username_individuality_returns_address() {
    // Individuality stores `Resources::UsernameOwnerOf` — a bare 32-byte AccountId32.
    let hex_payload = format!("0x{}", "ef".repeat(32));
    let resp = format!(r#"{{"jsonrpc":"2.0","id":1,"result":"{hex_payload}"}}"#);

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

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

#[tokio::test]
async fn test_resolve_username_individuality_returns_none_for_unknown() {
    let result = resolve_username_with("nobody", ChainId::Individuality, |_req| async {
        Ok(r#"{"jsonrpc":"2.0","id":1,"result":null}"#.to_string())
    })
    .await;

    assert_eq!(result, Ok(None));
}

// ---------------------------------------------------------------------------
// identity::resolve_identity_with — ConsumerInfo decode path
// ---------------------------------------------------------------------------

/// Construct a minimal SCALE-encoded `ConsumerInfo` buffer for use in tests.
///
/// Layout (from `decode_consumer_info` in host-encoding):
/// - identifier_key: Vec<u8> (compact len + bytes — 65 bytes of 0x04)
/// - full_username:  Option<String> — None (1 byte 0x00)
/// - lite_username:  String (compact len in bits + bytes)
/// - credibility:    u8 (0x00 = Lite)
fn build_consumer_info_bytes(lite_username: &str) -> Vec<u8> {
    let mut buf = Vec::new();

    // identifier_key: 65 bytes of 0x04 (compressed secp256k1 point prefix).
    buf.extend_from_slice(&[0x04u8; 65]);

    // full_username: None
    buf.push(0x00);

    // lite_username: compact len (in bits × 4) + bytes.
    // The SCALE compact len for a String is (byte_count << 2) in single-byte mode.
    let name_bytes = lite_username.as_bytes();
    buf.push((name_bytes.len() as u8) << 2);
    buf.extend_from_slice(name_bytes);

    // credibility: 0x00 = Lite
    buf.push(0x00);

    buf
}

#[tokio::test]
async fn test_resolve_identity_returns_display_name() {
    let account_id = format!("0x{}", "ab".repeat(32));
    let consumer_bytes = build_consumer_info_bytes("alice");
    let hex_payload = hex_encode(&consumer_bytes);
    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.expect("must succeed").expect("slot must be present");
    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_returns_none_when_no_identity() {
    // Null result means no consumer record for this account.
    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_propagates_rpc_error() {
    let account_id = format!("0x{}", "ab".repeat(32));
    let result = resolve_identity_with(&account_id, |_req| async {
        Ok(r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"internal"}}"#.to_string())
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("JSON-RPC error"));
}

#[tokio::test]
async fn test_resolve_identity_rejects_invalid_account_id() {
    // The transport must not be called when account_id is not valid hex.
    let result = resolve_identity_with("not-a-hex-id", |_req| async {
        unreachable!("transport must not be called for an 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() {
    // 16 bytes instead of 32 — must be rejected before any network call.
    let short_id = format!("0x{}", "ab".repeat(16));
    let result = resolve_identity_with(&short_id, |_req| async {
        unreachable!("transport must not be called for wrong-length account_id")
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("32 bytes"));
}

// ---------------------------------------------------------------------------
// dotns::resolve_dotns_with — CID extraction pipeline
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_resolve_dotns_returns_cid() {
    let (contract_bytes, expected_cid) = build_cid_contract_result();

    let result = resolve_dotns_with("mytestapp.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    let cid = result.expect("must produce a CID");
    assert_eq!(
        cid, expected_cid,
        "resolved CID must match the constructed fixture"
    );
    assert!(cid.starts_with('b'), "CIDv1 base32 must start with 'b'");
}

#[tokio::test]
async fn test_resolve_dotns_name_without_dot_suffix_resolves() {
    // Names without the ".dot" suffix must be appended automatically.
    let (contract_bytes, expected_cid) = build_cid_contract_result();

    let result = resolve_dotns_with("mytestapp", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    let cid = result.expect("must produce a CID");
    assert_eq!(cid, expected_cid);
}

#[tokio::test]
async fn test_resolve_dotns_propagates_transport_failure() {
    let result = resolve_dotns_with("fail.dot", |_req| async {
        Err("no route to host".to_string())
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("no route to host"));
}

#[tokio::test]
async fn test_resolve_dotns_returns_error_for_empty_return_data() {
    // ContractResult with empty payload → "domain not registered".
    let contract_bytes = build_contract_result(&[]);

    let result = resolve_dotns_with("unregistered.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("domain not registered"));
}

#[tokio::test]
async fn test_resolve_dotns_returns_error_for_zero_length_contenthash() {
    // ABI-encoded bytes with length=0 → "domain has no contenthash set".
    let abi_empty = build_abi_bytes(&[]);
    let contract_bytes = build_contract_result(&abi_empty);

    let result = resolve_dotns_with("nocontent.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .contains("domain has no contenthash set"));
}

// ---------------------------------------------------------------------------
// dotns::resolve_owner_with — H160 address extraction pipeline
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_resolve_owner_returns_account() {
    // Construct an H160 address: 20 bytes, each 0xde.
    let addr: [u8; 20] = [0xdeu8; 20];
    let contract_bytes = build_owner_contract_result(&addr);

    let result = resolve_owner_with("mytestapp.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    let owner = result.expect("must return Some(owner)");
    // Address should be 0x-prefixed 20-byte hex.
    assert!(owner.starts_with("0x"), "owner must be 0x-prefixed");
    assert_eq!(owner.len(), 42, "0x + 40 hex chars = 42 characters");
    assert!(
        owner[2..].chars().all(|c| c.is_ascii_hexdigit()),
        "owner must be valid hex"
    );
}

#[tokio::test]
async fn test_resolve_owner_returns_none_for_zero_address() {
    // All-zero H160 address signals "no owner" — must return None.
    let addr = [0u8; 20];
    let contract_bytes = build_owner_contract_result(&addr);

    let result = resolve_owner_with("unowned.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    assert_eq!(result, None, "zero address must map to None");
}

#[tokio::test]
async fn test_resolve_owner_returns_none_on_transport_failure() {
    // Transport failure for owner resolution must return None (not Err).
    let result = resolve_owner_with("fail.dot", |_req| async {
        Err("DNS lookup failed".to_string())
    })
    .await;

    assert_eq!(result, None);
}

#[tokio::test]
async fn test_resolve_owner_returns_none_for_short_return_data() {
    // Return data shorter than 32 bytes — can't extract ABI-encoded address.
    let contract_bytes = build_contract_result(&[0u8; 16]);

    let result = resolve_owner_with("short.dot", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    assert_eq!(result, None);
}

#[tokio::test]
async fn test_resolve_owner_name_without_dot_suffix_resolves() {
    // Names without ".dot" must be handled identically to names with the suffix.
    let addr: [u8; 20] = [0xabu8; 20];
    let contract_bytes = build_owner_contract_result(&addr);

    let with_suffix = resolve_owner_with("myapp.dot", {
        let bytes = contract_bytes.clone();
        move |_req| {
            let bytes = bytes.clone();
            async move { Ok(bytes) }
        }
    })
    .await;

    let without_suffix = resolve_owner_with("myapp", move |_req| {
        let bytes = contract_bytes.clone();
        async move { Ok(bytes) }
    })
    .await;

    assert_eq!(
        with_suffix, without_suffix,
        "suffix handling must be transparent to the caller"
    );
}

// ---------------------------------------------------------------------------
// Verify helper roundtrips (catches regressions in test infrastructure)
// ---------------------------------------------------------------------------

#[test]
fn test_build_contract_result_roundtrips_through_decoder() {
    let payload = b"hello world";
    let buf = build_contract_result(payload);
    let decoded = decode_contract_result(&buf).expect("must decode");
    assert_eq!(decoded, payload);
}

#[test]
fn test_build_abi_bytes_roundtrips_through_decoder() {
    let data = b"some contenthash bytes";
    let encoded = build_abi_bytes(data);
    let decoded = decode_abi_bytes(&encoded).expect("must decode");
    assert_eq!(decoded, data);
}

#[test]
fn test_build_ipfs_contenthash_produces_valid_cid() {
    let digest = [0x42u8; 32];
    let contenthash = build_ipfs_contenthash(&digest);
    let cid = contenthash_to_cid(&contenthash).expect("must produce CID");
    assert!(cid.starts_with('b'), "CIDv1 base32 starts with 'b'");
}

#[test]
fn test_decode_scale_compact_helper_is_accessible() {
    // Sanity check that the re-exported helper is usable in integration tests.
    let (val, consumed) = decode_scale_compact(&[0x04]).expect("must decode single-byte compact");
    assert_eq!(val, 1);
    assert_eq!(consumed, 1);
}