Skip to content

Commit

Permalink
Merge branch 'main' into trick-gift-wrap-events
Browse files Browse the repository at this point in the history
  • Loading branch information
grunch authored Nov 1, 2024
2 parents c801865 + df845f9 commit 03cb17f
Show file tree
Hide file tree
Showing 9 changed files with 252 additions and 64 deletions.
8 changes: 8 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ pub async fn run(
};

let event = unwrap_gift_wrap(&my_keys, &event)?;
// We discard events older than 10 seconds
let since_time = chrono::Utc::now()
.checked_sub_signed(chrono::Duration::seconds(10))
.unwrap()
.timestamp() as u64;
if event.rumor.created_at.as_u64() < since_time {
continue;
}

let message = Message::from_json(&event.rumor.content);
match message {
Expand Down
3 changes: 2 additions & 1 deletion src/app/admin_add_solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ pub async fn admin_add_solver_action(
let message = Message::new_dispute(None, Action::AdminAddSolver, None);
let message = message.as_json()?;
// Send the message
send_dm(&event.sender, message).await?;
let sender_keys = crate::util::get_keys().unwrap();
send_dm(&event.sender, sender_keys, message).await?;

Ok(())
}
24 changes: 16 additions & 8 deletions src/app/admin_cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use std::str::FromStr;
use crate::db::{find_dispute_by_order_id, is_assigned_solver};
use crate::lightning::LndConnector;
use crate::nip33::new_event;
use crate::util::{send_dm, send_new_order_msg, update_order_event};
use crate::NOSTR_CLIENT;
use crate::util::{get_nostr_client, send_dm, send_new_order_msg, update_order_event};

use anyhow::{Error, Result};
use mostro_core::dispute::Status as DisputeStatus;
Expand Down Expand Up @@ -59,7 +58,8 @@ pub async fn admin_cancel_action(
if order.status == Status::CooperativelyCanceled.to_string() {
let message = MessageKind::new(Some(order_id), Action::CooperativeCancelAccepted, None);
if let Ok(message) = message.as_json() {
let _ = send_dm(&event.sender, message).await;
let sender_keys = crate::util::get_keys().unwrap();
let _ = send_dm(&event.sender, sender_keys, message).await;
}
return Ok(());
}
Expand Down Expand Up @@ -109,7 +109,14 @@ pub async fn admin_cancel_action(
// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute_id.to_string(), tags)?;

NOSTR_CLIENT.get().unwrap().send_event(event).await?;
match get_nostr_client() {
Ok(client) => {
if let Err(e) = client.send_event(event).await {
error!("Failed to send dispute status event: {}", e);
}
}
Err(e) => error!("Failed to get Nostr client: {}", e),
}
}

// We publish a new replaceable kind nostr event with the status updated
Expand All @@ -120,7 +127,8 @@ pub async fn admin_cancel_action(
let message = Message::new_order(Some(order.id), Action::AdminCanceled, None);
let message = message.as_json()?;
// Message to admin
send_dm(&event.sender, message.clone()).await?;
let sender_keys = crate::util::get_keys().unwrap();
send_dm(&event.sender, sender_keys, message.clone()).await?;

let (seller_pubkey, buyer_pubkey) = match (&order.seller_pubkey, &order.buyer_pubkey) {
(Some(seller), Some(buyer)) => (
Expand All @@ -130,9 +138,9 @@ pub async fn admin_cancel_action(
(None, _) => return Err(Error::msg("Missing seller pubkey")),
(_, None) => return Err(Error::msg("Missing buyer pubkey")),
};

send_dm(&seller_pubkey, message.clone()).await?;
send_dm(&buyer_pubkey, message).await?;
let sender_keys = crate::util::get_keys().unwrap();
send_dm(&seller_pubkey, sender_keys.clone(), message.clone()).await?;
send_dm(&buyer_pubkey, sender_keys, message).await?;

Ok(())
}
36 changes: 29 additions & 7 deletions src/app/admin_settle.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::db::{find_dispute_by_order_id, is_assigned_solver};
use crate::lightning::LndConnector;
use crate::nip33::new_event;
use crate::util::{send_dm, send_new_order_msg, settle_seller_hold_invoice, update_order_event};
use crate::NOSTR_CLIENT;
use crate::util::{
get_nostr_client, send_dm, send_new_order_msg, settle_seller_hold_invoice, update_order_event,
};

use anyhow::{Error, Result};
use mostro_core::dispute::Status as DisputeStatus;
Expand Down Expand Up @@ -60,7 +61,8 @@ pub async fn admin_settle_action(
if order.status == Status::CooperativelyCanceled.to_string() {
let message = MessageKind::new(Some(order_id), Action::CooperativeCancelAccepted, None);
if let Ok(message) = message.as_json() {
let _ = send_dm(&event.sender, message).await;
let sender_keys = crate::util::get_keys().unwrap();
let _ = send_dm(&event.sender, sender_keys, message).await;
}
return Ok(());
}
Expand Down Expand Up @@ -107,18 +109,38 @@ pub async fn admin_settle_action(
// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute_id.to_string(), tags)?;

NOSTR_CLIENT.get().unwrap().send_event(event).await?;
match get_nostr_client() {
Ok(client) => {
if let Err(e) = client.send_event(event).await {
error!("Failed to send dispute settlement event: {}", e);
}
}
Err(e) => {
error!("Failed to get Nostr client for dispute settlement: {}", e);
}
}
}
// We create a Message for settle
let message = Message::new_order(Some(order_updated.id), Action::AdminSettled, None);
let message = message.as_json()?;
// Message to admin
send_dm(&event.sender, message.clone()).await?;
let sender_keys = crate::util::get_keys().unwrap();
send_dm(&event.sender, sender_keys.clone(), message.clone()).await?;
if let Some(ref seller_pubkey) = order_updated.seller_pubkey {
send_dm(&PublicKey::from_str(seller_pubkey)?, message.clone()).await?;
send_dm(
&PublicKey::from_str(seller_pubkey)?,
sender_keys.clone(),
message.clone(),
)
.await?;
}
if let Some(ref buyer_pubkey) = order_updated.buyer_pubkey {
send_dm(&PublicKey::from_str(buyer_pubkey)?, message.clone()).await?;
send_dm(
&PublicKey::from_str(buyer_pubkey)?,
sender_keys,
message.clone(),
)
.await?;
}

let _ = do_payment(order_updated).await;
Expand Down
26 changes: 19 additions & 7 deletions src/app/admin_take_dispute.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::db::find_solver_pubkey;
use crate::nip33::new_event;
use crate::util::{send_cant_do_msg, send_dm, send_new_order_msg};
use crate::NOSTR_CLIENT;
use crate::util::{get_nostr_client, send_cant_do_msg, send_dm, send_new_order_msg};

use anyhow::{Error, Result};
use mostro_core::dispute::{Dispute, Status};
Expand Down Expand Up @@ -103,7 +102,8 @@ pub async fn admin_take_dispute_action(
Some(Content::Order(new_order)),
);
let message = message.as_json()?;
send_dm(&event.sender, message).await?;
let sender_keys = crate::util::get_keys().unwrap();
send_dm(&event.sender, sender_keys, message).await?;
// Now we create a message to both parties of the order
// to them know who will assist them on the dispute
let solver_pubkey = Peer::new(event.sender.to_hex());
Expand All @@ -127,9 +127,9 @@ pub async fn admin_take_dispute_action(
(None, _) => return Err(Error::msg("Missing seller pubkey")),
(_, None) => return Err(Error::msg("Missing buyer pubkey")),
};

send_dm(&buyer_pubkey, msg_to_buyer.as_json()?).await?;
send_dm(&seller_pubkey, msg_to_seller.as_json()?).await?;
let sender_keys = crate::util::get_keys().unwrap();
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![
Tag::custom(
Expand All @@ -148,7 +148,19 @@ pub async fn admin_take_dispute_action(
// 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:#?}");
NOSTR_CLIENT.get().unwrap().send_event(event).await?;

let client = get_nostr_client().map_err(|e| {
info!(
"Failed to get nostr client for dispute {}: {}",
dispute_id, e
);
e
})?;

client.send_event(event).await.map_err(|e| {
info!("Failed to send dispute {} status event: {}", dispute_id, e);
e
})?;

Ok(())
}
8 changes: 5 additions & 3 deletions src/app/dispute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use std::str::FromStr;

use crate::db::find_dispute_by_order_id;
use crate::nip33::new_event;
use crate::util::{send_cant_do_msg, send_new_order_msg};
use crate::NOSTR_CLIENT;
use crate::util::{get_nostr_client, send_cant_do_msg, send_new_order_msg};

use anyhow::{Error, Result};
use mostro_core::dispute::Dispute;
Expand Down Expand Up @@ -174,7 +173,10 @@ pub async fn dispute_action(
// nip33 kind with dispute id as identifier
let event = new_event(my_keys, "", dispute.id.to_string(), tags)?;
info!("Dispute event to be published: {event:#?}");
NOSTR_CLIENT.get().unwrap().send_event(event).await?;

if let Ok(client) = get_nostr_client() {
let _ = client.send_event(event).await;
}

Ok(())
}
29 changes: 15 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ use lightning::LndConnector;
use nostr_sdk::prelude::*;
use scheduler::start_scheduler;
use std::env;
use std::process::exit;
use std::sync::Arc;
use std::sync::OnceLock;
use tokio::sync::Mutex;
use tracing::{error, info};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
use util::invoice_subscribe;
use util::{get_nostr_client, invoice_subscribe};

static MOSTRO_CONFIG: OnceLock<Settings> = OnceLock::new();
static NOSTR_CLIENT: OnceLock<Client> = OnceLock::new();
Expand Down Expand Up @@ -71,11 +72,18 @@ async fn main() -> Result<()> {
.kind(Kind::GiftWrap)
.limit(0);

NOSTR_CLIENT
.get()
.unwrap()
.subscribe(vec![subscription], None)
.await;
let client = match get_nostr_client() {
Ok(client) => client,
Err(e) => {
tracing::error!("Failed to initialize Nostr client. Cannot proceed: {e}");
// Clean up any resources if needed
exit(1)
}
};

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

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

if let Ok(held_invoices) = find_held_invoices(&pool).await {
Expand All @@ -92,14 +100,7 @@ async fn main() -> Result<()> {
// Start scheduler for tasks
start_scheduler(rate_list.clone()).await;

run(
my_keys,
NOSTR_CLIENT.get().unwrap(),
&mut ln_client,
pool,
rate_list.clone(),
)
.await
run(my_keys, client, &mut ln_client, pool, rate_list.clone()).await
}

#[cfg(test)]
Expand Down
39 changes: 23 additions & 16 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ use crate::cli::settings::Settings;
use crate::db::*;
use crate::lightning::LndConnector;
use crate::util;
use crate::NOSTR_CLIENT;
use crate::util::get_nostr_client;

use chrono::{TimeDelta, Utc};
use mostro_core::order::{Kind, Status};
use nostr_sdk::EventBuilder;
use nostr_sdk::{Event, Kind as NostrKind, Tag, Url};
use nostr_sdk::{Event, Kind as NostrKind, Tag};
use sqlx_crud::Crud;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{error, info};
use util::{get_keys, update_order_event};
use util::{get_keys, get_nostr_relays, update_order_event};

pub async fn start_scheduler(rate_list: Arc<Mutex<Vec<Event>>>) {
info!("Creating scheduler");
Expand All @@ -42,17 +41,22 @@ async fn job_relay_list() {
info!("Sending Mostro relay list");

let interval = Settings::get_mostro().publish_relays_interval as u64;
let relay_list = Settings::get_nostr().relays;
let mut relay_tags: Vec<Tag> = vec![];
if let Some(relays) = get_nostr_relays().await {
let mut relay_tags: Vec<Tag> = vec![];

for r in relay_list {
relay_tags.push(Tag::relay_metadata(Url::from_str(&r).unwrap(), None))
}
for (_, r) in relays.iter() {
if r.is_connected().await {
relay_tags.push(Tag::relay_metadata(r.url(), None))
}
}

if let Ok(relay_ev) =
EventBuilder::new(NostrKind::RelayList, "", relay_tags).to_event(&mostro_pubkey)
{
let _ = NOSTR_CLIENT.get().unwrap().send_event(relay_ev).await;
if let Ok(relay_ev) =
EventBuilder::new(NostrKind::RelayList, "", relay_tags).to_event(&mostro_pubkey)
{
if let Ok(client) = get_nostr_client() {
let _ = client.send_event(relay_ev).await;
}
}
}
tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await;
}
Expand All @@ -77,7 +81,10 @@ async fn job_info_event_send() {
Ok(info) => info,
Err(e) => return error!("{e}"),
};
let _ = NOSTR_CLIENT.get().unwrap().send_event(info_ev).await;

if let Ok(client) = get_nostr_client() {
let _ = client.send_event(info_ev).await;
}

tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await;
}
Expand Down Expand Up @@ -130,8 +137,8 @@ async fn job_update_rate_events(rate_list: Arc<Mutex<Vec<Event>>>) {

for ev in inner_list.lock().await.iter() {
// Send event to relay
if let Some(client) = NOSTR_CLIENT.get() {
match &client.send_event(ev.clone()).await {
if let Ok(client) = get_nostr_client() {
match client.send_event(ev.clone()).await {
Ok(id) => {
info!("Updated rate event with id {:?}", id)
}
Expand Down
Loading

0 comments on commit 03cb17f

Please sign in to comment.