penumbra_view/storage/
sct.rs

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use std::ops::Range;

use anyhow::Context as _;
use genawaiter::{rc::gen, yield_};
use r2d2_sqlite::rusqlite::Transaction;

use core::fmt::Debug;
use penumbra_tct::{
    storage::{Read, StoredPosition, Write},
    structure::Hash,
    Forgotten, Position, StateCommitment,
};

#[derive(Debug)]
pub struct TreeStore<'a, 'c: 'a>(pub &'a mut Transaction<'c>);

impl Read for TreeStore<'_, '_> {
    type Error = anyhow::Error;

    type HashesIter<'a> = Box<dyn Iterator<Item = Result<(Position, u8, Hash), Self::Error>> + 'a>
    where
        Self: 'a;

    type CommitmentsIter<'a> = Box<dyn Iterator<Item = Result<(Position, StateCommitment), Self::Error>>
        + 'a>
    where
        Self: 'a;

    fn position(&mut self) -> Result<StoredPosition, Self::Error> {
        let mut stmt = self
            .0
            .prepare_cached("SELECT position FROM sct_position LIMIT 1")
            .context("failed to prepare position query")?;
        let position = stmt
            .query_row::<Option<u64>, _, _>([], |row| row.get("position"))
            .context("failed to query position")?
            .map(Position::from)
            .into();
        Ok(position)
    }

    fn forgotten(&mut self) -> Result<Forgotten, Self::Error> {
        let mut stmt = self
            .0
            .prepare_cached("SELECT forgotten FROM sct_forgotten LIMIT 1")
            .context("failed to prepare forgotten query")?;
        let forgotten = stmt
            .query_row::<u64, _, _>([], |row| row.get("forgotten"))
            .context("failed to query forgotten")?
            .into();
        Ok(forgotten)
    }

    fn hash(&mut self, position: Position, height: u8) -> Result<Option<Hash>, Self::Error> {
        let position = u64::from(position) as i64;

        let mut stmt = self
            .0
            .prepare_cached(
                "SELECT hash FROM sct_hashes WHERE position = ?1 AND height = ?2 LIMIT 1",
            )
            .context("failed to prepare hash query")?;
        let bytes = stmt
            .query_row::<Option<Vec<u8>>, _, _>((&position, &height), |row| row.get("hash"))
            .context("failed to query hash")?;

        bytes
            .map(|bytes| {
                <[u8; 32]>::try_from(bytes)
                    .map_err(|_| anyhow::anyhow!("hash was of incorrect length"))
                    .and_then(|array| {
                        if let Ok(hash) = Hash::from_bytes(array) {
                            Ok(hash)
                        } else {
                            Err(anyhow::anyhow!("Failed to create Hash from bytes"))
                        }
                    })
            })
            .transpose()
    }

    fn hashes(&mut self) -> Self::HashesIter<'_> {
        // The iterator has to *own* the stmt because the rows borrow from it, so we use the
        // `genawaiter` crate to shove the entire preparation of the iterator into an (implicit)
        // async block, which handles the desuguaring to properly own the stmt for us.
        Box::new(
            gen!({
                let mut stmt = match self
                    .0
                    .prepare_cached("SELECT position, height, hash FROM sct_hashes")
                    .context("failed to prepare hashes query")
                {
                    Ok(stmt) => stmt,
                    // If an error happens while preparing the statement, shove it inside the first returned
                    // item of the iterator, because we can't return an outer error:
                    Err(e) => {
                        yield_!(Err(e));
                        return;
                    }
                };

                let rows = match stmt
                    .query_and_then([], |row| {
                        let position: i64 = row.get("position")?;
                        let height: u8 = row.get("height")?;
                        let hash: Vec<u8> = row.get("hash")?;
                        let hash = <[u8; 32]>::try_from(hash)
                            .map_err(|_| anyhow::anyhow!("hash was of incorrect length"))
                            .and_then(|array| {
                                Hash::from_bytes(array).map_err(|e| {
                                    // Explicitly convert any error to anyhow::Error
                                    anyhow::Error::msg(format!("Error converting hash: {}", e))
                                })
                            })?;
                        anyhow::Ok((Position::from(position as u64), height, hash))
                    })
                    .context("couldn't query database")
                {
                    Ok(rows) => rows,
                    // If an error happens while querying the database, shove it inside the first
                    // returned item of the iterator, because we can't return an outer error:
                    Err(e) => {
                        yield_!(Err(e));
                        return;
                    }
                };

                // Actually iterate through the rows:
                for row in rows {
                    yield_!(row);
                }
            })
            .into_iter(),
        )
    }

    fn commitment(&mut self, position: Position) -> Result<Option<StateCommitment>, Self::Error> {
        let position = u64::from(position) as i64;

        let mut stmt = self
            .0
            .prepare_cached("SELECT commitment FROM sct_commitments WHERE position = ?1 LIMIT 1")
            .context("failed to prepare commitment query")?;

        let bytes = stmt
            .query_row::<Option<Vec<u8>>, _, _>((&position,), |row| row.get("commitment"))
            .context("failed to query commitment")?;

        bytes
            .map(|bytes| {
                <[u8; 32]>::try_from(bytes)
                    .map_err(|_| anyhow::anyhow!("commitment was of incorrect length"))
                    .and_then(|array| StateCommitment::try_from(array).map_err(Into::into))
            })
            .transpose()
    }

    fn commitments(&mut self) -> Self::CommitmentsIter<'_> {
        // The iterator has to *own* the stmt because the rows borrow from it, so we use the
        // `genawaiter` crate to shove the entire preparation of the iterator into an (implicit)
        // async block, which handles the desuguaring to properly own the stmt for us.
        Box::new(
            gen!({
                let mut stmt = match self
                    .0
                    .prepare_cached("SELECT position, commitment FROM sct_commitments")
                    .context("failed to prepare commitments query")
                {
                    Ok(stmt) => stmt,
                    // If an error happens while preparing the statement, shove it inside the first returned
                    // item of the iterator, because we can't return an outer error:
                    Err(e) => {
                        yield_!(Err(e));
                        return;
                    }
                };

                let rows = match stmt
                    .query_and_then([], |row| {
                        let position: i64 = row.get("position")?;
                        let commitment: Vec<u8> = row.get("commitment")?;
                        let commitment = <[u8; 32]>::try_from(commitment)
                            .map_err(|_| anyhow::anyhow!("commitment was of incorrect length"))
                            .and_then(|array| {
                                StateCommitment::try_from(array).map_err(Into::into)
                            })?;
                        anyhow::Ok((Position::from(position as u64), commitment))
                    })
                    .context("couldn't query database")
                {
                    Ok(rows) => rows,
                    // If an error happens while querying the database, shove it inside the first
                    // returned item of the iterator, because we can't return an outer error:
                    Err(e) => {
                        yield_!(Err(e));
                        return;
                    }
                };

                // Actually iterate through the rows:
                for row in rows {
                    yield_!(row);
                }
            })
            .into_iter(),
        )
    }
}

impl Write for TreeStore<'_, '_> {
    fn set_position(&mut self, position: StoredPosition) -> Result<(), Self::Error> {
        let position = Option::from(position).map(|p: Position| u64::from(p) as i64);

        self.0
            .prepare_cached("UPDATE sct_position SET position = ?1")
            .context("failed to prepare position update")?
            .execute([&position])?;

        Ok(())
    }

    fn set_forgotten(&mut self, forgotten: Forgotten) -> Result<(), Self::Error> {
        let forgotten = u64::from(forgotten) as i64;

        self.0
            .prepare_cached("UPDATE sct_forgotten SET forgotten = ?1")
            .context("failed to prepare forgotten update")?
            .execute([&forgotten])?;

        Ok(())
    }

    fn add_hash(
        &mut self,
        position: Position,
        height: u8,
        hash: Hash,
        _essential: bool,
    ) -> Result<(), Self::Error> {
        let position = u64::from(position) as i64;
        let hash = hash.to_bytes().to_vec();

        self.0.prepare_cached(
            "INSERT INTO sct_hashes (position, height, hash) VALUES (?1, ?2, ?3) ON CONFLICT DO NOTHING"
        ).context("failed to prepare hash insert")?
            .execute((&position, &height, &hash))
            .context("failed to insert hash")?;

        Ok(())
    }

    fn add_commitment(
        &mut self,
        position: Position,
        commitment: StateCommitment,
    ) -> Result<(), Self::Error> {
        let position = u64::from(position) as i64;
        let commitment = <[u8; 32]>::from(commitment).to_vec();

        self.0.prepare_cached(
            "INSERT INTO sct_commitments (position, commitment) VALUES (?1, ?2) ON CONFLICT DO NOTHING"
        ).context("failed to prepare commitment insert")?
            .execute((&position, &commitment))
            .context("failed to insert commitment")?;

        Ok(())
    }

    fn delete_range(
        &mut self,
        below_height: u8,
        positions: Range<Position>,
    ) -> Result<(), Self::Error> {
        let start = u64::from(positions.start) as i64;
        let end = u64::from(positions.end) as i64;

        self.0
            .prepare_cached(
                "DELETE FROM sct_hashes WHERE position >= ?1 AND position < ?2 AND height < ?3",
            )
            .context("failed to prepare hash delete")?
            .execute((&start, &end, &below_height))
            .context("failed to delete hashes")?;

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use penumbra_tct::{StateCommitment, Witness};

    #[test]
    fn tree_store_spot_check() {
        // Set up the database:
        let mut db = r2d2_sqlite::rusqlite::Connection::open_in_memory().unwrap();
        let mut tx = db.transaction().unwrap();
        tx.execute_batch(include_str!("schema.sql")).unwrap();

        // Now we're exclusively going to talk to the db through the TreeStore:
        let mut store = TreeStore(&mut tx);

        // Check that the currently stored tree is the empty tree:
        let deserialized = penumbra_tct::Tree::from_reader(&mut store).unwrap();
        assert_eq!(deserialized, penumbra_tct::Tree::new());

        // Make some kind of tree:
        let mut tree = penumbra_tct::Tree::new();
        tree.insert(Witness::Keep, StateCommitment::try_from([0; 32]).unwrap())
            .unwrap();
        tree.end_block().unwrap();
        tree.insert(Witness::Forget, StateCommitment::try_from([1; 32]).unwrap())
            .unwrap();
        tree.end_epoch().unwrap();
        tree.insert(Witness::Keep, StateCommitment::try_from([2; 32]).unwrap())
            .unwrap();

        // Write the tree to the database:
        tree.to_writer(&mut store).unwrap();

        // Read the tree back from the database:
        let deserialized = penumbra_tct::Tree::from_reader(&mut store).unwrap();

        assert_eq!(tree, deserialized);
    }
}