use alloc::string::{String, ToString};
use alloc::vec;
use crate::event::Error as EventError;
use crate::json::JsonError;
use crate::signer::NostrSigner;
use crate::{Event, EventId, Keys, Kind, PublicKey, RelayUrl, Tag, Tags, Timestamp, UnsignedEvent};
use crate::nips::nip44;
pub const TWO_DAYS_SECS: u64 = 172_800;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("rng failed")]
Rng,
#[error("failed to encrypt")]
Encrypt(#[source] nip44::Error),
#[error("failed to decrypt")]
Decrypt(#[source] nip44::Error),
#[error("ephemeral key generation failed")]
EphemeralKey(#[source] crate::key::Error),
#[error("could not sign the unsigned event")]
Sign(#[source] crate::key::Error),
#[error("invalid JSON")]
Json(#[source] JsonError),
#[error("{0}")]
Shape(&'static str, #[source] JsonError),
#[error("rumor must be unsigned")]
RumorSigned,
#[error("invalid rumor")]
InvalidRumor,
#[error("not a gift wrap event")]
NotGiftWrap,
#[error("invalid gift wrap signature")]
GiftWrapSignature(#[source] EventError),
#[error("not a seal event")]
NotSeal,
#[error("seal carries a non-expiration tag")]
SealTags,
#[error("invalid seal signature")]
SealSignature(#[source] EventError),
#[error("seal pubkey does not match rumor pubkey")]
PubkeyMismatch,
#[error("cannot sign invalid unsigned event")]
InvalidUnsignedEvent,
#[error("signer failed")]
Signer(#[source] crate::SignerError),
}
pub type Result<T, E = Error> = core::result::Result<T, E>;
impl Kind {
#[must_use]
pub const fn is_gift_wrap(self) -> bool {
self.as_u16() == 1059 || self.as_u16() == 21059
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Rumor {
unsigned: UnsignedEvent,
id: EventId,
}
impl Rumor {
#[must_use]
pub fn new(unsigned: UnsignedEvent) -> Self {
let id = unsigned.id();
Self { unsigned, id }
}
#[must_use]
pub const fn id(&self) -> EventId {
self.id
}
#[must_use]
pub const fn unsigned(&self) -> &UnsignedEvent {
&self.unsigned
}
#[must_use]
pub fn into_unsigned(self) -> UnsignedEvent {
self.unsigned
}
#[must_use]
pub fn to_json(&self) -> String {
let unsigned = self.unsigned();
let mut json = alloc::format!(
"{{\"id\":\"{}\",\"pubkey\":\"{}\",\"created_at\":{},\"kind\":{},\"tags\":",
self.id().to_hex(),
unsigned.pubkey().to_hex(),
unsigned.created_at().as_secs(),
unsigned.kind().as_u16(),
);
json.push_str(&serde_json::to_string(unsigned.tags()).unwrap_or_default());
json.push_str(",\"content\":");
json.push_str(&serde_json::to_string(unsigned.content()).unwrap_or_default());
json.push('}');
json
}
pub fn from_json(json: &str) -> Result<Self> {
let value =
serde_json::from_str::<serde_json::Value>(json).map_err(|e| Error::Json(e.into()))?;
let object = value.as_object().ok_or(Error::InvalidRumor)?;
if object.contains_key("sig") {
return Err(Error::RumorSigned);
}
let given_id = object.get("id").and_then(serde_json::Value::as_str);
let unsigned = serde_json::from_value::<UnsignedEvent>(value.clone())
.map_err(|_| Error::InvalidRumor)?;
let rumor = Self::new(unsigned);
if given_id.is_some_and(|id| *id != rumor.id().to_hex()) {
return Err(Error::InvalidRumor);
}
Ok(rumor)
}
pub fn wrap<R>(
&self,
sender: &Keys,
recipient: &PublicKey,
options: &WrapOptions,
rng: &mut R,
) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let seal = seal(self, sender, recipient, options, rng)?;
gift_wrap(&seal, recipient, options, rng)
}
pub fn from_gift_wrap(gift_wrap: &Event, recipient: &Keys) -> Result<Self> {
check_gift_wrap(gift_wrap)?;
let seal_json = decrypt_layer(gift_wrap.content(), recipient, &gift_wrap.pubkey())?;
let seal = parse_seal(&seal_json)?;
let rumor_json = decrypt_layer(seal.content(), recipient, &seal.pubkey())?;
open_rumor(&seal, &rumor_json)
}
pub async fn wrap_with_signer<R>(
&self,
signer: &dyn NostrSigner,
recipient: &PublicKey,
options: &WrapOptions,
rng: &mut R,
) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let seal = seal_with_signer(self, signer, recipient, options, rng).await?;
gift_wrap(&seal, recipient, options, rng)
}
pub async fn from_gift_wrap_with_signer(
gift_wrap: &Event,
signer: &dyn NostrSigner,
) -> Result<Self> {
check_gift_wrap(gift_wrap)?;
let seal_json = signer
.nip44_decrypt(&gift_wrap.pubkey(), gift_wrap.content())
.await
.map_err(Error::Signer)?;
let seal = parse_seal(&seal_json)?;
let rumor_json = signer
.nip44_decrypt(&seal.pubkey(), seal.content())
.await
.map_err(Error::Signer)?;
open_rumor(&seal, &rumor_json)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Timestamps {
Random {
now: Timestamp,
scope: RandomScope,
},
Fixed {
seal: Timestamp,
wrap: Timestamp,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RandomScope {
SealAndWrap,
WrapOnly,
}
#[derive(Clone, Debug)]
pub struct WrapOptions {
timestamps: Timestamps,
relay_hint: Option<RelayUrl>,
extra_tags: Tags,
expiration: Option<Timestamp>,
ephemeral: bool,
}
impl WrapOptions {
#[must_use]
pub const fn new(timestamps: Timestamps) -> Self {
Self {
timestamps,
relay_hint: None,
extra_tags: Tags::new(),
expiration: None,
ephemeral: false,
}
}
#[must_use]
pub fn relay_hint(mut self, relay: RelayUrl) -> Self {
self.relay_hint = Some(relay);
self
}
#[must_use]
pub fn extra_tags<I: IntoIterator<Item = Tag>>(mut self, tags: I) -> Self {
self.extra_tags.extend(tags);
self
}
#[must_use]
pub const fn expiration(mut self, at: Timestamp) -> Self {
self.expiration = Some(at);
self
}
#[must_use]
pub const fn ephemeral(mut self, ephemeral: bool) -> Self {
self.ephemeral = ephemeral;
self
}
pub(crate) const fn dm_wrap(&self, relay_hint: Option<RelayUrl>) -> Self {
Self {
timestamps: self.timestamps,
relay_hint,
extra_tags: Tags::new(),
expiration: self.expiration,
ephemeral: self.ephemeral,
}
}
fn seal_created_at<R: rand_core::TryCryptoRng + ?Sized>(
&self,
rumor: &Rumor,
rng: &mut R,
) -> Result<Timestamp> {
match self.timestamps {
Timestamps::Fixed { seal, .. } => Ok(seal),
Timestamps::Random {
scope: RandomScope::WrapOnly,
..
} => Ok(rumor.unsigned.created_at()),
Timestamps::Random { now, .. } => random_past(now, rng),
}
}
fn wrap_created_at<R: rand_core::TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
) -> Result<Timestamp> {
match self.timestamps {
Timestamps::Fixed { wrap, .. } => Ok(wrap),
Timestamps::Random { now, .. } => random_past(now, rng),
}
}
}
fn expiration_tag(at: Timestamp) -> Tag {
Tag::custom("expiration", [at.as_secs().to_string()])
}
pub(crate) fn seal<R>(
rumor: &Rumor,
author: &Keys,
recipient: &PublicKey,
options: &WrapOptions,
rng: &mut R,
) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let created_at = options.seal_created_at(rumor, rng)?;
let content = encrypt_layer(&rumor.to_json(), author, recipient, rng)?;
let unsigned = seal_template(author.public_key(), content, created_at, options.expiration);
sign(unsigned, author, rng)
}
async fn seal_with_signer<R>(
rumor: &Rumor,
signer: &dyn NostrSigner,
recipient: &PublicKey,
options: &WrapOptions,
rng: &mut R,
) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let pubkey = signer.public_key().await.map_err(Error::Signer)?;
if pubkey != rumor.unsigned().pubkey() {
return Err(Error::PubkeyMismatch);
}
let created_at = options.seal_created_at(rumor, rng)?;
let content = signer
.nip44_encrypt(recipient, &rumor.to_json())
.await
.map_err(Error::Signer)?;
let unsigned = seal_template(pubkey, content, created_at, options.expiration);
signer.sign_event(unsigned).await.map_err(Error::Signer)
}
pub(crate) fn gift_wrap<R>(
seal: &Event,
recipient: &PublicKey,
options: &WrapOptions,
rng: &mut R,
) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let ephemeral = Keys::from_rng(rng).map_err(Error::EphemeralKey)?;
let created_at = options.wrap_created_at(rng)?;
let seal_json = serde_json::to_string(seal).map_err(|e| Error::Json(JsonError::from(e)))?;
let content = encrypt_layer(&seal_json, &ephemeral, recipient, rng)?;
let kind = if options.ephemeral {
Kind::GIFT_WRAP_EPHEMERAL
} else {
Kind::GIFT_WRAP
};
let mut tags = vec![Tag::public_key(
*recipient,
options.relay_hint.as_ref(),
None,
)];
if let Some(at) = options.expiration {
tags.push(expiration_tag(at));
}
tags.extend(options.extra_tags.iter().cloned());
let unsigned = UnsignedEvent::new(
ephemeral.public_key(),
created_at,
kind,
tags.into_iter().collect(),
content,
);
sign(unsigned, &ephemeral, rng)
}
pub(crate) fn seal_template(
author: PublicKey,
encrypted_rumor: String,
created_at: Timestamp,
expiration: Option<Timestamp>,
) -> UnsignedEvent {
let mut tags = Tags::new();
if let Some(at) = expiration {
tags.push(expiration_tag(at));
}
UnsignedEvent::new(author, created_at, Kind::SEAL, tags, encrypted_rumor)
}
pub(crate) fn check_gift_wrap(event: &Event) -> Result<()> {
if !event.kind().is_gift_wrap() {
return Err(Error::NotGiftWrap);
}
event.verify().map_err(Error::GiftWrapSignature)?;
Ok(())
}
pub(crate) fn parse_seal(json: &str) -> Result<Event> {
let seal = parse_event_json(json, "not a seal event")?;
if seal.kind() != Kind::SEAL {
return Err(Error::NotSeal);
}
let illegal = seal.tags().iter().any(|tag| {
tag.name() != "expiration"
|| !tag
.value()
.is_some_and(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
});
if illegal {
return Err(Error::SealTags);
}
seal.verify().map_err(Error::SealSignature)?;
Ok(seal)
}
pub(crate) fn open_rumor(seal: &Event, rumor_json: &str) -> Result<Rumor> {
let rumor = Rumor::from_json(rumor_json)?;
if seal.pubkey() != rumor.unsigned().pubkey() {
return Err(Error::PubkeyMismatch);
}
Ok(rumor)
}
fn random_past<R: rand_core::TryCryptoRng + ?Sized>(
now: Timestamp,
rng: &mut R,
) -> Result<Timestamp> {
const SPAN: u64 = u32::MAX as u64 + 1;
const LIMIT: u64 = SPAN / TWO_DAYS_SECS * TWO_DAYS_SECS;
loop {
let mut bytes = [0u8; 4];
rng.try_fill_bytes(&mut bytes).map_err(|_| Error::Rng)?;
let draw = u64::from(u32::from_be_bytes(bytes));
if draw < LIMIT {
return now
.as_secs()
.checked_sub(draw % TWO_DAYS_SECS)
.map(Timestamp::from_secs)
.ok_or(Error::InvalidUnsignedEvent);
}
}
}
fn encrypt_layer<R>(plaintext: &str, keys: &Keys, peer: &PublicKey, rng: &mut R) -> Result<String>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let conversation =
nip44::ConversationKey::derive(keys.secret_key(), peer).map_err(Error::Encrypt)?;
conversation.encrypt(plaintext, rng).map_err(Error::Encrypt)
}
fn sign<R>(unsigned: UnsignedEvent, keys: &Keys, rng: &mut R) -> Result<Event>
where
R: rand_core::TryCryptoRng + ?Sized,
{
keys.sign_event(unsigned, rng).map_err(|e| match e {
crate::key::Error::Rng => Error::Rng,
e => Error::Sign(e),
})
}
fn decrypt_layer(ciphertext: &str, recipient: &Keys, peer: &PublicKey) -> Result<String> {
let conversation =
nip44::ConversationKey::derive(recipient.secret_key(), peer).map_err(Error::Decrypt)?;
conversation.decrypt(ciphertext).map_err(Error::Decrypt)
}
fn parse_event_json(json: &str, shape_message: &'static str) -> Result<Event> {
serde_json::from_str(json).map_err(|e| {
if matches!(
e.classify(),
serde_json::error::Category::Syntax | serde_json::error::Category::Eof
) {
Error::Json(e.into())
} else {
Error::Shape(shape_message, e.into())
}
})
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::panic,
clippy::indexing_slicing,
clippy::cast_possible_truncation,
reason = "tests exercise fixed vectors by panicking"
)]
mod vectors {
use alloc::string::String;
use alloc::vec::Vec;
use serde_json::Value;
use crate::{Event, Keys, RelayUrl, SecretKey, Tag, Timestamp, UnsignedEvent};
use super::*;
const JSON: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../vectors/nip59/codec.json"
));
struct BytesRng(Vec<u8>);
impl rand_core::TryRng for BytesRng {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
let mut b = [0u8; 4];
self.try_fill_bytes(&mut b)?;
Ok(u32::from_be_bytes(b))
}
fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
let mut b = [0u8; 8];
self.try_fill_bytes(&mut b)?;
Ok(u64::from_be_bytes(b))
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> core::result::Result<(), Self::Error> {
let take: Vec<u8> = self.0.drain(..dest.len().min(self.0.len())).collect();
dest.copy_from_slice(&take);
Ok(())
}
}
impl rand_core::TryCryptoRng for BytesRng {}
fn unhex(s: &str) -> Vec<u8> {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap())
.collect()
}
fn unhex_arr<const N: usize>(s: &str) -> [u8; N] {
unhex(s).try_into().unwrap()
}
fn keys(s: &str) -> Keys {
Keys::new(SecretKey::from_bytes(unhex_arr(s)).unwrap())
}
fn rumor(v: &Value) -> Rumor {
let unsigned: UnsignedEvent = serde_json::from_value(v.clone()).unwrap();
Rumor::new(unsigned)
}
fn options(v: &Value) -> WrapOptions {
let mut o = WrapOptions::new(match &v["timestamps"] {
Value::Null => Timestamps::Random {
now: Timestamp::from_secs(v["now"].as_u64().unwrap_or(1_700_000_000)),
scope: match v["randomize"].as_str().unwrap_or("seal+wrap") {
"wrap" => RandomScope::WrapOnly,
_ => RandomScope::SealAndWrap,
},
},
t => Timestamps::Fixed {
seal: Timestamp::from_secs(t["seal"].as_u64().unwrap()),
wrap: Timestamp::from_secs(t["wrap"].as_u64().unwrap()),
},
});
if let Some(h) = v.get("relay_hint").and_then(Value::as_str) {
o = o.relay_hint(RelayUrl::parse(h).unwrap());
}
if let Some(tags) = v.get("extra_tags").and_then(Value::as_array) {
o = o.extra_tags(tags.iter().filter_map(|t| {
Tag::new(
t.as_array()
.unwrap()
.iter()
.filter_map(|x| x.as_str().map(String::from)),
)
.ok()
}));
}
if let Some(e) = v.get("expiration").and_then(Value::as_u64) {
o = o.expiration(Timestamp::from_secs(e));
}
if let Some(ep) = v.get("ephemeral").and_then(Value::as_bool) {
o = o.ephemeral(ep);
}
o
}
#[test]
fn vector_wrap() {
let doc: Value = serde_json::from_str(JSON).unwrap();
for case in doc["wrap"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let sender = keys(case["secret_key"].as_str().unwrap());
let recipient = keys(case["recipient_secret_key"].as_str().unwrap());
let r = rumor(&case["rumor"]);
let o = options(&case["options"]);
let mut rng = BytesRng(unhex(case["entropy"].as_str().unwrap()));
let wrap = r
.wrap(&sender, &recipient.public_key(), &o, &mut rng)
.unwrap_or_else(|e| panic!("{name}: {e}"));
let want: Event = serde_json::from_value(case["wrap"].clone()).unwrap();
assert_eq!(wrap.to_json(), want.to_json(), "{name}");
}
}
#[test]
fn vector_seal() {
let doc: Value = serde_json::from_str(JSON).unwrap();
for case in doc["seal"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let sender = keys(case["secret_key"].as_str().unwrap());
let recipient = keys(case["recipient_secret_key"].as_str().unwrap());
let r = rumor(&case["rumor"]);
let o = options(&case["options"]);
let mut rng = BytesRng(unhex(case["entropy"].as_str().unwrap()));
let s = seal(&r, &sender, &recipient.public_key(), &o, &mut rng)
.unwrap_or_else(|e| panic!("{name}: {e}"));
let want: Event = serde_json::from_value(case["seal"].clone()).unwrap();
assert_eq!(s.to_json(), want.to_json(), "{name}");
}
}
#[test]
fn vector_gift() {
let doc: Value = serde_json::from_str(JSON).unwrap();
for case in doc["gift"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let recipient = keys(case["recipient_secret_key"].as_str().unwrap());
let s: Event = serde_json::from_value(case["seal"].clone()).unwrap();
let o = options(&case["options"]);
let mut rng = BytesRng(unhex(case["entropy"].as_str().unwrap()));
let w = gift_wrap(&s, &recipient.public_key(), &o, &mut rng)
.unwrap_or_else(|e| panic!("{name}: {e}"));
let want: Event = serde_json::from_value(case["wrap"].clone()).unwrap();
assert_eq!(w.to_json(), want.to_json(), "{name}");
}
}
#[test]
fn vector_unwrap() {
let doc: Value = serde_json::from_str(JSON).unwrap();
for case in doc["unwrap"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let gw: Event = serde_json::from_value(case["gift_wrap"].clone()).unwrap();
let recipient = keys(case["recipient_secret_key"].as_str().unwrap());
match Rumor::from_gift_wrap(&gw, &recipient) {
Ok(r) => {
let want: UnsignedEvent =
serde_json::from_value(case["rumor"].clone()).unwrap();
assert_eq!(r.unsigned().to_json(), want.to_json(), "{name}");
}
Err(_) => {
assert!(case.get("error").is_some(), "{name}");
}
}
}
}
#[test]
fn gift_wrap_kind_predicate() {
assert!(Kind::GIFT_WRAP.is_gift_wrap());
assert!(Kind::GIFT_WRAP_EPHEMERAL.is_gift_wrap());
assert!(!Kind::SEAL.is_gift_wrap());
}
}