1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#[cfg(feature = "std")]
use std::collections::HashMap as Map;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap as Map;
use generic_array::GenericArray;
use digest::Digest;

use crate::{Value, ValueOf, IntermediateOf, EndOf, Backend};

#[derive(Debug, Eq, PartialEq, Clone)]
/// Noop DB error.
pub enum NoopBackendError {
    /// Not supported get operation.
    NotSupported,
}

#[derive(Clone)]
/// Noop merkle database.
pub struct NoopBackend<D: Digest, T: AsRef<[u8]> + Clone + Default>(
    Map<IntermediateOf<Self>, ((ValueOf<Self>, ValueOf<Self>), Option<usize>)>,
    Option<EndOf<Self>>,
);

impl<D: Digest, T: AsRef<[u8]> + Clone + Default> NoopBackend<D, T> {
    /// Create an in-memory database with unit empty value.
    pub fn new_with_unit_empty(value: EndOf<Self>) -> Self {
        Self(Default::default(), Some(value))
    }

    /// Create an in-memory database with inherited empty value.
    pub fn new_with_inherited_empty() -> Self {
        Self(Default::default(), None)
    }
}

impl<D: Digest, V: AsRef<[u8]> + Clone + Default> Backend for NoopBackend<D, V> {
    type Intermediate = GenericArray<u8, D::OutputSize>;
    type End = V;
    type Error = NoopBackendError;

    fn intermediate_of(&self, left: &ValueOf<Self>, right: &ValueOf<Self>) -> IntermediateOf<Self> {
        let mut digest = D::new();
        digest.input(&left.as_ref()[..]);
        digest.input(&right.as_ref()[..]);
        digest.result()
    }

    fn empty_at(&mut self, depth_to_bottom: usize) -> Result<ValueOf<Self>, Self::Error> {
        match &self.1 {
            Some(end) => Ok(Value::End(end.clone())),
            None => {
                let mut current = Value::End(Default::default());
                for _ in 0..depth_to_bottom {
                    let value = (current.clone(), current);
                    let key = self.intermediate_of(&value.0, &value.1);
                    self.0.insert(key.clone(), (value, None));
                    current = Value::Intermediate(key);
                }
                Ok(current)
            }
        }
    }

    fn get(&self, _key: &IntermediateOf<Self>) -> Result<(ValueOf<Self>, ValueOf<Self>), Self::Error> {
        Err(NoopBackendError::NotSupported)
    }

    fn rootify(&mut self, _key: &IntermediateOf<Self>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn unrootify(&mut self, _key: &IntermediateOf<Self>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn insert(&mut self, _key: IntermediateOf<Self>, _value: (ValueOf<Self>, ValueOf<Self>)) -> Result<(), Self::Error> {
        Ok(())
    }
}

#[derive(Debug, Eq, PartialEq, Clone)]
/// In-memory DB error.
pub enum InMemoryBackendError {
    /// Fetching key not exist.
    FetchingKeyNotExist,
    /// Trying to rootify a non-existing key.
    RootifyKeyNotExist,
    /// Set subkey does not exist.
    SetIntermediateNotExist
}

#[derive(Clone)]
/// In-memory merkle database.
pub struct InMemoryBackend<D: Digest, T: AsRef<[u8]> + Clone + Default>(
    Map<IntermediateOf<Self>, ((ValueOf<Self>, ValueOf<Self>), Option<usize>)>,
    Option<EndOf<Self>>,
);

impl<D: Digest, T: AsRef<[u8]> + Clone + Default> InMemoryBackend<D, T> {
    fn remove(&mut self, old_key: &IntermediateOf<Self>) -> Result<(), InMemoryBackendError> {
        let (old_value, to_remove) = {
            let value = self.0.get_mut(old_key).ok_or(InMemoryBackendError::SetIntermediateNotExist)?;
            value.1.as_mut().map(|v| *v -= 1);
            (value.0.clone(), value.1.map(|v| v == 0).unwrap_or(false))
        };

        if to_remove {
            match old_value.0 {
                Value::Intermediate(subkey) => { self.remove(&subkey)?; },
                Value::End(_) => (),
            }

            match old_value.1 {
                Value::Intermediate(subkey) => { self.remove(&subkey)?; },
                Value::End(_) => (),
            }

            self.0.remove(old_key);
        }

        Ok(())
    }

    /// Create an in-memory database with unit empty value.
    pub fn new_with_unit_empty(value: EndOf<Self>) -> Self {
        Self(Default::default(), Some(value))
    }

    /// Create an in-memory database with inherited empty value.
    pub fn new_with_inherited_empty() -> Self {
        Self(Default::default(), None)
    }

    /// Populate the database with proofs.
    pub fn populate(&mut self, proofs: Map<IntermediateOf<Self>, (ValueOf<Self>, ValueOf<Self>)>) {
        for (key, value) in proofs {
            self.0.insert(key, (value, None));
        }
    }
}

impl<D: Digest, T: AsRef<[u8]> + Clone + Default> AsRef<Map<IntermediateOf<Self>, ((ValueOf<Self>, ValueOf<Self>), Option<usize>)>> for InMemoryBackend<D, T> {
    fn as_ref(&self) -> &Map<IntermediateOf<Self>, ((ValueOf<Self>, ValueOf<Self>), Option<usize>)> {
        &self.0
    }
}

impl<D: Digest, V: AsRef<[u8]> + Clone + Default> Backend for InMemoryBackend<D, V> {
    type Intermediate = GenericArray<u8, D::OutputSize>;
    type End = V;
    type Error = InMemoryBackendError;

    fn intermediate_of(&self, left: &ValueOf<Self>, right: &ValueOf<Self>) -> IntermediateOf<Self> {
        let mut digest = D::new();
        digest.input(&left.as_ref()[..]);
        digest.input(&right.as_ref()[..]);
        digest.result()
    }

    fn empty_at(&mut self, depth_to_bottom: usize) -> Result<ValueOf<Self>, Self::Error> {
        match &self.1 {
            Some(end) => Ok(Value::End(end.clone())),
            None => {
                let mut current = Value::End(Default::default());
                for _ in 0..depth_to_bottom {
                    let value = (current.clone(), current);
                    let key = self.intermediate_of(&value.0, &value.1);
                    self.0.insert(key.clone(), (value, None));
                    current = Value::Intermediate(key);
                }
                Ok(current)
            }
        }
    }

    fn get(&self, key: &IntermediateOf<Self>) -> Result<(ValueOf<Self>, ValueOf<Self>), Self::Error> {
        self.0.get(key).map(|v| v.0.clone()).ok_or(InMemoryBackendError::FetchingKeyNotExist)
    }

    fn rootify(&mut self, key: &IntermediateOf<Self>) -> Result<(), Self::Error> {
        self.0.get_mut(key).ok_or(InMemoryBackendError::RootifyKeyNotExist)?.1
            .as_mut().map(|v| *v += 1);
        Ok(())
    }

    fn unrootify(&mut self, key: &IntermediateOf<Self>) -> Result<(), Self::Error> {
        self.remove(key)?;
        Ok(())
    }

    fn insert(&mut self, key: IntermediateOf<Self>, value: (ValueOf<Self>, ValueOf<Self>)) -> Result<(), Self::Error> {
        if self.0.contains_key(&key) {
            return Ok(())
        }

        let (left, right) = value;

        match &left {
            Value::Intermediate(ref subkey) => {
                self.0.get_mut(subkey).ok_or(InMemoryBackendError::SetIntermediateNotExist)?.1
                    .as_mut().map(|v| *v += 1);
            },
            Value::End(_) => (),
        }
        match &right {
            Value::Intermediate(ref subkey) => {
                self.0.get_mut(subkey).ok_or(InMemoryBackendError::SetIntermediateNotExist)?.1
                    .as_mut().map(|v| *v += 1);
            },
            Value::End(_) => (),
        }

        self.0.insert(key, ((left, right), Some(0)));
        Ok(())
    }
}