libsession 0.1.3

Session messenger core library - cryptography, config management, networking
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
//! Session protocol constants, Pro proof types, and protocol URL strings.
//!
//! Ported from `libsession-util/include/session/session_protocol.h`,
//! `libsession-util/include/session/session_protocol.hpp`, and
//! `libsession-util/src/session_protocol.cpp`.

use thiserror::Error;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Maximum number of unicode codepoints that a standard message can use. If the
/// message exceeds this then the message must activate the higher character limit
/// feature provided by Session Pro which allows messages up to 10k characters.
pub const PRO_STANDARD_CHARACTER_LIMIT: usize = 2000;

/// Maximum number of unicode codepoints that a Session Pro entitled user can
/// send in a message.
pub const PRO_HIGHER_CHARACTER_LIMIT: usize = 10000;

/// Amount of conversations that a user without Session Pro can pin.
pub const PRO_STANDARD_PINNED_CONVERSATION_LIMIT: usize = 5;

/// Amount of bytes that a community or 1o1 message `Content` must be padded by
/// before wrapping in an envelope.
pub const COMMUNITY_OR_1O1_MSG_PADDING: usize = 160;

/// Padding terminating byte used when padding messages.
pub const PADDING_TERMINATING_BYTE: u8 = 0x80;

// ---------------------------------------------------------------------------
// Blake2b personalisation strings (must be exactly 16 bytes)
// ---------------------------------------------------------------------------

/// BLAKE2b personalisation for generating Session Pro proofs.
pub const GENERATE_PROOF_HASH_PERSONALISATION: &str = "ProGenerateProof";
/// BLAKE2b personalisation for building Session Pro proofs.
pub const BUILD_PROOF_HASH_PERSONALISATION: &str = "ProProof________";
/// BLAKE2b personalisation for adding Session Pro payment records.
pub const ADD_PRO_PAYMENT_HASH_PERSONALISATION: &str = "ProAddPayment___";
/// BLAKE2b personalisation for requesting Session Pro payment refunds.
pub const SET_PAYMENT_REFUND_REQUESTED_HASH_PERSONALISATION: &str = "ProSetRefundReq_";
/// BLAKE2b personalisation for fetching Session Pro details.
pub const GET_PRO_DETAILS_HASH_PERSONALISATION: &str = "ProGetProDetReq_";

/// Internal Blake2b personalisation for the Session Pro backend proof hashing.
pub const PRO_BACKEND_BLAKE2B_PERSONALISATION: &str = "SeshProBackend__";

// ---------------------------------------------------------------------------
// Protocol URL strings
// ---------------------------------------------------------------------------

/// Bundle of hard-coded strings that an implementing application may use.
pub struct ProtocolStrings {
    pub build_variant_apk: &'static str,
    pub build_variant_fdroid: &'static str,
    pub build_variant_huawei: &'static str,
    pub build_variant_ipa: &'static str,
    pub url_donations: &'static str,
    pub url_donations_app: &'static str,
    pub url_download: &'static str,
    pub url_faq: &'static str,
    pub url_feedback: &'static str,
    pub url_network: &'static str,
    pub url_privacy_policy: &'static str,
    pub url_pro_access_not_found: &'static str,
    pub url_pro_faq: &'static str,
    pub url_pro_page: &'static str,
    pub url_pro_privacy_policy: &'static str,
    pub url_pro_roadmap: &'static str,
    pub url_pro_support: &'static str,
    pub url_pro_terms_of_service: &'static str,
    pub url_pro_upgrade: &'static str,
    pub url_staking: &'static str,
    pub url_support: &'static str,
    pub url_survey: &'static str,
    pub url_terms_of_service: &'static str,
    pub url_token: &'static str,
    pub url_translate: &'static str,
}

/// Global protocol strings matching the C++ `SESSION_PROTOCOL_STRINGS` constant.
pub static PROTOCOL_STRINGS: ProtocolStrings = ProtocolStrings {
    build_variant_apk: "APK",
    build_variant_fdroid: "F-Droid Store",
    build_variant_huawei: "Huawei App Gallery",
    build_variant_ipa: "IPA",
    url_donations: "https://getsession.org/donate",
    url_donations_app: "https://getsession.org/donate#app",
    url_download: "https://getsession.org/download",
    url_faq: "https://getsession.org/faq",
    url_feedback: "https://getsession.org/feedback",
    url_network: "https://docs.getsession.org/session-network",
    url_privacy_policy: "https://getsession.org/privacy-policy",
    url_pro_access_not_found:
        "https://sessionapp.zendesk.com/hc/sections/4416517450649-Support",
    url_pro_faq: "https://getsession.org/pro#faq",
    url_pro_page: "https://getsession.org/pro",
    url_pro_privacy_policy: "https://getsession.org/pro-privacy",
    url_pro_roadmap: "https://getsession.org/pro#roadmap",
    url_pro_support: "https://getsession.org/pro-support",
    url_pro_terms_of_service: "https://getsession.org/pro-terms",
    url_pro_upgrade: "https://getsession.org/pro#upgrade",
    url_staking: "https://docs.getsession.org/session-network/staking",
    url_support: "https://getsession.org/support",
    url_survey: "https://getsession.org/survey",
    url_terms_of_service: "https://getsession.org/terms-of-service",
    url_token: "https://token.getsession.org",
    url_translate: "https://getsession.org/translate",
};

// ---------------------------------------------------------------------------
// ProStatus
// ---------------------------------------------------------------------------

/// Status result from evaluating a Session Pro proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ProStatus {
    /// Pro proof signature was not signed by the Pro backend key.
    InvalidProBackendSig = 1,
    /// Pro signature in the envelope was not signed by the rotating key.
    InvalidUserSig = 2,
    /// Proof is verified and has not expired.
    Valid = 3,
    /// Proof is verified but has expired.
    Expired = 4,
}

// ---------------------------------------------------------------------------
// ProProofVersion
// ---------------------------------------------------------------------------

/// Version tag for Pro proofs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ProProofVersion {
    V0 = 0,
}

// ---------------------------------------------------------------------------
// ProProof
// ---------------------------------------------------------------------------

/// A Session Pro proof containing the fields needed to verify that a user is
/// entitled to Session Pro features.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProProof {
    /// Version of the proof set by the Session Pro Backend.
    pub version: u8,

    /// Hash of the generation index set by the Session Pro Backend.
    pub gen_index_hash: [u8; 32],

    /// The public key that the Session client registers their Session Pro
    /// entitlement under. Session clients must sign messages with this key
    /// alongside the sending of this proof for the network to authenticate
    /// their usage of the proof.
    pub rotating_pubkey: [u8; 32],

    /// Unix epoch timestamp (milliseconds) to which this proof's entitlement
    /// to Session Pro features is valid.
    pub expiry_unix_ts_ms: u64,

    /// Signature over the contents of the proof, signed by the Session Pro
    /// Backend key.
    pub sig: [u8; 64],
}

/// Errors that can occur during proof operations.
#[derive(Debug, Error)]
pub enum ProProofError {
    #[error("Invalid verify_pubkey: must be 32 byte Ed25519 public key (was: {0})")]
    InvalidPubkeySize(usize),

    #[error("Invalid signature: must be 64 bytes (was: {0})")]
    InvalidSignatureSize(usize),

    #[error("Crypto error: {0}")]
    Crypto(#[from] crate::crypto::types::CryptoError),
}

impl ProProof {
    /// Create a 32-byte Blake2b hash from the proof. This hash is the payload
    /// that is signed in the proof.
    ///
    /// Matches the C++ `ProProof::hash()` and the backend hashing at:
    /// <https://github.com/Doy-lee/session-pro-backend/blob/9417e00adbff3bf608b7ae831f87045bdab06232/backend.py#L545-L558>
    pub fn hash(&self) -> [u8; 32] {
        proof_hash_internal(
            self.version,
            &self.gen_index_hash,
            &self.rotating_pubkey,
            self.expiry_unix_ts_ms,
        )
    }

    /// Verify that the proof's contents was not tampered with by hashing the
    /// proof and checking that the hash was signed by the secret key of the
    /// given Ed25519 public key.
    ///
    /// For Session Pro, we expect proofs to be signed by the Session Pro
    /// Backend public key.
    pub fn verify_signature(&self, verify_pubkey: &[u8]) -> Result<bool, ProProofError> {
        if verify_pubkey.len() != 32 {
            return Err(ProProofError::InvalidPubkeySize(verify_pubkey.len()));
        }
        let hash_to_sign = self.hash();
        let result = crate::crypto::ed25519::verify(&self.sig, verify_pubkey, &hash_to_sign)?;
        Ok(result)
    }

    /// Check if the `rotating_pubkey` in the proof was the signatory of the
    /// given message and signature.
    pub fn verify_message(&self, sig: &[u8], msg: &[u8]) -> Result<bool, ProProofError> {
        if sig.len() != 64 {
            return Err(ProProofError::InvalidSignatureSize(sig.len()));
        }
        let result = crate::crypto::ed25519::verify(sig, &self.rotating_pubkey, msg)?;
        Ok(result)
    }

    /// Check if the Pro proof is currently entitled to Pro given the
    /// `unix_ts_ms` with respect to the proof's `expiry_unix_ts_ms`.
    pub fn is_active(&self, unix_ts_ms: u64) -> bool {
        unix_ts_ms <= self.expiry_unix_ts_ms
    }

    /// Evaluate the status of the pro proof by checking it is signed by the
    /// `verify_pubkey`, it has not expired via `unix_ts_ms`, and optionally
    /// verify that the `signed_msg` was signed by the `rotating_pubkey`.
    ///
    /// Returns an error only if the key/signature sizes are wrong. Otherwise
    /// returns a [`ProStatus`] indicating validity.
    pub fn status(
        &self,
        verify_pubkey: &[u8],
        unix_ts_ms: u64,
        signed_msg: Option<ProSignedMessage<'_>>,
    ) -> Result<ProStatus, ProProofError> {
        // Verify the proof is signed by the Session Pro Backend key
        if !self.verify_signature(verify_pubkey)? {
            return Ok(ProStatus::InvalidProBackendSig);
        }

        // Check if the message was signed by the rotating key
        if let Some(sm) = signed_msg
            && !self.verify_message(sm.sig, sm.msg)? {
                return Ok(ProStatus::InvalidUserSig);
            }

        // Check if the proof has expired
        if !self.is_active(unix_ts_ms) {
            return Ok(ProStatus::Expired);
        }

        Ok(ProStatus::Valid)
    }
}

/// A signed message to verify against the rotating key in a proof.
#[derive(Debug, Clone, Copy)]
pub struct ProSignedMessage<'a> {
    pub sig: &'a [u8],
    pub msg: &'a [u8],
}

// ---------------------------------------------------------------------------
// ProProfileFeatures (bitset)
// ---------------------------------------------------------------------------

/// Profile feature flags. Each variant represents a bit position in the bitset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u64)]
pub enum ProProfileFeature {
    ProBadge = 0,
    AnimatedAvatar = 1,
}

/// Number of defined profile features.
pub const PRO_PROFILE_FEATURES_COUNT: usize = 2;

/// A bitset for Session Pro profile features.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProProfileBitset {
    pub data: u64,
}

impl ProProfileBitset {
    /// Set a feature flag.
    pub fn set(&mut self, feature: ProProfileFeature) {
        self.data |= 1u64 << (feature as u64);
    }

    /// Unset a feature flag.
    pub fn unset(&mut self, feature: ProProfileFeature) {
        self.data &= !(1u64 << (feature as u64));
    }

    /// Check if a feature flag is set.
    pub fn is_set(&self, feature: ProProfileFeature) -> bool {
        (self.data & (1u64 << (feature as u64))) != 0
    }
}

// ---------------------------------------------------------------------------
// ProMessageFeatures (bitset)
// ---------------------------------------------------------------------------

/// Message feature flags. Each variant represents a bit position in the bitset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u64)]
pub enum ProMessageFeature {
    /// Message uses the 10k character limit.
    CharacterLimit10K = 0,
}

/// A bitset for Session Pro message features.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProMessageBitset {
    pub data: u64,
}

impl ProMessageBitset {
    /// Set a feature flag.
    pub fn set(&mut self, feature: ProMessageFeature) {
        self.data |= 1u64 << (feature as u64);
    }

    /// Unset a feature flag.
    pub fn unset(&mut self, feature: ProMessageFeature) {
        self.data &= !(1u64 << (feature as u64));
    }

    /// Check if a feature flag is set.
    pub fn is_set(&self, feature: ProMessageFeature) -> bool {
        (self.data & (1u64 << (feature as u64))) != 0
    }
}

// ---------------------------------------------------------------------------
// ProFeaturesForMsg
// ---------------------------------------------------------------------------

/// Status from evaluating a message for Pro features.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ProFeaturesForMsgStatus {
    Success = 0,
    /// Message byte stream could not be decoded into valid UTF-8.
    UtfDecodingError = 1,
    /// Decoded string exceeded the maximum character limit allowed for Session Pro.
    ExceedsCharacterLimit = 2,
}

/// Result of evaluating a message for Session Pro features.
#[derive(Debug, Clone)]
pub struct ProFeaturesForMsg {
    pub status: ProFeaturesForMsgStatus,
    pub error: Option<String>,
    pub bitset: ProMessageBitset,
    pub codepoint_count: usize,
}

/// Determine the Pro features used in a given UTF-8 conversation message.
///
/// Counts the number of unicode codepoints and determines if the message
/// requires the higher character limit available in Session Pro.
pub fn pro_features_for_utf8(text: &str) -> ProFeaturesForMsg {
    let codepoint_count = text.chars().count();

    if codepoint_count > PRO_HIGHER_CHARACTER_LIMIT {
        return ProFeaturesForMsg {
            status: ProFeaturesForMsgStatus::ExceedsCharacterLimit,
            error: Some("Message exceeds the maximum character limit allowed".into()),
            bitset: ProMessageBitset::default(),
            codepoint_count,
        };
    }

    let mut bitset = ProMessageBitset::default();
    if codepoint_count > PRO_STANDARD_CHARACTER_LIMIT {
        bitset.set(ProMessageFeature::CharacterLimit10K);
    }

    ProFeaturesForMsg {
        status: ProFeaturesForMsgStatus::Success,
        error: None,
        bitset,
        codepoint_count,
    }
}

// ---------------------------------------------------------------------------
// DestinationType
// ---------------------------------------------------------------------------

/// The type of destination for an encoded message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DestinationType {
    SyncOr1o1 = 0,
    /// Both legacy and non-legacy groups. A non-legacy group is detected by
    /// the (0x03) prefix byte on the given `dest_group_pubkey`.
    Group = 1,
    CommunityInbox = 2,
    Community = 3,
}

// ---------------------------------------------------------------------------
// Envelope flags
// ---------------------------------------------------------------------------

/// Bitflags indicating which optional fields in an envelope have been populated.
pub mod envelope_flags {
    /// Envelope includes the source Session ID.
    pub const SOURCE: u32 = 1 << 0;
    /// Envelope includes the source device identifier.
    pub const SOURCE_DEVICE: u32 = 1 << 1;
    /// Envelope includes the server-assigned timestamp.
    pub const SERVER_TIMESTAMP: u32 = 1 << 2;
    /// Envelope includes a Session Pro signature.
    pub const PRO_SIG: u32 = 1 << 3;
    /// Envelope includes the client-assigned timestamp.
    pub const TIMESTAMP: u32 = 1 << 4;
}

// ---------------------------------------------------------------------------
// Message padding
// ---------------------------------------------------------------------------

/// Pad a message to the required alignment for 1o1/community messages (160 bytes)
/// including space for the padding-terminating byte.
pub fn pad_message(payload: &[u8]) -> Vec<u8> {
    let padded_content_size = payload.len() + 1; // +1 for the padding terminating byte
    let bytes_for_padding =
        COMMUNITY_OR_1O1_MSG_PADDING - (padded_content_size % COMMUNITY_OR_1O1_MSG_PADDING);
    let total_size = padded_content_size + bytes_for_padding;
    debug_assert!(total_size.is_multiple_of(COMMUNITY_OR_1O1_MSG_PADDING));

    let mut result = vec![0u8; total_size];
    result[..payload.len()].copy_from_slice(payload);
    result[payload.len()] = PADDING_TERMINATING_BYTE;
    result
}

/// Strip padding from a padded message, returning the unpadded content.
pub fn unpad_message(payload: &[u8]) -> &[u8] {
    let mut size = payload.len();
    while size > 0 {
        let ch = payload[size - 1];
        if ch != 0 && ch != PADDING_TERMINATING_BYTE {
            // Non-zero/non-padding byte: message is not padded (or padding already stripped)
            return payload;
        }
        size -= 1;
        if ch == PADDING_TERMINATING_BYTE {
            break;
        }
    }
    &payload[..size]
}

// ---------------------------------------------------------------------------
// Internal: proof hash
// ---------------------------------------------------------------------------

/// Compute the 32-byte Blake2b hash of a proof's fields using the
/// `ProProof________` personalisation. This matches the C++ `proof_hash_internal`.
fn proof_hash_internal(
    version: u8,
    gen_index_hash: &[u8; 32],
    rotating_pubkey: &[u8; 32],
    expiry_unix_ts_ms: u64,
) -> [u8; 32] {
    use blake2b_simd::Params;

    let mut params = Params::new();
    params.hash_length(32);

    // The personalisation must be exactly 16 bytes for Blake2b
    debug_assert!(BUILD_PROOF_HASH_PERSONALISATION.len() == 16);
    let mut personal = [0u8; 16];
    personal.copy_from_slice(BUILD_PROOF_HASH_PERSONALISATION.as_bytes());
    params.personal(&personal);

    let mut state = params.to_state();
    state.update(&[version]);
    state.update(gen_index_hash);
    state.update(rotating_pubkey);
    state.update(&expiry_unix_ts_ms.to_le_bytes());

    let hash = state.finalize();
    let mut result = [0u8; 32];
    result.copy_from_slice(hash.as_bytes());
    result
}

/// Initialise a Blake2b-32 hashing context with the given personalisation string.
/// The personalisation must be exactly 16 bytes.
pub fn make_blake2b32_hasher(personalisation: &str) -> blake2b_simd::State {
    debug_assert!(personalisation.len() == 16);
    let mut personal = [0u8; 16];
    let len = personalisation.len().min(16);
    personal[..len].copy_from_slice(&personalisation.as_bytes()[..len]);

    let mut params = blake2b_simd::Params::new();
    params.hash_length(32);
    params.personal(&personal);
    params.to_state()
}

// ---------------------------------------------------------------------------
// Group message size limits (from protocol constants used in groups)
// ---------------------------------------------------------------------------

/// Maximum size of a group message content before encryption.
/// Groups v2 messages are encrypted with 256-byte padding alignment.
pub const GROUP_MESSAGE_PADDING: usize = 256;

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

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

    #[test]
    fn test_constants() {
        assert_eq!(PRO_STANDARD_CHARACTER_LIMIT, 2000);
        assert_eq!(PRO_HIGHER_CHARACTER_LIMIT, 10000);
        assert_eq!(PRO_STANDARD_PINNED_CONVERSATION_LIMIT, 5);
        assert_eq!(COMMUNITY_OR_1O1_MSG_PADDING, 160);
    }

    #[test]
    fn test_personalisation_lengths() {
        assert_eq!(GENERATE_PROOF_HASH_PERSONALISATION.len(), 16);
        assert_eq!(BUILD_PROOF_HASH_PERSONALISATION.len(), 16);
        assert_eq!(ADD_PRO_PAYMENT_HASH_PERSONALISATION.len(), 16);
        assert_eq!(SET_PAYMENT_REFUND_REQUESTED_HASH_PERSONALISATION.len(), 16);
        assert_eq!(GET_PRO_DETAILS_HASH_PERSONALISATION.len(), 16);
    }

    #[test]
    fn test_protocol_strings() {
        assert_eq!(PROTOCOL_STRINGS.build_variant_apk, "APK");
        assert_eq!(PROTOCOL_STRINGS.build_variant_fdroid, "F-Droid Store");
        assert_eq!(PROTOCOL_STRINGS.build_variant_huawei, "Huawei App Gallery");
        assert_eq!(PROTOCOL_STRINGS.build_variant_ipa, "IPA");
        assert_eq!(
            PROTOCOL_STRINGS.url_donations,
            "https://getsession.org/donate"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_donations_app,
            "https://getsession.org/donate#app"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_download,
            "https://getsession.org/download"
        );
        assert_eq!(PROTOCOL_STRINGS.url_faq, "https://getsession.org/faq");
        assert_eq!(
            PROTOCOL_STRINGS.url_feedback,
            "https://getsession.org/feedback"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_network,
            "https://docs.getsession.org/session-network"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_privacy_policy,
            "https://getsession.org/privacy-policy"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_access_not_found,
            "https://sessionapp.zendesk.com/hc/sections/4416517450649-Support"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_faq,
            "https://getsession.org/pro#faq"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_page,
            "https://getsession.org/pro"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_privacy_policy,
            "https://getsession.org/pro-privacy"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_roadmap,
            "https://getsession.org/pro#roadmap"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_support,
            "https://getsession.org/pro-support"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_terms_of_service,
            "https://getsession.org/pro-terms"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_pro_upgrade,
            "https://getsession.org/pro#upgrade"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_staking,
            "https://docs.getsession.org/session-network/staking"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_support,
            "https://getsession.org/support"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_survey,
            "https://getsession.org/survey"
        );
        assert_eq!(
            PROTOCOL_STRINGS.url_terms_of_service,
            "https://getsession.org/terms-of-service"
        );
        assert_eq!(PROTOCOL_STRINGS.url_token, "https://token.getsession.org");
        assert_eq!(
            PROTOCOL_STRINGS.url_translate,
            "https://getsession.org/translate"
        );
    }

    #[test]
    fn test_pro_status_values() {
        assert_eq!(ProStatus::InvalidProBackendSig as u8, 1);
        assert_eq!(ProStatus::InvalidUserSig as u8, 2);
        assert_eq!(ProStatus::Valid as u8, 3);
        assert_eq!(ProStatus::Expired as u8, 4);
    }

    #[test]
    fn test_pro_profile_bitset() {
        let mut bitset = ProProfileBitset::default();
        assert!(!bitset.is_set(ProProfileFeature::ProBadge));
        assert!(!bitset.is_set(ProProfileFeature::AnimatedAvatar));

        bitset.set(ProProfileFeature::ProBadge);
        assert!(bitset.is_set(ProProfileFeature::ProBadge));
        assert!(!bitset.is_set(ProProfileFeature::AnimatedAvatar));
        assert_eq!(bitset.data, 1);

        bitset.set(ProProfileFeature::AnimatedAvatar);
        assert!(bitset.is_set(ProProfileFeature::ProBadge));
        assert!(bitset.is_set(ProProfileFeature::AnimatedAvatar));
        assert_eq!(bitset.data, 3);

        bitset.unset(ProProfileFeature::ProBadge);
        assert!(!bitset.is_set(ProProfileFeature::ProBadge));
        assert!(bitset.is_set(ProProfileFeature::AnimatedAvatar));
        assert_eq!(bitset.data, 2);
    }

    #[test]
    fn test_pro_message_bitset() {
        let mut bitset = ProMessageBitset::default();
        assert!(!bitset.is_set(ProMessageFeature::CharacterLimit10K));

        bitset.set(ProMessageFeature::CharacterLimit10K);
        assert!(bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(bitset.data, 1);

        bitset.unset(ProMessageFeature::CharacterLimit10K);
        assert!(!bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(bitset.data, 0);
    }

    #[test]
    fn test_pro_features_for_utf8_short_message() {
        let msg = "Hello, world!";
        let result = pro_features_for_utf8(msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::Success);
        assert!(result.error.is_none());
        assert!(!result.bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(result.codepoint_count, 13);
    }

    #[test]
    fn test_pro_features_for_utf8_at_standard_limit() {
        let msg: String = "a".repeat(PRO_STANDARD_CHARACTER_LIMIT);
        let result = pro_features_for_utf8(&msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::Success);
        assert!(!result.bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(result.codepoint_count, PRO_STANDARD_CHARACTER_LIMIT);
    }

    #[test]
    fn test_pro_features_for_utf8_above_standard_limit() {
        let msg: String = "a".repeat(PRO_STANDARD_CHARACTER_LIMIT + 1);
        let result = pro_features_for_utf8(&msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::Success);
        assert!(result.bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(result.codepoint_count, PRO_STANDARD_CHARACTER_LIMIT + 1);
    }

    #[test]
    fn test_pro_features_for_utf8_at_pro_limit() {
        let msg: String = "a".repeat(PRO_HIGHER_CHARACTER_LIMIT);
        let result = pro_features_for_utf8(&msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::Success);
        assert!(result.bitset.is_set(ProMessageFeature::CharacterLimit10K));
        assert_eq!(result.codepoint_count, PRO_HIGHER_CHARACTER_LIMIT);
    }

    #[test]
    fn test_pro_features_for_utf8_above_pro_limit() {
        let msg: String = "a".repeat(PRO_HIGHER_CHARACTER_LIMIT + 1);
        let result = pro_features_for_utf8(&msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::ExceedsCharacterLimit);
        assert!(result.error.is_some());
    }

    #[test]
    fn test_pro_features_for_utf8_multibyte() {
        // Each emoji is 1 codepoint but multiple bytes
        let msg = "\u{1F600}\u{1F601}\u{1F602}"; // 3 emoji
        let result = pro_features_for_utf8(msg);
        assert_eq!(result.status, ProFeaturesForMsgStatus::Success);
        assert_eq!(result.codepoint_count, 3);
    }

    #[test]
    fn test_pad_message_alignment() {
        let payload = b"hello";
        let padded = pad_message(payload);
        assert_eq!(padded.len() % COMMUNITY_OR_1O1_MSG_PADDING, 0);
        assert!(padded.len() >= payload.len() + 1);
        assert_eq!(&padded[..payload.len()], payload);
        assert_eq!(padded[payload.len()], PADDING_TERMINATING_BYTE);
        // Rest should be zero
        for &b in &padded[payload.len() + 1..] {
            assert_eq!(b, 0);
        }
    }

    #[test]
    fn test_pad_message_exact_boundary() {
        // Payload that is exactly PADDING-1 bytes (content + padding byte = PADDING, but the
        // C++ algorithm always adds at least PADDING additional zero bytes after the terminator
        // when the content+terminator falls exactly on a boundary)
        let payload = vec![0xAA; COMMUNITY_OR_1O1_MSG_PADDING - 1];
        let padded = pad_message(&payload);
        assert_eq!(padded.len() % COMMUNITY_OR_1O1_MSG_PADDING, 0);
        assert_eq!(padded.len(), COMMUNITY_OR_1O1_MSG_PADDING * 2);
    }

    #[test]
    fn test_unpad_message() {
        let original = b"hello world";
        let padded = pad_message(original);
        let unpadded = unpad_message(&padded);
        assert_eq!(unpadded, original);
    }

    #[test]
    fn test_unpad_message_empty() {
        let unpadded = unpad_message(&[]);
        assert_eq!(unpadded, &[] as &[u8]);
    }

    #[test]
    fn test_proof_hash_deterministic() {
        let proof = ProProof {
            version: 0,
            gen_index_hash: [1u8; 32],
            rotating_pubkey: [2u8; 32],
            expiry_unix_ts_ms: 1000000,
            sig: [0u8; 64],
        };
        let h1 = proof.hash();
        let h2 = proof.hash();
        assert_eq!(h1, h2);
        assert_ne!(h1, [0u8; 32]);
    }

    #[test]
    fn test_proof_hash_different_inputs() {
        let proof1 = ProProof {
            version: 0,
            gen_index_hash: [1u8; 32],
            rotating_pubkey: [2u8; 32],
            expiry_unix_ts_ms: 1000000,
            sig: [0u8; 64],
        };
        let proof2 = ProProof {
            version: 1,
            gen_index_hash: [1u8; 32],
            rotating_pubkey: [2u8; 32],
            expiry_unix_ts_ms: 1000000,
            sig: [0u8; 64],
        };
        assert_ne!(proof1.hash(), proof2.hash());
    }

    #[test]
    fn test_proof_is_active() {
        let proof = ProProof {
            version: 0,
            gen_index_hash: [0u8; 32],
            rotating_pubkey: [0u8; 32],
            expiry_unix_ts_ms: 5000,
            sig: [0u8; 64],
        };
        assert!(proof.is_active(4999));
        assert!(proof.is_active(5000));
        assert!(!proof.is_active(5001));
    }

    #[test]
    fn test_proof_verify_signature_invalid_pubkey_size() {
        let proof = ProProof {
            version: 0,
            gen_index_hash: [0u8; 32],
            rotating_pubkey: [0u8; 32],
            expiry_unix_ts_ms: 5000,
            sig: [0u8; 64],
        };
        let bad_key = [0u8; 16];
        let result = proof.verify_signature(&bad_key);
        assert!(result.is_err());
    }

    #[test]
    fn test_proof_verify_message_invalid_sig_size() {
        let proof = ProProof {
            version: 0,
            gen_index_hash: [0u8; 32],
            rotating_pubkey: [0u8; 32],
            expiry_unix_ts_ms: 5000,
            sig: [0u8; 64],
        };
        let bad_sig = [0u8; 32];
        let result = proof.verify_message(&bad_sig, b"hello");
        assert!(result.is_err());
    }

    #[test]
    fn test_proof_sign_and_verify() {
        // Generate a keypair for the "backend"
        let (backend_pk, backend_sk) = crate::crypto::ed25519::ed25519_key_pair();

        // Generate a keypair for the rotating key
        let (rotating_pk, rotating_sk) = crate::crypto::ed25519::ed25519_key_pair();

        // Build a proof
        let mut proof = ProProof {
            version: 0,
            gen_index_hash: [0xAA; 32],
            rotating_pubkey: rotating_pk,
            expiry_unix_ts_ms: u64::MAX, // never expires for this test
            sig: [0u8; 64],
        };

        // Sign the proof hash with the backend key
        let hash = proof.hash();
        let sig = crate::crypto::ed25519::sign(&backend_sk, &hash).unwrap();
        proof.sig = sig;

        // Verify the proof signature
        assert!(proof.verify_signature(&backend_pk).unwrap());

        // Verify with wrong key should fail
        let (wrong_pk, _) = crate::crypto::ed25519::ed25519_key_pair();
        assert!(!proof.verify_signature(&wrong_pk).unwrap());

        // Verify a message signed by the rotating key
        let msg = b"test message";
        let msg_sig = crate::crypto::ed25519::sign(&rotating_sk, msg).unwrap();
        assert!(proof.verify_message(&msg_sig, msg).unwrap());

        // Full status check
        let status = proof.status(&backend_pk, 0, None).unwrap();
        assert_eq!(status, ProStatus::Valid);

        // Status with signed message
        let status = proof
            .status(
                &backend_pk,
                0,
                Some(ProSignedMessage {
                    sig: &msg_sig,
                    msg,
                }),
            )
            .unwrap();
        assert_eq!(status, ProStatus::Valid);
    }

    #[test]
    fn test_proof_status_expired() {
        let (backend_pk, backend_sk) = crate::crypto::ed25519::ed25519_key_pair();

        let mut proof = ProProof {
            version: 0,
            gen_index_hash: [0xBB; 32],
            rotating_pubkey: [0u8; 32],
            expiry_unix_ts_ms: 1000,
            sig: [0u8; 64],
        };

        let hash = proof.hash();
        proof.sig = crate::crypto::ed25519::sign(&backend_sk, &hash).unwrap();

        // Check at a time after expiry
        let status = proof.status(&backend_pk, 1001, None).unwrap();
        assert_eq!(status, ProStatus::Expired);
    }

    #[test]
    fn test_destination_type_values() {
        assert_eq!(DestinationType::SyncOr1o1 as u8, 0);
        assert_eq!(DestinationType::Group as u8, 1);
        assert_eq!(DestinationType::CommunityInbox as u8, 2);
        assert_eq!(DestinationType::Community as u8, 3);
    }

    #[test]
    fn test_envelope_flags() {
        assert_eq!(envelope_flags::SOURCE, 1);
        assert_eq!(envelope_flags::SOURCE_DEVICE, 2);
        assert_eq!(envelope_flags::SERVER_TIMESTAMP, 4);
        assert_eq!(envelope_flags::PRO_SIG, 8);
        assert_eq!(envelope_flags::TIMESTAMP, 16);
    }

    #[test]
    fn test_make_blake2b32_hasher() {
        let mut hasher = make_blake2b32_hasher(BUILD_PROOF_HASH_PERSONALISATION);
        hasher.update(b"test data");
        let result = hasher.finalize();
        assert_eq!(result.as_bytes().len(), 32);
    }
}