use crate::model::{APP_KIND, Release, tag_value};
use anyhow::{Context, Result, ensure};
use nostr::{Event, EventId, Keys, Kind};
use nostr_identity::{
FACT_SNAPSHOT_KIND, build_fact_snapshot_event_with_created_at_ms, compare_fact_snapshots, fact,
parse_fact_snapshot_event,
};
use nostr_social_graph::{NostrEvent, SocialGraph};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Attestation {
pub schema: String,
pub release: String,
pub approved: bool,
pub note: String,
}
pub fn attest(keys: &Keys, release: EventId, approved: bool, note: String) -> Result<Event> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_millis();
attest_at(keys, release, approved, note, u64::try_from(now)?)
}
pub fn attest_at(
keys: &Keys,
release: EventId,
approved: bool,
note: String,
at_ms: u64,
) -> Result<Event> {
ensure!(note.len() <= 4096, "attestation note is too long");
build_fact_snapshot_event_with_created_at_ms(
keys,
release.to_hex(),
[
fact("type", &["haps_release_attestation"]),
fact("schema", &["1"]),
fact("approved", &[if approved { "true" } else { "false" }]),
fact("note", &[¬e]),
],
[],
at_ms / 1000,
at_ms,
)
}
pub fn parse_attestation(event: &Event) -> Result<Attestation> {
event.verify()?;
let claim = if event.kind == Kind::from(FACT_SNAPSHOT_KIND) {
let snapshot = parse_fact_snapshot_event(event)?;
let scalar = |predicate: &str| -> Result<&str> {
let matches: Vec<_> = snapshot
.facts
.iter()
.filter(|f| f.predicate == predicate)
.collect();
ensure!(
matches.len() == 1 && matches[0].values.len() == 1,
"attestation needs one {predicate}"
);
Ok(matches[0].values[0].as_str())
};
ensure!(
scalar("type")? == "haps_release_attestation" && scalar("schema")? == "1",
"unsupported attestation profile"
);
let approved = match scalar("approved")? {
"true" => true,
"false" => false,
_ => anyhow::bail!("attestation approved must be true or false"),
};
Attestation {
schema: "haps.attestation.v1".into(),
release: snapshot.subject.clone(),
approved,
note: scalar("note")?.into(),
}
} else {
ensure!(
event.kind == APP_KIND,
"expected a Haps release attestation"
);
let claim: Attestation = serde_json::from_str(&event.content)?;
ensure!(
tag_value(event, "d")? == format!("haps/attestation/{}", claim.release),
"attestation target mismatch"
);
claim
};
ensure!(
claim.schema == "haps.attestation.v1" && claim.note.len() <= 4096,
"invalid attestation"
);
ensure!(
EventId::from_hex(&claim.release)?.to_hex() == claim.release,
"attestation release must be a canonical event hash"
);
Ok(claim)
}
pub fn attestation_time_ms(event: &Event) -> Result<u64> {
let seconds_ms = event
.created_at
.as_secs()
.checked_mul(1000)
.context("attestation timestamp overflow")?;
if event.kind == Kind::from(FACT_SNAPSHOT_KIND) {
Ok(parse_fact_snapshot_event(event)?
.created_at_ms
.unwrap_or(seconds_ms))
} else {
Ok(seconds_ms)
}
}
fn newer_attestation(event: &Event, old: &Event) -> Result<bool> {
if event.kind == Kind::from(FACT_SNAPSHOT_KIND) && old.kind == event.kind {
return Ok(compare_fact_snapshots(
&parse_fact_snapshot_event(event)?,
&parse_fact_snapshot_event(old)?,
)
.is_gt());
}
if event.kind == APP_KIND && old.kind == APP_KIND {
return Ok(event.created_at > old.created_at
|| (event.created_at == old.created_at && event.id < old.id));
}
Ok((
attestation_time_ms(event)?,
event.kind == Kind::from(FACT_SNAPSHOT_KIND),
) > (
attestation_time_ms(old)?,
old.kind == Kind::from(FACT_SNAPSHOT_KIND),
))
}
pub struct Trust {
root: String,
graph: SocialGraph,
events: BTreeMap<String, Event>,
reachable: BTreeSet<String>,
starting_point: Option<String>,
}
impl Trust {
pub fn new(root: String) -> Self {
Self {
graph: SocialGraph::new(&root),
reachable: BTreeSet::from([root.clone()]),
root,
events: BTreeMap::new(),
starting_point: None,
}
}
pub fn ingest(&mut self, event: Event) -> Result<()> {
event.verify()?;
ensure!(
event.created_at.as_secs() <= nostr::Timestamp::now().as_secs() + 300,
"social event is too far in the future"
);
let identifier = if event.kind == Kind::ContactList || event.kind == Kind::MuteList {
event.kind.as_u16().to_string()
} else {
let attestation = parse_attestation(&event)?;
format!("haps/attestation/{}", attestation.release)
};
let key = format!("{}/{}", event.pubkey.to_hex(), identifier);
if let Some(old) = self.events.get(&key) {
let newer = if event.kind == Kind::ContactList || event.kind == Kind::MuteList {
event.created_at > old.created_at
|| (event.created_at == old.created_at && event.id < old.id)
} else {
newer_attestation(&event, old)?
};
if !newer {
return Ok(());
}
}
self.events.insert(key, event);
self.rebuild()
}
fn rebuild(&mut self) -> Result<()> {
self.graph = SocialGraph::new(&self.root);
for event in self
.events
.values()
.filter(|e| e.kind == Kind::ContactList || e.kind == Kind::MuteList)
{
self.graph.handle_event(
&NostrEvent {
created_at: event.created_at.as_secs(),
content: event.content.clone(),
tags: event.tags.iter().map(|t| t.as_slice().to_vec()).collect(),
kind: event.kind.as_u16() as u32,
pubkey: event.pubkey.to_hex(),
id: event.id.to_hex(),
sig: event.sig.to_string(),
},
true,
1.0,
);
}
self.apply_starting_point()
}
pub fn set_starting_point(&mut self, key: Option<String>) -> Result<()> {
self.starting_point = key;
self.rebuild()
}
fn apply_starting_point(&mut self) -> Result<()> {
if let Some(key) = &self.starting_point {
self.graph.add_positive_relation(&self.root, key, 0)?;
}
self.graph.recalculate_follow_distances();
self.reachable = self
.graph
.users_in_distance_order(None)
.into_iter()
.collect();
Ok(())
}
pub fn events(&self) -> Vec<Event> {
self.events.values().cloned().collect()
}
pub fn distance(&self, author: &str) -> Option<u32> {
self.reachable
.contains(author)
.then(|| self.graph.get_follow_distance(author))
}
pub fn muted(&self, author: &str) -> bool {
self.graph
.get_muted_by_user(&self.root)
.iter()
.any(|p| p == author)
}
pub fn followed_by_friends(&self, author: &str) -> Vec<String> {
let mut friends: Vec<_> = self
.graph
.get_followed_by_user(&self.root)
.into_iter()
.filter(|key| {
key != &self.root && !self.muted(key) && self.graph.is_following(key, author)
})
.collect();
friends.sort();
friends
}
pub fn attesters(&self, release: &Release) -> Vec<String> {
self.attestations(release)
.iter()
.map(|event| event.pubkey.to_hex())
.collect()
}
pub fn attestations(&self, release: &Release) -> Vec<&Event> {
let mut attestations = Vec::new();
for event in self
.events
.values()
.filter(|e| e.kind == APP_KIND || e.kind == Kind::from(FACT_SNAPSHOT_KIND))
{
let author = event.pubkey.to_hex();
if author == release.author()
|| self.muted(&author)
|| self.distance(&author).is_none_or(|d| d > 1)
{
continue;
}
if let Ok(a) = parse_attestation(event)
&& a.release == release.event.id.to_hex()
&& a.approved
{
attestations.push(event);
}
}
attestations
}
pub fn authorize(
&self,
release: &Release,
allow_untrusted: bool,
minimum_attestations: usize,
) -> Result<()> {
ensure!(!self.muted(&release.author()), "publisher is muted");
let attestations = self.attesters(release).len();
ensure!(
attestations >= minimum_attestations,
"release requires {minimum_attestations} attestations from you or keys you follow; found {attestations}"
);
ensure!(
allow_untrusted
|| self.distance(&release.author()).is_some_and(|d| d <= 1)
|| (minimum_attestations > 0 && attestations >= minimum_attestations),
"publisher is outside your direct follows; inspect the public key, follow them, require trusted attestations, or explicitly use --allow-untrusted"
);
Ok(())
}
}