Skip to content

Commit

Permalink
Bump nostr-sdk to v0.36.0 (#383)
Browse files Browse the repository at this point in the history
* Bump `mostro-core` to `v0.6.10`
  • Loading branch information
yukibtc authored Nov 7, 2024
1 parent 8d45dd6 commit 2915f37
Show file tree
Hide file tree
Showing 12 changed files with 636 additions and 818 deletions.
1,332 changes: 580 additions & 752 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ anyhow = "1.0.89"
chrono = "0.4.35"
easy-hasher = "2.2.1"
lightning-invoice = { version = "0.32.0", features = ["std"] }
nostr-sdk = "0.32.0"
nostr-sdk = "0.36.0"
serde = { version = "1.0.210" }
serde_json = "1.0.128"
sqlx = { version = "0.6.2", features = [
Expand All @@ -38,7 +38,7 @@ uuid = { version = "1.8.0", features = [
"serde",
] }
reqwest = { version = "0.12.1", features = ["json"] }
mostro-core = { version = "0.6.9", features = ["sqlx"] }
mostro-core = { version = "0.6.10", features = ["sqlx"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
config = "0.14.0"
Expand Down
11 changes: 6 additions & 5 deletions src/app/admin_cancel.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::str::FromStr;

use crate::db::{find_dispute_by_order_id, is_assigned_solver};
Expand Down Expand Up @@ -100,20 +101,20 @@ pub async fn admin_cancel_action(
d.status = DisputeStatus::SellerRefunded.to_string();
d.update(pool).await?;
// We create a tag to show status of the dispute
let tags: Vec<Tag> = vec![
let tags: Tags = Tags::new(vec![
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("s")),
TagKind::Custom(Cow::Borrowed("s")),
vec![DisputeStatus::SellerRefunded.to_string()],
),
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("y")),
TagKind::Custom(Cow::Borrowed("y")),
vec!["mostrop2p".to_string()],
),
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("z")),
TagKind::Custom(Cow::Borrowed("z")),
vec!["dispute".to_string()],
),
];
]);
// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute_id.to_string(), tags)?;

Expand Down
4 changes: 2 additions & 2 deletions src/app/admin_settle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub async fn admin_settle_action(
d.status = DisputeStatus::Settled.to_string();
d.update(pool).await?;
// We create a tag to show status of the dispute
let tags: Vec<Tag> = vec![
let tags: Tags = Tags::new(vec![
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("s")),
vec![DisputeStatus::Settled.to_string()],
Expand All @@ -120,7 +120,7 @@ pub async fn admin_settle_action(
TagKind::Custom(std::borrow::Cow::Borrowed("z")),
vec!["dispute".to_string()],
),
];
]);

// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute_id.to_string(), tags)?;
Expand Down
4 changes: 2 additions & 2 deletions src/app/admin_take_dispute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ pub async fn admin_take_dispute_action(
send_dm(&buyer_pubkey, sender_keys.clone(), msg_to_buyer.as_json()?).await?;
send_dm(&seller_pubkey, sender_keys, msg_to_seller.as_json()?).await?;
// We create a tag to show status of the dispute
let tags: Vec<Tag> = vec![
let tags: Tags = Tags::new(vec![
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("s")),
vec![Status::InProgress.to_string()],
Expand All @@ -155,7 +155,7 @@ pub async fn admin_take_dispute_action(
TagKind::Custom(std::borrow::Cow::Borrowed("z")),
vec!["dispute".to_string()],
),
];
]);
// nip33 kind with dispute id as identifier
let event = new_event(&crate::util::get_keys()?, "", dispute_id.to_string(), tags)?;
info!("Dispute event to be published: {event:#?}");
Expand Down
11 changes: 6 additions & 5 deletions src/app/dispute.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::str::FromStr;

use crate::db::find_dispute_by_order_id;
Expand Down Expand Up @@ -159,20 +160,20 @@ pub async fn dispute_action(
.await;

// We create a tag to show status of the dispute
let tags: Vec<Tag> = vec![
let tags: Tags = Tags::new(vec![
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("s")),
TagKind::Custom(Cow::Borrowed("s")),
vec![dispute.status.to_string()],
),
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("y")),
TagKind::Custom(Cow::Borrowed("y")),
vec!["mostrop2p".to_string()],
),
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("z")),
TagKind::Custom(Cow::Borrowed("z")),
vec!["dispute".to_string()],
),
];
]);

// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute.id.to_string(), tags)?;
Expand Down
5 changes: 3 additions & 2 deletions src/app/rate_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ pub async fn get_user_reputation(user: &str, my_keys: &Keys) -> Result<Option<Ra
let mut user_reputation_event = NOSTR_CLIENT
.get()
.unwrap()
.get_events_of(vec![filters], Some(Duration::from_secs(10)))
.await?;
.fetch_events(vec![filters], Some(Duration::from_secs(10)))
.await?
.to_vec();

// Check if vector of answers is empty
if user_reputation_event.is_empty() {
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ async fn main() -> Result<()> {
};

// Client subscription
client.subscribe(vec![subscription], None).await;
client.subscribe(vec![subscription], None).await?;

let mut ln_client = LndConnector::new().await?;

Expand Down
17 changes: 9 additions & 8 deletions src/nip33.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ pub fn new_event(
keys: &Keys,
content: &str,
identifier: String,
extra_tags: Vec<Tag>,
extra_tags: Tags,
) -> Result<Event, Error> {
let mut tags: Vec<Tag> = vec![];
let mut tags: Vec<Tag> = Vec::with_capacity(1 + extra_tags.len());
tags.push(Tag::identifier(identifier));
tags.append(&mut extra_tags.clone());
tags.extend(extra_tags);

EventBuilder::new(Kind::Custom(NOSTR_REPLACEABLE_EVENT_KIND), content, tags).to_event(keys)
EventBuilder::new(Kind::Custom(NOSTR_REPLACEABLE_EVENT_KIND), content, tags)
.sign_with_keys(keys)
}

fn create_rating_string(rating: Option<Rating>) -> String {
Expand Down Expand Up @@ -66,7 +67,7 @@ fn create_fiat_amt_array(order: &Order) -> Vec<String> {
///
/// * `order` - The order to transform
///
pub fn order_to_tags(order: &Order, reputation: Option<Rating>) -> Vec<Tag> {
pub fn order_to_tags(order: &Order, reputation: Option<Rating>) -> Tags {
let tags: Vec<Tag> = vec![
Tag::custom(
TagKind::Custom(std::borrow::Cow::Borrowed("k")),
Expand Down Expand Up @@ -122,15 +123,15 @@ pub fn order_to_tags(order: &Order, reputation: Option<Rating>) -> Vec<Tag> {
),
];

tags
Tags::new(tags)
}

/// Transform mostro info fields to tags
///
/// # Arguments
///
///
pub fn info_to_tags(mostro_pubkey: &PublicKey) -> Vec<Tag> {
pub fn info_to_tags(mostro_pubkey: &PublicKey) -> Tags {
let mostro_settings = Settings::get_mostro();
let ln_settings = Settings::get_ln();

Expand Down Expand Up @@ -193,5 +194,5 @@ pub fn info_to_tags(mostro_pubkey: &PublicKey) -> Vec<Tag> {
),
];

tags
Tags::new(tags)
}
37 changes: 11 additions & 26 deletions src/nip59.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use base64::engine::{general_purpose, Engine};
use nip44::v2::{decrypt_to_bytes, encrypt_to_bytes, ConversationKey};
use nostr_sdk::event::builder::Error as BuilderError;
use nostr_sdk::nostr::nips::nip44::v2::{decrypt_to_bytes, encrypt_to_bytes, ConversationKey};
use nostr_sdk::prelude::*;

/// Creates a new nip59 event
Expand All @@ -21,9 +21,8 @@ pub fn gift_wrap(
content: String,
expiration: Option<Timestamp>,
) -> Result<Event, BuilderError> {
let rumor: UnsignedEvent =
EventBuilder::text_note(content, []).to_unsigned_event(sender_keys.public_key());
let seal: Event = seal(sender_keys, &receiver, rumor)?.to_event(sender_keys)?;
let rumor: UnsignedEvent = EventBuilder::text_note(content, []).build(sender_keys.public_key());
let seal: Event = seal(sender_keys, &receiver, rumor)?.sign_with_keys(sender_keys)?;

gift_wrap_from_seal(&receiver, &seal, expiration)
}
Expand All @@ -33,10 +32,8 @@ pub fn seal(
receiver_pubkey: &PublicKey,
rumor: UnsignedEvent,
) -> Result<EventBuilder, BuilderError> {
let sender_private_key = sender_keys.secret_key()?;

// Derive conversation key
let ck = ConversationKey::derive(sender_private_key, receiver_pubkey);
let ck = ConversationKey::derive(sender_keys.secret_key(), receiver_pubkey);
// Encrypt content
let encrypted_content = encrypt_to_bytes(&ck, rumor.as_json())?;
// Encode with base64
Expand All @@ -53,7 +50,7 @@ pub fn gift_wrap_from_seal(
) -> Result<Event, BuilderError> {
let ephemeral_keys: Keys = Keys::generate();
// Derive conversation key
let ck = ConversationKey::derive(ephemeral_keys.secret_key()?, receiver);
let ck = ConversationKey::derive(ephemeral_keys.secret_key(), receiver);
// Encrypt content
let encrypted_content = encrypt_to_bytes(&ck, seal.as_json())?;

Expand All @@ -67,39 +64,27 @@ pub fn gift_wrap_from_seal(
let b64decoded_content = general_purpose::STANDARD.encode(encrypted_content);
EventBuilder::new(Kind::GiftWrap, b64decoded_content, tags)
.custom_created_at(Timestamp::tweaked(nip59::RANGE_RANDOM_TIMESTAMP_TWEAK))
.to_event(&ephemeral_keys)
.sign_with_keys(&ephemeral_keys)
}

pub fn unwrap_gift_wrap(keys: &Keys, gift_wrap: &Event) -> Result<UnwrappedGift, BuilderError> {
let ck = ConversationKey::derive(keys.secret_key()?, &gift_wrap.pubkey);
let ck = ConversationKey::derive(keys.secret_key(), &gift_wrap.pubkey);
let b64decoded_content = match general_purpose::STANDARD.decode(gift_wrap.content.as_bytes()) {
Ok(b64decoded_content) => b64decoded_content,
Err(e) => {
return Err(BuilderError::NIP44(
nostr_sdk::nips::nip44::Error::NotFound(e.to_string()),
))
}
Err(e) => return Err(BuilderError::NIP44(nip44::Error::NotFound(e.to_string()))),
};
// Decrypt and verify seal
let seal = decrypt_to_bytes(&ck, b64decoded_content)?;
let seal = String::from_utf8(seal).expect("Found invalid UTF-8");
let seal = match Event::from_json(seal) {
Ok(seal) => seal,
Err(e) => {
return Err(BuilderError::NIP44(
nostr_sdk::nips::nip44::Error::NotFound(e.to_string()),
))
}
Err(e) => return Err(BuilderError::NIP44(nip44::Error::NotFound(e.to_string()))),
};

let ck = ConversationKey::derive(keys.secret_key()?, &seal.pubkey);
let ck = ConversationKey::derive(keys.secret_key(), &seal.pubkey);
let b64decoded_content = match general_purpose::STANDARD.decode(seal.content.as_bytes()) {
Ok(b64decoded_content) => b64decoded_content,
Err(e) => {
return Err(BuilderError::NIP44(
nostr_sdk::nips::nip44::Error::NotFound(e.to_string()),
))
}
Err(e) => return Err(BuilderError::NIP44(nip44::Error::NotFound(e.to_string()))),
};
// Decrypt rumor
let rumor = decrypt_to_bytes(&ck, b64decoded_content)?;
Expand Down
18 changes: 9 additions & 9 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub async fn start_scheduler(rate_list: Arc<Mutex<Vec<Event>>>) {
}

async fn job_relay_list() {
let mostro_pubkey = match get_keys() {
let mostro_keys = match get_keys() {
Ok(keys) => keys,
Err(e) => return error!("{e}"),
};
Expand All @@ -45,13 +45,13 @@ async fn job_relay_list() {
let mut relay_tags: Vec<Tag> = vec![];

for (_, r) in relays.iter() {
if r.is_connected().await {
relay_tags.push(Tag::relay_metadata(r.url(), None))
if r.is_connected() {
relay_tags.push(Tag::relay_metadata(r.url().clone(), None))
}
}

if let Ok(relay_ev) =
EventBuilder::new(NostrKind::RelayList, "", relay_tags).to_event(&mostro_pubkey)
if let Ok(relay_ev) = EventBuilder::new(NostrKind::RelayList, "", relay_tags)
.sign_with_keys(&mostro_keys)
{
if let Ok(client) = get_nostr_client() {
let _ = client.send_event(relay_ev).await;
Expand All @@ -64,7 +64,7 @@ async fn job_relay_list() {
}

async fn job_info_event_send() {
let mostro_pubkey = match get_keys() {
let mostro_keys = match get_keys() {
Ok(keys) => keys,
Err(e) => return error!("{e}"),
};
Expand All @@ -74,10 +74,10 @@ async fn job_info_event_send() {
loop {
info!("Sending info about mostro");

let tags = crate::nip33::info_to_tags(&mostro_pubkey.public_key());
let id = format!("info-{}", mostro_pubkey.public_key());
let tags = crate::nip33::info_to_tags(&mostro_keys.public_key());
let id = format!("info-{}", mostro_keys.public_key());

let info_ev = match crate::nip33::new_event(&mostro_pubkey, "", id, tags) {
let info_ev = match crate::nip33::new_event(&mostro_keys, "", id, tags) {
Ok(info) => info,
Err(e) => return error!("{e}"),
};
Expand Down
9 changes: 5 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ pub async fn update_user_rating_event(
user: &str,
buyer_sent_rate: bool,
seller_sent_rate: bool,
tags: Vec<Tag>,
tags: Tags,
order_id: Uuid,
keys: &Keys,
pool: &SqlitePool,
Expand Down Expand Up @@ -347,7 +347,9 @@ pub async fn connect_nostr() -> Result<Client> {
let client = ClientBuilder::default().opts(opts).build();

// Add relays
client.add_relays(nostr_settings.relays).await?;
for relay in nostr_settings.relays.iter() {
client.add_relay(relay).await?;
}

// Connect to relays and keep connection alive
client.connect().await;
Expand Down Expand Up @@ -704,8 +706,7 @@ mod tests {
async fn test_get_nostr_client_success() {
initialize();
// Mock NOSTR_CLIENT initialization
let keys = Keys::generate();
let client = Client::new(&keys);
let client = Client::default();
NOSTR_CLIENT.set(client).unwrap();
let client_result = get_nostr_client();
assert!(client_result.is_ok());
Expand Down

0 comments on commit 2915f37

Please sign in to comment.