This document describes the internal structure of mostro-cli, how major modules interact, and the main data/control flows. It is intentionally high-level to stay stable across refactors.
-
src/main.rs- Initializes the async runtime and delegates to
cli::run(). - Very thin; most logic is in
src/cli.rs.
- Initializes the async runtime and delegates to
-
src/cli.rs- Declares submodules for each logical command group:
add_invoice,adm_send_dm,conversation_key,dm_to_user,get_dm,get_dm_user,last_trade_index,list_disputes,list_orders,new_order,orders_info,rate_user,restore,send_dm,send_admin_dm_attach,send_msg,take_dispute,take_order. - Defines:
Context: runtime dependencies required by commands (Nostr client, keys, trade index, DB pool, optional admin context keys, and Mostro pubkey).Cli: top-level arguments parsed byclap(subcommand, verbosity, Mostro pubkey override, relay list, PoW, secret mode).Commands: enum containing all subcommands and their structured arguments.
run():- Parses CLI args via
Cli::parse(). - Constructs a
Contextusinginit_context(&cli). - Dispatches:
if let Some(cmd) = &cli.command { cmd.run(&ctx).await?; }.
- Parses CLI args via
init_context():- Sets environment variables from CLI flags (e.g.
MOSTRO_PUBKEY,RELAYS,POW,SECRET). - Connects to SQLite via
db::connect(). - Loads identity and per-trade keys from the local
userstable. - Optionally loads
ADMIN_NSECintocontext_keysfor admin commands. - Resolves
MOSTRO_PUBKEYvia CLI flag or environment. - Connects to Nostr relays via
util::connect_nostr().
- Sets environment variables from CLI flags (e.g.
- Declares submodules for each logical command group:
-
src/util/mod.rs- Organizes utility modules:
events: event filtering and retrieval from Nostr.messaging: higher-level DM helpers (gift-wrapped messages, admin keys, shared-key derivation and custom wraps).misc: small helpers such asget_mcli_pathand string utilities.net: Nostr network connection setup.storage: thin storage helpers for orders and DMs.types: small shared enums/wrappers.
- Re-exports commonly used symbols (
create_filter,send_dm,connect_nostr,save_order,derive_shared_keys,derive_shared_key_hex,keys_from_shared_hex,send_admin_chat_message_via_shared_key, etc.) so other modules can import fromcrate::utildirectly.
- Organizes utility modules:
-
src/util/storage.rssave_order(order, trade_keys, request_id, trade_index, pool):- Wraps
Order::newto insert/update an order row. - Logs created order IDs.
- Updates the
User'slast_trade_indexin theuserstable.
- Wraps
run_simple_order_msg(command, order_id, ctx):- Convenience wrapper that forwards to
cli::send_msg::execute_send_msg(...)for simple order messages (e.g.FiatSent,Release,Cancel,Dispute).
- Convenience wrapper that forwards to
admin_send_dm(ctx, msg):- Uses
util::messaging::get_admin_keysandutil::send_dmto send an admin DM via Nostr.
- Uses
-
src/util/types.rsEventenum:- Wraps
SmallOrder,Dispute, and aMessagetuple(Message, u64, PublicKey)for use in parsers and event handling.
- Wraps
ListKindenum:- Identifies what is being listed:
Orders,Disputes,DirectMessagesUser,DirectMessagesAdmin,PrivateDirectMessagesUser.
- Identifies what is being listed:
MessageType(internal toutil) distinguishes DM/gift-wrap styles.
src/db.rs- Connection:
connect()creates or opensmcli.dbin the CLI data directory fromget_mcli_path().- On first run, it creates the
ordersanduserstables via raw SQL. - On subsequent runs, it applies a small migration to drop legacy
buyer_token/seller_tokencolumns if present.
- Models:
User:- Represents the local identity (mnemonic, root pubkey, last trade index).
- Handles creation (
User::new), loading (User::get), updating (save), and key derivation helpers (identity keys and per-trade keys usingnip06).
Order:- Represents cached orders with fields mapped to the
orderstable. - Provides
new,insert_db,update_db, fluent setters,save,save_new_id,get_by_id,get_all_trade_keys,get_all_trade_and_counterparty_keys(distinct(trade_keys, counterparty_pubkey)pairs for orders where both are set), anddelete_by_id.
- Represents cached orders with fields mapped to the
- See
database.mdfor schema details.
- Connection:
-
src/parser/*- Interpret raw Nostr events into higher-level
Eventvariants based onmostro_coretypes. - Responsibility split:
orders.rs: parsing order-related events.disputes.rs: parsing dispute events.dms.rs: parsing direct messages.common.rs: shared parsing helpers.mod.rs: module glue.
- Interpret raw Nostr events into higher-level
-
Shared-key custom wraps (
src/util/messaging.rs):- Sending:
derive_shared_keys(local_keys, counterparty_pubkey)yields aKeyswhose public key is used as the NIP-59 gift-wrap recipient; inner content is a signed text note encrypted with NIP-44 to that pubkey. Used bydmtouserandsendadmindmattach. - Receiving:
unwrap_giftwrap_with_shared_key(shared_keys, event)decrypts with NIP-44 and returns(content, timestamp, sender_pubkey);fetch_gift_wraps_for_shared_key(client, shared_keys)fetches Kind::GiftWrap events with#p= shared key pubkey and unwraps them. Use when implementing flows that read shared-key DMs.
- Sending:
src/lightning/mod.rs- Houses Lightning Network–specific helpers used by order flows and invoice handling (exact functions depend on the current version of the file).
- Typically used by
add_invoice,new_order, andtake_ordermodules.
Each file in src/cli/ encapsulates the logic of a specific feature or a group of related commands:
- Order-related:
add_invoice.rs,list_orders.rs,new_order.rs,take_order.rs,orders_info.rs,rate_user.rs,restore.rs,last_trade_index.rs. - Disputes and admin:
list_disputes.rs,take_dispute.rs,adm_send_dm.rs. - Messaging:
send_dm.rs,send_msg.rs,dm_to_user.rs,get_dm.rs,get_dm_user.rs,send_admin_dm_attach.rs,conversation_key.rs.
Each module exports an execute_* function that Commands::run calls. This keeps src/cli.rs as a central router while pushing feature logic into focused files.
- User runs
mostro-cli neworder .... clapparses CLI arguments intoCliandCommands::NewOrder { ... }.cli::run()callsinit_context()to buildContext(DB, keys, Nostr client, Mostro pubkey).Commands::runmatchesCommands::NewOrderand callsexecute_new_order(...).- The handler:
- Uses
mostro_coretypes to construct an order message. - Sends it to the Mostro backend over Nostr via
util::connect_nostr/messaging helpers. - Persists or updates the local representation via
util::save_orderanddb::Order.
- Uses
When adding new features:
-
New command:
- Add a variant to
Commandsinsrc/cli.rs. - Add the corresponding
execute_*function in asrc/cli/*.rsmodule. - Extend the
Commands::runmatch arm. - Update
docs/commands.mdto keep documentation in sync.
- Add a variant to
-
New database fields / tables:
- Update
connect()schema creation and migrations insrc/db.rs. - Extend the relevant model structs and methods.
- Update
docs/database.md.
- Update
-
New protocol/event type:
- Extend
util::types::Eventand the relevant parser module insrc/parser/*. - Adjust listing or DM flows as needed.
- Extend