Bootstrap geth Rust workspace

This commit is contained in:
Eric Wendland 2026-05-15 15:08:20 +02:00
commit 26f81ff1ef
73 changed files with 4835 additions and 0 deletions

View file

@ -0,0 +1,14 @@
[package]
name = "geth-codec"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
blake3.workspace = true
hex.workspace = true
postcard.workspace = true
serde.workspace = true
thiserror.workspace = true
geth-types = { path = "../geth-types" }

View file

@ -0,0 +1,62 @@
use serde::{Serialize, de::DeserializeOwned};
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("canonical encoding failed: {0}")]
Encode(#[from] postcard::Error),
}
pub fn encode_canonical<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, CodecError> {
postcard::to_allocvec(value).map_err(CodecError::from)
}
pub fn decode_canonical<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, CodecError> {
postcard::from_bytes(bytes).map_err(CodecError::from)
}
pub fn hash_canonical<T: Serialize + ?Sized>(
value: &T,
) -> Result<geth_types::BlobHash, CodecError> {
let bytes = encode_canonical(value)?;
Ok(blake3_hash_bytes(&bytes))
}
#[must_use]
pub fn blake3_hash_bytes(bytes: &[u8]) -> geth_types::BlobHash {
geth_types::BlobHash::new(blake3::hash(bytes).to_hex().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Sample {
version: u8,
name: String,
values: Vec<u16>,
}
#[test]
fn canonical_encoding_is_deterministic() {
let sample = Sample {
version: 1,
name: "geth".to_owned(),
values: vec![1, 2, 3],
};
assert_eq!(
encode_canonical(&sample).expect("encode"),
encode_canonical(&sample).expect("encode again")
);
assert_eq!(
hash_canonical(&sample).expect("hash"),
hash_canonical(&sample).expect("hash again")
);
assert_eq!(
decode_canonical::<Sample>(&encode_canonical(&sample).expect("encode"))
.expect("decode"),
sample
);
}
}