node: Implement binary encoding for messages

Signed-off-by: Alexis Sellier <self@cloudhead.io>
This commit is contained in:
Alexis Sellier
2022-09-13 10:16:05 +02:00
parent c7f78eafb6
commit b3d3077ccc
11 changed files with 638 additions and 88 deletions
+16 -42
View File
@@ -1,5 +1,4 @@
use std::fmt;
use std::str::FromStr;
use std::{convert::TryInto, fmt};
use serde::{Deserialize, Serialize};
use sha2::{
@@ -10,8 +9,6 @@ use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum DecodeError {
#[error(transparent)]
Multibase(#[from] multibase::Error),
#[error("invalid digest length {0}")]
InvalidLength(usize),
}
@@ -24,38 +21,17 @@ impl Digest {
pub fn new(bytes: impl AsRef<[u8]>) -> Self {
Self::from(Sha256::digest(bytes))
}
pub fn encode(&self) -> String {
multibase::encode(multibase::Base::Base58Btc, &self.0)
}
pub fn decode(s: &str) -> Result<Self, DecodeError> {
let (_, bytes) = multibase::decode(s)?;
let array = bytes
.try_into()
.map_err(|v: Vec<u8>| DecodeError::InvalidLength(v.len()))?;
Ok(Self(array))
}
}
impl FromStr for Digest {
type Err = DecodeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::decode(s)
}
}
impl AsRef<[u8]> for Digest {
fn as_ref(&self) -> &[u8] {
impl AsRef<[u8; 32]> for Digest {
fn as_ref(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Debug for Digest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Hash({})", self.encode())
write!(f, "Hash({})", self)
}
}
@@ -74,22 +50,20 @@ impl From<[u8; 32]> for Digest {
}
}
impl TryFrom<&[u8]> for Digest {
type Error = DecodeError;
fn try_from(bytes: &[u8]) -> Result<Self, DecodeError> {
let bytes: [u8; 32] = bytes
.try_into()
.map_err(|_| DecodeError::InvalidLength(bytes.len()))?;
Ok(bytes.into())
}
}
impl From<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>> for Digest {
fn from(array: GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>) -> Self {
Self(array.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck_macros::quickcheck;
#[quickcheck]
fn prop_encode_decode(input: Digest) {
let encoded = input.encode();
let decoded = Digest::decode(&encoded).unwrap();
assert_eq!(input, decoded);
}
}