use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use thiserror::Error;
use crate::event::{Event, EventBuilder, EventId, Kind, Tag};
use crate::types::RelayUrl;
pub const KIND_OTS_ATTESTATION: Kind = Kind::OTS_ATTESTATION;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtsAttestation {
pub event_id: EventId,
pub relay_hint: Option<RelayUrl>,
pub attested_kind: Option<Kind>,
pub proof: Vec<u8>,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OtsError {
#[error("unexpected kind for NIP-03 attestation: {}", .0.as_u16())]
WrongKind(Kind),
#[error("NIP-03 event missing a valid `e` tag")]
MissingEventId,
#[error("NIP-03 content is not valid base64: {0}")]
InvalidBase64(#[from] base64::DecodeError),
#[error("NIP-03 proof is empty")]
EmptyProof,
}
impl OtsAttestation {
pub fn new(event_id: EventId, proof: Vec<u8>) -> Result<Self, OtsError> {
if proof.is_empty() {
return Err(OtsError::EmptyProof);
}
Ok(Self {
event_id,
relay_hint: None,
attested_kind: None,
proof,
})
}
#[must_use]
pub fn with_relay_hint(mut self, relay: RelayUrl) -> Self {
self.relay_hint = Some(relay);
self
}
#[must_use]
pub const fn with_attested_kind(mut self, kind: Kind) -> Self {
self.attested_kind = Some(kind);
self
}
#[must_use]
pub fn proof_base64(&self) -> String {
BASE64.encode(&self.proof)
}
pub fn from_event(event: &Event) -> Result<Self, OtsError> {
if event.kind != KIND_OTS_ATTESTATION {
return Err(OtsError::WrongKind(event.kind));
}
let e_tag = event
.tags
.iter()
.find(|tag| tag.name() == "e")
.ok_or(OtsError::MissingEventId)?;
let event_id = e_tag
.content()
.and_then(|raw| EventId::parse(raw).ok())
.ok_or(OtsError::MissingEventId)?;
let relay_hint = e_tag.get(2).and_then(|raw| RelayUrl::parse(raw).ok());
let attested_kind = event
.tags
.iter()
.find(|tag| tag.name() == "k")
.and_then(Tag::content)
.and_then(|raw| raw.parse::<Kind>().ok());
let proof = BASE64.decode(event.content.trim())?;
if proof.is_empty() {
return Err(OtsError::EmptyProof);
}
Ok(Self {
event_id,
relay_hint,
attested_kind,
proof,
})
}
}
impl EventBuilder {
#[must_use]
pub fn ots_attestation(attestation: &OtsAttestation) -> Self {
let e_tag = attestation.relay_hint.as_ref().map_or_else(
|| Tag::e(attestation.event_id),
|relay| Tag::e_with_relay(attestation.event_id, relay),
);
let mut builder = Self::new(KIND_OTS_ATTESTATION, attestation.proof_base64()).tag(e_tag);
if let Some(kind) = attestation.attested_kind {
builder = builder.tag(Tag::k(kind));
}
builder
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Keys;
fn keys() -> Keys {
Keys::parse("0000000000000000000000000000000000000000000000000000000000000003").unwrap()
}
fn target_id() -> EventId {
EventId::parse("e71c6ea722987debdb60f81f9ea4f604b5ac0664120dd64fb9d23abc4ec7c323").unwrap()
}
#[test]
fn round_trip() {
let att = OtsAttestation::new(target_id(), vec![0x00, 0x4f, 0x54, 0x53])
.unwrap()
.with_relay_hint(RelayUrl::parse("wss://relay.example/").unwrap())
.with_attested_kind(Kind::TEXT_NOTE);
let event = EventBuilder::ots_attestation(&att)
.sign_with_keys(&keys())
.unwrap();
let parsed = OtsAttestation::from_event(&event).unwrap();
assert_eq!(parsed, att);
}
#[test]
fn empty_proof_is_rejected() {
assert!(matches!(
OtsAttestation::new(target_id(), Vec::new()),
Err(OtsError::EmptyProof)
));
}
#[test]
fn wrong_kind_is_rejected() {
let event = EventBuilder::text_note("nope")
.sign_with_keys(&keys())
.unwrap();
assert!(matches!(
OtsAttestation::from_event(&event),
Err(OtsError::WrongKind(_))
));
}
#[test]
fn missing_e_tag_is_rejected() {
let event = EventBuilder::new(KIND_OTS_ATTESTATION, BASE64.encode(b"proof"))
.sign_with_keys(&keys())
.unwrap();
assert!(matches!(
OtsAttestation::from_event(&event),
Err(OtsError::MissingEventId)
));
}
#[test]
fn invalid_base64_is_rejected() {
let event = EventBuilder::new(KIND_OTS_ATTESTATION, "!!! not base64 !!!")
.tag(Tag::e(target_id()))
.sign_with_keys(&keys())
.unwrap();
assert!(matches!(
OtsAttestation::from_event(&event),
Err(OtsError::InvalidBase64(_))
));
}
}