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
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ reqwest = { version = "0.12.23", default-features = false, features = [
"json",
"rustls-tls",
] }
mostro-core = "0.11.1"
mostro-core = "0.11.3"
lnurl-rs = { version = "0.9.0", default-features = false, features = ["ureq"] }
pretty_env_logger = "0.5.0"
sqlx = { version = "0.8.6", features = ["sqlite", "runtime-tokio-rustls"] }
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,7 @@ Every command supports `-h, --help`. The list below is a one-line summary; run `
- `cancel -o <id>` — cancel a pending order or cooperatively cancel later.
- `rate -o <id> -r <1-5>` — rate counterpart.
- `dispute -o <id>` — open a dispute.
- `addbondinvoice -o <id> -i <invoice>` — reply to a bond payout request with an invoice for your share of a slashed bond.

### Messaging
- `getdm [--since <min>] [--from-user]` — fetch recent DMs.
Expand Down
14 changes: 14 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod add_bond_invoice;
pub mod add_invoice;
pub mod adm_send_dm;
pub mod conversation_key;
Expand All @@ -17,6 +18,7 @@ pub mod send_msg;
pub mod take_dispute;
pub mod take_order;

use crate::cli::add_bond_invoice::execute_add_bond_invoice;
use crate::cli::add_invoice::execute_add_invoice;
use crate::cli::adm_send_dm::execute_adm_send_dm;
use crate::cli::conversation_key::execute_conversation_key;
Expand Down Expand Up @@ -169,6 +171,15 @@ pub enum Commands {
#[arg(short, long)]
invoice: String,
},
/// Reply to a bond payout request with an invoice for your share of a slashed bond
AddBondInvoice {
/// Order id
#[arg(short, long)]
order_id: Uuid,
/// Invoice string
#[arg(short, long)]
invoice: String,
},
/// Get the latest direct messages
GetDm {
/// Since time of the messages in minutes
Expand Down Expand Up @@ -577,6 +588,9 @@ impl Commands {
Commands::AddInvoice { order_id, invoice } => {
execute_add_invoice(order_id, invoice, ctx).await
}
Commands::AddBondInvoice { order_id, invoice } => {
execute_add_bond_invoice(order_id, invoice, ctx).await
}
Commands::Rate { order_id, rating } => execute_rate_user(order_id, rating, ctx).await,

// DM retrieval commands
Expand Down
106 changes: 106 additions & 0 deletions src/cli/add_bond_invoice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use crate::parser::common::{
create_emoji_field_row, create_field_value_header, create_standard_table,
};
use crate::util::{print_dm_events, send_dm, wait_for_dm, WaitForDmTimeout};
use crate::{cli::Context, db::Order, lightning::is_valid_invoice};
use anyhow::Result;
use mostro_core::prelude::*;
use nostr_sdk::prelude::*;
use uuid::Uuid;

/// Reply to a Mostro `add-bond-invoice` request: the non-slashed counterparty
/// provides a bolt11 sized at their share of a slashed bond.
///
/// This is the inbound `add-bond-invoice` request's dual — Mostro asks for a
/// bolt11 (carried as [`Payload::BondPayoutRequest`]) and we answer with the
/// invoice in the standard [`Payload::PaymentRequest`] shape, signed with the
/// order's trade key. See the protocol's "Bond payout invoice" action.
pub async fn execute_add_bond_invoice(order_id: &Uuid, invoice: &str, ctx: &Context) -> Result<()> {
// Get order from order id
let order = Order::get_by_id(&ctx.pool, &order_id.to_string()).await?;
// Get trade keys of specific order (the non-slashed counterparty side)
let trade_keys = order
.trade_keys
.clone()
.ok_or(anyhow::anyhow!("Missing trade keys"))?;

let order_trade_keys = Keys::parse(&trade_keys)?;

println!("🪙 Add Bond Payout Invoice");
println!("═══════════════════════════════════════");

let mut table = create_standard_table();
table.set_header(create_field_value_header());
table.add_row(create_emoji_field_row(
"📋 ",
"Order ID",
&order_id.to_string(),
));
table.add_row(create_emoji_field_row(
"🔑 ",
"Trade Keys",
&order_trade_keys.public_key().to_hex(),
));
table.add_row(create_emoji_field_row(
"🎯 ",
"Target",
&ctx.mostro_pubkey.to_string(),
));
println!("{table}");
println!("💡 Sending bond payout invoice to Mostro...\n");
// The bond payout reply must be a bolt11 sized at the counterparty share.
// Lightning Addresses are not accepted here (the protocol's "Bond payout
// invoice" reply is a bolt11): validate locally so a bad input fails fast
// instead of bouncing back as a `cant-do` / `invalid-invoice` from Mostro.
let invoice = is_valid_invoice(invoice)
.map_err(|e| anyhow::anyhow!("Invalid invoice: {}", e))?
.to_string();
let payload = Payload::PaymentRequest(None, invoice, None);

// Create request id
let request_id = Uuid::new_v4().as_u128() as u64;
// Create AddBondInvoice reply message
let add_bond_invoice_message = Message::new_order(
Some(*order_id),
Some(request_id),
None,
Action::AddBondInvoice,
Some(payload),
);

// Serialize the message
let message_json = add_bond_invoice_message
.as_json()
.map_err(|_| anyhow::anyhow!("Failed to serialize message"))?;

// Send the DM
let sent_message = send_dm(
&ctx.client,
&ctx.identity_keys,
&order_trade_keys,
&ctx.mostro_pubkey,
message_json,
None,
false,
);

// Wait for a possible reply. On success Mostro pays the invoice from its
// wallet without acknowledging over Nostr, so a *timeout* here is the happy
// path; Mostro only answers with `cant-do` on failure (late reply, wrong
// sender, bad invoice, etc.). Any other error (subscribe/sign/transport)
// means the reply may never have been sent — surface it instead of
// misreporting it as success.
match wait_for_dm(ctx, Some(&order_trade_keys), sent_message).await {
Ok(recv_event) => {
print_dm_events(recv_event, request_id, ctx, Some(&order_trade_keys)).await?;
}
Err(e) if e.downcast_ref::<WaitForDmTimeout>().is_some() => {
println!("✅ Bond payout invoice submitted to Mostro.");
println!("💡 Mostro will pay it from its wallet; no further confirmation is sent.");
println!("💡 Run `get-dm` to check for a `cant-do` response in case of an error.");
}
Err(e) => return Err(e),
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

Ok(())
}
19 changes: 16 additions & 3 deletions src/cli/get_dm.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use anyhow::Result;
use mostro_core::prelude::Message;
use mostro_core::prelude::{Action, Message, Payload};
use nostr_sdk::prelude::*;

use crate::{
cli::Context,
parser::common::{print_key_value, print_section_header},
parser::dms::print_direct_messages,
util::{fetch_events_list, Event, ListKind},
util::{fetch_bond_claim_window_days, fetch_events_list, Event, ListKind},
};

pub async fn execute_get_dm(
Expand Down Expand Up @@ -42,6 +42,19 @@ pub async fn execute_get_dm(
}
}

print_direct_messages(&dm_events, Some(ctx.mostro_pubkey)).await?;
// Only hit the relay for the node's claim window when an inbound bond
// payout request is actually present, so the common get-dm path stays cheap.
let has_bond_payout_request = dm_events.iter().any(|(message, _, _)| {
let inner = message.get_inner_message_kind();
inner.action == Action::AddBondInvoice
&& matches!(inner.payload, Some(Payload::BondPayoutRequest(_)))
});
let claim_window_days = if has_bond_payout_request {
fetch_bond_claim_window_days(ctx).await
} else {
None
};

print_direct_messages(&dm_events, Some(ctx.mostro_pubkey), claim_window_days).await?;
Ok(())
}
88 changes: 85 additions & 3 deletions src/parser/dms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
print_payment_method, print_premium, print_required_amount, print_section_header,
print_success_message, print_trade_index,
},
util::save_order,
util::{fetch_bond_claim_window_days, save_order},
};
use serde_json;

Expand Down Expand Up @@ -98,14 +98,80 @@ fn handle_pay_bond_invoice_display(order: &Option<mostro_core::order::SmallOrder
println!();
}

/// Render the forfeit deadline of a bond payout request.
///
/// The protocol mandates computing it from the on-wire `slashed_at` anchor
/// (never the local receive time):
/// `deadline = slashed_at + bond_payout_claim_window_days * 86_400`. The claim
/// window comes from the node's kind-38385 info event and may be unavailable.
fn format_bond_forfeit_deadline(slashed_at: i64, claim_window_days: Option<i64>) -> String {
let slashed = format_timestamp(slashed_at);
match claim_window_days {
Some(days) => {
let deadline_ts = slashed_at.saturating_add(days.saturating_mul(86_400));
format!(
"Slashed at {} — forfeit deadline {} ({} day claim window)",
slashed,
format_timestamp(deadline_ts),
days
)
}
None => format!(
"Slashed at {} — claim window unknown (Mostro info event unavailable)",
slashed
),
}
}

/// Display an inbound `add-bond-invoice` request (Mostro → non-slashed
/// counterparty): the order context plus the locally-rendered forfeit deadline.
fn handle_add_bond_invoice_request_display(
req: &BondPayoutRequest,
claim_window_days: Option<i64>,
) {
print_section_header("🪙 Bond Payout Invoice Requested");
if let Some(order_id) = req.order.id {
println!("📋 Order ID: {}", order_id);
}
print_required_amount(req.order.amount);
print_fiat_code(&req.order.fiat_code);
println!("💵 Fiat Amount: {}", req.order.fiat_amount);
print_payment_method(&req.order.payment_method);
println!(
"⏰ {}",
format_bond_forfeit_deadline(req.slashed_at, claim_window_days)
);
println!();
println!("💡 A bond on this trade was slashed; you can claim your share.");
println!("💡 Reply before the deadline with a Lightning invoice for the amount above:");
println!(
" mostro-cli addbondinvoice -o {} -i <bolt11>",
req.order
.id
.map(|x| x.to_string())
.unwrap_or_else(|| "<order-id>".to_string())
);
println!();
}

/// Format payload details for DM table display
fn format_payload_details(payload: &Payload, action: &Action) -> String {
fn format_payload_details(
payload: &Payload,
action: &Action,
claim_window_days: Option<i64>,
) -> String {
match payload {
Payload::TextMessage(t) => format!("✉️ {}", t),
Payload::PaymentRequest(_, inv, _) => {
// For invoices, show the full invoice without truncation
format!("⚡ Lightning Invoice:\n{}", inv)
}
Payload::BondPayoutRequest(req) => format!(
"🪙 Bond payout request: {} sats ({})\n⏰ {}",
req.order.amount,
req.order.fiat_code,
format_bond_forfeit_deadline(req.slashed_at, claim_window_days)
),
Payload::Dispute(id, _) => format!("⚖️ Dispute ID: {}", id),
Payload::Order(o) if *action == Action::NewOrder => format!(
"🆕 New Order: {} {} sats ({})",
Expand Down Expand Up @@ -537,6 +603,20 @@ pub async fn print_commands_results(message: &MessageKind, ctx: &Context) -> Res
print_success_message("Order saved successfully!");
Ok(())
}
// mostro-core 0.11.3: bond payout invoice request sent to the
// non-slashed counterparty after a bond is slashed. Reply with
// `add-bond-invoice` carrying a bolt11 for your share.
Action::AddBondInvoice => match &message.payload {
Some(Payload::BondPayoutRequest(req)) => {
let claim_window_days = fetch_bond_claim_window_days(ctx).await;
handle_add_bond_invoice_request_display(req, claim_window_days);
Ok(())
}
other => Err(anyhow::anyhow!(
"AddBondInvoice expected Payload::BondPayoutRequest, got: {:?}",
other
)),
},
Action::CantDo => {
println!("❌ Action Cannot Be Completed");
println!("═══════════════════════════════════════");
Expand Down Expand Up @@ -871,6 +951,7 @@ pub async fn parse_dm_events(
pub async fn print_direct_messages(
dm: &[(Message, u64, PublicKey)],
mostro_pubkey: Option<PublicKey>,
claim_window_days: Option<i64>,
) -> Result<()> {
if dm.is_empty() {
println!();
Expand All @@ -896,6 +977,7 @@ pub async fn print_direct_messages(
Action::NewOrder => "🆕",
Action::AddInvoice | Action::PayInvoice => "⚡",
Action::PayBondInvoice => "🪙",
Action::AddBondInvoice => "💰",
Action::FiatSent | Action::FiatSentOk => "💸",
Action::Release | Action::Released => "🔓",
Action::Cancel | Action::Canceled => "🚫",
Expand Down Expand Up @@ -927,7 +1009,7 @@ pub async fn print_direct_messages(

// Print details with proper formatting
if let Some(payload) = &inner.payload {
let details = format_payload_details(payload, &inner.action);
let details = format_payload_details(payload, &inner.action, claim_window_days);
println!("📝 Details:");
for line in details.lines() {
println!(" {}", line);
Expand Down
33 changes: 33 additions & 0 deletions src/util/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,39 @@ pub fn create_filter(
}
}

/// Fetch the Mostro instance's kind-38385 info event and read the
/// `bond_payout_claim_window_days` tag.
///
/// Returns `None` when the node publishes no info event, the tag is absent
/// (older daemon or bonds disabled), or the value can't be parsed. Used to
/// render the forfeit deadline for an `add-bond-invoice` request locally, per
/// the protocol's "Bond payout invoice" / "Other events" docs. Best-effort:
/// any relay error degrades to `None` rather than failing the caller.
pub async fn fetch_bond_claim_window_days(ctx: &crate::cli::Context) -> Option<i64> {
Comment thread
grunch marked this conversation as resolved.
let filter = Filter::new()
.author(ctx.mostro_pubkey)
.kind(nostr_sdk::Kind::Custom(NOSTR_INFO_EVENT_KIND));

let events = ctx
.client
.fetch_events(filter, FETCH_EVENTS_TIMEOUT)
.await
.ok()?;

// kind-38385 is replaceable, but pick the newest revision by `created_at`
// explicitly: a lagging relay (or several relays at once) can still surface
// an older copy, and a stale claim window would render the wrong, very
// user-facing forfeit deadline.
let event = events.iter().max_by_key(|e| e.created_at)?;
for tag in event.tags.iter() {
let slice = tag.as_slice();
if slice.first().map(String::as_str) == Some("bond_payout_claim_window_days") {
return slice.get(1).and_then(|v| v.parse::<i64>().ok());
}
}
None
}

#[allow(clippy::too_many_arguments)]
pub async fn fetch_events_list(
list_kind: ListKind,
Expand Down
Loading
Loading