calimero_storage/interface.rs
1//! Storage interface implementing a repository pattern for CRDT-based data.
2//!
3//! This module provides the primary API for interacting with the storage system,
4//! handling entity persistence, hierarchy management, and distributed synchronization.
5//!
6//! # Architecture
7//!
8//! Calimero uses a **hybrid CRDT model**:
9//! - **Operation-based (CmRDT)**: Local changes emit [`Action`]s propagated to peers
10//! - **State-based (CvRDT)**: Merkle tree comparison for catch-up/reconciliation
11//!
12//! Each element maintains two Merkle hashes (own data, and full including descendants)
13//! enabling efficient tree comparison—only subtrees with differing hashes need examination.
14//!
15//! # API Entry Points
16//!
17//! **Direct Operations:**
18//! - [`save()`](Interface::save()) - Save/update entities
19//! - [`add_child_to()`](Interface::add_child_to()) - Add to collections
20//! - [`remove_child_from()`](Interface::remove_child_from()) - Remove from collections
21//! - [`find_by_id()`](Interface::find_by_id()) - Direct lookup
22//!
23//! **Synchronization:**
24//! - [`apply_action()`](Interface::apply_action()) - Execute remote changes
25//! - [`compare_trees()`](Interface::compare_trees()) - Generate sync actions
26//!
27//! # Conflict Resolution
28//!
29//! - Last-write-wins based on timestamps
30//! - Orphaned children (from out-of-order ops) stored temporarily
31//! - Future comparison reconciles inconsistencies
32//!
33//! See the [crate README](../README.md) for detailed design documentation.
34
35#[cfg(test)]
36#[path = "tests/interface.rs"]
37mod tests;
38
39use core::fmt::Debug;
40use core::marker::PhantomData;
41use std::collections::BTreeMap;
42
43use borsh::{from_slice, to_vec};
44use indexmap::IndexMap;
45use sha2::{Digest, Sha256};
46use tracing::{debug, info, warn};
47
48use crate::address::Id;
49use crate::constants;
50use crate::entities::{ChildInfo, Data, Metadata, SignatureData, StorageType};
51use crate::env::time_now;
52use crate::index::Index;
53use crate::store::{Key, MainStorage, StorageAdaptor};
54
55// Re-export types for convenience
56pub use crate::action::{Action, ComparisonData};
57pub use crate::error::StorageError;
58
59/// Convenient type alias for the main storage system.
60pub type MainInterface = Interface<MainStorage>;
61
62/// The primary interface for the storage system.
63#[derive(Debug, Default, Clone)]
64#[non_exhaustive]
65pub struct Interface<S: StorageAdaptor = MainStorage>(PhantomData<S>);
66
67impl<S: StorageAdaptor> Interface<S> {
68 /// Adds a child entity to a parent's collection.
69 ///
70 /// Updates Merkle hashes and generates sync actions automatically.
71 ///
72 /// # Errors
73 /// - `SerializationError` if child can't be encoded
74 /// - `IndexNotFound` if parent doesn't exist
75 ///
76 pub fn add_child_to<D: Data>(parent_id: Id, child: &mut D) -> Result<bool, StorageError> {
77 if !child.element().is_dirty() {
78 return Ok(false);
79 }
80
81 let data = to_vec(child).map_err(|e| StorageError::SerializationError(e.into()))?;
82
83 let own_hash = Sha256::digest(&data).into();
84
85 <Index<S>>::add_child_to(
86 parent_id,
87 ChildInfo::new(child.id(), own_hash, child.element().metadata.clone()),
88 )?;
89
90 let Some(hash) = Self::save_raw(child.id(), data, child.element().metadata.clone())? else {
91 return Ok(false);
92 };
93
94 child.element_mut().is_dirty = false;
95 child.element_mut().merkle_hash = hash;
96
97 Ok(true)
98 }
99
100 /// Applies a synchronization action from a remote node.
101 ///
102 /// Handles Add/Update/Delete actions, creating missing ancestors if needed.
103 /// Generates Compare action for hash verification after applying changes.
104 ///
105 /// # Errors
106 /// - `DeserializationError` if action data is invalid
107 /// - `ActionNotAllowed` if Compare action is passed directly
108 ///
109 pub fn apply_action(action: Action) -> Result<(), StorageError> {
110 // Verify that the action timestamp is not too far in the future
111 // to prevent LWW Time Drift attacks.
112 verify_action_timestamp(&action)?;
113
114 // TODO: refactor to a separate function.
115 // Run verification logic before applying
116 match &action {
117 Action::Add {
118 metadata, data, id, ..
119 }
120 | Action::Update {
121 metadata, data, id, ..
122 } => {
123 Self::verify_action_update(&action)?;
124
125 match &metadata.storage_type {
126 StorageType::User {
127 owner,
128 signature_data,
129 } => {
130 debug!(
131 %id,
132 created_at = metadata.created_at,
133 updated_at = metadata.updated_at(),
134 %owner,
135 ?owner,
136 data_len = data.len(),
137 "Interface::apply_action received upsert user action"
138 );
139 let sig_data = signature_data.as_ref().ok_or(StorageError::InvalidData(
140 "Remote User action must be signed".to_owned(),
141 ))?;
142
143 debug!(
144 %id,
145 ?id,
146 created_at = metadata.created_at,
147 updated_at = metadata.updated_at(),
148 %owner,
149 ?owner,
150 data_len = data.len(),
151 ?sig_data.signature,
152 sig_data.nonce,
153 "Interface::apply_action received upsert user action: sig data"
154 );
155
156 let payload = action.payload_for_signing();
157
158 // Replay protection check
159 let new_nonce = sig_data.nonce;
160 let last_nonce = <Index<S>>::get_metadata(*id)?
161 .map(|m| *m.updated_at)
162 .unwrap_or(0);
163
164 if new_nonce <= last_nonce {
165 return Err(StorageError::NonceReplay(Box::new((*owner, new_nonce))));
166 }
167
168 let verification_result = crate::env::ed25519_verify(
169 &sig_data.signature,
170 owner.digest(),
171 &payload,
172 );
173
174 if !verification_result {
175 return Err(StorageError::InvalidSignature);
176 }
177 }
178 StorageType::Frozen => {
179 debug!(
180 %id,
181 created_at = metadata.created_at,
182 updated_at = metadata.updated_at(),
183 data_len = data.len(),
184 "Interface::apply_action received upsert frozen action"
185 );
186 verify_frozen_action_upsert(&action, data)?;
187 }
188 StorageType::Public => { /* No special checks */ }
189 }
190 }
191 Action::DeleteRef { id, metadata, .. } => {
192 // Get the metadata of the item being deleted to check its domain
193 let existing_metadata = <Index<S>>::get_metadata(*id)?
194 .ok_or_else(|| StorageError::IndexNotFound(*id))?;
195
196 match existing_metadata.storage_type {
197 StorageType::Frozen => {
198 debug!(
199 %id,
200 created_at = metadata.created_at,
201 updated_at = metadata.updated_at(),
202 "Interface::apply_action received delete frozen action"
203 );
204 return Err(StorageError::ActionNotAllowed(
205 "Frozen data cannot be deleted".to_owned(),
206 ));
207 }
208 StorageType::User {
209 owner: existing_owner,
210 ..
211 } => {
212 // Verify the action's metadata, which contains the signature
213 match &metadata.storage_type {
214 StorageType::User {
215 owner,
216 signature_data,
217 } => {
218 // Check it matches the owner on record
219 if *owner != existing_owner {
220 return Err(StorageError::InvalidSignature);
221 }
222
223 let sig_data =
224 signature_data.as_ref().ok_or(StorageError::InvalidData(
225 "Remote User delete must be signed".to_owned(),
226 ))?;
227
228 // TODO: refactor to a separate function.
229 // Replay protection check
230 let new_nonce = sig_data.nonce;
231 // The nonce is the `deleted_at` time. We check it against the
232 // last `updated_at` time stored in the index.
233 let last_nonce = *existing_metadata.updated_at;
234
235 if new_nonce <= last_nonce {
236 return Err(StorageError::NonceReplay(Box::new((
237 *owner, new_nonce,
238 ))));
239 }
240
241 let payload = action.payload_for_signing();
242 let verification_result = crate::env::ed25519_verify(
243 &sig_data.signature,
244 owner.digest(),
245 &payload,
246 );
247
248 if !verification_result {
249 return Err(StorageError::InvalidSignature);
250 }
251 }
252 _ => {
253 // Action metadata is not User, but existing is.
254 return Err(StorageError::InvalidSignature);
255 }
256 }
257 }
258 StorageType::Public => { /* No special checks */ }
259 }
260 }
261 Action::Compare { .. } => { /* No checks needed */ }
262 }
263
264 match action {
265 Action::Add {
266 id,
267 data,
268 // Note: We track both parent and collection for full metadata,
269 // though parent_id alone would suffice for tree structure
270 ancestors,
271 metadata,
272 }
273 | Action::Update {
274 id,
275 data,
276 ancestors,
277 metadata,
278 } => {
279 debug!(
280 %id,
281 ancestor_ids = ?ancestors.iter().map(|a| a.id()).collect::<Vec<_>>(),
282 created_at = metadata.created_at,
283 updated_at = metadata.updated_at(),
284 data_len = data.len(),
285 "Interface::apply_action preparing to upsert entity"
286 );
287 let mut parent = None;
288 for this in ancestors.iter().rev() {
289 let parent = parent.replace(this);
290
291 if <Index<S>>::has_index(this.id()) {
292 debug!(
293 ancestor = %this.id(),
294 "Ancestor already present in index - skipping creation"
295 );
296 continue;
297 }
298
299 let Some(parent) = parent else {
300 debug!(
301 ancestor = %this.id(),
302 "Creating ancestor as root index entry (no parent yet)"
303 );
304 <Index<S>>::add_root(this.clone())?;
305
306 continue;
307 };
308
309 // Set up parent-child relationship
310 debug!(
311 parent = %parent.id(),
312 child = %this.id(),
313 "Linking ancestor to parent in index"
314 );
315 <Index<S>>::add_child_to(parent.id(), this.clone())?;
316 }
317
318 // For new entities, create a minimal index entry first to avoid orphan errors
319 if !<Index<S>>::has_index(id) {
320 if id.is_root() {
321 debug!(%id, "Creating root index entry for entity");
322 <Index<S>>::add_root(ChildInfo::new(id, [0; 32], metadata.clone()))?;
323 } else if let Some(parent) = parent {
324 // Create minimal index entry with placeholder hash
325 let placeholder_hash = Sha256::digest(&data).into();
326 debug!(
327 %id,
328 parent = %parent.id(),
329 placeholder_hash = ?placeholder_hash,
330 "Creating placeholder child entry pending save"
331 );
332 <Index<S>>::add_child_to(
333 parent.id(),
334 ChildInfo::new(id, placeholder_hash, metadata.clone()),
335 )?;
336 }
337 }
338
339 // Save data (might merge, producing different hash)
340 let Some((_, _full_hash)) = Self::save_internal(id, &data, metadata.clone())?
341 else {
342 debug!(
343 %id,
344 "Remote action produced no storage change (save_internal returned None)"
345 );
346 // we didn't save anything, so we skip updating the ancestors
347 return Ok(());
348 };
349
350 debug!(
351 %id,
352 ancestor_count = ancestors.len(),
353 "Applied Add/Update action to storage"
354 );
355
356 // ALWAYS update parent with correct hash after save (handles merging)
357 // save_internal calls update_hash_for which updates child_index.own_hash
358 if let Some(parent) = parent {
359 let (_, own_hash) =
360 <Index<S>>::get_hashes_for(id)?.ok_or(StorageError::IndexNotFound(id))?;
361
362 // Update parent relationship with the actual hash after any merging
363 debug!(
364 %id,
365 parent = %parent.id(),
366 own_hash = ?own_hash,
367 "Updating parent child info with final hash"
368 );
369 <Index<S>>::add_child_to(
370 parent.id(),
371 ChildInfo::new(id, own_hash, metadata.clone()),
372 )?;
373 }
374
375 crate::delta::push_action(Action::Compare { id });
376 debug!(%id, "Queued compare action after apply");
377 }
378 Action::Compare { .. } => {
379 return Err(StorageError::ActionNotAllowed("Compare".to_owned()))
380 }
381 Action::DeleteRef { id, deleted_at, .. } => {
382 Self::apply_delete_ref_action(id, deleted_at)?;
383 }
384 };
385
386 debug!("Interface::apply_action completed");
387
388 Ok(())
389 }
390
391 /// Applies DeleteRef action with CRDT conflict resolution.
392 ///
393 /// Uses guard clauses for clarity (KISS principle).
394 /// Handles three cases:
395 /// 1. Already deleted - update tombstone if newer
396 /// 2. Exists locally - compare timestamps (LWW)
397 /// 3. Never seen - ignore (could create tombstone in future)
398 ///
399 /// IMPORTANT: When deletion wins, we must also update the parent's children
400 /// list and recalculate ancestor hashes. This ensures convergence with nodes
401 /// that performed the deletion locally.
402 fn apply_delete_ref_action(id: Id, deleted_at: u64) -> Result<(), StorageError> {
403 // Guard: Already deleted, check if this deletion is newer
404 if <Index<S>>::is_deleted(id)? {
405 // Already has tombstone, use later deletion timestamp
406 let _ignored = <Index<S>>::mark_deleted(id, deleted_at);
407 return Ok(());
408 }
409
410 // Guard: Entity doesn't exist, nothing to delete
411 let Some(metadata) = <Index<S>>::get_metadata(id)? else {
412 // Entity doesn't exist - no tombstone needed
413 // CRDT rationale: Deleting non-existent entity is idempotent no-op.
414 return Ok(());
415 };
416
417 // Guard: Local update is newer, deletion loses
418 if deleted_at < *metadata.updated_at {
419 // Local update wins, ignore older deletion
420 return Ok(());
421 }
422
423 // Get parent ID BEFORE deleting - we need it to update the Merkle tree
424 let parent_id = <Index<S>>::get_parent_id(id)?;
425
426 // Deletion wins - apply it
427 let _ignored = S::storage_remove(Key::Entry(id));
428 let _ignored = <Index<S>>::mark_deleted(id, deleted_at);
429
430 // CRITICAL: Update parent's children list and recalculate hashes
431 // Without this, the receiving node would have a different root hash than
432 // the node that performed the deletion locally.
433 if let Some(parent_id) = parent_id {
434 // Remove child from parent's children list and recalculate hashes
435 <Index<S>>::update_parent_after_child_removal(parent_id, id)?;
436 <Index<S>>::recalculate_ancestor_hashes_for(parent_id)?;
437 }
438
439 Ok(())
440 }
441
442 /// Retrieves all children in a collection.
443 ///
444 /// Returns deserialized child entities. Order is not guaranteed.
445 ///
446 /// # Errors
447 /// - `IndexNotFound` if parent doesn't exist
448 /// - `DeserializationError` if child data is corrupt
449 ///
450 pub fn children_of<D: Data>(parent_id: Id) -> Result<Vec<D>, StorageError> {
451 let children_info = <Index<S>>::get_children_of(parent_id)?;
452 let mut children = Vec::new();
453 for child_info in children_info {
454 if let Some(child) = Self::find_by_id(child_info.id())? {
455 children.push(child);
456 }
457 }
458 Ok(children)
459 }
460
461 /// Retrieves child metadata without deserializing full data.
462 ///
463 /// Returns IDs, hashes, and timestamps only. More efficient than [`children_of()`](Self::children_of()).
464 ///
465 /// # Errors
466 /// Returns error if index lookup fails.
467 ///
468 pub fn child_info_for(parent_id: Id) -> Result<Vec<ChildInfo>, StorageError> {
469 <Index<S>>::get_children_of(parent_id)
470 }
471
472 /// Compares local and remote entity trees, generating sync actions.
473 ///
474 /// Compares Merkle hashes recursively, producing action lists for both sides.
475 /// Returns `(local_actions, remote_actions)` to bring trees into sync.
476 ///
477 /// # Errors
478 /// Returns error if index lookup or hash comparison fails.
479 ///
480 pub fn compare_trees(
481 foreign_entity_data: Option<Vec<u8>>,
482 foreign_index_data: ComparisonData,
483 ) -> Result<(Vec<Action>, Vec<Action>), StorageError> {
484 let mut actions = (vec![], vec![]);
485
486 let id = foreign_index_data.id;
487
488 let local_metadata = <Index<S>>::get_metadata(id)?;
489
490 let Some(local_entity) = Self::find_by_id_raw(id) else {
491 if let Some(foreign_entity) = foreign_entity_data {
492 // Local entity doesn't exist, so we need to add it
493 actions.0.push(Action::Add {
494 id,
495 data: foreign_entity,
496 ancestors: foreign_index_data.ancestors,
497 metadata: foreign_index_data.metadata,
498 });
499 }
500
501 return Ok(actions);
502 };
503
504 let local_metadata = local_metadata.ok_or(StorageError::IndexNotFound(id))?;
505
506 let (local_full_hash, local_own_hash) =
507 <Index<S>>::get_hashes_for(id)?.ok_or(StorageError::IndexNotFound(id))?;
508
509 // Compare full Merkle hashes
510 if local_full_hash == foreign_index_data.full_hash {
511 return Ok(actions);
512 }
513
514 // Compare own hashes and timestamps
515 if local_own_hash != foreign_index_data.own_hash {
516 match foreign_entity_data {
517 Some(foreign_entity_data)
518 if local_metadata.updated_at <= foreign_index_data.metadata.updated_at =>
519 {
520 actions.0.push(Action::Update {
521 id,
522 data: foreign_entity_data,
523 ancestors: foreign_index_data.ancestors,
524 metadata: foreign_index_data.metadata,
525 });
526 }
527 _ => {
528 actions.1.push(Action::Update {
529 id,
530 data: local_entity,
531 ancestors: <Index<S>>::get_ancestors_of(id)?,
532 metadata: local_metadata,
533 });
534 }
535 }
536 }
537
538 // The list of collections from the type will be the same on both sides, as
539 // the type is the same.
540
541 let local_collection_names = <Index<S>>::get_collection_names_for(id)?;
542
543 let local_collections = local_collection_names
544 .into_iter()
545 .map(|name| {
546 let children = <Index<S>>::get_children_of(id)?;
547 Ok((name, children))
548 })
549 .collect::<Result<BTreeMap<_, _>, StorageError>>()?;
550
551 // Compare children
552 for (local_coll_name, local_children) in &local_collections {
553 if let Some(foreign_children) = foreign_index_data.children.get(local_coll_name) {
554 let local_child_map: IndexMap<_, _> = local_children
555 .iter()
556 .map(|child| (child.id(), child.merkle_hash()))
557 .collect();
558 let foreign_child_map: IndexMap<_, _> = foreign_children
559 .iter()
560 .map(|child| (child.id(), child.merkle_hash()))
561 .collect();
562
563 for (child_id, local_hash) in &local_child_map {
564 match foreign_child_map.get(child_id) {
565 Some(foreign_hash) if local_hash != foreign_hash => {
566 actions.0.push(Action::Compare { id: *child_id });
567 actions.1.push(Action::Compare { id: *child_id });
568 }
569 None => {
570 if let Some(local_child) = Self::find_by_id_raw(*child_id) {
571 let metadata = <Index<S>>::get_metadata(*child_id)?
572 .ok_or(StorageError::IndexNotFound(*child_id))?;
573
574 actions.1.push(Action::Add {
575 id: *child_id,
576 data: local_child,
577 ancestors: <Index<S>>::get_ancestors_of(id)?,
578 metadata,
579 });
580 }
581 }
582 // Hashes match, no action needed
583 _ => {}
584 }
585 }
586
587 for id in foreign_child_map.keys() {
588 if !local_child_map.contains_key(id) {
589 // Child exists in foreign but not locally, compare.
590 // We can't get the full data for the foreign child, so we flag it for
591 // comparison.
592 actions.1.push(Action::Compare { id: *id });
593 }
594 }
595 } else {
596 // The entire collection is missing from the foreign entity
597 for child in local_children {
598 if let Some(local_child) = Self::find_by_id_raw(child.id()) {
599 let metadata = <Index<S>>::get_metadata(child.id())?
600 .ok_or(StorageError::IndexNotFound(child.id()))?;
601
602 actions.1.push(Action::Add {
603 id: child.id(),
604 data: local_child,
605 ancestors: <Index<S>>::get_ancestors_of(child.id())?,
606 metadata,
607 });
608 }
609 }
610 }
611 }
612
613 // Check for collections in the foreign entity that don't exist locally
614 for (foreign_coll_name, foreign_children) in &foreign_index_data.children {
615 if !local_collections.contains_key(foreign_coll_name) {
616 for child in foreign_children {
617 // We can't get the full data for the foreign child, so we flag it for comparison
618 actions.1.push(Action::Compare { id: child.id() });
619 }
620 }
621 }
622
623 Ok(actions)
624 }
625
626 /// Compares entities and automatically applies sync actions locally.
627 ///
628 /// Convenience wrapper around [`compare_trees()`](Self::compare_trees()) that applies
629 /// local actions immediately and pushes remote actions to sync queue.
630 ///
631 /// # Errors
632 /// Returns error if comparison or action application fails.
633 ///
634 pub fn compare_affective(
635 data: Option<Vec<u8>>,
636 comparison_data: ComparisonData,
637 ) -> Result<(), StorageError> {
638 let (local, remote) = <Interface<S>>::compare_trees(data, comparison_data)?;
639
640 for action in local {
641 if let Action::Compare { .. } = &action {
642 continue;
643 }
644
645 <Interface<S>>::apply_action(action)?;
646 }
647
648 for action in remote {
649 crate::delta::push_action(action);
650 }
651
652 Ok(())
653 }
654
655 /// Finds and deserializes an entity by its unique ID.
656 ///
657 /// Filters out tombstoned (deleted) entities automatically.
658 ///
659 /// # Errors
660 /// - `DeserializationError` if stored data is corrupt
661 /// - `IndexNotFound` if entity exists but has no index
662 ///
663 pub fn find_by_id<D: Data>(id: Id) -> Result<Option<D>, StorageError> {
664 // Check if entity is deleted (tombstone)
665 if <Index<S>>::is_deleted(id)? {
666 return Ok(None); // Entity is deleted
667 }
668
669 let value = S::storage_read(Key::Entry(id));
670
671 let Some(slice) = value else {
672 return Ok(None);
673 };
674
675 let mut item = from_slice::<D>(&slice).map_err(StorageError::DeserializationError)?;
676
677 let (full_hash, _) =
678 <Index<S>>::get_hashes_for(id)?.ok_or(StorageError::IndexNotFound(id))?;
679
680 item.element_mut().merkle_hash = full_hash;
681
682 item.element_mut().metadata =
683 <Index<S>>::get_metadata(id)?.ok_or(StorageError::IndexNotFound(id))?;
684
685 Ok(Some(item))
686 }
687
688 /// Finds an entity by ID, returning raw bytes without deserialization.
689 ///
690 /// Note: This does NOT filter deleted entities. Use `find_by_id` for automatic
691 /// tombstone filtering.
692 ///
693 pub fn find_by_id_raw(id: Id) -> Option<Vec<u8>> {
694 S::storage_read(Key::Entry(id))
695 }
696
697 /// Gets raw entity data by ID.
698 ///
699 /// This is a simple alias for `find_by_id_raw` for convenience in tests.
700 ///
701 /// # Errors
702 /// Returns `IndexNotFound` if entity doesn't exist.
703 ///
704 pub fn get(id: Id) -> Result<Vec<u8>, StorageError> {
705 Self::find_by_id_raw(id).ok_or(StorageError::IndexNotFound(id))
706 }
707
708 /// Generates comparison metadata for tree synchronization.
709 ///
710 /// Includes hashes, ancestors, children info. Used by [`compare_trees()`](Self::compare_trees()).
711 ///
712 /// # Errors
713 /// Returns error if index lookup fails.
714 ///
715 pub fn generate_comparison_data(id: Option<Id>) -> Result<ComparisonData, StorageError> {
716 let id = id.unwrap_or_else(Id::root);
717
718 let (full_hash, own_hash) = <Index<S>>::get_hashes_for(id)?.unwrap_or_default();
719
720 let metadata = <Index<S>>::get_metadata(id)?.unwrap_or_default();
721
722 let ancestors = <Index<S>>::get_ancestors_of(id)?;
723
724 let collection_names = <Index<S>>::get_collection_names_for(id)?;
725
726 let children = collection_names
727 .into_iter()
728 .map(|collection_name| {
729 <Index<S>>::get_children_of(id).map(|children| (collection_name.clone(), children))
730 })
731 .collect::<Result<BTreeMap<_, _>, _>>()?;
732
733 Ok(ComparisonData {
734 id,
735 own_hash,
736 full_hash,
737 ancestors,
738 children,
739 metadata,
740 })
741 }
742
743 /// Checks if a collection has any children.
744 ///
745 /// # Errors
746 /// Returns error if index lookup fails.
747 ///
748 pub fn has_children(parent_id: Id) -> Result<bool, StorageError> {
749 <Index<S>>::has_children(parent_id)
750 }
751
752 /// Retrieves the parent entity of a child.
753 ///
754 /// # Errors
755 /// Returns error if index lookup or deserialization fails.
756 ///
757 pub fn parent_of<D: Data>(child_id: Id) -> Result<Option<D>, StorageError> {
758 <Index<S>>::get_parent_id(child_id)?
759 .map_or_else(|| Ok(None), |parent_id| Self::find_by_id(parent_id))
760 }
761
762 /// Removes a child from a collection.
763 ///
764 /// Deletes the child entity and generates sync actions automatically.
765 ///
766 /// # Errors
767 /// Returns error if parent or child doesn't exist.
768 ///
769 pub fn remove_child_from(parent_id: Id, child_id: Id) -> Result<bool, StorageError> {
770 let child_exists = <Index<S>>::get_children_of(parent_id)?
771 .iter()
772 .any(|child| child.id() == child_id);
773 if !child_exists {
774 return Ok(false);
775 }
776
777 // This will act as our nonce
778 let deleted_at = time_now();
779
780 // Get metadata before removing index
781 let mut metadata =
782 <Index<S>>::get_metadata(child_id)?.ok_or(StorageError::IndexNotFound(child_id))?;
783
784 // If this is a local user action, set the nonce
785 if let StorageType::User { owner, .. } = metadata.storage_type {
786 if *owner == crate::env::executor_id() {
787 // Use the deletion timestamp as the nonce
788 metadata.storage_type = StorageType::User {
789 owner,
790 signature_data: Some(SignatureData {
791 signature: [0; 64], // Placeholder, added by signer
792 nonce: deleted_at,
793 }),
794 };
795 }
796 }
797
798 <Index<S>>::remove_child_from(parent_id, child_id)?;
799
800 // Use DeleteRef for efficient tombstone-based deletion.
801 // More efficient than Delete: only sends ID + timestamp + metadata vs full ancestor tree.
802 // The tombstone is created by remove_child_from, we just broadcast the deletion.
803 crate::delta::push_action(Action::DeleteRef {
804 id: child_id,
805 deleted_at,
806 // Pass the full metadata
807 metadata,
808 });
809
810 Ok(true)
811 }
812
813 /// Retrieves the root entity.
814 ///
815 /// # Errors
816 /// Returns error if deserialization fails.
817 ///
818 pub fn root<D: Data>() -> Result<Option<D>, StorageError> {
819 Self::find_by_id(Id::root())
820 }
821
822 /// Saves the root entity and commits sync actions.
823 ///
824 /// Should be called at the end of each transaction. Call once per execution.
825 ///
826 /// # Errors
827 /// - `UnexpectedId` if root ID doesn't match
828 /// - `SerializationError` if encoding fails
829 ///
830 pub fn commit_root<D: Data>(root: Option<D>) -> Result<(), StorageError> {
831 let id: Id = Id::root();
832
833 debug!(%id, has_root = root.is_some(), "commit_root invoked");
834 let hash = if let Some(root) = root {
835 if root.id() != id {
836 return Err(StorageError::UnexpectedId(root.id()));
837 }
838
839 if !root.element().is_dirty() {
840 return Ok(());
841 }
842
843 let data = to_vec(&root).map_err(|e| StorageError::SerializationError(e.into()))?;
844
845 Self::save_raw(id, data, root.element().metadata.clone())?
846 } else {
847 <Index<S>>::get_hashes_for(id)?.map(|(full_hash, _)| full_hash)
848 };
849
850 if let Some(hash) = hash {
851 crate::delta::commit_root(&hash)?;
852 }
853
854 debug!(%id, ?hash, "commit_root completed");
855 Ok(())
856 }
857
858 /// Saves an entity to storage, updating if it exists.
859 ///
860 /// Only saves if entity is dirty. Returns `false` if not saved due to:
861 /// - Entity not dirty
862 /// - Existing record is newer (last-write-wins guard)
863 ///
864 /// Automatically:
865 /// - Calculates Merkle hashes
866 /// - Updates timestamps
867 /// - Generates sync actions
868 /// - Propagates hash changes up ancestor chain
869 ///
870 /// **Note**: Use [`add_child_to()`](Self::add_child_to()) for new children,
871 /// then `save()` for subsequent updates.
872 ///
873 /// # Errors
874 /// - `SerializationError` if encoding fails
875 /// - `CannotCreateOrphan` if entity has no parent and isn't root
876 ///
877 pub fn save<D: Data>(entity: &mut D) -> Result<bool, StorageError> {
878 if !entity.element().is_dirty() {
879 return Ok(false);
880 }
881
882 let data = to_vec(entity).map_err(|e| StorageError::SerializationError(e.into()))?;
883
884 let Some(hash) = Self::save_raw(entity.id(), data, entity.element().metadata.clone())?
885 else {
886 return Ok(false);
887 };
888
889 entity.element_mut().is_dirty = false;
890 entity.element_mut().merkle_hash = hash;
891
892 Ok(true)
893 }
894
895 /// Saves raw data to the storage system.
896 ///
897 /// # Errors
898 ///
899 /// If an error occurs when serialising data or interacting with the storage
900 /// system, an error will be returned.
901 ///
902 fn save_internal(
903 id: Id,
904 data: &[u8],
905 metadata: Metadata,
906 ) -> Result<Option<(bool, [u8; 32])>, StorageError> {
907 let incoming_created_at = metadata.created_at;
908 let incoming_updated_at = metadata.updated_at();
909
910 // Compute incoming data hash for tracing
911 let incoming_hash: [u8; 32] = Sha256::digest(data).into();
912
913 let last_metadata = <Index<S>>::get_metadata(id)?;
914 let final_data = if let Some(last_metadata) = &last_metadata {
915 if last_metadata.updated_at > metadata.updated_at {
916 return Ok(None);
917 } else if id.is_root() {
918 // Root entity (app state) - ALWAYS merge using CRDT semantics.
919 // The Mergeable impl (auto-generated by #[app::state]) handles:
920 // - Counter: G-Counter merge (union of contributions from all nodes)
921 // - UnorderedMap: Per-key LWW with proper timestamp handling
922 // - Other CRDTs: Their respective merge logic
923 //
924 // This enables handlers to increment counters independently on each node,
925 // with all contributions properly merged during sync.
926 if let Some(existing_data) = S::storage_read(Key::Entry(id)) {
927 let existing_hash: [u8; 32] = Sha256::digest(&existing_data).into();
928 info!(
929 target: "storage::root_merge",
930 %id,
931 existing_len = existing_data.len(),
932 existing_hash = %hex::encode(&existing_hash),
933 incoming_len = data.len(),
934 incoming_hash = %hex::encode(&incoming_hash),
935 existing_updated_at = *last_metadata.updated_at,
936 incoming_updated_at,
937 "ROOT MERGE: Starting CRDT merge for root entity"
938 );
939 let merged = Self::try_merge_data(
940 id,
941 &existing_data,
942 data,
943 *last_metadata.updated_at,
944 *metadata.updated_at,
945 )?;
946 let merged_hash: [u8; 32] = Sha256::digest(&merged).into();
947 info!(
948 target: "storage::root_merge",
949 %id,
950 merged_len = merged.len(),
951 merged_hash = %hex::encode(&merged_hash),
952 same_as_existing = (merged_hash == existing_hash),
953 same_as_incoming = (merged_hash == incoming_hash),
954 "ROOT MERGE: Completed CRDT merge"
955 );
956 merged
957 } else {
958 info!(
959 target: "storage::root_merge",
960 %id,
961 incoming_len = data.len(),
962 incoming_hash = %hex::encode(&incoming_hash),
963 "ROOT MERGE: No existing data, using incoming directly"
964 );
965 data.to_vec()
966 }
967 } else if last_metadata.updated_at == metadata.updated_at {
968 // Concurrent update (same timestamp) - try to merge
969 if let Some(existing_data) = S::storage_read(Key::Entry(id)) {
970 Self::try_merge_non_root(
971 id,
972 &existing_data,
973 data,
974 &metadata,
975 *last_metadata.updated_at,
976 *metadata.updated_at,
977 )?
978 } else {
979 data.to_vec()
980 }
981 } else {
982 // Incoming is newer - try CRDT merge for non-root entities if possible
983 // (Invariant I5: no silent data loss)
984 if let Some(existing_data) = S::storage_read(Key::Entry(id)) {
985 Self::try_merge_non_root(
986 id,
987 &existing_data,
988 data,
989 &metadata,
990 *last_metadata.updated_at,
991 *metadata.updated_at,
992 )?
993 } else {
994 data.to_vec()
995 }
996 }
997 } else {
998 if id.is_root() {
999 info!(
1000 target: "storage::root_merge",
1001 %id,
1002 incoming_len = data.len(),
1003 incoming_hash = %hex::encode(&incoming_hash),
1004 "ROOT MERGE: First time creating root entity"
1005 );
1006 <Index<S>>::add_root(ChildInfo::new(id, [0_u8; 32], metadata.clone()))?;
1007 }
1008 data.to_vec()
1009 };
1010
1011 let own_hash: [u8; 32] = Sha256::digest(&final_data).into();
1012
1013 let full_hash = <Index<S>>::update_hash_for(id, own_hash, Some(metadata.updated_at))?;
1014
1015 if id.is_root() {
1016 info!(
1017 target: "storage::root_merge",
1018 %id,
1019 own_hash = %hex::encode(&own_hash),
1020 full_hash = %hex::encode(&full_hash),
1021 "ROOT MERGE: Final hashes after Merkle tree update"
1022 );
1023 }
1024
1025 _ = S::storage_write(Key::Entry(id), &final_data);
1026
1027 let is_new = metadata.created_at == *metadata.updated_at;
1028
1029 Ok(Some((is_new, full_hash)))
1030 }
1031
1032 /// Attempt to merge two versions of data using CRDT semantics.
1033 ///
1034 /// Returns the merged data, or an error if merge fails.
1035 /// Merge mode is enabled to prevent timestamp generation during merge operations.
1036 ///
1037 /// # Errors
1038 ///
1039 /// Returns `StorageError::MergeFailure` if no merge function is registered
1040 /// for the root entity type. This enforces I5 (No Silent Data Loss) by failing
1041 /// loudly rather than silently falling back to LWW.
1042 fn try_merge_data(
1043 _id: Id,
1044 existing: &[u8],
1045 incoming: &[u8],
1046 existing_timestamp: u64,
1047 incoming_timestamp: u64,
1048 ) -> Result<Vec<u8>, StorageError> {
1049 use crate::merge::merge_root_state;
1050
1051 // Attempt CRDT merge with merge mode enabled
1052 // This prevents timestamp generation during merge to ensure deterministic hashes
1053 let result = crate::env::with_merge_mode(|| {
1054 merge_root_state(existing, incoming, existing_timestamp, incoming_timestamp)
1055 });
1056
1057 // I5 Enforcement: Propagate merge errors instead of falling back to LWW.
1058 // If no merge function is registered, this prevents silent data loss.
1059 // The MergeError is preserved for programmatic error handling.
1060 result.map_err(StorageError::from)
1061 }
1062
1063 /// Attempt to merge two versions of non-root entity data using CRDT semantics.
1064 ///
1065 /// # Merge Dispatch by CrdtType
1066 ///
1067 /// For non-root entities, we dispatch based on `CrdtType` in metadata:
1068 ///
1069 /// **Built-in types** (all except `Custom`) - merged via [`merge_by_crdt_type`]:
1070 /// - `GCounter`, `PnCounter`: Semantic merge (max per executor)
1071 /// - `Rga`: Semantic merge (union of characters)
1072 /// - `LwwRegister`: Returns incoming (timestamp comparison done by caller)
1073 /// - `UnorderedMap`, `UnorderedSet`, `Vector`: Returns incoming (entries are
1074 /// separate entities with their own `CrdtType`, merged individually)
1075 /// - `UserStorage`: Returns incoming (LWW per user)
1076 /// - `FrozenStorage`: Returns existing (first-write-wins, immutable)
1077 ///
1078 /// **Custom types** - require WASM callback (PR #1940), currently fall back to LWW
1079 ///
1080 /// **Legacy data** (no CrdtType metadata) - fall back to LWW
1081 ///
1082 /// # Invariants
1083 ///
1084 /// - **I5 (No Silent Data Loss)**: Built-in CRDT types MUST use their semantic
1085 /// merge rules, not be overwritten by LWW.
1086 /// - **I10 (Metadata Persistence)**: Relies on `crdt_type` being persisted in
1087 /// entity metadata for correct dispatch.
1088 ///
1089 /// [`merge_by_crdt_type`]: crate::merge::merge_by_crdt_type
1090 fn try_merge_non_root(
1091 id: Id,
1092 existing: &[u8],
1093 incoming: &[u8],
1094 metadata: &Metadata,
1095 existing_timestamp: u64,
1096 incoming_timestamp: u64,
1097 ) -> Result<Vec<u8>, StorageError> {
1098 use crate::collections::crdt_meta::MergeError;
1099 use crate::merge::{is_builtin_crdt, merge_by_crdt_type};
1100
1101 // Check if we have CRDT type metadata
1102 let Some(crdt_type) = &metadata.crdt_type else {
1103 // Legacy data - no CRDT type, use LWW
1104 debug!(
1105 target: "storage::merge",
1106 %id,
1107 "No CRDT type metadata, falling back to LWW"
1108 );
1109 return Ok(if incoming_timestamp >= existing_timestamp {
1110 incoming.to_vec()
1111 } else {
1112 existing.to_vec()
1113 });
1114 };
1115
1116 // For built-in types, merge in storage layer
1117 if is_builtin_crdt(crdt_type) {
1118 let result =
1119 crate::env::with_merge_mode(|| merge_by_crdt_type(crdt_type, existing, incoming));
1120
1121 match result {
1122 Ok(merged) => {
1123 debug!(
1124 target: "storage::merge",
1125 %id,
1126 crdt_type = ?crdt_type,
1127 "Successfully merged non-root entity using CRDT semantics"
1128 );
1129 return Ok(merged);
1130 }
1131 Err(MergeError::SerializationError(msg)) => {
1132 warn!(
1133 target: "storage::merge",
1134 %id,
1135 crdt_type = ?crdt_type,
1136 error = %msg,
1137 "CRDT merge failed due to serialization error, falling back to LWW"
1138 );
1139 }
1140 Err(e) => {
1141 warn!(
1142 target: "storage::merge",
1143 %id,
1144 crdt_type = ?crdt_type,
1145 error = %e,
1146 "CRDT merge failed, falling back to LWW"
1147 );
1148 }
1149 }
1150 } else {
1151 // Types that need WASM callback (LwwRegister, collections, Custom)
1152 // For now, fall back to LWW. PR #1940 will add WASM callback support.
1153 debug!(
1154 target: "storage::merge",
1155 %id,
1156 crdt_type = ?crdt_type,
1157 "CRDT type requires WASM callback, falling back to LWW"
1158 );
1159 }
1160
1161 // Fall back to LWW
1162 Ok(if incoming_timestamp >= existing_timestamp {
1163 incoming.to_vec()
1164 } else {
1165 existing.to_vec()
1166 })
1167 }
1168
1169 /// Saves raw serialized data with orphan checking.
1170 ///
1171 /// # Errors
1172 /// - `CannotCreateOrphan` if entity has no parent and isn't root
1173 ///
1174 pub fn save_raw(
1175 id: Id,
1176 data: Vec<u8>,
1177 metadata: Metadata,
1178 ) -> Result<Option<[u8; 32]>, StorageError> {
1179 debug!(
1180 %id,
1181 data_len = data.len(),
1182 created_at = metadata.created_at,
1183 updated_at = metadata.updated_at(),
1184 "save_raw called"
1185 );
1186 if !id.is_root() && <Index<S>>::get_parent_id(id)?.is_none() {
1187 return Err(StorageError::CannotCreateOrphan(id));
1188 }
1189
1190 let mut metadata = metadata.clone();
1191 // If this is a local user action, set the nonce
1192 if let StorageType::User {
1193 owner,
1194 signature_data,
1195 } = metadata.storage_type
1196 {
1197 if *owner == crate::env::executor_id() && signature_data.is_none() {
1198 // This is a new local action. Set the nonce.
1199 // Use the `updated_at` timestamp as the nonce.
1200 let nonce = *metadata.updated_at;
1201 metadata.storage_type = StorageType::User {
1202 owner,
1203 signature_data: Some(SignatureData {
1204 signature: [0; 64], // Placeholder, added by signer
1205 nonce,
1206 }),
1207 };
1208 }
1209 }
1210
1211 let Some((is_new, full_hash)) = Self::save_internal(id, &data, metadata.clone())? else {
1212 return Ok(None);
1213 };
1214
1215 let ancestors = <Index<S>>::get_ancestors_of(id)?;
1216
1217 let action = if is_new {
1218 debug!(%id, "save_raw emitting Add action for entity");
1219 Action::Add {
1220 id,
1221 data,
1222 ancestors,
1223 metadata,
1224 }
1225 } else {
1226 debug!(%id, "save_raw emitting Update action for entity");
1227 Action::Update {
1228 id,
1229 data,
1230 ancestors,
1231 metadata,
1232 }
1233 };
1234
1235 crate::delta::push_action(action);
1236
1237 debug!(%id, ?full_hash, is_new, "save_raw completed");
1238
1239 Ok(Some(full_hash))
1240 }
1241
1242 /// Validates Merkle tree integrity.
1243 ///
1244 /// **Note**: Not yet implemented.
1245 ///
1246 /// # Errors
1247 /// Currently panics (unimplemented).
1248 ///
1249 pub fn validate() -> Result<(), StorageError> {
1250 unimplemented!()
1251 }
1252
1253 /// Helper to verify a new `Update` action.
1254 fn verify_action_update(action: &Action) -> Result<(), StorageError> {
1255 let (metadata, _data, id) = match action {
1256 Action::Update {
1257 metadata, data, id, ..
1258 } => (metadata, data, *id),
1259 // Should not happen
1260 _ => return Ok(()),
1261 };
1262
1263 // Get existing metadata
1264 let existing_metadata = <Index<S>>::get_metadata(id)?;
1265
1266 // Try to get existing metadata to determine if this is an Update or an Add (upsert)
1267 match existing_metadata {
1268 // This is indeed an update operation
1269 Some(existing_metadata) => {
1270 // Compare storage types and owners
1271 match (&existing_metadata.storage_type, &metadata.storage_type) {
1272 (StorageType::Public, StorageType::Public) => {
1273 // no checks needed for Public storage
1274 Ok(())
1275 }
1276 (StorageType::Frozen, StorageType::Frozen) => {
1277 // Mutability is verified in the main `apply_action()` function later
1278 Ok(())
1279 }
1280 (
1281 StorageType::User {
1282 owner: existing_owner,
1283 ..
1284 },
1285 StorageType::User { owner, .. },
1286 ) => {
1287 // Check owner hasn't changed
1288 if *owner != *existing_owner {
1289 return Err(StorageError::ActionNotAllowed(
1290 "Cannot change owner of User storage".to_owned(),
1291 ));
1292 }
1293
1294 Ok(())
1295 }
1296 (existing, new) => {
1297 // All other combinations are invalid
1298 debug!(?existing, ?new, "Invalid storage type change attempted");
1299 Err(StorageError::ActionNotAllowed(
1300 "Cannot change StorageType (e.g., User->Public/User->Frozen/etc)"
1301 .to_owned(),
1302 ))
1303 }
1304 }
1305 }
1306 None => {
1307 // This is an "add" (upsert).
1308 // TODO: refactor
1309 // The item doesn't exist. Run the "Add" verification logic (that is currently
1310 // located in the main `apply_function()`.
1311 Ok(())
1312 }
1313 }
1314 }
1315}
1316
1317/// Verifies an incoming `Frozen` action.
1318fn verify_frozen_action_upsert(action: &Action, data: &[u8]) -> Result<(), StorageError> {
1319 // Block all Updates.
1320 if let Action::Update { .. } = action {
1321 return Err(StorageError::ActionNotAllowed(
1322 "Frozen data cannot be updated".to_owned(),
1323 ));
1324 }
1325
1326 // Verify the content-addressing via byte-slicing.
1327 // The data blob is: [key_hash (32 bytes)] + [value_bytes (N bytes)] + [element_id (32 bytes)]
1328 const KEY_HASH_SIZE: usize = 32;
1329 const ELEMENT_ID_SIZE: usize = 32;
1330 const MIN_LEN: usize = KEY_HASH_SIZE + ELEMENT_ID_SIZE;
1331
1332 if data.len() < MIN_LEN {
1333 return Err(StorageError::InvalidData(
1334 "Frozen data blob is too small.".to_owned(),
1335 ));
1336 }
1337
1338 // Extract the three components
1339 let key_from_entry = &data[..KEY_HASH_SIZE];
1340 // We don't need the `Element::Id` from the end, but we know it's there and
1341 // we need to remove it from the value_bytes.
1342 let value_bytes = &data[KEY_HASH_SIZE..data.len() - ELEMENT_ID_SIZE];
1343
1344 // Re-calculate the hash of the `value bytes`
1345 let calculated_hash: [u8; 32] = Sha256::digest(value_bytes).into();
1346
1347 // Check: The key inside the `Entry` must match the hash
1348 // of the value inside the `Entry`.
1349 if key_from_entry != calculated_hash {
1350 return Err(StorageError::InvalidData(
1351 "Frozen data corruption: Entry key does not match hash of Entry value.".to_owned(),
1352 ));
1353 }
1354
1355 // If this check passes, the data is verified.
1356 Ok(())
1357}
1358
1359/// Verifies that the action timestamp is within acceptable bounds of the local clock.
1360fn verify_action_timestamp(action: &Action) -> Result<(), StorageError> {
1361 let timestamp = match action {
1362 Action::Add { metadata, .. } | Action::Update { metadata, .. } => metadata.updated_at(),
1363 Action::DeleteRef { deleted_at, .. } => *deleted_at,
1364 Action::Compare { .. } => return Ok(()),
1365 };
1366
1367 let now = time_now();
1368
1369 // Allow for network latency and small clock skew
1370 let max_allowed = now.saturating_add(constants::DRIFT_TOLERANCE_NANOS);
1371
1372 if timestamp > max_allowed {
1373 debug!(
1374 %timestamp,
1375 %now,
1376 %max_allowed,
1377 "Interface::verify_action_timestamp action with an invalid timestamp."
1378 );
1379
1380 return Err(StorageError::InvalidTimestamp(timestamp, now));
1381 }
1382
1383 Ok(())
1384}