1use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13
14use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
15use async_trait::async_trait;
16use chrono::Utc;
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, json};
19
20use super::error::{WALLET_RAIL_DATA_MISMATCH_CODE, refused};
21use super::policy::{Payee, RailRef};
22use super::rail::{PaymentRail, RailPayment, RailSettlement};
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct PaymentChallenge {
37 pub scheme: String,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub network: Option<String>,
42 pub resource: String,
44 pub pay_to: String,
46 pub amount: u64,
48 pub currency: String,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub description: Option<String>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub max_timeout_seconds: Option<u64>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub extra: Option<Value>,
59}
60
61impl PaymentChallenge {
62 pub fn new(resource: &str, pay_to: &str, amount: u64, currency: &str) -> Self {
65 Self {
66 scheme: "exact".to_string(),
67 network: None,
68 resource: resource.to_string(),
69 pay_to: pay_to.to_string(),
70 amount,
71 currency: currency.to_ascii_uppercase(),
72 description: None,
73 max_timeout_seconds: None,
74 extra: None,
75 }
76 }
77
78 pub fn payee(&self) -> Payee {
80 let payee = Payee::new(&self.pay_to);
81 match host_of(&self.resource) {
82 Some(host) => payee.with_domain(host),
83 None => payee,
84 }
85 }
86}
87
88pub(crate) fn host_of(url: &str) -> Option<String> {
90 let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
91 let authority = rest.split(['/', '?', '#']).next()?;
92 let authority = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
93 let host = if authority.starts_with('[') {
94 authority.split_once(']').map(|(host, _)| &host[1..])?
95 } else {
96 authority.split(':').next()?
97 };
98 (!host.is_empty()).then(|| host.to_ascii_lowercase())
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "camelCase")]
114pub struct PaymentProof {
115 pub header: String,
117 pub value: String,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct UseBasedPayment {
125 pub reference: String,
127 pub proof: PaymentProof,
129}
130
131#[async_trait]
138pub trait UseBasedScheme: Send + Sync {
139 fn name(&self) -> &str;
141
142 fn challenges(&self, body: &Value) -> Result<Vec<PaymentChallenge>>;
148
149 async fn pay(
156 &self,
157 challenge: &PaymentChallenge,
158 payment: &RailPayment,
159 ) -> Result<UseBasedPayment>;
160}
161
162pub struct UseBasedRail {
178 scheme: Arc<dyn UseBasedScheme>,
179}
180
181impl UseBasedRail {
182 pub fn new(scheme: Arc<dyn UseBasedScheme>) -> Self {
184 Self { scheme }
185 }
186
187 pub fn scheme(&self) -> &Arc<dyn UseBasedScheme> {
189 &self.scheme
190 }
191}
192
193fn challenge_of(payment: &RailPayment) -> Result<PaymentChallenge> {
194 let data = payment.rail_data.clone().ok_or_else(|| {
195 refused(
196 WALLET_RAIL_DATA_MISMATCH_CODE,
197 "a use-based payment carries the challenge it answers as its rail data",
198 )
199 })?;
200 serde_json::from_value(data).map_err(|error| {
201 refused(
202 WALLET_RAIL_DATA_MISMATCH_CODE,
203 format!("the use-based rail data is not a payment challenge: {error}"),
204 )
205 })
206}
207
208#[async_trait]
209impl PaymentRail for UseBasedRail {
210 fn rail(&self) -> RailRef {
211 RailRef::use_based()
212 }
213
214 fn check(&self, payment: &RailPayment) -> Result<()> {
215 let challenge = challenge_of(payment)?;
216 let mismatch = |what: String| Err(refused(WALLET_RAIL_DATA_MISMATCH_CODE, what));
217 if challenge.pay_to != payment.payee.id {
218 return mismatch(format!(
219 "the challenge pays {}, not payee {}",
220 challenge.pay_to, payment.payee.id
221 ));
222 }
223 if let Some(domain) = &payment.payee.domain
224 && challenge.payee().domain.as_deref() != Some(domain.to_ascii_lowercase().as_str())
225 {
226 return mismatch(format!(
227 "the challenge comes from {}, not the payee's domain {domain}",
228 challenge.resource
229 ));
230 }
231 if challenge.amount != payment.amount
232 || !challenge.currency.eq_ignore_ascii_case(&payment.currency)
233 {
234 return mismatch(format!(
235 "the challenge asks {} {}, not the {} {} the wallet allowed",
236 challenge.amount, challenge.currency, payment.amount, payment.currency
237 ));
238 }
239 Ok(())
240 }
241
242 async fn execute(&self, payment: &RailPayment) -> Result<RailSettlement> {
243 let challenge = challenge_of(payment)?;
244 let paid = self.scheme.pay(&challenge, payment).await?;
245 Ok(RailSettlement {
246 reference: paid.reference,
247 amount: payment.amount,
248 settled_at: Utc::now(),
249 proof: Some(serde_json::to_value(&paid.proof).unwrap_or(Value::Null)),
250 })
251 }
252}
253
254#[derive(Debug, Clone, Default)]
279pub struct InMemoryUseBasedScheme {
280 issued: Arc<Mutex<HashMap<String, (PaymentChallenge, bool)>>>,
281}
282
283impl InMemoryUseBasedScheme {
284 pub fn new() -> Self {
286 Self::default()
287 }
288
289 pub fn verify(&self, challenge: &PaymentChallenge, value: &str) -> bool {
292 let mut issued = self.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
293 match issued.get_mut(value) {
294 Some((paid, spent)) if paid == challenge && !*spent => {
295 *spent = true;
296 true
297 }
298 _ => false,
299 }
300 }
301
302 pub fn paid(&self) -> usize {
304 self.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len()
305 }
306}
307
308#[async_trait]
309impl UseBasedScheme for InMemoryUseBasedScheme {
310 fn name(&self) -> &str {
311 "x402-local"
312 }
313
314 fn challenges(&self, body: &Value) -> Result<Vec<PaymentChallenge>> {
315 let invalid = |reason: &str| {
316 AdkError::new(
317 ErrorComponent::Tool,
318 ErrorCategory::InvalidInput,
319 "wallet.use_based.invalid_challenge",
320 format!("not an x402 payment requirement: {reason}"),
321 )
322 };
323 let accepts =
324 body.get("accepts").and_then(Value::as_array).ok_or_else(|| invalid("no accepts"))?;
325 accepts
326 .iter()
327 .map(|item| {
328 let text = |key: &str| item.get(key).and_then(Value::as_str).map(str::to_string);
329 let amount = text("maxAmountRequired")
330 .and_then(|amount| amount.parse::<u64>().ok())
331 .ok_or_else(|| invalid("maxAmountRequired is not an amount"))?;
332 Ok(PaymentChallenge {
333 scheme: text("scheme").unwrap_or_else(|| "exact".to_string()),
334 network: text("network"),
335 resource: text("resource").ok_or_else(|| invalid("no resource"))?,
336 pay_to: text("payTo").ok_or_else(|| invalid("no payTo"))?,
337 amount,
338 currency: text("asset")
339 .ok_or_else(|| invalid("no asset"))?
340 .to_ascii_uppercase(),
341 description: text("description"),
342 max_timeout_seconds: item.get("maxTimeoutSeconds").and_then(Value::as_u64),
343 extra: item.get("extra").cloned(),
344 })
345 })
346 .collect()
347 }
348
349 async fn pay(
350 &self,
351 challenge: &PaymentChallenge,
352 payment: &RailPayment,
353 ) -> Result<UseBasedPayment> {
354 let token = json!({
355 "scheme": challenge.scheme,
356 "payTo": challenge.pay_to,
357 "amount": challenge.amount,
358 "currency": challenge.currency,
359 "payment": payment.payment_id,
360 });
361 let value = hex::encode(token.to_string());
362 self.issued
363 .lock()
364 .unwrap_or_else(std::sync::PoisonError::into_inner)
365 .entry(value.clone())
366 .or_insert_with(|| (challenge.clone(), false));
367 Ok(UseBasedPayment {
368 reference: format!("x402-local:{}", payment.payment_id),
369 proof: PaymentProof { header: "X-PAYMENT".to_string(), value },
370 })
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 #[test]
379 fn hosts_drop_scheme_user_info_port_and_path() {
380 assert_eq!(
381 host_of("https://API.example.com:8443/v1?x=1").as_deref(),
382 Some("api.example.com")
383 );
384 assert_eq!(host_of("http://user:pw@example.com/").as_deref(), Some("example.com"));
385 assert_eq!(host_of("https://[::1]:8080/x").as_deref(), Some("::1"));
386 assert_eq!(host_of("example.com/path").as_deref(), Some("example.com"));
387 assert_eq!(host_of("https:///nohost"), None);
388 }
389}