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
// Copyright 2021 Damir Jelić, Denis Kasak
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod fallback_keys;
mod one_time_keys;

use std::collections::HashMap;

use rand::thread_rng;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use x25519_dalek::ReusableSecret;

pub use self::one_time_keys::OneTimeKeyGenerationResult;
use self::{
    fallback_keys::FallbackKeys,
    one_time_keys::{OneTimeKeys, OneTimeKeysPickle},
};
use super::{
    messages::PreKeyMessage,
    session::{DecryptionError, Session},
    session_keys::SessionKeys,
    shared_secret::{RemoteShared3DHSecret, Shared3DHSecret},
    SessionConfig,
};
use crate::{
    types::{
        Curve25519Keypair, Curve25519KeypairPickle, Curve25519PublicKey, Curve25519SecretKey,
        Ed25519Keypair, Ed25519KeypairPickle, Ed25519PublicKey, KeyId,
    },
    utilities::{pickle, unpickle},
    Ed25519Signature, PickleError,
};

const PUBLIC_MAX_ONE_TIME_KEYS: usize = 50;

/// Error describing failure modes when creating a Olm [`Session`] from an
/// incoming Olm message.
#[derive(Error, Debug)]
pub enum SessionCreationError {
    /// The pre-key message contained an unknown one-time key. This happens
    /// either because we never had such a one-time key, or because it has
    /// already been used up.
    #[error("The pre-key message contained an unknown one-time key: {0}")]
    MissingOneTimeKey(Curve25519PublicKey),
    /// The pre-key message contains a Curve25519 identity key that doesn't
    /// match to the identity key that was given.
    #[error(
        "The given identity key doesn't match the one in the pre-key message: \
        expected {0}, got {1}"
    )]
    MismatchedIdentityKey(Curve25519PublicKey, Curve25519PublicKey),
    /// The pre-key message that was used to establish the [`Session`] couldn't
    /// be decrypted. The message needs to be decryptable, otherwise we will
    /// have created a Session that wasn't used to encrypt the pre-key
    /// message.
    #[error("The message that was used to establish the Session couldn't be decrypted")]
    Decryption(#[from] DecryptionError),
}

/// Struct holding the two public identity keys of an [`Account`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct IdentityKeys {
    /// The Ed25519 key, used for signing.
    pub ed25519: Ed25519PublicKey,
    /// The Curve25519 key, used for to establish shared secrets.
    pub curve25519: Curve25519PublicKey,
}

/// Return type for the creation of inbound [`Session`] objects.
#[derive(Debug)]
pub struct InboundCreationResult {
    /// The [`Session`] that was created from a pre-key message.
    pub session: Session,
    /// The plaintext of the pre-key message.
    pub plaintext: Vec<u8>,
}

/// An Olm [`Account`] manages all cryptographic keys used on a device.
pub struct Account {
    /// A permanent Ed25519 key used for signing. Also known as the fingerprint
    /// key.
    signing_key: Ed25519Keypair,
    /// The permanent Curve25519 key used for triple Diffie-Hellman (3DH). Also
    /// known as the sender key or the identity key.
    diffie_hellman_key: Curve25519Keypair,
    /// The ephemeral (one-time) Curve25519 keys used as part of the triple
    /// Diffie-Hellman (3DH).
    one_time_keys: OneTimeKeys,
    /// The ephemeral Curve25519 keys used in lieu of a one-time key as part of
    /// the 3DH, in case we run out of those. We keep track of both the current
    /// and the previous fallback key in any given moment.
    fallback_keys: FallbackKeys,
}

impl Account {
    /// Create a new [`Account`] with new random identity keys.
    pub fn new() -> Self {
        Self {
            signing_key: Ed25519Keypair::new(),
            diffie_hellman_key: Curve25519Keypair::new(),
            one_time_keys: OneTimeKeys::new(),
            fallback_keys: FallbackKeys::new(),
        }
    }

    /// Get the [`IdentityKeys`] of this Account
    pub const fn identity_keys(&self) -> IdentityKeys {
        IdentityKeys { ed25519: self.ed25519_key(), curve25519: self.curve25519_key() }
    }

    /// Get a copy of the account's public Ed25519 key
    pub const fn ed25519_key(&self) -> Ed25519PublicKey {
        self.signing_key.public_key()
    }

    /// Get a copy of the account's public Curve25519 key
    pub const fn curve25519_key(&self) -> Curve25519PublicKey {
        self.diffie_hellman_key.public_key()
    }

    /// Sign the given message using our Ed25519 fingerprint key.
    pub fn sign(&self, message: impl AsRef<[u8]>) -> Ed25519Signature {
        self.signing_key.sign(message.as_ref())
    }

    /// Get the maximum number of one-time keys the client should keep on the
    /// server.
    ///
    /// **Note**: this differs from the libolm method of the same name, the
    /// libolm method returned the maximum amount of one-time keys the
    /// [`Account`] could hold and only half of those should be uploaded.
    pub const fn max_number_of_one_time_keys(&self) -> usize {
        // We tell clients to upload a limited amount of one-time keys, this
        // amount is smaller than what we can store.
        //
        // We do this because a client might receive the count of uploaded keys
        // from the server before they receive all the pre-key messages that
        // used some of our one-time keys. This would mean that we would forget
        // private one-time keys, since we're generating new ones, while we
        // didn't yet receive the pre-key messages that used those one-time
        // keys.
        PUBLIC_MAX_ONE_TIME_KEYS
    }

    /// Create a [`Session`] with the given identity key and one-time key.
    pub fn create_outbound_session(
        &self,
        session_config: SessionConfig,
        identity_key: Curve25519PublicKey,
        one_time_key: Curve25519PublicKey,
    ) -> Session {
        let rng = thread_rng();

        let base_key = ReusableSecret::random_from_rng(rng);
        let public_base_key = Curve25519PublicKey::from(&base_key);

        let shared_secret = Shared3DHSecret::new(
            self.diffie_hellman_key.secret_key(),
            &base_key,
            &identity_key,
            &one_time_key,
        );

        let session_keys = SessionKeys {
            identity_key: self.curve25519_key(),
            base_key: public_base_key,
            one_time_key,
        };

        Session::new(session_config, shared_secret, session_keys)
    }

    /// Try to find a [`Curve25519SecretKey`] that forms a pair with the given
    /// [`Curve25519PublicKey`].
    fn find_one_time_key(&self, public_key: &Curve25519PublicKey) -> Option<&Curve25519SecretKey> {
        self.one_time_keys
            .get_secret_key(public_key)
            .or_else(|| self.fallback_keys.get_secret_key(public_key))
    }

    /// Remove a one-time key that has previously been published but not yet
    /// used.
    ///
    /// **Note**: This function is only rarely useful and you'll know if you
    /// need it. Notably, you do *not* need to call it manually when using up
    /// a key via [`Account::create_inbound_session`] since the key is
    /// automatically removed in that case.
    #[cfg(feature = "low-level-api")]
    pub fn remove_one_time_key(
        &mut self,
        public_key: Curve25519PublicKey,
    ) -> Option<Curve25519SecretKey> {
        self.remove_one_time_key_helper(public_key)
    }

    fn remove_one_time_key_helper(
        &mut self,
        public_key: Curve25519PublicKey,
    ) -> Option<Curve25519SecretKey> {
        self.one_time_keys.remove_secret_key(&public_key)
    }

    /// Create a [`Session`] from the given [`PreKeyMessage`] message and
    /// identity key
    pub fn create_inbound_session(
        &mut self,
        their_identity_key: Curve25519PublicKey,
        pre_key_message: &PreKeyMessage,
    ) -> Result<InboundCreationResult, SessionCreationError> {
        if their_identity_key != pre_key_message.identity_key() {
            Err(SessionCreationError::MismatchedIdentityKey(
                their_identity_key,
                pre_key_message.identity_key(),
            ))
        } else {
            // Find the matching private part of the OTK that the message claims
            // was used to create the session that encrypted it.
            let public_otk = pre_key_message.one_time_key();
            let private_otk = self
                .find_one_time_key(&public_otk)
                .ok_or(SessionCreationError::MissingOneTimeKey(public_otk))?;

            // Construct a 3DH shared secret from the various curve25519 keys.
            let shared_secret = RemoteShared3DHSecret::new(
                self.diffie_hellman_key.secret_key(),
                private_otk,
                &pre_key_message.identity_key(),
                &pre_key_message.base_key(),
            );

            // These will be used to uniquely identify the Session.
            let session_keys = SessionKeys {
                identity_key: pre_key_message.identity_key(),
                base_key: pre_key_message.base_key(),
                one_time_key: pre_key_message.one_time_key(),
            };

            let config = if pre_key_message.message.mac_truncated() {
                SessionConfig::version_1()
            } else {
                SessionConfig::version_2()
            };

            // Create a Session, AKA a double ratchet, this one will have an
            // inactive sending chain until we decide to encrypt a message.
            let mut session = Session::new_remote(
                config,
                shared_secret,
                pre_key_message.message.ratchet_key,
                session_keys,
            );

            // Decrypt the message to check if the Session is actually valid.
            let plaintext = session.decrypt_decoded(&pre_key_message.message)?;

            // We only drop the one-time key now, this is why we can't use a
            // one-time key type that takes `self`. If we didn't do this,
            // someone could maliciously pretend to use up our one-time key and
            // make us drop the private part. Unsuspecting users that actually
            // try to use such an one-time key won't be able to commnuicate with
            // us. This is strictly worse than the one-time key exhaustion
            // scenario.
            self.remove_one_time_key_helper(pre_key_message.one_time_key());

            Ok(InboundCreationResult { session, plaintext })
        }
    }

    /// Generates the supplied number of one time keys.
    /// Returns the public parts of the one-time keys that were created and
    /// discarded.
    ///
    /// Our one-time key store inside the [`Account`] has a limited amount of
    /// places for one-time keys, If we try to generate new ones while the store
    /// is completely populated, the oldest one-time keys will get discarded
    /// to make place for new ones.
    pub fn generate_one_time_keys(&mut self, count: usize) -> OneTimeKeyGenerationResult {
        self.one_time_keys.generate(count)
    }

    /// Get the number of one-time keys we have stored locally.
    ///
    /// This will be equal or greater to the number of one-time keys we have
    /// published. Each time a new [`Session`] is created using the
    /// [`Account::create_inbound_session()`] a one-time key will be used up
    /// and removed.
    pub fn stored_one_time_key_count(&self) -> usize {
        self.one_time_keys.private_keys.len()
    }

    /// Get the currently unpublished one-time keys.
    ///
    /// The one-time keys should be published to a server and marked as
    /// published using the `mark_keys_as_published()` method.
    pub fn one_time_keys(&self) -> HashMap<KeyId, Curve25519PublicKey> {
        self.one_time_keys
            .unpublished_public_keys
            .iter()
            .map(|(key_id, key)| (*key_id, *key))
            .collect()
    }

    /// Generate a single new fallback key.
    ///
    /// The fallback key will be used by other users to establish a [`Session`]
    /// if all the one-time keys on the server have been used up.
    ///
    /// Returns the public Curve25519 key of the *previous* fallback key, that
    /// is, the one that will get removed from the [`Account`] when this method
    /// is called. This return value is mostly useful for logging purposes.
    pub fn generate_fallback_key(&mut self) -> Option<Curve25519PublicKey> {
        self.fallback_keys.generate_fallback_key()
    }

    /// Get the currently unpublished fallback key.
    ///
    /// The fallback key should be published just like the one-time keys, after
    /// it has been successfully published it needs to be marked as published
    /// using the `mark_keys_as_published()` method as well.
    pub fn fallback_key(&self) -> HashMap<KeyId, Curve25519PublicKey> {
        let fallback_key = self.fallback_keys.unpublished_fallback_key();

        if let Some(fallback_key) = fallback_key {
            HashMap::from([(fallback_key.key_id(), fallback_key.public_key())])
        } else {
            HashMap::new()
        }
    }

    /// The [`Account`] stores at most two private parts of the fallback key.
    /// This method lets us forget the previously used fallback key.
    pub fn forget_fallback_key(&mut self) -> bool {
        self.fallback_keys.forget_previous_fallback_key().is_some()
    }

    /// Mark all currently unpublished one-time and fallback keys as published.
    pub fn mark_keys_as_published(&mut self) {
        self.one_time_keys.mark_as_published();
        self.fallback_keys.mark_as_published();
    }

    /// Convert the account into a struct which implements [`serde::Serialize`]
    /// and [`serde::Deserialize`].
    pub fn pickle(&self) -> AccountPickle {
        AccountPickle {
            signing_key: self.signing_key.clone().into(),
            diffie_hellman_key: self.diffie_hellman_key.clone().into(),
            one_time_keys: self.one_time_keys.clone().into(),
            fallback_keys: self.fallback_keys.clone(),
        }
    }

    /// Restore an [`Account`] from a previously saved [`AccountPickle`].
    pub fn from_pickle(pickle: AccountPickle) -> Self {
        pickle.into()
    }

    /// Create an [`Account`] object by unpickling an account pickle in libolm
    /// legacy pickle format.
    ///
    /// Such pickles are encrypted and need to first be decrypted using
    /// `pickle_key`.
    #[cfg(feature = "libolm-compat")]
    pub fn from_libolm_pickle(
        pickle: &str,
        pickle_key: &[u8],
    ) -> Result<Self, crate::LibolmPickleError> {
        use self::libolm::Pickle;
        use crate::utilities::unpickle_libolm;

        const PICKLE_VERSION: u32 = 4;
        unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
    }

    /// Pickle an [`Account`] into a libolm pickle format.
    ///
    /// This pickle can be restored using the [`Account::from_libolm_pickle()`]
    /// method, or can be used in the [`libolm`] C library.
    ///
    /// The pickle will be encrypted using the pickle key.
    ///
    /// *Note*: This method might be lossy, the vodozemac [`Account`] has the
    /// ability to hold more one-time keys compared to the [`libolm`]
    /// variant.
    ///
    /// ⚠️  ***Security Warning***: The pickle key will get expanded into both
    /// an AES key and an IV in a deterministic manner. If the same pickle
    /// key is reused, this will lead to IV reuse. To prevent this, users
    /// have to ensure that they always use a globally (probabilistically)
    /// unique pickle key.
    ///
    /// [`libolm`]: https://gitlab.matrix.org/matrix-org/olm/
    ///
    /// # Examples
    /// ```
    /// use vodozemac::olm::Account;
    /// use olm_rs::{account::OlmAccount, PicklingMode};
    /// let account = Account::new();
    ///
    /// let export = account
    ///     .to_libolm_pickle(&[0u8; 32])
    ///     .expect("We should be able to pickle a freshly created Account");
    ///
    /// let unpickled = OlmAccount::unpickle(
    ///     export,
    ///     PicklingMode::Encrypted { key: [0u8; 32].to_vec() },
    /// ).expect("We should be able to unpickle our exported Account");
    /// ```
    #[cfg(feature = "libolm-compat")]
    pub fn to_libolm_pickle(&self, pickle_key: &[u8]) -> Result<String, crate::LibolmPickleError> {
        use self::libolm::Pickle;
        use crate::utilities::pickle_libolm;
        pickle_libolm::<Pickle>(self.into(), pickle_key)
    }

    #[cfg(all(any(fuzzing, test), feature = "libolm-compat"))]
    #[doc(hidden)]
    pub fn from_decrypted_libolm_pickle(pickle: &[u8]) -> Result<Self, crate::LibolmPickleError> {
        use std::io::Cursor;

        use matrix_pickle::Decode;

        use self::libolm::Pickle;

        let mut cursor = Cursor::new(&pickle);
        let pickle = Pickle::decode(&mut cursor)?;

        pickle.try_into()
    }
}

impl Default for Account {
    fn default() -> Self {
        Self::new()
    }
}

/// A format suitable for serialization which implements [`serde::Serialize`]
/// and [`serde::Deserialize`]. Obtainable by calling [`Account::pickle`].
#[derive(Serialize, Deserialize)]
pub struct AccountPickle {
    signing_key: Ed25519KeypairPickle,
    diffie_hellman_key: Curve25519KeypairPickle,
    one_time_keys: OneTimeKeysPickle,
    fallback_keys: FallbackKeys,
}

/// A format suitable for serialization which implements [`serde::Serialize`]
/// and [`serde::Deserialize`]. Obtainable by calling [`Account::pickle`].
impl AccountPickle {
    /// Serialize and encrypt the pickle using the given key.
    ///
    /// This is the inverse of [`AccountPickle::from_encrypted`].
    pub fn encrypt(self, pickle_key: &[u8; 32]) -> String {
        pickle(&self, pickle_key)
    }

    /// Obtain a pickle from a ciphertext by decrypting and deserializing using
    /// the given key.
    ///
    /// This is the inverse of [`AccountPickle::encrypt`].
    pub fn from_encrypted(ciphertext: &str, pickle_key: &[u8; 32]) -> Result<Self, PickleError> {
        unpickle(ciphertext, pickle_key)
    }
}

impl From<AccountPickle> for Account {
    fn from(pickle: AccountPickle) -> Self {
        Self {
            signing_key: pickle.signing_key.into(),
            diffie_hellman_key: pickle.diffie_hellman_key.into(),
            one_time_keys: pickle.one_time_keys.into(),
            fallback_keys: pickle.fallback_keys,
        }
    }
}

#[cfg(feature = "libolm-compat")]
mod libolm {
    use matrix_pickle::{Decode, DecodeError, Encode, EncodeError};
    use zeroize::{Zeroize, ZeroizeOnDrop};

    use super::{
        fallback_keys::{FallbackKey, FallbackKeys},
        one_time_keys::OneTimeKeys,
        Account,
    };
    use crate::{
        types::{Curve25519Keypair, Curve25519SecretKey},
        utilities::LibolmEd25519Keypair,
        Curve25519PublicKey, Ed25519Keypair, KeyId,
    };

    #[derive(Encode, Decode, Zeroize, ZeroizeOnDrop)]
    struct OneTimeKey {
        key_id: u32,
        published: bool,
        public_key: [u8; 32],
        private_key: Box<[u8; 32]>,
    }

    impl From<&OneTimeKey> for FallbackKey {
        fn from(key: &OneTimeKey) -> Self {
            FallbackKey {
                key_id: KeyId(key.key_id.into()),
                key: Curve25519SecretKey::from_slice(&key.private_key),
                published: key.published,
            }
        }
    }

    #[derive(Zeroize, ZeroizeOnDrop)]
    struct FallbackKeysArray {
        fallback_key: Option<OneTimeKey>,
        previous_fallback_key: Option<OneTimeKey>,
    }

    impl Decode for FallbackKeysArray {
        fn decode(reader: &mut impl std::io::Read) -> Result<Self, DecodeError> {
            let count = u8::decode(reader)?;

            let (fallback_key, previous_fallback_key) = if count >= 1 {
                let fallback_key = OneTimeKey::decode(reader)?;

                let previous_fallback_key =
                    if count >= 2 { Some(OneTimeKey::decode(reader)?) } else { None };

                (Some(fallback_key), previous_fallback_key)
            } else {
                (None, None)
            };

            Ok(Self { fallback_key, previous_fallback_key })
        }
    }

    impl Encode for FallbackKeysArray {
        fn encode(&self, writer: &mut impl std::io::Write) -> Result<usize, EncodeError> {
            let ret = match (&self.fallback_key, &self.previous_fallback_key) {
                (None, None) => 0u8.encode(writer)?,
                (Some(key), None) | (None, Some(key)) => {
                    let mut ret = 1u8.encode(writer)?;
                    ret += key.encode(writer)?;

                    ret
                }
                (Some(key), Some(previous_key)) => {
                    let mut ret = 2u8.encode(writer)?;
                    ret += key.encode(writer)?;
                    ret += previous_key.encode(writer)?;

                    ret
                }
            };

            Ok(ret)
        }
    }

    #[derive(Encode, Decode, Zeroize, ZeroizeOnDrop)]
    pub(super) struct Pickle {
        version: u32,
        ed25519_keypair: LibolmEd25519Keypair,
        public_curve25519_key: [u8; 32],
        private_curve25519_key: Box<[u8; 32]>,
        one_time_keys: Vec<OneTimeKey>,
        fallback_keys: FallbackKeysArray,
        next_key_id: u32,
    }

    impl TryFrom<&FallbackKey> for OneTimeKey {
        type Error = ();

        fn try_from(key: &FallbackKey) -> Result<Self, ()> {
            Ok(OneTimeKey {
                key_id: key.key_id.0.try_into().map_err(|_| ())?,
                published: key.published(),
                public_key: key.public_key().to_bytes(),
                private_key: key.secret_key().to_bytes(),
            })
        }
    }

    impl From<&Account> for Pickle {
        fn from(account: &Account) -> Self {
            let one_time_keys: Vec<_> = account
                .one_time_keys
                .secret_keys()
                .iter()
                .filter_map(|(key_id, secret_key)| {
                    Some(OneTimeKey {
                        key_id: key_id.0.try_into().ok()?,
                        published: account.one_time_keys.is_secret_key_published(key_id),
                        public_key: Curve25519PublicKey::from(secret_key).to_bytes(),
                        private_key: secret_key.to_bytes(),
                    })
                })
                .collect();

            let fallback_keys = FallbackKeysArray {
                fallback_key: account
                    .fallback_keys
                    .fallback_key
                    .as_ref()
                    .and_then(|f| f.try_into().ok()),
                previous_fallback_key: account
                    .fallback_keys
                    .previous_fallback_key
                    .as_ref()
                    .and_then(|f| f.try_into().ok()),
            };

            let next_key_id = account.one_time_keys.next_key_id.try_into().unwrap_or_default();

            Self {
                version: 4,
                ed25519_keypair: LibolmEd25519Keypair {
                    private_key: account.signing_key.expanded_secret_key(),
                    public_key: account.signing_key.public_key().as_bytes().to_owned(),
                },
                public_curve25519_key: account.diffie_hellman_key.public_key().to_bytes(),
                private_curve25519_key: account.diffie_hellman_key.secret_key().to_bytes(),
                one_time_keys,
                fallback_keys,
                next_key_id,
            }
        }
    }

    impl TryFrom<Pickle> for Account {
        type Error = crate::LibolmPickleError;

        fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
            let mut one_time_keys = OneTimeKeys::new();

            for key in &pickle.one_time_keys {
                let secret_key = Curve25519SecretKey::from_slice(&key.private_key);
                let key_id = KeyId(key.key_id.into());
                one_time_keys.insert_secret_key(key_id, secret_key, key.published);
            }

            one_time_keys.next_key_id = pickle.next_key_id.into();

            let fallback_keys = FallbackKeys {
                key_id: pickle
                    .fallback_keys
                    .fallback_key
                    .as_ref()
                    .map(|k| k.key_id.wrapping_add(1))
                    .unwrap_or(0) as u64,
                fallback_key: pickle.fallback_keys.fallback_key.as_ref().map(|k| k.into()),
                previous_fallback_key: pickle
                    .fallback_keys
                    .previous_fallback_key
                    .as_ref()
                    .map(|k| k.into()),
            };

            Ok(Self {
                signing_key: Ed25519Keypair::from_expanded_key(
                    &pickle.ed25519_keypair.private_key,
                )?,
                diffie_hellman_key: Curve25519Keypair::from_secret_key(
                    &pickle.private_curve25519_key,
                ),
                one_time_keys,
                fallback_keys,
            })
        }
    }
}

#[cfg(test)]
mod test {
    use anyhow::{bail, Context, Result};
    #[cfg(feature = "libolm-compat")]
    use matrix_pickle::Encode;
    use olm_rs::{account::OlmAccount, session::OlmMessage as LibolmOlmMessage};

    #[cfg(feature = "libolm-compat")]
    use super::libolm::Pickle;
    use super::{Account, InboundCreationResult, SessionConfig, SessionCreationError};
    use crate::{
        cipher::Mac,
        olm::{
            account::PUBLIC_MAX_ONE_TIME_KEYS,
            messages::{OlmMessage, PreKeyMessage},
            AccountPickle,
        },
        Curve25519PublicKey as PublicKey,
    };

    const PICKLE_KEY: [u8; 32] = [0u8; 32];

    #[test]
    fn max_number_of_one_time_keys_matches_global_constant() {
        assert_eq!(Account::new().max_number_of_one_time_keys(), PUBLIC_MAX_ONE_TIME_KEYS);
    }

    #[test]
    #[cfg(feature = "low-level-api")]
    fn generate_and_remove_one_time_key() {
        let mut alice = Account::new();
        assert_eq!(alice.stored_one_time_key_count(), 0);

        alice.generate_one_time_keys(1);
        assert_eq!(alice.stored_one_time_key_count(), 1);

        let public_key = alice
            .one_time_keys()
            .values()
            .next()
            .copied()
            .expect("Should have an unpublished one-time key");
        let secret_key_bytes = alice
            .find_one_time_key(&public_key)
            .expect("Should find secret key for public one-time key")
            .to_bytes();
        let removed_key_bytes = alice
            .remove_one_time_key(public_key)
            .expect("Should be able to remove one-time key")
            .to_bytes();

        assert_eq!(removed_key_bytes, secret_key_bytes);
        assert_eq!(alice.stored_one_time_key_count(), 0);
    }

    #[test]
    fn generate_and_forget_fallback_keys() {
        let mut alice = Account::default();
        assert!(!alice.forget_fallback_key());
        alice.generate_fallback_key();
        assert!(!alice.forget_fallback_key());
        alice.generate_fallback_key();
        assert!(alice.forget_fallback_key());
    }

    #[test]
    fn vodozemac_libolm_communication() -> Result<()> {
        // vodozemac account
        let alice = Account::new();
        // libolm account
        let bob = OlmAccount::new();

        bob.generate_one_time_keys(1);

        let one_time_key = bob
            .parsed_one_time_keys()
            .curve25519()
            .values()
            .next()
            .cloned()
            .expect("Didn't find a valid one-time key");

        bob.mark_keys_as_published();

        let identity_keys = bob.parsed_identity_keys();
        let curve25519_key = PublicKey::from_base64(identity_keys.curve25519())?;
        let one_time_key = PublicKey::from_base64(&one_time_key)?;
        let mut alice_session =
            alice.create_outbound_session(SessionConfig::version_1(), curve25519_key, one_time_key);

        let message = "It's a secret to everybody";
        let olm_message: LibolmOlmMessage = alice_session.encrypt(message).into();

        if let LibolmOlmMessage::PreKey(m) = olm_message.clone() {
            let libolm_session =
                bob.create_inbound_session_from(&alice.curve25519_key().to_base64(), m)?;
            assert_eq!(alice_session.session_id(), libolm_session.session_id());

            let plaintext = libolm_session.decrypt(olm_message)?;
            assert_eq!(message, plaintext);

            let second_text = "Here's another secret to everybody";
            let olm_message = alice_session.encrypt(second_text).into();

            let plaintext = libolm_session.decrypt(olm_message)?;
            assert_eq!(second_text, plaintext);

            let reply_plain = "Yes, take this, it's dangerous out there";
            let reply = libolm_session.encrypt(reply_plain).into();
            let plaintext = alice_session.decrypt(&reply)?;

            assert_eq!(plaintext, reply_plain.as_bytes());

            let another_reply = "Last one";
            let reply = libolm_session.encrypt(another_reply).into();
            let plaintext = alice_session.decrypt(&reply)?;
            assert_eq!(plaintext, another_reply.as_bytes());

            let last_text = "Nope, I'll have the last word";
            let olm_message = alice_session.encrypt(last_text).into();

            let plaintext = libolm_session.decrypt(olm_message)?;
            assert_eq!(last_text, plaintext);
        } else {
            bail!("Received a invalid message type {:?}", olm_message);
        }

        Ok(())
    }

    #[test]
    fn vodozemac_vodozemac_communication() -> Result<()> {
        // Both of these are vodozemac accounts.
        let alice = Account::new();
        let mut bob = Account::new();

        bob.generate_one_time_keys(1);

        let mut alice_session = alice.create_outbound_session(
            SessionConfig::version_2(),
            bob.curve25519_key(),
            *bob.one_time_keys()
                .iter()
                .next()
                .context("Failed getting bob's OTK, which should never happen here.")?
                .1,
        );

        assert!(!bob.one_time_keys().is_empty());
        bob.mark_keys_as_published();
        assert!(bob.one_time_keys().is_empty());

        let message = "It's a secret to everybody";
        let olm_message = alice_session.encrypt(message);

        if let OlmMessage::PreKey(m) = olm_message {
            assert_eq!(m.session_keys(), alice_session.session_keys());
            assert_eq!(m.session_id(), alice_session.session_id());

            let InboundCreationResult { session: mut bob_session, plaintext } =
                bob.create_inbound_session(alice.curve25519_key(), &m)?;
            assert_eq!(alice_session.session_id(), bob_session.session_id());
            assert_eq!(m.session_keys(), bob_session.session_keys());

            assert_eq!(message.as_bytes(), plaintext);

            let second_text = "Here's another secret to everybody";
            let olm_message = alice_session.encrypt(second_text);

            let plaintext = bob_session.decrypt(&olm_message)?;
            assert_eq!(second_text.as_bytes(), plaintext);

            let reply_plain = "Yes, take this, it's dangerous out there";
            let reply = bob_session.encrypt(reply_plain);
            let plaintext = alice_session.decrypt(&reply)?;

            assert_eq!(plaintext, reply_plain.as_bytes());

            let another_reply = "Last one";
            let reply = bob_session.encrypt(another_reply);
            let plaintext = alice_session.decrypt(&reply)?;
            assert_eq!(plaintext, another_reply.as_bytes());

            let last_text = "Nope, I'll have the last word";
            let olm_message = alice_session.encrypt(last_text);

            let plaintext = bob_session.decrypt(&olm_message)?;
            assert_eq!(last_text.as_bytes(), plaintext);
        }

        Ok(())
    }

    #[test]
    fn inbound_session_creation() -> Result<()> {
        let alice = OlmAccount::new();
        let mut bob = Account::new();

        bob.generate_one_time_keys(1);

        let one_time_key =
            bob.one_time_keys().values().next().cloned().expect("Didn't find a valid one-time key");

        let alice_session = alice.create_outbound_session(
            &bob.curve25519_key().to_base64(),
            &one_time_key.to_base64(),
        )?;

        let text = "It's a secret to everybody";
        let message = alice_session.encrypt(text).into();

        let identity_key = PublicKey::from_base64(alice.parsed_identity_keys().curve25519())?;

        let InboundCreationResult { session, plaintext } = if let OlmMessage::PreKey(m) = &message {
            bob.create_inbound_session(identity_key, m)?
        } else {
            bail!("Got invalid message type from olm_rs {:?}", message);
        };

        assert_eq!(alice_session.session_id(), session.session_id());
        assert!(bob.one_time_keys.private_keys.is_empty());

        assert_eq!(text.as_bytes(), plaintext);

        Ok(())
    }

    #[test]
    fn inbound_session_creation_using_fallback_keys() -> Result<()> {
        let alice = OlmAccount::new();
        let mut bob = Account::new();

        bob.generate_fallback_key();

        let one_time_key =
            bob.fallback_key().values().next().cloned().expect("Didn't find a valid fallback key");
        assert!(bob.one_time_keys.private_keys.is_empty());

        let alice_session = alice.create_outbound_session(
            &bob.curve25519_key().to_base64(),
            &one_time_key.to_base64(),
        )?;

        let text = "It's a secret to everybody";

        let message = alice_session.encrypt(text).into();
        let identity_key = PublicKey::from_base64(alice.parsed_identity_keys().curve25519())?;

        if let OlmMessage::PreKey(m) = &message {
            let InboundCreationResult { session, plaintext } =
                bob.create_inbound_session(identity_key, m)?;

            assert_eq!(m.session_keys(), session.session_keys());
            assert_eq!(alice_session.session_id(), session.session_id());
            assert!(bob.fallback_keys.fallback_key.is_some());

            assert_eq!(text.as_bytes(), plaintext);
        } else {
            bail!("Got invalid message type from olm_rs");
        };

        Ok(())
    }

    #[test]
    fn account_pickling_roundtrip_is_identity() -> Result<()> {
        let mut account = Account::new();

        account.generate_one_time_keys(50);

        // Generate two fallback keys so the previous fallback key field gets populated.
        account.generate_fallback_key();
        account.generate_fallback_key();

        let pickle = account.pickle().encrypt(&PICKLE_KEY);

        let decrypted_pickle = AccountPickle::from_encrypted(&pickle, &PICKLE_KEY)?;
        let unpickled_account = Account::from_pickle(decrypted_pickle);
        let repickle = unpickled_account.pickle();

        assert_eq!(account.identity_keys(), unpickled_account.identity_keys());

        let decrypted_pickle = AccountPickle::from_encrypted(&pickle, &PICKLE_KEY)?;
        let pickle = serde_json::to_value(decrypted_pickle)?;
        let repickle = serde_json::to_value(repickle)?;

        assert_eq!(pickle, repickle);

        Ok(())
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn libolm_unpickling() -> Result<()> {
        let olm = OlmAccount::new();
        olm.generate_one_time_keys(10);
        olm.generate_fallback_key();

        let key = b"DEFAULT_PICKLE_KEY";
        let pickle = olm.pickle(olm_rs::PicklingMode::Encrypted { key: key.to_vec() });

        let unpickled = Account::from_libolm_pickle(&pickle, key)?;

        assert_eq!(olm.parsed_identity_keys().ed25519(), unpickled.ed25519_key().to_base64());
        assert_eq!(olm.parsed_identity_keys().curve25519(), unpickled.curve25519_key().to_base64());

        let mut olm_one_time_keys: Vec<_> =
            olm.parsed_one_time_keys().curve25519().values().map(|k| k.to_owned()).collect();
        let mut one_time_keys: Vec<_> =
            unpickled.one_time_keys().values().map(|k| k.to_base64()).collect();

        // We generated 10 one-time keys on the libolm side, we expect the next key id
        // to be 11.
        assert_eq!(unpickled.one_time_keys.next_key_id, 11);

        olm_one_time_keys.sort();
        one_time_keys.sort();
        assert_eq!(olm_one_time_keys, one_time_keys);

        let olm_fallback_key =
            olm.parsed_fallback_key().expect("libolm should have a fallback key");
        assert_eq!(
            olm_fallback_key.curve25519(),
            unpickled
                .fallback_key()
                .values()
                .next()
                .expect("We should have a fallback key")
                .to_base64()
        );

        Ok(())
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn pickle_cycle_with_one_fallback_key() {
        let mut alice = Account::new();
        alice.generate_fallback_key();

        let mut encoded = Vec::<u8>::new();
        let pickle = Pickle::from(&alice);
        let size = pickle.encode(&mut encoded).expect("Should encode pickle");
        assert_eq!(size, encoded.len());

        let account =
            Account::from_decrypted_libolm_pickle(&encoded).expect("Should unpickle account");

        let key_bytes = alice
            .fallback_key()
            .values()
            .next()
            .expect("Should have a fallback key before encoding")
            .to_bytes();
        let decoded_key_bytes = account
            .fallback_key()
            .values()
            .next()
            .expect("Should have a fallback key after decoding")
            .to_bytes();
        assert_eq!(key_bytes, decoded_key_bytes);
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn pickle_cycle_with_two_fallback_keys() {
        let mut alice = Account::new();
        alice.generate_fallback_key();
        alice.generate_fallback_key();

        let mut encoded = Vec::<u8>::new();
        let pickle = Pickle::from(&alice);
        let size = pickle.encode(&mut encoded).expect("Should encode pickle");
        assert_eq!(size, encoded.len());

        let account =
            Account::from_decrypted_libolm_pickle(&encoded).expect("Should unpickle account");

        let key_bytes = alice
            .fallback_key()
            .values()
            .next()
            .expect("Should have a fallback key before encoding")
            .to_bytes();
        let decoded_key_bytes = account
            .fallback_key()
            .values()
            .next()
            .expect("Should have a fallback key after decoding")
            .to_bytes();
        assert_eq!(key_bytes, decoded_key_bytes);
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn signing_with_expanded_key() -> Result<()> {
        let olm = OlmAccount::new();
        olm.generate_one_time_keys(10);
        olm.generate_fallback_key();

        let key = b"DEFAULT_PICKLE_KEY";
        let pickle = olm.pickle(olm_rs::PicklingMode::Encrypted { key: key.to_vec() });

        let account_with_expanded_key = Account::from_libolm_pickle(&pickle, key)?;

        // The clone is needed since we're later on using the account.
        #[allow(clippy::redundant_clone)]
        let signing_key_clone = account_with_expanded_key.signing_key.clone();
        signing_key_clone.sign("You met with a terrible fate, haven’t you?".as_bytes());
        account_with_expanded_key.sign("You met with a terrible fate, haven’t you?".as_bytes());

        Ok(())
    }

    #[test]
    fn invalid_session_creation_does_not_remove_otk() -> Result<()> {
        let mut alice = Account::new();
        let malory = Account::new();
        alice.generate_one_time_keys(1);

        let mut session = malory.create_outbound_session(
            SessionConfig::default(),
            alice.curve25519_key(),
            *alice.one_time_keys().values().next().expect("Should have one-time key"),
        );

        let message = session.encrypt("Test");

        if let OlmMessage::PreKey(m) = message {
            let mut message = m.to_bytes();
            let message_len = message.len();

            // We mangle the MAC so decryption fails but creating a Session
            // succeeds.
            message[message_len - Mac::TRUNCATED_LEN..message_len]
                .copy_from_slice(&[0u8; Mac::TRUNCATED_LEN]);

            let message = PreKeyMessage::try_from(message)?;

            match alice.create_inbound_session(malory.curve25519_key(), &message) {
                Err(SessionCreationError::Decryption(_)) => {}
                e => bail!("Expected a decryption error, got {:?}", e),
            }
            assert!(
                !alice.one_time_keys.private_keys.is_empty(),
                "The one-time key was removed when it shouldn't"
            );

            Ok(())
        } else {
            bail!("Invalid message type");
        }
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn fuzz_corpus_unpickling() {
        crate::run_corpus("olm-account-unpickling", |data| {
            let _ = Account::from_decrypted_libolm_pickle(data);
        });
    }

    #[test]
    #[cfg(feature = "libolm-compat")]
    fn libolm_pickle_cycle() -> Result<()> {
        let message = "It's a secret to everybody";

        let olm = OlmAccount::new();
        olm.generate_one_time_keys(10);
        olm.generate_fallback_key();

        let olm_signature = olm.sign(message);

        let key = b"DEFAULT_PICKLE_KEY";
        let pickle = olm.pickle(olm_rs::PicklingMode::Encrypted { key: key.to_vec() });

        let account = Account::from_libolm_pickle(&pickle, key).unwrap();
        let vodozemac_pickle = account.to_libolm_pickle(key).unwrap();
        let _ = Account::from_libolm_pickle(&vodozemac_pickle, key).unwrap();

        let vodozemac_signature = account.sign(message.as_bytes());
        let olm_signature = crate::types::Ed25519Signature::from_base64(&olm_signature)
            .expect("We should be able to parse a signature produced by libolm");
        account
            .identity_keys()
            .ed25519
            .verify(message.as_bytes(), &olm_signature)
            .expect("We should be able to verify the libolm signature with our vodozemac Account");

        let unpickled = OlmAccount::unpickle(
            vodozemac_pickle,
            olm_rs::PicklingMode::Encrypted { key: key.to_vec() },
        )
        .unwrap();

        let utility = olm_rs::utility::OlmUtility::new();
        utility
            .ed25519_verify(
                unpickled.parsed_identity_keys().ed25519(),
                message,
                vodozemac_signature.to_base64(),
            )
            .expect("We should be able to verify the signature vodozemac created");
        utility
            .ed25519_verify(
                unpickled.parsed_identity_keys().ed25519(),
                message,
                olm_signature.to_base64(),
            )
            .expect("We should be able to verify the original signature from libolm");

        assert_eq!(olm.parsed_identity_keys(), unpickled.parsed_identity_keys());

        Ok(())
    }
}