Skip to content

Commit

Permalink
Add bincode support for merkle tree cache
Browse files Browse the repository at this point in the history
  • Loading branch information
popzxc committed Mar 28, 2022
1 parent cfa54ca commit 96725e1
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 3 deletions.
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions core/lib/crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ fnv = "1.0.3"
rayon = "1.0.3"
hex = "0.4"
base64 = "0.13"
bincode = "2.0.0-rc.1"

[dev-dependencies]
serde_json = "1.0"
Expand Down
32 changes: 29 additions & 3 deletions core/lib/crypto/src/merkle_tree/parallel_smt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,20 @@ use std::{
/// Nodes are indexed starting with index(root) = 0
/// To store the index, at least 2 * TREE_HEIGHT bits is required.
/// Wrapper-structure is used to avoid mixing up with `ItemIndex` on the type level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Serialize,
Deserialize,
bincode::Encode,
bincode::Decode,
)]
struct NodeIndex(pub u64);

/// Lead index: 0 <= i < N.
Expand Down Expand Up @@ -106,7 +119,7 @@ where
}

/// Merkle Tree branch node.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct Node {
depth: Depth,
index: NodeIndex,
Expand Down Expand Up @@ -701,13 +714,26 @@ where
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct SparseMerkleTreeSerializableCacheBN256 {
root: NodeRef,
nodes: Vec<Node>,
cache: Vec<(NodeIndex, [u8; 32])>,
}

impl SparseMerkleTreeSerializableCacheBN256 {
pub fn encode_bincode(&self) -> Vec<u8> {
bincode::encode_to_vec(self, bincode::config::standard())
.expect("Unable to encode Merkle Tree cache")
}

pub fn decode_bincode(data: &[u8]) -> Self {
bincode::decode_from_slice(data, bincode::config::standard())
.expect("Unable to decode Merkle Tree cache")
.0
}
}

impl<T, H> SparseMerkleTree<T, Fr, H>
where
T: GetBits,
Expand Down

0 comments on commit 96725e1

Please sign in to comment.