use core::fmt;
use io::{Read, Write};
use super::serialize::{Deserialize, Serialize};
use crate::consensus::encode::{
self, deserialize, serialize, Decodable, Encodable, ReadExt, VarInt, WriteExt, MAX_VEC_SIZE,
};
use crate::prelude::*;
use crate::psbt::Error;
#[derive(Debug, PartialEq, Hash, Eq, Clone, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Key {
pub type_value: u8,
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))]
pub key: Vec<u8>,
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Pair {
pub key: Key,
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))]
pub value: Vec<u8>,
}
pub type ProprietaryType = u8;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct ProprietaryKey<Subtype = ProprietaryType>
where
Subtype: Copy + From<u8> + Into<u8>,
{
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))]
pub prefix: Vec<u8>,
pub subtype: Subtype,
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::hex_bytes"))]
pub key: Vec<u8>,
}
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.as_hex())
}
}
impl Key {
pub(crate) fn decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let VarInt(byte_size): VarInt = Decodable::consensus_decode(r)?;
if byte_size == 0 {
return Err(Error::NoMorePairs);
}
let key_byte_size: u64 = byte_size - 1;
if key_byte_size > MAX_VEC_SIZE as u64 {
return Err(encode::Error::OversizedVectorAllocation {
requested: key_byte_size as usize,
max: MAX_VEC_SIZE,
}
.into());
}
let type_value: u8 = Decodable::consensus_decode(r)?;
let mut key = Vec::with_capacity(key_byte_size as usize);
for _ in 0..key_byte_size {
key.push(Decodable::consensus_decode(r)?);
}
Ok(Key { type_value, key })
}
}
impl Serialize for Key {
fn serialize(&self) -> Vec<u8> {
let mut buf = Vec::new();
VarInt::from(self.key.len() + 1)
.consensus_encode(&mut buf)
.expect("in-memory writers don't error");
self.type_value.consensus_encode(&mut buf).expect("in-memory writers don't error");
for key in &self.key {
key.consensus_encode(&mut buf).expect("in-memory writers don't error");
}
buf
}
}
impl Serialize for Pair {
fn serialize(&self) -> Vec<u8> {
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<Self, Error> {
let mut decoder = bytes;
Pair::decode(&mut decoder)
}
}
impl Pair {
pub(crate) fn decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Pair { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? })
}
}
impl<Subtype> Encodable for ProprietaryKey<Subtype>
where
Subtype: Copy + From<u8> + Into<u8>,
{
fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = self.prefix.consensus_encode(w)? + 1;
w.emit_u8(self.subtype.into())?;
w.write_all(&self.key)?;
len += self.key.len();
Ok(len)
}
}
impl<Subtype> Decodable for ProprietaryKey<Subtype>
where
Subtype: Copy + From<u8> + Into<u8>,
{
fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let prefix = Vec::<u8>::consensus_decode(r)?;
let subtype = Subtype::from(r.read_u8()?);
let mut key = vec![];
let _ = r.read_to_limit(&mut key, 1024)?;
Ok(ProprietaryKey { prefix, subtype, key })
}
}
impl<Subtype> ProprietaryKey<Subtype>
where
Subtype: Copy + From<u8> + Into<u8>,
{
pub fn to_key(&self) -> Key { Key { type_value: 0xFC, key: serialize(self) } }
}
impl<Subtype> TryFrom<Key> for ProprietaryKey<Subtype>
where
Subtype: Copy + From<u8> + Into<u8>,
{
type Error = Error;
fn try_from(key: Key) -> Result<Self, Self::Error> {
if key.type_value != 0xFC {
return Err(Error::InvalidProprietaryKey);
}
Ok(deserialize(&key.key)?)
}
}