host-encoding 0.3.8

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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! Pure encoding and decoding for the Identity and Resources pallets on
//! People chains.
//!
//! No I/O. No network calls. WASM-safe.
//!
//! Provides username normalization, storage key derivation for
//! `Identity::UsernameInfoOf` and `Resources::Consumers`, and SCALE
//! decoding of the resulting storage values.

use thiserror::Error;

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

// Import compact-length encoder from the dotns module — avoids duplicating the
// SCALE logic that already lives there.
use crate::dotns::scale_compact_len;

/// Errors produced by the identity encoding layer.
#[derive(Debug, Error, PartialEq)]
pub enum IdentityError {
    /// The normalised username exceeds the 32-byte on-chain limit.
    #[error("username is too long: {len} bytes (max 32)")]
    UsernameTooLong { len: usize },

    /// An empty string was supplied.
    #[error("username must not be empty")]
    UsernameEmpty,

    /// A character that is not `[a-z0-9.]` was found after ASCII lowercasing.
    #[error("username contains invalid character: {ch:?}")]
    InvalidCharacter { ch: char },

    /// The dot placement is invalid (leading, trailing, or consecutive dots).
    #[error("username has invalid dot placement: {reason}")]
    InvalidDotPlacement { reason: &'static str },

    /// The storage response could not be decoded.
    #[error("invalid response: {msg}")]
    InvalidResponse { msg: String },
}

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Decoded identity information from `Resources::Consumers`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerInfo {
    /// 65-byte P-256 public key (uncompressed SEC1 format).
    pub identifier_key: Vec<u8>,
    /// Full person username, present only for Person-level credibility.
    pub full_username: Option<String>,
    /// Lite username (always present).
    pub lite_username: String,
    /// Credibility level for this consumer.
    pub credibility: Credibility,
}

/// Credibility level stored in `Resources::Consumers`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Credibility {
    /// Lite credibility — no alias or timestamp.
    Lite,
    /// Person-level credibility with a 32-byte alias and last-update timestamp.
    Person {
        /// 32-byte opaque alias identifier.
        alias: [u8; 32],
        /// UNIX timestamp (seconds) of the last credibility update.
        last_update: u64,
    },
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Normalise a username and return its UTF-8 bytes.
///
/// Applies ASCII lowercasing (not Unicode lowercasing, to avoid the Turkish İ
/// problem) and validates that every character is in `[a-z0-9.]`.  The
/// normalised form must be 1–32 bytes inclusive.
///
/// Dot placement rules (enforced after character validation):
/// - No leading dot (`".alice"` is rejected).
/// - No trailing dot (`"alice."` is rejected).
/// - No consecutive dots (`"alice..1"` is rejected).
///
/// These rules match the on-chain People pallet's username validity checks and
/// prevent storage key confusion from structurally malformed names.
pub fn normalize_username(username: &str) -> Result<Vec<u8>, IdentityError> {
    if username.is_empty() {
        return Err(IdentityError::UsernameEmpty);
    }

    // Reject null bytes before any further processing — they would pass the
    // `is_ascii()` check on some platforms and corrupt storage keys.
    if username.contains('\0') {
        return Err(IdentityError::InvalidCharacter { ch: '\0' });
    }

    // ASCII-only lowercase to sidestep Unicode case-folding quirks (Turkish İ,
    // Greek ς, etc.).
    let lower = username.to_ascii_lowercase();
    let bytes = lower.as_bytes();

    // Validate characters after lowercasing.
    for &b in bytes {
        let ch = b as char;
        if !matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'.') {
            return Err(IdentityError::InvalidCharacter { ch });
        }
    }

    if bytes.len() > 32 {
        return Err(IdentityError::UsernameTooLong { len: bytes.len() });
    }

    // Reject structurally invalid dot placements. Character validation above
    // has already confirmed every byte is in [a-z0-9.], so these checks are
    // purely positional.
    if bytes.first() == Some(&b'.') {
        return Err(IdentityError::InvalidDotPlacement {
            reason: "leading dot",
        });
    }
    if bytes.last() == Some(&b'.') {
        return Err(IdentityError::InvalidDotPlacement {
            reason: "trailing dot",
        });
    }
    if bytes.windows(2).any(|w| w == b"..") {
        return Err(IdentityError::InvalidDotPlacement {
            reason: "consecutive dots",
        });
    }

    Ok(bytes.to_vec())
}

/// Derive the Substrate storage key for `Identity::UsernameInfoOf[username]`.
///
/// Layout:
/// ```text
/// twox_128("Identity") ++ twox_128("UsernameInfoOf") ++ blake2_128_concat(scale_encode(username_bytes))
/// ```
///
/// The username is SCALE-encoded as `BoundedVec<u8>`:
/// `compact_len(bytes.len()) ++ bytes`.
///
/// `username_bytes` must already be normalised (i.e. the output of
/// [`normalize_username`]).
pub fn username_info_of_key(username_bytes: &[u8]) -> Vec<u8> {
    let pallet_hash = twox_128(b"Identity");
    let storage_hash = twox_128(b"UsernameInfoOf");

    // SCALE BoundedVec<u8>: compact length prefix followed by the raw bytes.
    let mut encoded_username = Vec::with_capacity(username_bytes.len() + 4);
    // scale_compact_len cannot fail for inputs <= 32 bytes (well within the
    // single-byte mode limit of 63).
    scale_compact_len(&mut encoded_username, username_bytes.len())
        .expect("username_bytes.len() <= 32 is always within compact single-byte range");
    encoded_username.extend_from_slice(username_bytes);

    // blake2_128_concat = blake2_128(data) ++ data
    let hash_prefix = blake2_128(&encoded_username);

    let mut key = Vec::with_capacity(16 + 16 + 16 + encoded_username.len());
    key.extend_from_slice(&pallet_hash);
    key.extend_from_slice(&storage_hash);
    key.extend_from_slice(&hash_prefix);
    key.extend_from_slice(&encoded_username);
    key
}

/// Derive the Substrate storage key for `Resources::UsernameOwnerOf[username]`.
///
/// Used on the Individuality chain where lite usernames are stored in the
/// `Resources` pallet rather than `Identity`.
///
/// Layout:
/// ```text
/// twox_128("Resources") ++ twox_128("UsernameOwnerOf") ++ blake2_128_concat(scale_encode(username_bytes))
/// ```
///
/// The username is SCALE-encoded as `BoundedVec<u8>`:
/// `compact_len(bytes.len()) ++ bytes`.
///
/// `username_bytes` must already be normalised (i.e. the output of
/// [`normalize_username`]).
pub fn username_owner_of_key(username_bytes: &[u8]) -> Vec<u8> {
    let pallet_hash = twox_128(b"Resources");
    let storage_hash = twox_128(b"UsernameOwnerOf");

    // SCALE BoundedVec<u8>: compact length prefix followed by the raw bytes.
    let mut encoded_username = Vec::with_capacity(username_bytes.len() + 4);
    // scale_compact_len cannot fail for inputs <= 32 bytes (well within the
    // single-byte mode limit of 63).
    scale_compact_len(&mut encoded_username, username_bytes.len())
        .expect("username_bytes.len() <= 32 is always within compact single-byte range");
    encoded_username.extend_from_slice(username_bytes);

    // blake2_128_concat = blake2_128(data) ++ data
    let hash_prefix = blake2_128(&encoded_username);

    let mut key = Vec::with_capacity(16 + 16 + 16 + encoded_username.len());
    key.extend_from_slice(&pallet_hash);
    key.extend_from_slice(&storage_hash);
    key.extend_from_slice(&hash_prefix);
    key.extend_from_slice(&encoded_username);
    key
}

/// Decode the raw `AccountId32` returned by `Resources::UsernameOwnerOf` on the
/// Individuality chain.
///
/// Unlike `Identity::UsernameInfoOf`, this storage map returns a bare
/// `AccountId32` — exactly 32 bytes with no Option wrapper and no provider byte.
///
/// | Input                        | Output               |
/// |------------------------------|----------------------|
/// | `[]` (empty — slot absent)   | `Ok(None)`           |
/// | `[b0..b31]` (32 bytes)       | `Ok(Some([u8; 32]))` |
/// | `< 32 bytes`                 | `Err`                |
///
/// Trailing bytes beyond 32 are silently ignored (same permissive behaviour as
/// `decode_username_info_owner`).
pub fn decode_username_owner(data: &[u8]) -> Result<Option<[u8; 32]>, IdentityError> {
    if data.is_empty() {
        return Ok(None);
    }
    if data.len() < 32 {
        return Err(IdentityError::InvalidResponse {
            msg: format!(
                "UsernameOwnerOf truncated: expected 32 bytes, got {}",
                data.len()
            ),
        });
    }
    let mut account = [0u8; 32];
    account.copy_from_slice(&data[..32]);
    Ok(Some(account))
}

/// Derive the Substrate storage key for `Resources::Consumers[account_id]`.
///
/// Layout:
/// ```text
/// twox_128("Resources") ++ twox_128("Consumers") ++ blake2_128_concat(account_id)
/// ```
///
/// `account_id` is a fixed-size 32-byte type — it is passed directly to
/// `blake2_128_concat` WITHOUT a SCALE compact length prefix (unlike
/// `BoundedVec<u8>` keys such as usernames).
pub fn consumers_key(account_id: &[u8; 32]) -> Vec<u8> {
    let pallet_hash = twox_128(b"Resources");
    let storage_hash = twox_128(b"Consumers");

    // blake2_128_concat over the raw 32-byte account ID — no length prefix.
    let hash_prefix = blake2_128(account_id);

    let mut key = Vec::with_capacity(16 + 16 + 16 + 32);
    key.extend_from_slice(&pallet_hash);
    key.extend_from_slice(&storage_hash);
    key.extend_from_slice(&hash_prefix);
    key.extend_from_slice(account_id);
    key
}

/// Decode the SCALE-encoded `Option<AccountId32>` returned by a storage query.
///
/// | Input                        | Output            |
/// |------------------------------|-------------------|
/// | `[]` (empty — slot absent)   | `Ok(None)`        |
/// | `[0x00]`                     | `Ok(None)`        |
/// | `[0x01, b0..b31]`            | `Ok(Some([u8;32]))`|
///
/// Returns `Err` for truncated data, unknown tag bytes, or trailing garbage.
pub fn decode_option_account_id(data: &[u8]) -> Result<Option<[u8; 32]>, IdentityError> {
    // Empty response — the storage slot doesn't exist on-chain.
    if data.is_empty() {
        return Ok(None);
    }

    match data[0] {
        0x00 => {
            // None variant — reject trailing bytes to catch malformed responses.
            if data.len() != 1 {
                return Err(IdentityError::InvalidResponse {
                    msg: format!(
                        "Option::None tag followed by {} unexpected byte(s)",
                        data.len() - 1
                    ),
                });
            }
            Ok(None)
        }
        0x01 => {
            // Some variant — expect exactly 32 bytes of AccountId32 payload.
            let payload = &data[1..];
            if payload.len() < 32 {
                return Err(IdentityError::InvalidResponse {
                    msg: format!(
                        "Option::Some truncated: expected 32 bytes, got {}",
                        payload.len()
                    ),
                });
            }
            if payload.len() > 32 {
                return Err(IdentityError::InvalidResponse {
                    msg: format!(
                        "Option::Some has {} trailing byte(s) after AccountId32",
                        payload.len() - 32
                    ),
                });
            }
            let mut account = [0u8; 32];
            account.copy_from_slice(payload);
            Ok(Some(account))
        }
        tag => Err(IdentityError::InvalidResponse {
            msg: format!("unknown Option tag byte: 0x{tag:02x}"),
        }),
    }
}

/// Decode the raw `UsernameInformation` value from `Identity::UsernameInfoOf`.
///
/// The value is `{ owner: AccountId32, provider: u8 }` — 33 bytes minimum.
/// We extract only the `owner` field (first 32 bytes).
///
/// Returns `Ok(Some([u8; 32]))` when data is present, `Ok(None)` for empty input.
pub fn decode_username_info_owner(data: &[u8]) -> Result<Option<[u8; 32]>, IdentityError> {
    if data.is_empty() {
        return Ok(None);
    }
    if data.len() < 32 {
        return Err(IdentityError::InvalidResponse {
            msg: format!(
                "UsernameInformation truncated: expected >= 32 bytes, got {}",
                data.len()
            ),
        });
    }
    let mut account = [0u8; 32];
    account.copy_from_slice(&data[..32]);
    Ok(Some(account))
}

/// Decode a SCALE-encoded `ConsumerInfo` from a `state_getStorage` response.
///
/// SCALE layout (in field order):
/// 1. `identifier_key`: 65 bytes (fixed array, no length prefix)
/// 2. `full_username`: `Option<BoundedVec<u8, 32>>` — `0x00` = None, `0x01 + compact_len + bytes` = Some
/// 3. `lite_username`: `BoundedVec<u8, 32>` — compact_len + bytes
/// 4. `credibility`: enum — `0x00` = Lite, `0x01 + alias(32B) + last_update(u64 LE)` = Person
///
/// Fields after `credibility` (e.g. `stmt_store_slots`) are intentionally
/// skipped — clients do not use them.
///
/// Returns `Err` for empty input, truncated data, invalid UTF-8, or unknown
/// enum tags.
pub fn decode_consumer_info(data: &[u8]) -> Result<ConsumerInfo, IdentityError> {
    if data.is_empty() {
        return Err(IdentityError::InvalidResponse {
            msg: "empty data — storage slot absent".into(),
        });
    }

    let mut cursor = 0usize;

    // 1. identifier_key: fixed 65 bytes.
    let identifier_key = read_fixed(data, &mut cursor, 65)?;

    // 2. full_username: Option<BoundedVec<u8, 32>>.
    let full_username = decode_option_bounded_vec_utf8(data, &mut cursor, "full_username")?;

    // 3. lite_username: BoundedVec<u8, 32> (always present).
    let lite_username = decode_bounded_vec_utf8(data, &mut cursor, "lite_username")?;

    // 4. credibility enum.
    let credibility = decode_credibility(data, &mut cursor)?;

    Ok(ConsumerInfo {
        identifier_key,
        full_username,
        lite_username,
        credibility,
    })
}

/// Format an AccountId32 as a `0x`-prefixed lowercase hex string.
pub fn account_id_to_hex(account_id: &[u8; 32]) -> String {
    hex_encode(account_id)
}

// ---------------------------------------------------------------------------
// Private decoding helpers
// ---------------------------------------------------------------------------

/// Read exactly `n` bytes from `data` starting at `*cursor`, advance the cursor.
fn read_fixed(data: &[u8], cursor: &mut usize, n: usize) -> Result<Vec<u8>, IdentityError> {
    let end = cursor
        .checked_add(n)
        .ok_or_else(|| IdentityError::InvalidResponse {
            msg: "byte offset overflow".into(),
        })?;
    if end > data.len() {
        return Err(IdentityError::InvalidResponse {
            msg: format!(
                "truncated: need {} bytes at offset {}, only {} available",
                n,
                *cursor,
                data.len() - *cursor
            ),
        });
    }
    let bytes = data[*cursor..end].to_vec();
    *cursor = end;
    Ok(bytes)
}

/// Decode a SCALE compact integer from `data` at `*cursor`, advance the cursor.
///
/// Only the single-byte (0–63) and two-byte (64–16383) modes are needed for
/// BoundedVec<u8, 32> fields (max length 32 fits in single-byte mode).
fn read_compact(data: &[u8], cursor: &mut usize, field: &str) -> Result<usize, IdentityError> {
    if *cursor >= data.len() {
        return Err(IdentityError::InvalidResponse {
            msg: format!("truncated: missing compact length byte for {field}"),
        });
    }
    let first = data[*cursor];
    let mode = first & 0b11;
    match mode {
        0b00 => {
            // Single-byte mode: value in top 6 bits.
            *cursor += 1;
            Ok((first >> 2) as usize)
        }
        0b01 => {
            // Two-byte mode: 14-bit value across two bytes.
            if *cursor + 2 > data.len() {
                return Err(IdentityError::InvalidResponse {
                    msg: format!("truncated: 2-byte compact integer for {field}"),
                });
            }
            let second = data[*cursor + 1];
            let value = first as usize >> 2 | (second as usize) << 6;
            *cursor += 2;
            Ok(value)
        }
        _ => Err(IdentityError::InvalidResponse {
            msg: format!("unsupported compact mode 0b{mode:02b} for {field}"),
        }),
    }
}

/// Decode a `BoundedVec<u8>` as a UTF-8 string.
fn decode_bounded_vec_utf8(
    data: &[u8],
    cursor: &mut usize,
    field: &str,
) -> Result<String, IdentityError> {
    let len = read_compact(data, cursor, field)?;
    let raw = read_fixed(data, cursor, len)?;
    String::from_utf8(raw).map_err(|_| IdentityError::InvalidResponse {
        msg: format!("{field} contains invalid UTF-8"),
    })
}

/// Decode an `Option<BoundedVec<u8>>` as an optional UTF-8 string.
fn decode_option_bounded_vec_utf8(
    data: &[u8],
    cursor: &mut usize,
    field: &str,
) -> Result<Option<String>, IdentityError> {
    if *cursor >= data.len() {
        return Err(IdentityError::InvalidResponse {
            msg: format!("truncated: missing Option tag for {field}"),
        });
    }
    let tag = data[*cursor];
    *cursor += 1;
    match tag {
        0x00 => Ok(None),
        0x01 => Ok(Some(decode_bounded_vec_utf8(data, cursor, field)?)),
        _ => Err(IdentityError::InvalidResponse {
            msg: format!("unknown Option tag 0x{tag:02x} for {field}"),
        }),
    }
}

/// Decode the `Credibility` enum at `*cursor`.
fn decode_credibility(data: &[u8], cursor: &mut usize) -> Result<Credibility, IdentityError> {
    if *cursor >= data.len() {
        return Err(IdentityError::InvalidResponse {
            msg: "truncated: missing credibility tag byte".into(),
        });
    }
    let tag = data[*cursor];
    *cursor += 1;
    match tag {
        0x00 => Ok(Credibility::Lite),
        0x01 => {
            // Person variant: 32-byte alias + u64 LE last_update.
            let alias_bytes = read_fixed(data, cursor, 32)?;
            let ts_bytes = read_fixed(data, cursor, 8)?;

            let mut alias = [0u8; 32];
            alias.copy_from_slice(&alias_bytes);

            let last_update = u64::from_le_bytes(
                ts_bytes
                    .as_slice()
                    .try_into()
                    .expect("ts_bytes is exactly 8 bytes from read_fixed"),
            );
            Ok(Credibility::Person { alias, last_update })
        }
        tag => Err(IdentityError::InvalidResponse {
            msg: format!("unknown Credibility variant tag: 0x{tag:02x}"),
        }),
    }
}

// ---------------------------------------------------------------------------
// Private hash helpers
// ---------------------------------------------------------------------------

/// XxHash-based 128-bit hash used by Substrate for pallet/storage name hashing.
///
/// Computes two independent XxHash64 values (seed 0 and seed 1) and
/// concatenates their little-endian bytes, matching the Substrate
/// `twox_128` implementation exactly.
fn twox_128(data: &[u8]) -> [u8; 16] {
    use std::hash::Hasher;
    use twox_hash::XxHash64;

    let mut h0 = XxHash64::with_seed(0);
    h0.write(data);
    let mut h1 = XxHash64::with_seed(1);
    h1.write(data);

    let mut result = [0u8; 16];
    result[..8].copy_from_slice(&h0.finish().to_le_bytes());
    result[8..].copy_from_slice(&h1.finish().to_le_bytes());
    result
}

/// Blake2b with a 16-byte (128-bit) output digest.
fn blake2_128(data: &[u8]) -> [u8; 16] {
    use blake2::digest::consts::U16;
    use blake2::{Blake2b, Digest};

    let mut hasher = Blake2b::<U16>::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut out = [0u8; 16];
    out.copy_from_slice(&result);
    out
}

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

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

    // -----------------------------------------------------------------------
    // normalize_username
    // -----------------------------------------------------------------------

    #[test]
    fn test_rejects_empty_username() {
        assert_eq!(normalize_username(""), Err(IdentityError::UsernameEmpty));
    }

    #[test]
    fn test_accepts_single_char_username() {
        assert_eq!(normalize_username("a"), Ok(b"a".to_vec()));
    }

    #[test]
    fn test_accepts_max_length_username() {
        // Exactly 32 lowercase ASCII characters — the on-chain limit.
        let username = "a".repeat(32);
        let result = normalize_username(&username).unwrap();
        assert_eq!(result.len(), 32);
    }

    #[test]
    fn test_rejects_username_one_over_max_length() {
        let username = "a".repeat(33);
        assert_eq!(
            normalize_username(&username),
            Err(IdentityError::UsernameTooLong { len: 33 })
        );
    }

    #[test]
    fn test_normalizes_mixed_case_username() {
        let result = normalize_username("Alice").unwrap();
        assert_eq!(result, b"alice");
    }

    #[test]
    fn test_accepts_already_lowercase_username() {
        let result = normalize_username("alice").unwrap();
        assert_eq!(result, b"alice");
    }

    #[test]
    fn test_rejects_space_character() {
        assert_eq!(
            normalize_username("ali ce"),
            Err(IdentityError::InvalidCharacter { ch: ' ' })
        );
    }

    #[test]
    fn test_rejects_tab_character() {
        assert_eq!(
            normalize_username("ali\tce"),
            Err(IdentityError::InvalidCharacter { ch: '\t' })
        );
    }

    #[test]
    fn test_rejects_null_byte() {
        assert_eq!(
            normalize_username("ali\0ce"),
            Err(IdentityError::InvalidCharacter { ch: '\0' })
        );
    }

    #[test]
    fn test_rejects_slash_character() {
        assert_eq!(
            normalize_username("ali/ce"),
            Err(IdentityError::InvalidCharacter { ch: '/' })
        );
    }

    #[test]
    fn test_rejects_exclamation_character() {
        assert_eq!(
            normalize_username("alice!"),
            Err(IdentityError::InvalidCharacter { ch: '!' })
        );
    }

    #[test]
    fn test_accepts_username_with_internal_dot() {
        // A dot between alphanumeric segments is valid (e.g. on-chain handles).
        let result = normalize_username("alice.dot").unwrap();
        assert_eq!(result, b"alice.dot");
    }

    #[test]
    fn test_rejects_username_with_leading_dot() {
        assert_eq!(
            normalize_username(".alice"),
            Err(IdentityError::InvalidDotPlacement {
                reason: "leading dot"
            })
        );
    }

    #[test]
    fn test_rejects_username_with_trailing_dot() {
        assert_eq!(
            normalize_username("alice."),
            Err(IdentityError::InvalidDotPlacement {
                reason: "trailing dot"
            })
        );
    }

    #[test]
    fn test_rejects_username_with_consecutive_dots() {
        assert_eq!(
            normalize_username("alice..1"),
            Err(IdentityError::InvalidDotPlacement {
                reason: "consecutive dots"
            })
        );
    }

    #[test]
    fn test_rejects_username_with_only_dots() {
        // A single dot is both a leading and trailing dot — rejected as leading dot first.
        assert_eq!(
            normalize_username("."),
            Err(IdentityError::InvalidDotPlacement {
                reason: "leading dot"
            })
        );
    }

    #[test]
    fn test_accepts_alphanumeric_username() {
        let result = normalize_username("user42").unwrap();
        assert_eq!(result, b"user42");
    }

    // -----------------------------------------------------------------------
    // username_info_of_key
    // -----------------------------------------------------------------------

    /// The storage key is 32 (pallet+storage hashes) + 16 (blake2_128 prefix) +
    /// compact_len(n) + n bytes for the username.  For a 1-byte username the
    /// compact length is 1 byte, so total = 32 + 16 + 1 + 1 = 50.
    #[test]
    fn test_username_info_of_key_length_single_byte_username() {
        let key = username_info_of_key(b"a");
        // 16 (pallet) + 16 (storage) + 16 (blake2_128) + 1 (compact len) + 1 (byte) = 50
        assert_eq!(key.len(), 50);
    }

    #[test]
    fn test_username_info_of_key_length_longer_username() {
        // "alice.dot" = 9 bytes; compact(9) = 1 byte → total = 58
        let key = username_info_of_key(b"alice.dot");
        assert_eq!(key.len(), 16 + 16 + 16 + 1 + 9);
    }

    /// The first 32 bytes of the storage key are fixed for any username queried
    /// against the same pallet/storage entry.
    #[test]
    fn test_username_info_of_key_prefix_is_stable() {
        let key_a = username_info_of_key(b"alice");
        let key_b = username_info_of_key(b"bob");
        // First 32 bytes = twox_128("Identity") ++ twox_128("UsernameInfoOf")
        assert_eq!(&key_a[..32], &key_b[..32]);
    }

    #[test]
    fn test_different_usernames_produce_different_storage_keys() {
        let key_a = username_info_of_key(b"alice");
        let key_b = username_info_of_key(b"bob");
        assert_ne!(key_a, key_b);
    }

    /// Normalised lowercase and the equivalent mixed-case input must produce
    /// identical keys (the caller is responsible for normalising first, but
    /// we verify that the byte-level encoding is stable).
    #[test]
    fn test_username_info_of_key_same_for_lowercase_and_normalised_input() {
        let lower = normalize_username("Alice").unwrap();
        let direct = normalize_username("alice").unwrap();
        assert_eq!(username_info_of_key(&lower), username_info_of_key(&direct));
    }

    /// Pinned vector: the first 32 bytes of the storage key are derived from
    /// `twox_128("Identity")` and `twox_128("UsernameInfoOf")`.  This value
    /// must not change without a corresponding on-chain storage migration.
    #[test]
    fn test_username_info_of_key_prefix_pinned() {
        let key = username_info_of_key(b"a");
        // twox_128("Identity") ++ twox_128("UsernameInfoOf") — computed once
        // from the twox_128 implementation in this crate and pinned here so
        // any accidental pallet rename is caught immediately.
        let identity_hash = hex_decode(&hex_encode(&twox_128(b"Identity"))).unwrap();
        let storage_hash = hex_decode(&hex_encode(&twox_128(b"UsernameInfoOf"))).unwrap();
        let mut expected_prefix = Vec::new();
        expected_prefix.extend_from_slice(&identity_hash);
        expected_prefix.extend_from_slice(&storage_hash);
        assert_eq!(&key[..32], expected_prefix.as_slice());
    }

    /// Pinned against the known live-chain value for `Identity::UsernameInfoOf`.
    ///
    /// The prefix `0x2aeddc77fe58c98d50bd37f1b90840f93da3e15a0621aae33d5d5d4a5487e798`
    /// was observed from the live Paseo People chain and is pinned here to catch
    /// any accidental regression in the pallet or storage name.
    #[test]
    fn test_username_info_of_key_prefix_matches_live_chain() {
        let key = username_info_of_key(b"a");
        let expected_hex = "2aeddc77fe58c98d50bd37f1b90840f93da3e15a0621aae33d5d5d4a5487e798";
        let expected_bytes = hex_decode(&format!("0x{expected_hex}")).unwrap();
        assert_eq!(&key[..32], expected_bytes.as_slice());
    }

    // -----------------------------------------------------------------------
    // username_owner_of_key
    // -----------------------------------------------------------------------

    /// Pin the first 32 bytes of the storage key for `Resources::UsernameOwnerOf`.
    ///
    /// These bytes are derived from `twox_128("Resources") ++ twox_128("UsernameOwnerOf")`
    /// and must remain stable unless the Individuality chain undergoes a storage
    /// migration that renames the pallet or storage item.
    #[test]
    fn test_username_owner_of_key_prefix_pinned() {
        let key = username_owner_of_key(b"a");
        let resources_hash = twox_128(b"Resources");
        let storage_hash = twox_128(b"UsernameOwnerOf");
        let mut expected_prefix = Vec::new();
        expected_prefix.extend_from_slice(&resources_hash);
        expected_prefix.extend_from_slice(&storage_hash);
        assert_eq!(&key[..32], expected_prefix.as_slice());
    }

    /// The same username must produce different storage keys for
    /// `Identity::UsernameInfoOf` vs `Resources::UsernameOwnerOf`.
    #[test]
    fn test_username_owner_of_key_differs_from_info_key() {
        let username = b"alice";
        let info_key = username_info_of_key(username);
        let owner_key = username_owner_of_key(username);
        // Different pallet/storage prefix means the keys must diverge.
        assert_ne!(info_key, owner_key);
        // The suffix (blake2_128_concat of the encoded username) is identical;
        // only the first 32 bytes differ.
        assert_ne!(&info_key[..32], &owner_key[..32]);
    }

    // -----------------------------------------------------------------------
    // decode_username_owner
    // -----------------------------------------------------------------------

    /// A valid 32-byte response decodes to `Some(account)`.
    #[test]
    fn test_decode_username_owner_valid() {
        let account = [0x42u8; 32];
        assert_eq!(decode_username_owner(&account), Ok(Some(account)));
    }

    /// An empty slice (storage slot absent) decodes to `None`.
    #[test]
    fn test_decode_username_owner_empty() {
        assert_eq!(decode_username_owner(&[]), Ok(None));
    }

    /// A slice shorter than 32 bytes is an error.
    #[test]
    fn test_decode_username_owner_truncated() {
        let data = vec![0x42u8; 10];
        assert!(matches!(
            decode_username_owner(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    // -----------------------------------------------------------------------
    // consumers_key
    // -----------------------------------------------------------------------

    #[test]
    fn test_consumers_key_has_correct_length() {
        let account_id = [0x42u8; 32];
        let key = consumers_key(&account_id);
        // 16 (pallet) + 16 (storage) + 16 (blake2_128) + 32 (account_id) = 80
        assert_eq!(key.len(), 80);
    }

    #[test]
    fn test_consumers_key_prefix_is_stable() {
        let key_a = consumers_key(&[0x01u8; 32]);
        let key_b = consumers_key(&[0x02u8; 32]);
        // First 32 bytes = twox_128("Resources") ++ twox_128("Consumers")
        assert_eq!(&key_a[..32], &key_b[..32]);
    }

    #[test]
    fn test_consumers_key_differs_for_different_account_ids() {
        let key_a = consumers_key(&[0x01u8; 32]);
        let key_b = consumers_key(&[0x02u8; 32]);
        assert_ne!(key_a, key_b);
    }

    #[test]
    fn test_consumers_key_prefix_uses_resources_pallet() {
        let key = consumers_key(&[0x00u8; 32]);
        let resources_hash = twox_128(b"Resources");
        let consumers_hash = twox_128(b"Consumers");
        assert_eq!(&key[..16], &resources_hash);
        assert_eq!(&key[16..32], &consumers_hash);
    }

    #[test]
    fn test_consumers_key_does_not_length_prefix_account_id() {
        // The account_id should appear verbatim in the last 32 bytes of the key.
        let account_id = [0xabu8; 32];
        let key = consumers_key(&account_id);
        // Last 32 bytes = raw account_id (no length prefix).
        assert_eq!(&key[48..], &account_id);
    }

    // -----------------------------------------------------------------------
    // decode_username_info_owner
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_username_info_owner_empty_returns_none() {
        assert_eq!(decode_username_info_owner(&[]), Ok(None));
    }

    #[test]
    fn test_decode_username_info_owner_valid_33_bytes() {
        // 32 bytes owner + 1 byte provider (Authority = 0x00).
        let owner = [0x42u8; 32];
        let mut data = Vec::with_capacity(33);
        data.extend_from_slice(&owner);
        data.push(0x00); // provider: Authority
        assert_eq!(decode_username_info_owner(&data), Ok(Some(owner)));
    }

    #[test]
    fn test_decode_username_info_owner_ignores_extra_bytes() {
        // More than 33 bytes is fine — we only extract the first 32.
        let owner = [0xabu8; 32];
        let mut data = Vec::with_capacity(40);
        data.extend_from_slice(&owner);
        data.extend_from_slice(&[0x01u8; 8]); // extra bytes
        assert_eq!(decode_username_info_owner(&data), Ok(Some(owner)));
    }

    #[test]
    fn test_decode_username_info_owner_truncated_returns_error() {
        // Only 10 bytes — too short for a 32-byte owner.
        let data = vec![0x42u8; 10];
        assert!(matches!(
            decode_username_info_owner(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_decode_username_info_owner_exactly_32_bytes() {
        // Exactly 32 bytes is valid (provider byte missing but we only need owner).
        let owner = [0x11u8; 32];
        assert_eq!(decode_username_info_owner(&owner), Ok(Some(owner)));
    }

    // -----------------------------------------------------------------------
    // decode_option_account_id
    // -----------------------------------------------------------------------

    #[test]
    fn test_decodes_empty_slice_as_none() {
        assert_eq!(decode_option_account_id(&[]), Ok(None));
    }

    #[test]
    fn test_decodes_zero_tag_as_none() {
        assert_eq!(decode_option_account_id(&[0x00]), Ok(None));
    }

    #[test]
    fn test_decodes_some_with_valid_account_id() {
        let mut data = vec![0x01u8];
        let account = [0x42u8; 32];
        data.extend_from_slice(&account);
        let result = decode_option_account_id(&data).unwrap();
        assert_eq!(result, Some(account));
    }

    #[test]
    fn test_decodes_all_zeros_account_id() {
        let mut data = vec![0x01u8];
        data.extend_from_slice(&[0x00u8; 32]);
        let result = decode_option_account_id(&data).unwrap();
        assert_eq!(result, Some([0x00u8; 32]));
    }

    #[test]
    fn test_decodes_all_ff_account_id() {
        let mut data = vec![0x01u8];
        data.extend_from_slice(&[0xffu8; 32]);
        let result = decode_option_account_id(&data).unwrap();
        assert_eq!(result, Some([0xffu8; 32]));
    }

    #[test]
    fn test_rejects_truncated_some_response() {
        // Tag = Some but only 10 bytes of payload instead of 32.
        let mut data = vec![0x01u8];
        data.extend_from_slice(&[0x00u8; 10]);
        assert!(matches!(
            decode_option_account_id(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_rejects_trailing_bytes_after_none() {
        // Tag = None but with extra garbage.
        let data = vec![0x00u8, 0xde, 0xad];
        assert!(matches!(
            decode_option_account_id(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_rejects_trailing_bytes_after_some() {
        // Tag = Some, 32-byte account, then extra byte.
        let mut data = vec![0x01u8];
        data.extend_from_slice(&[0x42u8; 32]);
        data.push(0xff); // trailing garbage
        assert!(matches!(
            decode_option_account_id(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_rejects_unknown_tag_byte() {
        let data = vec![0x02u8];
        assert!(matches!(
            decode_option_account_id(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_rejects_garbage_tag_byte() {
        let data = vec![0xffu8, 0x00, 0x00];
        assert!(matches!(
            decode_option_account_id(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    // -----------------------------------------------------------------------
    // account_id_to_hex
    // -----------------------------------------------------------------------

    #[test]
    fn test_converts_account_id_to_known_hex_string() {
        let account = [0xabu8; 32];
        let hex = account_id_to_hex(&account);
        // 0x prefix + 32 bytes * 2 hex chars each = 66 chars total.
        assert_eq!(hex.len(), 66);
        assert!(hex.starts_with("0x"));
        // Build the expected string programmatically to avoid off-by-one in the literal.
        let expected = format!("0x{}", "ab".repeat(32));
        assert_eq!(hex, expected);
    }

    #[test]
    fn test_converts_zero_account_id_to_hex() {
        let account = [0x00u8; 32];
        let hex = account_id_to_hex(&account);
        assert_eq!(
            hex,
            "0x0000000000000000000000000000000000000000000000000000000000000000"
        );
    }

    #[test]
    fn test_converts_mixed_account_id_to_lowercase_hex() {
        let mut account = [0x00u8; 32];
        account[0] = 0xAB;
        account[31] = 0xCD;
        let hex = account_id_to_hex(&account);
        // Must be lowercase.
        assert!(hex.chars().all(|c| !c.is_uppercase()));
        assert!(hex.starts_with("0xab"));
        assert!(hex.ends_with("cd"));
    }

    // -----------------------------------------------------------------------
    // decode_consumer_info
    // -----------------------------------------------------------------------

    /// Build a minimal valid ConsumerInfo SCALE encoding.
    fn build_consumer_info_bytes(
        identifier_key: &[u8; 65],
        full_username: Option<&[u8]>,
        lite_username: &[u8],
        credibility_tag: u8,
        alias: Option<&[u8; 32]>,
        last_update: Option<u64>,
    ) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(identifier_key);

        // full_username: Option<BoundedVec<u8, 32>>
        match full_username {
            None => buf.push(0x00),
            Some(s) => {
                buf.push(0x01);
                // SCALE compact length (single-byte mode for len <= 63)
                buf.push((s.len() as u8) << 2);
                buf.extend_from_slice(s);
            }
        }

        // lite_username: BoundedVec<u8, 32>
        buf.push((lite_username.len() as u8) << 2);
        buf.extend_from_slice(lite_username);

        // credibility
        buf.push(credibility_tag);
        if credibility_tag == 0x01 {
            buf.extend_from_slice(alias.unwrap());
            buf.extend_from_slice(&last_update.unwrap().to_le_bytes());
        }
        buf
    }

    #[test]
    fn test_decode_consumer_info_lite_credibility() {
        let identifier_key = [0x04u8; 65];
        let lite_username = b"alice.dot";
        let data = build_consumer_info_bytes(
            &identifier_key,
            None,
            lite_username,
            0x00, // Lite
            None,
            None,
        );

        let info = decode_consumer_info(&data).unwrap();
        assert_eq!(info.identifier_key, identifier_key);
        assert_eq!(info.full_username, None);
        assert_eq!(info.lite_username, "alice.dot");
        assert_eq!(info.credibility, Credibility::Lite);
    }

    #[test]
    fn test_decode_consumer_info_person_credibility() {
        let identifier_key = [0x04u8; 65];
        let full_username = b"alice.person";
        let lite_username = b"alice";
        let alias = [0xbbu8; 32];
        let last_update: u64 = 1_700_000_000;

        let data = build_consumer_info_bytes(
            &identifier_key,
            Some(full_username),
            lite_username,
            0x01, // Person
            Some(&alias),
            Some(last_update),
        );

        let info = decode_consumer_info(&data).unwrap();
        assert_eq!(info.identifier_key, identifier_key);
        assert_eq!(info.full_username, Some("alice.person".to_string()));
        assert_eq!(info.lite_username, "alice");
        assert_eq!(info.credibility, Credibility::Person { alias, last_update });
    }

    #[test]
    fn test_decode_consumer_info_rejects_empty_data() {
        assert!(matches!(
            decode_consumer_info(&[]),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_decode_consumer_info_rejects_truncated_identifier_key() {
        // Only 10 bytes — way too short for the 65-byte identifier_key.
        let data = vec![0x04u8; 10];
        assert!(matches!(
            decode_consumer_info(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_decode_consumer_info_rejects_unknown_credibility_tag() {
        let identifier_key = [0x04u8; 65];
        let mut data = build_consumer_info_bytes(&identifier_key, None, b"alice", 0x00, None, None);
        // Overwrite the credibility byte with an unknown tag.
        *data.last_mut().unwrap() = 0x05;
        assert!(matches!(
            decode_consumer_info(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_decode_consumer_info_person_truncated_alias() {
        let identifier_key = [0x04u8; 65];
        let lite_username = b"alice";
        let mut data = Vec::new();
        data.extend_from_slice(&identifier_key);
        data.push(0x00); // full_username: None
        data.push((lite_username.len() as u8) << 2);
        data.extend_from_slice(lite_username);
        data.push(0x01); // Person tag
                         // Only 10 bytes of alias instead of 32
        data.extend_from_slice(&[0xaau8; 10]);

        assert!(matches!(
            decode_consumer_info(&data),
            Err(IdentityError::InvalidResponse { .. })
        ));
    }

    #[test]
    fn test_decode_consumer_info_ignores_trailing_bytes() {
        // Fields after credibility (e.g. stmt_store_slots) are silently ignored.
        let identifier_key = [0x04u8; 65];
        let mut data = build_consumer_info_bytes(&identifier_key, None, b"alice", 0x00, None, None);
        data.extend_from_slice(&[0xff, 0xff, 0xff]); // trailing bytes from next field

        // Should succeed — extra bytes are intentionally skipped.
        assert!(decode_consumer_info(&data).is_ok());
    }
}