chore: update initialization function

This commit is contained in:
Magamedrasul Ibragimov 2022-10-28 15:07:32 +03:00
parent c708ea9fda
commit 88ab1f459f
3 changed files with 36 additions and 6 deletions

View File

@ -4,6 +4,6 @@ use crate::*;
pub trait Database {
fn new(dbpath: &str) -> Self;
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
fn put(&mut self, key: &[u8]) -> Result<()>;
fn put(&mut self, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&mut self, key: &[u8]) -> Result<()>;
}

View File

@ -1,7 +1,12 @@
pub trait ToBytes {
fn to_bytes(&self) -> Vec<u8>;
}
/// Trait that must be implemented for Hash Function
pub trait Hasher {
type Fr: Copy + Eq + Default;
type Fr: Copy + Eq + Default + From<Vec<u8>> + Into<Vec<u8>>;
fn new() -> Self;
fn default_leaf() -> Self::Fr;
fn hash(input: &[Self::Fr]) -> Self::Fr;
}

View File

@ -11,19 +11,39 @@ where
next_index: usize,
}
pub(crate) struct Key(usize, usize);
impl From<Key> for Vec<u8> {
fn from(key: Key) -> Vec<u8> {
todo!()
}
}
impl<D, H> MerkleTree<D, H>
where
D: Database,
H: Hasher,
{
/// Creates new `MerkleTree`
pub fn new(depth: usize, dbpath: &str) -> Self {
Self {
db: Database::new(dbpath),
pub fn new(depth: usize, dbpath: &str) -> Result<Self> {
// TODO: Use open instead of new, and check if the database is exists
let mut db: D = Database::new(dbpath);
db.put(&Vec::<u8>::from(Key(depth, 0)), &H::default_leaf().into())?;
for i in (0..depth).rev() {
let prev = db.get(&Vec::<u8>::from(Key(i + 1, 0)))?.unwrap();
db.put(
&Vec::<u8>::from(Key(i, 0)),
&H::hash(&[prev.clone().into(), prev.into()]).into(),
)?;
}
Ok(Self {
db,
h: Hasher::new(),
depth,
next_index: 0,
}
})
}
/// Inserts a leaf to the next available index
@ -31,6 +51,11 @@ where
todo!()
}
/// Recalculates `Merkle Tree` from the specified key
fn recalculate_from(&mut self, key: usize) {
todo!()
}
/// Deletes a leaf at the `key` by setting it to its default value
pub fn delete(&mut self, key: usize) {
todo!()