host-encoding 0.3.2

Pure codec and hash functions for DOTNS and statement-store — no I/O, WASM-safe
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
//! Pure DOTNS encoding and decoding functions.
//!
//! No I/O. No network calls. WASM-safe.
//!
//! Provides ENS-style namehashing, ABI encoding, SCALE encoding/decoding,
//! and contenthash → CID conversion for the DOTNS resolver protocol.

use tiny_keccak::{Hasher, Keccak};

/// Solidity function selector for `contenthash(bytes32)`.
pub const CONTENTHASH_SELECTOR: [u8; 4] = [0xbc, 0x1c, 0x58, 0xd1];

/// Compile-time hex string to 20-byte address.
pub const fn hex_addr(s: &str) -> [u8; 20] {
    let b = s.as_bytes();
    assert!(b.len() == 40, "address must be 40 hex chars");
    let mut out = [0u8; 20];
    let mut i = 0;
    while i < 20 {
        out[i] = (hex_nibble(b[i * 2]) << 4) | hex_nibble(b[i * 2 + 1]);
        i += 1;
    }
    out
}

/// Compile-time hex character to nibble value.
pub const fn hex_nibble(c: u8) -> u8 {
    match c {
        b'0'..=b'9' => c - b'0',
        b'a'..=b'f' => c - b'a' + 10,
        b'A'..=b'F' => c - b'A' + 10,
        _ => panic!("invalid hex"),
    }
}

/// Compute keccak256 hash of the given data.
pub fn keccak256(data: &[u8]) -> [u8; 32] {
    let mut hasher = Keccak::v256();
    hasher.update(data);
    let mut out = [0u8; 32];
    hasher.finalize(&mut out);
    out
}

/// ENS-style namehash: `namehash("mytestapp.dot")`.
///
/// Splits by `.`, reverses labels, and iteratively hashes to produce a
/// 32-byte node identifier compatible with the ENS/DOTNS registry.
pub fn namehash(domain: &str) -> [u8; 32] {
    if domain.is_empty() {
        return [0u8; 32];
    }
    let labels: Vec<&str> = domain.split('.').collect();
    let mut node = [0u8; 32];
    for label in labels.into_iter().rev() {
        let label_hash = keccak256(label.as_bytes());
        let mut buf = [0u8; 64];
        buf[..32].copy_from_slice(&node);
        buf[32..].copy_from_slice(&label_hash);
        node = keccak256(&buf);
    }
    node
}

/// ABI-encode `contenthash(bytes32 node)` call data.
pub fn encode_contenthash_call(node: &[u8; 32]) -> Vec<u8> {
    let mut data = Vec::with_capacity(36);
    data.extend_from_slice(&CONTENTHASH_SELECTOR);
    data.extend_from_slice(node);
    data
}

/// SCALE-encode the parameters for `ReviveApi::call()` runtime API.
///
/// Parameters (in order, from runtime metadata):
///   origin: AccountId32 ([u8; 32])
///   dest: H160 ([u8; 20])
///   value: u128 (BalanceOf<T>, 16 bytes LE)
///   gas_limit: Option<Weight> where Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
///   storage_deposit_limit: Option<u128>
///   input_data: Vec<u8>
pub fn scale_encode_revive_call(dest: &[u8; 20], input_data: &[u8]) -> Result<Vec<u8>, String> {
    let mut buf = Vec::with_capacity(128 + input_data.len());

    // origin: AccountId32 (Alice — matches dot.li's dry-run convention)
    buf.extend_from_slice(&[
        0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f,
        0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d,
        0xa2, 0x7d,
    ]);

    // dest: H160
    buf.extend_from_slice(dest);

    // value: u128 = 0
    buf.extend_from_slice(&0u128.to_le_bytes());

    // gas_limit: Option<Weight> = Some(Weight { ref_time: MAX, proof_size: MAX })
    buf.push(0x01); // Some
    scale_compact_u64(&mut buf, u64::MAX); // ref_time
    scale_compact_u64(&mut buf, u64::MAX); // proof_size

    // storage_deposit_limit: Option<u128> = Some(u64::MAX as u128)
    buf.push(0x01); // Some
    buf.extend_from_slice(&(u64::MAX as u128).to_le_bytes());

    // input_data: Vec<u8> = compact_len ++ bytes
    scale_compact_len(&mut buf, input_data.len())?;
    buf.extend_from_slice(input_data);

    Ok(buf)
}

/// SCALE compact encoding for a u64 value.
pub fn scale_compact_u64(buf: &mut Vec<u8>, val: u64) {
    if val < 64 {
        buf.push((val as u8) << 2);
    } else if val < 0x4000 {
        let v = ((val as u16) << 2) | 1;
        buf.extend_from_slice(&v.to_le_bytes());
    } else if val < 0x4000_0000 {
        let v = ((val as u32) << 2) | 2;
        buf.extend_from_slice(&v.to_le_bytes());
    } else {
        // Big integer mode: upper 6 bits = (byte_count - 4), lower 2 bits = 0b11
        // For u64, we need up to 8 bytes
        let bytes = val.to_le_bytes();
        let len = 8 - (val.leading_zeros() / 8) as usize;
        let len = len.max(4); // minimum 4 bytes in big mode
        let prefix = (((len - 4) as u8) << 2) | 3;
        buf.push(prefix);
        buf.extend_from_slice(&bytes[..len]);
    }
}

/// SCALE compact encoding for a length prefix.
///
/// Returns an error if `n` is >= 1 GiB, which is beyond the SCALE
/// single-byte-mode range and not expected in any RPC call this crate makes.
pub fn scale_compact_len(buf: &mut Vec<u8>, n: usize) -> Result<(), String> {
    if n < 64 {
        buf.push((n as u8) << 2);
    } else if n < 16384 {
        let v = ((n as u16) << 2) | 1;
        buf.extend_from_slice(&v.to_le_bytes());
    } else if n < 1_073_741_824 {
        let v = ((n as u32) << 2) | 2;
        buf.extend_from_slice(&v.to_le_bytes());
    } else {
        // Big mode — values >= 1 GiB are not valid for any RPC input_data this
        // crate produces; return an error instead of panicking.
        return Err(format!(
            "compact encoding: value {n} is too large (max 1_073_741_823)"
        ));
    }
    Ok(())
}

// Re-export shared hex utilities from the crate root.
pub use crate::{hex_decode, hex_encode};

/// Decode the SCALE-encoded `ContractResult` from pallet-revive's `ReviveApi::call`.
///
/// # Layout (pallet-revive, Asset Hub Paseo, 2025-03)
///
/// This is a hand-rolled positional decoder. The field order is:
/// - 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 enum (1 byte tag + u128)
/// - [pallet-revive extra] Option<Balance> (1 tag + 16 if Some)
/// - [pallet-revive extra] Balance (16 bytes u128)
/// - debug_message: Vec<u8> (Compact len + bytes)
/// - result: ExecReturnValue { flags: u32, data: Vec<u8> } (no Result wrapper)
///
/// If pallet-revive changes its ContractResult layout, this decoder must be
/// updated and a new test vector captured.
pub fn decode_contract_result(response: &[u8]) -> Result<Vec<u8>, String> {
    let mut pos = 0;

    // gas_consumed: Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
    let (_, n) = decode_scale_compact(&response[pos..])?;
    pos += n;
    let (_, n) = decode_scale_compact(&response[pos..])?;
    pos += n;

    // gas_required: Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
    let (_, n) = decode_scale_compact(&response[pos..])?;
    pos += n;
    let (_, n) = decode_scale_compact(&response[pos..])?;
    pos += n;

    // storage_deposit: StorageDeposit enum (1 byte variant + u128)
    if pos + 17 > response.len() {
        return Err("response too short (storage_deposit)".into());
    }
    pos += 1 + 16;

    // pallet-revive adds extra fields not present in pallet-contracts:
    // - Option<Balance> (1 tag + 16 u128 if Some) — likely storage deposit limit
    // - Balance (16 bytes u128) — likely eth gas price or fee
    if pos >= response.len() {
        return Err("response too short (extra fields)".into());
    }
    let opt_tag = response[pos];
    pos += 1; // Option tag
    if opt_tag == 1 {
        if pos + 16 > response.len() {
            return Err("response too short (option balance)".into());
        }
        pos += 16; // Some(u128)
    }
    if pos + 16 > response.len() {
        return Err("response too short (plain balance)".into());
    }
    pos += 16; // plain u128

    // debug_message: Vec<u8>
    let (msg_len, bytes_read) = decode_scale_compact(&response[pos..])?;
    pos += bytes_read + msg_len;

    // result: ExecReturnValue { flags: u32, data: Vec<u8> } (no Result wrapper in pallet-revive)
    if pos + 4 > response.len() {
        return Err("response too short (flags)".into());
    }
    pos += 4; // flags: u32

    // data: Vec<u8>
    let (data_len, bytes_read) = decode_scale_compact(&response[pos..])?;
    pos += bytes_read;

    if pos + data_len > response.len() {
        return Err(format!(
            "data extends beyond response (pos={pos}, data_len={data_len}, total={})",
            response.len()
        ));
    }

    Ok(response[pos..pos + data_len].to_vec())
}

/// Decode a SCALE compact-encoded integer, returning (value, bytes_consumed).
pub fn decode_scale_compact(data: &[u8]) -> Result<(usize, usize), String> {
    if data.is_empty() {
        return Err("empty data for compact decode".into());
    }
    let mode = data[0] & 0b11;
    match mode {
        0 => Ok(((data[0] >> 2) as usize, 1)),
        1 => {
            if data.len() < 2 {
                return Err("compact: need 2 bytes".into());
            }
            let v = u16::from_le_bytes([data[0], data[1]]) >> 2;
            Ok((v as usize, 2))
        }
        2 => {
            if data.len() < 4 {
                return Err("compact: need 4 bytes".into());
            }
            let v = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) >> 2;
            Ok((v as usize, 4))
        }
        3 => {
            // Big integer mode
            let bytes_needed = (data[0] >> 2) as usize + 4;
            if data.len() < 1 + bytes_needed {
                return Err("compact: big mode insufficient data".into());
            }
            let mut val: usize = 0;
            for i in (0..bytes_needed).rev() {
                val = (val << 8) | data[1 + i] as usize;
            }
            Ok((val, 1 + bytes_needed))
        }
        _ => unreachable!(),
    }
}

/// Decode ABI-encoded bytes return value from Solidity.
///
/// The `contenthash` function returns `bytes` which is ABI-encoded as:
///   offset (32 bytes, = 0x20)
///   length (32 bytes)
///   data (padded to 32-byte boundary)
pub fn decode_abi_bytes(data: &[u8]) -> Result<Vec<u8>, String> {
    if data.len() < 64 {
        return Err(format!("ABI bytes too short: {} bytes", data.len()));
    }
    // First 32 bytes: offset (should be 0x20 = 32)
    // Next 32 bytes: length
    let len = u32::from_be_bytes([data[60], data[61], data[62], data[63]]) as usize;
    if 64 + len > data.len() {
        return Err(format!("ABI bytes: length {len} exceeds data"));
    }
    Ok(data[64..64 + len].to_vec())
}

/// Parse a contenthash value to extract an IPFS CIDv1.
///
/// The contenthash format follows EIP-1577:
///   0xe3 0x01 0x01 <multihash>  (IPFS, codec dag-pb, CIDv1)
///   0xe5 0x01 ...               (Swarm)
///
/// We decode the CID and return it as a base32-encoded string (multibase prefix `b`).
pub fn contenthash_to_cid(data: &[u8]) -> Result<String, String> {
    if data.is_empty() {
        return Err("empty contenthash".into());
    }

    // EIP-1577 contenthash uses multicodec varint prefix.
    // IPFS namespace = 0xe3 = 227, encoded as varint `e3 01` (2 bytes).
    // Swarm namespace = 0xe5 = 229, encoded as varint `e5 01` (2 bytes).
    let (codec, varint_len) = decode_unsigned_varint(data);
    match codec {
        0xe3 => {
            // IPFS — skip the namespace varint, rest is the CID
            let cid_bytes = &data[varint_len..];
            Ok(format!("b{}", base32_encode(cid_bytes)))
        }
        0xe5 => Err("Swarm contenthash not supported".into()),
        _ => Err(format!(
            "contenthash_to_cid: unrecognized codec varint 0x{codec:02x}; only IPFS dag-pb (0x70) is supported"
        )),
    }
}

/// Decode an unsigned varint (LEB128), returning (value, bytes_consumed).
pub fn decode_unsigned_varint(data: &[u8]) -> (u64, usize) {
    let mut value: u64 = 0;
    let mut shift = 0;
    for (i, &byte) in data.iter().enumerate() {
        if shift >= 64 {
            break;
        }
        value |= ((byte & 0x7f) as u64) << shift;
        if byte & 0x80 == 0 {
            return (value, i + 1);
        }
        shift += 7;
    }
    (value, data.len())
}

/// RFC 4648 base32 encoding (lowercase, no padding).
pub fn base32_encode(data: &[u8]) -> String {
    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
    let mut result = String::new();
    let mut bits: u32 = 0;
    let mut num_bits: u32 = 0;
    for &byte in data {
        bits = (bits << 8) | byte as u32;
        num_bits += 8;
        while num_bits >= 5 {
            num_bits -= 5;
            result.push(ALPHABET[((bits >> num_bits) & 0x1f) as usize] as char);
        }
    }
    if num_bits > 0 {
        result.push(ALPHABET[((bits << (5 - num_bits)) & 0x1f) as usize] as char);
    }
    result
}

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

    #[test]
    fn test_hex_nibble_digits() {
        assert_eq!(hex_nibble(b'0'), 0);
        assert_eq!(hex_nibble(b'9'), 9);
        assert_eq!(hex_nibble(b'a'), 10);
        assert_eq!(hex_nibble(b'f'), 15);
        assert_eq!(hex_nibble(b'A'), 10);
        assert_eq!(hex_nibble(b'F'), 15);
    }

    #[test]
    fn test_hex_addr_roundtrip() {
        let addr = hex_addr("7756DF72CBc7f062e7403cD59e45fBc78bed1cD7");
        assert_eq!(addr[0], 0x77);
        assert_eq!(addr[19], 0xd7);
    }

    #[test]
    fn test_keccak256_empty() {
        // keccak256("") = c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470
        let result = keccak256(b"");
        assert_eq!(result[0], 0xc5);
        assert_eq!(result[1], 0xd2);
    }

    #[test]
    fn test_namehash_empty_domain() {
        assert_eq!(namehash(""), [0u8; 32]);
    }

    #[test]
    fn test_encode_contenthash_call_length() {
        let node = [0u8; 32];
        let call = encode_contenthash_call(&node);
        // 4 bytes selector + 32 bytes node
        assert_eq!(call.len(), 36);
        assert_eq!(&call[..4], &CONTENTHASH_SELECTOR);
    }

    #[test]
    fn test_scale_compact_u64_single_byte() {
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0);
        assert_eq!(buf, vec![0x00]);

        buf.clear();
        scale_compact_u64(&mut buf, 63);
        assert_eq!(buf, vec![0xfc]);
    }

    #[test]
    fn test_scale_compact_len_too_large_returns_error() {
        let mut buf = Vec::new();
        let result = scale_compact_len(&mut buf, 1_073_741_824);
        assert!(result.is_err());
    }

    #[test]
    fn test_hex_encode_decode_roundtrip() {
        let original = vec![0xde, 0xad, 0xbe, 0xef];
        let encoded = hex_encode(&original);
        assert_eq!(encoded, "0xdeadbeef");
        let decoded = hex_decode(&encoded).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_hex_decode_rejects_odd_length() {
        assert!(hex_decode("0xabc").is_none());
    }

    #[test]
    fn test_decode_scale_compact_single_byte() {
        let (val, consumed) = decode_scale_compact(&[0x04]).unwrap();
        assert_eq!(val, 1);
        assert_eq!(consumed, 1);
    }

    #[test]
    fn test_decode_scale_compact_empty_returns_error() {
        assert!(decode_scale_compact(&[]).is_err());
    }

    #[test]
    fn test_decode_abi_bytes_too_short_returns_error() {
        assert!(decode_abi_bytes(&[0u8; 32]).is_err());
    }

    #[test]
    fn test_contenthash_to_cid_empty_returns_error() {
        assert!(contenthash_to_cid(&[]).is_err());
    }

    #[test]
    fn test_contenthash_to_cid_swarm_returns_error() {
        // 0xe5 0x01 is the Swarm namespace varint
        assert!(contenthash_to_cid(&[0xe5, 0x01, 0x00]).is_err());
    }

    #[test]
    fn test_contenthash_to_cid_unknown_codec_returns_error() {
        // 0x01 is not a recognized namespace
        let result = contenthash_to_cid(&[0x01, 0x02, 0x03]);
        assert!(result.is_err());
        let msg = result.unwrap_err();
        assert!(msg.contains("unrecognized codec varint"));
    }

    #[test]
    fn test_base32_encode_known_vector() {
        // base32("") = ""
        assert_eq!(base32_encode(b""), "");
        // base32("f") = "my" (RFC 4648, lowercase)
        assert_eq!(base32_encode(b"f"), "my");
    }

    #[test]
    fn test_decode_unsigned_varint_single_byte() {
        let (val, consumed) = decode_unsigned_varint(&[0x05]);
        assert_eq!(val, 5);
        assert_eq!(consumed, 1);
    }

    #[test]
    fn test_decode_unsigned_varint_multi_byte() {
        // LEB128 encoding of 300 = 0xAC 0x02
        let (val, consumed) = decode_unsigned_varint(&[0xac, 0x02]);
        assert_eq!(val, 300);
        assert_eq!(consumed, 2);
    }

    /// Pinned vector: namehash("mytestapp.dot") must match the on-chain value
    /// used by dot.li and verified in host-chain's test_encoding_matches_dotli.
    #[test]
    fn test_namehash_mytestapp_dot_pinned() {
        let node = namehash("mytestapp.dot");
        // Verified against host-chain::dotns::test_encoding_matches_dotli
        // (bytes 142..174 of the encoded params = the namehash in the ABI calldata).
        let hex = hex_encode(&node);
        // The namehash appears in the known encoded params at the contenthash(bytes32) position.
        // Just verify it's deterministic and non-zero.
        assert_ne!(node, [0u8; 32]);
        // Pinned value from the first successful run:
        let expected = hex_decode(&hex).unwrap();
        assert_eq!(node.to_vec(), expected);
        // Cross-check: the encoding test in host-chain pins the full params string;
        // here we just verify the namehash portion is stable.
        assert_eq!(
            hex,
            "0xea3cb49a7f22581a2b768fdfd30be01a398514934d65b60e158ee9ee93c20894"
        );
    }

    /// Pinned vector: full SCALE-encoded ReviveApi::call() params for
    /// mytestapp.dot contenthash query, matching dot.li's state_call.
    #[test]
    fn test_scale_encode_revive_call_pinned() {
        let content_resolver: [u8; 20] = hex_addr("7756DF72CBc7f062e7403cD59e45fBc78bed1cD7");
        let node = namehash("mytestapp.dot");
        let call_data = encode_contenthash_call(&node);
        let params = scale_encode_revive_call(&content_resolver, &call_data).unwrap();
        let expected = "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d7756df72cbc7f062e7403cd59e45fbc78bed1cd7000000000000000000000000000000000113ffffffffffffffff13ffffffffffffffff01ffffffffffffffff000000000000000090bc1c58d1ea3cb49a7f22581a2b768fdfd30be01a398514934d65b60e158ee9ee93c20894";
        assert_eq!(hex_encode(&params), expected);
    }

    /// Pinned vector: contenthash → CIDv1 base32 for a known IPFS hash.
    #[test]
    fn test_contenthash_to_cid_ipfs_pinned() {
        // IPFS namespace 0xe3 0x01, followed by CIDv1 (0x01), dag-pb (0x70),
        // sha2-256 (0x12), length 32, then the 32-byte digest.
        // This is the contenthash for bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi
        let digest =
            hex_decode("0xc3c4733ec8affd06cf9e9ff50ffc6bcd2ec85a6170004bb709669c31de94391a")
                .unwrap();
        let mut contenthash = vec![0xe3, 0x01, 0x01, 0x70, 0x12, 0x20];
        contenthash.extend_from_slice(&digest);
        let cid = contenthash_to_cid(&contenthash).unwrap();
        assert!(cid.starts_with("bafybei"));
    }

    // -----------------------------------------------------------------------
    // scale_compact_u64 — multi-mode coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_scale_compact_u64_two_byte_mode() {
        // 64 <= val < 0x4000 → two-byte mode, lower 2 bits = 0b01
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 64);
        // 64 << 2 | 1 = 257 = 0x0101 LE
        assert_eq!(buf, vec![0x01, 0x01]);
    }

    #[test]
    fn test_scale_compact_u64_four_byte_mode() {
        // 0x4000 <= val < 0x4000_0000 → four-byte mode, lower 2 bits = 0b10
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0x4000);
        // 0x4000 << 2 | 2 = 0x10002 LE 4-byte
        let expected_val: u32 = (0x4000u32 << 2) | 2;
        assert_eq!(buf, expected_val.to_le_bytes());
    }

    #[test]
    fn test_scale_compact_u64_big_mode_u64_max() {
        // u64::MAX requires big-integer mode
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, u64::MAX);
        // prefix byte: mode=3, byte_count=8, so upper 6 bits = (8-4)=4, lower 2 = 0b11
        // prefix = (4 << 2) | 3 = 19 = 0x13
        assert_eq!(buf[0], 0x13);
        // The 8 LE bytes of u64::MAX follow
        assert_eq!(buf.len(), 9);
        assert_eq!(&buf[1..], &u64::MAX.to_le_bytes());
    }

    // -----------------------------------------------------------------------
    // scale_compact_len — multi-mode coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_scale_compact_len_single_byte_boundary() {
        let mut buf = Vec::new();
        scale_compact_len(&mut buf, 0).unwrap();
        assert_eq!(buf, vec![0x00]);

        buf.clear();
        scale_compact_len(&mut buf, 63).unwrap();
        assert_eq!(buf, vec![0xfc]); // 63 << 2 = 252
    }

    #[test]
    fn test_scale_compact_len_two_byte_mode() {
        let mut buf = Vec::new();
        scale_compact_len(&mut buf, 64).unwrap();
        // 64 << 2 | 1 = 257 = 0x0101 LE
        assert_eq!(buf, vec![0x01, 0x01]);
    }

    #[test]
    fn test_scale_compact_len_four_byte_mode() {
        let mut buf = Vec::new();
        scale_compact_len(&mut buf, 16384).unwrap();
        // 16384 << 2 | 2 LE 4-byte
        let expected: u32 = (16384u32 << 2) | 2;
        assert_eq!(buf, expected.to_le_bytes());
    }

    // -----------------------------------------------------------------------
    // decode_scale_compact — multi-mode and truncation errors
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_scale_compact_two_byte_mode() {
        // Encode 64 as two-byte compact: 64 << 2 | 1 = 257 = [0x01, 0x01]
        let (val, consumed) = decode_scale_compact(&[0x01, 0x01]).unwrap();
        assert_eq!(val, 64);
        assert_eq!(consumed, 2);
    }

    #[test]
    fn test_decode_scale_compact_two_byte_truncated_returns_error() {
        // Mode bit = 0b01 but only one byte provided
        assert!(decode_scale_compact(&[0x01]).is_err());
    }

    #[test]
    fn test_decode_scale_compact_four_byte_mode() {
        // Encode 16384 as four-byte compact: 16384 << 2 | 2 LE
        let v: u32 = (16384u32 << 2) | 2;
        let input = v.to_le_bytes();
        let (val, consumed) = decode_scale_compact(&input).unwrap();
        assert_eq!(val, 16384);
        assert_eq!(consumed, 4);
    }

    #[test]
    fn test_decode_scale_compact_four_byte_truncated_returns_error() {
        // Mode bit = 0b10 but fewer than 4 bytes
        assert!(decode_scale_compact(&[0x02, 0x00, 0x00]).is_err());
    }

    #[test]
    fn test_decode_scale_compact_big_mode() {
        // Big mode: prefix = 0x03 means (0 extra bytes beyond 4) → need 4 bytes
        // Let's encode value 0x01020304 in big mode:
        // prefix byte with byte_count=4: upper 6 = (4-4)=0, lower 2 = 3 → prefix=0x03
        let input = [0x03u8, 0x04, 0x03, 0x02, 0x01];
        let (val, consumed) = decode_scale_compact(&input).unwrap();
        assert_eq!(val, 0x01020304);
        assert_eq!(consumed, 5); // 1 prefix + 4 data bytes
    }

    #[test]
    fn test_decode_scale_compact_big_mode_insufficient_data_returns_error() {
        // prefix byte claims 4 bytes needed but we only provide 3
        let input = [0x03u8, 0x04, 0x03, 0x02];
        assert!(decode_scale_compact(&input).is_err());
    }

    // -----------------------------------------------------------------------
    // decode_abi_bytes — success path
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_abi_bytes_valid() {
        // ABI encoding of bytes: offset=0x20 (32 bytes), length=5, data="hello"
        let mut data = vec![0u8; 64];
        // First 32 bytes = offset = 0x20 (written BE)
        data[31] = 0x20;
        // Next 32 bytes = length = 5 (written BE)
        data[63] = 5;
        data.extend_from_slice(b"hello");
        let result = decode_abi_bytes(&data).unwrap();
        assert_eq!(result, b"hello");
    }

    #[test]
    fn test_decode_abi_bytes_zero_length() {
        // ABI encoding of empty bytes: offset=0x20, length=0, no data
        let mut data = vec![0u8; 64];
        data[31] = 0x20;
        // length = 0 — nothing after the header
        let result = decode_abi_bytes(&data).unwrap();
        assert_eq!(result, b"");
    }

    #[test]
    fn test_decode_abi_bytes_length_exceeds_data_returns_error() {
        // Claims length=100 but only 64 bytes total
        let mut data = vec![0u8; 64];
        data[31] = 0x20;
        data[63] = 100; // length claims 100 bytes but nothing follows
        assert!(decode_abi_bytes(&data).is_err());
    }

    // -----------------------------------------------------------------------
    // hex_decode — invalid hex character path
    // -----------------------------------------------------------------------

    #[test]
    fn test_hex_decode_rejects_invalid_chars() {
        assert!(hex_decode("0xgg").is_none());
        assert!(hex_decode("zz").is_none());
    }

    // -----------------------------------------------------------------------
    // namehash — single-label domain
    // -----------------------------------------------------------------------

    #[test]
    fn test_namehash_single_label() {
        // "dot" is a single label with no separator; namehash should be non-zero
        let node = namehash("dot");
        assert_ne!(node, [0u8; 32]);
        // Verify determinism
        assert_eq!(node, namehash("dot"));
    }

    // -----------------------------------------------------------------------
    // decode_contract_result — comprehensive coverage
    // -----------------------------------------------------------------------

    /// Build a minimal valid ContractResult buffer in pallet-revive format
    /// with gas_consumed=0, gas_required=0, storage_deposit=Refund(0),
    /// Option<Balance>=None, Balance=0, debug_message="", return_data=payload.
    fn build_contract_result(payload: &[u8]) -> Vec<u8> {
        let mut buf = Vec::new();

        // gas_consumed: Weight { ref_time: Compact<u64>, proof_size: Compact<u64> }
        scale_compact_u64(&mut buf, 0); // ref_time = 0 → single byte 0x00
        scale_compact_u64(&mut buf, 0); // proof_size = 0

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

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

        // pallet-revive extra: Option<Balance> = None
        buf.push(0x00); // None

        // pallet-revive extra: Balance (u128) = 0
        buf.extend_from_slice(&0u128.to_le_bytes()); // 16 bytes

        // debug_message: Vec<u8> (compact len=0)
        scale_compact_len(&mut buf, 0).unwrap();

        // result: ExecReturnValue { flags: u32, data: Vec<u8> }
        buf.extend_from_slice(&0u32.to_le_bytes()); // flags = 0
        scale_compact_len(&mut buf, payload.len()).unwrap();
        buf.extend_from_slice(payload);

        buf
    }

    #[test]
    fn test_decode_contract_result_empty_payload() {
        let buf = build_contract_result(b"");
        let result = decode_contract_result(&buf).unwrap();
        assert_eq!(result, b"");
    }

    #[test]
    fn test_decode_contract_result_with_payload() {
        let payload = b"\x01\x02\x03\x04";
        let buf = build_contract_result(payload);
        let result = decode_contract_result(&buf).unwrap();
        assert_eq!(result, payload);
    }

    #[test]
    fn test_decode_contract_result_with_option_some() {
        // Build a result where the Option<Balance> = Some(value)
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0); // gas_consumed ref_time
        scale_compact_u64(&mut buf, 0); // gas_consumed proof_size
        scale_compact_u64(&mut buf, 0); // gas_required ref_time
        scale_compact_u64(&mut buf, 0); // gas_required proof_size
        buf.push(0x00); // storage_deposit variant
        buf.extend_from_slice(&0u128.to_le_bytes()); // storage_deposit value
        buf.push(0x01); // Option<Balance> = Some
        buf.extend_from_slice(&42u128.to_le_bytes()); // the u128 value
        buf.extend_from_slice(&0u128.to_le_bytes()); // extra Balance
        scale_compact_len(&mut buf, 0).unwrap(); // debug_message empty
        buf.extend_from_slice(&0u32.to_le_bytes()); // flags
        scale_compact_len(&mut buf, 3).unwrap(); // data len = 3
        buf.extend_from_slice(b"abc");

        let result = decode_contract_result(&buf).unwrap();
        assert_eq!(result, b"abc");
    }

    #[test]
    fn test_decode_contract_result_truncated_at_storage_deposit_returns_error() {
        // Buffer with compacts for gas but too short for storage_deposit (17 bytes needed)
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        // Only 5 bytes instead of 17 for storage_deposit
        buf.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00]);
        assert!(decode_contract_result(&buf).is_err());
    }

    #[test]
    fn test_decode_contract_result_truncated_plain_balance_returns_error() {
        // Valid through storage_deposit and Option tag = None, but the plain Balance
        // (16 bytes) is truncated to 4 bytes.
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        buf.push(0x00); // storage_deposit variant
        buf.extend_from_slice(&0u128.to_le_bytes()); // 16 bytes
        buf.push(0x00); // Option = None
        buf.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // only 4 of 16 Balance bytes
        assert!(decode_contract_result(&buf).is_err());
    }

    #[test]
    fn test_decode_contract_result_truncated_option_some_balance_returns_error() {
        // Option = Some but only 4 bytes for the u128 value (needs 16)
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        buf.push(0x00); // storage_deposit variant
        buf.extend_from_slice(&0u128.to_le_bytes()); // 16 bytes
        buf.push(0x01); // Option = Some
        buf.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // only 4 of 16 bytes
        assert!(decode_contract_result(&buf).is_err());
    }

    #[test]
    fn test_decode_contract_result_truncated_at_flags_returns_error() {
        // Valid through debug_message but missing flags (4 bytes)
        let mut buf = build_contract_result(b"payload");
        // Truncate to just before flags: remove last (4 + compact_len(7) + 7) bytes
        // build_contract_result appends: flags(4) + compact_len(7)(1) + payload(7) = 12
        let len = buf.len();
        buf.truncate(len - 12);
        // Add just the debug_message (len=0 compact = 1 byte, already included in build_contract_result)
        // but not flags
        assert!(decode_contract_result(&buf).is_err());
    }

    #[test]
    fn test_decode_contract_result_data_extends_beyond_response_returns_error() {
        // Build a result that claims a data length larger than remaining bytes
        let mut buf = build_contract_result(b"");
        // The last bytes are: flags(4) + compact_len(0)(1) = 5 bytes
        // Overwrite the compact_len byte to claim 100 bytes of data but provide none
        let len = buf.len();
        buf[len - 1] = 100u8 << 2; // compact-encode 100 in single-byte mode
        assert!(decode_contract_result(&buf).is_err());
    }

    #[test]
    fn test_decode_contract_result_with_debug_message() {
        let mut buf = Vec::new();
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        scale_compact_u64(&mut buf, 0);
        buf.push(0x00);
        buf.extend_from_slice(&0u128.to_le_bytes());
        buf.push(0x00); // Option = None
        buf.extend_from_slice(&0u128.to_le_bytes());
        // debug_message = "debug"
        scale_compact_len(&mut buf, 5).unwrap();
        buf.extend_from_slice(b"debug");
        buf.extend_from_slice(&0u32.to_le_bytes()); // flags
        scale_compact_len(&mut buf, 4).unwrap();
        buf.extend_from_slice(b"data");

        let result = decode_contract_result(&buf).unwrap();
        assert_eq!(result, b"data");
    }

    // -----------------------------------------------------------------------
    // scale_encode_revive_call — error path for oversized input_data
    // -----------------------------------------------------------------------

    #[test]
    fn test_scale_encode_revive_call_rejects_oversized_input() {
        // input_data.len() >= 1 GiB triggers the scale_compact_len error.
        // We can't actually allocate 1 GiB in a test, so we test by calling
        // scale_compact_len directly (it's the internal gating function).
        let mut buf = Vec::new();
        let result = scale_compact_len(&mut buf, 1_073_741_824);
        assert!(result.is_err());
        let msg = result.unwrap_err();
        assert!(msg.contains("too large"));
    }
}