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
// Copyright 2023 litep2p developers
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! Memory store implementation for Kademlia.

#![allow(unused)]
use crate::protocol::libp2p::kademlia::record::{Key, ProviderRecord, Record};

use std::{
    collections::{hash_map::Entry, HashMap},
    num::NonZeroUsize,
};

/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::ipfs::kademlia::store";

/// Memory store events.
pub enum MemoryStoreEvent {}

/// Memory store.
pub struct MemoryStore {
    /// Records.
    records: HashMap<Key, Record>,
    /// Provider records.
    provider_keys: HashMap<Key, Vec<ProviderRecord>>,
    /// Configuration.
    config: MemoryStoreConfig,
}

impl MemoryStore {
    /// Create new [`MemoryStore`].
    pub fn new() -> Self {
        Self {
            records: HashMap::new(),
            provider_keys: HashMap::new(),
            config: MemoryStoreConfig::default(),
        }
    }

    /// Create new [`MemoryStore`] with the provided configuration.
    pub fn with_config(config: MemoryStoreConfig) -> Self {
        Self {
            records: HashMap::new(),
            provider_keys: HashMap::new(),
            config,
        }
    }

    /// Try to get record from local store for `key`.
    pub fn get(&mut self, key: &Key) -> Option<&Record> {
        let is_expired = self
            .records
            .get(key)
            .map_or(false, |record| record.is_expired(std::time::Instant::now()));

        if is_expired {
            self.records.remove(key);
            None
        } else {
            self.records.get(key)
        }
    }

    /// Store record.
    pub fn put(&mut self, record: Record) {
        if record.value.len() >= self.config.max_record_size_bytes {
            tracing::warn!(
                target: LOG_TARGET,
                key = ?record.key,
                publisher = ?record.publisher,
                size = record.value.len(),
                max_size = self.config.max_record_size_bytes,
                "discarding a DHT record that exceeds the configured size limit",
            );
            return;
        }

        let len = self.records.len();
        match self.records.entry(record.key.clone()) {
            Entry::Occupied(mut entry) => {
                // Lean towards the new record.
                if let (Some(stored_record_ttl), Some(new_record_ttl)) =
                    (entry.get().expires, record.expires)
                {
                    if stored_record_ttl > new_record_ttl {
                        return;
                    }
                }

                entry.insert(record);
            }

            Entry::Vacant(entry) => {
                if len >= self.config.max_records {
                    tracing::warn!(
                        target: LOG_TARGET,
                        max_records = self.config.max_records,
                        "discarding a DHT record, because maximum memory store size reached",
                    );
                    return;
                }

                entry.insert(record);
            }
        }
    }

    /// Try to get providers from local store for `key`.
    ///
    /// Returns a non-empty list of providers, if any.
    pub fn get_providers(&mut self, key: &Key) -> Vec<ProviderRecord> {
        let drop = self.provider_keys.get_mut(key).map_or(false, |providers| {
            let now = std::time::Instant::now();
            providers.retain(|p| !p.is_expired(now));

            providers.is_empty()
        });

        if drop {
            self.provider_keys.remove(key);

            Vec::default()
        } else {
            self.provider_keys.get(key).cloned().unwrap_or_else(Vec::default)
        }
    }

    /// Try to add a provider for `key`. If there are already `max_providers_per_key` for
    /// this `key`, the new provider is only inserted if its closer to `key` than
    /// the furthest already inserted provider. The furthest provider is then discarded.
    ///
    /// Returns `true` if the provider was added, `false` otherwise.
    pub fn put_provider(&mut self, provider_record: ProviderRecord) -> bool {
        // Make sure we have no more than `max_provider_addresses`.
        let provider_record = {
            let mut record = provider_record;
            record.addresses.truncate(self.config.max_provider_addresses);
            record
        };

        let can_insert_new_key = self.provider_keys.len() < self.config.max_provider_keys;

        match self.provider_keys.entry(provider_record.key.clone()) {
            Entry::Vacant(entry) =>
                if can_insert_new_key {
                    entry.insert(vec![provider_record]);

                    true
                } else {
                    tracing::warn!(
                        target: LOG_TARGET,
                        max_provider_keys = self.config.max_provider_keys,
                        "discarding a provider record, because the provider key limit reached",
                    );

                    false
                },
            Entry::Occupied(mut entry) => {
                let mut providers = entry.get_mut();

                // Providers under every key are sorted by distance from the provided key, with
                // equal distances meaning peer IDs (more strictly, their hashes)
                // are equal.
                let provider_position =
                    providers.binary_search_by(|p| p.distance().cmp(&provider_record.distance()));

                match provider_position {
                    Ok(i) => {
                        // Update the provider in place.
                        providers[i] = provider_record;

                        true
                    }
                    Err(i) => {
                        // `Err(i)` contains the insertion point.
                        if i == self.config.max_providers_per_key {
                            tracing::trace!(
                                target: LOG_TARGET,
                                key = ?provider_record.key,
                                provider = ?provider_record.provider,
                                max_providers_per_key = self.config.max_providers_per_key,
                                "discarding a provider record, because it's further than \
                                 existing `max_providers_per_key`",
                            );

                            false
                        } else {
                            if providers.len() == self.config.max_providers_per_key {
                                providers.pop();
                            }

                            providers.insert(i, provider_record);

                            true
                        }
                    }
                }
            }
        }
    }

    /// Poll next event from the store.
    async fn next_event() -> Option<MemoryStoreEvent> {
        None
    }
}

pub struct MemoryStoreConfig {
    /// Maximum number of records to store.
    pub max_records: usize,

    /// Maximum size of a record in bytes.
    pub max_record_size_bytes: usize,

    /// Maximum number of provider keys this node stores.
    pub max_provider_keys: usize,

    /// Maximum number of cached addresses per provider.
    pub max_provider_addresses: usize,

    /// Maximum number of providers per key. Only providers with peer IDs closest to the key are
    /// kept.
    pub max_providers_per_key: usize,
}

impl Default for MemoryStoreConfig {
    fn default() -> Self {
        Self {
            max_records: 1024,
            max_record_size_bytes: 65 * 1024,
            max_provider_keys: 1024,
            max_provider_addresses: 30,
            max_providers_per_key: 20,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PeerId;
    use multiaddr::{
        multiaddr,
        Protocol::{Ip4, Tcp},
    };

    #[test]
    fn put_get_record() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let record = Record::new(key.clone(), vec![4, 5, 6]);

        store.put(record.clone());
        assert_eq!(store.get(&key), Some(&record));
    }

    #[test]
    fn max_records() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_records: 1,
            max_record_size_bytes: 1024,
            ..Default::default()
        });

        let key1 = Key::from(vec![1, 2, 3]);
        let key2 = Key::from(vec![4, 5, 6]);
        let record1 = Record::new(key1.clone(), vec![4, 5, 6]);
        let record2 = Record::new(key2.clone(), vec![7, 8, 9]);

        store.put(record1.clone());
        store.put(record2.clone());

        assert_eq!(store.get(&key1), Some(&record1));
        assert_eq!(store.get(&key2), None);
    }

    #[test]
    fn expired_record_removed() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let record = Record {
            key: key.clone(),
            value: vec![4, 5, 6],
            publisher: None,
            expires: Some(std::time::Instant::now() - std::time::Duration::from_secs(5)),
        };
        // Record is already expired.
        assert!(record.is_expired(std::time::Instant::now()));

        store.put(record.clone());
        assert_eq!(store.get(&key), None);
    }

    #[test]
    fn new_record_overwrites() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let record1 = Record {
            key: key.clone(),
            value: vec![4, 5, 6],
            publisher: None,
            expires: Some(std::time::Instant::now() + std::time::Duration::from_secs(100)),
        };
        let record2 = Record {
            key: key.clone(),
            value: vec![4, 5, 6],
            publisher: None,
            expires: Some(std::time::Instant::now() + std::time::Duration::from_secs(1000)),
        };

        store.put(record1.clone());
        assert_eq!(store.get(&key), Some(&record1));

        store.put(record2.clone());
        assert_eq!(store.get(&key), Some(&record2));
    }

    #[test]
    fn max_record_size() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_records: 1024,
            max_record_size_bytes: 2,
            ..Default::default()
        });

        let key = Key::from(vec![1, 2, 3]);
        let record = Record::new(key.clone(), vec![4, 5]);
        store.put(record.clone());
        assert_eq!(store.get(&key), None);

        let record = Record::new(key.clone(), vec![4]);
        store.put(record.clone());
        assert_eq!(store.get(&key), Some(&record));
    }

    #[test]
    fn put_get_provider() {
        let mut store = MemoryStore::new();
        let provider = ProviderRecord {
            key: Key::from(vec![1, 2, 3]),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        store.put_provider(provider.clone());
        assert_eq!(store.get_providers(&provider.key), vec![provider]);
    }

    #[test]
    fn multiple_providers_per_key() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let provider1 = ProviderRecord {
            key: key.clone(),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };
        let provider2 = ProviderRecord {
            key: key.clone(),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        store.put_provider(provider1.clone());
        store.put_provider(provider2.clone());

        let got_providers = store.get_providers(&key);
        assert_eq!(got_providers.len(), 2);
        assert!(got_providers.contains(&provider1));
        assert!(got_providers.contains(&provider2));
    }

    #[test]
    fn providers_sorted_by_distance() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let providers = (0..10)
            .map(|_| ProviderRecord {
                key: key.clone(),
                provider: PeerId::random(),
                addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
                expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
            })
            .collect::<Vec<_>>();

        providers.iter().for_each(|p| {
            store.put_provider(p.clone());
        });

        let sorted_providers = {
            let mut providers = providers;
            providers.sort_unstable_by_key(ProviderRecord::distance);
            providers
        };

        assert_eq!(store.get_providers(&key), sorted_providers);
    }

    #[test]
    fn max_providers_per_key() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_providers_per_key: 10,
            ..Default::default()
        });
        let key = Key::from(vec![1, 2, 3]);
        let providers = (0..20)
            .map(|_| ProviderRecord {
                key: key.clone(),
                provider: PeerId::random(),
                addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
                expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
            })
            .collect::<Vec<_>>();

        providers.iter().for_each(|p| {
            store.put_provider(p.clone());
        });
        assert_eq!(store.get_providers(&key).len(), 10);
    }

    #[test]
    fn closest_providers_kept() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_providers_per_key: 10,
            ..Default::default()
        });
        let key = Key::from(vec![1, 2, 3]);
        let providers = (0..20)
            .map(|_| ProviderRecord {
                key: key.clone(),
                provider: PeerId::random(),
                addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
                expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
            })
            .collect::<Vec<_>>();

        providers.iter().for_each(|p| {
            store.put_provider(p.clone());
        });

        let closest_providers = {
            let mut providers = providers;
            providers.sort_unstable_by_key(ProviderRecord::distance);
            providers.truncate(10);
            providers
        };

        assert_eq!(store.get_providers(&key), closest_providers);
    }

    #[test]
    fn furthest_provider_discarded() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_providers_per_key: 10,
            ..Default::default()
        });
        let key = Key::from(vec![1, 2, 3]);
        let providers = (0..11)
            .map(|_| ProviderRecord {
                key: key.clone(),
                provider: PeerId::random(),
                addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
                expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
            })
            .collect::<Vec<_>>();

        let sorted_providers = {
            let mut providers = providers;
            providers.sort_unstable_by_key(ProviderRecord::distance);
            providers
        };

        // First 10 providers are inserted.
        for i in 0..10 {
            assert!(store.put_provider(sorted_providers[i].clone()));
        }
        assert_eq!(store.get_providers(&key), sorted_providers[..10]);

        // The furthests provider doesn't fit.
        assert!(!store.put_provider(sorted_providers[10].clone()));
        assert_eq!(store.get_providers(&key), sorted_providers[..10]);
    }

    #[test]
    fn update_provider_in_place() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_providers_per_key: 10,
            ..Default::default()
        });
        let key = Key::from(vec![1, 2, 3]);
        let peer_ids = (0..10).map(|_| PeerId::random()).collect::<Vec<_>>();
        let peer_id0 = peer_ids[0];
        let providers = peer_ids
            .iter()
            .map(|peer_id| ProviderRecord {
                key: key.clone(),
                provider: *peer_id,
                addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
                expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
            })
            .collect::<Vec<_>>();

        providers.iter().for_each(|p| {
            store.put_provider(p.clone());
        });

        let sorted_providers = {
            let mut providers = providers;
            providers.sort_unstable_by_key(ProviderRecord::distance);
            providers
        };

        assert_eq!(store.get_providers(&key), sorted_providers);

        let provider0_new = ProviderRecord {
            key: key.clone(),
            provider: peer_id0,
            addresses: vec![multiaddr!(Ip4([192, 168, 0, 1]), Tcp(20000u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        // Provider is updated in place.
        assert!(store.put_provider(provider0_new.clone()));

        let providers_new = sorted_providers
            .into_iter()
            .map(|p| {
                if p.provider == peer_id0 {
                    provider0_new.clone()
                } else {
                    p
                }
            })
            .collect::<Vec<_>>();

        assert_eq!(store.get_providers(&key), providers_new);
    }

    #[test]
    fn provider_record_expires() {
        let mut store = MemoryStore::new();
        let provider = ProviderRecord {
            key: Key::from(vec![1, 2, 3]),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() - std::time::Duration::from_secs(5),
        };

        // Provider record is already expired.
        assert!(provider.is_expired(std::time::Instant::now()));

        store.put_provider(provider.clone());
        assert!(store.get_providers(&provider.key).is_empty());
    }

    #[test]
    fn individual_provider_record_expires() {
        let mut store = MemoryStore::new();
        let key = Key::from(vec![1, 2, 3]);
        let provider1 = ProviderRecord {
            key: key.clone(),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() - std::time::Duration::from_secs(5),
        };
        let provider2 = ProviderRecord {
            key: key.clone(),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        assert!(provider1.is_expired(std::time::Instant::now()));

        store.put_provider(provider1.clone());
        store.put_provider(provider2.clone());

        assert_eq!(store.get_providers(&key), vec![provider2]);
    }

    #[test]
    fn max_addresses_per_provider() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_provider_addresses: 2,
            ..Default::default()
        });
        let key = Key::from(vec![1, 2, 3]);
        let provider = ProviderRecord {
            key: Key::from(vec![1, 2, 3]),
            provider: PeerId::random(),
            addresses: vec![
                multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10000u16)),
                multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10001u16)),
                multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10002u16)),
                multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10003u16)),
                multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10004u16)),
            ],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        store.put_provider(provider);

        let got_providers = store.get_providers(&key);
        assert_eq!(got_providers.len(), 1);
        assert_eq!(got_providers.first().unwrap().key, key);
        assert_eq!(got_providers.first().unwrap().addresses.len(), 2);
    }

    #[test]
    fn max_provider_keys() {
        let mut store = MemoryStore::with_config(MemoryStoreConfig {
            max_provider_keys: 2,
            ..Default::default()
        });

        let provider1 = ProviderRecord {
            key: Key::from(vec![1, 2, 3]),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10001u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };
        let provider2 = ProviderRecord {
            key: Key::from(vec![4, 5, 6]),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10002u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };
        let provider3 = ProviderRecord {
            key: Key::from(vec![7, 8, 9]),
            provider: PeerId::random(),
            addresses: vec![multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10003u16))],
            expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
        };

        assert!(store.put_provider(provider1.clone()));
        assert!(store.put_provider(provider2.clone()));
        assert!(!store.put_provider(provider3.clone()));

        assert_eq!(store.get_providers(&provider1.key), vec![provider1]);
        assert_eq!(store.get_providers(&provider2.key), vec![provider2]);
        assert_eq!(store.get_providers(&provider3.key), vec![]);
    }
}