Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
832 changes: 513 additions & 319 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ path = "src/main.rs"
[dependencies]
anyhow = "1.0.68"
clap = { version = "4.0.32", features = ["derive"] }
nostr-sdk = { version = "0.37.0", features = ["nip06", "nip44", "nip59"] }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr", features = ["nip06", "nip44", "nip59"], rev ="70db575d51965240aab1e1b3f1edab782c0ef625"}
# nostr-sdk = { version = "0.37.0", features = ["nip06", "nip44", "nip59"] }
Comment thread
grunch marked this conversation as resolved.
serde = "1.0.215"
serde_json = "1.0.91"
tokio = { version = "1.23.0", features = ["full"] }
Expand All @@ -39,11 +40,11 @@ uuid = { version = "1.3.0", features = [
dotenvy = "0.15.6"
lightning-invoice = "0.23.0"
reqwest = { version = "0.12.4", features = ["json"] }
mostro-core = "0.6.17"
mostro-core = { git = "https://github.com/MostroP2P/mostro-core", branch = "test-new-sdk" }
Comment thread
grunch marked this conversation as resolved.
bitcoin_hashes = "0.15.0"
lnurl-rs = "0.9.0"
pretty_env_logger = "0.5.0"
openssl = { version = "0.10.68", features = ["vendored"] }
sqlx = { version = "0.8.2", features = ["sqlite", "runtime-tokio-native-tls"] }
bip39 = { version = "2.1.0", features = ["rand"] }
dirs = "5.0.1"
dirs = "5.0.1"
5 changes: 5 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[toolchain]
channel = "1.82.0"
profile = "minimal"
components = ["clippy", "rust-docs", "rustfmt"]
targets = ["wasm32-unknown-unknown"]
17 changes: 6 additions & 11 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ pub enum Commands {
/// Pubkey of the counterpart
#[arg(short, long)]
pubkey: String,
/// Order id
#[arg(short, long)]
order_id: Uuid,
/// Message to send
#[arg(short, long)]
message: String,
Expand Down Expand Up @@ -410,24 +413,16 @@ pub async fn run() -> Result<()> {
.await?
}
Commands::Rate { order_id, rating } => {
execute_rate_user(
order_id,
rating,
&identity_keys,
&trade_keys,
mostro_key,
&client,
)
.await?;
execute_rate_user(order_id, rating, &identity_keys, mostro_key, &client).await?;
}
Commands::AdmTakeDispute { dispute_id } => {
execute_take_dispute(dispute_id, &identity_keys, &trade_keys, mostro_key, &client)
.await?
}
Commands::AdmListDisputes {} => execute_list_disputes(mostro_key, &client).await?,
Commands::SendDm { pubkey, message } => {
Commands::SendDm { pubkey, order_id, message } => {
let pubkey = PublicKey::from_str(pubkey)?;
execute_send_dm(&trade_keys, pubkey, &client, message).await?
execute_send_dm(pubkey, &client, order_id, message).await?
}
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/cli/add_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn execute_add_invoice(
.await
.unwrap();
let trade_keys = order.trade_keys.clone().unwrap();
let trade_keys = Keys::parse(trade_keys).unwrap();
let trade_keys = Keys::parse(&trade_keys).unwrap();
Comment thread
grunch marked this conversation as resolved.

println!(
"Sending a lightning invoice {} to mostro pubId {}",
Expand Down
23 changes: 20 additions & 3 deletions src/cli/rate_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ use mostro_core::message::{Action, Message, Payload};
use nostr_sdk::prelude::*;
use uuid::Uuid;

use crate::util::send_message_sync;
use crate::{
db::{connect, Order},
util::send_message_sync,
};

pub async fn execute_rate_user(
order_id: &Uuid,
rating: &u8,
identity_keys: &Keys,
trade_keys: &Keys,
mostro_key: PublicKey,
client: &Client,
) -> Result<()> {
Expand All @@ -24,6 +26,21 @@ pub async fn execute_rate_user(
std::process::exit(0);
}

let pool = connect().await?;

let trade_keys = if let Ok(order_to_vote) = Order::get_by_id(&pool, &order_id.to_string()).await
{
match order_to_vote.trade_keys.as_ref() {
Some(trade_keys) => Keys::parse(trade_keys)?,
None => {
anyhow::bail!("No trade_keys found for this order");
}
}
} else {
println!("order {} not found", order_id);
std::process::exit(0)
};

// Create rating message of counterpart
let rate_message = Message::new_order(
Some(*order_id),
Expand All @@ -36,7 +53,7 @@ pub async fn execute_rate_user(
send_message_sync(
client,
Some(identity_keys),
trade_keys,
&trade_keys,
mostro_key,
rate_message,
true,
Expand Down
24 changes: 21 additions & 3 deletions src/cli/send_dm.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use crate::util::send_message_sync;
use crate::{db::Order, util::send_message_sync};
use anyhow::Result;
use mostro_core::message::{Action, Message, Payload};
use nostr_sdk::prelude::*;
use uuid::Uuid;

pub async fn execute_send_dm(
trade_keys: &Keys,
receiver: PublicKey,
client: &Client,
order_id: &Uuid,
message: &str,
) -> Result<()> {
let message = Message::new_dm(
Expand All @@ -15,7 +16,24 @@ pub async fn execute_send_dm(
Action::SendDm,
Some(Payload::TextMessage(message.to_string())),
);
send_message_sync(client, None, trade_keys, receiver, message, true, true).await?;

let pool = crate::db::connect().await?;

let trade_keys = if let Ok(order_to_vote) = Order::get_by_id(&pool, &order_id.to_string()).await
{
match order_to_vote.trade_keys.as_ref() {
Some(trade_keys) => Keys::parse(trade_keys)?,
None => {
anyhow::bail!("No trade_keys found for this order");
}
}
} else {
println!("order {} not found", order_id);
std::process::exit(0)
};


send_message_sync(client, None, &trade_keys, receiver, message, true, true).await?;

Ok(())
}
2 changes: 1 addition & 1 deletion src/cli/send_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub async fn execute_send_msg(
match order {
Ok(order) => {
if let Some(trade_keys_str) = order.trade_keys {
let trade_keys = Keys::parse(trade_keys_str)?;
let trade_keys = Keys::parse(&trade_keys_str)?;
send_message_sync(
client,
identity_keys,
Expand Down
43 changes: 19 additions & 24 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::util::get_mcli_path;
use anyhow::Result;
use mostro_core::order::SmallOrder;
use mostro_core::NOSTR_REPLACEABLE_EVENT_KIND;
use nip06::FromMnemonic;
Expand All @@ -9,15 +10,15 @@ use sqlx::SqlitePool;
use std::fs::File;
use std::path::Path;

pub async fn connect() -> Result<Pool<Sqlite>, sqlx::Error> {
pub async fn connect() -> Result<Pool<Sqlite>> {
let mcli_dir = get_mcli_path();
let mcli_db_path = format!("{}/mcli.db", mcli_dir);
let db_url = format!("sqlite://{}", mcli_db_path);
let pool: Pool<Sqlite>;
if !Path::exists(Path::new(&mcli_db_path)) {
if let Err(res) = File::create(&mcli_db_path) {
println!("Error in creating db file: {}", res);
return Err(sqlx::Error::Io(res));
return Err(res.into());
}
pool = SqlitePool::connect(&db_url).await?;
println!("Creating database file with orders table...");
Expand Down Expand Up @@ -59,10 +60,10 @@ pub async fn connect() -> Result<Pool<Sqlite>, sqlx::Error> {
Ok(m) => m.to_string(),
Err(e) => {
println!("Error generating mnemonic: {}", e);
return Err(sqlx::Error::Decode(Box::new(e)));
return Err(e.into());
}
};
let user = User::new(mnemonic, &pool).await.unwrap();
let user = User::new(mnemonic, &pool).await?;
println!("User created with pubkey: {}", user.i0_pubkey);
} else {
pool = SqlitePool::connect(&db_url).await?;
Expand All @@ -81,10 +82,7 @@ pub struct User {
}

impl User {
pub async fn new(
mnemonic: String,
pool: &SqlitePool,
) -> Result<Self, Box<dyn std::error::Error>> {
pub async fn new(mnemonic: String, pool: &SqlitePool) -> Result<Self> {
let mut user = User::default();
let account = NOSTR_REPLACEABLE_EVENT_KIND as u32;
let i0_keys =
Expand Down Expand Up @@ -118,7 +116,7 @@ impl User {
}

// Applying changes to the database
pub async fn save(&self, pool: &SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
pub async fn save(&self, pool: &SqlitePool) -> Result<()> {
sqlx::query(
r#"
UPDATE users
Expand All @@ -140,7 +138,7 @@ impl User {
Ok(())
}

pub async fn get(pool: &SqlitePool) -> Result<User, Box<dyn std::error::Error>> {
pub async fn get(pool: &SqlitePool) -> Result<User> {
let user = sqlx::query_as::<_, User>(
r#"
SELECT i0_pubkey, mnemonic, last_trade_index, created_at
Expand All @@ -154,15 +152,15 @@ impl User {
Ok(user)
}

pub async fn get_next_trade_index(pool: SqlitePool) -> Result<i64, Box<dyn std::error::Error>> {
pub async fn get_next_trade_index(pool: SqlitePool) -> Result<i64> {
let user = User::get(&pool).await?;
match user.last_trade_index {
Some(index) => Ok(index + 1),
None => Ok(1),
}
}

pub async fn get_identity_keys(pool: &SqlitePool) -> Result<Keys, Box<dyn std::error::Error>> {
pub async fn get_identity_keys(pool: &SqlitePool) -> Result<Keys> {
let user = User::get(pool).await?;
let account = NOSTR_REPLACEABLE_EVENT_KIND as u32;
let keys =
Expand All @@ -171,10 +169,10 @@ impl User {
Ok(keys)
}

pub async fn get_next_trade_keys(
pool: &SqlitePool,
) -> Result<(Keys, i64), Box<dyn std::error::Error>> {
let trade_index = User::get_next_trade_index(pool.clone()).await?;
pub async fn get_next_trade_keys(pool: &SqlitePool) -> Result<(Keys, i64)> {
let mut trade_index = User::get_next_trade_index(pool.clone()).await?;
trade_index = trade_index - 1;

let user = User::get(pool).await?;
let account = NOSTR_REPLACEABLE_EVENT_KIND as u32;
match trade_index.try_into() {
Expand Down Expand Up @@ -225,7 +223,7 @@ impl Order {
order: SmallOrder,
trade_keys: &Keys,
request_id: Option<i64>,
) -> Result<Self, Box<dyn std::error::Error>> {
) -> Result<Self> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Storing trade_keys in plaintext.
If trade_keys is sensitive, consider whether storing it as plain hex is acceptable within the threat model. You may want to encrypt it at rest depending on security requirements.

let trade_keys_hex = trade_keys.secret_key().to_secret_hex();
let id = match order.id {
Some(id) => id.to_string(),
Expand Down Expand Up @@ -349,7 +347,7 @@ impl Order {
}

// Applying changes to the database
pub async fn save(&self, pool: &SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
pub async fn save(&self, pool: &SqlitePool) -> Result<()> {
// Validation if an identity document is present
if let Some(ref id) = self.id {
sqlx::query(
Expand Down Expand Up @@ -385,7 +383,7 @@ impl Order {

println!("Order with id {} updated in the database.", id);
} else {
return Err("Order must have an ID to be updated.".into());
return Err(anyhow::anyhow!("Order must have an ID to be updated."));
}

Ok(())
Expand All @@ -412,10 +410,7 @@ impl Order {
Ok(rows_affected > 0)
}

pub async fn get_by_id(
pool: &SqlitePool,
id: &str,
) -> Result<Order, Box<dyn std::error::Error>> {
pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Order> {
let order = sqlx::query_as::<_, Order>(
r#"
SELECT * FROM orders WHERE id = ?
Expand All @@ -429,7 +424,7 @@ impl Order {
Ok(order)
}

pub async fn get_all(pool: &SqlitePool) -> Result<Vec<Order>, Box<dyn std::error::Error>> {
pub async fn get_all(pool: &SqlitePool) -> Result<Vec<Order>> {
let orders = sqlx::query_as::<_, Order>(r#"SELECT * FROM orders"#)
.fetch_all(pool)
.await?;
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ pub mod db;
pub mod error;
pub mod lightning;
pub mod nip33;
pub mod nip59;
Comment thread
grunch marked this conversation as resolved.
pub mod pretty_table;
pub mod util;
Loading