@@ -26,7 +26,27 @@ use crate::olm::{
2626 session_config:: Version ,
2727} ;
2828
29+ /// The maximum number of message keys that can be skipped in a single receiver
30+ /// chain.
2931pub ( crate ) const MAX_MESSAGE_GAP : u64 = 2000 ;
32+
33+ /// The maximum number of message keys to retain when messages arrive out of
34+ /// order.
35+ ///
36+ /// For example, if we receive a message with chain index 2, we will cache the
37+ /// skipped message keys for chain indices 0 and 1.
38+ ///
39+ /// This limit applies per receiver chain. With the current configuration,
40+ /// that results in storing up to 200 skipped message keys in total.
41+ ///
42+ /// Matrix servers buffer messages and generally attempt to deliver them in
43+ /// send order. In practice, this limit does not need to be higher. Increasing
44+ /// it would add risk without providing any meaningful benefit.
45+ /// The number of message keys we'll store if we receive an out of order
46+ /// message.
47+ ///
48+ /// More info on the tradeoffs can be found in the double ratchet spec:
49+ /// https://signal.org/docs/specifications/doubleratchet/#deletion-of-skipped-message-keys
3050pub ( crate ) const MAX_MESSAGE_KEYS : usize = 40 ;
3151
3252#[ derive( Serialize , Deserialize , Clone ) ]
@@ -180,8 +200,18 @@ impl ReceiverChain {
180200 // Advance the ratchet up until our desired point.
181201 while ratchet. chain_index ( ) < chain_index {
182202 if chain_index - ratchet. chain_index ( ) > MAX_MESSAGE_KEYS as u64 {
203+ // If we're still too many messages away for us to save the skipped message
204+ // keys just advance the ratchet by one index. This avoids the expansion of a
205+ // message key we're going to throw away.
206+ //
207+ // NOTE: Messages that were encrypted with the chain index of this loop
208+ // iteration will not have their message key anymore around. This does not mean
209+ // that any messages new messages, following the message at `chain_index`, will
210+ // be undecryptable.
183211 ratchet. advance ( ) ;
184212 } else {
213+ // Otherwise advance the ratchet using the `create_message_key()` method and
214+ // store the skipped key.
185215 let key = ratchet. create_message_key ( ) ;
186216 skipped_keys. push ( key) ;
187217 }
0 commit comments