Skip to main content

ouisync/store/
root_node.rs

1use super::error::Error;
2use crate::{
3    crypto::{Hash, sign::PublicKey},
4    db::{self, MAX_BIND_PARAMS},
5    debug::DebugPrinter,
6    protocol::{
7        BlockId, MultiBlockPresence, NodeState, Proof, RootNode, RootNodeFilter, RootNodeKind,
8        SingleBlockPresence, Summary,
9    },
10    version_vector::VersionVector,
11};
12use futures_util::{Stream, StreamExt, TryStreamExt};
13use sqlx::{FromRow, QueryBuilder, Row, sqlite::SqliteRow};
14use std::{cmp::Ordering, collections::HashMap, fmt, future};
15
16/// Status of receiving a root node
17#[derive(PartialEq, Eq, Debug)]
18pub(crate) enum RootNodeStatus {
19    /// The incoming node is more up to date than the nodes we already have. Contains info about
20    /// which part of the node is more up to date and the block presence of the latest node we have
21    /// from the same branch as the incoming node.
22    Updated(RootNodeUpdated, MultiBlockPresence),
23    /// The node is outdated - discard it.
24    Outdated,
25}
26
27#[derive(PartialEq, Eq, Debug)]
28pub(crate) enum RootNodeUpdated {
29    /// The node represents a new snapshot - write it into the store and requests its children.
30    Snapshot,
31    /// The node represents a snapshot we already have but its block presence indicated the peer potentially has some
32    /// blocks we don't have. Don't write it into the store but do request its children.
33    Blocks,
34}
35
36impl RootNodeStatus {
37    pub fn request_children(&self) -> Option<MultiBlockPresence> {
38        match self {
39            Self::Updated(_, block_presence) => Some(*block_presence),
40            Self::Outdated => None,
41        }
42    }
43
44    pub fn write(&self) -> bool {
45        match self {
46            Self::Updated(RootNodeUpdated::Snapshot, _) => true,
47            Self::Updated(RootNodeUpdated::Blocks, _) | Self::Outdated => false,
48        }
49    }
50}
51
52impl fmt::Display for RootNodeStatus {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        match self {
55            Self::Updated(RootNodeUpdated::Snapshot, _) => write!(f, "new snapshot"),
56            Self::Updated(RootNodeUpdated::Blocks, _) => write!(f, "new blocks"),
57            Self::Outdated => write!(f, "outdated"),
58        }
59    }
60}
61
62/// Creates a root node with the specified proof and summary.
63///
64/// A root node can be either "published" or "draft". A published node is one whose version vector
65/// is strictly greater than the version vector of any previous node in the same branch.
66/// A draft node is one whose version vector is equal to the version vector of the previous node.
67///
68/// The `filter` parameter determines what kind of node can be created.
69///
70/// Attempt to create a node whose version vector is less than or concurrent to the previous one is
71/// not allowed.
72///
73/// Returns also the kind of node (published or draft) that was actually created.
74pub(super) async fn create(
75    tx: &mut db::WriteTransaction,
76    proof: Proof,
77    mut summary: Summary,
78    filter: RootNodeFilter,
79) -> Result<(RootNode, RootNodeKind), Error> {
80    // Check that the root node to be created is newer than the latest existing root node in
81    // the same branch.
82    let old_vv: VersionVector = sqlx::query(
83        "SELECT versions
84         FROM snapshot_root_nodes
85         WHERE snapshot_id = (
86             SELECT MAX(snapshot_id)
87             FROM snapshot_root_nodes
88             WHERE writer_id = ?
89         )",
90    )
91    .bind(&proof.writer_id)
92    .map(|row| row.get(0))
93    .fetch_optional(&mut *tx)
94    .await?
95    .unwrap_or_else(VersionVector::new);
96
97    let kind = match (proof.version_vector.partial_cmp(&old_vv), filter) {
98        (Some(Ordering::Greater), _) => RootNodeKind::Published,
99        (Some(Ordering::Equal), RootNodeFilter::Any) => RootNodeKind::Draft,
100        (Some(Ordering::Equal), RootNodeFilter::Published) => return Err(Error::OutdatedRootNode),
101        (Some(Ordering::Less), _) => return Err(Error::OutdatedRootNode),
102        (None, _) => return Err(Error::ConcurrentRootNode),
103    };
104
105    // Inherit non-incomplete state from existing nodes with the same hash.
106    // (All nodes with the same hash have the same state so it's enough to fetch only the first one)
107    if summary.state == NodeState::Incomplete {
108        let state = sqlx::query(
109            "SELECT state FROM snapshot_root_nodes WHERE hash = ? AND state <> ? LIMIT 1",
110        )
111        .bind(&proof.hash)
112        .bind(NodeState::Incomplete)
113        .fetch_optional(&mut *tx)
114        .await?
115        .map(|row| row.get(0));
116
117        if let Some(state) = state {
118            summary.state = state;
119        }
120    }
121
122    let snapshot_id = sqlx::query(
123        "INSERT INTO snapshot_root_nodes (
124             writer_id,
125             versions,
126             hash,
127             signature,
128             state,
129             block_presence
130         )
131         VALUES (?, ?, ?, ?, ?, ?)
132         RETURNING snapshot_id",
133    )
134    .bind(&proof.writer_id)
135    .bind(&proof.version_vector)
136    .bind(&proof.hash)
137    .bind(&proof.signature)
138    .bind(summary.state)
139    .bind(&summary.block_presence)
140    .map(|row| row.get(0))
141    .fetch_one(tx)
142    .await?;
143
144    let node = RootNode {
145        snapshot_id,
146        proof,
147        summary,
148    };
149
150    Ok((node, kind))
151}
152
153/// Returns the latest approved root node of the specified branch.
154pub(super) async fn load_latest_approved(
155    conn: &mut db::Connection,
156    branch_id: &PublicKey,
157) -> Result<RootNode, Error> {
158    sqlx::query_as(
159        "SELECT
160             snapshot_id,
161             writer_id,
162             versions,
163             hash,
164             signature,
165             state,
166             block_presence
167         FROM
168             snapshot_root_nodes
169         WHERE
170             snapshot_id = (
171                 SELECT MAX(snapshot_id)
172                 FROM snapshot_root_nodes
173                 WHERE writer_id = ? AND state = ?
174             )
175        ",
176    )
177    .bind(branch_id)
178    .bind(NodeState::Approved)
179    .fetch_optional(conn)
180    .await?
181    .ok_or(Error::BranchNotFound)
182}
183
184/// Load the previous approved root node of the same writer.
185pub(super) async fn load_prev_approved(
186    conn: &mut db::Connection,
187    node: &RootNode,
188) -> Result<Option<RootNode>, Error> {
189    sqlx::query_as(
190        "SELECT
191            snapshot_id,
192            writer_id,
193            versions,
194            hash,
195            signature,
196            state,
197            block_presence
198         FROM snapshot_root_nodes
199         WHERE writer_id = ? AND state = ? AND snapshot_id < ?
200         ORDER BY snapshot_id DESC
201         LIMIT 1",
202    )
203    .bind(&node.proof.writer_id)
204    .bind(NodeState::Approved)
205    .bind(node.snapshot_id)
206    .fetch(conn)
207    .err_into()
208    .try_next()
209    .await
210}
211
212/// Return the latest approved root nodes of all known writers.
213pub(super) fn load_all_latest_approved(
214    conn: &mut db::Connection,
215) -> impl Stream<Item = Result<RootNode, Error>> + '_ {
216    sqlx::query_as(
217        "SELECT
218             snapshot_id,
219             writer_id,
220             versions,
221             hash,
222             signature,
223             state,
224             block_presence
225         FROM
226             snapshot_root_nodes
227         WHERE
228             snapshot_id IN (
229                 SELECT MAX(snapshot_id)
230                 FROM snapshot_root_nodes
231                 WHERE state = ?
232                 GROUP BY writer_id
233             )",
234    )
235    .bind(NodeState::Approved)
236    .fetch(conn)
237    .err_into()
238}
239
240/// Return the latest root nodes of all known writers in any state.
241pub(super) fn load_all_latest(
242    conn: &mut db::Connection,
243) -> impl Stream<Item = Result<RootNode, Error>> + '_ {
244    sqlx::query_as(
245        "SELECT
246             snapshot_id,
247             writer_id,
248             versions,
249             hash,
250             signature,
251             state,
252             block_presence
253         FROM
254             snapshot_root_nodes
255         WHERE
256             snapshot_id IN (
257                 SELECT MAX(snapshot_id)
258                 FROM snapshot_root_nodes
259                 GROUP BY writer_id
260             )",
261    )
262    .fetch(conn)
263    .err_into()
264}
265
266/// Returns all nodes with the specified hash
267pub(super) fn load_all_by_hash<'a>(
268    conn: &'a mut db::Connection,
269    hash: &'a Hash,
270) -> impl Stream<Item = Result<RootNode, Error>> + 'a {
271    sqlx::query_as(
272        "SELECT
273             snapshot_id,
274             writer_id,
275             versions,
276             hash,
277             signature,
278             state,
279             block_presence
280         FROM snapshot_root_nodes
281         WHERE hash = ?",
282    )
283    .bind(hash)
284    .fetch(conn)
285    .err_into()
286}
287
288/// For each provided block id that is missing, return the "best" `NodeState` of all root nodes that
289/// reference it. Blocks that are not referenced from any root node of that are not missing are
290/// excluded from the returned map.
291pub(super) async fn load_node_states_of_missing(
292    conn: &mut db::Connection,
293    block_ids: &[BlockId],
294) -> Result<HashMap<BlockId, NodeState>, Error> {
295    let mut output = HashMap::with_capacity(block_ids.len());
296
297    if block_ids.is_empty() {
298        return Ok(output);
299    }
300
301    for block_ids_chunk in block_ids.chunks(MAX_BIND_PARAMS - 1) {
302        let mut builder = QueryBuilder::new(
303            "WITH RECURSIVE
304                 child_nodes(block_id, parent) AS (
305                     SELECT block_id, parent
306                         FROM snapshot_leaf_nodes
307                         WHERE block_presence = ",
308        );
309        builder.push_bind(SingleBlockPresence::Missing);
310        builder.push(" AND block_id IN (");
311
312        let mut separated = builder.separated(", ");
313        for block_id in block_ids_chunk {
314            separated.push_bind(block_id);
315        }
316
317        builder.push(
318            ")
319                     UNION
320                     SELECT c.block_id, i.parent
321                         FROM snapshot_inner_nodes i INNER JOIN child_nodes c
322                         WHERE i.hash = c.parent
323                 )
324             SELECT c.block_id, r.state
325                 FROM snapshot_root_nodes r INNER JOIN child_nodes c
326                 WHERE r.hash = c.parent",
327        );
328
329        builder
330            .build()
331            .persistent(block_ids.len() == 1)
332            .fetch(&mut *conn)
333            .map_ok(|row| (row.get::<BlockId, _>(0), row.get::<NodeState, _>(1)))
334            .try_for_each(|(block_id, new)| {
335                output
336                    .entry(block_id)
337                    .and_modify(|old| *old = best_node_state(*old, new))
338                    .or_insert(new);
339
340                future::ready(Ok(()))
341            })
342            .await?;
343    }
344
345    Ok(output)
346}
347
348/// Combines two node states, picking the "best" one (`Approved` > `Complete` > `Incomplete` >
349/// `Rejected`).
350fn best_node_state(old: NodeState, new: NodeState) -> NodeState {
351    use NodeState as S;
352
353    match (old, new) {
354        (S::Incomplete | S::Complete | S::Approved | S::Rejected, S::Approved)
355        | (S::Approved, S::Incomplete | S::Complete | S::Rejected) => S::Approved,
356        (S::Incomplete | S::Complete | S::Rejected, S::Complete)
357        | (S::Complete, S::Incomplete | S::Rejected) => S::Complete,
358        (S::Incomplete | S::Rejected, S::Incomplete) | (S::Incomplete, S::Rejected) => {
359            S::Incomplete
360        }
361        (S::Rejected, S::Rejected) => S::Rejected,
362    }
363}
364
365/// Removes the given root node including all its descendants that are not referenced from any
366/// other root nodes.
367pub(super) async fn remove(tx: &mut db::WriteTransaction, node: &RootNode) -> Result<(), Error> {
368    // This uses db triggers to delete the whole snapshot.
369    sqlx::query("DELETE FROM snapshot_root_nodes WHERE snapshot_id = ?")
370        .bind(node.snapshot_id)
371        .execute(tx)
372        .await?;
373
374    Ok(())
375}
376
377/// Removes all root nodes that are older than the given node and are on the same branch.
378pub(super) async fn remove_older(
379    tx: &mut db::WriteTransaction,
380    node: &RootNode,
381) -> Result<(), Error> {
382    // This uses db triggers to delete the whole snapshot.
383    sqlx::query("DELETE FROM snapshot_root_nodes WHERE snapshot_id < ? AND writer_id = ?")
384        .bind(node.snapshot_id)
385        .bind(&node.proof.writer_id)
386        .execute(tx)
387        .await?;
388
389    Ok(())
390}
391
392/// Removes all root nodes that are older than the given node and are on the same branch and are
393/// not complete.
394///
395/// Returns whether any node was removed.
396pub(super) async fn remove_older_incomplete(
397    tx: &mut db::WriteTransaction,
398    node: &RootNode,
399) -> Result<bool, Error> {
400    let mut changed = false;
401
402    // This uses db triggers to delete the whole snapshot.
403    sqlx::query(
404        "DELETE FROM snapshot_root_nodes
405         WHERE snapshot_id < ? AND writer_id = ? AND state IN (?, ?)
406         RETURNING hash",
407    )
408    .bind(node.snapshot_id)
409    .bind(&node.proof.writer_id)
410    .bind(NodeState::Incomplete)
411    .bind(NodeState::Rejected)
412    .fetch(tx)
413    .try_for_each(|row| {
414        tracing::trace!(hash = ?row.get::<Hash, _>(0), "outdated incomplete snapshot removed");
415        changed = true;
416        future::ready(Ok(()))
417    })
418    .await?;
419
420    Ok(changed)
421}
422
423/// Update the summaries of all nodes with the specified hash.
424pub(super) async fn update_summaries(
425    tx: &mut db::WriteTransaction,
426    hash: &Hash,
427    summary: Summary,
428) -> Result<NodeState, Error> {
429    let state = sqlx::query(
430        "UPDATE snapshot_root_nodes
431         SET block_presence = ?,
432             state = CASE state WHEN ? THEN ? ELSE state END
433         WHERE hash = ?
434         RETURNING state
435         ",
436    )
437    .bind(&summary.block_presence)
438    .bind(NodeState::Incomplete)
439    .bind(summary.state)
440    .bind(hash)
441    .fetch_optional(tx)
442    .await?
443    .map(|row| row.get(0))
444    .unwrap_or(NodeState::Incomplete);
445
446    Ok(state)
447}
448
449/// Check whether the `old` snapshot can serve as a fallback for the `new` snapshot.
450/// A snapshot can serve as a fallback if there is at least one locator that points to a missing
451/// block in `new` but present block in `old`.
452pub(super) async fn check_fallback(
453    conn: &mut db::Connection,
454    old: &RootNode,
455    new: &RootNode,
456) -> Result<bool, Error> {
457    // TODO: verify this query is efficient, especially on large repositories
458
459    Ok(sqlx::query(
460        "WITH RECURSIVE
461             inner_nodes_old(hash) AS (
462                 SELECT i.hash
463                     FROM snapshot_inner_nodes AS i
464                     INNER JOIN snapshot_root_nodes AS r ON r.hash = i.parent
465                     WHERE r.snapshot_id = ?
466                 UNION ALL
467                 SELECT c.hash
468                     FROM snapshot_inner_nodes AS c
469                     INNER JOIN inner_nodes_old AS p ON p.hash = c.parent
470             ),
471             inner_nodes_new(hash) AS (
472                 SELECT i.hash
473                     FROM snapshot_inner_nodes AS i
474                     INNER JOIN snapshot_root_nodes AS r ON r.hash = i.parent
475                     WHERE r.snapshot_id = ?
476                 UNION ALL
477                 SELECT c.hash
478                     FROM snapshot_inner_nodes AS c
479                     INNER JOIN inner_nodes_new AS p ON p.hash = c.parent
480             )
481         SELECT locator
482             FROM snapshot_leaf_nodes
483             WHERE block_presence = ? AND parent IN inner_nodes_old
484         INTERSECT
485         SELECT locator
486             FROM snapshot_leaf_nodes
487             WHERE block_presence = ? AND parent IN inner_nodes_new
488         LIMIT 1",
489    )
490    .bind(old.snapshot_id)
491    .bind(new.snapshot_id)
492    .bind(SingleBlockPresence::Present)
493    .bind(SingleBlockPresence::Missing)
494    .fetch_optional(conn)
495    .await?
496    .is_some())
497}
498
499/// Approve the nodes with the specified hash.
500pub(super) fn approve<'a>(
501    tx: &'a mut db::WriteTransaction,
502    hash: &'a Hash,
503) -> impl Stream<Item = Result<PublicKey, Error>> + 'a {
504    set_state(tx, hash, NodeState::Approved)
505}
506
507/// Reject the nodes with the specified hash.
508pub(super) fn reject<'a>(
509    tx: &'a mut db::WriteTransaction,
510    hash: &'a Hash,
511) -> impl Stream<Item = Result<PublicKey, Error>> + 'a {
512    set_state(tx, hash, NodeState::Rejected)
513}
514
515/// Set the state of the nodes with the specified hash and returns the writer ids of the updated
516/// nodes.
517fn set_state<'a>(
518    tx: &'a mut db::WriteTransaction,
519    hash: &'a Hash,
520    state: NodeState,
521) -> impl Stream<Item = Result<PublicKey, Error>> + 'a {
522    sqlx::query("UPDATE snapshot_root_nodes SET state = ? WHERE hash = ? RETURNING writer_id")
523        .bind(state)
524        .bind(hash)
525        .fetch(tx)
526        .map_ok(|row| row.get(0))
527        .err_into()
528}
529
530/// Returns all writer ids.
531pub(super) fn load_writer_ids(
532    conn: &mut db::Connection,
533) -> impl Stream<Item = Result<PublicKey, Error>> + '_ {
534    sqlx::query("SELECT DISTINCT writer_id FROM snapshot_root_nodes")
535        .fetch(conn)
536        .map_ok(|row| row.get(0))
537        .err_into()
538}
539
540/// Returns the writer ids of the nodes with the specified hash.
541pub(super) fn load_writer_ids_by_hash<'a>(
542    conn: &'a mut db::Connection,
543    hash: &'a Hash,
544) -> impl Stream<Item = Result<PublicKey, Error>> + 'a {
545    sqlx::query("SELECT DISTINCT writer_id FROM snapshot_root_nodes WHERE hash = ?")
546        .bind(hash)
547        .fetch(conn)
548        .map_ok(|row| row.get(0))
549        .err_into()
550}
551
552pub(super) async fn status(
553    conn: &mut db::Connection,
554    new_proof: &Proof,
555    new_block_presence: &MultiBlockPresence,
556) -> Result<RootNodeStatus, Error> {
557    let mut updated = RootNodeUpdated::Snapshot;
558    let mut block_presence = MultiBlockPresence::None;
559
560    let mut old_nodes = load_all_latest(conn);
561    while let Some(old_node) = old_nodes.try_next().await? {
562        match new_proof
563            .version_vector
564            .partial_cmp(&old_node.proof.version_vector)
565        {
566            Some(Ordering::Less) => {
567                // The incoming node is outdated compared to at least one existing node - discard
568                // it.
569                return Ok(RootNodeStatus::Outdated);
570            }
571            Some(Ordering::Equal) => {
572                if new_proof.hash == old_node.proof.hash {
573                    // The incoming node has the same version vector and the same hash as one of the
574                    // existing nodes which means its effectively the same node (except possibly in
575                    // a different branch). There is no point inserting it but if the incoming
576                    // summary is potentially more up-to-date than the existing one, we still want
577                    // to request the children. Otherwise we discard it.
578                    if old_node
579                        .summary
580                        .block_presence
581                        .is_outdated(new_block_presence)
582                    {
583                        updated = RootNodeUpdated::Blocks;
584                    } else {
585                        return Ok(RootNodeStatus::Outdated);
586                    }
587                } else {
588                    tracing::warn!(
589                        vv = ?old_node.proof.version_vector,
590                        old_writer_id = ?old_node.proof.writer_id,
591                        new_writer_id = ?new_proof.writer_id,
592                        old_hash = ?old_node.proof.hash,
593                        new_hash = ?new_proof.hash,
594                        "Received root node invalid - broken invariant: same vv but different hash"
595                    );
596
597                    return Ok(RootNodeStatus::Outdated);
598                }
599            }
600            Some(Ordering::Greater) => (),
601            None => {
602                if new_proof.writer_id == old_node.proof.writer_id {
603                    tracing::warn!(
604                        old_vv = ?old_node.proof.version_vector,
605                        new_vv = ?new_proof.version_vector,
606                        writer_id = ?new_proof.writer_id,
607                        "Received root node invalid - broken invariant: concurrency within branch is not allowed"
608                    );
609
610                    return Ok(RootNodeStatus::Outdated);
611                }
612            }
613        }
614
615        if old_node.proof.writer_id == new_proof.writer_id {
616            block_presence = old_node.summary.block_presence;
617        }
618    }
619
620    Ok(RootNodeStatus::Updated(updated, block_presence))
621}
622
623pub(super) async fn debug_print(conn: &mut db::Connection, printer: DebugPrinter) {
624    let mut roots = sqlx::query_as::<_, RootNode>(
625        "SELECT
626             snapshot_id,
627             writer_id,
628             versions,
629             hash,
630             signature,
631             state,
632             block_presence
633         FROM snapshot_root_nodes
634         ORDER BY snapshot_id DESC",
635    )
636    .fetch(conn);
637
638    while let Some(root_node) = roots.next().await {
639        match root_node {
640            Ok(root_node) => {
641                printer.debug(&format_args!(
642                    "RootNode: snapshot_id:{:?}, writer_id:{:?}, vv:{:?}, state:{:?}",
643                    root_node.snapshot_id,
644                    root_node.proof.writer_id,
645                    root_node.proof.version_vector,
646                    root_node.summary.state
647                ));
648            }
649            Err(err) => {
650                printer.debug(&format_args!("RootNode: error: {err:?}"));
651            }
652        }
653    }
654}
655
656/// Returns a stream of all root nodes corresponding to the specified writer ordered from the
657/// most recent to the least recent.
658#[cfg(test)]
659pub(super) fn load_all_by_writer<'a>(
660    conn: &'a mut db::Connection,
661    writer_id: &'a PublicKey,
662) -> impl Stream<Item = Result<RootNode, Error>> + 'a {
663    sqlx::query_as(
664        "SELECT
665             snapshot_id,
666             writer_id,
667             versions,
668             hash,
669             signature,
670             state,
671             block_presence
672         FROM snapshot_root_nodes
673         WHERE writer_id = ?
674         ORDER BY snapshot_id DESC",
675    )
676    .bind(writer_id) // needed to satisfy the borrow checker.
677    .fetch(conn)
678    .err_into()
679}
680
681impl FromRow<'_, SqliteRow> for RootNode {
682    fn from_row(row: &SqliteRow) -> Result<Self, sqlx::Error> {
683        Ok(RootNode {
684            snapshot_id: row.try_get(0)?,
685            proof: Proof::new_unchecked(
686                row.try_get(1)?,
687                row.try_get(2)?,
688                row.try_get(3)?,
689                row.try_get(4)?,
690            ),
691            summary: Summary {
692                state: row.try_get(5)?,
693                block_presence: row.try_get(6)?,
694            },
695        })
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use std::slice;
702
703    use super::super::{SnapshotWriter, Store};
704    use super::*;
705    use crate::{crypto::sign::Keypair, protocol::test_utils::Snapshot};
706    use assert_matches::assert_matches;
707    use tempfile::TempDir;
708
709    #[tokio::test]
710    async fn create_new() {
711        let (_base_dir, pool) = setup().await;
712
713        let writer_id = PublicKey::random();
714        let write_keys = Keypair::random();
715        let hash = rand::random();
716
717        let mut tx = pool.begin_write().await.unwrap();
718
719        let (node0, _) = create(
720            &mut tx,
721            Proof::new(
722                writer_id,
723                VersionVector::first(writer_id),
724                hash,
725                &write_keys,
726            ),
727            Summary::INCOMPLETE,
728            RootNodeFilter::Any,
729        )
730        .await
731        .unwrap();
732        assert_eq!(node0.proof.hash, hash);
733
734        let nodes: Vec<_> = load_all_by_writer(&mut tx, &writer_id)
735            .try_collect()
736            .await
737            .unwrap();
738        assert_eq!(nodes.len(), 1);
739        assert_eq!(nodes[0], node0);
740    }
741
742    #[tokio::test]
743    async fn create_draft() {
744        let (_base_dir, pool) = setup().await;
745
746        let writer_id = PublicKey::random();
747        let write_keys = Keypair::random();
748
749        let mut tx = pool.begin_write().await.unwrap();
750
751        let (node0, kind) = create(
752            &mut tx,
753            Proof::new(
754                writer_id,
755                VersionVector::first(writer_id),
756                rand::random(),
757                &write_keys,
758            ),
759            Summary::INCOMPLETE,
760            RootNodeFilter::Any,
761        )
762        .await
763        .unwrap();
764        assert_eq!(kind, RootNodeKind::Published);
765
766        let (_node1, kind) = create(
767            &mut tx,
768            Proof::new(
769                writer_id,
770                node0.proof.version_vector.clone(),
771                rand::random(),
772                &write_keys,
773            ),
774            Summary::INCOMPLETE,
775            RootNodeFilter::Any,
776        )
777        .await
778        .unwrap();
779        assert_eq!(kind, RootNodeKind::Draft);
780    }
781
782    #[tokio::test]
783    async fn attempt_to_create_outdated_node() {
784        let (_base_dir, pool) = setup().await;
785
786        let writer_id = PublicKey::random();
787        let write_keys = Keypair::random();
788        let hash = rand::random();
789
790        let mut tx = pool.begin_write().await.unwrap();
791
792        let vv0 = VersionVector::first(writer_id);
793        let vv1 = vv0.clone().incremented(writer_id);
794
795        create(
796            &mut tx,
797            Proof::new(writer_id, vv1.clone(), hash, &write_keys),
798            Summary::INCOMPLETE,
799            RootNodeFilter::Any,
800        )
801        .await
802        .unwrap();
803
804        // Same vv
805        assert_matches!(
806            create(
807                &mut tx,
808                Proof::new(writer_id, vv1, hash, &write_keys),
809                Summary::INCOMPLETE,
810                RootNodeFilter::Published, // With `RootNodeFilter::Any` this would be allowed
811            )
812            .await,
813            Err(Error::OutdatedRootNode)
814        );
815
816        // Old vv
817        assert_matches!(
818            create(
819                &mut tx,
820                Proof::new(writer_id, vv0, hash, &write_keys),
821                Summary::INCOMPLETE,
822                RootNodeFilter::Any,
823            )
824            .await,
825            Err(Error::OutdatedRootNode)
826        );
827    }
828
829    #[tokio::test]
830    async fn load_node_states_of_missing_blocks() {
831        let (_base_dir, pool) = setup().await;
832        let store = Store::new(pool);
833
834        let write_keys = Keypair::random();
835        let branch_id = PublicKey::random();
836        let snapshot = Snapshot::generate(&mut rand::rng(), 4);
837
838        let mut writer = SnapshotWriter::begin(&store, &snapshot)
839            .await
840            .save_nodes(&write_keys, branch_id, VersionVector::first(branch_id))
841            .await;
842
843        // Make one block present.
844        let (present_id, present_block) = snapshot.blocks().iter().next().unwrap();
845        writer
846            .client_writer()
847            .save_blocks(slice::from_ref(present_block))
848            .await
849            .unwrap();
850        writer.commit().await;
851
852        let unreferenced_id: BlockId = rand::random();
853        let block_ids: Vec<_> = snapshot
854            .blocks()
855            .keys()
856            .copied()
857            .chain([unreferenced_id])
858            .collect();
859
860        let mut tx = store.db().begin_read().await.unwrap();
861        let actual = load_node_states_of_missing(&mut tx, &block_ids)
862            .await
863            .unwrap();
864
865        // Present and unreferenced blocks are excluded.
866        let expected: HashMap<_, _> = snapshot
867            .blocks()
868            .keys()
869            .filter(|block_id| *block_id != present_id)
870            .map(|block_id| (*block_id, NodeState::Approved))
871            .collect();
872
873        assert_eq!(actual, expected);
874    }
875
876    async fn setup() -> (TempDir, db::Pool) {
877        db::create_temp().await.unwrap()
878    }
879}