use dig_chainsource_interface::ChainSource;
use dig_merkle::{Datastore, DigDataStoreMetadata};
use dig_social_profile::{Profile as SchemaProfile, SlotId, Value, VerifiedBody};
use crate::registry::ProfileAnchor;
use super::content::ProfileContentSource;
use super::error::{EditError, EditResult};
use super::fields::ProfileFields;
use super::slot::ProfileSlot;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileSnapshot {
root: [u8; 32],
body: VerifiedBody,
fields: ProfileFields,
}
impl ProfileSnapshot {
pub fn root(&self) -> [u8; 32] {
self.root
}
pub fn fields(&self) -> &ProfileFields {
&self.fields
}
pub fn body_bytes(&self) -> &[u8] {
self.body.as_bytes()
}
pub(crate) fn content(&self) -> &SchemaProfile {
self.body.profile()
}
}
pub fn read_profile<C, S>(
anchor: &ProfileAnchor,
chain: &C,
content: &S,
) -> EditResult<ProfileSnapshot>
where
C: ChainSource + ?Sized,
S: ProfileContentSource + ?Sized,
{
let store = resolve_store_tip(anchor, chain)?;
let root: [u8; 32] = store.info.metadata.root_hash.into();
let slots = content
.fetch_profile_slots(anchor.store_launcher_id(), root)
.map_err(|e| EditError::ContentUnavailable(e.to_string()))?;
let body = assemble_body(&slots)?;
if body.root() != root {
return Err(EditError::StaleOrTamperedContent);
}
Ok(ProfileSnapshot {
root,
fields: project_standard_slots(body.profile()),
body,
})
}
pub(crate) fn resolve_store_tip<C>(
anchor: &ProfileAnchor,
chain: &C,
) -> EditResult<Datastore<DigDataStoreMetadata>>
where
C: ChainSource + ?Sized,
{
let lineage = chain
.resolve_singleton_lineage(anchor.store_launcher_id())
.map_err(|e| EditError::ChainUnreachable(e.to_string()))?
.ok_or(EditError::NoStore)?;
let creating_spend = chain
.parent_spend(lineage.tip())
.map_err(|e| EditError::ChainUnreachable(e.to_string()))?
.ok_or(EditError::NoStore)?;
dig_merkle::hydrate(&creating_spend).map_err(|e| EditError::Format(format!("store tip: {e}")))
}
fn assemble_body(slots: &[(u16, Vec<u8>)]) -> EditResult<VerifiedBody> {
let mut pairs = Vec::with_capacity(slots.len());
for (id, encoded) in slots {
let value = Value::decode(encoded)
.map_err(|e| EditError::Format(format!("slot {id:#06x}: {e}")))?;
pairs.push((SlotId(*id), value));
}
pairs.sort_by_key(|(slot, _)| slot.0);
VerifiedBody::from_pairs(pairs).map_err(|e| EditError::Format(format!("profile body: {e}")))
}
fn project_standard_slots(body: &SchemaProfile) -> ProfileFields {
let mut fields = ProfileFields::new();
for slot in ProfileSlot::ALL {
if let Some(Value::Utf8(text)) = body.get(slot.slot_id()) {
fields.insert(slot, text.clone());
}
}
fields
}