|
| 1 | +// SPDX-License-Identifier: CC0-1.0 |
| 2 | + |
| 3 | +//! A map of public key to secret key. |
| 4 | +
|
| 5 | +use core::iter; |
| 6 | + |
| 7 | +use bitcoin::secp256k1::{Secp256k1, Signing}; |
| 8 | + |
| 9 | +#[cfg(doc)] |
| 10 | +use super::Descriptor; |
| 11 | +use super::{DescriptorKeyParseError, DescriptorPublicKey, DescriptorSecretKey}; |
| 12 | +use crate::prelude::{btree_map, BTreeMap}; |
| 13 | + |
| 14 | +/// Alias type for a map of public key to secret key. |
| 15 | +/// |
| 16 | +/// This map is returned whenever a descriptor that contains secrets is parsed using |
| 17 | +/// [`Descriptor::parse_descriptor`], since the descriptor will always only contain |
| 18 | +/// public keys. This map allows looking up the corresponding secret key given a |
| 19 | +/// public key from the descriptor. |
| 20 | +#[derive(Debug, Clone, Eq, PartialEq)] |
| 21 | +pub struct KeyMap { |
| 22 | + map: BTreeMap<DescriptorPublicKey, DescriptorSecretKey>, |
| 23 | +} |
| 24 | + |
| 25 | +impl KeyMap { |
| 26 | + /// Creates a new empty `KeyMap`. |
| 27 | + #[inline] |
| 28 | + pub fn new() -> Self { Self { map: BTreeMap::new() } } |
| 29 | + |
| 30 | + /// Inserts secret key into key map returning the associated public key. |
| 31 | + #[inline] |
| 32 | + pub fn insert<C: Signing>( |
| 33 | + &mut self, |
| 34 | + secp: &Secp256k1<C>, |
| 35 | + sk: DescriptorSecretKey, |
| 36 | + ) -> Result<DescriptorPublicKey, DescriptorKeyParseError> { |
| 37 | + let pk = sk.to_public(secp)?; |
| 38 | + if !self.map.contains_key(&pk) { |
| 39 | + self.map.insert(pk.clone(), sk); |
| 40 | + } |
| 41 | + Ok(pk) |
| 42 | + } |
| 43 | + |
| 44 | + /// Gets the secret key associated with `pk` if `pk` is in the map. |
| 45 | + #[inline] |
| 46 | + pub fn get(&self, pk: &DescriptorPublicKey) -> Option<&DescriptorSecretKey> { self.map.get(pk) } |
| 47 | + |
| 48 | + /// Returns the number of items in this map. |
| 49 | + #[inline] |
| 50 | + pub fn len(&self) -> usize { self.map.len() } |
| 51 | + |
| 52 | + /// Returns true if the map is empty. |
| 53 | + #[inline] |
| 54 | + pub fn is_empty(&self) -> bool { self.map.is_empty() } |
| 55 | +} |
| 56 | + |
| 57 | +impl Default for KeyMap { |
| 58 | + fn default() -> Self { Self::new() } |
| 59 | +} |
| 60 | + |
| 61 | +impl IntoIterator for KeyMap { |
| 62 | + type Item = (DescriptorPublicKey, DescriptorSecretKey); |
| 63 | + type IntoIter = btree_map::IntoIter<DescriptorPublicKey, DescriptorSecretKey>; |
| 64 | + |
| 65 | + #[inline] |
| 66 | + fn into_iter(self) -> Self::IntoIter { self.map.into_iter() } |
| 67 | +} |
| 68 | + |
| 69 | +impl iter::Extend<(DescriptorPublicKey, DescriptorSecretKey)> for KeyMap { |
| 70 | + #[inline] |
| 71 | + fn extend<T>(&mut self, iter: T) |
| 72 | + where |
| 73 | + T: IntoIterator<Item = (DescriptorPublicKey, DescriptorSecretKey)>, |
| 74 | + { |
| 75 | + self.map.extend(iter) |
| 76 | + } |
| 77 | +} |
0 commit comments