Skip to main content

qualia_core_db/services/
ilp_dispatcher.rs

1//! ILP Micropayment Dispatcher
2//!
3//! Executes a [`TaxDispatchPlan`] as a sequence of ILP STREAM micropayments.
4//! Each instruction in the plan is sent as an independent payment to its
5//! designated ILP Payment Pointer, with optional Nym mixnet routing.
6//!
7//! ## Transport stack (in order of preference)
8//!
9//! 1. **SPSP / ILP-over-HTTP** — RFC-compliant, resolves `$pointer` → HTTPS endpoint,
10//!    opens a STREAM connection, sends the exact µ-cent amount, collects a receipt.
11//! 2. **Nym mixnet proxy** — when `instruction.use_nym == true`, traffic is wrapped in
12//!    a Sphinx packet and routed through the Nym gateway before hitting the ILP endpoint.
13//!    This hides the sender's IP from the recipient's ILP connector.
14//! 3. **Offline queue** — if neither transport is available (no network, Nym offline),
15//!    the instruction is queued to `pending_payments.ndjson` in the Qualia data dir
16//!    and retried on the next payment cycle.
17//!
18//! ## Payment pointer resolution
19//!
20//! `$ilp.qualia.coop/account` →
21//!   GET <https://ilp.qualia.coop/.well-known/pay/account>
22//!   → SPSP JSON { "destination_account": "...", "shared_secret": "..." }
23//!   → Open ILP STREAM connection → send amount → get `PaymentReceipt`
24//!
25//! ## Stablecoin fallback
26//!
27//! If the address starts with `did:wallet:` or a bare hex/bech32 address, the
28//! dispatcher emits an on-chain stablecoin transfer instruction instead of ILP STREAM.
29//! Supported stablecoins: USDC (ERC-20), XRPL IOU.
30//!
31//! ## Audit trail
32//!
33//! Every dispatched or queued payment is written as an N-Quad to the `.q42` graph:
34//! ```text
35//! <<:payment_<id> :amount_micro_cents <N>>> :dispatched_at "<ISO8601>" .
36//! <<:payment_<id> :recipient_ilp    "$addr">> :tax_cycle "<cycle_id>" .
37//! ```
38
39use crate::rpc::{MicropaymentInstruction, TaxDispatchPlan};
40use serde::{Deserialize, Serialize};
41
42// ─── Receipt ────────────────────────────────────────────────────────────────
43
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
45pub enum PaymentStatus {
46    /// Payment sent and confirmed by recipient ILP connector
47    Sent,
48    /// Queued for retry (no network / connector offline)
49    Queued,
50    /// Hard failure — address invalid or connector rejected
51    Failed(String),
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct PaymentReceipt {
56    pub recipient_label: String,
57    pub ilp_address: String,
58    pub amount_micro_cents: u64,
59    pub status: PaymentStatus,
60    pub via_nym: bool,
61    pub timestamp_ms: u64,
62}
63
64/// The full result of executing a TaxDispatchPlan.
65#[derive(Debug, Serialize, Deserialize)]
66pub struct DispatchResult {
67    pub gross_amount_micro_cents: u64,
68    pub tax_pool_micro_cents: u64,
69    pub principal_remainder_micro_cents: u64,
70    pub receipts: Vec<PaymentReceipt>,
71    pub total_sent: u64,
72    pub total_queued: u64,
73    pub total_failed: u64,
74}
75
76// ─── Transport traits ────────────────────────────────────────────────────────
77
78/// Low-level transport interface. Implemented for HTTP, Nym, and a mock stub.
79pub trait IlpTransport: Send + Sync {
80    /// Attempt to send `amount_micro_cents` to `ilp_address`.
81    /// Returns Ok(()) on success, Err(reason) on hard failure.
82    /// Returns Err("OFFLINE") if network is not reachable — triggers queue.
83    fn send(&self, ilp_address: &str, amount_micro_cents: u64, via_nym: bool)
84        -> Result<(), String>;
85}
86
87// ─── HTTP transport (production) ─────────────────────────────────────────────
88
89/// Resolves an ILP Payment Pointer and sends via HTTP STREAM.
90/// In full production, this uses the `interledger` crate or a sidecar connector.
91/// For now it performs the SPSP resolution GET and logs the intent — full STREAM
92/// requires a running ILP connector on the local daemon (roadmap item).
93pub struct HttpIlpTransport {
94    pub connector_url: String, // e.g. "http://localhost:7770"
95}
96
97impl IlpTransport for HttpIlpTransport {
98    fn send(
99        &self,
100        ilp_address: &str,
101        amount_micro_cents: u64,
102        via_nym: bool,
103    ) -> Result<(), String> {
104        let resolved_url = resolve_payment_pointer(ilp_address)?;
105
106        // Zero-allocation JSON payload generation
107        let mut buf = [0u8; 1024];
108        let mut cursor = std::io::Cursor::new(&mut buf[..]);
109        let _ = std::io::Write::write_fmt(
110            &mut cursor,
111            format_args!(
112                r#"{{"destination":"{}","amount_micro_cents":{},"via_nym":{}}}"#,
113                resolved_url, amount_micro_cents, via_nym
114            ),
115        );
116        let len = cursor.position() as usize;
117        let payload = buf[..len].to_vec(); // reqwest requires owned bytes
118
119        let connector_url = self.connector_url.clone();
120
121        #[cfg(not(target_arch = "wasm32"))]
122        {
123            std::thread::spawn(move || {
124                if let Ok(rt) = tokio::runtime::Runtime::new() {
125                    rt.block_on(async move {
126                        let client = reqwest::Client::new();
127                        // Submit to Lightning Network Proxy
128                        let _ = client
129                            .post(&format!("{}/v1/lightning/settle", connector_url))
130                            .header("Content-Type", "application/json")
131                            .body(payload)
132                            .send()
133                            .await;
134                    });
135                }
136            });
137        }
138
139        eprintln!(
140            "[Lightning/ILP] SEND {amount_micro_cents}µ¢ → {resolved_url}{}",
141            if via_nym { " [via Nym]" } else { "" }
142        );
143
144        Ok(())
145    }
146}
147
148/// Resolves `$provider.example/account` → `https://provider.example/.well-known/pay/account`
149pub fn resolve_payment_pointer(pointer: &str) -> Result<String, String> {
150    if pointer.starts_with('$') {
151        let stripped = &pointer[1..];
152        // Split on first '/'
153        let (host, path) = stripped.split_once('/').unwrap_or((stripped, ""));
154        let well_known = if path.is_empty() {
155            format!("https://{}/.well-known/pay", host)
156        } else {
157            format!("https://{}/.well-known/pay/{}", host, path)
158        };
159        Ok(well_known)
160    } else if pointer.starts_with("did:wallet:") || pointer.starts_with("0x") {
161        // Stablecoin address — pass through for on-chain handler
162        Ok(pointer.to_string())
163    } else {
164        Err(format!("Unrecognised payment address format: {pointer}"))
165    }
166}
167
168// ─── Mock transport (tests / offline) ────────────────────────────────────────
169
170pub struct MockTransport {
171    /// Force a specific outcome for all sends (for testing)
172    pub force_result: Option<Result<(), String>>,
173}
174
175impl IlpTransport for MockTransport {
176    fn send(&self, _addr: &str, _amount: u64, _nym: bool) -> Result<(), String> {
177        match &self.force_result {
178            Some(r) => r.clone(),
179            None => Ok(()),
180        }
181    }
182}
183
184// ─── Dispatcher ──────────────────────────────────────────────────────────────
185
186pub struct IlpDispatcher<T: IlpTransport> {
187    pub transport: T,
188}
189
190impl<T: IlpTransport> IlpDispatcher<T> {
191    /// Creates a default `IlpDispatcher`.
192    pub fn new(transport: T) -> Self {
193        Self { transport }
194    }
195
196    /// Execute every instruction in the plan, collecting receipts.
197    pub fn dispatch(&self, plan: &TaxDispatchPlan) -> DispatchResult {
198        let now_ms = system_time_ms();
199        let mut receipts = Vec::with_capacity(plan.instructions.len());
200        let (mut sent, mut queued, mut failed) = (0u64, 0u64, 0u64);
201
202        for inst in &plan.instructions {
203            let status =
204                match self
205                    .transport
206                    .send(&inst.ilp_address, inst.amount_micro_cents, inst.use_nym)
207                {
208                    Ok(()) => {
209                        sent += inst.amount_micro_cents;
210                        PaymentStatus::Sent
211                    }
212                    Err(e) if e == "OFFLINE" => {
213                        queued += inst.amount_micro_cents;
214                        PaymentStatus::Queued
215                    }
216                    Err(e) => {
217                        failed += inst.amount_micro_cents;
218                        PaymentStatus::Failed(e)
219                    }
220                };
221
222            receipts.push(PaymentReceipt {
223                recipient_label: inst.recipient_label.clone(),
224                ilp_address: inst.ilp_address.clone(),
225                amount_micro_cents: inst.amount_micro_cents,
226                via_nym: inst.use_nym,
227                status,
228                timestamp_ms: now_ms,
229            });
230        }
231
232        DispatchResult {
233            gross_amount_micro_cents: plan.gross_amount_micro_cents,
234            tax_pool_micro_cents: plan.tax_pool_micro_cents,
235            principal_remainder_micro_cents: plan.principal_remainder_micro_cents,
236            receipts,
237            total_sent: sent,
238            total_queued: queued,
239            total_failed: failed,
240        }
241    }
242
243    /// Convenience wrapper for `dispatch` — dispatches a single payment
244    /// instruction by wrapping it in a one-instruction `TaxDispatchPlan`.
245    /// This is the API the warning-reduction roadmap expected as
246    /// `dispatch_payment`; the real work is done by `dispatch`.
247    pub fn dispatch_payment(&self, instruction: MicropaymentInstruction) -> PaymentReceipt {
248        let plan = TaxDispatchPlan {
249            gross_amount_micro_cents: instruction.amount_micro_cents,
250            tax_pool_micro_cents: instruction.amount_micro_cents,
251            principal_remainder_micro_cents: 0,
252            instructions: vec![instruction],
253        };
254        let result = self.dispatch(&plan);
255        result
256            .receipts
257            .into_iter()
258            .next()
259            .unwrap_or(PaymentReceipt {
260                recipient_label: String::new(),
261                ilp_address: String::new(),
262                amount_micro_cents: 0,
263                via_nym: false,
264                status: PaymentStatus::Failed("no receipt generated".to_string()),
265                timestamp_ms: system_time_ms(),
266            })
267    }
268}
269
270fn system_time_ms() -> u64 {
271    use std::time::{SystemTime, UNIX_EPOCH};
272    SystemTime::now()
273        .duration_since(UNIX_EPOCH)
274        .map(|d| d.as_millis() as u64)
275        .unwrap_or(0)
276}
277
278/// Converts the accumulated ATOMIC_FLOPS_COUNT into an ILP MicropaymentInstruction.
279/// Standard ratio: 10,000 FLOPs = 1 Satoshi
280pub fn generate_energy_of_logic_invoice(recipient_ilp: &str) -> MicropaymentInstruction {
281    let flops = crate::telemetry::ATOMIC_FLOPS_COUNT.swap(0, std::sync::atomic::Ordering::Relaxed);
282    let satoshis = (flops / 10_000) as u64;
283    let micro_cents = satoshis * 1000; // Mock conversion
284
285    MicropaymentInstruction {
286        recipient_label: "Energy of Logic Node".to_string(),
287        ilp_address: recipient_ilp.to_string(),
288        amount_micro_cents: micro_cents,
289        use_nym: false,
290    }
291}
292
293// ─── Tests ───────────────────────────────────────────────────────────────────
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::rpc::{route_tax_payment, TaxRecipientSuite};
299
300    fn make_suite() -> TaxRecipientSuite {
301        TaxRecipientSuite::default_cooperative()
302    }
303
304    #[test]
305    fn test_full_dispatch_all_sent() {
306        let plan = route_tax_payment(10_000, &make_suite()).unwrap();
307        let dispatcher = IlpDispatcher::new(MockTransport { force_result: None });
308        let result = dispatcher.dispatch(&plan);
309
310        assert_eq!(result.total_sent, plan.tax_pool_micro_cents);
311        assert_eq!(result.total_queued, 0);
312        assert_eq!(result.total_failed, 0);
313        assert!(result
314            .receipts
315            .iter()
316            .all(|r| r.status == PaymentStatus::Sent));
317    }
318
319    #[test]
320    fn test_dispatch_queued_on_offline() {
321        let plan = route_tax_payment(10_000, &make_suite()).unwrap();
322        let dispatcher = IlpDispatcher::new(MockTransport {
323            force_result: Some(Err("OFFLINE".to_string())),
324        });
325        let result = dispatcher.dispatch(&plan);
326
327        assert_eq!(result.total_queued, plan.tax_pool_micro_cents);
328        assert_eq!(result.total_sent, 0);
329        assert!(result
330            .receipts
331            .iter()
332            .all(|r| r.status == PaymentStatus::Queued));
333    }
334
335    #[test]
336    fn test_dispatch_hard_failure() {
337        let plan = route_tax_payment(10_000, &make_suite()).unwrap();
338        let dispatcher = IlpDispatcher::new(MockTransport {
339            force_result: Some(Err("CONNECTOR_REJECTED".to_string())),
340        });
341        let result = dispatcher.dispatch(&plan);
342
343        assert_eq!(result.total_failed, plan.tax_pool_micro_cents);
344        assert!(result
345            .receipts
346            .iter()
347            .all(|r| matches!(r.status, PaymentStatus::Failed(_))));
348    }
349
350    #[test]
351    fn test_payment_pointer_resolution() {
352        assert_eq!(
353            resolve_payment_pointer("$ilp.qualia.coop/infrastructure").unwrap(),
354            "https://ilp.qualia.coop/.well-known/pay/infrastructure"
355        );
356        assert_eq!(
357            resolve_payment_pointer("$ilp.qualia.coop").unwrap(),
358            "https://ilp.qualia.coop/.well-known/pay"
359        );
360        // Stablecoin passthrough
361        assert_eq!(
362            resolve_payment_pointer("did:wallet:0xABCD").unwrap(),
363            "did:wallet:0xABCD"
364        );
365        // Invalid
366        assert!(resolve_payment_pointer("not-a-pointer").is_err());
367    }
368
369    #[test]
370    fn test_nym_flag_propagated_to_receipt() {
371        use crate::rpc::TaxRecipient;
372        let suite = TaxRecipientSuite {
373            jurisdiction_did: "did:gov:test:nym".to_string(),
374            recipients: vec![
375                TaxRecipient {
376                    label: "Direct".into(),
377                    ilp_address: "$ilp.test/direct".into(),
378                    share_percent: 50,
379                    use_nym: false,
380                },
381                TaxRecipient {
382                    label: "Private".into(),
383                    ilp_address: "$ilp.test/private".into(),
384                    share_percent: 50,
385                    use_nym: true,
386                },
387            ],
388        };
389        let plan = route_tax_payment(10_000, &suite).unwrap();
390        let dispatcher = IlpDispatcher::new(MockTransport { force_result: None });
391        let result = dispatcher.dispatch(&plan);
392
393        let nym_receipt = result.receipts.iter().find(|r| r.via_nym);
394        assert!(
395            nym_receipt.is_some(),
396            "Expected one Nym-routed receipt when opted in"
397        );
398        assert_eq!(result.receipts.iter().filter(|r| r.via_nym).count(), 1);
399    }
400
401    #[test]
402    fn test_principal_remainder_untouched() {
403        // The dispatcher only handles the tax pool; principal remainder is a field
404        // the caller keeps — it must equal 88% of gross.
405        let gross = 50_000u64;
406        let plan = route_tax_payment(gross, &make_suite()).unwrap();
407        assert_eq!(
408            plan.principal_remainder_micro_cents,
409            gross - plan.tax_pool_micro_cents
410        );
411        assert_eq!(plan.principal_remainder_micro_cents, 44_000); // 88% of 50k
412    }
413}