// SPDX-License-Identifier: CC0-1.0 //! Raw PSBT key-value pairs. //! //! Raw PSBT key-value pairs as defined at //! . use core::fmt; use internals::ToU64 as _; use io::{BufRead, Write}; use super::serialize::{Deserialize, Serialize}; use crate::consensus::encode::{ self, deserialize, serialize, Decodable, Encodable, ReadExt, WriteExt, MAX_VEC_SIZE, }; use crate::prelude::{DisplayHex, Vec}; use crate::psbt::Error; /// A PSBT key in its raw byte form. /// /// ` := ` #[derive(Debug, PartialEq, Hash, Eq, Clone, Ord, PartialOrd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Key { /// The type of this PSBT key. pub type_value: u64, // Encoded as a compact size. /// The key data itself in raw byte form. #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))] pub key_data: Vec, } /// A PSBT key-value pair in its raw byte form. /// ` := ` #[derive(Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Pair { /// The key of this key-value pair. pub key: Key, /// The value data of this key-value pair in raw byte form. /// ` := ` #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))] pub value: Vec, } /// Default implementation for proprietary key subtyping pub type ProprietaryType = u64; /// Proprietary keys (i.e. keys starting with 0xFC byte) with their internal /// structure according to BIP 174. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct ProprietaryKey where Subtype: Copy + From + Into, { /// Proprietary type prefix used for grouping together keys under some /// application and avoid namespace collision #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))] pub prefix: Vec, /// Custom proprietary subtype pub subtype: Subtype, /// Additional key bytes (like serialized public key data etc) #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))] pub key: Vec, } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "type: {:#x}, key: {:x}", self.type_value, self.key_data.as_hex()) } } impl Key { pub(crate) fn decode(r: &mut R) -> Result { let byte_size = r.read_compact_size()?; if byte_size == 0 { return Err(Error::NoMorePairs); } let key_byte_size: u64 = byte_size - 1; if key_byte_size > MAX_VEC_SIZE.to_u64() { return Err(encode::Error::Parse(encode::ParseError::OversizedVectorAllocation { requested: key_byte_size as usize, max: MAX_VEC_SIZE, }) .into()); } let type_value = r.read_compact_size()?; let mut key_data = Vec::with_capacity(key_byte_size as usize); for _ in 0..key_byte_size { key_data.push(Decodable::consensus_decode(r)?); } Ok(Key { type_value, key_data }) } } impl Serialize for Key { fn serialize(&self) -> Vec { let mut buf = Vec::new(); buf.emit_compact_size(self.key_data.len() + 1).expect("in-memory writers don't error"); buf.emit_compact_size(self.type_value).expect("in-memory writers don't error"); for key in &self.key_data { key.consensus_encode(&mut buf).expect("in-memory writers don't error"); } buf } } impl Serialize for Pair { fn serialize(&self) -> Vec { let mut buf = Vec::new(); buf.extend(self.key.serialize()); // := self.value.consensus_encode(&mut buf).unwrap(); buf } } impl Deserialize for Pair { fn deserialize(bytes: &[u8]) -> Result { let mut decoder = bytes; Pair::decode(&mut decoder) } } impl Pair { pub(crate) fn decode(r: &mut R) -> Result { Ok(Pair { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? }) } } impl Encodable for ProprietaryKey where Subtype: Copy + From + Into, { fn consensus_encode(&self, w: &mut W) -> Result { let mut len = self.prefix.consensus_encode(w)? + 1; w.emit_compact_size(self.subtype.into())?; w.write_all(&self.key)?; len += self.key.len(); Ok(len) } } impl Decodable for ProprietaryKey where Subtype: Copy + From + Into, { fn consensus_decode(r: &mut R) -> Result { let prefix = Vec::::consensus_decode(r)?; let subtype = Subtype::from(r.read_compact_size()?); // The limit is a DOS protection mechanism the exact value is not // important, 1024 bytes is bigger than any key should be. let mut key = vec![]; let _ = r.read_to_limit(&mut key, 1024)?; Ok(ProprietaryKey { prefix, subtype, key }) } } impl ProprietaryKey where Subtype: Copy + From + Into, { /// Constructs full [Key] corresponding to this proprietary key type pub fn to_key(&self) -> Key { Key { type_value: 0xFC, key_data: serialize(self) } } } impl TryFrom for ProprietaryKey where Subtype: Copy + From + Into, { type Error = Error; /// Constructs a [`ProprietaryKey`] from a [`Key`]. /// /// # Errors /// /// Returns [`Error::InvalidProprietaryKey`] if `key` does not start with `0xFC` byte. fn try_from(key: Key) -> Result { if key.type_value != 0xFC { return Err(Error::InvalidProprietaryKey); } Ok(deserialize(&key.key_data)?) } }