litep2p/protocol/libp2p/kademlia/
record.rs1use crate::{
23 protocol::libp2p::kademlia::types::{
24 ConnectionType, Distance, KademliaPeer, Key as KademliaKey,
25 },
26 transport::manager::address::{AddressRecord, AddressStore},
27 Multiaddr, PeerId,
28};
29
30use bytes::Bytes;
31use multihash::Multihash;
32
33use std::{borrow::Borrow, time::Instant};
34
35#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37#[cfg_attr(feature = "fuzz", derive(serde::Serialize, serde::Deserialize))]
38pub struct Key(Bytes);
39
40impl Key {
41 pub fn new<K: AsRef<[u8]>>(key: &K) -> Self {
43 Key(Bytes::copy_from_slice(key.as_ref()))
44 }
45
46 pub fn to_vec(&self) -> Vec<u8> {
48 Vec::from(&self.0[..])
49 }
50}
51
52impl From<Key> for Vec<u8> {
53 fn from(k: Key) -> Vec<u8> {
54 Vec::from(&k.0[..])
55 }
56}
57
58impl Borrow<[u8]> for Key {
59 fn borrow(&self) -> &[u8] {
60 &self.0[..]
61 }
62}
63
64impl AsRef<[u8]> for Key {
65 fn as_ref(&self) -> &[u8] {
66 &self.0[..]
67 }
68}
69
70impl From<Vec<u8>> for Key {
71 fn from(v: Vec<u8>) -> Key {
72 Key(Bytes::from(v))
73 }
74}
75
76impl From<Multihash> for Key {
77 fn from(m: Multihash) -> Key {
78 Key::from(m.to_bytes())
79 }
80}
81
82#[derive(Clone, Debug, Eq, PartialEq, Hash)]
84#[cfg_attr(feature = "fuzz", derive(serde::Serialize, serde::Deserialize))]
85pub struct Record {
86 pub key: Key,
88
89 pub value: Vec<u8>,
91
92 pub publisher: Option<PeerId>,
94
95 #[cfg_attr(feature = "fuzz", serde(with = "serde_millis"))]
97 pub expires: Option<Instant>,
98}
99
100impl Record {
101 pub fn new<K>(key: K, value: Vec<u8>) -> Self
103 where
104 K: Into<Key>,
105 {
106 Record {
107 key: key.into(),
108 value,
109 publisher: None,
110 expires: None,
111 }
112 }
113
114 pub fn is_expired(&self, now: Instant) -> bool {
116 self.expires.is_some_and(|t| now >= t)
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct PeerRecord {
123 pub peer: PeerId,
125
126 pub record: Record,
128}
129
130#[derive(Clone, Debug, Eq, PartialEq, Hash)]
132pub struct ProviderRecord {
133 pub key: Key,
135
136 pub provider: PeerId,
138
139 pub addresses: Vec<Multiaddr>,
141
142 pub expires: Instant,
145}
146
147impl ProviderRecord {
148 pub fn distance(&self) -> Distance {
150 KademliaKey::from(self.provider).distance(&KademliaKey::new(self.key.clone()))
153 }
154
155 pub fn is_expired(&self, now: Instant) -> bool {
157 now >= self.expires
158 }
159}
160
161#[derive(Clone, Debug, Eq, PartialEq, Hash)]
163pub struct ContentProvider {
164 pub peer: PeerId,
166
167 pub addresses: Vec<Multiaddr>,
169}
170
171impl From<ContentProvider> for KademliaPeer {
172 fn from(provider: ContentProvider) -> Self {
173 let mut address_store = AddressStore::new();
174 for address in provider.addresses.iter() {
175 address_store.insert(AddressRecord::from_raw_multiaddr(address.clone()));
176 }
177
178 Self {
179 key: KademliaKey::from(provider.peer),
180 peer: provider.peer,
181 address_store,
182 connection: ConnectionType::NotConnected,
183 }
184 }
185}