kassandra_shared/
db.rs

1//! Shared types to be stored in the host databases
2
3use borsh::{BorshDeserialize, BorshSerialize};
4use chacha20poly1305::Key;
5use core::fmt::Formatter;
6use serde::de::{Error, Visitor};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9/// A wrapper around a ChaCha key
10///
11/// Used to encrypted enclave responses for users
12#[derive(Debug, Clone)]
13pub struct EncKey(Key);
14
15impl EncKey {
16    /// Get the hash of this key
17    pub fn hash(&self) -> alloc::string::String {
18        use sha2::Digest;
19        let mut hasher = sha2::Sha256::new();
20        hasher.update(self.0.as_slice());
21        let hash: [u8; 32] = hasher.finalize().into();
22        hex::encode(hash)
23    }
24}
25
26impl From<Key> for EncKey {
27    fn from(key: Key) -> Self {
28        Self(key)
29    }
30}
31
32impl<'a> From<&'a EncKey> for &'a Key {
33    fn from(key: &'a EncKey) -> Self {
34        &key.0
35    }
36}
37
38impl Serialize for EncKey {
39    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
40    where
41        S: Serializer,
42    {
43        serializer.serialize_bytes(self.0.as_slice())
44    }
45}
46
47impl<'de> Deserialize<'de> for EncKey {
48    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
49    where
50        D: Deserializer<'de>,
51    {
52        struct EncKeyVisitor;
53        impl Visitor<'_> for EncKeyVisitor {
54            type Value = EncKey;
55
56            fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result {
57                formatter.write_str("32 bytes")
58            }
59
60            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
61            where
62                E: Error,
63            {
64                let bytes: [u8; 32] = v
65                    .try_into()
66                    .map_err(|_| Error::custom("Unexpected length of encryption key"))?;
67                Ok(EncKey(*Key::from_slice(&bytes)))
68            }
69        }
70
71        deserializer.deserialize_bytes(EncKeyVisitor)
72    }
73}
74
75/// Simplified domain type for indexing a Tx on chain
76#[derive(
77    Debug,
78    Copy,
79    Clone,
80    PartialEq,
81    Eq,
82    PartialOrd,
83    Ord,
84    Serialize,
85    Deserialize,
86    BorshSerialize,
87    BorshDeserialize,
88)]
89pub struct Index {
90    pub height: u64,
91    pub tx: u32,
92}
93
94impl Index {
95    pub fn as_bytes(&self) -> [u8; 12] {
96        let mut bytes = [0u8; 12];
97        let h_bytes = self.height.to_le_bytes();
98        let tx_bytes = self.tx.to_le_bytes();
99        for ix in 0..12 {
100            if ix < 8 {
101                bytes[ix] = h_bytes[ix];
102            } else {
103                bytes[ix] = tx_bytes[ix - 8];
104            }
105        }
106        bytes
107    }
108
109    pub fn try_from_bytes(bytes: &[u8]) -> Option<Self> {
110        if bytes.len() != 12 {
111            None
112        } else {
113            let mut h_bytes = [0u8; 8];
114            let mut tx_bytes = [0u8; 4];
115            for ix in 0..12 {
116                if ix < 8 {
117                    h_bytes[ix] = bytes[ix];
118                } else {
119                    tx_bytes[ix - 8] = bytes[ix];
120                }
121            }
122            Some(Self {
123                height: u64::from_le_bytes(h_bytes),
124                tx: u32::from_le_bytes(tx_bytes),
125            })
126        }
127    }
128}
129
130#[derive(
131    Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
132)]
133pub struct IndexList(alloc::vec::Vec<Index>);
134
135impl IndexList {
136    /// Try to parse bytes into a list of indices
137    pub fn try_from_bytes(bytes: &[u8]) -> Option<Self> {
138        if 12 * (bytes.len() / 12) != bytes.len() {
139            return None;
140        }
141        let len = bytes.len() / 12;
142        let indices: alloc::vec::Vec<_> =
143            bytes.chunks(12).filter_map(Index::try_from_bytes).collect();
144        if indices.len() != len {
145            None
146        } else {
147            Some(Self(indices))
148        }
149    }
150
151    /// Given two index sets, produce a new index set
152    /// modifying self in-place.
153    ///
154    /// We assume `self` is synced ahead of `other`. The intersection of
155    /// the indices up to the common block height is kept along with all
156    /// indices of `self` with block height greater than `other`'s maximum
157    /// block height.
158    pub fn combine(&mut self, mut other: Self) {
159        if self.0.is_empty() {
160            *self = other;
161            return;
162        }
163        if other.0.is_empty() {
164            return;
165        }
166        self.0.sort();
167        other.0.sort();
168        let a_height = self.0.last().map(|ix| ix.height).unwrap_or_default();
169        let b_height = other.0.last().map(|ix| ix.height).unwrap_or_default();
170        // from here on out, we assume that `self` is synced further than `other`
171        let height = if a_height < b_height {
172            core::mem::swap(self, &mut other);
173            a_height
174        } else {
175            b_height
176        };
177        self.0.retain(|ix| {
178            if ix.height > height {
179                true
180            } else {
181                other.contains(ix)
182            }
183        });
184    }
185
186    /// Create a union of two index sets
187    pub fn union(&mut self, other: &Self) {
188        self.0.extend_from_slice(&other.0[..]);
189        self.0.sort();
190        self.0.dedup();
191    }
192
193    /// Check if an index is contained in `self`
194    /// Assumes `self` is sorted.
195    pub fn contains(&self, index: &Index) -> bool {
196        self.0.binary_search(index).is_ok()
197    }
198
199    /// Check if the index set contains a given height.
200    /// Assumes `self` is sorted.
201    pub fn contains_height(&self, height: u64) -> bool {
202        self.0.binary_search_by_key(&height, |ix| ix.height).is_ok()
203    }
204
205    /// Return and iterator of references to the
206    /// contained indices
207    pub fn iter(&self) -> alloc::slice::Iter<Index> {
208        self.0.iter()
209    }
210
211    /// Function for filtering out elements in-place
212    pub fn retain<P>(&mut self, pred: P)
213    where
214        P: FnMut(&Index) -> bool,
215    {
216        self.0.retain(pred);
217    }
218}
219
220impl IntoIterator for IndexList {
221    type Item = Index;
222    type IntoIter = alloc::vec::IntoIter<Index>;
223
224    fn into_iter(self) -> Self::IntoIter {
225        self.0.into_iter()
226    }
227}
228
229impl FromIterator<Index> for IndexList {
230    fn from_iter<T: IntoIterator<Item = Index>>(iter: T) -> Self {
231        Self(iter.into_iter().collect())
232    }
233}
234
235/// The response from the enclave for performing
236/// FMD for a particular uses
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct EncryptedResponse {
239    /// Hash of user's encryption key used to identify
240    /// when database entries belong to them
241    pub owner: alloc::string::String,
242    /// Nonce needed to decrypt the indices
243    pub nonce: [u8; 12],
244    /// encrypted indices
245    pub indices: alloc::vec::Vec<u8>,
246    /// The last height FMD was performed at
247    pub height: u64,
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use alloc::vec::Vec;
254
255    #[test]
256    fn test_combine_indices() {
257        let a = IndexList(Vec::from([
258            Index { height: 0, tx: 0 },
259            Index { height: 0, tx: 1 },
260            Index { height: 1, tx: 0 },
261            Index { height: 3, tx: 0 },
262        ]));
263        let mut b = IndexList(Vec::from([
264            Index { height: 0, tx: 1 },
265            Index { height: 1, tx: 4 },
266        ]));
267        let expected = IndexList(Vec::from([
268            Index { height: 0, tx: 1 },
269            Index { height: 3, tx: 0 },
270        ]));
271
272        let mut first = a.clone();
273        first.combine(b.clone());
274        assert_eq!(first, expected);
275        b.combine(a.clone());
276        assert_eq!(b, expected);
277
278        let mut new = IndexList::default();
279        new.combine(a.clone());
280        assert_eq!(new, a);
281        let mut third = a.clone();
282        third.combine(IndexList::default());
283        assert_eq!(third, a);
284    }
285}