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
// Copyright 2021 Damir Jelić
//
// 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.

use std::fmt::Debug;

use matrix_pickle::Decode;
use serde::{Deserialize, Serialize};
use x25519_dalek::SharedSecret;

use super::{
    chain_key::RemoteChainKey,
    root_key::{RemoteRootKey, RootKey},
};
use crate::{types::Curve25519SecretKey, Curve25519PublicKey};

/// A ratchet key which we created ourselves.
///
/// A new ratchet key is created each time the conversation changes direction,
/// and used to calculate the [root key](RootKey) for the new sender chain.
/// The public part of the sender's ratchet key is sent to the recipient in each
/// message.
///
/// Since this is *our own* key, we have both the secret and public parts of the
/// key.
///
/// The [Olm spec](https://gitlab.matrix.org/matrix-org/olm/blob/master/docs/olm.md) refers to
/// ratchet keys as `T`<sub>`i`</sub>.
#[derive(Serialize, Deserialize, Clone)]
#[serde(transparent)]
pub(super) struct RatchetKey(Curve25519SecretKey);

/// The public part of a [`RatchetKey`].
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct RatchetPublicKey(Curve25519PublicKey);

/// A ratchet key which was created by the other side.
///
/// See [`RatchetKey`] for explanation about ratchet keys in general. Since this
/// is the other side's key, we have only the public part of the key.
#[derive(Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize, Decode)]
#[serde(transparent)]
pub struct RemoteRatchetKey(Curve25519PublicKey);

impl Debug for RemoteRatchetKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl RatchetKey {
    pub fn new() -> Self {
        Self(Curve25519SecretKey::new())
    }

    pub fn diffie_hellman(&self, other: &RemoteRatchetKey) -> SharedSecret {
        self.0.diffie_hellman(&other.0)
    }
}

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

impl From<Curve25519SecretKey> for RatchetKey {
    fn from(key: Curve25519SecretKey) -> Self {
        Self(key)
    }
}

impl From<[u8; 32]> for RatchetPublicKey {
    fn from(bytes: [u8; 32]) -> Self {
        RatchetPublicKey(Curve25519PublicKey::from(bytes))
    }
}

impl From<[u8; 32]> for RemoteRatchetKey {
    fn from(bytes: [u8; 32]) -> Self {
        RemoteRatchetKey(Curve25519PublicKey::from(bytes))
    }
}

impl From<Curve25519PublicKey> for RemoteRatchetKey {
    fn from(key: Curve25519PublicKey) -> Self {
        RemoteRatchetKey(key)
    }
}

impl AsRef<Curve25519PublicKey> for RatchetPublicKey {
    fn as_ref(&self) -> &Curve25519PublicKey {
        &self.0
    }
}

impl From<&RatchetKey> for RatchetPublicKey {
    fn from(r: &RatchetKey) -> Self {
        RatchetPublicKey(Curve25519PublicKey::from(&r.0))
    }
}

/// Information about the root key ratchet, while our sender chain is active.
///
/// We only have one of these while the double ratchet is "active" - ie, while
/// we are encrypting messages. It stores the information necessary to calculate
/// the *next* root key; in particular, the root key of our active chain
/// `R`<sub>`i`</sub>, and our own ratchet key `T`<sub>`i`</sub>.
#[derive(Serialize, Deserialize, Clone)]
pub(super) struct Ratchet {
    root_key: RootKey,
    ratchet_key: RatchetKey,
}

impl Ratchet {
    pub fn new(root_key: RootKey) -> Self {
        let ratchet_key = RatchetKey::new();

        Self { root_key, ratchet_key }
    }

    pub const fn new_with_ratchet_key(root_key: RootKey, ratchet_key: RatchetKey) -> Self {
        Self { root_key, ratchet_key }
    }

    pub fn advance(&self, remote_key: RemoteRatchetKey) -> (RemoteRootKey, RemoteChainKey) {
        let (remote_root_key, remote_chain_key) =
            self.root_key.advance(&self.ratchet_key, &remote_key);

        (remote_root_key, remote_chain_key)
    }

    pub const fn ratchet_key(&self) -> &RatchetKey {
        &self.ratchet_key
    }
}

#[cfg(test)]
mod test {
    use super::RatchetKey;
    use crate::{olm::RatchetPublicKey, Curve25519SecretKey};

    #[test]
    fn ratchet_key_from_curve_25519_secret_key() {
        let bytes = b"aaaaaaaaaaaaaaawaaaaaaaaaaaaaaaa";
        let key = RatchetKey::from(Curve25519SecretKey::from_slice(bytes));
        assert_eq!(key.0.to_bytes().as_ref(), bytes);
    }

    #[test]
    fn ratchet_public_key_from_bytes() {
        let bytes = b"aaaaaaaaaaaaaaawaaaaaaaaaaaaaaaa";
        let key = RatchetPublicKey::from(*bytes);
        assert_eq!(key.0.to_bytes().as_ref(), bytes);
    }
}