1use crate::rpc::{MicropaymentInstruction, TaxDispatchPlan};
40use serde::{Deserialize, Serialize};
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
45pub enum PaymentStatus {
46 Sent,
48 Queued,
50 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#[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
76pub trait IlpTransport: Send + Sync {
80 fn send(&self, ilp_address: &str, amount_micro_cents: u64, via_nym: bool)
84 -> Result<(), String>;
85}
86
87pub struct HttpIlpTransport {
94 pub connector_url: String, }
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 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(); 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 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
148pub fn resolve_payment_pointer(pointer: &str) -> Result<String, String> {
150 if pointer.starts_with('$') {
151 let stripped = &pointer[1..];
152 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 Ok(pointer.to_string())
163 } else {
164 Err(format!("Unrecognised payment address format: {pointer}"))
165 }
166}
167
168pub struct MockTransport {
171 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
184pub struct IlpDispatcher<T: IlpTransport> {
187 pub transport: T,
188}
189
190impl<T: IlpTransport> IlpDispatcher<T> {
191 pub fn new(transport: T) -> Self {
193 Self { transport }
194 }
195
196 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 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
278pub 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; 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#[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 assert_eq!(
362 resolve_payment_pointer("did:wallet:0xABCD").unwrap(),
363 "did:wallet:0xABCD"
364 );
365 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 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); }
413}