host-encoding 0.3.12

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
//! Pure sp-statement-store encoding and decoding functions.
//!
//! No I/O. No network calls. WASM-safe.
//!
//! Implements the binary statement format used by Substrate's statement store pallet.
//! Callers are responsible for providing the current time (as Unix seconds) so that
//! this module remains free of `std::time` and is WASM-safe.

use blake2::digest::Mac;
use blake2::{digest::consts::U32, Blake2b, Digest};

type Blake2b256 = Blake2b<U32>;

/// Topic = 32-byte blake2b hash.
pub type Topic = [u8; 32];

/// Hash a string into a 32-byte Topic (blake2b-256).
pub fn string_to_topic(s: &str) -> Topic {
    let mut hasher = Blake2b256::new();
    hasher.update(s.as_bytes());
    let result = hasher.finalize();
    let mut topic = [0u8; 32];
    topic.copy_from_slice(&result);
    topic
}

// ---------------------------------------------------------------------------
// Statement binary encoding (sp-statement-store compatible)
//
// Substrate format: Compact<u32> field count, then tagged fields in order.
// Field tags: 0=Proof, 1=DecryptionKey, 2=Expiry, 3=Channel, 4-7=Topics, 8=Data
// Each field: u8 tag + SCALE-encoded payload.
// Proof::Sr25519 = tag 0, variant 0, sig[64], signer[32].
// Data = tag 8, Compact<u32> length, bytes.
// Signing payload: same fields without Compact prefix and without Proof field.
// ---------------------------------------------------------------------------

/// A decoded statement from the statement store.
#[derive(Debug, Clone, PartialEq)]
pub struct Statement {
    pub proof_pubkey: Option<[u8; 32]>,
    /// Raw sr25519 (or ed25519) signature over the signing payload.
    /// Present only for proof variants 0 (Sr25519) and 1 (Ed25519).
    pub proof_signature: Option<[u8; 64]>,
    pub decryption_key: Option<Topic>,
    pub channel: Option<Topic>,
    pub priority: u32,
    pub topics: Vec<Topic>,
    pub data: Vec<u8>,
}

/// Encode SCALE Compact<u32>.
pub fn encode_compact_u32(val: u32) -> Vec<u8> {
    if val < 0x40 {
        vec![(val as u8) << 2]
    } else if val < 0x4000 {
        let v = (val << 2) | 0x01;
        vec![v as u8, (v >> 8) as u8]
    } else if val < 0x4000_0000 {
        let v = (val << 2) | 0x02;
        v.to_le_bytes().to_vec()
    } else {
        let mut out = vec![0x03];
        out.extend_from_slice(&val.to_le_bytes());
        out
    }
}

/// Decode SCALE Compact<u32>, returns (value, bytes_consumed).
pub fn decode_compact_u32(data: &[u8]) -> Result<(u32, usize), String> {
    if data.is_empty() {
        return Err("compact: empty".into());
    }
    let mode = data[0] & 0x03;
    match mode {
        0 => Ok(((data[0] >> 2) as u32, 1)),
        1 => {
            if data.len() < 2 {
                return Err("compact: truncated 2-byte".into());
            }
            let v = u16::from_le_bytes([data[0], data[1]]) >> 2;
            Ok((v as u32, 2))
        }
        2 => {
            if data.len() < 4 {
                return Err("compact: truncated 4-byte".into());
            }
            let v = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) >> 2;
            Ok((v, 4))
        }
        3 => {
            if data.len() < 5 {
                return Err("compact: truncated big".into());
            }
            let v = u32::from_le_bytes([data[1], data[2], data[3], data[4]]);
            Ok((v, 5))
        }
        _ => unreachable!(),
    }
}

/// Build the signing payload for a statement.
///
/// Returns `(payload_bytes, num_fields)` where `payload_bytes` are the raw bytes
/// that must be signed (sr25519 context signing or equivalent), and `num_fields`
/// is needed by [`assemble_statement`] to write the SCALE header.
///
/// # Parameters
///
/// - `now_secs`: current Unix timestamp in seconds. Used to compute a 1-hour expiry.
/// - `topics`: at most 4 topics; returns `Err` if more are supplied.
pub fn build_signing_payload(
    now_secs: u64,
    decryption_key: Option<&Topic>,
    channel: Option<&Topic>,
    priority: u32,
    topics: &[Topic],
    data: &[u8],
) -> Result<(Vec<u8>, u32), String> {
    if topics.len() > 4 {
        return Err(format!("too many topics ({}, max 4)", topics.len()));
    }

    // Expiry: upper 32 bits = timestamp (seconds), lower 32 bits = priority.
    let expiry_ts = (now_secs + 3600) as u32;
    let expiry: u64 = ((expiry_ts as u64) << 32) | (priority as u64);

    // Count fields (proof + data fields).
    let mut num_fields: u32 = 1; // proof always present
    if decryption_key.is_some() {
        num_fields += 1;
    }
    num_fields += 1; // expiry always present
    if channel.is_some() {
        num_fields += 1;
    }
    num_fields += topics.len() as u32;
    if !data.is_empty() {
        num_fields += 1;
    }

    // Build signing payload (fields without Compact prefix and without Proof).
    let mut payload = Vec::new();
    if let Some(dk) = decryption_key {
        payload.push(1u8); // tag: DecryptionKey
        payload.extend_from_slice(dk);
    }
    payload.push(2u8); // tag: Expiry
    payload.extend_from_slice(&expiry.to_le_bytes());
    if let Some(ch) = channel {
        payload.push(3u8); // tag: Channel
        payload.extend_from_slice(ch);
    }
    for (i, t) in topics.iter().enumerate() {
        payload.push(4u8 + i as u8); // tag: Topic1..4
        payload.extend_from_slice(t);
    }
    if !data.is_empty() {
        payload.push(8u8); // tag: Data
        payload.extend_from_slice(&encode_compact_u32(data.len() as u32));
        payload.extend_from_slice(data);
    }

    Ok((payload, num_fields))
}

/// Assemble a complete encoded statement from a signing payload and sr25519 signature.
///
/// `signing_payload` and `num_fields` must come from [`build_signing_payload`].
pub fn assemble_statement(
    signing_payload: &[u8],
    num_fields: u32,
    sr25519_pubkey: &[u8; 32],
    signature: &[u8; 64],
) -> Vec<u8> {
    let mut out = Vec::new();

    // Compact<u32> field count prefix.
    out.extend_from_slice(&encode_compact_u32(num_fields));

    // Field 0: AuthenticityProof (Proof::Sr25519 = variant 0)
    out.push(0u8); // tag: AuthenticityProof
    out.push(0u8); // Proof variant 0 = Sr25519
    out.extend_from_slice(signature);
    out.extend_from_slice(sr25519_pubkey);

    // Remaining fields (same as signing_payload).
    out.extend_from_slice(signing_payload);

    out
}

/// Encode a statement into the sp-statement-store SCALE binary format.
///
/// Convenience wrapper that calls [`build_signing_payload`] then signs and
/// assembles in one step. For FFI or two-phase workflows where the signing
/// closure is unavailable, use the split API instead.
///
/// # Parameters
///
/// - `now_secs`: current Unix timestamp in seconds. Used to compute a 1-hour
///   expiry. Callers must supply this to keep the function pure and WASM-safe.
/// - `topics`: at most 4 topics; returns `Err` if more are supplied.
// All 8 parameters are required by the sp-statement-store wire format;
// grouping them into a struct would add churn for callers with no semantic gain.
#[allow(clippy::too_many_arguments)]
pub fn encode_statement(
    now_secs: u64,
    decryption_key: Option<&Topic>,
    channel: Option<&Topic>,
    priority: u32,
    topics: &[Topic],
    data: &[u8],
    sr25519_pubkey: &[u8; 32],
    sr25519_sign: &dyn Fn(&[u8]) -> [u8; 64],
) -> Result<Vec<u8>, String> {
    let (payload, num_fields) =
        build_signing_payload(now_secs, decryption_key, channel, priority, topics, data)?;
    let signature = sr25519_sign(&payload);
    Ok(assemble_statement(
        &payload,
        num_fields,
        sr25519_pubkey,
        &signature,
    ))
}

/// Extract the signing payload from a raw encoded statement.
///
/// The signing payload is the portion of the statement that was signed: all
/// fields except the Compact field-count prefix and the AuthenticityProof field
/// itself.  Callers use this to verify an embedded signature before trusting
/// any other field.
///
/// Returns `Err` if the statement is too short or malformed.
pub fn extract_signing_payload(encoded: &[u8]) -> Result<&[u8], String> {
    if encoded.is_empty() {
        return Err("empty statement".into());
    }
    // Skip the Compact<u32> field-count prefix.
    let (_, compact_len) = decode_compact_u32(encoded)?;

    // The proof field must be first: tag(1B) + variant(1B) + sig[64] + pk[32] = 98 B
    // for variants 0 (Sr25519) and 1 (Ed25519).  We only handle those here because
    // the chat protocol uses Sr25519 exclusively.
    let proof_start = compact_len;
    if encoded.len() < proof_start + 2 {
        return Err("truncated proof header".into());
    }
    let tag = encoded[proof_start];
    if tag != 0 {
        return Err(format!("expected AuthenticityProof tag (0), got {tag}"));
    }
    let variant = encoded[proof_start + 1];
    let proof_body_len = match variant {
        0 | 1 => 96, // sig[64] + pubkey[32]
        2 => 98,     // secp256k1: sig[65] + signer[33]
        3 => 72,     // on-chain: who[32] + block_hash[32] + u64
        _ => return Err(format!("unknown proof variant: {variant}")),
    };
    let payload_start = proof_start + 2 + proof_body_len;
    if encoded.len() < payload_start {
        return Err("truncated proof body".into());
    }
    Ok(&encoded[payload_start..])
}

/// Decode a statement from SCALE binary encoding (sp-statement-store format).
pub fn decode_statement(encoded: &[u8]) -> Result<Statement, String> {
    if encoded.is_empty() {
        return Err("empty statement".into());
    }

    let (num_fields, mut pos) = decode_compact_u32(encoded)?;

    let mut proof_pubkey = None;
    let mut proof_signature = None;
    let mut decryption_key = None;
    let mut channel = None;
    let mut priority = 0u32;
    let mut topics = Vec::new();
    let mut data = Vec::new();

    for _ in 0..num_fields {
        if pos >= encoded.len() {
            return Err("truncated field tag".into());
        }
        let tag = encoded[pos];
        pos += 1;

        match tag {
            0 => {
                // AuthenticityProof
                if pos >= encoded.len() {
                    return Err("truncated proof variant".into());
                }
                let variant = encoded[pos];
                pos += 1;
                match variant {
                    0 | 1 => {
                        // Sr25519 or Ed25519: sig[64] + signer[32]
                        if pos + 96 > encoded.len() {
                            return Err("truncated proof".into());
                        }
                        let mut sig = [0u8; 64];
                        sig.copy_from_slice(&encoded[pos..pos + 64]);
                        proof_signature = Some(sig);
                        let mut pk = [0u8; 32];
                        pk.copy_from_slice(&encoded[pos + 64..pos + 96]);
                        proof_pubkey = Some(pk);
                        pos += 96;
                    }
                    2 => {
                        // Secp256k1: sig[65] + signer[33]
                        if pos + 98 > encoded.len() {
                            return Err("truncated secp proof".into());
                        }
                        pos += 98;
                    }
                    3 => {
                        // OnChain: who[32] + block_hash[32] + u64
                        if pos + 72 > encoded.len() {
                            return Err("truncated onchain proof".into());
                        }
                        let mut pk = [0u8; 32];
                        pk.copy_from_slice(&encoded[pos..pos + 32]);
                        proof_pubkey = Some(pk);
                        pos += 72;
                    }
                    _ => return Err(format!("unknown proof variant: {variant}")),
                }
            }
            1 => {
                // DecryptionKey [32]
                if pos + 32 > encoded.len() {
                    return Err("truncated decryption_key".into());
                }
                let mut dk = [0u8; 32];
                dk.copy_from_slice(&encoded[pos..pos + 32]);
                decryption_key = Some(dk);
                pos += 32;
            }
            2 => {
                // Expiry u64 — upper 32 = timestamp, lower 32 = priority
                if pos + 8 > encoded.len() {
                    return Err("truncated expiry".into());
                }
                let expiry = u64::from_le_bytes([
                    encoded[pos],
                    encoded[pos + 1],
                    encoded[pos + 2],
                    encoded[pos + 3],
                    encoded[pos + 4],
                    encoded[pos + 5],
                    encoded[pos + 6],
                    encoded[pos + 7],
                ]);
                priority = expiry as u32; // lower 32 bits
                pos += 8;
            }
            3 => {
                // Channel [32]
                if pos + 32 > encoded.len() {
                    return Err("truncated channel".into());
                }
                let mut ch = [0u8; 32];
                ch.copy_from_slice(&encoded[pos..pos + 32]);
                channel = Some(ch);
                pos += 32;
            }
            4..=7 => {
                // Topic [32]
                if pos + 32 > encoded.len() {
                    return Err("truncated topic".into());
                }
                let mut t = [0u8; 32];
                t.copy_from_slice(&encoded[pos..pos + 32]);
                topics.push(t);
                pos += 32;
            }
            8 => {
                // Data: Compact<u32> length + bytes
                let (data_len, consumed) =
                    decode_compact_u32(&encoded[pos..]).map_err(|e| format!("data len: {e}"))?;
                pos += consumed;
                let data_len = data_len as usize;
                if pos + data_len > encoded.len() {
                    return Err("truncated data".into());
                }
                data = encoded[pos..pos + data_len].to_vec();
                pos += data_len;
            }
            _ => {
                // Unknown field — can't decode further without knowing size.
                return Err(format!("unknown field tag: {tag}"));
            }
        }
    }

    Ok(Statement {
        proof_pubkey,
        proof_signature,
        decryption_key,
        channel,
        priority,
        topics,
        data,
    })
}

/// Compute a blake2b-256 hash.
pub fn blake2b_256(data: &[u8]) -> [u8; 32] {
    let mut hasher = Blake2b256::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut out = [0u8; 32];
    out.copy_from_slice(&result);
    out
}

/// Keyed Blake2b-256 hash.
///
/// `key` must be 1..=64 bytes (Blake2b key length constraint).
/// Returns the 32-byte digest, or an error if the key length is invalid.
pub fn blake2b_256_keyed(key: &[u8], data: &[u8]) -> Result<[u8; 32], String> {
    use blake2::Blake2bMac;
    // Reject empty keys explicitly — some Blake2b implementations silently
    // degrade to unkeyed mode for key.len()==0, which would be a security bug.
    if key.is_empty() {
        return Err("blake2b key must not be empty".into());
    }
    let mut mac = <Blake2bMac<U32> as Mac>::new_from_slice(key)
        .map_err(|_| format!("blake2b key length must be 1..=64, got {}", key.len()))?;
    mac.update(data);
    let result = mac.finalize();
    Ok(result.into_bytes().into())
}

/// Derive a 32-byte topic from a context string, a raw AccountId, and optional extra bytes.
///
/// `topic = blake2b_256(SCALE_compact(context.len()) || context || account_id || extra)`
///
/// The context is length-prefixed with SCALE compact encoding to match the
/// deployed iOS protocol (`Data.encode(scaleEncoder:)` produces a SCALE
/// `Vec<u8>` prefix). AccountId is always exactly 32 bytes (enforced by
/// `&[u8; 32]`), so it acts as a fixed-width separator and needs no length
/// prefix.
pub fn derive_topic_from_account(context: &[u8], account_id: &[u8; 32], extra: &[u8]) -> [u8; 32] {
    let ctx_prefix = encode_compact_u32(context.len() as u32);
    let mut input = Vec::with_capacity(ctx_prefix.len() + context.len() + 32 + extra.len());
    input.extend_from_slice(&ctx_prefix);
    input.extend_from_slice(context);
    input.extend_from_slice(account_id);
    input.extend_from_slice(extra);
    blake2b_256(&input)
}

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

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

    #[test]
    fn test_string_to_topic_deterministic() {
        let t1 = string_to_topic("ss-dothost");
        let t2 = string_to_topic("ss-dothost");
        assert_eq!(t1, t2);
    }

    #[test]
    fn test_string_to_topic_distinct() {
        let t1 = string_to_topic("topic-a");
        let t2 = string_to_topic("topic-b");
        assert_ne!(t1, t2);
    }

    #[test]
    fn test_encode_compact_u32_single_byte() {
        assert_eq!(encode_compact_u32(0), vec![0x00]);
        assert_eq!(encode_compact_u32(1), vec![0x04]);
        assert_eq!(encode_compact_u32(63), vec![0xfc]);
    }

    #[test]
    fn test_decode_compact_u32_empty_returns_error() {
        assert!(decode_compact_u32(&[]).is_err());
    }

    #[test]
    fn test_encode_decode_compact_u32_roundtrip() {
        for val in [0u32, 1, 63, 64, 16383, 16384, 0x3FFF_FFFF] {
            let encoded = encode_compact_u32(val);
            let (decoded, _) = decode_compact_u32(&encoded).unwrap();
            assert_eq!(decoded, val, "roundtrip failed for {val}");
        }
    }

    #[test]
    fn test_build_signing_payload_rejects_too_many_topics() {
        let topic = [0u8; 32];
        let topics = vec![topic; 5];
        let result = build_signing_payload(1_700_000_000, None, None, 0, &topics, b"data");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too many topics"));
    }

    #[test]
    fn test_build_and_assemble_matches_encode_statement() {
        let dk = string_to_topic("room-id");
        let ch = string_to_topic("channel-1");
        let topic = string_to_topic("ss-dothost");
        let data = b"hello";
        let pubkey = [0xab; 32];
        let fake_sig = [0xcd; 64];

        let (payload, num_fields) =
            build_signing_payload(1_700_000_000, Some(&dk), Some(&ch), 42, &[topic], data).unwrap();

        let assembled = assemble_statement(&payload, num_fields, &pubkey, &fake_sig);
        let direct = encode_statement(
            1_700_000_000,
            Some(&dk),
            Some(&ch),
            42,
            &[topic],
            data,
            &pubkey,
            &|_| fake_sig,
        )
        .unwrap();

        assert_eq!(assembled, direct);
    }

    #[test]
    fn test_encode_statement_rejects_too_many_topics() {
        let topic = [0u8; 32];
        let topics = vec![topic; 5];
        let pubkey = [0u8; 32];
        let result = encode_statement(
            1_700_000_000,
            None,
            None,
            0,
            &topics,
            b"data",
            &pubkey,
            &|_| [0u8; 64],
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too many topics"));
    }

    #[test]
    fn test_encode_decode_statement_roundtrip() {
        let decryption_key = string_to_topic("room-id");
        let channel = string_to_topic("channel-1");
        let topic1 = string_to_topic("ss-dothost");
        let topic2 = string_to_topic("presence");
        let data = b"hello world";
        let pubkey = [0xab; 32];
        let fake_sig = [0xcd; 64];

        let encoded = encode_statement(
            1_700_000_000,
            Some(&decryption_key),
            Some(&channel),
            42,
            &[topic1, topic2],
            data,
            &pubkey,
            &|_| fake_sig,
        )
        .unwrap();

        let decoded = decode_statement(&encoded).unwrap();

        assert_eq!(decoded.proof_pubkey, Some(pubkey));
        assert_eq!(decoded.decryption_key, Some(decryption_key));
        assert_eq!(decoded.channel, Some(channel));
        assert_eq!(decoded.priority, 42);
        assert_eq!(decoded.topics.len(), 2);
        assert_eq!(decoded.topics[0], topic1);
        assert_eq!(decoded.topics[1], topic2);
        assert_eq!(decoded.data, data);
    }

    #[test]
    fn test_decode_statement_empty_returns_error() {
        assert!(decode_statement(&[]).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_returns_error() {
        assert!(decode_statement(&[0x04, 0x00]).is_err());
    }

    #[test]
    fn test_hex_encode_decode_roundtrip() {
        let original = vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
        let encoded = hex_encode(&original);
        assert_eq!(encoded, "0x0123456789abcdef");
        let decoded = hex_decode(&encoded).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_hex_decode_bare_string() {
        let decoded = hex_decode("deadbeef").unwrap();
        assert_eq!(decoded, vec![0xde, 0xad, 0xbe, 0xef]);
    }

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

    #[test]
    fn test_blake2b_256_deterministic() {
        let h1 = blake2b_256(b"test");
        let h2 = blake2b_256(b"test");
        assert_eq!(h1, h2);
        assert_ne!(h1, [0u8; 32]);
    }

    // -----------------------------------------------------------------------
    // encode_compact_u32 — two-byte and four-byte mode coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_encode_compact_u32_two_byte_mode() {
        // 64 <= val < 16384 → two-byte mode, lower 2 bits = 0b01
        let encoded = encode_compact_u32(64);
        assert_eq!(encoded.len(), 2);
        let (decoded, _) = decode_compact_u32(&encoded).unwrap();
        assert_eq!(decoded, 64);
    }

    #[test]
    fn test_encode_compact_u32_four_byte_mode() {
        // 16384 <= val < 0x40000000 → four-byte mode
        let encoded = encode_compact_u32(16384);
        assert_eq!(encoded.len(), 4);
        let (decoded, _) = decode_compact_u32(&encoded).unwrap();
        assert_eq!(decoded, 16384);
    }

    #[test]
    fn test_encode_compact_u32_big_mode() {
        // val >= 0x40000000 → big mode (5 bytes: 0x03 prefix + 4-byte value)
        let val = 0x4000_0000u32;
        let encoded = encode_compact_u32(val);
        assert_eq!(encoded.len(), 5);
        assert_eq!(encoded[0], 0x03); // big-mode prefix
        let (decoded, _) = decode_compact_u32(&encoded).unwrap();
        assert_eq!(decoded, val);
    }

    // -----------------------------------------------------------------------
    // decode_compact_u32 — truncation error paths
    // -----------------------------------------------------------------------

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

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

    #[test]
    fn test_decode_compact_u32_big_mode_truncated_returns_error() {
        // Mode bit = 0b11 (big mode) but fewer than 5 bytes
        assert!(decode_compact_u32(&[0x03, 0x00, 0x00, 0x00]).is_err());
    }

    // -----------------------------------------------------------------------
    // decode_statement — proof variant coverage
    // -----------------------------------------------------------------------

    /// Helper that builds a signed statement with one data field using a dummy key.
    fn minimal_statement_bytes(proof_variant: u8, proof_bytes: &[u8], data: &[u8]) -> Vec<u8> {
        // Two fields: proof + data (if non-empty), or just proof if data is empty.
        let num_fields: u32 = if data.is_empty() { 1 } else { 2 };
        let mut out = encode_compact_u32(num_fields);
        out.push(0u8); // tag: AuthenticityProof
        out.push(proof_variant);
        out.extend_from_slice(proof_bytes);
        if !data.is_empty() {
            out.push(8u8); // tag: Data
            out.extend_from_slice(&encode_compact_u32(data.len() as u32));
            out.extend_from_slice(data);
        }
        out
    }

    #[test]
    fn test_decode_statement_ed25519_proof_variant() {
        // Variant 1 = Ed25519: sig[64] + signer[32] = 96 bytes, same layout as Sr25519
        let sig = [0x11u8; 64];
        let pk = [0x22u8; 32];
        let mut proof_bytes = Vec::new();
        proof_bytes.extend_from_slice(&sig);
        proof_bytes.extend_from_slice(&pk);

        let encoded = minimal_statement_bytes(1, &proof_bytes, b"");
        let decoded = decode_statement(&encoded).unwrap();
        assert_eq!(decoded.proof_pubkey, Some(pk));
    }

    #[test]
    fn test_decode_statement_secp256k1_proof_variant() {
        // Variant 2 = Secp256k1: sig[65] + signer[33] = 98 bytes
        let proof_bytes = vec![0x33u8; 98];
        let encoded = minimal_statement_bytes(2, &proof_bytes, b"");
        let decoded = decode_statement(&encoded).unwrap();
        // Secp256k1 proof does not set proof_pubkey in the current implementation
        assert_eq!(decoded.proof_pubkey, None);
    }

    #[test]
    fn test_decode_statement_onchain_proof_variant() {
        // Variant 3 = OnChain: who[32] + block_hash[32] + u64[8] = 72 bytes
        let who = [0x44u8; 32];
        let block_hash = [0x55u8; 32];
        let block_num = [0x00u8; 8];
        let mut proof_bytes = Vec::new();
        proof_bytes.extend_from_slice(&who);
        proof_bytes.extend_from_slice(&block_hash);
        proof_bytes.extend_from_slice(&block_num);

        let encoded = minimal_statement_bytes(3, &proof_bytes, b"");
        let decoded = decode_statement(&encoded).unwrap();
        assert_eq!(decoded.proof_pubkey, Some(who));
    }

    #[test]
    fn test_decode_statement_unknown_proof_variant_returns_error() {
        // Variant 99 is not recognized
        let encoded = minimal_statement_bytes(99, &[0u8; 10], b"");
        assert!(decode_statement(&encoded).is_err());
    }

    #[test]
    fn test_decode_statement_unknown_field_tag_returns_error() {
        // Field count = 1, then use tag 9 (unknown after 8)
        let mut out = encode_compact_u32(1);
        out.push(9u8); // unknown tag
        assert!(decode_statement(&out).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_proof_returns_error() {
        // Proof variant 0 needs 96 bytes but only provide 10
        let encoded = minimal_statement_bytes(0, &[0u8; 10], b"");
        assert!(decode_statement(&encoded).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_secp_proof_returns_error() {
        // Variant 2 needs 98 bytes but only provide 10
        let encoded = minimal_statement_bytes(2, &[0u8; 10], b"");
        assert!(decode_statement(&encoded).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_onchain_proof_returns_error() {
        // Variant 3 needs 72 bytes but only provide 10
        let encoded = minimal_statement_bytes(3, &[0u8; 10], b"");
        assert!(decode_statement(&encoded).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_decryption_key_returns_error() {
        // 2 fields: proof (valid) + decryption_key (truncated)
        let mut out = encode_compact_u32(2);
        out.push(0u8); // AuthenticityProof
        out.push(0u8); // Sr25519
        out.extend_from_slice(&[0u8; 96]); // valid proof
        out.push(1u8); // DecryptionKey tag
        out.extend_from_slice(&[0u8; 10]); // only 10 bytes, needs 32
        assert!(decode_statement(&out).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_channel_returns_error() {
        let mut out = encode_compact_u32(2);
        out.push(0u8); // AuthenticityProof
        out.push(0u8); // Sr25519
        out.extend_from_slice(&[0u8; 96]);
        out.push(3u8); // Channel tag
        out.extend_from_slice(&[0u8; 10]); // only 10 bytes, needs 32
        assert!(decode_statement(&out).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_topic_returns_error() {
        let mut out = encode_compact_u32(2);
        out.push(0u8); // AuthenticityProof
        out.push(0u8); // Sr25519
        out.extend_from_slice(&[0u8; 96]);
        out.push(4u8); // Topic1 tag
        out.extend_from_slice(&[0u8; 10]); // only 10 bytes, needs 32
        assert!(decode_statement(&out).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_data_returns_error() {
        let mut out = encode_compact_u32(2);
        out.push(0u8); // AuthenticityProof
        out.push(0u8); // Sr25519
        out.extend_from_slice(&[0u8; 96]);
        out.push(8u8); // Data tag
                       // compact_len claims 50 bytes but we only provide 5
        out.extend_from_slice(&encode_compact_u32(50));
        out.extend_from_slice(&[0u8; 5]);
        assert!(decode_statement(&out).is_err());
    }

    #[test]
    fn test_decode_statement_truncated_expiry_returns_error() {
        let mut out = encode_compact_u32(2);
        out.push(0u8); // AuthenticityProof
        out.push(0u8); // Sr25519
        out.extend_from_slice(&[0u8; 96]);
        out.push(2u8); // Expiry tag
        out.extend_from_slice(&[0u8; 4]); // only 4 bytes, needs 8
        assert!(decode_statement(&out).is_err());
    }

    // -----------------------------------------------------------------------
    // encode_statement — minimal case (no optional fields, no data)
    // -----------------------------------------------------------------------

    #[test]
    fn test_encode_statement_minimal_no_optional_fields() {
        let pubkey = [0xabu8; 32];
        let fake_sig = [0xcdu8; 64];
        let encoded = encode_statement(
            1_700_000_000,
            None, // no decryption key
            None, // no channel
            0,
            &[], // no topics
            &[], // no data
            &pubkey,
            &|_| fake_sig,
        )
        .unwrap();

        // Should decode successfully and have no optional fields
        let decoded = decode_statement(&encoded).unwrap();
        assert_eq!(decoded.proof_pubkey, Some(pubkey));
        assert_eq!(decoded.decryption_key, None);
        assert_eq!(decoded.channel, None);
        assert_eq!(decoded.topics.len(), 0);
        assert_eq!(decoded.data, b"");
    }

    #[test]
    fn test_encode_statement_expiry_encodes_priority_in_lower_bits() {
        let pubkey = [0u8; 32];
        let fake_sig = [0u8; 64];
        let priority = 0x0000_cafe_u32;

        let encoded = encode_statement(
            1_700_000_000,
            None,
            None,
            priority,
            &[],
            &[],
            &pubkey,
            &|_| fake_sig,
        )
        .unwrap();

        let decoded = decode_statement(&encoded).unwrap();
        // The priority is stored in the lower 32 bits of the expiry u64
        assert_eq!(decoded.priority, priority);
    }

    #[test]
    fn test_encode_statement_max_topics_succeeds() {
        let topic = [0u8; 32];
        let topics = vec![topic; 4]; // exactly 4 — maximum allowed
        let pubkey = [0u8; 32];
        let result = encode_statement(1_700_000_000, None, None, 0, &topics, b"", &pubkey, &|_| {
            [0u8; 64]
        });
        assert!(result.is_ok());
        let decoded = decode_statement(&result.unwrap()).unwrap();
        assert_eq!(decoded.topics.len(), 4);
    }

    // -----------------------------------------------------------------------
    // blake2b_256_keyed
    // -----------------------------------------------------------------------

    #[test]
    fn test_blake2b_256_keyed_empty_key_returns_error() {
        let result = blake2b_256_keyed(b"", b"data");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("blake2b key must not be empty"));
    }

    #[test]
    fn test_blake2b_256_keyed_64_byte_key_succeeds() {
        let key = [0xabu8; 64];
        let result = blake2b_256_keyed(&key, b"data");
        assert!(result.is_ok());
        // Non-zero digest confirms something was computed.
        assert_ne!(result.unwrap(), [0u8; 32]);
    }

    #[test]
    fn test_blake2b_256_keyed_65_byte_key_returns_error() {
        let key = [0xabu8; 65];
        let result = blake2b_256_keyed(&key, b"data");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("blake2b key length must be 1..=64, got 65"));
    }

    /// Pinned test vector: blake2b_256_keyed(key=[0x01;32], data=b"polkadot").
    ///
    /// The expected value was computed by running `blake2b_256_keyed` and
    /// recording the output; it detects any future regression in the digest.
    #[test]
    fn test_blake2b_256_keyed_pinned_vector() {
        let key = [0x01u8; 32];
        let data = b"polkadot";
        let digest = blake2b_256_keyed(&key, data).unwrap();
        // Computed once and pinned for regression detection.
        let expected: [u8; 32] = [
            0xdc, 0xbc, 0x39, 0xc6, 0x21, 0xe8, 0xc2, 0x0c, 0x84, 0xc1, 0x81, 0x6b, 0x18, 0x3d,
            0x7c, 0xae, 0x76, 0x11, 0x7b, 0x36, 0x16, 0x0c, 0xd3, 0x3f, 0xda, 0x54, 0x8f, 0x91,
            0x14, 0x49, 0x98, 0x05,
        ];
        assert_eq!(
            digest, expected,
            "keyed blake2b digest must match pinned vector"
        );
    }

    // -----------------------------------------------------------------------
    // derive_topic_from_account
    // -----------------------------------------------------------------------

    /// Verifies that redistributing bytes between `context` and `extra`
    /// changes the output — the length prefix prevents concatenation collisions.
    #[test]
    fn test_derive_topic_from_account_domain_separation() {
        let account_id = [0x42u8; 32];
        // "ab" as context + "c" as extra  vs  "a" as context + "bc" as extra.
        // Without the length prefix these would produce identical inputs.
        let t1 = derive_topic_from_account(b"ab", &account_id, b"c");
        let t2 = derive_topic_from_account(b"a", &account_id, b"bc");
        assert_ne!(
            t1, t2,
            "length-prefixed context must prevent domain collision"
        );
    }

    #[test]
    fn test_derive_topic_from_account_deterministic() {
        let account_id = [0x01u8; 32];
        let t1 = derive_topic_from_account(b"ctx", &account_id, b"extra");
        let t2 = derive_topic_from_account(b"ctx", &account_id, b"extra");
        assert_eq!(t1, t2);
        assert_ne!(t1, [0u8; 32]);
    }

    #[test]
    fn test_derive_topic_from_account_empty_extra() {
        let account_id = [0x77u8; 32];
        let result = derive_topic_from_account(b"context", &account_id, b"");
        assert_ne!(result, [0u8; 32]);
    }

    /// Verify that derive_topic_from_account uses SCALE compact encoding for the
    /// context length prefix, matching the deployed iOS protocol.
    ///
    /// For context = "chat-request" (12 bytes), SCALE compact encodes 12 as a
    /// single byte: 12 * 4 = 48 = 0x30.
    #[test]
    fn test_derive_topic_from_account_uses_scale_compact_prefix() {
        let context = b"chat-request";
        let account_id = [0x01u8; 32];
        let extra = 0u64.to_le_bytes();

        // Build the expected preimage manually with SCALE compact prefix.
        let mut expected_input = Vec::new();
        expected_input.push(0x30); // SCALE compact(12) = single byte
        expected_input.extend_from_slice(context);
        expected_input.extend_from_slice(&account_id);
        expected_input.extend_from_slice(&extra);

        let expected = blake2b_256(&expected_input);
        let actual = derive_topic_from_account(context, &account_id, &extra);
        assert_eq!(
            actual, expected,
            "derive_topic_from_account must use SCALE compact prefix (iOS compatibility)"
        );
    }

    #[test]
    fn test_derive_topic_from_account_empty_context() {
        let account_id = [0x01u8; 32];
        let mut expected_input = Vec::new();
        expected_input.push(0x00); // SCALE compact(0)
        expected_input.extend_from_slice(&account_id);
        let expected = blake2b_256(&expected_input);
        let actual = derive_topic_from_account(b"", &account_id, b"");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_derive_topic_from_account_two_byte_compact_context() {
        // Length 64 triggers 2-byte SCALE compact: (64<<2)|1 = 257 = [0x01, 0x01]
        let context = vec![b'x'; 64];
        let account_id = [0x02u8; 32];
        let mut expected_input = Vec::new();
        expected_input.extend_from_slice(&encode_compact_u32(64));
        expected_input.extend_from_slice(&context);
        expected_input.extend_from_slice(&account_id);
        let expected = blake2b_256(&expected_input);
        let actual = derive_topic_from_account(&context, &account_id, b"");
        assert_eq!(actual, expected);
    }
}