A Rust codegen tool that generates Rust code from pythonic SSZ (Simple Serialize) definitions.
This project parses Python-style SSZ schema definitions
using sizzle-parser
and generates equivalent Rust implementations utilizing modified versions of libraries from
sigp:
ethereum_ssz(sszandssz_derive): For SSZ encoding / decodingssz_types: For SSZ types such asList,Vector,Bitfield, etctree_hash(tree_hashandtree_hash_derive): For Merklelization
These libraries have been modified to add StableContainer support and other enhancements.
- Support for
Container,StableContainer, andProfiletypes - Inheritance in container definitions
- Union types
- Constants and type aliases
- Built-in type aliases (
byte,bit,null,BytesX) - Documentation comments (
###) and pragma comments (#~#) for controlling code generation (fully-qualified custom derives, custom attributes) - Derive pragmas support fully qualified Rust paths (for example,
serde::Serialize,serde::Deserialize,rkyv::Archive,rkyv::Serialize,rkyv::Deserialize) - Derives are emitted exactly as configured in schema pragmas / derive config (the generator does not inject serde/rkyv imports based on derive names)
In order to use ssz-gen:
-
Add
ssz_codegenas abuild-dependency:[build-dependencies] ssz_codegen = { git = "https://github.com/alpenlabs/ssz-gen" }
-
Create a
build.rsfile in your crate root:use ssz_codegen::build_ssz_files; use std::path::Path; fn main() { let out_dir = std::env::var("OUT_DIR").unwrap(); let output_path = Path::new(&out_dir).join("generated_ssz.rs"); build_ssz_files( &["schema.ssz"], // Entry point SSZ files "specs/", // Base directory containing SSZ files &["external_ssz_crate"], // External crates you would like to import and use in your SSZ schemas output_path.to_str().unwrap(), ssz_codegen::ModuleGeneration::NestedModules, ) .expect("Failed to generate SSZ types"); }
-
Include the generated code in your
lib.rs:use ssz_types::*; use ssz::{Decode, Encode}; use tree_hash::TreeHash; include!(concat!(env!("OUT_DIR"), "/generated_ssz.rs")); // Your SSZ types are now available pub fn example() { let data = crate::specs::schema::MyContainer { /* ... */ }; // Use SSZ encoding/decoding, tree hashing, etc. }
Contributions are generally welcome. If you intend to make larger changes please discuss them in an issue before opening a PR to avoid duplicate work and architectural mismatches.
For more information please see CONTRIBUTING.md.
This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.