feat: change Hasher API

This commit is contained in:
Magamedrasul Ibragimov 2022-11-30 21:50:10 +03:00
parent 09d95a901f
commit ea8c7a5264
5 changed files with 155 additions and 173 deletions

View File

@ -3,7 +3,13 @@ use crate::*;
/// Trait that must be implemented for Hash Function
pub trait Hasher {
/// Native type for the hash-function
type Fr: Copy + Eq + Default + From<Value> + Into<Value>;
type Fr: Copy + Eq + Default;
/// Serializes Self::Fr
fn serialize(value: Self::Fr) -> Value;
/// Deserializes Self::Fr
fn deserialize(value: Value) -> Self::Fr;
/// Outputs the default leaf (Fr::default())
fn default_leaf() -> Self::Fr;

View File

@ -61,10 +61,10 @@ where
// Initialize one branch of the `Merkle Tree` from bottom to top
cache[depth] = H::default_leaf();
db.put(Key(depth, 0).into(), cache[depth].into())?;
db.put(Key(depth, 0).into(), H::serialize(cache[depth]))?;
for i in (0..depth).rev() {
cache[i] = H::hash(&[cache[i + 1], cache[i + 1]]);
db.put(Key(i, 0).into(), cache[i].into())?;
db.put(Key(i, 0).into(), H::serialize(cache[i]))?;
}
let root = cache[0];
@ -85,7 +85,7 @@ where
let db = D::load(dbpath)?;
// Load root
let root = db.get(Key(0, 0).into())?.unwrap().into();
let root = H::deserialize(db.get(Key(0, 0).into())?.unwrap());
// Load depth & next_index values from db
let depth = db.get(DEPTH_KEY)?.unwrap().try_into().unwrap();
@ -117,7 +117,8 @@ where
return Err(Error("Merkle Tree is full!".to_string()));
}
self.db.put(Key(self.depth, key).into(), leaf.into())?;
self.db
.put(Key(self.depth, key).into(), H::serialize(leaf))?;
self.recalculate_from(key)?;
// Update next_index in memory
@ -139,7 +140,7 @@ where
let value = self.hash_couple(depth, i)?;
i >>= 1;
depth -= 1;
self.db.put(Key(depth, i).into(), value.into())?;
self.db.put(Key(depth, i).into(), H::serialize(value))?;
if depth == 0 {
self.root = value;
@ -161,11 +162,12 @@ where
// Returns elem by the key
fn get_elem(&self, key: Key) -> Result<H::Fr> {
Ok(self
let res = self
.db
.get(key.into())?
.unwrap_or_else(|| self.cache[key.0].into())
.into())
.map_or(self.cache[key.0], |value| H::deserialize(value));
Ok(res)
}
/// Deletes a leaf at the `key` by setting it to its default value

View File

@ -6,9 +6,6 @@ use tiny_keccak::{Hasher as _, Keccak};
struct MemoryDB(HashMap<DBKey, Value>);
struct MyKeccak(Keccak);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct MyFr([u8; 32]);
impl Database for MemoryDB {
fn new(_dbpath: &str) -> Result<Self> {
Ok(MemoryDB(HashMap::new()))
@ -29,34 +26,29 @@ impl Database for MemoryDB {
}
}
impl From<Vec<u8>> for MyFr {
fn from(v: Vec<u8>) -> Self {
let v = v.try_into().unwrap();
MyFr(v)
}
}
impl From<MyFr> for Vec<u8> {
fn from(v: MyFr) -> Self {
v.0.to_vec()
}
}
impl Hasher for MyKeccak {
type Fr = MyFr;
type Fr = [u8; 32];
fn default_leaf() -> Self::Fr {
MyFr([0; 32])
[0; 32]
}
fn serialize(value: Self::Fr) -> Value {
value.to_vec()
}
fn deserialize(value: Value) -> Self::Fr {
value.try_into().unwrap()
}
fn hash(input: &[Self::Fr]) -> Self::Fr {
let mut output = [0; 32];
let mut hasher = Keccak::v256();
for element in input {
hasher.update(&element.0);
hasher.update(element);
}
hasher.finalize(&mut output);
MyFr(output)
output
}
}
@ -77,7 +69,7 @@ fn insert_delete() -> Result<()> {
let default_tree_root =
hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30");
assert_eq!(mt.root(), MyFr(default_tree_root));
assert_eq!(mt.root(), default_tree_root);
let roots = [
hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"),
@ -87,21 +79,21 @@ fn insert_delete() -> Result<()> {
];
for i in 0..leaves.len() {
mt.update_next(MyFr(leaves[i]))?;
assert_eq!(mt.root(), MyFr(roots[i]));
mt.update_next(leaves[i])?;
assert_eq!(mt.root(), roots[i]);
}
for (i, &leaf) in leaves.iter().enumerate() {
assert!(mt.verify(&MyFr(leaf), &mt.proof(i)?));
assert!(mt.verify(&leaf, &mt.proof(i)?));
}
for i in (0..leaves.len()).rev() {
mt.delete(i)?;
}
assert_eq!(mt.root(), MyFr(default_tree_root));
assert_eq!(mt.root(), default_tree_root);
assert!(mt.update_next(MyFr(leaves[0])).is_err());
assert!(mt.update_next(leaves[0]).is_err());
Ok(())
}

View File

@ -18,38 +18,28 @@ struct MySled(sled::Db);
#[derive(Clone, Copy, PartialEq, Eq)]
struct PoseidonHash;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct MyFr(Fr);
impl Hasher for PoseidonHash {
type Fr = MyFr;
type Fr = Fr;
fn default_leaf() -> Self::Fr {
MyFr(Fr::from(0))
Fr::from(0)
}
fn serialize(value: Self::Fr) -> Value {
let mut buf = vec![];
Fr::serialize(&value, &mut buf).unwrap();
buf
}
fn deserialize(value: Value) -> Self::Fr {
let c = Cursor::new(value);
Fr::deserialize(c).unwrap()
}
fn hash(inputs: &[Self::Fr]) -> Self::Fr {
MyFr(poseidon_hash(
&inputs.iter().map(|&x| x.0).collect::<Vec<_>>(),
))
}
}
impl From<Vec<u8>> for MyFr {
fn from(v: Vec<u8>) -> Self {
let c = Cursor::new(v);
let f = Fr::deserialize(c).unwrap();
MyFr(f)
}
}
impl From<MyFr> for Vec<u8> {
fn from(v: MyFr) -> Self {
let mut buf = vec![];
Fr::serialize(&v.0, &mut buf).unwrap();
buf
poseidon_hash(inputs)
}
}
@ -115,7 +105,7 @@ fn poseidon_memory() -> Result<()> {
let leaf_index = 3;
let identity_secret = hash_to_field(b"test-merkle-proof");
let id_commitment = MyFr(poseidon_hash(&[identity_secret]));
let id_commitment = poseidon_hash(&[identity_secret]);
// let default_leaf = Fr::from(0);
mt.set(leaf_index, id_commitment).unwrap();
@ -124,7 +114,7 @@ fn poseidon_memory() -> Result<()> {
let root = mt.root();
assert_eq!(
root.0,
root,
str_to_fr(
"0x21947ffd0bce0c385f876e7c97d6a42eec5b1fe935aab2f01c1f8a8cbcc356d2",
16
@ -138,86 +128,86 @@ fn poseidon_memory() -> Result<()> {
// We check correct computation of the path and indexes
// These values refers to TEST_TREE_HEIGHT == 16
let expected_path_elements = vec![
MyFr(str_to_fr(
str_to_fr(
"0x0000000000000000000000000000000000000000000000000000000000000000",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2098f5fb9e239eab3ceac3f27b81e481dc3124d55ffed523a839ee8446b64864",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1069673dcdb12263df301a6ff584a7ec261a44cb9dc68df067a4774460b1f1e1",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x18f43331537ee2af2e3d758d50f72106467c6eea50371dd528d57eb2b856d238",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x07f9d837cb17b0d36320ffe93ba52345f1b728571a568265caac97559dbc952a",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2b94cf5e8746b3f5c9631f4c5df32907a699c58c94b2ad4d7b5cec1639183f55",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2dee93c5a666459646ea7d22cca9e1bcfed71e6951b953611d11dda32ea09d78",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x078295e5a22b84e982cf601eb639597b8b0515a88cb5ac7fa8a4aabe3c87349d",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2fa5e5f18f6027a6501bec864564472a616b2e274a41211a444cbe3a99f3cc61",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x0e884376d0d8fd21ecb780389e941f66e45e7acce3e228ab3e2156a614fcd747",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1b7201da72494f1e28717ad1a52eb469f95892f957713533de6175e5da190af2",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1f8d8822725e36385200c0b201249819a6e6e1e4650808b5bebc6bface7d7636",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2c5d82f66c914bafb9701589ba8cfcfb6162b0a12acf88a8d0879a0471b5f85a",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x14c54148a0940bb820957f5adf3fa1134ef5c4aaa113f4646458f270e0bfbfd0",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x190d33b12f986f961e10c0ee44d8b9af11be25588cad89d416118e4bf4ebe80c",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x22f98aa9ce704152ac17354914ad73ed1167ae6596af510aa5b3649325e06c92",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2a7c7c9b6ce5880b9f6f228d72bf6a575a526f29c66ecceef8b753d38bba7323",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2e8186e558698ec1c67af9c14d463ffc470043c9c2988b954d75dd643f36b992",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x0f57c5571e9a4eab49e2c8cf050dae948aef6ead647392273546249d1c1ff10f",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1830ee67b5fb554ad5f63d4388800e1cfe78e310697d46e43c9ce36134f72cca",
16,
)),
),
];
let expected_identity_path_index: Vec<u8> =
@ -239,7 +229,7 @@ fn poseidon_sled() -> Result<()> {
let leaf_index = 3;
let identity_secret = hash_to_field(b"test-merkle-proof");
let id_commitment = MyFr(poseidon_hash(&[identity_secret]));
let id_commitment = poseidon_hash(&[identity_secret]);
// let default_leaf = Fr::from(0);
mt.set(leaf_index, id_commitment).unwrap();
@ -248,7 +238,7 @@ fn poseidon_sled() -> Result<()> {
let root = mt.root();
assert_eq!(
root.0,
root,
str_to_fr(
"0x21947ffd0bce0c385f876e7c97d6a42eec5b1fe935aab2f01c1f8a8cbcc356d2",
16
@ -262,86 +252,86 @@ fn poseidon_sled() -> Result<()> {
// We check correct computation of the path and indexes
// These values refers to TEST_TREE_HEIGHT == 16
let expected_path_elements = vec![
MyFr(str_to_fr(
str_to_fr(
"0x0000000000000000000000000000000000000000000000000000000000000000",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2098f5fb9e239eab3ceac3f27b81e481dc3124d55ffed523a839ee8446b64864",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1069673dcdb12263df301a6ff584a7ec261a44cb9dc68df067a4774460b1f1e1",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x18f43331537ee2af2e3d758d50f72106467c6eea50371dd528d57eb2b856d238",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x07f9d837cb17b0d36320ffe93ba52345f1b728571a568265caac97559dbc952a",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2b94cf5e8746b3f5c9631f4c5df32907a699c58c94b2ad4d7b5cec1639183f55",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2dee93c5a666459646ea7d22cca9e1bcfed71e6951b953611d11dda32ea09d78",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x078295e5a22b84e982cf601eb639597b8b0515a88cb5ac7fa8a4aabe3c87349d",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2fa5e5f18f6027a6501bec864564472a616b2e274a41211a444cbe3a99f3cc61",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x0e884376d0d8fd21ecb780389e941f66e45e7acce3e228ab3e2156a614fcd747",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1b7201da72494f1e28717ad1a52eb469f95892f957713533de6175e5da190af2",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1f8d8822725e36385200c0b201249819a6e6e1e4650808b5bebc6bface7d7636",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2c5d82f66c914bafb9701589ba8cfcfb6162b0a12acf88a8d0879a0471b5f85a",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x14c54148a0940bb820957f5adf3fa1134ef5c4aaa113f4646458f270e0bfbfd0",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x190d33b12f986f961e10c0ee44d8b9af11be25588cad89d416118e4bf4ebe80c",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x22f98aa9ce704152ac17354914ad73ed1167ae6596af510aa5b3649325e06c92",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2a7c7c9b6ce5880b9f6f228d72bf6a575a526f29c66ecceef8b753d38bba7323",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x2e8186e558698ec1c67af9c14d463ffc470043c9c2988b954d75dd643f36b992",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x0f57c5571e9a4eab49e2c8cf050dae948aef6ead647392273546249d1c1ff10f",
16,
)),
MyFr(str_to_fr(
),
str_to_fr(
"0x1830ee67b5fb554ad5f63d4388800e1cfe78e310697d46e43c9ce36134f72cca",
16,
)),
),
];
let expected_identity_path_index: Vec<u8> =

View File

@ -6,9 +6,6 @@ use tiny_keccak::{Hasher as _, Keccak};
struct MyKeccak(Keccak);
struct MySled(sled::Db);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct MyFr([u8; 32]);
impl Database for MySled {
fn new(dbpath: &str) -> Result<Self> {
let db = sled::open(dbpath).unwrap();
@ -44,40 +41,35 @@ impl Database for MySled {
}
}
impl From<Vec<u8>> for MyFr {
fn from(v: Vec<u8>) -> Self {
let v = v.try_into().unwrap();
MyFr(v)
}
}
impl From<MyFr> for Vec<u8> {
fn from(v: MyFr) -> Self {
v.0.to_vec()
}
}
impl Hasher for MyKeccak {
type Fr = MyFr;
type Fr = [u8; 32];
fn default_leaf() -> Self::Fr {
MyFr([0; 32])
[0; 32]
}
fn serialize(value: Self::Fr) -> Value {
value.to_vec()
}
fn deserialize(value: Value) -> Self::Fr {
value.to_vec().try_into().unwrap()
}
fn hash(input: &[Self::Fr]) -> Self::Fr {
let mut output = [0; 32];
let mut hasher = Keccak::v256();
for element in input {
hasher.update(&element.0);
hasher.update(element);
}
hasher.finalize(&mut output);
MyFr(output)
output
}
}
#[test]
fn insert_delete() -> Result<()> {
let mut mt = MerkleTree::<MySled, MyKeccak>::new(2, "abacaba")?;
let mut mt = MerkleTree::<MySled, MyKeccak>::new(2, "abacabas")?;
assert_eq!(mt.capacity(), 4);
assert_eq!(mt.depth(), 2);
@ -92,7 +84,7 @@ fn insert_delete() -> Result<()> {
let default_tree_root =
hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30");
assert_eq!(mt.root(), MyFr(default_tree_root));
assert_eq!(mt.root(), default_tree_root);
let roots = [
hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"),
@ -102,23 +94,23 @@ fn insert_delete() -> Result<()> {
];
for i in 0..leaves.len() {
mt.update_next(MyFr(leaves[i]))?;
assert_eq!(mt.root(), MyFr(roots[i]));
mt.update_next(leaves[i])?;
assert_eq!(mt.root(), roots[i]);
}
for (i, &leaf) in leaves.iter().enumerate() {
assert!(mt.verify(&MyFr(leaf), &mt.proof(i)?));
assert!(mt.verify(&leaf, &mt.proof(i)?));
}
for i in (0..leaves.len()).rev() {
mt.delete(i)?;
}
assert_eq!(mt.root(), MyFr(default_tree_root));
assert_eq!(mt.root(), default_tree_root);
assert!(mt.update_next(MyFr(leaves[0])).is_err());
assert!(mt.update_next(leaves[0]).is_err());
fs::remove_dir_all("abacaba").expect("Error removing db");
fs::remove_dir_all("abacabas").expect("Error removing db");
Ok(())
}