Skip to content

Commit 8c6798c

Browse files
committed
Checksum: compact serialization
1 parent 36d0add commit 8c6798c

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

packages/std/src/checksum.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ impl Serialize for Checksum {
7474
if serializer.is_human_readable() {
7575
serializer.serialize_str(&self.to_hex())
7676
} else {
77-
panic!("Checksum is only intended to be used with JSON serialization for now. If you are hitting this panic please open an issue at https://github.com/CosmWasm/cosmwasm describing your use case.")
77+
serializer.serialize_bytes(&self.0)
7878
}
7979
}
8080
}
@@ -88,7 +88,7 @@ impl<'de> Deserialize<'de> for Checksum {
8888
if deserializer.is_human_readable() {
8989
deserializer.deserialize_str(ChecksumVisitor)
9090
} else {
91-
panic!("Checksum is only intended to be used with JSON serialization for now. If you are hitting this panic please open an issue at https://github.com/CosmWasm/cosmwasm describing your use case.")
91+
deserializer.deserialize_bytes(ChecksumBytesVisitor)
9292
}
9393
}
9494
}
@@ -113,6 +113,23 @@ impl<'de> de::Visitor<'de> for ChecksumVisitor {
113113
}
114114
}
115115

116+
struct ChecksumBytesVisitor;
117+
118+
impl<'de> de::Visitor<'de> for ChecksumBytesVisitor {
119+
type Value = Checksum;
120+
121+
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
122+
formatter.write_str("32 byte checksum")
123+
}
124+
125+
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
126+
where
127+
E: de::Error,
128+
{
129+
Checksum::try_from(v).map_err(|ChecksumError| E::invalid_length(v.len(), &"32 bytes"))
130+
}
131+
}
132+
116133
#[derive(Error, Debug)]
117134
#[error("Checksum not of length 32")]
118135
pub struct ChecksumError;
@@ -235,4 +252,24 @@ mod tests {
235252
let deserialized: Checksum = serde_json::from_str(&serialized).unwrap();
236253
assert_eq!(deserialized, checksum);
237254
}
255+
256+
#[test]
257+
fn msgpack_works() {
258+
// echo -n "hij" | sha256sum
259+
let checksum =
260+
Checksum::from_hex("722c8c993fd75a7627d69ed941344fe2a1423a3e75efd3e6778a142884227104")
261+
.unwrap();
262+
263+
let serialized = rmp_serde::to_vec(&checksum).unwrap();
264+
// see: https://github.com/msgpack/msgpack/blob/8aa09e2/spec.md#bin-format-family
265+
let expected = vec![
266+
0xc4, 0x20, 0x72, 0x2c, 0x8c, 0x99, 0x3f, 0xd7, 0x5a, 0x76, 0x27, 0xd6, 0x9e, 0xd9,
267+
0x41, 0x34, 0x4f, 0xe2, 0xa1, 0x42, 0x3a, 0x3e, 0x75, 0xef, 0xd3, 0xe6, 0x77, 0x8a,
268+
0x14, 0x28, 0x84, 0x22, 0x71, 0x04,
269+
];
270+
assert_eq!(serialized, expected);
271+
272+
let deserialized: Checksum = rmp_serde::from_slice(&serialized).unwrap();
273+
assert_eq!(deserialized, checksum);
274+
}
238275
}

0 commit comments

Comments
 (0)