Skip to content

Commit 839c022

Browse files
committed
Make serde for LeafVersion to have byte representation
1 parent 67b8db0 commit 839c022

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

src/util/taproot.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,6 @@ impl ControlBlock {
762762

763763
/// The leaf version for tapleafs
764764
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
765-
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
766765
pub enum LeafVersion {
767766
/// BIP-342 tapscript
768767
TapScript,
@@ -812,6 +811,43 @@ impl fmt::Display for LeafVersion {
812811
}
813812
}
814813

814+
#[cfg(feature = "serde")]
815+
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
816+
impl ::serde::Serialize for LeafVersion {
817+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
818+
where
819+
S: ::serde::Serializer,
820+
{
821+
serializer.serialize_u8(self.into_consensus())
822+
}
823+
}
824+
825+
#[cfg(feature = "serde")]
826+
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
827+
impl<'de> ::serde::Deserialize<'de> for LeafVersion {
828+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
829+
struct U8Visitor;
830+
impl<'de> ::serde::de::Visitor<'de> for U8Visitor {
831+
type Value = LeafVersion;
832+
833+
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
834+
formatter.write_str("a valid consensus-encoded taproot leaf version")
835+
}
836+
837+
fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E>
838+
where
839+
E: ::serde::de::Error,
840+
{
841+
LeafVersion::from_consensus(value).map_err(|_| {
842+
E::invalid_value(::serde::de::Unexpected::Unsigned(value as u64), &"consensus-encoded leaf version as u8")
843+
})
844+
}
845+
}
846+
847+
deserializer.deserialize_u8(U8Visitor)
848+
}
849+
}
850+
815851
/// Detailed error type for taproot builder
816852
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
817853
pub enum TaprootBuilderError {

0 commit comments

Comments
 (0)