Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / third_party / betocore / np_adv / src / credential / book.rs

book.rs732 lines · 28.6 KiBRaw
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Traits defining credential books. These are used in the deserialization path to provide
16//! the credentials to try for either advertisement version.
17//! See [`CredentialBookBuilder`] for batteries-included implementations.
18
19use crate::credential::{
20 source::{CredentialSource, SliceCredentialSource},
21 v0::{V0DiscoveryCryptoMaterial, V0},
22 v1::{
23 MicExtendedSaltSectionIdentityResolutionMaterial,
24 MicExtendedSaltSectionVerificationMaterial, MicShortSaltSectionIdentityResolutionMaterial,
25 MicShortSaltSectionVerificationMaterial, V1DiscoveryCryptoMaterial, V1,
26 },
27 DiscoveryMetadataCryptoMaterial, MatchableCredential, MatchedCredential, ProtocolVersion,
28};
29use core::{borrow::Borrow, marker::PhantomData};
30use crypto_provider::CryptoProvider;
31
32#[cfg(any(feature = "alloc", test))]
33extern crate alloc;
34
35#[cfg(any(feature = "alloc", test))]
36use crate::credential::ReferencedMatchedCredential;
37#[cfg(any(feature = "alloc", test))]
38use alloc::vec::Vec;
39
40/// A collection of credentials to try when attempting to deserialize
41/// advertisements of either advertisement version which is
42/// valid for the given lifetime.
43pub trait CredentialBook<'a>
44where
45 Self: 'a,
46{
47 /// The type of the matched credentials for the credentials
48 /// held within this credential-book. May lend from the credential-book.
49 type Matched: MatchedCredential;
50
51 /// The type of V0 crypto-materials yielded by this credential-book.
52 type V0Crypto: V0DiscoveryCryptoMaterial;
53
54 /// The type of V1 crypto-materials yielded by this credential-book.
55 type V1Crypto: V1DiscoveryCryptoMaterial;
56
57 /// The iterator type returned from [`CredentialBook#v0_iter()`],
58 /// which yields `(crypto-material, match_data)` pairs.
59 /// This is a lending iterator which may borrow things from `self`.
60 type V0Iterator: Iterator<Item = (Self::V0Crypto, Self::Matched)>;
61
62 /// The iterator type returned from [`CredentialBook#v1_iter()`],
63 /// which yields `(crypto-material, match_data)` pairs.
64 /// This is a lending iterator which may borrow things from `self`.
65 type V1Iterator: Iterator<Item = (Self::V1Crypto, Self::Matched)>;
66
67 /// Returns an iterator over V0 credentials in this credential book.
68 fn v0_iter(&'a self) -> Self::V0Iterator;
69
70 /// Returns an iterator over V1 credentials in this credential book.
71 fn v1_iter(&'a self) -> Self::V1Iterator;
72}
73
74/// Convenient marker struct for building credential-books with
75/// some given match-data type.
76pub struct CredentialBookBuilder<M: MatchedCredential> {
77 _marker: PhantomData<M>,
78}
79
80impl<M: MatchedCredential> CredentialBookBuilder<M> {
81 /// Constructs a [`CachedSliceCredentialBook`] from the given slices of discovery credentials,
82 /// populating its internal buffers of cached credential crypto-materials for up to the
83 /// given number of credentials in each version (up to `N0` credentials cached in V0,
84 /// and up to `N1` credentials cached in `V1`.)
85 pub fn build_cached_slice_book<'a, const N0: usize, const N1: usize, P: CryptoProvider>(
86 v0_creds: &'a [MatchableCredential<V0, M>],
87 v1_creds: &'a [MatchableCredential<V1, M>],
88 ) -> CachedSliceCredentialBook<'a, M, N0, N1> {
89 let v0_source = SliceCredentialSource::new(v0_creds);
90 let v0_cache = init_cache_from_source::<V0, _, N0, P>(&v0_source);
91 let v0_source = CachedCredentialSource::<_, _, N0>::new(v0_source, v0_cache);
92
93 let v1_source = SliceCredentialSource::new(v1_creds);
94 let v1_cache = init_cache_from_source::<V1, _, N1, P>(&v1_source);
95 let v1_source = CachedCredentialSource::<_, _, N1>::new(v1_source, v1_cache);
96
97 CredentialBookFromSources::new(v0_source, v1_source)
98 }
99
100 #[cfg(feature = "alloc")]
101 /// Constructs a new credential-book which owns all of the given credentials,
102 /// and maintains pre-calculated cryptographic information about them
103 /// for speedy advertisement deserialization.
104 pub fn build_precalculated_owned_book<P: CryptoProvider>(
105 v0_iter: impl IntoIterator<Item = MatchableCredential<V0, M>>,
106 v1_iter: impl IntoIterator<Item = MatchableCredential<V1, M>>,
107 ) -> PrecalculatedOwnedCredentialBook<M> {
108 let v0_source = PrecalculatedOwnedCredentialSource::<V0, M>::new::<P>(v0_iter);
109 let v1_source = PrecalculatedOwnedCredentialSource::<V1, M>::new::<P>(v1_iter);
110 CredentialBookFromSources::new(v0_source, v1_source)
111 }
112
113 #[cfg(feature = "alloc")]
114 /// Constructs a new credential-book which owns all of the given credentials,
115 /// and maintains pre-calculated cryptographic information about them
116 /// for speedy advertisement deserialization.
117 pub fn build_precalculated_owned_book_with_id<P: CryptoProvider>(
118 v0_iter: impl IntoIterator<Item = MatchableCredential<V0, M>>,
119 v1_iter: impl IntoIterator<Item = MatchableCredential<V1, M>>,
120 ) -> PrecalculatedOwnedCredentialBookWithId<M>
121 where
122 M: MatchedCredential + Clone,
123 {
124 let v0_source = PrecalculatedOwnedV0CredentialSourceWithId::<M>::new::<P>(v0_iter);
125 let v1_source = PrecalculatedOwnedV1CredentialSourceWithId::<M>::new::<P>(v1_iter);
126 CredentialBookFromSources::new(v0_source, v1_source)
127 }
128}
129
130// Now, for the implementation details. External implementors still need
131// to be able to reference these types (since the returned types from
132// [`CredentialBookBuilder`]'s convenience methods are just type-aliases),
133// and if they want, they can use them as building-blocks to construct
134// their own [`CredentialBook`]s, but they're largely just scaffolding.
135
136/// A structure bundling both V0 and V1 credential-sources to define
137/// a credential-book which owns both of these independent sources.
138pub struct CredentialBookFromSources<S0, S1> {
139 /// The source for V0 credentials.
140 v0_source: S0,
141 /// The source for V1 credentials.
142 v1_source: S1,
143}
144
145impl<'a, S0, S1> CredentialBookFromSources<S0, S1>
146where
147 Self: 'a,
148 S0: CredentialSource<'a, V0>,
149 S1: CredentialSource<'a, V1, Matched = <S0 as CredentialSource<'a, V0>>::Matched>,
150 <S0 as CredentialSource<'a, V0>>::Crypto: V0DiscoveryCryptoMaterial,
151 <S1 as CredentialSource<'a, V1>>::Crypto: V1DiscoveryCryptoMaterial,
152{
153 /// Constructs a new [`CredentialBook`] out of the two given
154 /// credential-sources, one for v0 and one for v1. The match-data
155 /// of both credential sources must be the same.
156 pub fn new(v0_source: S0, v1_source: S1) -> Self {
157 Self { v0_source, v1_source }
158 }
159}
160
161impl<'a, S0, S1> CredentialBook<'a> for CredentialBookFromSources<S0, S1>
162where
163 Self: 'a,
164 S0: CredentialSource<'a, V0>,
165 S1: CredentialSource<'a, V1, Matched = <S0 as CredentialSource<'a, V0>>::Matched>,
166 <S0 as CredentialSource<'a, V0>>::Crypto: V0DiscoveryCryptoMaterial,
167 <S1 as CredentialSource<'a, V1>>::Crypto: V1DiscoveryCryptoMaterial,
168{
169 type Matched = <S0 as CredentialSource<'a, V0>>::Matched;
170 type V0Crypto = <S0 as CredentialSource<'a, V0>>::Crypto;
171 type V1Crypto = <S1 as CredentialSource<'a, V1>>::Crypto;
172 type V0Iterator = <S0 as CredentialSource<'a, V0>>::Iterator;
173 type V1Iterator = <S1 as CredentialSource<'a, V1>>::Iterator;
174
175 fn v0_iter(&'a self) -> Self::V0Iterator {
176 self.v0_source.iter()
177 }
178 fn v1_iter(&'a self) -> Self::V1Iterator {
179 self.v1_source.iter()
180 }
181}
182
183/// Type-level function used internally
184/// by [`CachedCredentialSource`] in order to uniformly
185/// refer to the "precalculated" crypto-material variants
186/// for each protocol version.
187pub(crate) mod precalculated_for_version {
188 use crate::credential::{
189 v0::{PrecalculatedV0DiscoveryCryptoMaterial, V0DiscoveryCredential, V0},
190 v1::{PrecalculatedV1DiscoveryCryptoMaterial, V1DiscoveryCredential, V1},
191 DiscoveryMetadataCryptoMaterial, ProtocolVersion,
192 };
193 use crypto_provider::CryptoProvider;
194
195 pub trait MappingTrait<V: ProtocolVersion> {
196 type Output: DiscoveryMetadataCryptoMaterial<V>;
197 /// Provides pre-calculated crypto-material for the given
198 /// discovery credential.
199 fn precalculate<C: CryptoProvider>(
200 discovery_credential: &V::DiscoveryCredential,
201 ) -> Self::Output;
202 }
203
204 pub enum Marker {}
205
206 impl MappingTrait<V0> for Marker {
207 type Output = PrecalculatedV0DiscoveryCryptoMaterial;
208 fn precalculate<C: CryptoProvider>(
209 discovery_credential: &V0DiscoveryCredential,
210 ) -> PrecalculatedV0DiscoveryCryptoMaterial {
211 PrecalculatedV0DiscoveryCryptoMaterial::new::<C>(discovery_credential)
212 }
213 }
214
215 impl MappingTrait<V1> for Marker {
216 type Output = PrecalculatedV1DiscoveryCryptoMaterial;
217 fn precalculate<C: CryptoProvider>(
218 discovery_credential: &V1DiscoveryCredential,
219 ) -> PrecalculatedV1DiscoveryCryptoMaterial {
220 discovery_credential.to_precalculated::<C>()
221 }
222 }
223}
224
225type PrecalculatedCryptoForProtocolVersion<V> =
226 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<V>>::Output;
227
228fn precalculate_crypto_material<V: ProtocolVersion, C: CryptoProvider>(
229 discovery_credential: &V::DiscoveryCredential,
230) -> PrecalculatedCryptoForProtocolVersion<V>
231where
232 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
233{
234 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<V>>::precalculate::<
235 C,
236 >(discovery_credential)
237}
238
239/// Iterator type for [`CachedCredentialSource`].
240pub struct CachedCredentialSourceIterator<'a, V, S, const N: usize>
241where
242 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
243 V: ProtocolVersion + 'a,
244 S: CredentialSource<'a, V> + 'a,
245 S::Crypto: Borrow<V::DiscoveryCredential>,
246{
247 /// The current index of the (enumerated) elements that we're iterating over.
248 /// Always counts up at every iteration, and may lie outside of the range
249 /// of the `cache` slice for uncached elements.
250 current_index: usize,
251 /// The cache of pre-calculated crypto-materials from the original source.
252 ///
253 /// The [`self.source_iterator`]'s (up-to) first `N` elements
254 /// must match (up-to) the first `N` elements in the cache,
255 /// and they must both appear in the same order.
256 cache: &'a [Option<PrecalculatedCryptoForProtocolVersion<V>>; N],
257 /// The iterator over the credentials in the original source
258 source_iterator: S::Iterator,
259}
260
261impl<'a, V, S, const N: usize> Iterator for CachedCredentialSourceIterator<'a, V, S, N>
262where
263 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
264 V: ProtocolVersion + 'a,
265 S: CredentialSource<'a, V> + 'a,
266 S::Crypto: Borrow<V::DiscoveryCredential>,
267{
268 type Item = (PossiblyCachedDiscoveryCryptoMaterial<'a, V>, S::Matched);
269 fn next(&mut self) -> Option<Self::Item> {
270 // Regardless of what we're going to do with the crypto-materials, we still need
271 // to advance the underlying iterator, and bail if it runs out.
272 let (discovery_credential, match_data) = self.source_iterator.next()?;
273 // Check whether/not we have cached crypto-material for the current index
274 let crypto = match self.cache.get(self.current_index) {
275 Some(precalculated_crypto_entry) => {
276 let precalculated_crypto = precalculated_crypto_entry
277 .as_ref()
278 .expect("iterator still going, but cache is not full?");
279 PossiblyCachedDiscoveryCryptoMaterial::from_precalculated(precalculated_crypto)
280 }
281 None => PossiblyCachedDiscoveryCryptoMaterial::from_discovery_credential(
282 discovery_credential.borrow().clone(),
283 ),
284 };
285 // Advance the index forward to point to the next item in the cache.
286 self.current_index += 1;
287 Some((crypto, match_data))
288 }
289}
290
291/// A [`CredentialSource`] which augments the externally-provided [`CredentialSource`] with
292/// a cache containing up to the specified number of pre-calculated credentials.
293pub struct CachedCredentialSource<V: ProtocolVersion, S, const N: usize>
294where
295 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
296{
297 wrapped: S,
298 cache: [Option<PrecalculatedCryptoForProtocolVersion<V>>; N],
299}
300
301/// Helper function to construct a cache for a [`CachedCredentialSource`] from
302/// a reference to some source of discovery-credentials.
303///
304/// This function needs to be kept separate from [`CachedCredentialSource#new`]
305/// to get around otherwise-tricky lifetime issues around ephemerally-borrowing
306/// from a moved object within the body of a function.
307pub(crate) fn init_cache_from_source<'a, V: ProtocolVersion, S, const N: usize, P: CryptoProvider>(
308 original: &'a S,
309) -> [Option<PrecalculatedCryptoForProtocolVersion<V>>; N]
310where
311 S: CredentialSource<'a, V> + 'a,
312 S::Crypto: Borrow<V::DiscoveryCredential>,
313 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
314{
315 let mut cache = [0u8; N].map(|_| None);
316 for (cache_entry, source_credential) in cache.iter_mut().zip(original.iter()) {
317 let (discovery_credential, _) = source_credential;
318 let precalculated_crypto_material =
319 precalculate_crypto_material::<V, P>(discovery_credential.borrow());
320 let _ = cache_entry.insert(precalculated_crypto_material);
321 }
322 cache
323}
324
325impl<'a, V: ProtocolVersion, S, const N: usize> CachedCredentialSource<V, S, N>
326where
327 S: CredentialSource<'a, V> + 'a,
328 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
329{
330 /// Constructs a [`CachedCredentialSource`] from the given [`CredentialSource`]
331 /// and the given (initial) cache contents, as constructed via the
332 /// [`init_cache_from_source`] helper function.
333 pub(crate) fn new(
334 wrapped: S,
335 cache: [Option<PrecalculatedCryptoForProtocolVersion<V>>; N],
336 ) -> Self {
337 Self { wrapped, cache }
338 }
339}
340
341/// Internal implementation of [`PossiblyCachedDiscoveryCryptoMaterial`] to hide
342/// what crypto-material variants we're actually storing in cached
343/// credential-books.
344pub(crate) enum PossiblyCachedDiscoveryCryptoMaterialKind<'a, V: ProtocolVersion>
345where
346 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
347{
348 Discovery(V::DiscoveryCredential),
349 Precalculated(&'a PrecalculatedCryptoForProtocolVersion<V>),
350}
351
352/// Crypto-materials that are potentially references to
353/// already-cached precomputed variants, or raw discovery
354/// credentials.
355pub struct PossiblyCachedDiscoveryCryptoMaterial<'a, V: ProtocolVersion>
356where
357 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
358{
359 pub(crate) wrapped: PossiblyCachedDiscoveryCryptoMaterialKind<'a, V>,
360}
361
362impl<'a, V: ProtocolVersion> PossiblyCachedDiscoveryCryptoMaterial<'a, V>
363where
364 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
365{
366 fn from_discovery_credential(discovery_credential: V::DiscoveryCredential) -> Self {
367 Self { wrapped: PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(discovery_credential) }
368 }
369 fn from_precalculated(precalculated: &'a PrecalculatedCryptoForProtocolVersion<V>) -> Self {
370 Self { wrapped: PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(precalculated) }
371 }
372}
373
374impl<V: ProtocolVersion> DiscoveryMetadataCryptoMaterial<V>
375 for PossiblyCachedDiscoveryCryptoMaterial<'_, V>
376where
377 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
378{
379 fn metadata_nonce<C: CryptoProvider>(&self) -> [u8; 12] {
380 match &self.wrapped {
381 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => x.metadata_nonce::<C>(),
382 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => x.metadata_nonce::<C>(),
383 }
384 }
385}
386
387impl V0DiscoveryCryptoMaterial for PossiblyCachedDiscoveryCryptoMaterial<'_, V0> {
388 fn ldt_adv_cipher<C: CryptoProvider>(&self) -> ldt_np_adv::AuthenticatedNpLdtDecryptCipher<C> {
389 match &self.wrapped {
390 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => x.ldt_adv_cipher::<C>(),
391 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => x.ldt_adv_cipher::<C>(),
392 }
393 }
394}
395
396impl V1DiscoveryCryptoMaterial for PossiblyCachedDiscoveryCryptoMaterial<'_, V1> {
397 fn mic_short_salt_identity_resolution_material<C: CryptoProvider>(
398 &self,
399 ) -> MicShortSaltSectionIdentityResolutionMaterial {
400 match &self.wrapped {
401 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => {
402 x.mic_short_salt_identity_resolution_material::<C>()
403 }
404 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => {
405 x.mic_short_salt_identity_resolution_material::<C>()
406 }
407 }
408 }
409
410 fn mic_extended_salt_identity_resolution_material<C: CryptoProvider>(
411 &self,
412 ) -> MicExtendedSaltSectionIdentityResolutionMaterial {
413 match &self.wrapped {
414 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => {
415 x.mic_extended_salt_identity_resolution_material::<C>()
416 }
417 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => {
418 x.mic_extended_salt_identity_resolution_material::<C>()
419 }
420 }
421 }
422
423 fn mic_short_salt_verification_material<C: CryptoProvider>(
424 &self,
425 ) -> MicShortSaltSectionVerificationMaterial {
426 match &self.wrapped {
427 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => {
428 x.mic_short_salt_verification_material::<C>()
429 }
430 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => {
431 x.mic_short_salt_verification_material::<C>()
432 }
433 }
434 }
435
436 fn mic_extended_salt_verification_material<C: CryptoProvider>(
437 &self,
438 ) -> MicExtendedSaltSectionVerificationMaterial {
439 match &self.wrapped {
440 PossiblyCachedDiscoveryCryptoMaterialKind::Discovery(x) => {
441 x.mic_extended_salt_verification_material::<C>()
442 }
443 PossiblyCachedDiscoveryCryptoMaterialKind::Precalculated(x) => {
444 x.mic_extended_salt_verification_material::<C>()
445 }
446 }
447 }
448}
449
450impl<'a, V: ProtocolVersion, S, const N: usize> CredentialSource<'a, V>
451 for CachedCredentialSource<V, S, N>
452where
453 Self: 'a,
454 S: CredentialSource<'a, V> + 'a,
455 S::Crypto: Borrow<V::DiscoveryCredential>,
456 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
457 PossiblyCachedDiscoveryCryptoMaterial<'a, V>: DiscoveryMetadataCryptoMaterial<V>,
458{
459 type Matched = <S as CredentialSource<'a, V>>::Matched;
460 type Crypto = PossiblyCachedDiscoveryCryptoMaterial<'a, V>;
461 type Iterator = CachedCredentialSourceIterator<'a, V, S, N>;
462
463 fn iter(&'a self) -> Self::Iterator {
464 CachedCredentialSourceIterator {
465 current_index: 0,
466 cache: &self.cache,
467 source_iterator: self.wrapped.iter(),
468 }
469 }
470}
471
472/// A simple credentials source for environments which are,
473/// for all practical purposes, not space-constrained, and hence
474/// can store an arbitrary amount of pre-calculated crypto-materials.
475///
476/// Requires `alloc` as a result of internally leveraging a `Vec`.
477#[cfg(any(feature = "alloc", test))]
478pub struct PrecalculatedOwnedCredentialSource<V: ProtocolVersion, M: MatchedCredential>
479where
480 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
481{
482 credentials: Vec<(PrecalculatedCryptoForProtocolVersion<V>, M)>,
483}
484
485#[cfg(any(feature = "alloc", test))]
486impl<V: ProtocolVersion, M: MatchedCredential> PrecalculatedOwnedCredentialSource<V, M>
487where
488 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
489{
490 /// Pre-calculates crypto material for the given credentials, and constructs a
491 /// credentials source which holds owned copies of this crypto-material.
492 pub fn new<P: CryptoProvider>(
493 credential_iter: impl IntoIterator<Item = MatchableCredential<V, M>>,
494 ) -> Self {
495 let credentials = credential_iter
496 .into_iter()
497 .map(|credential| {
498 (
499 precalculate_crypto_material::<V, P>(&credential.discovery_credential),
500 credential.match_data,
501 )
502 })
503 .collect();
504 Self { credentials }
505 }
506}
507
508#[cfg(any(feature = "alloc", test))]
509fn reference_crypto_and_match_data<C, M: MatchedCredential>(
510 pair_ref: &(C, M),
511) -> (&C, ReferencedMatchedCredential<'_, M>) {
512 let (c, m) = pair_ref;
513 (c, m.into())
514}
515
516#[cfg(any(feature = "alloc", test))]
517impl<'a, V: ProtocolVersion, M: MatchedCredential> CredentialSource<'a, V>
518 for PrecalculatedOwnedCredentialSource<V, M>
519where
520 Self: 'a,
521 precalculated_for_version::Marker: precalculated_for_version::MappingTrait<V>,
522 &'a PrecalculatedCryptoForProtocolVersion<V>: DiscoveryMetadataCryptoMaterial<V>,
523{
524 type Matched = ReferencedMatchedCredential<'a, M>;
525 type Crypto = &'a PrecalculatedCryptoForProtocolVersion<V>;
526 type Iterator = core::iter::Map<
527 core::slice::Iter<'a, (PrecalculatedCryptoForProtocolVersion<V>, M)>,
528 fn(
529 &'a (PrecalculatedCryptoForProtocolVersion<V>, M),
530 )
531 -> (&'a PrecalculatedCryptoForProtocolVersion<V>, ReferencedMatchedCredential<'a, M>),
532 >;
533
534 fn iter(&'a self) -> Self::Iterator {
535 self.credentials.iter().map(reference_crypto_and_match_data)
536 }
537}
538
539/// Type-alias for credential sources which are provided via slice credential-sources
540/// with a pre-calculated credential cache layered on top.
541pub type CachedSliceCredentialSource<'a, V, M, const N: usize> =
542 CachedCredentialSource<V, SliceCredentialSource<'a, V, M>, N>;
543
544/// A [`CredentialBook`] whose sources for V0 and V1 credentials come from the given slices
545/// of discovery credentials, with crypto-materials for up to the given number of credentials
546/// from the beginning of each slice kept in an in-memory cache.
547pub type CachedSliceCredentialBook<'a, M, const N0: usize, const N1: usize> =
548 CredentialBookFromSources<
549 CachedSliceCredentialSource<'a, V0, M, N0>,
550 CachedSliceCredentialSource<'a, V1, M, N1>,
551 >;
552
553#[cfg(any(feature = "alloc", test))]
554/// A credential-book which owns all of its (non-matched) credential data,
555/// and maintains pre-calculated cryptographic information about all
556/// stored credentials for speedy advertisement deserialization.
557///
558/// Use this credential book if memory usage is not terribly tight,
559/// and you're operating in an environment with an allocator.
560pub type PrecalculatedOwnedCredentialBook<M> = CredentialBookFromSources<
561 PrecalculatedOwnedCredentialSource<V0, M>,
562 PrecalculatedOwnedCredentialSource<V1, M>,
563>;
564
565#[cfg(any(feature = "alloc", test))]
566/// A credential-book which owns all of its (non-matched) credential data,
567/// and maintains pre-calculated cryptographic information about all
568/// stored credentials for speedy advertisement deserialization.
569pub type PrecalculatedOwnedCredentialBookWithId<M> = CredentialBookFromSources<
570 PrecalculatedOwnedV0CredentialSourceWithId<M>,
571 PrecalculatedOwnedV1CredentialSourceWithId<M>,
572>;
573
574#[cfg(any(feature = "alloc", test))]
575/// A simple credentials source that holds owned, pre-calculated V0 crypto-materials.
576pub struct PrecalculatedOwnedV0CredentialSourceWithId<M: MatchedCredential> {
577 credentials:
578 Vec<
579 (
580 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
581 V0,
582 >>::Output,
583 M,
584 ),
585 >,
586}
587
588#[cfg(any(feature = "alloc", test))]
589impl<M: MatchedCredential + Clone> PrecalculatedOwnedV0CredentialSourceWithId<M> {
590 /// Pre-calculates crypto material for the given credentials and constructs a
591 /// new source which owns this crypto-material.
592 pub fn new<P: CryptoProvider>(
593 credential_iter: impl IntoIterator<Item = MatchableCredential<V0, M>>,
594 ) -> Self {
595 let credentials = credential_iter
596 .into_iter()
597 .map(|credential| {
598 (
599 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
600 V0,
601 >>::precalculate::<P>(&credential.discovery_credential),
602 credential.match_data,
603 )
604 })
605 .collect();
606 Self { credentials }
607 }
608}
609
610#[cfg(any(feature = "alloc", test))]
611/// A simple credentials source that holds owned, pre-calculated V1 crypto-materials.
612pub struct PrecalculatedOwnedV1CredentialSourceWithId<M: MatchedCredential> {
613 credentials:
614 Vec<
615 (
616 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
617 V1,
618 >>::Output,
619 M,
620 ),
621 >,
622}
623
624#[cfg(any(feature = "alloc", test))]
625impl<M: MatchedCredential + Clone> PrecalculatedOwnedV1CredentialSourceWithId<M> {
626 /// Pre-calculates crypto material for the given credentials and constructs a
627 /// new source which owns this crypto-material.
628 pub fn new<P: CryptoProvider>(
629 credential_iter: impl IntoIterator<Item = MatchableCredential<V1, M>>,
630 ) -> Self {
631 let credentials = credential_iter
632 .into_iter()
633 .map(|credential| {
634 (
635 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
636 V1,
637 >>::precalculate::<P>(&credential.discovery_credential),
638 credential.match_data,
639 )
640 })
641 .collect();
642 Self { credentials }
643 }
644}
645
646#[cfg(any(feature = "alloc", test))]
647/// Mapping function for the iterator to return a reference to the crypto material
648/// and a clone of the match data.
649fn crypto_and_cloned_match_data<C, M: MatchedCredential + Clone>(pair_ref: &(C, M)) -> (&C, M) {
650 let (c, m) = pair_ref;
651 (c, m.clone())
652}
653
654#[cfg(any(feature = "alloc", test))]
655impl<'a, M: MatchedCredential + Clone> CredentialSource<'a, V0>
656 for PrecalculatedOwnedV0CredentialSourceWithId<M>
657where
658 Self: 'a,
659{
660 type Matched = M;
661 type Crypto = &'a <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
662 V0,
663 >>::Output;
664 type Iterator = core::iter::Map<
665 core::slice::Iter<
666 'a,
667 (
668 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
669 V0,
670 >>::Output,
671 M,
672 ),
673 >,
674 fn(
675 &'a (
676 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
677 V0,
678 >>::Output,
679 M,
680 ),
681 ) -> (
682 &'a <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
683 V0,
684 >>::Output,
685 M,
686 ),
687 >;
688
689 fn iter(&'a self) -> Self::Iterator {
690 self.credentials.iter().map(crypto_and_cloned_match_data)
691 }
692}
693
694#[cfg(any(feature = "alloc", test))]
695impl<'a, M: MatchedCredential + Clone> CredentialSource<'a, V1>
696 for PrecalculatedOwnedV1CredentialSourceWithId<M>
697where
698 Self: 'a,
699{
700 type Matched = M;
701 type Crypto = &'a <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
702 V1,
703 >>::Output;
704 type Iterator = core::iter::Map<
705 core::slice::Iter<
706 'a,
707 (
708 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
709 V1,
710 >>::Output,
711 M,
712 ),
713 >,
714 fn(
715 &'a (
716 <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
717 V1,
718 >>::Output,
719 M,
720 ),
721 ) -> (
722 &'a <precalculated_for_version::Marker as precalculated_for_version::MappingTrait<
723 V1,
724 >>::Output,
725 M,
726 ),
727 >;
728
729 fn iter(&'a self) -> Self::Iterator {
730 self.credentials.iter().map(crypto_and_cloned_match_data)
731 }
732}