Merge rust-bitcoin/rust-bitcoin#1523: Fix LeafVersion serde

a400757676 Add failing tests from serde-json (sanket1729)
b3246bf73f Fix LeafVersion serde (sanket1729)

Pull request description:

  The default implementation maps to visit_u64. The current implementation
  does not roundtrip with many deserializers, including serde_json. See
  the failing test in the second commit

ACKs for top commit:
  Kixunil:
    tACK a400757676
  tcharding:
    ACK a400757676

Tree-SHA512: a6307b799b0bb4af398addc9ddbff0d811b632d1cc6ab4bdd77aaf3f151e48dd1cd10e3f90a71ef8fc3feb1cd988f7a719f92ec745b5fdf2ae0f0ad97ab2fa10
This commit is contained in:
sanket1729 2023-01-09 01:39:42 -08:00
commit cc1e6c02c8
No known key found for this signature in database
GPG Key ID: 648FFB183E0870A2
1 changed files with 22 additions and 1 deletions

View File

@ -944,10 +944,16 @@ impl<'de> serde::Deserialize<'de> for LeafVersion {
formatter.write_str("a valid consensus-encoded taproot leaf version") formatter.write_str("a valid consensus-encoded taproot leaf version")
} }
fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E> fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where where
E: serde::de::Error, E: serde::de::Error,
{ {
let value = u8::try_from(value).map_err(|_| {
E::invalid_value(
serde::de::Unexpected::Unsigned(value),
&"consensus-encoded leaf version as u8",
)
})?;
LeafVersion::from_consensus(value).map_err(|_| { LeafVersion::from_consensus(value).map_err(|_| {
E::invalid_value( E::invalid_value(
::serde::de::Unexpected::Unsigned(value as u64), ::serde::de::Unexpected::Unsigned(value as u64),
@ -1098,6 +1104,9 @@ mod test {
use crate::{Address, Network}; use crate::{Address, Network};
extern crate serde_json; extern crate serde_json;
#[cfg(feature = "serde")]
use serde_test::{assert_tokens, Token};
fn tag_engine(tag_name: &str) -> sha256::HashEngine { fn tag_engine(tag_name: &str) -> sha256::HashEngine {
let mut engine = sha256::Hash::engine(); let mut engine = sha256::Hash::engine();
let tag_hash = sha256::Hash::hash(tag_name.as_bytes()); let tag_hash = sha256::Hash::hash(tag_name.as_bytes());
@ -1351,6 +1360,18 @@ mod test {
} }
} }
#[test]
#[cfg(feature = "serde")]
fn test_leaf_version_serde() {
let leaf_version = LeafVersion::TapScript;
// use serde_test to test serialization and deserialization
assert_tokens(&leaf_version, &[Token::U8(192)]);
let json = serde_json::to_string(&leaf_version).unwrap();
let leaf_version2 = serde_json::from_str(&json).unwrap();
assert_eq!(leaf_version, leaf_version2);
}
#[test] #[test]
fn bip_341_tests() { fn bip_341_tests() {
fn process_script_trees( fn process_script_trees(