use calimero_node_primitives::sync::{
build_handshake_from_raw, estimate_entity_count, estimate_max_depth, SyncHandshake,
};
use calimero_primitives::common::DIGEST_SIZE;
use calimero_primitives::context::ContextId;
use super::SyncManager;
impl SyncManager {
pub(super) fn build_local_handshake(
&self,
context: &calimero_primitives::context::Context,
) -> SyncHandshake {
let root_hash = *context.root_hash;
let dag_heads = context.dag_heads.clone();
let (entity_count, max_depth) = self.query_tree_stats(&context.id).unwrap_or_else(|| {
let count = estimate_entity_count(root_hash, dag_heads.len());
let depth = estimate_max_depth(count);
(count, depth)
});
build_handshake_from_raw(root_hash, entity_count, max_depth, dag_heads)
}
fn query_tree_stats(&self, context_id: &ContextId) -> Option<(u64, u32)> {
use calimero_node_primitives::sync::create_runtime_env;
use calimero_storage::address::Id;
use calimero_storage::env::with_runtime_env;
use calimero_storage::index::Index;
use calimero_storage::store::MainStorage;
let store = self.context_client.datastore_handle().into_inner();
let identity = calimero_primitives::identity::PublicKey::from([0u8; 32]);
let env = create_runtime_env(&store, *context_id, identity);
let root_id = Id::new(*context_id.as_ref());
with_runtime_env(env, || {
let root_index = Index::<MainStorage>::get_index(root_id).ok().flatten()?;
let children = root_index.children().unwrap_or_default();
let entity_count = (children.len() as u64).max(1);
let max_depth = 1;
Some((entity_count, max_depth))
})
}
pub(super) fn build_remote_handshake(
peer_root_hash: calimero_primitives::hash::Hash,
peer_dag_heads: &[[u8; DIGEST_SIZE]],
) -> SyncHandshake {
let root_hash = *peer_root_hash;
let entity_count = estimate_entity_count(root_hash, peer_dag_heads.len());
let max_depth = estimate_max_depth(entity_count);
build_handshake_from_raw(root_hash, entity_count, max_depth, peer_dag_heads.to_vec())
}
}