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
5 changes: 5 additions & 0 deletions .changelog/tempo-push-spec-alignment.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
mpp: patch
---

Aligned Tempo charge push payments (hash Credentials) with the spec, as mppx does: the server rejects them when the signed Challenge sets `methodDetails.memo`, requires the attribution memo on the primary transfer, and skips other Challenges' transfers in a batched transaction instead of rejecting it, counting a plain split only when the transaction pays no other Challenge. Challenges that set `methodDetails.memo` now always offer `pull` and drop `push` unless they accept Zones. The client pays them by pull or from a Zone, and skips offers it could only pay with a hash.
15 changes: 11 additions & 4 deletions src/client/tempo/accounts_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,17 +794,24 @@ impl PaymentProvider for TempoAccountsProvider {
self.trusted_tempo_proof_realms.push((origin, realm));
}

/// Skip offers that only a hash credential could pay when servers refuse
/// one (a `methodDetails.memo` with only `push` in `supportedModes`),
/// then prefer one funded by the preferred currency.
fn select_challenge<'a>(
&self,
challenges: &[&'a PaymentChallenge],
) -> Option<&'a PaymentChallenge> {
let first = challenges.first().copied()?;
let payable = || {
challenges
.iter()
.copied()
.filter(|challenge| super::charge::can_pay_offer(challenge))
};
let first = payable().next()?;
let Some(preferred_currency) = self.preferred_currency else {
return Some(first);
};
challenges
.iter()
.copied()
payable()
.find(|challenge| funded_by(challenge, preferred_currency))
.or(Some(first))
}
Expand Down
85 changes: 85 additions & 0 deletions src/client/tempo/charge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ async fn resolve_fee_token(
/// (`type="hash"`: the client broadcasts) when the challenge's
/// `supportedModes` lists only `push`. An omitted `supportedModes` allows
/// every mode.
///
/// A challenge whose request sets `methodDetails.memo` is never paid in
/// `push` mode: servers refuse hash credentials for it, after the transfer
/// has settled. Such a challenge that lists only `push` is an error, raised
/// before anything is broadcast (as mppx does).
fn resolve_push_mode(charge: &ChargeRequest) -> Result<bool, MppError> {
let supported_modes = charge
.method_details
Expand All @@ -175,6 +180,11 @@ fn resolve_push_mode(charge: &ChargeRequest) -> Result<bool, MppError> {
if supports("pull") {
Ok(false)
} else if supports("push") {
if sets_server_memo(charge) {
return Err(MppError::UnsupportedPaymentMethod(
"challenge has a memo but does not support pull mode".into(),
));
}
Ok(true)
} else {
Err(MppError::UnsupportedPaymentMethod(
Expand All @@ -183,6 +193,36 @@ fn resolve_push_mode(charge: &ChargeRequest) -> Result<bool, MppError> {
}
}

/// Whether a charge request's `methodDetails` sets a server `memo`.
fn sets_server_memo(charge: &ChargeRequest) -> bool {
charge
.method_details
.as_ref()
.and_then(|details| details.get("memo"))
.is_some_and(|memo| !memo.is_null())
}

/// Whether this client can pay `challenge` in a mode it supports: false for a
/// non-zero Tempo charge that sets `methodDetails.memo` and lists only
/// `push` in `supportedModes`, which only a hash credential could pay and
/// servers refuse one for (mppx `canHandleChallenge`). Providers skip such an
/// offer so another can be chosen. Other challenges, and requests that don't
/// decode, are left to [`TempoCharge::from_challenge`] to report.
pub(crate) fn can_pay_offer(challenge: &PaymentChallenge) -> bool {
if challenge.method.as_str() != crate::protocol::methods::tempo::METHOD_NAME
|| challenge.intent.as_str() != crate::protocol::methods::tempo::INTENT_CHARGE
{
return true;
}
let Ok(charge) = challenge.request.decode::<ChargeRequest>() else {
return true;
};
if charge.amount_u256().map_or(true, |amount| amount.is_zero()) || !sets_server_memo(&charge) {
return true;
}
resolve_push_mode(&charge).is_ok()
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

/// Resolve the transaction's `validBefore`: the requested timestamp, or
/// [`EXPIRING_NONCE_VALID_BEFORE_SECS`] from now, capped at the second after
/// the challenge `expires`.
Expand Down Expand Up @@ -1811,6 +1851,51 @@ mod tests {
}
}

/// A challenge that sets `methodDetails.memo` is paid by pull, and one
/// that offers only push can't be paid (as mppx).
#[test]
fn test_from_challenge_never_pushes_a_server_memo_challenge() {
use serde_json::json;

let memo = format!("0x{}", "ab".repeat(32));
let cases = [
("1000000", json!(null), Some(false)),
("1000000", json!(["pull"]), Some(false)),
("1000000", json!(["push", "pull"]), Some(false)),
("1000000", json!(["push"]), None),
// Zero-amount charges are answered with a proof, which has no mode.
("0", json!(["push"]), Some(false)),
];

for (amount, supported_modes, push) in cases {
let request = Base64UrlJson::from_value(&json!({
"amount": amount,
"currency": "0x20c0000000000000000000000000000000000000",
"recipient": "0x742d35Cc6634C0532925a3b844Bc9e7595f1B0F2",
"methodDetails": {
"chainId": 42431,
"memo": memo,
"supportedModes": supported_modes,
},
}))
.unwrap();
let challenge =
PaymentChallenge::new("test-id", "api.example.com", "tempo", "charge", request);

let result = TempoCharge::from_challenge(&challenge);
assert_eq!(
result.as_ref().ok().map(TempoCharge::is_push),
push,
"amount {amount}, supportedModes {supported_modes}: {result:?}"
);
assert_eq!(
can_pay_offer(&challenge),
push.is_some(),
"amount {amount}, supportedModes {supported_modes}"
);
}
}

#[tokio::test]
async fn test_valid_before_is_capped_at_challenge_expires() {
use alloy::eips::Decodable2718;
Expand Down
74 changes: 68 additions & 6 deletions src/client/tempo/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -825,8 +825,10 @@ impl PaymentProvider for TempoProvider {
self.trusted_tempo_proof_realms.push((origin, realm));
}

/// Skip offers that violate the currency or amount policy so an acceptable
/// offer can be chosen.
/// Skip offers that violate the currency or amount policy, or that only a
/// hash credential could pay when servers refuse one (a `methodDetails.memo`
/// with only `push` in `supportedModes`) and the configured Zone can't,
/// so an acceptable offer can be chosen.
fn select_challenge<'a>(
&self,
challenges: &[&'a PaymentChallenge],
Expand All @@ -838,10 +840,16 @@ impl PaymentProvider for TempoProvider {
{
return challenges.first().copied();
}
challenges
.iter()
.copied()
.find(|challenge| self.check_policy(challenge).is_ok())
challenges.iter().copied().find(|challenge| {
// A Zone withdrawal pays with a `zone` Credential, which a memo
// doesn't rule out.
(super::charge::can_pay_offer(challenge)
|| self
.zone
.as_ref()
.is_some_and(|zone| zone.may_pay(challenge, &self.signer, &self.signing_mode)))
&& self.check_policy(challenge).is_ok()
})
Comment thread
tempoxyz-bot marked this conversation as resolved.
Resolved
}

async fn pay(&self, challenge: &PaymentChallenge) -> Result<PaymentCredential, MppError> {
Expand Down Expand Up @@ -1938,6 +1946,60 @@ mod tests {
assert_eq!(credential.payload["type"], "transaction");
}

/// A challenge that sets `methodDetails.memo` is never paid with a hash,
/// which servers refuse for it: it is paid by pull when offered, and one
/// offering only push fails before anything is broadcast and is skipped
/// when another offer is acceptable (as mppx).
#[tokio::test]
async fn test_server_memo_challenge_is_never_paid_with_a_hash() {
let signer = alloy::signers::local::PrivateKeySigner::random();
let (rpc_url, sent) = push_rpc("0x1").await;
let provider = TempoProvider::new(signer, &rpc_url)
.unwrap()
.with_expected_chain_id(42431);
let memo_challenge = |id: &str, modes: serde_json::Value| {
let mut request = modes_challenge(modes).request.decode_value().unwrap();
request["methodDetails"]["memo"] = serde_json::json!(format!("0x{}", "ab".repeat(32)));
PaymentChallenge::new(
id,
"api.example.com",
"tempo",
"charge",
crate::protocol::core::Base64UrlJson::from_value(&request).unwrap(),
)
};

let push_only = memo_challenge("memo-push", serde_json::json!(["push"]));
let error = provider.pay(&push_only).await.unwrap_err();
assert!(
error.to_string().contains("does not support pull mode"),
"{error}"
);
assert!(sent.lock().unwrap().is_empty());

let both = memo_challenge("memo-both", serde_json::json!(["push", "pull"]));
let credential = provider.pay(&both).await.unwrap();
assert_eq!(credential.payload["type"], "transaction");
assert!(sent.lock().unwrap().is_empty());

let pull = memo_challenge("memo-pull", serde_json::json!(["pull"]));
assert_eq!(
provider
.select_challenge(&[&push_only, &pull])
.map(|c| c.id.as_str()),
Some("memo-pull")
);
assert!(provider.select_challenge(&[&push_only]).is_none());
// Without a memo, a push-only offer stays payable.
let plain = modes_challenge(serde_json::json!(["push"]));
assert_eq!(
provider
.select_challenge(&[&plain, &pull])
.map(|c| c.id.as_str()),
Some("push-challenge")
);
}

/// As mppx's `feeToken`, a configured fee token pays an unsponsored
/// charge's fee, and a sponsored charge leaves it to the fee payer.
#[tokio::test]
Expand Down
24 changes: 24 additions & 0 deletions src/client/tempo/zone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,30 @@ impl TempoZone {
self.chain_id
}

/// [`pays`](Self::pays), before the chain the client signs on is known:
/// on the chain the challenge names, else the Zone's parent chain. Lets
/// challenge selection keep an offer only this Zone can pay.
///
/// An error from `pays` keeps the offer, so paying it reports the error:
/// a withdrawal for these terms may be outstanding
/// ([`MppError::ZoneSettlementPending`]), and paying another offer could
/// pay the route twice.
pub(crate) fn may_pay(
&self,
challenge: &PaymentChallenge,
signer: &TempoPrimitiveSigner,
signing_mode: &TempoSigningMode,
) -> bool {
let Ok(request) = challenge.request.decode::<ChargeRequest>() else {
return false;
};
let Some(chain_id) = request.chain_id().or(self.parent_chain_id) else {
return false;
};
self.pays(challenge, &request, chain_id, signer, signing_mode)
.unwrap_or(true)
}

/// Whether to pay `challenge` (on Tempo chain `chain_id`) from this Zone: a
/// non-zero charge on the chain the Zone settles on, in a mode that allows
/// `push`, without splits, that accepts this Zone, and that leaves time to
Expand Down
71 changes: 71 additions & 0 deletions src/client/tempo/zone/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,77 @@ async fn test_pays_from_zone_on_challenge_chain() {
}
}

/// A push-only challenge with a server memo can't be paid with a hash, but
/// a Zone that accepts it still pays it with a `zone` Credential.
#[tokio::test]
async fn test_zone_pays_push_only_challenge_with_server_memo() {
let (zone_url, zone_calls) = unused_zone_rpc().await;
let (provider, _) =
provider_with_zone(TempoZone::new(zone_url, MODERATO_ZONE_3).unwrap()).await;
let memo = format!("0x{}", "ab".repeat(32));
let challenge = challenge_with(json!({ "memo": memo, "supportedModes": ["push"] }), None);

assert_eq!(
provider.select_challenge(&[&challenge]).map(|c| &c.id),
Some(&challenge.id)
);
let error = provider.pay(&challenge).await.unwrap_err();
assert!(error.to_string().contains("zone used"), "{error}");
assert!(!zone_calls.lock().unwrap().is_empty());

// Without a Zone that accepts it, the offer is skipped.
let elsewhere = challenge_with(
json!({ "memo": memo, "supportedModes": ["push"], "zones": [4] }),
None,
);
assert!(provider.select_challenge(&[&elsewhere]).is_none());
let (tempo_url, _) = tempo_rpc(Arc::new(Mutex::new(json!([])))).await;
let plain = TempoProvider::new(payer(), tempo_url).unwrap();
assert!(plain.select_challenge(&[&challenge]).is_none());

// When the Zone would decline it (here, too close to its expiry to
// settle), a later pull offer is chosen instead.
let mut expiring = challenge_with(
json!({ "memo": memo, "supportedModes": ["push"] }),
expires_in(5),
);
expiring.id = "expiring".into();
let mut pull = challenge_with(json!({ "memo": memo, "supportedModes": ["pull"] }), None);
pull.id = "pull".into();
assert_eq!(
provider
.select_challenge(&[&expiring, &pull])
.map(|c| c.id.as_str()),
Some("pull")
);
}

/// When deciding whether this Zone pays an offer fails, the offer is kept, so
/// that paying it reports the failure instead of paying another offer: an
/// outstanding withdrawal fails closed that way.
#[tokio::test]
async fn test_zone_may_pay_keeps_an_offer_it_cannot_decide() {
let (zone_url, _) = unused_zone_rpc().await;
let zone = TempoZone::new(zone_url, MODERATO_ZONE_3).unwrap();
let signer = TempoPrimitiveSigner::from(payer());
let signing_mode = TempoSigningMode::Direct;
let memo = format!("0x{}", "ab".repeat(32));
let details = json!({ "memo": memo, "supportedModes": ["push"] });

// An expired challenge with no withdrawal outstanding: `pays` errors.
let expired = challenge_with(details.clone(), expires_in(-60));
let request: ChargeRequest = expired.request.decode().unwrap();
assert!(zone
.pays(&expired, &request, 42431, &signer, &signing_mode)
.is_err());
assert!(zone.may_pay(&expired, &signer, &signing_mode));

// One this Zone isn't accepted for is declined.
let mut elsewhere = details;
elsewhere["zones"] = json!([4]);
assert!(!zone.may_pay(&challenge_with(elsewhere, None), &signer, &signing_mode));
}

#[tokio::test]
async fn test_pays_from_zone_for_challenge_with_line_breaks_in_description() {
let (zone_url, _) = unused_zone_rpc().await;
Expand Down
Loading